lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java
|
apache-2.0
|
9f7b4e050ba1b45070252b997d0523521823ba40
| 0 |
mtransitapps/ca-calgary-transit-bus-parser
|
package org.mtransit.parser.ca_calgary_transit_bus;
import java.util.HashSet;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MDirectionType;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MSpec;
import org.mtransit.parser.mt.data.MTrip;
import org.mtransit.parser.mt.data.MTripStop;
// https://www.calgarytransit.com/developer-resources
// https://data.calgary.ca/OpenData/Pages/DatasetDetails.aspx?DatasetID=PDC0-99999-99999-00501-P(CITYonlineDefault)
// https://data.calgary.ca/_layouts/OpenData/DownloadDataset.ashx?Format=FILE&DatasetId=PDC0-99999-99999-00501-P(CITYonlineDefault)&VariantId=5(CITYonlineDefault)
public class CalgaryTransitBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-calgary-transit-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new CalgaryTransitBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("Generating Calgary Transit bus data...\n");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this);
super.start(args);
System.out.printf("Generating Calgary Transit bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
@Override
public long getRouteId(GRoute gRoute) {
return Long.parseLong(gRoute.route_short_name); // using route short name as route ID
}
private static final Pattern CLEAN_STREET_POINT = Pattern.compile("((\\s)*(ave|st|mt)\\.(\\s)*)", Pattern.CASE_INSENSITIVE);
private static final String CLEAN_AVE_POINT_REPLACEMENT = "$2$3$4";
@Override
public String getRouteLongName(GRoute gRoute) {
String gRouteLongName = gRoute.route_long_name;
gRouteLongName = MSpec.CLEAN_SLASHES.matcher(gRouteLongName).replaceAll(MSpec.CLEAN_SLASHES_REPLACEMENT);
gRouteLongName = CLEAN_STREET_POINT.matcher(gRouteLongName).replaceAll(CLEAN_AVE_POINT_REPLACEMENT);
gRouteLongName = MSpec.cleanStreetTypes(gRouteLongName);
return MSpec.cleanLabel(gRouteLongName);
}
private static final String AGENCY_COLOR_RED = "B83A3F"; // LIGHT RED (from web site CSS)
private static final String AGENCY_COLOR = AGENCY_COLOR_RED;
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
private static final String COLOR_BUS_ROUTES = "004B85"; // BLUE (from PDF map)
private static final String COLOR_BUS_ROUTES_EXPRESS = "00BBE5"; // LIGHT BLUE (from PDF map)
private static final String COLOR_BUS_ROUTES_BRT = "ED1C2E"; // RED (from PDF map)
private static final String COLOR_BUS_ROUTES_SCHOOL = "E4A024"; // YELLOW (from PDF map)
@Override
public String getRouteColor(GRoute gRoute) {
int rsn = Integer.parseInt(gRoute.route_short_name);
switch (rsn) {
// @formatter:off
case 1: return null;
case 2: return null;
case 3: return null;
case 4: return null;
case 5: return null;
case 6: return null;
case 7: return null;
case 8: return null;
case 9: return null;
case 10: return null;
case 11: return null;
case 12: return null;
case 13: return null;
case 14: return null;
case 15: return null;
case 16: return null;
case 17: return null;
case 18: return null;
case 19: return null;
case 20: return null;
case 21: return null;
case 22: return COLOR_BUS_ROUTES_EXPRESS;
case 23: return COLOR_BUS_ROUTES_EXPRESS;
case 24: return null;
case 25: return null;
case 26: return null;
case 27: return COLOR_BUS_ROUTES;
case 28: return null;
case 29: return null;
case 30: return COLOR_BUS_ROUTES;
case 32: return null;
case 33: return COLOR_BUS_ROUTES;
case 34: return COLOR_BUS_ROUTES;
case 35: return COLOR_BUS_ROUTES;
case 36: return null;
case 37: return null;
case 38: return null;
case 39: return COLOR_BUS_ROUTES;
case 40: return null;
case 41: return null;
case 42: return null;
case 43: return null;
case 44: return COLOR_BUS_ROUTES;
case 45: return null;
case 46: return null;
case 47: return COLOR_BUS_ROUTES;
case 48: return null;
case 49: return null;
case 50: return null;
case 51: return null;
case 52: return null;
case 54: return null;
case 55: return null;
case 56: return null;
case 57: return null;
case 60: return null;
case 61: return COLOR_BUS_ROUTES;
case 62: return COLOR_BUS_ROUTES_EXPRESS;
case 63: return COLOR_BUS_ROUTES_EXPRESS;
case 64: return COLOR_BUS_ROUTES_EXPRESS;
case 66: return COLOR_BUS_ROUTES_EXPRESS;
case 69: return COLOR_BUS_ROUTES;
case 70: return COLOR_BUS_ROUTES_EXPRESS;
case 71: return COLOR_BUS_ROUTES;
case 72: return null;
case 73: return null;
case 74: return null;
case 75: return COLOR_BUS_ROUTES_EXPRESS;
case 76: return null;
case 77: return COLOR_BUS_ROUTES;
case 78: return null;
case 79: return null;
case 80: return null;
case 81: return COLOR_BUS_ROUTES;
case 83: return null;
case 84: return COLOR_BUS_ROUTES;
case 85: return null;
case 86: return null;
case 88: return null;
case 89: return COLOR_BUS_ROUTES;
case 91: return COLOR_BUS_ROUTES;
case 92: return null;
case 93: return COLOR_BUS_ROUTES;
case 94: return COLOR_BUS_ROUTES;
case 95: return COLOR_BUS_ROUTES;
case 96: return null;
case 98: return COLOR_BUS_ROUTES;
case 100: return null;
case 102: return COLOR_BUS_ROUTES_EXPRESS;
case 103: return COLOR_BUS_ROUTES_EXPRESS;
case 107: return COLOR_BUS_ROUTES;
case 109: return COLOR_BUS_ROUTES_EXPRESS;
case 110: return COLOR_BUS_ROUTES_EXPRESS;
case 112: return null;
case 114: return null;
case 116: return COLOR_BUS_ROUTES_EXPRESS;
case 117: return COLOR_BUS_ROUTES_EXPRESS;
case 118: return null;
case 122: return COLOR_BUS_ROUTES;
case 125: return COLOR_BUS_ROUTES_EXPRESS;
case 126: return COLOR_BUS_ROUTES_EXPRESS;
case 127: return null;
case 133: return COLOR_BUS_ROUTES_EXPRESS;
case 136: return COLOR_BUS_ROUTES;
case 137: return null;
case 142: return COLOR_BUS_ROUTES_EXPRESS;
case 143: return null;
case 145: return COLOR_BUS_ROUTES;
case 146: return COLOR_BUS_ROUTES;
case 151: return COLOR_BUS_ROUTES_EXPRESS;
case 152: return COLOR_BUS_ROUTES;
case 153: return COLOR_BUS_ROUTES;
case 154: return null;
case 157: return null;
case 158: return null;
case 159: return COLOR_BUS_ROUTES;
case 169: return null;
case 174: return null;
case 176: return COLOR_BUS_ROUTES_EXPRESS;
case 178: return COLOR_BUS_ROUTES;
case 181: return COLOR_BUS_ROUTES_EXPRESS;
case 182: return COLOR_BUS_ROUTES_EXPRESS;
case 199: return null;
case 299: return null;
case 300: return COLOR_BUS_ROUTES_BRT;
case 301: return COLOR_BUS_ROUTES_BRT;
case 302: return COLOR_BUS_ROUTES_BRT;
case 305: return COLOR_BUS_ROUTES_BRT;
case 306: return COLOR_BUS_ROUTES_BRT;
case 402: return COLOR_BUS_ROUTES;
case 404: return COLOR_BUS_ROUTES;
case 405: return COLOR_BUS_ROUTES;
case 406: return COLOR_BUS_ROUTES;
case 407: return COLOR_BUS_ROUTES;
case 408: return null;
case 409: return COLOR_BUS_ROUTES;
case 410: return COLOR_BUS_ROUTES;
case 411: return COLOR_BUS_ROUTES;
case 412: return COLOR_BUS_ROUTES;
case 414: return COLOR_BUS_ROUTES;
case 419: return COLOR_BUS_ROUTES;
case 420: return COLOR_BUS_ROUTES;
case 421: return COLOR_BUS_ROUTES;
case 425: return COLOR_BUS_ROUTES;
case 429: return COLOR_BUS_ROUTES;
case 430: return COLOR_BUS_ROUTES;
case 439: return COLOR_BUS_ROUTES;
case 440: return COLOR_BUS_ROUTES;
case 444: return COLOR_BUS_ROUTES;
case 445: return COLOR_BUS_ROUTES;
case 452: return COLOR_BUS_ROUTES;
case 453: return COLOR_BUS_ROUTES;
case 454: return COLOR_BUS_ROUTES;
case 456: return COLOR_BUS_ROUTES;
case 468: return COLOR_BUS_ROUTES;
case 502: return null;
case 506: return COLOR_BUS_ROUTES;
case 555: return null;
case 697: return COLOR_BUS_ROUTES_SCHOOL;
case 698: return COLOR_BUS_ROUTES_SCHOOL;
case 699: return COLOR_BUS_ROUTES_SCHOOL;
case 703: return COLOR_BUS_ROUTES_SCHOOL;
case 704: return COLOR_BUS_ROUTES_SCHOOL;
case 705: return COLOR_BUS_ROUTES_SCHOOL;
case 706: return COLOR_BUS_ROUTES_SCHOOL;
case 710: return COLOR_BUS_ROUTES_SCHOOL;
case 711: return COLOR_BUS_ROUTES_SCHOOL;
case 712: return COLOR_BUS_ROUTES_SCHOOL;
case 713: return COLOR_BUS_ROUTES_SCHOOL;
case 714: return COLOR_BUS_ROUTES_SCHOOL;
case 715: return COLOR_BUS_ROUTES_SCHOOL;
case 716: return COLOR_BUS_ROUTES_SCHOOL;
case 717: return COLOR_BUS_ROUTES_SCHOOL;
case 718: return COLOR_BUS_ROUTES_SCHOOL;
case 719: return COLOR_BUS_ROUTES_SCHOOL;
case 721: return COLOR_BUS_ROUTES_SCHOOL;
case 724: return COLOR_BUS_ROUTES_SCHOOL;
case 725: return COLOR_BUS_ROUTES_SCHOOL;
case 731: return COLOR_BUS_ROUTES_SCHOOL;
case 732: return COLOR_BUS_ROUTES_SCHOOL;
case 733: return COLOR_BUS_ROUTES_SCHOOL;
case 734: return COLOR_BUS_ROUTES_SCHOOL;
case 735: return COLOR_BUS_ROUTES_SCHOOL;
case 737: return COLOR_BUS_ROUTES_SCHOOL;
case 738: return COLOR_BUS_ROUTES_SCHOOL;
case 739: return COLOR_BUS_ROUTES_SCHOOL;
case 740: return COLOR_BUS_ROUTES_SCHOOL;
case 741: return COLOR_BUS_ROUTES_SCHOOL;
case 742: return COLOR_BUS_ROUTES_SCHOOL;
case 743: return COLOR_BUS_ROUTES_SCHOOL;
case 744: return COLOR_BUS_ROUTES_SCHOOL;
case 745: return COLOR_BUS_ROUTES_SCHOOL;
case 746: return COLOR_BUS_ROUTES_SCHOOL;
case 747: return COLOR_BUS_ROUTES_SCHOOL;
case 751: return COLOR_BUS_ROUTES_SCHOOL;
case 752: return COLOR_BUS_ROUTES_SCHOOL;
case 753: return COLOR_BUS_ROUTES_SCHOOL;
case 754: return COLOR_BUS_ROUTES_SCHOOL;
case 755: return COLOR_BUS_ROUTES_SCHOOL;
case 756: return COLOR_BUS_ROUTES_SCHOOL;
case 757: return COLOR_BUS_ROUTES_SCHOOL;
case 758: return COLOR_BUS_ROUTES_SCHOOL;
case 759: return COLOR_BUS_ROUTES_SCHOOL;
case 760: return COLOR_BUS_ROUTES_SCHOOL;
case 761: return COLOR_BUS_ROUTES_SCHOOL;
case 762: return COLOR_BUS_ROUTES_SCHOOL;
case 763: return COLOR_BUS_ROUTES_SCHOOL;
case 764: return COLOR_BUS_ROUTES_SCHOOL;
case 765: return COLOR_BUS_ROUTES_SCHOOL;
case 766: return COLOR_BUS_ROUTES_SCHOOL;
case 770: return COLOR_BUS_ROUTES_SCHOOL;
case 771: return COLOR_BUS_ROUTES_SCHOOL;
case 773: return COLOR_BUS_ROUTES_SCHOOL;
case 774: return COLOR_BUS_ROUTES_SCHOOL;
case 775: return COLOR_BUS_ROUTES_SCHOOL;
case 776: return COLOR_BUS_ROUTES_SCHOOL;
case 778: return COLOR_BUS_ROUTES_SCHOOL;
case 779: return COLOR_BUS_ROUTES_SCHOOL;
case 780: return COLOR_BUS_ROUTES_SCHOOL;
case 791: return COLOR_BUS_ROUTES_SCHOOL;
case 792: return COLOR_BUS_ROUTES_SCHOOL;
case 795: return COLOR_BUS_ROUTES_SCHOOL;
case 796: return COLOR_BUS_ROUTES_SCHOOL;
case 797: return COLOR_BUS_ROUTES_SCHOOL;
case 798: return COLOR_BUS_ROUTES_SCHOOL;
case 799: return COLOR_BUS_ROUTES_SCHOOL;
case 801: return COLOR_BUS_ROUTES_SCHOOL;
case 802: return COLOR_BUS_ROUTES_SCHOOL;
case 804: return COLOR_BUS_ROUTES_SCHOOL;
case 805: return COLOR_BUS_ROUTES_SCHOOL;
case 807: return COLOR_BUS_ROUTES_SCHOOL;
case 811: return COLOR_BUS_ROUTES_SCHOOL;
case 812: return COLOR_BUS_ROUTES_SCHOOL;
case 813: return COLOR_BUS_ROUTES_SCHOOL;
case 814: return COLOR_BUS_ROUTES_SCHOOL;
case 815: return COLOR_BUS_ROUTES_SCHOOL;
case 816: return COLOR_BUS_ROUTES_SCHOOL;
case 817: return COLOR_BUS_ROUTES_SCHOOL;
case 818: return COLOR_BUS_ROUTES_SCHOOL;
case 819: return COLOR_BUS_ROUTES_SCHOOL;
case 821: return COLOR_BUS_ROUTES_SCHOOL;
case 822: return COLOR_BUS_ROUTES_SCHOOL;
case 830: return COLOR_BUS_ROUTES_SCHOOL;
case 831: return COLOR_BUS_ROUTES_SCHOOL;
case 832: return COLOR_BUS_ROUTES_SCHOOL;
case 834: return COLOR_BUS_ROUTES_SCHOOL;
case 835: return COLOR_BUS_ROUTES_SCHOOL;
case 837: return COLOR_BUS_ROUTES_SCHOOL;
case 838: return COLOR_BUS_ROUTES_SCHOOL;
case 841: return COLOR_BUS_ROUTES_SCHOOL;
case 842: return COLOR_BUS_ROUTES_SCHOOL;
case 851: return COLOR_BUS_ROUTES_SCHOOL;
case 853: return COLOR_BUS_ROUTES_SCHOOL;
case 857: return COLOR_BUS_ROUTES_SCHOOL;
case 860: return COLOR_BUS_ROUTES_SCHOOL;
case 861: return COLOR_BUS_ROUTES_SCHOOL;
case 878: return COLOR_BUS_ROUTES_SCHOOL;
case 880: return COLOR_BUS_ROUTES_SCHOOL;
case 883: return COLOR_BUS_ROUTES_SCHOOL;
case 884: return COLOR_BUS_ROUTES_SCHOOL;
case 888: return COLOR_BUS_ROUTES_SCHOOL;
case 889: return COLOR_BUS_ROUTES_SCHOOL;
case 892: return COLOR_BUS_ROUTES_SCHOOL;
// @formatter:on
default:
System.out.println("Unexpected route color " + gRoute);
System.exit(-1);
return null;
}
}
private static final String _69_ST_STN = "69 St Stn";
private static final String ACADIA = "Acadia";
private static final String OAKRIDGE = "Oakridge";
private static final String ACADIA_OAKRIDGE = ACADIA + " / " + OAKRIDGE;
private static final String AIRPORT = "Airport";
private static final String ANDERSON = "Anderson";
private static final String ANDERSON_STN = ANDERSON; // "Anderson Stn";
private static final String ANNIE_GALE = "Annie Gale";
private static final String APPLEWOOD = "Applewood";
private static final String ARBOUR_LK = "Arbour Lk";
private static final String AUBURN_BAY = "Auburn Bay";
private static final String B_GRANDIN = "B Grandin";
private static final String BARLOW_STN = "Barlow Stn";
private static final String BEAVERBROOK = "Beaverbrook";
private static final String BEDDINGTON = "Beddington";
private static final String BISHOP_O_BYRNE = "B O'Byrne";
private static final String BONAVISTA = "Bonavista";
private static final String BONAVISTA_WEST = "W " + BONAVISTA;
private static final String BOWNESS = "Bowness";
private static final String BREBEUF = "Brebeuf";
private static final String BRENTWOOD = "Brentwood";
private static final String BRENTWOOD_STN = BRENTWOOD; // "Brentwood Stn";
private static final String BRIDGELAND = "Bridgeland";
private static final String CASTLERIDGE = "Castleridge";
private static final String CENTRAL_MEMORIAL = "Central Memorial";
private static final String CHAPARRAL = "Chaparral";
private static final String CHATEAU_ESTS = "Chateau Ests";
private static final String CHINOOK = "Chinook";
private static final String CHINOOK_STN = CHINOOK; // "Chinook Stn";
private static final String CHURCHILL = "Churchill";
private static final String CIRCLE_ROUTE = "Circle Route";
private static final String CITADEL = "Citadel";
private static final String CITY_CTR = "City Ctr";
private static final String COACH_HL = "Coach Hl";
private static final String COPPERFIELD = "Copperfield";
private static final String CORAL_SPGS = "Coral Spgs";
private static final String COUNTRY_HLS = "Country Hls";
private static final String COUNTRY_VLG = "Country Vlg";
private static final String COVENTRY = "Coventry";
private static final String COVENTRY_HLS = COVENTRY + " Hls";
private static final String COVENTRY_SOUTH = "S" + COVENTRY;
private static final String CRANSTON = "Cranston";
private static final String CRESCENT_HTS = "Crescent Hts";
private static final String DALHOUSIE = "Dalhousie";
private static final String DEER_RUN = "Deer Run";
private static final String DEERFOOT_CTR = "Deerfoot Ctr";
private static final String DIEFENBAKER = "Diefenbaker";
private static final String DISCOVERY_RIDGE = "Discovery Rdg";
private static final String DOUGLASDALE = "Douglasdale";
private static final String DOUGLAS_GLEN = "Douglas Glen";
private static final String DOWNTOWN = "Downtown";
private static final String EDGEBROOK_RISE = "Edgebrook Rise";
private static final String EDGEMONT = "Edgemont";
private static final String ELBOW_DR = "Elbow Dr";
private static final String ERIN_WOODS = "Erin Woods";
private static final String ERINWOODS = "Erinwoods";
private static final String EVANSTON = "Evanston";
private static final String EVERGREEN = "Evergreen";
private static final String SOMERSET = "Somerset";
private static final String EVERGREEN_SOMERSET = EVERGREEN + " / " + SOMERSET;
private static final String F_WHELIHAN = "F Whelihan";
private static final String FALCONRIDGE = "Falconridge";
private static final String FOOTHILLS_IND = "Foothills Ind";
private static final String FOREST_HTS = "Forest Hts";
private static final String FOREST_LAWN = "Forest Lawn";
private static final String FOWLER = "Fowler";
private static final String FRANKLIN = "Franklin";
private static final String GLAMORGAN = "Glamorgan";
private static final String GREENWOOD = "Greenwood";
private static final String HAMPTONS = "Hamptons";
private static final String HARVEST_HLS = "Harvest Hls";
private static final String HAWKWOOD = "Hawkwood";
private static final String HERITAGE = "Heritage";
private static final String HERITAGE_STN = HERITAGE; // "Heritage Stn";
private static final String HIDDEN_VLY = "Hidden Vly";
private static final String HILLHURST = "Hillhurst";
private static final String HUNTINGTON = "Huntington";
private static final String KINCORA = "Kincora";
private static final String LAKEVIEW = "Lakeview";
private static final String LIONS_PARK = "Lions Park";
private static final String LIONS_PARK_STN = LIONS_PARK; // "Lions Park Stn";
private static final String LYNNWOOD = "Lynnwood";
private static final String M_D_HOUET = "M d'Houet";
private static final String MAC_EWAN = "MacEwan";
private static final String MARLBOROUGH = "Marlborough";
private static final String MARTINDALE = "Martindale";
private static final String MC_CALL_WAY = "McCall Way";
private static final String MC_KENZIE = "McKenzie";
private static final String MC_KENZIE_LK_WAY = MC_KENZIE + " Lk Way";
private static final String MC_KENZIE_TOWNE = MC_KENZIE + " Towne";
private static final String MC_KENZIE_TOWNE_DR = MC_KENZIE_TOWNE; // "McKenzie Towne Dr";
private static final String MC_KINGHT_WESTWINDS = "McKinght-Westwinds";
private static final String MC_KNIGHT_WESTWINDS = "McKnight-Westwinds";
private static final String MRU = "MRU";
private static final String MRU_NORTH = MRU + " North";
private static final String MRU_SOUTH = MRU + " South";
private static final String MT_ROYAL_U = MRU; // "Mt Royal U";
private static final String MTN_PARK = "Mtn Park";
private static final String NEW_BRIGHTON = "New Brighton";
private static final String NORTH_HAVEN = "North Haven";
private static final String NORTH_POINTE = "North Pte";
private static final String NORTHLAND = "Northland";
private static final String NORTHMOUNT_DR = "Northmount Dr";
private static final String NORTHWEST_LOOP = "Northwest Loop";
private static final String NOTRE_DAME = "Notre Dame";
private static final String OAKRIDGE_ACADIA = OAKRIDGE + " / " + ACADIA;
private static final String OGDEN = "Ogden";
private static final String OGDEN_NORTH = "North " + OGDEN;
private static final String PALLISER_OAKRIDGE = "Palliser / Oakridge";
private static final String PANORAMA = "Panorama";
private static final String PANORAMA_HLS = PANORAMA + " Hls";
private static final String PANORAMA_HLS_NORTH = "N " + PANORAMA_HLS;
private static final String PARKHILL_FOOTHILLS = "Parkhill / Foothills";
private static final String PARKLAND = "Parkland";
private static final String PRESTWICK = "Prestwick";
private static final String QUEEN_ELIZABETH = "Queen Elizabeth";
private static final String QUEENSLAND = "Queensland";
private static final String R_THIRSK = "R Thirsk";
private static final String RAMSAY = "Ramsay";
private static final String RENFREW = "Renfrew";
private static final String RIVERBEND = "Riverbend";
private static final String ROCKY_RIDGE = "Rocky Rdg";
private static final String ROYAL_OAK = "Royal Oak";
private static final String SADDLECREST = "Saddlecrest";
private static final String SADDLE_RIDGE = "Saddle Rdg";
private static final String SADDLETOWN = "Saddletown";
private static final String SADDLETOWNE = "Saddletowne";
private static final String SAGE_HILL_KINCORA = "Sage Hill / Kincora";
private static final String SANDSTONE = "Sandstone";
private static final String SANDSTONE_AIRPORT = "Sandstone / " + AIRPORT;
private static final String SARCEE_RD = "Sarcee Rd";
private static final String SCARLETT = "Scarlett";
private static final String SCENIC_ACRES = "Scenic Acres";
private static final String SCENIC_ACRES_SOUTH = "S " + SCENIC_ACRES;
private static final String SCENIC_ACRES_NORTH = "N " + SCENIC_ACRES;
private static final String SHAWVILLE = "Shawville";
private static final String SHERWOOD = "Sherwood";
private static final String SILVER_SPGS = "Silver Spgs";
private static final String SKYVIEW_RANCH = "Skyview Ranch";
private static final String SOMERSET_BRIDLEWOOD_STN = SOMERSET + "-Bridlewood Stn";
private static final String SOUTH_CALGARY = "South Calgary";
private static final String SOUTH_HEALTH = "South Health";
private static final String SOUTHCENTER = "Southcentre";
private static final String ST_AUGUSTINE = "St Augustine";
private static final String ST_FRANCIS = "St Francis";
private static final String ST_ISABELLA = "St Isabella";
private static final String ST_MARGARET = "St Margaret";
private static final String ST_MATTHEW = "St Matthew";
private static final String ST_STEPHEN = "St Stephen";
private static final String STRATHCONA = "Strathcona";
private static final String TARADALE = "Taradale";
private static final String TOM_BAINES = "Tom Baines";
private static final String TUSCANY = "Tuscany";
private static final String VALLEY_RIDGE = "Vly Rdg";
private static final String VARSITY_ACRES = "Varsity Acres";
private static final String VINCENT_MASSEY = "V Massey";
private static final String VISTA_HTS = "Vista Hts";
private static final String WCHS_ST_MARY_S = "WCHS/St Mary''s";
private static final String WESTBROOK = "Westbrook";
private static final String WESTBROOK_STN = WESTBROOK + " Stn";
private static final String WESTERN_CANADA = "Western Canada";
private static final String WESTGATE = "Westgate";
private static final String WESTHILLS = "Westhills";
private static final String WHITEHORN = "Whitehorn";
private static final String WHITEHORN_STN = WHITEHORN; // WHITEHORN + " Stn";
private static final String WISE_WOOD = "Wise Wood";
private static final String WOODBINE = "Woodbine";
private static final String WOODLANDS = "Woodlands";
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
if (mRoute.id == 1l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(FOREST_LAWN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BOWNESS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 2l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.NORTH);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.SOUTH);
return;
}
} else if (mRoute.id == 3l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SANDSTONE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ELBOW_DR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 4l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HUNTINGTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 5l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(NORTH_HAVEN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 6l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(WESTBROOK_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 7l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SOUTH_CALGARY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 9l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BRIDGELAND, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(VARSITY_ACRES, gTrip.direction_id);
return;
}
} else if (mRoute.id == 10l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(DALHOUSIE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SOUTHCENTER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 13l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(WESTHILLS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 15l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.NORTH);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.SOUTH);
return;
}
} else if (mRoute.id == 17l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(RENFREW, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(RAMSAY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 18l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MT_ROYAL_U, gTrip.direction_id);
return;
}
} else if (mRoute.id == 19l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.EAST);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.WEST);
return;
}
} else if (mRoute.id == 20l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(NORTHMOUNT_DR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(HERITAGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 22l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(DALHOUSIE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 23l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLETOWNE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOOTHILLS_IND, gTrip.direction_id);
return;
}
} else if (mRoute.id == 24l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 26l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(FRANKLIN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MARLBOROUGH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 30l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.NORTH);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.SOUTH);
return;
}
} else if (mRoute.id == 33l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(VISTA_HTS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BARLOW_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 37l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(NORTHWEST_LOOP, gTrip.direction_id);
return;
}
} else if (mRoute.id == 41l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(LYNNWOOD, gTrip.direction_id);
return;
}
} else if (mRoute.id == 49l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOREST_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 52l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(EVERGREEN_SOMERSET, gTrip.direction_id);
return;
}
} else if (mRoute.id == 55l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(FALCONRIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 57l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MC_CALL_WAY, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ERINWOODS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 62l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HIDDEN_VLY, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 63l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(LAKEVIEW, gTrip.direction_id);
return;
}
} else if (mRoute.id == 64l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MAC_EWAN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 66l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLETOWNE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHINOOK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 69l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(DEERFOOT_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 70l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(VALLEY_RIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 71l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLETOWNE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KINGHT_WESTWINDS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 72l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CIRCLE_ROUTE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 73l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CIRCLE_ROUTE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 74l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(TUSCANY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 79l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ACADIA_OAKRIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 80l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(OAKRIDGE_ACADIA, gTrip.direction_id);
return;
}
} else if (mRoute.id == 81l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.NORTH);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.SOUTH);
return;
}
} else if (mRoute.id == 85l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLETOWNE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KNIGHT_WESTWINDS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 86l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.NORTH);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.SOUTH);
return;
}
} else if (mRoute.id == 91l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(LIONS_PARK_STN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BRENTWOOD_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 92l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ANDERSON_STN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KENZIE_TOWNE_DR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 93l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WESTBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(COACH_HL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 94l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(_69_ST_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 98l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(_69_ST_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 100l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(AIRPORT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KNIGHT_WESTWINDS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 102l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DOUGLASDALE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 103l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KENZIE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 107l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SOUTH_CALGARY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 109l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HARVEST_HLS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 110l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 112l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SARCEE_RD, gTrip.direction_id);
return;
}
} else if (mRoute.id == 116l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(COVENTRY_HLS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 117l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KENZIE_TOWNE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 125l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ERIN_WOODS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 126l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(APPLEWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 133l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRANSTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 142l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(PANORAMA, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 145l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(NORTHLAND, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 151l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(NEW_BRIGHTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 152l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(NEW_BRIGHTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 158l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ROYAL_OAK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 174l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(TUSCANY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 176l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.NORTH);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.SOUTH);
return;
}
} else if (mRoute.id == 178l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHAPARRAL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 181l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MRU_NORTH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 182l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MRU_SOUTH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 300l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(AIRPORT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DOWNTOWN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 301l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(COUNTRY_VLG, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 302l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SOUTH_HEALTH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 305l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.EAST);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.WEST);
return;
}
} else if (mRoute.id == 306l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WESTBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(HERITAGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 405l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BRENTWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(HILLHURST, gTrip.direction_id);
return;
}
} else if (mRoute.id == 406l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MC_KENZIE_TOWNE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SHAWVILLE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 407l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BRENTWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(GREENWOOD, gTrip.direction_id);
return;
}
} else if (mRoute.id == 408l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BRENTWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(VALLEY_RIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 411l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 412l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(WESTGATE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 419l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(PARKHILL_FOOTHILLS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 425l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SAGE_HILL_KINCORA, gTrip.direction_id);
return;
}
} else if (mRoute.id == 430l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SANDSTONE_AIRPORT, gTrip.direction_id);
return;
}
} else if (mRoute.id == 439l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(DISCOVERY_RIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 440l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CHATEAU_ESTS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FRANKLIN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 445l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SKYVIEW_RANCH, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SADDLETOWN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 697l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(EVANSTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 698l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WCHS_ST_MARY_S, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(_69_ST_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 699l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.NORTH);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.SOUTH);
return;
}
} else if (mRoute.id == 703l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SHERWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHURCHILL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 704l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(COUNTRY_HLS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHURCHILL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 705l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(EDGEBROOK_RISE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHURCHILL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 706l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HAMPTONS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHURCHILL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 710l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRANSTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 711l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DOUGLAS_GLEN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 712l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(PARKLAND, gTrip.direction_id);
return;
}
} else if (mRoute.id == 713l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DEER_RUN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 714l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(PRESTWICK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 715l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(QUEENSLAND, gTrip.direction_id);
return;
}
} else if (mRoute.id == 716l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(NEW_BRIGHTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 717l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(COPPERFIELD, gTrip.direction_id);
return;
}
} else if (mRoute.id == 718l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DOUGLASDALE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 719l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KENZIE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 721l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(TUSCANY, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BOWNESS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 724l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(TUSCANY, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BOWNESS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 725l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SILVER_SPGS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BOWNESS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 731l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(RIVERBEND, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CENTRAL_MEMORIAL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 732l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CENTRAL_MEMORIAL, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(GLAMORGAN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 733l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CENTRAL_MEMORIAL, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(LAKEVIEW, gTrip.direction_id);
return;
}
} else if (mRoute.id == 734l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(OGDEN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CENTRAL_MEMORIAL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 735l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(OGDEN_NORTH, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CENTRAL_MEMORIAL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 737l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HARVEST_HLS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DIEFENBAKER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 738l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(PANORAMA_HLS_NORTH, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DIEFENBAKER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 739l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(PANORAMA_HLS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DIEFENBAKER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 740l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLETOWNE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 741l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLECREST, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 742l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLE_RIDGE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 743l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WHITEHORN_STN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 744l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(COVENTRY_SOUTH, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 745l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(VISTA_HTS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 746l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(COVENTRY_HLS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 747l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HIDDEN_VLY, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 751l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(TARADALE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 752l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MARTINDALE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 753l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(EVANSTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 754l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLETOWNE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 755l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CASTLERIDGE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 756l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MARTINDALE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 757l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CORAL_SPGS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 758l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(TARADALE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 759l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(FALCONRIDGE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 760l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BONAVISTA_WEST, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SCARLETT, gTrip.direction_id);
return;
}
} else if (mRoute.id == 761l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SCARLETT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(AUBURN_BAY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 762l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BONAVISTA, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SCARLETT, gTrip.direction_id);
return;
}
} else if (mRoute.id == 763l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SCARLETT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(WOODBINE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 764l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SCARLETT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SOMERSET_BRIDLEWOOD_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 765l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SCARLETT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SOMERSET_BRIDLEWOOD_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 766l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SCARLETT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(EVERGREEN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 770l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WESTERN_CANADA, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(OGDEN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 771l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHINOOK_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 773l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(R_THIRSK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ROCKY_RIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 774l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(R_THIRSK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ROYAL_OAK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 775l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITADEL, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(R_THIRSK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 776l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WISE_WOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(PALLISER_OAKRIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 778l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WISE_WOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(WOODLANDS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 779l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WISE_WOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(WOODBINE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 780l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WISE_WOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(OAKRIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 791l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MAC_EWAN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(QUEEN_ELIZABETH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 792l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SANDSTONE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(QUEEN_ELIZABETH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 795l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(VINCENT_MASSEY, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(STRATHCONA, gTrip.direction_id);
return;
}
} else if (mRoute.id == 796l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(EDGEMONT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(TOM_BAINES, gTrip.direction_id);
return;
}
} else if (mRoute.id == 798l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(TARADALE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ANNIE_GALE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 799l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CORAL_SPGS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ANNIE_GALE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 801l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BREBEUF, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ROYAL_OAK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 802l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BREBEUF, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(HAWKWOOD, gTrip.direction_id);
return;
}
} else if (mRoute.id == 804l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SHERWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BREBEUF, gTrip.direction_id);
return;
}
} else if (mRoute.id == 805l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HAMPTONS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BREBEUF, gTrip.direction_id);
return;
}
} else if (mRoute.id == 807l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BREBEUF, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ROCKY_RIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 811l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(TUSCANY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 812l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITADEL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 813l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ARBOUR_LK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 814l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ROYAL_OAK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 815l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ARBOUR_LK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 816l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITADEL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 817l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ROCKY_RIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 818l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HAMPTONS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 819l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SHERWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 821l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MTN_PARK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BISHOP_O_BYRNE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 822l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MC_KENZIE_LK_WAY, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BISHOP_O_BYRNE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 830l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SANDSTONE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(M_D_HOUET, gTrip.direction_id);
return;
}
} else if (mRoute.id == 831l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SCENIC_ACRES_NORTH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 832l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SCENIC_ACRES_SOUTH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 834l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(DALHOUSIE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(M_D_HOUET, gTrip.direction_id);
return;
}
} else if (mRoute.id == 835l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ANDERSON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 837l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SCENIC_ACRES_SOUTH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 838l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SCENIC_ACRES_NORTH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 841l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(NOTRE_DAME, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(HIDDEN_VLY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 842l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(NOTRE_DAME, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MAC_EWAN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 851l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(LYNNWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ST_AUGUSTINE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 853l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(RIVERBEND, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ST_AUGUSTINE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 857l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_STEPHEN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(EVERGREEN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 860l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(B_GRANDIN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRANSTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 861l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(B_GRANDIN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(AUBURN_BAY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 878l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(F_WHELIHAN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHAPARRAL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 880l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_MATTHEW, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(HERITAGE_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 883l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(EVANSTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 884l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(KINCORA, gTrip.direction_id);
return;
}
} else if (mRoute.id == 888l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(NORTH_POINTE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ST_MARGARET, gTrip.direction_id);
return;
}
} else if (mRoute.id == 889l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEDDINGTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 892l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_ISABELLA, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KENZIE, gTrip.direction_id);
return;
}
}
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.trip_headsign.toLowerCase(Locale.ENGLISH)), gTrip.direction_id);
}
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = tripHeadsign.toLowerCase(Locale.ENGLISH);
return MSpec.cleanLabel(tripHeadsign);
}
private static final Pattern ENDS_WITH_BOUND = Pattern.compile("([\\s]*[s|e|w|n]b[\\s]$)", Pattern.CASE_INSENSITIVE);
private static final Pattern STARTS_WITH_BOUND = Pattern.compile("(^[\\s]*[s|e|w|n]b[\\s]*)", Pattern.CASE_INSENSITIVE);
private static final Pattern STARTS_WITH_SLASH = Pattern.compile("(^[\\s]*/[\\s]*)", Pattern.CASE_INSENSITIVE);
private static final String REGEX_START_END = "((^|[^A-Z]){1}(%s)([^a-zA-Z]|$){1})";
private static final String REGEX_START_END_REPLACEMENT = "$2 %s $4";
private static final Pattern AT_SIGN = Pattern.compile("([\\s]*@[\\s]*)", Pattern.CASE_INSENSITIVE);
private static final String AT_SIGN_REPLACEMENT = " / ";
private static final Pattern STATION = Pattern.compile(String.format(REGEX_START_END, "station"), Pattern.CASE_INSENSITIVE);
private static final String STATION_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Stn");
private static final Pattern AV = Pattern.compile(String.format(REGEX_START_END, "AV|AVE"));
private static final String AV_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Avenue");
private static final Pattern PA = Pattern.compile(String.format(REGEX_START_END, "PA"));
private static final String PA_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Park");
private static final Pattern HT = Pattern.compile(String.format(REGEX_START_END, "HT"));
private static final String HT_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Heights");
private static final Pattern GV = Pattern.compile(String.format(REGEX_START_END, "GV"));
private static final String GV_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Grove");
private static final Pattern PT = Pattern.compile(String.format(REGEX_START_END, "PT"));
private static final String PT_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Point");
private static final Pattern TC = Pattern.compile(String.format(REGEX_START_END, "TC"));
private static final String TC_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Terrace");
private static final Pattern RI = Pattern.compile(String.format(REGEX_START_END, "RI"));
private static final String RI_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Rise");
private static final Pattern MR = Pattern.compile(String.format(REGEX_START_END, "MR"));
private static final String MR_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Manor");
private static final Pattern DR = Pattern.compile(String.format(REGEX_START_END, "DR"));
private static final String DR_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Drive");
private static final Pattern ST = Pattern.compile(String.format(REGEX_START_END, "ST"));
private static final String ST_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Street");
private static final Pattern VI = Pattern.compile(String.format(REGEX_START_END, "VI"));
private static final String VI_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Villas");
private static final Pattern PZ = Pattern.compile(String.format(REGEX_START_END, "PZ"));
private static final String PZ_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Plaza");
private static final Pattern WY = Pattern.compile(String.format(REGEX_START_END, "WY"));
private static final String WY_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Way");
private static final Pattern GR = Pattern.compile(String.format(REGEX_START_END, "GR"));
private static final String GR_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Green");
private static final Pattern BV = Pattern.compile(String.format(REGEX_START_END, "BV"));
private static final String BV_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Boulevard");
private static final Pattern GA = Pattern.compile(String.format(REGEX_START_END, "GA"));
private static final String GA_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Gate");
private static final Pattern RD = Pattern.compile(String.format(REGEX_START_END, "RD"));
private static final String RD_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Road");
private static final Pattern LI = Pattern.compile(String.format(REGEX_START_END, "LI|LINK"));
private static final String LI_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Link");
private static final Pattern PL = Pattern.compile(String.format(REGEX_START_END, "PL"));
private static final String PL_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Place");
private static final Pattern SQ = Pattern.compile(String.format(REGEX_START_END, "SQ"));
private static final String SQ_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Square");
private static final Pattern CL = Pattern.compile(String.format(REGEX_START_END, "CL"));
private static final String CL_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Close");
private static final Pattern CR = Pattern.compile(String.format(REGEX_START_END, "CR"));
private static final String CR_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Crescent");
private static final Pattern GD = Pattern.compile(String.format(REGEX_START_END, "GD"));
private static final String GD_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Gardens");
private static final Pattern LN = Pattern.compile(String.format(REGEX_START_END, "LN"));
private static final String LN_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Lane");
private static final Pattern CO = Pattern.compile(String.format(REGEX_START_END, "CO"));
private static final String CO_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Ct");
private static final Pattern CI = Pattern.compile(String.format(REGEX_START_END, "CI"));
private static final String CI_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Circle");
private static final Pattern HE = Pattern.compile(String.format(REGEX_START_END, "HE"));
private static final String HE_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Heath");
private static final Pattern ME = Pattern.compile(String.format(REGEX_START_END, "ME"));
private static final String ME_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Mews");
private static final Pattern TR = Pattern.compile(String.format(REGEX_START_END, "TR"));
private static final String TR_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Trail");
private static final Pattern LD = Pattern.compile(String.format(REGEX_START_END, "LD"));
private static final String LD_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Landing");
private static final Pattern HL = Pattern.compile(String.format(REGEX_START_END, "HL"));
private static final String HL_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Hill");
private static final Pattern PK = Pattern.compile(String.format(REGEX_START_END, "PK"));
private static final String PK_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Park");
private static final Pattern CM = Pattern.compile(String.format(REGEX_START_END, "CM"));
private static final String CM_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Common");
private static final Pattern GT = Pattern.compile(String.format(REGEX_START_END, "GT"));
private static final String GT_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Gate");
private static final Pattern CV = Pattern.compile(String.format(REGEX_START_END, "CV"));
private static final String CV_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Cove");
private static final Pattern VW = Pattern.compile(String.format(REGEX_START_END, "VW"));
private static final String VW_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "View");
private static final Pattern BY = Pattern.compile(String.format(REGEX_START_END, "BY|BA|BAY"));
private static final String BY_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Bay");
private static final Pattern CE = Pattern.compile(String.format(REGEX_START_END, "CE"));
private static final String CE_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Center");
private static final Pattern CTR = Pattern.compile(String.format(REGEX_START_END, "CTR"));
private static final String CTR_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Center");
private static final Pattern MOUNT_ROYAL_UNIVERSITY = Pattern.compile(String.format(REGEX_START_END, "Mount Royal University"));
private static final String MOUNT_ROYAL_UNIVERSITY_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "MRU");
private static final Pattern MOUNT = Pattern.compile(String.format(REGEX_START_END, "Mount"));
private static final String MOUNT_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Mt");
@Override
public String cleanStopName(String gStopName) {
gStopName = STARTS_WITH_BOUND.matcher(gStopName).replaceAll(StringUtils.EMPTY);
gStopName = ENDS_WITH_BOUND.matcher(gStopName).replaceAll(StringUtils.EMPTY);
gStopName = AT_SIGN.matcher(gStopName).replaceAll(AT_SIGN_REPLACEMENT);
gStopName = AV.matcher(gStopName).replaceAll(AV_REPLACEMENT);
gStopName = PA.matcher(gStopName).replaceAll(PA_REPLACEMENT);
gStopName = HT.matcher(gStopName).replaceAll(HT_REPLACEMENT);
gStopName = GV.matcher(gStopName).replaceAll(GV_REPLACEMENT);
gStopName = PT.matcher(gStopName).replaceAll(PT_REPLACEMENT);
gStopName = TC.matcher(gStopName).replaceAll(TC_REPLACEMENT);
gStopName = RI.matcher(gStopName).replaceAll(RI_REPLACEMENT);
gStopName = MR.matcher(gStopName).replaceAll(MR_REPLACEMENT);
gStopName = DR.matcher(gStopName).replaceAll(DR_REPLACEMENT);
gStopName = ST.matcher(gStopName).replaceAll(ST_REPLACEMENT);
gStopName = VI.matcher(gStopName).replaceAll(VI_REPLACEMENT);
gStopName = PZ.matcher(gStopName).replaceAll(PZ_REPLACEMENT);
gStopName = WY.matcher(gStopName).replaceAll(WY_REPLACEMENT);
gStopName = GR.matcher(gStopName).replaceAll(GR_REPLACEMENT);
gStopName = BV.matcher(gStopName).replaceAll(BV_REPLACEMENT);
gStopName = GA.matcher(gStopName).replaceAll(GA_REPLACEMENT);
gStopName = RD.matcher(gStopName).replaceAll(RD_REPLACEMENT);
gStopName = LI.matcher(gStopName).replaceAll(LI_REPLACEMENT);
gStopName = PL.matcher(gStopName).replaceAll(PL_REPLACEMENT);
gStopName = SQ.matcher(gStopName).replaceAll(SQ_REPLACEMENT);
gStopName = CL.matcher(gStopName).replaceAll(CL_REPLACEMENT);
gStopName = CR.matcher(gStopName).replaceAll(CR_REPLACEMENT);
gStopName = GD.matcher(gStopName).replaceAll(GD_REPLACEMENT);
gStopName = LN.matcher(gStopName).replaceAll(LN_REPLACEMENT);
gStopName = CO.matcher(gStopName).replaceAll(CO_REPLACEMENT);
gStopName = ME.matcher(gStopName).replaceAll(ME_REPLACEMENT);
gStopName = TR.matcher(gStopName).replaceAll(TR_REPLACEMENT);
gStopName = CI.matcher(gStopName).replaceAll(CI_REPLACEMENT);
gStopName = HE.matcher(gStopName).replaceAll(HE_REPLACEMENT);
gStopName = LD.matcher(gStopName).replaceAll(LD_REPLACEMENT);
gStopName = HL.matcher(gStopName).replaceAll(HL_REPLACEMENT);
gStopName = PK.matcher(gStopName).replaceAll(PK_REPLACEMENT);
gStopName = CM.matcher(gStopName).replaceAll(CM_REPLACEMENT);
gStopName = GT.matcher(gStopName).replaceAll(GT_REPLACEMENT);
gStopName = CV.matcher(gStopName).replaceAll(CV_REPLACEMENT);
gStopName = VW.matcher(gStopName).replaceAll(VW_REPLACEMENT);
gStopName = BY.matcher(gStopName).replaceAll(BY_REPLACEMENT);
gStopName = CE.matcher(gStopName).replaceAll(CE_REPLACEMENT);
gStopName = CTR.matcher(gStopName).replaceAll(CTR_REPLACEMENT);
gStopName = MOUNT_ROYAL_UNIVERSITY.matcher(gStopName).replaceAll(MOUNT_ROYAL_UNIVERSITY_REPLACEMENT);
gStopName = MOUNT.matcher(gStopName).replaceAll(MOUNT_REPLACEMENT);
gStopName = STATION.matcher(gStopName).replaceAll(STATION_REPLACEMENT);
gStopName = MSpec.cleanStreetTypes(gStopName);
gStopName = MSpec.cleanNumbers(gStopName);
gStopName = STARTS_WITH_SLASH.matcher(gStopName).replaceAll(StringUtils.EMPTY);
return MSpec.cleanLabel(gStopName);
}
}
|
src/org/mtransit/parser/ca_calgary_transit_bus/CalgaryTransitBusAgencyTools.java
|
package org.mtransit.parser.ca_calgary_transit_bus;
import java.util.HashSet;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MDirectionType;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MSpec;
import org.mtransit.parser.mt.data.MTrip;
import org.mtransit.parser.mt.data.MTripStop;
// https://www.calgarytransit.com/developer-resources
// https://data.calgary.ca/OpenData/Pages/DatasetDetails.aspx?DatasetID=PDC0-99999-99999-00501-P(CITYonlineDefault)
// https://data.calgary.ca/_layouts/OpenData/DownloadDataset.ashx?Format=FILE&DatasetId=PDC0-99999-99999-00501-P(CITYonlineDefault)&VariantId=5(CITYonlineDefault)
public class CalgaryTransitBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-calgary-transit-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new CalgaryTransitBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("Generating Calgary Transit bus data...\n");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this);
super.start(args);
System.out.printf("Generating Calgary Transit bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
@Override
public long getRouteId(GRoute gRoute) {
return Long.parseLong(gRoute.route_short_name); // using route short name as route ID
}
private static final Pattern CLEAN_STREET_POINT = Pattern.compile("((\\s)*(ave|st|mt)\\.(\\s)*)", Pattern.CASE_INSENSITIVE);
private static final String CLEAN_AVE_POINT_REPLACEMENT = "$2$3$4";
@Override
public String getRouteLongName(GRoute gRoute) {
String gRouteLongName = gRoute.route_long_name;
gRouteLongName = MSpec.CLEAN_SLASHES.matcher(gRouteLongName).replaceAll(MSpec.CLEAN_SLASHES_REPLACEMENT);
gRouteLongName = CLEAN_STREET_POINT.matcher(gRouteLongName).replaceAll(CLEAN_AVE_POINT_REPLACEMENT);
gRouteLongName = MSpec.cleanStreetTypes(gRouteLongName);
return MSpec.cleanLabel(gRouteLongName);
}
private static final String AGENCY_COLOR_RED = "B83A3F"; // LIGHT RED (from web site CSS)
private static final String AGENCY_COLOR = AGENCY_COLOR_RED;
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
private static final String COLOR_BUS_ROUTES = "004B85"; // BLUE (from PDF map)
private static final String COLOR_BUS_ROUTES_EXPRESS = "00BBE5"; // LIGHT BLUE (from PDF map)
private static final String COLOR_BUS_ROUTES_BRT = "ED1C2E"; // RED (from PDF map)
private static final String COLOR_BUS_ROUTES_SCHOOL = "E4A024"; // YELLOW (from PDF map)
@Override
public String getRouteColor(GRoute gRoute) {
int rsn = Integer.parseInt(gRoute.route_short_name);
switch (rsn) {
// @formatter:off
case 1: return null;
case 2: return null;
case 3: return null;
case 4: return null;
case 5: return null;
case 6: return null;
case 7: return null;
case 8: return null;
case 9: return null;
case 10: return null;
case 11: return null;
case 12: return null;
case 13: return null;
case 14: return null;
case 15: return null;
case 16: return null;
case 17: return null;
case 18: return null;
case 19: return null;
case 20: return null;
case 21: return null;
case 22: return COLOR_BUS_ROUTES_EXPRESS;
case 23: return COLOR_BUS_ROUTES_EXPRESS;
case 24: return null;
case 25: return null;
case 26: return null;
case 27: return COLOR_BUS_ROUTES;
case 28: return null;
case 29: return null;
case 30: return COLOR_BUS_ROUTES;
case 32: return null;
case 33: return COLOR_BUS_ROUTES;
case 34: return COLOR_BUS_ROUTES;
case 35: return COLOR_BUS_ROUTES;
case 36: return null;
case 37: return null;
case 38: return null;
case 39: return COLOR_BUS_ROUTES;
case 40: return null;
case 41: return null;
case 42: return null;
case 43: return null;
case 44: return COLOR_BUS_ROUTES;
case 45: return null;
case 46: return null;
case 47: return COLOR_BUS_ROUTES;
case 48: return null;
case 49: return null;
case 50: return null;
case 51: return null;
case 52: return null;
case 54: return null;
case 55: return null;
case 56: return null;
case 57: return null;
case 60: return null;
case 61: return COLOR_BUS_ROUTES;
case 62: return COLOR_BUS_ROUTES_EXPRESS;
case 63: return COLOR_BUS_ROUTES_EXPRESS;
case 64: return COLOR_BUS_ROUTES_EXPRESS;
case 66: return COLOR_BUS_ROUTES_EXPRESS;
case 69: return COLOR_BUS_ROUTES;
case 70: return COLOR_BUS_ROUTES_EXPRESS;
case 71: return COLOR_BUS_ROUTES;
case 72: return null;
case 73: return null;
case 74: return null;
case 75: return COLOR_BUS_ROUTES_EXPRESS;
case 76: return null;
case 77: return COLOR_BUS_ROUTES;
case 78: return null;
case 79: return null;
case 80: return null;
case 81: return COLOR_BUS_ROUTES;
case 83: return null;
case 84: return COLOR_BUS_ROUTES;
case 85: return null;
case 86: return null;
case 88: return null;
case 89: return COLOR_BUS_ROUTES;
case 91: return COLOR_BUS_ROUTES;
case 92: return null;
case 93: return COLOR_BUS_ROUTES;
case 94: return COLOR_BUS_ROUTES;
case 95: return COLOR_BUS_ROUTES;
case 96: return null;
case 98: return COLOR_BUS_ROUTES;
case 100: return null;
case 102: return COLOR_BUS_ROUTES_EXPRESS;
case 103: return COLOR_BUS_ROUTES_EXPRESS;
case 107: return COLOR_BUS_ROUTES;
case 109: return COLOR_BUS_ROUTES_EXPRESS;
case 110: return COLOR_BUS_ROUTES_EXPRESS;
case 112: return null;
case 114: return null;
case 116: return COLOR_BUS_ROUTES_EXPRESS;
case 117: return COLOR_BUS_ROUTES_EXPRESS;
case 118: return null;
case 122: return COLOR_BUS_ROUTES;
case 125: return COLOR_BUS_ROUTES_EXPRESS;
case 126: return COLOR_BUS_ROUTES_EXPRESS;
case 127: return null;
case 133: return COLOR_BUS_ROUTES_EXPRESS;
case 136: return COLOR_BUS_ROUTES;
case 137: return null;
case 142: return COLOR_BUS_ROUTES_EXPRESS;
case 143: return null;
case 145: return COLOR_BUS_ROUTES;
case 146: return COLOR_BUS_ROUTES;
case 151: return COLOR_BUS_ROUTES_EXPRESS;
case 152: return COLOR_BUS_ROUTES;
case 153: return COLOR_BUS_ROUTES;
case 154: return null;
case 157: return null;
case 158: return null;
case 159: return COLOR_BUS_ROUTES;
case 169: return null;
case 174: return null;
case 176: return COLOR_BUS_ROUTES_EXPRESS;
case 178: return COLOR_BUS_ROUTES;
case 181: return COLOR_BUS_ROUTES_EXPRESS;
case 182: return COLOR_BUS_ROUTES_EXPRESS;
case 199: return null;
case 299: return null;
case 300: return COLOR_BUS_ROUTES_BRT;
case 301: return COLOR_BUS_ROUTES_BRT;
case 302: return COLOR_BUS_ROUTES_BRT;
case 305: return COLOR_BUS_ROUTES_BRT;
case 306: return COLOR_BUS_ROUTES_BRT;
case 402: return COLOR_BUS_ROUTES;
case 404: return COLOR_BUS_ROUTES;
case 405: return COLOR_BUS_ROUTES;
case 406: return COLOR_BUS_ROUTES;
case 407: return COLOR_BUS_ROUTES;
case 408: return null;
case 409: return COLOR_BUS_ROUTES;
case 410: return COLOR_BUS_ROUTES;
case 411: return COLOR_BUS_ROUTES;
case 412: return COLOR_BUS_ROUTES;
case 414: return COLOR_BUS_ROUTES;
case 419: return COLOR_BUS_ROUTES;
case 420: return COLOR_BUS_ROUTES;
case 421: return COLOR_BUS_ROUTES;
case 425: return COLOR_BUS_ROUTES;
case 429: return COLOR_BUS_ROUTES;
case 430: return COLOR_BUS_ROUTES;
case 439: return COLOR_BUS_ROUTES;
case 440: return COLOR_BUS_ROUTES;
case 444: return COLOR_BUS_ROUTES;
case 445: return COLOR_BUS_ROUTES;
case 452: return COLOR_BUS_ROUTES;
case 453: return COLOR_BUS_ROUTES;
case 454: return COLOR_BUS_ROUTES;
case 456: return COLOR_BUS_ROUTES;
case 468: return COLOR_BUS_ROUTES;
case 502: return null;
case 506: return COLOR_BUS_ROUTES;
case 555: return null;
case 697: return COLOR_BUS_ROUTES_SCHOOL;
case 698: return COLOR_BUS_ROUTES_SCHOOL;
case 699: return COLOR_BUS_ROUTES_SCHOOL;
case 703: return COLOR_BUS_ROUTES_SCHOOL;
case 704: return COLOR_BUS_ROUTES_SCHOOL;
case 705: return COLOR_BUS_ROUTES_SCHOOL;
case 706: return COLOR_BUS_ROUTES_SCHOOL;
case 710: return COLOR_BUS_ROUTES_SCHOOL;
case 711: return COLOR_BUS_ROUTES_SCHOOL;
case 712: return COLOR_BUS_ROUTES_SCHOOL;
case 713: return COLOR_BUS_ROUTES_SCHOOL;
case 714: return COLOR_BUS_ROUTES_SCHOOL;
case 715: return COLOR_BUS_ROUTES_SCHOOL;
case 716: return COLOR_BUS_ROUTES_SCHOOL;
case 717: return COLOR_BUS_ROUTES_SCHOOL;
case 718: return COLOR_BUS_ROUTES_SCHOOL;
case 719: return COLOR_BUS_ROUTES_SCHOOL;
case 721: return COLOR_BUS_ROUTES_SCHOOL;
case 724: return COLOR_BUS_ROUTES_SCHOOL;
case 725: return COLOR_BUS_ROUTES_SCHOOL;
case 731: return COLOR_BUS_ROUTES_SCHOOL;
case 732: return COLOR_BUS_ROUTES_SCHOOL;
case 733: return COLOR_BUS_ROUTES_SCHOOL;
case 734: return COLOR_BUS_ROUTES_SCHOOL;
case 735: return COLOR_BUS_ROUTES_SCHOOL;
case 737: return COLOR_BUS_ROUTES_SCHOOL;
case 738: return COLOR_BUS_ROUTES_SCHOOL;
case 739: return COLOR_BUS_ROUTES_SCHOOL;
case 740: return COLOR_BUS_ROUTES_SCHOOL;
case 741: return COLOR_BUS_ROUTES_SCHOOL;
case 742: return COLOR_BUS_ROUTES_SCHOOL;
case 743: return COLOR_BUS_ROUTES_SCHOOL;
case 744: return COLOR_BUS_ROUTES_SCHOOL;
case 745: return COLOR_BUS_ROUTES_SCHOOL;
case 746: return COLOR_BUS_ROUTES_SCHOOL;
case 747: return COLOR_BUS_ROUTES_SCHOOL;
case 751: return COLOR_BUS_ROUTES_SCHOOL;
case 752: return COLOR_BUS_ROUTES_SCHOOL;
case 753: return COLOR_BUS_ROUTES_SCHOOL;
case 754: return COLOR_BUS_ROUTES_SCHOOL;
case 755: return COLOR_BUS_ROUTES_SCHOOL;
case 756: return COLOR_BUS_ROUTES_SCHOOL;
case 757: return COLOR_BUS_ROUTES_SCHOOL;
case 758: return COLOR_BUS_ROUTES_SCHOOL;
case 759: return COLOR_BUS_ROUTES_SCHOOL;
case 760: return COLOR_BUS_ROUTES_SCHOOL;
case 761: return COLOR_BUS_ROUTES_SCHOOL;
case 762: return COLOR_BUS_ROUTES_SCHOOL;
case 763: return COLOR_BUS_ROUTES_SCHOOL;
case 764: return COLOR_BUS_ROUTES_SCHOOL;
case 765: return COLOR_BUS_ROUTES_SCHOOL;
case 766: return COLOR_BUS_ROUTES_SCHOOL;
case 770: return COLOR_BUS_ROUTES_SCHOOL;
case 771: return COLOR_BUS_ROUTES_SCHOOL;
case 773: return COLOR_BUS_ROUTES_SCHOOL;
case 774: return COLOR_BUS_ROUTES_SCHOOL;
case 775: return COLOR_BUS_ROUTES_SCHOOL;
case 776: return COLOR_BUS_ROUTES_SCHOOL;
case 778: return COLOR_BUS_ROUTES_SCHOOL;
case 779: return COLOR_BUS_ROUTES_SCHOOL;
case 780: return COLOR_BUS_ROUTES_SCHOOL;
case 791: return COLOR_BUS_ROUTES_SCHOOL;
case 792: return COLOR_BUS_ROUTES_SCHOOL;
case 795: return COLOR_BUS_ROUTES_SCHOOL;
case 796: return COLOR_BUS_ROUTES_SCHOOL;
case 797: return COLOR_BUS_ROUTES_SCHOOL;
case 798: return COLOR_BUS_ROUTES_SCHOOL;
case 799: return COLOR_BUS_ROUTES_SCHOOL;
case 801: return COLOR_BUS_ROUTES_SCHOOL;
case 802: return COLOR_BUS_ROUTES_SCHOOL;
case 804: return COLOR_BUS_ROUTES_SCHOOL;
case 805: return COLOR_BUS_ROUTES_SCHOOL;
case 807: return COLOR_BUS_ROUTES_SCHOOL;
case 811: return COLOR_BUS_ROUTES_SCHOOL;
case 812: return COLOR_BUS_ROUTES_SCHOOL;
case 813: return COLOR_BUS_ROUTES_SCHOOL;
case 814: return COLOR_BUS_ROUTES_SCHOOL;
case 815: return COLOR_BUS_ROUTES_SCHOOL;
case 816: return COLOR_BUS_ROUTES_SCHOOL;
case 817: return COLOR_BUS_ROUTES_SCHOOL;
case 818: return COLOR_BUS_ROUTES_SCHOOL;
case 819: return COLOR_BUS_ROUTES_SCHOOL;
case 821: return COLOR_BUS_ROUTES_SCHOOL;
case 822: return COLOR_BUS_ROUTES_SCHOOL;
case 830: return COLOR_BUS_ROUTES_SCHOOL;
case 831: return COLOR_BUS_ROUTES_SCHOOL;
case 832: return COLOR_BUS_ROUTES_SCHOOL;
case 834: return COLOR_BUS_ROUTES_SCHOOL;
case 835: return COLOR_BUS_ROUTES_SCHOOL;
case 837: return COLOR_BUS_ROUTES_SCHOOL;
case 838: return COLOR_BUS_ROUTES_SCHOOL;
case 841: return COLOR_BUS_ROUTES_SCHOOL;
case 842: return COLOR_BUS_ROUTES_SCHOOL;
case 851: return COLOR_BUS_ROUTES_SCHOOL;
case 853: return COLOR_BUS_ROUTES_SCHOOL;
case 857: return COLOR_BUS_ROUTES_SCHOOL;
case 860: return COLOR_BUS_ROUTES_SCHOOL;
case 861: return COLOR_BUS_ROUTES_SCHOOL;
case 878: return COLOR_BUS_ROUTES_SCHOOL;
case 880: return COLOR_BUS_ROUTES_SCHOOL;
case 883: return COLOR_BUS_ROUTES_SCHOOL;
case 884: return COLOR_BUS_ROUTES_SCHOOL;
case 888: return COLOR_BUS_ROUTES_SCHOOL;
case 889: return COLOR_BUS_ROUTES_SCHOOL;
case 892: return COLOR_BUS_ROUTES_SCHOOL;
// @formatter:on
default:
System.out.println("Unexpected route color " + gRoute);
System.exit(-1);
return null;
}
}
private static final String _69_ST_STN = "69 St Stn";
private static final String ACADIA = "Acadia";
private static final String OAKRIDGE = "Oakridge";
private static final String ACADIA_OAKRIDGE = ACADIA + " / " + OAKRIDGE;
private static final String AIRPORT = "Airport";
private static final String ANDERSON = "Anderson";
private static final String ANDERSON_STN = ANDERSON; // "Anderson Stn";
private static final String ANNIE_GALE = "Annie Gale";
private static final String APPLEWOOD = "Applewood";
private static final String ARBOUR_LK = "Arbour Lk";
private static final String AUBURN_BAY = "Auburn Bay";
private static final String B_GRANDIN = "B Grandin";
private static final String BARLOW_STN = "Barlow Stn";
private static final String BEAVERBROOK = "Beaverbrook";
private static final String BEDDINGTON = "Beddington";
private static final String BISHOP_O_BYRNE = "B O'Byrne";
private static final String BONAVISTA = "Bonavista";
private static final String BONAVISTA_WEST = "W " + BONAVISTA;
private static final String BOWNESS = "Bowness";
private static final String BREBEUF = "Brebeuf";
private static final String BRENTWOOD = "Brentwood";
private static final String BRENTWOOD_STN = BRENTWOOD; // "Brentwood Stn";
private static final String BRIDGELAND = "Bridgeland";
private static final String CASTLERIDGE = "Castleridge";
private static final String CENTRAL_MEMORIAL = "Central Memorial";
private static final String CHAPARRAL = "Chaparral";
private static final String CHATEAU_ESTS = "Chateau Ests";
private static final String CHINOOK = "Chinook";
private static final String CHINOOK_STN = CHINOOK; // "Chinook Stn";
private static final String CHURCHILL = "Churchill";
private static final String CIRCLE_ROUTE = "Circle Route";
private static final String CITADEL = "Citadel";
private static final String CITY_CTR = "City Ctr";
private static final String COACH_HL = "Coach Hl";
private static final String COPPERFIELD = "Copperfield";
private static final String CORAL_SPGS = "Coral Spgs";
private static final String COUNTRY_HLS = "Country Hls";
private static final String COUNTRY_VLG = "Country Vlg";
private static final String COVENTRY = "Coventry";
private static final String COVENTRY_HLS = COVENTRY + " Hls";
private static final String COVENTRY_SOUTH = "S" + COVENTRY;
private static final String CRANSTON = "Cranston";
private static final String CRESCENT_HTS = "Crescent Hts";
private static final String DALHOUSIE = "Dalhousie";
private static final String DEER_RUN = "Deer Run";
private static final String DEERFOOT_CTR = "Deerfoot Ctr";
private static final String DIEFENBAKER = "Diefenbaker";
private static final String DISCOVERY_RIDGE = "Discovery Rdg";
private static final String DOUGLASDALE = "Douglasdale";
private static final String DOUGLAS_GLEN = "Douglas Glen";
private static final String DOWNTOWN = "Downtown";
private static final String EDGEBROOK_RISE = "Edgebrook Rise";
private static final String EDGEMONT = "Edgemont";
private static final String ELBOW_DR = "Elbow Dr";
private static final String ERIN_WOODS = "Erin Woods";
private static final String ERINWOODS = "Erinwoods";
private static final String EVANSTON = "Evanston";
private static final String EVERGREEN = "Evergreen";
private static final String SOMERSET = "Somerset";
private static final String EVERGREEN_SOMERSET = EVERGREEN + " / " + SOMERSET;
private static final String F_WHELIHAN = "F Whelihan";
private static final String FALCONRIDGE = "Falconridge";
private static final String FOOTHILLS_IND = "Foothills Ind";
private static final String FOREST_HTS = "Forest Hts";
private static final String FOREST_LAWN = "Forest Lawn";
private static final String FOWLER = "Fowler";
private static final String FRANKLIN = "Franklin";
private static final String GLAMORGAN = "Glamorgan";
private static final String GREENWOOD = "Greenwood";
private static final String HAMPTONS = "Hamptons";
private static final String HARVEST_HLS = "Harvest Hls";
private static final String HAWKWOOD = "Hawkwood";
private static final String HERITAGE = "Heritage";
private static final String HERITAGE_STN = HERITAGE; // "Heritage Stn";
private static final String HIDDEN_VLY = "Hidden Vly";
private static final String HILLHURST = "Hillhurst";
private static final String HUNTINGTON = "Huntington";
private static final String KINCORA = "Kincora";
private static final String LAKEVIEW = "Lakeview";
private static final String LIONS_PARK = "Lions Park";
private static final String LIONS_PARK_STN = LIONS_PARK; // "Lions Park Stn";
private static final String LYNNWOOD = "Lynnwood";
private static final String M_D_HOUET = "M d'Houet";
private static final String MAC_EWAN = "MacEwan";
private static final String MARLBOROUGH = "Marlborough";
private static final String MARTINDALE = "Martindale";
private static final String MC_CALL_WAY = "McCall Way";
private static final String MC_KENZIE = "McKenzie";
private static final String MC_KENZIE_LK_WAY = MC_KENZIE + " Lk Way";
private static final String MC_KENZIE_TOWNE = MC_KENZIE + " Towne";
private static final String MC_KENZIE_TOWNE_DR = MC_KENZIE_TOWNE; // "McKenzie Towne Dr";
private static final String MC_KINGHT_WESTWINDS = "McKinght-Westwinds";
private static final String MC_KNIGHT_WESTWINDS = "McKnight-Westwinds";
private static final String MRU = "MRU";
private static final String MRU_NORTH = MRU + " North";
private static final String MRU_SOUTH = MRU + " South";
private static final String MT_ROYAL_U = MRU; // "Mt Royal U";
private static final String MTN_PARK = "Mtn Park";
private static final String NEW_BRIGHTON = "New Brighton";
private static final String NORTH_HAVEN = "North Haven";
private static final String NORTH_POINTE = "North Pte";
private static final String NORTHLAND = "Northland";
private static final String NORTHMOUNT_DR = "Northmount Dr";
private static final String NORTHWEST_LOOP = "Northwest Loop";
private static final String NOTRE_DAME = "Notre Dame";
private static final String OAKRIDGE_ACADIA = OAKRIDGE + " / " + ACADIA;
private static final String OGDEN = "Ogden";
private static final String OGDEN_NORTH = "North " + OGDEN;
private static final String PALLISER_OAKRIDGE = "Palliser / Oakridge";
private static final String PANORAMA = "Panorama";
private static final String PANORAMA_HLS = PANORAMA + " Hls";
private static final String PANORAMA_HLS_NORTH = "N " + PANORAMA_HLS;
private static final String PARKHILL_FOOTHILLS = "Parkhill / Foothills";
private static final String PARKLAND = "Parkland";
private static final String PRESTWICK = "Prestwick";
private static final String QUEEN_ELIZABETH = "Queen Elizabeth";
private static final String QUEENSLAND = "Queensland";
private static final String R_THIRSK = "R Thirsk";
private static final String RAMSAY = "Ramsay";
private static final String RENFREW = "Renfrew";
private static final String RIVERBEND = "Riverbend";
private static final String ROCKY_RIDGE = "Rocky Rdg";
private static final String ROYAL_OAK = "Royal Oak";
private static final String SADDLECREST = "Saddlecrest";
private static final String SADDLE_RIDGE = "Saddle Rdg";
private static final String SADDLETOWN = "Saddletown";
private static final String SADDLETOWNE = "Saddletowne";
private static final String SAGE_HILL_KINCORA = "Sage Hill / Kincora";
private static final String SANDSTONE = "Sandstone";
private static final String SANDSTONE_AIRPORT = "Sandstone / " + AIRPORT;
private static final String SARCEE_RD = "Sarcee Rd";
private static final String SCARLETT = "Scarlett";
private static final String SCENIC_ACRES = "Scenic Acres";
private static final String SCENIC_ACRES_SOUTH = "S " + SCENIC_ACRES;
private static final String SCENIC_ACRES_NORTH = "N " + SCENIC_ACRES;
private static final String SHAWVILLE = "Shawville";
private static final String SHERWOOD = "Sherwood";
private static final String SILVER_SPGS = "Silver Spgs";
private static final String SKYVIEW_RANCH = "Skyview Ranch";
private static final String SOMERSET_BRIDLEWOOD_STN = SOMERSET + "-Bridlewood Stn";
private static final String SOUTH_CALGARY = "South Calgary";
private static final String SOUTH_HEALTH = "South Health";
private static final String SOUTHCENTER = "Southcentre";
private static final String ST_AUGUSTINE = "St Augustine";
private static final String ST_FRANCIS = "St Francis";
private static final String ST_ISABELLA = "St Isabella";
private static final String ST_MARGARET = "St Margaret";
private static final String ST_MATTHEW = "St Matthew";
private static final String ST_STEPHEN = "St Stephen";
private static final String STRATHCONA = "Strathcona";
private static final String TARADALE = "Taradale";
private static final String TOM_BAINES = "Tom Baines";
private static final String TUSCANY = "Tuscany";
private static final String VALLEY_RIDGE = "Vly Rdg";
private static final String VARSITY_ACRES = "Varsity Acres";
private static final String VINCENT_MASSEY = "V Massey";
private static final String VISTA_HTS = "Vista Hts";
private static final String WCHS_ST_MARY_S = "WCHS/St Mary''s";
private static final String WESTBROOK = "Westbrook";
private static final String WESTBROOK_STN = WESTBROOK + " Stn";
private static final String WESTERN_CANADA = "Western Canada";
private static final String WESTGATE = "Westgate";
private static final String WESTHILLS = "Westhills";
private static final String WHITEHORN = "Whitehorn";
private static final String WHITEHORN_STN = WHITEHORN; // WHITEHORN + " Stn";
private static final String WISE_WOOD = "Wise Wood";
private static final String WOODBINE = "Woodbine";
private static final String WOODLANDS = "Woodlands";
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip) {
if (mRoute.id == 1l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(FOREST_LAWN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BOWNESS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 2l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.NORTH);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.SOUTH);
return;
}
} else if (mRoute.id == 3l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SANDSTONE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ELBOW_DR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 4l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HUNTINGTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 5l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(NORTH_HAVEN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 6l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(WESTBROOK_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 7l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SOUTH_CALGARY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 9l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BRIDGELAND, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(VARSITY_ACRES, gTrip.direction_id);
return;
}
} else if (mRoute.id == 10l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(DALHOUSIE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SOUTHCENTER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 13l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(WESTHILLS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 15l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.NORTH);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.SOUTH);
return;
}
} else if (mRoute.id == 17l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(RENFREW, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(RAMSAY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 18l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MT_ROYAL_U, gTrip.direction_id);
return;
}
} else if (mRoute.id == 19l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.EAST);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.WEST);
return;
}
} else if (mRoute.id == 20l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(NORTHMOUNT_DR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(HERITAGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 22l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(DALHOUSIE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 23l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLETOWNE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOOTHILLS_IND, gTrip.direction_id);
return;
}
} else if (mRoute.id == 24l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 26l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(FRANKLIN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MARLBOROUGH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 30l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.NORTH);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.SOUTH);
return;
}
} else if (mRoute.id == 33l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(VISTA_HTS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BARLOW_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 37l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(NORTHWEST_LOOP, gTrip.direction_id);
return;
}
} else if (mRoute.id == 41l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(LYNNWOOD, gTrip.direction_id);
return;
}
} else if (mRoute.id == 49l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOREST_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 52l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(EVERGREEN_SOMERSET, gTrip.direction_id);
return;
}
} else if (mRoute.id == 55l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(FALCONRIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 57l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MC_CALL_WAY, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ERINWOODS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 62l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HIDDEN_VLY, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 63l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(LAKEVIEW, gTrip.direction_id);
return;
}
} else if (mRoute.id == 64l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MAC_EWAN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 66l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLETOWNE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHINOOK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 69l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(DEERFOOT_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 70l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(VALLEY_RIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 71l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLETOWNE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KINGHT_WESTWINDS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 72l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CIRCLE_ROUTE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 73l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CIRCLE_ROUTE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 74l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(TUSCANY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 79l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ACADIA_OAKRIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 80l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(OAKRIDGE_ACADIA, gTrip.direction_id);
return;
}
} else if (mRoute.id == 81l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.NORTH);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.SOUTH);
return;
}
} else if (mRoute.id == 85l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLETOWNE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KNIGHT_WESTWINDS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 86l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.NORTH);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.SOUTH);
return;
}
} else if (mRoute.id == 91l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(LIONS_PARK_STN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BRENTWOOD_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 92l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ANDERSON_STN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KENZIE_TOWNE_DR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 93l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WESTBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(COACH_HL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 94l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(_69_ST_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 98l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(_69_ST_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 100l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(AIRPORT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KNIGHT_WESTWINDS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 102l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DOUGLASDALE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 103l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KENZIE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 107l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SOUTH_CALGARY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 109l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HARVEST_HLS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 110l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 112l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SARCEE_RD, gTrip.direction_id);
return;
}
} else if (mRoute.id == 116l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(COVENTRY_HLS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 117l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KENZIE_TOWNE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 125l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ERIN_WOODS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 126l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(APPLEWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 133l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRANSTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 142l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(PANORAMA, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 145l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(NORTHLAND, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 151l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(NEW_BRIGHTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 152l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(NEW_BRIGHTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 158l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ROYAL_OAK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 174l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(TUSCANY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 176l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.NORTH);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.SOUTH);
return;
}
} else if (mRoute.id == 178l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHAPARRAL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 181l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MRU_NORTH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 182l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MRU_SOUTH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 300l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(AIRPORT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DOWNTOWN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 301l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(COUNTRY_VLG, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 302l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SOUTH_HEALTH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 305l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.EAST);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.WEST);
return;
}
} else if (mRoute.id == 306l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WESTBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(HERITAGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 405l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BRENTWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(HILLHURST, gTrip.direction_id);
return;
}
} else if (mRoute.id == 406l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MC_KENZIE_TOWNE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SHAWVILLE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 407l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BRENTWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(GREENWOOD, gTrip.direction_id);
return;
}
} else if (mRoute.id == 408l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BRENTWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(VALLEY_RIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 411l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.direction_id);
return;
}
} else if (mRoute.id == 412l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(WESTGATE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 419l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(PARKHILL_FOOTHILLS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 425l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SAGE_HILL_KINCORA, gTrip.direction_id);
return;
}
} else if (mRoute.id == 430l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SANDSTONE_AIRPORT, gTrip.direction_id);
return;
}
} else if (mRoute.id == 439l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(DISCOVERY_RIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 440l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CHATEAU_ESTS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FRANKLIN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 445l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SKYVIEW_RANCH, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SADDLETOWN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 697l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(EVANSTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 698l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WCHS_ST_MARY_S, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(_69_ST_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 699l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignDirection(MDirectionType.NORTH);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignDirection(MDirectionType.SOUTH);
return;
}
} else if (mRoute.id == 703l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SHERWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHURCHILL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 704l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(COUNTRY_HLS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHURCHILL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 705l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(EDGEBROOK_RISE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHURCHILL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 706l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HAMPTONS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHURCHILL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 710l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRANSTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 711l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DOUGLAS_GLEN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 712l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(PARKLAND, gTrip.direction_id);
return;
}
} else if (mRoute.id == 713l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DEER_RUN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 714l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(PRESTWICK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 715l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(QUEENSLAND, gTrip.direction_id);
return;
}
} else if (mRoute.id == 716l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(NEW_BRIGHTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 717l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(COPPERFIELD, gTrip.direction_id);
return;
}
} else if (mRoute.id == 718l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DOUGLASDALE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 719l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEAVERBROOK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KENZIE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 721l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(TUSCANY, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BOWNESS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 724l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(TUSCANY, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BOWNESS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 725l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SILVER_SPGS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BOWNESS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 731l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(RIVERBEND, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CENTRAL_MEMORIAL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 732l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CENTRAL_MEMORIAL, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(GLAMORGAN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 733l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CENTRAL_MEMORIAL, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(LAKEVIEW, gTrip.direction_id);
return;
}
} else if (mRoute.id == 734l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(OGDEN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CENTRAL_MEMORIAL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 735l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(OGDEN_NORTH, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CENTRAL_MEMORIAL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 737l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HARVEST_HLS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DIEFENBAKER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 738l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(PANORAMA_HLS_NORTH, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DIEFENBAKER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 739l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(PANORAMA_HLS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(DIEFENBAKER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 740l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLETOWNE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 741l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLECREST, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 742l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLE_RIDGE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 743l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WHITEHORN_STN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 744l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(COVENTRY_SOUTH, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 745l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(VISTA_HTS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 746l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(COVENTRY_HLS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 747l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HIDDEN_VLY, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRESCENT_HTS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 751l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(TARADALE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 752l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MARTINDALE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 753l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(EVANSTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 754l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SADDLETOWNE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 755l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CASTLERIDGE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 756l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MARTINDALE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 757l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CORAL_SPGS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 758l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(TARADALE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 759l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(FALCONRIDGE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(FOWLER, gTrip.direction_id);
return;
}
} else if (mRoute.id == 760l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BONAVISTA_WEST, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SCARLETT, gTrip.direction_id);
return;
}
} else if (mRoute.id == 761l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SCARLETT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(AUBURN_BAY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 762l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BONAVISTA, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SCARLETT, gTrip.direction_id);
return;
}
} else if (mRoute.id == 763l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SCARLETT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(WOODBINE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 764l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SCARLETT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SOMERSET_BRIDLEWOOD_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 765l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SCARLETT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SOMERSET_BRIDLEWOOD_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 766l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SCARLETT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(EVERGREEN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 770l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WESTERN_CANADA, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(OGDEN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 771l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHINOOK_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 773l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(R_THIRSK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ROCKY_RIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 774l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(R_THIRSK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ROYAL_OAK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 775l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CITADEL, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(R_THIRSK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 776l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WISE_WOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(PALLISER_OAKRIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 778l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WISE_WOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(WOODLANDS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 779l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WISE_WOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(WOODBINE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 780l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(WISE_WOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(OAKRIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 791l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MAC_EWAN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(QUEEN_ELIZABETH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 792l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SANDSTONE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(QUEEN_ELIZABETH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 795l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(VINCENT_MASSEY, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(STRATHCONA, gTrip.direction_id);
return;
}
} else if (mRoute.id == 796l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(EDGEMONT, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(TOM_BAINES, gTrip.direction_id);
return;
}
} else if (mRoute.id == 798l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(TARADALE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ANNIE_GALE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 799l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(CORAL_SPGS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ANNIE_GALE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 801l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BREBEUF, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ROYAL_OAK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 802l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BREBEUF, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(HAWKWOOD, gTrip.direction_id);
return;
}
} else if (mRoute.id == 804l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SHERWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BREBEUF, gTrip.direction_id);
return;
}
} else if (mRoute.id == 805l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HAMPTONS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BREBEUF, gTrip.direction_id);
return;
}
} else if (mRoute.id == 807l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BREBEUF, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ROCKY_RIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 811l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(TUSCANY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 812l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITADEL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 813l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ARBOUR_LK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 814l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ROYAL_OAK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 815l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ARBOUR_LK, gTrip.direction_id);
return;
}
} else if (mRoute.id == 816l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CITADEL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 817l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ROCKY_RIDGE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 818l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(HAMPTONS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 819l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SHERWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
}
} else if (mRoute.id == 821l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MTN_PARK, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BISHOP_O_BYRNE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 822l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(MC_KENZIE_LK_WAY, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(BISHOP_O_BYRNE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 830l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(SANDSTONE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(M_D_HOUET, gTrip.direction_id);
return;
}
} else if (mRoute.id == 831l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SCENIC_ACRES_NORTH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 832l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_FRANCIS, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SCENIC_ACRES_SOUTH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 834l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(DALHOUSIE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(M_D_HOUET, gTrip.direction_id);
return;
}
} else if (mRoute.id == 835l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ANDERSON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 837l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SCENIC_ACRES_SOUTH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 838l) {
if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(SCENIC_ACRES_NORTH, gTrip.direction_id);
return;
}
} else if (mRoute.id == 841l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(NOTRE_DAME, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(HIDDEN_VLY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 842l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(NOTRE_DAME, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MAC_EWAN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 851l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(LYNNWOOD, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ST_AUGUSTINE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 853l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(RIVERBEND, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ST_AUGUSTINE, gTrip.direction_id);
return;
}
} else if (mRoute.id == 857l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_STEPHEN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(EVERGREEN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 860l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(B_GRANDIN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CRANSTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 861l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(B_GRANDIN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(AUBURN_BAY, gTrip.direction_id);
return;
}
} else if (mRoute.id == 878l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(F_WHELIHAN, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(CHAPARRAL, gTrip.direction_id);
return;
}
} else if (mRoute.id == 880l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_MATTHEW, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(HERITAGE_STN, gTrip.direction_id);
return;
}
} else if (mRoute.id == 883l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(EVANSTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 884l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(KINCORA, gTrip.direction_id);
return;
}
} else if (mRoute.id == 888l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(NORTH_POINTE, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(ST_MARGARET, gTrip.direction_id);
return;
}
} else if (mRoute.id == 889l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(BEDDINGTON, gTrip.direction_id);
return;
}
} else if (mRoute.id == 892l) {
if (gTrip.direction_id == 0) {
mTrip.setHeadsignString(ST_ISABELLA, gTrip.direction_id);
return;
} else if (gTrip.direction_id == 1) {
mTrip.setHeadsignString(MC_KENZIE, gTrip.direction_id);
return;
}
}
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.trip_headsign.toLowerCase(Locale.ENGLISH)), gTrip.direction_id);
}
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = tripHeadsign.toLowerCase(Locale.ENGLISH);
return MSpec.cleanLabel(tripHeadsign);
}
private static final Pattern ENDS_WITH_BOUND = Pattern.compile("([\\s]*[s|e|w|n]b[\\s]$)", Pattern.CASE_INSENSITIVE);
private static final Pattern STARTS_WITH_BOUND = Pattern.compile("(^[\\s]*[s|e|w|n]b[\\s]*)", Pattern.CASE_INSENSITIVE);
private static final Pattern STARTS_WITH_SLASH = Pattern.compile("(^[\\s]*/[\\s]*)", Pattern.CASE_INSENSITIVE);
private static final String REGEX_START_END = "((^|[^A-Z]){1}(%s)([^a-zA-Z]|$){1})";
private static final String REGEX_START_END_REPLACEMENT = "$2 %s $4";
private static final Pattern AT_SIGN = Pattern.compile("([\\s]*@[\\s]*)", Pattern.CASE_INSENSITIVE);
private static final String AT_SIGN_REPLACEMENT = " / ";
private static final Pattern STATION = Pattern.compile(String.format(REGEX_START_END, "station"), Pattern.CASE_INSENSITIVE);
private static final String STATION_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Stn");
private static final Pattern AV = Pattern.compile(String.format(REGEX_START_END, "AV|AVE"));
private static final String AV_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Avenue");
private static final Pattern PA = Pattern.compile(String.format(REGEX_START_END, "PA"));
private static final String PA_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Park");
private static final Pattern HT = Pattern.compile(String.format(REGEX_START_END, "HT"));
private static final String HT_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Heights");
private static final Pattern GV = Pattern.compile(String.format(REGEX_START_END, "GV"));
private static final String GV_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Grove");
private static final Pattern PT = Pattern.compile(String.format(REGEX_START_END, "PT"));
private static final String PT_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Point");
private static final Pattern TC = Pattern.compile(String.format(REGEX_START_END, "TC"));
private static final String TC_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Terrace");
private static final Pattern RI = Pattern.compile(String.format(REGEX_START_END, "RI"));
private static final String RI_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Rise");
private static final Pattern MR = Pattern.compile(String.format(REGEX_START_END, "MR"));
private static final String MR_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Manor");
private static final Pattern DR = Pattern.compile(String.format(REGEX_START_END, "DR"));
private static final String DR_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Drive");
private static final Pattern ST = Pattern.compile(String.format(REGEX_START_END, "ST"));
private static final String ST_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Street");
private static final Pattern VI = Pattern.compile(String.format(REGEX_START_END, "VI"));
private static final String VI_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Villas");
private static final Pattern PZ = Pattern.compile(String.format(REGEX_START_END, "PZ"));
private static final String PZ_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Plaza");
private static final Pattern WY = Pattern.compile(String.format(REGEX_START_END, "WY"));
private static final String WY_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Way");
private static final Pattern GR = Pattern.compile(String.format(REGEX_START_END, "GR"));
private static final String GR_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Green");
private static final Pattern BV = Pattern.compile(String.format(REGEX_START_END, "BV"));
private static final String BV_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Boulevard");
private static final Pattern GA = Pattern.compile(String.format(REGEX_START_END, "GA"));
private static final String GA_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Gate");
private static final Pattern RD = Pattern.compile(String.format(REGEX_START_END, "RD"));
private static final String RD_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Road");
private static final Pattern LI = Pattern.compile(String.format(REGEX_START_END, "LI|LINK"));
private static final String LI_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Link");
private static final Pattern PL = Pattern.compile(String.format(REGEX_START_END, "PL"));
private static final String PL_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Place");
private static final Pattern SQ = Pattern.compile(String.format(REGEX_START_END, "SQ"));
private static final String SQ_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Square");
private static final Pattern CL = Pattern.compile(String.format(REGEX_START_END, "CL"));
private static final String CL_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Close");
private static final Pattern CR = Pattern.compile(String.format(REGEX_START_END, "CR"));
private static final String CR_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Crescent");
private static final Pattern GD = Pattern.compile(String.format(REGEX_START_END, "GD"));
private static final String GD_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Gardens");
private static final Pattern LN = Pattern.compile(String.format(REGEX_START_END, "LN"));
private static final String LN_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Lane");
private static final Pattern CO = Pattern.compile(String.format(REGEX_START_END, "CO"));
private static final String CO_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Ct");
private static final Pattern CI = Pattern.compile(String.format(REGEX_START_END, "CI"));
private static final String CI_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Circle");
private static final Pattern HE = Pattern.compile(String.format(REGEX_START_END, "HE"));
private static final String HE_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Heath");
private static final Pattern ME = Pattern.compile(String.format(REGEX_START_END, "ME"));
private static final String ME_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Mews");
private static final Pattern TR = Pattern.compile(String.format(REGEX_START_END, "TR"));
private static final String TR_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Trail");
private static final Pattern LD = Pattern.compile(String.format(REGEX_START_END, "LD"));
private static final String LD_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Landing");
private static final Pattern HL = Pattern.compile(String.format(REGEX_START_END, "HL"));
private static final String HL_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Hill");
private static final Pattern PK = Pattern.compile(String.format(REGEX_START_END, "PK"));
private static final String PK_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Park");
private static final Pattern CM = Pattern.compile(String.format(REGEX_START_END, "CM"));
private static final String CM_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Common");
private static final Pattern GT = Pattern.compile(String.format(REGEX_START_END, "GT"));
private static final String GT_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Gate");
private static final Pattern CV = Pattern.compile(String.format(REGEX_START_END, "CV"));
private static final String CV_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Cove");
private static final Pattern VW = Pattern.compile(String.format(REGEX_START_END, "VW"));
private static final String VW_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "View");
private static final Pattern BY = Pattern.compile(String.format(REGEX_START_END, "BY|BA|BAY"));
private static final String BY_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Bay");
private static final Pattern CE = Pattern.compile(String.format(REGEX_START_END, "CE"));
private static final String CE_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Center");
private static final Pattern CTR = Pattern.compile(String.format(REGEX_START_END, "CTR"));
private static final String CTR_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Center");
private static final Pattern MOUNT_ROYAL_UNIVERSITY = Pattern.compile(String.format(REGEX_START_END, "Mount Royal University"));
private static final String MOUNT_ROYAL_UNIVERSITY_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "MRU");
private static final Pattern MOUNT = Pattern.compile(String.format(REGEX_START_END, "Mount"));
private static final String MOUNT_REPLACEMENT = String.format(REGEX_START_END_REPLACEMENT, "Mt");
@Override
public String cleanStopName(String gStopName) {
gStopName = STARTS_WITH_BOUND.matcher(gStopName).replaceAll(StringUtils.EMPTY);
gStopName = ENDS_WITH_BOUND.matcher(gStopName).replaceAll(StringUtils.EMPTY);
gStopName = AT_SIGN.matcher(gStopName).replaceAll(AT_SIGN_REPLACEMENT);
gStopName = AV.matcher(gStopName).replaceAll(AV_REPLACEMENT);
gStopName = PA.matcher(gStopName).replaceAll(PA_REPLACEMENT);
gStopName = HT.matcher(gStopName).replaceAll(HT_REPLACEMENT);
gStopName = GV.matcher(gStopName).replaceAll(GV_REPLACEMENT);
gStopName = PT.matcher(gStopName).replaceAll(PT_REPLACEMENT);
gStopName = TC.matcher(gStopName).replaceAll(TC_REPLACEMENT);
gStopName = RI.matcher(gStopName).replaceAll(RI_REPLACEMENT);
gStopName = MR.matcher(gStopName).replaceAll(MR_REPLACEMENT);
gStopName = DR.matcher(gStopName).replaceAll(DR_REPLACEMENT);
gStopName = ST.matcher(gStopName).replaceAll(ST_REPLACEMENT);
gStopName = VI.matcher(gStopName).replaceAll(VI_REPLACEMENT);
gStopName = PZ.matcher(gStopName).replaceAll(PZ_REPLACEMENT);
gStopName = WY.matcher(gStopName).replaceAll(WY_REPLACEMENT);
gStopName = GR.matcher(gStopName).replaceAll(GR_REPLACEMENT);
gStopName = BV.matcher(gStopName).replaceAll(BV_REPLACEMENT);
gStopName = GA.matcher(gStopName).replaceAll(GA_REPLACEMENT);
gStopName = RD.matcher(gStopName).replaceAll(RD_REPLACEMENT);
gStopName = LI.matcher(gStopName).replaceAll(LI_REPLACEMENT);
gStopName = PL.matcher(gStopName).replaceAll(PL_REPLACEMENT);
gStopName = SQ.matcher(gStopName).replaceAll(SQ_REPLACEMENT);
gStopName = CL.matcher(gStopName).replaceAll(CL_REPLACEMENT);
gStopName = CR.matcher(gStopName).replaceAll(CR_REPLACEMENT);
gStopName = GD.matcher(gStopName).replaceAll(GD_REPLACEMENT);
gStopName = LN.matcher(gStopName).replaceAll(LN_REPLACEMENT);
gStopName = CO.matcher(gStopName).replaceAll(CO_REPLACEMENT);
gStopName = ME.matcher(gStopName).replaceAll(ME_REPLACEMENT);
gStopName = TR.matcher(gStopName).replaceAll(TR_REPLACEMENT);
gStopName = CI.matcher(gStopName).replaceAll(CI_REPLACEMENT);
gStopName = HE.matcher(gStopName).replaceAll(HE_REPLACEMENT);
gStopName = LD.matcher(gStopName).replaceAll(LD_REPLACEMENT);
gStopName = HL.matcher(gStopName).replaceAll(HL_REPLACEMENT);
gStopName = PK.matcher(gStopName).replaceAll(PK_REPLACEMENT);
gStopName = CM.matcher(gStopName).replaceAll(CM_REPLACEMENT);
gStopName = GT.matcher(gStopName).replaceAll(GT_REPLACEMENT);
gStopName = CV.matcher(gStopName).replaceAll(CV_REPLACEMENT);
gStopName = VW.matcher(gStopName).replaceAll(VW_REPLACEMENT);
gStopName = BY.matcher(gStopName).replaceAll(BY_REPLACEMENT);
gStopName = CE.matcher(gStopName).replaceAll(CE_REPLACEMENT);
gStopName = CTR.matcher(gStopName).replaceAll(CTR_REPLACEMENT);
gStopName = MOUNT_ROYAL_UNIVERSITY.matcher(gStopName).replaceAll(MOUNT_ROYAL_UNIVERSITY_REPLACEMENT);
gStopName = MOUNT.matcher(gStopName).replaceAll(MOUNT_REPLACEMENT);
gStopName = STATION.matcher(gStopName).replaceAll(STATION_REPLACEMENT);
gStopName = MSpec.cleanStreetTypes(gStopName);
gStopName = MSpec.cleanNumbers(gStopName);
gStopName = STARTS_WITH_SLASH.matcher(gStopName).replaceAll(StringUtils.EMPTY);
return MSpec.cleanLabel(gStopName);
}
}
|
Compatibility with shared parser library & code cleaning.
|
src/org/mtransit/parser/ca_calgary_transit_bus/CalgaryTransitBusAgencyTools.java
|
Compatibility with shared parser library & code cleaning.
|
<ide><path>rc/org/mtransit/parser/ca_calgary_transit_bus/CalgaryTransitBusAgencyTools.java
<ide> import org.mtransit.parser.gtfs.data.GCalendar;
<ide> import org.mtransit.parser.gtfs.data.GCalendarDate;
<ide> import org.mtransit.parser.gtfs.data.GRoute;
<add>import org.mtransit.parser.gtfs.data.GSpec;
<ide> import org.mtransit.parser.gtfs.data.GStop;
<ide> import org.mtransit.parser.gtfs.data.GTrip;
<ide> import org.mtransit.parser.mt.data.MAgency;
<ide> private static final String WOODLANDS = "Woodlands";
<ide>
<ide> @Override
<del> public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip) {
<del>
<add> public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
<ide> if (mRoute.id == 1l) {
<ide> if (gTrip.direction_id == 0) {
<ide> mTrip.setHeadsignString(FOREST_LAWN, gTrip.direction_id);
|
|
Java
|
mit
|
e2707cc4245c368a4ca113fadf9c9b88c20747f9
| 0 |
qiniu/android-sdk,sxci/android-sdk
|
package com.qiniu.android.storage;
import com.qiniu.android.http.Client;
import com.qiniu.android.http.CompletionHandler;
import com.qiniu.android.http.ProgressHandler;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.utils.AndroidNetwork;
import com.qiniu.android.utils.Crc32;
import com.qiniu.android.utils.StringMap;
import com.qiniu.android.utils.StringUtils;
import com.qiniu.android.utils.UrlSafeBase64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
import java.util.Map;
import static java.lang.String.format;
/**
* 分片上传
* 文档:<a href="http://developer.qiniu.com/docs/v6/api/overview/up/chunked-upload.html">分片上传</a>
* <p/>
* 分片上传通过将一个文件分割为固定大小的块(4M),然后再将每个块分割为固定大小的片,每次
* 上传一个分片的内容,等待所有块的所有分片都上传完成之后,再将这些块拼接起来,构成一个
* 完整的文件。另外分片上传还支持纪录上传进度,如果本次上传被暂停,那么下次还可以从上次
* 上次完成的文件偏移位置,继续开始上传,这样就实现了断点续传功能。
* <p/>
* 分片上传在网络环境较差的情况下,可以有效地实现大文件的上传。
*/
final class ResumeUploader implements Runnable {
private final long totalSize;
private final String key;
private final UpCompletionHandler completionHandler;
private final UploadOptions options;
private final Client client;
private final Configuration config;
private final byte[] chunkBuffer;
private final String[] contexts;
// private final Header[] headers;
private final StringMap headers;
private final long modifyTime;
private final String recorderKey;
private RandomAccessFile file;
private File f;
private long crc32;
private UpToken token;
ResumeUploader(Client client, Configuration config, File f, String key, UpToken token,
final UpCompletionHandler completionHandler, UploadOptions options, String recorderKey) {
this.client = client;
this.config = config;
this.f = f;
this.recorderKey = recorderKey;
this.totalSize = f.length();
this.key = key;
this.headers = new StringMap().put("Authorization", "UpToken " + token.token);
this.file = null;
this.completionHandler = new UpCompletionHandler() {
@Override
public void complete(String key, ResponseInfo info, JSONObject response) {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
completionHandler.complete(key, info, response);
}
};
this.options = options != null ? options : UploadOptions.defaultOptions();
chunkBuffer = new byte[config.chunkSize];
long count = (totalSize + Configuration.BLOCK_SIZE - 1) / Configuration.BLOCK_SIZE;
contexts = new String[(int) count];
modifyTime = f.lastModified();
this.token = token;
}
private static boolean isChunkOK(ResponseInfo info, JSONObject response) {
return info.statusCode == 200 && info.error == null && (info.hasReqId() || isChunkResOK(response));
}
private static boolean isChunkResOK(JSONObject response) {
try {
// getXxxx 若获取不到值,会抛出异常
response.getString("ctx");
response.getLong("crc32");
} catch (Exception e) {
return false;
}
return true;
}
private static boolean isNotChunkToQiniu(ResponseInfo info, JSONObject response) {
return info.statusCode < 500 && info.statusCode >= 200 && (!info.hasReqId() && !isChunkResOK(response));
}
public void run() {
long offset = recoveryFromRecord();
try {
file = new RandomAccessFile(f, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
completionHandler.complete(key, ResponseInfo.fileError(e, token), null);
return;
}
nextTask(offset, 0, config.zone.upHost(token.token, config.useHttps, null));
}
/**
* 创建块,并上传第一个分片内容
*
* @param upHost 上传主机
* @param offset 本地文件偏移量
* @param blockSize 分块的块大小
* @param chunkSize 分片的片大小
* @param progress 上传进度
* @param _completionHandler 上传完成处理动作
*/
private void makeBlock(String upHost, long offset, int blockSize, int chunkSize, ProgressHandler progress,
CompletionHandler _completionHandler, UpCancellationSignal c) {
String path = format(Locale.ENGLISH, "/mkblk/%d", blockSize);
try {
file.seek(offset);
file.read(chunkBuffer, 0, chunkSize);
} catch (IOException e) {
completionHandler.complete(key, ResponseInfo.fileError(e, token), null);
return;
}
this.crc32 = Crc32.bytes(chunkBuffer, 0, chunkSize);
String postUrl = String.format("%s%s", upHost, path);
post(postUrl, chunkBuffer, 0, chunkSize, progress, _completionHandler, c);
}
private void putChunk(String upHost, long offset, int chunkSize, String context, ProgressHandler progress,
CompletionHandler _completionHandler, UpCancellationSignal c) {
int chunkOffset = (int) (offset % Configuration.BLOCK_SIZE);
String path = format(Locale.ENGLISH, "/bput/%s/%d", context, chunkOffset);
try {
file.seek(offset);
file.read(chunkBuffer, 0, chunkSize);
} catch (IOException e) {
completionHandler.complete(key, ResponseInfo.fileError(e, token), null);
return;
}
this.crc32 = Crc32.bytes(chunkBuffer, 0, chunkSize);
String postUrl = String.format("%s%s", upHost, path);
post(postUrl, chunkBuffer, 0, chunkSize, progress, _completionHandler, c);
}
private void makeFile(String upHost, CompletionHandler _completionHandler, UpCancellationSignal c) {
String mime = format(Locale.ENGLISH, "/mimeType/%s/fname/%s",
UrlSafeBase64.encodeToString(options.mimeType), UrlSafeBase64.encodeToString(f.getName()));
String keyStr = "";
if (key != null) {
keyStr = format("/key/%s", UrlSafeBase64.encodeToString(key));
}
String paramStr = "";
if (options.params.size() != 0) {
String str[] = new String[options.params.size()];
int j = 0;
for (Map.Entry<String, String> i : options.params.entrySet()) {
str[j++] = format(Locale.ENGLISH, "%s/%s", i.getKey(), UrlSafeBase64.encodeToString(i.getValue()));
}
paramStr = "/" + StringUtils.join(str, "/");
}
String path = format(Locale.ENGLISH, "/mkfile/%d%s%s%s", totalSize, mime, keyStr, paramStr);
String bodyStr = StringUtils.join(contexts, ",");
byte[] data = bodyStr.getBytes();
String postUrl = String.format("%s%s", upHost, path);
post(postUrl, data, 0, data.length, null, _completionHandler, c);
}
private void post(String upHost, byte[] data, int offset, int dataSize, ProgressHandler progress,
CompletionHandler completion, UpCancellationSignal c) {
client.asyncPost(upHost, data, offset, dataSize, headers, token, totalSize, progress, completion, c);
}
private long calcPutSize(long offset) {
long left = totalSize - offset;
return left < config.chunkSize ? left : config.chunkSize;
}
private long calcBlockSize(long offset) {
long left = totalSize - offset;
return left < Configuration.BLOCK_SIZE ? left : Configuration.BLOCK_SIZE;
}
private boolean isCancelled() {
return options.cancellationSignal.isCancelled();
}
private void nextTask(final long offset, final int retried, final String upHost) {
if (isCancelled()) {
ResponseInfo i = ResponseInfo.cancelled(token);
completionHandler.complete(key, i, null);
return;
}
if (offset == totalSize) {
//完成操作,返回的内容不确定,是否真正成功逻辑让用户自己判断
CompletionHandler complete = new CompletionHandler() {
@Override
public void complete(ResponseInfo info, JSONObject response) {
if (info.isNetworkBroken() && !AndroidNetwork.isNetWorkReady()) {
options.netReadyHandler.waitReady();
if (!AndroidNetwork.isNetWorkReady()) {
completionHandler.complete(key, info, response);
return;
}
}
if (info.isOK()) {
removeRecord();
options.progressHandler.progress(key, 1.0);
completionHandler.complete(key, info, response);
return;
}
// mkfile ,允许多重试一次
if (info.needRetry() && retried < config.retryMax + 1) {
String upHostRetry = config.zone.upHost(token.token, config.useHttps, upHost);
if (upHostRetry != null) {
nextTask(offset, retried + 1, upHostRetry);
return;
}
}
completionHandler.complete(key, info, response);
}
};
makeFile(upHost, complete, options.cancellationSignal);
return;
}
final int chunkSize = (int) calcPutSize(offset);
ProgressHandler progress = new ProgressHandler() {
@Override
public void onProgress(long bytesWritten, long totalSize) {
double percent = (double) (offset + bytesWritten) / totalSize;
if (percent > 0.95) {
percent = 0.95;
}
options.progressHandler.progress(key, percent);
}
};
// 分片上传,七牛响应内容固定,若缺少reqId,可通过响应体判断
CompletionHandler complete = new CompletionHandler() {
@Override
public void complete(ResponseInfo info, JSONObject response) {
if (info.isNetworkBroken() && !AndroidNetwork.isNetWorkReady()) {
options.netReadyHandler.waitReady();
if (!AndroidNetwork.isNetWorkReady()) {
completionHandler.complete(key, info, response);
return;
}
}
if (info.isCancelled()) {
completionHandler.complete(key, info, response);
return;
}
if (!isChunkOK(info, response)) {
String upHostRetry = config.zone.upHost(token.token, config.useHttps, upHost);
if (info.statusCode == 701 && retried < config.retryMax) {
nextTask((offset / Configuration.BLOCK_SIZE) * Configuration.BLOCK_SIZE, retried + 1, upHost);
return;
}
if (upHostRetry != null
&& ((isNotChunkToQiniu(info, response) || info.needRetry())
&& retried < config.retryMax)) {
nextTask(offset, retried + 1, upHostRetry);
return;
}
completionHandler.complete(key, info, response);
return;
}
String context = null;
if (response == null && retried < config.retryMax) {
String upHostRetry = config.zone.upHost(token.token, config.useHttps, upHost);
nextTask(offset, retried + 1, upHostRetry);
return;
}
long crc = 0;
Exception tempE = null;
try {
context = response.getString("ctx");
crc = response.getLong("crc32");
} catch (Exception e) {
tempE = e;
e.printStackTrace();
}
if ((context == null || crc != ResumeUploader.this.crc32) && retried < config.retryMax) {
String upHostRetry = config.zone.upHost(token.token, config.useHttps, upHost);
nextTask(offset, retried + 1, upHostRetry);
return;
}
if (context == null) {
String error = "get context failed.";
if (tempE != null) {
error += "\n";
error += tempE.getMessage();
}
ResponseInfo info2 = ResponseInfo.errorInfo(info, ResponseInfo.UnknownError, error);
completionHandler.complete(key, info2, response);
return;
}
if (crc != ResumeUploader.this.crc32) {
String error = "block's crc32 is not match. local: " + ResumeUploader.this.crc32 + ", remote: " + crc;
ResponseInfo info2 = ResponseInfo.errorInfo(info, ResponseInfo.Crc32NotMatch, error);
completionHandler.complete(key, info2, response);
return;
}
contexts[(int) (offset / Configuration.BLOCK_SIZE)] = context;
record(offset + chunkSize);
nextTask(offset + chunkSize, retried, upHost);
}
};
if (offset % Configuration.BLOCK_SIZE == 0) {
int blockSize = (int) calcBlockSize(offset);
makeBlock(upHost, offset, blockSize, chunkSize, progress, complete, options.cancellationSignal);
return;
}
String context = contexts[(int) (offset / Configuration.BLOCK_SIZE)];
putChunk(upHost, offset, chunkSize, context, progress, complete, options.cancellationSignal);
}
private long recoveryFromRecord() {
if (config.recorder == null) {
return 0;
}
byte[] data = config.recorder.get(recorderKey);
if (data == null) {
return 0;
}
String jsonStr = new String(data);
JSONObject obj;
try {
obj = new JSONObject(jsonStr);
} catch (JSONException e) {
e.printStackTrace();
return 0;
}
long offset = obj.optLong("offset", 0);
long modify = obj.optLong("modify_time", 0);
long fSize = obj.optLong("size", 0);
JSONArray array = obj.optJSONArray("contexts");
if (offset == 0 || modify != modifyTime || fSize != totalSize || array == null || array.length() == 0) {
return 0;
}
for (int i = 0; i < array.length(); i++) {
contexts[i] = array.optString(i);
}
return offset;
}
private void removeRecord() {
if (config.recorder != null) {
config.recorder.del(recorderKey);
}
}
// save json value
//{
// "size":filesize,
// "offset":lastSuccessOffset,
// "modify_time": lastFileModifyTime,
// "contexts": contexts
//}
private void record(long offset) {
if (config.recorder == null || offset == 0) {
return;
}
String data = format(Locale.ENGLISH, "{\"size\":%d,\"offset\":%d, \"modify_time\":%d, \"contexts\":[%s]}",
totalSize, offset, modifyTime, StringUtils.jsonJoin(contexts));
config.recorder.set(recorderKey, data.getBytes());
}
private URI newURI(URI uri, String path) {
try {
return new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), path, null, null);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return uri;
}
}
|
library/src/main/java/com/qiniu/android/storage/ResumeUploader.java
|
package com.qiniu.android.storage;
import com.qiniu.android.http.Client;
import com.qiniu.android.http.CompletionHandler;
import com.qiniu.android.http.ProgressHandler;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.utils.AndroidNetwork;
import com.qiniu.android.utils.Crc32;
import com.qiniu.android.utils.StringMap;
import com.qiniu.android.utils.StringUtils;
import com.qiniu.android.utils.UrlSafeBase64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
import java.util.Map;
import static java.lang.String.format;
/**
* 分片上传
* 文档:<a href="http://developer.qiniu.com/docs/v6/api/overview/up/chunked-upload.html">分片上传</a>
* <p/>
* 分片上传通过将一个文件分割为固定大小的块(4M),然后再将每个块分割为固定大小的片,每次
* 上传一个分片的内容,等待所有块的所有分片都上传完成之后,再将这些块拼接起来,构成一个
* 完整的文件。另外分片上传还支持纪录上传进度,如果本次上传被暂停,那么下次还可以从上次
* 上次完成的文件偏移位置,继续开始上传,这样就实现了断点续传功能。
* <p/>
* 分片上传在网络环境较差的情况下,可以有效地实现大文件的上传。
*/
final class ResumeUploader implements Runnable {
private final long totalSize;
private final String key;
private final UpCompletionHandler completionHandler;
private final UploadOptions options;
private final Client client;
private final Configuration config;
private final byte[] chunkBuffer;
private final String[] contexts;
// private final Header[] headers;
private final StringMap headers;
private final long modifyTime;
private final String recorderKey;
private RandomAccessFile file;
private File f;
private long crc32;
private UpToken token;
ResumeUploader(Client client, Configuration config, File f, String key, UpToken token,
final UpCompletionHandler completionHandler, UploadOptions options, String recorderKey) {
this.client = client;
this.config = config;
this.f = f;
this.recorderKey = recorderKey;
this.totalSize = f.length();
this.key = key;
this.headers = new StringMap().put("Authorization", "UpToken " + token.token);
this.file = null;
this.completionHandler = new UpCompletionHandler() {
@Override
public void complete(String key, ResponseInfo info, JSONObject response) {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
completionHandler.complete(key, info, response);
}
};
this.options = options != null ? options : UploadOptions.defaultOptions();
chunkBuffer = new byte[config.chunkSize];
long count = (totalSize + Configuration.BLOCK_SIZE - 1) / Configuration.BLOCK_SIZE;
contexts = new String[(int) count];
modifyTime = f.lastModified();
this.token = token;
}
private static boolean isChunkOK(ResponseInfo info, JSONObject response) {
return info.statusCode == 200 && info.error == null && (info.hasReqId() || isChunkResOK(response));
}
private static boolean isChunkResOK(JSONObject response) {
try {
// getXxxx 若获取不到值,会抛出异常
response.getString("ctx");
response.getLong("crc32");
} catch (Exception e) {
return false;
}
return true;
}
private static boolean isNotChunkToQiniu(ResponseInfo info, JSONObject response) {
return info.statusCode < 500 && info.statusCode >= 200 && (!info.hasReqId() && !isChunkResOK(response));
}
public void run() {
long offset = recoveryFromRecord();
try {
file = new RandomAccessFile(f, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
completionHandler.complete(key, ResponseInfo.fileError(e, token), null);
return;
}
nextTask(offset, 0, config.zone.upHost(token.token, config.useHttps, null));
}
/**
* 创建块,并上传第一个分片内容
*
* @param upHost 上传主机
* @param offset 本地文件偏移量
* @param blockSize 分块的块大小
* @param chunkSize 分片的片大小
* @param progress 上传进度
* @param _completionHandler 上传完成处理动作
*/
private void makeBlock(String upHost, long offset, int blockSize, int chunkSize, ProgressHandler progress,
CompletionHandler _completionHandler, UpCancellationSignal c) {
String path = format(Locale.ENGLISH, "/mkblk/%d", blockSize);
try {
file.seek(offset);
file.read(chunkBuffer, 0, chunkSize);
} catch (IOException e) {
completionHandler.complete(key, ResponseInfo.fileError(e, token), null);
return;
}
this.crc32 = Crc32.bytes(chunkBuffer, 0, chunkSize);
String postUrl = String.format("%s%s", upHost, path);
post(postUrl, chunkBuffer, 0, chunkSize, progress, _completionHandler, c);
}
private void putChunk(String upHost, long offset, int chunkSize, String context, ProgressHandler progress,
CompletionHandler _completionHandler, UpCancellationSignal c) {
int chunkOffset = (int) (offset % Configuration.BLOCK_SIZE);
String path = format(Locale.ENGLISH, "/bput/%s/%d", context, chunkOffset);
try {
file.seek(offset);
file.read(chunkBuffer, 0, chunkSize);
} catch (IOException e) {
completionHandler.complete(key, ResponseInfo.fileError(e, token), null);
return;
}
this.crc32 = Crc32.bytes(chunkBuffer, 0, chunkSize);
String postUrl = String.format("%s%s", upHost, path);
post(postUrl, chunkBuffer, 0, chunkSize, progress, _completionHandler, c);
}
private void makeFile(String upHost, CompletionHandler _completionHandler, UpCancellationSignal c) {
String mime = format(Locale.ENGLISH, "/mimeType/%s/fname/%s",
UrlSafeBase64.encodeToString(options.mimeType), UrlSafeBase64.encodeToString(f.getName()));
String keyStr = "";
if (key != null) {
keyStr = format("/key/%s", UrlSafeBase64.encodeToString(key));
}
String paramStr = "";
if (options.params.size() != 0) {
String str[] = new String[options.params.size()];
int j = 0;
for (Map.Entry<String, String> i : options.params.entrySet()) {
str[j++] = format(Locale.ENGLISH, "%s/%s", i.getKey(), UrlSafeBase64.encodeToString(i.getValue()));
}
paramStr = "/" + StringUtils.join(str, "/");
}
String path = format(Locale.ENGLISH, "/mkfile/%d%s%s%s", totalSize, mime, keyStr, paramStr);
String bodyStr = StringUtils.join(contexts, ",");
byte[] data = bodyStr.getBytes();
String postUrl = String.format("%s%s", upHost, path);
post(postUrl, data, 0, data.length, null, _completionHandler, c);
}
private void post(String upHost, byte[] data, int offset, int dataSize, ProgressHandler progress,
CompletionHandler completion, UpCancellationSignal c) {
client.asyncPost(upHost, data, offset, dataSize, headers, token, totalSize, progress, completion, c);
}
private long calcPutSize(long offset) {
long left = totalSize - offset;
return left < config.chunkSize ? left : config.chunkSize;
}
private long calcBlockSize(long offset) {
long left = totalSize - offset;
return left < Configuration.BLOCK_SIZE ? left : Configuration.BLOCK_SIZE;
}
private boolean isCancelled() {
return options.cancellationSignal.isCancelled();
}
private void nextTask(final long offset, final int retried, final String upHost) {
if (isCancelled()) {
ResponseInfo i = ResponseInfo.cancelled(token);
completionHandler.complete(key, i, null);
return;
}
if (offset == totalSize) {
//完成操作,返回的内容不确定,是否真正成功逻辑让用户自己判断
CompletionHandler complete = new CompletionHandler() {
@Override
public void complete(ResponseInfo info, JSONObject response) {
if (info.isNetworkBroken() && !AndroidNetwork.isNetWorkReady()) {
options.netReadyHandler.waitReady();
if (!AndroidNetwork.isNetWorkReady()) {
completionHandler.complete(key, info, response);
return;
}
}
if (info.isOK()) {
removeRecord();
options.progressHandler.progress(key, 1.0);
completionHandler.complete(key, info, response);
return;
}
// mkfile ,允许多重试一次
if (info.needRetry() && retried < config.retryMax + 1) {
String upHostRetry = config.zone.upHost(token.token, config.useHttps, upHost);
if (upHostRetry != null) {
nextTask(offset, retried + 1, upHostRetry);
return;
}
}
completionHandler.complete(key, info, response);
}
};
makeFile(upHost, complete, options.cancellationSignal);
return;
}
final int chunkSize = (int) calcPutSize(offset);
ProgressHandler progress = new ProgressHandler() {
@Override
public void onProgress(long bytesWritten, long totalSize) {
double percent = (double) (offset + bytesWritten) / totalSize;
if (percent > 0.95) {
percent = 0.95;
}
options.progressHandler.progress(key, percent);
}
};
// 分片上传,七牛响应内容固定,若缺少reqId,可通过响应体判断
CompletionHandler complete = new CompletionHandler() {
@Override
public void complete(ResponseInfo info, JSONObject response) {
if (info.isNetworkBroken() && !AndroidNetwork.isNetWorkReady()) {
options.netReadyHandler.waitReady();
if (!AndroidNetwork.isNetWorkReady()) {
completionHandler.complete(key, info, response);
return;
}
}
if (info.isCancelled()) {
completionHandler.complete(key, info, response);
return;
}
if (!isChunkOK(info, response)) {
String upHostRetry = config.zone.upHost(token.token, config.useHttps, upHost);
if (info.statusCode == 701 && retried < config.retryMax) {
nextTask((offset / Configuration.BLOCK_SIZE) * Configuration.BLOCK_SIZE, retried + 1, upHost);
return;
}
if (upHostRetry != null
&& ((isNotChunkToQiniu(info, response) || info.needRetry())
&& retried < config.retryMax)) {
nextTask(offset, retried + 1, upHostRetry);
return;
}
completionHandler.complete(key, info, response);
return;
}
String context = null;
if (response == null && retried < config.retryMax) {
String upHostRetry = config.zone.upHost(token.token, config.useHttps, upHost);
nextTask(offset, retried + 1, upHostRetry);
return;
}
long crc = 0;
Exception tempE = null;
try {
context = response.getString("ctx");
crc = response.getLong("crc32");
} catch (Exception e) {
tempE = e;
e.printStackTrace();
}
if ((context == null || crc != ResumeUploader.this.crc32) && retried < config.retryMax) {
String upHostRetry = config.zone.upHost(token.token, config.useHttps, upHost);
nextTask(offset, retried + 1, upHostRetry);
return;
}
if (crc != ResumeUploader.this.crc32) {
ResponseInfo info2 = ResponseInfo.errorInfo(info, ResponseInfo.Crc32NotMatch, "block's crc32 is not match");
completionHandler.complete(key, info2, response);
return;
}
if (context == null) {
String error = "get context failed.";
if (tempE != null) {
error += "\n";
error += tempE.getMessage();
}
ResponseInfo info2 = ResponseInfo.errorInfo(info, ResponseInfo.UnknownError, error);
completionHandler.complete(key, info2, response);
return;
}
contexts[(int) (offset / Configuration.BLOCK_SIZE)] = context;
record(offset + chunkSize);
nextTask(offset + chunkSize, retried, upHost);
}
};
if (offset % Configuration.BLOCK_SIZE == 0) {
int blockSize = (int) calcBlockSize(offset);
makeBlock(upHost, offset, blockSize, chunkSize, progress, complete, options.cancellationSignal);
return;
}
String context = contexts[(int) (offset / Configuration.BLOCK_SIZE)];
putChunk(upHost, offset, chunkSize, context, progress, complete, options.cancellationSignal);
}
private long recoveryFromRecord() {
if (config.recorder == null) {
return 0;
}
byte[] data = config.recorder.get(recorderKey);
if (data == null) {
return 0;
}
String jsonStr = new String(data);
JSONObject obj;
try {
obj = new JSONObject(jsonStr);
} catch (JSONException e) {
e.printStackTrace();
return 0;
}
long offset = obj.optLong("offset", 0);
long modify = obj.optLong("modify_time", 0);
long fSize = obj.optLong("size", 0);
JSONArray array = obj.optJSONArray("contexts");
if (offset == 0 || modify != modifyTime || fSize != totalSize || array == null || array.length() == 0) {
return 0;
}
for (int i = 0; i < array.length(); i++) {
contexts[i] = array.optString(i);
}
return offset;
}
private void removeRecord() {
if (config.recorder != null) {
config.recorder.del(recorderKey);
}
}
// save json value
//{
// "size":filesize,
// "offset":lastSuccessOffset,
// "modify_time": lastFileModifyTime,
// "contexts": contexts
//}
private void record(long offset) {
if (config.recorder == null || offset == 0) {
return;
}
String data = format(Locale.ENGLISH, "{\"size\":%d,\"offset\":%d, \"modify_time\":%d, \"contexts\":[%s]}",
totalSize, offset, modifyTime, StringUtils.jsonJoin(contexts));
config.recorder.set(recorderKey, data.getBytes());
}
private URI newURI(URI uri, String path) {
try {
return new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), path, null, null);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return uri;
}
}
|
check context first.
|
library/src/main/java/com/qiniu/android/storage/ResumeUploader.java
|
check context first.
|
<ide><path>ibrary/src/main/java/com/qiniu/android/storage/ResumeUploader.java
<ide> nextTask(offset, retried + 1, upHostRetry);
<ide> return;
<ide> }
<del> if (crc != ResumeUploader.this.crc32) {
<del> ResponseInfo info2 = ResponseInfo.errorInfo(info, ResponseInfo.Crc32NotMatch, "block's crc32 is not match");
<del> completionHandler.complete(key, info2, response);
<del> return;
<del> }
<ide> if (context == null) {
<ide> String error = "get context failed.";
<ide> if (tempE != null) {
<ide> completionHandler.complete(key, info2, response);
<ide> return;
<ide> }
<add> if (crc != ResumeUploader.this.crc32) {
<add> String error = "block's crc32 is not match. local: " + ResumeUploader.this.crc32 + ", remote: " + crc;
<add> ResponseInfo info2 = ResponseInfo.errorInfo(info, ResponseInfo.Crc32NotMatch, error);
<add> completionHandler.complete(key, info2, response);
<add> return;
<add> }
<add>
<ide> contexts[(int) (offset / Configuration.BLOCK_SIZE)] = context;
<ide> record(offset + chunkSize);
<ide> nextTask(offset + chunkSize, retried, upHost);
|
|
Java
|
mit
|
c5c2c972dc8606f08c9f3e2e35835e27f6e35c02
| 0 |
lemmy/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus
|
package util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.InitialDirContext;
import model.ModelInJar;
import tlc2.output.MP;
// Requires Java >=6 due to javax.activation only part starting with 6
public class MailSender {
public static final String MODEL_NAME = "modelName";
public static final String SPEC_NAME = "specName";
public static final String MAIL_ADDRESS = "result.mail.address";
/**
* @param from "Foo bar <[email protected]>"
* @param to An email address _with_ domain part ([email protected])
* @param subject
* @param messages
*/
private static boolean send(final InternetAddress from, final InternetAddress to, final String subject, final String body, final File[] files) {
// https://javaee.github.io/javamail/docs/api/com/sun/mail/smtp/package-summary.html
final Properties properties = System.getProperties();
// Prefer email to be delivered encrypted (assumes to lower likelihood of SMTP
// rejection or classification as spam too). Falls back to plain text if SMTP
// server does not support starttls.
properties.put("mail.smtp.starttls.enable", "true");
//properties.put("mail.debug", "true");
if (!to.getAddress().contains("@")) {
// no domain, no MX record to lookup
return false;
}
List<MXRecord> mailhosts;
try {
mailhosts = getMXForDomain(to.getAddress().split("@")[1]);
} catch (NamingException e) {
e.printStackTrace();
return false;
}
// retry all mx host
for (MXRecord mxRecord : mailhosts) {
properties.put("mail.smtp.host", mxRecord.hostname);
try {
final Session session = Session.getDefaultInstance(properties);
final Message msg = new MimeMessage(session);
msg.setFrom(from);
msg.addRecipient(Message.RecipientType.TO, to);
msg.setSubject(subject);
// not sure why the extra body part is needed here
MimeBodyPart messageBodyPart = new MimeBodyPart();
final Multipart multipart = new MimeMultipart();
// The main body part. Having a main body appears to have a very
// positive effect on the spam score compared to emails with
// just attachments. It is also visually more appealing to e.g.
// Outlook users who otherwise see an empty mail.
messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(body, "text/plain");
multipart.addBodyPart(messageBodyPart);
// attach file(s)
for (File file : files) {
if (file == null) {
continue;
}
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(
new FileDataSource(file)));
messageBodyPart.setFileName(file.getName());
messageBodyPart.setHeader("Content-Type", "text/plain");
multipart.addBodyPart(messageBodyPart);
}
msg.setContent(multipart);
Transport.send(msg);
return true;
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
return false;
}
private static List<MXRecord> getMXForDomain(String aDomain) throws NamingException {
final InitialDirContext ctx = new InitialDirContext();
final Attributes attributes = ctx.getAttributes("dns:/" + aDomain,
new String[] { "MX" });
final Attribute attr = attributes.get("MX");
final List<MXRecord> list = new ArrayList<MXRecord>();
// RFC 974
if (attr == null) {
list.add(new MXRecord(0, aDomain));
} else {
// split pref from hostname
for (int i = 0; i < attr.size(); i++) {
Object object = attr.get(i);
if (object != null && object instanceof String) {
String[] split = ((String) object).split("\\s+");
if (split != null && split.length == 2) {
Integer weight = Integer.parseInt(split[0]);
list.add(new MXRecord(weight, split[1]));
}
}
}
}
// sort (according to weight of mxrecord)
Collections.sort(list);
return list;
}
private static class MXRecord implements Comparable<MXRecord> {
public Integer weight;
public String hostname;
public MXRecord(int aWeight, String aHostname) {
weight = aWeight;
hostname = aHostname;
}
public int compareTo(MXRecord o) {
return weight.compareTo(o.weight);
}
}
// For testing only.
public static void main(String[] args) throws AddressException, FileNotFoundException, UnknownHostException {
MailSender mailSender = new MailSender();
mailSender.send();
}
private String modelName = "unknown model";
private String specName = "unknown spec";
private File err;
private File out;
// if null, no Mail is going to be send
private InternetAddress[] toAddresses;
private InternetAddress from;
private InternetAddress fromAlt;
public MailSender() throws FileNotFoundException, UnknownHostException, AddressException {
ModelInJar.loadProperties(); // Reads result.mail.address and so on.
final String mailto = System.getProperty(MAIL_ADDRESS);
if (mailto != null) {
this.toAddresses = InternetAddress.parse(mailto);
this.from = new InternetAddress("TLC - The friendly model checker <"
+ toAddresses[0].getAddress() + ">");
this.fromAlt = new InternetAddress("TLC - The friendly model checker <"
+ System.getProperty("user.name") + "@"
+ InetAddress.getLocalHost().getHostName() + ">");
// Record/Log output to later send it by email
final String tmpdir = System.getProperty("java.io.tmpdir");
this.out = new File(tmpdir + File.separator + "MC.out");
ToolIO.out = new LogPrintStream(out);
this.err = new File(tmpdir + File.separator + "MC.err");
ToolIO.err = new LogPrintStream(err);
}
}
public MailSender(String mainFile) throws FileNotFoundException, UnknownHostException, AddressException {
this();
setModelName(mainFile);
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public void setSpecName(String specName) {
this.specName = specName;
}
public boolean send() {
return send(new ArrayList<File>());
}
public boolean send(List<File> files) {
if (toAddresses != null) {
files.add(0, out);
// Only add the err file if there is actually content
if (err.length() != 0L) {
files.add(0, err);
}
// Try sending the mail with the model checking result to the receivers. Returns
// true if a least one email was delivered successfully.
boolean success = false;
for (final InternetAddress toAddress : toAddresses) {
if (send(from, toAddress, "Model Checking result for " + modelName + " with spec " + specName,
extractBody(out), files.toArray(new File[files.size()]))) {
success = true;
} else if (send(fromAlt, toAddress, "Model Checking result for " + modelName + " with spec " + specName,
extractBody(out), files.toArray(new File[files.size()]))) {
// Try with alternative from address which some receivers might actually accept.
success = true;
}
}
return success;
} else {
// ignore, just signal everything is fine
return true;
}
}
/**
* @return The human readable lines in the log file.
*/
private String extractBody(File out) {
StringBuffer result = new StringBuffer();
try {
final Scanner scanner = new Scanner(out);
while (scanner.hasNext()) {
final String line = scanner.nextLine();
if (line != null && !line.startsWith(MP.DELIM)) {
result.append(line);
result.append("\n");
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
result.append("Failed to find file " + out.getAbsolutePath());
}
return result.toString();
}
/**
* A LogPrintStream writes the logging statements to a file _and_ to
* System.out.
*/
private static class LogPrintStream extends PrintStream {
public LogPrintStream(File file) throws FileNotFoundException {
super(new FileOutputStream(file));
}
/* (non-Javadoc)
* @see java.io.PrintStream#println(java.lang.String)
*/
public void println(String str) {
System.out.println(str);
super.println(str);
}
}
}
|
tlatools/src/util/MailSender.java
|
package util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.InitialDirContext;
import model.ModelInJar;
import tlc2.output.MP;
// Requires Java >=6 due to javax.activation only part starting with 6
public class MailSender {
public static final String MODEL_NAME = "modelName";
public static final String SPEC_NAME = "specName";
public static final String MAIL_ADDRESS = "result.mail.address";
/**
* @param from "Foo bar <[email protected]>"
* @param to An email address _with_ domain part ([email protected])
* @param subject
* @param messages
*/
private static boolean send(final InternetAddress from, final InternetAddress to, final String subject, final String body, final File[] files) {
// https://javaee.github.io/javamail/docs/api/com/sun/mail/smtp/package-summary.html
final Properties properties = System.getProperties();
// Prefer email to be delivered encrypted (assumes to lower likelihood of SMTP
// rejection or classification as spam too). Falls back to plain text if SMTP
// server does not support starttls.
properties.put("mail.smtp.starttls.enable", "true");
//properties.put("mail.debug", "true");
try {
final List<MXRecord> mailhosts = getMXForDomain(to.getAddress().split("@")[1]);
// retry all mx host
for (MXRecord mxRecord : mailhosts) {
properties.put("mail.smtp.host", mxRecord.hostname);
final Session session = Session.getDefaultInstance(properties);
final Message msg = new MimeMessage(session);
msg.setFrom(from);
msg.addRecipient(Message.RecipientType.TO, to);
msg.setSubject(subject);
// not sure why the extra body part is needed here
MimeBodyPart messageBodyPart = new MimeBodyPart();
final Multipart multipart = new MimeMultipart();
// The main body part. Having a main body appears to have a very
// positive effect on the spam score compared to emails with
// just attachments. It is also visually more appealing to e.g.
// Outlook users who otherwise see an empty mail.
messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(body, "text/plain");
multipart.addBodyPart(messageBodyPart);
// attach file(s)
for (File file : files) {
if (file == null) {
continue;
}
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(
new FileDataSource(file)));
messageBodyPart.setFileName(file.getName());
messageBodyPart.setHeader("Content-Type", "text/plain");
multipart.addBodyPart(messageBodyPart);
}
msg.setContent(multipart);
Transport.send(msg);
return true;
}
} catch (NamingException e) {
e.printStackTrace();
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
return false;
}
private static List<MXRecord> getMXForDomain(String aDomain) throws NamingException {
final InitialDirContext ctx = new InitialDirContext();
final Attributes attributes = ctx.getAttributes("dns:/" + aDomain,
new String[] { "MX" });
final Attribute attr = attributes.get("MX");
final List<MXRecord> list = new ArrayList<MXRecord>();
// RFC 974
if (attr == null) {
list.add(new MXRecord(0, aDomain));
} else {
// split pref from hostname
for (int i = 0; i < attr.size(); i++) {
Object object = attr.get(i);
if (object != null && object instanceof String) {
String[] split = ((String) object).split("\\s+");
if (split != null && split.length == 2) {
Integer weight = Integer.parseInt(split[0]);
list.add(new MXRecord(weight, split[1]));
}
}
}
}
// sort (according to weight of mxrecord)
Collections.sort(list);
return list;
}
private static class MXRecord implements Comparable<MXRecord> {
public Integer weight;
public String hostname;
public MXRecord(int aWeight, String aHostname) {
weight = aWeight;
hostname = aHostname;
}
public int compareTo(MXRecord o) {
return weight.compareTo(o.weight);
}
}
// For testing only.
public static void main(String[] args) throws AddressException, FileNotFoundException, UnknownHostException {
MailSender mailSender = new MailSender();
mailSender.send();
}
private String modelName = "unknown model";
private String specName = "unknown spec";
private File err;
private File out;
// if null, no Mail is going to be send
private InternetAddress[] toAddresses;
private InternetAddress from;
private InternetAddress fromAlt;
public MailSender() throws FileNotFoundException, UnknownHostException, AddressException {
ModelInJar.loadProperties(); // Reads result.mail.address and so on.
final String mailto = System.getProperty(MAIL_ADDRESS);
if (mailto != null) {
this.toAddresses = InternetAddress.parse(mailto);
this.from = new InternetAddress("TLC - The friendly model checker <"
+ toAddresses[0].getAddress() + ">");
this.fromAlt = new InternetAddress("TLC - The friendly model checker <"
+ System.getProperty("user.name") + "@"
+ InetAddress.getLocalHost().getHostName() + ">");
// Record/Log output to later send it by email
final String tmpdir = System.getProperty("java.io.tmpdir");
this.out = new File(tmpdir + File.separator + "MC.out");
ToolIO.out = new LogPrintStream(out);
this.err = new File(tmpdir + File.separator + "MC.err");
ToolIO.err = new LogPrintStream(err);
}
}
public MailSender(String mainFile) throws FileNotFoundException, UnknownHostException, AddressException {
this();
setModelName(mainFile);
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public void setSpecName(String specName) {
this.specName = specName;
}
public boolean send() {
return send(new ArrayList<File>());
}
public boolean send(List<File> files) {
if (toAddresses != null) {
files.add(0, out);
// Only add the err file if there is actually content
if (err.length() != 0L) {
files.add(0, err);
}
// Try sending the mail with the model checking result to the receivers. Returns
// true if a least one email was delivered successfully.
boolean success = false;
for (final InternetAddress toAddress : toAddresses) {
if (send(from, toAddress, "Model Checking result for " + modelName + " with spec " + specName,
extractBody(out), files.toArray(new File[files.size()]))) {
success = true;
} else if (send(fromAlt, toAddress, "Model Checking result for " + modelName + " with spec " + specName,
extractBody(out), files.toArray(new File[files.size()]))) {
// Try with alternative from address which some receivers might actually accept.
success = true;
}
}
return success;
} else {
// ignore, just signal everything is fine
return true;
}
}
/**
* @return The human readable lines in the log file.
*/
private String extractBody(File out) {
StringBuffer result = new StringBuffer();
try {
final Scanner scanner = new Scanner(out);
while (scanner.hasNext()) {
final String line = scanner.nextLine();
if (line != null && !line.startsWith(MP.DELIM)) {
result.append(line);
result.append("\n");
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
result.append("Failed to find file " + out.getAbsolutePath());
}
return result.toString();
}
/**
* A LogPrintStream writes the logging statements to a file _and_ to
* System.out.
*/
private static class LogPrintStream extends PrintStream {
public LogPrintStream(File file) throws FileNotFoundException {
super(new FileOutputStream(file));
}
/* (non-Javadoc)
* @see java.io.PrintStream#println(java.lang.String)
*/
public void println(String str) {
System.out.println(str);
super.println(str);
}
}
}
|
Broken try/catch, actually retry alternative MX hosts.
[Bug][TLC]
|
tlatools/src/util/MailSender.java
|
Broken try/catch, actually retry alternative MX hosts.
|
<ide><path>latools/src/util/MailSender.java
<ide> properties.put("mail.smtp.starttls.enable", "true");
<ide> //properties.put("mail.debug", "true");
<ide>
<add> if (!to.getAddress().contains("@")) {
<add> // no domain, no MX record to lookup
<add> return false;
<add> }
<add> List<MXRecord> mailhosts;
<ide> try {
<del> final List<MXRecord> mailhosts = getMXForDomain(to.getAddress().split("@")[1]);
<del>
<del> // retry all mx host
<del> for (MXRecord mxRecord : mailhosts) {
<del> properties.put("mail.smtp.host", mxRecord.hostname);
<del>
<add> mailhosts = getMXForDomain(to.getAddress().split("@")[1]);
<add> } catch (NamingException e) {
<add> e.printStackTrace();
<add> return false;
<add> }
<add>
<add> // retry all mx host
<add> for (MXRecord mxRecord : mailhosts) {
<add> properties.put("mail.smtp.host", mxRecord.hostname);
<add> try {
<ide> final Session session = Session.getDefaultInstance(properties);
<ide> final Message msg = new MimeMessage(session);
<ide> msg.setFrom(from);
<ide>
<ide> // not sure why the extra body part is needed here
<ide> MimeBodyPart messageBodyPart = new MimeBodyPart();
<del>
<add>
<ide> final Multipart multipart = new MimeMultipart();
<ide>
<ide> // The main body part. Having a main body appears to have a very
<ide> messageBodyPart = new MimeBodyPart();
<ide> messageBodyPart.setContent(body, "text/plain");
<ide> multipart.addBodyPart(messageBodyPart);
<del>
<add>
<ide> // attach file(s)
<ide> for (File file : files) {
<ide> if (file == null) {
<ide>
<ide> Transport.send(msg);
<ide> return true;
<del> }
<del> } catch (NamingException e) {
<del> e.printStackTrace();
<del> } catch (AddressException e) {
<del> e.printStackTrace();
<del> } catch (MessagingException e) {
<del> e.printStackTrace();
<add> } catch (AddressException e) {
<add> e.printStackTrace();
<add> } catch (MessagingException e) {
<add> e.printStackTrace();
<add> }
<ide> }
<ide> return false;
<ide> }
|
|
Java
|
apache-2.0
|
84e5a6a1c07f4ecfffb6ade954a9187b404b3cea
| 0 |
msgpack-rpc/msgpack-rpc-java
|
package org.msgpack.rpc.client;
import java.util.ArrayList;
import java.util.List;
public class TCPTransport {
protected Session session;
protected EventLoop loop;
protected Boolean isConnecting;
protected Boolean isConnected;
protected TCPSocket socket;
protected List<Object> pendingMessages;
public TCPTransport(Session session, EventLoop loop) {
this.session = session;
this.loop = loop;
this.isConnecting = false;
this.isConnected = false;
this.socket = new TCPSocket(session.getAddress(), loop, this);
this.pendingMessages = new ArrayList<Object>();
}
// hide the connect(2) latency from the Transport user
public synchronized void sendMessage(Object msg) throws Exception {
if (isConnected) {
socket.trySend(msg);
} else {
if (!isConnecting) {
socket.tryConnect();
isConnecting = true;
}
pendingMessages.add(msg);
}
}
protected synchronized void trySendPending() throws Exception {
for (Object msg : pendingMessages)
socket.trySend(msg);
pendingMessages.clear();
}
public synchronized void tryClose() {
if (socket != null)
socket.tryClose();
isConnecting = false;
isConnected = false;
socket = null;
pendingMessages.clear();
}
// callback
public synchronized void onConnected() throws Exception {
isConnecting = false;
isConnected = true;
trySendPending();
}
// callback
public void onConnectFailed() {
tryClose();
session.onConnectFailed();
}
// callback
public void onMessageReceived(Object replyObject) throws Exception {
session.onMessageReceived(replyObject);
}
// callback
public void onClosed() {
tryClose();
session.onClosed();
}
// callback
public void onFailed(Exception e) {
tryClose();
session.onFailed(e);
}
}
|
src/main/java/org/msgpack/rpc/client/TCPTransport.java
|
package org.msgpack.rpc.client;
import java.util.ArrayList;
import java.util.List;
public class TCPTransport {
protected Session session;
protected EventLoop loop;
protected Boolean isConnecting;
protected Boolean isConnected;
protected TCPSocket socket;
protected List<Object> pendingMessages;
public TCPTransport(Session session, EventLoop loop) {
this.session = session;
this.loop = loop;
this.isConnecting = false;
this.isConnected = false;
this.socket = new TCPSocket(session.getAddress(), loop, this);
this.pendingMessages = new ArrayList<Object>();
}
// hide the connect(2) latency from the Transport user
public synchronized void sendMessage(Object msg) throws Exception {
if (isConnected) {
socket.trySend(msg);
} else {
if (!isConnecting) {
socket.tryConnect();
isConnecting = true;
}
pendingMessages.add(msg);
}
}
protected synchronized void trySendPending() throws Exception {
for (Object msg : pendingMessages)
socket.trySend(msg);
}
public synchronized void tryClose() {
if (socket != null)
socket.tryClose();
isConnecting = false;
isConnected = false;
socket = null;
pendingMessages.clear();
}
// callback
public synchronized void onConnected() throws Exception {
isConnecting = false;
isConnected = true;
trySendPending();
}
// callback
public void onConnectFailed() {
tryClose();
session.onConnectFailed();
}
// callback
public void onMessageReceived(Object replyObject) throws Exception {
session.onMessageReceived(replyObject);
}
// callback
public void onClosed() {
tryClose();
session.onClosed();
}
// callback
public void onFailed(Exception e) {
tryClose();
session.onFailed(e);
}
}
|
java: fixed critical bug that pendingMessages aren't cleared after sendPending()
|
src/main/java/org/msgpack/rpc/client/TCPTransport.java
|
java: fixed critical bug that pendingMessages aren't cleared after sendPending()
|
<ide><path>rc/main/java/org/msgpack/rpc/client/TCPTransport.java
<ide> protected synchronized void trySendPending() throws Exception {
<ide> for (Object msg : pendingMessages)
<ide> socket.trySend(msg);
<add> pendingMessages.clear();
<ide> }
<ide>
<ide> public synchronized void tryClose() {
|
|
Java
|
apache-2.0
|
d04b1603640a9109676d6e1d2dd769300525e381
| 0 |
idea4bsd/idea4bsd,vvv1559/intellij-community,apixandru/intellij-community,da1z/intellij-community,hurricup/intellij-community,jexp/idea2,ivan-fedorov/intellij-community,petteyg/intellij-community,consulo/consulo,youdonghai/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,izonder/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,caot/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,ernestp/consulo,akosyakov/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,consulo/consulo,caot/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,apixandru/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,ibinti/intellij-community,clumsy/intellij-community,adedayo/intellij-community,adedayo/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,youdonghai/intellij-community,izonder/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,caot/intellij-community,da1z/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,kool79/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,supersven/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,robovm/robovm-studio,kdwink/intellij-community,amith01994/intellij-community,joewalnes/idea-community,akosyakov/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,caot/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,adedayo/intellij-community,blademainer/intellij-community,semonte/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,slisson/intellij-community,blademainer/intellij-community,semonte/intellij-community,samthor/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,vladmm/intellij-community,apixandru/intellij-community,signed/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,fitermay/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,amith01994/intellij-community,holmes/intellij-community,blademainer/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,holmes/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,izonder/intellij-community,FHannes/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,allotria/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,gnuhub/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,ernestp/consulo,orekyuu/intellij-community,kdwink/intellij-community,asedunov/intellij-community,allotria/intellij-community,retomerz/intellij-community,ernestp/consulo,wreckJ/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,da1z/intellij-community,jexp/idea2,hurricup/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,jexp/idea2,da1z/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,tmpgit/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,signed/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,slisson/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,ibinti/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,slisson/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,allotria/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,jagguli/intellij-community,holmes/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,kool79/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,holmes/intellij-community,holmes/intellij-community,vladmm/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,supersven/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,consulo/consulo,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,adedayo/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,samthor/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,suncycheng/intellij-community,signed/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,jexp/idea2,ahb0327/intellij-community,petteyg/intellij-community,kool79/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,allotria/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,fitermay/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,allotria/intellij-community,suncycheng/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,semonte/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,jexp/idea2,robovm/robovm-studio,signed/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,signed/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,retomerz/intellij-community,adedayo/intellij-community,samthor/intellij-community,izonder/intellij-community,joewalnes/idea-community,caot/intellij-community,dslomov/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,jexp/idea2,ahb0327/intellij-community,adedayo/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,fnouama/intellij-community,vladmm/intellij-community,caot/intellij-community,FHannes/intellij-community,amith01994/intellij-community,asedunov/intellij-community,fnouama/intellij-community,hurricup/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,asedunov/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,signed/intellij-community,youdonghai/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,supersven/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,joewalnes/idea-community,apixandru/intellij-community,FHannes/intellij-community,da1z/intellij-community,ernestp/consulo,kool79/intellij-community,amith01994/intellij-community,samthor/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,robovm/robovm-studio,fnouama/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,allotria/intellij-community,semonte/intellij-community,vladmm/intellij-community,robovm/robovm-studio,jexp/idea2,fitermay/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,kdwink/intellij-community,clumsy/intellij-community,clumsy/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,allotria/intellij-community,samthor/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,diorcety/intellij-community,petteyg/intellij-community,da1z/intellij-community,slisson/intellij-community,caot/intellij-community,hurricup/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,diorcety/intellij-community,clumsy/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,consulo/consulo,xfournet/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,consulo/consulo,vladmm/intellij-community,Distrotech/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,jexp/idea2,fitermay/intellij-community,suncycheng/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,semonte/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,holmes/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,joewalnes/idea-community,fnouama/intellij-community,ernestp/consulo,da1z/intellij-community,kool79/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,blademainer/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,consulo/consulo,salguarnieri/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,diorcety/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,supersven/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,signed/intellij-community,youdonghai/intellij-community,holmes/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,izonder/intellij-community,jagguli/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,xfournet/intellij-community,petteyg/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,clumsy/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,signed/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,amith01994/intellij-community,petteyg/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,hurricup/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,slisson/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,jagguli/intellij-community,amith01994/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,signed/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,caot/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,izonder/intellij-community,allotria/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,dslomov/intellij-community,fitermay/intellij-community,supersven/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,allotria/intellij-community,signed/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,wreckJ/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,kool79/intellij-community,joewalnes/idea-community,blademainer/intellij-community,signed/intellij-community,samthor/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,apixandru/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd
|
/*
* Copyright 2000-2007 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.util.text;
import com.intellij.CommonBundle;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.util.Function;
import com.intellij.util.SmartList;
import com.intellij.util.text.CharArrayCharSequence;
import com.intellij.util.text.LineReader;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.beans.Introspector;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
public class StringUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.text.StringUtil");
@NonNls private static final String VOWELS = "aeiouy";
public static String replace(@NonNls @NotNull String text, @NonNls @NotNull String oldS, @NonNls @Nullable String newS) {
return replace(text, oldS, newS, false);
}
public static String replaceIgnoreCase(@NotNull String text, @NotNull String oldS, @Nullable String newS) {
return replace(text, oldS, newS, true);
}
public static void replaceChar(@NotNull char[] buffer, char oldChar, char newChar, int start, int end) {
for (int i = start; i < end; i++) {
char c = buffer[i];
if (c == oldChar) {
buffer[i] = newChar;
}
}
}
public static String replace(@NotNull final String text, @NotNull final String oldS, @Nullable final String newS, boolean ignoreCase) {
if (text.length() < oldS.length()) return text;
final String text1 = ignoreCase ? text.toLowerCase() : text;
final String oldS1 = ignoreCase ? oldS.toLowerCase() : oldS;
final StringBuilder newText = new StringBuilder();
int i = 0;
while (i < text1.length()) {
int i1 = text1.indexOf(oldS1, i);
if (i1 < 0) {
if (i == 0) return text;
newText.append(text, i, text.length());
break;
}
else {
if (newS == null) return null;
newText.append(text, i, i1);
newText.append(newS);
i = i1 + oldS.length();
}
}
return newText.toString();
}
@NotNull public static String getShortName(@NotNull String fqName) {
return getShortName(fqName, '.');
}
@NotNull public static String getShortName(@NotNull Class aClass) {
return getShortName(aClass.getName());
}
/**
* Implementation copied from {@link String#indexOf(String, int)} except character comparisons made case insensitive
*
* @param where
* @param what
* @param fromIndex
* @return
*/
public static int indexOfIgnoreCase(@NotNull String where, @NotNull String what, int fromIndex) {
int targetCount = what.length();
int sourceCount = where.length();
if (fromIndex >= sourceCount) {
return targetCount == 0 ? sourceCount : -1;
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
char first = what.charAt(0);
int max = sourceCount - targetCount;
for (int i = fromIndex; i <= max; i++) {
/* Look for first character. */
if (!charsEqualIgnoreCase(where.charAt(i), first)) {
while (++i <= max && !charsEqualIgnoreCase(where.charAt(i), first)) ;
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = 1; j < end && charsEqualIgnoreCase(where.charAt(j), what.charAt(k)); j++, k++) ;
if (j == end) {
/* Found whole string. */
return i;
}
}
}
return -1;
}
public static boolean containsIgnoreCase(String where, String what) {
return indexOfIgnoreCase(where, what, 0) >= 0;
}
public static boolean endsWithIgnoreCase(@NonNls String str, @NonNls String suffix) {
final int stringLength = str.length();
final int suffixLength = suffix.length();
return stringLength >= suffixLength && str.regionMatches(true, stringLength - suffixLength, suffix, 0, suffixLength);
}
public static boolean startsWithIgnoreCase(String str, String prefix) {
final int stringLength = str.length();
final int prefixLength = prefix.length();
return stringLength >= prefixLength && str.regionMatches(true, 0, prefix, 0, prefixLength);
}
public static boolean charsEqualIgnoreCase(char a, char b) {
return a == b || toUpperCase(a) == toUpperCase(b) || toLowerCase(a) == toLowerCase(b);
}
public static char toUpperCase(char a) {
if (a < 'a') {
return a;
}
if (a >= 'a' && a <= 'z') {
return (char)(a + ('A' - 'a'));
}
return Character.toUpperCase(a);
}
public static char toLowerCase(final char a) {
if (a < 'A' || a >= 'a' && a <= 'z') {
return a;
}
if (a >= 'A' && a <= 'Z') {
return (char)(a + ('a' - 'A'));
}
return Character.toLowerCase(a);
}
@Nullable
public static String toLowerCase(@Nullable final String str) {
return str == null? null : str.toLowerCase();
}
@NotNull public static String getShortName(@NotNull String fqName, char separator) {
int lastPointIdx = fqName.lastIndexOf(separator);
if (lastPointIdx >= 0) {
return fqName.substring(lastPointIdx + 1);
}
return fqName;
}
@NotNull public static String getPackageName(@NotNull String fqName) {
return getPackageName(fqName, '.');
}
@NotNull public static String getPackageName(@NotNull String fqName, char separator) {
int lastPointIdx = fqName.lastIndexOf(separator);
if (lastPointIdx >= 0) {
return fqName.substring(0, lastPointIdx);
}
return "";
}
/**
* Converts line separators to <code>"\n"</code>
*/
@NotNull public static String convertLineSeparators(@NotNull String text) {
return convertLineSeparators(text, "\n", null);
}
@NotNull public static String convertLineSeparators(@NotNull String text, @NotNull String newSeparator) {
return convertLineSeparators(text, newSeparator, null);
}
@NotNull public static String convertLineSeparators(@NotNull String text, @NotNull String newSeparator, @Nullable int[] offsetsToKeep) {
StringBuilder buffer = new StringBuilder(text.length());
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n') {
buffer.append(newSeparator);
shiftOffsets(offsetsToKeep, buffer.length(), 1, newSeparator.length());
}
else if (c == '\r') {
buffer.append(newSeparator);
if (i < text.length() - 1 && text.charAt(i + 1) == '\n') {
i++;
shiftOffsets(offsetsToKeep, buffer.length(), 2, newSeparator.length());
}
else {
shiftOffsets(offsetsToKeep, buffer.length(), 1, newSeparator.length());
}
}
else {
buffer.append(c);
}
}
return buffer.toString();
}
private static void shiftOffsets(int[] offsets, int changeOffset, int oldLength, int newLength) {
if (offsets == null) return;
int shift = newLength - oldLength;
if (shift == 0) return;
for (int i = 0; i < offsets.length; i++) {
int offset = offsets[i];
if (offset >= changeOffset + oldLength) {
offsets[i] += shift;
}
}
}
public static int getLineBreakCount(@NotNull CharSequence text) {
int count = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n') {
count++;
}
else if (c == '\r') {
if (i + 1 < text.length() && text.charAt(i + 1) == '\n') {
i++;
count++;
}
else {
count++;
}
}
}
return count;
}
public static int lineColToOffset(@NotNull CharSequence text, int line, int col) {
int curLine = 0;
int offset = 0;
while (line != curLine) {
if (offset == text.length()) return -1;
char c = text.charAt(offset);
if (c == '\n') {
curLine++;
}
else if (c == '\r') {
curLine++;
if (offset < text.length() - 1 && text.charAt(offset + 1) == '\n') {
offset++;
}
}
offset++;
}
return offset + col;
}
public static int offsetToLineNumber(@NotNull CharSequence text, int offset) {
int curLine = 0;
int curOffset = 0;
while (curOffset < offset) {
if (curOffset == text.length()) return -1;
char c = text.charAt(curOffset);
if (c == '\n') {
curLine++;
}
else if (c == '\r') {
curLine++;
if (curOffset < text.length() - 1 && text.charAt(curOffset + 1) == '\n') {
curOffset++;
}
}
curOffset++;
}
return curLine;
}
/**
* Classic dynamic programming algorithm for string differences.
*/
public static int difference(@NotNull String s1, @NotNull String s2) {
int[][] a = new int[s1.length()][s2.length()];
for (int i = 0; i < s1.length(); i++) {
a[i][0] = i;
}
for (int j = 0; j < s2.length(); j++) {
a[0][j] = j;
}
for (int i = 1; i < s1.length(); i++) {
for (int j = 1; j < s2.length(); j++) {
a[i][j] = Math.min(Math.min(a[i - 1][j - 1] + (s1.charAt(i) == s2.charAt(j) ? 0 : 1), a[i - 1][j] + 1), a[i][j - 1] + 1);
}
}
return a[s1.length() - 1][s2.length() - 1];
}
@NotNull public static String wordsToBeginFromUpperCase(@NotNull String s) {
StringBuffer buffer = null;
for (int i = 0; i < s.length(); i++) {
char prevChar = i == 0 ? ' ' : s.charAt(i - 1);
char currChar = s.charAt(i);
if (!Character.isLetterOrDigit(prevChar)) {
if (Character.isLetterOrDigit(currChar)) {
if (!Character.isUpperCase(currChar)) {
int j = i;
for (; j < s.length(); j++) {
if (!Character.isLetterOrDigit(s.charAt(j))) {
break;
}
}
if (!isPreposition(s, i, j - 1)) {
if (buffer == null) {
buffer = new StringBuffer(s);
}
buffer.setCharAt(i, toUpperCase(currChar));
}
}
}
}
}
if (buffer == null) {
return s;
}
else {
return buffer.toString();
}
}
@NonNls private static final String[] ourPrepositions =
new String[]{"at", "the", "and", "not", "if", "a", "or", "to", "in", "on", "into"};
public static boolean isPreposition(@NotNull String s, int firstChar, int lastChar) {
for (String preposition : ourPrepositions) {
boolean found = false;
if (lastChar - firstChar + 1 == preposition.length()) {
found = true;
for (int j = 0; j < preposition.length(); j++) {
if (!(toLowerCase(s.charAt(firstChar + j)) == preposition.charAt(j))) {
found = false;
}
}
}
if (found) {
return true;
}
}
return false;
}
public static void escapeStringCharacters(int length, final String str, @NotNull @NonNls StringBuilder buffer) {
for (int idx = 0; idx < length; idx++) {
char ch = str.charAt(idx);
switch (ch) {
case'\b':
buffer.append("\\b");
break;
case'\t':
buffer.append("\\t");
break;
case'\n':
buffer.append("\\n");
break;
case'\f':
buffer.append("\\f");
break;
case'\r':
buffer.append("\\r");
break;
case'\"':
buffer.append("\\\"");
break;
case'\\':
buffer.append("\\\\");
break;
default:
if (Character.isISOControl(ch)) {
String hexCode = Integer.toHexString(ch).toUpperCase();
buffer.append("\\u");
int paddingCount = 4 - hexCode.length();
while (paddingCount-- > 0) {
buffer.append(0);
}
buffer.append(hexCode);
}
else {
buffer.append(ch);
}
}
}
}
@NotNull public static String escapeStringCharacters(@NotNull String s) {
StringBuilder buffer = new StringBuilder();
escapeStringCharacters(s.length(), s, buffer);
return buffer.toString();
}
@NotNull public static String unescapeStringCharacters(@NotNull String s) {
StringBuilder buffer = new StringBuilder();
unescapeStringCharacters(s.length(), s, buffer);
return buffer.toString();
}
@NotNull public static String unquoteString( @NotNull String s )
{
if( s.length() > 1 && s.charAt( 0 ) == '"' && s.charAt( s.length() - 1) == '"' )
return s.substring( 1, s.length() - 1 );
else
return s;
}
private static void unescapeStringCharacters(int length, String s, StringBuilder buffer) {
boolean escaped = false;
for (int idx = 0; idx < length; idx++) {
char ch = s.charAt(idx);
if (!escaped) {
if (ch == '\\') {
escaped = true;
}
else {
buffer.append(ch);
}
}
else {
switch (ch) {
case'n':
buffer.append('\n');
break;
case'r':
buffer.append('\r');
break;
case'b':
buffer.append('\b');
break;
case't':
buffer.append('\t');
break;
case'f':
buffer.append('\f');
break;
case'\'':
buffer.append('\'');
break;
case'\"':
buffer.append('\"');
break;
case'\\':
buffer.append('\\');
break;
case'u':
if (idx + 4 < length) {
try {
int code = Integer.valueOf(s.substring(idx + 1, idx + 5), 16).intValue();
idx += 4;
buffer.append((char)code);
}
catch (NumberFormatException e) {
buffer.append("\\u");
}
}
else {
buffer.append("\\u");
}
break;
default:
buffer.append(ch);
break;
}
escaped = false;
}
}
if (escaped) buffer.append('\\');
}
@SuppressWarnings({"HardCodedStringLiteral"})
@NotNull public static String pluralize(@NotNull String suggestion) {
if (suggestion.endsWith("Child") || suggestion.endsWith("child")) {
return suggestion + "ren";
}
if (endsWithChar(suggestion, 's') || endsWithChar(suggestion, 'x') || suggestion.endsWith("ch")) {
return suggestion + "es";
}
int len = suggestion.length();
if (endsWithChar(suggestion, 'y') && len > 1 && !isVowel(suggestion.charAt(len - 2))) {
return suggestion.substring(0, len - 1) + "ies";
}
return suggestion + "s";
}
@NotNull public static String capitalizeWords(@NotNull String text, boolean allWords) {
StringTokenizer tokenizer = new StringTokenizer(text);
String out = "";
String delim = "";
boolean toCapitalize = true;
while (tokenizer.hasMoreTokens()) {
String word = tokenizer.nextToken();
out += delim + (toCapitalize ? capitalize(word) : word);
delim = " ";
if (!allWords) {
toCapitalize = false;
}
}
return out;
}
public static String decapitalize(String s) {
return Introspector.decapitalize(s);
}
public static boolean isVowel(char c) {
return VOWELS.indexOf(c) >= 0;
}
@NotNull public static String capitalize(@NotNull String s) {
if (s.length() == 0) return s;
if (s.length() == 1) return s.toUpperCase();
// Optimization
if (Character.isUpperCase(s.charAt(0)) ) return s;
return toUpperCase(s.charAt(0)) + s.substring(1);
}
public static int stringHashCode(CharSequence chars) {
if (chars instanceof String) return chars.hashCode();
if (chars instanceof CharSequenceWithStringHash) return chars.hashCode();
if (chars instanceof CharArrayCharSequence) return chars.hashCode();
int h = 0;
int to = chars.length();
for (int off = 0; off < to; off++) {
h = 31 * h + chars.charAt(off);
}
return h;
}
public static int stringHashCode(CharSequence chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + chars.charAt(off);
}
return h;
}
public static int stringHashCode(char[] chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + chars[off];
}
return h;
}
public static int stringHashCodeInsensitive(char[] chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + toLowerCase(chars[off]);
}
return h;
}
public static int stringHashCodeInsensitive(CharSequence chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + toLowerCase(chars.charAt(off));
}
return h;
}
public static int stringHashCodeInsensitive(@NotNull CharSequence chars) {
int h = 0;
final int len = chars.length();
for (int i = 0; i < len; i++) {
h = 31 * h + toLowerCase(chars.charAt(i));
}
return h;
}
@NotNull public static String trimEnd(@NotNull String s, @NonNls @NotNull String suffix) {
if (s.endsWith(suffix)) {
return s.substring(0, s.lastIndexOf(suffix));
}
return s;
}
public static boolean startsWithChar(@Nullable CharSequence s, char prefix) {
return s != null && s.length() != 0 && s.charAt(0) == prefix;
}
public static boolean endsWithChar(@Nullable CharSequence s, char suffix) {
return s != null && s.length() != 0 && s.charAt(s.length() - 1) == suffix;
}
@NotNull public static String trimStart(@NotNull String s, @NonNls @NotNull String prefix) {
if (s.startsWith(prefix)) {
return s.substring(prefix.length());
}
return s;
}
@NotNull public static String pluralize(@NotNull String base, int n) {
if (n == 1) return base;
return pluralize(base);
}
public static void repeatSymbol(Appendable buffer, char symbol, int times) {
try {
for (int i = 0; i < times; i++) {
buffer.append(symbol);
}
}
catch (IOException e) {
LOG.error(e);
}
}
public static boolean isNotEmpty(final String s) {
return s != null && s.length() > 0;
}
public static boolean isEmpty(final String s) {
return s == null || s.length() == 0;
}
@NotNull
public static String notNullize(final String s) {
return s == null ? "" : s;
}
public static boolean isEmptyOrSpaces(final String s) {
return s == null || s.trim().length() == 0;
}
public static String getThrowableText(final Throwable aThrowable) {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
aThrowable.printStackTrace(writer);
return stringWriter.getBuffer().toString();
}
public static String getThrowableText(final Throwable aThrowable, @NonNls @NotNull final String stackFrameSkipPattern) {
@NonNls final String prefix = "\tat ";
final String skipPattern = prefix + stackFrameSkipPattern;
final StringWriter stringWriter = new StringWriter();
final PrintWriter writer = new PrintWriter(stringWriter) {
boolean skipping = false;
public void println(final String x) {
if (x != null) {
if (!skipping && x.startsWith(skipPattern)) skipping = true;
else if (skipping && !x.startsWith(prefix)) skipping = false;
}
if (skipping) return;
super.println(x);
}
};
aThrowable.printStackTrace(writer);
return stringWriter.getBuffer().toString();
}
public static String getMessage(Throwable e) {
String result = e.getMessage();
@NonNls final String exceptionPattern = "Exception: ";
@NonNls final String errorPattern = "Error: ";
while ((result == null || result.contains(exceptionPattern) || result.contains(errorPattern)) && e.getCause() != null) {
e = e.getCause();
result = e.getMessage();
}
if (result != null) {
result = extractMessage(result, exceptionPattern);
result = extractMessage(result, errorPattern);
}
return result;
}
@NotNull private static String extractMessage(@NotNull String result, @NotNull final String errorPattern) {
if (result.lastIndexOf(errorPattern) >= 0) {
result = result.substring(result.lastIndexOf(errorPattern) + errorPattern.length());
}
return result;
}
@NotNull public static String repeatSymbol(final char aChar, final int count) {
final StringBuilder buffer = new StringBuilder();
repeatSymbol(buffer, aChar, count);
return buffer.toString();
}
@NotNull
public static List<String> splitHonorQuotes(@NotNull String s, char separator) {
final ArrayList<String> result = new ArrayList<String>();
final StringBuilder builder = new StringBuilder();
boolean inQuotes = false;
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (c == separator && !inQuotes) {
if (builder.length() > 0) {
result.add(builder.toString());
builder.setLength(0);
}
continue;
}
if ((c == '"' || c == '\'') && !(i > 0 && s.charAt(i - 1) == '\\')) {
inQuotes = !inQuotes;
}
builder.append(c);
}
if (builder.length() > 0) {
result.add(builder.toString());
}
return result;
}
@NotNull public static List<String> split(@NotNull String s, @NotNull String separator) {
if (separator.length() == 0) {
return Collections.singletonList(s);
}
ArrayList<String> result = new ArrayList<String>();
int pos = 0;
while (true) {
int index = s.indexOf(separator, pos);
if (index == -1) break;
String token = s.substring(pos, index);
if (token.length() != 0) {
result.add(token);
}
pos = index + separator.length();
}
if (pos < s.length()) {
result.add(s.substring(pos, s.length()));
}
return result;
}
@NotNull
public static Iterable<String> tokenize(@NotNull String s, @NotNull String separators) {
final com.intellij.util.text.StringTokenizer tokenizer = new com.intellij.util.text.StringTokenizer(s, separators);
return new Iterable<String>() {
public Iterator<String> iterator() {
return new Iterator<String>() {
public boolean hasNext() {
return tokenizer.hasMoreTokens();
}
public String next() {
return tokenizer.nextToken();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
@NotNull
public static List<String> getWordsIn(@NotNull String text) {
List<String> result = new SmartList<String>();
int start = -1;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
boolean isIdentifierPart = Character.isJavaIdentifierPart(c);
if (isIdentifierPart && start == -1) {
start = i;
}
if (isIdentifierPart && i == text.length() - 1 && start != -1) {
result.add(text.substring(start, i + 1));
}
else if (!isIdentifierPart && start != -1) {
result.add(text.substring(start, i));
start = -1;
}
}
return result;
}
@NotNull public static String join(@NotNull final String[] strings, @NotNull final String separator) {
return join(strings, 0, strings.length, separator);
}
@NotNull public static String join(@NotNull final String[] strings, int startIndex, int endIndex, @NotNull final String separator) {
final StringBuilder result = new StringBuilder();
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) result.append(separator);
result.append(strings[i]);
}
return result.toString();
}
@NotNull public static String[] zip(@NotNull String[] strings1, @NotNull String[] strings2, String separator) {
if (strings1.length != strings2.length) throw new IllegalArgumentException();
String[] result = new String[strings1.length];
for (int i = 0; i < result.length; i++) {
result[i] = strings1[i] + separator + strings2[i];
}
return result;
}
public static String[] surround(String[] strings1, String prefix, String suffix) {
String[] result = new String[strings1.length];
for (int i = 0; i < result.length; i++) {
result[i] = prefix + strings1[i] + suffix;
}
return result;
}
@NotNull public static <T> String join(@NotNull T[] items, @NotNull Function<T, String> f, @NotNull @NonNls String separator) {
return join(Arrays.asList(items), f, separator);
}
@NotNull public static <T> String join(@NotNull Iterable<T> items, @NotNull Function<T, String> f, @NotNull @NonNls String separator) {
final StringBuilder result = new StringBuilder();
for (T item : items) {
String string = f.fun(item);
if (string != null && string.length() != 0) {
if (result.length() != 0) result.append(separator);
result.append(string);
}
}
return result.toString();
}
@NotNull public static String join(@NotNull Collection<String> strings, @NotNull final String separator) {
final StringBuilder result = new StringBuilder();
for (String string : strings) {
if (string != null && string.length() != 0) {
if (result.length() != 0) result.append(separator);
result.append(string);
}
}
return result.toString();
}
@NotNull public static String join(@NotNull final int[] strings, @NotNull final String separator) {
final StringBuilder result = new StringBuilder();
for (int i = 0; i < strings.length; i++) {
if (i > 0) result.append(separator);
result.append(strings[i]);
}
return result.toString();
}
@NotNull public static String stripQuotesAroundValue(@NotNull String text) {
if (startsWithChar(text, '\"') || startsWithChar(text, '\'')) text = text.substring(1);
if (endsWithChar(text, '\"') || endsWithChar(text, '\'')) text = text.substring(0, text.length() - 1);
return text;
}
public static boolean isQuotedString(@NotNull String text) {
return startsWithChar(text, '\"') && endsWithChar(text, '\"')
|| startsWithChar(text, '\'') && endsWithChar(text, '\'');
}
/**
* Formats the specified file size as a string.
*
* @param fileSize the size to format.
* @return the size formatted as a string.
* @since 5.0.1
*/
@NotNull public static String formatFileSize(final long fileSize) {
if (fileSize < 0x400) {
return CommonBundle.message("file.size.format.bytes", fileSize);
}
if (fileSize < 0x100000) {
long kbytes = fileSize * 100 / 1024;
final String kbs = kbytes / 100 + "." + kbytes % 100;
return CommonBundle.message("file.size.format.kbytes", kbs);
}
long mbytes = fileSize * 100 / 1024 / 1024;
final String size = mbytes / 100 + "." + mbytes % 100;
return CommonBundle.message("file.size.format.mbytes", size);
}
/**
* Returns unpluralized variant using English based heuristics like properties -> property, names -> name, children -> child.
* Returns <code>null</code> if failed to match appropriate heuristic.
*
* @param name english word in plural form
* @return name in singular form or <code>null</code> if failed to find one.
*/
@SuppressWarnings({"HardCodedStringLiteral"})
@Nullable
public static String unpluralize(@NotNull final String name) {
if (name.endsWith("sses") || name.endsWith("shes") || name.endsWith("ches") || name.endsWith("xes")) { //?
return name.substring(0, name.length() - 2);
}
if (name.endsWith("ses")) {
return name.substring(0, name.length() - 1);
}
if (name.endsWith("ies")) {
return name.substring(0, name.length() - 3) + "y";
}
String result = stripEnding(name, "s");
if (result != null) {
return result;
}
if (name.endsWith("children")) {
return name.substring(0, name.length() - "children".length()) + "child";
}
if (name.endsWith("Children") && name.length() > "Children".length()) {
return name.substring(0, name.length() - "Children".length()) + "Child";
}
return null;
}
private static String stripEnding(String name, String ending) {
if (name.endsWith(ending)) {
if (name.equals(ending)) return name; // do not return empty string
return name.substring(0, name.length() - 1);
}
return null;
}
public static boolean containsAlphaCharacters(@NotNull String value) {
for (int i = 0; i < value.length(); i++) {
if (Character.isLetter(value.charAt(i))) return true;
}
return false;
}
public static String firstLetterToUpperCase(final String displayString) {
if (displayString == null || displayString.length() == 0) return displayString;
char firstChar = displayString.charAt(0);
char uppedFirstChar = toUpperCase(firstChar);
if (uppedFirstChar == firstChar) return displayString;
StringBuilder builder = new StringBuilder(displayString);
builder.setCharAt(0, uppedFirstChar);
return builder.toString();
}
/**
* Strip out all characters not accepted by given filter
* @param s e.g. "/n my string "
* @param filter e.g. {@link CharFilter#NOT_WHITESPACE_FILTER}
* @return stripped string e.g. "mystring"
*/
@NotNull public static String strip(@NotNull final String s, @NotNull CharFilter filter) {
StringBuilder result = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (filter.accept(ch)) {
result.append(ch);
}
}
return result.toString();
}
/**
* Find position of the first charachter accepted by given filter
* @param s the string to search
* @param filter
* @return position of the first charachter accepted or -1 if not found
*/
public static int findFirst(@NotNull final String s, @NotNull CharFilter filter) {
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (filter.accept(ch)) {
return i;
}
}
return -1;
}
@NotNull public static String replaceSubstring(@NotNull String string, @NotNull TextRange range, @NotNull String replacement) {
return string.substring(0, range.getStartOffset()) + replacement + string.substring(range.getEndOffset());
}
public static boolean startsWith(@NotNull CharSequence text, @NotNull CharSequence prefix) {
int l1 = text.length();
int l2 = prefix.length();
if (l1 < l2) return false;
for (int i = 0; i < l2; i++) {
if (text.charAt(i) != prefix.charAt(i)) return false;
}
return true;
}
public static boolean endsWith(@NotNull CharSequence text, @NotNull CharSequence suffix) {
int l1 = text.length();
int l2 = suffix.length();
if (l1 < l2) return false;
for (int i = l1-1; i >= l1-l2; i--) {
if (text.charAt(i) != suffix.charAt(i+l2-l1)) return false;
}
return true;
}
@NotNull
public static String commonPrefix(@NotNull String s1, @NotNull String s2) {
int i;
for (i = 0; i<s1.length() && i<s2.length(); i++) {
if (s1.charAt(i) != s2.charAt(i)) {
break;
}
}
return s1.substring(0, i);
}
@NotNull
public static String commonSuffix(@NotNull String s1, @NotNull String s2) {
if (s1.length() == 0 || s2.length() == 0) return "";
int i;
for (i = s1.length()-1; i>=0 && i>=s1.length() - s2.length(); i--) {
if (s1.charAt(i) != s2.charAt(i+s2.length()-s1.length())) {
break;
}
}
return s1.substring(i, s1.length());
}
public static int indexOf(CharSequence s, char c) {
int l = s.length();
for (int i = 0; i < l; i++) {
if (s.charAt(i) == c) return i;
}
return -1;
}
public static String first(final String text, final int length, final boolean appendEllipsis) {
return text.length() > length ? text.substring(0, length) + (appendEllipsis ? "..." : "") : text;
}
public static String escapeQuotes(@NotNull final String str) {
int idx = str.indexOf('"');
if (idx < 0) return str;
StringBuilder buf = new StringBuilder(str);
while (idx < buf.length()) {
if (buf.charAt(idx) == '"') {
buf.replace(idx, idx + 1, "\\\"");
idx += 2;
}
else {
idx += 1;
}
}
return buf.toString();
}
@NonNls private static final String[] REPLACES_REFS = new String[]{"<", " ", ">", "&", "'", """};
@NonNls private static final String[] REPLACES_DISP = new String[]{"<", "\u00a0", ">", "&", "'", "\""};
public static String unescapeXml(final String text) {
if (text == null) return null;
return replace(text, REPLACES_REFS, REPLACES_DISP);
}
public static String escapeXml(final String text) {
if (text == null) return null;
return replace(text, REPLACES_DISP, REPLACES_REFS);
}
public static String escapeToRegexp(String text) {
@NonNls StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
final char c = text.charAt(i);
if (c == ' ' || Character.isLetter(c) || Character.isDigit(c)) {
result.append(c);
}
else if (c == '\n') {
result.append("\\n");
}
else {
result.append('\\').append(c);
}
}
return result.toString();
}
private static String replace(final String text, final String[] from, final String[] to) {
final StringBuilder result = new StringBuilder(text.length());
replace:
for (int i = 0; i < text.length(); i++) {
for (int j = 0; j < from.length; j += 1) {
String toReplace = from[j];
String replaceWith = to[j];
final int len = toReplace.length();
if (text.regionMatches(i, toReplace, 0, len)) {
result.append(replaceWith);
i += len - 1;
continue replace;
}
}
result.append(text.charAt(i));
}
return result.toString();
}
public static String[] filterEmptyStrings(String[] strings) {
int emptyCount = 0;
for (String string : strings) {
if (string == null || string.length() == 0) emptyCount++;
}
if (emptyCount == 0) return strings;
String[] result = new String[strings.length - emptyCount];
int count = 0;
for (String string : strings) {
if (string == null || string.length() == 0) continue;
result[count++] = string;
}
return result;
}
public static int countNewLines(final CharSequence text) {
int lineShift = 0;
for(int i = 0; i < text.length(); ++i) {
final char ch = text.charAt(i);
if (ch == '\n') {
++lineShift;
}
}
return lineShift;
}
public static String capitalsOnly(String s) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (Character.isUpperCase(s.charAt(i))) {
b.append(s.charAt(i));
}
}
return b.toString();
}
// returns null if any of args is null
@Nullable
public static String joinOrNull(@NotNull String... args) {
StringBuilder r = new StringBuilder();
for (String arg : args) {
if (arg == null) return null;
r.append(arg);
}
return r.toString();
}
public static String getPropertyName(@NonNls final String methodName) {
if (methodName.startsWith("get")) {
return Introspector.decapitalize(methodName.substring(3));
}
else if (methodName.startsWith("is")) {
return Introspector.decapitalize(methodName.substring(2));
}
else if (methodName.startsWith("set")) {
return Introspector.decapitalize(methodName.substring(3));
}
else {
return null;
}
}
public static boolean isJavaIdentifierStart(char c) {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || Character.isJavaIdentifierStart(c);
}
public static boolean isJavaIdentifierPart(char c) {
return c >= '0' && c <= '9' || isJavaIdentifierStart(c);
}
public static boolean isJavaIdentifier(String text) {
int len = text.length();
if (len == 0) return false;
if (!isJavaIdentifierStart(text.charAt(0))) return false;
for (int i = 1; i < len; i++) {
if (!isJavaIdentifierPart(text.charAt(i))) return false;
}
return true;
}
public static String shiftIndentInside(final String initial, final int i, boolean shiftEmptyLines) throws IOException {
StringBuilder result = new StringBuilder(initial.length());
LineReader reader = new LineReader(new ByteArrayInputStream(initial.getBytes()));
boolean first = true;
for (byte[] line : reader.readLines()) {
try {
if (!first) result.append('\n');
if (line.length > 0 || shiftEmptyLines) {
result.append(repeatSymbol(' ', i));
}
result.append(new String(line));
}
finally {
first = false;
}
}
return result.toString();
}
}
|
util/src/com/intellij/openapi/util/text/StringUtil.java
|
/*
* Copyright 2000-2007 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.util.text;
import com.intellij.CommonBundle;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.util.Function;
import com.intellij.util.SmartList;
import com.intellij.util.text.CharArrayCharSequence;
import com.intellij.util.text.LineReader;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.beans.Introspector;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
public class StringUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.text.StringUtil");
@NonNls private static final String VOWELS = "aeiouy";
public static String replace(@NonNls @NotNull String text, @NonNls @NotNull String oldS, @NonNls @Nullable String newS) {
return replace(text, oldS, newS, false);
}
public static String replaceIgnoreCase(@NotNull String text, @NotNull String oldS, @Nullable String newS) {
return replace(text, oldS, newS, true);
}
public static void replaceChar(@NotNull char[] buffer, char oldChar, char newChar, int start, int end) {
for (int i = start; i < end; i++) {
char c = buffer[i];
if (c == oldChar) {
buffer[i] = newChar;
}
}
}
public static String replace(@NotNull final String text, @NotNull final String oldS, @Nullable final String newS, boolean ignoreCase) {
if (text.length() < oldS.length()) return text;
final String text1 = ignoreCase ? text.toLowerCase() : text;
final String oldS1 = ignoreCase ? oldS.toLowerCase() : oldS;
final StringBuilder newText = new StringBuilder();
int i = 0;
while (i < text1.length()) {
int i1 = text1.indexOf(oldS1, i);
if (i1 < 0) {
if (i == 0) return text;
newText.append(text, i, text.length());
break;
}
else {
if (newS == null) return null;
newText.append(text, i, i1);
newText.append(newS);
i = i1 + oldS.length();
}
}
return newText.toString();
}
@NotNull public static String getShortName(@NotNull String fqName) {
return getShortName(fqName, '.');
}
@NotNull public static String getShortName(@NotNull Class aClass) {
return getShortName(aClass.getName());
}
/**
* Implementation copied from {@link String#indexOf(String, int)} except character comparisons made case insensitive
*
* @param where
* @param what
* @param fromIndex
* @return
*/
public static int indexOfIgnoreCase(@NotNull String where, @NotNull String what, int fromIndex) {
int targetCount = what.length();
int sourceCount = where.length();
if (fromIndex >= sourceCount) {
return targetCount == 0 ? sourceCount : -1;
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
char first = what.charAt(0);
int max = sourceCount - targetCount;
for (int i = fromIndex; i <= max; i++) {
/* Look for first character. */
if (!charsEqualIgnoreCase(where.charAt(i), first)) {
while (++i <= max && !charsEqualIgnoreCase(where.charAt(i), first)) ;
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = 1; j < end && charsEqualIgnoreCase(where.charAt(j), what.charAt(k)); j++, k++) ;
if (j == end) {
/* Found whole string. */
return i;
}
}
}
return -1;
}
public static boolean containsIgnoreCase(String where, String what) {
return indexOfIgnoreCase(where, what, 0) >= 0;
}
public static boolean endsWithIgnoreCase(@NonNls String str, @NonNls String suffix) {
final int stringLength = str.length();
final int suffixLength = suffix.length();
return stringLength >= suffixLength && str.regionMatches(true, stringLength - suffixLength, suffix, 0, suffixLength);
}
public static boolean startsWithIgnoreCase(String str, String prefix) {
final int stringLength = str.length();
final int prefixLength = prefix.length();
return stringLength >= prefixLength && str.regionMatches(true, 0, prefix, 0, prefixLength);
}
public static boolean charsEqualIgnoreCase(char a, char b) {
return a == b || toUpperCase(a) == toUpperCase(b) || toLowerCase(a) == toLowerCase(b);
}
public static char toUpperCase(char a) {
if (a < 'a') {
return a;
}
if (a >= 'a' && a <= 'z') {
return (char)(a + ('A' - 'a'));
}
return Character.toUpperCase(a);
}
public static char toLowerCase(final char a) {
if (a < 'A' || a >= 'a' && a <= 'z') {
return a;
}
if (a >= 'A' && a <= 'Z') {
return (char)(a + ('a' - 'A'));
}
return Character.toLowerCase(a);
}
@NotNull public static String getShortName(@NotNull String fqName, char separator) {
int lastPointIdx = fqName.lastIndexOf(separator);
if (lastPointIdx >= 0) {
return fqName.substring(lastPointIdx + 1);
}
return fqName;
}
@NotNull public static String getPackageName(@NotNull String fqName) {
return getPackageName(fqName, '.');
}
@NotNull public static String getPackageName(@NotNull String fqName, char separator) {
int lastPointIdx = fqName.lastIndexOf(separator);
if (lastPointIdx >= 0) {
return fqName.substring(0, lastPointIdx);
}
return "";
}
/**
* Converts line separators to <code>"\n"</code>
*/
@NotNull public static String convertLineSeparators(@NotNull String text) {
return convertLineSeparators(text, "\n", null);
}
@NotNull public static String convertLineSeparators(@NotNull String text, @NotNull String newSeparator) {
return convertLineSeparators(text, newSeparator, null);
}
@NotNull public static String convertLineSeparators(@NotNull String text, @NotNull String newSeparator, @Nullable int[] offsetsToKeep) {
StringBuilder buffer = new StringBuilder(text.length());
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n') {
buffer.append(newSeparator);
shiftOffsets(offsetsToKeep, buffer.length(), 1, newSeparator.length());
}
else if (c == '\r') {
buffer.append(newSeparator);
if (i < text.length() - 1 && text.charAt(i + 1) == '\n') {
i++;
shiftOffsets(offsetsToKeep, buffer.length(), 2, newSeparator.length());
}
else {
shiftOffsets(offsetsToKeep, buffer.length(), 1, newSeparator.length());
}
}
else {
buffer.append(c);
}
}
return buffer.toString();
}
private static void shiftOffsets(int[] offsets, int changeOffset, int oldLength, int newLength) {
if (offsets == null) return;
int shift = newLength - oldLength;
if (shift == 0) return;
for (int i = 0; i < offsets.length; i++) {
int offset = offsets[i];
if (offset >= changeOffset + oldLength) {
offsets[i] += shift;
}
}
}
public static int getLineBreakCount(@NotNull CharSequence text) {
int count = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n') {
count++;
}
else if (c == '\r') {
if (i + 1 < text.length() && text.charAt(i + 1) == '\n') {
i++;
count++;
}
else {
count++;
}
}
}
return count;
}
public static int lineColToOffset(@NotNull CharSequence text, int line, int col) {
int curLine = 0;
int offset = 0;
while (line != curLine) {
if (offset == text.length()) return -1;
char c = text.charAt(offset);
if (c == '\n') {
curLine++;
}
else if (c == '\r') {
curLine++;
if (offset < text.length() - 1 && text.charAt(offset + 1) == '\n') {
offset++;
}
}
offset++;
}
return offset + col;
}
public static int offsetToLineNumber(@NotNull CharSequence text, int offset) {
int curLine = 0;
int curOffset = 0;
while (curOffset < offset) {
if (curOffset == text.length()) return -1;
char c = text.charAt(curOffset);
if (c == '\n') {
curLine++;
}
else if (c == '\r') {
curLine++;
if (curOffset < text.length() - 1 && text.charAt(curOffset + 1) == '\n') {
curOffset++;
}
}
curOffset++;
}
return curLine;
}
/**
* Classic dynamic programming algorithm for string differences.
*/
public static int difference(@NotNull String s1, @NotNull String s2) {
int[][] a = new int[s1.length()][s2.length()];
for (int i = 0; i < s1.length(); i++) {
a[i][0] = i;
}
for (int j = 0; j < s2.length(); j++) {
a[0][j] = j;
}
for (int i = 1; i < s1.length(); i++) {
for (int j = 1; j < s2.length(); j++) {
a[i][j] = Math.min(Math.min(a[i - 1][j - 1] + (s1.charAt(i) == s2.charAt(j) ? 0 : 1), a[i - 1][j] + 1), a[i][j - 1] + 1);
}
}
return a[s1.length() - 1][s2.length() - 1];
}
@NotNull public static String wordsToBeginFromUpperCase(@NotNull String s) {
StringBuffer buffer = null;
for (int i = 0; i < s.length(); i++) {
char prevChar = i == 0 ? ' ' : s.charAt(i - 1);
char currChar = s.charAt(i);
if (!Character.isLetterOrDigit(prevChar)) {
if (Character.isLetterOrDigit(currChar)) {
if (!Character.isUpperCase(currChar)) {
int j = i;
for (; j < s.length(); j++) {
if (!Character.isLetterOrDigit(s.charAt(j))) {
break;
}
}
if (!isPreposition(s, i, j - 1)) {
if (buffer == null) {
buffer = new StringBuffer(s);
}
buffer.setCharAt(i, toUpperCase(currChar));
}
}
}
}
}
if (buffer == null) {
return s;
}
else {
return buffer.toString();
}
}
@NonNls private static final String[] ourPrepositions =
new String[]{"at", "the", "and", "not", "if", "a", "or", "to", "in", "on", "into"};
public static boolean isPreposition(@NotNull String s, int firstChar, int lastChar) {
for (String preposition : ourPrepositions) {
boolean found = false;
if (lastChar - firstChar + 1 == preposition.length()) {
found = true;
for (int j = 0; j < preposition.length(); j++) {
if (!(toLowerCase(s.charAt(firstChar + j)) == preposition.charAt(j))) {
found = false;
}
}
}
if (found) {
return true;
}
}
return false;
}
public static void escapeStringCharacters(int length, final String str, @NotNull @NonNls StringBuilder buffer) {
for (int idx = 0; idx < length; idx++) {
char ch = str.charAt(idx);
switch (ch) {
case'\b':
buffer.append("\\b");
break;
case'\t':
buffer.append("\\t");
break;
case'\n':
buffer.append("\\n");
break;
case'\f':
buffer.append("\\f");
break;
case'\r':
buffer.append("\\r");
break;
case'\"':
buffer.append("\\\"");
break;
case'\\':
buffer.append("\\\\");
break;
default:
if (Character.isISOControl(ch)) {
String hexCode = Integer.toHexString(ch).toUpperCase();
buffer.append("\\u");
int paddingCount = 4 - hexCode.length();
while (paddingCount-- > 0) {
buffer.append(0);
}
buffer.append(hexCode);
}
else {
buffer.append(ch);
}
}
}
}
@NotNull public static String escapeStringCharacters(@NotNull String s) {
StringBuilder buffer = new StringBuilder();
escapeStringCharacters(s.length(), s, buffer);
return buffer.toString();
}
@NotNull public static String unescapeStringCharacters(@NotNull String s) {
StringBuilder buffer = new StringBuilder();
unescapeStringCharacters(s.length(), s, buffer);
return buffer.toString();
}
@NotNull public static String unquoteString( @NotNull String s )
{
if( s.length() > 1 && s.charAt( 0 ) == '"' && s.charAt( s.length() - 1) == '"' )
return s.substring( 1, s.length() - 1 );
else
return s;
}
private static void unescapeStringCharacters(int length, String s, StringBuilder buffer) {
boolean escaped = false;
for (int idx = 0; idx < length; idx++) {
char ch = s.charAt(idx);
if (!escaped) {
if (ch == '\\') {
escaped = true;
}
else {
buffer.append(ch);
}
}
else {
switch (ch) {
case'n':
buffer.append('\n');
break;
case'r':
buffer.append('\r');
break;
case'b':
buffer.append('\b');
break;
case't':
buffer.append('\t');
break;
case'f':
buffer.append('\f');
break;
case'\'':
buffer.append('\'');
break;
case'\"':
buffer.append('\"');
break;
case'\\':
buffer.append('\\');
break;
case'u':
if (idx + 4 < length) {
try {
int code = Integer.valueOf(s.substring(idx + 1, idx + 5), 16).intValue();
idx += 4;
buffer.append((char)code);
}
catch (NumberFormatException e) {
buffer.append("\\u");
}
}
else {
buffer.append("\\u");
}
break;
default:
buffer.append(ch);
break;
}
escaped = false;
}
}
if (escaped) buffer.append('\\');
}
@SuppressWarnings({"HardCodedStringLiteral"})
@NotNull public static String pluralize(@NotNull String suggestion) {
if (suggestion.endsWith("Child") || suggestion.endsWith("child")) {
return suggestion + "ren";
}
if (endsWithChar(suggestion, 's') || endsWithChar(suggestion, 'x') || suggestion.endsWith("ch")) {
return suggestion + "es";
}
int len = suggestion.length();
if (endsWithChar(suggestion, 'y') && len > 1 && !isVowel(suggestion.charAt(len - 2))) {
return suggestion.substring(0, len - 1) + "ies";
}
return suggestion + "s";
}
@NotNull public static String capitalizeWords(@NotNull String text, boolean allWords) {
StringTokenizer tokenizer = new StringTokenizer(text);
String out = "";
String delim = "";
boolean toCapitalize = true;
while (tokenizer.hasMoreTokens()) {
String word = tokenizer.nextToken();
out += delim + (toCapitalize ? capitalize(word) : word);
delim = " ";
if (!allWords) {
toCapitalize = false;
}
}
return out;
}
public static String decapitalize(String s) {
return Introspector.decapitalize(s);
}
public static boolean isVowel(char c) {
return VOWELS.indexOf(c) >= 0;
}
@NotNull public static String capitalize(@NotNull String s) {
if (s.length() == 0) return s;
if (s.length() == 1) return s.toUpperCase();
// Optimization
if (Character.isUpperCase(s.charAt(0)) ) return s;
return toUpperCase(s.charAt(0)) + s.substring(1);
}
public static int stringHashCode(CharSequence chars) {
if (chars instanceof String) return chars.hashCode();
if (chars instanceof CharSequenceWithStringHash) return chars.hashCode();
if (chars instanceof CharArrayCharSequence) return chars.hashCode();
int h = 0;
int to = chars.length();
for (int off = 0; off < to; off++) {
h = 31 * h + chars.charAt(off);
}
return h;
}
public static int stringHashCode(CharSequence chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + chars.charAt(off);
}
return h;
}
public static int stringHashCode(char[] chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + chars[off];
}
return h;
}
public static int stringHashCodeInsensitive(char[] chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + toLowerCase(chars[off]);
}
return h;
}
public static int stringHashCodeInsensitive(CharSequence chars, int from, int to) {
int h = 0;
for (int off = from; off < to; off++) {
h = 31 * h + toLowerCase(chars.charAt(off));
}
return h;
}
public static int stringHashCodeInsensitive(@NotNull CharSequence chars) {
int h = 0;
final int len = chars.length();
for (int i = 0; i < len; i++) {
h = 31 * h + toLowerCase(chars.charAt(i));
}
return h;
}
@NotNull public static String trimEnd(@NotNull String s, @NonNls @NotNull String suffix) {
if (s.endsWith(suffix)) {
return s.substring(0, s.lastIndexOf(suffix));
}
return s;
}
public static boolean startsWithChar(@Nullable CharSequence s, char prefix) {
return s != null && s.length() != 0 && s.charAt(0) == prefix;
}
public static boolean endsWithChar(@Nullable CharSequence s, char suffix) {
return s != null && s.length() != 0 && s.charAt(s.length() - 1) == suffix;
}
@NotNull public static String trimStart(@NotNull String s, @NonNls @NotNull String prefix) {
if (s.startsWith(prefix)) {
return s.substring(prefix.length());
}
return s;
}
@NotNull public static String pluralize(@NotNull String base, int n) {
if (n == 1) return base;
return pluralize(base);
}
public static void repeatSymbol(Appendable buffer, char symbol, int times) {
try {
for (int i = 0; i < times; i++) {
buffer.append(symbol);
}
}
catch (IOException e) {
LOG.error(e);
}
}
public static boolean isNotEmpty(final String s) {
return s != null && s.length() > 0;
}
public static boolean isEmpty(final String s) {
return s == null || s.length() == 0;
}
@NotNull
public static String notNullize(final String s) {
return s == null ? "" : s;
}
public static boolean isEmptyOrSpaces(final String s) {
return s == null || s.trim().length() == 0;
}
public static String getThrowableText(final Throwable aThrowable) {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
aThrowable.printStackTrace(writer);
return stringWriter.getBuffer().toString();
}
public static String getThrowableText(final Throwable aThrowable, @NonNls @NotNull final String stackFrameSkipPattern) {
@NonNls final String prefix = "\tat ";
final String skipPattern = prefix + stackFrameSkipPattern;
final StringWriter stringWriter = new StringWriter();
final PrintWriter writer = new PrintWriter(stringWriter) {
boolean skipping = false;
public void println(final String x) {
if (x != null) {
if (!skipping && x.startsWith(skipPattern)) skipping = true;
else if (skipping && !x.startsWith(prefix)) skipping = false;
}
if (skipping) return;
super.println(x);
}
};
aThrowable.printStackTrace(writer);
return stringWriter.getBuffer().toString();
}
public static String getMessage(Throwable e) {
String result = e.getMessage();
@NonNls final String exceptionPattern = "Exception: ";
@NonNls final String errorPattern = "Error: ";
while ((result == null || result.contains(exceptionPattern) || result.contains(errorPattern)) && e.getCause() != null) {
e = e.getCause();
result = e.getMessage();
}
if (result != null) {
result = extractMessage(result, exceptionPattern);
result = extractMessage(result, errorPattern);
}
return result;
}
@NotNull private static String extractMessage(@NotNull String result, @NotNull final String errorPattern) {
if (result.lastIndexOf(errorPattern) >= 0) {
result = result.substring(result.lastIndexOf(errorPattern) + errorPattern.length());
}
return result;
}
@NotNull public static String repeatSymbol(final char aChar, final int count) {
final StringBuilder buffer = new StringBuilder();
repeatSymbol(buffer, aChar, count);
return buffer.toString();
}
@NotNull
public static List<String> splitHonorQuotes(@NotNull String s, char separator) {
final ArrayList<String> result = new ArrayList<String>();
final StringBuilder builder = new StringBuilder();
boolean inQuotes = false;
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (c == separator && !inQuotes) {
if (builder.length() > 0) {
result.add(builder.toString());
builder.setLength(0);
}
continue;
}
if ((c == '"' || c == '\'') && !(i > 0 && s.charAt(i - 1) == '\\')) {
inQuotes = !inQuotes;
}
builder.append(c);
}
if (builder.length() > 0) {
result.add(builder.toString());
}
return result;
}
@NotNull public static List<String> split(@NotNull String s, @NotNull String separator) {
if (separator.length() == 0) {
return Collections.singletonList(s);
}
ArrayList<String> result = new ArrayList<String>();
int pos = 0;
while (true) {
int index = s.indexOf(separator, pos);
if (index == -1) break;
String token = s.substring(pos, index);
if (token.length() != 0) {
result.add(token);
}
pos = index + separator.length();
}
if (pos < s.length()) {
result.add(s.substring(pos, s.length()));
}
return result;
}
@NotNull
public static Iterable<String> tokenize(@NotNull String s, @NotNull String separators) {
final com.intellij.util.text.StringTokenizer tokenizer = new com.intellij.util.text.StringTokenizer(s, separators);
return new Iterable<String>() {
public Iterator<String> iterator() {
return new Iterator<String>() {
public boolean hasNext() {
return tokenizer.hasMoreTokens();
}
public String next() {
return tokenizer.nextToken();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
@NotNull
public static List<String> getWordsIn(@NotNull String text) {
List<String> result = new SmartList<String>();
int start = -1;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
boolean isIdentifierPart = Character.isJavaIdentifierPart(c);
if (isIdentifierPart && start == -1) {
start = i;
}
if (isIdentifierPart && i == text.length() - 1 && start != -1) {
result.add(text.substring(start, i + 1));
}
else if (!isIdentifierPart && start != -1) {
result.add(text.substring(start, i));
start = -1;
}
}
return result;
}
@NotNull public static String join(@NotNull final String[] strings, @NotNull final String separator) {
return join(strings, 0, strings.length, separator);
}
@NotNull public static String join(@NotNull final String[] strings, int startIndex, int endIndex, @NotNull final String separator) {
final StringBuilder result = new StringBuilder();
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) result.append(separator);
result.append(strings[i]);
}
return result.toString();
}
@NotNull public static String[] zip(@NotNull String[] strings1, @NotNull String[] strings2, String separator) {
if (strings1.length != strings2.length) throw new IllegalArgumentException();
String[] result = new String[strings1.length];
for (int i = 0; i < result.length; i++) {
result[i] = strings1[i] + separator + strings2[i];
}
return result;
}
public static String[] surround(String[] strings1, String prefix, String suffix) {
String[] result = new String[strings1.length];
for (int i = 0; i < result.length; i++) {
result[i] = prefix + strings1[i] + suffix;
}
return result;
}
@NotNull public static <T> String join(@NotNull T[] items, @NotNull Function<T, String> f, @NotNull @NonNls String separator) {
return join(Arrays.asList(items), f, separator);
}
@NotNull public static <T> String join(@NotNull Iterable<T> items, @NotNull Function<T, String> f, @NotNull @NonNls String separator) {
final StringBuilder result = new StringBuilder();
for (T item : items) {
String string = f.fun(item);
if (string != null && string.length() != 0) {
if (result.length() != 0) result.append(separator);
result.append(string);
}
}
return result.toString();
}
@NotNull public static String join(@NotNull Collection<String> strings, @NotNull final String separator) {
final StringBuilder result = new StringBuilder();
for (String string : strings) {
if (string != null && string.length() != 0) {
if (result.length() != 0) result.append(separator);
result.append(string);
}
}
return result.toString();
}
@NotNull public static String join(@NotNull final int[] strings, @NotNull final String separator) {
final StringBuilder result = new StringBuilder();
for (int i = 0; i < strings.length; i++) {
if (i > 0) result.append(separator);
result.append(strings[i]);
}
return result.toString();
}
@NotNull public static String stripQuotesAroundValue(@NotNull String text) {
if (startsWithChar(text, '\"') || startsWithChar(text, '\'')) text = text.substring(1);
if (endsWithChar(text, '\"') || endsWithChar(text, '\'')) text = text.substring(0, text.length() - 1);
return text;
}
public static boolean isQuotedString(@NotNull String text) {
return startsWithChar(text, '\"') && endsWithChar(text, '\"')
|| startsWithChar(text, '\'') && endsWithChar(text, '\'');
}
/**
* Formats the specified file size as a string.
*
* @param fileSize the size to format.
* @return the size formatted as a string.
* @since 5.0.1
*/
@NotNull public static String formatFileSize(final long fileSize) {
if (fileSize < 0x400) {
return CommonBundle.message("file.size.format.bytes", fileSize);
}
if (fileSize < 0x100000) {
long kbytes = fileSize * 100 / 1024;
final String kbs = kbytes / 100 + "." + kbytes % 100;
return CommonBundle.message("file.size.format.kbytes", kbs);
}
long mbytes = fileSize * 100 / 1024 / 1024;
final String size = mbytes / 100 + "." + mbytes % 100;
return CommonBundle.message("file.size.format.mbytes", size);
}
/**
* Returns unpluralized variant using English based heuristics like properties -> property, names -> name, children -> child.
* Returns <code>null</code> if failed to match appropriate heuristic.
*
* @param name english word in plural form
* @return name in singular form or <code>null</code> if failed to find one.
*/
@SuppressWarnings({"HardCodedStringLiteral"})
@Nullable
public static String unpluralize(@NotNull final String name) {
if (name.endsWith("sses") || name.endsWith("shes") || name.endsWith("ches") || name.endsWith("xes")) { //?
return name.substring(0, name.length() - 2);
}
if (name.endsWith("ses")) {
return name.substring(0, name.length() - 1);
}
if (name.endsWith("ies")) {
return name.substring(0, name.length() - 3) + "y";
}
String result = stripEnding(name, "s");
if (result != null) {
return result;
}
if (name.endsWith("children")) {
return name.substring(0, name.length() - "children".length()) + "child";
}
if (name.endsWith("Children") && name.length() > "Children".length()) {
return name.substring(0, name.length() - "Children".length()) + "Child";
}
return null;
}
private static String stripEnding(String name, String ending) {
if (name.endsWith(ending)) {
if (name.equals(ending)) return name; // do not return empty string
return name.substring(0, name.length() - 1);
}
return null;
}
public static boolean containsAlphaCharacters(@NotNull String value) {
for (int i = 0; i < value.length(); i++) {
if (Character.isLetter(value.charAt(i))) return true;
}
return false;
}
public static String firstLetterToUpperCase(final String displayString) {
if (displayString == null || displayString.length() == 0) return displayString;
char firstChar = displayString.charAt(0);
char uppedFirstChar = toUpperCase(firstChar);
if (uppedFirstChar == firstChar) return displayString;
StringBuilder builder = new StringBuilder(displayString);
builder.setCharAt(0, uppedFirstChar);
return builder.toString();
}
/**
* Strip out all characters not accepted by given filter
* @param s e.g. "/n my string "
* @param filter e.g. {@link CharFilter#NOT_WHITESPACE_FILTER}
* @return stripped string e.g. "mystring"
*/
@NotNull public static String strip(@NotNull final String s, @NotNull CharFilter filter) {
StringBuilder result = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (filter.accept(ch)) {
result.append(ch);
}
}
return result.toString();
}
/**
* Find position of the first charachter accepted by given filter
* @param s the string to search
* @param filter
* @return position of the first charachter accepted or -1 if not found
*/
public static int findFirst(@NotNull final String s, @NotNull CharFilter filter) {
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (filter.accept(ch)) {
return i;
}
}
return -1;
}
@NotNull public static String replaceSubstring(@NotNull String string, @NotNull TextRange range, @NotNull String replacement) {
return string.substring(0, range.getStartOffset()) + replacement + string.substring(range.getEndOffset());
}
public static boolean startsWith(@NotNull CharSequence text, @NotNull CharSequence prefix) {
int l1 = text.length();
int l2 = prefix.length();
if (l1 < l2) return false;
for (int i = 0; i < l2; i++) {
if (text.charAt(i) != prefix.charAt(i)) return false;
}
return true;
}
public static boolean endsWith(@NotNull CharSequence text, @NotNull CharSequence suffix) {
int l1 = text.length();
int l2 = suffix.length();
if (l1 < l2) return false;
for (int i = l1-1; i >= l1-l2; i--) {
if (text.charAt(i) != suffix.charAt(i+l2-l1)) return false;
}
return true;
}
@NotNull
public static String commonPrefix(@NotNull String s1, @NotNull String s2) {
int i;
for (i = 0; i<s1.length() && i<s2.length(); i++) {
if (s1.charAt(i) != s2.charAt(i)) {
break;
}
}
return s1.substring(0, i);
}
@NotNull
public static String commonSuffix(@NotNull String s1, @NotNull String s2) {
if (s1.length() == 0 || s2.length() == 0) return "";
int i;
for (i = s1.length()-1; i>=0 && i>=s1.length() - s2.length(); i--) {
if (s1.charAt(i) != s2.charAt(i+s2.length()-s1.length())) {
break;
}
}
return s1.substring(i, s1.length());
}
public static int indexOf(CharSequence s, char c) {
int l = s.length();
for (int i = 0; i < l; i++) {
if (s.charAt(i) == c) return i;
}
return -1;
}
public static String first(final String text, final int length, final boolean appendEllipsis) {
return text.length() > length ? text.substring(0, length) + (appendEllipsis ? "..." : "") : text;
}
public static String escapeQuotes(@NotNull final String str) {
int idx = str.indexOf('"');
if (idx < 0) return str;
StringBuilder buf = new StringBuilder(str);
while (idx < buf.length()) {
if (buf.charAt(idx) == '"') {
buf.replace(idx, idx + 1, "\\\"");
idx += 2;
}
else {
idx += 1;
}
}
return buf.toString();
}
@NonNls private static final String[] REPLACES_REFS = new String[]{"<", " ", ">", "&", "'", """};
@NonNls private static final String[] REPLACES_DISP = new String[]{"<", "\u00a0", ">", "&", "'", "\""};
public static String unescapeXml(final String text) {
if (text == null) return null;
return replace(text, REPLACES_REFS, REPLACES_DISP);
}
public static String escapeXml(final String text) {
if (text == null) return null;
return replace(text, REPLACES_DISP, REPLACES_REFS);
}
public static String escapeToRegexp(String text) {
@NonNls StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
final char c = text.charAt(i);
if (c == ' ' || Character.isLetter(c) || Character.isDigit(c)) {
result.append(c);
}
else if (c == '\n') {
result.append("\\n");
}
else {
result.append('\\').append(c);
}
}
return result.toString();
}
private static String replace(final String text, final String[] from, final String[] to) {
final StringBuilder result = new StringBuilder(text.length());
replace:
for (int i = 0; i < text.length(); i++) {
for (int j = 0; j < from.length; j += 1) {
String toReplace = from[j];
String replaceWith = to[j];
final int len = toReplace.length();
if (text.regionMatches(i, toReplace, 0, len)) {
result.append(replaceWith);
i += len - 1;
continue replace;
}
}
result.append(text.charAt(i));
}
return result.toString();
}
public static String[] filterEmptyStrings(String[] strings) {
int emptyCount = 0;
for (String string : strings) {
if (string == null || string.length() == 0) emptyCount++;
}
if (emptyCount == 0) return strings;
String[] result = new String[strings.length - emptyCount];
int count = 0;
for (String string : strings) {
if (string == null || string.length() == 0) continue;
result[count++] = string;
}
return result;
}
public static int countNewLines(final CharSequence text) {
int lineShift = 0;
for(int i = 0; i < text.length(); ++i) {
final char ch = text.charAt(i);
if (ch == '\n') {
++lineShift;
}
}
return lineShift;
}
public static String capitalsOnly(String s) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (Character.isUpperCase(s.charAt(i))) {
b.append(s.charAt(i));
}
}
return b.toString();
}
// returns null if any of args is null
@Nullable
public static String joinOrNull(@NotNull String... args) {
StringBuilder r = new StringBuilder();
for (String arg : args) {
if (arg == null) return null;
r.append(arg);
}
return r.toString();
}
public static String getPropertyName(@NonNls final String methodName) {
if (methodName.startsWith("get")) {
return Introspector.decapitalize(methodName.substring(3));
}
else if (methodName.startsWith("is")) {
return Introspector.decapitalize(methodName.substring(2));
}
else if (methodName.startsWith("set")) {
return Introspector.decapitalize(methodName.substring(3));
}
else {
return null;
}
}
public static boolean isJavaIdentifierStart(char c) {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || Character.isJavaIdentifierStart(c);
}
public static boolean isJavaIdentifierPart(char c) {
return c >= '0' && c <= '9' || isJavaIdentifierStart(c);
}
public static boolean isJavaIdentifier(String text) {
int len = text.length();
if (len == 0) return false;
if (!isJavaIdentifierStart(text.charAt(0))) return false;
for (int i = 1; i < len; i++) {
if (!isJavaIdentifierPart(text.charAt(i))) return false;
}
return true;
}
public static String shiftIndentInside(final String initial, final int i, boolean shiftEmptyLines) throws IOException {
StringBuilder result = new StringBuilder(initial.length());
LineReader reader = new LineReader(new ByteArrayInputStream(initial.getBytes()));
boolean first = true;
for (byte[] line : reader.readLines()) {
try {
if (!first) result.append('\n');
if (line.length > 0 || shiftEmptyLines) {
result.append(repeatSymbol(' ', i));
}
result.append(new String(line));
}
finally {
first = false;
}
}
return result.toString();
}
}
|
lowercase type
|
util/src/com/intellij/openapi/util/text/StringUtil.java
|
lowercase type
|
<ide><path>til/src/com/intellij/openapi/util/text/StringUtil.java
<ide> }
<ide>
<ide> return Character.toLowerCase(a);
<add> }
<add>
<add> @Nullable
<add> public static String toLowerCase(@Nullable final String str) {
<add> return str == null? null : str.toLowerCase();
<ide> }
<ide>
<ide> @NotNull public static String getShortName(@NotNull String fqName, char separator) {
|
|
Java
|
apache-2.0
|
7714a5c70e3a6a4d9a697c7701566c690ab76085
| 0 |
mdogan/hazelcast,dbrimley/hazelcast,mesutcelik/hazelcast,Donnerbart/hazelcast,emrahkocaman/hazelcast,Donnerbart/hazelcast,juanavelez/hazelcast,lmjacksoniii/hazelcast,dsukhoroslov/hazelcast,juanavelez/hazelcast,Donnerbart/hazelcast,mesutcelik/hazelcast,mdogan/hazelcast,lmjacksoniii/hazelcast,tufangorel/hazelcast,emre-aydin/hazelcast,dbrimley/hazelcast,dbrimley/hazelcast,tkountis/hazelcast,mdogan/hazelcast,tombujok/hazelcast,tkountis/hazelcast,dsukhoroslov/hazelcast,tombujok/hazelcast,emrahkocaman/hazelcast,emre-aydin/hazelcast,emre-aydin/hazelcast,tufangorel/hazelcast,tufangorel/hazelcast,mesutcelik/hazelcast,tkountis/hazelcast
|
/*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.diagnostics;
import com.hazelcast.instance.Node;
import com.hazelcast.instance.NodeState;
import com.hazelcast.instance.OutOfMemoryErrorDispatcher;
import com.hazelcast.internal.metrics.DoubleGauge;
import com.hazelcast.internal.metrics.LongGauge;
import com.hazelcast.internal.metrics.MetricsRegistry;
import com.hazelcast.logging.ILogger;
import com.hazelcast.memory.MemoryStats;
import com.hazelcast.spi.properties.GroupProperty;
import java.util.logging.Level;
import static com.hazelcast.internal.diagnostics.HealthMonitorLevel.OFF;
import static com.hazelcast.internal.diagnostics.HealthMonitorLevel.valueOf;
import static com.hazelcast.util.StringUtil.LINE_SEPARATOR;
import static java.lang.String.format;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* Health monitor periodically prints logs about related internal metrics using the {@link MetricsRegistry}
* to provide some clues about the internal Hazelcast state.
* <p/>
* Health monitor can be configured with system properties.
* <p/>
* {@link GroupProperty#HEALTH_MONITORING_LEVEL}
* This property can be one of the following:
* {@link HealthMonitorLevel#NOISY} => does not check threshold, always prints.
* {@link HealthMonitorLevel#SILENT} => prints only if metrics are above threshold (default).
* {@link HealthMonitorLevel#OFF} => does not print anything.
* <p/>
* {@link GroupProperty#HEALTH_MONITORING_DELAY_SECONDS}
* Time between printing two logs of health monitor. Default values is 30 seconds.
* <p/>
* {@link GroupProperty#HEALTH_MONITORING_THRESHOLD_MEMORY_PERCENTAGE}
* Threshold: Percentage of max memory currently in use
* <p/>
* {@link GroupProperty#HEALTH_MONITORING_THRESHOLD_CPU_PERCENTAGE}
* Threshold: CPU system/process load
*/
public class HealthMonitor {
private static final String[] UNITS = new String[]{"", "K", "M", "G", "T", "P", "E"};
private static final double PERCENTAGE_MULTIPLIER = 100d;
private static final double THRESHOLD_PERCENTAGE_INVOCATIONS = 70;
private static final double THRESHOLD_INVOCATIONS = 1000;
final HealthMetrics healthMetrics;
private final ILogger logger;
private final Node node;
private final HealthMonitorLevel monitorLevel;
private final int thresholdMemoryPercentage;
private final int thresholdCPUPercentage;
private final MetricsRegistry metricRegistry;
private final HealthMonitorThread monitorThread;
public HealthMonitor(Node node) {
this.node = node;
this.logger = node.getLogger(HealthMonitor.class);
this.metricRegistry = node.nodeEngine.getMetricsRegistry();
this.monitorLevel = getHealthMonitorLevel();
this.thresholdMemoryPercentage
= node.getProperties().getInteger(GroupProperty.HEALTH_MONITORING_THRESHOLD_MEMORY_PERCENTAGE);
this.thresholdCPUPercentage
= node.getProperties().getInteger(GroupProperty.HEALTH_MONITORING_THRESHOLD_CPU_PERCENTAGE);
this.monitorThread = initMonitorThread();
this.healthMetrics = new HealthMetrics();
}
private HealthMonitorThread initMonitorThread() {
if (monitorLevel == OFF) {
return null;
}
int delaySeconds = node.getProperties().getSeconds(GroupProperty.HEALTH_MONITORING_DELAY_SECONDS);
return new HealthMonitorThread(delaySeconds);
}
public HealthMonitor start() {
if (monitorLevel == OFF) {
logger.finest("HealthMonitor is disabled");
return this;
}
monitorThread.start();
logger.finest("HealthMonitor started");
return this;
}
private HealthMonitorLevel getHealthMonitorLevel() {
String healthMonitorLevel = node.getProperties().getString(GroupProperty.HEALTH_MONITORING_LEVEL);
return valueOf(healthMonitorLevel);
}
private final class HealthMonitorThread extends Thread {
private final int delaySeconds;
private boolean performanceLogHint;
private HealthMonitorThread(int delaySeconds) {
super(node.getHazelcastThreadGroup().getInternalThreadGroup(),
node.getHazelcastThreadGroup().getThreadNamePrefix("HealthMonitor"));
setDaemon(true);
this.delaySeconds = delaySeconds;
this.performanceLogHint = node.getProperties().getBoolean(Diagnostics.ENABLED);
}
@Override
public void run() {
try {
while (node.getState() == NodeState.ACTIVE) {
healthMetrics.update();
switch (monitorLevel) {
case NOISY:
if (healthMetrics.exceedsThreshold()) {
logDiagnosticsHint();
}
logger.log(Level.INFO, healthMetrics.render());
break;
case SILENT:
if (healthMetrics.exceedsThreshold()) {
logDiagnosticsHint();
logger.log(Level.INFO, healthMetrics.render());
}
break;
default:
throw new IllegalStateException("unrecognized HealthMonitorLevel:" + monitorLevel);
}
try {
SECONDS.sleep(delaySeconds);
} catch (InterruptedException e) {
return;
}
}
} catch (OutOfMemoryError e) {
OutOfMemoryErrorDispatcher.onOutOfMemory(e);
} catch (Throwable t) {
logger.warning("Health Monitor failed", t);
}
}
private void logDiagnosticsHint() {
if (!performanceLogHint) {
return;
}
// we only log the hint once
performanceLogHint = false;
logger.info(String.format("The HealthMonitor has detected a high load on the system. For more detailed information,%s"
+ "enable the Diagnostics by adding the property -D%s=true",
LINE_SEPARATOR, Diagnostics.ENABLED));
}
}
class HealthMetrics {
final LongGauge clientEndpointCount
= metricRegistry.newLongGauge("client.endpoint.count");
final LongGauge clusterTimeDiff
= metricRegistry.newLongGauge("cluster.clock.clusterTimeDiff");
final LongGauge executorAsyncQueueSize
= metricRegistry.newLongGauge("executor.hz:async.queueSize");
final LongGauge executorClientQueueSize
= metricRegistry.newLongGauge("executor.hz:client.queueSize");
final LongGauge executorClusterQueueSize
= metricRegistry.newLongGauge("executor.hz:cluster.queueSize");
final LongGauge executorScheduledQueueSize
= metricRegistry.newLongGauge("executor.hz:scheduled.queueSize");
final LongGauge executorSystemQueueSize
= metricRegistry.newLongGauge("executor.hz:system.queueSize");
final LongGauge executorIoQueueSize
= metricRegistry.newLongGauge("executor.hz:io.queueSize");
final LongGauge executorQueryQueueSize
= metricRegistry.newLongGauge("executor.hz:query.queueSize");
final LongGauge executorMapLoadQueueSize
= metricRegistry.newLongGauge("executor.hz:map-load.queueSize");
final LongGauge executorMapLoadAllKeysQueueSize
= metricRegistry.newLongGauge("executor.hz:map-loadAllKeys.queueSize");
final LongGauge eventQueueSize
= metricRegistry.newLongGauge("event.eventQueueSize");
final LongGauge gcMinorCount
= metricRegistry.newLongGauge("gc.minorCount");
final LongGauge gcMinorTime
= metricRegistry.newLongGauge("gc.minorTime");
final LongGauge gcMajorCount
= metricRegistry.newLongGauge("gc.majorCount");
final LongGauge gcMajorTime
= metricRegistry.newLongGauge("gc.majorTime");
final LongGauge gcUnknownCount
= metricRegistry.newLongGauge("gc.unknownCount");
final LongGauge gcUnknownTime
= metricRegistry.newLongGauge("gc.unknownTime");
final LongGauge runtimeAvailableProcessors
= metricRegistry.newLongGauge("runtime.availableProcessors");
final LongGauge runtimeMaxMemory
= metricRegistry.newLongGauge("runtime.maxMemory");
final LongGauge runtimeFreeMemory
= metricRegistry.newLongGauge("runtime.freeMemory");
final LongGauge runtimeTotalMemory
= metricRegistry.newLongGauge("runtime.totalMemory");
final LongGauge runtimeUsedMemory
= metricRegistry.newLongGauge("runtime.usedMemory");
final LongGauge threadPeakThreadCount
= metricRegistry.newLongGauge("thread.peakThreadCount");
final LongGauge threadThreadCount
= metricRegistry.newLongGauge("thread.threadCount");
final DoubleGauge osProcessCpuLoad
= metricRegistry.newDoubleGauge("os.processCpuLoad");
final DoubleGauge osSystemLoadAverage
= metricRegistry.newDoubleGauge("os.systemLoadAverage");
final DoubleGauge osSystemCpuLoad
= metricRegistry.newDoubleGauge("os.systemCpuLoad");
final LongGauge osTotalPhysicalMemorySize
= metricRegistry.newLongGauge("os.totalPhysicalMemorySize");
final LongGauge osFreePhysicalMemorySize
= metricRegistry.newLongGauge("os.freePhysicalMemorySize");
final LongGauge osTotalSwapSpaceSize
= metricRegistry.newLongGauge("os.totalSwapSpaceSize");
final LongGauge osFreeSwapSpaceSize
= metricRegistry.newLongGauge("os.freeSwapSpaceSize");
final LongGauge operationServiceExecutorQueueSize
= metricRegistry.newLongGauge("operation.queueSize");
final LongGauge operationServiceExecutorPriorityQueueSize
= metricRegistry.newLongGauge("operation.priorityQueueSize");
final LongGauge operationServiceResponseQueueSize
= metricRegistry.newLongGauge("operation.responseQueueSize");
final LongGauge operationServiceRunningOperationsCount
= metricRegistry.newLongGauge("operation.runningCount");
final LongGauge operationServiceCompletedOperationsCount
= metricRegistry.newLongGauge("operation.completedCount");
final LongGauge operationServicePendingInvocationsCount
= metricRegistry.newLongGauge("operation.invocations.pending");
final DoubleGauge operationServicePendingInvocationsPercentage
= metricRegistry.newDoubleGauge("operation.invocations.used");
final LongGauge proxyCount
= metricRegistry.newLongGauge("proxy.proxyCount");
final LongGauge tcpConnectionActiveCount
= metricRegistry.newLongGauge("tcp.connection.activeCount");
final LongGauge tcpConnectionCount
= metricRegistry.newLongGauge("tcp.connection.count");
final LongGauge tcpConnectionClientCount
= metricRegistry.newLongGauge("tcp.connection.clientCount");
private final StringBuilder sb = new StringBuilder();
private double memoryUsedOfTotalPercentage;
private double memoryUsedOfMaxPercentage;
public void update() {
memoryUsedOfTotalPercentage = (PERCENTAGE_MULTIPLIER * runtimeUsedMemory.read()) / runtimeTotalMemory.read();
memoryUsedOfMaxPercentage = (PERCENTAGE_MULTIPLIER * runtimeUsedMemory.read()) / runtimeMaxMemory.read();
}
boolean exceedsThreshold() {
if (memoryUsedOfMaxPercentage > thresholdMemoryPercentage) {
return true;
}
if (osProcessCpuLoad.read() > thresholdCPUPercentage) {
return true;
}
if (osSystemCpuLoad.read() > thresholdCPUPercentage) {
return true;
}
if (operationServicePendingInvocationsPercentage.read() > THRESHOLD_PERCENTAGE_INVOCATIONS) {
return true;
}
if (operationServicePendingInvocationsCount.read() > THRESHOLD_INVOCATIONS) {
return true;
}
return false;
}
public String render() {
update();
sb.setLength(0);
renderProcessors();
renderPhysicalMemory();
renderSwap();
renderHeap();
renderNativeMemory();
renderGc();
renderLoad();
renderThread();
renderCluster();
renderEvents();
renderExecutors();
renderOperationService();
renderProxy();
renderClient();
renderConnection();
return sb.toString();
}
private void renderConnection() {
sb.append("connection.active.count=")
.append(tcpConnectionActiveCount.read()).append(", ");
sb.append("client.connection.count=")
.append(tcpConnectionClientCount.read()).append(", ");
sb.append("connection.count=")
.append(tcpConnectionCount.read());
}
private void renderClient() {
sb.append("clientEndpoint.count=")
.append(clientEndpointCount.read()).append(", ");
}
private void renderProxy() {
sb.append("proxy.count=")
.append(proxyCount.read()).append(", ");
}
private void renderLoad() {
sb.append("load.process").append('=')
.append(format("%.2f", osProcessCpuLoad.read())).append("%, ");
sb.append("load.system").append('=')
.append(format("%.2f", osSystemCpuLoad.read())).append("%, ");
double value = osSystemLoadAverage.read();
if (value < 0) {
sb.append("load.systemAverage").append("=n/a ");
} else {
sb.append("load.systemAverage").append('=')
.append(format("%.2f", osSystemLoadAverage.read())).append("%, ");
}
}
private void renderProcessors() {
sb.append("processors=")
.append(runtimeAvailableProcessors.read()).append(", ");
}
private void renderPhysicalMemory() {
sb.append("physical.memory.total=")
.append(numberToUnit(osTotalPhysicalMemorySize.read())).append(", ");
sb.append("physical.memory.free=")
.append(numberToUnit(osFreePhysicalMemorySize.read())).append(", ");
}
private void renderSwap() {
sb.append("swap.space.total=")
.append(numberToUnit(osTotalSwapSpaceSize.read())).append(", ");
sb.append("swap.space.free=")
.append(numberToUnit(osFreeSwapSpaceSize.read())).append(", ");
}
private void renderHeap() {
sb.append("heap.memory.used=")
.append(numberToUnit(runtimeUsedMemory.read())).append(", ");
sb.append("heap.memory.free=")
.append(numberToUnit(runtimeFreeMemory.read())).append(", ");
sb.append("heap.memory.total=")
.append(numberToUnit(runtimeTotalMemory.read())).append(", ");
sb.append("heap.memory.max=")
.append(numberToUnit(runtimeMaxMemory.read())).append(", ");
sb.append("heap.memory.used/total=")
.append(percentageString(memoryUsedOfTotalPercentage)).append(", ");
sb.append("heap.memory.used/max=")
.append(percentageString(memoryUsedOfMaxPercentage)).append((", "));
}
private void renderEvents() {
sb.append("event.q.size=")
.append(eventQueueSize.read()).append(", ");
}
private void renderCluster() {
sb.append("cluster.timeDiff=")
.append(clusterTimeDiff.read()).append(", ");
}
private void renderThread() {
sb.append("thread.count=")
.append(threadThreadCount.read()).append(", ");
sb.append("thread.peakCount=")
.append(threadPeakThreadCount.read()).append(", ");
}
private void renderGc() {
sb.append("minor.gc.count=")
.append(gcMinorCount.read()).append(", ");
sb.append("minor.gc.time=")
.append(gcMinorTime.read()).append("ms, ");
sb.append("major.gc.count=")
.append(gcMajorCount.read()).append(", ");
sb.append("major.gc.time=")
.append(gcMajorTime.read()).append("ms, ");
if (gcUnknownCount.read() > 0) {
sb.append("unknown.gc.count=")
.append(gcUnknownCount.read()).append(", ");
sb.append("unknown.gc.time=")
.append(gcUnknownTime.read()).append("ms, ");
}
}
private void renderNativeMemory() {
MemoryStats memoryStats = node.getNodeExtension().getMemoryStats();
if (memoryStats.getMaxNative() <= 0L) {
return;
}
final long usedNative = memoryStats.getUsedNative();
sb.append("native.memory.used=")
.append(numberToUnit(usedNative)).append(", ");
sb.append("native.memory.free=")
.append(numberToUnit(memoryStats.getFreeNative())).append(", ");
sb.append("native.memory.total=")
.append(numberToUnit(memoryStats.getCommittedNative())).append(", ");
sb.append("native.memory.max=")
.append(numberToUnit(memoryStats.getMaxNative())).append(", ");
final long maxMeta = memoryStats.getMaxMetadata();
if (maxMeta > 0) {
final long usedMeta = memoryStats.getUsedMetadata();
sb.append("native.meta.memory.used=")
.append(numberToUnit(usedMeta)).append(", ");
sb.append("native.meta.memory.free=")
.append(numberToUnit(maxMeta - usedMeta)).append(", ");
sb.append("native.meta.memory.percentage=")
.append(percentageString(PERCENTAGE_MULTIPLIER * usedMeta / (usedNative + usedMeta))).append(", ");
}
}
private void renderExecutors() {
sb.append("executor.q.async.size=")
.append(executorAsyncQueueSize.read()).append(", ");
sb.append("executor.q.client.size=")
.append(executorClientQueueSize.read()).append(", ");
sb.append("executor.q.query.size=")
.append(executorQueryQueueSize.read()).append(", ");
sb.append("executor.q.scheduled.size=")
.append(executorScheduledQueueSize.read()).append(", ");
sb.append("executor.q.io.size=")
.append(executorIoQueueSize.read()).append(", ");
sb.append("executor.q.system.size=")
.append(executorSystemQueueSize.read()).append(", ");
sb.append("executor.q.operations.size=")
.append(operationServiceExecutorQueueSize.read()).append(", ");
sb.append("executor.q.priorityOperation.size=").
append(operationServiceExecutorPriorityQueueSize.read()).append(", ");
sb.append("operations.completed.count=")
.append(operationServiceCompletedOperationsCount.read()).append(", ");
sb.append("executor.q.mapLoad.size=")
.append(executorMapLoadQueueSize.read()).append(", ");
sb.append("executor.q.mapLoadAllKeys.size=")
.append(executorMapLoadAllKeysQueueSize.read()).append(", ");
sb.append("executor.q.cluster.size=")
.append(executorClusterQueueSize.read()).append(", ");
}
private void renderOperationService() {
sb.append("executor.q.response.size=")
.append(operationServiceResponseQueueSize.read()).append(", ");
sb.append("operations.running.count=")
.append(operationServiceRunningOperationsCount.read()).append(", ");
sb.append("operations.pending.invocations.percentage=")
.append(format("%.2f", operationServicePendingInvocationsPercentage.read())).append("%, ");
sb.append("operations.pending.invocations.count=")
.append(operationServicePendingInvocationsCount.read()).append(", ");
}
}
/**
* Given a number, returns that number as a percentage string.
*
* @param p the given number
* @return a string of the given number as a format float with two decimal places and a period
*/
private static String percentageString(double p) {
return format("%.2f%%", p);
}
@SuppressWarnings("checkstyle:magicnumber")
private static String numberToUnit(long number) {
for (int i = 6; i > 0; i--) {
// 1024 is for 1024 kb is 1 MB etc
double step = Math.pow(1024, i);
if (number > step) {
return format("%3.1f%s", number / step, UNITS[i]);
}
}
return Long.toString(number);
}
}
|
hazelcast/src/main/java/com/hazelcast/internal/diagnostics/HealthMonitor.java
|
/*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.diagnostics;
import com.hazelcast.instance.Node;
import com.hazelcast.instance.NodeState;
import com.hazelcast.instance.OutOfMemoryErrorDispatcher;
import com.hazelcast.internal.metrics.DoubleGauge;
import com.hazelcast.internal.metrics.LongGauge;
import com.hazelcast.internal.metrics.MetricsRegistry;
import com.hazelcast.logging.ILogger;
import com.hazelcast.memory.MemoryStats;
import com.hazelcast.spi.properties.GroupProperty;
import java.util.logging.Level;
import static com.hazelcast.internal.diagnostics.HealthMonitorLevel.OFF;
import static com.hazelcast.internal.diagnostics.HealthMonitorLevel.valueOf;
import static com.hazelcast.util.StringUtil.LINE_SEPARATOR;
import static java.lang.String.format;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* Health monitor periodically prints logs about related internal metrics using the {@link MetricsRegistry}
* to provide some clues about the internal Hazelcast state.
* <p/>
* Health monitor can be configured with system properties.
* <p/>
* {@link GroupProperty#HEALTH_MONITORING_LEVEL}
* This property can be one of the following:
* {@link HealthMonitorLevel#NOISY} => does not check threshold, always prints.
* {@link HealthMonitorLevel#SILENT} => prints only if metrics are above threshold (default).
* {@link HealthMonitorLevel#OFF} => does not print anything.
* <p/>
* {@link GroupProperty#HEALTH_MONITORING_DELAY_SECONDS}
* Time between printing two logs of health monitor. Default values is 30 seconds.
* <p/>
* {@link GroupProperty#HEALTH_MONITORING_THRESHOLD_MEMORY_PERCENTAGE}
* Threshold: Percentage of max memory currently in use
* <p/>
* {@link GroupProperty#HEALTH_MONITORING_THRESHOLD_CPU_PERCENTAGE}
* Threshold: CPU system/process load
*/
public class HealthMonitor {
private static final String[] UNITS = new String[]{"", "K", "M", "G", "T", "P", "E"};
private static final double PERCENTAGE_MULTIPLIER = 100d;
private static final double THRESHOLD_PERCENTAGE_INVOCATIONS = 70;
private static final double THRESHOLD_INVOCATIONS = 1000;
final HealthMetrics healthMetrics;
private final ILogger logger;
private final Node node;
private final HealthMonitorLevel monitorLevel;
private final int thresholdMemoryPercentage;
private final int thresholdCPUPercentage;
private final MetricsRegistry metricRegistry;
private final HealthMonitorThread monitorThread;
public HealthMonitor(Node node) {
this.node = node;
this.logger = node.getLogger(HealthMonitor.class);
this.metricRegistry = node.nodeEngine.getMetricsRegistry();
this.monitorLevel = getHealthMonitorLevel();
this.thresholdMemoryPercentage
= node.getProperties().getInteger(GroupProperty.HEALTH_MONITORING_THRESHOLD_MEMORY_PERCENTAGE);
this.thresholdCPUPercentage
= node.getProperties().getInteger(GroupProperty.HEALTH_MONITORING_THRESHOLD_CPU_PERCENTAGE);
this.monitorThread = initMonitorThread();
this.healthMetrics = new HealthMetrics();
}
private HealthMonitorThread initMonitorThread() {
if (monitorLevel == OFF) {
return null;
}
int delaySeconds = node.getProperties().getSeconds(GroupProperty.HEALTH_MONITORING_DELAY_SECONDS);
return new HealthMonitorThread(delaySeconds);
}
public HealthMonitor start() {
if (monitorLevel == OFF) {
logger.finest("HealthMonitor is disabled");
return this;
}
monitorThread.start();
logger.finest("HealthMonitor started");
return this;
}
private HealthMonitorLevel getHealthMonitorLevel() {
String healthMonitorLevel = node.getProperties().getString(GroupProperty.HEALTH_MONITORING_LEVEL);
return valueOf(healthMonitorLevel);
}
private final class HealthMonitorThread extends Thread {
private final int delaySeconds;
private boolean performanceLogHint;
private HealthMonitorThread(int delaySeconds) {
super(node.getHazelcastThreadGroup().getInternalThreadGroup(),
node.getHazelcastThreadGroup().getThreadNamePrefix("HealthMonitor"));
setDaemon(true);
this.delaySeconds = delaySeconds;
this.performanceLogHint = node.getProperties().getBoolean(Diagnostics.ENABLED);
}
@Override
public void run() {
try {
while (node.getState() == NodeState.ACTIVE) {
switch (monitorLevel) {
case NOISY:
if (healthMetrics.exceedsThreshold()) {
logDiagnosticsHint();
}
logger.log(Level.INFO, healthMetrics.render());
break;
case SILENT:
if (healthMetrics.exceedsThreshold()) {
logDiagnosticsHint();
logger.log(Level.INFO, healthMetrics.render());
}
break;
default:
throw new IllegalStateException("unrecognized HealthMonitorLevel:" + monitorLevel);
}
try {
SECONDS.sleep(delaySeconds);
} catch (InterruptedException e) {
return;
}
}
} catch (OutOfMemoryError e) {
OutOfMemoryErrorDispatcher.onOutOfMemory(e);
} catch (Throwable t) {
logger.warning("Health Monitor failed", t);
}
}
private void logDiagnosticsHint() {
if (!performanceLogHint) {
return;
}
// we only log the hint once
performanceLogHint = false;
logger.info(String.format("The HealthMonitor has detected a high load on the system. For more detailed information,%s"
+ "enable the Diagnostics by adding the property -D%s=true",
LINE_SEPARATOR, Diagnostics.ENABLED));
}
}
class HealthMetrics {
final LongGauge clientEndpointCount
= metricRegistry.newLongGauge("client.endpoint.count");
final LongGauge clusterTimeDiff
= metricRegistry.newLongGauge("cluster.clock.clusterTimeDiff");
final LongGauge executorAsyncQueueSize
= metricRegistry.newLongGauge("executor.hz:async.queueSize");
final LongGauge executorClientQueueSize
= metricRegistry.newLongGauge("executor.hz:client.queueSize");
final LongGauge executorClusterQueueSize
= metricRegistry.newLongGauge("executor.hz:cluster.queueSize");
final LongGauge executorScheduledQueueSize
= metricRegistry.newLongGauge("executor.hz:scheduled.queueSize");
final LongGauge executorSystemQueueSize
= metricRegistry.newLongGauge("executor.hz:system.queueSize");
final LongGauge executorIoQueueSize
= metricRegistry.newLongGauge("executor.hz:io.queueSize");
final LongGauge executorQueryQueueSize
= metricRegistry.newLongGauge("executor.hz:query.queueSize");
final LongGauge executorMapLoadQueueSize
= metricRegistry.newLongGauge("executor.hz:map-load.queueSize");
final LongGauge executorMapLoadAllKeysQueueSize
= metricRegistry.newLongGauge("executor.hz:map-loadAllKeys.queueSize");
final LongGauge eventQueueSize
= metricRegistry.newLongGauge("event.eventQueueSize");
final LongGauge gcMinorCount
= metricRegistry.newLongGauge("gc.minorCount");
final LongGauge gcMinorTime
= metricRegistry.newLongGauge("gc.minorTime");
final LongGauge gcMajorCount
= metricRegistry.newLongGauge("gc.majorCount");
final LongGauge gcMajorTime
= metricRegistry.newLongGauge("gc.majorTime");
final LongGauge gcUnknownCount
= metricRegistry.newLongGauge("gc.unknownCount");
final LongGauge gcUnknownTime
= metricRegistry.newLongGauge("gc.unknownTime");
final LongGauge runtimeAvailableProcessors
= metricRegistry.newLongGauge("runtime.availableProcessors");
final LongGauge runtimeMaxMemory
= metricRegistry.newLongGauge("runtime.maxMemory");
final LongGauge runtimeFreeMemory
= metricRegistry.newLongGauge("runtime.freeMemory");
final LongGauge runtimeAvailableMemory
= metricRegistry.newLongGauge("runtime.availableMemory");
final LongGauge runtimeTotalMemory
= metricRegistry.newLongGauge("runtime.totalMemory");
final LongGauge runtimeUsedMemory
= metricRegistry.newLongGauge("runtime.usedMemory");
final LongGauge threadPeakThreadCount
= metricRegistry.newLongGauge("thread.peakThreadCount");
final LongGauge threadThreadCount
= metricRegistry.newLongGauge("thread.threadCount");
final DoubleGauge osProcessCpuLoad
= metricRegistry.newDoubleGauge("os.processCpuLoad");
final DoubleGauge osSystemLoadAverage
= metricRegistry.newDoubleGauge("os.systemLoadAverage");
final DoubleGauge osSystemCpuLoad
= metricRegistry.newDoubleGauge("os.systemCpuLoad");
final LongGauge osTotalPhysicalMemorySize
= metricRegistry.newLongGauge("os.totalPhysicalMemorySize");
final LongGauge osFreePhysicalMemorySize
= metricRegistry.newLongGauge("os.freePhysicalMemorySize");
final LongGauge osTotalSwapSpaceSize
= metricRegistry.newLongGauge("os.totalSwapSpaceSize");
final LongGauge osFreeSwapSpaceSize
= metricRegistry.newLongGauge("os.freeSwapSpaceSize");
final LongGauge operationServiceExecutorQueueSize
= metricRegistry.newLongGauge("operation.queueSize");
final LongGauge operationServiceExecutorPriorityQueueSize
= metricRegistry.newLongGauge("operation.priorityQueueSize");
final LongGauge operationServiceResponseQueueSize
= metricRegistry.newLongGauge("operation.responseQueueSize");
final LongGauge operationServiceRunningOperationsCount
= metricRegistry.newLongGauge("operation.runningCount");
final LongGauge operationServiceCompletedOperationsCount
= metricRegistry.newLongGauge("operation.completedCount");
final LongGauge operationServicePendingInvocationsCount
= metricRegistry.newLongGauge("operation.invocations.pending");
final DoubleGauge operationServicePendingInvocationsPercentage
= metricRegistry.newDoubleGauge("operation.invocations.used");
final LongGauge proxyCount
= metricRegistry.newLongGauge("proxy.proxyCount");
final LongGauge tcpConnectionActiveCount
= metricRegistry.newLongGauge("tcp.connection.activeCount");
final LongGauge tcpConnectionCount
= metricRegistry.newLongGauge("tcp.connection.count");
final LongGauge tcpConnectionClientCount
= metricRegistry.newLongGauge("tcp.connection.clientCount");
private final StringBuilder sb = new StringBuilder();
private double memoryUsedOfTotalPercentage;
private double memoryUsedOfMaxPercentage;
public void update() {
memoryUsedOfTotalPercentage = PERCENTAGE_MULTIPLIER * runtimeUsedMemory.read() / runtimeTotalMemory.read();
memoryUsedOfMaxPercentage = PERCENTAGE_MULTIPLIER * runtimeUsedMemory.read() / runtimeMaxMemory.read();
}
boolean exceedsThreshold() {
if (memoryUsedOfMaxPercentage > thresholdMemoryPercentage) {
return true;
}
if (osProcessCpuLoad.read() > thresholdCPUPercentage) {
return true;
}
if (osSystemCpuLoad.read() > thresholdCPUPercentage) {
return true;
}
if (operationServicePendingInvocationsPercentage.read() > THRESHOLD_PERCENTAGE_INVOCATIONS) {
return true;
}
if (operationServicePendingInvocationsCount.read() > THRESHOLD_INVOCATIONS) {
return true;
}
return false;
}
public String render() {
sb.setLength(0);
renderProcessors();
renderPhysicalMemory();
renderSwap();
renderHeap();
renderNativeMemory();
renderGc();
renderLoad();
renderThread();
renderCluster();
renderEvents();
renderExecutors();
renderOperationService();
renderProxy();
renderClient();
renderConnection();
return sb.toString();
}
private void renderConnection() {
sb.append("connection.active.count=")
.append(tcpConnectionActiveCount.read()).append(", ");
sb.append("client.connection.count=")
.append(tcpConnectionClientCount.read()).append(", ");
sb.append("connection.count=")
.append(tcpConnectionCount.read());
}
private void renderClient() {
sb.append("clientEndpoint.count=")
.append(clientEndpointCount.read()).append(", ");
}
private void renderProxy() {
sb.append("proxy.count=")
.append(proxyCount.read()).append(", ");
}
private void renderLoad() {
sb.append("load.process").append('=')
.append(format("%.2f", osProcessCpuLoad.read())).append("%, ");
sb.append("load.system").append('=')
.append(format("%.2f", osSystemCpuLoad.read())).append("%, ");
double value = osSystemLoadAverage.read();
if (value < 0) {
sb.append("load.systemAverage").append("=n/a ");
} else {
sb.append("load.systemAverage").append('=')
.append(format("%.2f", osSystemLoadAverage.read())).append("%, ");
}
}
private void renderProcessors() {
sb.append("processors=")
.append(runtimeAvailableProcessors.read()).append(", ");
}
private void renderPhysicalMemory() {
sb.append("physical.memory.total=")
.append(numberToUnit(osTotalPhysicalMemorySize.read())).append(", ");
sb.append("physical.memory.free=")
.append(numberToUnit(osFreePhysicalMemorySize.read())).append(", ");
}
private void renderSwap() {
sb.append("swap.space.total=")
.append(numberToUnit(osTotalSwapSpaceSize.read())).append(", ");
sb.append("swap.space.free=")
.append(numberToUnit(osFreeSwapSpaceSize.read())).append(", ");
}
private void renderHeap() {
sb.append("heap.memory.used=")
.append(numberToUnit(runtimeUsedMemory.read())).append(", ");
sb.append("heap.memory.free=")
.append(numberToUnit(runtimeFreeMemory.read())).append(", ");
sb.append("heap.memory.available=")
.append(numberToUnit(runtimeAvailableMemory.read())).append(", ");
sb.append("heap.memory.total=")
.append(numberToUnit(runtimeTotalMemory.read())).append(", ");
sb.append("heap.memory.max=")
.append(numberToUnit(runtimeMaxMemory.read())).append(", ");
sb.append("heap.memory.used/total=")
.append(percentageString(memoryUsedOfTotalPercentage)).append(", ");
sb.append("heap.memory.used/max=")
.append(percentageString(memoryUsedOfMaxPercentage)).append((", "));
}
private void renderEvents() {
sb.append("event.q.size=")
.append(eventQueueSize.read()).append(", ");
}
private void renderCluster() {
sb.append("cluster.timeDiff=")
.append(clusterTimeDiff.read()).append(", ");
}
private void renderThread() {
sb.append("thread.count=")
.append(threadThreadCount.read()).append(", ");
sb.append("thread.peakCount=")
.append(threadPeakThreadCount.read()).append(", ");
}
private void renderGc() {
sb.append("minor.gc.count=")
.append(gcMinorCount.read()).append(", ");
sb.append("minor.gc.time=")
.append(gcMinorTime.read()).append("ms, ");
sb.append("major.gc.count=")
.append(gcMajorCount.read()).append(", ");
sb.append("major.gc.time=")
.append(gcMajorTime.read()).append("ms, ");
if (gcUnknownCount.read() > 0) {
sb.append("unknown.gc.count=")
.append(gcUnknownCount.read()).append(", ");
sb.append("unknown.gc.time=")
.append(gcUnknownTime.read()).append("ms, ");
}
}
private void renderNativeMemory() {
MemoryStats memoryStats = node.getNodeExtension().getMemoryStats();
if (memoryStats.getMaxNative() <= 0L) {
return;
}
final long usedNative = memoryStats.getUsedNative();
sb.append("native.memory.used=")
.append(numberToUnit(usedNative)).append(", ");
sb.append("native.memory.free=")
.append(numberToUnit(memoryStats.getFreeNative())).append(", ");
sb.append("native.memory.total=")
.append(numberToUnit(memoryStats.getCommittedNative())).append(", ");
sb.append("native.memory.max=")
.append(numberToUnit(memoryStats.getMaxNative())).append(", ");
final long maxMeta = memoryStats.getMaxMetadata();
if (maxMeta > 0) {
final long usedMeta = memoryStats.getUsedMetadata();
sb.append("native.meta.memory.used=")
.append(numberToUnit(usedMeta)).append(", ");
sb.append("native.meta.memory.free=")
.append(numberToUnit(maxMeta - usedMeta)).append(", ");
sb.append("native.meta.memory.percentage=")
.append(percentageString(PERCENTAGE_MULTIPLIER * usedMeta / (usedNative + usedMeta))).append(", ");
}
}
private void renderExecutors() {
sb.append("executor.q.async.size=")
.append(executorAsyncQueueSize.read()).append(", ");
sb.append("executor.q.client.size=")
.append(executorClientQueueSize.read()).append(", ");
sb.append("executor.q.query.size=")
.append(executorQueryQueueSize.read()).append(", ");
sb.append("executor.q.scheduled.size=")
.append(executorScheduledQueueSize.read()).append(", ");
sb.append("executor.q.io.size=")
.append(executorIoQueueSize.read()).append(", ");
sb.append("executor.q.system.size=")
.append(executorSystemQueueSize.read()).append(", ");
sb.append("executor.q.operations.size=")
.append(operationServiceExecutorQueueSize.read()).append(", ");
sb.append("executor.q.priorityOperation.size=").
append(operationServiceExecutorPriorityQueueSize.read()).append(", ");
sb.append("operations.completed.count=")
.append(operationServiceCompletedOperationsCount.read()).append(", ");
sb.append("executor.q.mapLoad.size=")
.append(executorMapLoadQueueSize.read()).append(", ");
sb.append("executor.q.mapLoadAllKeys.size=")
.append(executorMapLoadAllKeysQueueSize.read()).append(", ");
sb.append("executor.q.cluster.size=")
.append(executorClusterQueueSize.read()).append(", ");
}
private void renderOperationService() {
sb.append("executor.q.response.size=")
.append(operationServiceResponseQueueSize.read()).append(", ");
sb.append("operations.running.count=")
.append(operationServiceRunningOperationsCount.read()).append(", ");
sb.append("operations.pending.invocations.percentage=")
.append(format("%.2f", operationServicePendingInvocationsPercentage.read())).append("%, ");
sb.append("operations.pending.invocations.count=")
.append(operationServicePendingInvocationsCount.read()).append(", ");
}
}
/**
* Given a number, returns that number as a percentage string.
*
* @param p the given number
* @return a string of the given number as a format float with two decimal places and a period
*/
private static String percentageString(double p) {
return format("%.2f%%", p);
}
@SuppressWarnings("checkstyle:magicnumber")
private static String numberToUnit(long number) {
for (int i = 6; i > 0; i--) {
// 1024 is for 1024 kb is 1 MB etc
double step = Math.pow(1024, i);
if (number > step) {
return format("%3.1f%s", number / step, UNITS[i]);
}
}
return Long.toString(number);
}
}
|
Resolves some memory display fixes in health monitor.
availableMemory is not a probe + was not part of health monitor
Some fields in the healthmonitor.metrics were not updated correctly.
|
hazelcast/src/main/java/com/hazelcast/internal/diagnostics/HealthMonitor.java
|
Resolves some memory display fixes in health monitor.
|
<ide><path>azelcast/src/main/java/com/hazelcast/internal/diagnostics/HealthMonitor.java
<ide> public void run() {
<ide> try {
<ide> while (node.getState() == NodeState.ACTIVE) {
<add> healthMetrics.update();
<add>
<ide> switch (monitorLevel) {
<ide> case NOISY:
<ide> if (healthMetrics.exceedsThreshold()) {
<ide> = metricRegistry.newLongGauge("runtime.maxMemory");
<ide> final LongGauge runtimeFreeMemory
<ide> = metricRegistry.newLongGauge("runtime.freeMemory");
<del> final LongGauge runtimeAvailableMemory
<del> = metricRegistry.newLongGauge("runtime.availableMemory");
<ide> final LongGauge runtimeTotalMemory
<ide> = metricRegistry.newLongGauge("runtime.totalMemory");
<ide> final LongGauge runtimeUsedMemory
<ide> private double memoryUsedOfMaxPercentage;
<ide>
<ide> public void update() {
<del> memoryUsedOfTotalPercentage = PERCENTAGE_MULTIPLIER * runtimeUsedMemory.read() / runtimeTotalMemory.read();
<del> memoryUsedOfMaxPercentage = PERCENTAGE_MULTIPLIER * runtimeUsedMemory.read() / runtimeMaxMemory.read();
<add> memoryUsedOfTotalPercentage = (PERCENTAGE_MULTIPLIER * runtimeUsedMemory.read()) / runtimeTotalMemory.read();
<add> memoryUsedOfMaxPercentage = (PERCENTAGE_MULTIPLIER * runtimeUsedMemory.read()) / runtimeMaxMemory.read();
<ide> }
<ide>
<ide> boolean exceedsThreshold() {
<ide> }
<ide>
<ide> public String render() {
<add> update();
<ide> sb.setLength(0);
<ide> renderProcessors();
<ide> renderPhysicalMemory();
<ide> .append(numberToUnit(runtimeUsedMemory.read())).append(", ");
<ide> sb.append("heap.memory.free=")
<ide> .append(numberToUnit(runtimeFreeMemory.read())).append(", ");
<del> sb.append("heap.memory.available=")
<del> .append(numberToUnit(runtimeAvailableMemory.read())).append(", ");
<del> sb.append("heap.memory.total=")
<add> sb.append("heap.memory.total=")
<ide> .append(numberToUnit(runtimeTotalMemory.read())).append(", ");
<ide> sb.append("heap.memory.max=")
<ide> .append(numberToUnit(runtimeMaxMemory.read())).append(", ");
|
|
Java
|
apache-2.0
|
a4a79ce0f96bc1060c374ae6377dd49716bdabab
| 0 |
pruivo/JGroups,kedzie/JGroups,pferraro/JGroups,rhusar/JGroups,ligzy/JGroups,rvansa/JGroups,pruivo/JGroups,slaskawi/JGroups,dimbleby/JGroups,danberindei/JGroups,tristantarrant/JGroups,TarantulaTechnology/JGroups,rpelisse/JGroups,pferraro/JGroups,vjuranek/JGroups,deepnarsay/JGroups,rpelisse/JGroups,rpelisse/JGroups,vjuranek/JGroups,dimbleby/JGroups,kedzie/JGroups,pferraro/JGroups,danberindei/JGroups,ibrahimshbat/JGroups,ligzy/JGroups,slaskawi/JGroups,TarantulaTechnology/JGroups,slaskawi/JGroups,rvansa/JGroups,Sanne/JGroups,ibrahimshbat/JGroups,dimbleby/JGroups,deepnarsay/JGroups,TarantulaTechnology/JGroups,ligzy/JGroups,deepnarsay/JGroups,belaban/JGroups,kedzie/JGroups,vjuranek/JGroups,rhusar/JGroups,Sanne/JGroups,pruivo/JGroups,belaban/JGroups,tristantarrant/JGroups,ibrahimshbat/JGroups,rhusar/JGroups,danberindei/JGroups,Sanne/JGroups,ibrahimshbat/JGroups,belaban/JGroups
|
// $Id: JChannel.java,v 1.68 2006/05/03 08:18:01 belaban Exp $
package org.jgroups;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.conf.ConfiguratorFactory;
import org.jgroups.conf.ProtocolStackConfigurator;
import org.jgroups.stack.ProtocolStack;
import org.jgroups.stack.StateTransferInfo;
import org.jgroups.util.*;
import org.w3c.dom.Element;
import java.io.File;
import java.io.Serializable;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
/**
* JChannel is a pure Java implementation of Channel.
* When a JChannel object is instantiated it automatically sets up the
* protocol stack.
* <p>
* <B>Properties</B>
* <P>
* Properties are used to configure a channel, and are accepted in
* several forms; the String form is described here.
* A property string consists of a number of properties separated by
* colons. For example:
* <p>
* <pre>"<prop1>(arg1=val1):<prop2>(arg1=val1;arg2=val2):<prop3>:<propn>"</pre>
* <p>
* Each property relates directly to a protocol layer, which is
* implemented as a Java class. When a protocol stack is to be created
* based on the above property string, the first property becomes the
* bottom-most layer, the second one will be placed on the first, etc.:
* the stack is created from the bottom to the top, as the string is
* parsed from left to right. Each property has to be the name of a
* Java class that resides in the
* {@link org.jgroups.protocols} package.
* <p>
* Note that only the base name has to be given, not the fully specified
* class name (e.g., UDP instead of org.jgroups.protocols.UDP).
* <p>
* Each layer may have 0 or more arguments, which are specified as a
* list of name/value pairs in parentheses directly after the property.
* In the example above, the first protocol layer has 1 argument,
* the second 2, the third none. When a layer is created, these
* properties (if there are any) will be set in a layer by invoking
* the layer's setProperties() method
* <p>
* As an example the property string below instructs JGroups to create
* a JChannel with protocols UDP, PING, FD and GMS:<p>
* <pre>"UDP(mcast_addr=228.10.9.8;mcast_port=5678):PING:FD:GMS"</pre>
* <p>
* The UDP protocol layer is at the bottom of the stack, and it
* should use mcast address 228.10.9.8. and port 5678 rather than
* the default IP multicast address and port. The only other argument
* instructs FD to output debug information while executing.
* Property UDP refers to a class {@link org.jgroups.protocols.UDP},
* which is subsequently loaded and an instance of which is created as protocol layer.
* If any of these classes are not found, an exception will be thrown and
* the construction of the stack will be aborted.
*
* @author Bela Ban
* @version $Revision: 1.68 $
*/
public class JChannel extends Channel {
/**
* The default protocol stack used by the default constructor.
*/
public static final String DEFAULT_PROTOCOL_STACK=
"UDP(down_thread=false;mcast_send_buf_size=640000;mcast_port=45566;discard_incompatible_packets=true;" +
"ucast_recv_buf_size=20000000;mcast_addr=228.10.10.10;up_thread=false;loopback=false;" +
"mcast_recv_buf_size=25000000;max_bundle_size=64000;max_bundle_timeout=30;" +
"use_incoming_packet_handler=true;bind_addr=192.168.5.2;use_outgoing_packet_handler=false;" +
"ucast_send_buf_size=640000;tos=16;enable_bundling=true;ip_ttl=2):" +
"PING(timeout=2000;down_thread=false;num_initial_members=3;up_thread=false):" +
"MERGE2(max_interval=10000;down_thread=false;min_interval=5000;up_thread=false):" +
"FD(timeout=2000;max_tries=3;down_thread=false;up_thread=false):" +
"VERIFY_SUSPECT(timeout=1500;down_thread=false):" +
"pbcast.NAKACK(max_xmit_size=60000;down_thread=false;use_mcast_xmit=false;gc_lag=0;" +
"discard_delivered_msgs=true;up_thread=false;retransmit_timeout=100,200,300,600,1200,2400,4800):" +
"UNICAST(timeout=300,600,1200,2400,3600;down_thread=false;up_thread=false):" +
"pbcast.STABLE(stability_delay=1000;desired_avg_gossip=50000;max_bytes=400000;down_thread=false;" +
"up_thread=false):" +
"VIEW_SYNC(down_thread=false;avg_send_interval=60000;up_thread=false):" +
"pbcast.GMS(print_local_addr=true;join_timeout=3000;down_thread=false;" +
"join_retry_timeout=2000;up_thread=false;shun=true):" +
"FC(max_credits=2000000;down_thread=false;up_thread=false;min_threshold=0.10):" +
"FRAG2(frag_size=60000;down_thread=false;up_thread=false):" +
"pbcast.STATE_TRANSFER(down_thread=false;up_thread=false)";
static final String FORCE_PROPS="force.properties";
/* the protocol stack configuration string */
private String props=null;
/*the address of this JChannel instance*/
private Address local_addr=null;
/*the channel (also know as group) name*/
private String channel_name=null; // group name
/*the latest view of the group membership*/
private View my_view=null;
/*the queue that is used to receive messages (events) from the protocol stack*/
private final Queue mq=new Queue();
/*the protocol stack, used to send and receive messages from the protocol stack*/
private ProtocolStack prot_stack=null;
/** Thread responsible for closing a channel and potentially reconnecting to it (e.g., when shunned). */
protected CloserThread closer=null;
/** To wait until a local address has been assigned */
private final Promise local_addr_promise=new Promise();
/** To wait until we have connected successfully */
private final Promise connect_promise=new Promise();
/** To wait until we have been disconnected from the channel */
private final Promise disconnect_promise=new Promise();
private final Promise state_promise=new Promise();
/** wait until we have a non-null local_addr */
private long LOCAL_ADDR_TIMEOUT=30000; //=Long.parseLong(System.getProperty("local_addr.timeout", "30000"));
/*if the states is fetched automatically, this is the default timeout, 5 secs*/
private static final long GET_STATE_DEFAULT_TIMEOUT=5000;
/*flag to indicate whether to receive blocks, if this is set to true, receive_views is set to true*/
private boolean receive_blocks=false;
/*flag to indicate whether to receive local messages
*if this is set to false, the JChannel will not receive messages sent by itself*/
private boolean receive_local_msgs=true;
/*flag to indicate whether the channel will reconnect (reopen) when the exit message is received*/
private boolean auto_reconnect=false;
/*flag t indicate whether the state is supposed to be retrieved after the channel is reconnected
*setting this to true, automatically forces auto_reconnect to true*/
private boolean auto_getstate=false;
/*channel connected flag*/
protected boolean connected=false;
/*channel closed flag*/
protected boolean closed=false; // close() has been called, channel is unusable
/** True if a state transfer protocol is available, false otherwise */
private boolean state_transfer_supported=false; // set by CONFIG event from STATE_TRANSFER protocol
/** Used to maintain additional data across channel disconnects/reconnects. This is a kludge and will be remove
* as soon as JGroups supports logical addresses
*/
private byte[] additional_data=null;
protected final Log log=LogFactory.getLog(getClass());
/** Collect statistics */
protected boolean stats=true;
protected long sent_msgs=0, received_msgs=0, sent_bytes=0, received_bytes=0;
/** Used by subclass to create a JChannel without a protocol stack, don't use as application programmer */
protected JChannel(boolean no_op) {
;
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* specified by the <code>DEFAULT_PROTOCOL_STACK</code> member.
*
* @throws ChannelException if problems occur during the initialization of
* the protocol stack.
*/
public JChannel() throws ChannelException {
this(DEFAULT_PROTOCOL_STACK);
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration contained by the specified file.
*
* @param properties a file containing a JGroups XML protocol stack
* configuration.
*
* @throws ChannelException if problems occur during the configuration or
* initialization of the protocol stack.
*/
public JChannel(File properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration contained by the specified XML element.
*
* @param properties a XML element containing a JGroups XML protocol stack
* configuration.
*
* @throws ChannelException if problems occur during the configuration or
* initialization of the protocol stack.
*/
public JChannel(Element properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration indicated by the specified URL.
*
* @param properties a URL pointing to a JGroups XML protocol stack
* configuration.
*
* @throws ChannelException if problems occur during the configuration or
* initialization of the protocol stack.
*/
public JChannel(URL properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration based upon the specified properties parameter.
*
* @param properties an old style property string, a string representing a
* system resource containing a JGroups XML configuration,
* a string representing a URL pointing to a JGroups XML
* XML configuration, or a string representing a file name
* that contains a JGroups XML configuration.
*
* @throws ChannelException if problems occur during the configuration and
* initialization of the protocol stack.
*/
public JChannel(String properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration contained by the protocol stack configurator parameter.
* <p>
* All of the public constructors of this class eventually delegate to this
* method.
*
* @param configurator a protocol stack configurator containing a JGroups
* protocol stack configuration.
*
* @throws ChannelException if problems occur during the initialization of
* the protocol stack.
*/
protected JChannel(ProtocolStackConfigurator configurator) throws ChannelException {
props = configurator.getProtocolStackString();
/*create the new protocol stack*/
prot_stack=new ProtocolStack(this, props);
/* Setup protocol stack (create layers, queues between them */
try {
prot_stack.setup();
}
catch(Throwable e) {
throw new ChannelException("unable to setup the protocol stack", e);
}
}
/**
* Creates a new JChannel with the protocol stack as defined in the properties
* parameter. an example of this parameter is<BR>
* "UDP:PING:FD:STABLE:NAKACK:UNICAST:FRAG:FLUSH:GMS:VIEW_ENFORCER:STATE_TRANSFER:QUEUE"<BR>
* Other examples can be found in the ./conf directory<BR>
* @param properties the protocol stack setup; if null, the default protocol stack will be used.
* The properties can also be a java.net.URL object or a string that is a URL spec.
* The JChannel will validate any URL object and String object to see if they are a URL.
* In case of the parameter being a url, the JChannel will try to load the xml from there.
* In case properties is a org.w3c.dom.Element, the ConfiguratorFactory will parse the
* DOM tree with the element as its root element.
* @deprecated Use the constructors with specific parameter types instead.
*/
public JChannel(Object properties) throws ChannelException {
if (properties == null) {
properties = DEFAULT_PROTOCOL_STACK;
}
try {
ProtocolStackConfigurator c=ConfiguratorFactory.getStackConfigurator(properties);
props=c.getProtocolStackString();
}
catch(Exception x) {
throw new ChannelException("unable to load protocol stack", x);
}
/*create the new protocol stack*/
prot_stack=new ProtocolStack(this, props);
/* Setup protocol stack (create layers, queues between them */
try {
prot_stack.setup();
}
catch(Throwable e) {
throw new ChannelException("failed to setup protocol stack", e);
}
}
/**
* Returns the protocol stack.
* Currently used by Debugger.
* Specific to JChannel, therefore
* not visible in Channel
*/
public ProtocolStack getProtocolStack() {
return prot_stack;
}
protected Log getLog() {
return log;
}
/**
* returns the protocol stack configuration in string format.
* an example of this property is<BR>
* "UDP:PING:FD:STABLE:NAKACK:UNICAST:FRAG:FLUSH:GMS:VIEW_ENFORCER:STATE_TRANSFER:QUEUE"
*/
public String getProperties() {
return props;
}
public boolean statsEnabled() {
return stats;
}
public void enableStats(boolean stats) {
this.stats=stats;
}
public void resetStats() {
sent_msgs=received_msgs=sent_bytes=received_bytes=0;
}
public long getSentMessages() {return sent_msgs;}
public long getSentBytes() {return sent_bytes;}
public long getReceivedMessages() {return received_msgs;}
public long getReceivedBytes() {return received_bytes;}
public int getNumberOfTasksInTimer() {return prot_stack != null ? prot_stack.timer.size() : -1;}
public String dumpTimerQueue() {
return prot_stack != null? prot_stack.dumpTimerQueue() : "<n/a";
}
/**
* Returns a pretty-printed form of all the protocols. If include_properties is set,
* the properties for each protocol will also be printed.
*/
public String printProtocolSpec(boolean include_properties) {
return prot_stack != null ? prot_stack.printProtocolSpec(include_properties) : null;
}
/**
* Connects the channel to a group.
* If the channel is already connected, an error message will be printed to the error log.
* If the channel is closed a ChannelClosed exception will be thrown.
* This method starts the protocol stack by calling ProtocolStack.start,
* then it sends an Event.CONNECT event down the stack and waits to receive a CONNECT_OK event.
* Once the CONNECT_OK event arrives from the protocol stack, any channel listeners are notified
* and the channel is considered connected.
*
* @param channel_name A <code>String</code> denoting the group name. Cannot be null.
* @exception ChannelException The protocol stack cannot be started
* @exception ChannelClosedException The channel is closed and therefore cannot be used any longer.
* A new channel has to be created first.
*/
public synchronized void connect(String channel_name) throws ChannelException, ChannelClosedException {
/*make sure the channel is not closed*/
checkClosed();
/*if we already are connected, then ignore this*/
if(connected) {
if(log.isTraceEnabled()) log.trace("already connected to " + channel_name);
return;
}
/*make sure we have a valid channel name*/
if(channel_name == null) {
if(log.isInfoEnabled()) log.info("channel_name is null, assuming unicast channel");
}
else
this.channel_name=channel_name;
try {
prot_stack.startStack(); // calls start() in all protocols, from top to bottom
}
catch(Throwable e) {
throw new ChannelException("failed to start protocol stack", e);
}
/* try to get LOCAL_ADDR_TIMEOUT. Catch SecurityException if called in an untrusted environment (e.g. using JNLP) */
try {
LOCAL_ADDR_TIMEOUT=Long.parseLong(System.getProperty("local_addr.timeout","30000"));
}
catch (SecurityException e1) {
/* Use the default value specified above*/
}
/* Wait LOCAL_ADDR_TIMEOUT milliseconds for local_addr to have a non-null value (set by SET_LOCAL_ADDRESS) */
local_addr=(Address)local_addr_promise.getResult(LOCAL_ADDR_TIMEOUT);
if(local_addr == null) {
log.fatal("local_addr is null; cannot connect");
throw new ChannelException("local_addr is null");
}
/*create a temporary view, assume this channel is the only member and
*is the coordinator*/
Vector t=new Vector(1);
t.addElement(local_addr);
my_view=new View(local_addr, 0, t); // create a dummy view
// only connect if we are not a unicast channel
if(channel_name != null) {
connect_promise.reset();
Event connect_event=new Event(Event.CONNECT, channel_name);
down(connect_event);
Object res=connect_promise.getResult(); // waits forever until connected (or channel is closed)
if(res != null && res instanceof Exception) { // the JOIN was rejected by the coordinator
throw new ChannelException("connect() failed", (Throwable)res);
}
}
/*notify any channel listeners*/
connected=true;
notifyChannelConnected(this);
}
/**
* Disconnects the channel if it is connected. If the channel is closed, this operation is ignored<BR>
* Otherwise the following actions happen in the listed order<BR>
* <ol>
* <li> The JChannel sends a DISCONNECT event down the protocol stack<BR>
* <li> Blocks until the channel to receives a DISCONNECT_OK event<BR>
* <li> Sends a STOP_QUEING event down the stack<BR>
* <li> Stops the protocol stack by calling ProtocolStack.stop()<BR>
* <li> Notifies the listener, if the listener is available<BR>
* </ol>
*/
public synchronized void disconnect() {
if(closed) return;
if(connected) {
if(channel_name != null) {
/* Send down a DISCONNECT event. The DISCONNECT event travels down to the GMS, where a
* DISCONNECT_OK response is generated and sent up the stack. JChannel blocks until a
* DISCONNECT_OK has been received, or until timeout has elapsed.
*/
Event disconnect_event=new Event(Event.DISCONNECT, local_addr);
disconnect_promise.reset();
down(disconnect_event); // DISCONNECT is handled by each layer
disconnect_promise.getResult(); // wait for DISCONNECT_OK
}
// Just in case we use the QUEUE protocol and it is still blocked...
down(new Event(Event.STOP_QUEUEING));
connected=false;
try {
prot_stack.stopStack(); // calls stop() in all protocols, from top to bottom
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
}
notifyChannelDisconnected(this);
init(); // sets local_addr=null; changed March 18 2003 (bela) -- prevented successful rejoining
}
}
/**
* Destroys the channel.
* After this method has been called, the channel us unusable.<BR>
* This operation will disconnect the channel and close the channel receive queue immediately<BR>
*/
public synchronized void close() {
_close(true, true); // by default disconnect before closing channel and close mq
}
/** Shuts down the channel without disconnecting */
public synchronized void shutdown() {
_close(false, true); // by default disconnect before closing channel and close mq
}
/**
* Opens the channel.
* This does the following actions:
* <ol>
* <li> Resets the receiver queue by calling Queue.reset
* <li> Sets up the protocol stack by calling ProtocolStack.setup
* <li> Sets the closed flag to false
* </ol>
*/
public synchronized void open() throws ChannelException {
if(!closed)
throw new ChannelException("channel is already open");
try {
mq.reset();
// new stack is created on open() - bela June 12 2003
prot_stack=new ProtocolStack(this, props);
prot_stack.setup();
closed=false;
}
catch(Exception e) {
throw new ChannelException("failed to open channel" , e);
}
}
/**
* returns true if the Open operation has been called successfully
*/
public boolean isOpen() {
return !closed;
}
/**
* returns true if the Connect operation has been called successfully
*/
public boolean isConnected() {
return connected;
}
public int getNumMessages() {
return mq != null? mq.size() : -1;
}
public String dumpQueue() {
return Util.dumpQueue(mq);
}
/**
* Returns a map of statistics of the various protocols and of the channel itself.
* @return Map<String,Map>. A map where the keys are the protocols ("channel" pseudo key is
* used for the channel itself") and the values are property maps.
*/
public Map dumpStats() {
Map retval=prot_stack.dumpStats();
if(retval != null) {
Map tmp=dumpChannelStats();
if(tmp != null)
retval.put("channel", tmp);
}
return retval;
}
private Map dumpChannelStats() {
Map retval=new HashMap();
retval.put("sent_msgs", new Long(sent_msgs));
retval.put("sent_bytes", new Long(sent_bytes));
retval.put("received_msgs", new Long(received_msgs));
retval.put("received_bytes", new Long(received_bytes));
return retval;
}
/**
* Sends a message through the protocol stack.
* Implements the Transport interface.
*
* @param msg the message to be sent through the protocol stack,
* the destination of the message is specified inside the message itself
* @exception ChannelNotConnectedException
* @exception ChannelClosedException
*/
public void send(Message msg) throws ChannelNotConnectedException, ChannelClosedException {
checkClosed();
checkNotConnected();
if(stats) {
sent_msgs++;
sent_bytes+=msg.getLength();
}
if(msg == null)
throw new NullPointerException("msg is null");
down(new Event(Event.MSG, msg));
}
/**
* creates a new message with the destination address, and the source address
* and the object as the message value
* @param dst - the destination address of the message, null for all members
* @param src - the source address of the message
* @param obj - the value of the message
* @exception ChannelNotConnectedException
* @exception ChannelClosedException
* @see JChannel#send
*/
public void send(Address dst, Address src, Serializable obj) throws ChannelNotConnectedException, ChannelClosedException {
send(new Message(dst, src, obj));
}
/**
* Blocking receive method.
* This method returns the object that was first received by this JChannel and that has not been
* received before. After the object is received, it is removed from the receive queue.<BR>
* If you only want to inspect the object received without removing it from the queue call
* JChannel.peek<BR>
* If no messages are in the receive queue, this method blocks until a message is added or the operation times out<BR>
* By specifying a timeout of 0, the operation blocks forever, or until a message has been received.
* @param timeout the number of milliseconds to wait if the receive queue is empty. 0 means wait forever
* @exception TimeoutException if a timeout occured prior to a new message was received
* @exception ChannelNotConnectedException
* @exception ChannelClosedException
* @see JChannel#peek
*/
public Object receive(long timeout) throws ChannelNotConnectedException, ChannelClosedException, TimeoutException {
checkClosed();
checkNotConnected();
try {
Event evt=(timeout <= 0)? (Event)mq.remove() : (Event)mq.remove(timeout);
Object retval=getEvent(evt);
evt=null;
if(stats) {
if(retval != null && retval instanceof Message) {
received_msgs++;
received_bytes+=((Message)retval).getLength();
}
}
return retval;
}
catch(QueueClosedException queue_closed) {
throw new ChannelClosedException();
}
catch(TimeoutException t) {
throw t;
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
return null;
}
}
/**
* Just peeks at the next message, view or block. Does <em>not</em> install
* new view if view is received<BR>
* Does the same thing as JChannel.receive but doesn't remove the object from the
* receiver queue
*/
public Object peek(long timeout) throws ChannelNotConnectedException, ChannelClosedException, TimeoutException {
checkClosed();
checkNotConnected();
try {
Event evt=(timeout <= 0)? (Event)mq.peek() : (Event)mq.peek(timeout);
Object retval=getEvent(evt);
evt=null;
return retval;
}
catch(QueueClosedException queue_closed) {
if(log.isErrorEnabled()) log.error("exception: " + queue_closed);
return null;
}
catch(TimeoutException t) {
return null;
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
return null;
}
}
/**
* Returns the current view.
* <BR>
* If the channel is not connected or if it is closed it will return null.
* <BR>
* @return returns the current group view, or null if the channel is closed or disconnected
*/
public View getView() {
return closed || !connected ? null : my_view;
}
/**
* returns the local address of the channel
* returns null if the channel is closed
*/
public Address getLocalAddress() {
return closed ? null : local_addr;
}
/**
* returns the name of the channel
* if the channel is not connected or if it is closed it will return null
*/
public String getChannelName() {
return closed ? null : !connected ? null : channel_name;
}
/**
* Sets a channel option. The options can be one of the following:
* <UL>
* <LI> Channel.BLOCK
* <LI> Channel.LOCAL
* <LI> Channel.AUTO_RECONNECT
* <LI> Channel.AUTO_GETSTATE
* </UL>
* <P>
* There are certain dependencies between the options that you can set,
* I will try to describe them here.
* <P>
* Option: Channel.BLOCK<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true will set setOpt(VIEW, true) and the JChannel will receive BLOCKS and VIEW events<BR>
*<BR>
* Option: LOCAL<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true the JChannel will receive messages that it self sent out.<BR>
*<BR>
* Option: AUTO_RECONNECT<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true and the JChannel will try to reconnect when it is being closed<BR>
*<BR>
* Option: AUTO_GETSTATE<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true, the AUTO_RECONNECT will be set to true and the JChannel will try to get the state after a close and reconnect happens<BR>
* <BR>
*
* @param option the parameter option Channel.VIEW, Channel.SUSPECT, etc
* @param value the value to set for this option
*
*/
public void setOpt(int option, Object value) {
if(closed) {
if(log.isWarnEnabled()) log.warn("channel is closed; option not set !");
return;
}
switch(option) {
case VIEW:
if(log.isWarnEnabled())
log.warn("option VIEW has been deprecated (it is always true now); this option is ignored");
break;
case SUSPECT:
if(log.isWarnEnabled())
log.warn("option SUSPECT has been deprecated (it is always true now); this option is ignored");
break;
case BLOCK:
if(value instanceof Boolean)
receive_blocks=((Boolean)value).booleanValue();
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
case GET_STATE_EVENTS:
if(log.isWarnEnabled())
log.warn("option GET_STATE_EVENTS has been deprecated (it is always true now); this option is ignored");
break;
case LOCAL:
if(value instanceof Boolean)
receive_local_msgs=((Boolean)value).booleanValue();
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
case AUTO_RECONNECT:
if(value instanceof Boolean)
auto_reconnect=((Boolean)value).booleanValue();
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
case AUTO_GETSTATE:
if(value instanceof Boolean) {
auto_getstate=((Boolean)value).booleanValue();
if(auto_getstate)
auto_reconnect=true;
}
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
default:
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) + " not known");
break;
}
}
/**
* returns the value of an option.
* @param option the option you want to see the value for
* @return the object value, in most cases java.lang.Boolean
* @see JChannel#setOpt
*/
public Object getOpt(int option) {
switch(option) {
case VIEW:
return Boolean.TRUE;
case BLOCK:
return receive_blocks ? Boolean.TRUE : Boolean.FALSE;
case SUSPECT:
return Boolean.TRUE;
case GET_STATE_EVENTS:
return Boolean.TRUE;
case LOCAL:
return receive_local_msgs ? Boolean.TRUE : Boolean.FALSE;
default:
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) + " not known");
return null;
}
}
/**
* Called to acknowledge a block() (callback in <code>MembershipListener</code> or
* <code>BlockEvent</code> received from call to <code>receive()</code>).
* After sending blockOk(), no messages should be sent until a new view has been received.
* Calling this method on a closed channel has no effect.
*/
public void blockOk() {
down(new Event(Event.BLOCK_OK));
down(new Event(Event.START_QUEUEING));
}
/**
* Retrieves the current group state. Sends GET_STATE event down to STATE_TRANSFER layer.
* Blocks until STATE_TRANSFER sends up a GET_STATE_OK event or until <code>timeout</code>
* milliseconds have elapsed. The argument of GET_STATE_OK should be a single object.
* @param target - the target member to receive the state from. if null, state is retrieved from coordinator
* @param timeout - the number of milliseconds to wait for the operation to complete successfully
* @return true of the state was received, false if the operation timed out
*/
public boolean getState(Address target, long timeout) throws ChannelNotConnectedException, ChannelClosedException {
StateTransferInfo info=new StateTransferInfo(target, timeout);
boolean rc=_getState(new Event(Event.GET_STATE, info), info);
if(rc == false)
down(new Event(Event.RESUME_STABLE));
return rc;
}
/**
* Retrieves a substate (or partial state) from the target.
* @param target State provider. If null, coordinator is used
* @param state_id The ID of the substate. If null, the entire state will be transferred
* @param timeout
* @return
* @throws ChannelNotConnectedException
* @throws ChannelClosedException
*/
public boolean getState(Address target, String state_id, long timeout) throws ChannelNotConnectedException, ChannelClosedException {
StateTransferInfo info=new StateTransferInfo(target, state_id, timeout);
boolean rc=_getState(new Event(Event.GET_STATE, info), info);
if(rc == false)
down(new Event(Event.RESUME_STABLE));
return rc;
}
/**
* Retrieves the current group state. Sends GET_STATE event down to STATE_TRANSFER layer.
* Blocks until STATE_TRANSFER sends up a GET_STATE_OK event or until <code>timeout</code>
* milliseconds have elapsed. The argument of GET_STATE_OK should be a vector of objects.
* @param targets - the target members to receive the state from ( an Address list )
* @param timeout - the number of milliseconds to wait for the operation to complete successfully
* @return true of the state was received, false if the operation timed out
* @deprecated Not really needed - we always want to get the state from a single member,
* use {@link #getState(org.jgroups.Address, long)} instead
*/
public boolean getAllStates(Vector targets, long timeout) throws ChannelNotConnectedException, ChannelClosedException {
throw new UnsupportedOperationException("use getState() instead");
}
/**
* Called by the application is response to receiving a <code>getState()</code> object when
* calling <code>receive()</code>.
* When the application receives a getState() message on the receive() method,
* it should call returnState() to reply with the state of the application
* @param state The state of the application as a byte buffer
* (to send over the network).
*/
public void returnState(byte[] state) {
StateTransferInfo info=new StateTransferInfo(null, null, 0L, state);
down(new Event(Event.GET_APPLSTATE_OK, info));
}
/**
* Returns a substate as indicated by state_id
* @param state
* @param state_id
*/
public void returnState(byte[] state, String state_id) {
StateTransferInfo info=new StateTransferInfo(null, state_id, 0L, state);
down(new Event(Event.GET_APPLSTATE_OK, info));
}
/**
* Callback method <BR>
* Called by the ProtocolStack when a message is received.
* It will be added to the message queue from which subsequent
* <code>Receive</code>s will dequeue it.
* @param evt the event carrying the message from the protocol stack
*/
public void up(Event evt) {
int type=evt.getType();
Message msg;
switch(type) {
case Event.MSG:
msg=(Message)evt.getArg();
if(!receive_local_msgs) { // discard local messages (sent by myself to me)
if(local_addr != null && msg.getSrc() != null)
if(local_addr.equals(msg.getSrc()))
return;
}
break;
case Event.VIEW_CHANGE:
View tmp=(View)evt.getArg();
if(tmp instanceof MergeView)
my_view=new View(tmp.getVid(), tmp.getMembers());
else
my_view=tmp;
// crude solution to bug #775120: if we get our first view *before* the CONNECT_OK,
// we simply set the state to connected
if(connected == false) {
connected=true;
connect_promise.setResult(null);
}
// unblock queueing of messages due to previous BLOCK event:
down(new Event(Event.STOP_QUEUEING));
break;
case Event.CONFIG:
HashMap config=(HashMap)evt.getArg();
if(config != null && config.containsKey("state_transfer"))
state_transfer_supported=((Boolean)config.get("state_transfer")).booleanValue();
break;
case Event.BLOCK:
// If BLOCK is received by application, then we trust the application to not send
// any more messages until a VIEW_CHANGE is received. Otherwise (BLOCKs are disabled),
// we queue any messages sent until the next VIEW_CHANGE (they will be sent in the
// next view)
if(!receive_blocks) { // discard if client has not set 'receiving blocks' to 'on'
down(new Event(Event.BLOCK_OK));
down(new Event(Event.START_QUEUEING));
return;
}
break;
case Event.CONNECT_OK:
connect_promise.setResult(evt.getArg());
break;
case Event.DISCONNECT_OK:
disconnect_promise.setResult(Boolean.TRUE);
break;
case Event.GET_STATE_OK:
StateTransferInfo info=(StateTransferInfo)evt.getArg();
byte[] state=info.state;
state_promise.setResult(state != null? Boolean.TRUE : Boolean.FALSE);
if(up_handler != null) {
up_handler.up(evt);
return;
}
if(state != null) {
String state_id=info.state_id;
if(receiver != null) {
if(receiver instanceof ExtendedReceiver) {
((ExtendedReceiver)receiver).setState(state_id, state);
}
else {
receiver.setState(state);
}
}
else {
try {mq.add(new Event(Event.STATE_RECEIVED, info));} catch(Exception e) {}
}
}
break;
case Event.SET_LOCAL_ADDRESS:
local_addr_promise.setResult(evt.getArg());
break;
case Event.EXIT:
handleExit(evt);
return; // no need to pass event up; already done in handleExit()
default:
break;
}
// If UpHandler is installed, pass all events to it and return (UpHandler is e.g. a building block)
if(up_handler != null) {
up_handler.up(evt);
return;
}
switch(type) {
case Event.MSG:
if(receiver != null) {
receiver.receive((Message)evt.getArg());
return;
}
break;
case Event.VIEW_CHANGE:
if(receiver != null) {
receiver.viewAccepted((View)evt.getArg());
return;
}
break;
case Event.SUSPECT:
if(receiver != null) {
receiver.suspect((Address)evt.getArg());
return;
}
break;
case Event.GET_APPLSTATE:
if(receiver != null) {
StateTransferInfo info=(StateTransferInfo)evt.getArg();
byte[] tmp_state;
String state_id=info.state_id;
if(receiver instanceof ExtendedReceiver) {
tmp_state=((ExtendedReceiver)receiver).getState(state_id);
}
else {
tmp_state=receiver.getState();
}
returnState(tmp_state, state_id);
return;
}
break;
case Event.BLOCK:
if(receiver != null) {
receiver.block();
return;
}
break;
default:
break;
}
if(type == Event.MSG || type == Event.VIEW_CHANGE || type == Event.SUSPECT ||
type == Event.GET_APPLSTATE || type == Event.BLOCK) {
try {
mq.add(evt);
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
}
}
}
/**
* Sends a message through the protocol stack if the stack is available
* @param evt the message to send down, encapsulated in an event
*/
public void down(Event evt) {
if(evt == null) return;
// handle setting of additional data (kludge, will be removed soon)
if(evt.getType() == Event.CONFIG) {
try {
Map m=(Map)evt.getArg();
if(m != null && m.containsKey("additional_data")) {
additional_data=(byte[])m.get("additional_data");
}
}
catch(Throwable t) {
if(log.isErrorEnabled()) log.error("CONFIG event did not contain a hashmap: " + t);
}
}
if(prot_stack != null)
prot_stack.down(evt);
else
if(log.isErrorEnabled()) log.error("no protocol stack available");
}
public String toString(boolean details) {
StringBuffer sb=new StringBuffer();
sb.append("local_addr=").append(local_addr).append('\n');
sb.append("channel_name=").append(channel_name).append('\n');
sb.append("my_view=").append(my_view).append('\n');
sb.append("connected=").append(connected).append('\n');
sb.append("closed=").append(closed).append('\n');
if(mq != null)
sb.append("incoming queue size=").append(mq.size()).append('\n');
if(details) {
sb.append("receive_blocks=").append(receive_blocks).append('\n');
sb.append("receive_local_msgs=").append(receive_local_msgs).append('\n');
sb.append("auto_reconnect=").append(auto_reconnect).append('\n');
sb.append("auto_getstate=").append(auto_getstate).append('\n');
sb.append("state_transfer_supported=").append(state_transfer_supported).append('\n');
sb.append("props=").append(props).append('\n');
}
return sb.toString();
}
/* ----------------------------------- Private Methods ------------------------------------- */
/**
* Initializes all variables. Used after <tt>close()</tt> or <tt>disconnect()</tt>,
* to be ready for new <tt>connect()</tt>
*/
private void init() {
local_addr=null;
channel_name=null;
my_view=null;
// changed by Bela Sept 25 2003
//if(mq != null && mq.closed())
// mq.reset();
connect_promise.reset();
disconnect_promise.reset();
connected=false;
}
/**
* health check.<BR>
* throws a ChannelNotConnected exception if the channel is not connected
*/
protected void checkNotConnected() throws ChannelNotConnectedException {
if(!connected)
throw new ChannelNotConnectedException();
}
/**
* health check<BR>
* throws a ChannelClosed exception if the channel is closed
*/
protected void checkClosed() throws ChannelClosedException {
if(closed)
throw new ChannelClosedException();
}
/**
* returns the value of the event<BR>
* These objects will be returned<BR>
* <PRE>
* <B>Event Type - Return Type</B>
* Event.MSG - returns a Message object
* Event.VIEW_CHANGE - returns a View object
* Event.SUSPECT - returns a SuspectEvent object
* Event.BLOCK - returns a new BlockEvent object
* Event.GET_APPLSTATE - returns a GetStateEvent object
* Event.STATE_RECEIVED- returns a SetStateEvent object
* Event.Exit - returns an ExitEvent object
* All other - return the actual Event object
* </PRE>
* @param evt - the event of which you want to extract the value
* @return the event value if it matches the select list,
* returns null if the event is null
* returns the event itself if a match (See above) can not be made of the event type
*/
static Object getEvent(Event evt) {
if(evt == null)
return null; // correct ?
switch(evt.getType()) {
case Event.MSG:
return evt.getArg();
case Event.VIEW_CHANGE:
return evt.getArg();
case Event.SUSPECT:
return new SuspectEvent(evt.getArg());
case Event.BLOCK:
return new BlockEvent();
case Event.GET_APPLSTATE:
StateTransferInfo info=(StateTransferInfo)evt.getArg();
return new GetStateEvent(info.target, info.state_id);
case Event.STATE_RECEIVED:
info=(StateTransferInfo)evt.getArg();
return new SetStateEvent(info.state, info.state_id);
case Event.EXIT:
return new ExitEvent();
default:
return evt;
}
}
/**
* Receives the state from the group and modifies the JChannel.state object<br>
* This method initializes the local state variable to null, and then sends the state
* event down the stack. It waits for a GET_STATE_OK event to bounce back
* @param evt the get state event, has to be of type Event.GET_STATE
* @param info Information about the state transfer, e.g. target member and timeout
* @return true of the state was received, false if the operation timed out
*/
private boolean _getState(Event evt, StateTransferInfo info) throws ChannelNotConnectedException, ChannelClosedException {
checkClosed();
checkNotConnected();
if(!state_transfer_supported) {
throw new IllegalStateException("fetching state will fail as state transfer is not supported. "
+ "Add one of the STATE_TRANSFER protocols to your protocol configuration");
}
state_promise.reset();
down(evt);
Boolean state_transfer_successfull=(Boolean)state_promise.getResult(info.timeout);
return state_transfer_successfull != null && state_transfer_successfull.booleanValue();
}
/**
* Disconnects and closes the channel.
* This method does the folloing things
* <ol>
* <li>Calls <code>this.disconnect</code> if the disconnect parameter is true
* <li>Calls <code>Queue.close</code> on mq if the close_mq parameter is true
* <li>Calls <code>ProtocolStack.stop</code> on the protocol stack
* <li>Calls <code>ProtocolStack.destroy</code> on the protocol stack
* <li>Sets the channel closed and channel connected flags to true and false
* <li>Notifies any channel listener of the channel close operation
* </ol>
*/
protected void _close(boolean disconnect, boolean close_mq) {
if(closed)
return;
if(disconnect)
disconnect(); // leave group if connected
if(close_mq) {
try {
if(mq != null)
mq.close(false); // closes and removes all messages
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
}
}
if(prot_stack != null) {
try {
prot_stack.stopStack();
prot_stack.destroy();
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("failed destroying the protocol stack", e);
}
}
closed=true;
connected=false;
notifyChannelClosed(this);
init(); // sets local_addr=null; changed March 18 2003 (bela) -- prevented successful rejoining
}
public final void closeMessageQueue(boolean flush_entries) {
if(mq != null)
mq.close(flush_entries);
}
/**
* Creates a separate thread to close the protocol stack.
* This is needed because the thread that called JChannel.up() with the EXIT event would
* hang waiting for up() to return, while up() actually tries to kill that very thread.
* This way, we return immediately and allow the thread to terminate.
*/
private void handleExit(Event evt) {
notifyChannelShunned();
if(closer != null && !closer.isAlive())
closer=null;
if(closer == null) {
if(log.isInfoEnabled())
log.info("received an EXIT event, will leave the channel");
closer=new CloserThread(evt);
closer.start();
}
}
/* ------------------------------- End of Private Methods ---------------------------------- */
class CloserThread extends Thread {
final Event evt;
final Thread t=null;
CloserThread(Event evt) {
super(Util.getGlobalThreadGroup(), "CloserThread");
this.evt=evt;
setDaemon(true);
}
public void run() {
try {
String old_channel_name=channel_name; // remember because close() will null it
if(log.isInfoEnabled())
log.info("closing the channel");
_close(false, false); // do not disconnect before closing channel, do not close mq (yet !)
if(up_handler != null)
up_handler.up(this.evt);
else {
try {
if(receiver == null)
mq.add(this.evt);
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("exception: " + ex);
}
}
if(mq != null) {
Util.sleep(500); // give the mq thread a bit of time to deliver EXIT to the application
try {
mq.close(false);
}
catch(Exception ex) {
}
}
if(auto_reconnect) {
try {
if(log.isInfoEnabled()) log.info("reconnecting to group " + old_channel_name);
open();
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("failure reopening channel: " + ex);
return;
}
try {
if(additional_data != null) {
// set previously set additional data
Map m=new HashMap(11);
m.put("additional_data", additional_data);
down(new Event(Event.CONFIG, m));
}
connect(old_channel_name);
notifyChannelReconnected(local_addr);
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("failure reconnecting to channel: " + ex);
return;
}
}
if(auto_getstate) {
if(log.isInfoEnabled())
log.info("fetching the state (auto_getstate=true)");
boolean rc=JChannel.this.getState(null, GET_STATE_DEFAULT_TIMEOUT);
if(log.isInfoEnabled()) {
if(rc)
log.info("state was retrieved successfully");
else
log.info("state transfer failed");
}
}
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("exception: " + ex);
}
finally {
closer=null;
}
}
}
}
|
src/org/jgroups/JChannel.java
|
// $Id: JChannel.java,v 1.67 2006/04/28 15:40:07 belaban Exp $
package org.jgroups;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.conf.ConfiguratorFactory;
import org.jgroups.conf.ProtocolStackConfigurator;
import org.jgroups.stack.ProtocolStack;
import org.jgroups.stack.StateTransferInfo;
import org.jgroups.util.*;
import org.w3c.dom.Element;
import java.io.File;
import java.io.Serializable;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
/**
* JChannel is a pure Java implementation of Channel.
* When a JChannel object is instantiated it automatically sets up the
* protocol stack.
* <p>
* <B>Properties</B>
* <P>
* Properties are used to configure a channel, and are accepted in
* several forms; the String form is described here.
* A property string consists of a number of properties separated by
* colons. For example:
* <p>
* <pre>"<prop1>(arg1=val1):<prop2>(arg1=val1;arg2=val2):<prop3>:<propn>"</pre>
* <p>
* Each property relates directly to a protocol layer, which is
* implemented as a Java class. When a protocol stack is to be created
* based on the above property string, the first property becomes the
* bottom-most layer, the second one will be placed on the first, etc.:
* the stack is created from the bottom to the top, as the string is
* parsed from left to right. Each property has to be the name of a
* Java class that resides in the
* {@link org.jgroups.protocols} package.
* <p>
* Note that only the base name has to be given, not the fully specified
* class name (e.g., UDP instead of org.jgroups.protocols.UDP).
* <p>
* Each layer may have 0 or more arguments, which are specified as a
* list of name/value pairs in parentheses directly after the property.
* In the example above, the first protocol layer has 1 argument,
* the second 2, the third none. When a layer is created, these
* properties (if there are any) will be set in a layer by invoking
* the layer's setProperties() method
* <p>
* As an example the property string below instructs JGroups to create
* a JChannel with protocols UDP, PING, FD and GMS:<p>
* <pre>"UDP(mcast_addr=228.10.9.8;mcast_port=5678):PING:FD:GMS"</pre>
* <p>
* The UDP protocol layer is at the bottom of the stack, and it
* should use mcast address 228.10.9.8. and port 5678 rather than
* the default IP multicast address and port. The only other argument
* instructs FD to output debug information while executing.
* Property UDP refers to a class {@link org.jgroups.protocols.UDP},
* which is subsequently loaded and an instance of which is created as protocol layer.
* If any of these classes are not found, an exception will be thrown and
* the construction of the stack will be aborted.
*
* @author Bela Ban
* @version $Revision: 1.67 $
*/
public class JChannel extends Channel {
/**
* The default protocol stack used by the default constructor.
*/
public static final String DEFAULT_PROTOCOL_STACK=
"UDP(mcast_addr=228.1.2.3;mcast_port=45566;ip_ttl=32):" +
"PING(timeout=3000;num_initial_members=6):" +
"FD(timeout=3000):" +
"VERIFY_SUSPECT(timeout=1500):" +
"pbcast.NAKACK(gc_lag=10;retransmit_timeout=600,1200,2400,4800):" +
"UNICAST(timeout=600,1200,2400,4800):" +
"pbcast.STABLE(desired_avg_gossip=10000):" +
"FRAG:" +
"pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;" +
"shun=true;print_local_addr=true)";
static final String FORCE_PROPS="force.properties";
/* the protocol stack configuration string */
private String props=null;
/*the address of this JChannel instance*/
private Address local_addr=null;
/*the channel (also know as group) name*/
private String channel_name=null; // group name
/*the latest view of the group membership*/
private View my_view=null;
/*the queue that is used to receive messages (events) from the protocol stack*/
private final Queue mq=new Queue();
/*the protocol stack, used to send and receive messages from the protocol stack*/
private ProtocolStack prot_stack=null;
/** Thread responsible for closing a channel and potentially reconnecting to it (e.g., when shunned). */
protected CloserThread closer=null;
/** To wait until a local address has been assigned */
private final Promise local_addr_promise=new Promise();
/** To wait until we have connected successfully */
private final Promise connect_promise=new Promise();
/** To wait until we have been disconnected from the channel */
private final Promise disconnect_promise=new Promise();
private final Promise state_promise=new Promise();
/** wait until we have a non-null local_addr */
private long LOCAL_ADDR_TIMEOUT=30000; //=Long.parseLong(System.getProperty("local_addr.timeout", "30000"));
/*if the states is fetched automatically, this is the default timeout, 5 secs*/
private static final long GET_STATE_DEFAULT_TIMEOUT=5000;
/*flag to indicate whether to receive blocks, if this is set to true, receive_views is set to true*/
private boolean receive_blocks=false;
/*flag to indicate whether to receive local messages
*if this is set to false, the JChannel will not receive messages sent by itself*/
private boolean receive_local_msgs=true;
/*flag to indicate whether the channel will reconnect (reopen) when the exit message is received*/
private boolean auto_reconnect=false;
/*flag t indicate whether the state is supposed to be retrieved after the channel is reconnected
*setting this to true, automatically forces auto_reconnect to true*/
private boolean auto_getstate=false;
/*channel connected flag*/
protected boolean connected=false;
/*channel closed flag*/
protected boolean closed=false; // close() has been called, channel is unusable
/** True if a state transfer protocol is available, false otherwise */
private boolean state_transfer_supported=false; // set by CONFIG event from STATE_TRANSFER protocol
/** Used to maintain additional data across channel disconnects/reconnects. This is a kludge and will be remove
* as soon as JGroups supports logical addresses
*/
private byte[] additional_data=null;
protected final Log log=LogFactory.getLog(getClass());
/** Collect statistics */
protected boolean stats=true;
protected long sent_msgs=0, received_msgs=0, sent_bytes=0, received_bytes=0;
/** Used by subclass to create a JChannel without a protocol stack, don't use as application programmer */
protected JChannel(boolean no_op) {
;
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* specified by the <code>DEFAULT_PROTOCOL_STACK</code> member.
*
* @throws ChannelException if problems occur during the initialization of
* the protocol stack.
*/
public JChannel() throws ChannelException {
this(DEFAULT_PROTOCOL_STACK);
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration contained by the specified file.
*
* @param properties a file containing a JGroups XML protocol stack
* configuration.
*
* @throws ChannelException if problems occur during the configuration or
* initialization of the protocol stack.
*/
public JChannel(File properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration contained by the specified XML element.
*
* @param properties a XML element containing a JGroups XML protocol stack
* configuration.
*
* @throws ChannelException if problems occur during the configuration or
* initialization of the protocol stack.
*/
public JChannel(Element properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration indicated by the specified URL.
*
* @param properties a URL pointing to a JGroups XML protocol stack
* configuration.
*
* @throws ChannelException if problems occur during the configuration or
* initialization of the protocol stack.
*/
public JChannel(URL properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration based upon the specified properties parameter.
*
* @param properties an old style property string, a string representing a
* system resource containing a JGroups XML configuration,
* a string representing a URL pointing to a JGroups XML
* XML configuration, or a string representing a file name
* that contains a JGroups XML configuration.
*
* @throws ChannelException if problems occur during the configuration and
* initialization of the protocol stack.
*/
public JChannel(String properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration contained by the protocol stack configurator parameter.
* <p>
* All of the public constructors of this class eventually delegate to this
* method.
*
* @param configurator a protocol stack configurator containing a JGroups
* protocol stack configuration.
*
* @throws ChannelException if problems occur during the initialization of
* the protocol stack.
*/
protected JChannel(ProtocolStackConfigurator configurator) throws ChannelException {
props = configurator.getProtocolStackString();
/*create the new protocol stack*/
prot_stack=new ProtocolStack(this, props);
/* Setup protocol stack (create layers, queues between them */
try {
prot_stack.setup();
}
catch(Throwable e) {
throw new ChannelException("unable to setup the protocol stack", e);
}
}
/**
* Creates a new JChannel with the protocol stack as defined in the properties
* parameter. an example of this parameter is<BR>
* "UDP:PING:FD:STABLE:NAKACK:UNICAST:FRAG:FLUSH:GMS:VIEW_ENFORCER:STATE_TRANSFER:QUEUE"<BR>
* Other examples can be found in the ./conf directory<BR>
* @param properties the protocol stack setup; if null, the default protocol stack will be used.
* The properties can also be a java.net.URL object or a string that is a URL spec.
* The JChannel will validate any URL object and String object to see if they are a URL.
* In case of the parameter being a url, the JChannel will try to load the xml from there.
* In case properties is a org.w3c.dom.Element, the ConfiguratorFactory will parse the
* DOM tree with the element as its root element.
* @deprecated Use the constructors with specific parameter types instead.
*/
public JChannel(Object properties) throws ChannelException {
if (properties == null) {
properties = DEFAULT_PROTOCOL_STACK;
}
try {
ProtocolStackConfigurator c=ConfiguratorFactory.getStackConfigurator(properties);
props=c.getProtocolStackString();
}
catch(Exception x) {
throw new ChannelException("unable to load protocol stack", x);
}
/*create the new protocol stack*/
prot_stack=new ProtocolStack(this, props);
/* Setup protocol stack (create layers, queues between them */
try {
prot_stack.setup();
}
catch(Throwable e) {
throw new ChannelException("failed to setup protocol stack", e);
}
}
/**
* Returns the protocol stack.
* Currently used by Debugger.
* Specific to JChannel, therefore
* not visible in Channel
*/
public ProtocolStack getProtocolStack() {
return prot_stack;
}
protected Log getLog() {
return log;
}
/**
* returns the protocol stack configuration in string format.
* an example of this property is<BR>
* "UDP:PING:FD:STABLE:NAKACK:UNICAST:FRAG:FLUSH:GMS:VIEW_ENFORCER:STATE_TRANSFER:QUEUE"
*/
public String getProperties() {
return props;
}
public boolean statsEnabled() {
return stats;
}
public void enableStats(boolean stats) {
this.stats=stats;
}
public void resetStats() {
sent_msgs=received_msgs=sent_bytes=received_bytes=0;
}
public long getSentMessages() {return sent_msgs;}
public long getSentBytes() {return sent_bytes;}
public long getReceivedMessages() {return received_msgs;}
public long getReceivedBytes() {return received_bytes;}
public int getNumberOfTasksInTimer() {return prot_stack != null ? prot_stack.timer.size() : -1;}
public String dumpTimerQueue() {
return prot_stack != null? prot_stack.dumpTimerQueue() : "<n/a";
}
/**
* Returns a pretty-printed form of all the protocols. If include_properties is set,
* the properties for each protocol will also be printed.
*/
public String printProtocolSpec(boolean include_properties) {
return prot_stack != null ? prot_stack.printProtocolSpec(include_properties) : null;
}
/**
* Connects the channel to a group.
* If the channel is already connected, an error message will be printed to the error log.
* If the channel is closed a ChannelClosed exception will be thrown.
* This method starts the protocol stack by calling ProtocolStack.start,
* then it sends an Event.CONNECT event down the stack and waits to receive a CONNECT_OK event.
* Once the CONNECT_OK event arrives from the protocol stack, any channel listeners are notified
* and the channel is considered connected.
*
* @param channel_name A <code>String</code> denoting the group name. Cannot be null.
* @exception ChannelException The protocol stack cannot be started
* @exception ChannelClosedException The channel is closed and therefore cannot be used any longer.
* A new channel has to be created first.
*/
public synchronized void connect(String channel_name) throws ChannelException, ChannelClosedException {
/*make sure the channel is not closed*/
checkClosed();
/*if we already are connected, then ignore this*/
if(connected) {
if(log.isTraceEnabled()) log.trace("already connected to " + channel_name);
return;
}
/*make sure we have a valid channel name*/
if(channel_name == null) {
if(log.isInfoEnabled()) log.info("channel_name is null, assuming unicast channel");
}
else
this.channel_name=channel_name;
try {
prot_stack.startStack(); // calls start() in all protocols, from top to bottom
}
catch(Throwable e) {
throw new ChannelException("failed to start protocol stack", e);
}
/* try to get LOCAL_ADDR_TIMEOUT. Catch SecurityException if called in an untrusted environment (e.g. using JNLP) */
try {
LOCAL_ADDR_TIMEOUT=Long.parseLong(System.getProperty("local_addr.timeout","30000"));
}
catch (SecurityException e1) {
/* Use the default value specified above*/
}
/* Wait LOCAL_ADDR_TIMEOUT milliseconds for local_addr to have a non-null value (set by SET_LOCAL_ADDRESS) */
local_addr=(Address)local_addr_promise.getResult(LOCAL_ADDR_TIMEOUT);
if(local_addr == null) {
log.fatal("local_addr is null; cannot connect");
throw new ChannelException("local_addr is null");
}
/*create a temporary view, assume this channel is the only member and
*is the coordinator*/
Vector t=new Vector(1);
t.addElement(local_addr);
my_view=new View(local_addr, 0, t); // create a dummy view
// only connect if we are not a unicast channel
if(channel_name != null) {
connect_promise.reset();
Event connect_event=new Event(Event.CONNECT, channel_name);
down(connect_event);
Object res=connect_promise.getResult(); // waits forever until connected (or channel is closed)
if(res != null && res instanceof Exception) { // the JOIN was rejected by the coordinator
throw new ChannelException("connect() failed", (Throwable)res);
}
}
/*notify any channel listeners*/
connected=true;
notifyChannelConnected(this);
}
/**
* Disconnects the channel if it is connected. If the channel is closed, this operation is ignored<BR>
* Otherwise the following actions happen in the listed order<BR>
* <ol>
* <li> The JChannel sends a DISCONNECT event down the protocol stack<BR>
* <li> Blocks until the channel to receives a DISCONNECT_OK event<BR>
* <li> Sends a STOP_QUEING event down the stack<BR>
* <li> Stops the protocol stack by calling ProtocolStack.stop()<BR>
* <li> Notifies the listener, if the listener is available<BR>
* </ol>
*/
public synchronized void disconnect() {
if(closed) return;
if(connected) {
if(channel_name != null) {
/* Send down a DISCONNECT event. The DISCONNECT event travels down to the GMS, where a
* DISCONNECT_OK response is generated and sent up the stack. JChannel blocks until a
* DISCONNECT_OK has been received, or until timeout has elapsed.
*/
Event disconnect_event=new Event(Event.DISCONNECT, local_addr);
disconnect_promise.reset();
down(disconnect_event); // DISCONNECT is handled by each layer
disconnect_promise.getResult(); // wait for DISCONNECT_OK
}
// Just in case we use the QUEUE protocol and it is still blocked...
down(new Event(Event.STOP_QUEUEING));
connected=false;
try {
prot_stack.stopStack(); // calls stop() in all protocols, from top to bottom
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
}
notifyChannelDisconnected(this);
init(); // sets local_addr=null; changed March 18 2003 (bela) -- prevented successful rejoining
}
}
/**
* Destroys the channel.
* After this method has been called, the channel us unusable.<BR>
* This operation will disconnect the channel and close the channel receive queue immediately<BR>
*/
public synchronized void close() {
_close(true, true); // by default disconnect before closing channel and close mq
}
/** Shuts down the channel without disconnecting */
public synchronized void shutdown() {
_close(false, true); // by default disconnect before closing channel and close mq
}
/**
* Opens the channel.
* This does the following actions:
* <ol>
* <li> Resets the receiver queue by calling Queue.reset
* <li> Sets up the protocol stack by calling ProtocolStack.setup
* <li> Sets the closed flag to false
* </ol>
*/
public synchronized void open() throws ChannelException {
if(!closed)
throw new ChannelException("channel is already open");
try {
mq.reset();
// new stack is created on open() - bela June 12 2003
prot_stack=new ProtocolStack(this, props);
prot_stack.setup();
closed=false;
}
catch(Exception e) {
throw new ChannelException("failed to open channel" , e);
}
}
/**
* returns true if the Open operation has been called successfully
*/
public boolean isOpen() {
return !closed;
}
/**
* returns true if the Connect operation has been called successfully
*/
public boolean isConnected() {
return connected;
}
public int getNumMessages() {
return mq != null? mq.size() : -1;
}
public String dumpQueue() {
return Util.dumpQueue(mq);
}
/**
* Returns a map of statistics of the various protocols and of the channel itself.
* @return Map<String,Map>. A map where the keys are the protocols ("channel" pseudo key is
* used for the channel itself") and the values are property maps.
*/
public Map dumpStats() {
Map retval=prot_stack.dumpStats();
if(retval != null) {
Map tmp=dumpChannelStats();
if(tmp != null)
retval.put("channel", tmp);
}
return retval;
}
private Map dumpChannelStats() {
Map retval=new HashMap();
retval.put("sent_msgs", new Long(sent_msgs));
retval.put("sent_bytes", new Long(sent_bytes));
retval.put("received_msgs", new Long(received_msgs));
retval.put("received_bytes", new Long(received_bytes));
return retval;
}
/**
* Sends a message through the protocol stack.
* Implements the Transport interface.
*
* @param msg the message to be sent through the protocol stack,
* the destination of the message is specified inside the message itself
* @exception ChannelNotConnectedException
* @exception ChannelClosedException
*/
public void send(Message msg) throws ChannelNotConnectedException, ChannelClosedException {
checkClosed();
checkNotConnected();
if(stats) {
sent_msgs++;
sent_bytes+=msg.getLength();
}
if(msg == null)
throw new NullPointerException("msg is null");
down(new Event(Event.MSG, msg));
}
/**
* creates a new message with the destination address, and the source address
* and the object as the message value
* @param dst - the destination address of the message, null for all members
* @param src - the source address of the message
* @param obj - the value of the message
* @exception ChannelNotConnectedException
* @exception ChannelClosedException
* @see JChannel#send
*/
public void send(Address dst, Address src, Serializable obj) throws ChannelNotConnectedException, ChannelClosedException {
send(new Message(dst, src, obj));
}
/**
* Blocking receive method.
* This method returns the object that was first received by this JChannel and that has not been
* received before. After the object is received, it is removed from the receive queue.<BR>
* If you only want to inspect the object received without removing it from the queue call
* JChannel.peek<BR>
* If no messages are in the receive queue, this method blocks until a message is added or the operation times out<BR>
* By specifying a timeout of 0, the operation blocks forever, or until a message has been received.
* @param timeout the number of milliseconds to wait if the receive queue is empty. 0 means wait forever
* @exception TimeoutException if a timeout occured prior to a new message was received
* @exception ChannelNotConnectedException
* @exception ChannelClosedException
* @see JChannel#peek
*/
public Object receive(long timeout) throws ChannelNotConnectedException, ChannelClosedException, TimeoutException {
checkClosed();
checkNotConnected();
try {
Event evt=(timeout <= 0)? (Event)mq.remove() : (Event)mq.remove(timeout);
Object retval=getEvent(evt);
evt=null;
if(stats) {
if(retval != null && retval instanceof Message) {
received_msgs++;
received_bytes+=((Message)retval).getLength();
}
}
return retval;
}
catch(QueueClosedException queue_closed) {
throw new ChannelClosedException();
}
catch(TimeoutException t) {
throw t;
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
return null;
}
}
/**
* Just peeks at the next message, view or block. Does <em>not</em> install
* new view if view is received<BR>
* Does the same thing as JChannel.receive but doesn't remove the object from the
* receiver queue
*/
public Object peek(long timeout) throws ChannelNotConnectedException, ChannelClosedException, TimeoutException {
checkClosed();
checkNotConnected();
try {
Event evt=(timeout <= 0)? (Event)mq.peek() : (Event)mq.peek(timeout);
Object retval=getEvent(evt);
evt=null;
return retval;
}
catch(QueueClosedException queue_closed) {
if(log.isErrorEnabled()) log.error("exception: " + queue_closed);
return null;
}
catch(TimeoutException t) {
return null;
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
return null;
}
}
/**
* Returns the current view.
* <BR>
* If the channel is not connected or if it is closed it will return null.
* <BR>
* @return returns the current group view, or null if the channel is closed or disconnected
*/
public View getView() {
return closed || !connected ? null : my_view;
}
/**
* returns the local address of the channel
* returns null if the channel is closed
*/
public Address getLocalAddress() {
return closed ? null : local_addr;
}
/**
* returns the name of the channel
* if the channel is not connected or if it is closed it will return null
*/
public String getChannelName() {
return closed ? null : !connected ? null : channel_name;
}
/**
* Sets a channel option. The options can be one of the following:
* <UL>
* <LI> Channel.BLOCK
* <LI> Channel.LOCAL
* <LI> Channel.AUTO_RECONNECT
* <LI> Channel.AUTO_GETSTATE
* </UL>
* <P>
* There are certain dependencies between the options that you can set,
* I will try to describe them here.
* <P>
* Option: Channel.BLOCK<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true will set setOpt(VIEW, true) and the JChannel will receive BLOCKS and VIEW events<BR>
*<BR>
* Option: LOCAL<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true the JChannel will receive messages that it self sent out.<BR>
*<BR>
* Option: AUTO_RECONNECT<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true and the JChannel will try to reconnect when it is being closed<BR>
*<BR>
* Option: AUTO_GETSTATE<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true, the AUTO_RECONNECT will be set to true and the JChannel will try to get the state after a close and reconnect happens<BR>
* <BR>
*
* @param option the parameter option Channel.VIEW, Channel.SUSPECT, etc
* @param value the value to set for this option
*
*/
public void setOpt(int option, Object value) {
if(closed) {
if(log.isWarnEnabled()) log.warn("channel is closed; option not set !");
return;
}
switch(option) {
case VIEW:
if(log.isWarnEnabled())
log.warn("option VIEW has been deprecated (it is always true now); this option is ignored");
break;
case SUSPECT:
if(log.isWarnEnabled())
log.warn("option SUSPECT has been deprecated (it is always true now); this option is ignored");
break;
case BLOCK:
if(value instanceof Boolean)
receive_blocks=((Boolean)value).booleanValue();
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
case GET_STATE_EVENTS:
if(log.isWarnEnabled())
log.warn("option GET_STATE_EVENTS has been deprecated (it is always true now); this option is ignored");
break;
case LOCAL:
if(value instanceof Boolean)
receive_local_msgs=((Boolean)value).booleanValue();
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
case AUTO_RECONNECT:
if(value instanceof Boolean)
auto_reconnect=((Boolean)value).booleanValue();
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
case AUTO_GETSTATE:
if(value instanceof Boolean) {
auto_getstate=((Boolean)value).booleanValue();
if(auto_getstate)
auto_reconnect=true;
}
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
default:
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) + " not known");
break;
}
}
/**
* returns the value of an option.
* @param option the option you want to see the value for
* @return the object value, in most cases java.lang.Boolean
* @see JChannel#setOpt
*/
public Object getOpt(int option) {
switch(option) {
case VIEW:
return Boolean.TRUE;
case BLOCK:
return receive_blocks ? Boolean.TRUE : Boolean.FALSE;
case SUSPECT:
return Boolean.TRUE;
case GET_STATE_EVENTS:
return Boolean.TRUE;
case LOCAL:
return receive_local_msgs ? Boolean.TRUE : Boolean.FALSE;
default:
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) + " not known");
return null;
}
}
/**
* Called to acknowledge a block() (callback in <code>MembershipListener</code> or
* <code>BlockEvent</code> received from call to <code>receive()</code>).
* After sending blockOk(), no messages should be sent until a new view has been received.
* Calling this method on a closed channel has no effect.
*/
public void blockOk() {
down(new Event(Event.BLOCK_OK));
down(new Event(Event.START_QUEUEING));
}
/**
* Retrieves the current group state. Sends GET_STATE event down to STATE_TRANSFER layer.
* Blocks until STATE_TRANSFER sends up a GET_STATE_OK event or until <code>timeout</code>
* milliseconds have elapsed. The argument of GET_STATE_OK should be a single object.
* @param target - the target member to receive the state from. if null, state is retrieved from coordinator
* @param timeout - the number of milliseconds to wait for the operation to complete successfully
* @return true of the state was received, false if the operation timed out
*/
public boolean getState(Address target, long timeout) throws ChannelNotConnectedException, ChannelClosedException {
StateTransferInfo info=new StateTransferInfo(target, timeout);
boolean rc=_getState(new Event(Event.GET_STATE, info), info);
if(rc == false)
down(new Event(Event.RESUME_STABLE));
return rc;
}
/**
* Retrieves a substate (or partial state) from the target.
* @param target State provider. If null, coordinator is used
* @param state_id The ID of the substate. If null, the entire state will be transferred
* @param timeout
* @return
* @throws ChannelNotConnectedException
* @throws ChannelClosedException
*/
public boolean getState(Address target, String state_id, long timeout) throws ChannelNotConnectedException, ChannelClosedException {
StateTransferInfo info=new StateTransferInfo(target, state_id, timeout);
boolean rc=_getState(new Event(Event.GET_STATE, info), info);
if(rc == false)
down(new Event(Event.RESUME_STABLE));
return rc;
}
/**
* Retrieves the current group state. Sends GET_STATE event down to STATE_TRANSFER layer.
* Blocks until STATE_TRANSFER sends up a GET_STATE_OK event or until <code>timeout</code>
* milliseconds have elapsed. The argument of GET_STATE_OK should be a vector of objects.
* @param targets - the target members to receive the state from ( an Address list )
* @param timeout - the number of milliseconds to wait for the operation to complete successfully
* @return true of the state was received, false if the operation timed out
* @deprecated Not really needed - we always want to get the state from a single member,
* use {@link #getState(org.jgroups.Address, long)} instead
*/
public boolean getAllStates(Vector targets, long timeout) throws ChannelNotConnectedException, ChannelClosedException {
throw new UnsupportedOperationException("use getState() instead");
}
/**
* Called by the application is response to receiving a <code>getState()</code> object when
* calling <code>receive()</code>.
* When the application receives a getState() message on the receive() method,
* it should call returnState() to reply with the state of the application
* @param state The state of the application as a byte buffer
* (to send over the network).
*/
public void returnState(byte[] state) {
StateTransferInfo info=new StateTransferInfo(null, null, 0L, state);
down(new Event(Event.GET_APPLSTATE_OK, info));
}
/**
* Returns a substate as indicated by state_id
* @param state
* @param state_id
*/
public void returnState(byte[] state, String state_id) {
StateTransferInfo info=new StateTransferInfo(null, state_id, 0L, state);
down(new Event(Event.GET_APPLSTATE_OK, info));
}
/**
* Callback method <BR>
* Called by the ProtocolStack when a message is received.
* It will be added to the message queue from which subsequent
* <code>Receive</code>s will dequeue it.
* @param evt the event carrying the message from the protocol stack
*/
public void up(Event evt) {
int type=evt.getType();
Message msg;
switch(type) {
case Event.MSG:
msg=(Message)evt.getArg();
if(!receive_local_msgs) { // discard local messages (sent by myself to me)
if(local_addr != null && msg.getSrc() != null)
if(local_addr.equals(msg.getSrc()))
return;
}
break;
case Event.VIEW_CHANGE:
View tmp=(View)evt.getArg();
if(tmp instanceof MergeView)
my_view=new View(tmp.getVid(), tmp.getMembers());
else
my_view=tmp;
// crude solution to bug #775120: if we get our first view *before* the CONNECT_OK,
// we simply set the state to connected
if(connected == false) {
connected=true;
connect_promise.setResult(null);
}
// unblock queueing of messages due to previous BLOCK event:
down(new Event(Event.STOP_QUEUEING));
break;
case Event.CONFIG:
HashMap config=(HashMap)evt.getArg();
if(config != null && config.containsKey("state_transfer"))
state_transfer_supported=((Boolean)config.get("state_transfer")).booleanValue();
break;
case Event.BLOCK:
// If BLOCK is received by application, then we trust the application to not send
// any more messages until a VIEW_CHANGE is received. Otherwise (BLOCKs are disabled),
// we queue any messages sent until the next VIEW_CHANGE (they will be sent in the
// next view)
if(!receive_blocks) { // discard if client has not set 'receiving blocks' to 'on'
down(new Event(Event.BLOCK_OK));
down(new Event(Event.START_QUEUEING));
return;
}
break;
case Event.CONNECT_OK:
connect_promise.setResult(evt.getArg());
break;
case Event.DISCONNECT_OK:
disconnect_promise.setResult(Boolean.TRUE);
break;
case Event.GET_STATE_OK:
StateTransferInfo info=(StateTransferInfo)evt.getArg();
byte[] state=info.state;
state_promise.setResult(state != null? Boolean.TRUE : Boolean.FALSE);
if(up_handler != null) {
up_handler.up(evt);
return;
}
if(state != null) {
String state_id=info.state_id;
if(receiver != null) {
if(receiver instanceof ExtendedReceiver) {
((ExtendedReceiver)receiver).setState(state_id, state);
}
else {
receiver.setState(state);
}
}
else {
try {mq.add(new Event(Event.STATE_RECEIVED, info));} catch(Exception e) {}
}
}
break;
case Event.SET_LOCAL_ADDRESS:
local_addr_promise.setResult(evt.getArg());
break;
case Event.EXIT:
handleExit(evt);
return; // no need to pass event up; already done in handleExit()
default:
break;
}
// If UpHandler is installed, pass all events to it and return (UpHandler is e.g. a building block)
if(up_handler != null) {
up_handler.up(evt);
return;
}
switch(type) {
case Event.MSG:
if(receiver != null) {
receiver.receive((Message)evt.getArg());
return;
}
break;
case Event.VIEW_CHANGE:
if(receiver != null) {
receiver.viewAccepted((View)evt.getArg());
return;
}
break;
case Event.SUSPECT:
if(receiver != null) {
receiver.suspect((Address)evt.getArg());
return;
}
break;
case Event.GET_APPLSTATE:
if(receiver != null) {
StateTransferInfo info=(StateTransferInfo)evt.getArg();
byte[] tmp_state;
String state_id=info.state_id;
if(receiver instanceof ExtendedReceiver) {
tmp_state=((ExtendedReceiver)receiver).getState(state_id);
}
else {
tmp_state=receiver.getState();
}
returnState(tmp_state, state_id);
return;
}
break;
case Event.BLOCK:
if(receiver != null) {
receiver.block();
return;
}
break;
default:
break;
}
if(type == Event.MSG || type == Event.VIEW_CHANGE || type == Event.SUSPECT ||
type == Event.GET_APPLSTATE || type == Event.BLOCK) {
try {
mq.add(evt);
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
}
}
}
/**
* Sends a message through the protocol stack if the stack is available
* @param evt the message to send down, encapsulated in an event
*/
public void down(Event evt) {
if(evt == null) return;
// handle setting of additional data (kludge, will be removed soon)
if(evt.getType() == Event.CONFIG) {
try {
Map m=(Map)evt.getArg();
if(m != null && m.containsKey("additional_data")) {
additional_data=(byte[])m.get("additional_data");
}
}
catch(Throwable t) {
if(log.isErrorEnabled()) log.error("CONFIG event did not contain a hashmap: " + t);
}
}
if(prot_stack != null)
prot_stack.down(evt);
else
if(log.isErrorEnabled()) log.error("no protocol stack available");
}
public String toString(boolean details) {
StringBuffer sb=new StringBuffer();
sb.append("local_addr=").append(local_addr).append('\n');
sb.append("channel_name=").append(channel_name).append('\n');
sb.append("my_view=").append(my_view).append('\n');
sb.append("connected=").append(connected).append('\n');
sb.append("closed=").append(closed).append('\n');
if(mq != null)
sb.append("incoming queue size=").append(mq.size()).append('\n');
if(details) {
sb.append("receive_blocks=").append(receive_blocks).append('\n');
sb.append("receive_local_msgs=").append(receive_local_msgs).append('\n');
sb.append("auto_reconnect=").append(auto_reconnect).append('\n');
sb.append("auto_getstate=").append(auto_getstate).append('\n');
sb.append("state_transfer_supported=").append(state_transfer_supported).append('\n');
sb.append("props=").append(props).append('\n');
}
return sb.toString();
}
/* ----------------------------------- Private Methods ------------------------------------- */
/**
* Initializes all variables. Used after <tt>close()</tt> or <tt>disconnect()</tt>,
* to be ready for new <tt>connect()</tt>
*/
private void init() {
local_addr=null;
channel_name=null;
my_view=null;
// changed by Bela Sept 25 2003
//if(mq != null && mq.closed())
// mq.reset();
connect_promise.reset();
disconnect_promise.reset();
connected=false;
}
/**
* health check.<BR>
* throws a ChannelNotConnected exception if the channel is not connected
*/
protected void checkNotConnected() throws ChannelNotConnectedException {
if(!connected)
throw new ChannelNotConnectedException();
}
/**
* health check<BR>
* throws a ChannelClosed exception if the channel is closed
*/
protected void checkClosed() throws ChannelClosedException {
if(closed)
throw new ChannelClosedException();
}
/**
* returns the value of the event<BR>
* These objects will be returned<BR>
* <PRE>
* <B>Event Type - Return Type</B>
* Event.MSG - returns a Message object
* Event.VIEW_CHANGE - returns a View object
* Event.SUSPECT - returns a SuspectEvent object
* Event.BLOCK - returns a new BlockEvent object
* Event.GET_APPLSTATE - returns a GetStateEvent object
* Event.STATE_RECEIVED- returns a SetStateEvent object
* Event.Exit - returns an ExitEvent object
* All other - return the actual Event object
* </PRE>
* @param evt - the event of which you want to extract the value
* @return the event value if it matches the select list,
* returns null if the event is null
* returns the event itself if a match (See above) can not be made of the event type
*/
static Object getEvent(Event evt) {
if(evt == null)
return null; // correct ?
switch(evt.getType()) {
case Event.MSG:
return evt.getArg();
case Event.VIEW_CHANGE:
return evt.getArg();
case Event.SUSPECT:
return new SuspectEvent(evt.getArg());
case Event.BLOCK:
return new BlockEvent();
case Event.GET_APPLSTATE:
StateTransferInfo info=(StateTransferInfo)evt.getArg();
return new GetStateEvent(info.target, info.state_id);
case Event.STATE_RECEIVED:
info=(StateTransferInfo)evt.getArg();
return new SetStateEvent(info.state, info.state_id);
case Event.EXIT:
return new ExitEvent();
default:
return evt;
}
}
/**
* Receives the state from the group and modifies the JChannel.state object<br>
* This method initializes the local state variable to null, and then sends the state
* event down the stack. It waits for a GET_STATE_OK event to bounce back
* @param evt the get state event, has to be of type Event.GET_STATE
* @param info Information about the state transfer, e.g. target member and timeout
* @return true of the state was received, false if the operation timed out
*/
private boolean _getState(Event evt, StateTransferInfo info) throws ChannelNotConnectedException, ChannelClosedException {
checkClosed();
checkNotConnected();
if(!state_transfer_supported) {
throw new IllegalStateException("fetching state will fail as state transfer is not supported. "
+ "Add one of the STATE_TRANSFER protocols to your protocol configuration");
}
state_promise.reset();
down(evt);
Boolean state_transfer_successfull=(Boolean)state_promise.getResult(info.timeout);
return state_transfer_successfull != null && state_transfer_successfull.booleanValue();
}
/**
* Disconnects and closes the channel.
* This method does the folloing things
* <ol>
* <li>Calls <code>this.disconnect</code> if the disconnect parameter is true
* <li>Calls <code>Queue.close</code> on mq if the close_mq parameter is true
* <li>Calls <code>ProtocolStack.stop</code> on the protocol stack
* <li>Calls <code>ProtocolStack.destroy</code> on the protocol stack
* <li>Sets the channel closed and channel connected flags to true and false
* <li>Notifies any channel listener of the channel close operation
* </ol>
*/
protected void _close(boolean disconnect, boolean close_mq) {
if(closed)
return;
if(disconnect)
disconnect(); // leave group if connected
if(close_mq) {
try {
if(mq != null)
mq.close(false); // closes and removes all messages
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
}
}
if(prot_stack != null) {
try {
prot_stack.stopStack();
prot_stack.destroy();
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("failed destroying the protocol stack", e);
}
}
closed=true;
connected=false;
notifyChannelClosed(this);
init(); // sets local_addr=null; changed March 18 2003 (bela) -- prevented successful rejoining
}
public final void closeMessageQueue(boolean flush_entries) {
if(mq != null)
mq.close(flush_entries);
}
/**
* Creates a separate thread to close the protocol stack.
* This is needed because the thread that called JChannel.up() with the EXIT event would
* hang waiting for up() to return, while up() actually tries to kill that very thread.
* This way, we return immediately and allow the thread to terminate.
*/
private void handleExit(Event evt) {
notifyChannelShunned();
if(closer != null && !closer.isAlive())
closer=null;
if(closer == null) {
if(log.isInfoEnabled())
log.info("received an EXIT event, will leave the channel");
closer=new CloserThread(evt);
closer.start();
}
}
/* ------------------------------- End of Private Methods ---------------------------------- */
class CloserThread extends Thread {
final Event evt;
final Thread t=null;
CloserThread(Event evt) {
super(Util.getGlobalThreadGroup(), "CloserThread");
this.evt=evt;
setDaemon(true);
}
public void run() {
try {
String old_channel_name=channel_name; // remember because close() will null it
if(log.isInfoEnabled())
log.info("closing the channel");
_close(false, false); // do not disconnect before closing channel, do not close mq (yet !)
if(up_handler != null)
up_handler.up(this.evt);
else {
try {
if(receiver == null)
mq.add(this.evt);
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("exception: " + ex);
}
}
if(mq != null) {
Util.sleep(500); // give the mq thread a bit of time to deliver EXIT to the application
try {
mq.close(false);
}
catch(Exception ex) {
}
}
if(auto_reconnect) {
try {
if(log.isInfoEnabled()) log.info("reconnecting to group " + old_channel_name);
open();
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("failure reopening channel: " + ex);
return;
}
try {
if(additional_data != null) {
// set previously set additional data
Map m=new HashMap(11);
m.put("additional_data", additional_data);
down(new Event(Event.CONFIG, m));
}
connect(old_channel_name);
notifyChannelReconnected(local_addr);
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("failure reconnecting to channel: " + ex);
return;
}
}
if(auto_getstate) {
if(log.isInfoEnabled())
log.info("fetching the state (auto_getstate=true)");
boolean rc=JChannel.this.getState(null, GET_STATE_DEFAULT_TIMEOUT);
if(log.isInfoEnabled()) {
if(rc)
log.info("state was retrieved successfully");
else
log.info("state transfer failed");
}
}
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("exception: " + ex);
}
finally {
closer=null;
}
}
}
}
|
changed default stack to fc-fast-minimalthreads
|
src/org/jgroups/JChannel.java
|
changed default stack to fc-fast-minimalthreads
|
<ide><path>rc/org/jgroups/JChannel.java
<del>// $Id: JChannel.java,v 1.67 2006/04/28 15:40:07 belaban Exp $
<add>// $Id: JChannel.java,v 1.68 2006/05/03 08:18:01 belaban Exp $
<ide>
<ide> package org.jgroups;
<ide>
<ide> * the construction of the stack will be aborted.
<ide> *
<ide> * @author Bela Ban
<del> * @version $Revision: 1.67 $
<add> * @version $Revision: 1.68 $
<ide> */
<ide> public class JChannel extends Channel {
<ide>
<ide> * The default protocol stack used by the default constructor.
<ide> */
<ide> public static final String DEFAULT_PROTOCOL_STACK=
<del> "UDP(mcast_addr=228.1.2.3;mcast_port=45566;ip_ttl=32):" +
<del> "PING(timeout=3000;num_initial_members=6):" +
<del> "FD(timeout=3000):" +
<del> "VERIFY_SUSPECT(timeout=1500):" +
<del> "pbcast.NAKACK(gc_lag=10;retransmit_timeout=600,1200,2400,4800):" +
<del> "UNICAST(timeout=600,1200,2400,4800):" +
<del> "pbcast.STABLE(desired_avg_gossip=10000):" +
<del> "FRAG:" +
<del> "pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;" +
<del> "shun=true;print_local_addr=true)";
<add> "UDP(down_thread=false;mcast_send_buf_size=640000;mcast_port=45566;discard_incompatible_packets=true;" +
<add> "ucast_recv_buf_size=20000000;mcast_addr=228.10.10.10;up_thread=false;loopback=false;" +
<add> "mcast_recv_buf_size=25000000;max_bundle_size=64000;max_bundle_timeout=30;" +
<add> "use_incoming_packet_handler=true;bind_addr=192.168.5.2;use_outgoing_packet_handler=false;" +
<add> "ucast_send_buf_size=640000;tos=16;enable_bundling=true;ip_ttl=2):" +
<add> "PING(timeout=2000;down_thread=false;num_initial_members=3;up_thread=false):" +
<add> "MERGE2(max_interval=10000;down_thread=false;min_interval=5000;up_thread=false):" +
<add> "FD(timeout=2000;max_tries=3;down_thread=false;up_thread=false):" +
<add> "VERIFY_SUSPECT(timeout=1500;down_thread=false):" +
<add> "pbcast.NAKACK(max_xmit_size=60000;down_thread=false;use_mcast_xmit=false;gc_lag=0;" +
<add> "discard_delivered_msgs=true;up_thread=false;retransmit_timeout=100,200,300,600,1200,2400,4800):" +
<add> "UNICAST(timeout=300,600,1200,2400,3600;down_thread=false;up_thread=false):" +
<add> "pbcast.STABLE(stability_delay=1000;desired_avg_gossip=50000;max_bytes=400000;down_thread=false;" +
<add> "up_thread=false):" +
<add> "VIEW_SYNC(down_thread=false;avg_send_interval=60000;up_thread=false):" +
<add> "pbcast.GMS(print_local_addr=true;join_timeout=3000;down_thread=false;" +
<add> "join_retry_timeout=2000;up_thread=false;shun=true):" +
<add> "FC(max_credits=2000000;down_thread=false;up_thread=false;min_threshold=0.10):" +
<add> "FRAG2(frag_size=60000;down_thread=false;up_thread=false):" +
<add> "pbcast.STATE_TRANSFER(down_thread=false;up_thread=false)";
<ide>
<ide> static final String FORCE_PROPS="force.properties";
<ide>
|
|
Java
|
apache-2.0
|
52ed69bae0780ea27008b494b0f74b68094af024
| 0 |
rapidoid/rapidoid,rapidoid/rapidoid,rapidoid/rapidoid,rapidoid/rapidoid
|
package org.rapidoid.gui;
/*
* #%L
* rapidoid-gui
* %%
* Copyright (C) 2014 - 2017 Nikolche Mihajlovski 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.
* #L%
*/
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.group.Manageable;
@Authors("Nikolche Mihajlovski")
@Since("5.3.0")
public class GUIActions extends GUI {
public static Object of(Object target) {
MultiWidget actions = multi();
if (target instanceof Manageable) {
Manageable manageable = (Manageable) target;
for (String action : manageable.actions()) {
actions.add(action(manageable, action));
}
}
return actions;
}
private static Btn action(final Manageable manageable, final String action) {
Btn btn = cmd(action, manageable.getClass().getSimpleName(), manageable.group().name(), manageable.id()).smallest();
final String cmd = btn.command();
btn.onClick(new Runnable() {
@Override
public void run() {
manageable.execute(cmd);
}
});
return btn;
}
}
|
rapidoid-gui/src/main/java/org/rapidoid/gui/GUIActions.java
|
package org.rapidoid.gui;
/*
* #%L
* rapidoid-gui
* %%
* Copyright (C) 2014 - 2017 Nikolche Mihajlovski 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.
* #L%
*/
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.group.Manageable;
@Authors("Nikolche Mihajlovski")
@Since("5.3.0")
public class GUIActions extends GUI {
public static Object of(Object target) {
MultiWidget actions = multi();
if (target instanceof Manageable) {
Manageable manageable = (Manageable) target;
for (String action : manageable.actions()) {
actions.add(action(manageable, action));
}
}
return actions;
}
private static Btn action(final Manageable manageable, final String action) {
Btn btn = cmd(action).smallest();
final String cmd = btn.command();
btn.onClick(new Runnable() {
@Override
public void run() {
manageable.execute(cmd);
}
});
return btn;
}
}
|
More specific GUI action identifier.
|
rapidoid-gui/src/main/java/org/rapidoid/gui/GUIActions.java
|
More specific GUI action identifier.
|
<ide><path>apidoid-gui/src/main/java/org/rapidoid/gui/GUIActions.java
<ide> }
<ide>
<ide> private static Btn action(final Manageable manageable, final String action) {
<del> Btn btn = cmd(action).smallest();
<add> Btn btn = cmd(action, manageable.getClass().getSimpleName(), manageable.group().name(), manageable.id()).smallest();
<ide>
<ide> final String cmd = btn.command();
<ide> btn.onClick(new Runnable() {
|
|
Java
|
apache-2.0
|
c5a2cfd301c2ea2db6481324820876ddf90a9e02
| 0 |
NeilRen/NEILREN4J,NeilRen/NEILREN4J
|
package com.neilren.neilren4j.common.config;
import java.util.Map;
import com.google.common.collect.Maps;
import com.neilren.neilren4j.common.utils.PropertiesLoader;
import com.neilren.neilren4j.common.utils.StringUtils;
/**
* 全局配置类
*
* @author NeilRen
* @version 2017-06-07
*/
public class Global {
/**
* 获取当前对象实例
*/
public static Global getInstance() {
return global;
}
/**
* 当前对象实例
*/
private static Global global = new Global();
/**
* 保存全局属性值
*/
private static Map<String, String> map = Maps.newHashMap();
/**
* 属性文件加载对象
*/
private static PropertiesLoader loader = new PropertiesLoader("neilren.properties");
/**
* 显示/隐藏
*/
public static final String SHOW = "1";
public static final String HIDE = "0";
/**
* 是/否
*/
public static final String YES = "1";
public static final String NO = "0";
/**
* 对/错
*/
public static final String TRUE = "true";
public static final String FALSE = "false";
/**
* 上传文件基础虚拟路径
*/
public static final String USERFILES_BASE_URL = "/userfiles/";
/**
* 获取属性文件
* @return
*/
public static PropertiesLoader getLoader(){
return loader;
}
/**
* 获取配置
*
* @see
*/
public static String getConfig(String key) {
String value = map.get(key);
if (value == null) {
value = loader.getProperty(key);
map.put(key, value != null ? value : StringUtils.EMPTY);
}
return value;
}
/**
* 获取管理端根路径
*/
public static String getAdminPath() {
return getConfig("adminPath");
}
/**
* 获取前端根路径
*/
public static String getFrontPath() {
return getConfig("frontPath");
}
/**
* 获取URL后缀
*/
public static String getUrlSuffix() {
return getConfig("urlSuffix");
}
/**
* 页面获取常量
*/
public static Object getConst(String field) {
try {
return Global.class.getField(field).get(null);
} catch (Exception e) {
// 异常代表无配置,这里什么也不做
}
return null;
}
/**
* Memcached缓存时间,秒
*/
public static int MemcachedExpire = 1800;
/**
* Yubico 的客户ID
*/
public static Integer YubicoClientId = Integer.parseInt(getConfig("Yubico.ClientId"));
/**
* Yubico 的key
*/
public static String YubicoClientSecretKey = getConfig("Yubico.ClientSecretKey");
}
|
src/main/java/com/neilren/neilren4j/common/config/Global.java
|
package com.neilren.neilren4j.common.config;
import java.util.Map;
import com.google.common.collect.Maps;
import com.neilren.neilren4j.common.utils.PropertiesLoader;
import com.neilren.neilren4j.common.utils.StringUtils;
/**
* 全局配置类
*
* @author NeilRen
* @version 2017-06-07
*/
public class Global {
/**
* 获取当前对象实例
*/
public static Global getInstance() {
return global;
}
/**
* 当前对象实例
*/
private static Global global = new Global();
/**
* 保存全局属性值
*/
private static Map<String, String> map = Maps.newHashMap();
/**
* 属性文件加载对象
*/
private static PropertiesLoader loader = new PropertiesLoader("neilren.properties");
/**
* 显示/隐藏
*/
public static final String SHOW = "1";
public static final String HIDE = "0";
/**
* 是/否
*/
public static final String YES = "1";
public static final String NO = "0";
/**
* 对/错
*/
public static final String TRUE = "true";
public static final String FALSE = "false";
/**
* 上传文件基础虚拟路径
*/
public static final String USERFILES_BASE_URL = "/userfiles/";
/**
* 获取属性文件
* @return
*/
public static PropertiesLoader getLoader(){
return loader;
}
/**
* 获取配置
*
* @see
*/
public static String getConfig(String key) {
String value = map.get(key);
if (value == null) {
value = loader.getProperty(key);
map.put(key, value != null ? value : StringUtils.EMPTY);
}
return value;
}
/**
* 获取管理端根路径
*/
public static String getAdminPath() {
return getConfig("adminPath");
}
/**
* 获取前端根路径
*/
public static String getFrontPath() {
return getConfig("frontPath");
}
/**
* 获取URL后缀
*/
public static String getUrlSuffix() {
return getConfig("urlSuffix");
}
/**
* 页面获取常量
*/
public static Object getConst(String field) {
try {
return Global.class.getField(field).get(null);
} catch (Exception e) {
// 异常代表无配置,这里什么也不做
}
return null;
}
/**
* Memcached缓存时间,秒
*/
public static int MemcachedExpire = 600;
/**
* Yubico 的客户ID
*/
public static Integer YubicoClientId = Integer.parseInt(getConfig("Yubico.ClientId"));
/**
* Yubico 的key
*/
public static String YubicoClientSecretKey = getConfig("Yubico.ClientSecretKey");
}
|
Memcache缓存时间更新为半个小时
|
src/main/java/com/neilren/neilren4j/common/config/Global.java
|
Memcache缓存时间更新为半个小时
|
<ide><path>rc/main/java/com/neilren/neilren4j/common/config/Global.java
<ide> /**
<ide> * Memcached缓存时间,秒
<ide> */
<del> public static int MemcachedExpire = 600;
<add> public static int MemcachedExpire = 1800;
<ide>
<ide> /**
<ide> * Yubico 的客户ID
|
|
Java
|
apache-2.0
|
d500ac433d828d9f1850ee1d4856a9a8de65959a
| 0 |
markcoble/droolsjbpm-integration,jesuino/droolsjbpm-integration,baldimir/droolsjbpm-integration,droolsjbpm/droolsjbpm-integration,baldimir/droolsjbpm-integration,jakubschwan/droolsjbpm-integration,winklerm/droolsjbpm-integration,winklerm/droolsjbpm-integration,reynoldsm88/droolsjbpm-integration,jesuino/droolsjbpm-integration,reynoldsm88/droolsjbpm-integration,droolsjbpm/droolsjbpm-integration,baldimir/droolsjbpm-integration,jakubschwan/droolsjbpm-integration,droolsjbpm/droolsjbpm-integration,baldimir/droolsjbpm-integration,markcoble/droolsjbpm-integration,winklerm/droolsjbpm-integration,jakubschwan/droolsjbpm-integration,droolsjbpm/droolsjbpm-integration,winklerm/droolsjbpm-integration,reynoldsm88/droolsjbpm-integration,jesuino/droolsjbpm-integration,jakubschwan/droolsjbpm-integration,markcoble/droolsjbpm-integration,jesuino/droolsjbpm-integration,reynoldsm88/droolsjbpm-integration,markcoble/droolsjbpm-integration
|
kie-infinispan/drools-infinispan-persistence/src/test/java/org/drools/persistence/command/KBuilderBatchExecutionPersistenceTest.java
|
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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.drools.persistence.command;
import static org.drools.persistence.util.PersistenceUtil.DROOLS_PERSISTENCE_UNIT_NAME;
import static org.drools.persistence.util.PersistenceUtil.cleanUp;
import static org.drools.persistence.util.PersistenceUtil.createEnvironment;
import java.util.HashMap;
import org.drools.compiler.command.KBuilderBatchExecutionTest;
import org.drools.core.impl.KnowledgeBaseFactory;
import org.drools.persistence.util.PersistenceUtil;
import org.junit.After;
import org.kie.internal.persistence.infinispan.InfinispanKnowledgeService;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSessionConfiguration;
import org.kie.internal.runtime.StatefulKnowledgeSession;
public class KBuilderBatchExecutionPersistenceTest extends KBuilderBatchExecutionTest {
private HashMap<String, Object> context;
@After
public void cleanUpPersistence() throws Exception {
disposeKSession();
cleanUp(context);
context = null;
}
protected StatefulKnowledgeSession createKnowledgeSession(KieBase kbase) {
if( context == null ) {
context = PersistenceUtil.setupWithPoolingDataSource(DROOLS_PERSISTENCE_UNIT_NAME);
}
KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
return InfinispanKnowledgeService.newStatefulKnowledgeSession(kbase, ksconf, createEnvironment(context));
}
}
|
[DROOLS-1583] remove redundant methods and review locks on KnowledgeBaseImpl (#1002)
|
kie-infinispan/drools-infinispan-persistence/src/test/java/org/drools/persistence/command/KBuilderBatchExecutionPersistenceTest.java
|
[DROOLS-1583] remove redundant methods and review locks on KnowledgeBaseImpl (#1002)
|
<ide><path>ie-infinispan/drools-infinispan-persistence/src/test/java/org/drools/persistence/command/KBuilderBatchExecutionPersistenceTest.java
<del>/*
<del> * Copyright 2015 Red Hat, Inc. and/or its affiliates.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del>*/
<del>
<del>package org.drools.persistence.command;
<del>
<del>import static org.drools.persistence.util.PersistenceUtil.DROOLS_PERSISTENCE_UNIT_NAME;
<del>import static org.drools.persistence.util.PersistenceUtil.cleanUp;
<del>import static org.drools.persistence.util.PersistenceUtil.createEnvironment;
<del>
<del>import java.util.HashMap;
<del>
<del>import org.drools.compiler.command.KBuilderBatchExecutionTest;
<del>import org.drools.core.impl.KnowledgeBaseFactory;
<del>import org.drools.persistence.util.PersistenceUtil;
<del>import org.junit.After;
<del>import org.kie.internal.persistence.infinispan.InfinispanKnowledgeService;
<del>import org.kie.api.KieBase;
<del>import org.kie.api.runtime.KieSessionConfiguration;
<del>import org.kie.internal.runtime.StatefulKnowledgeSession;
<del>
<del>public class KBuilderBatchExecutionPersistenceTest extends KBuilderBatchExecutionTest {
<del>
<del> private HashMap<String, Object> context;
<del>
<del> @After
<del> public void cleanUpPersistence() throws Exception {
<del> disposeKSession();
<del> cleanUp(context);
<del> context = null;
<del> }
<del>
<del> protected StatefulKnowledgeSession createKnowledgeSession(KieBase kbase) {
<del> if( context == null ) {
<del> context = PersistenceUtil.setupWithPoolingDataSource(DROOLS_PERSISTENCE_UNIT_NAME);
<del> }
<del> KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
<del> return InfinispanKnowledgeService.newStatefulKnowledgeSession(kbase, ksconf, createEnvironment(context));
<del> }
<del>
<del>}
|
||
JavaScript
|
mit
|
e68569da1f4a3b9aad46c93c116e9e215cadc0bc
| 0 |
materialsproject/MPContribs,materialsproject/MPContribs,materialsproject/MPContribs,materialsproject/MPContribs
|
import Handsontable from "handsontable";
import get from "lodash/get";
import set from "lodash/set";
import sha1 from "js-sha1";
import hljs from "highlight-core";
import python from "highlight-languages";
hljs.registerLanguage('python', python);
hljs.highlightAll();
$('a[name="read_more"]').on('click', function() {
$(this).hide().siblings('[name="read_more"]').removeClass("is-hidden").show();
});
function get_column_config(col) {
var config = {readOnly: true};
var name = col.split(' ')[0];
if (col.endsWith(']')) { name += '.value'; }
config.data = name;
return config;
}
const project = $('[name=table]').first().data('project');
const table_id = 'table_' + project;
const objectid_regex = /^[a-f\d]{24}$/i;
const data_cols = $('#'+table_id).data('columns');
const headers = data_cols ? data_cols.split(',') : [];
const columns = $.map(headers, get_column_config);
const fields = columns.flatMap((conf) => {
var ret = [conf.data];
if (conf.data.endsWith('.value')) {
ret.push(conf.data.replace(/\.value/g, '.error'))
}
return ret;
});
const default_limit = 20;
const default_query = {
_fields: fields.join(','), project: project, _skip: 0, _limit: default_limit
};
const rowHeight = 23;
var query = $.extend(true, {}, default_query);
var total_count;
function get_data() {
$('#table_filter').addClass('is-loading');
const url = window.api['host'] + 'contributions/';
return $.get({
contentType: "json", dataType: "json", url: url, headers:
window.api['headers'], data: query
});
}
function make_url(text, href) {
var url = $('<a/>', {href: href, target: '_blank', rel: "noopener noreferrer"});
$(url).text(text);
return url;
}
function make_url_cell(td, text, href) {
Handsontable.dom.empty(td);
var url = make_url(text, href);
$(td).addClass('htCenter').addClass('htMiddle').append(url);
}
function urlRenderer(instance, td, row, col, prop, value, cellProperties) {
if (Array.isArray(value)) {
Handsontable.renderers.HtmlRenderer.apply(this, arguments);
Handsontable.dom.empty(td);
var field = $('<div/>', {'class': 'field is-grouped'});
$.each(value, function(i, v) {
var control = $('<div/>', {'class': 'control'});
var tags = $('<div/>', {'class': 'tags has-addons'});
var tag1 = $('<a/>', {'class': 'tag is-link is-light', text: v['name']});
tag1.click(function(e) {
var url = '/contributions/show_component/' + v['id'];
$.get({url: url}).done(function(response) {
var modal = $("#component-modal");
var content = modal.children(".modal-content").first();
content.html(response);
modal.addClass("is-active");
});
});
var href = '/contributions/component/' + v['id'];
var tag2 = $('<a/>', {'class': 'tag', href: href});
var span = $('<span/>', {'class': 'icon'});
var icon = $('<i/>', {'class': 'fas fa-download'});
$(span).append(icon);
$(tag2).append(span);
$(tags).append(tag1, tag2);
$(control).append(tags);
$(field).append(control);
});
$(td).addClass('htCenter').addClass('htMiddle').append(field);
} else {
value = (value === null || typeof value === 'undefined') ? '' : String(value);
var basename = value.split('/').pop();
if (value.startsWith('http://') || value.startsWith('https://')) {
Handsontable.renderers.HtmlRenderer.apply(this, arguments);
Handsontable.dom.empty(td);
const url = new URL(value);
var tag = $('<a/>', {
'class': 'tag is-link is-light', href: value,
target: "_blank", rel: "noopener noreferrer"
});
var span = $('<span/>', {text: url.hostname});
var span_icon = $('<span/>', {'class': 'icon'});
var icon = $('<i/>', {'class': 'fas fa-external-link-alt'});
$(span_icon).append(icon);
$(tag).append(span_icon);
$(tag).append(span);
$(td).addClass('htCenter').addClass('htMiddle').append(tag);
} else if (basename.startsWith('mp-') || basename.startsWith('mvc-')) {
Handsontable.renderers.HtmlRenderer.apply(this, arguments);
var href = 'https://materialsproject.org/materials/' + basename;
make_url_cell(td, basename, href);
} else if (objectid_regex.test(basename)) {
Handsontable.renderers.HtmlRenderer.apply(this, arguments);
Handsontable.dom.empty(td);
var href = '/contributions/' + basename;
var tag;
if (prop === "id") {
tag = $('<a/>', {'class': 'tag is-link is-light', href: href});
} else {
tag = $('<p/>', {'class': 'tag is-light'});
}
var span = $('<span/>', {text: basename.slice(-7)});
var span_icon = $('<span/>', {'class': 'icon'});
var icon = $('<i/>', {'class': 'fas fa-file-alt'});
$(span_icon).append(icon);
$(tag).append(span_icon);
$(tag).append(span);
$(td).addClass('htCenter').addClass('htMiddle').append(tag);
} else {
Handsontable.renderers.TextRenderer.apply(this, arguments);
}
}
}
function load_data(dom) {
get_data().done(function(response) {
total_count = response.total_count;
$('#total_count').html('<b>' + total_count + '</b>');
$('#total_count').data('count', total_count);
var rlen = response.data.length;
for (var r = 0; r < rlen; r++) {
var doc = response['data'][r];
for (var c = 0; c < columns.length; c++) {
var col = columns[c].data;
if (col.endsWith('.value')) {
var v = get(doc, col, '');
if (v) {
var e = get(doc, col.replace(/\.value/g, '.error'), '');
if (e) { set(doc, col, v + "±" + e); }
}
}
}
}
dom.loadData(response.data);
if (total_count > default_limit) {
const height = response.data.length * rowHeight;
dom.updateSettings({height: height});
}
$('#table_filter').removeClass('is-loading');
$('#table_delete').removeClass('is-loading');
$('[name=table]').first().removeClass("is-invisible");
});
}
var nestedHeadersPrep = [];
const levels = $.map(headers, function(h) { return h.split('.').length; });
const depth = Math.max.apply(Math, levels);
for (var i = 0; i < depth; i++) { nestedHeadersPrep.push([]); }
$.each(headers, function(i, h) {
const hs = h.split('.');
const deep = hs.length;
for (var d = 0; d < depth-deep; d++) { nestedHeadersPrep[d].push(' '); }
$.each(hs, function(j, l) { nestedHeadersPrep[j+depth-deep].push(l); });
});
var nestedHeaders = [];
$.each(nestedHeadersPrep, function(r, row) {
var new_row = [];
for (var i = 0; i < row.length; i++) {
if (!new_row.length || row[i] !== new_row[new_row.length-1]['label']) {
new_row.push({label: row[i], colspan: 0});
}
new_row[new_row.length-1]['colspan']++;
}
nestedHeaders.push(new_row);
});
var hot;
const container = document.getElementById(table_id);
if (container) {
hot = new Handsontable(container, {
colHeaders: headers, columns: columns, rowHeaders: false,
hiddenColumns: true, nestedHeaders: nestedHeaders, //rowHeaderWidth: 75,
width: '100%', stretchH: 'all', rowHeights: rowHeight,
preventOverflow: 'horizontal',
licenseKey: 'non-commercial-and-evaluation',
disableVisualSelection: true,
className: "htCenter htMiddle",
persistentState: true, columnSorting: true,
//manualColumnMove: true,
manualColumnResize: true, collapsibleColumns: true,
beforeColumnSort: function(currentSortConfig, destinationSortConfigs) {
const columnSortPlugin = this.getPlugin('columnSorting');
columnSortPlugin.setSortConfig(destinationSortConfigs);
const num = destinationSortConfigs[0].column;
query['_order_by'] = columns[num].data.replace(/\./g, '__');
query['order'] = destinationSortConfigs[0].sortOrder;
query['_skip'] = 0;
load_data(this);
return false; // block default sort
},
cells: function (row, col) { return {renderer: urlRenderer}; },
afterScrollVertically: function() {
const plugin = this.getPlugin('AutoRowSize');
const last = plugin.getLastVisibleRow() + 1;
const nrows = this.countRows();
if (last === nrows && last > query._skip && last < total_count) {
const ht = this;
query['_skip'] = last;
get_data().done(function(response) {
var rlen = response.data.length;
ht.alter('insert_row', last, rlen);
var update = [];
for (var r = 0; r < rlen; r++) {
var doc = response['data'][r];
for (var c = 0; c < columns.length; c++) {
var col = columns[c].data;
var v = get(doc, col, '');
if (v && col.endsWith('.value')) {
var e = get(doc, col.replace(/\.value/g, '.error'), '');
if (e) { v += "±" + e; }
}
update.push([last+r, c, v]);
}
}
ht.setDataAtCell(update);
$('#table_filter').removeClass('is-loading');
});
}
}
});
load_data(hot);
hot.addHook('afterOnCellMouseOver', function(e, coords, TD) {
var row = coords["row"];
if (row > 0) { $(TD).parent().addClass("htHover"); }
});
hot.addHook('afterOnCellMouseOut', function(e, coords, TD) {
var row = coords["row"];
if (row > 0) { $(TD).parent().removeClass("htHover"); }
});
}
function toggle_columns(doms) {
var plugin = hot.getPlugin('hiddenColumns');
$(doms).each(function(idx, dom) {
var id_split = $(dom).attr('id').split('_');
var col_idx = parseInt(id_split[id_split.length-1]);
if ($(dom).prop("checked")) { plugin.showColumn(col_idx); }
else { plugin.hideColumn(col_idx); }
})
hot.render();
}
$('#table_filter').on('click', function(e) {
reset_table_download();
var kw = $('#table_keyword').val();
if (kw) {
$(this).addClass('is-loading');
e.preventDefault();
var sel = $( "#table_select option:selected" ).text();
var key = sel.replace(/\./g, '__') + '__contains';
query[key] = kw;
query['_skip'] = 0;
toggle_columns("input[name=column_manager_item]:checked");
load_data(hot);
}
});
$('#table_keyword').keypress(function(e) {
if (e.which == 13) { $('#table_filter').click(); }
});
$('#table_delete').click(function(e) {
reset_table_download();
$(this).addClass('is-loading');
e.preventDefault();
$('#table_keyword').val('');
query = $.extend(true, {}, default_query);
toggle_columns("input[name=column_manager_item]:checked");
load_data(hot);
});
$('#table_select').change(function(e) {
reset_table_download();
$('#table_keyword').val('');
});
$('input[name=column_manager_item]').click(function() {
reset_table_download();
var n = $("input[name=column_manager_item]:checked").length;
$('#column_manager_count').text(n);
toggle_columns(this);
});
$('#column_manager_select_all').click(function() {
reset_table_download();
var plugin = hot.getPlugin('hiddenColumns');
var items = $("input[name=column_manager_item]");
if ($(this).prop('checked')) {
var cols = [];
$(items).each(function(idx) {
if (!$(this).prop("checked") && !$(this).prop('disabled')) {
$(this).prop("checked", true);
cols.push(idx);
}
});
plugin.showColumns(cols);
$('#column_manager_count').text(items.length);
} else {
var cols = [];
$(items).each(function(idx) {
if ($(this).prop("checked") && !$(this).prop('disabled')) {
$(this).prop("checked", false);
cols.push(idx);
}
});
plugin.hideColumns(cols);
var n = $("input[name=column_manager_item]:disabled").length;
$('#column_manager_count').text(n);
}
hot.render();
});
$('.modal-close').click(function() {
$(this).parent().removeClass('is-active');
});
function prep_download(query, prefix) {
const url = "/contributions/download/create";
$.get({
contentType: "json", dataType: "json", url: url, data: query
}).done(function(response) {
if ("error" in response) {
alert(response["error"]);
} else if (response["progress"] < 1) {
const progress = (response["progress"] * 100).toFixed(0);
$("#" + prefix + "download_progress").text(progress + "%");
prep_download(query, prefix);
} else {
const href = "/contributions/download/get?" + $.param(query);
$("#" + prefix + "get_download").attr("href", href).removeClass("is-hidden");
const fmt = query["format"];
$("#" + prefix + "download_" + fmt).removeClass('is-loading').addClass("is-hidden");
$("#" + prefix + "download_progress").addClass("is-hidden");
}
});
}
$('a[name="download"]').click(function(e) {
$('a[name="download"]').addClass("is-hidden");
$(this).addClass('is-loading').removeClass("is-hidden");
$("#download_progress").text("0%").removeClass("is-hidden");
const fmt = $(this).data('format');
const include = $('input[name="include"]:checked').map(function() {
return $(this).val();
}).get().join(',');
var download_query = {"format": fmt, "project": project};
if (include) { download_query["include"] = include; }
prep_download(download_query, "");
});
function reset_download() {
$('a[name="download"]').removeClass("is-hidden");
$("#download_progress").addClass("is-hidden");
$("#get_download").addClass("is-hidden");
}
$('input[name="include"]').click(function() { reset_download(); });
$('#get_download').click(function() { reset_download(); });
function reset_table_download() {
$('a[name="table_download"]').removeClass("is-hidden");
$("#table_download_progress").addClass("is-hidden");
$("#table_get_download").addClass("is-hidden");
}
$('a[name=table_download]').click(function(e) {
$('a[name="table_download"]').addClass("is-hidden");
$(this).addClass('is-loading').removeClass("is-hidden");
$("#table_download_progress").text("0%").removeClass("is-hidden");
const fmt = $(this).data('format');
var download_query = $.extend(true, {format: fmt}, query);
download_query['_fields'] = $("input[name=column_manager_item]:checked").map(function() {
var id_split = $(this).attr('id').split('_');
return get_column_config(id_split[3]).data;
}).get().join(',');
delete download_query['_skip'];
delete download_query['_limit'];
prep_download(download_query, "table_");
});
$("#table_get_download").click(function() { reset_table_download(); });
//if ($("#graph").length && project !== 'redox_thermo_csp') {
// render_overview(project, grid);
//}
//$("#graph").html('<b>Default graphs will be back soon</b>');
//if ($("#graph_custom").length) {
// import(/* webpackChunkName: "project" */ `${project}/explorer/assets/index.js`)
// .then(function() {$("#graph_custom").html('<b>Custom graphs will be back in January 2020</b>');})
// .catch(function(err) { console.log(err); });
//}
//$("#graph_custom").html('<b>Custom graphs will be back soon</b>');
|
mpcontribs-portal/mpcontribs/portal/assets/js/landingpage.js
|
import Handsontable from "handsontable";
import get from "lodash/get";
import set from "lodash/set";
import sha1 from "js-sha1";
import hljs from "highlight-core";
import python from "highlight-languages";
hljs.registerLanguage('python', python);
hljs.highlightAll();
$('a[name="read_more"]').on('click', function() {
$(this).hide().siblings('[name="read_more"]').removeClass("is-hidden").show();
});
function get_column_config(col) {
var config = {readOnly: true};
var name = col.split(' ')[0];
if (col.endsWith(']')) { name += '.value'; }
config.data = name;
return config;
}
const project = $('[name=table]').first().data('project');
const table_id = 'table_' + project;
const objectid_regex = /^[a-f\d]{24}$/i;
const data_cols = $('#'+table_id).data('columns');
const headers = data_cols ? data_cols.split(',') : [];
const columns = $.map(headers, get_column_config);
const fields = columns.flatMap((conf) => {
var ret = [conf.data];
if (conf.data.endsWith('.value')) {
ret.push(conf.data.replace(/\.value/g, '.error'))
}
return ret;
});
const default_limit = 20;
const default_query = {
_fields: fields.join(','), project: project, _skip: 0, _limit: default_limit
};
const rowHeight = 23;
var query = $.extend(true, {}, default_query);
var total_count;
function get_data() {
$('#table_filter').addClass('is-loading');
const url = window.api['host'] + 'contributions/';
return $.get({
contentType: "json", dataType: "json", url: url, headers:
window.api['headers'], data: query
});
}
function make_url(text, href) {
var url = $('<a/>', {href: href, target: '_blank', rel: "noopener noreferrer"});
$(url).text(text);
return url;
}
function make_url_cell(td, text, href) {
Handsontable.dom.empty(td);
var url = make_url(text, href);
$(td).addClass('htCenter').addClass('htMiddle').append(url);
}
function urlRenderer(instance, td, row, col, prop, value, cellProperties) {
if (Array.isArray(value)) {
Handsontable.renderers.HtmlRenderer.apply(this, arguments);
Handsontable.dom.empty(td);
var field = $('<div/>', {'class': 'field is-grouped'});
$.each(value, function(i, v) {
var control = $('<div/>', {'class': 'control'});
var tags = $('<div/>', {'class': 'tags has-addons'});
var tag1 = $('<a/>', {'class': 'tag is-link is-light', text: v['name']});
tag1.click(function(e) {
var url = '/contributions/show_component/' + v['id'];
$.get({url: url}).done(function(response) {
var modal = $("#component-modal");
var content = modal.children(".modal-content").first();
content.html(response);
modal.addClass("is-active");
});
});
var href = '/contributions/component/' + v['id'];
var tag2 = $('<a/>', {'class': 'tag', href: href});
var span = $('<span/>', {'class': 'icon'});
var icon = $('<i/>', {'class': 'fas fa-download'});
$(span).append(icon);
$(tag2).append(span);
$(tags).append(tag1, tag2);
$(control).append(tags);
$(field).append(control);
});
$(td).addClass('htCenter').addClass('htMiddle').append(field);
} else {
value = (value === null || typeof value === 'undefined') ? '' : String(value);
var basename = value.split('/').pop();
if (value.startsWith('http://') || value.startsWith('https://')) {
Handsontable.renderers.HtmlRenderer.apply(this, arguments);
Handsontable.dom.empty(td);
const url = new URL(value);
var tag = $('<a/>', {
'class': 'tag is-link is-light', href: value,
target: "_blank", rel: "noopener noreferrer"
});
var span = $('<span/>', {text: url.hostname});
var span_icon = $('<span/>', {'class': 'icon'});
var icon = $('<i/>', {'class': 'fas fa-external-link-alt'});
$(span_icon).append(icon);
$(tag).append(span_icon);
$(tag).append(span);
$(td).addClass('htCenter').addClass('htMiddle').append(tag);
} else if (basename.startsWith('mp-') || basename.startsWith('mvc-')) {
Handsontable.renderers.HtmlRenderer.apply(this, arguments);
var href = 'https://materialsproject.org/materials/' + basename;
make_url_cell(td, basename, href);
} else if (objectid_regex.test(basename)) {
Handsontable.renderers.HtmlRenderer.apply(this, arguments);
Handsontable.dom.empty(td);
var href = '/contributions/' + basename;
var tag;
if (prop === "id") {
tag = $('<a/>', {'class': 'tag is-link is-light', href: href});
} else {
tag = $('<p/>', {'class': 'tag is-light'});
}
var span = $('<span/>', {text: basename.slice(-7)});
var span_icon = $('<span/>', {'class': 'icon'});
var icon = $('<i/>', {'class': 'fas fa-file-alt'});
$(span_icon).append(icon);
$(tag).append(span_icon);
$(tag).append(span);
$(td).addClass('htCenter').addClass('htMiddle').append(tag);
} else {
Handsontable.renderers.TextRenderer.apply(this, arguments);
}
}
}
function load_data(dom) {
get_data().done(function(response) {
total_count = response.total_count;
$('#total_count').html('<b>' + total_count + '</b>');
$('#total_count').data('count', total_count);
var rlen = response.data.length;
for (var r = 0; r < rlen; r++) {
var doc = response['data'][r];
for (var c = 0; c < columns.length; c++) {
var col = columns[c].data;
if (col.endsWith('.value')) {
var v = get(doc, col, '');
if (v) {
var e = get(doc, col.replace(/\.value/g, '.error'), '');
if (e) { set(doc, col, v + "±" + e); }
}
}
}
}
dom.loadData(response.data);
if (total_count > default_limit) {
const height = response.data.length * rowHeight;
dom.updateSettings({height: height});
}
$('#table_filter').removeClass('is-loading');
$('#table_delete').removeClass('is-loading');
$('[name=table]').first().removeClass("is-invisible");
});
}
var nestedHeadersPrep = [];
const levels = $.map(headers, function(h) { return h.split('.').length; });
const depth = Math.max.apply(Math, levels);
for (var i = 0; i < depth; i++) { nestedHeadersPrep.push([]); }
$.each(headers, function(i, h) {
const hs = h.split('.');
const deep = hs.length;
for (var d = 0; d < depth-deep; d++) { nestedHeadersPrep[d].push(' '); }
$.each(hs, function(j, l) { nestedHeadersPrep[j+depth-deep].push(l); });
});
var nestedHeaders = [];
$.each(nestedHeadersPrep, function(r, row) {
var new_row = [];
for (var i = 0; i < row.length; i++) {
if (!new_row.length || row[i] !== new_row[new_row.length-1]['label']) {
new_row.push({label: row[i], colspan: 0});
}
new_row[new_row.length-1]['colspan']++;
}
nestedHeaders.push(new_row);
});
var hot;
const container = document.getElementById(table_id);
if (container) {
hot = new Handsontable(container, {
colHeaders: headers, columns: columns, rowHeaders: false,
hiddenColumns: true, nestedHeaders: nestedHeaders, //rowHeaderWidth: 75,
width: '100%', stretchH: 'all', rowHeights: rowHeight,
preventOverflow: 'horizontal',
licenseKey: 'non-commercial-and-evaluation',
disableVisualSelection: true,
className: "htCenter htMiddle",
persistentState: true, columnSorting: true,
//manualColumnMove: true,
manualColumnResize: true, collapsibleColumns: true,
beforeColumnSort: function(currentSortConfig, destinationSortConfigs) {
const columnSortPlugin = this.getPlugin('columnSorting');
columnSortPlugin.setSortConfig(destinationSortConfigs);
const num = destinationSortConfigs[0].column;
query['_order_by'] = columns[num].data.replace(/\./g, '__');
query['order'] = destinationSortConfigs[0].sortOrder;
query['_skip'] = 0;
load_data(this);
return false; // block default sort
},
cells: function (row, col) { return {renderer: urlRenderer}; },
afterScrollVertically: function() {
const plugin = this.getPlugin('AutoRowSize');
const last = plugin.getLastVisibleRow() + 1;
const nrows = this.countRows();
if (last === nrows && last > query._skip && last < total_count) {
const ht = this;
query['_skip'] = last;
get_data().done(function(response) {
var rlen = response.data.length;
ht.alter('insert_row', last, rlen);
var update = [];
for (var r = 0; r < rlen; r++) {
var doc = response['data'][r];
for (var c = 0; c < columns.length; c++) {
var col = columns[c].data;
var v = get(doc, col, '');
if (v && col.endsWith('.value')) {
var e = get(doc, col.replace(/\.value/g, '.error'), '');
if (e) { v += "±" + e; }
}
update.push([last+r, c, v]);
}
}
ht.setDataAtCell(update);
$('#table_filter').removeClass('is-loading');
});
}
}
});
load_data(hot);
}
function toggle_columns(doms) {
var plugin = hot.getPlugin('hiddenColumns');
$(doms).each(function(idx, dom) {
var id_split = $(dom).attr('id').split('_');
var col_idx = parseInt(id_split[id_split.length-1]);
if ($(dom).prop("checked")) { plugin.showColumn(col_idx); }
else { plugin.hideColumn(col_idx); }
})
hot.render();
}
$('#table_filter').on('click', function(e) {
reset_table_download();
var kw = $('#table_keyword').val();
if (kw) {
$(this).addClass('is-loading');
e.preventDefault();
var sel = $( "#table_select option:selected" ).text();
var key = sel.replace(/\./g, '__') + '__contains';
query[key] = kw;
query['_skip'] = 0;
toggle_columns("input[name=column_manager_item]:checked");
load_data(hot);
}
});
$('#table_keyword').keypress(function(e) {
if (e.which == 13) { $('#table_filter').click(); }
});
$('#table_delete').click(function(e) {
reset_table_download();
$(this).addClass('is-loading');
e.preventDefault();
$('#table_keyword').val('');
query = $.extend(true, {}, default_query);
toggle_columns("input[name=column_manager_item]:checked");
load_data(hot);
});
$('#table_select').change(function(e) {
reset_table_download();
$('#table_keyword').val('');
});
$('input[name=column_manager_item]').click(function() {
reset_table_download();
var n = $("input[name=column_manager_item]:checked").length;
$('#column_manager_count').text(n);
toggle_columns(this);
});
$('#column_manager_select_all').click(function() {
reset_table_download();
var plugin = hot.getPlugin('hiddenColumns');
var items = $("input[name=column_manager_item]");
if ($(this).prop('checked')) {
var cols = [];
$(items).each(function(idx) {
if (!$(this).prop("checked") && !$(this).prop('disabled')) {
$(this).prop("checked", true);
cols.push(idx);
}
});
plugin.showColumns(cols);
$('#column_manager_count').text(items.length);
} else {
var cols = [];
$(items).each(function(idx) {
if ($(this).prop("checked") && !$(this).prop('disabled')) {
$(this).prop("checked", false);
cols.push(idx);
}
});
plugin.hideColumns(cols);
var n = $("input[name=column_manager_item]:disabled").length;
$('#column_manager_count').text(n);
}
hot.render();
});
$('.modal-close').click(function() {
$(this).parent().removeClass('is-active');
});
function prep_download(query, prefix) {
const url = "/contributions/download/create";
$.get({
contentType: "json", dataType: "json", url: url, data: query
}).done(function(response) {
if ("error" in response) {
alert(response["error"]);
} else if (response["progress"] < 1) {
const progress = (response["progress"] * 100).toFixed(0);
$("#" + prefix + "download_progress").text(progress + "%");
prep_download(query, prefix);
} else {
const href = "/contributions/download/get?" + $.param(query);
$("#" + prefix + "get_download").attr("href", href).removeClass("is-hidden");
const fmt = query["format"];
$("#" + prefix + "download_" + fmt).removeClass('is-loading').addClass("is-hidden");
$("#" + prefix + "download_progress").addClass("is-hidden");
}
});
}
$('a[name="download"]').click(function(e) {
$('a[name="download"]').addClass("is-hidden");
$(this).addClass('is-loading').removeClass("is-hidden");
$("#download_progress").text("0%").removeClass("is-hidden");
const fmt = $(this).data('format');
const include = $('input[name="include"]:checked').map(function() {
return $(this).val();
}).get().join(',');
var download_query = {"format": fmt, "project": project};
if (include) { download_query["include"] = include; }
prep_download(download_query, "");
});
function reset_download() {
$('a[name="download"]').removeClass("is-hidden");
$("#download_progress").addClass("is-hidden");
$("#get_download").addClass("is-hidden");
}
$('input[name="include"]').click(function() { reset_download(); });
$('#get_download').click(function() { reset_download(); });
function reset_table_download() {
$('a[name="table_download"]').removeClass("is-hidden");
$("#table_download_progress").addClass("is-hidden");
$("#table_get_download").addClass("is-hidden");
}
$('a[name=table_download]').click(function(e) {
$('a[name="table_download"]').addClass("is-hidden");
$(this).addClass('is-loading').removeClass("is-hidden");
$("#table_download_progress").text("0%").removeClass("is-hidden");
const fmt = $(this).data('format');
var download_query = $.extend(true, {format: fmt}, query);
download_query['_fields'] = $("input[name=column_manager_item]:checked").map(function() {
var id_split = $(this).attr('id').split('_');
return get_column_config(id_split[3]).data;
}).get().join(',');
delete download_query['_skip'];
delete download_query['_limit'];
prep_download(download_query, "table_");
});
$("#table_get_download").click(function() { reset_table_download(); });
//if ($("#graph").length && project !== 'redox_thermo_csp') {
// render_overview(project, grid);
//}
//$("#graph").html('<b>Default graphs will be back soon</b>');
//if ($("#graph_custom").length) {
// import(/* webpackChunkName: "project" */ `${project}/explorer/assets/index.js`)
// .then(function() {$("#graph_custom").html('<b>Custom graphs will be back in January 2020</b>');})
// .catch(function(err) { console.log(err); });
//}
//$("#graph_custom").html('<b>Custom graphs will be back soon</b>');
|
portal: row hover on landingpages
|
mpcontribs-portal/mpcontribs/portal/assets/js/landingpage.js
|
portal: row hover on landingpages
|
<ide><path>pcontribs-portal/mpcontribs/portal/assets/js/landingpage.js
<ide> }
<ide> }
<ide> });
<del>
<ide> load_data(hot);
<add> hot.addHook('afterOnCellMouseOver', function(e, coords, TD) {
<add> var row = coords["row"];
<add> if (row > 0) { $(TD).parent().addClass("htHover"); }
<add> });
<add> hot.addHook('afterOnCellMouseOut', function(e, coords, TD) {
<add> var row = coords["row"];
<add> if (row > 0) { $(TD).parent().removeClass("htHover"); }
<add> });
<ide> }
<ide>
<ide> function toggle_columns(doms) {
|
|
JavaScript
|
apache-2.0
|
dab7e0efb5aea60d231f576745061c476c0822af
| 0 |
googlearchive/npm-publish-scripts,googlearchive/npm-publish-scripts,googlearchive/npm-publish-scripts,googlearchive/npm-publish-scripts
|
/**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
'use strict';
const fs = require('fs');
const path = require('path');
const minimist = require('minimist');
const chokidar = require('chokidar');
const fse = require('fs-extra');
const spawn = require('child_process').spawn;
const spawnSync = require('child_process').spawnSync;
const semver = require('semver');
const inquirer = require('inquirer');
const gitBranch = require('git-branch');
const updateNotifier = require('update-notifier');
const glob = require('glob');
const exitLifeCycle = require('./exit-lifecycle');
const logHelper = require('./log-helper');
const strings = require('./strings');
const packageInfo = require('../../../package.json');
const REFERENCE_DOCS_DIR = 'reference-docs';
/**
* The module that performs the logic of the CLI.
*/
class NPMPublishScriptCLI {
/**
* Initialises the class.
*/
constructor() {
this._spawnedProcesses = [];
const notifier = updateNotifier({pkg: packageInfo});
notifier.notify();
}
/**
* This method is the entry method that kicks of logic and expects the
* output of minimist module.
* @param {object} argv This is the output minimist which parses the command
* line arguments.
* @return {Promise} Returns a promise for the given task.
*/
argv(argv) {
const cliArgs = minimist(argv);
if (cliArgs._.length > 0) {
// We have a command
return this.handleCommand(cliArgs._[0], cliArgs._.splice(1), cliArgs)
.then(() => {
process.exit(0);
})
.catch(() => {
process.exit(1);
});
} else {
// we have a flag only request
return this.handleFlag(cliArgs)
.then(() => {
process.exit(0);
})
.catch(() => {
process.exit(1);
});
}
}
/**
* Prints the help text to the terminal.
*/
printHelpText() {
const helpText = fs.readFileSync(
path.join(__dirname, 'cli-help.txt'), {
encoding: 'utf8',
});
logHelper.info(helpText);
}
/**
* If there is no command given to the CLI then the flags will be passed
* to this function in case a relevant action can be taken.
* @param {object} args The available flags from the command line.
* @return {Promise} returns a promise once handled.
*/
handleFlag(args) {
let handled = false;
if (args.h || args.help) {
this.printHelpText();
handled = true;
}
if (args.v || args.version) {
logHelper.info(packageInfo.version);
handled = true;
}
if (handled) {
return Promise.resolve();
}
// This is a fallback
this.printHelpText();
return Promise.reject();
}
/**
* If a command is given in the command line args, this method will handle
* the appropriate action.
* @param {string} command The command name.
* @param {object} args The arguments given to this command.
* @param {object} flags The flags supplied with the command line.
* @return {Promise} A promise for the provided task.
*/
handleCommand(command, args, flags) {
switch (command) {
case 'init':
return this.initProject();
case 'serve': {
return this.serveSite();
}
case 'publish-release': {
return this.pushRelease();
}
case 'publish-docs': {
return this.publishDocs();
}
default:
logHelper.error(`Invlaid command given '${command}'`);
return Promise.reject();
}
}
/**
* This method will create the appropriate directories and files
* to initialise the project.
* @return {Promise} Returns a promise once initialising is done.
*/
initProject() {
try {
const files = [
{
input: path.join(__dirname, '..', '..', 'defaults', 'docs'),
output: path.join(process.cwd(), 'docs'),
},
{
input: path.join(__dirname, '..', '..', 'defaults', 'Gemfile'),
output: path.join(process.cwd(), 'Gemfile'),
},
{
input: path.join(__dirname, '..', '..', 'defaults', '.ruby-version'),
output: path.join(process.cwd(), '.ruby-version'),
},
{
input: path.join(__dirname, '..', '..', 'defaults', 'jsdoc.conf'),
output: path.join(process.cwd(), 'jsdoc.conf'),
},
];
files.forEach((fileOptions) => {
try {
fs.accessSync(fileOptions.output, fs.F_OK);
} catch (err) {
fse.copySync(
fileOptions.input,
fileOptions.output
);
}
});
return Promise.resolve();
} catch (err) {
return Promise.reject(err);
}
}
/**
* This method implements the 'serve' command and started jekyll
* serve and copies the appropriate files to demo the site.
* @return {Promise} Returns a promise that resolves once serving has
* finished.
*/
serveSite() {
const docsPath = path.join(process.cwd(), 'docs');
try {
fs.accessSync(docsPath, fs.F_OK);
} catch (err) {
logHelper.error('Can\'t build and serve the site since there is ' +
'no docs directory.');
return Promise.reject();
}
const filesRemove = [];
const fileWatchers = [];
return new Promise((resolve, reject) => {
exitLifeCycle.addEventListener('exit', () => {
try {
this.stopServingDocSite(filesRemove, fileWatchers);
} catch (err) {
return reject(err);
}
resolve();
});
const docsPath = path.join(process.cwd(), 'docs');
try {
// Check ./docs exists
const stats = fs.statSync(docsPath);
if (!stats.isDirectory()) {
throw new Error('./docs is a file, not a directory.');
}
} catch (err) {
logHelper.error('Please ensure the docs directory exists in your ' +
'current directory.');
logHelper.error(err);
return Promise.reject(err);
}
return Promise.resolve()
.then(() => {
filesRemove.push(path.join(docsPath, 'themes'));
this.updateJekyllTemplate(docsPath);
})
.then(() => {
const jsdocConf = path.join(process.cwd(), 'jsdoc.conf');
let jsdocConfContents = null;
try {
jsdocConfContents = JSON.parse(fs.readFileSync(jsdocConf));
} catch (err) {
logHelper.info('Skipping JSDocs due to no jsdoc.conf');
return;
}
if (!jsdocConfContents) {
logHelper.info('Skipping JSDocs - Unable to read and parse ' +
'jsdoc.conf');
return;
}
filesRemove.push(path.join(docsPath, 'reference-docs'));
const jsdocPaths = jsdocConfContents.source.include;
const watcherGlobs = [];
jsdocPaths.forEach((jsdocIncludePath) => {
const watchPath = path.join(process.cwd(), jsdocIncludePath);
watcherGlobs.push(watchPath + '/**/*');
});
const watcher = chokidar.watch(watcherGlobs, {
recursive: true,
});
watcher.on('change', () => {
return this.buildJSDocs(docsPath, 'stable', 'v0.0.0');
});
fileWatchers.push(watcher);
return this.buildJSDocs(docsPath, 'stable', 'v0.0.0');
})
.then(() => {
filesRemove.push(path.join(docsPath, '_data'));
this.buildReferenceDocsList(docsPath);
// Copy Jekyll gem - only needed for local build
fse.copySync(
path.join(__dirname, '..', '..', 'defaults', 'Gemfile'),
path.join(docsPath, 'Gemfile')
);
filesRemove.push(path.join(docsPath, 'Gemfile'));
})
.then(() => {
logHelper.info('Starting Jekyll serve.');
const jekyllCommand =
process.platform === 'win32' ? 'jekyll.bat' : 'jekyll';
const params = [
'exec',
jekyllCommand,
'serve',
'--trace',
'--config',
'_config.yml',
];
const jekyllProcess = spawn('bundle', params, {
cwd: docsPath,
stdio: 'inherit',
});
jekyllProcess.on('error', (err) => {
logHelper.error('Unable to run Jekyll. Please ensure that you ' +
'run the followings commands:');
logHelper.error('');
logHelper.error(' gem install bundler');
logHelper.error(' rvm . do bundle install');
logHelper.error('');
logHelper.error(err);
});
filesRemove.push(path.join(docsPath, '_site'));
this._spawnedProcesses.push(jekyllProcess);
});
});
}
/**
* Should get the latest docs from git-pages branch, update the entries
* build any reference docs and commit changes accordingly.
* @param {String} [tag] Tag for JSDocs.
* @param {String} [newVersion] Version name for JSDocs.
* @return {Promise} Returns a promise which resolves the publish is complete.
*/
publishDocs(tag, newVersion) {
const githubPagesRoot = path.join(process.cwd(), 'gh-pages');
let ghPageDirExists = false;
try {
fs.accessSync(githubPagesRoot, fs.F_OK);
ghPageDirExists = true;
} catch (err) {
// NOOP
}
if (ghPageDirExists) {
logHelper.error('The directory \'gh-pages\' already exists.');
logHelper.error('Please delete it to publish docs.');
return Promise.reject();
}
return this.checkoutGithubPages(githubPagesRoot)
.then(() => {
return this.cleanupGithubPages(githubPagesRoot);
})
.then(() => {
this.copyDocs(githubPagesRoot);
this.updateJekyllTemplate(githubPagesRoot);
})
.then(() => {
return this.buildJSDocs(githubPagesRoot, tag, newVersion);
})
.then(() => {
this.buildReferenceDocsList(githubPagesRoot);
})
.then(() => {
return this.pushChangesToGithub(githubPagesRoot);
})
.catch((err) => {
logHelper.error(err);
fse.removeSync(githubPagesRoot);
throw err;
})
.then(() => {
fse.removeSync(githubPagesRoot);
})
.catch((err) => {
logHelper.warn(`Unable to publish docs. '${err.message}'`);
throw err;
});
}
/**
* Checkout the current projects github pages branch
* @param {string} newPath This should be the path to the root of
* the docs output (i.e. github pages or temp build directory).
* @return {Promise} Returns a promise that resolves once the github
* repo has been checked out.
*/
checkoutGithubPages(newPath) {
return new Promise((resolve, reject) => {
const scriptPath = path.join(__dirname, 'shell-scripts',
'checkout-gh-pages.sh');
const gitCheckoutProcess = spawn(scriptPath, [newPath], {
stdio: 'inherit',
});
gitCheckoutProcess.on('close', function(code) {
if (code === 0) {
resolve();
} else {
reject(new Error(`Unexpected status code. [${code}]`));
}
});
gitCheckoutProcess.on('error', function(err) {
reject(err);
});
});
}
/**
* This method deletes any files that can be updated by
* npm-publish-scripts are documents that may be out of date with the
* master branch.
* @param {string} newPath This should be the path to the root of
* the docs output (i.e. github pages or temp build directory).
* @return {Promise} Returns a promise that resolves once the github
* repo has been checked out.
*/
cleanupGithubPages(newPath) {
return new Promise((resolve, reject) => {
const scriptPath = path.join(__dirname, 'shell-scripts',
'remove-old-files.sh');
const cleanupProcess = spawn(scriptPath, [REFERENCE_DOCS_DIR], {
cwd: newPath,
stdio: 'inherit',
});
cleanupProcess.on('close', function(code) {
if (code === 0) {
resolve();
} else {
reject(new Error(`Unexpected status code. [${code}]`));
}
});
cleanupProcess.on('error', function(err) {
reject(err);
});
});
}
/**
* This method will push everything to Github on the gh-pages branch.
* @param {string} newPath This should be the path to the root of
* the docs output (i.e. github pages or temp build directory).
* @return {Promise} Returns a promise that resolves once the github
* repo has been pushed to.
*/
pushChangesToGithub(newPath) {
return new Promise((resolve, reject) => {
const scriptPath = path.join(__dirname, 'shell-scripts',
'push-to-github.sh');
const pushProcess = spawn(scriptPath, [], {
cwd: newPath,
stdio: 'inherit',
});
pushProcess.on('close', function(code) {
if (code === 0) {
resolve();
} else {
reject(new Error(`Unexpected status code. [${code}]`));
}
});
pushProcess.on('error', function(err) {
reject(err);
});
});
}
/**
* Copyies over contents of /docs in a project to Github pages.
* @param {string} newPath This should be the path to the root of
* the docs output (i.e. github pages or temp build directory).
*/
copyDocs(newPath) {
fse.copySync(
path.join(process.cwd(), 'docs'),
newPath
);
}
/**
* This method will remove any current jekyll files and copy over the
* new files.
* @param {string} newPath This should be the path to the root of
* the docs output (i.e. github pages or temp build directory).
*/
updateJekyllTemplate(newPath) {
fse.copySync(
path.join(__dirname, '..', '..', '..', 'build', 'themes', 'jekyll'),
path.join(newPath, 'themes', 'jekyll')
);
}
/**
* Building the JSDocs for the current project
* @param {string} newPath This should be the path to the root of
* the docs output (i.e. github pages or temp build directory).
* @param {string} tag The tag stable, beta or alpha for docs.
* @param {string} version The version string for the directories.
* @return {Promise} that resolves once the docs have been built if requested
* by the developer.
*/
buildJSDocs(newPath, tag, version) {
const jsdocConf = path.join(process.cwd(), 'jsdoc.conf');
try {
fs.accessSync(jsdocConf, fs.F_OK);
} catch (err) {
logHelper.info('Skipping JSDocs due to no jsdoc.conf');
return;
}
logHelper.info('Building JSDocs');
let detailsPromise;
if (tag && version) {
detailsPromise = Promise.resolve({
tag,
version,
});
} else {
detailsPromise = inquirer.prompt(
[
{
type: 'confirm',
name: 'buildNewDocs',
message: 'Would you like to build new JSDocs? (Otherwise we\'ll ' +
'just update the theme for Github Pages.)',
},
{
type: 'list',
name: 'tag',
message: 'Is this release of docs a stable, beta or alpha release?',
choices: ['stable', 'beta', 'alpha'],
when: (results) => {
return results.buildNewDocs;
},
},
{
name: 'version',
message: 'What is the tag for this set of docs? (i.e. v1.0.0)',
when: (results) => {
return results.buildNewDocs;
},
},
]
);
}
return detailsPromise.then((results) => {
if (results.buildNewDocs === false) {
return;
}
const jsDocParams = [
'-c', jsdocConf,
'--template', path.join(__dirname, '..', '..', 'themes', 'jsdoc'),
'-d',
path.join(
newPath, REFERENCE_DOCS_DIR, results.tag, results.version
),
];
const jsdocProcess = spawnSync(
path.join(__dirname, '..', '..', '..',
'node_modules', '.bin', 'jsdoc'),
jsDocParams,
{
cwd: process.cwd(),
stdio: 'inherit',
}
);
if (jsdocProcess.error) {
logHelper.error(jsdocProcess.error);
}
});
}
/**
* The way reference docs are surfaced to Jekyll are through a
* _data/ list that defines all the stable, beta and alpha reference
* docs.
*
* This method will build that list and make it available to the Jekyll
* theme.
*
* @param {string} newPath This should be the path to the root of
* the docs output (i.e. github pages or temp build directory).
*/
buildReferenceDocsList(newPath) {
const referenceDocsPath = path.join(newPath, REFERENCE_DOCS_DIR);
try {
// Check if it exists
fs.accessSync(referenceDocsPath, fs.F_OK);
} catch (err) {
logHelper.info('Skipping reference-docs list as none exist.');
return;
}
const lines = [
'# Auto-generated by the npm-publish-scripts module.',
];
const otherReleases = [];
const versionedRelease = {
stable: [],
beta: [],
alpha: [],
};
const knownReleaseGroups = Object.keys(versionedRelease);
const directories = fs.readdirSync(referenceDocsPath);
directories.forEach((refDocsDir) => {
if (knownReleaseGroups.indexOf(refDocsDir) !== -1) {
// Version release
const releaseGroup = fs.readdirSync(
path.join(referenceDocsPath, refDocsDir)
);
releaseGroup.forEach((releaseDir) => {
if (releaseDir === 'latest') {
// Exclude latest directory from the sorted list. Latest is just
// used for re-directs.
return;
}
versionedRelease[refDocsDir].push(releaseDir);
});
} else {
// Just a raw docs type
try {
// Check if it exists
fs.accessSync(
path.join(referenceDocsPath, refDocsDir, 'index.html'), fs.F_OK);
} catch (err) {
// No Index page
return;
}
otherReleases.push(refDocsDir);
}
});
knownReleaseGroups.forEach((releaseGroup) => {
if (versionedRelease[releaseGroup].length === 0) {
return;
}
versionedRelease[releaseGroup].sort(semver.rcompare);
lines.push(`${releaseGroup}:`);
lines.push(` latest: /${REFERENCE_DOCS_DIR}/${releaseGroup}/` +
`${versionedRelease[releaseGroup][0]}`);
lines.push(` all:`);
versionedRelease[releaseGroup].forEach((version) => {
lines.push(` - /${REFERENCE_DOCS_DIR}/${releaseGroup}/` +
`${version}`);
});
});
if (otherReleases.length > 0) {
lines.push('other:');
otherReleases.forEach((release) => {
lines.push(` - ${release}: /${REFERENCE_DOCS_DIR}/${release}`);
});
}
fse.ensureDirSync(
path.join(newPath, '_data')
);
const file = fs.createWriteStream(
path.join(newPath, '_data', 'releases.yml'));
file.on('error', (err) => {
logHelper.error(err);
});
lines.forEach((line) => {
file.write(line + '\n');
});
file.end();
if (versionedRelease.stable.length > 0) {
const latestDocsPath = path.join(newPath, 'reference-docs', 'stable',
'latest');
fse.ensureDirSync(latestDocsPath);
const refDocPath = path.join(newPath, 'reference-docs', 'stable',
versionedRelease.stable[0]);
const referenceDocFiles = glob.sync(
path.join(refDocPath, '**', '*')
);
referenceDocFiles.forEach((refDocFile) => {
const docsRelPath = path.relative(refDocPath, refDocFile);
const redirectRelPath = path.relative(newPath, refDocFile);
const pathParts = path.parse(docsRelPath);
pathParts.ext = '.md';
const newFilePath = path.format(pathParts);
const file = fs.createWriteStream(
path.join(latestDocsPath, newFilePath));
file.on('error', (err) => {
logHelper.error(err);
});
file.write(
`---\n` +
`layout: redirect\n` +
`relPath: ${redirectRelPath}\n` +
`---\n`);
file.end();
});
}
}
/**
* This method stops any currently running processes.
* @param {Array<String>} filesToRemove Files / Directories to delete after
* killing jekyll process.
* @param {Array<Watcher>} fileWatchers An array of watchers to close.
*/
stopServingDocSite(filesToRemove, fileWatchers) {
logHelper.info('Stopping Jekyll serve.');
this._spawnedProcesses.forEach((spawnedProcess) => {
spawnedProcess.kill('SIGHUP');
});
logHelper.error('Perform tidy up');
if (filesToRemove && filesToRemove.length > 0) {
filesToRemove.forEach((file) => {
fse.removeSync(file);
});
}
if (fileWatchers && fileWatchers.length > 0) {
fileWatchers.forEach((watcher) => {
watcher.close();
});
}
}
/**
* A method that publishes a release to NPM.
* @return {Promise} Promise that resolves once finished publishing release.
*/
pushRelease() {
return this.confirmExpectedGitBranch()
.then(() => this.getPublishDetails())
.then((publishDetails) => {
return this.runNPMScripts()
.then(() => {
return this.loginToNPM()
.catch((err) => {
logHelper.error(`An error occured when logging into NPM. ` +
`'${err.message}'`);
throw err;
});
})
.then(() => this.confirmNewPackageVersion(publishDetails))
.then(() => {
return this.updatePackageVersion(publishDetails.version)
.catch((err) => {
logHelper.error(`An error occured when bumping the version with ` +
`'npm version ${publishDetails.version}'. '${err.message}'`);
throw err;
});
})
.then((newVersion) => {
let githubTag = newVersion;
if (publishDetails.tag !== 'stable') {
githubTag += `-${publishDetails.tag}`;
}
return this.publishToNPM(publishDetails.tag)
.catch((err) => {
logHelper.error(`An error occured when publish to NPM with ` +
`'npm publish'. '${err.message}'`);
throw err;
})
.then(() => {
return this.pushGithubTag(githubTag)
.catch((err) => {
logHelper.warn(`Unable to push the new Github Tags to remote ` +
`repo. '${err.message}'`);
throw err;
});
})
.then(() => {
return this.publishDocs(publishDetails.tag, newVersion);
});
});
});
}
/**
* This method resolves if the user is on the master branch, otherwise
* the CLI confirms with the user if they really want to publish a release
* from the current branch.
* @return {Promise} Resolves if the branch is ok to use.
*/
confirmExpectedGitBranch() {
return this.getCurrentBranchName()
.catch((err) => {
logHelper.error(`Unable to retrieve the current Git branch. ` +
`'${err.message}'`);
throw err;
})
.then((branchName) => {
if (branchName !== 'master') {
return inquirer.prompt([
{
type: 'confirm',
name: 'publish',
message: 'You are not currently on the master branch of this ' +
'project. Are you sure you want to publish a release from the ' +
`'${branchName}' branch?`,
default: false,
},
])
.then((answers) => {
const shouldPublish = answers['publish'];
if (!shouldPublish) {
throw new Error('User declined to publish on non-master branch.');
}
}, (err) => {
logHelper.error(`Unable to confirm the use of a seperate branch. ` +
`'${err.message}'`);
throw err;
});
}
});
}
/**
* @return {Promise<String>} Returns a promise that resolves with the current
* branch name
*/
getCurrentBranchName() {
return new Promise((resolve, reject) => {
gitBranch((err, branchName) => {
if (err) {
reject(err);
return;
}
resolve(branchName);
});
});
}
/**
* This gets what the release should be, patch, minor or major release with
* a tag of either stable, beta or alpha.
* @return {Promise<Object>} Resolves with the relevant details.
*/
getPublishDetails() {
return inquirer.prompt([
{
type: 'list',
name: 'version',
message: 'Is this a major, minor or patch release?',
choices: ['patch', 'minor', 'major'],
default: 'patch',
},
{
type: 'list',
name: 'tag',
message: 'Is this a stable, beta or alpha release?',
choices: ['stable', 'beta', 'alpha'],
default: 'stable',
},
])
.catch((err) => {
logHelper.error(`Unable to get the required details for the ` +
`release. '${err.message}'`);
throw err;
});
}
/**
* This should run the build and test scripts
* @return {Promise} Resolves once build and test scripts have run.
*/
runNPMScripts() {
return this.getProjectPackage()
.then((packageDetails) => {
if (!packageDetails.scripts || !packageDetails.scripts.test) {
logHelper.warn(strings['no-test-script']);
}
if (!packageDetails.scripts) {
return;
}
let promiseChain = Promise.resolve();
if (packageDetails.scripts.build) {
promiseChain = promiseChain.then(() => this._runNPMScript('build'));
}
if (packageDetails.scripts.test) {
promiseChain = promiseChain.then(() => this._runNPMScript('test'));
}
return promiseChain;
});
}
/**
* Gets the current package.json file in the current working directory.
* @return {Promise<Object>} Returns the parsed JSON file.
*/
getProjectPackage() {
const packageFile = path.join(process.cwd(), 'package.json');
return new Promise((resolve, reject) => {
fse.readJSON(packageFile, (err, pkg) => {
if (err) {
reject(err);
return;
}
resolve(pkg);
});
});
}
/**
* A helper method that will execute npm run scripts.
* @param {string} scriptName The name of the script to run.
* @return {Promise} Resolves once the script has finished executing.
*/
_runNPMScript(scriptName) {
return new Promise((resolve, reject) => {
const buildProcess = spawn('npm', ['run', scriptName], {
cwd: process.cwd(),
stdio: 'inherit',
});
buildProcess.on('error', (err) => {
logHelper.error(`Unable to run 'npm run ${scriptName}'. ` +
`'${err.message}'`);
reject(err);
});
buildProcess.on('close', (code) => {
if (code === 0) {
resolve();
return;
}
logHelper.error(`Unexpected status code from ` +
`'npm run ${scriptName}'. '${code}'`);
reject(new Error(`Unexpected status code from ` +
`'npm run ${scriptName}'`));
});
this._spawnedProcesses.push(buildProcess);
});
}
/**
* Logs the user into NPM if they aren't currently logged in.
* @return {Promise} Returns a promise that resolves once the user is logged
* in to npm.
*/
loginToNPM() {
return new Promise((resolve, reject) => {
const scriptPath = path.join(__dirname, 'shell-scripts',
'login-to-npm.sh');
const npmloginProcess = spawn(scriptPath, [], {
cwd: process.cwd(),
stdio: 'inherit',
});
npmloginProcess.on('close', function(code) {
if (code === 0) {
resolve();
} else {
reject(new Error(`Unexpected status code. [${code}]`));
}
});
npmloginProcess.on('error', (err) => {
reject(err);
});
this._spawnedProcesses.push(npmloginProcess);
});
}
/**
* Confirms with the user the entered details are correct before finally
* publishing the changes.
* @param {Object} publishDetails This is the details for the release.
* @return {Promise} Promsie that resolves if the user wishes to continue.
*/
confirmNewPackageVersion(publishDetails) {
return inquirer.prompt([
{
type: 'confirm',
name: 'publish-confirm',
message: `You're about to publish a new ${publishDetails.tag} - ` +
`${publishDetails.version} release. Are you sure you want to ` +
`continue?`,
default: false,
},
])
.then((answer) => {
if (answer['publish-confirm'] !== true) {
throw new Error('User did not confirm publishing.');
}
}, (err) => {
logHelper.error(`An error occured requesting publish confirmation. ` +
`'${err.message}'`);
throw err;
});
}
/**
* Bumps the current version with npm bump.
* @param {string} versionBump This should be 'patch', 'minor' or 'major'
* @return {Promise<String>} Resolves once the new version has been bumped.
*/
updatePackageVersion(versionBump) {
return new Promise((resolve, reject) => {
let newVersion = '';
const cliArgs = [
'--no-git-tag-version',
'version',
versionBump,
];
const npmloginProcess = spawn('npm', cliArgs, {
cwd: process.cwd(),
stdio: ['pipe', 'pipe', 'inherit'],
});
npmloginProcess.stdout.on('data', (data) => {
newVersion += data;
});
npmloginProcess.on('close', function(code) {
if (code === 0) {
resolve(newVersion.trim());
} else {
reject(new Error(`Unexpected status code. [${code}]`));
}
});
npmloginProcess.on('error', (err) => {
reject(err);
});
this._spawnedProcesses.push(npmloginProcess);
});
}
/**
* Publishes the project to NPM and will create a tag in Git.
* @param {string} tag A tag of 'stable', 'beta' or 'alpha'
* @return {Promise} Resolves once the npm publish call has finished.
*/
publishToNPM(tag) {
return new Promise((resolve, reject) => {
const cliArgs = [
'publish',
];
if (tag !== 'stable') {
cliArgs.push('--tag');
cliArgs.push(tag);
}
const npmPublishProcess = spawn('npm', cliArgs, {
cwd: process.cwd(),
stdio: 'inherit',
});
npmPublishProcess.on('close', function(code) {
if (code === 0) {
resolve();
} else {
reject(new Error(`Unexpected status code. [${code}]`));
}
});
npmPublishProcess.on('error', (err) => {
reject(err);
});
this._spawnedProcesses.push(npmPublishProcess);
});
}
/**
* Push the Github tag to the remote repo.
* @param {string} tag The tag to assign to the git.
* @return {Promise} Resolves once tags have been pushed.
*/
pushGithubTag(tag) {
return new Promise((resolve, reject) => {
const scriptPath = path.join(__dirname, 'shell-scripts',
'push-git-tags.sh');
const pushGitTags = spawn(scriptPath, [tag], {
cwd: process.cwd(),
stdio: 'inherit',
});
pushGitTags.on('close', function(code) {
if (code === 0) {
resolve();
} else {
reject(new Error(`Unexpected status code. [${code}]`));
}
});
pushGitTags.on('error', (err) => {
reject(err);
});
this._spawnedProcesses.push(pushGitTags);
});
}
}
module.exports = NPMPublishScriptCLI;
|
src/node/cli/index.js
|
/**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
'use strict';
const fs = require('fs');
const path = require('path');
const minimist = require('minimist');
const chokidar = require('chokidar');
const fse = require('fs-extra');
const spawn = require('child_process').spawn;
const spawnSync = require('child_process').spawnSync;
const semver = require('semver');
const inquirer = require('inquirer');
const gitBranch = require('git-branch');
const updateNotifier = require('update-notifier');
const glob = require('glob');
const exitLifeCycle = require('./exit-lifecycle');
const logHelper = require('./log-helper');
const strings = require('./strings');
const packageInfo = require('../../../package.json');
const REFERENCE_DOCS_DIR = 'reference-docs';
/**
* The module that performs the logic of the CLI.
*/
class NPMPublishScriptCLI {
/**
* Initialises the class.
*/
constructor() {
this._spawnedProcesses = [];
const notifier = updateNotifier({pkg: packageInfo});
notifier.notify();
}
/**
* This method is the entry method that kicks of logic and expects the
* output of minimist module.
* @param {object} argv This is the output minimist which parses the command
* line arguments.
* @return {Promise} Returns a promise for the given task.
*/
argv(argv) {
const cliArgs = minimist(argv);
if (cliArgs._.length > 0) {
// We have a command
return this.handleCommand(cliArgs._[0], cliArgs._.splice(1), cliArgs)
.then(() => {
process.exit(0);
})
.catch(() => {
process.exit(1);
});
} else {
// we have a flag only request
return this.handleFlag(cliArgs)
.then(() => {
process.exit(0);
})
.catch(() => {
process.exit(1);
});
}
}
/**
* Prints the help text to the terminal.
*/
printHelpText() {
const helpText = fs.readFileSync(
path.join(__dirname, 'cli-help.txt'), {
encoding: 'utf8',
});
logHelper.info(helpText);
}
/**
* If there is no command given to the CLI then the flags will be passed
* to this function in case a relevant action can be taken.
* @param {object} args The available flags from the command line.
* @return {Promise} returns a promise once handled.
*/
handleFlag(args) {
let handled = false;
if (args.h || args.help) {
this.printHelpText();
handled = true;
}
if (args.v || args.version) {
logHelper.info(packageInfo.version);
handled = true;
}
if (handled) {
return Promise.resolve();
}
// This is a fallback
this.printHelpText();
return Promise.reject();
}
/**
* If a command is given in the command line args, this method will handle
* the appropriate action.
* @param {string} command The command name.
* @param {object} args The arguments given to this command.
* @param {object} flags The flags supplied with the command line.
* @return {Promise} A promise for the provided task.
*/
handleCommand(command, args, flags) {
switch (command) {
case 'init':
return this.initProject();
case 'serve': {
return this.serveSite();
}
case 'publish-release': {
return this.pushRelease();
}
case 'publish-docs': {
return this.publishDocs();
}
default:
logHelper.error(`Invlaid command given '${command}'`);
return Promise.reject();
}
}
/**
* This method will create the appropriate directories and files
* to initialise the project.
* @return {Promise} Returns a promise once initialising is done.
*/
initProject() {
try {
const files = [
{
input: path.join(__dirname, '..', '..', 'defaults', 'docs'),
output: path.join(process.cwd(), 'docs'),
},
{
input: path.join(__dirname, '..', '..', 'defaults', 'Gemfile'),
output: path.join(process.cwd(), 'Gemfile'),
},
{
input: path.join(__dirname, '..', '..', 'defaults', '.ruby-version'),
output: path.join(process.cwd(), '.ruby-version'),
},
{
input: path.join(__dirname, '..', '..', 'defaults', 'jsdoc.conf'),
output: path.join(process.cwd(), 'jsdoc.conf'),
},
];
files.forEach((fileOptions) => {
try {
fs.accessSync(fileOptions.output, fs.F_OK);
} catch (err) {
fse.copySync(
fileOptions.input,
fileOptions.output
);
}
});
return Promise.resolve();
} catch (err) {
return Promise.reject(err);
}
}
/**
* This method implements the 'serve' command and started jekyll
* serve and copies the appropriate files to demo the site.
* @return {Promise} Returns a promise that resolves once serving has
* finished.
*/
serveSite() {
const docsPath = path.join(process.cwd(), 'docs');
try {
fs.accessSync(docsPath, fs.F_OK);
} catch (err) {
logHelper.error('Can\'t build and serve the site since there is ' +
'no docs directory.');
return Promise.reject();
}
const filesRemove = [];
const fileWatchers = [];
return new Promise((resolve, reject) => {
exitLifeCycle.addEventListener('exit', () => {
try {
this.stopServingDocSite(filesRemove, fileWatchers);
} catch (err) {
return reject(err);
}
resolve();
});
const docsPath = path.join(process.cwd(), 'docs');
try {
// Check ./docs exists
const stats = fs.statSync(docsPath);
if (!stats.isDirectory()) {
throw new Error('./docs is a file, not a directory.');
}
} catch (err) {
logHelper.error('Please ensure the docs directory exists in your ' +
'current directory.');
logHelper.error(err);
return Promise.reject(err);
}
return Promise.resolve()
.then(() => {
filesRemove.push(path.join(docsPath, 'themes'));
this.updateJekyllTemplate(docsPath);
})
.then(() => {
const jsdocConf = path.join(process.cwd(), 'jsdoc.conf');
let jsdocConfContents = null;
try {
jsdocConfContents = JSON.parse(fs.readFileSync(jsdocConf));
} catch (err) {
logHelper.info('Skipping JSDocs due to no jsdoc.conf');
return;
}
if (!jsdocConfContents) {
logHelper.info('Skipping JSDocs - Unable to read and parse ' +
'jsdoc.conf');
return;
}
filesRemove.push(path.join(docsPath, 'reference-docs'));
const jsdocPaths = jsdocConfContents.source.include;
const watcherGlobs = [];
jsdocPaths.forEach((jsdocIncludePath) => {
const watchPath = path.join(process.cwd(), jsdocIncludePath);
watcherGlobs.push(watchPath + '/**/*');
});
const watcher = chokidar.watch(watcherGlobs, {
recursive: true,
});
watcher.on('change', () => {
return this.buildJSDocs(docsPath, 'stable', 'v0.0.0');
});
fileWatchers.push(watcher);
return this.buildJSDocs(docsPath, 'stable', 'v0.0.0');
})
.then(() => {
filesRemove.push(path.join(docsPath, '_data'));
this.buildReferenceDocsList(docsPath);
// Copy Jekyll gem - only needed for local build
fse.copySync(
path.join(__dirname, '..', '..', '..', 'Gemfile'),
path.join(docsPath, 'Gemfile')
);
filesRemove.push(path.join(docsPath, 'Gemfile'));
})
.then(() => {
logHelper.info('Starting Jekyll serve.');
const jekyllCommand =
process.platform === 'win32' ? 'jekyll.bat' : 'jekyll';
const params = [
'exec',
jekyllCommand,
'serve',
'--trace',
'--config',
'_config.yml',
];
const jekyllProcess = spawn('bundle', params, {
cwd: docsPath,
stdio: 'inherit',
});
jekyllProcess.on('error', (err) => {
logHelper.error('Unable to run Jekyll. Please ensure that you ' +
'run the followings commands:');
logHelper.error('');
logHelper.error(' gem install bundler');
logHelper.error(' rvm . do bundle install');
logHelper.error('');
logHelper.error(err);
});
filesRemove.push(path.join(docsPath, '_site'));
this._spawnedProcesses.push(jekyllProcess);
});
});
}
/**
* Should get the latest docs from git-pages branch, update the entries
* build any reference docs and commit changes accordingly.
* @param {String} [tag] Tag for JSDocs.
* @param {String} [newVersion] Version name for JSDocs.
* @return {Promise} Returns a promise which resolves the publish is complete.
*/
publishDocs(tag, newVersion) {
const githubPagesRoot = path.join(process.cwd(), 'gh-pages');
let ghPageDirExists = false;
try {
fs.accessSync(githubPagesRoot, fs.F_OK);
ghPageDirExists = true;
} catch (err) {
// NOOP
}
if (ghPageDirExists) {
logHelper.error('The directory \'gh-pages\' already exists.');
logHelper.error('Please delete it to publish docs.');
return Promise.reject();
}
return this.checkoutGithubPages(githubPagesRoot)
.then(() => {
return this.cleanupGithubPages(githubPagesRoot);
})
.then(() => {
this.copyDocs(githubPagesRoot);
this.updateJekyllTemplate(githubPagesRoot);
})
.then(() => {
return this.buildJSDocs(githubPagesRoot, tag, newVersion);
})
.then(() => {
this.buildReferenceDocsList(githubPagesRoot);
})
.then(() => {
return this.pushChangesToGithub(githubPagesRoot);
})
.catch((err) => {
logHelper.error(err);
fse.removeSync(githubPagesRoot);
throw err;
})
.then(() => {
fse.removeSync(githubPagesRoot);
})
.catch((err) => {
logHelper.warn(`Unable to publish docs. '${err.message}'`);
throw err;
});
}
/**
* Checkout the current projects github pages branch
* @param {string} newPath This should be the path to the root of
* the docs output (i.e. github pages or temp build directory).
* @return {Promise} Returns a promise that resolves once the github
* repo has been checked out.
*/
checkoutGithubPages(newPath) {
return new Promise((resolve, reject) => {
const scriptPath = path.join(__dirname, 'shell-scripts',
'checkout-gh-pages.sh');
const gitCheckoutProcess = spawn(scriptPath, [newPath], {
stdio: 'inherit',
});
gitCheckoutProcess.on('close', function(code) {
if (code === 0) {
resolve();
} else {
reject(new Error(`Unexpected status code. [${code}]`));
}
});
gitCheckoutProcess.on('error', function(err) {
reject(err);
});
});
}
/**
* This method deletes any files that can be updated by
* npm-publish-scripts are documents that may be out of date with the
* master branch.
* @param {string} newPath This should be the path to the root of
* the docs output (i.e. github pages or temp build directory).
* @return {Promise} Returns a promise that resolves once the github
* repo has been checked out.
*/
cleanupGithubPages(newPath) {
return new Promise((resolve, reject) => {
const scriptPath = path.join(__dirname, 'shell-scripts',
'remove-old-files.sh');
const cleanupProcess = spawn(scriptPath, [REFERENCE_DOCS_DIR], {
cwd: newPath,
stdio: 'inherit',
});
cleanupProcess.on('close', function(code) {
if (code === 0) {
resolve();
} else {
reject(new Error(`Unexpected status code. [${code}]`));
}
});
cleanupProcess.on('error', function(err) {
reject(err);
});
});
}
/**
* This method will push everything to Github on the gh-pages branch.
* @param {string} newPath This should be the path to the root of
* the docs output (i.e. github pages or temp build directory).
* @return {Promise} Returns a promise that resolves once the github
* repo has been pushed to.
*/
pushChangesToGithub(newPath) {
return new Promise((resolve, reject) => {
const scriptPath = path.join(__dirname, 'shell-scripts',
'push-to-github.sh');
const pushProcess = spawn(scriptPath, [], {
cwd: newPath,
stdio: 'inherit',
});
pushProcess.on('close', function(code) {
if (code === 0) {
resolve();
} else {
reject(new Error(`Unexpected status code. [${code}]`));
}
});
pushProcess.on('error', function(err) {
reject(err);
});
});
}
/**
* Copyies over contents of /docs in a project to Github pages.
* @param {string} newPath This should be the path to the root of
* the docs output (i.e. github pages or temp build directory).
*/
copyDocs(newPath) {
fse.copySync(
path.join(process.cwd(), 'docs'),
newPath
);
}
/**
* This method will remove any current jekyll files and copy over the
* new files.
* @param {string} newPath This should be the path to the root of
* the docs output (i.e. github pages or temp build directory).
*/
updateJekyllTemplate(newPath) {
fse.copySync(
path.join(__dirname, '..', '..', '..', 'build', 'themes', 'jekyll'),
path.join(newPath, 'themes', 'jekyll')
);
}
/**
* Building the JSDocs for the current project
* @param {string} newPath This should be the path to the root of
* the docs output (i.e. github pages or temp build directory).
* @param {string} tag The tag stable, beta or alpha for docs.
* @param {string} version The version string for the directories.
* @return {Promise} that resolves once the docs have been built if requested
* by the developer.
*/
buildJSDocs(newPath, tag, version) {
const jsdocConf = path.join(process.cwd(), 'jsdoc.conf');
try {
fs.accessSync(jsdocConf, fs.F_OK);
} catch (err) {
logHelper.info('Skipping JSDocs due to no jsdoc.conf');
return;
}
logHelper.info('Building JSDocs');
let detailsPromise;
if (tag && version) {
detailsPromise = Promise.resolve({
tag,
version,
});
} else {
detailsPromise = inquirer.prompt(
[
{
type: 'confirm',
name: 'buildNewDocs',
message: 'Would you like to build new JSDocs? (Otherwise we\'ll ' +
'just update the theme for Github Pages.)',
},
{
type: 'list',
name: 'tag',
message: 'Is this release of docs a stable, beta or alpha release?',
choices: ['stable', 'beta', 'alpha'],
when: (results) => {
return results.buildNewDocs;
},
},
{
name: 'version',
message: 'What is the tag for this set of docs? (i.e. v1.0.0)',
when: (results) => {
return results.buildNewDocs;
},
},
]
);
}
return detailsPromise.then((results) => {
if (results.buildNewDocs === false) {
return;
}
const jsDocParams = [
'-c', jsdocConf,
'--template', path.join(__dirname, '..', '..', 'themes', 'jsdoc'),
'-d',
path.join(
newPath, REFERENCE_DOCS_DIR, results.tag, results.version
),
];
const jsdocProcess = spawnSync(
path.join(__dirname, '..', '..', '..',
'node_modules', '.bin', 'jsdoc'),
jsDocParams,
{
cwd: process.cwd(),
stdio: 'inherit',
}
);
if (jsdocProcess.error) {
logHelper.error(jsdocProcess.error);
}
});
}
/**
* The way reference docs are surfaced to Jekyll are through a
* _data/ list that defines all the stable, beta and alpha reference
* docs.
*
* This method will build that list and make it available to the Jekyll
* theme.
*
* @param {string} newPath This should be the path to the root of
* the docs output (i.e. github pages or temp build directory).
*/
buildReferenceDocsList(newPath) {
const referenceDocsPath = path.join(newPath, REFERENCE_DOCS_DIR);
try {
// Check if it exists
fs.accessSync(referenceDocsPath, fs.F_OK);
} catch (err) {
logHelper.info('Skipping reference-docs list as none exist.');
return;
}
const lines = [
'# Auto-generated by the npm-publish-scripts module.',
];
const otherReleases = [];
const versionedRelease = {
stable: [],
beta: [],
alpha: [],
};
const knownReleaseGroups = Object.keys(versionedRelease);
const directories = fs.readdirSync(referenceDocsPath);
directories.forEach((refDocsDir) => {
if (knownReleaseGroups.indexOf(refDocsDir) !== -1) {
// Version release
const releaseGroup = fs.readdirSync(
path.join(referenceDocsPath, refDocsDir)
);
releaseGroup.forEach((releaseDir) => {
if (releaseDir === 'latest') {
// Exclude latest directory from the sorted list. Latest is just
// used for re-directs.
return;
}
versionedRelease[refDocsDir].push(releaseDir);
});
} else {
// Just a raw docs type
try {
// Check if it exists
fs.accessSync(
path.join(referenceDocsPath, refDocsDir, 'index.html'), fs.F_OK);
} catch (err) {
// No Index page
return;
}
otherReleases.push(refDocsDir);
}
});
knownReleaseGroups.forEach((releaseGroup) => {
if (versionedRelease[releaseGroup].length === 0) {
return;
}
versionedRelease[releaseGroup].sort(semver.rcompare);
lines.push(`${releaseGroup}:`);
lines.push(` latest: /${REFERENCE_DOCS_DIR}/${releaseGroup}/` +
`${versionedRelease[releaseGroup][0]}`);
lines.push(` all:`);
versionedRelease[releaseGroup].forEach((version) => {
lines.push(` - /${REFERENCE_DOCS_DIR}/${releaseGroup}/` +
`${version}`);
});
});
if (otherReleases.length > 0) {
lines.push('other:');
otherReleases.forEach((release) => {
lines.push(` - ${release}: /${REFERENCE_DOCS_DIR}/${release}`);
});
}
fse.ensureDirSync(
path.join(newPath, '_data')
);
const file = fs.createWriteStream(
path.join(newPath, '_data', 'releases.yml'));
file.on('error', (err) => {
logHelper.error(err);
});
lines.forEach((line) => {
file.write(line + '\n');
});
file.end();
if (versionedRelease.stable.length > 0) {
const latestDocsPath = path.join(newPath, 'reference-docs', 'stable',
'latest');
fse.ensureDirSync(latestDocsPath);
const refDocPath = path.join(newPath, 'reference-docs', 'stable',
versionedRelease.stable[0]);
const referenceDocFiles = glob.sync(
path.join(refDocPath, '**', '*')
);
referenceDocFiles.forEach((refDocFile) => {
const docsRelPath = path.relative(refDocPath, refDocFile);
const redirectRelPath = path.relative(newPath, refDocFile);
const pathParts = path.parse(docsRelPath);
pathParts.ext = '.md';
const newFilePath = path.format(pathParts);
const file = fs.createWriteStream(
path.join(latestDocsPath, newFilePath));
file.on('error', (err) => {
logHelper.error(err);
});
file.write(
`---\n` +
`layout: redirect\n` +
`relPath: ${redirectRelPath}\n` +
`---\n`);
file.end();
});
}
}
/**
* This method stops any currently running processes.
* @param {Array<String>} filesToRemove Files / Directories to delete after
* killing jekyll process.
* @param {Array<Watcher>} fileWatchers An array of watchers to close.
*/
stopServingDocSite(filesToRemove, fileWatchers) {
logHelper.info('Stopping Jekyll serve.');
this._spawnedProcesses.forEach((spawnedProcess) => {
spawnedProcess.kill('SIGHUP');
});
logHelper.error('Perform tidy up');
if (filesToRemove && filesToRemove.length > 0) {
filesToRemove.forEach((file) => {
fse.removeSync(file);
});
}
if (fileWatchers && fileWatchers.length > 0) {
fileWatchers.forEach((watcher) => {
watcher.close();
});
}
}
/**
* A method that publishes a release to NPM.
* @return {Promise} Promise that resolves once finished publishing release.
*/
pushRelease() {
return this.confirmExpectedGitBranch()
.then(() => this.getPublishDetails())
.then((publishDetails) => {
return this.runNPMScripts()
.then(() => {
return this.loginToNPM()
.catch((err) => {
logHelper.error(`An error occured when logging into NPM. ` +
`'${err.message}'`);
throw err;
});
})
.then(() => this.confirmNewPackageVersion(publishDetails))
.then(() => {
return this.updatePackageVersion(publishDetails.version)
.catch((err) => {
logHelper.error(`An error occured when bumping the version with ` +
`'npm version ${publishDetails.version}'. '${err.message}'`);
throw err;
});
})
.then((newVersion) => {
let githubTag = newVersion;
if (publishDetails.tag !== 'stable') {
githubTag += `-${publishDetails.tag}`;
}
return this.publishToNPM(publishDetails.tag)
.catch((err) => {
logHelper.error(`An error occured when publish to NPM with ` +
`'npm publish'. '${err.message}'`);
throw err;
})
.then(() => {
return this.pushGithubTag(githubTag)
.catch((err) => {
logHelper.warn(`Unable to push the new Github Tags to remote ` +
`repo. '${err.message}'`);
throw err;
});
})
.then(() => {
return this.publishDocs(publishDetails.tag, newVersion);
});
});
});
}
/**
* This method resolves if the user is on the master branch, otherwise
* the CLI confirms with the user if they really want to publish a release
* from the current branch.
* @return {Promise} Resolves if the branch is ok to use.
*/
confirmExpectedGitBranch() {
return this.getCurrentBranchName()
.catch((err) => {
logHelper.error(`Unable to retrieve the current Git branch. ` +
`'${err.message}'`);
throw err;
})
.then((branchName) => {
if (branchName !== 'master') {
return inquirer.prompt([
{
type: 'confirm',
name: 'publish',
message: 'You are not currently on the master branch of this ' +
'project. Are you sure you want to publish a release from the ' +
`'${branchName}' branch?`,
default: false,
},
])
.then((answers) => {
const shouldPublish = answers['publish'];
if (!shouldPublish) {
throw new Error('User declined to publish on non-master branch.');
}
}, (err) => {
logHelper.error(`Unable to confirm the use of a seperate branch. ` +
`'${err.message}'`);
throw err;
});
}
});
}
/**
* @return {Promise<String>} Returns a promise that resolves with the current
* branch name
*/
getCurrentBranchName() {
return new Promise((resolve, reject) => {
gitBranch((err, branchName) => {
if (err) {
reject(err);
return;
}
resolve(branchName);
});
});
}
/**
* This gets what the release should be, patch, minor or major release with
* a tag of either stable, beta or alpha.
* @return {Promise<Object>} Resolves with the relevant details.
*/
getPublishDetails() {
return inquirer.prompt([
{
type: 'list',
name: 'version',
message: 'Is this a major, minor or patch release?',
choices: ['patch', 'minor', 'major'],
default: 'patch',
},
{
type: 'list',
name: 'tag',
message: 'Is this a stable, beta or alpha release?',
choices: ['stable', 'beta', 'alpha'],
default: 'stable',
},
])
.catch((err) => {
logHelper.error(`Unable to get the required details for the ` +
`release. '${err.message}'`);
throw err;
});
}
/**
* This should run the build and test scripts
* @return {Promise} Resolves once build and test scripts have run.
*/
runNPMScripts() {
return this.getProjectPackage()
.then((packageDetails) => {
if (!packageDetails.scripts || !packageDetails.scripts.test) {
logHelper.warn(strings['no-test-script']);
}
if (!packageDetails.scripts) {
return;
}
let promiseChain = Promise.resolve();
if (packageDetails.scripts.build) {
promiseChain = promiseChain.then(() => this._runNPMScript('build'));
}
if (packageDetails.scripts.test) {
promiseChain = promiseChain.then(() => this._runNPMScript('test'));
}
return promiseChain;
});
}
/**
* Gets the current package.json file in the current working directory.
* @return {Promise<Object>} Returns the parsed JSON file.
*/
getProjectPackage() {
const packageFile = path.join(process.cwd(), 'package.json');
return new Promise((resolve, reject) => {
fse.readJSON(packageFile, (err, pkg) => {
if (err) {
reject(err);
return;
}
resolve(pkg);
});
});
}
/**
* A helper method that will execute npm run scripts.
* @param {string} scriptName The name of the script to run.
* @return {Promise} Resolves once the script has finished executing.
*/
_runNPMScript(scriptName) {
return new Promise((resolve, reject) => {
const buildProcess = spawn('npm', ['run', scriptName], {
cwd: process.cwd(),
stdio: 'inherit',
});
buildProcess.on('error', (err) => {
logHelper.error(`Unable to run 'npm run ${scriptName}'. ` +
`'${err.message}'`);
reject(err);
});
buildProcess.on('close', (code) => {
if (code === 0) {
resolve();
return;
}
logHelper.error(`Unexpected status code from ` +
`'npm run ${scriptName}'. '${code}'`);
reject(new Error(`Unexpected status code from ` +
`'npm run ${scriptName}'`));
});
this._spawnedProcesses.push(buildProcess);
});
}
/**
* Logs the user into NPM if they aren't currently logged in.
* @return {Promise} Returns a promise that resolves once the user is logged
* in to npm.
*/
loginToNPM() {
return new Promise((resolve, reject) => {
const scriptPath = path.join(__dirname, 'shell-scripts',
'login-to-npm.sh');
const npmloginProcess = spawn(scriptPath, [], {
cwd: process.cwd(),
stdio: 'inherit',
});
npmloginProcess.on('close', function(code) {
if (code === 0) {
resolve();
} else {
reject(new Error(`Unexpected status code. [${code}]`));
}
});
npmloginProcess.on('error', (err) => {
reject(err);
});
this._spawnedProcesses.push(npmloginProcess);
});
}
/**
* Confirms with the user the entered details are correct before finally
* publishing the changes.
* @param {Object} publishDetails This is the details for the release.
* @return {Promise} Promsie that resolves if the user wishes to continue.
*/
confirmNewPackageVersion(publishDetails) {
return inquirer.prompt([
{
type: 'confirm',
name: 'publish-confirm',
message: `You're about to publish a new ${publishDetails.tag} - ` +
`${publishDetails.version} release. Are you sure you want to ` +
`continue?`,
default: false,
},
])
.then((answer) => {
if (answer['publish-confirm'] !== true) {
throw new Error('User did not confirm publishing.');
}
}, (err) => {
logHelper.error(`An error occured requesting publish confirmation. ` +
`'${err.message}'`);
throw err;
});
}
/**
* Bumps the current version with npm bump.
* @param {string} versionBump This should be 'patch', 'minor' or 'major'
* @return {Promise<String>} Resolves once the new version has been bumped.
*/
updatePackageVersion(versionBump) {
return new Promise((resolve, reject) => {
let newVersion = '';
const cliArgs = [
'--no-git-tag-version',
'version',
versionBump,
];
const npmloginProcess = spawn('npm', cliArgs, {
cwd: process.cwd(),
stdio: ['pipe', 'pipe', 'inherit'],
});
npmloginProcess.stdout.on('data', (data) => {
newVersion += data;
});
npmloginProcess.on('close', function(code) {
if (code === 0) {
resolve(newVersion.trim());
} else {
reject(new Error(`Unexpected status code. [${code}]`));
}
});
npmloginProcess.on('error', (err) => {
reject(err);
});
this._spawnedProcesses.push(npmloginProcess);
});
}
/**
* Publishes the project to NPM and will create a tag in Git.
* @param {string} tag A tag of 'stable', 'beta' or 'alpha'
* @return {Promise} Resolves once the npm publish call has finished.
*/
publishToNPM(tag) {
return new Promise((resolve, reject) => {
const cliArgs = [
'publish',
];
if (tag !== 'stable') {
cliArgs.push('--tag');
cliArgs.push(tag);
}
const npmPublishProcess = spawn('npm', cliArgs, {
cwd: process.cwd(),
stdio: 'inherit',
});
npmPublishProcess.on('close', function(code) {
if (code === 0) {
resolve();
} else {
reject(new Error(`Unexpected status code. [${code}]`));
}
});
npmPublishProcess.on('error', (err) => {
reject(err);
});
this._spawnedProcesses.push(npmPublishProcess);
});
}
/**
* Push the Github tag to the remote repo.
* @param {string} tag The tag to assign to the git.
* @return {Promise} Resolves once tags have been pushed.
*/
pushGithubTag(tag) {
return new Promise((resolve, reject) => {
const scriptPath = path.join(__dirname, 'shell-scripts',
'push-git-tags.sh');
const pushGitTags = spawn(scriptPath, [tag], {
cwd: process.cwd(),
stdio: 'inherit',
});
pushGitTags.on('close', function(code) {
if (code === 0) {
resolve();
} else {
reject(new Error(`Unexpected status code. [${code}]`));
}
});
pushGitTags.on('error', (err) => {
reject(err);
});
this._spawnedProcesses.push(pushGitTags);
});
}
}
module.exports = NPMPublishScriptCLI;
|
Changing the location of the Gemfile used for copying
|
src/node/cli/index.js
|
Changing the location of the Gemfile used for copying
|
<ide><path>rc/node/cli/index.js
<ide>
<ide> // Copy Jekyll gem - only needed for local build
<ide> fse.copySync(
<del> path.join(__dirname, '..', '..', '..', 'Gemfile'),
<add> path.join(__dirname, '..', '..', 'defaults', 'Gemfile'),
<ide> path.join(docsPath, 'Gemfile')
<ide> );
<ide>
|
|
JavaScript
|
mit
|
bc77477239dd0c4a351c03e804a2b16fa0d60e79
| 0 |
johniek/meteor-rock,johniek/meteor-rock
|
a1ef9744-306c-11e5-9929-64700227155b
|
helloWorld.js
|
a1ed95ca-306c-11e5-9929-64700227155b
|
a1ef9744-306c-11e5-9929-64700227155b
|
helloWorld.js
|
a1ef9744-306c-11e5-9929-64700227155b
|
<ide><path>elloWorld.js
<del>a1ed95ca-306c-11e5-9929-64700227155b
<add>a1ef9744-306c-11e5-9929-64700227155b
|
|
Java
|
bsd-3-clause
|
faa48f94c136f7d9e66aa0ab17e68030c144b209
| 0 |
deib-polimi/modaclouds-data-collectors,boc-modaclouds/modaclouds-data-collectors,imperial-modaclouds/modaclouds-data-collectors
|
/**
* Copyright ${year} imperial
* Contact: imperial <[email protected]>
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 imperial.modaclouds.monitoring.datacollectors.monitors;
import imperial.modaclouds.monitoring.datacollectors.basic.AbstractMonitor;
import imperial.modaclouds.monitoring.datacollectors.basic.DataCollectorAgent;
import imperial.modaclouds.monitoring.datacollectors.basic.Metric;
import it.polimi.modaclouds.monitoring.dcfactory.DCMetaData;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* The monitoring collector for Sigar.
*/
public class SigarMonitor extends AbstractMonitor {
private Logger logger = LoggerFactory.getLogger(SigarMonitor.class);
/**
* Sigar instance.
*/
protected static Sigar sigar;
/**
* Sigar monitor thread.
*/
private Thread sigt;
/**
* The unique monitored target.
*/
private String monitoredTarget;
/**
* The metric list.
*/
private List<Metric> metricList;
private DataCollectorAgent dcAgent;
/**
* Constructor of the class.
*
* @param measure Monitoring measure
* @throws MalformedURLException
* @throws FileNotFoundException
*/
public SigarMonitor( String resourceId, String mode) {
super(resourceId, mode);
monitoredTarget = resourceId;
monitorName = "sigar";
dcAgent = DataCollectorAgent.getInstance();
}
@Override
public void run() {
long startTime = 0;
List<Integer> period = null;
List<Integer> nextPauseTime = null;
while (!sigt.isInterrupted()) {
if (mode.equals("kb")) {
if (System.currentTimeMillis() - startTime > 10000) {
period = new ArrayList<Integer>();
nextPauseTime = new ArrayList<Integer>();
metricList = new ArrayList<Metric>();
Collection<DCMetaData> dcConfig = dcAgent.getDataCollectors(resourceId);
for (DCMetaData dc: dcConfig) {
if (ModacloudsMonitor.findCollector(dc.getMonitoredMetric()).equals("sigar")) {
Metric temp = new Metric();
temp.setMetricName(dc.getMonitoredMetric());
Map<String, String> parameters = dc.getParameters();
period.add(Integer.valueOf(parameters.get("samplingTime"))*1000);
nextPauseTime.add(Integer.valueOf(parameters.get("samplingTime"))*1000);
temp.setSamplingProb(Double.valueOf(parameters.get("samplingProbability")));
metricList.add(temp);
}
}
startTime = System.currentTimeMillis();
}
}
else {
if (System.currentTimeMillis() - startTime > 3600000) {
try {
period = new ArrayList<Integer>();
nextPauseTime = new ArrayList<Integer>();
metricList = new ArrayList<Metric>();
int temp_period = 0;
String folder = new File(".").getCanonicalPath();
File file = new File(folder+"/config/configuration_SIGAR.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(file);
doc.getDocumentElement().normalize();
NodeList nList_jdbc = doc.getElementsByTagName("sigar-metric");
for (int i = 0; i < nList_jdbc.getLength(); i++) {
Node nNode = nList_jdbc.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
monitoredTarget = eElement.getElementsByTagName("monitoredTarget").item(0).getTextContent();
temp_period = Integer.valueOf(eElement.getElementsByTagName("monitorPeriod").item(0).getTextContent());
}
}
NodeList nList = doc.getElementsByTagName("metricName");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
Metric temp_metric = new Metric();
temp_metric.setMetricName(nNode.getTextContent());
temp_metric.setSamplingProb(1);
metricList.add(temp_metric);
period.add(temp_period*1000);
nextPauseTime.add(temp_period*1000);
}
} catch (ParserConfigurationException e1) {
logger.info(e1.getMessage());
} catch (SAXException e) {
logger.info(e.getMessage());
} catch (IOException e) {
logger.info(e.getMessage());
}
startTime = System.currentTimeMillis();
}
}
int toSleep = Collections.min(nextPauseTime);
int index = nextPauseTime.indexOf(toSleep);
try {
Thread.sleep(Math.max(toSleep, 0));
} catch (InterruptedException e) {
logger.info(e.getMessage());
}
long t0 = System.currentTimeMillis();
double value = 0;
try {
switch (metricList.get(index).getMetricName().toLowerCase()) {
case "cpuutilization":
value = 1 - sigar.getCpuPerc().getIdle();
break;
case "cpustolen":
value = sigar.getCpuPerc().getStolen();
break;
case "memused":
value = sigar.getMem().getActualUsed();
break;
}
} catch (SigarException e) {
logger.info(e.getMessage());
}
boolean isSent = false;
if (Math.random() < metricList.get(index).getSamplingProb()) {
isSent = true;
}
try {
if (isSent) {
logger.info("Sending datum: {} {} {}",value, metricList.get(index).getMetricName(), monitoredTarget);
dcAgent.sendSyncMonitoringDatum(String.valueOf(value), metricList.get(index).getMetricName(), monitoredTarget);
}
} catch (Exception e) {
logger.info(e.getMessage());
}
long t1 = System.currentTimeMillis();
for (int i = 0; i < nextPauseTime.size(); i++) {
nextPauseTime.set(i, Math.max(0, Integer.valueOf(nextPauseTime.get(i)-toSleep-(int)(t1-t0))));
}
nextPauseTime.set(index,period.get(index));
}
}
@Override
public void start() {
logger.info("Starting Sigar DC");
sigar = SingletonSigar.getInstance();
sigt = new Thread(this, "sig-mon");
}
@Override
public void init() {
sigt.start();
logger.info("Sigar monitor running");
}
@Override
public void stop() {
while (!sigt.isInterrupted()) {
sigt.interrupt();
}
logger.info("Sigar monitor stopped!");
}
}
|
src/main/java/imperial/modaclouds/monitoring/datacollectors/monitors/SigarMonitor.java
|
/**
* Copyright ${year} imperial
* Contact: imperial <[email protected]>
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 imperial.modaclouds.monitoring.datacollectors.monitors;
import imperial.modaclouds.monitoring.datacollectors.basic.AbstractMonitor;
import imperial.modaclouds.monitoring.datacollectors.basic.DataCollectorAgent;
import imperial.modaclouds.monitoring.datacollectors.basic.Metric;
import it.polimi.modaclouds.monitoring.dcfactory.DCMetaData;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* The monitoring collector for Sigar.
*/
public class SigarMonitor extends AbstractMonitor {
private Logger logger = LoggerFactory.getLogger(SigarMonitor.class);
/**
* Sigar instance.
*/
protected static Sigar sigar;
/**
* Sigar monitor thread.
*/
private Thread sigt;
/**
* The unique monitored target.
*/
private String monitoredTarget;
/**
* The metric list.
*/
private List<Metric> metricList;
private DataCollectorAgent dcAgent;
/**
* Constructor of the class.
*
* @param measure Monitoring measure
* @throws MalformedURLException
* @throws FileNotFoundException
*/
public SigarMonitor( String resourceId, String mode) {
super(resourceId, mode);
monitoredTarget = resourceId;
monitorName = "sigar";
dcAgent = DataCollectorAgent.getInstance();
}
@Override
public void run() {
long startTime = 0;
List<Integer> period = null;
List<Integer> nextPauseTime = null;
while (!sigt.isInterrupted()) {
if (mode.equals("kb")) {
if (System.currentTimeMillis() - startTime > 10000) {
period = new ArrayList<Integer>();
nextPauseTime = new ArrayList<Integer>();
metricList = new ArrayList<Metric>();
Collection<DCMetaData> dcConfig = dcAgent.getDataCollectors(resourceId);
for (DCMetaData dc: dcConfig) {
if (ModacloudsMonitor.findCollector(dc.getMonitoredMetric()).equals("sigar")) {
Metric temp = new Metric();
temp.setMetricName(dc.getMonitoredMetric());
Map<String, String> parameters = dc.getParameters();
period.add(Integer.valueOf(parameters.get("samplingTime"))*1000);
nextPauseTime.add(Integer.valueOf(parameters.get("samplingTime"))*1000);
temp.setSamplingProb(Double.valueOf(parameters.get("samplingProbability")));
metricList.add(temp);
}
}
startTime = System.currentTimeMillis();
}
}
else {
if (System.currentTimeMillis() - startTime > 3600000) {
try {
period = new ArrayList<Integer>();
nextPauseTime = new ArrayList<Integer>();
metricList = new ArrayList<Metric>();
int temp_period = 0;
String folder = new File(".").getCanonicalPath();
File file = new File(folder+"/config/configuration_SIGAR.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(file);
doc.getDocumentElement().normalize();
NodeList nList_jdbc = doc.getElementsByTagName("sigar-metric");
for (int i = 0; i < nList_jdbc.getLength(); i++) {
Node nNode = nList_jdbc.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
monitoredTarget = eElement.getElementsByTagName("monitoredTarget").item(0).getTextContent();
temp_period = Integer.valueOf(eElement.getElementsByTagName("monitorPeriod").item(0).getTextContent());
}
}
NodeList nList = doc.getElementsByTagName("metricName");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
Metric temp_metric = new Metric();
temp_metric.setMetricName(nNode.getTextContent());
temp_metric.setSamplingProb(1);
metricList.add(temp_metric);
period.add(temp_period*1000);
nextPauseTime.add(temp_period*1000);
}
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
startTime = System.currentTimeMillis();
}
}
int toSleep = Collections.min(nextPauseTime);
int index = nextPauseTime.indexOf(toSleep);
try {
Thread.sleep(Math.max(toSleep, 0));
} catch (InterruptedException e) {
e.printStackTrace();
}
long t0 = System.currentTimeMillis();
double value = 0;
try {
switch (metricList.get(index).getMetricName().toLowerCase()) {
case "cpuutilization":
value = 1 - sigar.getCpuPerc().getIdle();
break;
case "cpustolen":
value = sigar.getCpuPerc().getStolen();
break;
case "memused":
value = sigar.getMem().getActualUsed();
break;
}
} catch (SigarException e) {
e.printStackTrace();
}
boolean isSent = false;
if (Math.random() < metricList.get(index).getSamplingProb()) {
isSent = true;
}
try {
if (isSent) {
logger.info("Sending datum: {} {} {}",value, metricList.get(index).getMetricName(), monitoredTarget);
dcAgent.sendSyncMonitoringDatum(String.valueOf(value), metricList.get(index).getMetricName(), monitoredTarget);
}
} catch (Exception e) {
e.printStackTrace();
}
long t1 = System.currentTimeMillis();
for (int i = 0; i < nextPauseTime.size(); i++) {
nextPauseTime.set(i, Math.max(0, Integer.valueOf(nextPauseTime.get(i)-toSleep-(int)(t1-t0))));
}
nextPauseTime.set(index,period.get(index));
}
}
@Override
public void start() {
logger.info("Starting Sigar DC");
sigar = SingletonSigar.getInstance();
sigt = new Thread(this, "sig-mon");
}
@Override
public void init() {
sigt.start();
logger.info("Sigar monitor running");
}
@Override
public void stop() {
while (!sigt.isInterrupted()) {
sigt.interrupt();
}
logger.info("Sigar monitor stopped!");
}
}
|
log fix
|
src/main/java/imperial/modaclouds/monitoring/datacollectors/monitors/SigarMonitor.java
|
log fix
|
<ide><path>rc/main/java/imperial/modaclouds/monitoring/datacollectors/monitors/SigarMonitor.java
<ide>
<ide>
<ide> } catch (ParserConfigurationException e1) {
<del> e1.printStackTrace();
<add> logger.info(e1.getMessage());
<ide> } catch (SAXException e) {
<del> e.printStackTrace();
<add> logger.info(e.getMessage());
<ide> } catch (IOException e) {
<del> e.printStackTrace();
<add> logger.info(e.getMessage());
<ide> }
<ide> startTime = System.currentTimeMillis();
<ide> }
<ide> try {
<ide> Thread.sleep(Math.max(toSleep, 0));
<ide> } catch (InterruptedException e) {
<del> e.printStackTrace();
<add> logger.info(e.getMessage());
<ide> }
<ide>
<ide> long t0 = System.currentTimeMillis();
<ide> break;
<ide> }
<ide> } catch (SigarException e) {
<del> e.printStackTrace();
<add> logger.info(e.getMessage());
<ide> }
<ide>
<ide> boolean isSent = false;
<ide> dcAgent.sendSyncMonitoringDatum(String.valueOf(value), metricList.get(index).getMetricName(), monitoredTarget);
<ide> }
<ide> } catch (Exception e) {
<del> e.printStackTrace();
<add> logger.info(e.getMessage());
<ide> }
<ide>
<ide> long t1 = System.currentTimeMillis();
|
|
Java
|
apache-2.0
|
871a336c38f6461bb45de81ad637c39dbf583e86
| 0 |
IWSDevelopers/iws,IWSDevelopers/iws
|
/*
* =============================================================================
* Copyright 1998-2016, IAESTE Internet Development Team. All rights reserved.
* ----------------------------------------------------------------------------
* Project: IntraWeb Services (iws-ejb) - net.iaeste.iws.ejb.StateBean
* -----------------------------------------------------------------------------
* This software is provided by the members of the IAESTE Internet Development
* Team (IDT) to IAESTE A.s.b.l. It is for internal use only and may not be
* redistributed. IAESTE A.s.b.l. is not permitted to sell this software.
*
* This software is provided "as is"; the IDT or individuals within the IDT
* cannot be held legally responsible for any problems the software may cause.
* =============================================================================
*/
package net.iaeste.iws.ejb;
import net.iaeste.iws.api.constants.IWSConstants;
import net.iaeste.iws.api.enums.GroupStatus;
import net.iaeste.iws.api.enums.GroupType;
import net.iaeste.iws.api.enums.UserStatus;
import net.iaeste.iws.api.enums.exchange.OfferState;
import net.iaeste.iws.api.exceptions.IWSException;
import net.iaeste.iws.api.util.Date;
import net.iaeste.iws.common.configuration.InternalConstants;
import net.iaeste.iws.common.configuration.Settings;
import net.iaeste.iws.core.monitors.ActiveSessions;
import net.iaeste.iws.core.notifications.Notifications;
import net.iaeste.iws.core.services.AccountService;
import net.iaeste.iws.ejb.cdi.IWSBean;
import net.iaeste.iws.persistence.AccessDao;
import net.iaeste.iws.persistence.Authentication;
import net.iaeste.iws.persistence.ExchangeDao;
import net.iaeste.iws.persistence.entities.SessionEntity;
import net.iaeste.iws.persistence.entities.UserEntity;
import net.iaeste.iws.persistence.entities.UserGroupEntity;
import net.iaeste.iws.persistence.entities.exchange.OfferEntity;
import net.iaeste.iws.persistence.jpa.AccessJpaDao;
import net.iaeste.iws.persistence.jpa.ExchangeJpaDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.ScheduleExpression;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
/**
* <p>When the IWS is starting up, we need to ensure that the current State is
* such that the system will work correctly. The purpose of this Bean is simply
* to ensure that.</p>
*
* <p>The Bean has two parts. First is what happens at startup, the second is to
* managed a Cron like service, which will run every night during the time where
* the system has the lowest load.</p>
*
* <p>At startup, the Bean will Clear all existing active Sessions, so nothing
* exists in the database. This will prevent existing Sessions from continuing
* to work, but as there may be other issues around a re-start, it is the least
* harmful.</p>
*
* <p>The Cron part will run every night, and both discard deprecated Sessions,
* but also update Accounts. To avoid that inactive/suspended/dead Accounts will
* clutter up the system.</p>
*
* @author Kim Jensen / last $Author:$
* @version $Revision:$ / $Date:$
* @since IWS 1.1
*/
@Startup
@Singleton
@TransactionAttribute(TransactionAttributeType.REQUIRED)
@TransactionManagement(TransactionManagementType.CONTAINER)
public class StateBean {
private static final Logger LOG = LoggerFactory.getLogger(StateBean.class);
@Inject @IWSBean private Notifications notifications;
@Inject @IWSBean private EntityManager entityManager;
@Inject @IWSBean private Settings settings;
@Resource private TimerService timerService;
private ActiveSessions activeSessions = null;
private ExchangeDao exchangeDao = null;
private AccessDao accessDao = null;
private AccountService service = null;
// =========================================================================
// Startup Functionality
// =========================================================================
/**
* To ensure that the system State is always consistent, we have two things
* that must be accomplished. First thing is to load the former state and
* ensure that the system is working using this as base.<br />
* Second part is to have a timer service (cron job), which will once per
* day run and perform certain cleanup actions.<br />
* This method is run once the Bean is initialized and will perform two
* things, first it will initialize the Timer Service, so it can run at
* frequent Intervals, secondly, it will initialize the Sessions.<br />
* Heavier maintenance operations like cleaning up accounts is left for
* the Timed Service to handle, since it may otherwise put the server under
* unnecessary pressure during the initial Startup Phase.
*/
@PostConstruct
public void startup() {
LOG.info("Starting IWS Initialization.");
// First, we need to initialize our dependencies
activeSessions = ActiveSessions.getInstance(settings);
accessDao = new AccessJpaDao(entityManager);
exchangeDao = new ExchangeJpaDao(entityManager);
service = new AccountService(settings, accessDao, notifications);
// Second, we're registering the Timer Service. This will ensure that the
// Bean is invoked daily at 2 in the morning.
final TimerConfig timerConfig = new TimerConfig();
timerConfig.setInfo("IWS State Cleaner");
timerConfig.setPersistent(false);
final ScheduleExpression expression = new ScheduleExpression();
final String[] time = settings.getRunCleanTime().split(":", 2);
expression.hour(time[0]).minute(time[1]);
timerService.createCalendarTimer(expression, timerConfig);
LOG.info("First cleanup run scheduled to begin at {}", expression);
if (settings.resetSessionsAtStartup()) {
// Now, remove all deprecated Sessions from the Server. These Sessions
// may or may not work correctly, since IW4 with JSF is combining the
// Sessions with a Windows Id, and upon restart - the Windows Id is
// renewed. Even if it isn't renewed, JSF will not recognize it
final int deprecated = accessDao.deprecateAllActiveSessions();
LOG.info("Deprecated {} Stale Sessions.", deprecated);
} else {
loadActiveTokens();
}
// That's it - we're done :-)
LOG.info("IWS Initialization Completed.");
}
private void loadActiveTokens() {
final List<SessionEntity> sessions = accessDao.findActiveSessions();
for (final SessionEntity entity : sessions) {
activeSessions.registerToken(entity.getSessionKey(), entity.getCreated());
}
}
// =========================================================================
// Timeout Functionality
// =========================================================================
/**
* Timeout Method, which will start the frequent cleaning.
*
* @param timer Timer information, useful for logging
*/
@Timeout
public void doCleanup(final Timer timer) {
LOG.info("Timeout occurred, will start the Cleanup");
final long start = System.nanoTime();
// For the suspension & deleting, we need to use an Authentication
// Object for history information. We're using the System account for
// this. Even if nothing is to be deleted, we're still fetching the
// record here, since the Cron job is only running once every 24 hours,
// we do not care much for performance problems.
final UserEntity system = entityManager.find(UserEntity.class, InternalConstants.SYSTEM_ACCOUNT);
final Authentication authentication = new Authentication(system, timer.getInfo().toString());
// First, let's get rid of those pesky expired sessions. For more
// information, see the Trac ticket #900.
removeDeprecatedSessions();
// Second, we'll handle Offers which have expired.
runExpiredOfferProcessing();
// third, we'll deal with accounts which are inactive. For more
// information, see the Trac ticket #720.
final int expired = removeUnusedNewAccounts();
final int suspended = suspendInactiveAccounts(authentication);
final int deleted = deleteSuspendedAccounts(authentication);
final DateFormat dateFormatter = new SimpleDateFormat(IWSConstants.DATE_TIME_FORMAT, IWSConstants.DEFAULT_LOCALE);
final long duration = (System.nanoTime() - start) / 1000000;
LOG.info("Cleanup took: {}ms (Users expired {}, suspended {} & deleted {}), next Timeout: {}", duration, expired, suspended, deleted, dateFormatter.format(timer.getNextTimeout()));
}
/**
* Remove deprecated Sessions.
*/
private int removeDeprecatedSessions() {
// First, let's calculate the time of expiry. All Sessions with a
// modification date before this, will be deprecated
final Long timeout = settings.getMaxIdleTimeForSessions();
final Date date = new Date(new Date().getTime() - timeout);
int count = 0;
// Iterate over the currently active sessions and remove them.
final List<SessionEntity> sessions = accessDao.findActiveSessions();
for (final SessionEntity session : sessions) {
if (session.getModified().before(date.toDate())) {
// Remove the found Session from the ActiveSessions Registry ...
activeSessions.removeToken(session.getSessionKey());
// ... and remove it from the database as well
accessDao.deprecateSession(session);
count++;
}
}
return count;
}
/**
* Runs the Offer Expiration. Although the state for an Offer is part of
* both the Offer & Offer Shares, only the Offer itself is updated, thus
* avoiding that any information is lost.<br />
* Offers expire if the Nomination Deadline passed. Please see Trac Ticket
* #1020 for more on the discussion. Please note, that although the code
* here is passing an auditing, there has been a problem with Offers that
* has suddenly expired, please see Trac ticket #1052 for details. For this
* reason, the method is now having increased logging.
*/
private void runExpiredOfferProcessing() {
try {
final List<OfferEntity> offers = exchangeDao.findExpiredOffers(new java.util.Date());
LOG.info("Found {} Offers to expire.", offers.size());
for (final OfferEntity offer : offers) {
offer.setStatus(OfferState.EXPIRED);
accessDao.persist(offer);
LOG.info("Offer {} has expired.", offer.getRefNo());
}
} catch (IllegalArgumentException | IWSException e) {
LOG.error("Error in processing expired offers", e);
}
}
/**
* Remove unused Accounts, i.e. Account with status NEW and which have not
* been activated following a period of x days.
*
* @return Number of Expired (never activated) Accounts
*/
private int removeUnusedNewAccounts() {
final Long days = settings.getAccountUnusedRemovedDays();
LOG.debug("Checking of any accounts exists which has expired, i.e. status NEW after {} days.", days);
int accounts = 0;
// We have a User Account, that was never activated. This we can
// delete completely
final List<UserEntity> newUsers = accessDao.findAccountsWithState(UserStatus.NEW, days);
for (final UserEntity user : newUsers) {
// Just to make sure that we're not removing the System Account, as
// that would be rather fatal!
if (user.getId() != InternalConstants.SYSTEM_ACCOUNT) {
LOG.info("Deleting Expired NEW Account for {} {} <{}>.", user.getFirstname(), user.getLastname(), user.getUsername());
service.deleteNewUser(user);
accounts++;
}
}
return accounts;
}
/**
* <p>This will suspend all inactive Accounts, meaning an account which has
* not been used for a period of time, which is defined in the IWS
* Properties.</p>
*
* <p>Suspension will change the state of the Account from ACTIVE to
* SUSPENDED. Note that National Secretaries is except from this rule, so
* any currently active Committee will always have at least one active
* account.</p>
*
* @return Number of Suspended Accounts
*/
private int suspendInactiveAccounts(final Authentication authentication) {
final Long days = settings.getAccountInactiveDays();
LOG.info("Fetching the list of Users to be suspended.");
final List<UserEntity> users = accessDao.findInactiveAccounts(days);
int suspended = 0;
if (!users.isEmpty()) {
for (final UserEntity user : users) {
if (maySuspendUser(user)) {
LOG.info("Attempting to suspend the User {} {} <{}>.", user.getFirstname(), user.getLastname(), user.getUsername());
service.suspendUser(authentication, user);
suspended++;
} else {
LOG.info("Ignoring inactive National Secretary {} {} <{}>.", user.getFirstname(), user.getLastname(), user.getUsername());
}
}
}
return suspended;
}
/**
* <p>It has been an ongoing problem that some accounts have been suspended,
* although they belong to the National Secretary of a Country. This is
* problematic, as it prevents that the person can do a correct hand-over if
* been inactive for too long.</p>
*
* <p>Instead, this check is added, and if a User is Owner of either an
* Administrative, International, Member or National (Staff) Group, then it
* is skipped.</p>
*
* @param user The User to check, if may be suspended
* @return True if the User may be suspended, otherwise false
*/
private boolean maySuspendUser(final UserEntity user) {
final List<UserGroupEntity> relations = accessDao.findAllUserGroups(user);
final Set<GroupType> allowed = EnumSet.of(GroupType.ADMINISTRATION, GroupType.INTERNATIONAL, GroupType.MEMBER, GroupType.NATIONAL);
boolean maySuspend = true;
for (final UserGroupEntity relation : relations) {
final GroupType type = relation.getGroup().getGroupType().getGrouptype();
final GroupStatus status = relation.getGroup().getStatus();
final long roleId = relation.getRole().getId();
if ((status == GroupStatus.ACTIVE) &&
(roleId == InternalConstants.ROLE_OWNER) &&
allowed.contains(type)) {
maySuspend = false;
break;
}
}
return maySuspend;
}
/**
* Delete inactive users. Accounts which have status SUSPENDED will after a
* period of y days be deleted, meaning that all private information will be
* removed, and account will have the status set to DELETED.<br />
* Note, that although accounts should be deleted, we cannot leave member
* groups without an owner. Accounts which is currently owner, will simply
* be ignored. The rule applies only to currently active Groups. Groups
* which have been suspended will be ignored.
*
* @return Number of Deleted Accounts
*/
private int deleteSuspendedAccounts(final Authentication authentication) {
final Long days = settings.getAccountSuspendedDays();
LOG.debug("Checking if Accounts exists with status SUSPENDED after {} days.", days);
int accounts = 0;
final List<UserEntity> suspendedUsers = accessDao.findAccountsWithState(UserStatus.SUSPENDED, days);
if (!suspendedUsers.isEmpty()) {
for (final UserEntity user : suspendedUsers) {
try {
LOG.info("Attempting to delete Suspended Account for {} {} <{}>.", user.getFirstname(), user.getLastname(), user.getUsername());
service.deletePrivateData(authentication, user);
accounts++;
} catch (IWSException e) {
LOG.debug(e.getMessage(), e);
LOG.warn("Unable to delete the Account for {} {} <{}>, reason: {}", user.getFirstname(), user.getLastname(), user.getUsername(), e.getMessage());
}
}
}
return accounts;
}
}
|
iws-ejb/src/main/java/net/iaeste/iws/ejb/StateBean.java
|
/*
* =============================================================================
* Copyright 1998-2016, IAESTE Internet Development Team. All rights reserved.
* ----------------------------------------------------------------------------
* Project: IntraWeb Services (iws-ejb) - net.iaeste.iws.ejb.StateBean
* -----------------------------------------------------------------------------
* This software is provided by the members of the IAESTE Internet Development
* Team (IDT) to IAESTE A.s.b.l. It is for internal use only and may not be
* redistributed. IAESTE A.s.b.l. is not permitted to sell this software.
*
* This software is provided "as is"; the IDT or individuals within the IDT
* cannot be held legally responsible for any problems the software may cause.
* =============================================================================
*/
package net.iaeste.iws.ejb;
import net.iaeste.iws.api.constants.IWSConstants;
import net.iaeste.iws.api.enums.UserStatus;
import net.iaeste.iws.api.enums.exchange.OfferState;
import net.iaeste.iws.api.exceptions.IWSException;
import net.iaeste.iws.api.util.Date;
import net.iaeste.iws.common.configuration.InternalConstants;
import net.iaeste.iws.common.configuration.Settings;
import net.iaeste.iws.core.monitors.ActiveSessions;
import net.iaeste.iws.core.notifications.Notifications;
import net.iaeste.iws.core.services.AccountService;
import net.iaeste.iws.ejb.cdi.IWSBean;
import net.iaeste.iws.persistence.AccessDao;
import net.iaeste.iws.persistence.Authentication;
import net.iaeste.iws.persistence.ExchangeDao;
import net.iaeste.iws.persistence.entities.SessionEntity;
import net.iaeste.iws.persistence.entities.UserEntity;
import net.iaeste.iws.persistence.entities.exchange.OfferEntity;
import net.iaeste.iws.persistence.jpa.AccessJpaDao;
import net.iaeste.iws.persistence.jpa.ExchangeJpaDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.ScheduleExpression;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
/**
* When the IWS is starting up, we need to ensure that the current State is such
* that the system will work correctly. The purpose of this Bean is simply to
* ensure that.<br />
* The Bean has two parts. First is what happens at startup, the second is to
* managed a Cron like service, which will run every night during the time where
* the system has the lowest load.<br />
* At startup, the Bean will Clear all existing active Sessions, so nothing
* exists in the database. This will prevent existing Sessions from continuing
* to work, but as there may be other issues around a re-start, it is the least
* harmful.<br />
* The Cron part will run every night, and both discard deprecated Sessions,
* but also update Accounts. To avoid that inactive/suspended/dead Accounts will
* clutter up the system.
*
* @author Kim Jensen / last $Author:$
* @version $Revision:$ / $Date:$
* @since IWS 1.1
*/
@Startup
@Singleton
@TransactionAttribute(TransactionAttributeType.REQUIRED)
@TransactionManagement(TransactionManagementType.CONTAINER)
public class StateBean {
private static final Logger LOG = LoggerFactory.getLogger(StateBean.class);
@Inject @IWSBean private Notifications notifications;
@Inject @IWSBean private EntityManager entityManager;
@Inject @IWSBean private Settings settings;
@Resource private TimerService timerService;
private ActiveSessions activeSessions = null;
private ExchangeDao exchangeDao = null;
private AccessDao accessDao = null;
private AccountService service = null;
// =========================================================================
// Startup Functionality
// =========================================================================
/**
* To ensure that the system State is always consistent, we have two things
* that must be accomplished. First thing is to load the former state and
* ensure that the system is working using this as base.<br />
* Second part is to have a timer service (cron job), which will once per
* day run and perform certain cleanup actions.<br />
* This method is run once the Bean is initialized and will perform two
* things, first it will initialize the Timer Service, so it can run at
* frequent Intervals, secondly, it will initialize the Sessions.<br />
* Heavier maintenance operations like cleaning up accounts is left for
* the Timed Service to handle, since it may otherwise put the server under
* unnecessary pressure during the initial Startup Phase.
*/
@PostConstruct
public void startup() {
LOG.info("Starting IWS Initialization.");
// First, we need to initialize our dependencies
activeSessions = ActiveSessions.getInstance(settings);
accessDao = new AccessJpaDao(entityManager);
exchangeDao = new ExchangeJpaDao(entityManager);
service = new AccountService(settings, accessDao, notifications);
// Second, we're registering the Timer Service. This will ensure that the
// Bean is invoked daily at 2 in the morning.
final TimerConfig timerConfig = new TimerConfig();
timerConfig.setInfo("IWS State Cleaner");
timerConfig.setPersistent(false);
final ScheduleExpression expression = new ScheduleExpression();
final String[] time = settings.getRunCleanTime().split(":", 2);
expression.hour(time[0]).minute(time[1]);
timerService.createCalendarTimer(expression, timerConfig);
LOG.info("First cleanup run scheduled to begin at {}", expression);
if (settings.resetSessionsAtStartup()) {
// Now, remove all deprecated Sessions from the Server. These Sessions
// may or may not work correctly, since IW4 with JSF is combining the
// Sessions with a Windows Id, and upon restart - the Windows Id is
// renewed. Even if it isn't renewed, JSF will not recognize it
final int deprecated = accessDao.deprecateAllActiveSessions();
LOG.info("Deprecated {} Stale Sessions.", deprecated);
} else {
loadActiveTokens();
}
// That's it - we're done :-)
LOG.info("IWS Initialization Completed.");
}
private void loadActiveTokens() {
final List<SessionEntity> sessions = accessDao.findActiveSessions();
for (final SessionEntity entity : sessions) {
activeSessions.registerToken(entity.getSessionKey(), entity.getCreated());
}
}
// =========================================================================
// Timeout Functionality
// =========================================================================
/**
* Timeout Method, which will start the frequent cleaning.
*
* @param timer Timer information, useful for logging
*/
@Timeout
public void doCleanup(final Timer timer) {
LOG.info("Timeout occurred, will start the Cleanup");
final long start = System.nanoTime();
// For the suspension & deleting, we need to use an Authentication
// Object for history information. We're using the System account for
// this. Even if nothing is to be deleted, we're still fetching the
// record here, since the Cron job is only running once every 24 hours,
// we do not care much for performance problems.
final UserEntity system = entityManager.find(UserEntity.class, InternalConstants.SYSTEM_ACCOUNT);
final Authentication authentication = new Authentication(system, timer.getInfo().toString());
// First, let's get rid of those pesky expired sessions. For more
// information, see the Trac ticket #900.
removeDeprecatedSessions();
// Second, we'll handle Offers which have expired.
runExpiredOfferProcessing();
// third, we'll deal with accounts which are inactive. For more
// information, see the Trac ticket #720.
final int expired = removeUnusedNewAccounts();
final int suspended = suspendInactiveAccounts(authentication);
final int deleted = deleteSuspendedAccounts(authentication);
final DateFormat dateFormatter = new SimpleDateFormat(IWSConstants.DATE_TIME_FORMAT, IWSConstants.DEFAULT_LOCALE);
final long duration = (System.nanoTime() - start) / 1000000;
LOG.info("Cleanup took: {}ms (Users expired {}, suspended {} & deleted {}), next Timeout: {}", duration, expired, suspended, deleted, dateFormatter.format(timer.getNextTimeout()));
}
/**
* Remove deprecated Sessions.
*/
private int removeDeprecatedSessions() {
// First, let's calculate the time of expiry. All Sessions with a
// modification date before this, will be deprecated
final Long timeout = settings.getMaxIdleTimeForSessions();
final Date date = new Date(new Date().getTime() - timeout);
int count = 0;
// Iterate over the currently active sessions and remove them.
final List<SessionEntity> sessions = accessDao.findActiveSessions();
for (final SessionEntity session : sessions) {
if (session.getModified().before(date.toDate())) {
// Remove the found Session from the ActiveSessions Registry ...
activeSessions.removeToken(session.getSessionKey());
// ... and remove it from the database as well
accessDao.deprecateSession(session);
count++;
}
}
return count;
}
/**
* Runs the Offer Expiration. Although the state for an Offer is part of
* both the Offer & Offer Shares, only the Offer itself is updated, thus
* avoiding that any information is lost.<br />
* Offers expire if the Nomination Deadline passed. Please see Trac Ticket
* #1020 for more on the discussion. Please note, that although the code
* here is passing an auditing, there has been a problem with Offers that
* has suddenly expired, please see Trac ticket #1052 for details. For this
* reason, the method is now having increased logging.
*/
private void runExpiredOfferProcessing() {
try {
final List<OfferEntity> offers = exchangeDao.findExpiredOffers(new java.util.Date());
LOG.info("Found {} Offers to expire.", offers.size());
for (final OfferEntity offer : offers) {
offer.setStatus(OfferState.EXPIRED);
accessDao.persist(offer);
LOG.info("Offer {} has expired.", offer.getRefNo());
}
} catch (IllegalArgumentException | IWSException e) {
LOG.error("Error in processing expired offers", e);
}
}
/**
* Remove unused Accounts, i.e. Account with status NEW and which have not
* been activated following a period of x days.
*
* @return Number of Expired (never activated) Accounts
*/
private int removeUnusedNewAccounts() {
final Long days = settings.getAccountUnusedRemovedDays();
LOG.debug("Checking of any accounts exists which has expired, i.e. status NEW after {} days.", days);
int accounts = 0;
// We have a User Account, that was never activated. This we can
// delete completely
final List<UserEntity> newUsers = accessDao.findAccountsWithState(UserStatus.NEW, days);
for (final UserEntity user : newUsers) {
// Just to make sure that we're not removing the System Account, as
// that would be rather fatal!
if (user.getId() != InternalConstants.SYSTEM_ACCOUNT) {
LOG.info("Deleting Expired NEW Account for {} {} <{}>.", user.getFirstname(), user.getLastname(), user.getUsername());
service.deleteNewUser(user);
accounts++;
}
}
return accounts;
}
/**
* Suspend inactive users. Accounts which are currently having status
* ACTIVE, but have not been used after z days, will be set to SUSPENDED.
*
* @return Number of Suspended Accounts
*/
private int suspendInactiveAccounts(final Authentication authentication) {
// Note, that we have 2 problems here. The first problem is to fetch all
// Users, who've been inactive for a a period of x days. This is the
// permanent problem to solve with this function, since otherwise
// inactive accounts, i.e. accounts where no sessions exists will be
// dealt with also.
// However, it leaves remaining accounts, which was migrated and have
// status ACTIVE, but was never used. Dealing with these accounts is
// beyond the scope of this Bean - and must be dealt with separately. It
// is easy to find these, since the SALT they have for their encrypted
// Passwords is either "undefined" or "heartbleed".
// Accounts which have not been used since the Migration from IW3 to
// IWS in January 2014, was given the "undefined" SALT, since IW3 used a
// simple MD5 checksum, and IWS uses a Salted SHA2. As of September
// 2014, 1.645 Accounts still have this Salt. Which means these Accounts
// can all be considered abandoned or deprecated.
// In April 2014, an OpenSSL flaw submerged dubbed Heartbleed. All
// Accounts was re-salted with the salt "heartbleed", to force a renewal
// of the Passwords. As of September 2014, 375 Accounts still have this
// Salt, and have thus never updated the Passwords. However, Re-salting
// was never applied to the originally migrated Accounts, so these will
// be caught by this method.
// The complexity of this Update is rather high, since we have to look
// at a number of parameters, which either is or should be indexed! This
// is an SQL query to solve the issue, which must be converted to JPA:
// -----------------------------------
// with activity as (
// select
// u.id as id,
// max(s.created) as latest
// from
// users u
// left join sessions s on u.id = s.user_id
// where u.status = 'ACTIVE'
// group by u.id)
// select id
// from activity
// where latest is null
// or latest < :date;
// -----------------------------------
final Long days = settings.getAccountInactiveDays();
LOG.info("Fetching the list of Users to be suspended.");
final List<UserEntity> users = accessDao.findInactiveAccounts(days);
if (!users.isEmpty()) {
for (final UserEntity user : users) {
LOG.info("Attempting to suspend the User {} {} <{}>.", user.getFirstname(), user.getLastname(), user.getUsername());
service.suspendUser(authentication, user);
}
}
// For now - just returning the number of Records
return users.size();
}
/**
* Delete inactive users. Accounts which have status SUSPENDED will after a
* period of y days be deleted, meaning that all private information will be
* removed, and account will have the status set to DELETED.<br />
* Note, that although accounts should be deleted, we cannot leave member
* groups without an owner. Accounts which is currently owner, will simply
* be ignored. The rule applies only to currently active Groups. Groups
* which have been suspended will be ignored.
*
* @return Number of Deleted Accounts
*/
private int deleteSuspendedAccounts(final Authentication authentication) {
// select
// u.id,
// u.firstname,
// u.lastname,
// max(s.modified)
// from
// sessions s
// join users u on s.user_id = u.id
// where u.status = 'ACTIVE'
// and s.modified < '2014-09-01'::date
// group by u.id, u.firstname, u.lastname
// order by max(s.modified);
final Long days = settings.getAccountSuspendedDays();
LOG.debug("Checking if Accounts exists with status SUSPENDED after {} days.", days);
int accounts = 0;
final List<UserEntity> suspendedUsers = accessDao.findAccountsWithState(UserStatus.SUSPENDED, days);
if (!suspendedUsers.isEmpty()) {
for (final UserEntity user : suspendedUsers) {
try {
LOG.info("Attempting to delete Suspended Account for {} {} <{}>.", user.getFirstname(), user.getLastname(), user.getUsername());
service.deletePrivateData(authentication, user);
accounts++;
} catch (IWSException e) {
LOG.debug(e.getMessage(), e);
LOG.warn("Unable to delete the Account for {} {} <{}>, reason: {}", user.getFirstname(), user.getLastname(), user.getUsername(), e.getMessage());
}
}
}
return accounts;
}
}
|
Added NS Check to State Bean before Suspending Accounts.
The State Bean was so far suspending accounts if they were inactive for longer than n days (configurable via the properties file). However, this had the undesirable side-effect that some National Secretaries were also suspended, although they shouldn't be. As a consequence, some countries lost access to the IntraWeb.
This commit adds a check to see if a person is the owner of either an Administrative, Member, National or International Group, if so - we're logging this and ignoring the Account.
|
iws-ejb/src/main/java/net/iaeste/iws/ejb/StateBean.java
|
Added NS Check to State Bean before Suspending Accounts.
|
<ide><path>ws-ejb/src/main/java/net/iaeste/iws/ejb/StateBean.java
<ide> package net.iaeste.iws.ejb;
<ide>
<ide> import net.iaeste.iws.api.constants.IWSConstants;
<add>import net.iaeste.iws.api.enums.GroupStatus;
<add>import net.iaeste.iws.api.enums.GroupType;
<ide> import net.iaeste.iws.api.enums.UserStatus;
<ide> import net.iaeste.iws.api.enums.exchange.OfferState;
<ide> import net.iaeste.iws.api.exceptions.IWSException;
<ide> import net.iaeste.iws.persistence.ExchangeDao;
<ide> import net.iaeste.iws.persistence.entities.SessionEntity;
<ide> import net.iaeste.iws.persistence.entities.UserEntity;
<add>import net.iaeste.iws.persistence.entities.UserGroupEntity;
<ide> import net.iaeste.iws.persistence.entities.exchange.OfferEntity;
<ide> import net.iaeste.iws.persistence.jpa.AccessJpaDao;
<ide> import net.iaeste.iws.persistence.jpa.ExchangeJpaDao;
<ide> import javax.persistence.EntityManager;
<ide> import java.text.DateFormat;
<ide> import java.text.SimpleDateFormat;
<add>import java.util.EnumSet;
<ide> import java.util.List;
<add>import java.util.Set;
<ide>
<ide> /**
<del> * When the IWS is starting up, we need to ensure that the current State is such
<del> * that the system will work correctly. The purpose of this Bean is simply to
<del> * ensure that.<br />
<del> * The Bean has two parts. First is what happens at startup, the second is to
<add> * <p>When the IWS is starting up, we need to ensure that the current State is
<add> * such that the system will work correctly. The purpose of this Bean is simply
<add> * to ensure that.</p>
<add> *
<add> * <p>The Bean has two parts. First is what happens at startup, the second is to
<ide> * managed a Cron like service, which will run every night during the time where
<del> * the system has the lowest load.<br />
<del> * At startup, the Bean will Clear all existing active Sessions, so nothing
<add> * the system has the lowest load.</p>
<add> *
<add> * <p>At startup, the Bean will Clear all existing active Sessions, so nothing
<ide> * exists in the database. This will prevent existing Sessions from continuing
<ide> * to work, but as there may be other issues around a re-start, it is the least
<del> * harmful.<br />
<del> * The Cron part will run every night, and both discard deprecated Sessions,
<add> * harmful.</p>
<add> *
<add> * <p>The Cron part will run every night, and both discard deprecated Sessions,
<ide> * but also update Accounts. To avoid that inactive/suspended/dead Accounts will
<del> * clutter up the system.
<add> * clutter up the system.</p>
<ide> *
<ide> * @author Kim Jensen / last $Author:$
<ide> * @version $Revision:$ / $Date:$
<ide> }
<ide>
<ide> /**
<del> * Suspend inactive users. Accounts which are currently having status
<del> * ACTIVE, but have not been used after z days, will be set to SUSPENDED.
<add> * <p>This will suspend all inactive Accounts, meaning an account which has
<add> * not been used for a period of time, which is defined in the IWS
<add> * Properties.</p>
<add> *
<add> * <p>Suspension will change the state of the Account from ACTIVE to
<add> * SUSPENDED. Note that National Secretaries is except from this rule, so
<add> * any currently active Committee will always have at least one active
<add> * account.</p>
<ide> *
<ide> * @return Number of Suspended Accounts
<ide> */
<ide> private int suspendInactiveAccounts(final Authentication authentication) {
<del> // Note, that we have 2 problems here. The first problem is to fetch all
<del> // Users, who've been inactive for a a period of x days. This is the
<del> // permanent problem to solve with this function, since otherwise
<del> // inactive accounts, i.e. accounts where no sessions exists will be
<del> // dealt with also.
<del> // However, it leaves remaining accounts, which was migrated and have
<del> // status ACTIVE, but was never used. Dealing with these accounts is
<del> // beyond the scope of this Bean - and must be dealt with separately. It
<del> // is easy to find these, since the SALT they have for their encrypted
<del> // Passwords is either "undefined" or "heartbleed".
<del> // Accounts which have not been used since the Migration from IW3 to
<del> // IWS in January 2014, was given the "undefined" SALT, since IW3 used a
<del> // simple MD5 checksum, and IWS uses a Salted SHA2. As of September
<del> // 2014, 1.645 Accounts still have this Salt. Which means these Accounts
<del> // can all be considered abandoned or deprecated.
<del> // In April 2014, an OpenSSL flaw submerged dubbed Heartbleed. All
<del> // Accounts was re-salted with the salt "heartbleed", to force a renewal
<del> // of the Passwords. As of September 2014, 375 Accounts still have this
<del> // Salt, and have thus never updated the Passwords. However, Re-salting
<del> // was never applied to the originally migrated Accounts, so these will
<del> // be caught by this method.
<del> // The complexity of this Update is rather high, since we have to look
<del> // at a number of parameters, which either is or should be indexed! This
<del> // is an SQL query to solve the issue, which must be converted to JPA:
<del> // -----------------------------------
<del> // with activity as (
<del> // select
<del> // u.id as id,
<del> // max(s.created) as latest
<del> // from
<del> // users u
<del> // left join sessions s on u.id = s.user_id
<del> // where u.status = 'ACTIVE'
<del> // group by u.id)
<del> // select id
<del> // from activity
<del> // where latest is null
<del> // or latest < :date;
<del> // -----------------------------------
<ide> final Long days = settings.getAccountInactiveDays();
<ide> LOG.info("Fetching the list of Users to be suspended.");
<ide> final List<UserEntity> users = accessDao.findInactiveAccounts(days);
<add> int suspended = 0;
<add>
<ide> if (!users.isEmpty()) {
<ide> for (final UserEntity user : users) {
<del> LOG.info("Attempting to suspend the User {} {} <{}>.", user.getFirstname(), user.getLastname(), user.getUsername());
<del> service.suspendUser(authentication, user);
<del> }
<del> }
<del>
<del> // For now - just returning the number of Records
<del> return users.size();
<add> if (maySuspendUser(user)) {
<add> LOG.info("Attempting to suspend the User {} {} <{}>.", user.getFirstname(), user.getLastname(), user.getUsername());
<add> service.suspendUser(authentication, user);
<add> suspended++;
<add> } else {
<add> LOG.info("Ignoring inactive National Secretary {} {} <{}>.", user.getFirstname(), user.getLastname(), user.getUsername());
<add> }
<add> }
<add> }
<add>
<add> return suspended;
<add> }
<add>
<add> /**
<add> * <p>It has been an ongoing problem that some accounts have been suspended,
<add> * although they belong to the National Secretary of a Country. This is
<add> * problematic, as it prevents that the person can do a correct hand-over if
<add> * been inactive for too long.</p>
<add> *
<add> * <p>Instead, this check is added, and if a User is Owner of either an
<add> * Administrative, International, Member or National (Staff) Group, then it
<add> * is skipped.</p>
<add> *
<add> * @param user The User to check, if may be suspended
<add> * @return True if the User may be suspended, otherwise false
<add> */
<add> private boolean maySuspendUser(final UserEntity user) {
<add> final List<UserGroupEntity> relations = accessDao.findAllUserGroups(user);
<add> final Set<GroupType> allowed = EnumSet.of(GroupType.ADMINISTRATION, GroupType.INTERNATIONAL, GroupType.MEMBER, GroupType.NATIONAL);
<add> boolean maySuspend = true;
<add>
<add> for (final UserGroupEntity relation : relations) {
<add> final GroupType type = relation.getGroup().getGroupType().getGrouptype();
<add> final GroupStatus status = relation.getGroup().getStatus();
<add> final long roleId = relation.getRole().getId();
<add>
<add> if ((status == GroupStatus.ACTIVE) &&
<add> (roleId == InternalConstants.ROLE_OWNER) &&
<add> allowed.contains(type)) {
<add> maySuspend = false;
<add> break;
<add> }
<add> }
<add>
<add> return maySuspend;
<ide> }
<ide>
<ide> /**
<ide> * @return Number of Deleted Accounts
<ide> */
<ide> private int deleteSuspendedAccounts(final Authentication authentication) {
<del> // select
<del> // u.id,
<del> // u.firstname,
<del> // u.lastname,
<del> // max(s.modified)
<del> // from
<del> // sessions s
<del> // join users u on s.user_id = u.id
<del> // where u.status = 'ACTIVE'
<del> // and s.modified < '2014-09-01'::date
<del> // group by u.id, u.firstname, u.lastname
<del> // order by max(s.modified);
<ide> final Long days = settings.getAccountSuspendedDays();
<ide> LOG.debug("Checking if Accounts exists with status SUSPENDED after {} days.", days);
<ide> int accounts = 0;
|
|
Java
|
mit
|
5ea43e73c06032f437271f86c509e3d13016d309
| 0 |
yasikstudio/devrank,yasikstudio/devrank,yasikstudio/devrank,yasikstudio/devrank,yasikstudio/devrank
|
package com.yasikstudio.devrank.merge;
import java.io.IOException;
import java.util.List;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class DataMergeReducer extends Reducer<Text, UserRecord, Text, NullWritable> {
private static final String FIELD_SEP = "|";
private static final String LIST_SEP = ",";
private static final String COUNT_SEP = ":";
@Override
protected void reduce(Text key, Iterable<UserRecord> values, Context context)
throws IOException, InterruptedException {
UserRecord user = new UserRecord();
boolean existing = user.exists();
user.setUid(key.toString());
for (UserRecord u : values) {
existing = existing || u.exists();
MergeUtils.merge(user, u);
}
user.setExists(existing);
//if (existing) {
context.write(new Text(writeToString(user)), null);
//}
}
private String writeToString(UserRecord user) {
// uid
// |follow1:1,follow2:1
// |fork1:1,fork2:1
// |pull_1:324,pull_2:123
// |star1:1,star2:1
// |watch1:1,watch2:1
StringBuilder out = new StringBuilder();
out.append(user.getUid()).append(FIELD_SEP);
appendWeightList(out, user.getFollowings()).append(FIELD_SEP);
appendWeightList(out, user.getForks()).append(FIELD_SEP);
appendWeightList(out, user.getPulls()).append(FIELD_SEP);
appendWeightList(out, user.getStars()).append(FIELD_SEP);
appendWeightList(out, user.getWatchs());
return out.toString();
}
private StringBuilder appendWeightList(StringBuilder out, List<Weight> weights) {
int size = weights.size();
for (int i = 0; i < size; i++) {
Weight w = weights.get(i);
out.append(w.getId()).append(COUNT_SEP).append(w.getCount());
if (i != size - 1) {
out.append(LIST_SEP);
}
}
return out;
}
}
|
devrank-job/src/main/java/com/yasikstudio/devrank/merge/DataMergeReducer.java
|
package com.yasikstudio.devrank.merge;
import java.io.IOException;
import java.util.List;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class DataMergeReducer extends Reducer<Text, UserRecord, Text, NullWritable> {
private static final String FIELD_SEP = "|";
private static final String LIST_SEP = ",";
private static final String COUNT_SEP = ":";
@Override
protected void reduce(Text key, Iterable<UserRecord> values, Context context)
throws IOException, InterruptedException {
UserRecord user = new UserRecord();
boolean existing = user.exists();
user.setUid(key.toString());
for (UserRecord u : values) {
existing = existing || u.exists();
MergeUtils.merge(user, u);
}
user.setExists(existing);
if (existing) {
context.write(new Text(writeToString(user)), null);
}
}
private String writeToString(UserRecord user) {
// uid
// |follow1:1,follow2:1
// |fork1:1,fork2:1
// |pull_1:324,pull_2:123
// |star1:1,star2:1
// |watch1:1,watch2:1
StringBuilder out = new StringBuilder();
out.append(user.getUid()).append(FIELD_SEP);
appendWeightList(out, user.getFollowings()).append(FIELD_SEP);
appendWeightList(out, user.getForks()).append(FIELD_SEP);
appendWeightList(out, user.getPulls()).append(FIELD_SEP);
appendWeightList(out, user.getStars()).append(FIELD_SEP);
appendWeightList(out, user.getWatchs());
return out.toString();
}
private StringBuilder appendWeightList(StringBuilder out, List<Weight> weights) {
int size = weights.size();
for (int i = 0; i < size; i++) {
Weight w = weights.get(i);
out.append(w.getId()).append(COUNT_SEP).append(w.getCount());
if (i != size - 1) {
out.append(LIST_SEP);
}
}
return out;
}
}
|
Supress existing check
|
devrank-job/src/main/java/com/yasikstudio/devrank/merge/DataMergeReducer.java
|
Supress existing check
|
<ide><path>evrank-job/src/main/java/com/yasikstudio/devrank/merge/DataMergeReducer.java
<ide>
<ide> user.setExists(existing);
<ide>
<del> if (existing) {
<del> context.write(new Text(writeToString(user)), null);
<del> }
<add> //if (existing) {
<add> context.write(new Text(writeToString(user)), null);
<add> //}
<ide> }
<ide>
<ide> private String writeToString(UserRecord user) {
|
|
Java
|
apache-2.0
|
cd8cf72b11e86492e4ab85ddb7f21e19cba14eb5
| 0 |
eFaps/eFapsApp-Accounting
|
/*
* Copyright 2003 - 2013 The eFaps Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Revision: $Rev: 7855 $
* Last Changed: $Date: 2012-08-02 20:35:53 -0500 (jue, 02 ago 2012) $
* Last Changed By: $Author: [email protected] $
*/
package org.efaps.esjp.accounting;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.efaps.admin.datamodel.Classification;
import org.efaps.admin.datamodel.Type;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.event.Return;
import org.efaps.admin.program.esjp.EFapsRevision;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.ci.CIType;
import org.efaps.db.Context;
import org.efaps.db.Context.FileParameter;
import org.efaps.db.Delete;
import org.efaps.db.Insert;
import org.efaps.db.Instance;
import org.efaps.db.InstanceQuery;
import org.efaps.db.MultiPrintQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.db.SelectBuilder;
import org.efaps.db.Update;
import org.efaps.esjp.ci.CIAccounting;
import org.efaps.util.EFapsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import au.com.bytecode.opencsv.CSVReader;
/**
* TODO comment!
*
* @author The eFaps Team
* @version $Id: Periode_Base.java 7855 2012-08-03 01:35:53Z [email protected] $
*/
@EFapsUUID("4f7c8d48-01d0-4862-82e7-2efcf6761e5a")
@EFapsRevision("$Rev: 7855 $")
public abstract class Import_Base
{
private static final Logger LOG = LoggerFactory.getLogger(Import_Base.class);
/**
* Definitions for Columns.
*/
public interface Column
{
/**
* @return key
*/
String getKey();
}
private enum CaseColumn implements Import_Base.Column {
/** */
A2CTYPE("[Account2Case_Type]"),
A2CACC("[Account2Case_Account]"),
A2CCLA("[Account2Case_Classification]"),
A2CNUM("[Account2Case_Numerator]"),
A2CDENUM("[Account2Case_Denominator]"),
A2CDEFAULT("[Account2Case_Default]"),
CASETYPE("[Case_Type]"),
CASENAME("[Case_Name]"),
CASEDESC("[Case_Description]");
;
/** Key. */
private final String key;
/**
* @param _key key
*/
private CaseColumn(final String _key)
{
this.key = _key;
}
/**
* Getter method for instance variable {@link #key}.
*
* @return value of instance variable {@link #key}
*/
@Override
public String getKey()
{
return this.key;
}
}
/**
* Columns for an account table.
*
*/
private enum AcccountColumn implements Import_Base.Column {
/** */
VALUE("[Account_Value]"),
/** */
NAME("[Account_Name]"),
/** */
TYPE("[Account_Type]"),
/** */
SUMMARY("[Account_Summary]"),
/** */
PARENT("[Account_Parent]"),
/** */
KEY("[Account_Key]"),
/** */
ACC_REL("[Account_Relation]"),
/** */
ACC_TARGET("[Account_Target]");
/** Key. */
private final String key;
/**
* @param _key key
*/
private AcccountColumn(final String _key)
{
this.key = _key;
}
/**
* Getter method for instance variable {@link #key}.
*
* @return value of instance variable {@link #key}
*/
@Override
public String getKey()
{
return this.key;
}
}
/**
* Columns for an report.
*/
private enum ReportColumn implements Import_Base.Column {
/** */
TYPE("[Report_Type]"),
/** */
NAME("[Report_Name]"),
/** */
DESC("[Report_Description]"),
/** */
NUMBERING("[Report_Numbering]"),
/** */
NODE_TYPE("[Node_Type]"),
/** */
NODE_SHOW("[Node_ShowAllways]"),
/** */
NODE_SUM("[Node_ShowSum]"),
/** */
NODE_NUMBER("[Node_Number]");
/** Key. */
private final String key;
/**
* @param _key key
*/
private ReportColumn(final String _key)
{
this.key = _key;
}
/**
* Getter method for instance variable {@link #key}.
*
* @return value of instance variable {@link #key}
*/
@Override
public String getKey()
{
return this.key;
}
}
/**
* Mapping of types as written in the csv and the name in eFaps.
*/
protected static final Map<String, CIType> TYPE2TYPE = new HashMap<String, CIType>();
static {
Import_Base.TYPE2TYPE.put("Asset", CIAccounting.AccountBalanceSheetAsset);
Import_Base.TYPE2TYPE.put("Liability", CIAccounting.AccountBalanceSheetLiability);
Import_Base.TYPE2TYPE.put("Owner's equity", CIAccounting.AccountBalanceSheetEquity);
Import_Base.TYPE2TYPE.put("Expense", CIAccounting.AccountIncomeStatementExpenses);
Import_Base.TYPE2TYPE.put("Revenue", CIAccounting.AccountIncomeStatementRevenue);
Import_Base.TYPE2TYPE.put("Current", CIAccounting.AccountCurrent);
Import_Base.TYPE2TYPE.put("Creditor", CIAccounting.AccountCurrentCreditor);
Import_Base.TYPE2TYPE.put("Debtor", CIAccounting.AccountCurrentDebtor);
Import_Base.TYPE2TYPE.put("Memo", CIAccounting.AccountMemo);
Import_Base.TYPE2TYPE.put("Balance", CIAccounting.ReportBalance);
Import_Base.TYPE2TYPE.put("ProfitLoss", CIAccounting.ReportProfitLoss);
Import_Base.TYPE2TYPE.put("Other", CIAccounting.ReportTransaction);
Import_Base.TYPE2TYPE.put("Root", CIAccounting.ReportNodeRoot);
Import_Base.TYPE2TYPE.put("Tree", CIAccounting.ReportNodeTree);
Import_Base.TYPE2TYPE.put("Account", CIAccounting.ReportNodeAccount);
Import_Base.TYPE2TYPE.put("ReportAccount", CIAccounting.ReportAccount);
Import_Base.TYPE2TYPE.put("ViewRoot", CIAccounting.ViewRoot);
Import_Base.TYPE2TYPE.put("ViewSum", CIAccounting.ViewSum);
Import_Base.TYPE2TYPE.put("CaseBankCashGain", CIAccounting.CaseBankCashGain);
Import_Base.TYPE2TYPE.put("CaseBankCashPay", CIAccounting.CaseBankCashPay);
Import_Base.TYPE2TYPE.put("CaseDocBooking", CIAccounting.CaseDocBooking);
Import_Base.TYPE2TYPE.put("CaseDocRegister", CIAccounting.CaseDocRegister);
Import_Base.TYPE2TYPE.put("CaseExternalBooking", CIAccounting.CaseExternalBooking);
Import_Base.TYPE2TYPE.put("CaseExternalRegister", CIAccounting.CaseExternalRegister);
Import_Base.TYPE2TYPE.put("CaseGeneral", CIAccounting.CaseGeneral);
Import_Base.TYPE2TYPE.put("CasePayroll", CIAccounting.CasePayroll);
Import_Base.TYPE2TYPE.put("CasePettyCash", CIAccounting.CasePettyCash);
Import_Base.TYPE2TYPE.put("CaseStockBooking", CIAccounting.CaseStockBooking);
}
protected static final Map<String, CIType> ACC2ACC = new HashMap<String, CIType>();
static {
Import_Base.ACC2ACC.put("ViewSumAccount", CIAccounting.ViewSum2Account);
Import_Base.ACC2ACC.put("AccountCosting", CIAccounting.Account2AccountCosting);
Import_Base.ACC2ACC.put("AccountInverseCosting", CIAccounting.Account2AccountCostingInverse);
Import_Base.ACC2ACC.put("AccountAbono", CIAccounting.Account2AccountCredit);
Import_Base.ACC2ACC.put("AccountCargo", CIAccounting.Account2AccountDebit);
}
protected static final Map<String, CIType> ACC2CASE = new HashMap<String, CIType>();
static {
Import_Base.ACC2CASE.put("Credit", CIAccounting.Account2CaseCredit);
Import_Base.ACC2CASE.put("Debit", CIAccounting.Account2CaseDebit);
Import_Base.ACC2CASE.put("CreditClassification", CIAccounting.Account2CaseCredit4Classification);
Import_Base.ACC2CASE.put("DebitClassification", CIAccounting.Account2CaseDebit4Classification);
}
/**
* Key for a level column.
*/
private static String LEVELCOLUMN = "[Level #]";
/**
* Called on a command to create a new reports of the file.
*
* @param _parameter Paremeter as passed from the eFaps API.
* @return new Return
* @throws EFapsException on error
*/
public Return createReportOfFile(final Parameter _parameter)
throws EFapsException
{
final String periode = _parameter.getParameterValue("periodeLink");
final FileParameter reports = Context.getThreadContext().getFileParameters().get("reports");
if (periode != null && reports != null) {
final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.Periode);
queryBldr.addWhereAttrEqValue(CIAccounting.Periode.ID, periode);
final MultiPrintQuery multi = queryBldr.getPrint();
multi.addAttribute(CIAccounting.Periode.OID);
multi.execute();
Instance instance = null;
while (multi.next()) {
instance = Instance.get(multi.<String>getAttribute(CIAccounting.Periode.OID));
}
if (instance != null) {
createReports(instance, reports, getImportAccountFromDB(_parameter, instance));
}
}
return new Return();
}
/**
* Obtains account from the DB.
*
* @param _parameter Parameter as passed from the eFaps API.
* @param _instance Instance of the period.
* @return ret with accounts.
* @throws EFapsException on error.
*/
protected Map<String, ImportAccount> getImportAccountFromDB(final Parameter _parameter,
final Instance _instance)
throws EFapsException
{
final Map<String, ImportAccount> ret = new HashMap<String, ImportAccount>();
final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.PeriodeAbstractLink, _instance.getId());
final MultiPrintQuery multi = queryBldr.getPrint();
final SelectBuilder sel = new SelectBuilder().linkto(CIAccounting.AccountAbstract.ParentLink)
.attribute(CIAccounting.AccountAbstract.Name);
multi.addSelect(sel);
multi.addAttribute(CIAccounting.AccountAbstract.Name,
CIAccounting.AccountAbstract.Description);
multi.execute();
while (multi.next()) {
final String parentName = multi.<String>getSelect(sel);
final String name = multi.<String>getAttribute(CIAccounting.AccountAbstract.Name);
final String desc = multi.<String>getAttribute(CIAccounting.AccountAbstract.Description);
ret.put(name, new ImportAccount(multi.getCurrentInstance(), parentName, name, desc, null, null, null, null));
}
return ret;
}
/**
* @param _periodInst periode the account table belongs to
* @param _reports csv file
* @param _accounts map of accounts
* @throws EFapsException on error
*/
protected void createReports(final Instance _periodInst,
final FileParameter _reports,
final Map<String, ImportAccount> _accounts)
throws EFapsException
{
try {
final CSVReader reader = new CSVReader(new InputStreamReader(_reports.getInputStream(), "UTF-8"));
final List<String[]> entries = reader.readAll();
if (!entries.isEmpty()) {
final Map<String, Integer> colName2Index = evaluateCSVFileHeader(Import_Base.ReportColumn.values(),
entries.get(0), null);
reader.close();
Integer i = 0;
final String[] headRow = entries.get(0);
boolean found = true;
while (found) {
found = false;
final String level = Import_Base.LEVELCOLUMN.replace("#", i.toString());
int idx = 0;
for (final String column : headRow) {
if (level.equals(column.trim())) {
i++;
found = true;
colName2Index.put(level, idx);
break;
}
idx++;
}
}
entries.remove(0);
final Map<String, ImportReport> reports = new HashMap<String, ImportReport>();
ImportReport report = null;
for (final String[] row : entries) {
report = getImportReport(_periodInst, colName2Index, row, reports);
report.addNode(colName2Index, row, i, _accounts);
}
}
} catch (final IOException e) {
throw new EFapsException(Import_Base.class, "createReports.IOException", e);
}
}
/**
* method for obtains reports of a import.
*
* @param _periodInst Instance of the period.
* @param _colName2Index cols of the report.
* @param _row rows of the report.
* @param _reports values of the report.
* @return ret with values.
* @throws EFapsException on error.
*/
protected ImportReport getImportReport(final Instance _periodInst,
final Map<String, Integer> _colName2Index,
final String[] _row,
final Map<String, ImportReport> _reports)
throws EFapsException
{
final ImportReport ret;
final String type = _row[_colName2Index.get(Import_Base.ReportColumn.TYPE.getKey())].trim()
.replaceAll("\n", "");
final String name = _row[_colName2Index.get(Import_Base.ReportColumn.NAME.getKey())].trim()
.replaceAll("\n", "");
final String description = _row[_colName2Index.get(Import_Base.ReportColumn.DESC.getKey())].trim()
.replaceAll("\n", "");
final String numbering = _row[_colName2Index.get(Import_Base.ReportColumn.NUMBERING.getKey())].trim()
.replaceAll("\n", "");
final String key = type + ":" + name;
if (_reports.containsKey(key)) {
ret = _reports.get(key);
} else {
ret = new ImportReport(_periodInst, type, name, description, numbering);
_reports.put(key, ret);
}
return ret;
}
/**
* @param _periodInst periode the account table belongs to
* @param _accountTable csv file
* @return HashMap
* @throws EFapsException on error
*/
protected HashMap<String, ImportAccount> createAccountTable(final Instance _periodInst,
final FileParameter _accountTable)
throws EFapsException
{
final HashMap<String, ImportAccount> accounts = new HashMap<String, ImportAccount>();
try {
final CSVReader reader = new CSVReader(new InputStreamReader(_accountTable.getInputStream(), "UTF-8"));
final List<String[]> entries = reader.readAll();
reader.close();
final Map<String, List<String>> validateMap = new HashMap<String, List<String>>();
final Map<String, Integer> colName2Index = evaluateCSVFileHeader(Import_Base.AcccountColumn.values(),
entries.get(0), validateMap);
entries.remove(0);
for (final String[] row : entries) {
final ImportAccount account = new ImportAccount(_periodInst, colName2Index, row, validateMap, null);
accounts.put(account.getValue(), account);
}
for (final ImportAccount account : accounts.values()) {
if (account.getParent() != null && account.getParent().length() > 0) {
final ImportAccount parent = accounts.get(account.getParent());
if (parent != null) {
final Update update = new Update(account.getInstance());
update.add("ParentLink", parent.getInstance().getId());
update.execute();
}
}
if (account.getLstTypeConn() != null && !account.getLstTypeConn().isEmpty() &&
account.getLstTargetConn() != null && !account.getLstTargetConn().isEmpty()) {
final List<Type> lstTypes = account.getLstTypeConn();
final List<String> lstTarget = account.getLstTargetConn();
int cont = 0;
for (final Type type : lstTypes) {
deleteExistingConnections(type, account.getInstance());
final String nameAcc = lstTarget.get(cont);
final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, nameAcc);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.PeriodeAbstractLink,
_periodInst.getId());
final InstanceQuery query = queryBldr.getQuery();
query.execute();
if (query.next()) {
final Insert insert = new Insert(type);
insert.add(CIAccounting.Account2AccountAbstract.FromAccountLink,
account.getInstance().getId());
insert.add(CIAccounting.Account2AccountAbstract.ToAccountLink,
query.getCurrentValue().getId());
insert.execute();
}
cont++;
}
}
}
} catch (final IOException e) {
throw new EFapsException(Periode.class, "createAccountTable.IOException", e);
}
return accounts;
}
protected void deleteExistingConnections(final Type _type,
final Instance _accInstance)
throws EFapsException
{
final QueryBuilder queryBldrConn = new QueryBuilder(_type);
queryBldrConn.addWhereAttrEqValue(CIAccounting.Account2AccountAbstract.FromAccountLink, _accInstance);
final InstanceQuery query = queryBldrConn.getQuery();
query.execute();
while (query.next()) {
final Delete delete = new Delete(query.getCurrentValue());
delete.execute();
}
}
protected HashMap<String, ImportAccount> createViewAccountTable(final Instance _periodInst,
final FileParameter _accountTable)
throws EFapsException
{
final HashMap<String, ImportAccount> accounts = new HashMap<String, ImportAccount>();
final HashMap<String, ImportAccount> accountsVal = new HashMap<String, ImportAccount>();
try {
final CSVReader reader = new CSVReader(new InputStreamReader(_accountTable.getInputStream(), "UTF-8"));
final List<String[]> entries = reader.readAll();
reader.close();
final Map<String, List<String>> validateMap = new HashMap<String, List<String>>();
final Map<String, Integer> colName2Index = evaluateCSVFileHeader(Import_Base.AcccountColumn.values(),
entries.get(0), validateMap);
entries.remove(0);
for (final String[] row : entries) {
final ImportAccount account = new ImportAccount(colName2Index, row);
accountsVal.put(account.getOrder(), account);
}
for (final ImportAccount account : accountsVal.values()) {
ImportAccount parent = accountsVal.get(account.getParent());
while (parent != null) {
account.setPath(account.getPath() + "_" + parent.getValue());
parent = parent.getParent() != null ? accountsVal.get(parent.getParent()) : null;
}
}
for (final String[] row : entries) {
final ImportAccount account = new ImportAccount(_periodInst, colName2Index, row, validateMap, accountsVal);
accounts.put(account.getOrder(), account);
}
for (final ImportAccount account : accounts.values()) {
if (account.getParent() != null && account.getParent().length() > 0) {
final ImportAccount parent = accounts.get(account.getParent());
if (parent != null) {
final Update update = new Update(account.getInstance());
update.add(CIAccounting.AccountBaseAbstract.ParentLink, parent.getInstance().getId());
update.execute();
}
}
if (account.getLstTypeConn() != null && !account.getLstTypeConn().isEmpty() &&
account.getLstTargetConn() != null && !account.getLstTargetConn().isEmpty()) {
final List<Type> lstTypes = account.getLstTypeConn();
final List<String> lstTarget = account.getLstTargetConn();
int cont = 0;
for (final Type type : lstTypes) {
final String nameAcc = lstTarget.get(cont);
final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, nameAcc);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.PeriodeAbstractLink,
_periodInst.getId());
final InstanceQuery query = queryBldr.getQuery();
query.execute();
if (query.next()) {
final Insert insert = new Insert(type);
insert.add(CIAccounting.View2AccountAbstract.FromLinkAbstract,
account.getInstance().getId());
insert.add(CIAccounting.View2AccountAbstract.ToLinkAbstract,
query.getCurrentValue().getId());
insert.execute();
}
cont++;
}
}
}
} catch (final IOException e) {
throw new EFapsException(Periode.class, "createAccountTable.IOException", e);
}
return accounts;
}
protected void createCaseTable(final Instance _periodInst,
final FileParameter _accountTable)
throws EFapsException
{
try {
final CSVReader reader = new CSVReader(new InputStreamReader(_accountTable.getInputStream(), "UTF-8"));
final List<String[]> entries = reader.readAll();
reader.close();
final Map<String, List<String>> validateMap = new HashMap<String, List<String>>();
final Map<String, Integer> colName2Index = evaluateCSVFileHeader(Import_Base.CaseColumn.values(),
entries.get(0), validateMap);
entries.remove(0);
final List<ImportCase> cases = new ArrayList<ImportCase>();
int i = 1;
boolean valid = true;
for (final String[] row : entries) {
Import_Base.LOG.info("reading Line {}: {}",i, row);
final ImportCase impCase = new ImportCase(_periodInst, colName2Index, row);
if (!impCase.validate()) {
valid = false;
Import_Base.LOG.error("Line {} is invalid; {}",i , impCase);
}
cases.add(impCase);
i++;
}
if (valid) {
for (final ImportCase impCase : cases) {
impCase.update();
}
}
} catch (final UnsupportedEncodingException e) {
throw new EFapsException("UnsupportedEncodingException", e);
} catch (final IOException e) {
throw new EFapsException("IOException", e);
}
}
/**
* Evaluates the header of a CSV file to get for each defined column the
* related column number. If no keys are given all columns will be read;
*
* @param _columns columns to read (defined in the header of the file),
* <code>null</code> if all must be read
* @param _headerLine string array with the header line
* @return map defining for each key the related column number
* @throws EFapsException if a column from the list of keys is not defined
*/
protected Map<String, Integer> evaluateCSVFileHeader(final Import_Base.Column[] _columns,
final String[] _headerLine,
final Map<String, List<String>> _validateMap)
throws EFapsException
{
// evaluate header
int idx = 0;
final Map<String, Integer> ret = new HashMap<String, Integer>();
for (final String column : _headerLine) {
if (_columns == null) {
ret.put(column, idx);
} else {
for (final Column columns : _columns) {
if (columns.getKey().equals(column)) {
ret.put(column, idx);
break;
} else {
if (_validateMap != null && column.contains(columns.getKey().replace("]", ""))) {
final String numStr = column.replace(columns.getKey().replace("]", ""), "").replace("]", "");
if (_validateMap.containsKey(numStr)) {
final List<String> lst = _validateMap.get(numStr);
lst.add(column);
} else {
final ArrayList<String> lst = new ArrayList<String>();
lst.add(column);
_validateMap.put(numStr, lst);
}
ret.put(column, idx);
break;
}
}
}
}
idx++;
}
// if keys are defined, check for all required indexes
if (_columns != null) {
for (final Column column : _columns) {
if (ret.get(column.getKey()) == null) {
if (_validateMap != null) {
for (final Entry<String, List<String>> entry : _validateMap.entrySet()) {
if (ret.get(column.getKey().replace("]", "") + entry.getKey() + "]") == null) {
throw new EFapsException(Import_Base.class, "ColumnNotDefinded", column.getKey());
} else {
if (entry.getValue().size() != 2) {
throw new EFapsException(Import_Base.class, "ColumnNotDefinded",
column.getKey() + entry.getKey());
}
}
}
} else {
throw new EFapsException(Import_Base.class, "ColumnNotDefinded",
column.getKey() + column.getKey());
}
}
}
}
Import_Base.LOG.info("analysed table headers: {}", ret);
return ret;
}
public class ImportCase
{
private String caseName;
private String caseDescription;
private CIType casetype;
private CIType a2cType;
private String a2cClass;
private String a2cNum;
private String a2cDenum;
private boolean a2cDefault;
private Instance accInst;
private Instance periodeInst;
/**
* @param _colName2Index
* @param _row
*/
public ImportCase(final Instance _periodInst,
final Map<String, Integer> _colName2Index,
final String[] _row)
{
try {
this.periodeInst = _periodInst;
this.caseName = _row[_colName2Index.get(Import_Base.CaseColumn.CASENAME.getKey())].trim()
.replaceAll("\n", "");
this.caseDescription = _row[_colName2Index.get(Import_Base.CaseColumn.CASEDESC.getKey())].trim()
.replaceAll("\n", "");
final String type = _row[_colName2Index.get(Import_Base.CaseColumn.CASETYPE.getKey())].trim()
.replaceAll("\n", "");
this.casetype = Import_Base.TYPE2TYPE.get(type);
final String a2c = _row[_colName2Index.get(Import_Base.CaseColumn.A2CTYPE.getKey())].trim()
.replaceAll("\n", "");
this.a2cType = Import_Base.ACC2CASE.get(a2c);
this.a2cNum = _row[_colName2Index.get(Import_Base.CaseColumn.A2CNUM.getKey())].trim()
.replaceAll("\n", "");
this.a2cDenum = _row[_colName2Index.get(Import_Base.CaseColumn.A2CDENUM.getKey())].trim()
.replaceAll("\n", "");
this.a2cDefault = "yes".equalsIgnoreCase(_row[_colName2Index.get(Import_Base.CaseColumn.A2CDEFAULT
.getKey())])
|| "true".equalsIgnoreCase(_row[_colName2Index.get(Import_Base.CaseColumn.A2CDEFAULT
.getKey())]);
final String accName = _row[_colName2Index.get(Import_Base.CaseColumn.A2CACC.getKey())].trim()
.replaceAll("\n", "");
if (_colName2Index.containsKey(Import_Base.CaseColumn.A2CCLA.getKey())
&& (a2cType.getType().isKindOf(CIAccounting.Account2CaseDebit4Classification.getType())
|| a2cType.getType().isKindOf(CIAccounting.Account2CaseCredit4Classification.getType()))) {
this.a2cClass = _row[_colName2Index.get(Import_Base.CaseColumn.A2CCLA.getKey())].trim()
.replaceAll("\n", "");
}
final QueryBuilder queryBuilder = new QueryBuilder(CIAccounting.AccountAbstract);
queryBuilder.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, accName);
queryBuilder.addWhereAttrEqValue(CIAccounting.AccountAbstract.PeriodeAbstractLink, _periodInst.getId());
final InstanceQuery query = queryBuilder.getQuery();
query.executeWithoutAccessCheck();
if (query.next()) {
this.accInst = query.getCurrentValue();
}
} catch (final Exception e) {
Import_Base.LOG.error("Catched error on Import.", e);
}
}
/**
* @return
*/
public boolean validate()
{
return this.caseName != null && this.casetype != null && this.a2cDenum != null && this.a2cNum != null
&& this.accInst != null
&& this.accInst.isValid();
}
/**
*
*/
public void update()
throws EFapsException
{
final QueryBuilder queryBuilder = new QueryBuilder(this.casetype);
queryBuilder.addWhereAttrEqValue(CIAccounting.CaseAbstract.Name, this.caseName);
queryBuilder.addWhereAttrEqValue(CIAccounting.CaseAbstract.PeriodeAbstractLink, this.periodeInst.getId());
final InstanceQuery query = queryBuilder.getQuery();
query.executeWithoutAccessCheck();
Instance caseInst;
if (query.next()) {
caseInst = query.getCurrentValue();
} else {
final Insert insert = new Insert(this.casetype);
insert.add(CIAccounting.CaseAbstract.Name, this.caseName);
insert.add(CIAccounting.CaseAbstract.Description, this.caseDescription);
insert.add(CIAccounting.CaseAbstract.PeriodeAbstractLink, this.periodeInst.getId());
insert.execute();
caseInst = insert.getInstance();
}
final Insert insert = new Insert(this.a2cType);
insert.add(CIAccounting.Account2CaseAbstract.ToCaseAbstractLink, caseInst.getId());
insert.add(CIAccounting.Account2CaseAbstract.FromAccountAbstractLink, this.accInst.getId());
insert.add(CIAccounting.Account2CaseAbstract.Denominator, this.a2cDenum);
insert.add(CIAccounting.Account2CaseAbstract.Numerator, this.a2cNum);
insert.add(CIAccounting.Account2CaseAbstract.Default, this.a2cDefault);
if (this.a2cClass != null) {
insert.add(CIAccounting.Account2CaseAbstract.LinkValue, Classification.get(this.a2cClass).getId());
}
insert.execute();
}
@Override
public String toString()
{
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}
/**
* represents one account to be imported.
*/
public class ImportAccount
{
/**
* Value for this account.
*/
private final String value;
/**
* Description for this account.
*/
private final String description;
/**
* Value for this account.
*/
private final String order;
/**
* Parent of this account.
*/
private final String parent;
/**
* Path of this account.
*/
private String path;
/**
* Instance of this account.
*/
private final Instance instance;
/**
* Type for the account connection.
*/
private final List<Type> lstTypeConn;
/**
* Type for the account connection.
*/
private final List<String> lstTargetConn;
/**
* @param _periode periode this account belong to
* @param _colName2Index mapping o column name to index
* @param _row actual row
* @throws EFapsException on error
*/
public ImportAccount(final Instance _periode,
final Map<String, Integer> _colName2Index,
final String[] _row,
final Map<String, List<String>> _validateMap,
final Map<String, ImportAccount> _accountVal)
throws EFapsException
{
this.lstTypeConn = new ArrayList<Type>();
this.lstTargetConn = new ArrayList<String>();
this.value = _row[_colName2Index.get(Import_Base.AcccountColumn.VALUE.getKey())].trim().replaceAll("\n",
"");
this.description = _row[_colName2Index.get(Import_Base.AcccountColumn.NAME.getKey())].trim()
.replaceAll("\n", "");
final String type = _row[_colName2Index.get(Import_Base.AcccountColumn.TYPE.getKey())].trim().replaceAll(
"\n", "");
final boolean summary = "yes".equalsIgnoreCase(_row[_colName2Index.get(Import_Base.AcccountColumn.SUMMARY
.getKey())]);
final String parentTmp = _row[_colName2Index.get(Import_Base.AcccountColumn.PARENT.getKey())];
if (_validateMap != null) {
for (final Entry<String, List<String>> entry : _validateMap.entrySet()) {
final String typeConnTmp = _row[_colName2Index.get(Import_Base.AcccountColumn.ACC_REL.getKey()
.replace("]", entry.getKey() + "]"))].trim().replaceAll("\n", "");
final String targetConnTmp = _row[_colName2Index.get(Import_Base.AcccountColumn.ACC_TARGET.getKey()
.replace("]", entry.getKey() + "]"))].trim().replaceAll("\n", "");
if (typeConnTmp != null && !typeConnTmp.isEmpty()
&& targetConnTmp != null && !targetConnTmp.isEmpty()) {
this.lstTypeConn.add(Type.get(Import_Base.ACC2ACC.get(typeConnTmp).uuid));
this.lstTargetConn.add(targetConnTmp);
}
}
this.order = _row[_colName2Index.get(Import_Base.AcccountColumn.KEY.getKey())]
.trim().replaceAll("\n", "");
} else {
this.order = null;
}
if (_accountVal != null) {
this.path = _accountVal.get(this.order).getPath();
} else {
this.path = null;
}
this.parent = parentTmp == null ? null : parentTmp.trim().replaceAll("\n", "");
Update update = null;
if (Import_Base.TYPE2TYPE.get(type).getType().isKindOf(CIAccounting.AccountAbstract.getType())) {
final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountBaseAbstract.Name, this.value);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountBaseAbstract.PeriodeAbstractLink, _periode.getId());
final MultiPrintQuery multi = queryBldr.getPrint();
final SelectBuilder selParent = new SelectBuilder().linkto(CIAccounting.AccountBaseAbstract.ParentLink)
.attribute(CIAccounting.AccountBaseAbstract.Name);
multi.addSelect(selParent);
multi.execute();
if (multi.next()) {
final String parentName = multi.<String>getSelect(selParent);
if (parentName != null && parentName.equals(parentTmp)) {
update = new Update(multi.getCurrentInstance());
} else {
update = new Insert(Import_Base.TYPE2TYPE.get(type));
}
} else {
update = new Insert(Import_Base.TYPE2TYPE.get(type));
}
} else if (Import_Base.TYPE2TYPE.get(type).getType().isKindOf(CIAccounting.ViewAbstract.getType())) {
final String[] parts = this.path.split("_");
final Instance updateInst = validateUpdate(this.value, null, _periode, 0, parts);
if (updateInst != null) {
update = new Update(updateInst);
} else {
update = new Insert(Import_Base.TYPE2TYPE.get(type));
}
}
if (Import_Base.TYPE2TYPE.get(type).getType().isKindOf(CIAccounting.AccountAbstract.getType())) {
update.add("Summary", summary);
}
update.add(CIAccounting.AccountBaseAbstract.PeriodeAbstractLink, _periode.getId());
update.add(CIAccounting.AccountBaseAbstract.Name, this.value);
update.add(CIAccounting.AccountBaseAbstract.Description, this.description);
update.execute();
this.instance = update.getInstance();
}
private Instance validateUpdate(final String _name,
final Long _id,
final Instance _periode,
int _cont,
final String[] _parts) throws EFapsException {
Instance ret = null;
boolean ver = false;
Instance instCur = null;
final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.ViewAbstract);
if (_cont == 0) {
queryBldr.addWhereAttrEqValue(CIAccounting.AccountBaseAbstract.Name, _name);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountBaseAbstract.PeriodeAbstractLink, _periode.getId());
ver = true;
} else {
queryBldr.addWhereAttrEqValue(CIAccounting.AccountBaseAbstract.ID, _id);
}
final MultiPrintQuery multi = queryBldr.getPrint();
final SelectBuilder selParent = new SelectBuilder().linkto(CIAccounting.AccountBaseAbstract.ParentLink)
.attribute(CIAccounting.AccountBaseAbstract.Name);
multi.addSelect(selParent);
multi.addAttribute(CIAccounting.ViewAbstract.ParentLink, CIAccounting.ViewAbstract.Name);
multi.execute();
_cont++;
while (multi.next()) {
instCur = multi.getCurrentInstance();
final Long parentId = multi.<Long>getAttribute(CIAccounting.ViewAbstract.ParentLink);
final String parentName = multi.<String>getSelect(selParent);
if (_cont < (_parts.length)) {
if (parentName.equals(_parts[_cont])) {
ret = validateUpdate(parentName, parentId, _periode, _cont, _parts);
if (ret != null) {
break;
}
}
} else if (_cont == _parts.length && parentId == null) {
ret = multi.getCurrentInstance();
break;
}
}
if (ver && ret != null) {
ret = instCur;
}
return ret;
}
/**
* new Constructor for import accounts of the period.
* @param _accountIns Instance of the account.
* @param _parentName name of a parent accounts.
* @param _name name of account.
*/
public ImportAccount(final Map<String, Integer> _colName2Index,
final String[] _row)
{
this.lstTypeConn = new ArrayList<Type>();
this.lstTargetConn = new ArrayList<String>();
this.value = _row[_colName2Index.get(Import_Base.AcccountColumn.VALUE.getKey())].trim().replaceAll("\n",
"");
this.description = _row[_colName2Index.get(Import_Base.AcccountColumn.NAME.getKey())].trim().replaceAll("\n",
"");
final String parentTmp = _row[_colName2Index.get(Import_Base.AcccountColumn.PARENT.getKey())];
this.order = _row[_colName2Index.get(Import_Base.AcccountColumn.KEY.getKey())]
.trim().replaceAll("\n", "");
this.parent = parentTmp == null ? null : parentTmp.trim().replaceAll("\n", "");
this.instance = null;
this.path = this.value;
}
/**
* new Constructor for import accounts of the period.
* @param _accountIns Instance of the account.
* @param _parentName name of a parent accounts.
* @param _name name of account.
*/
public ImportAccount(final Instance _accountIns,
final String _parentName,
final String _name,
final String _description,
final String _order,
final String _path,
final List<Type> _lstTypeConn,
final List<String> _lstTargetConn)
{
this.instance = _accountIns;
this.parent = _parentName;
this.value = _name;
this.description = _description;
this.lstTypeConn = _lstTypeConn;
this.lstTargetConn = _lstTargetConn;
this.order = _order;
this.path = _path;
}
/**
* Getter method for instance variable {@link #value}.
*
* @return value of instance variable {@link #value}
*/
public String getValue()
{
return this.value;
}
/**
* Getter method for instance variable {@link #description}.
*
* @return description of instance variable {@link #description}
*/
public String getDescription()
{
return this.description;
}
/**
* Getter method for instance variable {@link #parent}.
*
* @return value of instance variable {@link #parent}
*/
public String getParent()
{
return this.parent;
}
/**
* Getter method for instance variable {@link #order}.
*
* @return value of instance variable {@link #order}
*/
public String getOrder()
{
return this.order;
}
/**
* Getter method for instance variable {@link #instance}.
*
* @return value of instance variable {@link #instance}
*/
public Instance getInstance()
{
return this.instance;
}
/**
* Getter method for instance variable {@link #lstTypeConn}.
*
* @return the lstTypeConn
*/
private List<Type> getLstTypeConn()
{
return this.lstTypeConn;
}
/**
* Getter method for instance variable {@link #lstTargetConn}.
*
* @return the lstTargetConn
*/
private List<String> getLstTargetConn()
{
return this.lstTargetConn;
}
/**
* @return the path
*/
private String getPath()
{
return this.path;
}
/**
* @param path the path to set
*/
private void setPath(final String path)
{
this.path = path;
}
}
/**
* Represents on report to be imported.
*/
public class ImportReport
{
/**
* Instance of this report.
*/
private final Instance instance;
/**
* Mapping of node to node level.
*/
private final Map<Integer, List<ImportNode>> level2Nodes = new HashMap<Integer, List<ImportNode>>();
/**
* @param _periodInst instance of the period.
* @param _type name of type.
* @param _name name of the report.
* @param _description description of the report.
* @param _numbering numbering of the report.
* @throws EFapsException on error
*/
protected ImportReport(final Instance _periodInst,
final String _type,
final String _name,
final String _description,
final String _numbering)
throws EFapsException
{
final Insert insert = new Insert(Import_Base.TYPE2TYPE.get(_type));
insert.add(CIAccounting.ReportAbstract.PeriodeLink, _periodInst.getId());
insert.add(CIAccounting.ReportAbstract.Name, _name);
insert.add(CIAccounting.ReportAbstract.Description, _description);
insert.add(CIAccounting.ReportAbstract.Numbering, _numbering);
insert.execute();
this.instance = insert.getInstance();
}
/**
* Add a node to this report.
*
* @param _colName2Index mapping of column name 2 index
* @param _row actual row
* @param _max max level key
* @param _accounts list of accounts
* @throws EFapsException on error
*/
public void addNode(final Map<String, Integer> _colName2Index,
final String[] _row,
final Integer _max,
final Map<String, Import_Base.ImportAccount> _accounts)
throws EFapsException
{
// search the level
int level = 0;
String levelkey = "";
for (Integer i = 0; i < _max; i++) {
levelkey = Import_Base.LEVELCOLUMN.replace("#", i.toString());
final String value = _row[_colName2Index.get(levelkey)];
if (value != null && value.length() > 1) {
level = i;
break;
}
}
final Instance parentInst;
if (level < 1) {
parentInst = this.instance;
} else {
final List<ImportNode> lis = this.level2Nodes.get(level - 1);
parentInst = lis.get(lis.size() - 1).getInstance();
}
List<ImportNode> nodes;
if (this.level2Nodes.containsKey(level)) {
nodes = this.level2Nodes.get(level);
} else {
nodes = new ArrayList<ImportNode>();
this.level2Nodes.put(level, nodes);
}
final ImportNode node = new ImportNode(_colName2Index, _row, levelkey, parentInst, _accounts, nodes.size());
nodes.add(node);
}
}
/**
* Represents one node to be imported.
*/
public class ImportNode
{
/**
* Instance of this node.
*/
private final Instance instance;
/**
* new Constructor for import Nodes.
*
* @param _colName2Index mapping of column name 2 index.
* @param _row actual row.
* @param _level level key.
* @param _parentInst parent instance.
* @param _accounts list of accounts.
* @param _position order position.
* @throws EFapsException on error.
*/
public ImportNode(final Map<String, Integer> _colName2Index,
final String[] _row,
final String _level,
final Instance _parentInst,
final Map<String, Import_Base.ImportAccount> _accounts,
final int _position)
throws EFapsException
{
final String type = _row[_colName2Index.get(Import_Base.ReportColumn.NODE_TYPE.getKey())].trim()
.replaceAll("\n", "");
final boolean showAllways = !"false".equalsIgnoreCase(_row[_colName2Index
.get(Import_Base.ReportColumn.NODE_SHOW.getKey())]);
final boolean showSum = !"false".equalsIgnoreCase(_row[_colName2Index
.get(Import_Base.ReportColumn.NODE_SUM.getKey())]);
final String number = _row[_colName2Index.get(Import_Base.ReportColumn.NODE_NUMBER.getKey())].trim()
.replaceAll("\n", "");
final String value = _row[_colName2Index.get(_level)].trim().replaceAll("\n", "");
final Insert insert = new Insert(Import_Base.TYPE2TYPE.get(type));
insert.add(CIAccounting.ReportNodeAbstract.ShowAllways, showAllways);
insert.add(CIAccounting.ReportNodeAbstract.ShowSum, showSum);
if (CIAccounting.ReportNodeRoot.equals(Import_Base.TYPE2TYPE.get(type))) {
if (_parentInst.isValid()) {
insert.add(CIAccounting.ReportNodeRoot.Number, number);
insert.add(CIAccounting.ReportNodeRoot.Label, value);
insert.add(CIAccounting.ReportNodeRoot.ReportLink, _parentInst);
insert.add(CIAccounting.ReportNodeRoot.Position, _position);
insert.execute();
} else {
Import_Base.LOG.error("Report Instance does not exist for '{}'- '{}' ", number, value);
}
} else if (CIAccounting.ReportNodeTree.equals(Import_Base.TYPE2TYPE.get(type))) {
if (_parentInst.isValid()) {
insert.add(CIAccounting.ReportNodeTree.Number, number);
insert.add(CIAccounting.ReportNodeTree.Label, value);
insert.add(CIAccounting.ReportNodeTree.ParentLink, _parentInst);
insert.add(CIAccounting.ReportNodeTree.Position, _position);
insert.execute();
} else {
Import_Base.LOG.error("Parent Node Instance does not exist for '{}'- '{}' ", number, value);
}
} else if (CIAccounting.ReportNodeAccount.equals(Import_Base.TYPE2TYPE.get(type))) {
if (_parentInst.isValid()) {
insert.add(CIAccounting.ReportNodeAccount.ParentLink, _parentInst.getId());
if (_accounts.get(value) == null) {
Import_Base.LOG.error("Account Instance not exist: " + value);
} else {
insert.add(CIAccounting.ReportNodeAccount.AccountLink, _accounts.get(value).getInstance());
insert.add(CIAccounting.ReportNodeAccount.Label,
value + " - " + _accounts.get(value).getDescription());
insert.execute();
}
} else {
Import_Base.LOG.error("Parent Node Instance does not exist for Account Node '{}'- '{}' ",
number, value);
}
}
this.instance = insert.getInstance();
}
/**
* Getter method for instance variable {@link #instance}.
*
* @return value of instance variable {@link #instance}
*/
public Instance getInstance()
{
return this.instance;
}
}
}
|
src/main/efaps/ESJP/org/efaps/esjp/accounting/Import_Base.java
|
/*
* Copyright 2003 - 2010 The eFaps Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Revision: $Rev: 7855 $
* Last Changed: $Date: 2012-08-02 20:35:53 -0500 (jue, 02 ago 2012) $
* Last Changed By: $Author: [email protected] $
*/
package org.efaps.esjp.accounting;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.efaps.admin.datamodel.Type;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.event.Return;
import org.efaps.admin.program.esjp.EFapsRevision;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.ci.CIType;
import org.efaps.db.Context;
import org.efaps.db.Context.FileParameter;
import org.efaps.db.Insert;
import org.efaps.db.Instance;
import org.efaps.db.InstanceQuery;
import org.efaps.db.MultiPrintQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.db.SelectBuilder;
import org.efaps.db.Update;
import org.efaps.esjp.ci.CIAccounting;
import org.efaps.util.EFapsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import au.com.bytecode.opencsv.CSVReader;
/**
* TODO comment!
*
* @author The eFaps Team
* @version $Id: Periode_Base.java 7855 2012-08-03 01:35:53Z [email protected] $
*/
@EFapsUUID("4f7c8d48-01d0-4862-82e7-2efcf6761e5a")
@EFapsRevision("$Rev: 7855 $")
public abstract class Import_Base
{
private static final Logger LOG = LoggerFactory.getLogger(Import_Base.class);
/**
* Definitions for Columns.
*/
public interface Column
{
/**
* @return key
*/
String getKey();
}
private enum CaseColumn implements Import_Base.Column {
/** */
A2CTYPE("[Account2Case_Type]"),
A2CACC("[Account2Case_Account]"),
A2CNUM("[Account2Case_Numerator]"),
A2CDENUM("[Account2Case_Denominator]"),
A2CDEFAULT("[Account2Case_Default]"),
CASETYPE("[Case_Type]"),
CASENAME("[Case_Name]"),
CASEDESC("[Case_Description]");
;
/** Key. */
private final String key;
/**
* @param _key key
*/
private CaseColumn(final String _key)
{
this.key = _key;
}
/**
* Getter method for instance variable {@link #key}.
*
* @return value of instance variable {@link #key}
*/
@Override
public String getKey()
{
return this.key;
}
}
/**
* Columns for an account table.
*
*/
private enum AcccountColumn implements Import_Base.Column {
/** */
VALUE("[Account_Value]"),
/** */
NAME("[Account_Name]"),
/** */
TYPE("[Account_Type]"),
/** */
SUMMARY("[Account_Summary]"),
/** */
PARENT("[Account_Parent]"),
/** */
KEY("[Account_Key]"),
/** */
ACC_REL("[Account_Relation]"),
/** */
ACC_TARGET("[Account_Target]");
/** Key. */
private final String key;
/**
* @param _key key
*/
private AcccountColumn(final String _key)
{
this.key = _key;
}
/**
* Getter method for instance variable {@link #key}.
*
* @return value of instance variable {@link #key}
*/
@Override
public String getKey()
{
return this.key;
}
}
/**
* Columns for an report.
*/
private enum ReportColumn implements Import_Base.Column {
/** */
TYPE("[Report_Type]"),
/** */
NAME("[Report_Name]"),
/** */
DESC("[Report_Description]"),
/** */
NUMBERING("[Report_Numbering]"),
/** */
NODE_TYPE("[Node_Type]"),
/** */
NODE_SHOW("[Node_ShowAllways]"),
/** */
NODE_SUM("[Node_ShowSum]"),
/** */
NODE_NUMBER("[Node_Number]");
/** Key. */
private final String key;
/**
* @param _key key
*/
private ReportColumn(final String _key)
{
this.key = _key;
}
/**
* Getter method for instance variable {@link #key}.
*
* @return value of instance variable {@link #key}
*/
@Override
public String getKey()
{
return this.key;
}
}
/**
* Mapping of types as written in the csv and the name in eFaps.
*/
protected static final Map<String, CIType> TYPE2TYPE = new HashMap<String, CIType>();
static {
Import_Base.TYPE2TYPE.put("Asset", CIAccounting.AccountBalanceSheetAsset);
Import_Base.TYPE2TYPE.put("Liability", CIAccounting.AccountBalanceSheetLiability);
Import_Base.TYPE2TYPE.put("Owner's equity", CIAccounting.AccountBalanceSheetEquity);
Import_Base.TYPE2TYPE.put("Expense", CIAccounting.AccountIncomeStatementExpenses);
Import_Base.TYPE2TYPE.put("Revenue", CIAccounting.AccountIncomeStatementRevenue);
Import_Base.TYPE2TYPE.put("Current", CIAccounting.AccountCurrent);
Import_Base.TYPE2TYPE.put("Creditor", CIAccounting.AccountCurrentCreditor);
Import_Base.TYPE2TYPE.put("Debtor", CIAccounting.AccountCurrentDebtor);
Import_Base.TYPE2TYPE.put("Memo", CIAccounting.AccountMemo);
Import_Base.TYPE2TYPE.put("Balance", CIAccounting.ReportBalance);
Import_Base.TYPE2TYPE.put("ProfitLoss", CIAccounting.ReportProfitLoss);
Import_Base.TYPE2TYPE.put("Other", CIAccounting.ReportTransaction);
Import_Base.TYPE2TYPE.put("Root", CIAccounting.ReportNodeRoot);
Import_Base.TYPE2TYPE.put("Tree", CIAccounting.ReportNodeTree);
Import_Base.TYPE2TYPE.put("Account", CIAccounting.ReportNodeAccount);
Import_Base.TYPE2TYPE.put("ReportAccount", CIAccounting.ReportAccount);
Import_Base.TYPE2TYPE.put("ViewRoot", CIAccounting.ViewRoot);
Import_Base.TYPE2TYPE.put("ViewSum", CIAccounting.ViewSum);
Import_Base.TYPE2TYPE.put("CaseBankCashGain", CIAccounting.CaseBankCashGain);
Import_Base.TYPE2TYPE.put("CaseBankCashPay", CIAccounting.CaseBankCashPay);
Import_Base.TYPE2TYPE.put("CaseDocBooking", CIAccounting.CaseDocBooking);
Import_Base.TYPE2TYPE.put("CaseDocRegister", CIAccounting.CaseDocRegister);
Import_Base.TYPE2TYPE.put("CaseExternalBooking", CIAccounting.CaseExternalBooking);
Import_Base.TYPE2TYPE.put("CaseExternalRegister", CIAccounting.CaseExternalRegister);
Import_Base.TYPE2TYPE.put("CaseGeneral", CIAccounting.CaseGeneral);
Import_Base.TYPE2TYPE.put("CasePayroll", CIAccounting.CasePayroll);
Import_Base.TYPE2TYPE.put("CasePettyCash", CIAccounting.CasePettyCash);
Import_Base.TYPE2TYPE.put("CaseStockBooking", CIAccounting.CaseStockBooking);
}
protected static final Map<String, CIType> ACC2ACC = new HashMap<String, CIType>();
static {
Import_Base.ACC2ACC.put("ViewSumAccount", CIAccounting.ViewSum2Account);
Import_Base.ACC2ACC.put("AccountCosting", CIAccounting.Account2AccountCosting);
Import_Base.ACC2ACC.put("AccountInverseCosting", CIAccounting.Account2AccountCostingInverse);
Import_Base.ACC2ACC.put("AccountCredit", CIAccounting.Account2AccountCredit);
Import_Base.ACC2ACC.put("AccountDebit", CIAccounting.Account2AccountDebit);
}
protected static final Map<String, CIType> ACC2CASE = new HashMap<String, CIType>();
static {
Import_Base.ACC2CASE.put("Credit", CIAccounting.Account2CaseCredit);
Import_Base.ACC2CASE.put("Debit", CIAccounting.Account2CaseDebit);
}
/**
* Key for a level column.
*/
private static String LEVELCOLUMN = "[Level #]";
/**
* Called on a command to create a new reports of the file.
*
* @param _parameter Paremeter as passed from the eFaps API.
* @return new Return
* @throws EFapsException on error
*/
public Return createReportOfFile(final Parameter _parameter)
throws EFapsException
{
final String periode = _parameter.getParameterValue("periodeLink");
final FileParameter reports = Context.getThreadContext().getFileParameters().get("reports");
if (periode != null && reports != null) {
final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.Periode);
queryBldr.addWhereAttrEqValue(CIAccounting.Periode.ID, periode);
final MultiPrintQuery multi = queryBldr.getPrint();
multi.addAttribute(CIAccounting.Periode.OID);
multi.execute();
Instance instance = null;
while (multi.next()) {
instance = Instance.get(multi.<String>getAttribute(CIAccounting.Periode.OID));
}
if (instance != null) {
createReports(instance, reports, getImportAccountFromDB(_parameter, instance));
}
}
return new Return();
}
/**
* Obtains account from the DB.
*
* @param _parameter Parameter as passed from the eFaps API.
* @param _instance Instance of the period.
* @return ret with accounts.
* @throws EFapsException on error.
*/
protected Map<String, ImportAccount> getImportAccountFromDB(final Parameter _parameter,
final Instance _instance)
throws EFapsException
{
final Map<String, ImportAccount> ret = new HashMap<String, ImportAccount>();
final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.PeriodeAbstractLink, _instance.getId());
final MultiPrintQuery multi = queryBldr.getPrint();
final SelectBuilder sel = new SelectBuilder().linkto(CIAccounting.AccountAbstract.ParentLink)
.attribute(CIAccounting.AccountAbstract.Name);
multi.addSelect(sel);
multi.addAttribute(CIAccounting.AccountAbstract.Name,
CIAccounting.AccountAbstract.Description);
multi.execute();
while (multi.next()) {
final String parentName = multi.<String>getSelect(sel);
final String name = multi.<String>getAttribute(CIAccounting.AccountAbstract.Name);
final String desc = multi.<String>getAttribute(CIAccounting.AccountAbstract.Description);
ret.put(name, new ImportAccount(multi.getCurrentInstance(), parentName, name, desc, null, null, null, null));
}
return ret;
}
/**
* @param _periodInst periode the account table belongs to
* @param _reports csv file
* @param _accounts map of accounts
* @throws EFapsException on error
*/
protected void createReports(final Instance _periodInst,
final FileParameter _reports,
final Map<String, ImportAccount> _accounts)
throws EFapsException
{
try {
final CSVReader reader = new CSVReader(new InputStreamReader(_reports.getInputStream(), "UTF-8"));
final List<String[]> entries = reader.readAll();
if (!entries.isEmpty()) {
final Map<String, Integer> colName2Index = evaluateCSVFileHeader(Import_Base.ReportColumn.values(),
entries.get(0), null);
reader.close();
Integer i = 0;
final String[] headRow = entries.get(0);
boolean found = true;
while (found) {
found = false;
final String level = Import_Base.LEVELCOLUMN.replace("#", i.toString());
int idx = 0;
for (final String column : headRow) {
if (level.equals(column.trim())) {
i++;
found = true;
colName2Index.put(level, idx);
break;
}
idx++;
}
}
entries.remove(0);
final Map<String, ImportReport> reports = new HashMap<String, ImportReport>();
ImportReport report = null;
for (final String[] row : entries) {
report = getImportReport(_periodInst, colName2Index, row, reports);
report.addNode(colName2Index, row, i, _accounts);
}
}
} catch (final IOException e) {
throw new EFapsException(Import_Base.class, "createReports.IOException", e);
}
}
/**
* method for obtains reports of a import.
*
* @param _periodInst Instance of the period.
* @param _colName2Index cols of the report.
* @param _row rows of the report.
* @param _reports values of the report.
* @return ret with values.
* @throws EFapsException on error.
*/
protected ImportReport getImportReport(final Instance _periodInst,
final Map<String, Integer> _colName2Index,
final String[] _row,
final Map<String, ImportReport> _reports)
throws EFapsException
{
final ImportReport ret;
final String type = _row[_colName2Index.get(Import_Base.ReportColumn.TYPE.getKey())].trim()
.replaceAll("\n", "");
final String name = _row[_colName2Index.get(Import_Base.ReportColumn.NAME.getKey())].trim()
.replaceAll("\n", "");
final String description = _row[_colName2Index.get(Import_Base.ReportColumn.DESC.getKey())].trim()
.replaceAll("\n", "");
final String numbering = _row[_colName2Index.get(Import_Base.ReportColumn.NUMBERING.getKey())].trim()
.replaceAll("\n", "");
final String key = type + ":" + name;
if (_reports.containsKey(key)) {
ret = _reports.get(key);
} else {
ret = new ImportReport(_periodInst, type, name, description, numbering);
_reports.put(key, ret);
}
return ret;
}
/**
* @param _periodInst periode the account table belongs to
* @param _accountTable csv file
* @return HashMap
* @throws EFapsException on error
*/
protected HashMap<String, ImportAccount> createAccountTable(final Instance _periodInst,
final FileParameter _accountTable)
throws EFapsException
{
final HashMap<String, ImportAccount> accounts = new HashMap<String, ImportAccount>();
try {
final CSVReader reader = new CSVReader(new InputStreamReader(_accountTable.getInputStream(), "UTF-8"));
final List<String[]> entries = reader.readAll();
reader.close();
final Map<String, List<String>> validateMap = new HashMap<String, List<String>>();
final Map<String, Integer> colName2Index = evaluateCSVFileHeader(Import_Base.AcccountColumn.values(),
entries.get(0), validateMap);
entries.remove(0);
for (final String[] row : entries) {
final ImportAccount account = new ImportAccount(_periodInst, colName2Index, row, null, null);
accounts.put(account.getValue(), account);
}
for (final ImportAccount account : accounts.values()) {
if (account.getParent() != null && account.getParent().length() > 0) {
final ImportAccount parent = accounts.get(account.getParent());
if (parent != null) {
final Update update = new Update(account.getInstance());
update.add("ParentLink", parent.getInstance().getId());
update.execute();
}
}
if (account.getLstTypeConn() != null && !account.getLstTypeConn().isEmpty() &&
account.getLstTargetConn() != null && !account.getLstTargetConn().isEmpty()) {
final List<Type> lstTypes = account.getLstTypeConn();
final List<String> lstTarget = account.getLstTargetConn();
final int cont = 0;
for (final Type type : lstTypes) {
final String nameAcc = lstTarget.get(cont);
final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, nameAcc);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.PeriodeAbstractLink,
_periodInst.getId());
final InstanceQuery query = queryBldr.getQuery();
query.execute();
if (query.next()) {
final Insert insert = new Insert(type);
insert.add(CIAccounting.Account2AccountAbstract.FromAccountLink,
account.getInstance().getId());
insert.add(CIAccounting.Account2AccountAbstract.ToAccountLink,
query.getCurrentValue().getId());
insert.execute();
}
}
}
}
} catch (final IOException e) {
throw new EFapsException(Periode.class, "createAccountTable.IOException", e);
}
return accounts;
}
protected HashMap<String, ImportAccount> createViewAccountTable(final Instance _periodInst,
final FileParameter _accountTable)
throws EFapsException
{
final HashMap<String, ImportAccount> accounts = new HashMap<String, ImportAccount>();
final HashMap<String, ImportAccount> accountsVal = new HashMap<String, ImportAccount>();
try {
final CSVReader reader = new CSVReader(new InputStreamReader(_accountTable.getInputStream(), "UTF-8"));
final List<String[]> entries = reader.readAll();
reader.close();
final Map<String, List<String>> validateMap = new HashMap<String, List<String>>();
final Map<String, Integer> colName2Index = evaluateCSVFileHeader(Import_Base.AcccountColumn.values(),
entries.get(0), validateMap);
entries.remove(0);
for (final String[] row : entries) {
final ImportAccount account = new ImportAccount(colName2Index, row);
accountsVal.put(account.getOrder(), account);
}
for (final ImportAccount account : accountsVal.values()) {
ImportAccount parent = accountsVal.get(account.getParent());
while (parent != null) {
account.setPath(account.getPath() + "_" + parent.getValue());
parent = parent.getParent() != null ? accountsVal.get(parent.getParent()) : null;
}
}
for (final String[] row : entries) {
final ImportAccount account = new ImportAccount(_periodInst, colName2Index, row, validateMap, accountsVal);
accounts.put(account.getOrder(), account);
}
for (final ImportAccount account : accounts.values()) {
if (account.getParent() != null && account.getParent().length() > 0) {
final ImportAccount parent = accounts.get(account.getParent());
if (parent != null) {
final Update update = new Update(account.getInstance());
update.add(CIAccounting.AccountBaseAbstract.ParentLink, parent.getInstance().getId());
update.execute();
}
}
if (account.getLstTypeConn() != null && !account.getLstTypeConn().isEmpty() &&
account.getLstTargetConn() != null && !account.getLstTargetConn().isEmpty()) {
final List<Type> lstTypes = account.getLstTypeConn();
final List<String> lstTarget = account.getLstTargetConn();
int cont = 0;
for (final Type type : lstTypes) {
final String nameAcc = lstTarget.get(cont);
final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, nameAcc);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.PeriodeAbstractLink,
_periodInst.getId());
final InstanceQuery query = queryBldr.getQuery();
query.execute();
if (query.next()) {
final Insert insert = new Insert(type);
insert.add(CIAccounting.View2AccountAbstract.FromLinkAbstract,
account.getInstance().getId());
insert.add(CIAccounting.View2AccountAbstract.ToLinkAbstract,
query.getCurrentValue().getId());
insert.execute();
}
cont++;
}
}
}
} catch (final IOException e) {
throw new EFapsException(Periode.class, "createAccountTable.IOException", e);
}
return accounts;
}
protected void createCaseTable(final Instance _periodInst,
final FileParameter _accountTable)
throws EFapsException
{
try {
final CSVReader reader = new CSVReader(new InputStreamReader(_accountTable.getInputStream(), "UTF-8"));
final List<String[]> entries = reader.readAll();
reader.close();
final Map<String, List<String>> validateMap = new HashMap<String, List<String>>();
final Map<String, Integer> colName2Index = evaluateCSVFileHeader(Import_Base.CaseColumn.values(),
entries.get(0), validateMap);
entries.remove(0);
final List<ImportCase> cases = new ArrayList<ImportCase>();
int i = 1;
boolean valid = true;
for (final String[] row : entries) {
Import_Base.LOG.info("reading Line {}: {}",i, row);
final ImportCase impCase = new ImportCase(_periodInst, colName2Index, row);
if (!impCase.validate()) {
valid = false;
Import_Base.LOG.error("Line {} is invalid; {}",i , impCase);
}
cases.add(impCase);
i++;
}
if (valid) {
for (final ImportCase impCase : cases) {
impCase.update();
}
}
} catch (final UnsupportedEncodingException e) {
throw new EFapsException("UnsupportedEncodingException", e);
} catch (final IOException e) {
throw new EFapsException("IOException", e);
}
}
/**
* Evaluates the header of a CSV file to get for each defined column the
* related column number. If no keys are given all columns will be read;
*
* @param _columns columns to read (defined in the header of the file),
* <code>null</code> if all must be read
* @param _headerLine string array with the header line
* @return map defining for each key the related column number
* @throws EFapsException if a column from the list of keys is not defined
*/
protected Map<String, Integer> evaluateCSVFileHeader(final Import_Base.Column[] _columns,
final String[] _headerLine,
final Map<String, List<String>> _validateMap)
throws EFapsException
{
// evaluate header
int idx = 0;
final Map<String, Integer> ret = new HashMap<String, Integer>();
for (final String column : _headerLine) {
if (_columns == null) {
ret.put(column, idx);
} else {
for (final Column columns : _columns) {
if (columns.getKey().equals(column)) {
ret.put(column, idx);
break;
} else {
if (_validateMap != null && column.contains(columns.getKey().replace("]", ""))) {
final String numStr = column.replace(columns.getKey().replace("]", ""), "").replace("]", "");
if (_validateMap.containsKey(numStr)) {
final List<String> lst = _validateMap.get(numStr);
lst.add(column);
} else {
final ArrayList<String> lst = new ArrayList<String>();
lst.add(column);
_validateMap.put(numStr, lst);
}
ret.put(column, idx);
break;
}
}
}
}
idx++;
}
// if keys are defined, check for all required indexes
if (_columns != null) {
for (final Column column : _columns) {
if (ret.get(column.getKey()) == null) {
if (_validateMap != null) {
for (final Entry<String, List<String>> entry : _validateMap.entrySet()) {
if (ret.get(column.getKey().replace("]", "") + entry.getKey() + "]") == null) {
throw new EFapsException(Import_Base.class, "ColumnNotDefinded", column.getKey());
} else {
if (entry.getValue().size() != 2) {
throw new EFapsException(Import_Base.class, "ColumnNotDefinded",
column.getKey() + entry.getKey());
}
}
}
} else {
throw new EFapsException(Import_Base.class, "ColumnNotDefinded",
column.getKey() + column.getKey());
}
}
}
}
Import_Base.LOG.info("analysed table headers: {}", ret);
return ret;
}
public class ImportCase
{
private String caseName;
private String caseDescription;
private CIType casetype;
private CIType a2cType;
private String a2cNum;
private String a2cDenum;
private boolean a2cDefault;
private Instance accInst;
private Instance periodeInst;
/**
* @param _colName2Index
* @param _row
*/
public ImportCase(final Instance _periodInst,
final Map<String, Integer> _colName2Index,
final String[] _row)
{
try {
this.periodeInst = _periodInst;
this.caseName = _row[_colName2Index.get(Import_Base.CaseColumn.CASENAME.getKey())].trim().replaceAll(
"\n",
"");
this.caseDescription = _row[_colName2Index.get(Import_Base.CaseColumn.CASEDESC.getKey())].trim()
.replaceAll("\n",
"");
final String type = _row[_colName2Index.get(Import_Base.CaseColumn.CASETYPE.getKey())].trim()
.replaceAll(
"\n", "");
this.casetype = Import_Base.TYPE2TYPE.get(type);
final String a2c = _row[_colName2Index.get(Import_Base.CaseColumn.A2CTYPE.getKey())].trim().replaceAll(
"\n", "");
this.a2cType = Import_Base.ACC2CASE.get(a2c);
this.a2cNum = _row[_colName2Index.get(Import_Base.CaseColumn.A2CNUM.getKey())].trim().replaceAll(
"\n", "");
this.a2cDenum = _row[_colName2Index.get(Import_Base.CaseColumn.A2CDENUM.getKey())].trim().replaceAll(
"\n", "");
this.a2cDefault = "yes".equalsIgnoreCase(_row[_colName2Index.get(Import_Base.CaseColumn.A2CDEFAULT
.getKey())])
|| "true".equalsIgnoreCase(_row[_colName2Index.get(Import_Base.CaseColumn.A2CDEFAULT
.getKey())]);
final String accName = _row[_colName2Index.get(Import_Base.CaseColumn.A2CACC.getKey())].trim()
.replaceAll(
"\n", "");
final QueryBuilder queryBuilder = new QueryBuilder(CIAccounting.AccountAbstract);
queryBuilder.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, accName);
queryBuilder.addWhereAttrEqValue(CIAccounting.AccountAbstract.PeriodeAbstractLink, _periodInst.getId());
final InstanceQuery query = queryBuilder.getQuery();
query.executeWithoutAccessCheck();
if (query.next()) {
this.accInst = query.getCurrentValue();
}
} catch (final Exception e) {
Import_Base.LOG.error("Catched error on Import.", e);
}
}
/**
* @return
*/
public boolean validate()
{
return this.caseName != null && this.casetype != null && this.a2cDenum != null && this.a2cNum != null
&& this.accInst != null
&& this.accInst.isValid();
}
/**
*
*/
public void update()
throws EFapsException
{
final QueryBuilder queryBuilder = new QueryBuilder(this.casetype);
queryBuilder.addWhereAttrEqValue(CIAccounting.CaseAbstract.Name, this.caseName);
queryBuilder.addWhereAttrEqValue(CIAccounting.CaseAbstract.PeriodeAbstractLink, this.periodeInst.getId());
final InstanceQuery query = queryBuilder.getQuery();
query.executeWithoutAccessCheck();
Instance caseInst;
if (query.next()) {
caseInst = query.getCurrentValue();
} else {
final Insert insert = new Insert(this.casetype);
insert.add(CIAccounting.CaseAbstract.Name, this.caseName);
insert.add(CIAccounting.CaseAbstract.Description, this.caseDescription);
insert.add(CIAccounting.CaseAbstract.PeriodeAbstractLink, this.periodeInst.getId());
insert.execute();
caseInst = insert.getInstance();
}
final Insert insert = new Insert(this.a2cType);
insert.add(CIAccounting.Account2CaseAbstract.ToCaseAbstractLink, caseInst.getId());
insert.add(CIAccounting.Account2CaseAbstract.FromAccountAbstractLink, this.accInst.getId());
insert.add(CIAccounting.Account2CaseAbstract.Denominator, this.a2cDenum);
insert.add(CIAccounting.Account2CaseAbstract.Numerator, this.a2cNum);
insert.add(CIAccounting.Account2CaseAbstract.Default, this.a2cDefault);
insert.execute();
}
@Override
public String toString()
{
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}
/**
* represents one account to be imported.
*/
public class ImportAccount
{
/**
* Value for this account.
*/
private final String value;
/**
* Description for this account.
*/
private final String description;
/**
* Value for this account.
*/
private final String order;
/**
* Parent of this account.
*/
private final String parent;
/**
* Path of this account.
*/
private String path;
/**
* Instance of this account.
*/
private final Instance instance;
/**
* Type for the account connection.
*/
private final List<Type> lstTypeConn;
/**
* Type for the account connection.
*/
private final List<String> lstTargetConn;
/**
* @param _periode periode this account belong to
* @param _colName2Index mapping o column name to index
* @param _row actual row
* @throws EFapsException on error
*/
public ImportAccount(final Instance _periode,
final Map<String, Integer> _colName2Index,
final String[] _row,
final Map<String, List<String>> _validateMap,
final Map<String, ImportAccount> _accountVal)
throws EFapsException
{
this.lstTypeConn = new ArrayList<Type>();
this.lstTargetConn = new ArrayList<String>();
this.value = _row[_colName2Index.get(Import_Base.AcccountColumn.VALUE.getKey())].trim().replaceAll("\n",
"");
this.description = _row[_colName2Index.get(Import_Base.AcccountColumn.NAME.getKey())].trim()
.replaceAll("\n", "");
final String type = _row[_colName2Index.get(Import_Base.AcccountColumn.TYPE.getKey())].trim().replaceAll(
"\n", "");
final boolean summary = "yes".equalsIgnoreCase(_row[_colName2Index.get(Import_Base.AcccountColumn.SUMMARY
.getKey())]);
final String parentTmp = _row[_colName2Index.get(Import_Base.AcccountColumn.PARENT.getKey())];
if (_validateMap != null) {
for (final Entry<String, List<String>> entry : _validateMap.entrySet()) {
final String typeConnTmp = _row[_colName2Index.get(Import_Base.AcccountColumn.ACC_REL.getKey()
.replace("]", entry.getKey() + "]"))].trim().replaceAll("\n", "");
final String targetConnTmp = _row[_colName2Index.get(Import_Base.AcccountColumn.ACC_TARGET.getKey()
.replace("]", entry.getKey() + "]"))].trim().replaceAll("\n", "");
if (typeConnTmp != null && !typeConnTmp.isEmpty()
&& targetConnTmp != null && !targetConnTmp.isEmpty()) {
this.lstTypeConn.add(Type.get(Import_Base.ACC2ACC.get(typeConnTmp).uuid));
this.lstTargetConn.add(targetConnTmp);
}
}
this.order = _row[_colName2Index.get(Import_Base.AcccountColumn.KEY.getKey())]
.trim().replaceAll("\n", "");
} else {
this.order = null;
}
if (_accountVal != null) {
this.path = _accountVal.get(this.order).getPath();
} else {
this.path = null;
}
this.parent = parentTmp == null ? null : parentTmp.trim().replaceAll("\n", "");
Update update = null;
if (Import_Base.TYPE2TYPE.get(type).getType().isKindOf(CIAccounting.AccountAbstract.getType())) {
final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountBaseAbstract.Name, this.value);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountBaseAbstract.PeriodeAbstractLink, _periode.getId());
final MultiPrintQuery multi = queryBldr.getPrint();
final SelectBuilder selParent = new SelectBuilder().linkto(CIAccounting.AccountBaseAbstract.ParentLink)
.attribute(CIAccounting.AccountBaseAbstract.Name);
multi.addSelect(selParent);
multi.execute();
if (multi.next()) {
final String parentName = multi.<String>getSelect(selParent);
if (parentName != null && parentName.equals(parentTmp)) {
update = new Update(multi.getCurrentInstance());
} else {
update = new Insert(Import_Base.TYPE2TYPE.get(type));
}
} else {
update = new Insert(Import_Base.TYPE2TYPE.get(type));
}
} else if (Import_Base.TYPE2TYPE.get(type).getType().isKindOf(CIAccounting.ViewAbstract.getType())) {
final String[] parts = this.path.split("_");
final Instance updateInst = validateUpdate(this.value, null, _periode, 0, parts);
if (updateInst != null) {
update = new Update(updateInst);
} else {
update = new Insert(Import_Base.TYPE2TYPE.get(type));
}
}
if (Import_Base.TYPE2TYPE.get(type).getType().isKindOf(CIAccounting.AccountAbstract.getType())) {
update.add("Summary", summary);
}
update.add(CIAccounting.AccountBaseAbstract.PeriodeAbstractLink, _periode.getId());
update.add(CIAccounting.AccountBaseAbstract.Name, this.value);
update.add(CIAccounting.AccountBaseAbstract.Description, this.description);
update.execute();
this.instance = update.getInstance();
}
private Instance validateUpdate(final String _name,
final Long _id,
final Instance _periode,
int _cont,
final String[] _parts) throws EFapsException {
Instance ret = null;
boolean ver = false;
Instance instCur = null;
final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.ViewAbstract);
if (_cont == 0) {
queryBldr.addWhereAttrEqValue(CIAccounting.AccountBaseAbstract.Name, _name);
queryBldr.addWhereAttrEqValue(CIAccounting.AccountBaseAbstract.PeriodeAbstractLink, _periode.getId());
ver = true;
} else {
queryBldr.addWhereAttrEqValue(CIAccounting.AccountBaseAbstract.ID, _id);
}
final MultiPrintQuery multi = queryBldr.getPrint();
final SelectBuilder selParent = new SelectBuilder().linkto(CIAccounting.AccountBaseAbstract.ParentLink)
.attribute(CIAccounting.AccountBaseAbstract.Name);
multi.addSelect(selParent);
multi.addAttribute(CIAccounting.ViewAbstract.ParentLink, CIAccounting.ViewAbstract.Name);
multi.execute();
_cont++;
while (multi.next()) {
instCur = multi.getCurrentInstance();
final Long parentId = multi.<Long>getAttribute(CIAccounting.ViewAbstract.ParentLink);
final String parentName = multi.<String>getSelect(selParent);
if (_cont < (_parts.length)) {
if (parentName.equals(_parts[_cont])) {
ret = validateUpdate(parentName, parentId, _periode, _cont, _parts);
if (ret != null) {
break;
}
}
} else if (_cont == _parts.length && parentId == null) {
ret = multi.getCurrentInstance();
break;
}
}
if (ver && ret != null) {
ret = instCur;
}
return ret;
}
/**
* new Constructor for import accounts of the period.
* @param _accountIns Instance of the account.
* @param _parentName name of a parent accounts.
* @param _name name of account.
*/
public ImportAccount(final Map<String, Integer> _colName2Index,
final String[] _row)
{
this.lstTypeConn = new ArrayList<Type>();
this.lstTargetConn = new ArrayList<String>();
this.value = _row[_colName2Index.get(Import_Base.AcccountColumn.VALUE.getKey())].trim().replaceAll("\n",
"");
this.description = _row[_colName2Index.get(Import_Base.AcccountColumn.NAME.getKey())].trim().replaceAll("\n",
"");
final String parentTmp = _row[_colName2Index.get(Import_Base.AcccountColumn.PARENT.getKey())];
this.order = _row[_colName2Index.get(Import_Base.AcccountColumn.KEY.getKey())]
.trim().replaceAll("\n", "");
this.parent = parentTmp == null ? null : parentTmp.trim().replaceAll("\n", "");
this.instance = null;
this.path = this.value;
}
/**
* new Constructor for import accounts of the period.
* @param _accountIns Instance of the account.
* @param _parentName name of a parent accounts.
* @param _name name of account.
*/
public ImportAccount(final Instance _accountIns,
final String _parentName,
final String _name,
final String _description,
final String _order,
final String _path,
final List<Type> _lstTypeConn,
final List<String> _lstTargetConn)
{
this.instance = _accountIns;
this.parent = _parentName;
this.value = _name;
this.description = _description;
this.lstTypeConn = _lstTypeConn;
this.lstTargetConn = _lstTargetConn;
this.order = _order;
this.path = _path;
}
/**
* Getter method for instance variable {@link #value}.
*
* @return value of instance variable {@link #value}
*/
public String getValue()
{
return this.value;
}
/**
* Getter method for instance variable {@link #description}.
*
* @return description of instance variable {@link #description}
*/
public String getDescription()
{
return this.description;
}
/**
* Getter method for instance variable {@link #parent}.
*
* @return value of instance variable {@link #parent}
*/
public String getParent()
{
return this.parent;
}
/**
* Getter method for instance variable {@link #order}.
*
* @return value of instance variable {@link #order}
*/
public String getOrder()
{
return this.order;
}
/**
* Getter method for instance variable {@link #instance}.
*
* @return value of instance variable {@link #instance}
*/
public Instance getInstance()
{
return this.instance;
}
/**
* Getter method for instance variable {@link #lstTypeConn}.
*
* @return the lstTypeConn
*/
private List<Type> getLstTypeConn()
{
return this.lstTypeConn;
}
/**
* Getter method for instance variable {@link #lstTargetConn}.
*
* @return the lstTargetConn
*/
private List<String> getLstTargetConn()
{
return this.lstTargetConn;
}
/**
* @return the path
*/
private String getPath()
{
return this.path;
}
/**
* @param path the path to set
*/
private void setPath(final String path)
{
this.path = path;
}
}
/**
* Represents on report to be imported.
*/
public class ImportReport
{
/**
* Instance of this report.
*/
private final Instance instance;
/**
* Mapping of node to node level.
*/
private final Map<Integer, List<ImportNode>> level2Nodes = new HashMap<Integer, List<ImportNode>>();
/**
* @param _periodInst instance of the period.
* @param _type name of type.
* @param _name name of the report.
* @param _description description of the report.
* @param _numbering numbering of the report.
* @throws EFapsException on error
*/
protected ImportReport(final Instance _periodInst,
final String _type,
final String _name,
final String _description,
final String _numbering)
throws EFapsException
{
final Insert insert = new Insert(Import_Base.TYPE2TYPE.get(_type));
insert.add(CIAccounting.ReportAbstract.PeriodeLink, _periodInst.getId());
insert.add(CIAccounting.ReportAbstract.Name, _name);
insert.add(CIAccounting.ReportAbstract.Description, _description);
insert.add(CIAccounting.ReportAbstract.Numbering, _numbering);
insert.execute();
this.instance = insert.getInstance();
}
/**
* Add a node to this report.
*
* @param _colName2Index mapping of column name 2 index
* @param _row actual row
* @param _max max level key
* @param _accounts list of accounts
* @throws EFapsException on error
*/
public void addNode(final Map<String, Integer> _colName2Index,
final String[] _row,
final Integer _max,
final Map<String, Import_Base.ImportAccount> _accounts)
throws EFapsException
{
// search the level
int level = 0;
String levelkey = "";
for (Integer i = 0; i < _max; i++) {
levelkey = Import_Base.LEVELCOLUMN.replace("#", i.toString());
final String value = _row[_colName2Index.get(levelkey)];
if (value != null && value.length() > 1) {
level = i;
break;
}
}
final Instance parentInst;
if (level < 1) {
parentInst = this.instance;
} else {
final List<ImportNode> lis = this.level2Nodes.get(level - 1);
parentInst = lis.get(lis.size() - 1).getInstance();
}
List<ImportNode> nodes;
if (this.level2Nodes.containsKey(level)) {
nodes = this.level2Nodes.get(level);
} else {
nodes = new ArrayList<ImportNode>();
this.level2Nodes.put(level, nodes);
}
final ImportNode node = new ImportNode(_colName2Index, _row, levelkey, parentInst, _accounts, nodes.size());
nodes.add(node);
}
}
/**
* Represents one node to be imported.
*/
public class ImportNode
{
/**
* Instance of this node.
*/
private final Instance instance;
/**
* new Constructor for import Nodes.
*
* @param _colName2Index mapping of column name 2 index.
* @param _row actual row.
* @param _level level key.
* @param _parentInst parent instance.
* @param _accounts list of accounts.
* @param _position order position.
* @throws EFapsException on error.
*/
public ImportNode(final Map<String, Integer> _colName2Index,
final String[] _row,
final String _level,
final Instance _parentInst,
final Map<String, Import_Base.ImportAccount> _accounts,
final int _position)
throws EFapsException
{
final String type = _row[_colName2Index.get(Import_Base.ReportColumn.NODE_TYPE.getKey())].trim()
.replaceAll("\n", "");
final boolean showAllways = !"false".equalsIgnoreCase(_row[_colName2Index
.get(Import_Base.ReportColumn.NODE_SHOW.getKey())]);
final boolean showSum = !"false".equalsIgnoreCase(_row[_colName2Index
.get(Import_Base.ReportColumn.NODE_SUM.getKey())]);
final String number = _row[_colName2Index.get(Import_Base.ReportColumn.NODE_NUMBER.getKey())].trim()
.replaceAll("\n", "");
final String value = _row[_colName2Index.get(_level)].trim().replaceAll("\n", "");
final Insert insert = new Insert(Import_Base.TYPE2TYPE.get(type));
insert.add(CIAccounting.ReportNodeAbstract.ShowAllways, showAllways);
insert.add(CIAccounting.ReportNodeAbstract.ShowSum, showSum);
if (CIAccounting.ReportNodeRoot.equals(Import_Base.TYPE2TYPE.get(type))) {
if (_parentInst.isValid()) {
insert.add(CIAccounting.ReportNodeRoot.Number, number);
insert.add(CIAccounting.ReportNodeRoot.Label, value);
insert.add(CIAccounting.ReportNodeRoot.ReportLink, _parentInst);
insert.add(CIAccounting.ReportNodeRoot.Position, _position);
insert.execute();
} else {
Import_Base.LOG.error("Report Instance does not exist for '{}'- '{}' ", number, value);
}
} else if (CIAccounting.ReportNodeTree.equals(Import_Base.TYPE2TYPE.get(type))) {
if (_parentInst.isValid()) {
insert.add(CIAccounting.ReportNodeTree.Number, number);
insert.add(CIAccounting.ReportNodeTree.Label, value);
insert.add(CIAccounting.ReportNodeTree.ParentLink, _parentInst);
insert.add(CIAccounting.ReportNodeTree.Position, _position);
insert.execute();
} else {
Import_Base.LOG.error("Parent Node Instance does not exist for '{}'- '{}' ", number, value);
}
} else if (CIAccounting.ReportNodeAccount.equals(Import_Base.TYPE2TYPE.get(type))) {
if (_parentInst.isValid()) {
insert.add(CIAccounting.ReportNodeAccount.ParentLink, _parentInst.getId());
if (_accounts.get(value) == null) {
Import_Base.LOG.error("Account Instance not exist: " + value);
} else {
insert.add(CIAccounting.ReportNodeAccount.AccountLink, _accounts.get(value).getInstance());
insert.add(CIAccounting.ReportNodeAccount.Label,
value + " - " + _accounts.get(value).getDescription());
insert.execute();
}
} else {
Import_Base.LOG.error("Parent Node Instance does not exist for Account Node '{}'- '{}' ",
number, value);
}
}
this.instance = insert.getInstance();
}
/**
* Getter method for instance variable {@link #instance}.
*
* @return value of instance variable {@link #instance}
*/
public Instance getInstance()
{
return this.instance;
}
}
}
|
- accounting: update methods to import cases.
git-svn-id: ac075fd2700e7900720405e7f73d39e95a0f4823@10670 fee104cc-1dfa-8c0f-632d-d3b7e6b59fb0
|
src/main/efaps/ESJP/org/efaps/esjp/accounting/Import_Base.java
|
- accounting: update methods to import cases.
|
<ide><path>rc/main/efaps/ESJP/org/efaps/esjp/accounting/Import_Base.java
<ide> /*
<del> * Copyright 2003 - 2010 The eFaps Team
<add> * Copyright 2003 - 2013 The eFaps Team
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import org.apache.commons.lang3.builder.ToStringBuilder;
<ide> import org.apache.commons.lang3.builder.ToStringStyle;
<add>import org.efaps.admin.datamodel.Classification;
<ide> import org.efaps.admin.datamodel.Type;
<ide> import org.efaps.admin.event.Parameter;
<ide> import org.efaps.admin.event.Return;
<ide> import org.efaps.ci.CIType;
<ide> import org.efaps.db.Context;
<ide> import org.efaps.db.Context.FileParameter;
<add>import org.efaps.db.Delete;
<ide> import org.efaps.db.Insert;
<ide> import org.efaps.db.Instance;
<ide> import org.efaps.db.InstanceQuery;
<ide> /** */
<ide> A2CTYPE("[Account2Case_Type]"),
<ide> A2CACC("[Account2Case_Account]"),
<add> A2CCLA("[Account2Case_Classification]"),
<ide> A2CNUM("[Account2Case_Numerator]"),
<ide> A2CDENUM("[Account2Case_Denominator]"),
<ide> A2CDEFAULT("[Account2Case_Default]"),
<ide> Import_Base.ACC2ACC.put("ViewSumAccount", CIAccounting.ViewSum2Account);
<ide> Import_Base.ACC2ACC.put("AccountCosting", CIAccounting.Account2AccountCosting);
<ide> Import_Base.ACC2ACC.put("AccountInverseCosting", CIAccounting.Account2AccountCostingInverse);
<del> Import_Base.ACC2ACC.put("AccountCredit", CIAccounting.Account2AccountCredit);
<del> Import_Base.ACC2ACC.put("AccountDebit", CIAccounting.Account2AccountDebit);
<add> Import_Base.ACC2ACC.put("AccountAbono", CIAccounting.Account2AccountCredit);
<add> Import_Base.ACC2ACC.put("AccountCargo", CIAccounting.Account2AccountDebit);
<ide> }
<ide>
<ide>
<ide> static {
<ide> Import_Base.ACC2CASE.put("Credit", CIAccounting.Account2CaseCredit);
<ide> Import_Base.ACC2CASE.put("Debit", CIAccounting.Account2CaseDebit);
<add> Import_Base.ACC2CASE.put("CreditClassification", CIAccounting.Account2CaseCredit4Classification);
<add> Import_Base.ACC2CASE.put("DebitClassification", CIAccounting.Account2CaseDebit4Classification);
<ide> }
<ide>
<ide> /**
<ide> entries.remove(0);
<ide>
<ide> for (final String[] row : entries) {
<del> final ImportAccount account = new ImportAccount(_periodInst, colName2Index, row, null, null);
<add> final ImportAccount account = new ImportAccount(_periodInst, colName2Index, row, validateMap, null);
<ide> accounts.put(account.getValue(), account);
<ide> }
<ide> for (final ImportAccount account : accounts.values()) {
<ide> final List<Type> lstTypes = account.getLstTypeConn();
<ide> final List<String> lstTarget = account.getLstTargetConn();
<ide>
<del> final int cont = 0;
<add> int cont = 0;
<ide> for (final Type type : lstTypes) {
<add> deleteExistingConnections(type, account.getInstance());
<add>
<ide> final String nameAcc = lstTarget.get(cont);
<ide> final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract);
<ide> queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, nameAcc);
<ide> query.getCurrentValue().getId());
<ide> insert.execute();
<ide> }
<add> cont++;
<ide> }
<ide> }
<ide> }
<ide> throw new EFapsException(Periode.class, "createAccountTable.IOException", e);
<ide> }
<ide> return accounts;
<add> }
<add>
<add> protected void deleteExistingConnections(final Type _type,
<add> final Instance _accInstance)
<add> throws EFapsException
<add> {
<add> final QueryBuilder queryBldrConn = new QueryBuilder(_type);
<add> queryBldrConn.addWhereAttrEqValue(CIAccounting.Account2AccountAbstract.FromAccountLink, _accInstance);
<add> final InstanceQuery query = queryBldrConn.getQuery();
<add> query.execute();
<add> while (query.next()) {
<add> final Delete delete = new Delete(query.getCurrentValue());
<add> delete.execute();
<add> }
<ide> }
<ide>
<ide> protected HashMap<String, ImportAccount> createViewAccountTable(final Instance _periodInst,
<ide> private String caseDescription;
<ide> private CIType casetype;
<ide> private CIType a2cType;
<add> private String a2cClass;
<ide> private String a2cNum;
<ide> private String a2cDenum;
<ide> private boolean a2cDefault;
<ide> {
<ide> try {
<ide> this.periodeInst = _periodInst;
<del> this.caseName = _row[_colName2Index.get(Import_Base.CaseColumn.CASENAME.getKey())].trim().replaceAll(
<del> "\n",
<del> "");
<add> this.caseName = _row[_colName2Index.get(Import_Base.CaseColumn.CASENAME.getKey())].trim()
<add> .replaceAll("\n", "");
<ide> this.caseDescription = _row[_colName2Index.get(Import_Base.CaseColumn.CASEDESC.getKey())].trim()
<del> .replaceAll("\n",
<del> "");
<add> .replaceAll("\n", "");
<ide> final String type = _row[_colName2Index.get(Import_Base.CaseColumn.CASETYPE.getKey())].trim()
<del> .replaceAll(
<del> "\n", "");
<add> .replaceAll("\n", "");
<ide> this.casetype = Import_Base.TYPE2TYPE.get(type);
<del> final String a2c = _row[_colName2Index.get(Import_Base.CaseColumn.A2CTYPE.getKey())].trim().replaceAll(
<del> "\n", "");
<add> final String a2c = _row[_colName2Index.get(Import_Base.CaseColumn.A2CTYPE.getKey())].trim()
<add> .replaceAll("\n", "");
<add>
<ide> this.a2cType = Import_Base.ACC2CASE.get(a2c);
<ide>
<del> this.a2cNum = _row[_colName2Index.get(Import_Base.CaseColumn.A2CNUM.getKey())].trim().replaceAll(
<del> "\n", "");
<del> this.a2cDenum = _row[_colName2Index.get(Import_Base.CaseColumn.A2CDENUM.getKey())].trim().replaceAll(
<del> "\n", "");
<add> this.a2cNum = _row[_colName2Index.get(Import_Base.CaseColumn.A2CNUM.getKey())].trim()
<add> .replaceAll("\n", "");
<add> this.a2cDenum = _row[_colName2Index.get(Import_Base.CaseColumn.A2CDENUM.getKey())].trim()
<add> .replaceAll("\n", "");
<ide> this.a2cDefault = "yes".equalsIgnoreCase(_row[_colName2Index.get(Import_Base.CaseColumn.A2CDEFAULT
<ide> .getKey())])
<ide> || "true".equalsIgnoreCase(_row[_colName2Index.get(Import_Base.CaseColumn.A2CDEFAULT
<ide> .getKey())]);
<ide>
<ide> final String accName = _row[_colName2Index.get(Import_Base.CaseColumn.A2CACC.getKey())].trim()
<del> .replaceAll(
<del> "\n", "");
<add> .replaceAll("\n", "");
<add>
<add> if (_colName2Index.containsKey(Import_Base.CaseColumn.A2CCLA.getKey())
<add> && (a2cType.getType().isKindOf(CIAccounting.Account2CaseDebit4Classification.getType())
<add> || a2cType.getType().isKindOf(CIAccounting.Account2CaseCredit4Classification.getType()))) {
<add> this.a2cClass = _row[_colName2Index.get(Import_Base.CaseColumn.A2CCLA.getKey())].trim()
<add> .replaceAll("\n", "");
<add> }
<ide>
<ide> final QueryBuilder queryBuilder = new QueryBuilder(CIAccounting.AccountAbstract);
<ide> queryBuilder.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, accName);
<ide> insert.add(CIAccounting.Account2CaseAbstract.Denominator, this.a2cDenum);
<ide> insert.add(CIAccounting.Account2CaseAbstract.Numerator, this.a2cNum);
<ide> insert.add(CIAccounting.Account2CaseAbstract.Default, this.a2cDefault);
<add> if (this.a2cClass != null) {
<add> insert.add(CIAccounting.Account2CaseAbstract.LinkValue, Classification.get(this.a2cClass).getId());
<add> }
<ide> insert.execute();
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
9da21889315cfcc555710face23041cfdeae3fa9
| 0 |
codarchlab/chronontology-connected,codarchlab/chronontology-connected
|
package org.dainst.chronontology.handler;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.commons.lang3.RandomStringUtils;
import org.dainst.chronontology.handler.dispatch.Dispatcher;
import org.dainst.chronontology.handler.model.Document;
import org.dainst.chronontology.handler.model.RightsValidator;
import spark.Request;
import spark.Response;
import java.io.IOException;
import static org.dainst.chronontology.Constants.HTTP_BAD_REQUEST;
import static org.dainst.chronontology.Constants.HTTP_FORBIDDEN;
import static org.dainst.chronontology.util.JsonUtils.json;
/**
* @author Daniel de Oliveira
*/
public abstract class DocumentHandler implements Handler {
private static final String ID = ":id";
public DocumentHandler(Dispatcher dispatcher, RightsValidator rightsValidator) {
this.dispatcher = dispatcher;
this.rightsValidator= rightsValidator;
}
protected final Dispatcher dispatcher;
protected final RightsValidator rightsValidator;
protected final Document makeDocumentModel(
Request req,
Response res,
boolean createId) {
JsonNode n= json(req.body());
if (n==null) {
res.status(HTTP_BAD_REQUEST);
return null;
}
String resourceId= null;
String resourceType= null;
String pathInfo= req.pathInfo();
System.out.println("rq"+req);
System.out.println("pathInfo"+pathInfo);
if (req.pathInfo().startsWith("/data/")) {
pathInfo= req.pathInfo().substring(5);
}
if (createId) {
resourceId= determineFreeId(req);
resourceType= pathInfo.replaceAll("/","");
} else {
resourceId= pathInfo.replaceFirst("\\/.*\\/","");
resourceType= pathInfo.substring(0,pathInfo.lastIndexOf("/")).replaceAll("/","");
}
Document dm = new Document(
resourceId, resourceType,json(req.body()), req.attribute("user"));
if (!userAccessLevelSufficient(req,dm, RightsValidator.Operation.EDIT)) {
res.status(HTTP_FORBIDDEN);
return null;
}
return dm;
}
protected final boolean userAccessLevelSufficient(Request req, Document dm, RightsValidator.Operation operation) {
if (dm.getDataset()!=null &&
!rightsValidator.hasPermission(req.attribute("user"),
dm.getDataset(), operation)) {
return false;
}
return true;
}
protected String type(Request req) {
String tmp = req.pathInfo();
if (tmp.startsWith("/data/")) tmp = tmp.substring(6);
if (req.params(ID) != null) tmp = tmp.replace(req.params(ID),"");
return tmp;
}
protected String simpleId(Request req) {
return req.params(ID);
}
private static String generateId() {
return RandomStringUtils.randomAlphanumeric(12);
}
private String determineFreeId(Request req) {
String id;
JsonNode existingDoc= null;
do {
id= generateId();
existingDoc = dispatcher.dispatchGet(req.pathInfo(),id);
} while (existingDoc!=null);
return id;
}
@Override
public abstract Object handle(Request req, Response res) throws IOException;
}
|
src/main/java/org/dainst/chronontology/handler/DocumentHandler.java
|
package org.dainst.chronontology.handler;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.commons.lang3.RandomStringUtils;
import org.dainst.chronontology.handler.dispatch.Dispatcher;
import org.dainst.chronontology.handler.model.Document;
import org.dainst.chronontology.handler.model.RightsValidator;
import spark.Request;
import spark.Response;
import java.io.IOException;
import static org.dainst.chronontology.Constants.HTTP_BAD_REQUEST;
import static org.dainst.chronontology.Constants.HTTP_FORBIDDEN;
import static org.dainst.chronontology.util.JsonUtils.json;
/**
* @author Daniel de Oliveira
*/
public abstract class DocumentHandler implements Handler {
private static final String ID = ":id";
public DocumentHandler(Dispatcher dispatcher, RightsValidator rightsValidator) {
this.dispatcher = dispatcher;
this.rightsValidator= rightsValidator;
}
protected final Dispatcher dispatcher;
protected final RightsValidator rightsValidator;
protected final Document makeDocumentModel(
Request req,
Response res,
boolean createId) {
JsonNode n= json(req.body());
if (n==null) {
res.status(HTTP_BAD_REQUEST);
return null;
}
String resourceId= null;
String resourceType= null;
String pathInfo= req.pathInfo();
if (req.pathInfo().startsWith("/data/")) {
pathInfo= req.pathInfo().substring(5);
}
if (createId) {
resourceId= determineFreeId(req);
resourceType= pathInfo.replaceAll("/","");
} else {
resourceId= pathInfo.replaceFirst("\\/.*\\/","");
resourceType= pathInfo.substring(0,pathInfo.lastIndexOf("/")).replaceAll("/","");
}
Document dm = new Document(
resourceId, resourceType,json(req.body()), req.attribute("user"));
if (!userAccessLevelSufficient(req,dm, RightsValidator.Operation.EDIT)) {
res.status(HTTP_FORBIDDEN);
return null;
}
return dm;
}
protected final boolean userAccessLevelSufficient(Request req, Document dm, RightsValidator.Operation operation) {
if (dm.getDataset()!=null &&
!rightsValidator.hasPermission(req.attribute("user"),
dm.getDataset(), operation)) {
return false;
}
return true;
}
protected String type(Request req) {
String tmp = req.pathInfo();
if (tmp.startsWith("/data/")) tmp = tmp.substring(6);
if (req.params(ID) != null) tmp = tmp.replace(req.params(ID),"");
return tmp;
}
protected String simpleId(Request req) {
return req.params(ID);
}
private static String generateId() {
return RandomStringUtils.randomAlphanumeric(12);
}
private String determineFreeId(Request req) {
String id;
JsonNode existingDoc= null;
do {
id= generateId();
existingDoc = dispatcher.dispatchGet(req.pathInfo(),id);
} while (existingDoc!=null);
return id;
}
@Override
public abstract Object handle(Request req, Response res) throws IOException;
}
|
Add log msg
|
src/main/java/org/dainst/chronontology/handler/DocumentHandler.java
|
Add log msg
|
<ide><path>rc/main/java/org/dainst/chronontology/handler/DocumentHandler.java
<ide> String resourceType= null;
<ide>
<ide> String pathInfo= req.pathInfo();
<add> System.out.println("rq"+req);
<add> System.out.println("pathInfo"+pathInfo);
<ide> if (req.pathInfo().startsWith("/data/")) {
<ide> pathInfo= req.pathInfo().substring(5);
<ide> }
|
|
Java
|
mit
|
ad4c253341aef17ee9a401f23aa5c31c43257676
| 0 |
fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg
|
package ua.com.fielden.platform.dao;
import static org.junit.Assert.*;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.*;
import java.util.List;
import org.junit.Test;
import ua.com.fielden.platform.entity.query.fluent.fetch;
import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel;
import ua.com.fielden.platform.entity.query.model.OrderingModel;
import ua.com.fielden.platform.persistence.composite.EntityWithDynamicCompositeKey;
import ua.com.fielden.platform.persistence.types.EntityWithMoney;
import ua.com.fielden.platform.test.ioc.UniversalConstantsForTesting;
import ua.com.fielden.platform.test_config.AbstractDaoTestCase;
import ua.com.fielden.platform.types.Money;
import ua.com.fielden.platform.utils.IUniversalConstants;
/**
* A test case to ensure correct instantiation of entities from the instrumentation perspective during retrieval.
*
* @author TG Team
*
*/
public class CommonEntityDaoInstrumentationTest extends AbstractDaoTestCase {
@Test
public void by_default_find_by_key_returns_instrumented_instances() {
final EntityWithMoney entity = co(EntityWithMoney.class).findByKey("KEY1");
assertTrue(entity.isInstrumented());
}
@Test
public void uninstrumented_find_by_key_returns_unnstrumented_instances() {
final EntityWithMoney entity = co(EntityWithMoney.class).uninstrumented().findByKey("KEY1");
assertFalse(entity.isInstrumented());
}
@Test
public void by_default_find_by_id_returns_instrumented_instances() {
final IEntityDao<EntityWithMoney> co = co(EntityWithMoney.class);
final EntityWithMoney entity = co.findById(co.findByKey("KEY1").getId());
assertTrue(entity.isInstrumented());
}
@Test
public void uninstrumented_find_by_id_returns_uninstrumented_instances() {
final IEntityDao<EntityWithMoney> co = co(EntityWithMoney.class);
final EntityWithMoney entity = co.uninstrumented().findById(co.findByKey("KEY1").getId());
assertFalse(entity.isInstrumented());
}
@Test
public void by_default_find_by_id_and_fetch_returns_instrumented_instances() {
final IEntityDao<EntityWithMoney> co = co(EntityWithMoney.class);
final EntityWithMoney entity = co.findById(co.findByKey("KEY1").getId(), fetchAll(EntityWithMoney.class));
assertTrue(entity.isInstrumented());
}
@Test
public void uninstrumented_find_by_id_and_fetch_returns_uninstrumented_instances() {
final IEntityDao<EntityWithMoney> co = co(EntityWithMoney.class);
final EntityWithMoney entity = co.uninstrumented().findById(co.findByKey("KEY1").getId(), fetchAll(EntityWithMoney.class));
assertFalse(entity.isInstrumented());
}
@Test
public void by_default_find_by_key_and_fetch_returns_instrumented_instances() {
final IEntityDao<EntityWithMoney> co = co(EntityWithMoney.class);
final EntityWithMoney entity = co.findByKeyAndFetch(fetchAll(EntityWithMoney.class), "KEY1");
assertTrue(entity.isInstrumented());
}
@Test
public void uninstrumented_find_by_key_and_fetch_returns_uninstrumented_instances() {
final IEntityDao<EntityWithMoney> co = co(EntityWithMoney.class);
final EntityWithMoney entity = co.uninstrumented().findByKeyAndFetch(fetchAll(EntityWithMoney.class), "KEY1");
assertFalse(entity.isInstrumented());
}
@Test
public void by_default_first_page_returns_instrumented_instances() {
final List<EntityWithMoney> entities = co(EntityWithMoney.class).firstPage(10).data();
assertTrue(entities.size() > 0);
assertEquals("All entities are instrumented", entities.size(), entities.stream().filter(e -> e.isInstrumented()).count());
}
@Test
public void uninstrumented_first_page_returns_uninstrumented_instances() {
final List<EntityWithMoney> entities = co(EntityWithMoney.class).uninstrumented().firstPage(10).data();
assertTrue(entities.size() > 0);
assertEquals("All entities are instrumented", 0, entities.stream().filter(e -> e.isInstrumented()).count());
}
@Test
public void by_default_first_page_with_EQL_model_returns_instrumented_instances() {
final QueryExecutionModel<EntityWithMoney, EntityResultQueryModel<EntityWithMoney>> qem =
from(select(EntityWithMoney.class).where().prop("money.amount").gt().val(20).model())
.with(fetchAll(EntityWithMoney.class))
.with(orderBy().prop("key").asc().model()).model();
final List<EntityWithMoney> entities = co(EntityWithMoney.class).firstPage(qem, 10).data();
assertTrue(entities.size() > 0);
assertEquals("All entities are instrumented", entities.size(), entities.stream().filter(e -> e.isInstrumented()).count());
}
@Test
public void by_default_first_page_with_lightweight_EQL_model_returns_uninstrumented_instances() {
final QueryExecutionModel<EntityWithMoney, EntityResultQueryModel<EntityWithMoney>> qem =
from(select(EntityWithMoney.class).where().prop("money.amount").gt().val(20).model())
.with(fetchAll(EntityWithMoney.class))
.with(orderBy().prop("key").asc().model()).lightweight().model();
final List<EntityWithMoney> entities = co(EntityWithMoney.class).firstPage(qem, 10).data();
assertTrue(entities.size() > 0);
assertEquals("All entities are instrumented", 0, entities.stream().filter(e -> e.isInstrumented()).count());
}
@Test
public void uninstrumented_first_page_with_EQL_model_returns_uninstrumented_instances() {
final QueryExecutionModel<EntityWithMoney, EntityResultQueryModel<EntityWithMoney>> qem =
from(select(EntityWithMoney.class).where().prop("money.amount").gt().val(20).model())
.with(fetchAll(EntityWithMoney.class))
.with(orderBy().prop("key").asc().model()).model();
final List<EntityWithMoney> entities = co(EntityWithMoney.class).uninstrumented().firstPage(qem, 10).data();
assertTrue(entities.size() > 0);
assertEquals("All entities are instrumented", 0, entities.stream().filter(e -> e.isInstrumented()).count());
}
@Test
public void uninstrumented_first_page_with_lightweight_EQL_model_returns_uninstrumented_instances() {
final QueryExecutionModel<EntityWithMoney, EntityResultQueryModel<EntityWithMoney>> qem =
from(select(EntityWithMoney.class).where().prop("money.amount").gt().val(20).model())
.with(fetchAll(EntityWithMoney.class))
.with(orderBy().prop("key").asc().model()).lightweight().model();
final List<EntityWithMoney> entities = co(EntityWithMoney.class).uninstrumented().firstPage(qem, 10).data();
assertTrue(entities.size() > 0);
assertEquals("All entities are instrumented", 0, entities.stream().filter(e -> e.isInstrumented()).count());
}
@Override
protected void populateDomain() {
super.populateDomain();
final UniversalConstantsForTesting constants = (UniversalConstantsForTesting) getInstance(IUniversalConstants.class);
constants.setNow(dateTime("2016-02-19 02:47:00"));
final EntityWithMoney keyPartTwo = save(new_ (EntityWithMoney.class, "KEY1", "desc").setMoney(new Money("20.00")).setDateTimeProperty(date("2009-03-01 11:00:55")));
save(new_composite(EntityWithDynamicCompositeKey.class, "key-1-1", keyPartTwo));
save(new_ (EntityWithMoney.class, "KEY2", "desc").setMoney(new Money("30.00")).setDateTimeProperty(date("2009-03-01 00:00:00")));
save(new_ (EntityWithMoney.class, "KEY3", "desc").setMoney(new Money("40.00")));
save(new_ (EntityWithMoney.class, "KEY4", "desc").setMoney(new Money("50.00")).setDateTimeProperty(date("2009-03-01 10:00:00")));
}
}
|
platform-dao/src/test/java/ua/com/fielden/platform/dao/CommonEntityDaoInstrumentationTest.java
|
package ua.com.fielden.platform.dao;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.cond;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.expr;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetch;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchAggregates;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchAll;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchAllInclCalc;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchKeyAndDescOnly;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchOnly;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.from;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.orderBy;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select;
import org.junit.Test;
import ua.com.fielden.platform.entity.query.EntityAggregates;
import ua.com.fielden.platform.entity.query.fluent.fetch;
import ua.com.fielden.platform.entity.query.model.AggregatedResultQueryModel;
import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel;
import ua.com.fielden.platform.entity.query.model.OrderingModel;
import ua.com.fielden.platform.persistence.composite.EntityWithDynamicCompositeKey;
import ua.com.fielden.platform.persistence.types.EntityWithMoney;
import ua.com.fielden.platform.test.ioc.UniversalConstantsForTesting;
import ua.com.fielden.platform.test_config.AbstractDaoTestCase;
import ua.com.fielden.platform.types.Money;
import ua.com.fielden.platform.utils.IUniversalConstants;
/**
* A test case to ensure correct instantiation of entities from the instrumentation perspective during retrieval.
*
* @author TG Team
*
*/
public class CommonEntityDaoInstrumentationTest extends AbstractDaoTestCase {
@Test
public void by_default_find_by_key_returns_instrumented_instances() {
final EntityWithMoney entity = co(EntityWithMoney.class).findByKey("KEY1");
assertTrue(entity.isInstrumented());
}
@Test
public void uninstrumented_find_by_key_returns_unnstrumented_instances() {
final EntityWithMoney entity = co(EntityWithMoney.class).uninstrumented().findByKey("KEY1");
assertFalse(entity.isInstrumented());
}
@Test
public void by_default_find_by_id_returns_instrumented_instances() {
final IEntityDao<EntityWithMoney> co = co(EntityWithMoney.class);
final EntityWithMoney entity = co.findById(co.findByKey("KEY1").getId());
assertTrue(entity.isInstrumented());
}
@Test
public void uninstrumented_find_by_id_returns_uninstrumented_instances() {
final IEntityDao<EntityWithMoney> co = co(EntityWithMoney.class);
final EntityWithMoney entity = co.uninstrumented().findById(co.findByKey("KEY1").getId());
assertFalse(entity.isInstrumented());
}
@Test
public void by_default_find_by_id_and_fetch_returns_instrumented_instances() {
final IEntityDao<EntityWithMoney> co = co(EntityWithMoney.class);
final EntityWithMoney entity = co.findById(co.findByKey("KEY1").getId(), fetchAll(EntityWithMoney.class));
assertTrue(entity.isInstrumented());
}
@Test
public void uninstrumented_find_by_id_and_fetch_returns_uninstrumented_instances() {
final IEntityDao<EntityWithMoney> co = co(EntityWithMoney.class);
final EntityWithMoney entity = co.uninstrumented().findById(co.findByKey("KEY1").getId(), fetchAll(EntityWithMoney.class));
assertFalse(entity.isInstrumented());
}
@Test
public void by_default_find_by_key_and_fetch_returns_instrumented_instances() {
final IEntityDao<EntityWithMoney> co = co(EntityWithMoney.class);
final EntityWithMoney entity = co.findByKeyAndFetch(fetchAll(EntityWithMoney.class), "KEY1");
assertTrue(entity.isInstrumented());
}
@Test
public void uninstrumented_find_by_key_and_fetch_returns_uninstrumented_instances() {
final IEntityDao<EntityWithMoney> co = co(EntityWithMoney.class);
final EntityWithMoney entity = co.uninstrumented().findByKeyAndFetch(fetchAll(EntityWithMoney.class), "KEY1");
assertFalse(entity.isInstrumented());
}
@Override
protected void populateDomain() {
super.populateDomain();
final UniversalConstantsForTesting constants = (UniversalConstantsForTesting) getInstance(IUniversalConstants.class);
constants.setNow(dateTime("2016-02-19 02:47:00"));
final EntityWithMoney keyPartTwo = save(new_ (EntityWithMoney.class, "KEY1", "desc").setMoney(new Money("20.00")).setDateTimeProperty(date("2009-03-01 11:00:55")));
save(new_composite(EntityWithDynamicCompositeKey.class, "key-1-1", keyPartTwo));
save(new_ (EntityWithMoney.class, "KEY2", "desc").setMoney(new Money("30.00")).setDateTimeProperty(date("2009-03-01 00:00:00")));
save(new_ (EntityWithMoney.class, "KEY3", "desc").setMoney(new Money("40.00")));
save(new_ (EntityWithMoney.class, "KEY4", "desc").setMoney(new Money("50.00")).setDateTimeProperty(date("2009-03-01 10:00:00")));
}
}
|
#612 Implemented unit tests for 'firstPage' set of methods ('IEntityDao' API).
|
platform-dao/src/test/java/ua/com/fielden/platform/dao/CommonEntityDaoInstrumentationTest.java
|
#612 Implemented unit tests for 'firstPage' set of methods ('IEntityDao' API).
|
<ide><path>latform-dao/src/test/java/ua/com/fielden/platform/dao/CommonEntityDaoInstrumentationTest.java
<ide> package ua.com.fielden.platform.dao;
<ide>
<del>import static org.junit.Assert.assertFalse;
<del>import static org.junit.Assert.assertTrue;
<del>import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.cond;
<del>import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.expr;
<del>import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetch;
<del>import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchAggregates;
<del>import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchAll;
<del>import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchAllInclCalc;
<del>import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchKeyAndDescOnly;
<del>import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchOnly;
<del>import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.from;
<del>import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.orderBy;
<del>import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select;
<add>import static org.junit.Assert.*;
<add>import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.*;
<add>
<add>import java.util.List;
<ide>
<ide> import org.junit.Test;
<ide>
<del>import ua.com.fielden.platform.entity.query.EntityAggregates;
<ide> import ua.com.fielden.platform.entity.query.fluent.fetch;
<del>import ua.com.fielden.platform.entity.query.model.AggregatedResultQueryModel;
<ide> import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel;
<ide> import ua.com.fielden.platform.entity.query.model.OrderingModel;
<ide> import ua.com.fielden.platform.persistence.composite.EntityWithDynamicCompositeKey;
<ide> assertFalse(entity.isInstrumented());
<ide> }
<ide>
<del>
<add> @Test
<add> public void by_default_first_page_returns_instrumented_instances() {
<add> final List<EntityWithMoney> entities = co(EntityWithMoney.class).firstPage(10).data();
<add> assertTrue(entities.size() > 0);
<add> assertEquals("All entities are instrumented", entities.size(), entities.stream().filter(e -> e.isInstrumented()).count());
<add> }
<add>
<add> @Test
<add> public void uninstrumented_first_page_returns_uninstrumented_instances() {
<add> final List<EntityWithMoney> entities = co(EntityWithMoney.class).uninstrumented().firstPage(10).data();
<add> assertTrue(entities.size() > 0);
<add> assertEquals("All entities are instrumented", 0, entities.stream().filter(e -> e.isInstrumented()).count());
<add> }
<add>
<add> @Test
<add> public void by_default_first_page_with_EQL_model_returns_instrumented_instances() {
<add> final QueryExecutionModel<EntityWithMoney, EntityResultQueryModel<EntityWithMoney>> qem =
<add> from(select(EntityWithMoney.class).where().prop("money.amount").gt().val(20).model())
<add> .with(fetchAll(EntityWithMoney.class))
<add> .with(orderBy().prop("key").asc().model()).model();
<add>
<add> final List<EntityWithMoney> entities = co(EntityWithMoney.class).firstPage(qem, 10).data();
<add> assertTrue(entities.size() > 0);
<add> assertEquals("All entities are instrumented", entities.size(), entities.stream().filter(e -> e.isInstrumented()).count());
<add> }
<add>
<add> @Test
<add> public void by_default_first_page_with_lightweight_EQL_model_returns_uninstrumented_instances() {
<add> final QueryExecutionModel<EntityWithMoney, EntityResultQueryModel<EntityWithMoney>> qem =
<add> from(select(EntityWithMoney.class).where().prop("money.amount").gt().val(20).model())
<add> .with(fetchAll(EntityWithMoney.class))
<add> .with(orderBy().prop("key").asc().model()).lightweight().model();
<add>
<add> final List<EntityWithMoney> entities = co(EntityWithMoney.class).firstPage(qem, 10).data();
<add> assertTrue(entities.size() > 0);
<add> assertEquals("All entities are instrumented", 0, entities.stream().filter(e -> e.isInstrumented()).count());
<add> }
<add>
<add> @Test
<add> public void uninstrumented_first_page_with_EQL_model_returns_uninstrumented_instances() {
<add> final QueryExecutionModel<EntityWithMoney, EntityResultQueryModel<EntityWithMoney>> qem =
<add> from(select(EntityWithMoney.class).where().prop("money.amount").gt().val(20).model())
<add> .with(fetchAll(EntityWithMoney.class))
<add> .with(orderBy().prop("key").asc().model()).model();
<add>
<add> final List<EntityWithMoney> entities = co(EntityWithMoney.class).uninstrumented().firstPage(qem, 10).data();
<add> assertTrue(entities.size() > 0);
<add> assertEquals("All entities are instrumented", 0, entities.stream().filter(e -> e.isInstrumented()).count());
<add> }
<add>
<add> @Test
<add> public void uninstrumented_first_page_with_lightweight_EQL_model_returns_uninstrumented_instances() {
<add> final QueryExecutionModel<EntityWithMoney, EntityResultQueryModel<EntityWithMoney>> qem =
<add> from(select(EntityWithMoney.class).where().prop("money.amount").gt().val(20).model())
<add> .with(fetchAll(EntityWithMoney.class))
<add> .with(orderBy().prop("key").asc().model()).lightweight().model();
<add>
<add> final List<EntityWithMoney> entities = co(EntityWithMoney.class).uninstrumented().firstPage(qem, 10).data();
<add> assertTrue(entities.size() > 0);
<add> assertEquals("All entities are instrumented", 0, entities.stream().filter(e -> e.isInstrumented()).count());
<add> }
<add>
<ide> @Override
<ide> protected void populateDomain() {
<ide> super.populateDomain();
|
|
Java
|
mit
|
f421f8f8e3e29f593b9d552d05450cd23434dbca
| 0 |
fr1kin/ForgeHax,fr1kin/ForgeHax
|
package com.matt.forgehax.asm.reflection;
import com.matt.forgehax.asm.ASMCommon;
import com.matt.forgehax.asm.utils.fasttype.FastField;
import com.matt.forgehax.asm.utils.fasttype.FastMethod;
import com.matt.forgehax.asm.utils.fasttype.FastTypeBuilder;
import java.nio.FloatBuffer;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.GuiDisconnected;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiEditSign;
import net.minecraft.client.multiplayer.GuiConnecting;
import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.client.renderer.ActiveRenderInfo;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.IAttribute;
import net.minecraft.entity.monster.EntityPigZombie;
import net.minecraft.entity.passive.AbstractHorse;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.item.ItemTool;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.network.play.client.CPacketCloseWindow;
import net.minecraft.network.play.client.CPacketEntityAction;
import net.minecraft.network.play.client.CPacketPlayer;
import net.minecraft.network.play.client.CPacketVehicleMove;
import net.minecraft.network.play.server.SPacketEntityVelocity;
import net.minecraft.network.play.server.SPacketExplosion;
import net.minecraft.network.play.server.SPacketPlayerPosLook;
import net.minecraft.potion.PotionEffect;
import net.minecraft.tileentity.TileEntitySign;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Session;
import net.minecraft.util.Timer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.AnvilChunkLoader;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
/** Created on 5/8/2017 by fr1kin */
public interface FastReflection extends ASMCommon {
// ****************************************
// FIELDS
// ****************************************
interface Fields {
/** ActiveRenderInfo */
FastField<FloatBuffer> ActiveRenderInfo_MODELVIEW =
FastTypeBuilder.create()
.setInsideClass(ActiveRenderInfo.class)
.setName("MODELVIEW")
.autoAssign()
.asField();
FastField<FloatBuffer> ActiveRenderInfo_PROJECTION =
FastTypeBuilder.create()
.setInsideClass(ActiveRenderInfo.class)
.setName("PROJECTION")
.autoAssign()
.asField();
FastField<Vec3d> ActiveRenderInfo_position =
FastTypeBuilder.create()
.setInsideClass(ActiveRenderInfo.class)
.setName("position")
.autoAssign()
.asField();
/** CPacketPlayer */
FastField<Float> CPacketPlayer_pitch =
FastTypeBuilder.create()
.setInsideClass(CPacketPlayer.class)
.setName("pitch")
.autoAssign()
.asField();
FastField<Float> CPacketPlayer_yaw =
FastTypeBuilder.create()
.setInsideClass(CPacketPlayer.class)
.setName("yaw")
.autoAssign()
.asField();
FastField<Boolean> CPacketPlayer_rotating =
FastTypeBuilder.create()
.setInsideClass(CPacketPlayer.class)
.setName("rotating")
.autoAssign()
.asField();
FastField<Boolean> CPacketPlayer_onGround =
FastTypeBuilder.create()
.setInsideClass(CPacketPlayer.class)
.setName("onGround")
.autoAssign()
.asField();
FastField<Double> CPacketPlayer_Y =
FastTypeBuilder.create()
.setInsideClass(CPacketPlayer.class)
.setName("y")
.autoAssign()
.asField();
/** CPacketVehicleMove */
FastField<Float> CPacketVehicleMove_yaw =
FastTypeBuilder.create()
.setInsideClass(CPacketVehicleMove.class)
.setName("yaw")
.autoAssign()
.asField();
/** CPacketCloseWindow */
FastField<Integer> CPacketCloseWindow_windowId =
FastTypeBuilder.create()
.setInsideClass(CPacketCloseWindow.class)
.setName("windowId")
.autoAssign()
.asField();
/** CPacketEntityAction */
FastField<Integer> CPacketEntityAction_entityID =
FastTypeBuilder.create()
.setInsideClass(CPacketEntityAction.class)
.setName("entityID")
.autoAssign()
.asField();
/** SPacketPlayerPosLook */
FastField<Float> SPacketPlayer_pitch =
FastTypeBuilder.create()
.setInsideClass(SPacketPlayerPosLook.class)
.setName("pitch")
.autoAssign()
.asField();
FastField<Float> SPacketPlayer_yaw =
FastTypeBuilder.create()
.setInsideClass(SPacketPlayerPosLook.class)
.setName("yaw")
.autoAssign()
.asField();
/** Entity */
FastField<EntityDataManager> Entity_dataManager =
FastTypeBuilder.create()
.setInsideClass(Entity.class)
.setName("dataManager")
.autoAssign()
.asField();
FastField<Boolean> Entity_inPortal =
FastTypeBuilder.create()
.setInsideClass(Entity.class)
.setName("inPortal")
.autoAssign()
.asField();
/** EntityPigZombie */
FastField<Integer> EntityPigZombie_angerLevel =
FastTypeBuilder.create()
.setInsideClass(EntityPigZombie.class)
.setName("angerLevel")
.autoAssign()
.asField();
/** EntityPlayer */
FastField<Boolean> EntityPlayer_sleeping =
FastTypeBuilder.create()
.setInsideClass(EntityPlayer.class)
.setName("sleeping")
.autoAssign()
.asField();
FastField<Integer> EntityPlayer_sleepTimer =
FastTypeBuilder.create()
.setInsideClass(EntityPlayer.class)
.setName("sleepTimer")
.autoAssign()
.asField();
/** EntityPlayerSP */
FastField<Float> EntityPlayerSP_horseJumpPower =
FastTypeBuilder.create()
.setInsideClass(EntityPlayerSP.class)
.setName("horseJumpPower")
.autoAssign()
.asField();
/** GuiConnecting */
FastField<NetworkManager> GuiConnecting_networkManager =
FastTypeBuilder.create()
.setInsideClass(GuiConnecting.class)
.setName("networkManager")
.autoAssign()
.asField();
/** GuiDisconnected */
FastField<GuiScreen> GuiDisconnected_parentScreen =
FastTypeBuilder.create()
.setInsideClass(GuiDisconnected.class)
.setName("parentScreen")
.autoAssign()
.asField();
FastField<ITextComponent> GuiDisconnected_message =
FastTypeBuilder.create()
.setInsideClass(GuiDisconnected.class)
.setName("message")
.autoAssign()
.asField();
FastField<String> GuiDisconnected_reason =
FastTypeBuilder.create()
.setInsideClass(GuiDisconnected.class)
.setName("reason")
.autoAssign()
.asField();
/** Minecraft */
FastField<Integer> Minecraft_leftClickCounter =
FastTypeBuilder.create()
.setInsideClass(Minecraft.class)
.setName("leftClickCounter")
.autoAssign()
.asField();
FastField<Integer> Minecraft_rightClickDelayTimer =
FastTypeBuilder.create()
.setInsideClass(Minecraft.class)
.setName("rightClickDelayTimer")
.autoAssign()
.asField();
FastField<Timer> Minecraft_timer =
FastTypeBuilder.create()
.setInsideClass(Minecraft.class)
.setName("timer")
.autoAssign()
.asField();
/** PlayerControllerMP */
FastField<Integer> PlayerControllerMP_blockHitDelay =
FastTypeBuilder.create()
.setInsideClass(PlayerControllerMP.class)
.setName("blockHitDelay")
.autoAssign()
.asField();
FastField<Float> PlayerControllerMP_curBlockDamageMP =
FastTypeBuilder.create()
.setInsideClass(PlayerControllerMP.class)
.setName("curBlockDamageMP")
.autoAssign()
.asField();
FastField<Integer> PlayerControllerMP_currentPlayerItem =
FastTypeBuilder.create()
.setInsideClass(PlayerControllerMP.class)
.setName("currentPlayerItem")
.autoAssign()
.asField();
/** SPacketEntityVelocity */
FastField<Integer> SPacketEntityVelocity_motionX =
FastTypeBuilder.create()
.setInsideClass(SPacketEntityVelocity.class)
.setName("motionX")
.autoAssign()
.asField();
FastField<Integer> SPacketEntityVelocity_motionY =
FastTypeBuilder.create()
.setInsideClass(SPacketEntityVelocity.class)
.setName("motionY")
.autoAssign()
.asField();
FastField<Integer> SPacketEntityVelocity_motionZ =
FastTypeBuilder.create()
.setInsideClass(SPacketEntityVelocity.class)
.setName("motionZ")
.autoAssign()
.asField();
/** SPacketExplosion */
FastField<Float> SPacketExplosion_motionX =
FastTypeBuilder.create()
.setInsideClass(SPacketExplosion.class)
.setName("motionX")
.autoAssign()
.asField();
FastField<Float> SPacketExplosion_motionY =
FastTypeBuilder.create()
.setInsideClass(SPacketExplosion.class)
.setName("motionY")
.autoAssign()
.asField();
FastField<Float> SPacketExplosion_motionZ =
FastTypeBuilder.create()
.setInsideClass(SPacketExplosion.class)
.setName("motionZ")
.autoAssign()
.asField();
/** BufferBuilder */
FastField<Boolean> BufferBuilder_isDrawing =
FastTypeBuilder.create()
.setInsideClass(BufferBuilder.class)
.setName("isDrawing")
.autoAssign()
.asField();
/** Session */
FastField<String> Session_username =
FastTypeBuilder.create()
.setInsideClass(Session.class)
.setName("username")
.autoAssign()
.asField();
/** TextureManager */
FastField<Map<ResourceLocation, ITextureObject>> TextureManager_mapTextureObjects =
FastTypeBuilder.create()
.setInsideClass(TextureManager.class)
.setName("mapTextureObjects")
.autoAssign()
.asField();
/** EntityRenderer */
FastField<ItemStack> EntityRenderer_itemActivationItem =
FastTypeBuilder.create()
.setInsideClass(EntityRenderer.class)
.setName("itemActivationItem")
.autoAssign()
.asField();
/** AbstractHorse */
FastField<IAttribute> AbstractHorse_JUMP_STRENGTH =
FastTypeBuilder.create()
.setInsideClass(AbstractHorse.class)
.setName("JUMP_STRENGTH")
.autoAssign()
.asField();
/** SharedMonsterAttributes */
FastField<IAttribute> SharedMonsterAttributes_MOVEMENT_SPEED =
FastTypeBuilder.create()
.setInsideClass(SharedMonsterAttributes.class)
.setName("MOVEMENT_SPEED")
.autoAssign()
.asField();
/** GuiEditSign */
FastField<TileEntitySign> GuiEditSign_tileSign =
FastTypeBuilder.create()
.setInsideClass(GuiEditSign.class)
.setName("tileSign")
.autoAssign()
.asField();
/** NBTTagCompound */
FastField<Map<String, NBTBase>> NBTTag_tagMap =
FastTypeBuilder.create()
.setInsideClass(NBTTagCompound.class)
.setName("tagMap")
.autoAssign()
.asField();
/** Timer */
FastField<Float> Timer_tickLength =
FastTypeBuilder.create()
.setInsideClass(Timer.class)
.setName("tickLength")
.autoAssign()
.asField();
/** KeyBinding */
FastField<Integer> Binding_pressTime =
FastTypeBuilder.create()
.setInsideClass(KeyBinding.class)
.setName("pressTime")
.autoAssign()
.asField();
FastField<Boolean> Binding_pressed =
FastTypeBuilder.create()
.setInsideClass(KeyBinding.class)
.setName("pressed")
.autoAssign()
.asField();
/** ItemSword */
FastField<Float> ItemSword_attackDamage =
FastTypeBuilder.create()
.setInsideClass(ItemSword.class)
.setName("attackDamage")
.autoAssign()
.asField();
/** ItemTool */
FastField<Float> ItemTool_damageVsEntity =
FastTypeBuilder.create()
.setInsideClass(ItemTool.class)
.setName("damageVsEntity")
.autoAssign()
.asField();
FastField<Float> ItemTool_attackSpeed =
FastTypeBuilder.create()
.setInsideClass(ItemTool.class)
.setName("attackSpeed")
.autoAssign()
.asField();
/** ItemFood */
FastField<PotionEffect> ItemFood_potionId =
FastTypeBuilder.create()
.setInsideClass(ItemFood.class)
.setName("potionId")
.autoAssign()
.asField();
/** Chunk */
FastField<ExtendedBlockStorage[]> Chunk_storageArrays =
FastTypeBuilder.create()
.setInsideClass(Chunk.class)
.setName("storageArrays")
.autoAssign()
.asField();
}
// ****************************************
// METHODS
// ****************************************
interface Methods {
/** Block */
FastMethod<Boolean> Block_onBlockActivated =
FastTypeBuilder.create()
.setInsideClass(Block.class)
.setName("onBlockActivated")
.setParameters(
World.class,
BlockPos.class,
IBlockState.class,
EntityPlayer.class,
EnumHand.class,
EnumFacing.class,
float.class,
float.class,
float.class)
.setReturnType(boolean.class)
.autoAssign()
.asMethod();
/** Entity */
FastMethod<Boolean> Entity_getFlag =
FastTypeBuilder.create()
.setInsideClass(Entity.class)
.setName("getFlag")
.setParameters(int.class)
.setReturnType(boolean.class)
.autoAssign()
.asMethod();
FastMethod<Void> Entity_setFlag =
FastTypeBuilder.create()
.setInsideClass(Entity.class)
.setName("setFlag")
.setParameters(int.class, boolean.class)
.setReturnType(void.class)
.autoAssign()
.asMethod();
/** EntityLivingBase */
FastMethod<Void> EntityLivingBase_resetPotionEffectMetadata =
FastTypeBuilder.create()
.setInsideClass(EntityLivingBase.class)
.setName("resetPotionEffectMetadata")
.setParameters()
.setReturnType(void.class)
.autoAssign()
.asMethod();
/** Minecraft */
FastMethod<Void> Minecraft_clickMouse =
FastTypeBuilder.create()
.setInsideClass(Minecraft.class)
.setName("clickMouse")
.setParameters()
.setReturnType(void.class)
.autoAssign()
.asMethod();
FastMethod<Void> Minecraft_rightClickMouse =
FastTypeBuilder.create()
.setInsideClass(Minecraft.class)
.setName("rightClickMouse")
.setParameters()
.setReturnType(void.class)
.autoAssign()
.asMethod();
/** KeyBinding */
FastMethod<Void> KeyBinding_unPress =
FastTypeBuilder.create()
.setInsideClass(KeyBinding.class)
.setName("unpressKey")
.setParameters()
.setReturnType(void.class)
.autoAssign()
.asMethod();
/** IChunkLoader */
FastMethod<AnvilChunkLoader> AnvilChunkLoader_writeChunkToNBT =
FastTypeBuilder.create()
.setInsideClass(AnvilChunkLoader.class)
.setName("writeChunkToNBT")
.setParameters(Chunk.class, World.class, NBTTagCompound.class)
.setReturnType(void.class)
.autoAssign()
.asMethod();
}
}
|
src/main/java/com/matt/forgehax/asm/reflection/FastReflection.java
|
package com.matt.forgehax.asm.reflection;
import com.matt.forgehax.asm.ASMCommon;
import com.matt.forgehax.asm.utils.fasttype.FastField;
import com.matt.forgehax.asm.utils.fasttype.FastMethod;
import com.matt.forgehax.asm.utils.fasttype.FastTypeBuilder;
import java.nio.FloatBuffer;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.GuiDisconnected;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiEditSign;
import net.minecraft.client.multiplayer.GuiConnecting;
import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.client.renderer.ActiveRenderInfo;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.IAttribute;
import net.minecraft.entity.monster.EntityPigZombie;
import net.minecraft.entity.passive.AbstractHorse;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.item.ItemTool;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.network.play.client.CPacketCloseWindow;
import net.minecraft.network.play.client.CPacketEntityAction;
import net.minecraft.network.play.client.CPacketPlayer;
import net.minecraft.network.play.client.CPacketVehicleMove;
import net.minecraft.network.play.server.SPacketEntityVelocity;
import net.minecraft.network.play.server.SPacketExplosion;
import net.minecraft.network.play.server.SPacketPlayerPosLook;
import net.minecraft.potion.PotionEffect;
import net.minecraft.tileentity.TileEntitySign;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Session;
import net.minecraft.util.Timer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.AnvilChunkLoader;
/** Created on 5/8/2017 by fr1kin */
public interface FastReflection extends ASMCommon {
// ****************************************
// FIELDS
// ****************************************
interface Fields {
/** ActiveRenderInfo */
FastField<FloatBuffer> ActiveRenderInfo_MODELVIEW =
FastTypeBuilder.create()
.setInsideClass(ActiveRenderInfo.class)
.setName("MODELVIEW")
.autoAssign()
.asField();
FastField<FloatBuffer> ActiveRenderInfo_PROJECTION =
FastTypeBuilder.create()
.setInsideClass(ActiveRenderInfo.class)
.setName("PROJECTION")
.autoAssign()
.asField();
FastField<Vec3d> ActiveRenderInfo_position =
FastTypeBuilder.create()
.setInsideClass(ActiveRenderInfo.class)
.setName("position")
.autoAssign()
.asField();
/** CPacketPlayer */
FastField<Float> CPacketPlayer_pitch =
FastTypeBuilder.create()
.setInsideClass(CPacketPlayer.class)
.setName("pitch")
.autoAssign()
.asField();
FastField<Float> CPacketPlayer_yaw =
FastTypeBuilder.create()
.setInsideClass(CPacketPlayer.class)
.setName("yaw")
.autoAssign()
.asField();
FastField<Boolean> CPacketPlayer_rotating =
FastTypeBuilder.create()
.setInsideClass(CPacketPlayer.class)
.setName("rotating")
.autoAssign()
.asField();
FastField<Boolean> CPacketPlayer_onGround =
FastTypeBuilder.create()
.setInsideClass(CPacketPlayer.class)
.setName("onGround")
.autoAssign()
.asField();
FastField<Double> CPacketPlayer_Y =
FastTypeBuilder.create()
.setInsideClass(CPacketPlayer.class)
.setName("y")
.autoAssign()
.asField();
/** CPacketVehicleMove */
FastField<Float> CPacketVehicleMove_yaw =
FastTypeBuilder.create()
.setInsideClass(CPacketVehicleMove.class)
.setName("yaw")
.autoAssign()
.asField();
/** CPacketCloseWindow */
FastField<Integer> CPacketCloseWindow_windowId =
FastTypeBuilder.create()
.setInsideClass(CPacketCloseWindow.class)
.setName("windowId")
.autoAssign()
.asField();
/** CPacketEntityAction */
FastField<Integer> CPacketEntityAction_entityID =
FastTypeBuilder.create()
.setInsideClass(CPacketEntityAction.class)
.setName("entityID")
.autoAssign()
.asField();
/** SPacketPlayerPosLook */
FastField<Float> SPacketPlayer_pitch =
FastTypeBuilder.create()
.setInsideClass(SPacketPlayerPosLook.class)
.setName("pitch")
.autoAssign()
.asField();
FastField<Float> SPacketPlayer_yaw =
FastTypeBuilder.create()
.setInsideClass(SPacketPlayerPosLook.class)
.setName("yaw")
.autoAssign()
.asField();
/** Entity */
FastField<EntityDataManager> Entity_dataManager =
FastTypeBuilder.create()
.setInsideClass(Entity.class)
.setName("dataManager")
.autoAssign()
.asField();
FastField<Boolean> Entity_inPortal =
FastTypeBuilder.create()
.setInsideClass(Entity.class)
.setName("inPortal")
.autoAssign()
.asField();
/** EntityPigZombie */
FastField<Integer> EntityPigZombie_angerLevel =
FastTypeBuilder.create()
.setInsideClass(EntityPigZombie.class)
.setName("angerLevel")
.autoAssign()
.asField();
/** EntityPlayer */
FastField<Boolean> EntityPlayer_sleeping =
FastTypeBuilder.create()
.setInsideClass(EntityPlayer.class)
.setName("sleeping")
.autoAssign()
.asField();
FastField<Integer> EntityPlayer_sleepTimer =
FastTypeBuilder.create()
.setInsideClass(EntityPlayer.class)
.setName("sleepTimer")
.autoAssign()
.asField();
/** EntityPlayerSP */
FastField<Float> EntityPlayerSP_horseJumpPower =
FastTypeBuilder.create()
.setInsideClass(EntityPlayerSP.class)
.setName("horseJumpPower")
.autoAssign()
.asField();
/** GuiConnecting */
FastField<NetworkManager> GuiConnecting_networkManager =
FastTypeBuilder.create()
.setInsideClass(GuiConnecting.class)
.setName("networkManager")
.autoAssign()
.asField();
/** GuiDisconnected */
FastField<GuiScreen> GuiDisconnected_parentScreen =
FastTypeBuilder.create()
.setInsideClass(GuiDisconnected.class)
.setName("parentScreen")
.autoAssign()
.asField();
FastField<ITextComponent> GuiDisconnected_message =
FastTypeBuilder.create()
.setInsideClass(GuiDisconnected.class)
.setName("message")
.autoAssign()
.asField();
FastField<String> GuiDisconnected_reason =
FastTypeBuilder.create()
.setInsideClass(GuiDisconnected.class)
.setName("reason")
.autoAssign()
.asField();
/** Minecraft */
FastField<Integer> Minecraft_leftClickCounter =
FastTypeBuilder.create()
.setInsideClass(Minecraft.class)
.setName("leftClickCounter")
.autoAssign()
.asField();
FastField<Integer> Minecraft_rightClickDelayTimer =
FastTypeBuilder.create()
.setInsideClass(Minecraft.class)
.setName("rightClickDelayTimer")
.autoAssign()
.asField();
FastField<Timer> Minecraft_timer =
FastTypeBuilder.create()
.setInsideClass(Minecraft.class)
.setName("timer")
.autoAssign()
.asField();
/** PlayerControllerMP */
FastField<Integer> PlayerControllerMP_blockHitDelay =
FastTypeBuilder.create()
.setInsideClass(PlayerControllerMP.class)
.setName("blockHitDelay")
.autoAssign()
.asField();
FastField<Float> PlayerControllerMP_curBlockDamageMP =
FastTypeBuilder.create()
.setInsideClass(PlayerControllerMP.class)
.setName("curBlockDamageMP")
.autoAssign()
.asField();
FastField<Integer> PlayerControllerMP_currentPlayerItem =
FastTypeBuilder.create()
.setInsideClass(PlayerControllerMP.class)
.setName("currentPlayerItem")
.autoAssign()
.asField();
/** SPacketEntityVelocity */
FastField<Integer> SPacketEntityVelocity_motionX =
FastTypeBuilder.create()
.setInsideClass(SPacketEntityVelocity.class)
.setName("motionX")
.autoAssign()
.asField();
FastField<Integer> SPacketEntityVelocity_motionY =
FastTypeBuilder.create()
.setInsideClass(SPacketEntityVelocity.class)
.setName("motionY")
.autoAssign()
.asField();
FastField<Integer> SPacketEntityVelocity_motionZ =
FastTypeBuilder.create()
.setInsideClass(SPacketEntityVelocity.class)
.setName("motionZ")
.autoAssign()
.asField();
/** SPacketExplosion */
FastField<Float> SPacketExplosion_motionX =
FastTypeBuilder.create()
.setInsideClass(SPacketExplosion.class)
.setName("motionX")
.autoAssign()
.asField();
FastField<Float> SPacketExplosion_motionY =
FastTypeBuilder.create()
.setInsideClass(SPacketExplosion.class)
.setName("motionY")
.autoAssign()
.asField();
FastField<Float> SPacketExplosion_motionZ =
FastTypeBuilder.create()
.setInsideClass(SPacketExplosion.class)
.setName("motionZ")
.autoAssign()
.asField();
/** BufferBuilder */
FastField<Boolean> BufferBuilder_isDrawing =
FastTypeBuilder.create()
.setInsideClass(BufferBuilder.class)
.setName("isDrawing")
.autoAssign()
.asField();
/** Session */
FastField<String> Session_username =
FastTypeBuilder.create()
.setInsideClass(Session.class)
.setName("username")
.autoAssign()
.asField();
/** TextureManager */
FastField<Map<ResourceLocation, ITextureObject>> TextureManager_mapTextureObjects =
FastTypeBuilder.create()
.setInsideClass(TextureManager.class)
.setName("mapTextureObjects")
.autoAssign()
.asField();
/** EntityRenderer */
FastField<ItemStack> EntityRenderer_itemActivationItem =
FastTypeBuilder.create()
.setInsideClass(EntityRenderer.class)
.setName("itemActivationItem")
.autoAssign()
.asField();
/** AbstractHorse */
FastField<IAttribute> AbstractHorse_JUMP_STRENGTH =
FastTypeBuilder.create()
.setInsideClass(AbstractHorse.class)
.setName("JUMP_STRENGTH")
.autoAssign()
.asField();
/** SharedMonsterAttributes */
FastField<IAttribute> SharedMonsterAttributes_MOVEMENT_SPEED =
FastTypeBuilder.create()
.setInsideClass(SharedMonsterAttributes.class)
.setName("MOVEMENT_SPEED")
.autoAssign()
.asField();
/** GuiEditSign */
FastField<TileEntitySign> GuiEditSign_tileSign =
FastTypeBuilder.create()
.setInsideClass(GuiEditSign.class)
.setName("tileSign")
.autoAssign()
.asField();
/** NBTTagCompound */
FastField<Map<String, NBTBase>> NBTTag_tagMap =
FastTypeBuilder.create()
.setInsideClass(NBTTagCompound.class)
.setName("tagMap")
.autoAssign()
.asField();
/** Timer */
FastField<Float> Timer_tickLength =
FastTypeBuilder.create()
.setInsideClass(Timer.class)
.setName("tickLength")
.autoAssign()
.asField();
/** KeyBinding */
FastField<Integer> Binding_pressTime =
FastTypeBuilder.create()
.setInsideClass(KeyBinding.class)
.setName("pressTime")
.autoAssign()
.asField();
FastField<Boolean> Binding_pressed =
FastTypeBuilder.create()
.setInsideClass(KeyBinding.class)
.setName("pressed")
.autoAssign()
.asField();
/** ItemSword */
FastField<Float> ItemSword_attackDamage =
FastTypeBuilder.create()
.setInsideClass(ItemSword.class)
.setName("attackDamage")
.autoAssign()
.asField();
/** ItemTool */
FastField<Float> ItemTool_damageVsEntity =
FastTypeBuilder.create()
.setInsideClass(ItemTool.class)
.setName("damageVsEntity")
.autoAssign()
.asField();
FastField<Float> ItemTool_attackSpeed =
FastTypeBuilder.create()
.setInsideClass(ItemTool.class)
.setName("attackSpeed")
.autoAssign()
.asField();
/** ItemFood */
FastField<PotionEffect> ItemFood_potionId =
FastTypeBuilder.create()
.setInsideClass(ItemFood.class)
.setName("potionId")
.autoAssign()
.asField();
}
// ****************************************
// METHODS
// ****************************************
interface Methods {
/** Block */
FastMethod<Boolean> Block_onBlockActivated =
FastTypeBuilder.create()
.setInsideClass(Block.class)
.setName("onBlockActivated")
.setParameters(
World.class,
BlockPos.class,
IBlockState.class,
EntityPlayer.class,
EnumHand.class,
EnumFacing.class,
float.class,
float.class,
float.class)
.setReturnType(boolean.class)
.autoAssign()
.asMethod();
/** Entity */
FastMethod<Boolean> Entity_getFlag =
FastTypeBuilder.create()
.setInsideClass(Entity.class)
.setName("getFlag")
.setParameters(int.class)
.setReturnType(boolean.class)
.autoAssign()
.asMethod();
FastMethod<Void> Entity_setFlag =
FastTypeBuilder.create()
.setInsideClass(Entity.class)
.setName("setFlag")
.setParameters(int.class, boolean.class)
.setReturnType(void.class)
.autoAssign()
.asMethod();
/** EntityLivingBase */
FastMethod<Void> EntityLivingBase_resetPotionEffectMetadata =
FastTypeBuilder.create()
.setInsideClass(EntityLivingBase.class)
.setName("resetPotionEffectMetadata")
.setParameters()
.setReturnType(void.class)
.autoAssign()
.asMethod();
/** Minecraft */
FastMethod<Void> Minecraft_clickMouse =
FastTypeBuilder.create()
.setInsideClass(Minecraft.class)
.setName("clickMouse")
.setParameters()
.setReturnType(void.class)
.autoAssign()
.asMethod();
FastMethod<Void> Minecraft_rightClickMouse =
FastTypeBuilder.create()
.setInsideClass(Minecraft.class)
.setName("rightClickMouse")
.setParameters()
.setReturnType(void.class)
.autoAssign()
.asMethod();
/** KeyBinding */
FastMethod<Void> KeyBinding_unPress =
FastTypeBuilder.create()
.setInsideClass(KeyBinding.class)
.setName("unpressKey")
.setParameters()
.setReturnType(void.class)
.autoAssign()
.asMethod();
/** IChunkLoader */
FastMethod<AnvilChunkLoader> AnvilChunkLoader_writeChunkToNBT =
FastTypeBuilder.create()
.setInsideClass(AnvilChunkLoader.class)
.setName("writeChunkToNBT")
.setParameters(Chunk.class, World.class, NBTTagCompound.class)
.setReturnType(void.class)
.autoAssign()
.asMethod();
}
}
|
I forgot what I changed but I want to stop stashing this change everytime I pull
|
src/main/java/com/matt/forgehax/asm/reflection/FastReflection.java
|
I forgot what I changed but I want to stop stashing this change everytime I pull
|
<ide><path>rc/main/java/com/matt/forgehax/asm/reflection/FastReflection.java
<ide> import net.minecraft.world.World;
<ide> import net.minecraft.world.chunk.Chunk;
<ide> import net.minecraft.world.chunk.storage.AnvilChunkLoader;
<add>import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
<ide>
<ide> /** Created on 5/8/2017 by fr1kin */
<ide> public interface FastReflection extends ASMCommon {
<ide> FastTypeBuilder.create()
<ide> .setInsideClass(ItemFood.class)
<ide> .setName("potionId")
<add> .autoAssign()
<add> .asField();
<add>
<add> /** Chunk */
<add> FastField<ExtendedBlockStorage[]> Chunk_storageArrays =
<add> FastTypeBuilder.create()
<add> .setInsideClass(Chunk.class)
<add> .setName("storageArrays")
<ide> .autoAssign()
<ide> .asField();
<ide> }
|
|
Java
|
apache-2.0
|
7f12a64ad2f9463809dc8a8a27f67c67f1c5f164
| 0 |
Matthias247/jawampa,MaTriXy/jawampa,GoodgameStudios/jawampa,pplatek/jawampa,ichrome/jawampa,mbonneau/jawampa,jrogers/jawampa,Matthias247/jawampa,alex-vas/jawampa,alex-vas/jawampa
|
/*
* Copyright 2014 Matthias Einwag
*
* The jawampa authors license 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 ws.wamp.jawampa;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadFactory;
import rx.Scheduler;
import rx.schedulers.Schedulers;
import ws.wamp.jawampa.WampMessages.*;
import ws.wamp.jawampa.internal.IdGenerator;
import ws.wamp.jawampa.internal.IdValidator;
import ws.wamp.jawampa.internal.RealmConfig;
import ws.wamp.jawampa.internal.UriValidator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* The {@link WampRouter} provides Dealer and Broker functionality for the WAMP
* protocol.<br>
*/
public class WampRouter {
final static Set<WampRoles> SUPPORTED_CLIENT_ROLES;
static {
SUPPORTED_CLIENT_ROLES = new HashSet<WampRoles>();
SUPPORTED_CLIENT_ROLES.add(WampRoles.Caller);
SUPPORTED_CLIENT_ROLES.add(WampRoles.Callee);
SUPPORTED_CLIENT_ROLES.add(WampRoles.Publisher);
SUPPORTED_CLIENT_ROLES.add(WampRoles.Subscriber);
}
/** Represents a realm that is exposed through the router */
static class Realm {
final RealmConfig config;
final List<WampRouterHandler> channels = new ArrayList<WampRouterHandler>();
final Map<String, Procedure> procedures = new HashMap<String, Procedure>();
final Map<String, Set<Subscription>> subscriptions = new HashMap<String, Set<Subscription>>();
public Realm(RealmConfig config) {
this.config = config;
}
void includeChannel(WampRouterHandler channel, long sessionId, Set<WampRoles> roles) {
channels.add(channel);
channel.realm = this;
channel.sessionId = sessionId;
channel.roles = roles;
}
void removeChannel(WampRouterHandler channel, boolean removeFromList) {
if (channel.realm == null) return;
if (channel.subscriptions != null) {
// Remove the channels subscriptions from our subscription table
for (Subscription sub : channel.subscriptions.values()) {
Set<Subscription> subscriptionSet = subscriptions.get(sub.topic);
subscriptionSet.remove(sub);
if (subscriptionSet.isEmpty()) {
subscriptions.remove(sub.topic);
}
}
channel.subscriptions.clear();
channel.subscriptions = null;
}
if (channel.providedProcedures != null) {
// Remove the clients procedures from our procedure table
for (Procedure proc : channel.providedProcedures.values()) {
// Clear all pending invocations and thereby inform other clients
// that the proc has gone away
for (Invocation invoc : proc.pendingCalls) {
if (invoc.caller.state != RouterHandlerState.Open) continue;
ErrorMessage errMsg = new ErrorMessage(CallMessage.ID, invoc.callRequestId,
null, ApplicationError.NO_SUCH_PROCEDURE, null, null);
invoc.caller.ctx.writeAndFlush(errMsg);
}
proc.pendingCalls.clear();
// Remove the procedure from the realm
procedures.remove(proc.procName);
}
channel.providedProcedures = null;
channel.pendingInvocations = null;
}
channel.realm = null;
channel.roles.clear();
channel.roles = null;
channel.sessionId = 0;
if (removeFromList) {
channels.remove(channel);
}
}
}
static class Procedure {
final String procName;
final WampRouterHandler provider;
final long registrationId;
final List<Invocation> pendingCalls = new ArrayList<WampRouter.Invocation>();
public Procedure(String name, WampRouterHandler provider, long registrationId) {
this.procName = name;
this.provider = provider;
this.registrationId = registrationId;
}
}
static class Invocation {
Procedure procedure;
long callRequestId;
WampRouterHandler caller;
long invocationRequestId;
}
static class Subscription {
final String topic;
final long subscriptionId;
final WampRouterHandler subscriber;
public Subscription(String topic, long subscriptionId, WampRouterHandler subscriber) {
this.topic = topic;
this.subscriptionId = subscriptionId;
this.subscriber = subscriber;
}
}
final EventLoopGroup eventLoop;
final Scheduler scheduler;
final ObjectMapper objectMapper = new ObjectMapper();
boolean isDisposed = false;
final Map<String, Realm> realms;
final ChannelGroup idleChannels;
/**
* Returns the (singlethreaded) EventLoop on which this router is running.<br>
* This is required by other Netty ChannelHandlers that want to forward messages
* to the router.
*/
public EventLoopGroup eventLoop() {
return eventLoop;
}
/**
* Returns the Jackson {@link ObjectMapper} that is used for JSON serialization,
* deserialization and object mapping by this router.
*/
public ObjectMapper objectMapper() {
return objectMapper;
}
WampRouter(Map<String, RealmConfig> realms) {
// Populate the realms from the configuration
this.realms = new HashMap<String, Realm>();
for (Map.Entry<String, RealmConfig> e : realms.entrySet()) {
Realm info = new Realm(e.getValue());
this.realms.put(e.getKey(), info);
}
// Create an eventloop and the RX scheduler on top of it
this.eventLoop = new NioEventLoopGroup(1, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "WampRouterEventLoop");
t.setDaemon(true);
return t;
}
});
this.scheduler = Schedulers.from(eventLoop);
idleChannels = new DefaultChannelGroup(eventLoop.next());
}
/**
* Closes the router.<br>
* This will shut down all realm that are registered to the router.
* All connections to clients on the realm will be closed.<br>
* However pending calls will be completed through an error message
* as far as possible.
*/
public void close() {
if (eventLoop.isShuttingDown() || eventLoop.isShutdown()) return;
eventLoop.execute(new Runnable() {
@Override
public void run() {
if (isDisposed) return;
isDisposed = true;
// Close all currently connected channels
idleChannels.close();
idleChannels.clear();
for (Realm ri : realms.values()) {
for (WampRouterHandler channel : ri.channels) {
ri.removeChannel(channel, false);
channel.markAsClosed();
GoodbyeMessage goodbye = new GoodbyeMessage(null, ApplicationError.SYSTEM_SHUTDOWN);
channel.ctx.writeAndFlush(goodbye).addListener(ChannelFutureListener.CLOSE);
}
ri.channels.clear();
}
eventLoop.shutdownGracefully();
}
});
}
public ChannelHandler createRouterHandler() {
return new WampRouterHandler();
}
enum RouterHandlerState {
Open,
Closed
}
class WampRouterHandler extends SimpleChannelInboundHandler<WampMessage> {
public RouterHandlerState state = RouterHandlerState.Open;
ChannelHandlerContext ctx;
long sessionId;
Realm realm;
Set<WampRoles> roles;
/**
* Procedures that this channel provides.<br>
* Key is the registration ID, Value is the procedure
*/
Map<Long, Procedure> providedProcedures;
Map<Long, Invocation> pendingInvocations;
Map<Long, Subscription> subscriptions;
long lastUsedId = IdValidator.MIN_VALID_ID;
void markAsClosed() {
state = RouterHandlerState.Closed;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
// System.out.println("Router handler added on thread " + Thread.currentThread().getId());
this.ctx = ctx;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// System.out.println("Router handler active on thread " + Thread.currentThread().getId());
if (state != RouterHandlerState.Open) return;
if (isDisposed) {
// Got an incoming connection after the router has already shut down.
// Therefore we close the connection
state = RouterHandlerState.Closed;
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
} else {
idleChannels.add(ctx.channel());
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// System.out.println("Router handler inactive on thread " + Thread.currentThread().getId());
if (isDisposed || state != RouterHandlerState.Open) return;
markAsClosed();
if (realm != null) {
realm.removeChannel(this, true);
} else {
idleChannels.remove(ctx.channel());
}
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, WampMessage msg) throws Exception {
//System.out.println("Router channel read on thread " + Thread.currentThread().getId());
if (isDisposed || state != RouterHandlerState.Open) return;
if (realm == null) {
onMessageFromUnregisteredChannel(this, msg);
} else {
onMessageFromRegisteredChannel(this, msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (isDisposed || state != RouterHandlerState.Open) return;
if (realm != null) {
closeActiveChannel(this, null);
} else {
closePassiveChannel(this);
}
}
}
private void onMessageFromRegisteredChannel(WampRouterHandler handler, WampMessage msg) {
// TODO: Validate roles for all relevant messages
if (msg instanceof HelloMessage || msg instanceof WelcomeMessage) {
// The client sent hello but it was already registered -> This is an error
// If the client sends welcome it's also an error
closeActiveChannel(handler, new GoodbyeMessage(null, ApplicationError.INVALID_ARGUMENT));
} else if (msg instanceof AbortMessage || msg instanceof GoodbyeMessage) {
// The client wants to leave the realm
// Remove the channel from the realm
handler.realm.removeChannel(handler, true);
// But add it to the list of passive channels
idleChannels.add(handler.ctx.channel());
// Echo the message in case of goodbye
if (msg instanceof GoodbyeMessage) {
GoodbyeMessage reply = new GoodbyeMessage(null, ApplicationError.GOODBYE_AND_OUT);
handler.ctx.writeAndFlush(reply);
}
} else if (msg instanceof CallMessage) {
// The client wants to call a remote function
// Verify the message
CallMessage call = (CallMessage) msg;
String err = null;
if (!UriValidator.tryValidate(call.procedure)) {
// Client sent an invalid URI
err = ApplicationError.INVALID_URI;
}
if (err == null && !(IdValidator.isValidId(call.requestId))) {
// Client sent an invalid request ID
err = ApplicationError.INVALID_ARGUMENT;
}
Procedure proc = null;
if (err == null) {
proc = handler.realm.procedures.get(call.procedure);
if (proc == null) err = ApplicationError.NO_SUCH_PROCEDURE;
}
if (err != null) { // If we have an error send that to the client
ErrorMessage errMsg = new ErrorMessage(CallMessage.ID, call.requestId,
null, err, null, null);
handler.ctx.writeAndFlush(errMsg);
return;
}
// Everything checked, we can forward the call to the provider
Invocation invoc = new Invocation();
invoc.callRequestId = call.requestId;
invoc.caller = handler;
invoc.procedure = proc;
invoc.invocationRequestId = IdGenerator.newLinearId(proc.provider.lastUsedId,
proc.provider.pendingInvocations);
proc.provider.lastUsedId = invoc.invocationRequestId;
// Store the invocation
proc.provider.pendingInvocations.put(invoc.invocationRequestId, invoc);
// Store the call in the procedure to return error if client unregisters
proc.pendingCalls.add(invoc);
// And send it to the provider
InvocationMessage imsg = new InvocationMessage(invoc.invocationRequestId,
proc.registrationId, null, call.arguments, call.argumentsKw);
proc.provider.ctx.writeAndFlush(imsg);
} else if (msg instanceof YieldMessage) {
// The clients sends as the result of an RPC
// Verify the message
YieldMessage yield = (YieldMessage) msg;
if (!(IdValidator.isValidId(yield.requestId))) return;
// Look up the invocation to find the original caller
if (handler.pendingInvocations == null) return; // If a client send a yield without an invocation, return
Invocation invoc = handler.pendingInvocations.get(yield.requestId);
if (invoc == null) return; // There is no invocation pending under this ID
handler.pendingInvocations.remove(yield.requestId);
invoc.procedure.pendingCalls.remove(invoc);
// Send the result to the original caller
ResultMessage result = new ResultMessage(invoc.callRequestId, null, yield.arguments, yield.argumentsKw);
invoc.caller.ctx.writeAndFlush(result);
} else if (msg instanceof ErrorMessage) {
ErrorMessage err = (ErrorMessage) msg;
if (!(IdValidator.isValidId(err.requestId))) {
return;
}
if (err.requestType == InvocationMessage.ID) {
if (!UriValidator.tryValidate(err.error)) {
// The Message provider has sent us an invalid URI for the error string
// We better don't forward it but instead close the connection, which will
// give the original caller an unknown message error
closeActiveChannel(handler, new GoodbyeMessage(null, ApplicationError.INVALID_ARGUMENT));
return;
}
// Look up the invocation to find the original caller
if (handler.pendingInvocations == null) return; // if an error is send before an invocation, do not do anything
Invocation invoc = handler.pendingInvocations.get(err.requestId);
if (invoc == null) return; // There is no invocation pending under this ID
handler.pendingInvocations.remove(err.requestId);
invoc.procedure.pendingCalls.remove(invoc);
// Send the result to the original caller
ErrorMessage fwdError = new ErrorMessage(CallMessage.ID, invoc.callRequestId,
null, err.error, err.arguments, err.argumentsKw);
invoc.caller.ctx.writeAndFlush(fwdError);
}
// else TODO: Are there any other possibilities where a client could return ERROR
} else if (msg instanceof RegisterMessage) {
// The client wants to register a procedure
// Verify the message
RegisterMessage reg = (RegisterMessage) msg;
String err = null;
if (!UriValidator.tryValidate(reg.procedure)) {
// Client sent an invalid URI
err = ApplicationError.INVALID_URI;
}
if (err == null && !(IdValidator.isValidId(reg.requestId))) {
// Client sent an invalid request ID
err = ApplicationError.INVALID_ARGUMENT;
}
Procedure proc = null;
if (err == null) {
proc = handler.realm.procedures.get(reg.procedure);
if (proc != null) err = ApplicationError.PROCEDURE_ALREADY_EXISTS;
}
if (err != null) { // If we have an error send that to the client
ErrorMessage errMsg = new ErrorMessage(RegisterMessage.ID, reg.requestId,
null, err, null, null);
handler.ctx.writeAndFlush(errMsg);
return;
}
// Everything checked, we can register the caller as the procedure provider
long registrationId = IdGenerator.newLinearId(handler.lastUsedId, handler.providedProcedures);
handler.lastUsedId = registrationId;
Procedure procInfo = new Procedure(reg.procedure, handler, registrationId);
// Insert new procedure
handler.realm.procedures.put(reg.procedure, procInfo);
if (handler.providedProcedures == null) {
handler.providedProcedures = new HashMap<Long, WampRouter.Procedure>();
handler.pendingInvocations = new HashMap<Long, WampRouter.Invocation>();
}
handler.providedProcedures.put(procInfo.registrationId, procInfo);
RegisteredMessage response = new RegisteredMessage(reg.requestId, procInfo.registrationId);
handler.ctx.writeAndFlush(response);
} else if (msg instanceof UnregisterMessage) {
// The client wants to unregister a procedure
// Verify the message
UnregisterMessage unreg = (UnregisterMessage) msg;
String err = null;
if (!(IdValidator.isValidId(unreg.requestId))
|| !(IdValidator.isValidId(unreg.registrationId))) {
// Client sent an invalid request or registration ID
err = ApplicationError.INVALID_ARGUMENT;
}
Procedure proc = null;
if (err == null) {
if (handler.providedProcedures != null) {
proc = handler.providedProcedures.get(unreg.registrationId);
}
// Check whether the procedure exists AND if the caller is the owner
// If the caller is not the owner it might be an attack, so we don't
// disclose that the procedure exists.
if (proc == null) {
err = ApplicationError.NO_SUCH_REGISTRATION;
}
}
if (err != null) { // If we have an error send that to the client
ErrorMessage errMsg = new ErrorMessage(UnregisterMessage.ID, unreg.requestId,
null, err, null, null);
handler.ctx.writeAndFlush(errMsg);
return;
}
// Mark pending calls to this procedure as failed
for (Invocation invoc : proc.pendingCalls) {
handler.pendingInvocations.remove(invoc.invocationRequestId);
if (invoc.caller.state == RouterHandlerState.Open) {
ErrorMessage errMsg = new ErrorMessage(CallMessage.ID, invoc.callRequestId,
null, ApplicationError.NO_SUCH_PROCEDURE, null, null);
invoc.caller.ctx.writeAndFlush(errMsg);
}
}
proc.pendingCalls.clear();
// Remove the procedure from the realm and the handler
handler.realm.procedures.remove(proc.procName);
handler.providedProcedures.remove(proc.registrationId);
if (handler.providedProcedures.size() == 0) {
handler.providedProcedures = null;
handler.pendingInvocations = null;
}
// Send the acknowledge
UnregisteredMessage response = new UnregisteredMessage(unreg.requestId);
handler.ctx.writeAndFlush(response);
} else if (msg instanceof SubscribeMessage) {
// The client wants to subscribe to a procedure
// Verify the message
SubscribeMessage sub = (SubscribeMessage) msg;
String err = null;
if (!UriValidator.tryValidate(sub.topic)) {
// Client sent an invalid URI
err = ApplicationError.INVALID_URI;
}
if (err == null && !(IdValidator.isValidId(sub.requestId))) {
// Client sent an invalid request ID
err = ApplicationError.INVALID_ARGUMENT;
}
if (err != null) { // If we have an error send that to the client
ErrorMessage errMsg = new ErrorMessage(SubscribeMessage.ID, sub.requestId,
null, err, null, null);
handler.ctx.writeAndFlush(errMsg);
return;
}
// Everything checked, we can add the caller as a subscriber
long subscriptionId = IdGenerator.newLinearId(handler.lastUsedId, handler.subscriptions);
handler.lastUsedId = subscriptionId;
Subscription s = new Subscription(sub.topic, subscriptionId, handler);
// Add the subscription on the realm
Set<Subscription> subscriptionSet = handler.realm.subscriptions.get(sub.topic);
if (subscriptionSet == null) {
// First subscriber - create a new set
subscriptionSet = new HashSet<Subscription>();
handler.realm.subscriptions.put(sub.topic, subscriptionSet);
}
subscriptionSet.add(s);
// Add the subscription on the client
if (handler.subscriptions == null) {
handler.subscriptions = new HashMap<Long, WampRouter.Subscription>();
}
handler.subscriptions.put(subscriptionId, s);
SubscribedMessage response = new SubscribedMessage(sub.requestId, subscriptionId);
handler.ctx.writeAndFlush(response);
} else if (msg instanceof UnsubscribeMessage) {
// The client wants to cancel a subscription
// Verify the message
UnsubscribeMessage unsub = (UnsubscribeMessage) msg;
String err = null;
if (!(IdValidator.isValidId(unsub.requestId))
|| !(IdValidator.isValidId(unsub.subscriptionId))) {
// Client sent an invalid request or registration ID
err = ApplicationError.INVALID_ARGUMENT;
}
Subscription s = null;
if (err == null) {
// Check whether such a subscription exists and fetch the topic name
if (handler.subscriptions != null) {
s = handler.subscriptions.get(unsub.subscriptionId);
}
if (s == null) {
err = ApplicationError.NO_SUCH_SUBSCRIPTION;
}
}
if (err != null) { // If we have an error send that to the client
ErrorMessage errMsg = new ErrorMessage(UnsubscribeMessage.ID, unsub.requestId,
null, err, null, null);
handler.ctx.writeAndFlush(errMsg);
return;
}
// Remove the subscription from the realm
Set<Subscription> subscriptionSet = handler.realm.subscriptions.get(s.topic);
subscriptionSet.remove(s);
if (subscriptionSet.isEmpty()) {
handler.realm.subscriptions.remove(s.topic);
}
// Remove the subscription from the handler
handler.subscriptions.remove(unsub.subscriptionId);
if (handler.subscriptions.isEmpty()) {
handler.subscriptions = null;
}
// Send the acknowledge
UnsubscribedMessage response = new UnsubscribedMessage(unsub.requestId);
handler.ctx.writeAndFlush(response);
} else if (msg instanceof PublishMessage) {
// The client wants to publish something to all subscribers (apart from himself)
PublishMessage pub = (PublishMessage) msg;
// Check whether the client wants an acknowledgement for the publication
// Default is no
boolean sendAcknowledge = false;
JsonNode ackOption = pub.options.get("acknowledge");
if (ackOption != null && ackOption.asBoolean() == true)
sendAcknowledge = true;
String err = null;
if (!UriValidator.tryValidate(pub.topic)) {
// Client sent an invalid URI
err = ApplicationError.INVALID_URI;
}
if (err == null && !(IdValidator.isValidId(pub.requestId))) {
// Client sent an invalid request ID
err = ApplicationError.INVALID_ARGUMENT;
}
if (err != null) { // If we have an error send that to the client
ErrorMessage errMsg = new ErrorMessage(PublishMessage.ID, pub.requestId,
null, err, null, null);
if (sendAcknowledge) {
handler.ctx.writeAndFlush(errMsg);
}
return;
}
long publicationId = IdGenerator.newRandomId(null); // Store that somewhere?
// Get the subscriptions for this topic on the realm
Set<Subscription> subscriptionSet = handler.realm.subscriptions.get(pub.topic);
if (subscriptionSet != null) {
for (Subscription subscriber : subscriptionSet) {
if (subscriber.subscriber == handler) continue; // Skip the publisher
// Publish the event to the subscriber
EventMessage ev = new EventMessage(subscriber.subscriptionId, publicationId,
null, pub.arguments, pub.argumentsKw);
subscriber.subscriber.ctx.writeAndFlush(ev);
}
}
if (sendAcknowledge) {
PublishedMessage response = new PublishedMessage(pub.requestId, publicationId);
handler.ctx.writeAndFlush(response);
}
}
}
private void onMessageFromUnregisteredChannel(WampRouterHandler channelHandler, WampMessage msg)
{
// Only HELLO is allowed when a channel is not registered
if (!(msg instanceof HelloMessage)) {
// Close the connection
closePassiveChannel(channelHandler);
return;
}
HelloMessage hello = (HelloMessage) msg;
String errorMsg = null;
Realm realm = null;
if (!UriValidator.tryValidate(hello.realm)) {
errorMsg = ApplicationError.INVALID_URI;
} else {
realm = realms.get(hello.realm);
if (realm == null) {
errorMsg = ApplicationError.NO_SUCH_REALM;
}
}
if (errorMsg != null) {
AbortMessage abort = new AbortMessage(null, errorMsg);
channelHandler.ctx.writeAndFlush(abort);
return;
}
Set<WampRoles> roles = new HashSet<WampRoles>();
boolean hasUnsupportedRoles = false;
JsonNode n = hello.details.get("roles");
if (n != null && n.isObject()) {
ObjectNode rolesNode = (ObjectNode) n;
Iterator<String> roleKeys = rolesNode.fieldNames();
while (roleKeys.hasNext()) {
WampRoles role = WampRoles.fromString(roleKeys.next());
if (!SUPPORTED_CLIENT_ROLES.contains(role)) hasUnsupportedRoles = true;
if (role != null) roles.add(role);
}
}
if (roles.size() == 0 || hasUnsupportedRoles) {
AbortMessage abort = new AbortMessage(null, ApplicationError.NO_SUCH_ROLE);
channelHandler.ctx.writeAndFlush(abort);
return;
}
long sessionId = IdGenerator.newRandomId(null);
// TODO: Should be unique on the router and should be stored somewhere
// Include the channel into the realm
realm.includeChannel(channelHandler, sessionId, roles);
// Remove the channel from the idle channel list - It is no longer idle
idleChannels.remove(channelHandler.ctx.channel());
// Expose the roles that are configured for the realm
ObjectNode welcomeDetails = objectMapper.createObjectNode();
ObjectNode routerRoles = welcomeDetails.putObject("roles");
for (WampRoles role : realm.config.roles) {
routerRoles.putObject(role.toString());
}
// Respond with the WELCOME message
WelcomeMessage welcome = new WelcomeMessage(channelHandler.sessionId, welcomeDetails);
channelHandler.ctx.writeAndFlush(welcome);
}
private void closeActiveChannel(WampRouterHandler channel, WampMessage closeMessage) {
if (channel == null) return;
channel.realm.removeChannel(channel, true);
channel.markAsClosed();
if (channel.ctx != null) {
Object m = (closeMessage == null) ? Unpooled.EMPTY_BUFFER : closeMessage;
channel.ctx.writeAndFlush(m)
.addListener(ChannelFutureListener.CLOSE);
}
}
private void closePassiveChannel(WampRouterHandler channelHandler) {
idleChannels.remove(channelHandler.ctx.channel());
channelHandler.markAsClosed();
channelHandler.ctx.close();
}
}
|
src/main/java/ws/wamp/jawampa/WampRouter.java
|
/*
* Copyright 2014 Matthias Einwag
*
* The jawampa authors license 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 ws.wamp.jawampa;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadFactory;
import rx.Scheduler;
import rx.schedulers.Schedulers;
import ws.wamp.jawampa.WampMessages.*;
import ws.wamp.jawampa.internal.IdGenerator;
import ws.wamp.jawampa.internal.IdValidator;
import ws.wamp.jawampa.internal.RealmConfig;
import ws.wamp.jawampa.internal.UriValidator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* The {@link WampRouter} provides Dealer and Broker functionality for the WAMP
* protocol.<br>
*/
public class WampRouter {
final static Set<WampRoles> SUPPORTED_CLIENT_ROLES;
static {
SUPPORTED_CLIENT_ROLES = new HashSet<WampRoles>();
SUPPORTED_CLIENT_ROLES.add(WampRoles.Caller);
SUPPORTED_CLIENT_ROLES.add(WampRoles.Callee);
SUPPORTED_CLIENT_ROLES.add(WampRoles.Publisher);
SUPPORTED_CLIENT_ROLES.add(WampRoles.Subscriber);
}
/** Represents a realm that is exposed through the router */
static class Realm {
final RealmConfig config;
final List<WampRouterHandler> channels = new ArrayList<WampRouterHandler>();
final Map<String, Procedure> procedures = new HashMap<String, Procedure>();
final Map<String, Set<Subscription>> subscriptions = new HashMap<String, Set<Subscription>>();
public Realm(RealmConfig config) {
this.config = config;
}
void includeChannel(WampRouterHandler channel, long sessionId, Set<WampRoles> roles) {
channels.add(channel);
channel.realm = this;
channel.sessionId = sessionId;
channel.roles = roles;
}
void removeChannel(WampRouterHandler channel, boolean removeFromList) {
if (channel.realm == null) return;
if (channel.subscriptions != null) {
// Remove the channels subscriptions from our subscription table
for (Subscription sub : channel.subscriptions.values()) {
Set<Subscription> subscriptionSet = subscriptions.get(sub.topic);
subscriptionSet.remove(sub);
if (subscriptionSet.isEmpty()) {
subscriptions.remove(sub.topic);
}
}
channel.subscriptions.clear();
channel.subscriptions = null;
}
if (channel.providedProcedures != null) {
// Remove the clients procedures from our procedure table
for (Procedure proc : channel.providedProcedures.values()) {
// Clear all pending invocations and thereby inform other clients
// that the proc has gone away
for (Invocation invoc : proc.pendingCalls) {
if (invoc.caller.state != RouterHandlerState.Open) continue;
ErrorMessage errMsg = new ErrorMessage(CallMessage.ID, invoc.callRequestId,
null, ApplicationError.NO_SUCH_PROCEDURE, null, null);
invoc.caller.ctx.writeAndFlush(errMsg);
}
proc.pendingCalls.clear();
// Remove the procedure from the realm
procedures.remove(proc.procName);
}
channel.providedProcedures = null;
channel.pendingInvocations = null;
}
channel.realm = null;
channel.roles.clear();
channel.roles = null;
channel.sessionId = 0;
if (removeFromList) {
channels.remove(channel);
}
}
}
static class Procedure {
final String procName;
final WampRouterHandler provider;
final long registrationId;
final List<Invocation> pendingCalls = new ArrayList<WampRouter.Invocation>();
public Procedure(String name, WampRouterHandler provider, long registrationId) {
this.procName = name;
this.provider = provider;
this.registrationId = registrationId;
}
}
static class Invocation {
Procedure procedure;
long callRequestId;
WampRouterHandler caller;
long invocationRequestId;
}
static class Subscription {
final String topic;
final long subscriptionId;
final WampRouterHandler subscriber;
public Subscription(String topic, long subscriptionId, WampRouterHandler subscriber) {
this.topic = topic;
this.subscriptionId = subscriptionId;
this.subscriber = subscriber;
}
}
final EventLoopGroup eventLoop;
final Scheduler scheduler;
final ObjectMapper objectMapper = new ObjectMapper();
boolean isDisposed = false;
final Map<String, Realm> realms;
final ChannelGroup idleChannels;
/**
* Returns the (singlethreaded) EventLoop on which this router is running.<br>
* This is required by other Netty ChannelHandlers that want to forward messages
* to the router.
*/
public EventLoopGroup eventLoop() {
return eventLoop;
}
/**
* Returns the Jackson {@link ObjectMapper} that is used for JSON serialization,
* deserialization and object mapping by this router.
*/
public ObjectMapper objectMapper() {
return objectMapper;
}
WampRouter(Map<String, RealmConfig> realms) {
// Populate the realms from the configuration
this.realms = new HashMap<String, Realm>();
for (Map.Entry<String, RealmConfig> e : realms.entrySet()) {
Realm info = new Realm(e.getValue());
this.realms.put(e.getKey(), info);
}
// Create an eventloop and the RX scheduler on top of it
this.eventLoop = new NioEventLoopGroup(1, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "WampRouterEventLoop");
t.setDaemon(true);
return t;
}
});
this.scheduler = Schedulers.from(eventLoop);
idleChannels = new DefaultChannelGroup(eventLoop.next());
}
/**
* Closes the router.<br>
* This will shut down all realm that are registered to the router.
* All connections to clients on the realm will be closed.<br>
* However pending calls will be completed through an error message
* as far as possible.
*/
public void close() {
if (eventLoop.isShuttingDown() || eventLoop.isShutdown()) return;
eventLoop.execute(new Runnable() {
@Override
public void run() {
if (isDisposed) return;
isDisposed = true;
// Close all currently connected channels
idleChannels.close();
idleChannels.clear();
for (Realm ri : realms.values()) {
for (WampRouterHandler channel : ri.channels) {
ri.removeChannel(channel, false);
channel.markAsClosed();
GoodbyeMessage goodbye = new GoodbyeMessage(null, ApplicationError.SYSTEM_SHUTDOWN);
channel.ctx.writeAndFlush(goodbye).addListener(ChannelFutureListener.CLOSE);
}
ri.channels.clear();
}
eventLoop.shutdownGracefully();
}
});
}
public ChannelHandler createRouterHandler() {
return new WampRouterHandler();
}
enum RouterHandlerState {
Open,
Closed
}
class WampRouterHandler extends SimpleChannelInboundHandler<WampMessage> {
public RouterHandlerState state = RouterHandlerState.Open;
ChannelHandlerContext ctx;
long sessionId;
Realm realm;
Set<WampRoles> roles;
/**
* Procedures that this channel provides.<br>
* Key is the registration ID, Value is the procedure
*/
Map<Long, Procedure> providedProcedures;
Map<Long, Invocation> pendingInvocations;
Map<Long, Subscription> subscriptions;
long lastUsedId = IdValidator.MIN_VALID_ID;
void markAsClosed() {
state = RouterHandlerState.Closed;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
// System.out.println("Router handler added on thread " + Thread.currentThread().getId());
this.ctx = ctx;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// System.out.println("Router handler active on thread " + Thread.currentThread().getId());
if (state != RouterHandlerState.Open) return;
if (isDisposed) {
// Got an incoming connection after the router has already shut down.
// Therefore we close the connection
state = RouterHandlerState.Closed;
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
} else {
idleChannels.add(ctx.channel());
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// System.out.println("Router handler inactive on thread " + Thread.currentThread().getId());
if (isDisposed || state != RouterHandlerState.Open) return;
markAsClosed();
if (realm != null) {
realm.removeChannel(this, true);
} else {
idleChannels.remove(ctx.channel());
}
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, WampMessage msg) throws Exception {
//System.out.println("Router channel read on thread " + Thread.currentThread().getId());
if (isDisposed || state != RouterHandlerState.Open) return;
if (realm == null) {
onMessageFromUnregisteredChannel(this, msg);
} else {
onMessageFromRegisteredChannel(this, msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (isDisposed || state != RouterHandlerState.Open) return;
if (realm != null) {
closeActiveChannel(this, null);
} else {
closePassiveChannel(this);
}
}
}
private void onMessageFromRegisteredChannel(WampRouterHandler handler, WampMessage msg) {
// TODO: Validate roles for all relevant messages
if (msg instanceof HelloMessage || msg instanceof WelcomeMessage) {
// The client sent hello but it was already registered -> This is an error
// If the client sends welcome it's also an error
closeActiveChannel(handler, new GoodbyeMessage(null, ApplicationError.INVALID_ARGUMENT));
} else if (msg instanceof AbortMessage || msg instanceof GoodbyeMessage) {
// The client wants to leave the realm
// Remove the channel from the realm
handler.realm.removeChannel(handler, true);
// But add it to the list of passive channels
idleChannels.add(handler.ctx.channel());
// Echo the message in case of goodbye
if (msg instanceof GoodbyeMessage) {
GoodbyeMessage reply = new GoodbyeMessage(null, ApplicationError.GOODBYE_AND_OUT);
handler.ctx.writeAndFlush(reply);
}
} else if (msg instanceof CallMessage) {
// The client wants to call a remote function
// Verify the message
CallMessage call = (CallMessage) msg;
String err = null;
if (!UriValidator.tryValidate(call.procedure)) {
// Client sent an invalid URI
err = ApplicationError.INVALID_URI;
}
if (err == null && !(IdValidator.isValidId(call.requestId))) {
// Client sent an invalid request ID
err = ApplicationError.INVALID_ARGUMENT;
}
Procedure proc = null;
if (err == null) {
proc = handler.realm.procedures.get(call.procedure);
if (proc == null) err = ApplicationError.NO_SUCH_PROCEDURE;
}
if (err != null) { // If we have an error send that to the client
ErrorMessage errMsg = new ErrorMessage(CallMessage.ID, call.requestId,
null, err, null, null);
handler.ctx.writeAndFlush(errMsg);
return;
}
// Everything checked, we can forward the call to the provider
Invocation invoc = new Invocation();
invoc.callRequestId = call.requestId;
invoc.caller = handler;
invoc.procedure = proc;
invoc.invocationRequestId = IdGenerator.newLinearId(proc.provider.lastUsedId,
proc.provider.pendingInvocations);
proc.provider.lastUsedId = invoc.invocationRequestId;
// Store the invocation
proc.provider.pendingInvocations.put(invoc.invocationRequestId, invoc);
// Store the call in the procedure to return error if client unregisters
proc.pendingCalls.add(invoc);
// And send it to the provider
InvocationMessage imsg = new InvocationMessage(invoc.invocationRequestId,
proc.registrationId, null, call.arguments, call.argumentsKw);
proc.provider.ctx.writeAndFlush(imsg);
} else if (msg instanceof YieldMessage) {
// The clients sends as the result of an RPC
// Verify the message
YieldMessage yield = (YieldMessage) msg;
if (!(IdValidator.isValidId(yield.requestId))) return;
// Look up the invocation to find the original caller
if (handler.pendingInvocations == null) return; // If a client send a yield without an invocation, return
Invocation invoc = handler.pendingInvocations.get(yield.requestId);
if (invoc == null) return; // There is no invocation pending under this ID
handler.pendingInvocations.remove(yield.requestId);
invoc.procedure.pendingCalls.remove(invoc);
// Send the result to the original caller
ResultMessage result = new ResultMessage(invoc.callRequestId, null, yield.arguments, yield.argumentsKw);
invoc.caller.ctx.writeAndFlush(result);
} else if (msg instanceof ErrorMessage) {
ErrorMessage err = (ErrorMessage) msg;
if (!(IdValidator.isValidId(err.requestId))) {
return;
}
if (err.requestType == InvocationMessage.ID) {
if (!UriValidator.tryValidate(err.error)) {
// The Message provider has sent us an invalid URI for the error string
// We better don't forward it but instead close the connection, which will
// give the original caller an unknown message error
closeActiveChannel(handler, new GoodbyeMessage(null, ApplicationError.INVALID_ARGUMENT));
return;
}
// Look up the invocation to find the original caller
if (handler.pendingInvocations == null) return; // if an error is send before an invocation, do not do anything
Invocation invoc = handler.pendingInvocations.get(err.requestId);
if (invoc == null) return; // There is no invocation pending under this ID
handler.pendingInvocations.remove(err.requestId);
invoc.procedure.pendingCalls.remove(invoc);
// Send the result to the original caller
ErrorMessage fwdError = new ErrorMessage(CallMessage.ID, invoc.callRequestId,
null, err.error, err.arguments, err.argumentsKw);
invoc.caller.ctx.writeAndFlush(fwdError);
}
// else TODO: Are there any other possibilities where a client could return ERROR
} else if (msg instanceof RegisterMessage) {
// The client wants to register a procedure
// Verify the message
RegisterMessage reg = (RegisterMessage) msg;
String err = null;
if (!UriValidator.tryValidate(reg.procedure)) {
// Client sent an invalid URI
err = ApplicationError.INVALID_URI;
}
if (err == null && !(IdValidator.isValidId(reg.requestId))) {
// Client sent an invalid request ID
err = ApplicationError.INVALID_ARGUMENT;
}
Procedure proc = null;
if (err == null) {
proc = handler.realm.procedures.get(reg.procedure);
if (proc != null) err = ApplicationError.PROCEDURE_ALREADY_EXISTS;
}
if (err != null) { // If we have an error send that to the client
ErrorMessage errMsg = new ErrorMessage(RegisterMessage.ID, reg.requestId,
null, err, null, null);
handler.ctx.writeAndFlush(errMsg);
return;
}
// Everything checked, we can register the caller as the procedure provider
long registrationId = IdGenerator.newLinearId(handler.lastUsedId, handler.providedProcedures);
handler.lastUsedId = registrationId;
Procedure procInfo = new Procedure(reg.procedure, handler, registrationId);
// Insert new procedure
handler.realm.procedures.put(reg.procedure, procInfo);
if (handler.providedProcedures == null) {
handler.providedProcedures = new HashMap<Long, WampRouter.Procedure>();
handler.pendingInvocations = new HashMap<Long, WampRouter.Invocation>();
}
handler.providedProcedures.put(procInfo.registrationId, procInfo);
RegisteredMessage response = new RegisteredMessage(reg.requestId, procInfo.registrationId);
handler.ctx.writeAndFlush(response);
} else if (msg instanceof UnregisterMessage) {
// The client wants to unregister a procedure
// Verify the message
UnregisterMessage unreg = (UnregisterMessage) msg;
String err = null;
if (!(IdValidator.isValidId(unreg.requestId))
|| !(IdValidator.isValidId(unreg.registrationId))) {
// Client sent an invalid request or registration ID
err = ApplicationError.INVALID_ARGUMENT;
}
Procedure proc = null;
if (err == null) {
if (handler.providedProcedures != null) {
proc = handler.providedProcedures.get(unreg.registrationId);
}
// Check whether the procedure exists AND if the caller is the owner
// If the caller is not the owner it might be an attack, so we don't
// disclose that the procedure exists.
if (proc == null) {
err = ApplicationError.NO_SUCH_REGISTRATION;
}
}
if (err != null) { // If we have an error send that to the client
ErrorMessage errMsg = new ErrorMessage(UnregisterMessage.ID, unreg.requestId,
null, err, null, null);
handler.ctx.writeAndFlush(errMsg);
return;
}
// Mark pending calls to this procedure as failed
for (Invocation invoc : proc.pendingCalls) {
handler.pendingInvocations.remove(invoc.invocationRequestId);
if (invoc.caller.state == RouterHandlerState.Open) {
ErrorMessage errMsg = new ErrorMessage(CallMessage.ID, invoc.callRequestId,
null, ApplicationError.NO_SUCH_PROCEDURE, null, null);
invoc.caller.ctx.writeAndFlush(errMsg);
}
}
proc.pendingCalls.clear();
// Remove the procedure from the realm and the handler
handler.realm.procedures.remove(proc.procName);
handler.providedProcedures.remove(proc.registrationId);
if (handler.providedProcedures.size() == 0) {
handler.providedProcedures = null;
handler.pendingInvocations = null;
}
// Send the acknowledge
UnregisteredMessage response = new UnregisteredMessage(unreg.requestId);
handler.ctx.writeAndFlush(response);
} else if (msg instanceof SubscribeMessage) {
// The client wants to subscribe to a procedure
// Verify the message
SubscribeMessage sub = (SubscribeMessage) msg;
String err = null;
if (!UriValidator.tryValidate(sub.topic)) {
// Client sent an invalid URI
err = ApplicationError.INVALID_URI;
}
if (err == null && !(IdValidator.isValidId(sub.requestId))) {
// Client sent an invalid request ID
err = ApplicationError.INVALID_ARGUMENT;
}
if (err != null) { // If we have an error send that to the client
ErrorMessage errMsg = new ErrorMessage(SubscribeMessage.ID, sub.requestId,
null, err, null, null);
handler.ctx.writeAndFlush(errMsg);
return;
}
// Everything checked, we can add the caller as a subscriber
long subscriptionId = IdGenerator.newLinearId(handler.lastUsedId, handler.subscriptions);
handler.lastUsedId = subscriptionId;
Subscription s = new Subscription(sub.topic, subscriptionId, handler);
// Add the subscription on the realm
Set<Subscription> subscriptionSet = handler.realm.subscriptions.get(sub.topic);
if (subscriptionSet == null) {
// First subscriber - create a new set
subscriptionSet = new HashSet<Subscription>();
handler.realm.subscriptions.put(sub.topic, subscriptionSet);
}
subscriptionSet.add(s);
// Add the subscription on the client
if (handler.subscriptions == null) {
handler.subscriptions = new HashMap<Long, WampRouter.Subscription>();
}
handler.subscriptions.put(subscriptionId, s);
SubscribedMessage response = new SubscribedMessage(sub.requestId, subscriptionId);
handler.ctx.writeAndFlush(response);
} else if (msg instanceof UnsubscribeMessage) {
// The client wants to cancel a subscription
// Verify the message
UnsubscribeMessage unsub = (UnsubscribeMessage) msg;
String err = null;
if (!(IdValidator.isValidId(unsub.requestId))
|| !(IdValidator.isValidId(unsub.subscriptionId))) {
// Client sent an invalid request or registration ID
err = ApplicationError.INVALID_ARGUMENT;
}
Subscription s = null;
if (err == null) {
// Check whether such a subscription exists and fetch the topic name
if (handler.subscriptions != null) {
s = handler.subscriptions.get(unsub.subscriptionId);
}
if (s == null) {
err = ApplicationError.NO_SUCH_SUBSCRIPTION;
}
}
if (err != null) { // If we have an error send that to the client
ErrorMessage errMsg = new ErrorMessage(UnsubscribeMessage.ID, unsub.requestId,
null, err, null, null);
handler.ctx.writeAndFlush(errMsg);
return;
}
// Remove the subscription from the realm
Set<Subscription> subscriptionSet = handler.realm.subscriptions.get(s.topic);
subscriptionSet.remove(s);
if (subscriptionSet.isEmpty()) {
handler.realm.subscriptions.remove(s.topic);
}
// Remove the subscription from the handler
handler.subscriptions.remove(unsub.subscriptionId);
if (handler.subscriptions.isEmpty()) {
handler.subscriptions = null;
}
// Send the acknowledge
UnsubscribedMessage response = new UnsubscribedMessage(unsub.requestId);
handler.ctx.writeAndFlush(response);
} else if (msg instanceof PublishMessage) {
// The client wants to publish something to all subscribers (apart from himself)
PublishMessage pub = (PublishMessage) msg;
String err = null;
if (!UriValidator.tryValidate(pub.topic)) {
// Client sent an invalid URI
err = ApplicationError.INVALID_URI;
}
if (err == null && !(IdValidator.isValidId(pub.requestId))) {
// Client sent an invalid request ID
err = ApplicationError.INVALID_ARGUMENT;
}
if (err != null) { // If we have an error send that to the client
ErrorMessage errMsg = new ErrorMessage(PublishMessage.ID, pub.requestId,
null, err, null, null);
handler.ctx.writeAndFlush(errMsg);
return;
}
long publicationId = IdGenerator.newRandomId(null); // Store that somewhere?
// Get the subscriptions for this topic on the realm
Set<Subscription> subscriptionSet = handler.realm.subscriptions.get(pub.topic);
if (subscriptionSet != null) {
for (Subscription subscriber : subscriptionSet) {
if (subscriber.subscriber == handler) continue; // Skip the publisher
// Publish the event to the subscriber
EventMessage ev = new EventMessage(subscriber.subscriptionId, publicationId,
null, pub.arguments, pub.argumentsKw);
subscriber.subscriber.ctx.writeAndFlush(ev);
}
}
PublishedMessage response = new PublishedMessage(pub.requestId, publicationId);
handler.ctx.writeAndFlush(response);
}
}
private void onMessageFromUnregisteredChannel(WampRouterHandler channelHandler, WampMessage msg)
{
// Only HELLO is allowed when a channel is not registered
if (!(msg instanceof HelloMessage)) {
// Close the connection
closePassiveChannel(channelHandler);
return;
}
HelloMessage hello = (HelloMessage) msg;
String errorMsg = null;
Realm realm = null;
if (!UriValidator.tryValidate(hello.realm)) {
errorMsg = ApplicationError.INVALID_URI;
} else {
realm = realms.get(hello.realm);
if (realm == null) {
errorMsg = ApplicationError.NO_SUCH_REALM;
}
}
if (errorMsg != null) {
AbortMessage abort = new AbortMessage(null, errorMsg);
channelHandler.ctx.writeAndFlush(abort);
return;
}
Set<WampRoles> roles = new HashSet<WampRoles>();
boolean hasUnsupportedRoles = false;
JsonNode n = hello.details.get("roles");
if (n != null && n.isObject()) {
ObjectNode rolesNode = (ObjectNode) n;
Iterator<String> roleKeys = rolesNode.fieldNames();
while (roleKeys.hasNext()) {
WampRoles role = WampRoles.fromString(roleKeys.next());
if (!SUPPORTED_CLIENT_ROLES.contains(role)) hasUnsupportedRoles = true;
if (role != null) roles.add(role);
}
}
if (roles.size() == 0 || hasUnsupportedRoles) {
AbortMessage abort = new AbortMessage(null, ApplicationError.NO_SUCH_ROLE);
channelHandler.ctx.writeAndFlush(abort);
return;
}
long sessionId = IdGenerator.newRandomId(null);
// TODO: Should be unique on the router and should be stored somewhere
// Include the channel into the realm
realm.includeChannel(channelHandler, sessionId, roles);
// Remove the channel from the idle channel list - It is no longer idle
idleChannels.remove(channelHandler.ctx.channel());
// Expose the roles that are configured for the realm
ObjectNode welcomeDetails = objectMapper.createObjectNode();
ObjectNode routerRoles = welcomeDetails.putObject("roles");
for (WampRoles role : realm.config.roles) {
routerRoles.putObject(role.toString());
}
// Respond with the WELCOME message
WelcomeMessage welcome = new WelcomeMessage(channelHandler.sessionId, welcomeDetails);
channelHandler.ctx.writeAndFlush(welcome);
}
private void closeActiveChannel(WampRouterHandler channel, WampMessage closeMessage) {
if (channel == null) return;
channel.realm.removeChannel(channel, true);
channel.markAsClosed();
if (channel.ctx != null) {
Object m = (closeMessage == null) ? Unpooled.EMPTY_BUFFER : closeMessage;
channel.ctx.writeAndFlush(m)
.addListener(ChannelFutureListener.CLOSE);
}
}
private void closePassiveChannel(WampRouterHandler channelHandler) {
idleChannels.remove(channelHandler.ctx.channel());
channelHandler.markAsClosed();
channelHandler.ctx.close();
}
}
|
Send responses to Publish messages only when requested by the client.
|
src/main/java/ws/wamp/jawampa/WampRouter.java
|
Send responses to Publish messages only when requested by the client.
|
<ide><path>rc/main/java/ws/wamp/jawampa/WampRouter.java
<ide> } else if (msg instanceof PublishMessage) {
<ide> // The client wants to publish something to all subscribers (apart from himself)
<ide> PublishMessage pub = (PublishMessage) msg;
<add> // Check whether the client wants an acknowledgement for the publication
<add> // Default is no
<add> boolean sendAcknowledge = false;
<add> JsonNode ackOption = pub.options.get("acknowledge");
<add> if (ackOption != null && ackOption.asBoolean() == true)
<add> sendAcknowledge = true;
<add>
<ide> String err = null;
<ide> if (!UriValidator.tryValidate(pub.topic)) {
<ide> // Client sent an invalid URI
<ide> if (err != null) { // If we have an error send that to the client
<ide> ErrorMessage errMsg = new ErrorMessage(PublishMessage.ID, pub.requestId,
<ide> null, err, null, null);
<del> handler.ctx.writeAndFlush(errMsg);
<add> if (sendAcknowledge) {
<add> handler.ctx.writeAndFlush(errMsg);
<add> }
<ide> return;
<ide> }
<ide>
<ide> // Get the subscriptions for this topic on the realm
<ide> Set<Subscription> subscriptionSet = handler.realm.subscriptions.get(pub.topic);
<ide> if (subscriptionSet != null) {
<del>
<ide> for (Subscription subscriber : subscriptionSet) {
<ide> if (subscriber.subscriber == handler) continue; // Skip the publisher
<ide> // Publish the event to the subscriber
<ide> }
<ide> }
<ide>
<del> PublishedMessage response = new PublishedMessage(pub.requestId, publicationId);
<del> handler.ctx.writeAndFlush(response);
<add> if (sendAcknowledge) {
<add> PublishedMessage response = new PublishedMessage(pub.requestId, publicationId);
<add> handler.ctx.writeAndFlush(response);
<add> }
<ide> }
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
05beb1769cdf0fa1d44e769e6455a6f5edebb982
| 0 |
grgrzybek/karaf,grgrzybek/karaf,grgrzybek/karaf
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.karaf.config.core.impl;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import org.apache.felix.utils.properties.TypedProperties;
import org.apache.karaf.config.core.ConfigRepository;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConfigRepositoryImpl implements ConfigRepository {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigRepositoryImpl.class);
private static final String FILEINSTALL_FILE_NAME = "felix.fileinstall.filename";
private ConfigurationAdmin configAdmin;
public ConfigRepositoryImpl(ConfigurationAdmin configAdmin) {
this.configAdmin = configAdmin;
}
/* (non-Javadoc)
* @see org.apache.karaf.shell.config.impl.ConfigRepository#update(java.lang.String, java.util.Dictionary, boolean)
*/
@Override
public void update(String pid, Map<String, Object> properties) throws IOException {
try {
LOGGER.trace("Updating configuration {}", pid);
Configuration cfg = configAdmin.getConfiguration(pid, "?");
Dictionary<String, Object> dict = cfg.getProperties();
TypedProperties props = new TypedProperties();
File file = getCfgFileFromProperties(dict);
if (file != null) {
props.load(file);
props.putAll(properties);
props.save(file);
props.clear();
props.load(file);
props.put(FILEINSTALL_FILE_NAME, file.toURI().toString());
} else {
file = new File(System.getProperty("karaf.etc"), pid + ".cfg");
props.putAll(properties);
props.save(file);
props.put(FILEINSTALL_FILE_NAME, file.toURI().toString());
}
cfg.update(new Hashtable<>(props));
} catch (URISyntaxException e) {
throw new IOException("Error updating config", e);
}
}
/* (non-Javadoc)
* @see org.apache.karaf.shell.config.impl.ConfigRepository#delete(java.lang.String)
*/
@Override
public void delete(String pid) throws Exception {
LOGGER.trace("Deleting configuration {}", pid);
Configuration configuration = configAdmin.getConfiguration(pid, null);
configuration.delete();
}
private File getCfgFileFromProperties(Dictionary<String, Object> properties) throws URISyntaxException, MalformedURLException {
if (properties != null) {
Object val = properties.get(FILEINSTALL_FILE_NAME);
return getCfgFileFromProperty(val);
}
return null;
}
private File getCfgFileFromProperty(Object val) throws URISyntaxException, MalformedURLException {
if (val instanceof URL) {
return new File(((URL) val).toURI());
}
if (val instanceof URI) {
return new File((URI) val);
}
if (val instanceof String) {
return new File(new URL((String) val).toURI());
}
return null;
}
@Override
public TypedProperties getConfig(String pid) throws IOException, InvalidSyntaxException {
if (pid != null && configAdmin != null) {
Configuration configuration = configAdmin.getConfiguration(pid, null);
if (configuration != null) {
TypedProperties tp = new TypedProperties();
Dictionary<String, Object> props = configuration.getProperties();
if (props != null) {
File file;
try {
file = getCfgFileFromProperties(props);
} catch (URISyntaxException e) {
throw new IOException(e);
}
if (file != null) {
tp.load(file);
} else {
for (Enumeration<String> e = props.keys(); e.hasMoreElements();) {
String key = e.nextElement();
Object val = props.get(key);
tp.put(key, val);
}
tp.remove( Constants.SERVICE_PID );
tp.remove( ConfigurationAdmin.SERVICE_FACTORYPID );
}
}
return tp;
}
}
return null;
}
@Override
public String createFactoryConfiguration(String factoryPid, Map<String, Object> properties) throws IOException {
return createFactoryConfiguration(factoryPid, null, properties);
}
@Override
public String createFactoryConfiguration(String factoryPid, String alias, Map<String, Object> properties) throws IOException {
Configuration config = configAdmin.createFactoryConfiguration(factoryPid, "?");
TypedProperties props = new TypedProperties();
File file = File.createTempFile(factoryPid + "-", ".cfg", new File(System.getProperty("karaf.etc")));
props.putAll(properties);
props.save(file);
props.put(FILEINSTALL_FILE_NAME, file.toURI().toString());
config.update(new Hashtable<>(props));
return config.getPid();
}
@Override
public ConfigurationAdmin getConfigAdmin() {
return configAdmin;
}
}
|
config/src/main/java/org/apache/karaf/config/core/impl/ConfigRepositoryImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.karaf.config.core.impl;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import org.apache.felix.utils.properties.TypedProperties;
import org.apache.karaf.config.core.ConfigRepository;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConfigRepositoryImpl implements ConfigRepository {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigRepositoryImpl.class);
private static final String FILEINSTALL_FILE_NAME = "felix.fileinstall.filename";
private ConfigurationAdmin configAdmin;
public ConfigRepositoryImpl(ConfigurationAdmin configAdmin) {
this.configAdmin = configAdmin;
}
/* (non-Javadoc)
* @see org.apache.karaf.shell.config.impl.ConfigRepository#update(java.lang.String, java.util.Dictionary, boolean)
*/
@Override
public void update(String pid, Map<String, Object> properties) throws IOException {
try {
LOGGER.trace("Updating configuration {}", pid);
Configuration cfg = configAdmin.getConfiguration(pid, null);
Dictionary<String, Object> dict = cfg.getProperties();
TypedProperties props = new TypedProperties();
File file = getCfgFileFromProperties(dict);
if (file != null) {
props.load(file);
props.putAll(properties);
props.save(file);
props.clear();
props.load(file);
props.put(FILEINSTALL_FILE_NAME, file.toURI().toString());
} else {
props.putAll(properties);
}
cfg.update(new Hashtable<>(props));
} catch (URISyntaxException e) {
throw new IOException("Error updating config", e);
}
}
/* (non-Javadoc)
* @see org.apache.karaf.shell.config.impl.ConfigRepository#delete(java.lang.String)
*/
@Override
public void delete(String pid) throws Exception {
LOGGER.trace("Deleting configuration {}", pid);
Configuration configuration = configAdmin.getConfiguration(pid, null);
configuration.delete();
}
private File getCfgFileFromProperties(Dictionary<String, Object> properties) throws URISyntaxException, MalformedURLException {
if (properties != null) {
Object val = properties.get(FILEINSTALL_FILE_NAME);
return getCfgFileFromProperty(val);
}
return null;
}
private File getCfgFileFromProperty(Object val) throws URISyntaxException, MalformedURLException {
if (val instanceof URL) {
return new File(((URL) val).toURI());
}
if (val instanceof URI) {
return new File((URI) val);
}
if (val instanceof String) {
return new File(new URL((String) val).toURI());
}
return null;
}
@Override
public TypedProperties getConfig(String pid) throws IOException, InvalidSyntaxException {
if (pid != null && configAdmin != null) {
Configuration configuration = configAdmin.getConfiguration(pid, null);
if (configuration != null) {
TypedProperties tp = new TypedProperties();
Dictionary<String, Object> props = configuration.getProperties();
if (props != null) {
File file;
try {
file = getCfgFileFromProperties(props);
} catch (URISyntaxException e) {
throw new IOException(e);
}
if (file != null) {
tp.load(file);
} else {
for (Enumeration<String> e = props.keys(); e.hasMoreElements();) {
String key = e.nextElement();
Object val = props.get(key);
tp.put(key, val);
}
tp.remove( Constants.SERVICE_PID );
tp.remove( ConfigurationAdmin.SERVICE_FACTORYPID );
}
}
return tp;
}
}
return null;
}
@Override
public String createFactoryConfiguration(String factoryPid, Map<String, Object> properties) throws IOException {
return createFactoryConfiguration(factoryPid, null, properties);
}
@Override
public String createFactoryConfiguration(String factoryPid, String alias, Map<String, Object> properties) throws IOException {
Configuration config = configAdmin.createFactoryConfiguration(factoryPid, "?");
config.update(new Hashtable<>(properties));
return config.getPid();
}
@Override
public ConfigurationAdmin getConfigAdmin() {
return configAdmin;
}
}
|
[KARAF-5023] Fix regression that cause newly created configurations to not be persisted in the etc directory
|
config/src/main/java/org/apache/karaf/config/core/impl/ConfigRepositoryImpl.java
|
[KARAF-5023] Fix regression that cause newly created configurations to not be persisted in the etc directory
|
<ide><path>onfig/src/main/java/org/apache/karaf/config/core/impl/ConfigRepositoryImpl.java
<ide> public void update(String pid, Map<String, Object> properties) throws IOException {
<ide> try {
<ide> LOGGER.trace("Updating configuration {}", pid);
<del> Configuration cfg = configAdmin.getConfiguration(pid, null);
<add> Configuration cfg = configAdmin.getConfiguration(pid, "?");
<ide> Dictionary<String, Object> dict = cfg.getProperties();
<ide> TypedProperties props = new TypedProperties();
<ide> File file = getCfgFileFromProperties(dict);
<ide> props.load(file);
<ide> props.put(FILEINSTALL_FILE_NAME, file.toURI().toString());
<ide> } else {
<add> file = new File(System.getProperty("karaf.etc"), pid + ".cfg");
<ide> props.putAll(properties);
<add> props.save(file);
<add> props.put(FILEINSTALL_FILE_NAME, file.toURI().toString());
<ide> }
<ide> cfg.update(new Hashtable<>(props));
<ide> } catch (URISyntaxException e) {
<ide> @Override
<ide> public String createFactoryConfiguration(String factoryPid, String alias, Map<String, Object> properties) throws IOException {
<ide> Configuration config = configAdmin.createFactoryConfiguration(factoryPid, "?");
<del> config.update(new Hashtable<>(properties));
<add> TypedProperties props = new TypedProperties();
<add> File file = File.createTempFile(factoryPid + "-", ".cfg", new File(System.getProperty("karaf.etc")));
<add> props.putAll(properties);
<add> props.save(file);
<add> props.put(FILEINSTALL_FILE_NAME, file.toURI().toString());
<add> config.update(new Hashtable<>(props));
<ide> return config.getPid();
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
603abdabf98f56566d19acf692f722bf42828794
| 0 |
niklaspolke/MyExpenses
|
package vu.de.npolke.myexpenses.servlets;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
import vu.de.npolke.myexpenses.model.Account;
import vu.de.npolke.myexpenses.services.AccountDAO;
import vu.de.npolke.myexpenses.servlets.util.ServletReaction;
import vu.de.npolke.myexpenses.util.HashUtil;
/**
* Copyright 2015 Niklas Polke
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* @author Niklas Polke
*/
public class EditAccountServletTest {
private static final String PASSWORD_OLD = "password";
private static final String PASSWORD_NEW = "new password";
private EditAccountServlet servlet;
private Account account;
@Before
public void init() {
servlet = new EditAccountServlet();
servlet.accountDAO = mock(AccountDAO.class);
account = new Account();
account.setPassword(HashUtil.toMD5(PASSWORD_OLD));
}
@Test
public void prepareEditAccount() {
ServletReaction reaction = servlet.prepareEditAccount(account);
assertNotNull(reaction);
// correct session attribute: account to edit
Object accountObject = reaction.getSessionAttributes().get("account");
assertTrue(accountObject instanceof Account);
Account accountInSession = (Account) accountObject;
assertEquals(account, accountInSession);
// correct navigation
assertEquals("editaccount.jsp", reaction.getRedirect());
}
@Test
public void editAccount() {
ServletReaction reaction = servlet.editAccount(account, PASSWORD_OLD, PASSWORD_NEW, PASSWORD_NEW);
assertNotNull(reaction);
// correct new account password
assertEquals(HashUtil.toMD5(PASSWORD_NEW), account.getPassword());
// correct persisting
verify(servlet.accountDAO).update(account);
// correct navigation
assertEquals("listexpenses", reaction.getRedirect());
}
@Test
public void editAccount_wrongPassword() {
ServletReaction reaction = servlet.editAccount(account, "notOldPassword", PASSWORD_NEW, PASSWORD_NEW);
assertNotNull(reaction);
// correct persisting
verify(servlet.accountDAO, never()).update(account);
// correct error message
assertEquals("old password wasn't correct", reaction.getRequestAttributes().get("errorMessage"));
// correct navigation
assertEquals("editaccount.jsp", reaction.getForward());
}
@Test
public void editAccount_newPasswordsNotEqual() {
ServletReaction reaction = servlet.editAccount(account, PASSWORD_OLD, PASSWORD_NEW, "notNewPassword");
assertNotNull(reaction);
// correct persisting
verify(servlet.accountDAO, never()).update(account);
// correct error message
assertEquals("new password 1 wasn't equal to new password 2", reaction.getRequestAttributes().get("errorMessage"));
// correct navigation
assertEquals("editaccount.jsp", reaction.getForward());
}
}
|
src/test/java/vu/de/npolke/myexpenses/servlets/EditAccountServletTest.java
|
package vu.de.npolke.myexpenses.servlets;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
import vu.de.npolke.myexpenses.model.Account;
import vu.de.npolke.myexpenses.services.AccountDAO;
import vu.de.npolke.myexpenses.servlets.util.ServletReaction;
import vu.de.npolke.myexpenses.util.HashUtil;
/**
* Copyright 2015 Niklas Polke
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* @author Niklas Polke
*/
public class EditAccountServletTest {
private static final String PASSWORD_OLD = "password";
private static final String PASSWORD_NEW = "new password";
private EditAccountServlet servlet;
private Account account;
@Before
public void init() {
servlet = new EditAccountServlet();
servlet.accountDAO = mock(AccountDAO.class);
account = new Account();
account.setPassword(HashUtil.toMD5(PASSWORD_OLD));
}
@Test
public void prepareEditAccount() {
ServletReaction reaction = servlet.prepareEditAccount(account);
assertNotNull(reaction);
// correct session attribute: account to edit
Object accountObject = reaction.getSessionAttributes().get("account");
assertTrue(accountObject instanceof Account);
Account accountInSession = (Account) accountObject;
assertEquals(account, accountInSession);
// correct navigation
assertEquals("editaccount.jsp", reaction.getRedirect());
}
@Test
public void editAccount() {
ServletReaction reaction = servlet.editAccount(account, PASSWORD_OLD, PASSWORD_NEW, PASSWORD_NEW);
assertNotNull(reaction);
// correct new account password
assertEquals(HashUtil.toMD5(PASSWORD_NEW), account.getPassword());
// correct persisting
verify(servlet.accountDAO).update(account);
// correct navigation
assertEquals("listexpenses", reaction.getRedirect());
}
@Test
public void editAccount_wrongPassword() {
ServletReaction reaction = servlet.editAccount(account, "notOldPassword", PASSWORD_NEW, PASSWORD_NEW);
assertNotNull(reaction);
// correct persisting
verify(servlet.accountDAO, never()).update(account);
// correct error message
assertEquals("oldpassword wasn't correct", reaction.getRequestAttributes().get("errorMessage"));
// correct navigation
assertEquals("editaccount.jsp", reaction.getForward());
}
@Test
public void editAccount_newPasswordsNotEqual() {
ServletReaction reaction = servlet.editAccount(account, PASSWORD_OLD, PASSWORD_NEW, "notNewPassword");
assertNotNull(reaction);
// correct persisting
verify(servlet.accountDAO, never()).update(account);
// correct error message
assertEquals("password1 wasn't equal to password2", reaction.getRequestAttributes().get("errorMessage"));
// correct navigation
assertEquals("editaccount.jsp", reaction.getForward());
}
}
|
Fix JUnit test
|
src/test/java/vu/de/npolke/myexpenses/servlets/EditAccountServletTest.java
|
Fix JUnit test
|
<ide><path>rc/test/java/vu/de/npolke/myexpenses/servlets/EditAccountServletTest.java
<ide> // correct persisting
<ide> verify(servlet.accountDAO, never()).update(account);
<ide> // correct error message
<del> assertEquals("oldpassword wasn't correct", reaction.getRequestAttributes().get("errorMessage"));
<add> assertEquals("old password wasn't correct", reaction.getRequestAttributes().get("errorMessage"));
<ide> // correct navigation
<ide> assertEquals("editaccount.jsp", reaction.getForward());
<ide> }
<ide> // correct persisting
<ide> verify(servlet.accountDAO, never()).update(account);
<ide> // correct error message
<del> assertEquals("password1 wasn't equal to password2", reaction.getRequestAttributes().get("errorMessage"));
<add> assertEquals("new password 1 wasn't equal to new password 2", reaction.getRequestAttributes().get("errorMessage"));
<ide> // correct navigation
<ide> assertEquals("editaccount.jsp", reaction.getForward());
<ide> }
|
|
Java
|
mit
|
b149f9f1d1a205fc3d44e129ca1f14ab3b49db29
| 0 |
FASAM-ES/projeto-zeus
|
package br.com.fasam.projetoexemplo.entidades;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author João Carlos Ottobboni
*/
public class Artigo {
String titulo;
String descricao;
Usuario usuario;
List<Comentario> comentarios;
List<Tag> tags;
public Artigo(Usuario usuario){
this.usuario = usuario;
this.titulo = "Ciências aplicadas Globais";
this.descricao = "Artigo referente a materia de Ciências Aplicadas, necessario que o usuario tenha sido aprovado no Modulo01";
this.addTag(new Tag());
}
public Usuario getUsuario() {
return usuario;
}
/**
* Metodo que Retorna usuário
* @return Usuario
*
*/
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
/**
* Metodo que seta usuário
*/
public Comentario getComentario(Integer i){
return comentarios.get(i);
}
/**
* Metodo que retorna usuário
*/
public void addComentario(Comentario comentario){
if(this.comentarios == null){
this.comentarios = new ArrayList<Comentario>();
}
this.comentarios.add(comentario);
}
/**
* Metodo que adiciona comentarios
*/
public void remComentario(Comentario comentario){
if(this.comentarios == null){
this.comentarios.remove(comentario);
}
}
/**
* Metodo que remove comentarios
*/
public Tag getTag(Integer i){
return tags.get(i);
}
/**
* Metodo que retorna tag
*/
public void addTag(Tag tag){
if(this.tags == null){
this.tags = new ArrayList<Tag>();
}
this.tags.add(tag);
}
/**
* Metodo que adicona uma tag a lista
*/
public void remTag(Tag tag){
if(this.tags == null){
this.tags.remove(tag);
}
}
/**
* Metodo que remove uma tag da lista
*/
public String getTitulo() {
return titulo;
}
/**
* Metodo que retorna titulo
*/
public void setTitulo(String titulo) {
this.titulo = titulo;
}
/**
* Metodo que seta o titulo
*/
public String getDescricao() {
return descricao;
}
/**
* Metodo que retorna descricao
*/
public void setDescricao(String descricao) {
this.descricao = descricao;
}
/**
* Metodo que seta descricao
*/
}
|
ProjetoExemplo/src/main/java/br/com/fasam/projetoexemplo/entidades/Artigo.java
|
package br.com.fasam.projetoexemplo.entidades;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author João Carlos Ottobboni
*/
public class Artigo {
String titulo;
String descricao;
Usuario usuario;
List<Comentario> comentarios;
List<Tag> tags;
public Artigo(Usuario usuario){
this.usuario = usuario;
this.titulo = "Ciências aplicadas Globais";
this.descricao = "Artigo referente a materia de Ciências Aplicadas, necessario que o usuario tenha sido aprovado no Modulo01";
this.addTag(new Tag());
}
public Usuario getUsuario() {
return usuario;
}
/**
* Metodo que Retorna usuário
* @return Usuario
*
*/
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
/**
* Metodo que seta usuário
*/
public Comentario getComentario(Integer i){
return comentarios.get(i);
}
/**
* Metodo que retorna usuário
*/
public void addComentario(Comentario comentario){
if(this.comentarios == null){
this.comentarios = new ArrayList<Comentario>();
}
this.comentarios.add(comentario);
}
public void remComentario(Comentario comentario){
if(this.comentarios == null){
this.comentarios.remove(comentario);
}
}
public Tag getTag(Integer i){
return tags.get(i);
}
public void addTag(Tag tag){
if(this.tags == null){
this.tags = new ArrayList<Tag>();
}
this.tags.add(tag);
}
public void remTag(Tag tag){
if(this.tags == null){
this.tags.remove(tag);
}
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
|
Adicionando docs
|
ProjetoExemplo/src/main/java/br/com/fasam/projetoexemplo/entidades/Artigo.java
|
Adicionando docs
|
<ide><path>rojetoExemplo/src/main/java/br/com/fasam/projetoexemplo/entidades/Artigo.java
<ide> }
<ide> this.comentarios.add(comentario);
<ide> }
<add> /**
<add> * Metodo que adiciona comentarios
<add> */
<ide> public void remComentario(Comentario comentario){
<ide> if(this.comentarios == null){
<ide> this.comentarios.remove(comentario);
<ide> }
<ide> }
<add> /**
<add> * Metodo que remove comentarios
<add> */
<ide>
<ide> public Tag getTag(Integer i){
<ide> return tags.get(i);
<ide> }
<add> /**
<add> * Metodo que retorna tag
<add> */
<ide> public void addTag(Tag tag){
<ide> if(this.tags == null){
<ide> this.tags = new ArrayList<Tag>();
<ide> }
<ide> this.tags.add(tag);
<ide> }
<add> /**
<add> * Metodo que adicona uma tag a lista
<add> */
<ide> public void remTag(Tag tag){
<ide> if(this.tags == null){
<ide> this.tags.remove(tag);
<ide> }
<ide> }
<add> /**
<add> * Metodo que remove uma tag da lista
<add> */
<ide>
<ide> public String getTitulo() {
<ide> return titulo;
<ide> }
<add> /**
<add> * Metodo que retorna titulo
<add> */
<ide>
<ide> public void setTitulo(String titulo) {
<ide> this.titulo = titulo;
<ide> }
<add> /**
<add> * Metodo que seta o titulo
<add> */
<ide>
<ide> public String getDescricao() {
<ide> return descricao;
<ide> }
<add> /**
<add> * Metodo que retorna descricao
<add> */
<ide>
<ide> public void setDescricao(String descricao) {
<ide> this.descricao = descricao;
<ide> }
<add> /**
<add> * Metodo que seta descricao
<add> */
<ide>
<ide>
<ide> }
|
|
JavaScript
|
bsd-3-clause
|
0f2ab5b6967200aa31e88bc773f905bb8e3a1a27
| 0 |
crowdcover/mapbox-studio,mapbox/mapbox-studio-classic,xrwang/mapbox-studio,Zhao-Qi/mapbox-studio-classic,tizzybec/mapbox-studio,mapbox/mapbox-studio,adozenlines/mapbox-studio,mapbox/mapbox-studio-classic,ali/mapbox-studio,ali/mapbox-studio,crowdcover/mapbox-studio,adozenlines/mapbox-studio,mapbox/mapbox-studio,tizzybec/mapbox-studio,xrwang/mapbox-studio,mapbox/mapbox-studio,AbelSu131/mapbox-studio,crowdcover/mapbox-studio,AbelSu131/mapbox-studio,tizzybec/mapbox-studio,danieljoppi/mapbox-studio,adozenlines/mapbox-studio,wakermahmud/mapbox-studio,xrwang/mapbox-studio,AbelSu131/mapbox-studio,Zhao-Qi/mapbox-studio-classic,Zhao-Qi/mapbox-studio-classic,ali/mapbox-studio,wakermahmud/mapbox-studio,wakermahmud/mapbox-studio,AbelSu131/mapbox-studio,tizzybec/mapbox-studio,crowdcover/mapbox-studio,xrwang/mapbox-studio,mapbox/mapbox-studio,danieljoppi/mapbox-studio,wakermahmud/mapbox-studio,danieljoppi/mapbox-studio,danieljoppi/mapbox-studio,mapbox/mapbox-studio-classic,xrwang/mapbox-studio,Zhao-Qi/mapbox-studio-classic,adozenlines/mapbox-studio,Zhao-Qi/mapbox-studio-classic,mapbox/mapbox-studio-classic,mapbox/mapbox-studio,crowdcover/mapbox-studio,AbelSu131/mapbox-studio,ali/mapbox-studio,wakermahmud/mapbox-studio,adozenlines/mapbox-studio,tizzybec/mapbox-studio,ali/mapbox-studio,danieljoppi/mapbox-studio
|
var _ = require('underscore');
var carto = require('carto');
var crypto = require('crypto');
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var Vector = require('tilelive-vector');
var sm = new (require('sphericalmercator'));
var yaml = require('js-yaml');
var tm = require('./tm');
var mapnik = require('mapnik');
var fstream = require('fstream');
var tar = require('tar');
var zlib = require('zlib');
var tilelive = require('tilelive');
var url = require('url');
var upload = require('mapbox-upload');
var task = require('./task');
var gazetteer = require('gazetteer');
var defaults = {
name:'',
description:'',
attribution:'',
source:'',
styles:{},
center:[0,0,3],
bounds:[-180,-85.0511,180,85.0511],
minzoom:0,
maxzoom:22,
format:'png8:m=h',
template:'',
interactivity_layer:'',
layers:null,
_properties: {},
_prefs: {
saveCenter: true,
mapid: ''
}
};
var cache = {};
module.exports = style;
tilelive.protocols['tmstyle:'] = style;
tilelive.protocols['tmpstyle:'] = style;
function style(arg, callback) {
if ('string' !== typeof arg) {
var id = url.format(arg);
var uri = arg;
} else {
var id = arg;
var uri = tm.parse(arg);
}
if (!uri || (uri.protocol !== 'tmstyle:' && uri.protocol !== 'tmpstyle:'))
return callback(new Error('Invalid style protocol'));
if (cache[id]) return callback(null, cache[id]);
// Reading.
style.info(id, function(err, data) {
if (err) return callback(err);
style.toXML(data, function(err, xml) {
if (err) return callback(err);
style.refresh(data, xml, callback);
});
});
};
// Load or refresh the relevant source using specified data + xml.
style.refresh = function(data, xml, callback) {
var id = data.id;
var uri = tm.parse(data.id);
var done = function(err, p) {
if (err) return callback(err);
cache[id] = cache[id] || p;
cache[id].data = data;
cache[id].data.background = _('rgba(<%=r%>,<%=g%>,<%=b%>,<%=(a/255).toFixed(2)%>)').template(cache[id]._map.background);
cache[id].stats = {};
cache[id].errors = [];
return callback(null, cache[id]);
};
var opts = {};
opts.xml = xml;
opts.base = uri.dirname;
opts.scale = data.scale || 1;
opts.source = 'mapbox:///mapbox.mapbox-streets-v2';
return cache[id] ? cache[id].update(opts, done) : new Vector(opts, done);
};
// Clear reference to cached style.
style.clear = function(id) {
delete cache[id];
};
// Writing.
style.save = function(data, callback) {
var id = data.id;
var uri = tm.parse(data.id);
var perm = !style.tmpid(id);
// Saving a tmp project permanently to a new location.
// Copy tmp project first before saving.
if (perm && data._tmp) {
var src = tm.parse(data._tmp).dirname;
var dst = uri.dirname;
var exclude = [ /^[\.\_]/, 'package.json' ];
return tm.copydir(src, dst, exclude, function(err) {
if (err) return callback(err);
data._tmp = false;
style.save(data, callback);
});
}
data = _(data).defaults(defaults);
data._tmp = data._tmp || (style.tmpid(id) ? id : false);
// validate key info keys.
var err = tilelive.verify(data, [
'name',
'description',
'attribution',
'source',
'center',
'bounds',
'minzoom',
'maxzoom',
'format',
'template'
]);
if (err) return callback(err);
// validate custom layers.
if (data.layers) {
function layervalidate(layers) {
if (!Array.isArray(layers))
return new Error('layers must be an array');
for (var i = 0; i < layers.length; i++) {
console.log(layers[i]);
if (/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\"":<>\?]/g.test(layers[i])) return new Error('Invalid characters in layer' + layers[i]);
}
}
var err = layervalidate(data.layers);
if (err) return callback(err);
}
if (data._bookmarks) {
// validate bookmarks.
var err = gazetteer.validate(data._bookmarks);
if (err) return callback(err);
}
style.toXML(data, function(err, xml) {
if (err) return callback(err);
if (!perm) return style.refresh(data, xml, callback);
var files = _(data.styles).map(function(v,k) { return { basename:k, data:v }; });
var filtered = tm.filterkeys(data, defaults);
// Bookmarks saved to separate file.
files.push({
basename: 'bookmarks.yml',
data: yaml.dump(data._bookmarks, null, 2)
});
// Styles are turned back into filename references.
filtered.styles = _(filtered.styles).keys();
files.push({
basename: 'project.yml',
data: yaml.dump(tm.sortkeys(filtered), null, 2)
});
// Include XML in files to be written.
files.push({ basename: 'project.xml', data: xml });
tm.writefiles(uri.dirname, files, function(err) {
if (err) return callback(err);
data._tmp = false;
style.refresh(data, xml, function(err, p) {
if (err) return callback(err);
style.thumbSave(id);
callback(null, p);
});
});
});
};
style.tmpid = function(id) {
return id ? id.indexOf('tmpstyle:') === 0 : style.examples['mapbox-studio-default-style'];
};
// Render data to XML.
style.toXML = function(data, callback) {
tilelive.load(data.source, function(err, backend) {
if (err) return callback(err);
// Include params to be written to XML.
var opts = [
'name',
'description',
'attribution',
'bounds',
'center',
'format',
'minzoom',
'maxzoom',
'source',
'template',
'interactivity_layer',
'legend'
].reduce(function(memo, key) {
if (key in data) switch(key) {
// @TODO this is backwards because carto currently only allows the
// TM1 abstrated representation of these params. Add support in
// carto for "literal" definition of these fields.
case 'interactivity_layer':
if (!backend.data) break;
if (!backend.data.vector_layers) break;
var fields = data.template.match(/{{([a-z0-9\-_]+)}}/ig);
if (!fields) break;
memo['interactivity'] = {
layer: data[key],
fields: fields.map(function(t) { return t.replace(/[{}]+/g,''); })
};
break;
default:
memo[key] = data[key];
break;
}
return memo;
}, {});
// Set projection for Mapnik.
opts.srs = tm.srs['900913'];
// Convert datatiles sources to mml layers.
var layers;
if (data.layers) {
layers = data.layers.map(function(l) {
return { id: l.split('.')[0], 'class': l.split('.')[1] }
});
// Normal vector source (both remote + local)
} else if (backend.data.vector_layers) {
layers = backend.data.vector_layers;
// Assume image source
} else {
layers = [{id:'_image'}];
}
opts.Layer = layers.map(function(layer) { return {
id:layer.id,
name:layer.id,
'class':layer['class'],
// Styles can provide a hidden _properties key with
// layer-specific property overrides. Current workaround to layer
// properties that could (?) eventually be controlled via carto.
properties: (data._properties && data._properties[layer.id]) || {},
srs:tm.srs['900913']
} });
opts.Stylesheet = _(data.styles).map(function(style,basename) { return {
id: basename,
data: style
}; });
try {
var xml = new carto.Renderer().render(tm.sortkeys(opts));
} catch(err) {
return callback(err);
}
return callback(null, xml);
});
};
// Light read of style info.
style.info = function(id, callback) {
var uri = tm.parse(id);
if (uri.protocol !== 'tmstyle:' && uri.protocol !== 'tmpstyle:')
return callback(new Error('Invalid style protocol'));
var project_path = path.join(uri.dirname,'project.yml');
return fs.readFile(project_path, 'utf8', function(err, data) {
if (err) return callback(err);
try { data = yaml.load(data); }
catch(err) { return callback(err); }
// Might be valid yaml and yet not be an object.
// Error out appropriately.
if (!(data instanceof Object)) {
return callback(new Error('Invalid YAML: ' + project_path));
}
// Migrate sources key to source.
if (Array.isArray(data.sources)) {
data.source = data.sources[0];
delete data.sources;
}
data.id = id;
data.source = (function(s) {
switch(s) {
// Legacy.
case 'mbstreets':
return 'mapbox:///mapbox.mapbox-streets-v2';
}
// Legacy.
if (/^mapbox:\/\/[^\/]/.test(s)) {
return s.replace('mapbox://', 'mapbox:///');
} else {
return s;
}
})(data.source);
// Provide a reference to the origin of the tmp project.
// If/when it is saved it will be used to copy the original
// project's files fully before saving.
data._tmp = style.tmpid(id) ? id : false;
var stylesheets = {};
readbookmarks();
function readbookmarks() {
// Initialize bookmarks here.
// They are not included in defaults object to keep from
// being written to the main project.yml file.
data._bookmarks = [];
var bookmarks_path = path.join(uri.dirname,'bookmarks.yml');
fs.readFile(bookmarks_path, 'utf8', function(err, bookmarks) {
if (err && err.code !== 'ENOENT') return callback(err);
// Bookmarks file is optional so continue style if not found.
if (err) { return readstyles(); }
try { data._bookmarks = yaml.load(bookmarks);}
catch(err) { return callback(err); }
readstyles();
});
};
function readstyles() {
if (!data.styles || !data.styles.length) {
data.styles = stylesheets;
return callback(null, _(data).defaults(defaults));
}
var basename = data.styles.shift();
fs.readFile(path.join(uri.dirname, basename), 'utf8', function(err, mss) {
if (err && err.code !== 'ENOENT') return callback(err);
if (mss) stylesheets[basename] = mss;
readstyles();
});
};
});
};
// Read style thumb.
style.thumb = function(id, callback) {
var uri = tm.parse(id);
return fs.readFile(path.join(uri.dirname,'.thumb.png'), function(err, buffer) {
if (err && err.code === 'ENOENT') {
return callback(new Error('Tile does not exist'));
};
return callback(null, buffer);
});
};
// Write style thumb
style.thumbSave = function(id, dest, callback) {
callback = callback || function() {};
var uri = tm.parse(id);
dest = dest || path.join(uri.dirname,'.thumb.png');
return style(id, function(err, source) {
if (err) return callback(err);
var center = source.data.center;
var xyz = sm.xyz([center[0],center[1],center[0],center[1]], center[2], false);
source.getTile(center[2],xyz.minX,xyz.minY, function(err, buffer) {
if (err) return callback(err);
callback(null, buffer);
// Save the thumb to disk.
fs.writeFile(dest, buffer, function(err) {
if (err && err.code !== 'ENOENT') console.error(err);
});
});
});
};
// Writes a tm2z tarball at filepath.
style.toPackage = function(id, dest, callback) {
if (!id)
return callback(new Error('id is required.'));
if (typeof dest !== 'string' && !dest.writable)
return callback(new Error('dest filepath or stream is required.'));
if (style.tmpid(id))
return callback(new Error('temporary style must be saved first'));
callback = callback || function() {};
var uri = tm.parse(id);
// If dest is an HTTP response object, set an appropriate header.
if (dest.writable && dest.setHeader) {
var basename = path.basename(uri.dirname, '.tm2');
dest.setHeader('content-disposition', 'attachment; filename="'+basename+'.tm2z"');
}
// @TODO this extra read/write step can be removed in the future.
// It is included to ensure the project.xml file is written, which
// cannot be said of early tm2 styles.
style(id, function(err, source) {
if (err) return callback(err);
style.save(source.data, function(err) {
if (err) return callback(err);
pack();
});
});
function pack() {
var writer = typeof dest === 'string'
? fstream.Writer({ path: dest, type: 'File' })
: dest;
var reader = fstream.Reader({
path: uri.dirname,
type: 'Directory',
// Write project.xml first so streaming readers can load it first.
sort: function(basename) {
return basename.toLowerCase() === 'project.xml' ? -1 : 1;
},
filter: function(info) {
if (info.props.basename[0] === '.') return false;
if (info.props.basename[0] === '_') return false;
if (info.props.type === 'Directory') return true;
if (info.props.basename.toLowerCase() === 'project.xml') return true;
var extname = path.extname(info.props.basename).toLowerCase();
if (extname === '.png') return true;
if (extname === '.jpg') return true;
if (extname === '.svg') return true;
}
})
.pipe(tar.Pack({ noProprietary:true }))
.pipe(zlib.Gzip())
.pipe(writer);
reader.on('error', callback);
writer.on('error', callback);
writer.on('end', callback);
}
};
// Set or get stats for a given zoom level.
style.stats = function(id, key, z, val) {
if (!cache[id]) return false;
if ('number' === typeof z && val) {
cache[id].stats = cache[id].stats || {};
cache[id].stats[key] = cache[id].stats[key] || {};
cache[id].stats[key][z] = cache[id].stats[key][z] || { count:0 };
var stats = cache[id].stats[key][z];
stats.min = Math.min(val, stats.min||Infinity);
stats.max = Math.max(val, stats.max||0);
stats.avg = stats.count ? ((stats.avg * stats.count) + val) / (stats.count + 1) : val;
stats.count++;
}
return cache[id].stats[key];
};
// Set or get tile serving errors.
style.error = function(id, err) {
if (!cache[id]) return false;
cache[id].errors = cache[id].errors || [];
if (err && cache[id].errors.indexOf(err.message) === -1) {
cache[id].errors.push(err.message);
}
return cache[id].errors;
};
style.upload = function(id, callback) {
try {
var oauth = tm.oauth();
} catch(err) {
return callback(err);
}
if (style.tmpid(id))
return callback(new Error('Style must be saved first'));
style.info(id, function(err, info) {
if (err) return callback(err);
try {
var mapid = info._prefs.mapid || tm.mapid();
} catch(err) {
return callback(err);
}
var pckage = path.join(tm.config().cache, 'package-' + mapid + '.tm2z');
style.toPackage(info.id, pckage, function(err) {
if (err) return callback(err);
createProg();
});
function createProg() {
var prog;
try {
prog = upload({
file: pckage,
account: oauth.account,
accesstoken: oauth.accesstoken,
mapid: mapid,
mapbox: tm.config().mapboxauth
});
} catch(err) {
return callback(err);
}
prog.once('error', function(err) {
return callback(err);
});
prog.once('finished', mapSaved);
return prog;
}
function mapSaved() {
info._prefs.mapid = mapid;
style.save(info, function(err) {
if (err) return callback(err);
fs.unlink(pckage, function(err) {
if (err) return callback(err);
return callback(null, info);
});
});
}
});
};
// Hash of ids to tmp example styles.
style.examples = {};
style.examples['mapbox-studio-default-style'] = 'tmpstyle://' + tm.join(path.dirname(require.resolve('mapbox-studio-default-style')));
style.examples['osm-bright'] = 'tmpstyle://' + tm.join(path.dirname(require.resolve('osm-bright')));
style.examples['mapbox-outdoors'] = 'tmpstyle://' + tm.join(path.dirname(require.resolve('mapbox-outdoors')));
style.examples['satellite-afternoon'] = 'tmpstyle://' + tm.join(path.dirname(require.resolve('satellite-afternoon')));
|
lib/style.js
|
var _ = require('underscore');
var carto = require('carto');
var crypto = require('crypto');
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var Vector = require('tilelive-vector');
var sm = new (require('sphericalmercator'));
var yaml = require('js-yaml');
var tm = require('./tm');
var mapnik = require('mapnik');
var fstream = require('fstream');
var tar = require('tar');
var zlib = require('zlib');
var tilelive = require('tilelive');
var url = require('url');
var upload = require('mapbox-upload');
var task = require('./task');
var gazetteer = require('gazetteer');
var defaults = {
name:'',
description:'',
attribution:'',
source:'',
styles:{},
center:[0,0,3],
bounds:[-180,-85.0511,180,85.0511],
minzoom:0,
maxzoom:22,
format:'png8:m=h',
template:'',
interactivity_layer:'',
layers:null,
_properties: {},
_prefs: {
saveCenter: true,
mapid: ''
}
};
var cache = {};
module.exports = style;
tilelive.protocols['tmstyle:'] = style;
tilelive.protocols['tmpstyle:'] = style;
function style(arg, callback) {
if ('string' !== typeof arg) {
var id = url.format(arg);
var uri = arg;
} else {
var id = arg;
var uri = tm.parse(arg);
}
if (!uri || (uri.protocol !== 'tmstyle:' && uri.protocol !== 'tmpstyle:'))
return callback(new Error('Invalid style protocol'));
if (cache[id]) return callback(null, cache[id]);
// Reading.
style.info(id, function(err, data) {
if (err) return callback(err);
style.toXML(data, function(err, xml) {
if (err) return callback(err);
style.refresh(data, xml, callback);
});
});
};
// Load or refresh the relevant source using specified data + xml.
style.refresh = function(data, xml, callback) {
var id = data.id;
var uri = tm.parse(data.id);
var done = function(err, p) {
if (err) return callback(err);
cache[id] = cache[id] || p;
cache[id].data = data;
cache[id].data.background = _('rgba(<%=r%>,<%=g%>,<%=b%>,<%=(a/255).toFixed(2)%>)').template(cache[id]._map.background);
cache[id].stats = {};
cache[id].errors = [];
return callback(null, cache[id]);
};
var opts = {};
opts.xml = xml;
opts.base = uri.dirname;
opts.scale = data.scale || 1;
opts.source = 'mapbox:///mapbox.mapbox-streets-v2';
return cache[id] ? cache[id].update(opts, done) : new Vector(opts, done);
};
// Clear reference to cached style.
style.clear = function(id) {
delete cache[id];
};
// Writing.
style.save = function(data, callback) {
var id = data.id;
var uri = tm.parse(data.id);
var perm = !style.tmpid(id);
// Saving a tmp project permanently to a new location.
// Copy tmp project first before saving.
if (perm && data._tmp) {
var src = tm.parse(data._tmp).dirname;
var dst = uri.dirname;
var exclude = [ /^[\.\_]/, 'package.json' ];
return tm.copydir(src, dst, exclude, function(err) {
if (err) return callback(err);
data._tmp = false;
style.save(data, callback);
});
}
data = _(data).defaults(defaults);
data._tmp = data._tmp || (style.tmpid(id) ? id : false);
// validate key info keys.
var err = tilelive.verify(data, [
'name',
'description',
'attribution',
'source',
'center',
'bounds',
'minzoom',
'maxzoom',
'format',
'template'
]);
if (err) return callback(err);
if (data._bookmarks) {
// validate bookmarks.
var err = gazetteer.validate(data._bookmarks);
if (err) return callback(err);
}
style.toXML(data, function(err, xml) {
if (err) return callback(err);
if (!perm) return style.refresh(data, xml, callback);
var files = _(data.styles).map(function(v,k) { return { basename:k, data:v }; });
var filtered = tm.filterkeys(data, defaults);
// Bookmarks saved to separate file.
files.push({
basename: 'bookmarks.yml',
data: yaml.dump(data._bookmarks, null, 2)
});
// Styles are turned back into filename references.
filtered.styles = _(filtered.styles).keys();
files.push({
basename: 'project.yml',
data: yaml.dump(tm.sortkeys(filtered), null, 2)
});
// Include XML in files to be written.
files.push({ basename: 'project.xml', data: xml });
tm.writefiles(uri.dirname, files, function(err) {
if (err) return callback(err);
data._tmp = false;
style.refresh(data, xml, function(err, p) {
if (err) return callback(err);
style.thumbSave(id);
callback(null, p);
});
});
});
};
style.tmpid = function(id) {
return id ? id.indexOf('tmpstyle:') === 0 : style.examples['mapbox-studio-default-style'];
};
// Render data to XML.
style.toXML = function(data, callback) {
tilelive.load(data.source, function(err, backend) {
if (err) return callback(err);
// Include params to be written to XML.
var opts = [
'name',
'description',
'attribution',
'bounds',
'center',
'format',
'minzoom',
'maxzoom',
'source',
'template',
'interactivity_layer',
'legend'
].reduce(function(memo, key) {
if (key in data) switch(key) {
// @TODO this is backwards because carto currently only allows the
// TM1 abstrated representation of these params. Add support in
// carto for "literal" definition of these fields.
case 'interactivity_layer':
if (!backend.data) break;
if (!backend.data.vector_layers) break;
var fields = data.template.match(/{{([a-z0-9\-_]+)}}/ig);
if (!fields) break;
memo['interactivity'] = {
layer: data[key],
fields: fields.map(function(t) { return t.replace(/[{}]+/g,''); })
};
break;
default:
memo[key] = data[key];
break;
}
return memo;
}, {});
// Set projection for Mapnik.
opts.srs = tm.srs['900913'];
// Convert datatiles sources to mml layers.
var layers;
if (data.layers) {
layers = data.layers.map(function(l) {
return { id: l.split('.')[0], 'class': l.split('.')[1] }
});
// Normal vector source (both remote + local)
} else if (backend.data.vector_layers) {
layers = backend.data.vector_layers;
// Assume image source
} else {
layers = [{id:'_image'}];
}
opts.Layer = layers.map(function(layer) { return {
id:layer.id,
name:layer.id,
'class':layer['class'],
// Styles can provide a hidden _properties key with
// layer-specific property overrides. Current workaround to layer
// properties that could (?) eventually be controlled via carto.
properties: (data._properties && data._properties[layer.id]) || {},
srs:tm.srs['900913']
} });
opts.Stylesheet = _(data.styles).map(function(style,basename) { return {
id: basename,
data: style
}; });
try {
var xml = new carto.Renderer().render(tm.sortkeys(opts));
} catch(err) {
return callback(err);
}
return callback(null, xml);
});
};
// Light read of style info.
style.info = function(id, callback) {
var uri = tm.parse(id);
if (uri.protocol !== 'tmstyle:' && uri.protocol !== 'tmpstyle:')
return callback(new Error('Invalid style protocol'));
var project_path = path.join(uri.dirname,'project.yml');
return fs.readFile(project_path, 'utf8', function(err, data) {
if (err) return callback(err);
try { data = yaml.load(data); }
catch(err) { return callback(err); }
// Might be valid yaml and yet not be an object.
// Error out appropriately.
if (!(data instanceof Object)) {
return callback(new Error('Invalid YAML: ' + project_path));
}
// Migrate sources key to source.
if (Array.isArray(data.sources)) {
data.source = data.sources[0];
delete data.sources;
}
data.id = id;
data.source = (function(s) {
switch(s) {
// Legacy.
case 'mbstreets':
return 'mapbox:///mapbox.mapbox-streets-v2';
}
// Legacy.
if (/^mapbox:\/\/[^\/]/.test(s)) {
return s.replace('mapbox://', 'mapbox:///');
} else {
return s;
}
})(data.source);
// Provide a reference to the origin of the tmp project.
// If/when it is saved it will be used to copy the original
// project's files fully before saving.
data._tmp = style.tmpid(id) ? id : false;
var stylesheets = {};
readbookmarks();
function readbookmarks() {
// Initialize bookmarks here.
// They are not included in defaults object to keep from
// being written to the main project.yml file.
data._bookmarks = [];
var bookmarks_path = path.join(uri.dirname,'bookmarks.yml');
fs.readFile(bookmarks_path, 'utf8', function(err, bookmarks) {
if (err && err.code !== 'ENOENT') return callback(err);
// Bookmarks file is optional so continue style if not found.
if (err) { return readstyles(); }
try { data._bookmarks = yaml.load(bookmarks);}
catch(err) { return callback(err); }
readstyles();
});
};
function readstyles() {
if (!data.styles || !data.styles.length) {
data.styles = stylesheets;
return callback(null, _(data).defaults(defaults));
}
var basename = data.styles.shift();
fs.readFile(path.join(uri.dirname, basename), 'utf8', function(err, mss) {
if (err && err.code !== 'ENOENT') return callback(err);
if (mss) stylesheets[basename] = mss;
readstyles();
});
};
});
};
// Read style thumb.
style.thumb = function(id, callback) {
var uri = tm.parse(id);
return fs.readFile(path.join(uri.dirname,'.thumb.png'), function(err, buffer) {
if (err && err.code === 'ENOENT') {
return callback(new Error('Tile does not exist'));
};
return callback(null, buffer);
});
};
// Write style thumb
style.thumbSave = function(id, dest, callback) {
callback = callback || function() {};
var uri = tm.parse(id);
dest = dest || path.join(uri.dirname,'.thumb.png');
return style(id, function(err, source) {
if (err) return callback(err);
var center = source.data.center;
var xyz = sm.xyz([center[0],center[1],center[0],center[1]], center[2], false);
source.getTile(center[2],xyz.minX,xyz.minY, function(err, buffer) {
if (err) return callback(err);
callback(null, buffer);
// Save the thumb to disk.
fs.writeFile(dest, buffer, function(err) {
if (err && err.code !== 'ENOENT') console.error(err);
});
});
});
};
// Writes a tm2z tarball at filepath.
style.toPackage = function(id, dest, callback) {
if (!id)
return callback(new Error('id is required.'));
if (typeof dest !== 'string' && !dest.writable)
return callback(new Error('dest filepath or stream is required.'));
if (style.tmpid(id))
return callback(new Error('temporary style must be saved first'));
callback = callback || function() {};
var uri = tm.parse(id);
// If dest is an HTTP response object, set an appropriate header.
if (dest.writable && dest.setHeader) {
var basename = path.basename(uri.dirname, '.tm2');
dest.setHeader('content-disposition', 'attachment; filename="'+basename+'.tm2z"');
}
// @TODO this extra read/write step can be removed in the future.
// It is included to ensure the project.xml file is written, which
// cannot be said of early tm2 styles.
style(id, function(err, source) {
if (err) return callback(err);
style.save(source.data, function(err) {
if (err) return callback(err);
pack();
});
});
function pack() {
var writer = typeof dest === 'string'
? fstream.Writer({ path: dest, type: 'File' })
: dest;
var reader = fstream.Reader({
path: uri.dirname,
type: 'Directory',
// Write project.xml first so streaming readers can load it first.
sort: function(basename) {
return basename.toLowerCase() === 'project.xml' ? -1 : 1;
},
filter: function(info) {
if (info.props.basename[0] === '.') return false;
if (info.props.basename[0] === '_') return false;
if (info.props.type === 'Directory') return true;
if (info.props.basename.toLowerCase() === 'project.xml') return true;
var extname = path.extname(info.props.basename).toLowerCase();
if (extname === '.png') return true;
if (extname === '.jpg') return true;
if (extname === '.svg') return true;
}
})
.pipe(tar.Pack({ noProprietary:true }))
.pipe(zlib.Gzip())
.pipe(writer);
reader.on('error', callback);
writer.on('error', callback);
writer.on('end', callback);
}
};
// Set or get stats for a given zoom level.
style.stats = function(id, key, z, val) {
if (!cache[id]) return false;
if ('number' === typeof z && val) {
cache[id].stats = cache[id].stats || {};
cache[id].stats[key] = cache[id].stats[key] || {};
cache[id].stats[key][z] = cache[id].stats[key][z] || { count:0 };
var stats = cache[id].stats[key][z];
stats.min = Math.min(val, stats.min||Infinity);
stats.max = Math.max(val, stats.max||0);
stats.avg = stats.count ? ((stats.avg * stats.count) + val) / (stats.count + 1) : val;
stats.count++;
}
return cache[id].stats[key];
};
// Set or get tile serving errors.
style.error = function(id, err) {
if (!cache[id]) return false;
cache[id].errors = cache[id].errors || [];
if (err && cache[id].errors.indexOf(err.message) === -1) {
cache[id].errors.push(err.message);
}
return cache[id].errors;
};
style.upload = function(id, callback) {
try {
var oauth = tm.oauth();
} catch(err) {
return callback(err);
}
if (style.tmpid(id))
return callback(new Error('Style must be saved first'));
style.info(id, function(err, info) {
if (err) return callback(err);
try {
var mapid = info._prefs.mapid || tm.mapid();
} catch(err) {
return callback(err);
}
var pckage = path.join(tm.config().cache, 'package-' + mapid + '.tm2z');
style.toPackage(info.id, pckage, function(err) {
if (err) return callback(err);
createProg();
});
function createProg() {
var prog;
try {
prog = upload({
file: pckage,
account: oauth.account,
accesstoken: oauth.accesstoken,
mapid: mapid,
mapbox: tm.config().mapboxauth
});
} catch(err) {
return callback(err);
}
prog.once('error', function(err) {
return callback(err);
});
prog.once('finished', mapSaved);
return prog;
}
function mapSaved() {
info._prefs.mapid = mapid;
style.save(info, function(err) {
if (err) return callback(err);
fs.unlink(pckage, function(err) {
if (err) return callback(err);
return callback(null, info);
});
});
}
});
};
// Hash of ids to tmp example styles.
style.examples = {};
style.examples['mapbox-studio-default-style'] = 'tmpstyle://' + tm.join(path.dirname(require.resolve('mapbox-studio-default-style')));
style.examples['osm-bright'] = 'tmpstyle://' + tm.join(path.dirname(require.resolve('osm-bright')));
style.examples['mapbox-outdoors'] = 'tmpstyle://' + tm.join(path.dirname(require.resolve('mapbox-outdoors')));
style.examples['satellite-afternoon'] = 'tmpstyle://' + tm.join(path.dirname(require.resolve('satellite-afternoon')));
|
add validation to layer naming
|
lib/style.js
|
add validation to layer naming
|
<ide><path>ib/style.js
<ide> 'template'
<ide> ]);
<ide> if (err) return callback(err);
<add>
<add> // validate custom layers.
<add> if (data.layers) {
<add> function layervalidate(layers) {
<add> if (!Array.isArray(layers))
<add> return new Error('layers must be an array');
<add>
<add> for (var i = 0; i < layers.length; i++) {
<add> console.log(layers[i]);
<add> if (/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\"":<>\?]/g.test(layers[i])) return new Error('Invalid characters in layer' + layers[i]);
<add> }
<add> }
<add> var err = layervalidate(data.layers);
<add> if (err) return callback(err);
<add> }
<ide>
<ide> if (data._bookmarks) {
<ide> // validate bookmarks.
|
|
Java
|
apache-2.0
|
46e0528a1b7edff8daf7e8bffab008ce5d8d7efd
| 0 |
zhangwei5095/memcached-session-manager,mosoft521/memcached-session-manager,hongzhenglin/memcached-session-manager-1,xloye/memcached-session-manager,magro/memcached-session-manager,shelsonjava/memcached-session-manager,magro/memcached-session-manager,KihwanCheon/memcached-session-manager,mosoft521/memcached-session-manager,xloye/memcached-session-manager,KihwanCheon/memcached-session-manager,fengshao0907/memcached-session-manager,hongzhenglin/memcached-session-manager-1,fengshao0907/memcached-session-manager,shelsonjava/memcached-session-manager,zhangwei5095/memcached-session-manager
|
/*
* Copyright 2009 Martin Grotzke
*
* 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.javakaffee.web.msm;
import static de.javakaffee.web.msm.SessionValidityInfo.createValidityInfoKeyName;
import static de.javakaffee.web.msm.integration.TestServlet.PARAM_REMOVE;
import static de.javakaffee.web.msm.integration.TestServlet.PATH_INVALIDATE;
import static de.javakaffee.web.msm.integration.TestUtils.*;
import static org.testng.Assert.*;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nonnull;
import net.spy.memcached.ConnectionFactory;
import net.spy.memcached.DefaultConnectionFactory;
import net.spy.memcached.MemcachedClient;
import org.apache.catalina.Container;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Session;
import org.apache.catalina.startup.Embedded;
import org.apache.http.HttpException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.thimbleware.jmemcached.MemCacheDaemon;
import de.javakaffee.web.msm.MemcachedNodesManager.MemcachedClientCallback;
import de.javakaffee.web.msm.MemcachedSessionService.SessionManager;
import de.javakaffee.web.msm.integration.TestUtils;
import de.javakaffee.web.msm.integration.TestUtils.Response;
import de.javakaffee.web.msm.integration.TestUtils.SessionAffinityMode;
/**
* Integration test testing basic session manager functionality.
*
* @author <a href="mailto:[email protected]">Martin Grotzke</a>
* @version $Id$
*/
public abstract class MemcachedSessionManagerIntegrationTest {
private static final Log LOG = LogFactory.getLog( MemcachedSessionManagerIntegrationTest.class );
private static final String GROUP_WITHOUT_NODE_ID = "withoutNodeId";
private MemCacheDaemon<?> _daemon;
private MemcachedClient _memcached;
private Embedded _tomcat1;
private int _portTomcat1;
private final String _memcachedNodeId = "n1";
private DefaultHttpClient _httpClient;
private int _memcachedPort;
private final MemcachedClientCallback _memcachedClientCallback = new MemcachedClientCallback() {
@Override
public Object get(final String key) {
return _memcached.get(key);
}
};
@BeforeMethod
public void setUp(final Method testMethod) throws Throwable {
_portTomcat1 = 18888;
_memcachedPort = 21211;
final InetSocketAddress address = new InetSocketAddress( "localhost", _memcachedPort );
_daemon = createDaemon( address );
_daemon.start();
final String[] testGroups = testMethod.getAnnotation(Test.class).groups();
final String nodePrefix = testGroups.length == 0 || !GROUP_WITHOUT_NODE_ID.equals(testGroups[0]) ? _memcachedNodeId + ":" : "";
final String memcachedNodes = nodePrefix + "localhost:" + _memcachedPort;
try {
System.setProperty( "org.apache.catalina.startup.EXIT_ON_INIT_FAILURE", "true" );
_tomcat1 = getTestUtils().createCatalina( _portTomcat1, memcachedNodes, "app1" );
getManager( _tomcat1 ).setSticky( true );
_tomcat1.start();
} catch ( final Throwable e ) {
LOG.error( "could not start tomcat.", e );
throw e;
}
_memcached = createMemcachedClient( memcachedNodes, address );
_httpClient = new DefaultHttpClient();
}
private MemcachedClient createMemcachedClient( final String memcachedNodes, final InetSocketAddress address ) throws IOException, InterruptedException {
final MemcachedNodesManager nodesManager = MemcachedNodesManager.createFor(memcachedNodes, null, _memcachedClientCallback);
final ConnectionFactory cf = nodesManager.isEncodeNodeIdInSessionId()
? new SuffixLocatorConnectionFactory( nodesManager, nodesManager.getSessionIdFormat(), Statistics.create(), 1000 )
: new DefaultConnectionFactory();
final MemcachedClient result = new MemcachedClient( cf, Arrays.asList( address ) );
// Wait a little bit, so that the memcached client can connect and is ready when test starts
Thread.sleep( 100 );
return result;
}
@AfterMethod
public void tearDown() throws Exception {
_memcached.shutdown();
_tomcat1.stop();
_httpClient.getConnectionManager().shutdown();
_daemon.stop();
}
/**
* Test for issue 106: Session not updated in memcached when only a session attribute was removed
* http://code.google.com/p/memcached-session-manager/issues/detail?id=106
*/
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testSessionUpdatedInMemcachedWhenSessionAttributeIsRemovedIssue106( final SessionAffinityMode sessionAffinity ) throws IOException, InterruptedException, HttpException {
setStickyness(sessionAffinity);
final String key = "foo";
final String value = "bar";
final String sessionId1 = post( _httpClient, _portTomcat1, null, key, value ).getSessionId();
assertNotNull( sessionId1, "No session created." );
Response response = get( _httpClient, _portTomcat1, sessionId1 );
assertEquals( response.getSessionId(), sessionId1 );
assertEquals( response.get( key ), value );
final Map<String, String> params = asMap( PARAM_REMOVE, key );
response = get( _httpClient, _portTomcat1, "/", sessionId1, params );
assertEquals( response.getSessionId(), sessionId1 );
assertNull( response.get( key ) );
// also the next request must not include this session attribute
response = get( _httpClient, _portTomcat1, sessionId1 );
assertEquals( response.getSessionId(), sessionId1 );
assertNull( response.get( key ) );
}
@Test( enabled = true )
public void testConfiguredMemcachedNodeId() throws IOException, InterruptedException, HttpException {
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
/*
* test that we have the configured memcachedNodeId in the sessionId,
* the session id looks like "<sid>-<memcachedId>[.<jvmRoute>]"
*/
final String nodeId = sessionId1.substring( sessionId1.indexOf( '-' ) + 1, sessionId1.indexOf( '.' ) );
assertEquals( _memcachedNodeId, nodeId, "Invalid memcached node id" );
}
/**
* Related to issue/feature 105 (single memcached node without node id): this shall be possible
* and the generated session id must not contain a node id.
*/
@Test( enabled = true, groups = GROUP_WITHOUT_NODE_ID )
public void testSessionIdIsNotChangedIfSingleNodeWithNoMemcachedNodeIdConfigured() throws IOException, InterruptedException, HttpException {
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
assertTrue( sessionId1.indexOf( '-' ) == -1 );
}
/**
* Related to issue/feature 105 (single memcached node without node id): the session must be
* found on a second request.
*/
@Test( enabled = true, groups = GROUP_WITHOUT_NODE_ID, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testSessionFoundIfSingleNodeWithNoMemcachedNodeIdConfigured( final SessionAffinityMode sessionAffinity ) throws IOException, InterruptedException, HttpException {
setStickyness(sessionAffinity);
final String key = "foo";
final String value = "bar";
final String sessionId1 = post( _httpClient, _portTomcat1, null, key, value ).getSessionId();
assertNotNull( sessionId1, "No session created." );
final Response response = get( _httpClient, _portTomcat1, sessionId1 );
final String sessionId2 = response.getSessionId();
assertEquals( sessionId2, sessionId1 );
/* check session attributes could be read
*/
final String actualValue = response.get( key );
assertEquals( value, actualValue );
}
@Test( enabled = true )
public void testSessionIdJvmRouteCompatibility() throws IOException, InterruptedException, HttpException {
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
assertTrue( sessionId1.matches( "[^-.]+-[^.]+(\\.[\\w]+)?" ),
"Invalid session format, must be <sid>-<memcachedId>[.<jvmRoute>]." );
}
/**
* Tests, that session ids with an invalid format (not containing the
* memcached id) do not cause issues. Instead, we want to retrieve a new
* session id.
*
* @throws IOException
* @throws InterruptedException
* @throws HttpException
*/
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testInvalidSessionId( final SessionAffinityMode sessionAffinity ) throws IOException, InterruptedException, HttpException {
setStickyness(sessionAffinity);
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, "12345" );
assertNotNull( sessionId1, "No session created." );
assertTrue( sessionId1.indexOf( '-' ) > -1, "Invalid session id format" );
}
private void setStickyness(final SessionAffinityMode sessionAffinity) {
if(!sessionAffinity.isSticky()) {
getEngine(_tomcat1).setJvmRoute(null);
}
getManager( _tomcat1 ).setSticky( sessionAffinity.isSticky() );
}
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testSessionAvailableInMemcached( final SessionAffinityMode sessionAffinity ) throws IOException, InterruptedException, HttpException {
setStickyness(sessionAffinity);
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
Thread.sleep( 50 );
assertNotNull( _memcached.get( sessionId1 ), "Session not available in memcached." );
}
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testExpiredSessionRemovedFromMemcached( @Nonnull final SessionAffinityMode sessionAffinity ) throws IOException, InterruptedException, HttpException {
setStickyness(sessionAffinity);
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
waitForSessionExpiration( sessionAffinity.isSticky() );
assertNull( _memcached.get( sessionId1 ), "Expired session still existing in memcached" );
}
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testInvalidatedSessionRemovedFromMemcached( @Nonnull final SessionAffinityMode sessionAffinity ) throws IOException, InterruptedException, HttpException {
setStickyness(sessionAffinity);
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
final Response response = get( _httpClient, _portTomcat1, PATH_INVALIDATE, sessionId1 );
assertNull( response.getResponseSessionId() );
assertEquals(_daemon.getCache().getGetMisses(), 1); // 1 is ok
assertNull( _memcached.get( sessionId1 ), "Invalidated session still existing in memcached" );
if(!sessionAffinity.isSticky()) {
assertNull( _memcached.get(createValidityInfoKeyName( sessionId1 )), "ValidityInfo for invalidated session still exists in memcached." );
}
}
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testInvalidSessionNotFound( @Nonnull final SessionAffinityMode sessionAffinity ) throws IOException, InterruptedException, HttpException {
setStickyness(sessionAffinity);
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
/*
* wait some time, as processExpires runs every second and the
* maxInactiveTime is set to 1 sec...
*/
Thread.sleep( 2100 );
final String sessionId2 = makeRequest( _httpClient, _portTomcat1, sessionId1 );
assertNotSame( sessionId1, sessionId2, "Expired session returned." );
}
/**
* Tests, that for a session that was not sent to memcached (because it's attributes
* were not modified), the expiration is updated so that they don't expire in memcached
* before they expire in tomcat.
*
* @throws Exception if something goes wrong with the http communication with tomcat
*/
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testExpirationOfSessionsInMemcachedIfBackupWasSkippedSimple( final SessionAffinityMode stickyness ) throws Exception {
final SessionManager manager = getManager( _tomcat1 );
manager.setSticky( stickyness.isSticky() );
// Wait some time for reconfiguration
waitForReconnect(manager.getMemcachedSessionService().getMemcached(), 1, 500);
// set to 1 sec above (in setup), default is 10 seconds
final int delay = manager.getContainer().getBackgroundProcessorDelay();
manager.setMaxInactiveInterval( delay * 4 );
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
assertNotNull( _memcached.get( sessionId1 ), "Session not available in memcached." );
/* after 2 seconds make another request without changing the session, so that
* it's not sent to memcached
*/
Thread.sleep( TimeUnit.SECONDS.toMillis( delay * 2 ) );
assertEquals( makeRequest( _httpClient, _portTomcat1, sessionId1 ), sessionId1, "SessionId should be the same" );
/* after another 3 seconds check that the session is still alive in memcached,
* this would have been expired without an updated expiration
*/
Thread.sleep( TimeUnit.SECONDS.toMillis( delay * 3 ) );
assertNotNull( _memcached.get( sessionId1 ), "Session should still exist in memcached." );
/* after another >1 second (4 seconds since the last request)
* the session must be expired in memcached
*/
Thread.sleep( TimeUnit.SECONDS.toMillis( delay ) + 500 ); // +1000 just to be sure that we're >4 secs
assertNotSame( makeRequest( _httpClient, _portTomcat1, sessionId1 ), sessionId1,
"The sessionId should have changed due to expired sessin" );
}
public static void waitForReconnect( final MemcachedClient client, final int expectedNumServers, final long timeToWait )
throws InterruptedException, RuntimeException {
final long start = System.currentTimeMillis();
while( System.currentTimeMillis() < start + timeToWait ) {
if ( client.getAvailableServers().size() >= expectedNumServers ) {
return;
}
Thread.sleep( 20 );
}
throw new RuntimeException( "MemcachedClient did not reconnect after " + timeToWait + " millis." );
}
/**
* Tests update of session expiration in memcached (like {@link #testExpirationOfSessionsInMemcachedIfBackupWasSkippedSimple()})
* but for the scenario where many readonly requests occur: in this case, we cannot just use
* <em>maxInactiveInterval - secondsSinceLastBackup</em> (in {@link MemcachedSessionService#updateExpirationInMemcached})
* to determine if an expiration update is required, but we must use the last expiration time sent to memcached.
*
* @throws Exception if something goes wrong with the http communication with tomcat
*/
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testExpirationOfSessionsInMemcachedIfBackupWasSkippedManyReadonlyRequests( final SessionAffinityMode stickyness ) throws Exception {
final SessionManager manager = getManager( _tomcat1 );
manager.setSticky( stickyness.isSticky() );
// set to 1 sec above (in setup), default is 10 seconds
final int delay = manager.getContainer().getBackgroundProcessorDelay();
manager.setMaxInactiveInterval( delay * 4 );
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
assertNotNull( _memcached.get( sessionId1 ), "Session not available in memcached." );
/* after 3 seconds make another request without changing the session, so that
* it's not sent to memcached
*/
Thread.sleep( TimeUnit.SECONDS.toMillis( delay * 3 ) );
assertEquals( makeRequest( _httpClient, _portTomcat1, sessionId1 ), sessionId1, "SessionId should be the same" );
assertNotNull( _memcached.get( sessionId1 ), "Session should still exist in memcached." );
/* after another 3 seconds make another request without changing the session
*/
Thread.sleep( TimeUnit.SECONDS.toMillis( delay * 3 ) );
assertEquals( makeRequest( _httpClient, _portTomcat1, sessionId1 ), sessionId1, "SessionId should be the same" );
assertNotNull( _memcached.get( sessionId1 ), "Session should still exist in memcached." );
/* after another nearly 4 seconds (maxInactiveInterval) check that the session is still alive in memcached,
* this would have been expired without an updated expiration
*/
Thread.sleep( TimeUnit.SECONDS.toMillis( manager.getMaxInactiveInterval() ) - 500 );
assertNotNull( _memcached.get( sessionId1 ), "Session should still exist in memcached." );
/* after another second in sticky mode (more than 4 seconds since the last request), or an two times the
* maxInactiveInterval in non-sticky mode (we must keep sessions in memcached with double expirationtime)
* the session must be expired in memcached
*/
Thread.sleep( TimeUnit.SECONDS.toMillis( delay ) + 500 );
assertNotSame( makeRequest( _httpClient, _portTomcat1, sessionId1 ), sessionId1,
"The sessionId should have changed due to expired sessin" );
}
/**
* Test for issue #49:
* Sessions not associated with a memcached node don't get associated as soon as a memcached is available
* @throws InterruptedException
* @throws IOException
* @throws TimeoutException
* @throws ExecutionException
*/
@Test( enabled = true )
public void testNotAssociatedSessionGetsAssociatedIssue49() throws InterruptedException, IOException, ExecutionException, TimeoutException {
_daemon.stop();
final SessionManager manager = getManager( _tomcat1 );
manager.setMaxInactiveInterval( 5 );
manager.setSticky( true );
final SessionIdFormat sessionIdFormat = new SessionIdFormat();
final Session session = manager.createSession( null );
assertNull( sessionIdFormat.extractMemcachedId( session.getId() ) );
_daemon.start();
// Wait so that the daemon will be available and the client can reconnect (async get didn't do the trick)
Thread.sleep( 4000 );
final String newSessionId = manager.getMemcachedSessionService().changeSessionIdOnMemcachedFailover( session.getId() );
assertNotNull( newSessionId );
assertEquals( newSessionId, session.getId() );
assertEquals( sessionIdFormat.extractMemcachedId( newSessionId ), _memcachedNodeId );
}
/**
* Test for issue #60 (Add possibility to disable msm at runtime): disable msm
*/
@Test( enabled = true )
public void testDisableMsmAtRuntime() throws InterruptedException, IOException, ExecutionException, TimeoutException, LifecycleException, HttpException {
final SessionManager manager = getManager( _tomcat1 );
manager.setSticky( true );
// disable msm, shutdown our server and our client
manager.setEnabled( false );
_memcached.shutdown();
_daemon.stop();
checkSessionFunctionalityWithMsmDisabled();
}
/**
* Test for issue #60 (Add possibility to disable msm at runtime): start msm disabled and afterwards enable
*/
@Test( enabled = true )
public void testStartMsmDisabled() throws InterruptedException, IOException, ExecutionException, TimeoutException, LifecycleException, HttpException {
// shutdown our server and our client
_memcached.shutdown();
_daemon.stop();
// start a new tomcat with msm initially disabled
_tomcat1.stop();
Thread.sleep( 500 );
final String memcachedNodes = _memcachedNodeId + ":localhost:" + _memcachedPort;
_tomcat1 = getTestUtils().createCatalina( _portTomcat1, memcachedNodes, "app1" );
final SessionManager manager = getManager( _tomcat1 );
manager.setSticky( true );
manager.setEnabled( false );
_tomcat1.start();
LOG.info( "Waiting, check logs to see if the client causes any 'Connection refused' logging..." );
Thread.sleep( 1000 );
// some basic tests for session functionality
checkSessionFunctionalityWithMsmDisabled();
// start memcached, client and reenable msm
_daemon.start();
_memcached = createMemcachedClient( memcachedNodes, new InetSocketAddress( "localhost", _memcachedPort ) );
manager.setEnabled( true );
// Wait a little bit, so that msm's memcached client can connect and is ready when test starts
Thread.sleep( 100 );
// memcached based stuff should work again
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
assertNotNull( new SessionIdFormat().extractMemcachedId( sessionId1 ), "memcached node id missing with msm switched to enabled" );
Thread.sleep( 50 );
assertNotNull( _memcached.get( sessionId1 ), "Session not available in memcached." );
waitForSessionExpiration( true );
assertNull( _memcached.get( sessionId1 ), "Expired session still existing in memcached" );
}
abstract TestUtils getTestUtils();
private void checkSessionFunctionalityWithMsmDisabled() throws IOException, HttpException, InterruptedException {
assertTrue( getManager( _tomcat1 ).getMemcachedSessionService().isSticky() );
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
assertNull( new SessionIdFormat().extractMemcachedId( sessionId1 ), "Got a memcached node id, even with msm disabled." );
waitForSessionExpiration( true );
final String sessionId2 = makeRequest( _httpClient, _portTomcat1, sessionId1 );
assertNotSame( sessionId2, sessionId1, "SessionId not changed." );
}
private void waitForSessionExpiration(final boolean sticky) throws InterruptedException {
final SessionManager manager = getManager( _tomcat1 );
assertEquals( manager.getMemcachedSessionService().isSticky(), sticky );
final Container container = manager.getContainer();
final long timeout = TimeUnit.SECONDS.toMillis(
sticky ? container.getBackgroundProcessorDelay() + manager.getMaxInactiveInterval()
: 2 * manager.getMaxInactiveInterval() ) + 1000;
Thread.sleep( timeout );
}
}
|
core/src/test/java/de/javakaffee/web/msm/MemcachedSessionManagerIntegrationTest.java
|
/*
* Copyright 2009 Martin Grotzke
*
* 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.javakaffee.web.msm;
import static de.javakaffee.web.msm.SessionValidityInfo.createValidityInfoKeyName;
import static de.javakaffee.web.msm.integration.TestServlet.PARAM_REMOVE;
import static de.javakaffee.web.msm.integration.TestServlet.PATH_INVALIDATE;
import static de.javakaffee.web.msm.integration.TestUtils.*;
import static org.testng.Assert.*;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nonnull;
import net.spy.memcached.ConnectionFactory;
import net.spy.memcached.DefaultConnectionFactory;
import net.spy.memcached.MemcachedClient;
import org.apache.catalina.Container;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Session;
import org.apache.catalina.startup.Embedded;
import org.apache.http.HttpException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.thimbleware.jmemcached.MemCacheDaemon;
import de.javakaffee.web.msm.MemcachedNodesManager.MemcachedClientCallback;
import de.javakaffee.web.msm.MemcachedSessionService.SessionManager;
import de.javakaffee.web.msm.integration.TestUtils;
import de.javakaffee.web.msm.integration.TestUtils.Response;
import de.javakaffee.web.msm.integration.TestUtils.SessionAffinityMode;
/**
* Integration test testing basic session manager functionality.
*
* @author <a href="mailto:[email protected]">Martin Grotzke</a>
* @version $Id$
*/
public abstract class MemcachedSessionManagerIntegrationTest {
private static final Log LOG = LogFactory.getLog( MemcachedSessionManagerIntegrationTest.class );
private static final String GROUP_WITHOUT_NODE_ID = "withoutNodeId";
private MemCacheDaemon<?> _daemon;
private MemcachedClient _memcached;
private Embedded _tomcat1;
private int _portTomcat1;
private final String _memcachedNodeId = "n1";
private DefaultHttpClient _httpClient;
private int _memcachedPort;
private final MemcachedClientCallback _memcachedClientCallback = new MemcachedClientCallback() {
@Override
public Object get(final String key) {
return _memcached.get(key);
}
};
@BeforeMethod
public void setUp(final Method testMethod) throws Throwable {
_portTomcat1 = 18888;
_memcachedPort = 21211;
final InetSocketAddress address = new InetSocketAddress( "localhost", _memcachedPort );
_daemon = createDaemon( address );
_daemon.start();
final String[] testGroups = testMethod.getAnnotation(Test.class).groups();
final String nodePrefix = testGroups.length == 0 || !GROUP_WITHOUT_NODE_ID.equals(testGroups[0]) ? _memcachedNodeId + ":" : "";
final String memcachedNodes = nodePrefix + "localhost:" + _memcachedPort;
try {
System.setProperty( "org.apache.catalina.startup.EXIT_ON_INIT_FAILURE", "true" );
_tomcat1 = getTestUtils().createCatalina( _portTomcat1, memcachedNodes, "app1" );
getManager( _tomcat1 ).setSticky( true );
_tomcat1.start();
} catch ( final Throwable e ) {
LOG.error( "could not start tomcat.", e );
throw e;
}
_memcached = createMemcachedClient( memcachedNodes, address );
_httpClient = new DefaultHttpClient();
}
private MemcachedClient createMemcachedClient( final String memcachedNodes, final InetSocketAddress address ) throws IOException, InterruptedException {
final MemcachedNodesManager nodesManager = MemcachedNodesManager.createFor(memcachedNodes, null, _memcachedClientCallback);
final ConnectionFactory cf = nodesManager.isEncodeNodeIdInSessionId()
? new SuffixLocatorConnectionFactory( nodesManager, nodesManager.getSessionIdFormat(), Statistics.create(), 1000 )
: new DefaultConnectionFactory();
final MemcachedClient result = new MemcachedClient( cf, Arrays.asList( address ) );
// Wait a little bit, so that the memcached client can connect and is ready when test starts
Thread.sleep( 100 );
return result;
}
@AfterMethod
public void tearDown() throws Exception {
_memcached.shutdown();
_tomcat1.stop();
_httpClient.getConnectionManager().shutdown();
_daemon.stop();
}
/**
* Test for issue 106: Session not updated in memcached when only a session attribute was removed
* http://code.google.com/p/memcached-session-manager/issues/detail?id=106
*/
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testSessionUpdatedInMemcachedWhenSessionAttributeIsRemovedIssue106( final SessionAffinityMode sessionAffinity ) throws IOException, InterruptedException, HttpException {
setStickyness(sessionAffinity);
final String key = "foo";
final String value = "bar";
final String sessionId1 = post( _httpClient, _portTomcat1, null, key, value ).getSessionId();
assertNotNull( sessionId1, "No session created." );
Response response = get( _httpClient, _portTomcat1, sessionId1 );
assertEquals( response.getSessionId(), sessionId1 );
assertEquals( response.get( key ), value );
final Map<String, String> params = asMap( PARAM_REMOVE, key );
response = get( _httpClient, _portTomcat1, "/", sessionId1, params );
assertEquals( response.getSessionId(), sessionId1 );
assertNull( response.get( key ) );
// also the next request must not include this session attribute
response = get( _httpClient, _portTomcat1, sessionId1 );
assertEquals( response.getSessionId(), sessionId1 );
assertNull( response.get( key ) );
}
@Test( enabled = true )
public void testConfiguredMemcachedNodeId() throws IOException, InterruptedException, HttpException {
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
/*
* test that we have the configured memcachedNodeId in the sessionId,
* the session id looks like "<sid>-<memcachedId>[.<jvmRoute>]"
*/
final String nodeId = sessionId1.substring( sessionId1.indexOf( '-' ) + 1, sessionId1.indexOf( '.' ) );
assertEquals( _memcachedNodeId, nodeId, "Invalid memcached node id" );
}
/**
* Related to issue/feature 105 (single memcached node without node id): this shall be possible
* and the generated session id must not contain a node id.
*/
@Test( enabled = true, groups = GROUP_WITHOUT_NODE_ID )
public void testSessionIdIsNotChangedIfSingleNodeWithNoMemcachedNodeIdConfigured() throws IOException, InterruptedException, HttpException {
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
assertTrue( sessionId1.indexOf( '-' ) == -1 );
}
/**
* Related to issue/feature 105 (single memcached node without node id): the session must be
* found on a second request.
*/
@Test( enabled = true, groups = GROUP_WITHOUT_NODE_ID, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testSessionFoundIfSingleNodeWithNoMemcachedNodeIdConfigured( final SessionAffinityMode sessionAffinity ) throws IOException, InterruptedException, HttpException {
setStickyness(sessionAffinity);
final String key = "foo";
final String value = "bar";
final String sessionId1 = post( _httpClient, _portTomcat1, null, key, value ).getSessionId();
assertNotNull( sessionId1, "No session created." );
final Response response = get( _httpClient, _portTomcat1, sessionId1 );
final String sessionId2 = response.getSessionId();
assertEquals( sessionId2, sessionId1 );
/* check session attributes could be read
*/
final String actualValue = response.get( key );
assertEquals( value, actualValue );
}
@Test( enabled = true )
public void testSessionIdJvmRouteCompatibility() throws IOException, InterruptedException, HttpException {
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
assertTrue( sessionId1.matches( "[^-.]+-[^.]+(\\.[\\w]+)?" ),
"Invalid session format, must be <sid>-<memcachedId>[.<jvmRoute>]." );
}
/**
* Tests, that session ids with an invalid format (not containing the
* memcached id) do not cause issues. Instead, we want to retrieve a new
* session id.
*
* @throws IOException
* @throws InterruptedException
* @throws HttpException
*/
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testInvalidSessionId( final SessionAffinityMode sessionAffinity ) throws IOException, InterruptedException, HttpException {
setStickyness(sessionAffinity);
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, "12345" );
assertNotNull( sessionId1, "No session created." );
assertTrue( sessionId1.indexOf( '-' ) > -1, "Invalid session id format" );
}
private void setStickyness(final SessionAffinityMode sessionAffinity) {
if(!sessionAffinity.isSticky()) {
getEngine(_tomcat1).setJvmRoute(null);
}
getManager( _tomcat1 ).setSticky( sessionAffinity.isSticky() );
}
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testSessionAvailableInMemcached( final SessionAffinityMode sessionAffinity ) throws IOException, InterruptedException, HttpException {
setStickyness(sessionAffinity);
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
Thread.sleep( 50 );
assertNotNull( _memcached.get( sessionId1 ), "Session not available in memcached." );
}
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testExpiredSessionRemovedFromMemcached( @Nonnull final SessionAffinityMode sessionAffinity ) throws IOException, InterruptedException, HttpException {
setStickyness(sessionAffinity);
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
waitForSessionExpiration( sessionAffinity.isSticky() );
assertNull( _memcached.get( sessionId1 ), "Expired session still existing in memcached" );
}
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testInvalidatedSessionRemovedFromMemcached( @Nonnull final SessionAffinityMode sessionAffinity ) throws IOException, InterruptedException, HttpException {
setStickyness(sessionAffinity);
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
final Response response = get( _httpClient, _portTomcat1, PATH_INVALIDATE, sessionId1 );
assertNull( response.getResponseSessionId() );
assertEquals(_daemon.getCache().getGetMisses(), 1); // 1 is ok
assertNull( _memcached.get( sessionId1 ), "Invalidated session still existing in memcached" );
if(!sessionAffinity.isSticky()) {
assertNull( _memcached.get(createValidityInfoKeyName( sessionId1 )), "ValidityInfo for invalidated session still exists in memcached." );
}
}
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testInvalidSessionNotFound( @Nonnull final SessionAffinityMode sessionAffinity ) throws IOException, InterruptedException, HttpException {
setStickyness(sessionAffinity);
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
/*
* wait some time, as processExpires runs every second and the
* maxInactiveTime is set to 1 sec...
*/
Thread.sleep( 2100 );
final String sessionId2 = makeRequest( _httpClient, _portTomcat1, sessionId1 );
assertNotSame( sessionId1, sessionId2, "Expired session returned." );
}
/**
* Tests, that for a session that was not sent to memcached (because it's attributes
* were not modified), the expiration is updated so that they don't expire in memcached
* before they expire in tomcat.
*
* @throws Exception if something goes wrong with the http communication with tomcat
*/
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testExpirationOfSessionsInMemcachedIfBackupWasSkippedSimple( final SessionAffinityMode stickyness ) throws Exception {
final SessionManager manager = getManager( _tomcat1 );
manager.setSticky( stickyness.isSticky() );
// set to 1 sec above (in setup), default is 10 seconds
final int delay = manager.getContainer().getBackgroundProcessorDelay();
manager.setMaxInactiveInterval( delay * 4 );
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
assertNotNull( _memcached.get( sessionId1 ), "Session not available in memcached." );
/* after 2 seconds make another request without changing the session, so that
* it's not sent to memcached
*/
Thread.sleep( TimeUnit.SECONDS.toMillis( delay * 2 ) );
assertEquals( makeRequest( _httpClient, _portTomcat1, sessionId1 ), sessionId1, "SessionId should be the same" );
/* after another 3 seconds check that the session is still alive in memcached,
* this would have been expired without an updated expiration
*/
Thread.sleep( TimeUnit.SECONDS.toMillis( delay * 3 ) );
assertNotNull( _memcached.get( sessionId1 ), "Session should still exist in memcached." );
/* after another >1 second (4 seconds since the last request)
* the session must be expired in memcached
*/
Thread.sleep( TimeUnit.SECONDS.toMillis( delay ) + 500 ); // +1000 just to be sure that we're >4 secs
assertNotSame( makeRequest( _httpClient, _portTomcat1, sessionId1 ), sessionId1,
"The sessionId should have changed due to expired sessin" );
}
/**
* Tests update of session expiration in memcached (like {@link #testExpirationOfSessionsInMemcachedIfBackupWasSkippedSimple()})
* but for the scenario where many readonly requests occur: in this case, we cannot just use
* <em>maxInactiveInterval - secondsSinceLastBackup</em> (in {@link MemcachedSessionService#updateExpirationInMemcached})
* to determine if an expiration update is required, but we must use the last expiration time sent to memcached.
*
* @throws Exception if something goes wrong with the http communication with tomcat
*/
@Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
public void testExpirationOfSessionsInMemcachedIfBackupWasSkippedManyReadonlyRequests( final SessionAffinityMode stickyness ) throws Exception {
final SessionManager manager = getManager( _tomcat1 );
manager.setSticky( stickyness.isSticky() );
// set to 1 sec above (in setup), default is 10 seconds
final int delay = manager.getContainer().getBackgroundProcessorDelay();
manager.setMaxInactiveInterval( delay * 4 );
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
assertNotNull( _memcached.get( sessionId1 ), "Session not available in memcached." );
/* after 3 seconds make another request without changing the session, so that
* it's not sent to memcached
*/
Thread.sleep( TimeUnit.SECONDS.toMillis( delay * 3 ) );
assertEquals( makeRequest( _httpClient, _portTomcat1, sessionId1 ), sessionId1, "SessionId should be the same" );
assertNotNull( _memcached.get( sessionId1 ), "Session should still exist in memcached." );
/* after another 3 seconds make another request without changing the session
*/
Thread.sleep( TimeUnit.SECONDS.toMillis( delay * 3 ) );
assertEquals( makeRequest( _httpClient, _portTomcat1, sessionId1 ), sessionId1, "SessionId should be the same" );
assertNotNull( _memcached.get( sessionId1 ), "Session should still exist in memcached." );
/* after another nearly 4 seconds (maxInactiveInterval) check that the session is still alive in memcached,
* this would have been expired without an updated expiration
*/
Thread.sleep( TimeUnit.SECONDS.toMillis( manager.getMaxInactiveInterval() ) - 500 );
assertNotNull( _memcached.get( sessionId1 ), "Session should still exist in memcached." );
/* after another second in sticky mode (more than 4 seconds since the last request), or an two times the
* maxInactiveInterval in non-sticky mode (we must keep sessions in memcached with double expirationtime)
* the session must be expired in memcached
*/
Thread.sleep( TimeUnit.SECONDS.toMillis( delay ) + 500 );
assertNotSame( makeRequest( _httpClient, _portTomcat1, sessionId1 ), sessionId1,
"The sessionId should have changed due to expired sessin" );
}
/**
* Test for issue #49:
* Sessions not associated with a memcached node don't get associated as soon as a memcached is available
* @throws InterruptedException
* @throws IOException
* @throws TimeoutException
* @throws ExecutionException
*/
@Test( enabled = true )
public void testNotAssociatedSessionGetsAssociatedIssue49() throws InterruptedException, IOException, ExecutionException, TimeoutException {
_daemon.stop();
final SessionManager manager = getManager( _tomcat1 );
manager.setMaxInactiveInterval( 5 );
manager.setSticky( true );
final SessionIdFormat sessionIdFormat = new SessionIdFormat();
final Session session = manager.createSession( null );
assertNull( sessionIdFormat.extractMemcachedId( session.getId() ) );
_daemon.start();
// Wait so that the daemon will be available and the client can reconnect (async get didn't do the trick)
Thread.sleep( 4000 );
final String newSessionId = manager.getMemcachedSessionService().changeSessionIdOnMemcachedFailover( session.getId() );
assertNotNull( newSessionId );
assertEquals( newSessionId, session.getId() );
assertEquals( sessionIdFormat.extractMemcachedId( newSessionId ), _memcachedNodeId );
}
/**
* Test for issue #60 (Add possibility to disable msm at runtime): disable msm
*/
@Test( enabled = true )
public void testDisableMsmAtRuntime() throws InterruptedException, IOException, ExecutionException, TimeoutException, LifecycleException, HttpException {
final SessionManager manager = getManager( _tomcat1 );
manager.setSticky( true );
// disable msm, shutdown our server and our client
manager.setEnabled( false );
_memcached.shutdown();
_daemon.stop();
checkSessionFunctionalityWithMsmDisabled();
}
/**
* Test for issue #60 (Add possibility to disable msm at runtime): start msm disabled and afterwards enable
*/
@Test( enabled = true )
public void testStartMsmDisabled() throws InterruptedException, IOException, ExecutionException, TimeoutException, LifecycleException, HttpException {
// shutdown our server and our client
_memcached.shutdown();
_daemon.stop();
// start a new tomcat with msm initially disabled
_tomcat1.stop();
Thread.sleep( 500 );
final String memcachedNodes = _memcachedNodeId + ":localhost:" + _memcachedPort;
_tomcat1 = getTestUtils().createCatalina( _portTomcat1, memcachedNodes, "app1" );
final SessionManager manager = getManager( _tomcat1 );
manager.setSticky( true );
manager.setEnabled( false );
_tomcat1.start();
LOG.info( "Waiting, check logs to see if the client causes any 'Connection refused' logging..." );
Thread.sleep( 1000 );
// some basic tests for session functionality
checkSessionFunctionalityWithMsmDisabled();
// start memcached, client and reenable msm
_daemon.start();
_memcached = createMemcachedClient( memcachedNodes, new InetSocketAddress( "localhost", _memcachedPort ) );
manager.setEnabled( true );
// Wait a little bit, so that msm's memcached client can connect and is ready when test starts
Thread.sleep( 100 );
// memcached based stuff should work again
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
assertNotNull( new SessionIdFormat().extractMemcachedId( sessionId1 ), "memcached node id missing with msm switched to enabled" );
Thread.sleep( 50 );
assertNotNull( _memcached.get( sessionId1 ), "Session not available in memcached." );
waitForSessionExpiration( true );
assertNull( _memcached.get( sessionId1 ), "Expired session still existing in memcached" );
}
abstract TestUtils getTestUtils();
private void checkSessionFunctionalityWithMsmDisabled() throws IOException, HttpException, InterruptedException {
assertTrue( getManager( _tomcat1 ).getMemcachedSessionService().isSticky() );
final String sessionId1 = makeRequest( _httpClient, _portTomcat1, null );
assertNotNull( sessionId1, "No session created." );
assertNull( new SessionIdFormat().extractMemcachedId( sessionId1 ), "Got a memcached node id, even with msm disabled." );
waitForSessionExpiration( true );
final String sessionId2 = makeRequest( _httpClient, _portTomcat1, sessionId1 );
assertNotSame( sessionId2, sessionId1, "SessionId not changed." );
}
private void waitForSessionExpiration(final boolean sticky) throws InterruptedException {
final SessionManager manager = getManager( _tomcat1 );
assertEquals( manager.getMemcachedSessionService().isSticky(), sticky );
final Container container = manager.getContainer();
final long timeout = TimeUnit.SECONDS.toMillis(
sticky ? container.getBackgroundProcessorDelay() + manager.getMaxInactiveInterval()
: 2 * manager.getMaxInactiveInterval() ) + 1000;
Thread.sleep( timeout );
}
}
|
Wait for reconfiguration in MemcachedSessionManagerIntegrationTest.testExpirationOfSessionsInMemcachedIfBackupWasSkippedSimple
This test failed in build #56
|
core/src/test/java/de/javakaffee/web/msm/MemcachedSessionManagerIntegrationTest.java
|
Wait for reconfiguration in MemcachedSessionManagerIntegrationTest.testExpirationOfSessionsInMemcachedIfBackupWasSkippedSimple
|
<ide><path>ore/src/test/java/de/javakaffee/web/msm/MemcachedSessionManagerIntegrationTest.java
<ide> final SessionManager manager = getManager( _tomcat1 );
<ide> manager.setSticky( stickyness.isSticky() );
<ide>
<add> // Wait some time for reconfiguration
<add> waitForReconnect(manager.getMemcachedSessionService().getMemcached(), 1, 500);
<add>
<ide> // set to 1 sec above (in setup), default is 10 seconds
<ide> final int delay = manager.getContainer().getBackgroundProcessorDelay();
<ide> manager.setMaxInactiveInterval( delay * 4 );
<ide> assertNotSame( makeRequest( _httpClient, _portTomcat1, sessionId1 ), sessionId1,
<ide> "The sessionId should have changed due to expired sessin" );
<ide>
<add> }
<add>
<add> public static void waitForReconnect( final MemcachedClient client, final int expectedNumServers, final long timeToWait )
<add> throws InterruptedException, RuntimeException {
<add> final long start = System.currentTimeMillis();
<add> while( System.currentTimeMillis() < start + timeToWait ) {
<add> if ( client.getAvailableServers().size() >= expectedNumServers ) {
<add> return;
<add> }
<add> Thread.sleep( 20 );
<add> }
<add> throw new RuntimeException( "MemcachedClient did not reconnect after " + timeToWait + " millis." );
<ide> }
<ide>
<ide> /**
|
|
JavaScript
|
mit
|
29e62131802faf140bba416103b471beff96d65e
| 0 |
aed86/sssn,aed86/sssn,aed86/sssn
|
(function($){
$.fn.app.attachment = function(method) {
var sandbox,
// Стандарный input для файлов
maxAttachments = Constants.max_attachments_count,
maxFileSize = Constants.upload_max_filesize,
attCounter = 0,
fancyboxContainer = ".fancybox"
;
var maxFileSizeMB = Math.round(maxFileSize / 1024 / 1024);
var methods = {
init: function(options) {
sandbox = $.extend(true, {}, this.app.attachment.defaults, options);
return this.each(function() {
var $this = $(this);
helpers.initAttachmentMenu($this);
helpers.initCancelSurvey($this);
helpers.initFancyBoxImage($this);
});
}
};
var helpers = {
initAttachmentMenu: function(d) {
helpers.bindPhotoAttachment();
helpers.bindFileAttachment();
helpers.bindRemoveIcon();
$(d).on('click', '.plus-menu li', function(e) {
e.stopPropagation();
var $filesInputContainer = $(this).closest('form').find('.files-input');
if (window.FormData === undefined) {
alert('Ваш браузер устарел. Вы не можете прикрепить файлы.');
return false;
}
var fileInput = '';
var attachmentType = $(this).find('i').data('attachment-type');
attCounter++;
if (attachmentType == "image") {
fileInput = $('<input type="file" name="images[]" class="image-field hide input-file-'+ attCounter +'"/>')
.clone()
.appendTo($filesInputContainer);
} else if (attachmentType == "document") {
fileInput = $('<input type="file" name="documents[]" class="document-field hide input-file-'+ attCounter +'"/>')
.clone()
.appendTo($filesInputContainer);
} else if (attachmentType == "survey") {
helpers.showHideSurvey(1);
return true;
} else {
alert("Error");
}
// спрятать меню
$(document).find(".plus-menu").removeClass("active");
if (fileInput) {
fileInput.click();
}
}
);
},
initFancyBoxImage: function(d) {
$(d).find(fancyboxContainer).fancybox({
cycling: false,
padding: 0,
hideOnOverlayClick: true,
//openEffect : 'elastic',
openSpeed : 250,
overlayShow: true,
// closeEffect : 'elastic',
// closeSpeed : 250,
"autoScale": false,
"autoSize": true,
"fitToView": false,
closeClick : true,
helpers: {
overlay: {
locked: false
}
}
});
},
initCancelSurvey: function(d) {
$(d).on('click', '#post-content-poll .icon-close', function() {
helpers.showHideSurvey(0);
})
},
showHideSurvey: function(show) {
if (show) {
$('#post-content-status').fadeOut(function(){
$('#post-content-poll').show().addClass('animated bounceIn').removeClass('bounceOut');
reloadMasonry(0);
});
} else {
if (Modernizr.csstransforms3d){
$('#post-content-poll').removeClass('bounceIn').addClass('bounceOut').delay(500).queue(function(){
$(this).hide();
$('#post-content-status').fadeIn();
reloadMasonry(0);
$(this).dequeue();
});
}
else {
$('#post-content-poll').removeClass('bounceIn').addClass('bounceOut').hide();
$('#post-content-status').show();
reloadMasonry(0);
}
}
reloadMasonry();
},
bindPhotoAttachment: function() {
$(document).on('change', '.image-field', function() {
helpers.displayFiles(this, 'image');
});
},
bindFileAttachment: function() {
$(document).on('change', '.document-field', function() {
helpers.displayFiles(this, 'document');
});
},
bindRemoveIcon: function() {
// Удаление из нового поста
$(document).on('click', ".create-post .fancybox-close", function() {
var num = $(this).data('num');
$(".input-file-"+num).remove();
$(this).closest('li').remove();
reloadMasonry();
return false;
});
// Удаление из редактируемого поста
$(document).on('click', ".edit-post-footer .fancybox-close", function() {
var $form = $(this).closest('form');
var $removeContainer = $form.find('.attach-to-remove');
var id = $(this).data('id');
$(this).closest('li').remove();
var $checkbox = $('<input type="hidden" name="post[attachToRemove][]" value="'+id+'"/>');
$removeContainer.append($checkbox);
reloadMasonry();
return false;
});
$(document).on('click', ".remove-doc-icon", function() {
var num = $(this).closest('.doc-element').data('num');
$(".input-file-"+num).remove();
$(this).closest('.doc-element').remove();
if ($(".document-field").length == 0) {
$(".doc-block .documents-title").hide();
}
reloadMasonry();
return false;
});
},
displayFiles: function(input, type) {
var files = input.files;
var $form = $(input).closest('form');
var num = 0,
imgList = $form.find('.image-gallery-preview'),
docList = $form.find('.doc-block .doc-list'),
imageType = /image.*/
;
$form = $form.add(docList.closest('form'));
$(document).on('reset', $form, function() {
imgList.empty();
docList.empty();
$('.files-input input:file', this).remove();
$(".doc-block .documents-title").hide();
})
var alreadyAttached = $(".files-input input").length;
$.each(files, function(i, file){
num++;
//Проверка на максимальное количество приаттаченых документов
if (alreadyAttached <= maxAttachments) {
// Отсеиваем не картинки
if (type == 'image' && !file.type.match(imageType)) {
alert('Файл "' + file.name + '" не является картинкой.');
input.remove();
return true;
}
//Проверка на максимальный размер приаттаченого документа
if (file.size > maxFileSize) {
alert('Файл "'+ file.name + '" не добавлен, т.к. он превышает допустимый размер '+ maxFileSizeMB + 'Мб.');
input.remove();
return true;
}
if (type == 'image') {
displayImage(file);
} else {
displayDocument(file);
}
} else {
alert('Количество прикрепляемых файлов не может быть больше ' + maxAttachments);
return false;
}
reloadMasonry();
});
function displayImage(file) {
var li = $('<li/>').appendTo(imgList);
var img = $('<img alt="image" />').appendTo(li);
li.get(0).file = file;
// Создаем объект FileReader и по завершении чтения файла,
// отображаем миниатюру и обновляем инфу обо всех файлах
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.attr('src', e.target.result);
};
})(img);
var rmIcon = $('<a href="#" class="fancybox-close" title="Удалить" data-num="'+ attCounter +'"></a>');
img.after(rmIcon);
reader.readAsDataURL(file);
}
function displayDocument(file) {
if ($(".doc-block .documents-title").hasClass('hide')) {
$(".doc-block .documents-title").show();
}
var div = $(".doc-element.hide").eq(0).clone().removeClass('hide').appendTo(docList).show();
div.attr("data-num", attCounter);
div.get(0).file = file;
var reader = new FileReader();
reader.onload = (function(aDiv, filename) {
if (filename.length > Constants.max_attachment_name_length) {
var extensionPosition = filename.lastIndexOf('.');
var name = filename.substr(0, extensionPosition);
if (name.length > Constants.max_attachment_name_length) {
var extension = file.name.substr(extensionPosition);
name = name.substr(0, Constants.max_attachment_name_length - extension.length) + '...' + extension;
filename = name;
}
}
return function(e) {
aDiv.find('.doc-name').prepend(filename);
};
})(div, file.name);
reader.readAsDataURL(file);
}
}
};
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
}
else {
$.error('Method ' + method + ' does not exist in app.attachment plugin.');
}
};
$.fn.app.attachment.defaults = {
};
})(jQuery);
var app = app || {};
$(document).ready(function() {
if (typeof app.attachment === 'undefined') {
$('body').app('attachment', app.attachment);
}
});
|
src/Bundle/MainBundle/Resources/public/js/attachment.js
|
(function($){
$.fn.app.attachment = function(method) {
var sandbox,
// Стандарный input для файлов
maxAttachments = Constants.max_attachments_count,
maxFileSize = Constants.upload_max_filesize,
attCounter = 0,
fancyboxContainer = ".fancybox"
;
var maxFileSizeMB = Math.round(maxFileSize / 1024 / 1024);
var methods = {
init: function(options) {
sandbox = $.extend(true, {}, this.app.attachment.defaults, options);
return this.each(function() {
var $this = $(this);
helpers.initAttachmentMenu($this);
helpers.initCancelSurvey($this);
helpers.initFancyBoxImage($this);
});
}
};
var helpers = {
initAttachmentMenu: function(d) {
helpers.bindPhotoAttachment();
helpers.bindFileAttachment();
helpers.bindRemoveIcon();
$(d).on('click', '.plus-menu li', function(e) {
e.stopPropagation();
var $filesInputContainer = $(this).closest('form').find('.files-input');
if (window.FormData === undefined) {
alert('Ваш браузер устарел. Вы не можете прикрепить файлы.');
return false;
}
var fileInput = '';
var attachmentType = $(this).find('i').data('attachment-type');
attCounter++;
if (attachmentType == "image") {
fileInput = $('<input type="file" name="images[]" class="image-field hide input-file-'+ attCounter +'"/>')
.clone()
.appendTo($filesInputContainer);
} else if (attachmentType == "document") {
fileInput = $('<input type="file" name="documents[]" class="document-field hide input-file-'+ attCounter +'"/>')
.clone()
.appendTo($filesInputContainer);
} else if (attachmentType == "survey") {
helpers.showHideSurvey(1);
return true;
} else {
alert("Error");
}
// спрятать меню
$(document).find(".plus-menu").removeClass("active");
if (fileInput) {
fileInput.click();
}
}
);
},
initFancyBoxImage: function(d) {
$(d).find(fancyboxContainer).fancybox({
cycling: false,
padding: 0,
hideOnOverlayClick: true,
//openEffect : 'elastic',
openSpeed : 250,
overlayShow: true,
// closeEffect : 'elastic',
// closeSpeed : 250,
"autoScale": false,
"autoSize": true,
"fitToView": false,
closeClick : true,
helpers: {
overlay: {
locked: false
}
}
});
},
initCancelSurvey: function(d) {
$(d).on('click', '#post-content-poll .icon-close', function() {
helpers.showHideSurvey(0);
})
},
showHideSurvey: function(show) {
if (show) {
$('#post-content-status').fadeOut(function(){
$('#post-content-poll').show().addClass('animated bounceIn').removeClass('bounceOut');
reloadMasonry(0);
});
} else {
if (Modernizr.csstransforms3d){
$('#post-content-poll').removeClass('bounceIn').addClass('bounceOut').delay(500).queue(function(){
$(this).hide();
$('#post-content-status').fadeIn();
reloadMasonry(0);
$(this).dequeue();
});
}
else {
$('#post-content-poll').removeClass('bounceIn').addClass('bounceOut').hide();
$('#post-content-status').show();
reloadMasonry(0);
}
}
reloadMasonry();
},
bindPhotoAttachment: function() {
$(document).on('change', '.image-field', function() {
helpers.displayFiles(this, 'image');
});
},
bindFileAttachment: function() {
$(document).on('change', '.document-field', function() {
helpers.displayFiles(this, 'document');
});
},
bindRemoveIcon: function() {
// Удаление из нового поста
$(document).on('click', ".create-post .fancybox-close", function() {
var num = $(this).data('num');
$(".input-file-"+num).remove();
$(this).closest('li').remove();
return false;
});
// Удаление из редактируемого поста
$(document).on('click', ".edit-post-footer .fancybox-close", function() {
var $form = $(this).closest('form');
var $removeContainer = $form.find('.attach-to-remove');
var id = $(this).data('id');
$(this).closest('li').remove();
var $checkbox = $('<input type="hidden" name="post[attachToRemove][]" value="'+id+'"/>');
$removeContainer.append($checkbox);
return false;
});
$(document).on('click', ".remove-doc-icon", function() {
var num = $(this).closest('.doc-element').data('num');
$(".input-file-"+num).remove();
$(this).closest('.doc-element').remove();
if ($(".document-field").length == 0) {
$(".doc-block .documents-title").hide();
}
return false;
});
},
displayFiles: function(input, type) {
var files = input.files;
var $form = $(input).closest('form');
var num = 0,
imgList = $form.find('.image-gallery-preview'),
docList = $form.find('.doc-block .doc-list'),
imageType = /image.*/
;
$form = $form.add(docList.closest('form'));
$(document).on('reset', $form, function() {
imgList.empty();
docList.empty();
$('.files-input input:file', this).remove();
$(".doc-block .documents-title").hide();
})
var alreadyAttached = $(".files-input input").length;
$.each(files, function(i, file){
num++;
//Проверка на максимальное количество приаттаченых документов
if (alreadyAttached <= maxAttachments) {
// Отсеиваем не картинки
if (type == 'image' && !file.type.match(imageType)) {
alert('Файл "' + file.name + '" не является картинкой.');
input.remove();
return true;
}
//Проверка на максимальный размер приаттаченого документа
if (file.size > maxFileSize) {
alert('Файл "'+ file.name + '" не добавлен, т.к. он превышает допустимый размер '+ maxFileSizeMB + 'Мб.');
input.remove();
return true;
}
if (type == 'image') {
displayImage(file);
} else {
displayDocument(file);
}
} else {
alert('Количество прикрепляемых файлов не может быть больше ' + maxAttachments);
return false;
}
reloadMasonry();
});
function displayImage(file) {
var li = $('<li/>').appendTo(imgList);
var img = $('<img alt="image" />').appendTo(li);
li.get(0).file = file;
// Создаем объект FileReader и по завершении чтения файла,
// отображаем миниатюру и обновляем инфу обо всех файлах
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.attr('src', e.target.result);
};
})(img);
var rmIcon = $('<a href="#" class="fancybox-close" title="Удалить" data-num="'+ attCounter +'"></a>');
img.after(rmIcon);
reader.readAsDataURL(file);
}
function displayDocument(file) {
if ($(".doc-block .documents-title").hasClass('hide')) {
$(".doc-block .documents-title").show();
}
var div = $(".doc-element.hide").eq(0).clone().removeClass('hide').appendTo(docList).show();
div.attr("data-num", attCounter);
div.get(0).file = file;
var reader = new FileReader();
reader.onload = (function(aDiv, filename) {
if (filename.length > Constants.max_attachment_name_length) {
var extensionPosition = filename.lastIndexOf('.');
var name = filename.substr(0, extensionPosition);
if (name.length > Constants.max_attachment_name_length) {
var extension = file.name.substr(extensionPosition);
name = name.substr(0, Constants.max_attachment_name_length - extension.length) + '...' + extension;
filename = name;
}
}
return function(e) {
aDiv.find('.doc-name').prepend(filename);
};
})(div, file.name);
reader.readAsDataURL(file);
}
}
};
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
}
else {
$.error('Method ' + method + ' does not exist in app.attachment plugin.');
}
};
$.fn.app.attachment.defaults = {
};
})(jQuery);
var app = app || {};
$(document).ready(function() {
if (typeof app.attachment === 'undefined') {
$('body').app('attachment', app.attachment);
}
});
|
Правки
|
src/Bundle/MainBundle/Resources/public/js/attachment.js
|
Правки
|
<ide><path>rc/Bundle/MainBundle/Resources/public/js/attachment.js
<ide> var num = $(this).data('num');
<ide> $(".input-file-"+num).remove();
<ide> $(this).closest('li').remove();
<add> reloadMasonry();
<ide>
<ide> return false;
<ide> });
<ide> $(this).closest('li').remove();
<ide> var $checkbox = $('<input type="hidden" name="post[attachToRemove][]" value="'+id+'"/>');
<ide> $removeContainer.append($checkbox);
<add> reloadMasonry();
<add>
<ide> return false;
<ide> });
<ide>
<ide> if ($(".document-field").length == 0) {
<ide> $(".doc-block .documents-title").hide();
<ide> }
<add> reloadMasonry();
<ide>
<ide> return false;
<ide> });
|
|
Java
|
apache-2.0
|
e787bee4ddce8099db4870c082a33a5a697ac7e2
| 0 |
BiovistaInc/resty-gwt,resty-gwt/resty-gwt,ibaca/resty-gwt,BiovistaInc/resty-gwt,BiovistaInc/resty-gwt,Armageddon-/resty-gwt,paul-duffy/resty-gwt,paul-duffy/resty-gwt,dldinternet/resty-gwt,cguillot/resty-gwt,paul-duffy/resty-gwt,resty-gwt/resty-gwt,Armageddon-/resty-gwt,ibaca/resty-gwt,ibaca/resty-gwt,dldinternet/resty-gwt,cguillot/resty-gwt,Armageddon-/resty-gwt,cguillot/resty-gwt,resty-gwt/resty-gwt
|
/**
* Copyright (C) 2009-2010 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.fusesource.restygwt.client;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Logger;
import org.fusesource.restygwt.rebind.AnnotationResolver;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
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.json.client.JSONException;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.XMLParser;
/**
*
* @author <a href="http://hiramchirino.com">Hiram Chirino</a>
*/
public class Method {
/**
* GWT hides the full spectrum of methods because safari has a bug:
* http://bugs.webkit.org/show_bug.cgi?id=3812
*
* We extend assume the server side will also check the
* X-HTTP-Method-Override header.
*
* TODO: add an option to support using this approach to bypass restrictive
* firewalls even if the browser does support the setting all the method
* types.
*
* @author chirino
*/
static private class MethodRequestBuilder extends RequestBuilder {
public MethodRequestBuilder(String method, String url) {
super(method, url);
setHeader("X-HTTP-Method-Override", method);
}
}
public RequestBuilder builder;
final Set<Integer> expectedStatuses;
{
expectedStatuses = new HashSet<Integer>();
expectedStatuses.add(200);
expectedStatuses.add(201);
expectedStatuses.add(204);
};
boolean anyStatus;
Request request;
Response response;
Dispatcher dispatcher = Defaults.getDispatcher();
/**
* additional data which can be set per instance, e.g. from a {@link AnnotationResolver}
*/
private final Map<String, String> data = new HashMap<String, String>();
protected Method() {
}
public Method(Resource resource, String method) {
builder = new MethodRequestBuilder(method, resource.getUri());
}
public Method user(String user) {
builder.setUser(user);
return this;
}
public Method password(String password) {
builder.setPassword(password);
return this;
}
public Method header(String header, String value) {
builder.setHeader(header, value);
return this;
}
public Method headers(Map<String, String> headers) {
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
builder.setHeader(entry.getKey(), entry.getValue());
}
}
return this;
}
private void doSetTimeout() {
if (Defaults.getRequestTimeout() > -1) {
builder.setTimeoutMillis(Defaults.getRequestTimeout());
}
}
public Method text(String data) {
defaultContentType(Resource.CONTENT_TYPE_TEXT);
builder.setRequestData(data);
return this;
}
public Method json(JSONValue data) {
defaultContentType(Resource.CONTENT_TYPE_JSON);
builder.setRequestData(data.toString());
return this;
}
public Method xml(Document data) {
defaultContentType(Resource.CONTENT_TYPE_XML);
builder.setRequestData(data.toString());
return this;
}
public Method timeout(int timeout) {
builder.setTimeoutMillis(timeout);
return this;
}
/**
* sets the expected response status code. If the response status code does not match
* any of the values specified then the request is considered to have failed. Defaults to accepting
* 200,201,204. If set to -1 then any status code is considered a success.
*/
public Method expect(int ... statuses) {
if ( statuses.length==1 && statuses[0] < 0) {
anyStatus = true;
} else {
anyStatus = false;
this.expectedStatuses.clear();
for( int status : statuses ) {
this.expectedStatuses.add(status);
}
}
return this;
}
/**
* Local file-system (file://) does not return any status codes.
* Therefore - if we read from the file-system we accept all codes.
*
* This is for instance relevant when developing a PhoneGap application with
* restyGwt.
*/
public boolean isExpected(int status) {
String baseUrl = GWT.getHostPageBaseURL();
String requestUrl = builder.getUrl();
if (FileSystemHelper.isRequestGoingToFileSystem(baseUrl, requestUrl)) {
return true;
} else if (anyStatus) {
return true;
} else {
return this.expectedStatuses.contains(status);
}
}
public void send(final RequestCallback callback) throws RequestException {
doSetTimeout();
builder.setCallback(callback);
dispatcher.send(this, builder);
}
public void send(final TextCallback callback) {
defaultAcceptType(Resource.CONTENT_TYPE_TEXT);
try {
send(new AbstractRequestCallback<String>(this, callback) {
protected String parseResult() throws Exception {
return response.getText();
}
});
} catch (Throwable e) {
GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e);
callback.onFailure(this, e);
}
}
public void send(final JsonCallback callback) {
defaultAcceptType(Resource.CONTENT_TYPE_JSON);
try {
send(new AbstractRequestCallback<JSONValue>(this, callback) {
protected JSONValue parseResult() throws Exception {
try {
return JSONParser.parseStrict(response.getText());
} catch (Throwable e) {
throw new ResponseFormatException("Response was NOT a valid JSON document", e);
}
}
});
} catch (Throwable e) {
GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e);
callback.onFailure(this, e);
}
}
public void send(final XmlCallback callback) {
defaultAcceptType(Resource.CONTENT_TYPE_XML);
try {
send(new AbstractRequestCallback<Document>(this, callback) {
protected Document parseResult() throws Exception {
try {
return XMLParser.parse(response.getText());
} catch (Throwable e) {
throw new ResponseFormatException("Response was NOT a valid XML document", e);
}
}
});
} catch (Throwable e) {
GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e);
callback.onFailure(this, e);
}
}
public <T extends JavaScriptObject> void send(final OverlayCallback<T> callback) {
defaultAcceptType(Resource.CONTENT_TYPE_JSON);
try {
send(new AbstractRequestCallback<T>(this, callback) {
protected T parseResult() throws Exception {
try {
JSONValue val = JSONParser.parseStrict(response.getText());
if (val.isObject() != null) {
return (T) val.isObject().getJavaScriptObject();
} else if (val.isArray() != null) {
return (T) val.isArray().getJavaScriptObject();
} else {
throw new ResponseFormatException("Response was NOT a JSON object");
}
} catch (JSONException e) {
throw new ResponseFormatException("Response was NOT a valid JSON document", e);
} catch (IllegalArgumentException e) {
throw new ResponseFormatException("Response was NOT a valid JSON document", e);
}
}
});
} catch (Throwable e) {
GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e);
callback.onFailure(this, e);
}
}
public Request getRequest() {
return request;
}
public Response getResponse() {
return response;
}
protected void defaultContentType(String type) {
if (builder.getHeader(Resource.HEADER_CONTENT_TYPE) == null) {
header(Resource.HEADER_CONTENT_TYPE, type);
}
}
protected void defaultAcceptType(String type) {
if (builder.getHeader(Resource.HEADER_ACCEPT) == null) {
header(Resource.HEADER_ACCEPT, type);
}
}
public Dispatcher getDispatcher() {
return dispatcher;
}
public void setDispatcher(Dispatcher dispatcher) {
this.dispatcher = dispatcher;
}
/**
* add some information onto the method which could be interesting when this method
* comes back to the dispatcher.
*
* @param key
* @param value
*/
public void addData(String key, String value) {
data.put(key, value);
}
/**
* get all data fields which was previously added
*
* @return
*/
public Map<String, String> getData() {
return data;
}
}
|
restygwt/src/main/java/org/fusesource/restygwt/client/Method.java
|
/**
* Copyright (C) 2009-2010 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.fusesource.restygwt.client;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Logger;
import org.fusesource.restygwt.rebind.AnnotationResolver;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
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.json.client.JSONException;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.XMLParser;
/**
*
* @author <a href="http://hiramchirino.com">Hiram Chirino</a>
*/
public class Method {
/**
* GWT hides the full spectrum of methods because safari has a bug:
* http://bugs.webkit.org/show_bug.cgi?id=3812
*
* We extend assume the server side will also check the
* X-HTTP-Method-Override header.
*
* TODO: add an option to support using this approach to bypass restrictive
* firewalls even if the browser does support the setting all the method
* types.
*
* @author chirino
*/
static private class MethodRequestBuilder extends RequestBuilder {
public MethodRequestBuilder(String method, String url) {
super(method, url);
setHeader("X-HTTP-Method-Override", method);
}
}
public RequestBuilder builder;
final Set<Integer> expectedStatuses;
{
expectedStatuses = new HashSet<Integer>();
expectedStatuses.add(200);
expectedStatuses.add(201);
expectedStatuses.add(204);
};
boolean anyStatus;
Request request;
Response response;
Dispatcher dispatcher = Defaults.getDispatcher();
/**
* additional data which can be set per instance, e.g. from a {@link AnnotationResolver}
*/
private final Map<String, String> data = new HashMap<String, String>();
protected Method() {
}
public Method(Resource resource, String method) {
builder = new MethodRequestBuilder(method, resource.getUri());
}
public Method user(String user) {
builder.setUser(user);
return this;
}
public Method password(String password) {
builder.setPassword(password);
return this;
}
public Method header(String header, String value) {
builder.setHeader(header, value);
return this;
}
public Method headers(Map<String, String> headers) {
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
builder.setHeader(entry.getKey(), entry.getValue());
}
}
return this;
}
private void doSetTimeout() {
if (Defaults.getRequestTimeout() > -1) {
builder.setTimeoutMillis(Defaults.getRequestTimeout());
}
}
public Method text(String data) {
defaultContentType(Resource.CONTENT_TYPE_TEXT);
builder.setRequestData(data);
return this;
}
public Method json(JSONValue data) {
defaultContentType(Resource.CONTENT_TYPE_JSON);
builder.setRequestData(data.toString());
return this;
}
public Method xml(Document data) {
defaultContentType(Resource.CONTENT_TYPE_XML);
builder.setRequestData(data.toString());
return this;
}
public Method timeout(int timeout) {
builder.setTimeoutMillis(timeout);
return this;
}
/**
* sets the expected response status code. If the response status code does not match
* any of the values specified then the request is considered to have failed. Defaults to accepting
* 200,201,204. If set to -1 then any status code is considered a success.
*/
public Method expect(int ... statuses) {
if ( statuses.length==1 && statuses[0] < 0) {
anyStatus = true;
} else {
anyStatus = false;
this.expectedStatuses.clear();
for( int status : statuses ) {
this.expectedStatuses.add(status);
}
}
return this;
}
public boolean isExpected(int status) {
if (anyStatus) {
return true;
} else {
return this.expectedStatuses.contains(status);
}
}
public void send(final RequestCallback callback) throws RequestException {
doSetTimeout();
builder.setCallback(callback);
dispatcher.send(this, builder);
}
public void send(final TextCallback callback) {
defaultAcceptType(Resource.CONTENT_TYPE_TEXT);
try {
send(new AbstractRequestCallback<String>(this, callback) {
protected String parseResult() throws Exception {
return response.getText();
}
});
} catch (Throwable e) {
GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e);
callback.onFailure(this, e);
}
}
public void send(final JsonCallback callback) {
defaultAcceptType(Resource.CONTENT_TYPE_JSON);
try {
send(new AbstractRequestCallback<JSONValue>(this, callback) {
protected JSONValue parseResult() throws Exception {
try {
return JSONParser.parseStrict(response.getText());
} catch (Throwable e) {
throw new ResponseFormatException("Response was NOT a valid JSON document", e);
}
}
});
} catch (Throwable e) {
GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e);
callback.onFailure(this, e);
}
}
public void send(final XmlCallback callback) {
defaultAcceptType(Resource.CONTENT_TYPE_XML);
try {
send(new AbstractRequestCallback<Document>(this, callback) {
protected Document parseResult() throws Exception {
try {
return XMLParser.parse(response.getText());
} catch (Throwable e) {
throw new ResponseFormatException("Response was NOT a valid XML document", e);
}
}
});
} catch (Throwable e) {
GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e);
callback.onFailure(this, e);
}
}
public <T extends JavaScriptObject> void send(final OverlayCallback<T> callback) {
defaultAcceptType(Resource.CONTENT_TYPE_JSON);
try {
send(new AbstractRequestCallback<T>(this, callback) {
protected T parseResult() throws Exception {
try {
JSONValue val = JSONParser.parseStrict(response.getText());
if (val.isObject() != null) {
return (T) val.isObject().getJavaScriptObject();
} else if (val.isArray() != null) {
return (T) val.isArray().getJavaScriptObject();
} else {
throw new ResponseFormatException("Response was NOT a JSON object");
}
} catch (JSONException e) {
throw new ResponseFormatException("Response was NOT a valid JSON document", e);
} catch (IllegalArgumentException e) {
throw new ResponseFormatException("Response was NOT a valid JSON document", e);
}
}
});
} catch (Throwable e) {
GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e);
callback.onFailure(this, e);
}
}
public Request getRequest() {
return request;
}
public Response getResponse() {
return response;
}
protected void defaultContentType(String type) {
if (builder.getHeader(Resource.HEADER_CONTENT_TYPE) == null) {
header(Resource.HEADER_CONTENT_TYPE, type);
}
}
protected void defaultAcceptType(String type) {
if (builder.getHeader(Resource.HEADER_ACCEPT) == null) {
header(Resource.HEADER_ACCEPT, type);
}
}
public Dispatcher getDispatcher() {
return dispatcher;
}
public void setDispatcher(Dispatcher dispatcher) {
this.dispatcher = dispatcher;
}
/**
* add some information onto the method which could be interesting when this method
* comes back to the dispatcher.
*
* @param key
* @param value
*/
public void addData(String key, String value) {
data.put(key, value);
}
/**
* get all data fields which was previously added
*
* @return
*/
public Map<String, String> getData() {
return data;
}
}
|
added file system support for isExpected
|
restygwt/src/main/java/org/fusesource/restygwt/client/Method.java
|
added file system support for isExpected
|
<ide><path>estygwt/src/main/java/org/fusesource/restygwt/client/Method.java
<ide> return this;
<ide> }
<ide>
<del>
<add> /**
<add> * Local file-system (file://) does not return any status codes.
<add> * Therefore - if we read from the file-system we accept all codes.
<add> *
<add> * This is for instance relevant when developing a PhoneGap application with
<add> * restyGwt.
<add> */
<ide> public boolean isExpected(int status) {
<del> if (anyStatus) {
<add>
<add> String baseUrl = GWT.getHostPageBaseURL();
<add> String requestUrl = builder.getUrl();
<add>
<add> if (FileSystemHelper.isRequestGoingToFileSystem(baseUrl, requestUrl)) {
<add> return true;
<add> } else if (anyStatus) {
<ide> return true;
<ide> } else {
<ide> return this.expectedStatuses.contains(status);
|
|
Java
|
apache-2.0
|
6c1841aab953be34249a008cb8b13bc81d02ec2b
| 0 |
raphw/byte-buddy,raphw/byte-buddy,raphw/byte-buddy
|
/*
* Copyright 2014 - Present Rafael Winterhalter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.bytebuddy.utility;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.description.enumeration.EnumerationDescription;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.description.type.TypeList;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.pool.TypePool;
import org.objectweb.asm.ConstantDynamic;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.util.*;
/**
* Returns a Java instance of an object that has a special meaning to the Java virtual machine and that is not
* available to Java in versions 6.
*/
public interface JavaConstant {
/**
* Returns the represented instance as a constant pool value.
*
* @return The constant pool value in a format that can be written by ASM.
*/
Object asConstantPoolValue();
/**
* Returns this constant as a Java {@code java.lang.constant.ConstantDesc} if the current VM is of at least version 12.
* If the current VM is of an older version and does not support the type, an exception is thrown.
*
* @return This constant as a Java {@code java.lang.constant.ConstantDesc}.
*/
Object asConstantDescription();
/**
* Returns a description of the type of the represented instance or at least a stub.
*
* @return A description of the type of the represented instance or at least a stub.
*/
TypeDescription getTypeDescription();
/**
* Represents a simple Java constant, either a primitive constant, a {@link String} or a {@link Class}.
*/
class Simple implements JavaConstant {
/**
* A dispatcher for interaction with {@code java.lang.constant.ClassDesc}.
*/
protected static final Dispatcher CONSTANT_DESC = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.class));
/**
* A dispatcher for interaction with {@code java.lang.constant.ClassDesc}.
*/
protected static final Dispatcher.OfClassDesc CLASS_DESC = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.OfClassDesc.class));
/**
* A dispatcher for interaction with {@code java.lang.constant.MethodTypeDesc}.
*/
protected static final Dispatcher.OfMethodTypeDesc METHOD_TYPE_DESC = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.OfMethodTypeDesc.class));
/**
* A dispatcher for interaction with {@code java.lang.constant.MethodHandleDesc}.
*/
protected static final Dispatcher.OfMethodHandleDesc METHOD_HANDLE_DESC = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.OfMethodHandleDesc.class));
/**
* A dispatcher for interaction with {@code java.lang.constant.DirectMethodHandleDesc}.
*/
protected static final Dispatcher.OfDirectMethodHandleDesc DIRECT_METHOD_HANDLE_DESC = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.OfDirectMethodHandleDesc.class));
/**
* A dispatcher for interaction with {@code java.lang.constant.DirectMethodHandleDesc}.
*/
protected static final Dispatcher.OfDirectMethodHandleDesc.ForKind DIRECT_METHOD_HANDLE_DESC_KIND = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.OfDirectMethodHandleDesc.ForKind.class));
/**
* A dispatcher for interaction with {@code java.lang.constant.DirectMethodHandleDesc}.
*/
protected static final Dispatcher.OfDynamicConstantDesc DYNAMIC_CONSTANT_DESC = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.OfDynamicConstantDesc.class));
/**
* The represented constant pool value.
*/
private final Object value;
/**
* A description of the type of the constant.
*/
private final TypeDescription typeDescription;
/**
* Creates a simple Java constant.
*
* @param value The represented constant pool value.
* @param typeDescription A description of the type of the constant.
*/
protected Simple(Object value, TypeDescription typeDescription) {
this.value = value;
this.typeDescription = typeDescription;
}
/**
* Resolves a loaded Java value to a Java constant representation.
*
* @param value The value to represent.
* @return An appropriate Java constant representation.
*/
public static JavaConstant ofLoaded(Object value) {
if (value instanceof Integer) {
return new Simple(value, TypeDescription.ForLoadedType.of(int.class));
} else if (value instanceof Long) {
return new Simple(value, TypeDescription.ForLoadedType.of(long.class));
} else if (value instanceof Float) {
return new Simple(value, TypeDescription.ForLoadedType.of(float.class));
} else if (value instanceof Double) {
return new Simple(value, TypeDescription.ForLoadedType.of(double.class));
} else if (value instanceof String) {
return new Simple(value, TypeDescription.STRING);
} else if (value instanceof Class<?>) {
return new Simple(TypeDescription.ForLoadedType.of((Class<?>) value), TypeDescription.CLASS);
} else if (JavaType.METHOD_HANDLE.isInstance(value)) {
return MethodHandle.ofLoaded(value);
} else if (JavaType.METHOD_TYPE.isInstance(value)) {
return MethodType.ofLoaded(value);
} else {
throw new IllegalArgumentException("Not a loaded Java constant value: " + value);
}
}
/**
* Creates a Java constant value from a {@code java.lang.constant.ConstantDesc}.
*
* @param value The {@code java.lang.constant.ConstantDesc} to represent.
* @param classLoader The class loader to use for resolving type information from the supplied value.
* @return An appropriate Java constant representation.
*/
public static JavaConstant ofDescription(Object value, ClassLoader classLoader) {
return ofDescription(value, ClassFileLocator.ForClassLoader.of(classLoader));
}
/**
* Creates a Java constant value from a {@code java.lang.constant.ConstantDesc}.
*
* @param value The {@code java.lang.constant.ConstantDesc} to represent.
* @param classFileLocator The class file locator to use for resolving type information from the supplied value.
* @return An appropriate Java constant representation.
*/
public static JavaConstant ofDescription(Object value, ClassFileLocator classFileLocator) {
return ofDescription(value, TypePool.Default.WithLazyResolution.of(classFileLocator));
}
/**
* Creates a Java constant value from a {@code java.lang.constant.ConstantDesc}.
*
* @param value The {@code java.lang.constant.ConstantDesc} to represent.
* @param typePool The type pool to use for resolving type information from the supplied value.
* @return An appropriate Java constant representation.
*/
public static JavaConstant ofDescription(Object value, TypePool typePool) {
if (value instanceof Integer) {
return new Simple(value, TypeDescription.ForLoadedType.of(int.class));
} else if (value instanceof Long) {
return new Simple(value, TypeDescription.ForLoadedType.of(long.class));
} else if (value instanceof Float) {
return new Simple(value, TypeDescription.ForLoadedType.of(float.class));
} else if (value instanceof Double) {
return new Simple(value, TypeDescription.ForLoadedType.of(double.class));
} else if (value instanceof String) {
return new Simple(value, TypeDescription.STRING);
} else if (CLASS_DESC.isInstance(value)) {
return new Simple(typePool.describe(Type.getType(CLASS_DESC.descriptorString(value)).getClassName()).resolve(), TypeDescription.CLASS);
} else if (METHOD_TYPE_DESC.isInstance(value)) {
Object[] parameterTypes = METHOD_TYPE_DESC.parameterArray(value);
List<TypeDescription> typeDescriptions = new ArrayList<TypeDescription>(parameterTypes.length);
for (Object parameterType : parameterTypes) {
typeDescriptions.add(typePool.describe(Type.getType(CLASS_DESC.descriptorString(parameterType)).getClassName()).resolve());
}
return MethodType.of(typePool.describe(Type.getType(CLASS_DESC.descriptorString(METHOD_TYPE_DESC.returnType(value))).getClassName()).resolve(), typeDescriptions);
} else if (DIRECT_METHOD_HANDLE_DESC.isInstance(value)) {
Object[] parameterTypes = METHOD_TYPE_DESC.parameterArray(METHOD_HANDLE_DESC.invocationType(value));
List<TypeDescription> typeDescriptions = new ArrayList<TypeDescription>(parameterTypes.length);
for (Object parameterType : parameterTypes) {
typeDescriptions.add(typePool.describe(Type.getType(CLASS_DESC.descriptorString(parameterType)).getClassName()).resolve());
}
return new MethodHandle(MethodHandle.HandleType.of(DIRECT_METHOD_HANDLE_DESC.refKind(value)),
typePool.describe(Type.getType(CLASS_DESC.descriptorString(DIRECT_METHOD_HANDLE_DESC.owner(value))).getClassName()).resolve(),
DIRECT_METHOD_HANDLE_DESC.methodName(value),
DIRECT_METHOD_HANDLE_DESC.refKind(value) == Opcodes.H_NEWINVOKESPECIAL
? TypeDescription.VOID
: typePool.describe(Type.getType(CLASS_DESC.descriptorString(METHOD_TYPE_DESC.returnType(METHOD_HANDLE_DESC.invocationType(value)))).getClassName()).resolve(),
typeDescriptions);
} else if (DYNAMIC_CONSTANT_DESC.isInstance(value)) {
Type methodType = Type.getMethodType(DIRECT_METHOD_HANDLE_DESC.lookupDescriptor(DYNAMIC_CONSTANT_DESC.bootstrapMethod(value)));
List<TypeDescription> parameterTypes = new ArrayList<TypeDescription>(methodType.getArgumentTypes().length);
for (Type type : methodType.getArgumentTypes()) {
parameterTypes.add(typePool.describe(type.getClassName()).resolve());
}
Object[] constant = DYNAMIC_CONSTANT_DESC.bootstrapArgs(value);
List<JavaConstant> arguments = new ArrayList<JavaConstant>(constant.length);
for (Object aConstant : constant) {
arguments.add(ofDescription(aConstant, typePool));
}
return new Dynamic(DYNAMIC_CONSTANT_DESC.constantName(value),
typePool.describe(Type.getType(CLASS_DESC.descriptorString(DYNAMIC_CONSTANT_DESC.constantType(value))).getClassName()).resolve(),
new MethodHandle(MethodHandle.HandleType.of(DIRECT_METHOD_HANDLE_DESC.refKind(DYNAMIC_CONSTANT_DESC.bootstrapMethod(value))),
typePool.describe(Type.getType(CLASS_DESC.descriptorString(DIRECT_METHOD_HANDLE_DESC.owner(DYNAMIC_CONSTANT_DESC.bootstrapMethod(value)))).getClassName()).resolve(),
DIRECT_METHOD_HANDLE_DESC.methodName(DYNAMIC_CONSTANT_DESC.bootstrapMethod(value)),
typePool.describe(methodType.getReturnType().getClassName()).resolve(),
parameterTypes),
arguments);
} else {
throw new IllegalArgumentException("Not a resolvable constant description or not expressible as a constant pool value: " + value);
}
}
/**
* Returns a Java constant representation for a {@link TypeDescription}.
*
* @param typeDescription The type to represent as a constant.
* @return An appropriate Java constant representation.
*/
public static JavaConstant of(TypeDescription typeDescription) {
return new Simple(typeDescription, TypeDescription.CLASS);
}
/**
* Wraps a value representing a loaded or unloaded constant as {@link JavaConstant} instance.
*
* @param value The value to wrap.
* @return A wrapped Java constant.
*/
public static JavaConstant wrap(Object value) {
if (value instanceof JavaConstant) {
return (JavaConstant) value;
} else if (value instanceof TypeDescription) {
return of((TypeDescription) value);
} else {
return ofLoaded(value);
}
}
/**
* Wraps a list of either loaded or unloaded constant representations as {@link JavaConstant} instances.
*
* @param values The values to wrap.
* @return A list of wrapped Java constants.
*/
public static List<JavaConstant> wrap(List<?> values) {
List<JavaConstant> constants = new ArrayList<JavaConstant>(values.size());
for (Object value : values) {
constants.add(wrap(value));
}
return constants;
}
/**
* {@inheritDoc}
*/
public Object asConstantPoolValue() {
if (value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double || value instanceof String) {
return value;
} else if (value instanceof TypeDescription) {
return Type.getType(((TypeDescription) value).getDescriptor());
} else {
throw new IllegalStateException("Cannot resolve to a constant pool value: " + value);
}
}
/**
* {@inheritDoc}
*/
public Object asConstantDescription() {
if (value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double || value instanceof String) {
return value;
} else if (value instanceof TypeDescription) {
return CLASS_DESC.ofDescriptor(((TypeDescription) value).getDescriptor());
} else {
throw new IllegalStateException("Cannot resolve to a constant description: " + value);
}
}
/**
* {@inheritDoc}
*/
public TypeDescription getTypeDescription() {
return typeDescription;
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
return value.equals(((Simple) object).value);
}
@Override
public String toString() {
return value.toString();
}
/**
* A dispatcher to represent {@code java.lang.constant.ConstantDesc}.
*/
@JavaDispatcher.Proxied("java.lang.constant.ConstantDesc")
protected interface Dispatcher {
/**
* Checks if the supplied instance is of the type of this dispatcher.
*
* @param instance The instance to verify.
* @return {@code true} if the instance is of the supplied type.
*/
@JavaDispatcher.Instance
boolean isInstance(Object instance);
/**
* Returns an array of the dispatcher type.
*
* @param length The length of the array.
* @return An array of the type that is represented by this dispatcher with the given length.
*/
@JavaDispatcher.Container
Object[] toArray(int length);
/**
* A dispatcher to represent {@code java.lang.constant.ClassDesc}.
*/
@JavaDispatcher.Proxied("java.lang.constant.ClassDesc")
interface OfClassDesc extends Dispatcher {
/**
* Resolves a {@code java.lang.constant.ClassDesc} of a descriptor.
*
* @param descriptor The descriptor to resolve.
* @return An appropriate {@code java.lang.constant.ClassDesc}.
*/
@JavaDispatcher.IsStatic
Object ofDescriptor(String descriptor);
/**
* Returns the descriptor of the supplied class description.
*
* @param value The {@code java.lang.constant.ClassDesc} to resolve.
* @return The class's descriptor.
*/
String descriptorString(Object value);
}
/**
* A dispatcher to represent {@code java.lang.constant.MethodTypeDesc}.
*/
@JavaDispatcher.Proxied("java.lang.constant.MethodTypeDesc")
interface OfMethodTypeDesc extends Dispatcher {
/**
* Resolves a {@code java.lang.constant.MethodTypeDesc} from descriptions of the return type descriptor and parameter types.
*
* @param returnType A {@code java.lang.constant.ClassDesc} representing the return type.
* @param parameterType An array of {@code java.lang.constant.ClassDesc}s representing the parameter types.
* @return An appropriate {@code java.lang.constant.MethodTypeDesc}.
*/
@JavaDispatcher.IsStatic
Object of(@JavaDispatcher.Proxied("java.lang.constant.ClassDesc") Object returnType,
@JavaDispatcher.Proxied("java.lang.constant.ClassDesc") Object[] parameterType);
/**
* Returns a {@code java.lang.constant.MethodTypeDesc} for a given descriptor.
*
* @param descriptor The method type's descriptor.
* @return A {@code java.lang.constant.MethodTypeDesc} of the supplied descriptor
*/
@JavaDispatcher.IsStatic
Object ofDescriptor(String descriptor);
/**
* Returns the return type of a {@code java.lang.constant.MethodTypeDesc}.
*
* @param value The {@code java.lang.constant.MethodTypeDesc} to resolve.
* @return A {@code java.lang.constant.ClassDesc} of the supplied {@code java.lang.constant.MethodTypeDesc}'s return type.
*/
Object returnType(Object value);
/**
* Returns the parameter types of a {@code java.lang.constant.MethodTypeDesc}.
*
* @param value The {@code java.lang.constant.MethodTypeDesc} to resolve.
* @return An array of {@code java.lang.constant.ClassDesc} of the supplied {@code java.lang.constant.MethodTypeDesc}'s parameter types.
*/
Object[] parameterArray(Object value);
}
/**
* A dispatcher to represent {@code java.lang.constant.MethodHandleDesc}.
*/
@JavaDispatcher.Proxied("java.lang.constant.MethodHandleDesc")
interface OfMethodHandleDesc extends Dispatcher {
/**
* Resolves a {@code java.lang.constant.MethodHandleDesc}.
*
* @param kind The {@code java.lang.constant.DirectMethodHandleDesc$Kind} of the resolved method handle description.
* @param owner The {@code java.lang.constant.ClassDesc} of the resolved method handle description's owner type.
* @param name The name of the method handle to resolve.
* @param descriptor A descriptor of the lookup type.
* @return An {@code java.lang.constant.MethodTypeDesc} representing the invocation type.
*/
@JavaDispatcher.IsStatic
Object of(@JavaDispatcher.Proxied("java.lang.constant.DirectMethodHandleDesc$Kind") Object kind,
@JavaDispatcher.Proxied("java.lang.constant.ClassDesc") Object owner,
String name,
String descriptor);
/**
* Resolves a {@code java.lang.constant.MethodTypeDesc} representing the invocation type of
* the supplied {@code java.lang.constant.DirectMethodHandleDesc}.
*
* @param value The {@code java.lang.constant.DirectMethodHandleDesc} to resolve.
* @return An {@code java.lang.constant.MethodTypeDesc} representing the invocation type.
*/
Object invocationType(Object value);
}
/**
* A dispatcher to represent {@code java.lang.constant.DirectMethodHandleDesc}.
*/
@JavaDispatcher.Proxied("java.lang.constant.DirectMethodHandleDesc")
interface OfDirectMethodHandleDesc extends Dispatcher {
/**
* Resolves the type of method handle for the supplied method handle description.
*
* @param value The {@code java.lang.constant.DirectMethodHandleDesc} to resolve.
* @return The type of the handle.
*/
int refKind(Object value);
/**
* Resolves the method name of the supplied direct method handle.
*
* @param value The {@code java.lang.constant.DirectMethodHandleDesc} to resolve.
* @return The handle's method name.
*/
String methodName(Object value);
/**
* Resolves a {@code java.lang.constant.ClassDesc} representing the owner of a direct method handle description.
*
* @param value The {@code java.lang.constant.DirectMethodHandleDesc} to resolve.
* @return A {@code java.lang.constant.ClassDesc} describing the handle's owner.
*/
Object owner(Object value);
/**
* Checks if the represented method handle's owner is an interface type.
*
* @param value The {@code java.lang.constant.DirectMethodHandleDesc} to resolve.
* @return {@code true} if the supplied method handle description is owned by an interface.
*/
boolean isOwnerInterface(Object value);
/**
* Resolves the lookup descriptor of the supplied direct method handle description.
*
* @param value The {@code java.lang.constant.DirectMethodHandleDesc} to resolve.
* @return A descriptor of the supplied direct method handle's lookup.
*/
String lookupDescriptor(Object value);
/**
* A dispatcher to represent {@code java.lang.constant.DirectMethodHandleDesc$Kind}.
*/
@JavaDispatcher.Proxied("java.lang.constant.DirectMethodHandleDesc$Kind")
interface ForKind {
/**
* Resolves a {@code java.lang.constant.DirectMethodHandleDesc$Kind} from an identifier.
*
* @param identifier The identifier to resolve.
* @param isInterface {@code true} if the handle invokes an interface type.
* @return The identifier's {@code java.lang.constant.DirectMethodHandleDesc$Kind}.
*/
@JavaDispatcher.IsStatic
Object valueOf(int identifier, boolean isInterface);
}
}
/**
* A dispatcher to represent {@code java.lang.constant.DynamicConstantDesc}.
*/
@JavaDispatcher.Proxied("java.lang.constant.DynamicConstantDesc")
interface OfDynamicConstantDesc extends Dispatcher {
/**
* Resolves a {@code java.lang.constant.DynamicConstantDesc} for a canonical description of the constant.
*
* @param bootstrap A {@code java.lang.constant.DirectMethodHandleDesc} describing the boostrap method of the dynamic constant.
* @param constantName The constant's name.
* @param type A {@code java.lang.constant.ClassDesc} describing the constant's type.
* @param argument Descriptions of the dynamic constant's arguments.
* @return A {@code java.lang.constant.DynamicConstantDesc} for the supplied arguments.
*/
@JavaDispatcher.IsStatic
Object ofCanonical(@JavaDispatcher.Proxied("java.lang.constant.DirectMethodHandleDesc") Object bootstrap,
String constantName,
@JavaDispatcher.Proxied("java.lang.constant.ClassDesc") Object type,
@JavaDispatcher.Proxied("java.lang.constant.ConstantDesc") Object[] argument);
/**
* Resolves a {@code java.lang.constant.DynamicConstantDesc}'s arguments.
*
* @param value The {@code java.lang.constant.DynamicConstantDesc} to resolve.
* @return An array of {@code java.lang.constant.ConstantDesc} describing the arguments of the supplied dynamic constant description.
*/
Object[] bootstrapArgs(Object value);
/**
* Resolves the dynamic constant description's name.
*
* @param value The {@code java.lang.constant.DynamicConstantDesc} to resolve.
* @return The dynamic constant description's name.
*/
String constantName(Object value);
/**
* Resolves a {@code java.lang.constant.ClassDesc} for the dynamic constant's type.
*
* @param value The {@code java.lang.constant.DynamicConstantDesc} to resolve.
* @return A {@code java.lang.constant.ClassDesc} describing the constant's type.
*/
Object constantType(Object value);
/**
* Resolves a {@code java.lang.constant.DirectMethodHandleDesc} representing the dynamic constant's bootstrap method.
*
* @param value The {@code java.lang.constant.DynamicConstantDesc} to resolve.
* @return A {@code java.lang.constant.DirectMethodHandleDesc} representing the dynamic constant's bootstrap method.
*/
Object bootstrapMethod(Object value);
}
}
}
/**
* Represents a {@code java.lang.invoke.MethodType} object.
*/
class MethodType implements JavaConstant {
/**
* A dispatcher for extracting information from a {@code java.lang.invoke.MethodType} instance.
*/
private static final Dispatcher DISPATCHER = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.class));
/**
* The return type of this method type.
*/
private final TypeDescription returnType;
/**
* The parameter types of this method type.
*/
private final List<? extends TypeDescription> parameterTypes;
/**
* Creates a method type for the given types.
*
* @param returnType The return type of the method type.
* @param parameterTypes The parameter types of the method type.
*/
protected MethodType(TypeDescription returnType, List<? extends TypeDescription> parameterTypes) {
this.returnType = returnType;
this.parameterTypes = parameterTypes;
}
/**
* Returns a method type representation of a loaded {@code MethodType} object.
*
* @param methodType A method type object to represent as a {@link JavaConstant}.
* @return The method type represented as a {@link MethodType}.
*/
public static MethodType ofLoaded(Object methodType) {
if (!JavaType.METHOD_TYPE.isInstance(methodType)) {
throw new IllegalArgumentException("Expected method type object: " + methodType);
}
return of(DISPATCHER.returnType(methodType), DISPATCHER.parameterArray(methodType));
}
/**
* Returns a method type description of the given return type and parameter types.
*
* @param returnType The return type to represent.
* @param parameterType The parameter types to represent.
* @return A method type of the given return type and parameter types.
*/
public static MethodType of(Class<?> returnType, Class<?>... parameterType) {
return of(TypeDescription.ForLoadedType.of(returnType), new TypeList.ForLoadedTypes(parameterType));
}
/**
* Returns a method type description of the given return type and parameter types.
*
* @param returnType The return type to represent.
* @param parameterType The parameter types to represent.
* @return A method type of the given return type and parameter types.
*/
public static MethodType of(TypeDescription returnType, TypeDescription... parameterType) {
return new MethodType(returnType, Arrays.asList(parameterType));
}
/**
* Returns a method type description of the given return type and parameter types.
*
* @param returnType The return type to represent.
* @param parameterTypes The parameter types to represent.
* @return A method type of the given return type and parameter types.
*/
public static MethodType of(TypeDescription returnType, List<? extends TypeDescription> parameterTypes) {
return new MethodType(returnType, parameterTypes);
}
/**
* Returns a method type description of the given method.
*
* @param method The method to extract the method type from.
* @return The method type of the given method.
*/
public static MethodType of(Method method) {
return of(new MethodDescription.ForLoadedMethod(method));
}
/**
* Returns a method type description of the given constructor.
*
* @param constructor The constructor to extract the method type from.
* @return The method type of the given constructor.
*/
public static MethodType of(Constructor<?> constructor) {
return of(new MethodDescription.ForLoadedConstructor(constructor));
}
/**
* Returns a method type description of the given method.
*
* @param methodDescription The method to extract the method type from.
* @return The method type of the given method.
*/
public static MethodType of(MethodDescription methodDescription) {
return new MethodType(methodDescription.getReturnType().asErasure(), methodDescription.getParameters().asTypeList().asErasures());
}
/**
* Returns a method type for a setter of the given field.
*
* @param field The field to extract a setter type for.
* @return The type of a setter for the given field.
*/
public static MethodType ofSetter(Field field) {
return ofSetter(new FieldDescription.ForLoadedField(field));
}
/**
* Returns a method type for a setter of the given field.
*
* @param fieldDescription The field to extract a setter type for.
* @return The type of a setter for the given field.
*/
public static MethodType ofSetter(FieldDescription fieldDescription) {
return new MethodType(TypeDescription.VOID, Collections.singletonList(fieldDescription.getType().asErasure()));
}
/**
* Returns a method type for a getter of the given field.
*
* @param field The field to extract a getter type for.
* @return The type of a getter for the given field.
*/
public static MethodType ofGetter(Field field) {
return ofGetter(new FieldDescription.ForLoadedField(field));
}
/**
* Returns a method type for a getter of the given field.
*
* @param fieldDescription The field to extract a getter type for.
* @return The type of a getter for the given field.
*/
public static MethodType ofGetter(FieldDescription fieldDescription) {
return new MethodType(fieldDescription.getType().asErasure(), Collections.<TypeDescription>emptyList());
}
/**
* Returns a method type for the given constant.
*
* @param instance The constant for which a constant method type should be created.
* @return A method type for the given constant.
*/
public static MethodType ofConstant(Object instance) {
return ofConstant(instance.getClass());
}
/**
* Returns a method type for the given constant type.
*
* @param type The constant type for which a constant method type should be created.
* @return A method type for the given constant type.
*/
public static MethodType ofConstant(Class<?> type) {
return ofConstant(TypeDescription.ForLoadedType.of(type));
}
/**
* Returns a method type for the given constant type.
*
* @param typeDescription The constant type for which a constant method type should be created.
* @return A method type for the given constant type.
*/
public static MethodType ofConstant(TypeDescription typeDescription) {
return new MethodType(typeDescription, Collections.<TypeDescription>emptyList());
}
/**
* Returns the return type of this method type.
*
* @return The return type of this method type.
*/
public TypeDescription getReturnType() {
return returnType;
}
/**
* Returns the parameter types of this method type.
*
* @return The parameter types of this method type.
*/
public TypeList getParameterTypes() {
return new TypeList.Explicit(parameterTypes);
}
/**
* Returns the method descriptor of this method type representation.
*
* @return The method descriptor of this method type representation.
*/
public String getDescriptor() {
StringBuilder stringBuilder = new StringBuilder("(");
for (TypeDescription parameterType : parameterTypes) {
stringBuilder.append(parameterType.getDescriptor());
}
return stringBuilder.append(')').append(returnType.getDescriptor()).toString();
}
/**
* {@inheritDoc}
*/
public Type asConstantPoolValue() {
StringBuilder stringBuilder = new StringBuilder().append('(');
for (TypeDescription parameterType : getParameterTypes()) {
stringBuilder.append(parameterType.getDescriptor());
}
return Type.getMethodType(stringBuilder.append(')').append(getReturnType().getDescriptor()).toString());
}
/**
* {@inheritDoc}
*/
public Object asConstantDescription() {
Object[] parameterTypes = Simple.CLASS_DESC.toArray(getParameterTypes().size());
for (int index = 0; index < getParameterTypes().size(); index++) {
parameterTypes[index] = Simple.CLASS_DESC.ofDescriptor(getParameterTypes().get(index).getDescriptor());
}
return Simple.METHOD_TYPE_DESC.of(Simple.CLASS_DESC.ofDescriptor(getReturnType().getDescriptor()), parameterTypes);
}
/**
* {@inheritDoc}
*/
public TypeDescription getTypeDescription() {
return JavaType.METHOD_TYPE.getTypeStub();
}
@Override
public int hashCode() {
int result = returnType.hashCode();
result = 31 * result + parameterTypes.hashCode();
return result;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof MethodType)) {
return false;
}
MethodType methodType = (MethodType) other;
return parameterTypes.equals(methodType.parameterTypes) && returnType.equals(methodType.returnType);
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder().append('(');
boolean first = true;
for (TypeDescription typeDescription : parameterTypes) {
if (first) {
first = false;
} else {
stringBuilder.append(',');
}
stringBuilder.append(typeDescription.getSimpleName());
}
return stringBuilder.append(')').append(returnType.getSimpleName()).toString();
}
/**
* A dispatcher for extracting information from a {@code java.lang.invoke.MethodType} instance.
*/
@JavaDispatcher.Proxied("java.lang.invoke.MethodType")
protected interface Dispatcher {
/**
* Extracts the return type of the supplied method type.
*
* @param methodType An instance of {@code java.lang.invoke.MethodType}.
* @return The return type that is described by the supplied instance.
*/
Class<?> returnType(Object methodType);
/**
* Extracts the parameter types of the supplied method type.
*
* @param methodType An instance of {@code java.lang.invoke.MethodType}.
* @return The parameter types that are described by the supplied instance.
*/
Class<?>[] parameterArray(Object methodType);
}
}
/**
* Represents a {@code java.lang.invoke.MethodHandle} object. Note that constant {@code MethodHandle}s cannot
* be represented within the constant pool of a Java class and can therefore not be represented as an instance of
* this representation order.
*/
class MethodHandle implements JavaConstant {
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodHandleInfo}.
*/
protected static final MethodHandleInfo METHOD_HANDLE_INFO = AccessController.doPrivileged(JavaDispatcher.of(MethodHandleInfo.class));
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodType}.
*/
protected static final MethodType METHOD_TYPE = AccessController.doPrivileged(JavaDispatcher.of(MethodType.class));
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodHandles}.
*/
protected static final MethodHandles METHOD_HANDLES = AccessController.doPrivileged(JavaDispatcher.of(MethodHandles.class));
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodHandles$Lookup}.
*/
protected static final MethodHandles.Lookup METHOD_HANDLES_LOOKUP = AccessController.doPrivileged(JavaDispatcher.of(MethodHandles.Lookup.class));
/**
* The handle type that is represented by this instance.
*/
private final HandleType handleType;
/**
* The owner type that is represented by this instance.
*/
private final TypeDescription ownerType;
/**
* The name that is represented by this instance.
*/
private final String name;
/**
* The return type that is represented by this instance.
*/
private final TypeDescription returnType;
/**
* The parameter types that is represented by this instance.
*/
private final List<? extends TypeDescription> parameterTypes;
/**
* Creates a method handle representation.
*
* @param handleType The handle type that is represented by this instance.
* @param ownerType The owner type that is represented by this instance.
* @param name The name that is represented by this instance.
* @param returnType The return type that is represented by this instance.
* @param parameterTypes The parameter types that is represented by this instance.
*/
protected MethodHandle(HandleType handleType,
TypeDescription ownerType,
String name,
TypeDescription returnType,
List<? extends TypeDescription> parameterTypes) {
this.handleType = handleType;
this.ownerType = ownerType;
this.name = name;
this.returnType = returnType;
this.parameterTypes = parameterTypes;
}
/**
* Creates a method handles representation of a loaded method handle which is analyzed using a public {@code MethodHandles.Lookup} object.
* A method handle can only be analyzed on virtual machines that support the corresponding API (Java 7+). For virtual machines before Java 8+,
* a method handle instance can only be analyzed by taking advantage of private APIs what might require a access context.
*
* @param methodHandle The loaded method handle to represent.
* @return A representation of the loaded method handle
*/
public static MethodHandle ofLoaded(Object methodHandle) {
return ofLoaded(methodHandle, METHOD_HANDLES.publicLookup());
}
/**
* Creates a method handles representation of a loaded method handle which is analyzed using the given lookup context.
* A method handle can only be analyzed on virtual machines that support the corresponding API (Java 7+). For virtual machines before Java 8+,
* a method handle instance can only be analyzed by taking advantage of private APIs what might require a access context.
*
* @param methodHandle The loaded method handle to represent.
* @param lookup The lookup object to use for analyzing the method handle.
* @return A representation of the loaded method handle
*/
public static MethodHandle ofLoaded(Object methodHandle, Object lookup) {
if (!JavaType.METHOD_HANDLE.isInstance(methodHandle)) {
throw new IllegalArgumentException("Expected method handle object: " + methodHandle);
} else if (!JavaType.METHOD_HANDLES_LOOKUP.isInstance(lookup)) {
throw new IllegalArgumentException("Expected method handle lookup object: " + lookup);
}
Object methodHandleInfo = ClassFileVersion.ofThisVm(ClassFileVersion.JAVA_V8).isAtMost(ClassFileVersion.JAVA_V7)
? METHOD_HANDLE_INFO.revealDirect(methodHandle)
: METHOD_HANDLES_LOOKUP.revealDirect(lookup, methodHandle);
Object methodType = METHOD_HANDLE_INFO.getMethodType(methodHandleInfo);
return new MethodHandle(HandleType.of(METHOD_HANDLE_INFO.getReferenceKind(methodHandleInfo)),
TypeDescription.ForLoadedType.of(METHOD_HANDLE_INFO.getDeclaringClass(methodHandleInfo)),
METHOD_HANDLE_INFO.getName(methodHandleInfo),
TypeDescription.ForLoadedType.of(METHOD_TYPE.returnType(methodType)),
new TypeList.ForLoadedTypes(METHOD_TYPE.parameterArray(methodType)));
}
/**
* Creates a method handle representation of the given method.
*
* @param method The method ro represent.
* @return A method handle representing the given method.
*/
public static MethodHandle of(Method method) {
return of(new MethodDescription.ForLoadedMethod(method));
}
/**
* Creates a method handle representation of the given constructor.
*
* @param constructor The constructor ro represent.
* @return A method handle representing the given constructor.
*/
public static MethodHandle of(Constructor<?> constructor) {
return of(new MethodDescription.ForLoadedConstructor(constructor));
}
/**
* Creates a method handle representation of the given method.
*
* @param methodDescription The method ro represent.
* @return A method handle representing the given method.
*/
public static MethodHandle of(MethodDescription.InDefinedShape methodDescription) {
return new MethodHandle(HandleType.of(methodDescription),
methodDescription.getDeclaringType().asErasure(),
methodDescription.getInternalName(),
methodDescription.getReturnType().asErasure(),
methodDescription.getParameters().asTypeList().asErasures());
}
/**
* Creates a method handle representation of the given method for an explicit special method invocation of an otherwise virtual method.
*
* @param method The method ro represent.
* @param type The type on which the method is to be invoked on as a special method invocation.
* @return A method handle representing the given method as special method invocation.
*/
public static MethodHandle ofSpecial(Method method, Class<?> type) {
return ofSpecial(new MethodDescription.ForLoadedMethod(method), TypeDescription.ForLoadedType.of(type));
}
/**
* Creates a method handle representation of the given method for an explicit special method invocation of an otherwise virtual method.
*
* @param methodDescription The method ro represent.
* @param typeDescription The type on which the method is to be invoked on as a special method invocation.
* @return A method handle representing the given method as special method invocation.
*/
public static MethodHandle ofSpecial(MethodDescription.InDefinedShape methodDescription, TypeDescription typeDescription) {
if (!methodDescription.isSpecializableFor(typeDescription)) {
throw new IllegalArgumentException("Cannot specialize " + methodDescription + " for " + typeDescription);
}
return new MethodHandle(HandleType.ofSpecial(methodDescription),
typeDescription,
methodDescription.getInternalName(),
methodDescription.getReturnType().asErasure(),
methodDescription.getParameters().asTypeList().asErasures());
}
/**
* Returns a method handle for a setter of the given field.
*
* @param field The field to represent.
* @return A method handle for a setter of the given field.
*/
public static MethodHandle ofGetter(Field field) {
return ofGetter(new FieldDescription.ForLoadedField(field));
}
/**
* Returns a method handle for a setter of the given field.
*
* @param fieldDescription The field to represent.
* @return A method handle for a setter of the given field.
*/
public static MethodHandle ofGetter(FieldDescription.InDefinedShape fieldDescription) {
return new MethodHandle(HandleType.ofGetter(fieldDescription),
fieldDescription.getDeclaringType().asErasure(),
fieldDescription.getInternalName(),
fieldDescription.getType().asErasure(),
Collections.<TypeDescription>emptyList());
}
/**
* Returns a method handle for a getter of the given field.
*
* @param field The field to represent.
* @return A method handle for a getter of the given field.
*/
public static MethodHandle ofSetter(Field field) {
return ofSetter(new FieldDescription.ForLoadedField(field));
}
/**
* Returns a method handle for a getter of the given field.
*
* @param fieldDescription The field to represent.
* @return A method handle for a getter of the given field.
*/
public static MethodHandle ofSetter(FieldDescription.InDefinedShape fieldDescription) {
return new MethodHandle(HandleType.ofSetter(fieldDescription),
fieldDescription.getDeclaringType().asErasure(),
fieldDescription.getInternalName(),
TypeDescription.VOID,
Collections.singletonList(fieldDescription.getType().asErasure()));
}
/**
* Returns the lookup type of the provided {@code java.lang.invoke.MethodHandles$Lookup} instance.
*
* @param callerClassLookup An instance of {@code java.lang.invoke.MethodHandles$Lookup}.
* @return The instance's lookup type.
*/
public static Class<?> lookupType(Object callerClassLookup) {
return METHOD_HANDLES_LOOKUP.lookupClass(callerClassLookup);
}
/**
* {@inheritDoc}
*/
public Handle asConstantPoolValue() {
return new Handle(getHandleType().getIdentifier(),
getOwnerType().getInternalName(),
getName(),
getDescriptor(),
getOwnerType().isInterface());
}
/**
* {@inheritDoc}
*/
public Object asConstantDescription() {
return Simple.METHOD_HANDLE_DESC.of(Simple.DIRECT_METHOD_HANDLE_DESC_KIND.valueOf(getHandleType().getIdentifier(), getOwnerType().isInterface()),
Simple.CLASS_DESC.ofDescriptor(getOwnerType().getDescriptor()),
getName(),
getDescriptor());
}
/**
* {@inheritDoc}
*/
public TypeDescription getTypeDescription() {
return JavaType.METHOD_HANDLE.getTypeStub();
}
/**
* Returns the handle type represented by this instance.
*
* @return The handle type represented by this instance.
*/
public HandleType getHandleType() {
return handleType;
}
/**
* Returns the owner type of this instance.
*
* @return The owner type of this instance.
*/
public TypeDescription getOwnerType() {
return ownerType;
}
/**
* Returns the name represented by this instance.
*
* @return The name represented by this instance.
*/
public String getName() {
return name;
}
/**
* Returns the return type represented by this instance.
*
* @return The return type represented by this instance.
*/
public TypeDescription getReturnType() {
return returnType;
}
/**
* Returns the parameter types represented by this instance.
*
* @return The parameter types represented by this instance.
*/
public TypeList getParameterTypes() {
return new TypeList.Explicit(parameterTypes);
}
/**
* Returns the method descriptor of this method handle representation.
*
* @return The method descriptor of this method handle representation.
*/
public String getDescriptor() {
switch (handleType) {
case GET_FIELD:
case GET_STATIC_FIELD:
return returnType.getDescriptor();
case PUT_FIELD:
case PUT_STATIC_FIELD:
return parameterTypes.get(0).getDescriptor();
default:
StringBuilder stringBuilder = new StringBuilder().append('(');
for (TypeDescription parameterType : parameterTypes) {
stringBuilder.append(parameterType.getDescriptor());
}
return stringBuilder.append(')').append(returnType.getDescriptor()).toString();
}
}
@Override
public int hashCode() {
int result = handleType.hashCode();
result = 31 * result + ownerType.hashCode();
result = 31 * result + name.hashCode();
result = 31 * result + returnType.hashCode();
result = 31 * result + parameterTypes.hashCode();
return result;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (!(other instanceof MethodHandle)) {
return false;
}
MethodHandle methodHandle = (MethodHandle) other;
return handleType == methodHandle.handleType
&& name.equals(methodHandle.name)
&& ownerType.equals(methodHandle.ownerType)
&& parameterTypes.equals(methodHandle.parameterTypes)
&& returnType.equals(methodHandle.returnType);
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder()
.append(handleType.name())
.append(ownerType.isInterface() && !handleType.isField() && handleType != HandleType.INVOKE_INTERFACE
? "@interface"
: "")
.append('/')
.append(ownerType.getSimpleName())
.append("::")
.append(name)
.append('(');
boolean first = true;
for (TypeDescription typeDescription : parameterTypes) {
if (first) {
first = false;
} else {
stringBuilder.append(',');
}
stringBuilder.append(typeDescription.getSimpleName());
}
return stringBuilder.append(')').append(returnType.getSimpleName()).toString();
}
/**
* A representation of a method handle's type.
*/
public enum HandleType {
/**
* A handle representing an invokevirtual invocation.
*/
INVOKE_VIRTUAL(Opcodes.H_INVOKEVIRTUAL, false),
/**
* A handle representing an invokestatic invocation.
*/
INVOKE_STATIC(Opcodes.H_INVOKESTATIC, false),
/**
* A handle representing an invokespecial invocation for a non-constructor.
*/
INVOKE_SPECIAL(Opcodes.H_INVOKESPECIAL, false),
/**
* A handle representing an invokeinterface invocation.
*/
INVOKE_INTERFACE(Opcodes.H_INVOKEINTERFACE, false),
/**
* A handle representing an invokespecial invocation for a constructor.
*/
INVOKE_SPECIAL_CONSTRUCTOR(Opcodes.H_NEWINVOKESPECIAL, false),
/**
* A handle representing a write of a non-static field invocation.
*/
PUT_FIELD(Opcodes.H_PUTFIELD, true),
/**
* A handle representing a read of a non-static field invocation.
*/
GET_FIELD(Opcodes.H_GETFIELD, true),
/**
* A handle representing a write of a static field invocation.
*/
PUT_STATIC_FIELD(Opcodes.H_PUTSTATIC, true),
/**
* A handle representing a read of a static field invocation.
*/
GET_STATIC_FIELD(Opcodes.H_GETSTATIC, true);
/**
* The represented identifier.
*/
private final int identifier;
/**
* {@code} true if this handle type represents a field handle.
*/
private final boolean field;
/**
* Creates a new handle type.
*
* @param identifier The represented identifier.
* @param field {@code} true if this handle type represents a field handle.
*/
HandleType(int identifier, boolean field) {
this.identifier = identifier;
this.field = field;
}
/**
* Extracts a handle type for invoking the given method.
*
* @param methodDescription The method for which a handle type should be found.
* @return The handle type for the given method.
*/
protected static HandleType of(MethodDescription.InDefinedShape methodDescription) {
if (methodDescription.isTypeInitializer()) {
throw new IllegalArgumentException("Cannot create handle of type initializer " + methodDescription);
} else if (methodDescription.isStatic()) {
return INVOKE_STATIC;
} else if (methodDescription.isConstructor()) { // Private constructors must use this handle type.
return INVOKE_SPECIAL_CONSTRUCTOR;
} else if (methodDescription.isPrivate()) {
return INVOKE_SPECIAL;
} else if (methodDescription.getDeclaringType().isInterface()) {
return INVOKE_INTERFACE;
} else {
return INVOKE_VIRTUAL;
}
}
/**
* Extracts a handle type for the given identifier.
*
* @param identifier The identifier to extract a handle type for.
* @return The representing handle type.
*/
protected static HandleType of(int identifier) {
for (HandleType handleType : HandleType.values()) {
if (handleType.getIdentifier() == identifier) {
return handleType;
}
}
throw new IllegalArgumentException("Unknown handle type: " + identifier);
}
/**
* Extracts a handle type for invoking the given method via invokespecial.
*
* @param methodDescription The method for which a handle type should be found.
* @return The handle type for the given method.
*/
protected static HandleType ofSpecial(MethodDescription.InDefinedShape methodDescription) {
if (methodDescription.isStatic() || methodDescription.isAbstract()) {
throw new IllegalArgumentException("Cannot invoke " + methodDescription + " via invokespecial");
}
return methodDescription.isConstructor()
? INVOKE_SPECIAL_CONSTRUCTOR
: INVOKE_SPECIAL;
}
/**
* Extracts a handle type for a getter of the given field.
*
* @param fieldDescription The field for which to create a getter handle.
* @return The corresponding handle type.
*/
protected static HandleType ofGetter(FieldDescription.InDefinedShape fieldDescription) {
return fieldDescription.isStatic()
? GET_STATIC_FIELD
: GET_FIELD;
}
/**
* Extracts a handle type for a setter of the given field.
*
* @param fieldDescription The field for which to create a setter handle.
* @return The corresponding handle type.
*/
protected static HandleType ofSetter(FieldDescription.InDefinedShape fieldDescription) {
return fieldDescription.isStatic()
? PUT_STATIC_FIELD
: PUT_FIELD;
}
/**
* Returns the represented identifier.
*
* @return The represented identifier.
*/
public int getIdentifier() {
return identifier;
}
/**
* Returns {@code} true if this handle type represents a field handle.
*
* @return {@code} true if this handle type represents a field handle.
*/
public boolean isField() {
return field;
}
}
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodHandleInfo}.
*/
@JavaDispatcher.Proxied("java.lang.invoke.MethodHandleInfo")
protected interface MethodHandleInfo {
/**
* Returns the name of the method handle info.
*
* @param value The {@code java.lang.invoke.MethodHandleInfo} to resolve.
* @return The name of the method handle info.
*/
String getName(Object value);
/**
* Returns the declaring type of the method handle info.
*
* @param value The {@code java.lang.invoke.MethodHandleInfo} to resolve.
* @return The declaring type of the method handle info.
*/
Class<?> getDeclaringClass(Object value);
/**
* Returns the reference kind of the method handle info.
*
* @param value The {@code java.lang.invoke.MethodHandleInfo} to resolve.
* @return The reference kind of the method handle info.
*/
int getReferenceKind(Object value);
/**
* Returns the {@code java.lang.invoke.MethodType} of the method handle info.
*
* @param value The {@code java.lang.invoke.MethodHandleInfo} to resolve.
* @return The {@code java.lang.invoke.MethodType} of the method handle info.
*/
Object getMethodType(Object value);
/**
* Returns the {@code java.lang.invoke.MethodHandleInfo} of the provided method handle. This method
* was available on Java 7 but replaced by a lookup-based method in Java 8 and later.
*
* @param handle The {@code java.lang.invoke.MethodHandle} to resolve.
* @return A {@code java.lang.invoke.MethodHandleInfo} to describe the supplied method handle.
*/
@JavaDispatcher.IsConstructor
Object revealDirect(@JavaDispatcher.Proxied("java.lang.invoke.MethodHandle") Object handle);
}
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodType}.
*/
@JavaDispatcher.Proxied("java.lang.invoke.MethodType")
protected interface MethodType {
/**
* Resolves a method type's return type.
*
* @param value The {@code java.lang.invoke.MethodType} to resolve.
* @return The method type's return type.
*/
Class<?> returnType(Object value);
/**
* Resolves a method type's parameter type.
*
* @param value The {@code java.lang.invoke.MethodType} to resolve.
* @return The method type's parameter types.
*/
Class<?>[] parameterArray(Object value);
}
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodHandles}.
*/
@JavaDispatcher.Proxied("java.lang.invoke.MethodHandles")
protected interface MethodHandles {
/**
* Resolves the public {@code java.lang.invoke.MethodHandles$Lookup}.
*
* @return The public {@code java.lang.invoke.MethodHandles$Lookup}.
*/
@JavaDispatcher.IsStatic
Object publicLookup();
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodHandles$Lookup}.
*/
@JavaDispatcher.Proxied("java.lang.invoke.MethodHandles$Lookup")
interface Lookup {
/**
* Resolves the lookup type for a given lookup instance.
*
* @param value The {@code java.lang.invoke.MethodHandles$Lookup} to resolve.
* @return The lookup's lookup class.
*/
Class<?> lookupClass(Object value);
/**
* Reveals the {@code java.lang.invoke.MethodHandleInfo} for the supplied method handle.
*
* @param value The {@code java.lang.invoke.MethodHandles$Lookup} to use for resolving the supplied handle
* @param handle The {@code java.lang.invoke.MethodHandle} to resolve.
* @return A {@code java.lang.invoke.MethodHandleInfo} representing the supplied method handle.
*/
Object revealDirect(Object value, @JavaDispatcher.Proxied("java.lang.invoke.MethodHandle") Object handle);
}
}
}
/**
* Represents a dynamically resolved constant pool entry of a class file. This feature is supported for class files in version 11 and newer.
*/
class Dynamic implements JavaConstant {
/**
* The default name of a dynamic constant.
*/
public static final String DEFAULT_NAME = "_";
/**
* The name of the dynamic constant.
*/
private final String name;
/**
* A description of the represented value's type.
*/
private final TypeDescription typeDescription;
/**
* A handle representation of the bootstrap method.
*/
private final MethodHandle bootstrap;
/**
* A list of the arguments to the dynamic constant.
*/
private final List<JavaConstant> arguments;
/**
* Creates a dynamic resolved constant.
*
* @param name The name of the dynamic constant.
* @param typeDescription A description of the represented value's type.
* @param bootstrap A handle representation of the bootstrap method.
* @param arguments A list of the arguments to the dynamic constant.
*/
protected Dynamic(String name, TypeDescription typeDescription, MethodHandle bootstrap, List<JavaConstant> arguments) {
this.name = name;
this.typeDescription = typeDescription;
this.bootstrap = bootstrap;
this.arguments = arguments;
}
/**
* Returns a constant {@code null} value of type {@link Object}.
*
* @return A dynamically resolved null constant.
*/
public static Dynamic ofNullConstant() {
return new Dynamic(DEFAULT_NAME,
TypeDescription.OBJECT,
new MethodHandle(MethodHandle.HandleType.INVOKE_STATIC,
JavaType.CONSTANT_BOOTSTRAPS.getTypeStub(),
"nullConstant",
TypeDescription.OBJECT,
Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(), TypeDescription.STRING, TypeDescription.CLASS)),
Collections.<JavaConstant>emptyList());
}
/**
* Returns a {@link Class} constant for a primitive type.
*
* @param type The primitive type to represent.
* @return A dynamically resolved primitive type constant.
*/
public static JavaConstant ofPrimitiveType(Class<?> type) {
return ofPrimitiveType(TypeDescription.ForLoadedType.of(type));
}
/**
* Returns a {@link Class} constant for a primitive type.
*
* @param typeDescription The primitive type to represent.
* @return A dynamically resolved primitive type constant.
*/
public static JavaConstant ofPrimitiveType(TypeDescription typeDescription) {
if (!typeDescription.isPrimitive()) {
throw new IllegalArgumentException("Not a primitive type: " + typeDescription);
}
return new Dynamic(typeDescription.getDescriptor(),
TypeDescription.CLASS,
new MethodHandle(MethodHandle.HandleType.INVOKE_STATIC,
JavaType.CONSTANT_BOOTSTRAPS.getTypeStub(),
"primitiveClass",
TypeDescription.CLASS,
Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(), TypeDescription.STRING, TypeDescription.CLASS)),
Collections.<JavaConstant>emptyList());
}
/**
* Returns a {@link Enum} value constant.
*
* @param enumeration The enumeration value to represent.
* @return A dynamically resolved enumeration constant.
*/
public static JavaConstant ofEnumeration(Enum<?> enumeration) {
return ofEnumeration(new EnumerationDescription.ForLoadedEnumeration(enumeration));
}
/**
* Returns a {@link Enum} value constant.
*
* @param enumerationDescription The enumeration value to represent.
* @return A dynamically resolved enumeration constant.
*/
public static JavaConstant ofEnumeration(EnumerationDescription enumerationDescription) {
return new Dynamic(enumerationDescription.getValue(),
enumerationDescription.getEnumerationType(),
new MethodHandle(MethodHandle.HandleType.INVOKE_STATIC,
JavaType.CONSTANT_BOOTSTRAPS.getTypeStub(),
"enumConstant",
TypeDescription.ForLoadedType.of(Enum.class),
Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(), TypeDescription.STRING, TypeDescription.CLASS)),
Collections.<JavaConstant>emptyList());
}
/**
* Returns a {@code static}, {@code final} field constant.
*
* @param field The field to represent a value of.
* @return A dynamically resolved field value constant.
*/
public static Dynamic ofField(Field field) {
return ofField(new FieldDescription.ForLoadedField(field));
}
/**
* Returns a {@code static}, {@code final} field constant.
*
* @param fieldDescription The field to represent a value of.
* @return A dynamically resolved field value constant.
*/
public static Dynamic ofField(FieldDescription.InDefinedShape fieldDescription) {
if (!fieldDescription.isStatic() || !fieldDescription.isFinal()) {
throw new IllegalArgumentException("Field must be static and final: " + fieldDescription);
}
boolean selfDeclared = fieldDescription.getType().isPrimitive()
? fieldDescription.getType().asErasure().asBoxed().equals(fieldDescription.getType().asErasure())
: fieldDescription.getDeclaringType().equals(fieldDescription.getType().asErasure());
return new Dynamic(fieldDescription.getInternalName(),
fieldDescription.getType().asErasure(),
new MethodHandle(MethodHandle.HandleType.INVOKE_STATIC,
JavaType.CONSTANT_BOOTSTRAPS.getTypeStub(),
"getStaticFinal",
TypeDescription.OBJECT,
selfDeclared
? Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(), TypeDescription.STRING, TypeDescription.CLASS)
: Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(), TypeDescription.STRING, TypeDescription.CLASS, TypeDescription.CLASS)),
selfDeclared
? Collections.<JavaConstant>emptyList()
: Collections.singletonList(Simple.of(fieldDescription.getDeclaringType())));
}
/**
* Represents a constant that is resolved by invoking a {@code static} factory method.
*
* @param method The method to invoke to create the represented constant value.
* @param constant The method's constant arguments.
* @return A dynamic constant that is resolved by the supplied factory method.
*/
public static Dynamic ofInvocation(Method method, Object... constant) {
return ofInvocation(method, Arrays.asList(constant));
}
/**
* Represents a constant that is resolved by invoking a {@code static} factory method.
*
* @param method The method to invoke to create the represented constant value.
* @param constants The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that is resolved by the supplied factory method.
*/
public static Dynamic ofInvocation(Method method, List<?> constants) {
return ofInvocation(new MethodDescription.ForLoadedMethod(method), constants);
}
/**
* Represents a constant that is resolved by invoking a constructor.
*
* @param constructor The constructor to invoke to create the represented constant value.
* @param constant The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that is resolved by the supplied constuctor.
*/
public static Dynamic ofInvocation(Constructor<?> constructor, Object... constant) {
return ofInvocation(constructor, Arrays.asList(constant));
}
/**
* Represents a constant that is resolved by invoking a constructor.
*
* @param constructor The constructor to invoke to create the represented constant value.
* @param constants The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that is resolved by the supplied constuctor.
*/
public static Dynamic ofInvocation(Constructor<?> constructor, List<?> constants) {
return ofInvocation(new MethodDescription.ForLoadedConstructor(constructor), constants);
}
/**
* Represents a constant that is resolved by invoking a {@code static} factory method or a constructor.
*
* @param methodDescription The method or constructor to invoke to create the represented constant value.
* @param constant The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that is resolved by the supplied factory method or constructor.
*/
public static Dynamic ofInvocation(MethodDescription.InDefinedShape methodDescription, Object... constant) {
return ofInvocation(methodDescription, Arrays.asList(constant));
}
/**
* Represents a constant that is resolved by invoking a {@code static} factory method or a constructor.
*
* @param methodDescription The method or constructor to invoke to create the represented constant value.
* @param constants The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that is resolved by the supplied factory method or constructor.
*/
public static Dynamic ofInvocation(MethodDescription.InDefinedShape methodDescription, List<?> constants) {
if (!methodDescription.isConstructor() && methodDescription.getReturnType().represents(void.class)) {
throw new IllegalArgumentException("Bootstrap method is no constructor or non-void static factory: " + methodDescription);
} else if (methodDescription.isVarArgs()
? methodDescription.getParameters().size() + (methodDescription.isStatic() || methodDescription.isConstructor() ? 0 : 1) > constants.size() + 1
: methodDescription.getParameters().size() + (methodDescription.isStatic() || methodDescription.isConstructor() ? 0 : 1) != constants.size()) {
throw new IllegalArgumentException("Cannot assign " + constants + " to " + methodDescription);
}
List<TypeDescription> parameters = (methodDescription.isStatic() || methodDescription.isConstructor()
? methodDescription.getParameters().asTypeList().asErasures()
: CompoundList.of(methodDescription.getDeclaringType(), methodDescription.getParameters().asTypeList().asErasures()));
Iterator<TypeDescription> iterator;
if (methodDescription.isVarArgs()) {
iterator = CompoundList.of(parameters.subList(0, parameters.size() - 1), Collections.nCopies(
constants.size() - parameters.size() + 1,
parameters.get(parameters.size() - 1).getComponentType())).iterator();
} else {
iterator = parameters.iterator();
}
List<JavaConstant> arguments = new ArrayList<JavaConstant>(constants.size() + 1);
arguments.add(MethodHandle.of(methodDescription));
for (Object constant : constants) {
JavaConstant argument = Simple.wrap(constant);
if (!argument.getTypeDescription().isAssignableTo(iterator.next())) {
throw new IllegalArgumentException("Cannot assign " + constants + " to " + methodDescription);
}
arguments.add(argument);
}
return new Dynamic(DEFAULT_NAME,
methodDescription.isConstructor()
? methodDescription.getDeclaringType()
: methodDescription.getReturnType().asErasure(),
new MethodHandle(MethodHandle.HandleType.INVOKE_STATIC,
JavaType.CONSTANT_BOOTSTRAPS.getTypeStub(),
"invoke",
TypeDescription.OBJECT,
Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(),
TypeDescription.STRING,
TypeDescription.CLASS,
JavaType.METHOD_HANDLE.getTypeStub(),
TypeDescription.ArrayProjection.of(TypeDescription.OBJECT))),
arguments);
}
/**
* Resolves a var handle constant for a field.
*
* @param field The field to represent a var handle for.
* @return A dynamic constant that represents the created var handle constant.
*/
public static JavaConstant ofVarHandle(Field field) {
return ofVarHandle(new FieldDescription.ForLoadedField(field));
}
/**
* Resolves a var handle constant for a field.
*
* @param fieldDescription The field to represent a var handle for.
* @return A dynamic constant that represents the created var handle constant.
*/
public static JavaConstant ofVarHandle(FieldDescription.InDefinedShape fieldDescription) {
return new Dynamic(fieldDescription.getInternalName(),
JavaType.VAR_HANDLE.getTypeStub(),
new MethodHandle(MethodHandle.HandleType.INVOKE_STATIC,
JavaType.CONSTANT_BOOTSTRAPS.getTypeStub(),
fieldDescription.isStatic()
? "staticFieldVarHandle"
: "fieldVarHandle",
JavaType.VAR_HANDLE.getTypeStub(),
Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(),
TypeDescription.STRING,
TypeDescription.CLASS,
TypeDescription.CLASS,
TypeDescription.CLASS)),
Arrays.asList(Simple.of(fieldDescription.getDeclaringType()), Simple.of(fieldDescription.getType().asErasure())));
}
/**
* Resolves a var handle constant for an array.
*
* @param type The array type for which the var handle is resolved.
* @return A dynamic constant that represents the created var handle constant.
*/
public static JavaConstant ofArrayVarHandle(Class<?> type) {
return ofArrayVarHandle(TypeDescription.ForLoadedType.of(type));
}
/**
* Resolves a var handle constant for an array.
*
* @param typeDescription The array type for which the var handle is resolved.
* @return A dynamic constant that represents the created var handle constant.
*/
public static JavaConstant ofArrayVarHandle(TypeDescription typeDescription) {
if (!typeDescription.isArray()) {
throw new IllegalArgumentException("Not an array type: " + typeDescription);
}
return new Dynamic(DEFAULT_NAME,
JavaType.VAR_HANDLE.getTypeStub(),
new MethodHandle(MethodHandle.HandleType.INVOKE_STATIC,
JavaType.CONSTANT_BOOTSTRAPS.getTypeStub(),
"arrayVarHandle",
JavaType.VAR_HANDLE.getTypeStub(),
Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(),
TypeDescription.STRING,
TypeDescription.CLASS,
TypeDescription.CLASS)),
Collections.singletonList(Simple.of(typeDescription)));
}
/**
* Binds the supplied bootstrap method for the resolution of a dynamic constant.
*
* @param name The name of the bootstrap constant that is provided to the bootstrap method or constructor.
* @param method The bootstrap method to invoke.
* @param constant The arguments for the bootstrap method represented as primitive wrapper types,
* {@link String}, {@link TypeDescription} or {@link JavaConstant} values or their loaded forms.
* @return A dynamic constant that represents the bootstrapped method's result.
*/
public static Dynamic bootstrap(String name, Method method, Object... constant) {
return bootstrap(name, method, Arrays.asList(constant));
}
/**
* Binds the supplied bootstrap method for the resolution of a dynamic constant.
*
* @param name The name of the bootstrap constant that is provided to the bootstrap method or constructor.
* @param method The bootstrap method to invoke.
* @param constants The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that represents the bootstrapped method's result.
*/
public static Dynamic bootstrap(String name, Method method, List<?> constants) {
return bootstrap(name, new MethodDescription.ForLoadedMethod(method), constants);
}
/**
* Binds the supplied bootstrap constructor for the resolution of a dynamic constant.
*
* @param name The name of the bootstrap constant that is provided to the bootstrap method or constructor.
* @param constructor The bootstrap constructor to invoke.
* @param constant The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that represents the bootstrapped constructor's result.
*/
public static Dynamic bootstrap(String name, Constructor<?> constructor, Object... constant) {
return bootstrap(name, constructor, Arrays.asList(constant));
}
/**
* Binds the supplied bootstrap constructor for the resolution of a dynamic constant.
*
* @param name The name of the bootstrap constant that is provided to the bootstrap method or constructor.
* @param constructor The bootstrap constructor to invoke.
* @param constants The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that represents the bootstrapped constructor's result.
*/
public static Dynamic bootstrap(String name, Constructor<?> constructor, List<?> constants) {
return bootstrap(name, new MethodDescription.ForLoadedConstructor(constructor), constants);
}
/**
* Binds the supplied bootstrap method or constructor for the resolution of a dynamic constant.
*
* @param name The name of the bootstrap constant that is provided to the bootstrap method or constructor.
* @param bootstrapMethod The bootstrap method or constructor to invoke.
* @param constant The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that represents the bootstrapped method's or constructor's result.
*/
public static Dynamic bootstrap(String name, MethodDescription.InDefinedShape bootstrapMethod, Object... constant) {
return bootstrap(name, bootstrapMethod, Arrays.asList(constant));
}
/**
* Binds the supplied bootstrap method or constructor for the resolution of a dynamic constant.
*
* @param name The name of the bootstrap constant that is provided to the bootstrap method or constructor.
* @param bootstrap The bootstrap method or constructor to invoke.
* @param constants The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that represents the bootstrapped method's or constructor's result.
*/
public static Dynamic bootstrap(String name, MethodDescription.InDefinedShape bootstrap, List<?> constants) {
if (name.length() == 0 || name.contains(".")) {
throw new IllegalArgumentException("Not a valid field name: " + name);
}
List<JavaConstant> arguments = new ArrayList<JavaConstant>(constants.size());
List<TypeDescription> types = new ArrayList<TypeDescription>(constants.size());
for (Object constant : constants) {
JavaConstant argument = JavaConstant.Simple.wrap(constant);
arguments.add(argument);
types.add(argument.getTypeDescription());
}
if (!bootstrap.isConstantBootstrap(types)) {
throw new IllegalArgumentException("Not a valid bootstrap method " + bootstrap + " for " + arguments);
}
return new Dynamic(name,
bootstrap.isConstructor()
? bootstrap.getDeclaringType()
: bootstrap.getReturnType().asErasure(),
new MethodHandle(bootstrap.isConstructor() ? MethodHandle.HandleType.INVOKE_SPECIAL_CONSTRUCTOR : MethodHandle.HandleType.INVOKE_STATIC,
bootstrap.isConstructor()
? bootstrap.getDeclaringType()
: bootstrap.getReturnType().asErasure(),
bootstrap.getInternalName(),
bootstrap.getReturnType().asErasure(),
bootstrap.getParameters().asTypeList().asErasures()),
arguments);
}
/**
* Returns the name of the dynamic constant.
*
* @return The name of the dynamic constant.
*/
public String getName() {
return name;
}
/**
* Returns a handle representation of the bootstrap method.
*
* @return A handle representation of the bootstrap method.
*/
public MethodHandle getBootstrap() {
return bootstrap;
}
/**
* Returns a list of the arguments to the dynamic constant.
*
* @return A list of the arguments to the dynamic constant.
*/
public List<JavaConstant> getArguments() {
return arguments;
}
/**
* Resolves this {@link Dynamic} constant to resolve the returned instance to the supplied type. The type must be a subtype of the
* bootstrap method's return type. Constructors cannot be resolved to a different type.
*
* @param type The type to resolve the bootstrapped value to.
* @return This dynamic constant but resolved to the supplied type.
*/
public JavaConstant withType(Class<?> type) {
return withType(TypeDescription.ForLoadedType.of(type));
}
/**
* Resolves this {@link Dynamic} constant to resolve the returned instance to the supplied type. The type must be a subtype of the
* bootstrap method's return type. Constructors cannot be resolved to a different type.
*
* @param typeDescription The type to resolve the bootstrapped value to.
* @return This dynamic constant but resolved to the supplied type.
*/
public JavaConstant withType(TypeDescription typeDescription) {
if (typeDescription.represents(void.class)) {
throw new IllegalArgumentException("Constant value cannot represent void");
} else if (getBootstrap().getName().equals(MethodDescription.CONSTRUCTOR_INTERNAL_NAME)
? !getTypeDescription().isAssignableTo(typeDescription)
: (!typeDescription.asBoxed().isInHierarchyWith(getTypeDescription().asBoxed()))) {
throw new IllegalArgumentException(typeDescription + " is not compatible with bootstrapped type " + getTypeDescription());
}
return new Dynamic(getName(), typeDescription, getBootstrap(), getArguments());
}
/**
* {@inheritDoc}
*/
public ConstantDynamic asConstantPoolValue() {
Object[] arguments = new Object[getArguments().size()];
for (int index = 0; index < arguments.length; index++) {
arguments[index] = getArguments().get(index).asConstantPoolValue();
}
return new ConstantDynamic(getName(),
getTypeDescription().getDescriptor(),
getBootstrap().asConstantPoolValue(),
arguments);
}
/**
* {@inheritDoc}
*/
public Object asConstantDescription() {
Object[] argument = Simple.CONSTANT_DESC.toArray(getArguments().size());
for (int index = 0; index < argument.length; index++) {
argument[index] = getArguments().get(index).asConstantDescription();
}
return Simple.DYNAMIC_CONSTANT_DESC.ofCanonical(Simple.METHOD_HANDLE_DESC.of(
Simple.DIRECT_METHOD_HANDLE_DESC_KIND.valueOf(getBootstrap().getHandleType().getIdentifier(), getBootstrap().getOwnerType().isInterface()),
Simple.CLASS_DESC.ofDescriptor(getBootstrap().getOwnerType().getDescriptor()),
getBootstrap().getName(),
getBootstrap().getDescriptor()), getName(), Simple.CLASS_DESC.ofDescriptor(getTypeDescription().getDescriptor()), argument);
}
/**
* {@inheritDoc}
*/
public TypeDescription getTypeDescription() {
return typeDescription;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + typeDescription.hashCode();
result = 31 * result + bootstrap.hashCode();
result = 31 * result + arguments.hashCode();
return result;
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Dynamic dynamic = (Dynamic) object;
if (!name.equals(dynamic.name)) return false;
if (!typeDescription.equals(dynamic.typeDescription)) return false;
if (!bootstrap.equals(dynamic.bootstrap)) return false;
return arguments.equals(dynamic.arguments);
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder()
.append(getBootstrap().getOwnerType().getSimpleName())
.append("::")
.append(getBootstrap().getName())
.append('(')
.append(getName().equals(DEFAULT_NAME) ? "" : getName())
.append('/');
boolean first = true;
for (JavaConstant constant : getArguments()) {
if (first) {
first = false;
} else {
stringBuilder.append(',');
}
stringBuilder.append(constant.toString());
}
return stringBuilder.append(')').append(getTypeDescription().getSimpleName()).toString();
}
}
}
|
byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java
|
/*
* Copyright 2014 - Present Rafael Winterhalter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.bytebuddy.utility;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.description.enumeration.EnumerationDescription;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.description.type.TypeList;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.pool.TypePool;
import org.objectweb.asm.ConstantDynamic;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.util.*;
/**
* Returns a Java instance of an object that has a special meaning to the Java virtual machine and that is not
* available to Java in versions 6.
*/
public interface JavaConstant {
/**
* Returns the represented instance as a constant pool value.
*
* @return The constant pool value in a format that can be written by ASM.
*/
Object asConstantPoolValue();
/**
* Returns this constant as a Java {@code java.lang.constant.ConstantDesc} if the current VM is of at least version 12.
* If the current VM is of an older version and does not support the type, an exception is thrown.
*
* @return This constant as a Java {@code java.lang.constant.ConstantDesc}.
*/
Object asConstantDescription();
/**
* Returns a description of the type of the represented instance or at least a stub.
*
* @return A description of the type of the represented instance or at least a stub.
*/
TypeDescription getTypeDescription();
/**
* Represents a simple Java constant, either a primitive constant, a {@link String} or a {@link Class}.
*/
class Simple implements JavaConstant {
/**
* A dispatcher for interaction with {@code java.lang.constant.ClassDesc}.
*/
protected static final Dispatcher CONSTANT_DESC = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.class));
/**
* A dispatcher for interaction with {@code java.lang.constant.ClassDesc}.
*/
protected static final Dispatcher.OfClassDesc CLASS_DESC = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.OfClassDesc.class));
/**
* A dispatcher for interaction with {@code java.lang.constant.MethodTypeDesc}.
*/
protected static final Dispatcher.OfMethodTypeDesc METHOD_TYPE_DESC = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.OfMethodTypeDesc.class));
/**
* A dispatcher for interaction with {@code java.lang.constant.MethodHandleDesc}.
*/
protected static final Dispatcher.OfMethodHandleDesc METHOD_HANDLE_DESC = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.OfMethodHandleDesc.class));
/**
* A dispatcher for interaction with {@code java.lang.constant.DirectMethodHandleDesc}.
*/
protected static final Dispatcher.OfDirectMethodHandleDesc DIRECT_METHOD_HANDLE_DESC = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.OfDirectMethodHandleDesc.class));
/**
* A dispatcher for interaction with {@code java.lang.constant.DirectMethodHandleDesc}.
*/
protected static final Dispatcher.OfDirectMethodHandleDesc.ForKind DIRECT_METHOD_HANDLE_DESC_KIND = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.OfDirectMethodHandleDesc.ForKind.class));
/**
* A dispatcher for interaction with {@code java.lang.constant.DirectMethodHandleDesc}.
*/
protected static final Dispatcher.OfDynamicConstantDesc DYNAMIC_CONSTANT_DESC = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.OfDynamicConstantDesc.class));
/**
* The represented constant pool value.
*/
private final Object value;
/**
* A description of the type of the constant.
*/
private final TypeDescription typeDescription;
/**
* Creates a simple Java constant.
*
* @param value The represented constant pool value.
* @param typeDescription A description of the type of the constant.
*/
protected Simple(Object value, TypeDescription typeDescription) {
this.value = value;
this.typeDescription = typeDescription;
}
/**
* Resolves a loaded Java value to a Java constant representation.
*
* @param value The value to represent.
* @return An appropriate Java constant representation.
*/
public static JavaConstant ofLoaded(Object value) {
if (value instanceof Integer) {
return new Simple(value, TypeDescription.ForLoadedType.of(int.class));
} else if (value instanceof Long) {
return new Simple(value, TypeDescription.ForLoadedType.of(long.class));
} else if (value instanceof Float) {
return new Simple(value, TypeDescription.ForLoadedType.of(float.class));
} else if (value instanceof Double) {
return new Simple(value, TypeDescription.ForLoadedType.of(double.class));
} else if (value instanceof String) {
return new Simple(value, TypeDescription.STRING);
} else if (value instanceof Class<?>) {
return new Simple(TypeDescription.ForLoadedType.of((Class<?>) value), TypeDescription.CLASS);
} else if (JavaType.METHOD_HANDLE.isInstance(value)) {
return MethodHandle.ofLoaded(value);
} else if (JavaType.METHOD_TYPE.isInstance(value)) {
return MethodType.ofLoaded(value);
} else {
throw new IllegalArgumentException("Not a loaded Java constant value: " + value);
}
}
/**
* Creates a Java constant value from a {@code java.lang.constant.ConstantDesc}.
*
* @param value The {@code java.lang.constant.ConstantDesc} to represent.
* @param classLoader The class loader to use for resolving type information from the supplied value.
* @return An appropriate Java constant representation.
*/
public static JavaConstant ofDescription(Object value, ClassLoader classLoader) {
return ofDescription(value, ClassFileLocator.ForClassLoader.of(classLoader));
}
/**
* Creates a Java constant value from a {@code java.lang.constant.ConstantDesc}.
*
* @param value The {@code java.lang.constant.ConstantDesc} to represent.
* @param classFileLocator The class file locator to use for resolving type information from the supplied value.
* @return An appropriate Java constant representation.
*/
public static JavaConstant ofDescription(Object value, ClassFileLocator classFileLocator) {
return ofDescription(value, TypePool.Default.WithLazyResolution.of(classFileLocator));
}
/**
* Creates a Java constant value from a {@code java.lang.constant.ConstantDesc}.
*
* @param value The {@code java.lang.constant.ConstantDesc} to represent.
* @param typePool The type pool to use for resolving type information from the supplied value.
* @return An appropriate Java constant representation.
*/
public static JavaConstant ofDescription(Object value, TypePool typePool) {
if (value instanceof Integer) {
return new Simple(value, TypeDescription.ForLoadedType.of(int.class));
} else if (value instanceof Long) {
return new Simple(value, TypeDescription.ForLoadedType.of(long.class));
} else if (value instanceof Float) {
return new Simple(value, TypeDescription.ForLoadedType.of(float.class));
} else if (value instanceof Double) {
return new Simple(value, TypeDescription.ForLoadedType.of(double.class));
} else if (value instanceof String) {
return new Simple(value, TypeDescription.STRING);
} else if (CLASS_DESC.isInstance(value)) {
return new Simple(typePool.describe(Type.getType(CLASS_DESC.descriptorString(value)).getClassName()).resolve(), TypeDescription.CLASS);
} else if (METHOD_TYPE_DESC.isInstance(value)) {
Object[] parameterTypes = METHOD_TYPE_DESC.parameterArray(value);
List<TypeDescription> typeDescriptions = new ArrayList<TypeDescription>(parameterTypes.length);
for (Object parameterType : parameterTypes) {
typeDescriptions.add(typePool.describe(Type.getType(CLASS_DESC.descriptorString(parameterType)).getClassName()).resolve());
}
return MethodType.of(typePool.describe(Type.getType(CLASS_DESC.descriptorString(METHOD_TYPE_DESC.returnType(value))).getClassName()).resolve(), typeDescriptions);
} else if (DIRECT_METHOD_HANDLE_DESC.isInstance(value)) {
Object[] parameterTypes = METHOD_TYPE_DESC.parameterArray(METHOD_HANDLE_DESC.invocationType(value));
List<TypeDescription> typeDescriptions = new ArrayList<TypeDescription>(parameterTypes.length);
for (Object parameterType : parameterTypes) {
typeDescriptions.add(typePool.describe(Type.getType(CLASS_DESC.descriptorString(parameterType)).getClassName()).resolve());
}
return new MethodHandle(MethodHandle.HandleType.of(DIRECT_METHOD_HANDLE_DESC.refKind(value)),
typePool.describe(Type.getType(CLASS_DESC.descriptorString(DIRECT_METHOD_HANDLE_DESC.owner(value))).getClassName()).resolve(),
DIRECT_METHOD_HANDLE_DESC.methodName(value),
DIRECT_METHOD_HANDLE_DESC.refKind(value) == Opcodes.H_NEWINVOKESPECIAL
? TypeDescription.VOID
: typePool.describe(Type.getType(CLASS_DESC.descriptorString(METHOD_TYPE_DESC.returnType(METHOD_HANDLE_DESC.invocationType(value)))).getClassName()).resolve(),
typeDescriptions);
} else if (DYNAMIC_CONSTANT_DESC.isInstance(value)) {
Type methodType = Type.getMethodType(DIRECT_METHOD_HANDLE_DESC.lookupDescriptor(DYNAMIC_CONSTANT_DESC.bootstrapMethod(value)));
List<TypeDescription> parameterTypes = new ArrayList<TypeDescription>(methodType.getArgumentTypes().length);
for (Type type : methodType.getArgumentTypes()) {
parameterTypes.add(typePool.describe(methodType.getReturnType().getClassName()).resolve());
}
Object[] constant = DYNAMIC_CONSTANT_DESC.bootstrapArgs(value);
List<JavaConstant> arguments = new ArrayList<JavaConstant>(constant.length);
for (Object aConstant : constant) {
arguments.add(ofDescription(aConstant, typePool));
}
return new Dynamic(DYNAMIC_CONSTANT_DESC.constantName(value),
typePool.describe(Type.getType(CLASS_DESC.descriptorString(DYNAMIC_CONSTANT_DESC.constantType(value))).getClassName()).resolve(),
new MethodHandle(MethodHandle.HandleType.of(DIRECT_METHOD_HANDLE_DESC.refKind(DYNAMIC_CONSTANT_DESC.bootstrapMethod(value))),
typePool.describe(Type.getType(CLASS_DESC.descriptorString(DIRECT_METHOD_HANDLE_DESC.owner(DYNAMIC_CONSTANT_DESC.bootstrapMethod(value)))).getClassName()).resolve(),
DIRECT_METHOD_HANDLE_DESC.methodName(DYNAMIC_CONSTANT_DESC.bootstrapMethod(value)),
typePool.describe(methodType.getReturnType().getClassName()).resolve(),
parameterTypes),
arguments);
} else {
throw new IllegalArgumentException("Not a resolvable constant description or not expressible as a constant pool value: " + value);
}
}
/**
* Returns a Java constant representation for a {@link TypeDescription}.
*
* @param typeDescription The type to represent as a constant.
* @return An appropriate Java constant representation.
*/
public static JavaConstant of(TypeDescription typeDescription) {
return new Simple(typeDescription, TypeDescription.CLASS);
}
/**
* Wraps a value representing a loaded or unloaded constant as {@link JavaConstant} instance.
*
* @param value The value to wrap.
* @return A wrapped Java constant.
*/
public static JavaConstant wrap(Object value) {
if (value instanceof JavaConstant) {
return (JavaConstant) value;
} else if (value instanceof TypeDescription) {
return of((TypeDescription) value);
} else {
return ofLoaded(value);
}
}
/**
* Wraps a list of either loaded or unloaded constant representations as {@link JavaConstant} instances.
*
* @param values The values to wrap.
* @return A list of wrapped Java constants.
*/
public static List<JavaConstant> wrap(List<?> values) {
List<JavaConstant> constants = new ArrayList<JavaConstant>(values.size());
for (Object value : values) {
constants.add(wrap(value));
}
return constants;
}
/**
* {@inheritDoc}
*/
public Object asConstantPoolValue() {
if (value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double || value instanceof String) {
return value;
} else if (value instanceof TypeDescription) {
return Type.getType(((TypeDescription) value).getDescriptor());
} else {
throw new IllegalStateException("Cannot resolve to a constant pool value: " + value);
}
}
/**
* {@inheritDoc}
*/
public Object asConstantDescription() {
if (value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double || value instanceof String) {
return value;
} else if (value instanceof TypeDescription) {
return CLASS_DESC.ofDescriptor(((TypeDescription) value).getDescriptor());
} else {
throw new IllegalStateException("Cannot resolve to a constant description: " + value);
}
}
/**
* {@inheritDoc}
*/
public TypeDescription getTypeDescription() {
return typeDescription;
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
return value.equals(((Simple) object).value);
}
@Override
public String toString() {
return value.toString();
}
/**
* A dispatcher to represent {@code java.lang.constant.ConstantDesc}.
*/
@JavaDispatcher.Proxied("java.lang.constant.ConstantDesc")
protected interface Dispatcher {
/**
* Checks if the supplied instance is of the type of this dispatcher.
*
* @param instance The instance to verify.
* @return {@code true} if the instance is of the supplied type.
*/
@JavaDispatcher.Instance
boolean isInstance(Object instance);
/**
* Returns an array of the dispatcher type.
*
* @param length The length of the array.
* @return An array of the type that is represented by this dispatcher with the given length.
*/
@JavaDispatcher.Container
Object[] toArray(int length);
/**
* A dispatcher to represent {@code java.lang.constant.ClassDesc}.
*/
@JavaDispatcher.Proxied("java.lang.constant.ClassDesc")
interface OfClassDesc extends Dispatcher {
/**
* Resolves a {@code java.lang.constant.ClassDesc} of a descriptor.
*
* @param descriptor The descriptor to resolve.
* @return An appropriate {@code java.lang.constant.ClassDesc}.
*/
@JavaDispatcher.IsStatic
Object ofDescriptor(String descriptor);
/**
* Returns the descriptor of the supplied class description.
*
* @param value The {@code java.lang.constant.ClassDesc} to resolve.
* @return The class's descriptor.
*/
String descriptorString(Object value);
}
/**
* A dispatcher to represent {@code java.lang.constant.MethodTypeDesc}.
*/
@JavaDispatcher.Proxied("java.lang.constant.MethodTypeDesc")
interface OfMethodTypeDesc extends Dispatcher {
/**
* Resolves a {@code java.lang.constant.MethodTypeDesc} from descriptions of the return type descriptor and parameter types.
*
* @param returnType A {@code java.lang.constant.ClassDesc} representing the return type.
* @param parameterType An array of {@code java.lang.constant.ClassDesc}s representing the parameter types.
* @return An appropriate {@code java.lang.constant.MethodTypeDesc}.
*/
@JavaDispatcher.IsStatic
Object of(@JavaDispatcher.Proxied("java.lang.constant.ClassDesc") Object returnType,
@JavaDispatcher.Proxied("java.lang.constant.ClassDesc") Object[] parameterType);
/**
* Returns a {@code java.lang.constant.MethodTypeDesc} for a given descriptor.
*
* @param descriptor The method type's descriptor.
* @return A {@code java.lang.constant.MethodTypeDesc} of the supplied descriptor
*/
@JavaDispatcher.IsStatic
Object ofDescriptor(String descriptor);
/**
* Returns the return type of a {@code java.lang.constant.MethodTypeDesc}.
*
* @param value The {@code java.lang.constant.MethodTypeDesc} to resolve.
* @return A {@code java.lang.constant.ClassDesc} of the supplied {@code java.lang.constant.MethodTypeDesc}'s return type.
*/
Object returnType(Object value);
/**
* Returns the parameter types of a {@code java.lang.constant.MethodTypeDesc}.
*
* @param value The {@code java.lang.constant.MethodTypeDesc} to resolve.
* @return An array of {@code java.lang.constant.ClassDesc} of the supplied {@code java.lang.constant.MethodTypeDesc}'s parameter types.
*/
Object[] parameterArray(Object value);
}
/**
* A dispatcher to represent {@code java.lang.constant.MethodHandleDesc}.
*/
@JavaDispatcher.Proxied("java.lang.constant.MethodHandleDesc")
interface OfMethodHandleDesc extends Dispatcher {
/**
* Resolves a {@code java.lang.constant.MethodHandleDesc}.
*
* @param kind The {@code java.lang.constant.DirectMethodHandleDesc$Kind} of the resolved method handle description.
* @param owner The {@code java.lang.constant.ClassDesc} of the resolved method handle description's owner type.
* @param name The name of the method handle to resolve.
* @param descriptor A descriptor of the lookup type.
* @return An {@code java.lang.constant.MethodTypeDesc} representing the invocation type.
*/
@JavaDispatcher.IsStatic
Object of(@JavaDispatcher.Proxied("java.lang.constant.DirectMethodHandleDesc$Kind") Object kind,
@JavaDispatcher.Proxied("java.lang.constant.ClassDesc") Object owner,
String name,
String descriptor);
/**
* Resolves a {@code java.lang.constant.MethodTypeDesc} representing the invocation type of
* the supplied {@code java.lang.constant.DirectMethodHandleDesc}.
*
* @param value The {@code java.lang.constant.DirectMethodHandleDesc} to resolve.
* @return An {@code java.lang.constant.MethodTypeDesc} representing the invocation type.
*/
Object invocationType(Object value);
}
/**
* A dispatcher to represent {@code java.lang.constant.DirectMethodHandleDesc}.
*/
@JavaDispatcher.Proxied("java.lang.constant.DirectMethodHandleDesc")
interface OfDirectMethodHandleDesc extends Dispatcher {
/**
* Resolves the type of method handle for the supplied method handle description.
*
* @param value The {@code java.lang.constant.DirectMethodHandleDesc} to resolve.
* @return The type of the handle.
*/
int refKind(Object value);
/**
* Resolves the method name of the supplied direct method handle.
*
* @param value The {@code java.lang.constant.DirectMethodHandleDesc} to resolve.
* @return The handle's method name.
*/
String methodName(Object value);
/**
* Resolves a {@code java.lang.constant.ClassDesc} representing the owner of a direct method handle description.
*
* @param value The {@code java.lang.constant.DirectMethodHandleDesc} to resolve.
* @return A {@code java.lang.constant.ClassDesc} describing the handle's owner.
*/
Object owner(Object value);
/**
* Checks if the represented method handle's owner is an interface type.
*
* @param value The {@code java.lang.constant.DirectMethodHandleDesc} to resolve.
* @return {@code true} if the supplied method handle description is owned by an interface.
*/
boolean isOwnerInterface(Object value);
/**
* Resolves the lookup descriptor of the supplied direct method handle description.
*
* @param value The {@code java.lang.constant.DirectMethodHandleDesc} to resolve.
* @return A descriptor of the supplied direct method handle's lookup.
*/
String lookupDescriptor(Object value);
/**
* A dispatcher to represent {@code java.lang.constant.DirectMethodHandleDesc$Kind}.
*/
@JavaDispatcher.Proxied("java.lang.constant.DirectMethodHandleDesc$Kind")
interface ForKind {
/**
* Resolves a {@code java.lang.constant.DirectMethodHandleDesc$Kind} from an identifier.
*
* @param identifier The identifier to resolve.
* @param isInterface {@code true} if the handle invokes an interface type.
* @return The identifier's {@code java.lang.constant.DirectMethodHandleDesc$Kind}.
*/
@JavaDispatcher.IsStatic
Object valueOf(int identifier, boolean isInterface);
}
}
/**
* A dispatcher to represent {@code java.lang.constant.DynamicConstantDesc}.
*/
@JavaDispatcher.Proxied("java.lang.constant.DynamicConstantDesc")
interface OfDynamicConstantDesc extends Dispatcher {
/**
* Resolves a {@code java.lang.constant.DynamicConstantDesc} for a canonical description of the constant.
*
* @param bootstrap A {@code java.lang.constant.DirectMethodHandleDesc} describing the boostrap method of the dynamic constant.
* @param constantName The constant's name.
* @param type A {@code java.lang.constant.ClassDesc} describing the constant's type.
* @param argument Descriptions of the dynamic constant's arguments.
* @return A {@code java.lang.constant.DynamicConstantDesc} for the supplied arguments.
*/
@JavaDispatcher.IsStatic
Object ofCanonical(@JavaDispatcher.Proxied("java.lang.constant.DirectMethodHandleDesc") Object bootstrap,
String constantName,
@JavaDispatcher.Proxied("java.lang.constant.ClassDesc") Object type,
@JavaDispatcher.Proxied("java.lang.constant.ConstantDesc") Object[] argument);
/**
* Resolves a {@code java.lang.constant.DynamicConstantDesc}'s arguments.
*
* @param value The {@code java.lang.constant.DynamicConstantDesc} to resolve.
* @return An array of {@code java.lang.constant.ConstantDesc} describing the arguments of the supplied dynamic constant description.
*/
Object[] bootstrapArgs(Object value);
/**
* Resolves the dynamic constant description's name.
*
* @param value The {@code java.lang.constant.DynamicConstantDesc} to resolve.
* @return The dynamic constant description's name.
*/
String constantName(Object value);
/**
* Resolves a {@code java.lang.constant.ClassDesc} for the dynamic constant's type.
*
* @param value The {@code java.lang.constant.DynamicConstantDesc} to resolve.
* @return A {@code java.lang.constant.ClassDesc} describing the constant's type.
*/
Object constantType(Object value);
/**
* Resolves a {@code java.lang.constant.DirectMethodHandleDesc} representing the dynamic constant's bootstrap method.
*
* @param value The {@code java.lang.constant.DynamicConstantDesc} to resolve.
* @return A {@code java.lang.constant.DirectMethodHandleDesc} representing the dynamic constant's bootstrap method.
*/
Object bootstrapMethod(Object value);
}
}
}
/**
* Represents a {@code java.lang.invoke.MethodType} object.
*/
class MethodType implements JavaConstant {
/**
* A dispatcher for extracting information from a {@code java.lang.invoke.MethodType} instance.
*/
private static final Dispatcher DISPATCHER = AccessController.doPrivileged(JavaDispatcher.of(Dispatcher.class));
/**
* The return type of this method type.
*/
private final TypeDescription returnType;
/**
* The parameter types of this method type.
*/
private final List<? extends TypeDescription> parameterTypes;
/**
* Creates a method type for the given types.
*
* @param returnType The return type of the method type.
* @param parameterTypes The parameter types of the method type.
*/
protected MethodType(TypeDescription returnType, List<? extends TypeDescription> parameterTypes) {
this.returnType = returnType;
this.parameterTypes = parameterTypes;
}
/**
* Returns a method type representation of a loaded {@code MethodType} object.
*
* @param methodType A method type object to represent as a {@link JavaConstant}.
* @return The method type represented as a {@link MethodType}.
*/
public static MethodType ofLoaded(Object methodType) {
if (!JavaType.METHOD_TYPE.isInstance(methodType)) {
throw new IllegalArgumentException("Expected method type object: " + methodType);
}
return of(DISPATCHER.returnType(methodType), DISPATCHER.parameterArray(methodType));
}
/**
* Returns a method type description of the given return type and parameter types.
*
* @param returnType The return type to represent.
* @param parameterType The parameter types to represent.
* @return A method type of the given return type and parameter types.
*/
public static MethodType of(Class<?> returnType, Class<?>... parameterType) {
return of(TypeDescription.ForLoadedType.of(returnType), new TypeList.ForLoadedTypes(parameterType));
}
/**
* Returns a method type description of the given return type and parameter types.
*
* @param returnType The return type to represent.
* @param parameterType The parameter types to represent.
* @return A method type of the given return type and parameter types.
*/
public static MethodType of(TypeDescription returnType, TypeDescription... parameterType) {
return new MethodType(returnType, Arrays.asList(parameterType));
}
/**
* Returns a method type description of the given return type and parameter types.
*
* @param returnType The return type to represent.
* @param parameterTypes The parameter types to represent.
* @return A method type of the given return type and parameter types.
*/
public static MethodType of(TypeDescription returnType, List<? extends TypeDescription> parameterTypes) {
return new MethodType(returnType, parameterTypes);
}
/**
* Returns a method type description of the given method.
*
* @param method The method to extract the method type from.
* @return The method type of the given method.
*/
public static MethodType of(Method method) {
return of(new MethodDescription.ForLoadedMethod(method));
}
/**
* Returns a method type description of the given constructor.
*
* @param constructor The constructor to extract the method type from.
* @return The method type of the given constructor.
*/
public static MethodType of(Constructor<?> constructor) {
return of(new MethodDescription.ForLoadedConstructor(constructor));
}
/**
* Returns a method type description of the given method.
*
* @param methodDescription The method to extract the method type from.
* @return The method type of the given method.
*/
public static MethodType of(MethodDescription methodDescription) {
return new MethodType(methodDescription.getReturnType().asErasure(), methodDescription.getParameters().asTypeList().asErasures());
}
/**
* Returns a method type for a setter of the given field.
*
* @param field The field to extract a setter type for.
* @return The type of a setter for the given field.
*/
public static MethodType ofSetter(Field field) {
return ofSetter(new FieldDescription.ForLoadedField(field));
}
/**
* Returns a method type for a setter of the given field.
*
* @param fieldDescription The field to extract a setter type for.
* @return The type of a setter for the given field.
*/
public static MethodType ofSetter(FieldDescription fieldDescription) {
return new MethodType(TypeDescription.VOID, Collections.singletonList(fieldDescription.getType().asErasure()));
}
/**
* Returns a method type for a getter of the given field.
*
* @param field The field to extract a getter type for.
* @return The type of a getter for the given field.
*/
public static MethodType ofGetter(Field field) {
return ofGetter(new FieldDescription.ForLoadedField(field));
}
/**
* Returns a method type for a getter of the given field.
*
* @param fieldDescription The field to extract a getter type for.
* @return The type of a getter for the given field.
*/
public static MethodType ofGetter(FieldDescription fieldDescription) {
return new MethodType(fieldDescription.getType().asErasure(), Collections.<TypeDescription>emptyList());
}
/**
* Returns a method type for the given constant.
*
* @param instance The constant for which a constant method type should be created.
* @return A method type for the given constant.
*/
public static MethodType ofConstant(Object instance) {
return ofConstant(instance.getClass());
}
/**
* Returns a method type for the given constant type.
*
* @param type The constant type for which a constant method type should be created.
* @return A method type for the given constant type.
*/
public static MethodType ofConstant(Class<?> type) {
return ofConstant(TypeDescription.ForLoadedType.of(type));
}
/**
* Returns a method type for the given constant type.
*
* @param typeDescription The constant type for which a constant method type should be created.
* @return A method type for the given constant type.
*/
public static MethodType ofConstant(TypeDescription typeDescription) {
return new MethodType(typeDescription, Collections.<TypeDescription>emptyList());
}
/**
* Returns the return type of this method type.
*
* @return The return type of this method type.
*/
public TypeDescription getReturnType() {
return returnType;
}
/**
* Returns the parameter types of this method type.
*
* @return The parameter types of this method type.
*/
public TypeList getParameterTypes() {
return new TypeList.Explicit(parameterTypes);
}
/**
* Returns the method descriptor of this method type representation.
*
* @return The method descriptor of this method type representation.
*/
public String getDescriptor() {
StringBuilder stringBuilder = new StringBuilder("(");
for (TypeDescription parameterType : parameterTypes) {
stringBuilder.append(parameterType.getDescriptor());
}
return stringBuilder.append(')').append(returnType.getDescriptor()).toString();
}
/**
* {@inheritDoc}
*/
public Type asConstantPoolValue() {
StringBuilder stringBuilder = new StringBuilder().append('(');
for (TypeDescription parameterType : getParameterTypes()) {
stringBuilder.append(parameterType.getDescriptor());
}
return Type.getMethodType(stringBuilder.append(')').append(getReturnType().getDescriptor()).toString());
}
/**
* {@inheritDoc}
*/
public Object asConstantDescription() {
Object[] parameterTypes = Simple.CLASS_DESC.toArray(getParameterTypes().size());
for (int index = 0; index < getParameterTypes().size(); index++) {
parameterTypes[index] = Simple.CLASS_DESC.ofDescriptor(getParameterTypes().get(index).getDescriptor());
}
return Simple.METHOD_TYPE_DESC.of(Simple.CLASS_DESC.ofDescriptor(getReturnType().getDescriptor()), parameterTypes);
}
/**
* {@inheritDoc}
*/
public TypeDescription getTypeDescription() {
return JavaType.METHOD_TYPE.getTypeStub();
}
@Override
public int hashCode() {
int result = returnType.hashCode();
result = 31 * result + parameterTypes.hashCode();
return result;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof MethodType)) {
return false;
}
MethodType methodType = (MethodType) other;
return parameterTypes.equals(methodType.parameterTypes) && returnType.equals(methodType.returnType);
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder().append('(');
boolean first = true;
for (TypeDescription typeDescription : parameterTypes) {
if (first) {
first = false;
} else {
stringBuilder.append(',');
}
stringBuilder.append(typeDescription.getSimpleName());
}
return stringBuilder.append(')').append(returnType.getSimpleName()).toString();
}
/**
* A dispatcher for extracting information from a {@code java.lang.invoke.MethodType} instance.
*/
@JavaDispatcher.Proxied("java.lang.invoke.MethodType")
protected interface Dispatcher {
/**
* Extracts the return type of the supplied method type.
*
* @param methodType An instance of {@code java.lang.invoke.MethodType}.
* @return The return type that is described by the supplied instance.
*/
Class<?> returnType(Object methodType);
/**
* Extracts the parameter types of the supplied method type.
*
* @param methodType An instance of {@code java.lang.invoke.MethodType}.
* @return The parameter types that are described by the supplied instance.
*/
Class<?>[] parameterArray(Object methodType);
}
}
/**
* Represents a {@code java.lang.invoke.MethodHandle} object. Note that constant {@code MethodHandle}s cannot
* be represented within the constant pool of a Java class and can therefore not be represented as an instance of
* this representation order.
*/
class MethodHandle implements JavaConstant {
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodHandleInfo}.
*/
protected static final MethodHandleInfo METHOD_HANDLE_INFO = AccessController.doPrivileged(JavaDispatcher.of(MethodHandleInfo.class));
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodType}.
*/
protected static final MethodType METHOD_TYPE = AccessController.doPrivileged(JavaDispatcher.of(MethodType.class));
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodHandles}.
*/
protected static final MethodHandles METHOD_HANDLES = AccessController.doPrivileged(JavaDispatcher.of(MethodHandles.class));
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodHandles$Lookup}.
*/
protected static final MethodHandles.Lookup METHOD_HANDLES_LOOKUP = AccessController.doPrivileged(JavaDispatcher.of(MethodHandles.Lookup.class));
/**
* The handle type that is represented by this instance.
*/
private final HandleType handleType;
/**
* The owner type that is represented by this instance.
*/
private final TypeDescription ownerType;
/**
* The name that is represented by this instance.
*/
private final String name;
/**
* The return type that is represented by this instance.
*/
private final TypeDescription returnType;
/**
* The parameter types that is represented by this instance.
*/
private final List<? extends TypeDescription> parameterTypes;
/**
* Creates a method handle representation.
*
* @param handleType The handle type that is represented by this instance.
* @param ownerType The owner type that is represented by this instance.
* @param name The name that is represented by this instance.
* @param returnType The return type that is represented by this instance.
* @param parameterTypes The parameter types that is represented by this instance.
*/
protected MethodHandle(HandleType handleType,
TypeDescription ownerType,
String name,
TypeDescription returnType,
List<? extends TypeDescription> parameterTypes) {
this.handleType = handleType;
this.ownerType = ownerType;
this.name = name;
this.returnType = returnType;
this.parameterTypes = parameterTypes;
}
/**
* Creates a method handles representation of a loaded method handle which is analyzed using a public {@code MethodHandles.Lookup} object.
* A method handle can only be analyzed on virtual machines that support the corresponding API (Java 7+). For virtual machines before Java 8+,
* a method handle instance can only be analyzed by taking advantage of private APIs what might require a access context.
*
* @param methodHandle The loaded method handle to represent.
* @return A representation of the loaded method handle
*/
public static MethodHandle ofLoaded(Object methodHandle) {
return ofLoaded(methodHandle, METHOD_HANDLES.publicLookup());
}
/**
* Creates a method handles representation of a loaded method handle which is analyzed using the given lookup context.
* A method handle can only be analyzed on virtual machines that support the corresponding API (Java 7+). For virtual machines before Java 8+,
* a method handle instance can only be analyzed by taking advantage of private APIs what might require a access context.
*
* @param methodHandle The loaded method handle to represent.
* @param lookup The lookup object to use for analyzing the method handle.
* @return A representation of the loaded method handle
*/
public static MethodHandle ofLoaded(Object methodHandle, Object lookup) {
if (!JavaType.METHOD_HANDLE.isInstance(methodHandle)) {
throw new IllegalArgumentException("Expected method handle object: " + methodHandle);
} else if (!JavaType.METHOD_HANDLES_LOOKUP.isInstance(lookup)) {
throw new IllegalArgumentException("Expected method handle lookup object: " + lookup);
}
Object methodHandleInfo = ClassFileVersion.ofThisVm(ClassFileVersion.JAVA_V8).isAtMost(ClassFileVersion.JAVA_V7)
? METHOD_HANDLE_INFO.revealDirect(methodHandle)
: METHOD_HANDLES_LOOKUP.revealDirect(lookup, methodHandle);
Object methodType = METHOD_HANDLE_INFO.getMethodType(methodHandleInfo);
return new MethodHandle(HandleType.of(METHOD_HANDLE_INFO.getReferenceKind(methodHandleInfo)),
TypeDescription.ForLoadedType.of(METHOD_HANDLE_INFO.getDeclaringClass(methodHandleInfo)),
METHOD_HANDLE_INFO.getName(methodHandleInfo),
TypeDescription.ForLoadedType.of(METHOD_TYPE.returnType(methodType)),
new TypeList.ForLoadedTypes(METHOD_TYPE.parameterArray(methodType)));
}
/**
* Creates a method handle representation of the given method.
*
* @param method The method ro represent.
* @return A method handle representing the given method.
*/
public static MethodHandle of(Method method) {
return of(new MethodDescription.ForLoadedMethod(method));
}
/**
* Creates a method handle representation of the given constructor.
*
* @param constructor The constructor ro represent.
* @return A method handle representing the given constructor.
*/
public static MethodHandle of(Constructor<?> constructor) {
return of(new MethodDescription.ForLoadedConstructor(constructor));
}
/**
* Creates a method handle representation of the given method.
*
* @param methodDescription The method ro represent.
* @return A method handle representing the given method.
*/
public static MethodHandle of(MethodDescription.InDefinedShape methodDescription) {
return new MethodHandle(HandleType.of(methodDescription),
methodDescription.getDeclaringType().asErasure(),
methodDescription.getInternalName(),
methodDescription.getReturnType().asErasure(),
methodDescription.getParameters().asTypeList().asErasures());
}
/**
* Creates a method handle representation of the given method for an explicit special method invocation of an otherwise virtual method.
*
* @param method The method ro represent.
* @param type The type on which the method is to be invoked on as a special method invocation.
* @return A method handle representing the given method as special method invocation.
*/
public static MethodHandle ofSpecial(Method method, Class<?> type) {
return ofSpecial(new MethodDescription.ForLoadedMethod(method), TypeDescription.ForLoadedType.of(type));
}
/**
* Creates a method handle representation of the given method for an explicit special method invocation of an otherwise virtual method.
*
* @param methodDescription The method ro represent.
* @param typeDescription The type on which the method is to be invoked on as a special method invocation.
* @return A method handle representing the given method as special method invocation.
*/
public static MethodHandle ofSpecial(MethodDescription.InDefinedShape methodDescription, TypeDescription typeDescription) {
if (!methodDescription.isSpecializableFor(typeDescription)) {
throw new IllegalArgumentException("Cannot specialize " + methodDescription + " for " + typeDescription);
}
return new MethodHandle(HandleType.ofSpecial(methodDescription),
typeDescription,
methodDescription.getInternalName(),
methodDescription.getReturnType().asErasure(),
methodDescription.getParameters().asTypeList().asErasures());
}
/**
* Returns a method handle for a setter of the given field.
*
* @param field The field to represent.
* @return A method handle for a setter of the given field.
*/
public static MethodHandle ofGetter(Field field) {
return ofGetter(new FieldDescription.ForLoadedField(field));
}
/**
* Returns a method handle for a setter of the given field.
*
* @param fieldDescription The field to represent.
* @return A method handle for a setter of the given field.
*/
public static MethodHandle ofGetter(FieldDescription.InDefinedShape fieldDescription) {
return new MethodHandle(HandleType.ofGetter(fieldDescription),
fieldDescription.getDeclaringType().asErasure(),
fieldDescription.getInternalName(),
fieldDescription.getType().asErasure(),
Collections.<TypeDescription>emptyList());
}
/**
* Returns a method handle for a getter of the given field.
*
* @param field The field to represent.
* @return A method handle for a getter of the given field.
*/
public static MethodHandle ofSetter(Field field) {
return ofSetter(new FieldDescription.ForLoadedField(field));
}
/**
* Returns a method handle for a getter of the given field.
*
* @param fieldDescription The field to represent.
* @return A method handle for a getter of the given field.
*/
public static MethodHandle ofSetter(FieldDescription.InDefinedShape fieldDescription) {
return new MethodHandle(HandleType.ofSetter(fieldDescription),
fieldDescription.getDeclaringType().asErasure(),
fieldDescription.getInternalName(),
TypeDescription.VOID,
Collections.singletonList(fieldDescription.getType().asErasure()));
}
/**
* Returns the lookup type of the provided {@code java.lang.invoke.MethodHandles$Lookup} instance.
*
* @param callerClassLookup An instance of {@code java.lang.invoke.MethodHandles$Lookup}.
* @return The instance's lookup type.
*/
public static Class<?> lookupType(Object callerClassLookup) {
return METHOD_HANDLES_LOOKUP.lookupClass(callerClassLookup);
}
/**
* {@inheritDoc}
*/
public Handle asConstantPoolValue() {
return new Handle(getHandleType().getIdentifier(),
getOwnerType().getInternalName(),
getName(),
getDescriptor(),
getOwnerType().isInterface());
}
/**
* {@inheritDoc}
*/
public Object asConstantDescription() {
return Simple.METHOD_HANDLE_DESC.of(Simple.DIRECT_METHOD_HANDLE_DESC_KIND.valueOf(getHandleType().getIdentifier(), getOwnerType().isInterface()),
Simple.CLASS_DESC.ofDescriptor(getOwnerType().getDescriptor()),
getName(),
getDescriptor());
}
/**
* {@inheritDoc}
*/
public TypeDescription getTypeDescription() {
return JavaType.METHOD_HANDLE.getTypeStub();
}
/**
* Returns the handle type represented by this instance.
*
* @return The handle type represented by this instance.
*/
public HandleType getHandleType() {
return handleType;
}
/**
* Returns the owner type of this instance.
*
* @return The owner type of this instance.
*/
public TypeDescription getOwnerType() {
return ownerType;
}
/**
* Returns the name represented by this instance.
*
* @return The name represented by this instance.
*/
public String getName() {
return name;
}
/**
* Returns the return type represented by this instance.
*
* @return The return type represented by this instance.
*/
public TypeDescription getReturnType() {
return returnType;
}
/**
* Returns the parameter types represented by this instance.
*
* @return The parameter types represented by this instance.
*/
public TypeList getParameterTypes() {
return new TypeList.Explicit(parameterTypes);
}
/**
* Returns the method descriptor of this method handle representation.
*
* @return The method descriptor of this method handle representation.
*/
public String getDescriptor() {
switch (handleType) {
case GET_FIELD:
case GET_STATIC_FIELD:
return returnType.getDescriptor();
case PUT_FIELD:
case PUT_STATIC_FIELD:
return parameterTypes.get(0).getDescriptor();
default:
StringBuilder stringBuilder = new StringBuilder().append('(');
for (TypeDescription parameterType : parameterTypes) {
stringBuilder.append(parameterType.getDescriptor());
}
return stringBuilder.append(')').append(returnType.getDescriptor()).toString();
}
}
@Override
public int hashCode() {
int result = handleType.hashCode();
result = 31 * result + ownerType.hashCode();
result = 31 * result + name.hashCode();
result = 31 * result + returnType.hashCode();
result = 31 * result + parameterTypes.hashCode();
return result;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (!(other instanceof MethodHandle)) {
return false;
}
MethodHandle methodHandle = (MethodHandle) other;
return handleType == methodHandle.handleType
&& name.equals(methodHandle.name)
&& ownerType.equals(methodHandle.ownerType)
&& parameterTypes.equals(methodHandle.parameterTypes)
&& returnType.equals(methodHandle.returnType);
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder()
.append(handleType.name())
.append(ownerType.isInterface() && !handleType.isField() && handleType != HandleType.INVOKE_INTERFACE
? "@interface"
: "")
.append('/')
.append(ownerType.getSimpleName())
.append("::")
.append(name)
.append('(');
boolean first = true;
for (TypeDescription typeDescription : parameterTypes) {
if (first) {
first = false;
} else {
stringBuilder.append(',');
}
stringBuilder.append(typeDescription.getSimpleName());
}
return stringBuilder.append(')').append(returnType.getSimpleName()).toString();
}
/**
* A representation of a method handle's type.
*/
public enum HandleType {
/**
* A handle representing an invokevirtual invocation.
*/
INVOKE_VIRTUAL(Opcodes.H_INVOKEVIRTUAL, false),
/**
* A handle representing an invokestatic invocation.
*/
INVOKE_STATIC(Opcodes.H_INVOKESTATIC, false),
/**
* A handle representing an invokespecial invocation for a non-constructor.
*/
INVOKE_SPECIAL(Opcodes.H_INVOKESPECIAL, false),
/**
* A handle representing an invokeinterface invocation.
*/
INVOKE_INTERFACE(Opcodes.H_INVOKEINTERFACE, false),
/**
* A handle representing an invokespecial invocation for a constructor.
*/
INVOKE_SPECIAL_CONSTRUCTOR(Opcodes.H_NEWINVOKESPECIAL, false),
/**
* A handle representing a write of a non-static field invocation.
*/
PUT_FIELD(Opcodes.H_PUTFIELD, true),
/**
* A handle representing a read of a non-static field invocation.
*/
GET_FIELD(Opcodes.H_GETFIELD, true),
/**
* A handle representing a write of a static field invocation.
*/
PUT_STATIC_FIELD(Opcodes.H_PUTSTATIC, true),
/**
* A handle representing a read of a static field invocation.
*/
GET_STATIC_FIELD(Opcodes.H_GETSTATIC, true);
/**
* The represented identifier.
*/
private final int identifier;
/**
* {@code} true if this handle type represents a field handle.
*/
private final boolean field;
/**
* Creates a new handle type.
*
* @param identifier The represented identifier.
* @param field {@code} true if this handle type represents a field handle.
*/
HandleType(int identifier, boolean field) {
this.identifier = identifier;
this.field = field;
}
/**
* Extracts a handle type for invoking the given method.
*
* @param methodDescription The method for which a handle type should be found.
* @return The handle type for the given method.
*/
protected static HandleType of(MethodDescription.InDefinedShape methodDescription) {
if (methodDescription.isTypeInitializer()) {
throw new IllegalArgumentException("Cannot create handle of type initializer " + methodDescription);
} else if (methodDescription.isStatic()) {
return INVOKE_STATIC;
} else if (methodDescription.isConstructor()) { // Private constructors must use this handle type.
return INVOKE_SPECIAL_CONSTRUCTOR;
} else if (methodDescription.isPrivate()) {
return INVOKE_SPECIAL;
} else if (methodDescription.getDeclaringType().isInterface()) {
return INVOKE_INTERFACE;
} else {
return INVOKE_VIRTUAL;
}
}
/**
* Extracts a handle type for the given identifier.
*
* @param identifier The identifier to extract a handle type for.
* @return The representing handle type.
*/
protected static HandleType of(int identifier) {
for (HandleType handleType : HandleType.values()) {
if (handleType.getIdentifier() == identifier) {
return handleType;
}
}
throw new IllegalArgumentException("Unknown handle type: " + identifier);
}
/**
* Extracts a handle type for invoking the given method via invokespecial.
*
* @param methodDescription The method for which a handle type should be found.
* @return The handle type for the given method.
*/
protected static HandleType ofSpecial(MethodDescription.InDefinedShape methodDescription) {
if (methodDescription.isStatic() || methodDescription.isAbstract()) {
throw new IllegalArgumentException("Cannot invoke " + methodDescription + " via invokespecial");
}
return methodDescription.isConstructor()
? INVOKE_SPECIAL_CONSTRUCTOR
: INVOKE_SPECIAL;
}
/**
* Extracts a handle type for a getter of the given field.
*
* @param fieldDescription The field for which to create a getter handle.
* @return The corresponding handle type.
*/
protected static HandleType ofGetter(FieldDescription.InDefinedShape fieldDescription) {
return fieldDescription.isStatic()
? GET_STATIC_FIELD
: GET_FIELD;
}
/**
* Extracts a handle type for a setter of the given field.
*
* @param fieldDescription The field for which to create a setter handle.
* @return The corresponding handle type.
*/
protected static HandleType ofSetter(FieldDescription.InDefinedShape fieldDescription) {
return fieldDescription.isStatic()
? PUT_STATIC_FIELD
: PUT_FIELD;
}
/**
* Returns the represented identifier.
*
* @return The represented identifier.
*/
public int getIdentifier() {
return identifier;
}
/**
* Returns {@code} true if this handle type represents a field handle.
*
* @return {@code} true if this handle type represents a field handle.
*/
public boolean isField() {
return field;
}
}
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodHandleInfo}.
*/
@JavaDispatcher.Proxied("java.lang.invoke.MethodHandleInfo")
protected interface MethodHandleInfo {
/**
* Returns the name of the method handle info.
*
* @param value The {@code java.lang.invoke.MethodHandleInfo} to resolve.
* @return The name of the method handle info.
*/
String getName(Object value);
/**
* Returns the declaring type of the method handle info.
*
* @param value The {@code java.lang.invoke.MethodHandleInfo} to resolve.
* @return The declaring type of the method handle info.
*/
Class<?> getDeclaringClass(Object value);
/**
* Returns the reference kind of the method handle info.
*
* @param value The {@code java.lang.invoke.MethodHandleInfo} to resolve.
* @return The reference kind of the method handle info.
*/
int getReferenceKind(Object value);
/**
* Returns the {@code java.lang.invoke.MethodType} of the method handle info.
*
* @param value The {@code java.lang.invoke.MethodHandleInfo} to resolve.
* @return The {@code java.lang.invoke.MethodType} of the method handle info.
*/
Object getMethodType(Object value);
/**
* Returns the {@code java.lang.invoke.MethodHandleInfo} of the provided method handle. This method
* was available on Java 7 but replaced by a lookup-based method in Java 8 and later.
*
* @param handle The {@code java.lang.invoke.MethodHandle} to resolve.
* @return A {@code java.lang.invoke.MethodHandleInfo} to describe the supplied method handle.
*/
@JavaDispatcher.IsConstructor
Object revealDirect(@JavaDispatcher.Proxied("java.lang.invoke.MethodHandle") Object handle);
}
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodType}.
*/
@JavaDispatcher.Proxied("java.lang.invoke.MethodType")
protected interface MethodType {
/**
* Resolves a method type's return type.
*
* @param value The {@code java.lang.invoke.MethodType} to resolve.
* @return The method type's return type.
*/
Class<?> returnType(Object value);
/**
* Resolves a method type's parameter type.
*
* @param value The {@code java.lang.invoke.MethodType} to resolve.
* @return The method type's parameter types.
*/
Class<?>[] parameterArray(Object value);
}
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodHandles}.
*/
@JavaDispatcher.Proxied("java.lang.invoke.MethodHandles")
protected interface MethodHandles {
/**
* Resolves the public {@code java.lang.invoke.MethodHandles$Lookup}.
*
* @return The public {@code java.lang.invoke.MethodHandles$Lookup}.
*/
@JavaDispatcher.IsStatic
Object publicLookup();
/**
* A dispatcher to interact with {@code java.lang.invoke.MethodHandles$Lookup}.
*/
@JavaDispatcher.Proxied("java.lang.invoke.MethodHandles$Lookup")
interface Lookup {
/**
* Resolves the lookup type for a given lookup instance.
*
* @param value The {@code java.lang.invoke.MethodHandles$Lookup} to resolve.
* @return The lookup's lookup class.
*/
Class<?> lookupClass(Object value);
/**
* Reveals the {@code java.lang.invoke.MethodHandleInfo} for the supplied method handle.
*
* @param value The {@code java.lang.invoke.MethodHandles$Lookup} to use for resolving the supplied handle
* @param handle The {@code java.lang.invoke.MethodHandle} to resolve.
* @return A {@code java.lang.invoke.MethodHandleInfo} representing the supplied method handle.
*/
Object revealDirect(Object value, @JavaDispatcher.Proxied("java.lang.invoke.MethodHandle") Object handle);
}
}
}
/**
* Represents a dynamically resolved constant pool entry of a class file. This feature is supported for class files in version 11 and newer.
*/
class Dynamic implements JavaConstant {
/**
* The default name of a dynamic constant.
*/
public static final String DEFAULT_NAME = "_";
/**
* The name of the dynamic constant.
*/
private final String name;
/**
* A description of the represented value's type.
*/
private final TypeDescription typeDescription;
/**
* A handle representation of the bootstrap method.
*/
private final MethodHandle bootstrap;
/**
* A list of the arguments to the dynamic constant.
*/
private final List<JavaConstant> arguments;
/**
* Creates a dynamic resolved constant.
*
* @param name The name of the dynamic constant.
* @param typeDescription A description of the represented value's type.
* @param bootstrap A handle representation of the bootstrap method.
* @param arguments A list of the arguments to the dynamic constant.
*/
protected Dynamic(String name, TypeDescription typeDescription, MethodHandle bootstrap, List<JavaConstant> arguments) {
this.name = name;
this.typeDescription = typeDescription;
this.bootstrap = bootstrap;
this.arguments = arguments;
}
/**
* Returns a constant {@code null} value of type {@link Object}.
*
* @return A dynamically resolved null constant.
*/
public static Dynamic ofNullConstant() {
return new Dynamic(DEFAULT_NAME,
TypeDescription.OBJECT,
new MethodHandle(MethodHandle.HandleType.INVOKE_STATIC,
JavaType.CONSTANT_BOOTSTRAPS.getTypeStub(),
"nullConstant",
TypeDescription.OBJECT,
Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(), TypeDescription.STRING, TypeDescription.CLASS)),
Collections.<JavaConstant>emptyList());
}
/**
* Returns a {@link Class} constant for a primitive type.
*
* @param type The primitive type to represent.
* @return A dynamically resolved primitive type constant.
*/
public static JavaConstant ofPrimitiveType(Class<?> type) {
return ofPrimitiveType(TypeDescription.ForLoadedType.of(type));
}
/**
* Returns a {@link Class} constant for a primitive type.
*
* @param typeDescription The primitive type to represent.
* @return A dynamically resolved primitive type constant.
*/
public static JavaConstant ofPrimitiveType(TypeDescription typeDescription) {
if (!typeDescription.isPrimitive()) {
throw new IllegalArgumentException("Not a primitive type: " + typeDescription);
}
return new Dynamic(typeDescription.getDescriptor(),
TypeDescription.CLASS,
new MethodHandle(MethodHandle.HandleType.INVOKE_STATIC,
JavaType.CONSTANT_BOOTSTRAPS.getTypeStub(),
"primitiveClass",
TypeDescription.CLASS,
Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(), TypeDescription.STRING, TypeDescription.CLASS)),
Collections.<JavaConstant>emptyList());
}
/**
* Returns a {@link Enum} value constant.
*
* @param enumeration The enumeration value to represent.
* @return A dynamically resolved enumeration constant.
*/
public static JavaConstant ofEnumeration(Enum<?> enumeration) {
return ofEnumeration(new EnumerationDescription.ForLoadedEnumeration(enumeration));
}
/**
* Returns a {@link Enum} value constant.
*
* @param enumerationDescription The enumeration value to represent.
* @return A dynamically resolved enumeration constant.
*/
public static JavaConstant ofEnumeration(EnumerationDescription enumerationDescription) {
return new Dynamic(enumerationDescription.getValue(),
enumerationDescription.getEnumerationType(),
new MethodHandle(MethodHandle.HandleType.INVOKE_STATIC,
JavaType.CONSTANT_BOOTSTRAPS.getTypeStub(),
"enumConstant",
TypeDescription.ForLoadedType.of(Enum.class),
Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(), TypeDescription.STRING, TypeDescription.CLASS)),
Collections.<JavaConstant>emptyList());
}
/**
* Returns a {@code static}, {@code final} field constant.
*
* @param field The field to represent a value of.
* @return A dynamically resolved field value constant.
*/
public static Dynamic ofField(Field field) {
return ofField(new FieldDescription.ForLoadedField(field));
}
/**
* Returns a {@code static}, {@code final} field constant.
*
* @param fieldDescription The field to represent a value of.
* @return A dynamically resolved field value constant.
*/
public static Dynamic ofField(FieldDescription.InDefinedShape fieldDescription) {
if (!fieldDescription.isStatic() || !fieldDescription.isFinal()) {
throw new IllegalArgumentException("Field must be static and final: " + fieldDescription);
}
boolean selfDeclared = fieldDescription.getType().isPrimitive()
? fieldDescription.getType().asErasure().asBoxed().equals(fieldDescription.getType().asErasure())
: fieldDescription.getDeclaringType().equals(fieldDescription.getType().asErasure());
return new Dynamic(fieldDescription.getInternalName(),
fieldDescription.getType().asErasure(),
new MethodHandle(MethodHandle.HandleType.INVOKE_STATIC,
JavaType.CONSTANT_BOOTSTRAPS.getTypeStub(),
"getStaticFinal",
TypeDescription.OBJECT,
selfDeclared
? Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(), TypeDescription.STRING, TypeDescription.CLASS)
: Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(), TypeDescription.STRING, TypeDescription.CLASS, TypeDescription.CLASS)),
selfDeclared
? Collections.<JavaConstant>emptyList()
: Collections.singletonList(Simple.of(fieldDescription.getDeclaringType())));
}
/**
* Represents a constant that is resolved by invoking a {@code static} factory method.
*
* @param method The method to invoke to create the represented constant value.
* @param constant The method's constant arguments.
* @return A dynamic constant that is resolved by the supplied factory method.
*/
public static Dynamic ofInvocation(Method method, Object... constant) {
return ofInvocation(method, Arrays.asList(constant));
}
/**
* Represents a constant that is resolved by invoking a {@code static} factory method.
*
* @param method The method to invoke to create the represented constant value.
* @param constants The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that is resolved by the supplied factory method.
*/
public static Dynamic ofInvocation(Method method, List<?> constants) {
return ofInvocation(new MethodDescription.ForLoadedMethod(method), constants);
}
/**
* Represents a constant that is resolved by invoking a constructor.
*
* @param constructor The constructor to invoke to create the represented constant value.
* @param constant The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that is resolved by the supplied constuctor.
*/
public static Dynamic ofInvocation(Constructor<?> constructor, Object... constant) {
return ofInvocation(constructor, Arrays.asList(constant));
}
/**
* Represents a constant that is resolved by invoking a constructor.
*
* @param constructor The constructor to invoke to create the represented constant value.
* @param constants The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that is resolved by the supplied constuctor.
*/
public static Dynamic ofInvocation(Constructor<?> constructor, List<?> constants) {
return ofInvocation(new MethodDescription.ForLoadedConstructor(constructor), constants);
}
/**
* Represents a constant that is resolved by invoking a {@code static} factory method or a constructor.
*
* @param methodDescription The method or constructor to invoke to create the represented constant value.
* @param constant The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that is resolved by the supplied factory method or constructor.
*/
public static Dynamic ofInvocation(MethodDescription.InDefinedShape methodDescription, Object... constant) {
return ofInvocation(methodDescription, Arrays.asList(constant));
}
/**
* Represents a constant that is resolved by invoking a {@code static} factory method or a constructor.
*
* @param methodDescription The method or constructor to invoke to create the represented constant value.
* @param constants The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that is resolved by the supplied factory method or constructor.
*/
public static Dynamic ofInvocation(MethodDescription.InDefinedShape methodDescription, List<?> constants) {
if (!methodDescription.isConstructor() && methodDescription.getReturnType().represents(void.class)) {
throw new IllegalArgumentException("Bootstrap method is no constructor or non-void static factory: " + methodDescription);
} else if (methodDescription.isVarArgs()
? methodDescription.getParameters().size() + (methodDescription.isStatic() || methodDescription.isConstructor() ? 0 : 1) > constants.size() + 1
: methodDescription.getParameters().size() + (methodDescription.isStatic() || methodDescription.isConstructor() ? 0 : 1) != constants.size()) {
throw new IllegalArgumentException("Cannot assign " + constants + " to " + methodDescription);
}
List<TypeDescription> parameters = (methodDescription.isStatic() || methodDescription.isConstructor()
? methodDescription.getParameters().asTypeList().asErasures()
: CompoundList.of(methodDescription.getDeclaringType(), methodDescription.getParameters().asTypeList().asErasures()));
Iterator<TypeDescription> iterator;
if (methodDescription.isVarArgs()) {
iterator = CompoundList.of(parameters.subList(0, parameters.size() - 1), Collections.nCopies(
constants.size() - parameters.size() + 1,
parameters.get(parameters.size() - 1).getComponentType())).iterator();
} else {
iterator = parameters.iterator();
}
List<JavaConstant> arguments = new ArrayList<JavaConstant>(constants.size() + 1);
arguments.add(MethodHandle.of(methodDescription));
for (Object constant : constants) {
JavaConstant argument = Simple.wrap(constant);
if (!argument.getTypeDescription().isAssignableTo(iterator.next())) {
throw new IllegalArgumentException("Cannot assign " + constants + " to " + methodDescription);
}
arguments.add(argument);
}
return new Dynamic(DEFAULT_NAME,
methodDescription.isConstructor()
? methodDescription.getDeclaringType()
: methodDescription.getReturnType().asErasure(),
new MethodHandle(MethodHandle.HandleType.INVOKE_STATIC,
JavaType.CONSTANT_BOOTSTRAPS.getTypeStub(),
"invoke",
TypeDescription.OBJECT,
Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(),
TypeDescription.STRING,
TypeDescription.CLASS,
JavaType.METHOD_HANDLE.getTypeStub(),
TypeDescription.ArrayProjection.of(TypeDescription.OBJECT))),
arguments);
}
/**
* Resolves a var handle constant for a field.
*
* @param field The field to represent a var handle for.
* @return A dynamic constant that represents the created var handle constant.
*/
public static JavaConstant ofVarHandle(Field field) {
return ofVarHandle(new FieldDescription.ForLoadedField(field));
}
/**
* Resolves a var handle constant for a field.
*
* @param fieldDescription The field to represent a var handle for.
* @return A dynamic constant that represents the created var handle constant.
*/
public static JavaConstant ofVarHandle(FieldDescription.InDefinedShape fieldDescription) {
return new Dynamic(fieldDescription.getInternalName(),
JavaType.VAR_HANDLE.getTypeStub(),
new MethodHandle(MethodHandle.HandleType.INVOKE_STATIC,
JavaType.CONSTANT_BOOTSTRAPS.getTypeStub(),
fieldDescription.isStatic()
? "staticFieldVarHandle"
: "fieldVarHandle",
JavaType.VAR_HANDLE.getTypeStub(),
Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(),
TypeDescription.STRING,
TypeDescription.CLASS,
TypeDescription.CLASS,
TypeDescription.CLASS)),
Arrays.asList(Simple.of(fieldDescription.getDeclaringType()), Simple.of(fieldDescription.getType().asErasure())));
}
/**
* Resolves a var handle constant for an array.
*
* @param type The array type for which the var handle is resolved.
* @return A dynamic constant that represents the created var handle constant.
*/
public static JavaConstant ofArrayVarHandle(Class<?> type) {
return ofArrayVarHandle(TypeDescription.ForLoadedType.of(type));
}
/**
* Resolves a var handle constant for an array.
*
* @param typeDescription The array type for which the var handle is resolved.
* @return A dynamic constant that represents the created var handle constant.
*/
public static JavaConstant ofArrayVarHandle(TypeDescription typeDescription) {
if (!typeDescription.isArray()) {
throw new IllegalArgumentException("Not an array type: " + typeDescription);
}
return new Dynamic(DEFAULT_NAME,
JavaType.VAR_HANDLE.getTypeStub(),
new MethodHandle(MethodHandle.HandleType.INVOKE_STATIC,
JavaType.CONSTANT_BOOTSTRAPS.getTypeStub(),
"arrayVarHandle",
JavaType.VAR_HANDLE.getTypeStub(),
Arrays.asList(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub(),
TypeDescription.STRING,
TypeDescription.CLASS,
TypeDescription.CLASS)),
Collections.singletonList(Simple.of(typeDescription)));
}
/**
* Binds the supplied bootstrap method for the resolution of a dynamic constant.
*
* @param name The name of the bootstrap constant that is provided to the bootstrap method or constructor.
* @param method The bootstrap method to invoke.
* @param constant The arguments for the bootstrap method represented as primitive wrapper types,
* {@link String}, {@link TypeDescription} or {@link JavaConstant} values or their loaded forms.
* @return A dynamic constant that represents the bootstrapped method's result.
*/
public static Dynamic bootstrap(String name, Method method, Object... constant) {
return bootstrap(name, method, Arrays.asList(constant));
}
/**
* Binds the supplied bootstrap method for the resolution of a dynamic constant.
*
* @param name The name of the bootstrap constant that is provided to the bootstrap method or constructor.
* @param method The bootstrap method to invoke.
* @param constants The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that represents the bootstrapped method's result.
*/
public static Dynamic bootstrap(String name, Method method, List<?> constants) {
return bootstrap(name, new MethodDescription.ForLoadedMethod(method), constants);
}
/**
* Binds the supplied bootstrap constructor for the resolution of a dynamic constant.
*
* @param name The name of the bootstrap constant that is provided to the bootstrap method or constructor.
* @param constructor The bootstrap constructor to invoke.
* @param constant The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that represents the bootstrapped constructor's result.
*/
public static Dynamic bootstrap(String name, Constructor<?> constructor, Object... constant) {
return bootstrap(name, constructor, Arrays.asList(constant));
}
/**
* Binds the supplied bootstrap constructor for the resolution of a dynamic constant.
*
* @param name The name of the bootstrap constant that is provided to the bootstrap method or constructor.
* @param constructor The bootstrap constructor to invoke.
* @param constants The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that represents the bootstrapped constructor's result.
*/
public static Dynamic bootstrap(String name, Constructor<?> constructor, List<?> constants) {
return bootstrap(name, new MethodDescription.ForLoadedConstructor(constructor), constants);
}
/**
* Binds the supplied bootstrap method or constructor for the resolution of a dynamic constant.
*
* @param name The name of the bootstrap constant that is provided to the bootstrap method or constructor.
* @param bootstrapMethod The bootstrap method or constructor to invoke.
* @param constant The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that represents the bootstrapped method's or constructor's result.
*/
public static Dynamic bootstrap(String name, MethodDescription.InDefinedShape bootstrapMethod, Object... constant) {
return bootstrap(name, bootstrapMethod, Arrays.asList(constant));
}
/**
* Binds the supplied bootstrap method or constructor for the resolution of a dynamic constant.
*
* @param name The name of the bootstrap constant that is provided to the bootstrap method or constructor.
* @param bootstrap The bootstrap method or constructor to invoke.
* @param constants The constant values passed to the bootstrap method. Values can be represented either
* as {@link TypeDescription}, as {@link JavaConstant}, as {@link String} or a primitive
* {@code int}, {@code long}, {@code float} or {@code double} represented as wrapper type.
* @return A dynamic constant that represents the bootstrapped method's or constructor's result.
*/
public static Dynamic bootstrap(String name, MethodDescription.InDefinedShape bootstrap, List<?> constants) {
if (name.length() == 0 || name.contains(".")) {
throw new IllegalArgumentException("Not a valid field name: " + name);
}
List<JavaConstant> arguments = new ArrayList<JavaConstant>(constants.size());
List<TypeDescription> types = new ArrayList<TypeDescription>(constants.size());
for (Object constant : constants) {
JavaConstant argument = JavaConstant.Simple.wrap(constant);
arguments.add(argument);
types.add(argument.getTypeDescription());
}
if (!bootstrap.isConstantBootstrap(types)) {
throw new IllegalArgumentException("Not a valid bootstrap method " + bootstrap + " for " + arguments);
}
return new Dynamic(name,
bootstrap.isConstructor()
? bootstrap.getDeclaringType()
: bootstrap.getReturnType().asErasure(),
new MethodHandle(bootstrap.isConstructor() ? MethodHandle.HandleType.INVOKE_SPECIAL_CONSTRUCTOR : MethodHandle.HandleType.INVOKE_STATIC,
bootstrap.isConstructor()
? bootstrap.getDeclaringType()
: bootstrap.getReturnType().asErasure(),
bootstrap.getInternalName(),
bootstrap.getReturnType().asErasure(),
bootstrap.getParameters().asTypeList().asErasures()),
arguments);
}
/**
* Returns the name of the dynamic constant.
*
* @return The name of the dynamic constant.
*/
public String getName() {
return name;
}
/**
* Returns a handle representation of the bootstrap method.
*
* @return A handle representation of the bootstrap method.
*/
public MethodHandle getBootstrap() {
return bootstrap;
}
/**
* Returns a list of the arguments to the dynamic constant.
*
* @return A list of the arguments to the dynamic constant.
*/
public List<JavaConstant> getArguments() {
return arguments;
}
/**
* Resolves this {@link Dynamic} constant to resolve the returned instance to the supplied type. The type must be a subtype of the
* bootstrap method's return type. Constructors cannot be resolved to a different type.
*
* @param type The type to resolve the bootstrapped value to.
* @return This dynamic constant but resolved to the supplied type.
*/
public JavaConstant withType(Class<?> type) {
return withType(TypeDescription.ForLoadedType.of(type));
}
/**
* Resolves this {@link Dynamic} constant to resolve the returned instance to the supplied type. The type must be a subtype of the
* bootstrap method's return type. Constructors cannot be resolved to a different type.
*
* @param typeDescription The type to resolve the bootstrapped value to.
* @return This dynamic constant but resolved to the supplied type.
*/
public JavaConstant withType(TypeDescription typeDescription) {
if (typeDescription.represents(void.class)) {
throw new IllegalArgumentException("Constant value cannot represent void");
} else if (getBootstrap().getName().equals(MethodDescription.CONSTRUCTOR_INTERNAL_NAME)
? !getTypeDescription().isAssignableTo(typeDescription)
: (!typeDescription.asBoxed().isInHierarchyWith(getTypeDescription().asBoxed()))) {
throw new IllegalArgumentException(typeDescription + " is not compatible with bootstrapped type " + getTypeDescription());
}
return new Dynamic(getName(), typeDescription, getBootstrap(), getArguments());
}
/**
* {@inheritDoc}
*/
public ConstantDynamic asConstantPoolValue() {
Object[] arguments = new Object[getArguments().size()];
for (int index = 0; index < arguments.length; index++) {
arguments[index] = getArguments().get(index).asConstantPoolValue();
}
return new ConstantDynamic(getName(),
getTypeDescription().getDescriptor(),
getBootstrap().asConstantPoolValue(),
arguments);
}
/**
* {@inheritDoc}
*/
public Object asConstantDescription() {
Object[] argument = Simple.CONSTANT_DESC.toArray(getArguments().size());
for (int index = 0; index < argument.length; index++) {
argument[index] = getArguments().get(index).asConstantDescription();
}
return Simple.DYNAMIC_CONSTANT_DESC.ofCanonical(Simple.METHOD_HANDLE_DESC.of(
Simple.DIRECT_METHOD_HANDLE_DESC_KIND.valueOf(getBootstrap().getHandleType().getIdentifier(), getBootstrap().getOwnerType().isInterface()),
Simple.CLASS_DESC.ofDescriptor(getBootstrap().getOwnerType().getDescriptor()),
getBootstrap().getName(),
getBootstrap().getDescriptor()), getName(), Simple.CLASS_DESC.ofDescriptor(getTypeDescription().getDescriptor()), argument);
}
/**
* {@inheritDoc}
*/
public TypeDescription getTypeDescription() {
return typeDescription;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + typeDescription.hashCode();
result = 31 * result + bootstrap.hashCode();
result = 31 * result + arguments.hashCode();
return result;
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Dynamic dynamic = (Dynamic) object;
if (!name.equals(dynamic.name)) return false;
if (!typeDescription.equals(dynamic.typeDescription)) return false;
if (!bootstrap.equals(dynamic.bootstrap)) return false;
return arguments.equals(dynamic.arguments);
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder()
.append(getBootstrap().getOwnerType().getSimpleName())
.append("::")
.append(getBootstrap().getName())
.append('(')
.append(getName().equals(DEFAULT_NAME) ? "" : getName())
.append('/');
boolean first = true;
for (JavaConstant constant : getArguments()) {
if (first) {
first = false;
} else {
stringBuilder.append(',');
}
stringBuilder.append(constant.toString());
}
return stringBuilder.append(')').append(getTypeDescription().getSimpleName()).toString();
}
}
}
|
Correct parameter types.
|
byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java
|
Correct parameter types.
|
<ide><path>yte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java
<ide> Type methodType = Type.getMethodType(DIRECT_METHOD_HANDLE_DESC.lookupDescriptor(DYNAMIC_CONSTANT_DESC.bootstrapMethod(value)));
<ide> List<TypeDescription> parameterTypes = new ArrayList<TypeDescription>(methodType.getArgumentTypes().length);
<ide> for (Type type : methodType.getArgumentTypes()) {
<del> parameterTypes.add(typePool.describe(methodType.getReturnType().getClassName()).resolve());
<add> parameterTypes.add(typePool.describe(type.getClassName()).resolve());
<ide> }
<ide> Object[] constant = DYNAMIC_CONSTANT_DESC.bootstrapArgs(value);
<ide> List<JavaConstant> arguments = new ArrayList<JavaConstant>(constant.length);
|
|
JavaScript
|
apache-2.0
|
4eba09df32cdc18d38c59e7d4514cba1f74d664d
| 0 |
vronvali/iLanguage,cesine/FieldDBGlosser,vronvali/iLanguage,cesine/FieldDBGlosser,cesine/iLanguage,FieldDB/FieldDBGlosser,iLanguage/iLanguage,vronvali/iLanguage,vronvali/iLanguage,cesine/iLanguage,iLanguage/iLanguage,cesine/iLanguage,iLanguage/iLanguage,cesine/iLanguage,vronvali/iLanguage,FieldDB/FieldDBGlosser,cesine/iLanguage,iLanguage/iLanguage,iLanguage/iLanguage,vronvali/iLanguage
|
var Glosser = Glosser || {};
Glosser.currentCorpusName = "";
Glosser.downloadPrecedenceRules = function(pouchname, glosserURL, callback){
if(!glosserURL ||glosserURL == "default"){
var couchConnection = app.get("corpus").get("couchConnection");
var couchurl = OPrime.getCouchUrl(couchConnection);
glosserURL = couchurl + "/_design/pages/_view/precedence_rules?group=true";
}
OPrime.makeCORSRequest({
type : 'GET',
url : glosserURL,
success : function(rules) {
localStorage.setItem(pouchname+"precendenceRules", JSON.stringify(rules.rows));
// Reduce the rules such that rules which are found in multiple source
// words are only used/included once.
var reducedRules = _.chain(rules.rows).groupBy(function(rule) {
return rule.key.x + "-" + rule.key.y;
}).value();
// Save the reduced precedence rules in localStorage
localStorage.setItem(pouchname+"reducedRules", JSON.stringify(reducedRules));
Glosser.currentCorpusName = pouchname;
if(typeof callback == "function"){
callback();
}
},
error : function(e) {
console.log("error getting precedence rules:", e);
},
dataType : ""
});
};
/**
* Takes in an utterance line and, based on our current set of precendence
* rules, guesses what the morpheme line would be. The algorithm is
* very conservative.
*
* @param {String} unparsedUtterance The raw utterance line.
*
* @return {String} The guessed morphemes line.
*/
Glosser.morphemefinder = function(unparsedUtterance) {
var potentialParse = '';
// Get the precedence rules from localStorage
var rules = localStorage.getItem(Glosser.currentCorpusName+"reducedRules");
var parsedWords = [];
if (rules) {
// Parse the rules from JSON into an object
rules = JSON.parse(rules);
// Divide the utterance line into words
var unparsedWords = unparsedUtterance.trim().split(/ +/);
for (var word in unparsedWords) {
// Add the start/end-of-word character to the word
unparsedWords[word] = "@" + unparsedWords[word] + "@";
// Find the rules which match in local precedence
var matchedRules = [];
for (var r in rules) {
if (unparsedWords[word].indexOf(r.replace(/-/, "")) >= 0) {
matchedRules.push({
r : rules[r]
})
}
}
// Attempt to find the longest template which the matching rules can
// generate from start to end
var prefixtemplate = [];
prefixtemplate.push("@");
for (var i = 0; i < 10; i++) {
if (prefixtemplate[i] == undefined) {
break;
}
for (var j in matchedRules) {
if (prefixtemplate[i] == matchedRules[j].r[0].key.x) {
if (prefixtemplate[i + 1]) { // ambiguity (two potential following
// morphemes)
prefixtemplate.pop();
break;
} else {
prefixtemplate[i + 1] = matchedRules[j].r[0].key.y;
}
}
}
}
// If the prefix template hit ambiguity in the middle, try from the suffix
// in until it hits ambiguity
var suffixtemplate = [];
if (prefixtemplate[prefixtemplate.length - 1] != "@" || prefixtemplate.length == 1) {
// Suffix:
suffixtemplate.push("@")
for (var i = 0; i < 10; i++) {
if (suffixtemplate[i] == undefined) {
break;
}
for (var j in matchedRules) {
if (suffixtemplate[i] == matchedRules[j].r[0].key.y) {
if (suffixtemplate[i + 1]) { // ambiguity (two potential
// following morphemes)
suffixtemplate.pop();
break;
} else {
suffixtemplate[i + 1] = matchedRules[j].r[0].key.x;
}
}
}
}
}
// Combine prefix and suffix templates into one regular expression which
// can be tested against the word to find a potential parse.
// Regular expressions will look something like
// (@)(.*)(hall)(.*)(o)(.*)(wa)(.*)(n)(.*)(@)
var template = [];
template = prefixtemplate.concat(suffixtemplate.reverse())
for (var slot in template) {
template[slot] = "(" + template[slot] + ")";
}
var regex = new RegExp(template.join("(.*)"), "");
// Use the regular expression to find a guessed morphemes line
potentialParse = unparsedWords[word]
.replace(regex, "$1-$2-$3-$4-$5-$6-$7-$8-$9") // Use backreferences to parse into morphemes
.replace(/\$[0-9]/g, "")// Remove any backreferences that weren't used
.replace(/@/g, "") // Remove the start/end-of-line symbol
.replace(/--+/g, "-") // Ensure that there is only ever one "-" in a row
.replace(/^-/, "") // Remove "-" at the start of the word
.replace(/-$/, ""); // Remove "-" at the end of the word
if (OPrime.debugMode) OPrime.debug("Potential parse of " + unparsedWords[word].replace(/@/g, "")
+ " is " + potentialParse);
parsedWords.push(potentialParse);
}
}
return parsedWords.join(" ");
}
Glosser.toastedUserToSync = false;
Glosser.toastedUserToImport = 0;
Glosser.glossFinder = function(morphemesLine){
//Guess a gloss
var morphemeGroup = morphemesLine.split(/ +/);
var glossGroups = [];
if(! window.app.get("corpus")){
return "";
}
if(! window.app.get("corpus").lexicon.get("lexiconNodes")){
var corpusSize = 31; //TODO get corpus size another way. // app.get("corpus").datalists.models[app.get("corpus").datalists.models.length-1].get("datumIds").length;
if(corpusSize > 30 && !Glosser.toastedUserToSync){
Glosser.toastedUserToSync = true;
window.appView.toastUser("You probably have enough data to train an autoglosser for your corpus.\n\nIf you sync your data with the team server then editing the morphemes will automatically run the auto glosser.","alert-success","Sync to train your auto-glosser:");
}else{
Glosser.toastedUserToImport ++;
if(Glosser.toastedUserToImport % 10 == 1 && corpusSize < 30){
window.appView.toastUser("You have roughly "+corpusSize+" datum saved in your pouch, if you have around 30 datum, then you have enough data to train an autoglosser for your corpus.","alert-info","AutoGlosser:");
}
}
return "";
}
var lexiconNodes = window.app.get("corpus").lexicon.get("lexiconNodes");
for (var group in morphemeGroup) {
var morphemes = morphemeGroup[group].split("-");
var glosses = [];
for (var m in morphemes) {
// Take the first gloss for this morpheme
var matchingNode = _.max(lexiconNodes.where({morpheme: morphemes[m]}), function(node) { return node.get("value"); });
// console.log(matchingNode);
var gloss = "?"; // If there's no matching gloss, use question marks
if (matchingNode) {
gloss = matchingNode.get("gloss");
}
glosses.push(gloss);
}
glossGroups.push(glosses.join("-"));
}
// Replace the gloss line with the guessed glosses
return glossGroups.join(" ");
};
/**
* Takes as a parameters an array of rules which came from CouchDB precedence rule query.
* Example Rule: {"key":{"x":"@","relation":"preceeds","y":"aqtu","context":"aqtu-nay-wa-n"},"value":2}
*/
Glosser.generateForceDirectedRulesJsonForD3 = function(rules, pouchname) {
if(!pouchname){
pouchname = Glosser.currentCorpusName;
}
if(!rules){
rules = localStorage.getItem(pouchname+"precendenceRules");
if(rules){
rules = JSON.parse(rules);
}
}
if(!rules ){
return;
}
/*
* Cycle through the precedence rules, convert them into graph edges with the morpheme index in the morpheme array as the source/target values
*/
morphemeLinks = [];
morphemes = [];
for ( var i in rules) {
/* make the @ more like what a linguist recognizes for word boundaries */
if(rules[i].key.x == "@"){
rules[i].key.x = "#_"
}
if(rules[i].key.y == "@"){
rules[i].key.y = "_#"
}
var xpos = morphemes.indexOf(rules[i].key.x);
if (xpos < 0) {
morphemes.push(rules[i].key.x);
xpos = morphemes.length - 1;
}
var ypos = morphemes.indexOf(rules[i].key.y);
if (ypos < 0) {
morphemes.push(rules[i].key.y);
ypos = morphemes.length - 1;
}
//To avoid loops?
if (rules[i].key.y.indexOf("@") == -1) {
morphemeLinks.push({
source : xpos,
target : ypos,
value : 1 //TODO use the context counting to get a weight measure
});
}
}
/*
* Build the morphemes into nodes and color them by their morpheme length, could be a good measure of outliers
*/
var morphemenodes = [];
for (m in morphemes) {
morphemenodes.push({
name : morphemes[m],
group : morphemes[m].length
});
}
/*
* Create the JSON required by D3
*/
var rulesGraph = {};
rulesGraph.links = morphemeLinks;
rulesGraph.nodes = morphemenodes;
Glosser.rulesGraph = rulesGraph;
return rulesGraph;
}
Glosser.saveAndInterConnectInApp = function(callback){
if(typeof callback == "function"){
callback();
}
}
/*
* Some sample D3 from the force-html.html example
*
*/
//Glosser.rulesGraph = Glosser.rulesGraph || {};
Glosser.visualizeMorphemesAsForceDirectedGraph = function(rulesGraph, divElement, pouchname){
if(pouchname){
Glosser.currentCorpusName = pouchname;
}else{
throw("Must provide corpus name to be able to visualize morphemes");
}
if(!rulesGraph){
rulesGraph = Glosser.rulesGraph;
if(rulesGraph){
if(rulesGraph.links.length == 0){
rulesGraph = Glosser.generateForceDirectedRulesJsonForD3();
}
}else{
rulesGraph = Glosser.generateForceDirectedRulesJsonForD3();
}
}
if(!rulesGraph){
return;
}
if( Glosser.rulesGraph.links.length == 0 ){
return;
}
json = rulesGraph;
var width = 800,
height = 300;
var color = d3.scale.category20();
var x = d3.scale.linear()
.range([0, width]);
var y = d3.scale.linear()
.range([0, height - 40]);
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);
var svg = d3.select("#corpus-precedence-rules-visualization-fullscreen").append("svg")
.attr("width", width)
.attr('title', "Morphology Visualization for "+ pouchname)
.attr("height", height);
var titletext = "Morphemes in your corpus";
if(rulesGraph.nodes.length < 3){
titletext = "Your morpheme visualizer will appear here after you have synced.";
}
//A label for the current year.
var title = svg.append("text")
.attr("class", "vis-title")
.attr("dy", "1em")
.attr("dx", "1em")
// .attr("transform", "translate(" + x(1) + "," + y(1) + ")scale(-1,-1)")
.text(titletext);
var tooltip = null;
//d3.json("./libs/rules.json", function(json) {
force
.nodes(json.nodes)
.links(json.links)
.start();
var link = svg.selectAll("line.link")
.data(json.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = svg.selectAll("circle.node")
.data(json.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", function(d) { return color(d.group); })
.on("mouseover", function(d) {
tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "visible")
.style("color","#fff")
.text(d.name)
})
.on("mouseout", function() {
tooltip.style("visibility", "hidden");
})
.call(force.drag);
node.append("title")
.text(function(d) { return d.name; });
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
//});
}
|
Glosser.js
|
var Glosser = Glosser || {};
Glosser.currentCorpusName = "";
Glosser.downloadPrecedenceRules = function(pouchname, glosserURL, callback){
if(!glosserURL ||glosserURL == "default"){
var couchConnection = app.get("corpus").get("couchConnection");
var couchurl = OPrime.getCouchUrl(couchConnection);
glosserURL = couchurl + "/_design/get_precedence_rules_from_morphemes/_view/precedence_rules?group=true";
}
OPrime.makeCORSRequest({
type : 'GET',
url : glosserURL,
success : function(rules) {
localStorage.setItem(pouchname+"precendenceRules", JSON.stringify(rules.rows));
// Reduce the rules such that rules which are found in multiple source
// words are only used/included once.
var reducedRules = _.chain(rules.rows).groupBy(function(rule) {
return rule.key.x + "-" + rule.key.y;
}).value();
// Save the reduced precedence rules in localStorage
localStorage.setItem(pouchname+"reducedRules", JSON.stringify(reducedRules));
Glosser.currentCorpusName = pouchname;
if(typeof callback == "function"){
callback();
}
},
error : function(e) {
console.log("error getting precedence rules:", e);
},
dataType : ""
});
};
/**
* Takes in an utterance line and, based on our current set of precendence
* rules, guesses what the morpheme line would be. The algorithm is
* very conservative.
*
* @param {String} unparsedUtterance The raw utterance line.
*
* @return {String} The guessed morphemes line.
*/
Glosser.morphemefinder = function(unparsedUtterance) {
var potentialParse = '';
// Get the precedence rules from localStorage
var rules = localStorage.getItem(Glosser.currentCorpusName+"reducedRules");
var parsedWords = [];
if (rules) {
// Parse the rules from JSON into an object
rules = JSON.parse(rules);
// Divide the utterance line into words
var unparsedWords = unparsedUtterance.trim().split(/ +/);
for (var word in unparsedWords) {
// Add the start/end-of-word character to the word
unparsedWords[word] = "@" + unparsedWords[word] + "@";
// Find the rules which match in local precedence
var matchedRules = [];
for (var r in rules) {
if (unparsedWords[word].indexOf(r.replace(/-/, "")) >= 0) {
matchedRules.push({
r : rules[r]
})
}
}
// Attempt to find the longest template which the matching rules can
// generate from start to end
var prefixtemplate = [];
prefixtemplate.push("@");
for (var i = 0; i < 10; i++) {
if (prefixtemplate[i] == undefined) {
break;
}
for (var j in matchedRules) {
if (prefixtemplate[i] == matchedRules[j].r[0].key.x) {
if (prefixtemplate[i + 1]) { // ambiguity (two potential following
// morphemes)
prefixtemplate.pop();
break;
} else {
prefixtemplate[i + 1] = matchedRules[j].r[0].key.y;
}
}
}
}
// If the prefix template hit ambiguity in the middle, try from the suffix
// in until it hits ambiguity
var suffixtemplate = [];
if (prefixtemplate[prefixtemplate.length - 1] != "@" || prefixtemplate.length == 1) {
// Suffix:
suffixtemplate.push("@")
for (var i = 0; i < 10; i++) {
if (suffixtemplate[i] == undefined) {
break;
}
for (var j in matchedRules) {
if (suffixtemplate[i] == matchedRules[j].r[0].key.y) {
if (suffixtemplate[i + 1]) { // ambiguity (two potential
// following morphemes)
suffixtemplate.pop();
break;
} else {
suffixtemplate[i + 1] = matchedRules[j].r[0].key.x;
}
}
}
}
}
// Combine prefix and suffix templates into one regular expression which
// can be tested against the word to find a potential parse.
// Regular expressions will look something like
// (@)(.*)(hall)(.*)(o)(.*)(wa)(.*)(n)(.*)(@)
var template = [];
template = prefixtemplate.concat(suffixtemplate.reverse())
for (var slot in template) {
template[slot] = "(" + template[slot] + ")";
}
var regex = new RegExp(template.join("(.*)"), "");
// Use the regular expression to find a guessed morphemes line
potentialParse = unparsedWords[word]
.replace(regex, "$1-$2-$3-$4-$5-$6-$7-$8-$9") // Use backreferences to parse into morphemes
.replace(/\$[0-9]/g, "")// Remove any backreferences that weren't used
.replace(/@/g, "") // Remove the start/end-of-line symbol
.replace(/--+/g, "-") // Ensure that there is only ever one "-" in a row
.replace(/^-/, "") // Remove "-" at the start of the word
.replace(/-$/, ""); // Remove "-" at the end of the word
if (OPrime.debugMode) OPrime.debug("Potential parse of " + unparsedWords[word].replace(/@/g, "")
+ " is " + potentialParse);
parsedWords.push(potentialParse);
}
}
return parsedWords.join(" ");
}
Glosser.toastedUserToSync = false;
Glosser.toastedUserToImport = 0;
Glosser.glossFinder = function(morphemesLine){
//Guess a gloss
var morphemeGroup = morphemesLine.split(/ +/);
var glossGroups = [];
if(! window.app.get("corpus")){
return "";
}
if(! window.app.get("corpus").lexicon.get("lexiconNodes")){
var corpusSize = 31; //TODO get corpus size another way. // app.get("corpus").datalists.models[app.get("corpus").datalists.models.length-1].get("datumIds").length;
if(corpusSize > 30 && !Glosser.toastedUserToSync){
Glosser.toastedUserToSync = true;
window.appView.toastUser("You probably have enough data to train an autoglosser for your corpus.\n\nIf you sync your data with the team server then editing the morphemes will automatically run the auto glosser.","alert-success","Sync to train your auto-glosser:");
}else{
Glosser.toastedUserToImport ++;
if(Glosser.toastedUserToImport % 10 == 1 && corpusSize < 30){
window.appView.toastUser("You have roughly "+corpusSize+" datum saved in your pouch, if you have around 30 datum, then you have enough data to train an autoglosser for your corpus.","alert-info","AutoGlosser:");
}
}
return "";
}
var lexiconNodes = window.app.get("corpus").lexicon.get("lexiconNodes");
for (var group in morphemeGroup) {
var morphemes = morphemeGroup[group].split("-");
var glosses = [];
for (var m in morphemes) {
// Take the first gloss for this morpheme
var matchingNode = _.max(lexiconNodes.where({morpheme: morphemes[m]}), function(node) { return node.get("value"); });
// console.log(matchingNode);
var gloss = "?"; // If there's no matching gloss, use question marks
if (matchingNode) {
gloss = matchingNode.get("gloss");
}
glosses.push(gloss);
}
glossGroups.push(glosses.join("-"));
}
// Replace the gloss line with the guessed glosses
return glossGroups.join(" ");
};
/**
* Takes as a parameters an array of rules which came from CouchDB precedence rule query.
* Example Rule: {"key":{"x":"@","relation":"preceeds","y":"aqtu","context":"aqtu-nay-wa-n"},"value":2}
*/
Glosser.generateForceDirectedRulesJsonForD3 = function(rules, pouchname) {
if(!pouchname){
pouchname = Glosser.currentCorpusName;
}
if(!rules){
rules = localStorage.getItem(pouchname+"precendenceRules");
if(rules){
rules = JSON.parse(rules);
}
}
if(!rules ){
return;
}
/*
* Cycle through the precedence rules, convert them into graph edges with the morpheme index in the morpheme array as the source/target values
*/
morphemeLinks = [];
morphemes = [];
for ( var i in rules) {
/* make the @ more like what a linguist recognizes for word boundaries */
if(rules[i].key.x == "@"){
rules[i].key.x = "#_"
}
if(rules[i].key.y == "@"){
rules[i].key.y = "_#"
}
var xpos = morphemes.indexOf(rules[i].key.x);
if (xpos < 0) {
morphemes.push(rules[i].key.x);
xpos = morphemes.length - 1;
}
var ypos = morphemes.indexOf(rules[i].key.y);
if (ypos < 0) {
morphemes.push(rules[i].key.y);
ypos = morphemes.length - 1;
}
//To avoid loops?
if (rules[i].key.y.indexOf("@") == -1) {
morphemeLinks.push({
source : xpos,
target : ypos,
value : 1 //TODO use the context counting to get a weight measure
});
}
}
/*
* Build the morphemes into nodes and color them by their morpheme length, could be a good measure of outliers
*/
var morphemenodes = [];
for (m in morphemes) {
morphemenodes.push({
name : morphemes[m],
group : morphemes[m].length
});
}
/*
* Create the JSON required by D3
*/
var rulesGraph = {};
rulesGraph.links = morphemeLinks;
rulesGraph.nodes = morphemenodes;
Glosser.rulesGraph = rulesGraph;
return rulesGraph;
}
Glosser.saveAndInterConnectInApp = function(callback){
if(typeof callback == "function"){
callback();
}
}
/*
* Some sample D3 from the force-html.html example
*
*/
//Glosser.rulesGraph = Glosser.rulesGraph || {};
Glosser.visualizeMorphemesAsForceDirectedGraph = function(rulesGraph, divElement, pouchname){
if(pouchname){
Glosser.currentCorpusName = pouchname;
}else{
throw("Must provide corpus name to be able to visualize morphemes");
}
if(!rulesGraph){
rulesGraph = Glosser.rulesGraph;
if(rulesGraph){
if(rulesGraph.links.length == 0){
rulesGraph = Glosser.generateForceDirectedRulesJsonForD3();
}
}else{
rulesGraph = Glosser.generateForceDirectedRulesJsonForD3();
}
}
if(!rulesGraph){
return;
}
if( Glosser.rulesGraph.links.length == 0 ){
return;
}
json = rulesGraph;
var width = 800,
height = 300;
var color = d3.scale.category20();
var x = d3.scale.linear()
.range([0, width]);
var y = d3.scale.linear()
.range([0, height - 40]);
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);
var svg = d3.select("#corpus-precedence-rules-visualization-fullscreen").append("svg")
.attr("width", width)
.attr('title', "Morphology Visualization for "+ pouchname)
.attr("height", height);
var titletext = "Explore the precedence relations of morphemes in your corpus";
if(rulesGraph.nodes.length < 3){
titletext = "Your morpheme visualizer will appear here after you have synced.";
}
//A label for the current year.
var title = svg.append("text")
.attr("class", "vis-title")
.attr("dy", "1.5em")
.attr("dx", "1.5em")
// .attr("transform", "translate(" + x(1) + "," + y(1) + ")scale(-1,-1)")
.text(titletext);
var tooltip = null;
//d3.json("./libs/rules.json", function(json) {
force
.nodes(json.nodes)
.links(json.links)
.start();
var link = svg.selectAll("line.link")
.data(json.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = svg.selectAll("circle.node")
.data(json.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", function(d) { return color(d.group); })
.on("mouseover", function(d) {
tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "visible")
.style("color","#fff")
.text(d.name)
})
.on("mouseout", function() {
tooltip.style("visibility", "hidden");
})
.call(force.drag);
node.append("title")
.text(function(d) { return d.name; });
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
//});
}
|
moving all the views into the pages couchapp so they can be deployed and updated together
|
Glosser.js
|
moving all the views into the pages couchapp so they can be deployed and updated together
|
<ide><path>losser.js
<ide> if(!glosserURL ||glosserURL == "default"){
<ide> var couchConnection = app.get("corpus").get("couchConnection");
<ide> var couchurl = OPrime.getCouchUrl(couchConnection);
<del> glosserURL = couchurl + "/_design/get_precedence_rules_from_morphemes/_view/precedence_rules?group=true";
<add> glosserURL = couchurl + "/_design/pages/_view/precedence_rules?group=true";
<ide> }
<ide> OPrime.makeCORSRequest({
<ide> type : 'GET',
<ide> .attr('title', "Morphology Visualization for "+ pouchname)
<ide> .attr("height", height);
<ide>
<del> var titletext = "Explore the precedence relations of morphemes in your corpus";
<add> var titletext = "Morphemes in your corpus";
<ide> if(rulesGraph.nodes.length < 3){
<ide> titletext = "Your morpheme visualizer will appear here after you have synced.";
<ide> }
<ide> //A label for the current year.
<ide> var title = svg.append("text")
<ide> .attr("class", "vis-title")
<del> .attr("dy", "1.5em")
<del> .attr("dx", "1.5em")
<add> .attr("dy", "1em")
<add> .attr("dx", "1em")
<ide> // .attr("transform", "translate(" + x(1) + "," + y(1) + ")scale(-1,-1)")
<ide> .text(titletext);
<ide>
|
|
Java
|
apache-2.0
|
fe00da60628e62e23df8fe764b879ebcccecc9d8
| 0 |
boxheed/nookee
|
package com.fizzpod.nookee;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;
public final class ScriptResolver {
private final Logger LOGGER = LoggerFactory.getLogger(ScriptResolver.class);
private final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
private final File scriptRoot;
public ScriptResolver(File scriptRoot) {
this.scriptRoot = scriptRoot;
final List<ScriptEngineFactory> factories = scriptEngineManager.getEngineFactories();
for (final ScriptEngineFactory factory : factories) {
LOGGER.info("ScriptEngineFactory Info");
final String engName = factory.getEngineName();
final String engVersion = factory.getEngineVersion();
final String langName = factory.getLanguageName();
final String langVersion = factory.getLanguageVersion();
LOGGER.info("Script Engine: {} ({})", engName, engVersion);
LOGGER.info(" Language: {} ({})", langName, langVersion);
final List<String> engNames = factory.getNames();
for (final String name : engNames) {
LOGGER.info(" Alias: {}", name);
}
}
}
public Script getScript(final String path, final RequestMethod verb) {
File scriptFile = findScript(path, verb);
Script script = loadScript(scriptFile);
return script;
}
private Script loadScript(File scriptFile) {
Script script = null;
if (scriptFile != null) {
try {
final String scriptContent = FileUtils.readFileToString(scriptFile, "UTF-8");
final ScriptEngine engine = this.resolveEngine(scriptFile);
if(StringUtils.hasText(scriptContent) && engine != null) {
script = new Script(scriptContent, engine);
}
} catch (IOException e) {
LOGGER.error("Could not read script file {}", scriptFile, e);
}
}
return script;
}
private ScriptEngine resolveEngine(File scriptFile) {
ScriptEngine engine = null;
final String extension = FilenameUtils.getExtension(scriptFile.getName());
LOGGER.info("Looking for script engine for extension {}", extension);
try {
engine = scriptEngineManager.getEngineByExtension(extension);
} catch (final NullPointerException e) {
LOGGER.error("Could not get a script engine for extension {}", extension);
}
return engine;
}
private File findScript(final String path, final RequestMethod verb) {
File scriptPath = new File(scriptRoot, path);
File scriptFile = scanForScript(scriptPath, verb);
return scriptFile;
}
/**
* Work the way up the tree to thescript root.
* Look for the a file starting with a matching verb.
*/
private File scanForScript(final File scriptPath, final RequestMethod verb) {
File folder = scriptPath;
File scriptFile = null;
while(!folder.equals(scriptRoot)) {
if(folder.exists() && folder.isDirectory()) {
LOGGER.info("Scanning {} for script with verb {}", scriptPath, verb);
IOFileFilter fileFileFilter = FileFilterUtils.fileFileFilter();
IOFileFilter prefixFileFilter = FileFilterUtils.prefixFileFilter(verb.name());
File[] matchingFiles = folder.listFiles((FilenameFilter) FileFilterUtils.and(fileFileFilter, prefixFileFilter));
if(matchingFiles != null && matchingFiles.length >= 1) {
scriptFile = matchingFiles[0];
break;
}
}
folder = folder.getParentFile();
}
return scriptFile;
}
}
|
src/main/java/com/fizzpod/nookee/ScriptResolver.java
|
package com.fizzpod.nookee;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;
public final class ScriptResolver {
private final Logger LOGGER = LoggerFactory.getLogger(ScriptResolver.class);
private final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
private final File scriptRoot;
public ScriptResolver(File scriptRoot) {
this.scriptRoot = scriptRoot;
final List<ScriptEngineFactory> factories = scriptEngineManager.getEngineFactories();
for (final ScriptEngineFactory factory : factories) {
LOGGER.info("ScriptEngineFactory Info");
final String engName = factory.getEngineName();
final String engVersion = factory.getEngineVersion();
final String langName = factory.getLanguageName();
final String langVersion = factory.getLanguageVersion();
LOGGER.info("Script Engine: {} ({})", engName, engVersion);
LOGGER.info(" Language: {} ({})", langName, langVersion);
final List<String> engNames = factory.getNames();
for (final String name : engNames) {
LOGGER.info(" Alias: {}", name);
}
}
}
public Script getScript(final String path, final RequestMethod verb) {
File scriptFile = findScript(path, verb);
Script script = loadScript(scriptFile);
return script;
}
private Script loadScript(File scriptFile) {
Script script = null;
if (scriptFile != null) {
try {
final String scriptContent = FileUtils.readFileToString(scriptFile, "UTF-8");
final ScriptEngine engine = this.resolveEngine(scriptFile);
if(StringUtils.hasText(scriptContent) && engine != null) {
script = new Script(scriptContent, engine);
}
} catch (IOException e) {
LOGGER.error("Could not read script file {}", scriptFile, e);
}
}
return script;
}
private ScriptEngine resolveEngine(File scriptFile) {
ScriptEngine engine = null;
final String extension = FilenameUtils.getExtension(scriptFile.getName());
LOGGER.info("Looking for script engine for extension {}", extension);
try {
engine = scriptEngineManager.getEngineByExtension(extension);
} catch (final NullPointerException e) {
LOGGER.error("Could not get a script engine for extension {}", extension);
}
return engine;
}
private File findScript(final String path, final RequestMethod verb) {
File scriptPath = new File(scriptRoot, path);
File scriptFile = scanForScript(scriptPath, verb);
return scriptFile;
}
/**
* Work the way up the tree to thescript root.
* Look for the a file starting with a matching verb.
*/
private File scanForScript(final File scriptPath, final RequestMethod verb) {
File folder = scriptPath;
File scriptFile = null;
while(!folder.equals(scriptRoot)) {
LOGGER.info("Scanning {} for script with verb {}", scriptPath, verb);
IOFileFilter fileFileFilter = FileFilterUtils.fileFileFilter();
IOFileFilter prefixFileFilter = FileFilterUtils.prefixFileFilter(verb.name());
File[] matchingFiles = folder.listFiles((FilenameFilter) FileFilterUtils.and(fileFileFilter, prefixFileFilter));
if(matchingFiles.length >= 1) {
scriptFile = matchingFiles[0];
break;
}
folder = folder.getParentFile();
}
return scriptFile;
}
}
|
fixed null pointer
|
src/main/java/com/fizzpod/nookee/ScriptResolver.java
|
fixed null pointer
|
<ide><path>rc/main/java/com/fizzpod/nookee/ScriptResolver.java
<ide> File folder = scriptPath;
<ide> File scriptFile = null;
<ide> while(!folder.equals(scriptRoot)) {
<del> LOGGER.info("Scanning {} for script with verb {}", scriptPath, verb);
<del> IOFileFilter fileFileFilter = FileFilterUtils.fileFileFilter();
<del> IOFileFilter prefixFileFilter = FileFilterUtils.prefixFileFilter(verb.name());
<del> File[] matchingFiles = folder.listFiles((FilenameFilter) FileFilterUtils.and(fileFileFilter, prefixFileFilter));
<del> if(matchingFiles.length >= 1) {
<del> scriptFile = matchingFiles[0];
<del> break;
<add> if(folder.exists() && folder.isDirectory()) {
<add> LOGGER.info("Scanning {} for script with verb {}", scriptPath, verb);
<add> IOFileFilter fileFileFilter = FileFilterUtils.fileFileFilter();
<add> IOFileFilter prefixFileFilter = FileFilterUtils.prefixFileFilter(verb.name());
<add> File[] matchingFiles = folder.listFiles((FilenameFilter) FileFilterUtils.and(fileFileFilter, prefixFileFilter));
<add> if(matchingFiles != null && matchingFiles.length >= 1) {
<add> scriptFile = matchingFiles[0];
<add> break;
<add> }
<ide> }
<ide> folder = folder.getParentFile();
<ide> }
|
|
Java
|
mit
|
error: pathspec 'src/br/com/juliocnsouza/ocpjp/tests/StringProcessing.java' did not match any file(s) known to git
|
e146be31d60360f6d0a44059b0b82d7746979e88
| 1 |
juliocnsouzadev/ocpjp
|
package br.com.juliocnsouza.ocpjp.tests;
/**
* StringProcessing.java -> Job:
* @since 23/02/2015
* @version 1.0
* @author Julio Cesar Nunes de Souza ([email protected])
*/
public class StringProcessing {
}
|
src/br/com/juliocnsouza/ocpjp/tests/StringProcessing.java
|
testes string processing
|
src/br/com/juliocnsouza/ocpjp/tests/StringProcessing.java
|
testes string processing
|
<ide><path>rc/br/com/juliocnsouza/ocpjp/tests/StringProcessing.java
<add>package br.com.juliocnsouza.ocpjp.tests;
<add>
<add>
<add>/**
<add> * StringProcessing.java -> Job:
<add> * @since 23/02/2015
<add> * @version 1.0
<add> * @author Julio Cesar Nunes de Souza ([email protected])
<add> */
<add>
<add>public class StringProcessing {
<add>
<add>}
|
|
Java
|
apache-2.0
|
0642bc77a4521a978c372a1df56c6c0b85fd3c77
| 0 |
halatmit/appinventor-sources,puravidaapps/appinventor-sources,marksherman/appinventor-sources,halatmit/appinventor-sources,jisqyv/appinventor-sources,josmas/app-inventor,ewpatton/appinventor-sources,Klomi/appinventor-sources,mit-cml/appinventor-sources,mit-cml/appinventor-sources,mit-cml/appinventor-sources,farxinu/appinventor-sources,warren922/appinventor-sources,josmas/app-inventor,puravidaapps/appinventor-sources,mit-cml/appinventor-sources,kkashi01/appinventor-sources,farxinu/appinventor-sources,josmas/app-inventor,warren922/appinventor-sources,warren922/appinventor-sources,farxinu/appinventor-sources,puravidaapps/appinventor-sources,kkashi01/appinventor-sources,farxinu/appinventor-sources,kkashi01/appinventor-sources,jisqyv/appinventor-sources,marksherman/appinventor-sources,mit-dig/punya,RachaelT/appinventor-sources,jisqyv/appinventor-sources,jisqyv/appinventor-sources,ewpatton/appinventor-sources,ewpatton/appinventor-sources,josmas/app-inventor,mit-cml/appinventor-sources,halatmit/appinventor-sources,barreeeiroo/appinventor-sources,marksherman/appinventor-sources,puravidaapps/appinventor-sources,mit-dig/punya,warren922/appinventor-sources,mit-dig/punya,mit-dig/punya,farxinu/appinventor-sources,mit-dig/punya,barreeeiroo/appinventor-sources,halatmit/appinventor-sources,marksherman/appinventor-sources,RachaelT/appinventor-sources,mit-dig/punya,barreeeiroo/appinventor-sources,Klomi/appinventor-sources,jisqyv/appinventor-sources,kkashi01/appinventor-sources,marksherman/appinventor-sources,RachaelT/appinventor-sources,halatmit/appinventor-sources,Klomi/appinventor-sources,Klomi/appinventor-sources,kkashi01/appinventor-sources,josmas/app-inventor,RachaelT/appinventor-sources,puravidaapps/appinventor-sources,Klomi/appinventor-sources,halatmit/appinventor-sources,ewpatton/appinventor-sources,ewpatton/appinventor-sources,jisqyv/appinventor-sources,kkashi01/appinventor-sources,mit-dig/punya,josmas/app-inventor,barreeeiroo/appinventor-sources,marksherman/appinventor-sources,ewpatton/appinventor-sources,barreeeiroo/appinventor-sources,warren922/appinventor-sources,mit-cml/appinventor-sources,RachaelT/appinventor-sources
|
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.buildserver;
import com.google.appinventor.common.utils.StringUtils;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.Files;
import com.google.common.io.InputSupplier;
import com.google.common.io.Resources;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.FileUtils;
/**
* Provides support for building Young Android projects.
*
* @author [email protected] (Mark Friedman)
*/
public final class ProjectBuilder {
private File outputApk;
private File outputKeystore;
private boolean saveKeystore;
// Logging support
private static final Logger LOG = Logger.getLogger(ProjectBuilder.class.getName());
private static final int MAX_COMPILER_MESSAGE_LENGTH = 160;
// Project folder prefixes
// TODO(user): These constants are (or should be) also defined in
// appengine/src/com/google/appinventor/server/project/youngandroid/YoungAndroidProjectService
// They should probably be in some place shared with the server
private static final String PROJECT_DIRECTORY = "youngandroidproject";
private static final String PROJECT_PROPERTIES_FILE_NAME = PROJECT_DIRECTORY + "/" +
"project.properties";
private static final String KEYSTORE_FILE_NAME = YoungAndroidConstants.PROJECT_KEYSTORE_LOCATION;
private static final String FORM_PROPERTIES_EXTENSION =
YoungAndroidConstants.FORM_PROPERTIES_EXTENSION;
private static final String YAIL_EXTENSION = YoungAndroidConstants.YAIL_EXTENSION;
private static final String CODEBLOCKS_SOURCE_EXTENSION =
YoungAndroidConstants.CODEBLOCKS_SOURCE_EXTENSION;
private static final String ALL_COMPONENT_TYPES =
Compiler.RUNTIME_FILES_DIR + "simple_components.txt";
public File getOutputApk() {
return outputApk;
}
public File getOutputKeystore() {
return outputKeystore;
}
/**
* Creates a new directory beneath the system's temporary directory (as
* defined by the {@code java.io.tmpdir} system property), and returns its
* name. The name of the directory will contain the current time (in millis),
* and a random number.
*
* <p>This method assumes that the temporary volume is writable, has free
* inodes and free blocks, and that it will not be called thousands of times
* per second.
*
* @return the newly-created directory
* @throws IllegalStateException if the directory could not be created
*/
private static File createNewTempDir() {
File baseDir = new File(System.getProperty("java.io.tmpdir"));
String baseNamePrefix = System.currentTimeMillis() + "_" + Math.random() + "-";
final int TEMP_DIR_ATTEMPTS = 10000;
for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
File tempDir = new File(baseDir, baseNamePrefix + counter);
if (tempDir.exists()) {
continue;
}
if (tempDir.mkdir()) {
return tempDir;
}
}
throw new IllegalStateException("Failed to create directory within "
+ TEMP_DIR_ATTEMPTS + " attempts (tried "
+ baseNamePrefix + "0 to " + baseNamePrefix + (TEMP_DIR_ATTEMPTS - 1) + ')');
}
Result build(String userName, ZipFile inputZip, File outputDir, boolean isForCompanion,
int childProcessRam, String dexCachePath) {
try {
// Download project files into a temporary directory
File projectRoot = createNewTempDir();
LOG.info("temporary project root: " + projectRoot.getAbsolutePath());
try {
List<String> sourceFiles;
try {
sourceFiles = extractProjectFiles(inputZip, projectRoot);
} catch (IOException e) {
LOG.severe("unexpected problem extracting project file from zip");
return Result.createFailingResult("", "Problems processing zip file.");
}
try {
genYailFilesIfNecessary(sourceFiles);
} catch (YailGenerationException e) {
// Note that we're using a special result code here for the case of a Yail gen error.
return new Result(Result.YAIL_GENERATION_ERROR, "", e.getMessage(), e.getFormName());
} catch (Exception e) {
LOG.severe("Unknown exception signalled by genYailFilesIf Necessary");
e.printStackTrace();
return Result.createFailingResult("", "Unexpected problems generating YAIL.");
}
File keyStoreFile = new File(projectRoot, KEYSTORE_FILE_NAME);
String keyStorePath = keyStoreFile.getPath();
if (!keyStoreFile.exists()) {
keyStorePath = createKeyStore(userName, projectRoot, KEYSTORE_FILE_NAME);
saveKeystore = true;
}
// Create project object from project properties file.
Project project = getProjectProperties(projectRoot);
File buildTmpDir = new File(projectRoot, "build/tmp");
buildTmpDir.mkdirs();
// Prepare for redirection of compiler message output
ByteArrayOutputStream output = new ByteArrayOutputStream();
PrintStream console = new PrintStream(output);
ByteArrayOutputStream errors = new ByteArrayOutputStream();
PrintStream userErrors = new PrintStream(errors);
Set<String> componentTypes = isForCompanion ? getAllComponentTypes() :
getComponentTypes(sourceFiles, project.getAssetsDirectory());
// Invoke YoungAndroid compiler
boolean success =
Compiler.compile(project, componentTypes, console, console, userErrors, isForCompanion,
keyStorePath, childProcessRam, dexCachePath);
console.close();
userErrors.close();
// Retrieve compiler messages and convert to HTML and log
String srcPath = projectRoot.getAbsolutePath() + "/" + PROJECT_DIRECTORY + "/../src/";
String messages = processCompilerOutput(output.toString(PathUtil.DEFAULT_CHARSET),
srcPath);
if (success) {
// Locate output file
File outputFile = new File(projectRoot,
"build/deploy/" + project.getProjectName() + ".apk");
if (!outputFile.exists()) {
LOG.warning("Young Android build - " + outputFile + " does not exist");
} else {
outputApk = new File(outputDir, outputFile.getName());
Files.copy(outputFile, outputApk);
if (saveKeystore) {
outputKeystore = new File(outputDir, KEYSTORE_FILE_NAME);
Files.copy(keyStoreFile, outputKeystore);
}
}
}
return new Result(success, messages, errors.toString(PathUtil.DEFAULT_CHARSET));
} finally {
// On some platforms (OS/X), the java.io.tmpdir contains a symlink. We need to use the
// canonical path here so that Files.deleteRecursively will work.
// Note (ralph): deleteRecursively has been removed from the guava-11.0.1 lib
// Replacing with deleteDirectory, which is supposed to delete the entire directory.
FileUtils.deleteQuietly(new File(projectRoot.getCanonicalPath()));
}
} catch (Exception e) {
e.printStackTrace();
return Result.createFailingResult("", "Server error performing build");
}
}
private void genYailFilesIfNecessary(List<String> sourceFiles)
throws IOException, YailGenerationException {
// Filter out the files that aren't really source files (i.e. that don't end in .scm or .yail)
Collection<String> formAndYailSourceFiles = Collections2.filter(
sourceFiles,
new Predicate<String>() {
@Override
public boolean apply(String input) {
return input.endsWith(FORM_PROPERTIES_EXTENSION) || input.endsWith(YAIL_EXTENSION);
}
});
for (String sourceFile : formAndYailSourceFiles) {
if (sourceFile.endsWith(FORM_PROPERTIES_EXTENSION)) {
String rootPath = sourceFile.substring(0, sourceFile.length()
- FORM_PROPERTIES_EXTENSION.length());
String yailFilePath = rootPath + YAIL_EXTENSION;
// Note: Famous last words: The following contains() makes this method O(n**2) but n should
// be pretty small.
if (!sourceFiles.contains(yailFilePath)) {
generateYail(rootPath);
}
}
}
}
private static Set<String> getAllComponentTypes() throws IOException {
Set<String> compSet = Sets.newHashSet();
String[] components = Resources.toString(
ProjectBuilder.class.getResource(ALL_COMPONENT_TYPES), Charsets.UTF_8).split("\n");
for (String component : components) {
compSet.add(component);
}
return compSet;
}
private ArrayList<String> extractProjectFiles(ZipFile inputZip, File projectRoot)
throws IOException {
ArrayList<String> projectFileNames = Lists.newArrayList();
Enumeration<? extends ZipEntry> inputZipEnumeration = inputZip.entries();
while (inputZipEnumeration.hasMoreElements()) {
ZipEntry zipEntry = inputZipEnumeration.nextElement();
final InputStream extractedInputStream = inputZip.getInputStream(zipEntry);
File extractedFile = new File(projectRoot, zipEntry.getName());
LOG.info("extracting " + extractedFile.getAbsolutePath() + " from input zip");
Files.createParentDirs(extractedFile); // Do I need this?
Files.copy(
new InputSupplier<InputStream>() {
public InputStream getInput() throws IOException {
return extractedInputStream;
}
},
extractedFile);
projectFileNames.add(extractedFile.getPath());
}
return projectFileNames;
}
private static Set<String> getComponentTypes(List<String> files, File assetsDir)
throws IOException, JSONException {
Map<String, String> nameTypeMap = createNameTypeMap(assetsDir);
Set<String> componentTypes = Sets.newHashSet();
for (String f : files) {
if (f.endsWith(".scm")) {
File scmFile = new File(f);
String scmContent = new String(Files.toByteArray(scmFile),
PathUtil.DEFAULT_CHARSET);
for (String compName : getTypesFromScm(scmContent)) {
componentTypes.add(nameTypeMap.get(compName));
}
}
}
return componentTypes;
}
/**
* In ode code, component names are used to identify a component though the
* variables storing component names appear to be "type". While there's no
* harm in ode, here in build server, they need to be separated.
* This method returns a name-type map, mapping the component names used in
* ode to the corresponding type, aka fully qualified name. The type will be
* used to build apk.
*/
private static Map<String, String> createNameTypeMap(File assetsDir)
throws IOException, JSONException {
Map<String, String> nameTypeMap = Maps.newHashMap();
JSONArray simpleCompsJson = new JSONArray(Resources.toString(ProjectBuilder.
class.getResource("/files/simple_components.json"), Charsets.UTF_8));
for (int i = 0; i < simpleCompsJson.length(); ++i) {
JSONObject simpleCompJson = simpleCompsJson.getJSONObject(i);
nameTypeMap.put(simpleCompJson.getString("name"),
simpleCompJson.getString("type"));
}
File extCompsDir = new File(assetsDir, "external_comps");
if (!extCompsDir.exists()) {
return nameTypeMap;
}
for (File extCompDir : extCompsDir.listFiles()) {
if (!extCompDir.isDirectory()) {
continue;
}
File extCompJsonFile = new File (extCompDir, "component.json");
if (extCompJsonFile.exists()) {
JSONObject extCompJson = new JSONObject(Resources.toString(
extCompJsonFile.toURI().toURL(), Charsets.UTF_8));
nameTypeMap.put(extCompJson.getString("name"),
extCompJson.getString("type"));
} else { // multi-extension package
extCompJsonFile = new File(extCompDir, "components.json");
if (extCompJsonFile.exists()) {
JSONArray extCompJson = new JSONArray(Resources.toString(
extCompJsonFile.toURI().toURL(), Charsets.UTF_8));
for (int i = 0; i < extCompJson.length(); i++) {
JSONObject extCompDescriptor = extCompJson.getJSONObject(i);
nameTypeMap.put(extCompDescriptor.getString("name"),
extCompDescriptor.getString("type"));
}
}
}
}
return nameTypeMap;
}
static String createKeyStore(String userName, File projectRoot, String keystoreFileName)
throws IOException {
File keyStoreFile = new File(projectRoot.getPath(), keystoreFileName);
/* Note: must expire after October 22, 2033, to be in the Android
* marketplace. Android docs recommend "10000" as the expiration # of
* days.
*
* For DNAME, US may not the right country to assign it to.
*/
String[] keytoolCommandline = {
System.getProperty("java.home") + "/bin/keytool",
"-genkey",
"-keystore", keyStoreFile.getAbsolutePath(),
"-alias", "AndroidKey",
"-keyalg", "RSA",
"-dname", "CN=" + quotifyUserName(userName) + ", O=AppInventor for Android, C=US",
"-validity", "10000",
"-storepass", "android",
"-keypass", "android"
};
if (Execution.execute(null, keytoolCommandline, System.out, System.err)) {
if (keyStoreFile.length() > 0) {
return keyStoreFile.getAbsolutePath();
}
}
return null;
}
@VisibleForTesting
static Set<String> getTypesFromScm(String scm) {
return FormPropertiesAnalyzer.getComponentTypesFromFormFile(scm);
}
@VisibleForTesting
static String processCompilerOutput(String output, String srcPath) {
// First, remove references to the temp source directory from the messages.
String messages = output.replace(srcPath, "");
// Then, format warnings and errors nicely.
try {
// Split the messages by \n and process each line separately.
String[] lines = messages.split("\n");
Pattern pattern = Pattern.compile("(.*?):(\\d+):\\d+: (error|warning)?:? ?(.*?)");
StringBuilder sb = new StringBuilder();
boolean skippedErrorOrWarning = false;
for (String line : lines) {
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
// Determine whether it is an error or warning.
String kind;
String spanClass;
// Scanner messages do not contain either 'error' or 'warning'.
// I treat them as errors because they prevent compilation.
if ("warning".equals(matcher.group(3))) {
kind = "WARNING";
spanClass = "compiler-WarningMarker";
} else {
kind = "ERROR";
spanClass = "compiler-ErrorMarker";
}
// Extract the filename, lineNumber, and message.
String filename = matcher.group(1);
String lineNumber = matcher.group(2);
String text = matcher.group(4);
// If the error/warning is in a yail file, generate a div and append it to the
// StringBuilder.
if (filename.endsWith(YoungAndroidConstants.YAIL_EXTENSION)) {
skippedErrorOrWarning = false;
sb.append("<div><span class='" + spanClass + "'>" + kind + "</span>: " +
StringUtils.escape(filename) + " line " + lineNumber + ": " +
StringUtils.escape(text) + "</div>");
} else {
// The error/warning is in runtime.scm. Don't append it to the StringBuilder.
skippedErrorOrWarning = true;
}
// Log the message, first truncating it if it is too long.
if (text.length() > MAX_COMPILER_MESSAGE_LENGTH) {
text = text.substring(0, MAX_COMPILER_MESSAGE_LENGTH);
}
} else {
// The line isn't an error or a warning. This is expected.
// If the line begins with two spaces, it is a continuation of the previous
// error/warning.
if (line.startsWith(" ")) {
// If we didn't skip the most recent error/warning, append the line to our
// StringBuilder.
if (!skippedErrorOrWarning) {
sb.append(StringUtils.escape(line)).append("<br>");
}
} else {
skippedErrorOrWarning = false;
// We just append the line to our StringBuilder.
sb.append(StringUtils.escape(line)).append("<br>");
}
}
}
messages = sb.toString();
} catch (Exception e) {
// Report exceptions that happen during the processing of output, but don't make the
// whole build fail.
e.printStackTrace();
// We were not able to process the output, so we just escape for HTML.
messages = StringUtils.escape(messages);
}
return messages;
}
/*
* Adds quotes around the given userName and encodes embedded quotes as \".
*/
private static String quotifyUserName(String userName) {
Preconditions.checkNotNull(userName);
int length = userName.length();
StringBuilder sb = new StringBuilder(length + 2);
sb.append('"');
for (int i = 0; i < length; i++) {
char ch = userName.charAt(i);
if (ch == '"') {
sb.append('\\').append(ch);
} else {
sb.append(ch);
}
}
sb.append('"');
return sb.toString();
}
/*
* Loads the project properties file of a Young Android project.
*/
private Project getProjectProperties(File projectRoot) {
return new Project(projectRoot.getAbsolutePath() + "/" + PROJECT_PROPERTIES_FILE_NAME);
}
private File generateYail(String rootName) throws IOException, YailGenerationException {
String formPropertiesPath = rootName + FORM_PROPERTIES_EXTENSION;
String codeblocksSourcePath = rootName + CODEBLOCKS_SOURCE_EXTENSION;
String yailPath = rootName + YAIL_EXTENSION;
String[] commandLine = {
System.getProperty("java.home") + "/bin/java",
"-mx1024M",
"-jar",
Compiler.getResource(Compiler.RUNTIME_FILES_DIR + "YailGenerator.jar"),
new File(formPropertiesPath).getAbsolutePath(),
new File(codeblocksSourcePath).getAbsolutePath(),
yailPath
};
StringBuffer out = new StringBuffer();
StringBuffer err = new StringBuffer();
int exitValue = Execution.execute(null, commandLine, out, err);
if (exitValue == 0) {
String generatedYailString = out.toString();
File generatedYailFile = new File(yailPath);
Files.write(generatedYailString, generatedYailFile, Charsets.UTF_8);
return generatedYailFile;
} else {
String formName = PathUtil.trimOffExtension(PathUtil.basename(formPropertiesPath));
if (exitValue == 1) {
// Failed to generate yail for legitimate reasons, such as empty sockets.
throw new YailGenerationException("Unable to generate code for " + formName + "."
+ "\n -- err is " + err.toString()
+ "\n -- out is" + out.toString(),
formName);
} else {
// Any other exit value is unexpected.
throw new RuntimeException("YailGenerator for form " + formName
+ " exited with code " + exitValue
+ "\n -- err is " + err.toString()
+ "\n -- out is" + out.toString());
}
}
}
private static class YailGenerationException extends Exception {
// The name of the form being built when an error occurred
private final String formName;
YailGenerationException(String message, String formName) {
super(message);
this.formName = formName;
}
/**
* Return the name of the form that Yail generation failed on.
*/
String getFormName() {
return formName;
}
}
public int getProgress() {
return Compiler.getProgress();
}
}
|
appinventor/buildserver/src/com/google/appinventor/buildserver/ProjectBuilder.java
|
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.buildserver;
import com.google.appinventor.common.utils.StringUtils;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.Files;
import com.google.common.io.InputSupplier;
import com.google.common.io.Resources;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.FileUtils;
/**
* Provides support for building Young Android projects.
*
* @author [email protected] (Mark Friedman)
*/
public final class ProjectBuilder {
private File outputApk;
private File outputKeystore;
private boolean saveKeystore;
// Logging support
private static final Logger LOG = Logger.getLogger(ProjectBuilder.class.getName());
private static final int MAX_COMPILER_MESSAGE_LENGTH = 160;
// Project folder prefixes
// TODO(user): These constants are (or should be) also defined in
// appengine/src/com/google/appinventor/server/project/youngandroid/YoungAndroidProjectService
// They should probably be in some place shared with the server
private static final String PROJECT_DIRECTORY = "youngandroidproject";
private static final String PROJECT_PROPERTIES_FILE_NAME = PROJECT_DIRECTORY + "/" +
"project.properties";
private static final String KEYSTORE_FILE_NAME = YoungAndroidConstants.PROJECT_KEYSTORE_LOCATION;
private static final String FORM_PROPERTIES_EXTENSION =
YoungAndroidConstants.FORM_PROPERTIES_EXTENSION;
private static final String YAIL_EXTENSION = YoungAndroidConstants.YAIL_EXTENSION;
private static final String CODEBLOCKS_SOURCE_EXTENSION =
YoungAndroidConstants.CODEBLOCKS_SOURCE_EXTENSION;
private static final String ALL_COMPONENT_TYPES =
Compiler.RUNTIME_FILES_DIR + "simple_components.txt";
public File getOutputApk() {
return outputApk;
}
public File getOutputKeystore() {
return outputKeystore;
}
/**
* Creates a new directory beneath the system's temporary directory (as
* defined by the {@code java.io.tmpdir} system property), and returns its
* name. The name of the directory will contain the current time (in millis),
* and a random number.
*
* <p>This method assumes that the temporary volume is writable, has free
* inodes and free blocks, and that it will not be called thousands of times
* per second.
*
* @return the newly-created directory
* @throws IllegalStateException if the directory could not be created
*/
private static File createNewTempDir() {
File baseDir = new File(System.getProperty("java.io.tmpdir"));
String baseNamePrefix = System.currentTimeMillis() + "_" + Math.random() + "-";
final int TEMP_DIR_ATTEMPTS = 10000;
for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
File tempDir = new File(baseDir, baseNamePrefix + counter);
if (tempDir.exists()) {
continue;
}
if (tempDir.mkdir()) {
return tempDir;
}
}
throw new IllegalStateException("Failed to create directory within "
+ TEMP_DIR_ATTEMPTS + " attempts (tried "
+ baseNamePrefix + "0 to " + baseNamePrefix + (TEMP_DIR_ATTEMPTS - 1) + ')');
}
Result build(String userName, ZipFile inputZip, File outputDir, boolean isForCompanion,
int childProcessRam, String dexCachePath) {
try {
// Download project files into a temporary directory
File projectRoot = createNewTempDir();
LOG.info("temporary project root: " + projectRoot.getAbsolutePath());
try {
List<String> sourceFiles;
try {
sourceFiles = extractProjectFiles(inputZip, projectRoot);
} catch (IOException e) {
LOG.severe("unexpected problem extracting project file from zip");
return Result.createFailingResult("", "Problems processing zip file.");
}
try {
genYailFilesIfNecessary(sourceFiles);
} catch (YailGenerationException e) {
// Note that we're using a special result code here for the case of a Yail gen error.
return new Result(Result.YAIL_GENERATION_ERROR, "", e.getMessage(), e.getFormName());
} catch (Exception e) {
LOG.severe("Unknown exception signalled by genYailFilesIf Necessary");
e.printStackTrace();
return Result.createFailingResult("", "Unexpected problems generating YAIL.");
}
File keyStoreFile = new File(projectRoot, KEYSTORE_FILE_NAME);
String keyStorePath = keyStoreFile.getPath();
if (!keyStoreFile.exists()) {
keyStorePath = createKeyStore(userName, projectRoot, KEYSTORE_FILE_NAME);
saveKeystore = true;
}
// Create project object from project properties file.
Project project = getProjectProperties(projectRoot);
File buildTmpDir = new File(projectRoot, "build/tmp");
buildTmpDir.mkdirs();
// Prepare for redirection of compiler message output
ByteArrayOutputStream output = new ByteArrayOutputStream();
PrintStream console = new PrintStream(output);
ByteArrayOutputStream errors = new ByteArrayOutputStream();
PrintStream userErrors = new PrintStream(errors);
Set<String> componentTypes = isForCompanion ? getAllComponentTypes() :
getComponentTypes(sourceFiles, project.getAssetsDirectory());
// Invoke YoungAndroid compiler
boolean success =
Compiler.compile(project, componentTypes, console, console, userErrors, isForCompanion,
keyStorePath, childProcessRam, dexCachePath);
console.close();
userErrors.close();
// Retrieve compiler messages and convert to HTML and log
String srcPath = projectRoot.getAbsolutePath() + "/" + PROJECT_DIRECTORY + "/../src/";
String messages = processCompilerOutput(output.toString(PathUtil.DEFAULT_CHARSET),
srcPath);
if (success) {
// Locate output file
File outputFile = new File(projectRoot,
"build/deploy/" + project.getProjectName() + ".apk");
if (!outputFile.exists()) {
LOG.warning("Young Android build - " + outputFile + " does not exist");
} else {
outputApk = new File(outputDir, outputFile.getName());
Files.copy(outputFile, outputApk);
if (saveKeystore) {
outputKeystore = new File(outputDir, KEYSTORE_FILE_NAME);
Files.copy(keyStoreFile, outputKeystore);
}
}
}
return new Result(success, messages, errors.toString(PathUtil.DEFAULT_CHARSET));
} finally {
// On some platforms (OS/X), the java.io.tmpdir contains a symlink. We need to use the
// canonical path here so that Files.deleteRecursively will work.
// Note (ralph): deleteRecursively has been removed from the guava-11.0.1 lib
// Replacing with deleteDirectory, which is supposed to delete the entire directory.
FileUtils.deleteDirectory(new File(projectRoot.getCanonicalPath()));
}
} catch (Exception e) {
e.printStackTrace();
return Result.createFailingResult("", "Server error performing build");
}
}
private void genYailFilesIfNecessary(List<String> sourceFiles)
throws IOException, YailGenerationException {
// Filter out the files that aren't really source files (i.e. that don't end in .scm or .yail)
Collection<String> formAndYailSourceFiles = Collections2.filter(
sourceFiles,
new Predicate<String>() {
@Override
public boolean apply(String input) {
return input.endsWith(FORM_PROPERTIES_EXTENSION) || input.endsWith(YAIL_EXTENSION);
}
});
for (String sourceFile : formAndYailSourceFiles) {
if (sourceFile.endsWith(FORM_PROPERTIES_EXTENSION)) {
String rootPath = sourceFile.substring(0, sourceFile.length()
- FORM_PROPERTIES_EXTENSION.length());
String yailFilePath = rootPath + YAIL_EXTENSION;
// Note: Famous last words: The following contains() makes this method O(n**2) but n should
// be pretty small.
if (!sourceFiles.contains(yailFilePath)) {
generateYail(rootPath);
}
}
}
}
private static Set<String> getAllComponentTypes() throws IOException {
Set<String> compSet = Sets.newHashSet();
String[] components = Resources.toString(
ProjectBuilder.class.getResource(ALL_COMPONENT_TYPES), Charsets.UTF_8).split("\n");
for (String component : components) {
compSet.add(component);
}
return compSet;
}
private ArrayList<String> extractProjectFiles(ZipFile inputZip, File projectRoot)
throws IOException {
ArrayList<String> projectFileNames = Lists.newArrayList();
Enumeration<? extends ZipEntry> inputZipEnumeration = inputZip.entries();
while (inputZipEnumeration.hasMoreElements()) {
ZipEntry zipEntry = inputZipEnumeration.nextElement();
final InputStream extractedInputStream = inputZip.getInputStream(zipEntry);
File extractedFile = new File(projectRoot, zipEntry.getName());
LOG.info("extracting " + extractedFile.getAbsolutePath() + " from input zip");
Files.createParentDirs(extractedFile); // Do I need this?
Files.copy(
new InputSupplier<InputStream>() {
public InputStream getInput() throws IOException {
return extractedInputStream;
}
},
extractedFile);
projectFileNames.add(extractedFile.getPath());
}
return projectFileNames;
}
private static Set<String> getComponentTypes(List<String> files, File assetsDir)
throws IOException, JSONException {
Map<String, String> nameTypeMap = createNameTypeMap(assetsDir);
Set<String> componentTypes = Sets.newHashSet();
for (String f : files) {
if (f.endsWith(".scm")) {
File scmFile = new File(f);
String scmContent = new String(Files.toByteArray(scmFile),
PathUtil.DEFAULT_CHARSET);
for (String compName : getTypesFromScm(scmContent)) {
componentTypes.add(nameTypeMap.get(compName));
}
}
}
return componentTypes;
}
/**
* In ode code, component names are used to identify a component though the
* variables storing component names appear to be "type". While there's no
* harm in ode, here in build server, they need to be separated.
* This method returns a name-type map, mapping the component names used in
* ode to the corresponding type, aka fully qualified name. The type will be
* used to build apk.
*/
private static Map<String, String> createNameTypeMap(File assetsDir)
throws IOException, JSONException {
Map<String, String> nameTypeMap = Maps.newHashMap();
JSONArray simpleCompsJson = new JSONArray(Resources.toString(ProjectBuilder.
class.getResource("/files/simple_components.json"), Charsets.UTF_8));
for (int i = 0; i < simpleCompsJson.length(); ++i) {
JSONObject simpleCompJson = simpleCompsJson.getJSONObject(i);
nameTypeMap.put(simpleCompJson.getString("name"),
simpleCompJson.getString("type"));
}
File extCompsDir = new File(assetsDir, "external_comps");
if (!extCompsDir.exists()) {
return nameTypeMap;
}
for (File extCompDir : extCompsDir.listFiles()) {
if (!extCompDir.isDirectory()) {
continue;
}
File extCompJsonFile = new File (extCompDir, "component.json");
if (extCompJsonFile.exists()) {
JSONObject extCompJson = new JSONObject(Resources.toString(
extCompJsonFile.toURI().toURL(), Charsets.UTF_8));
nameTypeMap.put(extCompJson.getString("name"),
extCompJson.getString("type"));
} else { // multi-extension package
extCompJsonFile = new File(extCompDir, "components.json");
if (extCompJsonFile.exists()) {
JSONArray extCompJson = new JSONArray(Resources.toString(
extCompJsonFile.toURI().toURL(), Charsets.UTF_8));
for (int i = 0; i < extCompJson.length(); i++) {
JSONObject extCompDescriptor = extCompJson.getJSONObject(i);
nameTypeMap.put(extCompDescriptor.getString("name"),
extCompDescriptor.getString("type"));
}
}
}
}
return nameTypeMap;
}
static String createKeyStore(String userName, File projectRoot, String keystoreFileName)
throws IOException {
File keyStoreFile = new File(projectRoot.getPath(), keystoreFileName);
/* Note: must expire after October 22, 2033, to be in the Android
* marketplace. Android docs recommend "10000" as the expiration # of
* days.
*
* For DNAME, US may not the right country to assign it to.
*/
String[] keytoolCommandline = {
System.getProperty("java.home") + "/bin/keytool",
"-genkey",
"-keystore", keyStoreFile.getAbsolutePath(),
"-alias", "AndroidKey",
"-keyalg", "RSA",
"-dname", "CN=" + quotifyUserName(userName) + ", O=AppInventor for Android, C=US",
"-validity", "10000",
"-storepass", "android",
"-keypass", "android"
};
if (Execution.execute(null, keytoolCommandline, System.out, System.err)) {
if (keyStoreFile.length() > 0) {
return keyStoreFile.getAbsolutePath();
}
}
return null;
}
@VisibleForTesting
static Set<String> getTypesFromScm(String scm) {
return FormPropertiesAnalyzer.getComponentTypesFromFormFile(scm);
}
@VisibleForTesting
static String processCompilerOutput(String output, String srcPath) {
// First, remove references to the temp source directory from the messages.
String messages = output.replace(srcPath, "");
// Then, format warnings and errors nicely.
try {
// Split the messages by \n and process each line separately.
String[] lines = messages.split("\n");
Pattern pattern = Pattern.compile("(.*?):(\\d+):\\d+: (error|warning)?:? ?(.*?)");
StringBuilder sb = new StringBuilder();
boolean skippedErrorOrWarning = false;
for (String line : lines) {
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
// Determine whether it is an error or warning.
String kind;
String spanClass;
// Scanner messages do not contain either 'error' or 'warning'.
// I treat them as errors because they prevent compilation.
if ("warning".equals(matcher.group(3))) {
kind = "WARNING";
spanClass = "compiler-WarningMarker";
} else {
kind = "ERROR";
spanClass = "compiler-ErrorMarker";
}
// Extract the filename, lineNumber, and message.
String filename = matcher.group(1);
String lineNumber = matcher.group(2);
String text = matcher.group(4);
// If the error/warning is in a yail file, generate a div and append it to the
// StringBuilder.
if (filename.endsWith(YoungAndroidConstants.YAIL_EXTENSION)) {
skippedErrorOrWarning = false;
sb.append("<div><span class='" + spanClass + "'>" + kind + "</span>: " +
StringUtils.escape(filename) + " line " + lineNumber + ": " +
StringUtils.escape(text) + "</div>");
} else {
// The error/warning is in runtime.scm. Don't append it to the StringBuilder.
skippedErrorOrWarning = true;
}
// Log the message, first truncating it if it is too long.
if (text.length() > MAX_COMPILER_MESSAGE_LENGTH) {
text = text.substring(0, MAX_COMPILER_MESSAGE_LENGTH);
}
} else {
// The line isn't an error or a warning. This is expected.
// If the line begins with two spaces, it is a continuation of the previous
// error/warning.
if (line.startsWith(" ")) {
// If we didn't skip the most recent error/warning, append the line to our
// StringBuilder.
if (!skippedErrorOrWarning) {
sb.append(StringUtils.escape(line)).append("<br>");
}
} else {
skippedErrorOrWarning = false;
// We just append the line to our StringBuilder.
sb.append(StringUtils.escape(line)).append("<br>");
}
}
}
messages = sb.toString();
} catch (Exception e) {
// Report exceptions that happen during the processing of output, but don't make the
// whole build fail.
e.printStackTrace();
// We were not able to process the output, so we just escape for HTML.
messages = StringUtils.escape(messages);
}
return messages;
}
/*
* Adds quotes around the given userName and encodes embedded quotes as \".
*/
private static String quotifyUserName(String userName) {
Preconditions.checkNotNull(userName);
int length = userName.length();
StringBuilder sb = new StringBuilder(length + 2);
sb.append('"');
for (int i = 0; i < length; i++) {
char ch = userName.charAt(i);
if (ch == '"') {
sb.append('\\').append(ch);
} else {
sb.append(ch);
}
}
sb.append('"');
return sb.toString();
}
/*
* Loads the project properties file of a Young Android project.
*/
private Project getProjectProperties(File projectRoot) {
return new Project(projectRoot.getAbsolutePath() + "/" + PROJECT_PROPERTIES_FILE_NAME);
}
private File generateYail(String rootName) throws IOException, YailGenerationException {
String formPropertiesPath = rootName + FORM_PROPERTIES_EXTENSION;
String codeblocksSourcePath = rootName + CODEBLOCKS_SOURCE_EXTENSION;
String yailPath = rootName + YAIL_EXTENSION;
String[] commandLine = {
System.getProperty("java.home") + "/bin/java",
"-mx1024M",
"-jar",
Compiler.getResource(Compiler.RUNTIME_FILES_DIR + "YailGenerator.jar"),
new File(formPropertiesPath).getAbsolutePath(),
new File(codeblocksSourcePath).getAbsolutePath(),
yailPath
};
StringBuffer out = new StringBuffer();
StringBuffer err = new StringBuffer();
int exitValue = Execution.execute(null, commandLine, out, err);
if (exitValue == 0) {
String generatedYailString = out.toString();
File generatedYailFile = new File(yailPath);
Files.write(generatedYailString, generatedYailFile, Charsets.UTF_8);
return generatedYailFile;
} else {
String formName = PathUtil.trimOffExtension(PathUtil.basename(formPropertiesPath));
if (exitValue == 1) {
// Failed to generate yail for legitimate reasons, such as empty sockets.
throw new YailGenerationException("Unable to generate code for " + formName + "."
+ "\n -- err is " + err.toString()
+ "\n -- out is" + out.toString(),
formName);
} else {
// Any other exit value is unexpected.
throw new RuntimeException("YailGenerator for form " + formName
+ " exited with code " + exitValue
+ "\n -- err is " + err.toString()
+ "\n -- out is" + out.toString());
}
}
}
private static class YailGenerationException extends Exception {
// The name of the form being built when an error occurred
private final String formName;
YailGenerationException(String message, String formName) {
super(message);
this.formName = formName;
}
/**
* Return the name of the form that Yail generation failed on.
*/
String getFormName() {
return formName;
}
}
public int getProgress() {
return Compiler.getProgress();
}
}
|
Update ProjectBuilder.java
|
appinventor/buildserver/src/com/google/appinventor/buildserver/ProjectBuilder.java
|
Update ProjectBuilder.java
|
<ide><path>ppinventor/buildserver/src/com/google/appinventor/buildserver/ProjectBuilder.java
<ide>
<ide> // Note (ralph): deleteRecursively has been removed from the guava-11.0.1 lib
<ide> // Replacing with deleteDirectory, which is supposed to delete the entire directory.
<del> FileUtils.deleteDirectory(new File(projectRoot.getCanonicalPath()));
<add> FileUtils.deleteQuietly(new File(projectRoot.getCanonicalPath()));
<ide> }
<ide> } catch (Exception e) {
<ide> e.printStackTrace();
|
|
Java
|
bsd-2-clause
|
56acb6043a84b0c2ca509a70e8917446bf5b8779
| 0 |
biovoxxel/imagej,biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej,TehSAUCE/imagej
|
/*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2012 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package imagej.updater.ssh;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import imagej.log.LogService;
import imagej.plugin.Plugin;
import imagej.updater.core.AbstractUploader;
import imagej.updater.core.FilesUploader;
import imagej.updater.core.Uploader;
import imagej.updater.core.Uploadable;
import imagej.updater.util.UpdateCanceledException;
import imagej.updater.util.InputStream2OutputStream;
import imagej.updater.util.UpdaterUserInterface;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/**
* Uploads files to an update server using SSH. In addition to writing files, it
* uses 'mv' and permissions to provide safe locking.
*
* @author Johannes Schindelin
* @author Yap Chin Kiet
*/
@Plugin(type = Uploader.class)
public class SSHFileUploader extends AbstractUploader {
private Session session;
private Channel channel;
private OutputStream out;
protected OutputStream err;
private InputStream in;
private LogService log;
public SSHFileUploader() throws JSchException {
err = UpdaterUserInterface.get().getOutputStream();
}
@Override
public boolean login(final FilesUploader uploader) {
if (!super.login(uploader)) return false;
log = uploader.getLog();
session = SSHSessionCreator.getSession(uploader);
return session != null;
}
@Override
public void logout() {
try {
disconnectSession();
} catch (IOException e) {
log.error(e);
}
}
// Steps to accomplish entire upload task
@Override
public synchronized void upload(final List<Uploadable> sources,
final List<String> locks) throws IOException
{
setCommand("date -u +%Y%m%d%H%M%S");
timestamp = readNumber(in);
setTitle("Uploading");
final String uploadFilesCommand = "scp -p -t -r " + uploadDir;
setCommand(uploadFilesCommand);
if (checkAck(in) != 0) {
throw new IOException("Failed to set command " + uploadFilesCommand);
}
try {
uploadFiles(sources);
}
catch (final UpdateCanceledException cancel) {
for (final String lock : locks)
setCommand("rm " + uploadDir + lock + ".lock");
out.close();
channel.disconnect();
throw cancel;
}
// Unlock process
for (final String lock : locks)
setCommand("mv " + uploadDir + lock + ".lock " + uploadDir + lock);
out.close();
disconnectSession();
}
private void uploadFiles(final List<Uploadable> sources) throws IOException {
calculateTotalSize(sources);
int count = 0;
String prefix = "";
final byte[] buf = new byte[16384];
for (final Uploadable source : sources) {
final String target = source.getFilename();
while (!target.startsWith(prefix))
prefix = cdUp(prefix);
// maybe need to enter directory
final int slash = target.lastIndexOf('/');
final String directory = target.substring(0, slash + 1);
cdInto(directory.substring(prefix.length()));
prefix = directory;
// notification that file is about to be written
final String command =
source.getPermissions() + " " + source.getFilesize() + " " +
target.substring(slash + 1) + "\n";
out.write(command.getBytes());
out.flush();
checkAckUploadError(target);
/*
* Make sure that the file is there; this is critical
* to get the server timestamp from db.xml.gz.lock.
*/
addItem(source);
// send contents of file
final InputStream input = source.getInputStream();
int currentCount = 0;
final int currentTotal = (int) source.getFilesize();
for (;;) {
final int len = input.read(buf, 0, buf.length);
if (len <= 0) break;
out.write(buf, 0, len);
currentCount += len;
setItemCount(currentCount, currentTotal);
setCount(count + currentCount, total);
}
input.close();
count += currentCount;
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
checkAckUploadError(target);
itemDone(source);
}
while (!prefix.equals("")) {
prefix = cdUp(prefix);
}
done();
}
private String cdUp(final String directory) throws IOException {
out.write("E\n".getBytes());
out.flush();
checkAckUploadError(directory);
final int slash = directory.lastIndexOf('/', directory.length() - 2);
return directory.substring(0, slash + 1);
}
private void cdInto(String directory) throws IOException {
while (!directory.equals("")) {
final int slash = directory.indexOf('/');
final String name =
(slash < 0 ? directory : directory.substring(0, slash));
final String command = "D2775 0 " + name + "\n";
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) throw new IOException("Cannot enter directory " +
name);
if (slash < 0) return;
directory = directory.substring(slash + 1);
}
}
private void setCommand(final String command) throws IOException {
if (out != null) {
out.close();
channel.disconnect();
}
try {
UpdaterUserInterface.get().debug("launching command " + command);
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(err);
// get I/O streams for remote scp
out = channel.getOutputStream();
in = channel.getInputStream();
channel.connect();
}
catch (final JSchException e) {
log.error(e);
throw new IOException(e.getMessage());
}
}
private void checkAckUploadError(final String target) throws IOException {
if (checkAck(in) != 0) throw new IOException("Failed to upload " + target);
}
public void disconnectSession() throws IOException {
if (in != null)
new InputStream2OutputStream(in, UpdaterUserInterface.get().getOutputStream());
try {
Thread.sleep(100);
}
catch (final InterruptedException e) {
/* ignore */
}
if (out != null)
out.close();
try {
Thread.sleep(1000);
}
catch (final InterruptedException e) {
/* ignore */
}
int exitStatus = 0;
if (channel != null) {
exitStatus = channel.getExitStatus();
UpdaterUserInterface.get().debug(
"disconnect session; exit status is " + exitStatus);
channel.disconnect();
}
if (session != null)
session.disconnect();
if (err != null)
err.close();
if (exitStatus != 0) throw new IOException("Command failed with status " +
exitStatus + " (see Log)!");
}
protected long readNumber(final InputStream in) throws IOException {
long result = 0;
for (;;) {
final int b = in.read();
if (b >= '0' && b <= '9') result = 10 * result + b - '0';
else if (b == '\n') return result;
}
}
private int checkAck(final InputStream in) throws IOException {
final int b = in.read();
// b may be 0 for success,
// 1 for error,
// 2 for fatal error,
// -1
if (b == 0) return b;
UpdaterUserInterface.get().handleException(new Exception("checkAck returns " + b));
if (b == -1) return b;
if (b == 1 || b == 2) {
final StringBuffer sb = new StringBuffer();
int c;
do {
c = in.read();
sb.append((char) c);
}
while (c != '\n');
UpdaterUserInterface.get().log("checkAck returned '" + sb.toString() + "'");
UpdaterUserInterface.get().error(sb.toString());
}
return b;
}
@Override
public String getProtocol() {
return "ssh";
}
}
|
core/updater/ssh/src/main/java/imagej/updater/ssh/SSHFileUploader.java
|
/*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2012 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package imagej.updater.ssh;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import imagej.log.LogService;
import imagej.plugin.Plugin;
import imagej.updater.core.AbstractUploader;
import imagej.updater.core.FilesUploader;
import imagej.updater.core.Uploader;
import imagej.updater.core.Uploadable;
import imagej.updater.util.UpdateCanceledException;
import imagej.updater.util.InputStream2OutputStream;
import imagej.updater.util.UpdaterUserInterface;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/**
* Uploads files to an update server using SSH. In addition to writing files, it
* uses 'mv' and permissions to provide safe locking.
*
* @author Johannes Schindelin
* @author Yap Chin Kiet
*/
@Plugin(type = Uploader.class)
public class SSHFileUploader extends AbstractUploader {
private Session session;
private Channel channel;
private OutputStream out;
protected OutputStream err;
private InputStream in;
private LogService log;
public SSHFileUploader() throws JSchException {
err = UpdaterUserInterface.get().getOutputStream();
}
@Override
public boolean login(final FilesUploader uploader) {
if (!super.login(uploader)) return false;
log = uploader.getLog();
session = SSHSessionCreator.getSession(uploader);
return session != null;
}
@Override
public void logout() {
try {
disconnectSession();
} catch (IOException e) {
log.error(e);
}
}
// Steps to accomplish entire upload task
@Override
public synchronized void upload(final List<Uploadable> sources,
final List<String> locks) throws IOException
{
setCommand("date --utc +%Y%m%d%H%M%S");
timestamp = readNumber(in);
setTitle("Uploading");
final String uploadFilesCommand = "scp -p -t -r " + uploadDir;
setCommand(uploadFilesCommand);
if (checkAck(in) != 0) {
throw new IOException("Failed to set command " + uploadFilesCommand);
}
try {
uploadFiles(sources);
}
catch (final UpdateCanceledException cancel) {
for (final String lock : locks)
setCommand("rm " + uploadDir + lock + ".lock");
out.close();
channel.disconnect();
throw cancel;
}
// Unlock process
for (final String lock : locks)
setCommand("mv " + uploadDir + lock + ".lock " + uploadDir + lock);
out.close();
disconnectSession();
}
private void uploadFiles(final List<Uploadable> sources) throws IOException {
calculateTotalSize(sources);
int count = 0;
String prefix = "";
final byte[] buf = new byte[16384];
for (final Uploadable source : sources) {
final String target = source.getFilename();
while (!target.startsWith(prefix))
prefix = cdUp(prefix);
// maybe need to enter directory
final int slash = target.lastIndexOf('/');
final String directory = target.substring(0, slash + 1);
cdInto(directory.substring(prefix.length()));
prefix = directory;
// notification that file is about to be written
final String command =
source.getPermissions() + " " + source.getFilesize() + " " +
target.substring(slash + 1) + "\n";
out.write(command.getBytes());
out.flush();
checkAckUploadError(target);
/*
* Make sure that the file is there; this is critical
* to get the server timestamp from db.xml.gz.lock.
*/
addItem(source);
// send contents of file
final InputStream input = source.getInputStream();
int currentCount = 0;
final int currentTotal = (int) source.getFilesize();
for (;;) {
final int len = input.read(buf, 0, buf.length);
if (len <= 0) break;
out.write(buf, 0, len);
currentCount += len;
setItemCount(currentCount, currentTotal);
setCount(count + currentCount, total);
}
input.close();
count += currentCount;
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
checkAckUploadError(target);
itemDone(source);
}
while (!prefix.equals("")) {
prefix = cdUp(prefix);
}
done();
}
private String cdUp(final String directory) throws IOException {
out.write("E\n".getBytes());
out.flush();
checkAckUploadError(directory);
final int slash = directory.lastIndexOf('/', directory.length() - 2);
return directory.substring(0, slash + 1);
}
private void cdInto(String directory) throws IOException {
while (!directory.equals("")) {
final int slash = directory.indexOf('/');
final String name =
(slash < 0 ? directory : directory.substring(0, slash));
final String command = "D2775 0 " + name + "\n";
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) throw new IOException("Cannot enter directory " +
name);
if (slash < 0) return;
directory = directory.substring(slash + 1);
}
}
private void setCommand(final String command) throws IOException {
if (out != null) {
out.close();
channel.disconnect();
}
try {
UpdaterUserInterface.get().debug("launching command " + command);
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(err);
// get I/O streams for remote scp
out = channel.getOutputStream();
in = channel.getInputStream();
channel.connect();
}
catch (final JSchException e) {
log.error(e);
throw new IOException(e.getMessage());
}
}
private void checkAckUploadError(final String target) throws IOException {
if (checkAck(in) != 0) throw new IOException("Failed to upload " + target);
}
public void disconnectSession() throws IOException {
if (in != null)
new InputStream2OutputStream(in, UpdaterUserInterface.get().getOutputStream());
try {
Thread.sleep(100);
}
catch (final InterruptedException e) {
/* ignore */
}
if (out != null)
out.close();
try {
Thread.sleep(1000);
}
catch (final InterruptedException e) {
/* ignore */
}
int exitStatus = 0;
if (channel != null) {
exitStatus = channel.getExitStatus();
UpdaterUserInterface.get().debug(
"disconnect session; exit status is " + exitStatus);
channel.disconnect();
}
if (session != null)
session.disconnect();
if (err != null)
err.close();
if (exitStatus != 0) throw new IOException("Command failed with status " +
exitStatus + " (see Log)!");
}
protected long readNumber(final InputStream in) throws IOException {
long result = 0;
for (;;) {
final int b = in.read();
if (b >= '0' && b <= '9') result = 10 * result + b - '0';
else if (b == '\n') return result;
}
}
private int checkAck(final InputStream in) throws IOException {
final int b = in.read();
// b may be 0 for success,
// 1 for error,
// 2 for fatal error,
// -1
if (b == 0) return b;
UpdaterUserInterface.get().handleException(new Exception("checkAck returns " + b));
if (b == -1) return b;
if (b == 1 || b == 2) {
final StringBuffer sb = new StringBuffer();
int c;
do {
c = in.read();
sb.append((char) c);
}
while (c != '\n');
UpdaterUserInterface.get().log("checkAck returned '" + sb.toString() + "'");
UpdaterUserInterface.get().error(sb.toString());
}
return b;
}
@Override
public String getProtocol() {
return "ssh";
}
}
|
Updater: support uploading to a MacOSX server
As pointed out by Jerôme Mutterer in the Fiji bug report
http://fiji.sc/bugzilla/show_bug.cgi?id=535, 'date --utc' is not
portable enough.
So let's use 'date -u' instead, which is not as expressive, but at
least it is understood by MacOSX in addition to Linux.
Signed-off-by: Johannes Schindelin <[email protected]>
|
core/updater/ssh/src/main/java/imagej/updater/ssh/SSHFileUploader.java
|
Updater: support uploading to a MacOSX server
|
<ide><path>ore/updater/ssh/src/main/java/imagej/updater/ssh/SSHFileUploader.java
<ide> final List<String> locks) throws IOException
<ide> {
<ide>
<del> setCommand("date --utc +%Y%m%d%H%M%S");
<add> setCommand("date -u +%Y%m%d%H%M%S");
<ide> timestamp = readNumber(in);
<ide> setTitle("Uploading");
<ide>
|
|
JavaScript
|
mit
|
d2730ef851090544eb110861eec395904c89b764
| 0 |
ArnaudBuchholz/gpf-js,ArnaudBuchholz/gpf-js
|
/*#ifndef(UMD)*/
"use strict";
/*global _gpfIgnore*/ // Helper to remove unused parameter warning
/*global _gpfObjectForEach*/ // Similar to [].forEach but for objects
/*global _gpfStringReplaceEx*/ // String replacement using dictionary map
/*exported _gpfErrorDeclare*/
/*#endif*/
/**
* GPF Error class
*
* @constructor
* @class _GpfError
* @alias gpf.Error
*/
var _GpfError = gpf.Error = function () {};
_GpfError.prototype = {
constructor: _GpfError,
// Error code @readonly
code: 0,
// Error name @readonly
name: "Error",
// Error message @readonly
message: ""
};
function _gpfErrorFactory (code, name, message) {
return function (context) {
var error = new _GpfError(),
finalMessage,
replacements;
/*gpf:constant*/
error.code = code;
/*gpf:constant*/
error.name = name;
if (context) {
replacements = {};
/*gpf:inline(object)*/
_gpfObjectForEach(context, function (value, key) {
replacements["{" + key + "}"] = value.toString();
});
finalMessage = _gpfStringReplaceEx(message, replacements);
} else {
finalMessage = message;
}
/*gpf:constant*/
error.message = finalMessage;
return error;
};
}
/**
* Generates an error function
*
* @param {Number} code
* @param {String} name
* @return {Function}
* @closure
*/
function _gpfGenenerateErrorFunction (code, name, message) {
var result = _gpfErrorFactory(code, name, message);
/*gpf:constant*/ result.CODE = code;
/*gpf:constant*/ result.NAME = name;
/*gpf:constant*/ result.MESSAGE = message;
return result;
}
// Last allocated error code
var _gpfLastErrorCode = 0;
/**
* Declare error messages.
* Each module declares its own errors.
*
* @param {String} module
* @param {Object} list Dictionary of name to message
*/
function _gpfErrorDeclare (module, list) {
var
name,
code;
_gpfIgnore(module);
for (name in list) {
/* istanbul ignore else */
if (list.hasOwnProperty(name)) {
code = ++_gpfLastErrorCode;
gpf.Error["CODE_" + name.toUpperCase()] = code;
gpf.Error[name] = _gpfGenenerateErrorFunction(code, name, list[name]);
}
}
}
_gpfErrorDeclare("boot", {
notImplemented:
"Not implemented",
abstractMethod:
"Abstract method",
assertionFailed:
"Assertion failed: {message}",
invalidParameter:
"Invalid parameter"
});
|
src/error.js
|
/*#ifndef(UMD)*/
"use strict";
/*global _gpfIgnore*/ // Helper to remove unused parameter warning
/*global _gpfObjectForEach*/ // Similar to [].forEach but for objects
/*global _gpfStringReplaceEx*/ // String replacement using dictionary map
/*exported _gpfErrorDeclare*/
/*#endif*/
/**
* GPF Error class
*
* @constructor
* @class _GpfError
* @alias gpf.Error
*/
var _GpfError = gpf.Error = function () {};
_GpfError.prototype = {
constructor: _GpfError,
// Error code @readonly
code: 0,
// Error name @readonly
name: "Error",
// Error message @readonly
message: ""
};
function _gpfErrorFactory (code, name, message) {
return function (context) {
var error = new _GpfError(),
finalMessage,
replacements;
/*gpf:constant*/
error.code = code;
/*gpf:constant*/
error.name = name;
if (context) {
replacements = {};
/*gpf:inline(object)*/
_gpfObjectForEach(context, function (value, key) {
replacements["{" + key + "}"] = value.toString();
});
finalMessage = _gpfStringReplaceEx(message, replacements);
} else {
finalMessage = message;
}
/*gpf:constant*/
error.message = finalMessage;
return error;
};
}
/**
* Generates an error function
*
* @param {Number} code
* @param {String} name
* @return {Function}
* @closure
*/
function _gpfGenenerateErrorFunction (code, name, message) {
var result = _gpfErrorFactory(code, name, message);
/*gpf:constant*/ result.CODE = code;
/*gpf:constant*/ result.NAME = name;
/*gpf:constant*/ result.MESSAGE = message;
return result;
}
// Last allocated error code
var _gpfLastErrorCode = 0;
/**
* Declare error messages.
* Each module declares its own errors.
*
* @param {String} module
* @param {Object} list Dictionary of name to message
*/
function _gpfErrorDeclare (module, list) {
var
name,
code;
_gpfIgnore(module);
for (name in list) {
if (list.hasOwnProperty(name)) {
code = ++_gpfLastErrorCode;
gpf.Error["CODE_" + name.toUpperCase()] = code;
gpf.Error[name] = _gpfGenenerateErrorFunction(code, name, list[name]);
}
}
}
_gpfErrorDeclare("boot", {
notImplemented:
"Not implemented",
abstractMethod:
"Abstract method",
assertionFailed:
"Assertion failed: {message}",
invalidParameter:
"Invalid parameter"
});
|
Improved coverage
|
src/error.js
|
Improved coverage
|
<ide><path>rc/error.js
<ide> code;
<ide> _gpfIgnore(module);
<ide> for (name in list) {
<add> /* istanbul ignore else */
<ide> if (list.hasOwnProperty(name)) {
<ide> code = ++_gpfLastErrorCode;
<ide> gpf.Error["CODE_" + name.toUpperCase()] = code;
|
|
Java
|
mit
|
029dda8861683a814a973557f51930f35c1dcd39
| 0 |
conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5
|
package com.conveyal.r5.analyst;
import com.conveyal.r5.analyst.cluster.AnalysisTask;
import com.conveyal.r5.analyst.cluster.TimeGridWriter;
import com.conveyal.r5.analyst.error.TaskError;
import com.conveyal.r5.common.JsonUtilities;
import com.conveyal.r5.multipoint.MultipointDataStore;
import com.conveyal.r5.profile.FastRaptorWorker;
import com.conveyal.r5.profile.PerTargetPropagater;
import com.conveyal.r5.transit.TransportNetwork;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collection;
/**
* Take the travel times to targets at each iteration (passed in one target at a time, because storing them all in memory
* is not practical), and summarize that list to a few percentiles of travel time and return them in an AccessGrid-format
* file (see AccessGridWriter for format documentation).
*
* FIXME the destinations are always passed in in order. Why not just stream them through?
* i.e. call startWrite() then writeOnePixel() in a loop, then endWrite()
*/
public class TravelTimeSurfaceReducer implements PerTargetPropagater.TravelTimeReducer {
private static final Logger LOG = LoggerFactory.getLogger(TravelTimeSurfaceReducer.class);
/** Travel time results encoded as an access grid */
private TimeGridWriter timeResults;
/** The output stream to write the result to */
private OutputStream outputStream;
/** The network used to compute the travel time results */
public final TransportNetwork network;
/** The task used to create travel times being reduced herein */
public final AnalysisTask task;
public TravelTimeSurfaceReducer (AnalysisTask task, TransportNetwork network, OutputStream outputStream) {
this.task = task;
this.network = network;
this.outputStream = outputStream;
try {
// use an in-memory access grid, don't specify disk cache file
timeResults = new TimeGridWriter(task.zoom, task.west, task.north, task.width, task.height, task.percentiles.length);
timeResults.initialize("ACCESSGR", 0);
} catch (IOException e) {
// in memory, should not be able to throw this
throw new RuntimeException(e);
}
}
@Override
public void recordTravelTimesForTarget (int target, int[] times) {
int nPercentiles = task.percentiles.length;
// sort the times at each target and read off percentiles
Arrays.sort(times);
int[] results = new int[nPercentiles];
for (int i = 0; i < nPercentiles; i++) {
// We scale the interval between the beginning and end elements of the array (the min and max values).
// In an array with N values the interval is N-1 elements. We should be scaling N-1, which makes the result
// always defined even when using a high percentile and low number of elements. Previously, this caused
// an error below when requesting the 95th percentile when times.length = 1 (or any length less than 10).
int offset = (int) Math.round(task.percentiles[i] / 100d * (times.length-1));
// Int divide will floor; this is correct because value 0 has travel times of up to one minute, etc.
// This means that anything less than a cutoff of (say) 60 minutes (in seconds) will have value 59,
// which is what we want. But maybe this is tying the backend and frontend too closely.
results[i] = times[offset] == FastRaptorWorker.UNREACHED ? FastRaptorWorker.UNREACHED : times[offset] / 60;
}
int x = target % task.width;
int y = target / task.width;
try {
timeResults.writePixel(x, y, results);
} catch (IOException e) {
// can't happen as we're not using a file system backed output
throw new RuntimeException(e);
}
}
/**
* Write the accumulated results out to the location specified in the request, or the output stream.
*
* If no travel times to destinations have been streamed in by calling recordTravelTimesForTarget, the
* AccessGridWriter (encodedResults) will have a buffer full of UNREACHED. This allows shortcutting around
* routing and propagation when the origin point is not connected to the street network.
*/
@Override
public void finish () {
try {
LOG.info("Travel time surface of size {} kB complete", timeResults.buffer.position() / 1000);
// if the outputStream was null in the constructor, write to S3.
if (outputStream == null) {
outputStream = MultipointDataStore.getOutputStream(task, task.taskId + "_times.dat", "application/octet-stream");
}
outputStream.write(timeResults.buffer.array());
LOG.info("Travel time surface written, appending metadata with {} warnings",
network.scenarioApplicationWarnings.size());
// Append scenario application warning JSON to result
ResultMetadata metadata = new ResultMetadata();
metadata.scenarioApplicationWarnings = network.scenarioApplicationWarnings;
JsonUtilities.objectMapper.writeValue(outputStream, metadata);
LOG.info("Done writing");
outputStream.close();
} catch (IOException e) {
LOG.warn("Unexpected IOException returning travel time surface to client", e);
}
}
private static class ResultMetadata {
public Collection<TaskError> scenarioApplicationWarnings;
}
}
|
src/main/java/com/conveyal/r5/analyst/TravelTimeSurfaceReducer.java
|
package com.conveyal.r5.analyst;
import com.conveyal.r5.analyst.cluster.AnalysisTask;
import com.conveyal.r5.analyst.cluster.TimeGridWriter;
import com.conveyal.r5.analyst.error.TaskError;
import com.conveyal.r5.common.JsonUtilities;
import com.conveyal.r5.multipoint.MultipointDataStore;
import com.conveyal.r5.profile.FastRaptorWorker;
import com.conveyal.r5.profile.PerTargetPropagater;
import com.conveyal.r5.transit.TransportNetwork;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collection;
/**
* Take the travel times to targets at each iteration (passed in one target at a time, because storing them all in memory
* is not practical), and summarize that list to a few percentiles of travel time and return them in an AccessGrid-format
* file (see AccessGridWriter for format documentation).
*
* FIXME the destinations are always passed in in order. Why not just stream them through?
* i.e. call startWrite() then writeOnePixel() in a loop, then endWrite()
*/
public class TravelTimeSurfaceReducer implements PerTargetPropagater.TravelTimeReducer {
private static final Logger LOG = LoggerFactory.getLogger(TravelTimeSurfaceReducer.class);
/** Travel time results encoded as an access grid */
private TimeGridWriter timeResults;
/** The output stream to write the result to */
private OutputStream outputStream;
/** The network used to compute the travel time results */
public final TransportNetwork network;
/** The task used to create travel times being reduced herein */
public final AnalysisTask task;
public TravelTimeSurfaceReducer (AnalysisTask task, TransportNetwork network, OutputStream outputStream) {
this.task = task;
this.network = network;
this.outputStream = outputStream;
try {
// use an in-memory access grid, don't specify disk cache file
timeResults = new TimeGridWriter(task.zoom, task.west, task.north, task.width, task.height, task.percentiles.length);
timeResults.initialize("TIMEGRID", 0);
} catch (IOException e) {
// in memory, should not be able to throw this
throw new RuntimeException(e);
}
}
@Override
public void recordTravelTimesForTarget (int target, int[] times) {
int nPercentiles = task.percentiles.length;
// sort the times at each target and read off percentiles
Arrays.sort(times);
int[] results = new int[nPercentiles];
for (int i = 0; i < nPercentiles; i++) {
// We scale the interval between the beginning and end elements of the array (the min and max values).
// In an array with N values the interval is N-1 elements. We should be scaling N-1, which makes the result
// always defined even when using a high percentile and low number of elements. Previously, this caused
// an error below when requesting the 95th percentile when times.length = 1 (or any length less than 10).
int offset = (int) Math.round(task.percentiles[i] / 100d * (times.length-1));
// Int divide will floor; this is correct because value 0 has travel times of up to one minute, etc.
// This means that anything less than a cutoff of (say) 60 minutes (in seconds) will have value 59,
// which is what we want. But maybe this is tying the backend and frontend too closely.
results[i] = times[offset] == FastRaptorWorker.UNREACHED ? FastRaptorWorker.UNREACHED : times[offset] / 60;
}
int x = target % task.width;
int y = target / task.width;
try {
timeResults.writePixel(x, y, results);
} catch (IOException e) {
// can't happen as we're not using a file system backed output
throw new RuntimeException(e);
}
}
/**
* Write the accumulated results out to the location specified in the request, or the output stream.
*
* If no travel times to destinations have been streamed in by calling recordTravelTimesForTarget, the
* AccessGridWriter (encodedResults) will have a buffer full of UNREACHED. This allows shortcutting around
* routing and propagation when the origin point is not connected to the street network.
*/
@Override
public void finish () {
try {
LOG.info("Travel time surface of size {} kB complete", timeResults.buffer.position() / 1000);
// if the outputStream was null in the constructor, write to S3.
if (outputStream == null) {
outputStream = MultipointDataStore.getOutputStream(task, task.taskId + "_times.dat", "application/octet-stream");
}
outputStream.write(timeResults.buffer.array());
LOG.info("Travel time surface written, appending metadata with {} warnings",
network.scenarioApplicationWarnings.size());
// Append scenario application warning JSON to result
ResultMetadata metadata = new ResultMetadata();
metadata.scenarioApplicationWarnings = network.scenarioApplicationWarnings;
JsonUtilities.objectMapper.writeValue(outputStream, metadata);
LOG.info("Done writing");
outputStream.close();
} catch (IOException e) {
LOG.warn("Unexpected IOException returning travel time surface to client", e);
}
}
private static class ResultMetadata {
public Collection<TaskError> scenarioApplicationWarnings;
}
}
|
fix(multipoint): make surface type "ACCESSGR"
to maintain compatibility with current front-end
|
src/main/java/com/conveyal/r5/analyst/TravelTimeSurfaceReducer.java
|
fix(multipoint): make surface type "ACCESSGR"
|
<ide><path>rc/main/java/com/conveyal/r5/analyst/TravelTimeSurfaceReducer.java
<ide> try {
<ide> // use an in-memory access grid, don't specify disk cache file
<ide> timeResults = new TimeGridWriter(task.zoom, task.west, task.north, task.width, task.height, task.percentiles.length);
<del> timeResults.initialize("TIMEGRID", 0);
<add> timeResults.initialize("ACCESSGR", 0);
<ide>
<ide> } catch (IOException e) {
<ide> // in memory, should not be able to throw this
|
|
JavaScript
|
mit
|
7330daa38e4b5cac0e9ce5bfd76b918aeaa6cd14
| 0 |
scratchdesignstudio/translate-formatter,scratchdesignstudio/translate-formatter
|
var link, age, appropriate, patience, whatIsSDS, result;
document.onkeyup = function(){
unique1 = document.getElementById('unique1').value.replace(/[\"]/g, "\\\"") + "\\n" + "<br/><br/>";
unique2 = document.getElementById('unique2').value.replace(/[\"]/g, "\\\"") + "<br/>";
unique3 = document.getElementById('unique3').value.replace(/[\"]/g, "\\\"") + "<br/>";
unique4 = document.getElementById('unique4').value.replace(/[\"]/g, "\\\"") + "<br/>";
unique5 = document.getElementById('unique5').value.replace(/[\"]/g, "\\\"") + "<br/>";
unique6 = document.getElementById('unique6').value.replace(/[\"]/g, "\\\"") + "<br/>";
unique7 = document.getElementById('unique7').value.replace(/[\"]/g, "\\\"") + "\\n" + "<br/><br/>";
unique8 = document.getElementById('unique8').value.replace(/[\"]/g, "\\\"") + "\\n" +"<br/><br/>";
result = document.getElementById('result');
result.innerHTML = unique1 + unique2 + unique3 + unique4 + unique5 + unique6 + unique7 + unique8;
link = document.getElementById('link').value.replace(/[\"]/g, "\\\"") + "\\n" + "<br/>";
age = document.getElementById('age').value.replace(/[\"]/g, "\\\"") + "\\n" + "<br/>";
appropriate = document.getElementById('appropriate').value.replace(/[\"]/g, "\\\"") + "\\n" + "<br/>";
patience = document.getElementById('patience').value.replace(/[\"]/g, "\\\"") + "\\n" + "<br/><br/>";
whatIsSDS = document.getElementById('whatIsSDS').value.replace(/[\"]/g, "\\\"") + "\\n";
selected = " " + document.getElementById('selected').value.replace(/[\"]/g, "\\\"") + " <a href=\"https://scratch.mit.edu/projects/55738732/\">" + "https://scratch.mit.edu/projects/55738732/" + "</a>" + "\\n";
ask = document.getElementById('ask').value.replace(/[\"]/g, "\\\"") + "\\n" + "<br/><br/>";
idea = document.getElementById('idea').value.replace(/[\"]/g, "\\\"") + " <a href=\"https://scratch.mit.edu/studios/93627/\">" + "https://scratch.mit.edu/studios/93627/" + "</a>" + "\\n" + "<br/><br/>";
wiki = document.getElementById('wiki').value.replace(/[\"]/g, "\\\"") + " <a href=\"http://wiki.scratch.mit.edu/wiki/SDS/\">" + "http://wiki.scratch.mit.edu/wiki/SDS/" + "</a>" + "\\n" + "<br/><br/>";
account = document.getElementById('account').value.replace(/[\"]/g, "\\\"") + " <a href=\"https://scratch.mit.edu/users/SDS-Updates/\">" + "@SDS-Updates" + "</a>" + "\\n" + "<br/><br/>";
thumbnail = document.getElementById('thumbnail').value.replace(/[\"]/g, "\\\"");
result2 = document.getElementById('result2');
result2.innerHTML = link + age + appropriate + patience + whatIsSDS + selected + ask + idea + wiki + account + thumbnail;
};
|
formatter.js
|
var link, age, appropriate, patience, whatIsSDS, result;
document.onkeyup = function(){
unique1 = document.getElementById('unique1').value.replace(/[\"]/g, "\\\"") + "<br/><br/>";
unique2 = document.getElementById('unique2').value.replace(/[\"]/g, "\\\"") + "<br/>";
unique3 = document.getElementById('unique3').value.replace(/[\"]/g, "\\\"") + "<br/>";
unique4 = document.getElementById('unique4').value.replace(/[\"]/g, "\\\"") + "<br/>";
unique5 = document.getElementById('unique5').value.replace(/[\"]/g, "\\\"") + "<br/>";
unique6 = document.getElementById('unique6').value.replace(/[\"]/g, "\\\"") + "<br/>";
unique7 = document.getElementById('unique7').value.replace(/[\"]/g, "\\\"") + "<br/><br/>";
unique8 = document.getElementById('unique8').value.replace(/[\"]/g, "\\\"") + "<br/><br/>";
result = document.getElementById('result');
result.innerHTML = unique1 + unique2 + unique3 + unique4 + unique5 + unique6 + unique7 + unique8;
link = document.getElementById('link').value.replace(/[\"]/g, "\\\"") + "\\n" + "<br/>";
age = document.getElementById('age').value.replace(/[\"]/g, "\\\"") + "\\n" + "<br/>";
appropriate = document.getElementById('appropriate').value.replace(/[\"]/g, "\\\"") + "\\n" + "<br/>";
patience = document.getElementById('patience').value.replace(/[\"]/g, "\\\"") + "\\n" + "<br/><br/>";
whatIsSDS = document.getElementById('whatIsSDS').value.replace(/[\"]/g, "\\\"") + "\\n";
selected = " " + document.getElementById('selected').value.replace(/[\"]/g, "\\\"") + " <a href=\"https://scratch.mit.edu/projects/55738732/\">" + "https://scratch.mit.edu/projects/55738732/" + "</a>" + "\\n";
ask = document.getElementById('ask').value.replace(/[\"]/g, "\\\"") + "\\n" + "<br/><br/>";
idea = document.getElementById('idea').value.replace(/[\"]/g, "\\\"") + " <a href=\"https://scratch.mit.edu/studios/93627/\">" + "https://scratch.mit.edu/studios/93627/" + "</a>" + "\\n" + "<br/><br/>";
wiki = document.getElementById('wiki').value.replace(/[\"]/g, "\\\"") + " <a href=\"http://wiki.scratch.mit.edu/wiki/SDS/\">" + "http://wiki.scratch.mit.edu/wiki/SDS/" + "</a>" + "\\n" + "<br/><br/>";
account = document.getElementById('account').value.replace(/[\"]/g, "\\\"") + " <a href=\"https://scratch.mit.edu/users/SDS-Updates/\">" + "@SDS-Updates" + "</a>" + "\\n" + "<br/><br/>";
thumbnail = document.getElementById('thumbnail').value.replace(/[\"]/g, "\\\"");
result2 = document.getElementById('result2');
result2.innerHTML = link + age + appropriate + patience + whatIsSDS + selected + ask + idea + wiki + account + thumbnail;
};
|
New lines
|
formatter.js
|
New lines
|
<ide><path>ormatter.js
<ide> var link, age, appropriate, patience, whatIsSDS, result;
<ide> document.onkeyup = function(){
<del> unique1 = document.getElementById('unique1').value.replace(/[\"]/g, "\\\"") + "<br/><br/>";
<add> unique1 = document.getElementById('unique1').value.replace(/[\"]/g, "\\\"") + "\\n" + "<br/><br/>";
<ide> unique2 = document.getElementById('unique2').value.replace(/[\"]/g, "\\\"") + "<br/>";
<ide> unique3 = document.getElementById('unique3').value.replace(/[\"]/g, "\\\"") + "<br/>";
<ide> unique4 = document.getElementById('unique4').value.replace(/[\"]/g, "\\\"") + "<br/>";
<ide> unique5 = document.getElementById('unique5').value.replace(/[\"]/g, "\\\"") + "<br/>";
<ide> unique6 = document.getElementById('unique6').value.replace(/[\"]/g, "\\\"") + "<br/>";
<del> unique7 = document.getElementById('unique7').value.replace(/[\"]/g, "\\\"") + "<br/><br/>";
<del> unique8 = document.getElementById('unique8').value.replace(/[\"]/g, "\\\"") + "<br/><br/>";
<add> unique7 = document.getElementById('unique7').value.replace(/[\"]/g, "\\\"") + "\\n" + "<br/><br/>";
<add> unique8 = document.getElementById('unique8').value.replace(/[\"]/g, "\\\"") + "\\n" +"<br/><br/>";
<ide> result = document.getElementById('result');
<ide> result.innerHTML = unique1 + unique2 + unique3 + unique4 + unique5 + unique6 + unique7 + unique8;
<ide>
|
|
Java
|
lgpl-2.1
|
73f24dc5d1e04aabbd12e04f0304dd08f565234a
| 0 |
CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine
|
/*
* jETeL/Clover - Java based ETL application framework.
* Copyright (C) 2005-06 Javlin Consulting <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jetel.connection.jdbc;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jetel.data.Defaults;
import org.jetel.util.primitive.DuplicateKeyMap;
import org.jetel.util.string.StringUtils;
/**
* This class can be used for analyzing sql queries which contain mapping between clover and db fields.
* Example queries:<br>
* insert into mytable [(f1,f2,...,fn)] values (val1, $field2, ...,$fieldm ) returning $key := dbfield1, $field := dbfield2;<br>
* delete from mytable where f1 = $field1 and ... fn = $fieldn; <br>
* update mytable set f1 = $field1,...,fn=$fieldn
*
*
* @author avackova ([email protected]) ;
* (c) JavlinConsulting s.r.o.
* www.javlinconsulting.cz
*
* @since Oct 11, 2007
*
*/
public class QueryAnalyzer {
private final static Pattern CLOVER_DB_MAPPING_PATTERN = Pattern.compile(
"(\\$([\\w\\?]+)\\s*" + Defaults.ASSIGN_SIGN + "\\s*)([\\w.]+)");//$cloverField:=dbfield
private final static Pattern DB_CLOVER_MAPPING_PATTERN = Pattern.compile("(([\\w]+)\\s*=)\\s*[\\?\\$](\\w*)");//dbField = $cloverField or dbField = ?
private final static Pattern FIELDS_PATTERN = Pattern.compile("\\$?([\\w.]+)|\\?");//[$]field or ?
private final static Pattern CLOVER_FIELDS_PATTERN = Pattern.compile(Defaults.CLOVER_FIELD_REGEX);//$cloverField
private final static Pattern DB_FIELDS_PATTERN = Pattern.compile("\\w+");//dbField
private final static Pattern FIELDS_LIST_PATTERN = Pattern.compile("\\((\\s*\\$?\\w+|\\?)[\\.,\\s\\$\\w\\?]*\\)");//(dbfield1,dbField2,..) or (smth, $field1, ...)
private String query;
private String source;
private HashMap<String, String> cloverDbFieldMap = new LinkedHashMap<String, String>();
private DuplicateKeyMap dbCloverFieldMap = new DuplicateKeyMap(new LinkedHashMap<String, String>());
public final static String RETURNING_KEY_WORD = "returning";
/**
* Empty constructor. Must be called setQuery(String) then
*/
public QueryAnalyzer(){
}
/**
* Constructor
*
* @param query to analyze with db - clover mapping
*
*/
public QueryAnalyzer(String query){
source = query;
this.query = query.trim();
}
/**
* Sets new query for analyze. Old results are forgotten.
*
* @param query
*/
public void setQuery(String query){
source = query;
this.query = query.trim();
cloverDbFieldMap.clear();
dbCloverFieldMap.clear();
}
/**
* Analyze select/update/delete query
*
* @return query in form consumable for PreparedStatement object
*/
public String getNotInsertQuery() {
//find $field:=dbfield mapping
Matcher mappingMatcher = CLOVER_DB_MAPPING_PATTERN.matcher(query);
StringBuffer sb = new StringBuffer();
while(mappingMatcher.find()){
cloverDbFieldMap.put(mappingMatcher.group(2), mappingMatcher.group(3));
mappingMatcher.appendReplacement(sb, mappingMatcher.group(3));
}
mappingMatcher.appendTail(sb);
//find dbField = $field or dbField = ? mapping
mappingMatcher = DB_CLOVER_MAPPING_PATTERN.matcher(sb.toString());
sb.setLength(0);
while(mappingMatcher.find()){
if (!StringUtils.isEmpty(mappingMatcher.group(3))) {//found dbField = $field
dbCloverFieldMap.put(mappingMatcher.group(2), mappingMatcher.group(3));
}else{//found dbField = ?
dbCloverFieldMap.put(mappingMatcher.group(2), null);
}
//replace whole mapping by dbField = ?
mappingMatcher.appendReplacement(sb, mappingMatcher.group(1) + "?");
}
mappingMatcher.appendTail(sb);
return sb.toString();
}
/**
* Analyze insert query
*
* @return query in form consumable for PreparedStatement object
*/
public String getInsertQuery() throws SQLException{
List<String> dbFields = new ArrayList<String>();
//find (smth,smth, ..., smth) in query: insert into mytable [(dbfield1, .., dbfieldN)] values ($f1,...,$fn)
Matcher fieldsListMatcher = FIELDS_LIST_PATTERN.matcher(query);
Matcher cloverFieldsMatcher = null;
if (fieldsListMatcher.find()) {
String fieldsList = fieldsListMatcher.group();
if (fieldsListMatcher.find()) {//list found 2x: first - db fields, second - clover fields
Matcher dbFieldsMatcher = DB_FIELDS_PATTERN.matcher(fieldsList);
//get db fields
while (dbFieldsMatcher.find()) {
dbFields.add(dbFieldsMatcher.group());
}
cloverFieldsMatcher = FIELDS_PATTERN.matcher(fieldsListMatcher.group());
}else{//list found once only
cloverFieldsMatcher = FIELDS_PATTERN.matcher(fieldsList);
}
}
//get clover fields
int index = 0;
int size = dbFields.size();
while(cloverFieldsMatcher.find()){
if (size > 0 && index >= size) {
throw new SQLException("Error in sql query: " + query);
}
if (cloverFieldsMatcher.group().startsWith(Defaults.CLOVER_FIELD_INDICATOR)) {
dbCloverFieldMap.put(size > 0 ? dbFields.get(index) : null, cloverFieldsMatcher.group(1));
}else if (index < size){
dbCloverFieldMap.put(dbFields.get(index), null);
}
index++;
}
//get autogenerated columns
int indexReturning = query.toLowerCase().indexOf(RETURNING_KEY_WORD);
if (indexReturning > -1) {
Matcher mappingMatcher = CLOVER_DB_MAPPING_PATTERN.matcher(query);
while(mappingMatcher.find()){
cloverDbFieldMap.put(mappingMatcher.group(2), mappingMatcher.group(3));
}
}
return indexReturning == -1 ?
CLOVER_FIELDS_PATTERN.matcher(query).replaceAll("?") :
CLOVER_FIELDS_PATTERN.matcher(query.subSequence(0, indexReturning)).replaceAll("?");
}
/**
* @return clover - db mapping
*/
public HashMap<String, String> getCloverDbFieldMap() {
return cloverDbFieldMap;
}
/**
* @return db - clover mapping (can have null as a key eg: Insert into abc values($f1, sysdate , $f2, $f3))
*/
public DuplicateKeyMap getDbCloverFieldMap() {
return dbCloverFieldMap;
}
/**
* @return query as has been set by user
*/
public String getSource(){
return source;
}
@Override
public String toString() {
return query != null ? query : source;
}
}
|
cloveretl.connection/src/org/jetel/connection/jdbc/QueryAnalyzer.java
|
/*
* jETeL/Clover - Java based ETL application framework.
* Copyright (C) 2005-06 Javlin Consulting <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jetel.connection.jdbc;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jetel.util.primitive.DuplicateKeyMap;
import org.jetel.util.string.StringUtils;
/**
* This class can be used for analyzing sql queries which contain mapping between clover and db fields.
* Example queries:<br>
* insert into mytable [(f1,f2,...,fn)] values (val1, $field2, ...,$fieldm ) returning $key := dbfield1, $field := dbfield2;<br>
* delete from mytable where f1 = $field1 and ... fn = $fieldn; <br>
* update mytable set f1 = $field1,...,fn=$fieldn
*
*
* @author avackova ([email protected]) ;
* (c) JavlinConsulting s.r.o.
* www.javlinconsulting.cz
*
* @since Oct 11, 2007
*
*/
public class QueryAnalyzer {
public final static String ASSIGN_SIGN = ":=";
public final static char CLOVER_FIELD_PREFIX_CHAR = '$';
public final static String CLOVER_FIELD_PREFIX = String.valueOf(CLOVER_FIELD_PREFIX_CHAR);
private final static Pattern CLOVER_DB_MAPPING_PATTERN = Pattern.compile("(\\$([\\w\\?]+)\\s*" + ASSIGN_SIGN + "\\s*)([\\w.]+)");//$cloverField:=dbfield
private final static Pattern DB_CLOVER_MAPPING_PATTERN = Pattern.compile("(([\\w]+)\\s*=)\\s*[\\?\\$](\\w*)");//dbField = $cloverField or dbField = ?
private final static Pattern FIELDS_PATTERN = Pattern.compile("\\$?([\\w.]+)|\\?");//[$]field or ?
private final static Pattern CLOVER_FIELDS_PATTERN = Pattern.compile("\\$\\w+");//$cloverField
private final static Pattern DB_FIELDS_PATTERN = Pattern.compile("\\w+");//dbField
private final static Pattern FIELDS_LIST_PATTERN = Pattern.compile("\\((\\s*\\$?\\w+|\\?)[\\.,\\s\\$\\w\\?]*\\)");//(dbfield1,dbField2,..) or (smth, $field1, ...)
private String query;
private String source;
private HashMap<String, String> cloverDbFieldMap = new LinkedHashMap<String, String>();
private DuplicateKeyMap dbCloverFieldMap = new DuplicateKeyMap(new LinkedHashMap<String, String>());
public final static String RETURNING_KEY_WORD = "returning";
/**
* Empty constructor. Must be called setQuery(String) then
*/
public QueryAnalyzer(){
}
/**
* Constructor
*
* @param query to analyze with db - clover mapping
*
*/
public QueryAnalyzer(String query){
source = query;
this.query = query.trim();
}
/**
* Sets new query for analyze. Old results are forgotten.
*
* @param query
*/
public void setQuery(String query){
source = query;
this.query = query.trim();
cloverDbFieldMap.clear();
dbCloverFieldMap.clear();
}
/**
* Analyze select/update/delete query
*
* @return query in form consumable for PreparedStatement object
*/
public String getNotInsertQuery() {
//find $field:=dbfield mapping
Matcher mappingMatcher = CLOVER_DB_MAPPING_PATTERN.matcher(query);
StringBuffer sb = new StringBuffer();
while(mappingMatcher.find()){
cloverDbFieldMap.put(mappingMatcher.group(2), mappingMatcher.group(3));
mappingMatcher.appendReplacement(sb, mappingMatcher.group(3));
}
mappingMatcher.appendTail(sb);
//find dbField = $field or dbField = ? mapping
mappingMatcher = DB_CLOVER_MAPPING_PATTERN.matcher(sb.toString());
sb.setLength(0);
while(mappingMatcher.find()){
if (!StringUtils.isEmpty(mappingMatcher.group(3))) {//found dbField = $field
dbCloverFieldMap.put(mappingMatcher.group(2), mappingMatcher.group(3));
}else{//found dbField = ?
dbCloverFieldMap.put(mappingMatcher.group(2), null);
}
//replace whole mapping by dbField = ?
mappingMatcher.appendReplacement(sb, mappingMatcher.group(1) + "?");
}
mappingMatcher.appendTail(sb);
return sb.toString();
}
/**
* Analyze insert query
*
* @return query in form consumable for PreparedStatement object
*/
public String getInsertQuery() throws SQLException{
List<String> dbFields = new ArrayList<String>();
//find (smth,smth, ..., smth) in query: insert into mytable [(dbfield1, .., dbfieldN)] values ($f1,...,$fn)
Matcher fieldsListMatcher = FIELDS_LIST_PATTERN.matcher(query);
Matcher cloverFieldsMatcher = null;
if (fieldsListMatcher.find()) {
String fieldsList = fieldsListMatcher.group();
if (fieldsListMatcher.find()) {//list found 2x: first - db fields, second - clover fields
Matcher dbFieldsMatcher = DB_FIELDS_PATTERN.matcher(fieldsList);
//get db fields
while (dbFieldsMatcher.find()) {
dbFields.add(dbFieldsMatcher.group());
}
cloverFieldsMatcher = FIELDS_PATTERN.matcher(fieldsListMatcher.group());
}else{//list found once only
cloverFieldsMatcher = FIELDS_PATTERN.matcher(fieldsList);
}
}
//get clover fields
int index = 0;
int size = dbFields.size();
while(cloverFieldsMatcher.find()){
if (size > 0 && index >= size) {
throw new SQLException("Error in sql query: " + query);
}
if (cloverFieldsMatcher.group().startsWith(CLOVER_FIELD_PREFIX)) {
dbCloverFieldMap.put(size > 0 ? dbFields.get(index) : null, cloverFieldsMatcher.group(1));
}else if (index < size){
dbCloverFieldMap.put(dbFields.get(index), null);
}
index++;
}
//get autogenerated columns
int indexReturning = query.toLowerCase().indexOf(RETURNING_KEY_WORD);
if (indexReturning > -1) {
Matcher mappingMatcher = CLOVER_DB_MAPPING_PATTERN.matcher(query);
while(mappingMatcher.find()){
cloverDbFieldMap.put(mappingMatcher.group(2), mappingMatcher.group(3));
}
}
return indexReturning == -1 ?
CLOVER_FIELDS_PATTERN.matcher(query).replaceAll("?") :
CLOVER_FIELDS_PATTERN.matcher(query.subSequence(0, indexReturning)).replaceAll("?");
}
/**
* @return clover - db mapping
*/
public HashMap<String, String> getCloverDbFieldMap() {
return cloverDbFieldMap;
}
/**
* @return db - clover mapping (can have null as a key eg: Insert into abc values($f1, sysdate , $f2, $f3))
*/
public DuplicateKeyMap getDbCloverFieldMap() {
return dbCloverFieldMap;
}
/**
* @return query as has been set by user
*/
public String getSource(){
return source;
}
@Override
public String toString() {
return query != null ? query : source;
}
}
|
UPDATE:standardization of mapping syntax
git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@4505 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
|
cloveretl.connection/src/org/jetel/connection/jdbc/QueryAnalyzer.java
|
UPDATE:standardization of mapping syntax
|
<ide><path>loveretl.connection/src/org/jetel/connection/jdbc/QueryAnalyzer.java
<ide> import java.util.regex.Matcher;
<ide> import java.util.regex.Pattern;
<ide>
<add>import org.jetel.data.Defaults;
<ide> import org.jetel.util.primitive.DuplicateKeyMap;
<ide> import org.jetel.util.string.StringUtils;
<ide>
<ide> */
<ide> public class QueryAnalyzer {
<ide>
<del> public final static String ASSIGN_SIGN = ":=";
<del> public final static char CLOVER_FIELD_PREFIX_CHAR = '$';
<del> public final static String CLOVER_FIELD_PREFIX = String.valueOf(CLOVER_FIELD_PREFIX_CHAR);
<del>
<del> private final static Pattern CLOVER_DB_MAPPING_PATTERN = Pattern.compile("(\\$([\\w\\?]+)\\s*" + ASSIGN_SIGN + "\\s*)([\\w.]+)");//$cloverField:=dbfield
<add> private final static Pattern CLOVER_DB_MAPPING_PATTERN = Pattern.compile(
<add> "(\\$([\\w\\?]+)\\s*" + Defaults.ASSIGN_SIGN + "\\s*)([\\w.]+)");//$cloverField:=dbfield
<ide> private final static Pattern DB_CLOVER_MAPPING_PATTERN = Pattern.compile("(([\\w]+)\\s*=)\\s*[\\?\\$](\\w*)");//dbField = $cloverField or dbField = ?
<ide> private final static Pattern FIELDS_PATTERN = Pattern.compile("\\$?([\\w.]+)|\\?");//[$]field or ?
<del> private final static Pattern CLOVER_FIELDS_PATTERN = Pattern.compile("\\$\\w+");//$cloverField
<add> private final static Pattern CLOVER_FIELDS_PATTERN = Pattern.compile(Defaults.CLOVER_FIELD_REGEX);//$cloverField
<ide> private final static Pattern DB_FIELDS_PATTERN = Pattern.compile("\\w+");//dbField
<ide> private final static Pattern FIELDS_LIST_PATTERN = Pattern.compile("\\((\\s*\\$?\\w+|\\?)[\\.,\\s\\$\\w\\?]*\\)");//(dbfield1,dbField2,..) or (smth, $field1, ...)
<ide>
<ide> if (size > 0 && index >= size) {
<ide> throw new SQLException("Error in sql query: " + query);
<ide> }
<del> if (cloverFieldsMatcher.group().startsWith(CLOVER_FIELD_PREFIX)) {
<add> if (cloverFieldsMatcher.group().startsWith(Defaults.CLOVER_FIELD_INDICATOR)) {
<ide> dbCloverFieldMap.put(size > 0 ? dbFields.get(index) : null, cloverFieldsMatcher.group(1));
<ide> }else if (index < size){
<ide> dbCloverFieldMap.put(dbFields.get(index), null);
|
|
JavaScript
|
cc0-1.0
|
0c95d11d512cbafcdc7b119f77caa5cd713404ae
| 0 |
lepieru/myconfig,lepieru/myconfig,lepieru/myconfig
|
//////// KeySnail Init File
// Put all your code except special key, set*key, hook, blacklist.
// {{%PRESERVE%
// }}%PRESERVE%
//// Special key settings
key.quitKey = "C-g"
key.helpKey = "<f1>"
key.escapeKey = "C-q"
key.macroStartKey = "<f3>"
key.macroEndKey = "<f4>"
key.suspendKey = "<f2>"
key.universalArgumentKey = "C-u"
key.negativeArgument1Key = "C--"
key.negativeArgument2Key = "C-M--"
key.negativeArgument3Key = "M--"
//// Hooks
hook.addToHook("KeyBoardQuit", function (event) {
if (key.currentKeySequence.length) return
command.closeFindBar()
let marked = command.marked(event)
if (util.isCaretEnabled()) {
if (marked) {
command.resetMark(event)
} else {
if ("blur" in event.target) event.target.blur()
gBrowser.focus()
_content.focus()
}
} else {
goDoCommand("cmd_selectNone")
}
if (KeySnail.windowType === "navigator:browser" && !marked) {
key.generateKey(event.originalTarget, KeyEvent.DOM_VK_ESCAPE, true)
}
})
//// Key bindings
key.setGlobalKey("C-M-r", (event) => {
userscript.reload()
}, "Reload the initialization file", true)
key.setGlobalKey("M-x", (event, arg) => {
ext.select(arg, event)
}, "List exts and execute selected one", true)
key.setGlobalKey("M-:", (event) => {
command.interpreter()
}, "Command interpreter", true)
key.setGlobalKey(["<f1>", "b"], (event) => {
key.listKeyBindings()
}, "List all keybindings", false)
key.setGlobalKey("C-m", (event) => {
key.generateKey(event.originalTarget, KeyEvent.DOM_VK_RETURN, true)
}, "Generate the return key code", false)
key.setGlobalKey(["<f1>", "F"], (event) => {
openHelpLink("firefox-help")
}, "Display Firefox help", false)
key.setGlobalKey(["C-x", "l"], (event) => {
command.focusToById("urlbar")
}, "Focus to the location bar", true)
key.setGlobalKey(["C-x", "g"], (event) => {
command.focusToById("searchbar")
}, "Focus to the search bar", true)
key.setGlobalKey(["C-x", "t"], (event) => {
command.focusElement(command.elementsRetrieverTextarea, 0)
}, "Focus to the first textarea", true)
key.setGlobalKey(["C-x", "s"], (event) => {
command.focusElement(command.elementsRetrieverButton, 0)
}, "Focus to the first button", true)
key.setGlobalKey("M-w", (event) => {
command.copyRegion(event)
}, "Copy selected text", true)
key.setGlobalKey("C-s", (event) => {
command.iSearchForwardKs(event)
}, "Emacs like incremental search forward", true)
key.setGlobalKey("C-r", (event) => {
command.iSearchBackwardKs(event)
}, "Emacs like incremental search backward", true)
key.setGlobalKey(["C-x", "k"], (event) => {
BrowserCloseTabOrWindow()
}, "Close tab / window", false)
key.setGlobalKey(["C-x", "K"], (event) => {
closeWindow(true)
}, "Close the window", false)
key.setGlobalKey(["C-c", "u"], (event) => {
undoCloseTab()
}, "Undo closed tab", false)
key.setGlobalKey(["C-x", "n"], (event) => {
OpenBrowserWindow()
}, "Open new window", false)
key.setGlobalKey("C-M-l", (event) => {
getBrowser().mTabContainer.advanceSelectedTab(1, true)
}, "Select next tab", false)
key.setGlobalKey("C-M-h", (event) => {
getBrowser().mTabContainer.advanceSelectedTab(-1, true)
}, "Select previous tab", false)
key.setGlobalKey(["C-x", "C-c"], (event) => {
goQuitApplication()
}, "Exit Firefox", true)
key.setGlobalKey(["C-x", "o"], (event, arg) => {
command.focusOtherFrame(arg)
}, "Select next frame", false)
key.setGlobalKey(["C-x", "1"], (event) => {
window.loadURI(event.target.ownerDocument.location.href)
}, "Show current frame only", true)
key.setGlobalKey(["C-x", "C-f"], (event) => {
BrowserOpenFileWindow()
}, "Open the local file", true)
key.setGlobalKey(["C-x", "C-s"], (event) => {
saveDocument(window.content.document)
}, "Save current page to the file", true)
key.setGlobalKey(["C-c", "C-c", "C-v"], (event) => {
toJavaScriptConsole()
}, "Display JavaScript console", true)
key.setGlobalKey(["C-c", "C-c", "C-c"], (event) => {
command.clearConsole()
}, "Clear Javascript console", true)
key.setEditKey(["C-x", "h"], (event) => {
command.selectAll(event)
}, "Select whole text", true)
key.setEditKey([["C-SPC"], ["C-@"]], (event) => {
command.setMark(event)
}, "Set the mark", true)
key.setEditKey("C-o", (event) => {
command.openLine(event)
}, "Open line", false)
key.setEditKey([["C-x", "u"], ["C-_"]], (event) => {
display.echoStatusBar("Undo!", 2000)
goDoCommand("cmd_undo")
}, "Undo", false)
key.setEditKey("C-\\", (event) => {
display.echoStatusBar("Redo!", 2000)
goDoCommand("cmd_redo")
}, "Redo", false)
key.setEditKey("C-a", (event) => {
command.beginLine(event)
}, "Beginning of the line", false)
key.setEditKey("C-e", (event) => {
command.endLine(event)
}, "End of the line", false)
key.setEditKey("C-f", (event) => {
command.nextChar(event)
}, "Forward char", false)
key.setEditKey("C-b", (event) => {
command.previousChar(event)
}, "Backward char", false)
key.setEditKey("M-f", (event) => {
command.forwardWord(event)
}, "Next word", false)
key.setEditKey("M-b", (event) => {
command.backwardWord(event)
}, "Previous word", false)
key.setEditKey("C-n", (event) => {
command.nextLine(event)
}, "Next line", false)
key.setEditKey("C-p", (event) => {
command.previousLine(event)
}, "Previous line", false)
key.setEditKey("C-v", (event) => {
command.pageDown(event)
}, "Page down", false)
key.setEditKey("M-v", (event) => {
command.pageUp(event)
}, "Page up", false)
key.setEditKey("M-<", (event) => {
command.moveTop(event)
}, "Beginning of the text area", false)
key.setEditKey("M->", (event) => {
command.moveBottom(event)
}, "End of the text area", false)
key.setEditKey("C-d", (event) => {
goDoCommand("cmd_deleteCharForward")
}, "Delete forward char", false)
key.setEditKey("C-h", (event) => {
goDoCommand("cmd_deleteCharBackward")
}, "Delete backward char", false)
key.setEditKey("M-d", (event) => {
command.deleteForwardWord(event)
}, "Delete forward word", false)
key.setEditKey([["C-<backspace>"], ["M-<delete>"]], (event) => {
command.deleteBackwardWord(event)
}, "Delete backward word", false)
key.setEditKey("M-u", (event, arg) => {
command.wordCommand(event, arg, command.upcaseForwardWord, command.upcaseBackwardWord)
}, "Convert following word to upper case", false)
key.setEditKey("M-l", (event, arg) => {
command.wordCommand(event, arg, command.downcaseForwardWord, command.downcaseBackwardWord)
}, "Convert following word to lower case", false)
key.setEditKey("M-c", (event, arg) => {
command.wordCommand(event, arg, command.capitalizeForwardWord, command.capitalizeBackwardWord)
}, "Capitalize the following word", false)
key.setEditKey("C-k", (event) => {
command.killLine(event)
}, "Kill the rest of the line", false)
key.setEditKey("C-y", (event) => {
command.yank()
}, "Paste (Yank)", false)
key.setEditKey("M-y", (event) => {
command.yankPop()
}, "Paste pop (Yank pop)", true)
key.setEditKey("C-M-y", (event) => {
if (!command.kill.ring.length) return
let (ct = command.getClipboardText())
(!command.kill.ring.length || ct != command.kill.ring[0]) && command.pushKillRing(ct)
prompt.selector({
message: "Paste:",
collection: command.kill.ring,
callback: (i) => {
if (i >= 0) key.insertText(command.kill.ring[i])
}
})
}, "Show kill-ring and select text to paste", true)
key.setEditKey("C-w", (event) => {
goDoCommand("cmd_copy")
goDoCommand("cmd_delete")
command.resetMark(event)
}, "Cut current region", true)
key.setEditKey(["C-x", "r", "d"], (event, arg) => {
command.replaceRectangle(event.originalTarget, "", false, !arg)
}, "Delete text in the region-rectangle", true)
key.setEditKey(["C-x", "r", "t"], (event) => {
prompt.read("String rectangle: ", (string, input) => {
command.replaceRectangle(input, string)
}, event.originalTarget)
}, "Replace text in the region-rectangle with user inputted string", true)
key.setEditKey(["C-x", "r", "o"], (event) => {
command.openRectangle(event.originalTarget)
}, "Blank out the region-rectangle, shifting text right", true)
key.setEditKey(["C-x", "r", "k"], (event, arg) => {
command.kill.buffer = command.killRectangle(event.originalTarget, !arg)
}, "Delete the region-rectangle and save it as the last killed one", true)
key.setEditKey(["C-x", "r", "y"], (event) => {
command.yankRectangle(event.originalTarget, command.kill.buffer)
}, "Yank the last killed rectangle with upper left corner at point", true)
key.setEditKey("M-n", (event) => {
command.walkInputElement(command.elementsRetrieverTextarea, true, true)
}, "Focus to the next text area", false)
key.setEditKey("M-p", (event) => {
command.walkInputElement(command.elementsRetrieverTextarea, false, true)
}, "Focus to the previous text area", false)
key.setViewKey([["C-n"], ["j"]], (event) => {
key.generateKey(event.originalTarget, KeyEvent.DOM_VK_DOWN, true)
}, "Scroll line down", false)
key.setViewKey([["C-p"], ["k"]], (event) => {
key.generateKey(event.originalTarget, KeyEvent.DOM_VK_UP, true)
}, "Scroll line up", false)
key.setViewKey([["C-f"], ["."]], (event) => {
key.generateKey(event.originalTarget, KeyEvent.DOM_VK_RIGHT, true)
}, "Scroll right", false)
key.setViewKey([["C-b"], [","]], (event) => {
key.generateKey(event.originalTarget, KeyEvent.DOM_VK_LEFT, true)
}, "Scroll left", false)
key.setViewKey([["M-v"], ["b"]], (event) => {
goDoCommand("cmd_scrollPageUp")
}, "Scroll page up", false)
key.setViewKey("C-v", (event) => {
goDoCommand("cmd_scrollPageDown")
}, "Scroll page down", false)
key.setViewKey([["M-<"], ["g"]], (event) => {
goDoCommand("cmd_scrollTop")
}, "Scroll to the top of the page", true)
key.setViewKey([["M->"], ["G"]], (event) => {
goDoCommand("cmd_scrollBottom")
}, "Scroll to the bottom of the page", true)
key.setViewKey("l", (event) => {
getBrowser().mTabContainer.advanceSelectedTab(1, true)
}, "Select next tab", false)
key.setViewKey("h", (event) => {
getBrowser().mTabContainer.advanceSelectedTab(-1, true)
}, "Select previous tab", false)
key.setViewKey(":", (event, arg) => {
shell.input(null, arg)
}, "List and execute commands", true)
key.setViewKey("R", (event) => {
BrowserReload()
}, "Reload the page", true)
key.setViewKey("B", (event) => {
BrowserBack()
}, "Back", false)
key.setViewKey("F", (event) => {
BrowserForward()
}, "Forward", false)
key.setViewKey(["C-x", "h"], (event) => {
goDoCommand("cmd_selectAll")
}, "Select all", true)
key.setViewKey("f", (event) => {
command.focusElement(command.elementsRetrieverTextarea, 0)
}, "Focus to the first textarea", true)
key.setViewKey("M-p", (event) => {
command.walkInputElement(command.elementsRetrieverButton, true, true)
}, "Focus to the next button", false)
key.setViewKey("M-n", (event) => {
command.walkInputElement(command.elementsRetrieverButton, false, true)
}, "Focus to the previous button", false)
key.setCaretKey([["C-a"], ["^"]], (event) => {
event.target.ksMarked ? goDoCommand("cmd_selectBeginLine") : goDoCommand("cmd_beginLine")
}, "Move caret to the beginning of the line", false)
key.setCaretKey([["C-e"], ["$"]], (event) => {
event.target.ksMarked ? goDoCommand("cmd_selectEndLine") : goDoCommand("cmd_endLine")
}, "Move caret to the end of the line", false)
key.setCaretKey([["C-n"], ["j"]], (event) => {
event.target.ksMarked ? goDoCommand("cmd_selectLineNext") : goDoCommand("cmd_scrollLineDown")
}, "Move caret to the next line", false)
key.setCaretKey([["C-p"], ["k"]], (event) => {
event.target.ksMarked ? goDoCommand("cmd_selectLinePrevious") : goDoCommand("cmd_scrollLineUp")
}, "Move caret to the previous line", false)
key.setCaretKey([["C-f"], ["l"]], (event) => {
event.target.ksMarked ? goDoCommand("cmd_selectCharNext") : goDoCommand("cmd_scrollRight")
}, "Move caret to the right", false)
key.setCaretKey([["C-b"], ["h"], ["C-h"]], (event) => {
event.target.ksMarked ? goDoCommand("cmd_selectCharPrevious") : goDoCommand("cmd_scrollLeft")
}, "Move caret to the left", false)
key.setCaretKey([["M-f"], ["w"]], (event) => {
event.target.ksMarked ? goDoCommand("cmd_selectWordNext") : goDoCommand("cmd_wordNext")
}, "Move caret to the right by word", false)
key.setCaretKey([["M-b"], ["W"]], (event) => {
event.target.ksMarked ? goDoCommand("cmd_selectWordPrevious") : goDoCommand("cmd_wordPrevious")
}, "Move caret to the left by word", false)
key.setCaretKey([["C-v"], ["SPC"]], (event) => {
event.target.ksMarked ? goDoCommand("cmd_selectPageNext") : goDoCommand("cmd_movePageDown")
}, "Move caret down by page", false)
key.setCaretKey([["M-v"], ["b"]], (event) => {
event.target.ksMarked ? goDoCommand("cmd_selectPagePrevious") : goDoCommand("cmd_movePageUp")
}, "Move caret up by page", false)
key.setCaretKey([["M-<"], ["g"]], (event) => {
event.target.ksMarked ? goDoCommand("cmd_selectTop") : goDoCommand("cmd_scrollTop")
}, "Move caret to the top of the page", false)
key.setCaretKey([["M->"], ["G"]], (event) => {
event.target.ksMarked ? goDoCommand("cmd_selectEndLine") : goDoCommand("cmd_endLine")
}, "Move caret to the end of the line", false)
key.setCaretKey("J", (event) => {
util.getSelectionController().scrollLine(true)
}, "Scroll line down", false)
key.setCaretKey("K", (event) => {
util.getSelectionController().scrollLine(false)
}, "Scroll line up", false)
key.setCaretKey(",", (event) => {
util.getSelectionController().scrollHorizontal(true)
goDoCommand("cmd_scrollLeft")
}, "Scroll left", false)
key.setCaretKey(".", (event) => {
goDoCommand("cmd_scrollRight")
util.getSelectionController().scrollHorizontal(false)
}, "Scroll right", false)
key.setCaretKey("z", (event) => {
command.recenter(event)
}, "Scroll to the cursor position", false)
key.setCaretKey([["C-SPC"], ["C-@"]], (event) => {
command.setMark(event)
}, "Set the mark", true)
key.setCaretKey(":", (event, arg) => {
shell.input(null, arg)
}, "List and execute commands", true)
key.setCaretKey("R", (event) => {
BrowserReload()
}, "Reload the page", true)
key.setCaretKey("B", (event) => {
BrowserBack()
}, "Back", false)
key.setCaretKey("F", (event) => {
BrowserForward()
}, "Forward", false)
key.setCaretKey(["C-x", "h"], (event) => {
goDoCommand("cmd_selectAll")
}, "Select all", true)
key.setCaretKey("f", (event) => {
command.focusElement(command.elementsRetrieverTextarea, 0)
}, "Focus to the first textarea", true)
key.setCaretKey("M-p", (event) => {
command.walkInputElement(command.elementsRetrieverButton, true, true)
}, "Focus to the next button", false)
key.setCaretKey("M-n", (event) => {
command.walkInputElement(command.elementsRetrieverButton, false, true)
}, "Focus to the previous button", false)
|
keysnail/keysnail.js
|
//////// KeySnail Init File
// Put all your code except special key, set*key, hook, blacklist.
// {{%PRESERVE%
// }}%PRESERVE%
//// Special key settings
key.quitKey = "C-g"
key.helpKey = "<f1>"
key.escapeKey = "C-q"
key.macroStartKey = "<f3>"
key.macroEndKey = "<f4>"
key.suspendKey = "<f2>"
key.universalArgumentKey = "C-u"
key.negativeArgument1Key = "C--"
key.negativeArgument2Key = "C-M--"
key.negativeArgument3Key = "M--"
//// Hooks
hook.addToHook('KeyBoardQuit', function (aEvent) {
if (key.currentKeySequence.length) return
command.closeFindBar()
let marked = command.marked(aEvent)
if (util.isCaretEnabled()) {
if (marked) {
command.resetMark(aEvent)
} else {
if ("blur" in aEvent.target) aEvent.target.blur()
gBrowser.focus()
_content.focus()
}
} else {
goDoCommand("cmd_selectNone")
}
if (KeySnail.windowType === "navigator:browser" && !marked) {
key.generateKey(aEvent.originalTarget, KeyEvent.DOM_VK_ESCAPE, true)
}
})
//// Key bindings
key.setGlobalKey('C-M-r', function (ev) {
userscript.reload()
}, 'Reload the initialization file', true)
key.setGlobalKey('M-x', function (ev, arg) {
ext.select(arg, ev)
}, 'List exts and execute selected one', true)
key.setGlobalKey('M-:', function (ev) {
command.interpreter()
}, 'Command interpreter', true)
key.setGlobalKey(["<f1>", "b"], function (ev) {
key.listKeyBindings()
}, 'List all keybindings', false)
key.setGlobalKey('C-m', function (ev) {
key.generateKey(ev.originalTarget, KeyEvent.DOM_VK_RETURN, true)
}, 'Generate the return key code', false)
key.setGlobalKey(["<f1>", "F"], function (ev) {
openHelpLink("firefox-help")
}, 'Display Firefox help', false)
key.setGlobalKey(["C-x", "l"], function (ev) {
command.focusToById("urlbar")
}, 'Focus to the location bar', true)
key.setGlobalKey(["C-x", "g"], function (ev) {
command.focusToById("searchbar")
}, 'Focus to the search bar', true)
key.setGlobalKey(["C-x", "t"], function (ev) {
command.focusElement(command.elementsRetrieverTextarea, 0)
}, 'Focus to the first textarea', true)
key.setGlobalKey(["C-x", "s"], function (ev) {
command.focusElement(command.elementsRetrieverButton, 0)
}, 'Focus to the first button', true)
key.setGlobalKey('M-w', function (ev) {
command.copyRegion(ev)
}, 'Copy selected text', true)
key.setGlobalKey('C-s', function (ev) {
command.iSearchForwardKs(ev)
}, 'Emacs like incremental search forward', true)
key.setGlobalKey('C-r', function (ev) {
command.iSearchBackwardKs(ev)
}, 'Emacs like incremental search backward', true)
key.setGlobalKey(["C-x", "k"], function (ev) {
BrowserCloseTabOrWindow()
}, 'Close tab / window', false)
key.setGlobalKey(["C-x", "K"], function (ev) {
closeWindow(true)
}, 'Close the window', false)
key.setGlobalKey(["C-c", "u"], function (ev) {
undoCloseTab()
}, 'Undo closed tab', false)
key.setGlobalKey(["C-x", "n"], function (ev) {
OpenBrowserWindow()
}, 'Open new window', false)
key.setGlobalKey('C-M-l', function (ev) {
getBrowser().mTabContainer.advanceSelectedTab(1, true)
}, 'Select next tab', false)
key.setGlobalKey('C-M-h', function (ev) {
getBrowser().mTabContainer.advanceSelectedTab(-1, true)
}, 'Select previous tab', false)
key.setGlobalKey(["C-x", "C-c"], function (ev) {
goQuitApplication()
}, 'Exit Firefox', true)
key.setGlobalKey(["C-x", "o"], function (ev, arg) {
command.focusOtherFrame(arg)
}, 'Select next frame', false)
key.setGlobalKey(["C-x", "1"], function (ev) {
window.loadURI(ev.target.ownerDocument.location.href)
}, 'Show current frame only', true)
key.setGlobalKey(["C-x", "C-f"], function (ev) {
BrowserOpenFileWindow()
}, 'Open the local file', true)
key.setGlobalKey(["C-x", "C-s"], function (ev) {
saveDocument(window.content.document)
}, 'Save current page to the file', true)
key.setGlobalKey(["C-c", "C-c", "C-v"], function (ev) {
toJavaScriptConsole()
}, 'Display JavaScript console', true)
key.setGlobalKey(["C-c", "C-c", "C-c"], function (ev) {
command.clearConsole()
}, 'Clear Javascript console', true)
key.setEditKey(["C-x", "h"], function (ev) {
command.selectAll(ev)
}, 'Select whole text', true)
key.setEditKey([["C-SPC"], ["C-@"]], function (ev) {
command.setMark(ev)
}, 'Set the mark', true)
key.setEditKey('C-o', function (ev) {
command.openLine(ev)
}, 'Open line', false)
key.setEditKey([["C-x", "u"], ["C-_"]], function (ev) {
display.echoStatusBar("Undo!", 2000)
goDoCommand("cmd_undo")
}, 'Undo', false)
key.setEditKey('C-\\', function (ev) {
display.echoStatusBar("Redo!", 2000)
goDoCommand("cmd_redo")
}, 'Redo', false)
key.setEditKey('C-a', function (ev) {
command.beginLine(ev)
}, 'Beginning of the line', false)
key.setEditKey('C-e', function (ev) {
command.endLine(ev)
}, 'End of the line', false)
key.setEditKey('C-f', function (ev) {
command.nextChar(ev)
}, 'Forward char', false)
key.setEditKey('C-b', function (ev) {
command.previousChar(ev)
}, 'Backward char', false)
key.setEditKey('M-f', function (ev) {
command.forwardWord(ev)
}, 'Next word', false)
key.setEditKey('M-b', function (ev) {
command.backwardWord(ev)
}, 'Previous word', false)
key.setEditKey('C-n', function (ev) {
command.nextLine(ev)
}, 'Next line', false)
key.setEditKey('C-p', function (ev) {
command.previousLine(ev)
}, 'Previous line', false)
key.setEditKey('C-v', function (ev) {
command.pageDown(ev)
}, 'Page down', false)
key.setEditKey('M-v', function (ev) {
command.pageUp(ev)
}, 'Page up', false)
key.setEditKey('M-<', function (ev) {
command.moveTop(ev)
}, 'Beginning of the text area', false)
key.setEditKey('M->', function (ev) {
command.moveBottom(ev)
}, 'End of the text area', false)
key.setEditKey('C-d', function (ev) {
goDoCommand("cmd_deleteCharForward")
}, 'Delete forward char', false)
key.setEditKey('C-h', function (ev) {
goDoCommand("cmd_deleteCharBackward")
}, 'Delete backward char', false)
key.setEditKey('M-d', function (ev) {
command.deleteForwardWord(ev)
}, 'Delete forward word', false)
key.setEditKey([["C-<backspace>"], ["M-<delete>"]], function (ev) {
command.deleteBackwardWord(ev)
}, 'Delete backward word', false)
key.setEditKey('M-u', function (ev, arg) {
command.wordCommand(ev, arg, command.upcaseForwardWord, command.upcaseBackwardWord)
}, 'Convert following word to upper case', false)
key.setEditKey('M-l', function (ev, arg) {
command.wordCommand(ev, arg, command.downcaseForwardWord, command.downcaseBackwardWord)
}, 'Convert following word to lower case', false)
key.setEditKey('M-c', function (ev, arg) {
command.wordCommand(ev, arg, command.capitalizeForwardWord, command.capitalizeBackwardWord)
}, 'Capitalize the following word', false)
key.setEditKey('C-k', function (ev) {
command.killLine(ev)
}, 'Kill the rest of the line', false)
key.setEditKey('C-y', command.yank, 'Paste (Yank)', false)
key.setEditKey('M-y', command.yankPop, 'Paste pop (Yank pop)', true)
key.setEditKey('C-M-y', function (ev) {
if (!command.kill.ring.length)
return
let (ct = command.getClipboardText())
(!command.kill.ring.length || ct != command.kill.ring[0]) && command.pushKillRing(ct)
prompt.selector(
{
message: "Paste:",
collection: command.kill.ring,
callback: function (i) { if (i >= 0) key.insertText(command.kill.ring[i]) }
}
)
}, 'Show kill-ring and select text to paste', true)
key.setEditKey('C-w', function (ev) {
goDoCommand("cmd_copy")
goDoCommand("cmd_delete")
command.resetMark(ev)
}, 'Cut current region', true)
key.setEditKey(["C-x", "r", "d"], function (ev, arg) {
command.replaceRectangle(ev.originalTarget, "", false, !arg)
}, 'Delete text in the region-rectangle', true)
key.setEditKey(["C-x", "r", "t"], function (ev) {
prompt.read("String rectangle: ", function (aStr, aInput) {
command.replaceRectangle(aInput, aStr)
},
ev.originalTarget)
}, 'Replace text in the region-rectangle with user inputted string', true)
key.setEditKey(["C-x", "r", "o"], function (ev) {
command.openRectangle(ev.originalTarget)
}, 'Blank out the region-rectangle, shifting text right', true)
key.setEditKey(["C-x", "r", "k"], function (ev, arg) {
command.kill.buffer = command.killRectangle(ev.originalTarget, !arg)
}, 'Delete the region-rectangle and save it as the last killed one', true)
key.setEditKey(["C-x", "r", "y"], function (ev) {
command.yankRectangle(ev.originalTarget, command.kill.buffer)
}, 'Yank the last killed rectangle with upper left corner at point', true)
key.setEditKey('M-n', function (ev) {
command.walkInputElement(command.elementsRetrieverTextarea, true, true)
}, 'Focus to the next text area', false)
key.setEditKey('M-p', function (ev) {
command.walkInputElement(command.elementsRetrieverTextarea, false, true)
}, 'Focus to the previous text area', false)
key.setViewKey([["C-n"], ["j"]], function (ev) {
key.generateKey(ev.originalTarget, KeyEvent.DOM_VK_DOWN, true)
}, 'Scroll line down', false)
key.setViewKey([["C-p"], ["k"]], function (ev) {
key.generateKey(ev.originalTarget, KeyEvent.DOM_VK_UP, true)
}, 'Scroll line up', false)
key.setViewKey([["C-f"], ["."]], function (ev) {
key.generateKey(ev.originalTarget, KeyEvent.DOM_VK_RIGHT, true)
}, 'Scroll right', false)
key.setViewKey([["C-b"], [","]], function (ev) {
key.generateKey(ev.originalTarget, KeyEvent.DOM_VK_LEFT, true)
}, 'Scroll left', false)
key.setViewKey([["M-v"], ["b"]], function (ev) {
goDoCommand("cmd_scrollPageUp")
}, 'Scroll page up', false)
key.setViewKey('C-v', function (ev) {
goDoCommand("cmd_scrollPageDown")
}, 'Scroll page down', false)
key.setViewKey([["M-<"], ["g"]], function (ev) {
goDoCommand("cmd_scrollTop")
}, 'Scroll to the top of the page', true)
key.setViewKey([["M->"], ["G"]], function (ev) {
goDoCommand("cmd_scrollBottom")
}, 'Scroll to the bottom of the page', true)
key.setViewKey('l', function (ev) {
getBrowser().mTabContainer.advanceSelectedTab(1, true)
}, 'Select next tab', false)
key.setViewKey('h', function (ev) {
getBrowser().mTabContainer.advanceSelectedTab(-1, true)
}, 'Select previous tab', false)
key.setViewKey(':', function (ev, arg) {
shell.input(null, arg)
}, 'List and execute commands', true)
key.setViewKey('R', function (ev) {
BrowserReload()
}, 'Reload the page', true)
key.setViewKey('B', function (ev) {
BrowserBack()
}, 'Back', false)
key.setViewKey('F', function (ev) {
BrowserForward()
}, 'Forward', false)
key.setViewKey(["C-x", "h"], function (ev) {
goDoCommand("cmd_selectAll")
}, 'Select all', true)
key.setViewKey('f', function (ev) {
command.focusElement(command.elementsRetrieverTextarea, 0)
}, 'Focus to the first textarea', true)
key.setViewKey('M-p', function (ev) {
command.walkInputElement(command.elementsRetrieverButton, true, true)
}, 'Focus to the next button', false)
key.setViewKey('M-n', function (ev) {
command.walkInputElement(command.elementsRetrieverButton, false, true)
}, 'Focus to the previous button', false)
key.setCaretKey([["C-a"], ["^"]], function (ev) {
ev.target.ksMarked ? goDoCommand("cmd_selectBeginLine") : goDoCommand("cmd_beginLine")
}, 'Move caret to the beginning of the line', false)
key.setCaretKey([["C-e"], ["$"]], function (ev) {
ev.target.ksMarked ? goDoCommand("cmd_selectEndLine") : goDoCommand("cmd_endLine")
}, 'Move caret to the end of the line', false)
key.setCaretKey([["C-n"], ["j"]], function (ev) {
ev.target.ksMarked ? goDoCommand("cmd_selectLineNext") : goDoCommand("cmd_scrollLineDown")
}, 'Move caret to the next line', false)
key.setCaretKey([["C-p"], ["k"]], function (ev) {
ev.target.ksMarked ? goDoCommand("cmd_selectLinePrevious") : goDoCommand("cmd_scrollLineUp")
}, 'Move caret to the previous line', false)
key.setCaretKey([["C-f"], ["l"]], function (ev) {
ev.target.ksMarked ? goDoCommand("cmd_selectCharNext") : goDoCommand("cmd_scrollRight")
}, 'Move caret to the right', false)
key.setCaretKey([["C-b"], ["h"], ["C-h"]], function (ev) {
ev.target.ksMarked ? goDoCommand("cmd_selectCharPrevious") : goDoCommand("cmd_scrollLeft")
}, 'Move caret to the left', false)
key.setCaretKey([["M-f"], ["w"]], function (ev) {
ev.target.ksMarked ? goDoCommand("cmd_selectWordNext") : goDoCommand("cmd_wordNext")
}, 'Move caret to the right by word', false)
key.setCaretKey([["M-b"], ["W"]], function (ev) {
ev.target.ksMarked ? goDoCommand("cmd_selectWordPrevious") : goDoCommand("cmd_wordPrevious")
}, 'Move caret to the left by word', false)
key.setCaretKey([["C-v"], ["SPC"]], function (ev) {
ev.target.ksMarked ? goDoCommand("cmd_selectPageNext") : goDoCommand("cmd_movePageDown")
}, 'Move caret down by page', false)
key.setCaretKey([["M-v"], ["b"]], function (ev) {
ev.target.ksMarked ? goDoCommand("cmd_selectPagePrevious") : goDoCommand("cmd_movePageUp")
}, 'Move caret up by page', false)
key.setCaretKey([["M-<"], ["g"]], function (ev) {
ev.target.ksMarked ? goDoCommand("cmd_selectTop") : goDoCommand("cmd_scrollTop")
}, 'Move caret to the top of the page', false)
key.setCaretKey([["M->"], ["G"]], function (ev) {
ev.target.ksMarked ? goDoCommand("cmd_selectEndLine") : goDoCommand("cmd_endLine")
}, 'Move caret to the end of the line', false)
key.setCaretKey('J', function (ev) {
util.getSelectionController().scrollLine(true)
}, 'Scroll line down', false)
key.setCaretKey('K', function (ev) {
util.getSelectionController().scrollLine(false)
}, 'Scroll line up', false)
key.setCaretKey(',', function (ev) {
util.getSelectionController().scrollHorizontal(true)
goDoCommand("cmd_scrollLeft")
}, 'Scroll left', false)
key.setCaretKey('.', function (ev) {
goDoCommand("cmd_scrollRight")
util.getSelectionController().scrollHorizontal(false)
}, 'Scroll right', false)
key.setCaretKey('z', function (ev) {
command.recenter(ev)
}, 'Scroll to the cursor position', false)
key.setCaretKey([["C-SPC"], ["C-@"]], function (ev) {
command.setMark(ev)
}, 'Set the mark', true)
key.setCaretKey(':', function (ev, arg) {
shell.input(null, arg)
}, 'List and execute commands', true)
key.setCaretKey('R', function (ev) {
BrowserReload()
}, 'Reload the page', true)
key.setCaretKey('B', function (ev) {
BrowserBack()
}, 'Back', false)
key.setCaretKey('F', function (ev) {
BrowserForward()
}, 'Forward', false)
key.setCaretKey(["C-x", "h"], function (ev) {
goDoCommand("cmd_selectAll")
}, 'Select all', true)
key.setCaretKey('f', function (ev) {
command.focusElement(command.elementsRetrieverTextarea, 0)
}, 'Focus to the first textarea', true)
key.setCaretKey('M-p', function (ev) {
command.walkInputElement(command.elementsRetrieverButton, true, true)
}, 'Focus to the next button', false)
key.setCaretKey('M-n', function (ev) {
command.walkInputElement(command.elementsRetrieverButton, false, true)
}, 'Focus to the previous button', false)
|
[KeySnail] Functions typo changed to ES6 style.
|
keysnail/keysnail.js
|
[KeySnail] Functions typo changed to ES6 style.
|
<ide><path>eysnail/keysnail.js
<ide>
<ide> //// Hooks
<ide>
<del>hook.addToHook('KeyBoardQuit', function (aEvent) {
<add>hook.addToHook("KeyBoardQuit", function (event) {
<ide> if (key.currentKeySequence.length) return
<del>
<ide> command.closeFindBar()
<del>
<del> let marked = command.marked(aEvent)
<del>
<add> let marked = command.marked(event)
<ide> if (util.isCaretEnabled()) {
<ide> if (marked) {
<del> command.resetMark(aEvent)
<add> command.resetMark(event)
<ide> } else {
<del> if ("blur" in aEvent.target) aEvent.target.blur()
<add> if ("blur" in event.target) event.target.blur()
<ide> gBrowser.focus()
<ide> _content.focus()
<ide> }
<ide> } else {
<ide> goDoCommand("cmd_selectNone")
<ide> }
<del>
<ide> if (KeySnail.windowType === "navigator:browser" && !marked) {
<del> key.generateKey(aEvent.originalTarget, KeyEvent.DOM_VK_ESCAPE, true)
<add> key.generateKey(event.originalTarget, KeyEvent.DOM_VK_ESCAPE, true)
<ide> }
<ide> })
<ide>
<ide> //// Key bindings
<ide>
<del>key.setGlobalKey('C-M-r', function (ev) {
<add>key.setGlobalKey("C-M-r", (event) => {
<ide> userscript.reload()
<del>}, 'Reload the initialization file', true)
<del>
<del>key.setGlobalKey('M-x', function (ev, arg) {
<del> ext.select(arg, ev)
<del>}, 'List exts and execute selected one', true)
<del>
<del>key.setGlobalKey('M-:', function (ev) {
<add>}, "Reload the initialization file", true)
<add>
<add>key.setGlobalKey("M-x", (event, arg) => {
<add> ext.select(arg, event)
<add>}, "List exts and execute selected one", true)
<add>
<add>key.setGlobalKey("M-:", (event) => {
<ide> command.interpreter()
<del>}, 'Command interpreter', true)
<del>
<del>key.setGlobalKey(["<f1>", "b"], function (ev) {
<add>}, "Command interpreter", true)
<add>
<add>key.setGlobalKey(["<f1>", "b"], (event) => {
<ide> key.listKeyBindings()
<del>}, 'List all keybindings', false)
<del>
<del>key.setGlobalKey('C-m', function (ev) {
<del> key.generateKey(ev.originalTarget, KeyEvent.DOM_VK_RETURN, true)
<del>}, 'Generate the return key code', false)
<del>
<del>key.setGlobalKey(["<f1>", "F"], function (ev) {
<add>}, "List all keybindings", false)
<add>
<add>key.setGlobalKey("C-m", (event) => {
<add> key.generateKey(event.originalTarget, KeyEvent.DOM_VK_RETURN, true)
<add>}, "Generate the return key code", false)
<add>
<add>key.setGlobalKey(["<f1>", "F"], (event) => {
<ide> openHelpLink("firefox-help")
<del>}, 'Display Firefox help', false)
<del>
<del>key.setGlobalKey(["C-x", "l"], function (ev) {
<add>}, "Display Firefox help", false)
<add>
<add>key.setGlobalKey(["C-x", "l"], (event) => {
<ide> command.focusToById("urlbar")
<del>}, 'Focus to the location bar', true)
<del>
<del>key.setGlobalKey(["C-x", "g"], function (ev) {
<add>}, "Focus to the location bar", true)
<add>
<add>key.setGlobalKey(["C-x", "g"], (event) => {
<ide> command.focusToById("searchbar")
<del>}, 'Focus to the search bar', true)
<del>
<del>key.setGlobalKey(["C-x", "t"], function (ev) {
<add>}, "Focus to the search bar", true)
<add>
<add>key.setGlobalKey(["C-x", "t"], (event) => {
<ide> command.focusElement(command.elementsRetrieverTextarea, 0)
<del>}, 'Focus to the first textarea', true)
<del>
<del>key.setGlobalKey(["C-x", "s"], function (ev) {
<add>}, "Focus to the first textarea", true)
<add>
<add>key.setGlobalKey(["C-x", "s"], (event) => {
<ide> command.focusElement(command.elementsRetrieverButton, 0)
<del>}, 'Focus to the first button', true)
<del>
<del>key.setGlobalKey('M-w', function (ev) {
<del> command.copyRegion(ev)
<del>}, 'Copy selected text', true)
<del>
<del>key.setGlobalKey('C-s', function (ev) {
<del> command.iSearchForwardKs(ev)
<del>}, 'Emacs like incremental search forward', true)
<del>
<del>key.setGlobalKey('C-r', function (ev) {
<del> command.iSearchBackwardKs(ev)
<del>}, 'Emacs like incremental search backward', true)
<del>
<del>key.setGlobalKey(["C-x", "k"], function (ev) {
<add>}, "Focus to the first button", true)
<add>
<add>key.setGlobalKey("M-w", (event) => {
<add> command.copyRegion(event)
<add>}, "Copy selected text", true)
<add>
<add>key.setGlobalKey("C-s", (event) => {
<add> command.iSearchForwardKs(event)
<add>}, "Emacs like incremental search forward", true)
<add>
<add>key.setGlobalKey("C-r", (event) => {
<add> command.iSearchBackwardKs(event)
<add>}, "Emacs like incremental search backward", true)
<add>
<add>key.setGlobalKey(["C-x", "k"], (event) => {
<ide> BrowserCloseTabOrWindow()
<del>}, 'Close tab / window', false)
<del>
<del>key.setGlobalKey(["C-x", "K"], function (ev) {
<add>}, "Close tab / window", false)
<add>
<add>key.setGlobalKey(["C-x", "K"], (event) => {
<ide> closeWindow(true)
<del>}, 'Close the window', false)
<del>
<del>key.setGlobalKey(["C-c", "u"], function (ev) {
<add>}, "Close the window", false)
<add>
<add>key.setGlobalKey(["C-c", "u"], (event) => {
<ide> undoCloseTab()
<del>}, 'Undo closed tab', false)
<del>
<del>key.setGlobalKey(["C-x", "n"], function (ev) {
<add>}, "Undo closed tab", false)
<add>
<add>key.setGlobalKey(["C-x", "n"], (event) => {
<ide> OpenBrowserWindow()
<del>}, 'Open new window', false)
<del>
<del>key.setGlobalKey('C-M-l', function (ev) {
<add>}, "Open new window", false)
<add>
<add>key.setGlobalKey("C-M-l", (event) => {
<ide> getBrowser().mTabContainer.advanceSelectedTab(1, true)
<del>}, 'Select next tab', false)
<del>
<del>key.setGlobalKey('C-M-h', function (ev) {
<add>}, "Select next tab", false)
<add>
<add>key.setGlobalKey("C-M-h", (event) => {
<ide> getBrowser().mTabContainer.advanceSelectedTab(-1, true)
<del>}, 'Select previous tab', false)
<del>
<del>key.setGlobalKey(["C-x", "C-c"], function (ev) {
<add>}, "Select previous tab", false)
<add>
<add>key.setGlobalKey(["C-x", "C-c"], (event) => {
<ide> goQuitApplication()
<del>}, 'Exit Firefox', true)
<del>
<del>key.setGlobalKey(["C-x", "o"], function (ev, arg) {
<add>}, "Exit Firefox", true)
<add>
<add>key.setGlobalKey(["C-x", "o"], (event, arg) => {
<ide> command.focusOtherFrame(arg)
<del>}, 'Select next frame', false)
<del>
<del>key.setGlobalKey(["C-x", "1"], function (ev) {
<del> window.loadURI(ev.target.ownerDocument.location.href)
<del>}, 'Show current frame only', true)
<del>
<del>key.setGlobalKey(["C-x", "C-f"], function (ev) {
<add>}, "Select next frame", false)
<add>
<add>key.setGlobalKey(["C-x", "1"], (event) => {
<add> window.loadURI(event.target.ownerDocument.location.href)
<add>}, "Show current frame only", true)
<add>
<add>key.setGlobalKey(["C-x", "C-f"], (event) => {
<ide> BrowserOpenFileWindow()
<del>}, 'Open the local file', true)
<del>
<del>key.setGlobalKey(["C-x", "C-s"], function (ev) {
<add>}, "Open the local file", true)
<add>
<add>key.setGlobalKey(["C-x", "C-s"], (event) => {
<ide> saveDocument(window.content.document)
<del>}, 'Save current page to the file', true)
<del>
<del>key.setGlobalKey(["C-c", "C-c", "C-v"], function (ev) {
<add>}, "Save current page to the file", true)
<add>
<add>key.setGlobalKey(["C-c", "C-c", "C-v"], (event) => {
<ide> toJavaScriptConsole()
<del>}, 'Display JavaScript console', true)
<del>
<del>key.setGlobalKey(["C-c", "C-c", "C-c"], function (ev) {
<add>}, "Display JavaScript console", true)
<add>
<add>key.setGlobalKey(["C-c", "C-c", "C-c"], (event) => {
<ide> command.clearConsole()
<del>}, 'Clear Javascript console', true)
<del>
<del>key.setEditKey(["C-x", "h"], function (ev) {
<del> command.selectAll(ev)
<del>}, 'Select whole text', true)
<del>
<del>key.setEditKey([["C-SPC"], ["C-@"]], function (ev) {
<del> command.setMark(ev)
<del>}, 'Set the mark', true)
<del>
<del>key.setEditKey('C-o', function (ev) {
<del> command.openLine(ev)
<del>}, 'Open line', false)
<del>
<del>key.setEditKey([["C-x", "u"], ["C-_"]], function (ev) {
<add>}, "Clear Javascript console", true)
<add>
<add>key.setEditKey(["C-x", "h"], (event) => {
<add> command.selectAll(event)
<add>}, "Select whole text", true)
<add>
<add>key.setEditKey([["C-SPC"], ["C-@"]], (event) => {
<add> command.setMark(event)
<add>}, "Set the mark", true)
<add>
<add>key.setEditKey("C-o", (event) => {
<add> command.openLine(event)
<add>}, "Open line", false)
<add>
<add>key.setEditKey([["C-x", "u"], ["C-_"]], (event) => {
<ide> display.echoStatusBar("Undo!", 2000)
<ide> goDoCommand("cmd_undo")
<del>}, 'Undo', false)
<del>
<del>key.setEditKey('C-\\', function (ev) {
<add>}, "Undo", false)
<add>
<add>key.setEditKey("C-\\", (event) => {
<ide> display.echoStatusBar("Redo!", 2000)
<ide> goDoCommand("cmd_redo")
<del>}, 'Redo', false)
<del>
<del>key.setEditKey('C-a', function (ev) {
<del> command.beginLine(ev)
<del>}, 'Beginning of the line', false)
<del>
<del>key.setEditKey('C-e', function (ev) {
<del> command.endLine(ev)
<del>}, 'End of the line', false)
<del>
<del>key.setEditKey('C-f', function (ev) {
<del> command.nextChar(ev)
<del>}, 'Forward char', false)
<del>
<del>key.setEditKey('C-b', function (ev) {
<del> command.previousChar(ev)
<del>}, 'Backward char', false)
<del>
<del>key.setEditKey('M-f', function (ev) {
<del> command.forwardWord(ev)
<del>}, 'Next word', false)
<del>
<del>key.setEditKey('M-b', function (ev) {
<del> command.backwardWord(ev)
<del>}, 'Previous word', false)
<del>
<del>key.setEditKey('C-n', function (ev) {
<del> command.nextLine(ev)
<del>}, 'Next line', false)
<del>
<del>key.setEditKey('C-p', function (ev) {
<del> command.previousLine(ev)
<del>}, 'Previous line', false)
<del>
<del>key.setEditKey('C-v', function (ev) {
<del> command.pageDown(ev)
<del>}, 'Page down', false)
<del>
<del>key.setEditKey('M-v', function (ev) {
<del> command.pageUp(ev)
<del>}, 'Page up', false)
<del>
<del>key.setEditKey('M-<', function (ev) {
<del> command.moveTop(ev)
<del>}, 'Beginning of the text area', false)
<del>
<del>key.setEditKey('M->', function (ev) {
<del> command.moveBottom(ev)
<del>}, 'End of the text area', false)
<del>
<del>key.setEditKey('C-d', function (ev) {
<add>}, "Redo", false)
<add>
<add>key.setEditKey("C-a", (event) => {
<add> command.beginLine(event)
<add>}, "Beginning of the line", false)
<add>
<add>key.setEditKey("C-e", (event) => {
<add> command.endLine(event)
<add>}, "End of the line", false)
<add>
<add>key.setEditKey("C-f", (event) => {
<add> command.nextChar(event)
<add>}, "Forward char", false)
<add>
<add>key.setEditKey("C-b", (event) => {
<add> command.previousChar(event)
<add>}, "Backward char", false)
<add>
<add>key.setEditKey("M-f", (event) => {
<add> command.forwardWord(event)
<add>}, "Next word", false)
<add>
<add>key.setEditKey("M-b", (event) => {
<add> command.backwardWord(event)
<add>}, "Previous word", false)
<add>
<add>key.setEditKey("C-n", (event) => {
<add> command.nextLine(event)
<add>}, "Next line", false)
<add>
<add>key.setEditKey("C-p", (event) => {
<add> command.previousLine(event)
<add>}, "Previous line", false)
<add>
<add>key.setEditKey("C-v", (event) => {
<add> command.pageDown(event)
<add>}, "Page down", false)
<add>
<add>key.setEditKey("M-v", (event) => {
<add> command.pageUp(event)
<add>}, "Page up", false)
<add>
<add>key.setEditKey("M-<", (event) => {
<add> command.moveTop(event)
<add>}, "Beginning of the text area", false)
<add>
<add>key.setEditKey("M->", (event) => {
<add> command.moveBottom(event)
<add>}, "End of the text area", false)
<add>
<add>key.setEditKey("C-d", (event) => {
<ide> goDoCommand("cmd_deleteCharForward")
<del>}, 'Delete forward char', false)
<del>
<del>key.setEditKey('C-h', function (ev) {
<add>}, "Delete forward char", false)
<add>
<add>key.setEditKey("C-h", (event) => {
<ide> goDoCommand("cmd_deleteCharBackward")
<del>}, 'Delete backward char', false)
<del>
<del>key.setEditKey('M-d', function (ev) {
<del> command.deleteForwardWord(ev)
<del>}, 'Delete forward word', false)
<del>
<del>key.setEditKey([["C-<backspace>"], ["M-<delete>"]], function (ev) {
<del> command.deleteBackwardWord(ev)
<del>}, 'Delete backward word', false)
<del>
<del>key.setEditKey('M-u', function (ev, arg) {
<del> command.wordCommand(ev, arg, command.upcaseForwardWord, command.upcaseBackwardWord)
<del>}, 'Convert following word to upper case', false)
<del>
<del>key.setEditKey('M-l', function (ev, arg) {
<del> command.wordCommand(ev, arg, command.downcaseForwardWord, command.downcaseBackwardWord)
<del>}, 'Convert following word to lower case', false)
<del>
<del>key.setEditKey('M-c', function (ev, arg) {
<del> command.wordCommand(ev, arg, command.capitalizeForwardWord, command.capitalizeBackwardWord)
<del>}, 'Capitalize the following word', false)
<del>
<del>key.setEditKey('C-k', function (ev) {
<del> command.killLine(ev)
<del>}, 'Kill the rest of the line', false)
<del>
<del>key.setEditKey('C-y', command.yank, 'Paste (Yank)', false)
<del>
<del>key.setEditKey('M-y', command.yankPop, 'Paste pop (Yank pop)', true)
<del>
<del>key.setEditKey('C-M-y', function (ev) {
<del> if (!command.kill.ring.length)
<del> return
<del>
<add>}, "Delete backward char", false)
<add>
<add>key.setEditKey("M-d", (event) => {
<add> command.deleteForwardWord(event)
<add>}, "Delete forward word", false)
<add>
<add>key.setEditKey([["C-<backspace>"], ["M-<delete>"]], (event) => {
<add> command.deleteBackwardWord(event)
<add>}, "Delete backward word", false)
<add>
<add>key.setEditKey("M-u", (event, arg) => {
<add> command.wordCommand(event, arg, command.upcaseForwardWord, command.upcaseBackwardWord)
<add>}, "Convert following word to upper case", false)
<add>
<add>key.setEditKey("M-l", (event, arg) => {
<add> command.wordCommand(event, arg, command.downcaseForwardWord, command.downcaseBackwardWord)
<add>}, "Convert following word to lower case", false)
<add>
<add>key.setEditKey("M-c", (event, arg) => {
<add> command.wordCommand(event, arg, command.capitalizeForwardWord, command.capitalizeBackwardWord)
<add>}, "Capitalize the following word", false)
<add>
<add>key.setEditKey("C-k", (event) => {
<add> command.killLine(event)
<add>}, "Kill the rest of the line", false)
<add>
<add>key.setEditKey("C-y", (event) => {
<add> command.yank()
<add>}, "Paste (Yank)", false)
<add>
<add>key.setEditKey("M-y", (event) => {
<add> command.yankPop()
<add>}, "Paste pop (Yank pop)", true)
<add>
<add>key.setEditKey("C-M-y", (event) => {
<add> if (!command.kill.ring.length) return
<ide> let (ct = command.getClipboardText())
<ide> (!command.kill.ring.length || ct != command.kill.ring[0]) && command.pushKillRing(ct)
<del>
<del> prompt.selector(
<del> {
<del> message: "Paste:",
<del> collection: command.kill.ring,
<del> callback: function (i) { if (i >= 0) key.insertText(command.kill.ring[i]) }
<add> prompt.selector({
<add> message: "Paste:",
<add> collection: command.kill.ring,
<add> callback: (i) => {
<add> if (i >= 0) key.insertText(command.kill.ring[i])
<ide> }
<del> )
<del>}, 'Show kill-ring and select text to paste', true)
<del>
<del>key.setEditKey('C-w', function (ev) {
<add> })
<add>}, "Show kill-ring and select text to paste", true)
<add>
<add>key.setEditKey("C-w", (event) => {
<ide> goDoCommand("cmd_copy")
<ide> goDoCommand("cmd_delete")
<del> command.resetMark(ev)
<del>}, 'Cut current region', true)
<del>
<del>key.setEditKey(["C-x", "r", "d"], function (ev, arg) {
<del> command.replaceRectangle(ev.originalTarget, "", false, !arg)
<del>}, 'Delete text in the region-rectangle', true)
<del>
<del>key.setEditKey(["C-x", "r", "t"], function (ev) {
<del> prompt.read("String rectangle: ", function (aStr, aInput) {
<del> command.replaceRectangle(aInput, aStr)
<del> },
<del> ev.originalTarget)
<del>}, 'Replace text in the region-rectangle with user inputted string', true)
<del>
<del>key.setEditKey(["C-x", "r", "o"], function (ev) {
<del> command.openRectangle(ev.originalTarget)
<del>}, 'Blank out the region-rectangle, shifting text right', true)
<del>
<del>key.setEditKey(["C-x", "r", "k"], function (ev, arg) {
<del> command.kill.buffer = command.killRectangle(ev.originalTarget, !arg)
<del>}, 'Delete the region-rectangle and save it as the last killed one', true)
<del>
<del>key.setEditKey(["C-x", "r", "y"], function (ev) {
<del> command.yankRectangle(ev.originalTarget, command.kill.buffer)
<del>}, 'Yank the last killed rectangle with upper left corner at point', true)
<del>
<del>key.setEditKey('M-n', function (ev) {
<add> command.resetMark(event)
<add>}, "Cut current region", true)
<add>
<add>key.setEditKey(["C-x", "r", "d"], (event, arg) => {
<add> command.replaceRectangle(event.originalTarget, "", false, !arg)
<add>}, "Delete text in the region-rectangle", true)
<add>
<add>key.setEditKey(["C-x", "r", "t"], (event) => {
<add> prompt.read("String rectangle: ", (string, input) => {
<add> command.replaceRectangle(input, string)
<add> }, event.originalTarget)
<add>}, "Replace text in the region-rectangle with user inputted string", true)
<add>
<add>key.setEditKey(["C-x", "r", "o"], (event) => {
<add> command.openRectangle(event.originalTarget)
<add>}, "Blank out the region-rectangle, shifting text right", true)
<add>
<add>key.setEditKey(["C-x", "r", "k"], (event, arg) => {
<add> command.kill.buffer = command.killRectangle(event.originalTarget, !arg)
<add>}, "Delete the region-rectangle and save it as the last killed one", true)
<add>
<add>key.setEditKey(["C-x", "r", "y"], (event) => {
<add> command.yankRectangle(event.originalTarget, command.kill.buffer)
<add>}, "Yank the last killed rectangle with upper left corner at point", true)
<add>
<add>key.setEditKey("M-n", (event) => {
<ide> command.walkInputElement(command.elementsRetrieverTextarea, true, true)
<del>}, 'Focus to the next text area', false)
<del>
<del>key.setEditKey('M-p', function (ev) {
<add>}, "Focus to the next text area", false)
<add>
<add>key.setEditKey("M-p", (event) => {
<ide> command.walkInputElement(command.elementsRetrieverTextarea, false, true)
<del>}, 'Focus to the previous text area', false)
<del>
<del>key.setViewKey([["C-n"], ["j"]], function (ev) {
<del> key.generateKey(ev.originalTarget, KeyEvent.DOM_VK_DOWN, true)
<del>}, 'Scroll line down', false)
<del>
<del>key.setViewKey([["C-p"], ["k"]], function (ev) {
<del> key.generateKey(ev.originalTarget, KeyEvent.DOM_VK_UP, true)
<del>}, 'Scroll line up', false)
<del>
<del>key.setViewKey([["C-f"], ["."]], function (ev) {
<del> key.generateKey(ev.originalTarget, KeyEvent.DOM_VK_RIGHT, true)
<del>}, 'Scroll right', false)
<del>
<del>key.setViewKey([["C-b"], [","]], function (ev) {
<del> key.generateKey(ev.originalTarget, KeyEvent.DOM_VK_LEFT, true)
<del>}, 'Scroll left', false)
<del>
<del>key.setViewKey([["M-v"], ["b"]], function (ev) {
<add>}, "Focus to the previous text area", false)
<add>
<add>key.setViewKey([["C-n"], ["j"]], (event) => {
<add> key.generateKey(event.originalTarget, KeyEvent.DOM_VK_DOWN, true)
<add>}, "Scroll line down", false)
<add>
<add>key.setViewKey([["C-p"], ["k"]], (event) => {
<add> key.generateKey(event.originalTarget, KeyEvent.DOM_VK_UP, true)
<add>}, "Scroll line up", false)
<add>
<add>key.setViewKey([["C-f"], ["."]], (event) => {
<add> key.generateKey(event.originalTarget, KeyEvent.DOM_VK_RIGHT, true)
<add>}, "Scroll right", false)
<add>
<add>key.setViewKey([["C-b"], [","]], (event) => {
<add> key.generateKey(event.originalTarget, KeyEvent.DOM_VK_LEFT, true)
<add>}, "Scroll left", false)
<add>
<add>key.setViewKey([["M-v"], ["b"]], (event) => {
<ide> goDoCommand("cmd_scrollPageUp")
<del>}, 'Scroll page up', false)
<del>
<del>key.setViewKey('C-v', function (ev) {
<add>}, "Scroll page up", false)
<add>
<add>key.setViewKey("C-v", (event) => {
<ide> goDoCommand("cmd_scrollPageDown")
<del>}, 'Scroll page down', false)
<del>
<del>key.setViewKey([["M-<"], ["g"]], function (ev) {
<add>}, "Scroll page down", false)
<add>
<add>key.setViewKey([["M-<"], ["g"]], (event) => {
<ide> goDoCommand("cmd_scrollTop")
<del>}, 'Scroll to the top of the page', true)
<del>
<del>key.setViewKey([["M->"], ["G"]], function (ev) {
<add>}, "Scroll to the top of the page", true)
<add>
<add>key.setViewKey([["M->"], ["G"]], (event) => {
<ide> goDoCommand("cmd_scrollBottom")
<del>}, 'Scroll to the bottom of the page', true)
<del>
<del>key.setViewKey('l', function (ev) {
<add>}, "Scroll to the bottom of the page", true)
<add>
<add>key.setViewKey("l", (event) => {
<ide> getBrowser().mTabContainer.advanceSelectedTab(1, true)
<del>}, 'Select next tab', false)
<del>
<del>key.setViewKey('h', function (ev) {
<add>}, "Select next tab", false)
<add>
<add>key.setViewKey("h", (event) => {
<ide> getBrowser().mTabContainer.advanceSelectedTab(-1, true)
<del>}, 'Select previous tab', false)
<del>
<del>key.setViewKey(':', function (ev, arg) {
<add>}, "Select previous tab", false)
<add>
<add>key.setViewKey(":", (event, arg) => {
<ide> shell.input(null, arg)
<del>}, 'List and execute commands', true)
<del>
<del>key.setViewKey('R', function (ev) {
<add>}, "List and execute commands", true)
<add>
<add>key.setViewKey("R", (event) => {
<ide> BrowserReload()
<del>}, 'Reload the page', true)
<del>
<del>key.setViewKey('B', function (ev) {
<add>}, "Reload the page", true)
<add>
<add>key.setViewKey("B", (event) => {
<ide> BrowserBack()
<del>}, 'Back', false)
<del>
<del>key.setViewKey('F', function (ev) {
<add>}, "Back", false)
<add>
<add>key.setViewKey("F", (event) => {
<ide> BrowserForward()
<del>}, 'Forward', false)
<del>
<del>key.setViewKey(["C-x", "h"], function (ev) {
<add>}, "Forward", false)
<add>
<add>key.setViewKey(["C-x", "h"], (event) => {
<ide> goDoCommand("cmd_selectAll")
<del>}, 'Select all', true)
<del>
<del>key.setViewKey('f', function (ev) {
<add>}, "Select all", true)
<add>
<add>key.setViewKey("f", (event) => {
<ide> command.focusElement(command.elementsRetrieverTextarea, 0)
<del>}, 'Focus to the first textarea', true)
<del>
<del>key.setViewKey('M-p', function (ev) {
<add>}, "Focus to the first textarea", true)
<add>
<add>key.setViewKey("M-p", (event) => {
<ide> command.walkInputElement(command.elementsRetrieverButton, true, true)
<del>}, 'Focus to the next button', false)
<del>
<del>key.setViewKey('M-n', function (ev) {
<add>}, "Focus to the next button", false)
<add>
<add>key.setViewKey("M-n", (event) => {
<ide> command.walkInputElement(command.elementsRetrieverButton, false, true)
<del>}, 'Focus to the previous button', false)
<del>
<del>key.setCaretKey([["C-a"], ["^"]], function (ev) {
<del> ev.target.ksMarked ? goDoCommand("cmd_selectBeginLine") : goDoCommand("cmd_beginLine")
<del>}, 'Move caret to the beginning of the line', false)
<del>
<del>key.setCaretKey([["C-e"], ["$"]], function (ev) {
<del> ev.target.ksMarked ? goDoCommand("cmd_selectEndLine") : goDoCommand("cmd_endLine")
<del>}, 'Move caret to the end of the line', false)
<del>
<del>key.setCaretKey([["C-n"], ["j"]], function (ev) {
<del> ev.target.ksMarked ? goDoCommand("cmd_selectLineNext") : goDoCommand("cmd_scrollLineDown")
<del>}, 'Move caret to the next line', false)
<del>
<del>key.setCaretKey([["C-p"], ["k"]], function (ev) {
<del> ev.target.ksMarked ? goDoCommand("cmd_selectLinePrevious") : goDoCommand("cmd_scrollLineUp")
<del>}, 'Move caret to the previous line', false)
<del>
<del>key.setCaretKey([["C-f"], ["l"]], function (ev) {
<del> ev.target.ksMarked ? goDoCommand("cmd_selectCharNext") : goDoCommand("cmd_scrollRight")
<del>}, 'Move caret to the right', false)
<del>
<del>key.setCaretKey([["C-b"], ["h"], ["C-h"]], function (ev) {
<del> ev.target.ksMarked ? goDoCommand("cmd_selectCharPrevious") : goDoCommand("cmd_scrollLeft")
<del>}, 'Move caret to the left', false)
<del>
<del>key.setCaretKey([["M-f"], ["w"]], function (ev) {
<del> ev.target.ksMarked ? goDoCommand("cmd_selectWordNext") : goDoCommand("cmd_wordNext")
<del>}, 'Move caret to the right by word', false)
<del>
<del>key.setCaretKey([["M-b"], ["W"]], function (ev) {
<del> ev.target.ksMarked ? goDoCommand("cmd_selectWordPrevious") : goDoCommand("cmd_wordPrevious")
<del>}, 'Move caret to the left by word', false)
<del>
<del>key.setCaretKey([["C-v"], ["SPC"]], function (ev) {
<del> ev.target.ksMarked ? goDoCommand("cmd_selectPageNext") : goDoCommand("cmd_movePageDown")
<del>}, 'Move caret down by page', false)
<del>
<del>key.setCaretKey([["M-v"], ["b"]], function (ev) {
<del> ev.target.ksMarked ? goDoCommand("cmd_selectPagePrevious") : goDoCommand("cmd_movePageUp")
<del>}, 'Move caret up by page', false)
<del>
<del>key.setCaretKey([["M-<"], ["g"]], function (ev) {
<del> ev.target.ksMarked ? goDoCommand("cmd_selectTop") : goDoCommand("cmd_scrollTop")
<del>}, 'Move caret to the top of the page', false)
<del>
<del>key.setCaretKey([["M->"], ["G"]], function (ev) {
<del> ev.target.ksMarked ? goDoCommand("cmd_selectEndLine") : goDoCommand("cmd_endLine")
<del>}, 'Move caret to the end of the line', false)
<del>
<del>key.setCaretKey('J', function (ev) {
<add>}, "Focus to the previous button", false)
<add>
<add>key.setCaretKey([["C-a"], ["^"]], (event) => {
<add> event.target.ksMarked ? goDoCommand("cmd_selectBeginLine") : goDoCommand("cmd_beginLine")
<add>}, "Move caret to the beginning of the line", false)
<add>
<add>key.setCaretKey([["C-e"], ["$"]], (event) => {
<add> event.target.ksMarked ? goDoCommand("cmd_selectEndLine") : goDoCommand("cmd_endLine")
<add>}, "Move caret to the end of the line", false)
<add>
<add>key.setCaretKey([["C-n"], ["j"]], (event) => {
<add> event.target.ksMarked ? goDoCommand("cmd_selectLineNext") : goDoCommand("cmd_scrollLineDown")
<add>}, "Move caret to the next line", false)
<add>
<add>key.setCaretKey([["C-p"], ["k"]], (event) => {
<add> event.target.ksMarked ? goDoCommand("cmd_selectLinePrevious") : goDoCommand("cmd_scrollLineUp")
<add>}, "Move caret to the previous line", false)
<add>
<add>key.setCaretKey([["C-f"], ["l"]], (event) => {
<add> event.target.ksMarked ? goDoCommand("cmd_selectCharNext") : goDoCommand("cmd_scrollRight")
<add>}, "Move caret to the right", false)
<add>
<add>key.setCaretKey([["C-b"], ["h"], ["C-h"]], (event) => {
<add> event.target.ksMarked ? goDoCommand("cmd_selectCharPrevious") : goDoCommand("cmd_scrollLeft")
<add>}, "Move caret to the left", false)
<add>
<add>key.setCaretKey([["M-f"], ["w"]], (event) => {
<add> event.target.ksMarked ? goDoCommand("cmd_selectWordNext") : goDoCommand("cmd_wordNext")
<add>}, "Move caret to the right by word", false)
<add>
<add>key.setCaretKey([["M-b"], ["W"]], (event) => {
<add> event.target.ksMarked ? goDoCommand("cmd_selectWordPrevious") : goDoCommand("cmd_wordPrevious")
<add>}, "Move caret to the left by word", false)
<add>
<add>key.setCaretKey([["C-v"], ["SPC"]], (event) => {
<add> event.target.ksMarked ? goDoCommand("cmd_selectPageNext") : goDoCommand("cmd_movePageDown")
<add>}, "Move caret down by page", false)
<add>
<add>key.setCaretKey([["M-v"], ["b"]], (event) => {
<add> event.target.ksMarked ? goDoCommand("cmd_selectPagePrevious") : goDoCommand("cmd_movePageUp")
<add>}, "Move caret up by page", false)
<add>
<add>key.setCaretKey([["M-<"], ["g"]], (event) => {
<add> event.target.ksMarked ? goDoCommand("cmd_selectTop") : goDoCommand("cmd_scrollTop")
<add>}, "Move caret to the top of the page", false)
<add>
<add>key.setCaretKey([["M->"], ["G"]], (event) => {
<add> event.target.ksMarked ? goDoCommand("cmd_selectEndLine") : goDoCommand("cmd_endLine")
<add>}, "Move caret to the end of the line", false)
<add>
<add>key.setCaretKey("J", (event) => {
<ide> util.getSelectionController().scrollLine(true)
<del>}, 'Scroll line down', false)
<del>
<del>key.setCaretKey('K', function (ev) {
<add>}, "Scroll line down", false)
<add>
<add>key.setCaretKey("K", (event) => {
<ide> util.getSelectionController().scrollLine(false)
<del>}, 'Scroll line up', false)
<del>
<del>key.setCaretKey(',', function (ev) {
<add>}, "Scroll line up", false)
<add>
<add>key.setCaretKey(",", (event) => {
<ide> util.getSelectionController().scrollHorizontal(true)
<ide> goDoCommand("cmd_scrollLeft")
<del>}, 'Scroll left', false)
<del>
<del>key.setCaretKey('.', function (ev) {
<add>}, "Scroll left", false)
<add>
<add>key.setCaretKey(".", (event) => {
<ide> goDoCommand("cmd_scrollRight")
<ide> util.getSelectionController().scrollHorizontal(false)
<del>}, 'Scroll right', false)
<del>
<del>key.setCaretKey('z', function (ev) {
<del> command.recenter(ev)
<del>}, 'Scroll to the cursor position', false)
<del>
<del>key.setCaretKey([["C-SPC"], ["C-@"]], function (ev) {
<del> command.setMark(ev)
<del>}, 'Set the mark', true)
<del>
<del>key.setCaretKey(':', function (ev, arg) {
<add>}, "Scroll right", false)
<add>
<add>key.setCaretKey("z", (event) => {
<add> command.recenter(event)
<add>}, "Scroll to the cursor position", false)
<add>
<add>key.setCaretKey([["C-SPC"], ["C-@"]], (event) => {
<add> command.setMark(event)
<add>}, "Set the mark", true)
<add>
<add>key.setCaretKey(":", (event, arg) => {
<ide> shell.input(null, arg)
<del>}, 'List and execute commands', true)
<del>
<del>key.setCaretKey('R', function (ev) {
<add>}, "List and execute commands", true)
<add>
<add>key.setCaretKey("R", (event) => {
<ide> BrowserReload()
<del>}, 'Reload the page', true)
<del>
<del>key.setCaretKey('B', function (ev) {
<add>}, "Reload the page", true)
<add>
<add>key.setCaretKey("B", (event) => {
<ide> BrowserBack()
<del>}, 'Back', false)
<del>
<del>key.setCaretKey('F', function (ev) {
<add>}, "Back", false)
<add>
<add>key.setCaretKey("F", (event) => {
<ide> BrowserForward()
<del>}, 'Forward', false)
<del>
<del>key.setCaretKey(["C-x", "h"], function (ev) {
<add>}, "Forward", false)
<add>
<add>key.setCaretKey(["C-x", "h"], (event) => {
<ide> goDoCommand("cmd_selectAll")
<del>}, 'Select all', true)
<del>
<del>key.setCaretKey('f', function (ev) {
<add>}, "Select all", true)
<add>
<add>key.setCaretKey("f", (event) => {
<ide> command.focusElement(command.elementsRetrieverTextarea, 0)
<del>}, 'Focus to the first textarea', true)
<del>
<del>key.setCaretKey('M-p', function (ev) {
<add>}, "Focus to the first textarea", true)
<add>
<add>key.setCaretKey("M-p", (event) => {
<ide> command.walkInputElement(command.elementsRetrieverButton, true, true)
<del>}, 'Focus to the next button', false)
<del>
<del>key.setCaretKey('M-n', function (ev) {
<add>}, "Focus to the next button", false)
<add>
<add>key.setCaretKey("M-n", (event) => {
<ide> command.walkInputElement(command.elementsRetrieverButton, false, true)
<del>}, 'Focus to the previous button', false)
<del>
<add>}, "Focus to the previous button", false)
|
|
Java
|
lgpl-2.1
|
e6f298dc92ec99c7fa2aa3a4afd0076cddcf572e
| 0 |
EgorZhuk/pentaho-reporting,mbatchelor/pentaho-reporting,mbatchelor/pentaho-reporting,mbatchelor/pentaho-reporting,EgorZhuk/pentaho-reporting,EgorZhuk/pentaho-reporting,mbatchelor/pentaho-reporting,EgorZhuk/pentaho-reporting
|
/*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2001 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors.. All rights reserved.
*/
package org.pentaho.reporting.engine.classic.core.layout;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.reporting.engine.classic.core.layout.model.FinishedRenderNode;
import org.pentaho.reporting.engine.classic.core.layout.model.LogicalPageBox;
import org.pentaho.reporting.engine.classic.core.layout.model.ParagraphRenderBox;
import org.pentaho.reporting.engine.classic.core.layout.model.RenderBox;
import org.pentaho.reporting.engine.classic.core.layout.model.RenderNode;
import org.pentaho.reporting.engine.classic.core.layout.model.RenderableText;
import org.pentaho.reporting.engine.classic.core.layout.model.table.TableCellRenderBox;
import org.pentaho.reporting.engine.classic.core.layout.model.table.TableSectionRenderBox;
/**
* Creation-Date: Jan 9, 2007, 2:22:59 PM
*
* @author Thomas Morgner
*/
public class ModelPrinter
{
private static final Log logger = LogFactory.getLog(ModelPrinter.class);
private static final boolean PRINT_LINEBOX_CONTENTS = false;
private ModelPrinter()
{
}
public static void printParents(RenderNode box)
{
while (box != null)
{
final StringBuffer b = new StringBuffer();
b.append(box.getClass().getName());
b.append('[');
b.append(box.getElementType().getClass().getName());
//b.append(Integer.toHexString(System.identityHashCode(box)));
b.append(';');
b.append(box.getName());
b.append(']');
b.append("={stateKey=");
b.append(box.getStateKey());
b.append(", x=");
b.append(box.getX());
b.append(", y=");
b.append(box.getY());
b.append(", width=");
b.append(box.getWidth());
b.append(", height=");
b.append(box.getHeight());
b.append(", min-chunk-width=");
b.append(box.getMinimumChunkWidth());
b.append(", computed-width=");
b.append(box.getComputedWidth());
b.append(", cached-x=");
b.append(box.getCachedX());
b.append(", cached-y=");
b.append(box.getCachedY());
b.append(", cached-width=");
b.append(box.getCachedWidth());
b.append(", cached-height=");
b.append(box.getCachedHeight());
b.append('}');
logger.debug(b);
box = box.getParent();
}
}
public static void print(final RenderBox box)
{
printBox(box, 0);
}
public static void printBox(final RenderBox box, final int level)
{
StringBuffer b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append(box.getClass().getName());
b.append('[');
b.append(box.getElementType().getClass().getName());
//b.append(Integer.toHexString(System.identityHashCode(box)));
b.append(';');
b.append(box.getName());
b.append(']');
b.append("={stateKey=");
b.append(box.getStateKey());
b.append(", pinned=");
b.append(box.getPinned());
b.append('}');
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("-layout x=");
b.append(box.getX());
b.append(", y=");
b.append(box.getY());
b.append(", width=");
b.append(box.getWidth());
b.append(", height=");
b.append(box.getHeight());
b.append(", min-chunk-width=");
b.append(box.getMinimumChunkWidth());
b.append(", computed-width=");
b.append(box.getComputedWidth());
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("-cached-layout cached-x=");
b.append(box.getCachedX());
b.append(", cached-y=");
b.append(box.getCachedY());
b.append(", cached-width=");
b.append(box.getCachedWidth());
b.append(", cached-height=");
b.append(box.getCachedHeight());
b.append(", content-area-x1=");
b.append(box.getContentAreaX1());
b.append(", content-area-x2=");
b.append(box.getContentAreaX2());
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- boxDefinition=");
b.append(box.getBoxDefinition());
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- nodeLayoutProperties=");
b.append(box.getNodeLayoutProperties());
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- staticBoxLayoutProperties=");
b.append(box.getStaticBoxLayoutProperties());
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- breakContext=");
b.append(box.getBreakContext());
logger.debug(b.toString());
if (box instanceof LogicalPageBox)
{
final LogicalPageBox pageBox = (LogicalPageBox) box;
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- PageBox={PageOffset=");
b.append(pageBox.getPageOffset());
b.append(", PageHeight=");
b.append(pageBox.getPageHeight());
b.append(", PageEnd=");
b.append(pageBox.getPageEnd());
b.append(", PageWidth=");
b.append(pageBox.getPageWidth());
b.append('}');
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- PageBreaks={");
b.append(pageBox.getAllVerticalBreaks());
b.append('}');
logger.debug(b.toString());
}
if (box instanceof TableSectionRenderBox)
{
final TableSectionRenderBox pageBox = (TableSectionRenderBox) box;
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- Role: ");
b.append(pageBox.getDisplayRole());
logger.debug(b.toString());
}
if (box instanceof TableCellRenderBox)
{
final TableCellRenderBox pageBox = (TableCellRenderBox) box;
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- Column-Index=");
b.append(pageBox.getColumnIndex());
b.append(", ColSpan=");
b.append(pageBox.getColSpan());
b.append(", RowSpan=");
b.append(pageBox.getRowSpan());
logger.debug(b.toString());
}
if (box.isOpen())
{
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- WARNING: THIS BOX IS STILL OPEN");
logger.debug(b.toString());
}
if (box.isFinishedTable() || box.isFinishedPaginate())
{
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- INFO: THIS BOX IS FINISHED: ");
if (box.isFinishedTable())
{
b.append("- TABLE ");
}
if (box.isFinishedPaginate())
{
b.append("- PAGE ");
}
logger.debug(b.toString());
}
if (box.isCommited())
{
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- INFO: THIS BOX IS COMMITED");
logger.debug(b.toString());
}
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
logger.debug(b.toString());
if (box instanceof ParagraphRenderBox)
{
if (PRINT_LINEBOX_CONTENTS)
{
final ParagraphRenderBox paraBox = (ParagraphRenderBox) box;
logger.debug("---------------- START PARAGRAPH POOL CONTAINER -------------------------------------");
printBox(paraBox.getPool(), level + 1);
logger.debug("---------------- FINISH PARAGRAPH POOL CONTAINER -------------------------------------");
if (paraBox.isComplexParagraph())
{
logger.debug("---------------- START PARAGRAPH LINEBOX CONTAINER -------------------------------------");
printBox(paraBox.getLineboxContainer(), level + 1);
logger.debug("---------------- FINISH PARAGRAPH LINEBOX CONTAINER -------------------------------------");
}
}
}
if (box instanceof LogicalPageBox)
{
final LogicalPageBox lbox = (LogicalPageBox) box;
printBox(lbox.getHeaderArea(), level + 1);
printBox(lbox.getWatermarkArea(), level + 1);
}
printChilds(box, level);
if (box instanceof LogicalPageBox)
{
final LogicalPageBox lbox = (LogicalPageBox) box;
printBox(lbox.getRepeatFooterArea(), level + 1);
printBox(lbox.getFooterArea(), level + 1);
}
}
private static void printChilds(final RenderBox box, final int level)
{
RenderNode childs = box.getFirstChild();
while (childs != null)
{
if (childs instanceof RenderBox)
{
printBox((RenderBox) childs, level + 1);
}
else if (childs instanceof RenderableText)
{
printText((RenderableText) childs, level + 1);
}
else
{
printNode(childs, level + 1);
}
childs = childs.getNext();
}
}
private static void printNode(final RenderNode node, final int level)
{
StringBuffer b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append(node.getClass().getName());
b.append('[');
//b.append(Integer.toHexString(System.identityHashCode(node)));
b.append(']');
b.append("={x=");
b.append(node.getX());
b.append(", y=");
b.append(node.getY());
b.append(", width=");
b.append(node.getWidth());
b.append(", height=");
b.append(node.getHeight());
b.append(", min-chunk-width=");
b.append(node.getMinimumChunkWidth());
b.append(", computed-width=");
b.append(node.getComputedWidth());
if (node instanceof FinishedRenderNode)
{
final FinishedRenderNode fn = (FinishedRenderNode) node;
b.append(", layouted-width=");
b.append(fn.getLayoutedWidth());
b.append(", layouted-height=");
b.append(fn.getLayoutedHeight());
}
b.append('}');
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- cacheSize={x=");
b.append(node.getCachedX());
b.append(", y=");
b.append(node.getCachedY());
b.append(", width=");
b.append(node.getCachedWidth());
b.append(", height=");
b.append(node.getCachedHeight());
b.append('}');
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- nodeLayoutProperties=");
b.append(node.getNodeLayoutProperties());
logger.debug(b.toString());
logger.debug("");
}
private static void printText(final RenderableText text, final int level)
{
StringBuffer b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("Text");
b.append('[');
//b.append(Integer.toHexString(System.identityHashCode(text)));
b.append(']');
b.append("={x=");
b.append(text.getX());
b.append(", y=");
b.append(text.getY());
b.append(", width=");
b.append(text.getWidth());
b.append(", height=");
b.append(text.getHeight());
b.append(", min-chunk-width=");
b.append(text.getMinimumChunkWidth());
b.append(", computed-width=");
b.append(text.getComputedWidth());
b.append(", text='");
b.append(text.getRawText());
b.append("'}");
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- cacheSize={x=");
b.append(text.getCachedX());
b.append(", y=");
b.append(text.getCachedY());
b.append(", width=");
b.append(text.getCachedWidth());
b.append(", height=");
b.append(text.getCachedHeight());
b.append('}');
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- nodeLayoutProperties=");
b.append(text.getNodeLayoutProperties());
logger.debug(b.toString());
}
}
|
engine/core/source/org/pentaho/reporting/engine/classic/core/layout/ModelPrinter.java
|
/*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2001 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors.. All rights reserved.
*/
package org.pentaho.reporting.engine.classic.core.layout;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.reporting.engine.classic.core.layout.model.FinishedRenderNode;
import org.pentaho.reporting.engine.classic.core.layout.model.LogicalPageBox;
import org.pentaho.reporting.engine.classic.core.layout.model.ParagraphRenderBox;
import org.pentaho.reporting.engine.classic.core.layout.model.RenderBox;
import org.pentaho.reporting.engine.classic.core.layout.model.RenderNode;
import org.pentaho.reporting.engine.classic.core.layout.model.RenderableText;
import org.pentaho.reporting.engine.classic.core.layout.model.table.TableCellRenderBox;
import org.pentaho.reporting.engine.classic.core.layout.model.table.TableSectionRenderBox;
/**
* Creation-Date: Jan 9, 2007, 2:22:59 PM
*
* @author Thomas Morgner
*/
public class ModelPrinter
{
private static final Log logger = LogFactory.getLog(ModelPrinter.class);
private static final boolean PRINT_LINEBOX_CONTENTS = false;
private ModelPrinter()
{
}
public static void printParents(RenderNode box)
{
while (box != null)
{
final StringBuffer b = new StringBuffer();
b.append(box.getClass().getName());
b.append('[');
b.append(box.getElementType().getClass().getName());
//b.append(Integer.toHexString(System.identityHashCode(box)));
b.append(';');
b.append(box.getName());
b.append(']');
b.append("={stateKey=");
b.append(box.getStateKey());
b.append(", x=");
b.append(box.getX());
b.append(", y=");
b.append(box.getY());
b.append(", width=");
b.append(box.getWidth());
b.append(", height=");
b.append(box.getHeight());
b.append(", min-chunk-width=");
b.append(box.getMinimumChunkWidth());
b.append(", computed-width=");
b.append(box.getComputedWidth());
b.append(", cached-x=");
b.append(box.getCachedX());
b.append(", cached-y=");
b.append(box.getCachedY());
b.append(", cached-width=");
b.append(box.getCachedWidth());
b.append(", cached-height=");
b.append(box.getCachedHeight());
b.append('}');
logger.debug(b);
box = box.getParent();
}
}
public static void print(final RenderBox box)
{
printBox(box, 0);
}
public static void printBox(final RenderBox box, final int level)
{
StringBuffer b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append(box.getClass().getName());
b.append('[');
b.append(box.getElementType().getClass().getName());
//b.append(Integer.toHexString(System.identityHashCode(box)));
b.append(';');
b.append(box.getName());
b.append(']');
b.append("={stateKey=");
b.append(box.getStateKey());
b.append(", pinned=");
b.append(box.getPinned());
b.append('}');
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("-layout x=");
b.append(box.getX());
b.append(", y=");
b.append(box.getY());
b.append(", width=");
b.append(box.getWidth());
b.append(", height=");
b.append(box.getHeight());
b.append(", min-chunk-width=");
b.append(box.getMinimumChunkWidth());
b.append(", computed-width=");
b.append(box.getComputedWidth());
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("-cached-layout cached-x=");
b.append(box.getCachedX());
b.append(", cached-y=");
b.append(box.getCachedY());
b.append(", cached-width=");
b.append(box.getCachedWidth());
b.append(", cached-height=");
b.append(box.getCachedHeight());
b.append(", content-area-x1=");
b.append(box.getContentAreaX1());
b.append(", content-area-x2=");
b.append(box.getContentAreaX2());
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- boxDefinition=");
b.append(box.getBoxDefinition());
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- nodeLayoutProperties=");
b.append(box.getNodeLayoutProperties());
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- staticBoxLayoutProperties=");
b.append(box.getStaticBoxLayoutProperties());
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- breakContext=");
b.append(box.getBreakContext());
logger.debug(b.toString());
if (box instanceof LogicalPageBox)
{
final LogicalPageBox pageBox = (LogicalPageBox) box;
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- PageBox={PageOffset=");
b.append(pageBox.getPageOffset());
b.append(", PageHeight=");
b.append(pageBox.getPageHeight());
b.append(", PageEnd=");
b.append(pageBox.getPageEnd());
b.append(", PageWidth=");
b.append(pageBox.getPageWidth());
b.append('}');
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- PageBreaks={");
b.append(pageBox.getAllVerticalBreaks());
b.append('}');
logger.debug(b.toString());
}
if (box instanceof TableSectionRenderBox)
{
final TableSectionRenderBox pageBox = (TableSectionRenderBox) box;
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- Role: ");
b.append(pageBox.getDisplayRole());
logger.debug(b.toString());
}
if (box instanceof TableCellRenderBox)
{
final TableCellRenderBox pageBox = (TableCellRenderBox) box;
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- Column-Index=");
b.append(pageBox.getColumnIndex());
b.append(", ColSpan=");
b.append(pageBox.getColSpan());
b.append(", RowSpan=");
b.append(pageBox.getRowSpan());
logger.debug(b.toString());
}
if (box.isOpen())
{
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- WARNING: THIS BOX IS STILL OPEN");
logger.debug(b.toString());
}
if (box.isFinishedTable() || box.isFinishedPaginate())
{
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- INFO: THIS BOX IS FINISHED: ");
if (box.isFinishedTable())
{
b.append("- TABLE ");
}
if (box.isFinishedPaginate())
{
b.append("- PAGE ");
}
logger.debug(b.toString());
}
if (box.isCommited())
{
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- INFO: THIS BOX IS COMMITED");
logger.debug(b.toString());
}
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
logger.debug(b.toString());
if (box instanceof ParagraphRenderBox)
{
if (PRINT_LINEBOX_CONTENTS)
{
final ParagraphRenderBox paraBox = (ParagraphRenderBox) box;
logger.debug("---------------- START PARAGRAPH POOL CONTAINER -------------------------------------");
printBox(paraBox.getPool(), level + 1);
logger.debug("---------------- FINISH PARAGRAPH POOL CONTAINER -------------------------------------");
if (paraBox.isComplexParagraph())
{
logger.debug("---------------- START PARAGRAPH LINEBOX CONTAINER -------------------------------------");
printBox(paraBox.getLineboxContainer(), level + 1);
logger.debug("---------------- FINISH PARAGRAPH LINEBOX CONTAINER -------------------------------------");
}
}
}
if (box instanceof LogicalPageBox)
{
final LogicalPageBox lbox = (LogicalPageBox) box;
printBox(lbox.getHeaderArea(), level + 1);
printBox(lbox.getWatermarkArea(), level + 1);
}
printChilds(box, level);
if (box instanceof LogicalPageBox)
{
final LogicalPageBox lbox = (LogicalPageBox) box;
printBox(lbox.getRepeatFooterArea(), level + 1);
printBox(lbox.getFooterArea(), level + 1);
}
}
private static void printChilds(final RenderBox box, final int level)
{
RenderNode childs = box.getFirstChild();
while (childs != null)
{
if (childs instanceof RenderBox)
{
printBox((RenderBox) childs, level + 1);
}
else if (childs instanceof RenderableText)
{
printText((RenderableText) childs, level + 1);
}
else
{
printNode(childs, level + 1);
}
childs = childs.getNext();
}
}
private static void printNode(final RenderNode node, final int level)
{
StringBuffer b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append(node.getClass().getName());
b.append('[');
//b.append(Integer.toHexString(System.identityHashCode(node)));
b.append(']');
b.append("={x=");
b.append(node.getX());
b.append(", y=");
b.append(node.getY());
b.append(", width=");
b.append(node.getWidth());
b.append(", height=");
b.append(node.getHeight());
b.append(", min-chunk-width=");
b.append(node.getMinimumChunkWidth());
b.append(", computed-width=");
b.append(node.getComputedWidth());
if (node instanceof FinishedRenderNode)
{
final FinishedRenderNode fn = (FinishedRenderNode) node;
b.append(", layouted-width=");
b.append(fn.getLayoutedWidth());
b.append(", layouted-height=");
b.append(fn.getLayoutedHeight());
}
b.append('}');
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- cacheSize={x=");
b.append(node.getCachedX());
b.append(", y=");
b.append(node.getCachedY());
b.append(", width=");
b.append(node.getCachedWidth());
b.append(", height=");
b.append(node.getCachedHeight());
b.append('}');
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- nodeLayoutProperties=");
b.append(node.getNodeLayoutProperties());
logger.debug(b.toString());
}
private static void printText(final RenderableText text, final int level)
{
StringBuffer b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("Text");
b.append('[');
//b.append(Integer.toHexString(System.identityHashCode(text)));
b.append(']');
b.append("={x=");
b.append(text.getX());
b.append(", y=");
b.append(text.getY());
b.append(", width=");
b.append(text.getWidth());
b.append(", height=");
b.append(text.getHeight());
b.append(", min-chunk-width=");
b.append(text.getMinimumChunkWidth());
b.append(", computed-width=");
b.append(text.getComputedWidth());
b.append(", text='");
b.append(text.getRawText());
b.append("'}");
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- cacheSize={x=");
b.append(text.getCachedX());
b.append(", y=");
b.append(text.getCachedY());
b.append(", width=");
b.append(text.getCachedWidth());
b.append(", height=");
b.append(text.getCachedHeight());
b.append('}');
logger.debug(b.toString());
b = new StringBuffer();
for (int i = 0; i < level; i++)
{
b.append(" ");
}
b.append("- nodeLayoutProperties=");
b.append(text.getNodeLayoutProperties());
logger.debug(b.toString());
}
}
|
PRD-3857 - Clearer output for model printer (extra line after finished node)
|
engine/core/source/org/pentaho/reporting/engine/classic/core/layout/ModelPrinter.java
|
PRD-3857 - Clearer output for model printer (extra line after finished node)
|
<ide><path>ngine/core/source/org/pentaho/reporting/engine/classic/core/layout/ModelPrinter.java
<ide> b.append("- nodeLayoutProperties=");
<ide> b.append(node.getNodeLayoutProperties());
<ide> logger.debug(b.toString());
<add> logger.debug("");
<ide> }
<ide>
<ide> private static void printText(final RenderableText text, final int level)
|
|
Java
|
apache-2.0
|
810c8b2adb6bd925d103c8e955ae7f1f6b10ff70
| 0 |
carlossg/KubernetesAPIJavaClient
|
/*
*
* 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.github.kubernetes.java.client.exceptions;
import javax.ws.rs.ClientErrorException;
public class KubernetesClientException extends RuntimeException {
private static final long serialVersionUID = -7521673271244696906L;
public KubernetesClientException(String message, Exception exception) {
super(message, exception);
}
public KubernetesClientException(Exception exception) {
super(buildMessage(exception), exception);
}
public KubernetesClientException(String msg) {
super(msg);
}
private static Status getResponse(Throwable exception) {
if (exception instanceof ClientErrorException) {
ClientErrorException error = (ClientErrorException) exception;
return error.getResponse().readEntity(Status.class);
}
return null;
}
private static String buildMessage(Exception exception) {
Status response = getResponse(exception);
return response != null ? response.getMessage() : null;
}
public Status getResponse() {
return getResponse(getCause());
}
}
|
src/main/java/com/github/kubernetes/java/client/exceptions/KubernetesClientException.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.github.kubernetes.java.client.exceptions;
import javax.ws.rs.ClientErrorException;
public class KubernetesClientException extends Exception {
private static final long serialVersionUID = -7521673271244696906L;
public KubernetesClientException(String message, Exception exception) {
super(message, exception);
}
public KubernetesClientException(Exception exception) {
super(buildMessage(exception), exception);
}
public KubernetesClientException(String msg) {
super(msg);
}
private static Status getResponse(Throwable exception) {
if (exception instanceof ClientErrorException) {
ClientErrorException error = (ClientErrorException) exception;
return error.getResponse().readEntity(Status.class);
}
return null;
}
private static String buildMessage(Exception exception) {
Status response = getResponse(exception);
return response != null ? response.getMessage() : null;
}
public Status getResponse() {
return getResponse(getCause());
}
}
|
Make KubernetesClientException a RuntimeException
To avoid having to catch it all the time
|
src/main/java/com/github/kubernetes/java/client/exceptions/KubernetesClientException.java
|
Make KubernetesClientException a RuntimeException
|
<ide><path>rc/main/java/com/github/kubernetes/java/client/exceptions/KubernetesClientException.java
<ide>
<ide> import javax.ws.rs.ClientErrorException;
<ide>
<del>public class KubernetesClientException extends Exception {
<add>public class KubernetesClientException extends RuntimeException {
<ide>
<ide> private static final long serialVersionUID = -7521673271244696906L;
<ide>
|
|
Java
|
apache-2.0
|
ce1251c9304cbf86db27a6335929b8ef332de3e7
| 0 |
jojoejohn/the-app,Rossdar/the-app,ojacques/the-app,luisgtz/the-app,devops-dojo/the-app,ojacques/the-app,ojacques/the-app,ojacques/the-app,Rossdar/the-app,jojoejohn/the-app,luisgtz/the-app,Rossdar/the-app,jojoejohn/the-app,devops-dojo/the-app,Rossdar/the-app,devops-dojo/the-app,ojacques/the-app,Rossdar/the-app,devops-dojo/the-app,luisgtz/the-app,devops-dojo/the-app,Rossdar/the-app,devops-dojo/the-app,jojoejohn/the-app,luisgtz/the-app,jojoejohn/the-app,luisgtz/the-app,luisgtz/the-app,Rossdar/the-app,devops-dojo/the-app,ojacques/the-app,ojacques/the-app,jojoejohn/the-app,luisgtz/the-app,jojoejohn/the-app
|
package io.github.zutherb.appstash.shop.service.cart.impl;
import io.github.zutherb.appstash.shop.service.cart.model.CartItemInfo;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
public abstract class AbstractFulfillmentProvider {
public BigDecimal getTotalSum() {
BigDecimal sum = BigDecimal.ZERO;
for (CartItemInfo cartItemInfo : getAllItems()) {
sum = sum.add(cartItemInfo.getTotalSum());
}
// double fraction = 25/100;
// return sum.subtract(sum.multiply(new BigDecimal(fraction)));
return sum;
}
public BigDecimal getDiscountSum() {
BigDecimal sum = BigDecimal.ZERO;
for (CartItemInfo cartItemInfo : getAllItems()) {
sum = sum.add(cartItemInfo.getTotalSum());
}
double factor = 25/100.0;
double result = sum.doubleValue() * factor;
return new BigDecimal(result);
}
public abstract List<CartItemInfo> getAllItems();
}
|
monolithic/service/cart/src/main/java/io/github/zutherb/appstash/shop/service/cart/impl/AbstractFulfillmentProvider.java
|
package io.github.zutherb.appstash.shop.service.cart.impl;
import io.github.zutherb.appstash.shop.service.cart.model.CartItemInfo;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
public abstract class AbstractFulfillmentProvider {
public BigDecimal getTotalSum() {
BigDecimal sum = BigDecimal.ZERO;
for (CartItemInfo cartItemInfo : getAllItems()) {
sum = sum.add(cartItemInfo.getTotalSum());
}
// double fraction = 25/100;
// return sum.subtract(sum.multiply(new BigDecimal(fraction)));
return sum;
}
public BigDecimal getDiscountSum() {
BigDecimal sum = BigDecimal.ZERO;
for (CartItemInfo cartItemInfo : getAllItems()) {
sum = sum.add(cartItemInfo.getTotalSum());
}
double discountPercent = 25/100;
BigDecimal decimalDiscountPercent = new BigDecimal(Double.toString(discountPercent));
BigDecimal discountAmount = sum.multiply(decimalDiscountPercent);
discountAmount = discountAmount.setScale(2, RoundingMode.HALF_UP);
return discountAmount;
}
public abstract List<CartItemInfo> getAllItems();
}
|
Update AbstractFulfillmentProvider.java
|
monolithic/service/cart/src/main/java/io/github/zutherb/appstash/shop/service/cart/impl/AbstractFulfillmentProvider.java
|
Update AbstractFulfillmentProvider.java
|
<ide><path>onolithic/service/cart/src/main/java/io/github/zutherb/appstash/shop/service/cart/impl/AbstractFulfillmentProvider.java
<ide> for (CartItemInfo cartItemInfo : getAllItems()) {
<ide> sum = sum.add(cartItemInfo.getTotalSum());
<ide> }
<del>
<del> double discountPercent = 25/100;
<del> BigDecimal decimalDiscountPercent = new BigDecimal(Double.toString(discountPercent));
<del> BigDecimal discountAmount = sum.multiply(decimalDiscountPercent);
<del> discountAmount = discountAmount.setScale(2, RoundingMode.HALF_UP);
<del> return discountAmount;
<del>
<add>
<add> double factor = 25/100.0;
<add> double result = sum.doubleValue() * factor;
<add> return new BigDecimal(result);
<ide> }
<ide>
<ide> public abstract List<CartItemInfo> getAllItems();
|
|
JavaScript
|
bsd-3-clause
|
cbe857df075896b30793ea2fd125a2e6280c520e
| 0 |
giros/alloy-ui,giros/alloy-ui,giros/alloy-ui,giros/alloy-ui
|
AUI.add('image-viewer', function(A) {
/*
* ImageViewer
*/
var L = A.Lang,
isBoolean = L.isBoolean,
isNumber = L.isNumber,
isObject = L.isObject,
isString = L.isString,
NodeFx = A.Plugin.NodeFX,
ANIM = 'anim',
ARROW = 'arrow',
ARROW_LEFT_EL = 'arrowLeftEl',
ARROW_RIGHT_EL = 'arrowRightEl',
BD = 'bd',
BLANK = 'blank',
BODY = 'body',
BOUNDING_BOX = 'boundingBox',
CAPTION = 'caption',
CAPTION_EL = 'captionEl',
CAPTION_FROM_TITLE = 'captionFromTitle',
CENTERED = 'centered',
CLOSE = 'close',
CLOSE_EL = 'closeEl',
CREATE_DOCUMENT_FRAGMENT = 'createDocumentFragment',
CURRENT_INDEX = 'currentIndex',
EASE_BOTH_STRONG = 'easeBothStrong',
FOOTER = 'footer',
HELPER = 'helper',
HIDDEN = 'hidden',
HIDE = 'hide',
HREF = 'href',
ICON = 'icon',
IMAGE = 'image',
IMAGE_ANIM = 'imageAnim',
IMAGE_VIEWER = 'image-viewer',
INFO = 'info',
INFO_EL = 'infoEl',
INFO_TEMPLATE = 'infoTemplate',
LEFT = 'left',
LINK = 'link',
LINKS = 'links',
LOADER = 'loader',
LOADING = 'loading',
LOADING_EL = 'loadingEl',
LOCK = 'lock',
LOCK_SCROLL = 'lockScroll',
MODAL = 'modal',
OFFSET_HEIGHT = 'offsetHeight',
OFFSET_WIDTH = 'offsetWidth',
OPACITY = 'opacity',
OVERLAY = 'overlay',
PRELOAD_ALL_IMAGES = 'preloadAllImages',
PRELOAD_NEIGHBOR_IMAGES = 'preloadNeighborImages',
PX = 'px',
RIGHT = 'right',
SCROLL = 'scroll',
SHOW = 'show',
SHOW_ARROWS = 'showArrows',
SHOW_CLOSE = 'showClose',
SPACE = ' ',
SRC = 'src',
TITLE = 'title',
TOP = 'top',
VIEWPORT_REGION = 'viewportRegion',
VISIBLE = 'visible',
OWNER_DOCUMENT = 'ownerDocument',
isNodeList = function(v) {
return (v instanceof A.NodeList);
},
concat = function() {
return Array.prototype.slice.call(arguments).join(SPACE);
},
KEY_ESC = 27,
KEY_RIGHT = 39,
KEY_LEFT = 37,
getCN = A.ClassNameManager.getClassName,
CSS_HELPER_SCROLL_LOCK = getCN(HELPER, SCROLL, LOCK),
CSS_ICON_LOADING = getCN(ICON, LOADING),
CSS_IMAGE_VIEWER_ARROW = getCN(IMAGE_VIEWER, ARROW),
CSS_IMAGE_VIEWER_ARROW_LEFT = getCN(IMAGE_VIEWER, ARROW, LEFT),
CSS_IMAGE_VIEWER_ARROW_RIGHT = getCN(IMAGE_VIEWER, ARROW, RIGHT),
CSS_IMAGE_VIEWER_BD = getCN(IMAGE_VIEWER, BD),
CSS_IMAGE_VIEWER_CAPTION = getCN(IMAGE_VIEWER, CAPTION),
CSS_IMAGE_VIEWER_CLOSE = getCN(IMAGE_VIEWER, CLOSE),
CSS_IMAGE_VIEWER_IMAGE = getCN(IMAGE_VIEWER, IMAGE),
CSS_IMAGE_VIEWER_INFO = getCN(IMAGE_VIEWER, INFO),
CSS_IMAGE_VIEWER_LINK = getCN(IMAGE_VIEWER, LINK),
CSS_OVERLAY_HIDDEN = getCN(OVERLAY, HIDDEN),
INFO_LABEL_TEMPLATE = 'Image {current} of {total}',
TPL_ARROW_LEFT = '<a href="#" class="'+concat(CSS_IMAGE_VIEWER_ARROW, CSS_IMAGE_VIEWER_ARROW_LEFT)+'"></a>',
TPL_ARROW_RIGHT = '<a href="#" class="'+concat(CSS_IMAGE_VIEWER_ARROW, CSS_IMAGE_VIEWER_ARROW_RIGHT)+'"></a>',
TPL_CAPTION = '<div class="' + CSS_IMAGE_VIEWER_CAPTION + '"></div>',
TPL_CLOSE = '<a href="#" class="'+ CSS_IMAGE_VIEWER_CLOSE +'"></a>',
TPL_IMAGE = '<img class="' + CSS_IMAGE_VIEWER_IMAGE + '" />',
TPL_INFO = '<div class="' + CSS_IMAGE_VIEWER_INFO + '"></div>',
TPL_LOADER = '<div class="' + CSS_OVERLAY_HIDDEN + '"></div>',
TPL_LOADING = '<div class="' + CSS_ICON_LOADING + '"></div>';
function ImageViewer(config) {
ImageViewer.superclass.constructor.apply(this, arguments);
}
A.mix(ImageViewer, {
NAME: IMAGE_VIEWER,
ATTRS: {
anim: {
value: true,
validator: isBoolean
},
bodyContent: {
value: SPACE
},
caption: {
value: BLANK,
validator: isString
},
captionFromTitle: {
value: true,
validator: isBoolean
},
centered: {
value: true
},
currentIndex: {
value: 0,
validator: isNumber
},
image: {
readOnly: true,
valueFn: function() {
return A.Node.create(TPL_IMAGE);
}
},
imageAnim: {
value: {},
setter: function(value) {
return A.merge(
{
to: {
opacity: 1
},
easing: EASE_BOTH_STRONG,
duration: .8
},
value
);
},
validator: isObject
},
infoTemplate: {
getter: function(v) {
var instance = this;
var total = instance.get(LINKS).size();
var current = instance.get(CURRENT_INDEX) + 1;
return A.substitute(v, {
current: current,
total: total
});
},
value: INFO_LABEL_TEMPLATE,
validator: isString
},
links: {
setter: function(v) {
var instance = this;
if (isNodeList(v)) {
return v;
}
else if (isString(v)) {
return A.all(v);
}
return new A.NodeList([v]);
}
},
loading: {
value: false,
validator: isBoolean
},
lockScroll: {
value: true,
validator: isBoolean
},
modal: {
value: {
opacity: .8,
background: '#000'
}
},
preloadAllImages: {
value: false,
validator: isBoolean
},
preloadNeighborImages: {
value: true,
validator: isBoolean
},
showClose: {
value: true,
validator: isBoolean
},
showArrows: {
value: true,
validator: isBoolean
},
visible: {
value: false
},
zIndex: {
value: 2000
},
/*
* Static Attrs
*/
arrowLeftEl: {
readOnly: true,
valueFn: function() {
return A.Node.create(TPL_ARROW_LEFT);
}
},
arrowRightEl: {
readOnly: true,
valueFn: function() {
return A.Node.create(TPL_ARROW_RIGHT);
}
},
captionEl: {
readOnly: true,
valueFn: function() {
return A.Node.create(TPL_CAPTION);
}
},
closeEl: {
readOnly: true,
valueFn: function() {
return A.Node.create(TPL_CLOSE);
}
},
infoEl: {
readOnly: true,
valueFn: function() {
return A.Node.create(TPL_INFO);
}
},
loader: {
readOnly: true,
valueFn: function() {
return A.Node.create(TPL_LOADER).appendTo(document.body);
}
},
loadingEl: {
valueFn: function() {
return A.Node.create(TPL_LOADING);
}
}
}
});
A.extend(ImageViewer, A.ComponentOverlay, {
activeImage: 0,
_keyHandler: null,
/*
* Lifecycle
*/
renderUI: function() {
var instance = this;
instance._renderControls();
instance._renderFooter();
instance.get(LINKS).addClass(CSS_IMAGE_VIEWER_LINK);
},
bindUI: function() {
var instance = this;
var links = instance.get(LINKS);
var arrowLeftEl = instance.get(ARROW_LEFT_EL);
var arrowRightEl = instance.get(ARROW_RIGHT_EL);
var closeEl = instance.get(CLOSE_EL);
arrowLeftEl.on('click', A.bind(instance._onClickLeftArrow, instance));
arrowRightEl.on('click', A.bind(instance._onClickRightArrow, instance));
closeEl.on('click', A.bind(instance._onClickCloseEl, instance));
links.on('click', A.bind(instance._onClickLinks, instance));
instance._keyHandler = A.bind(instance._onKeyInteraction, instance);
// NOTE: using keydown to avoid keyCode bug on IE
A.getDoc().on('keydown', instance._keyHandler);
instance.after('render', instance._afterRender);
instance.after('loadingChange', instance._afterLoadingChange);
instance.after('visibleChange', instance._afterVisibleChange);
},
destroy: function() {
var instance = this;
var boundingBox = instance.get(BOUNDING_BOX);
var links = instance.get(LINKS);
instance.close();
links.detach('click');
links.removeClass(CSS_IMAGE_VIEWER_LINK);
// detach key global listener from the document
A.getDoc().detach('keydown', instance._keyHandler);
instance.get(ARROW_LEFT_EL).remove();
instance.get(ARROW_RIGHT_EL).remove();
instance.get(CLOSE_EL).remove();
instance.get(LOADER).remove();
boundingBox.remove();
},
/*
* Methods
*/
close: function() {
var instance = this;
instance.hide();
instance.hideMask();
},
getLink: function(currentIndex) {
var instance = this;
return instance.get(LINKS).item(currentIndex);
},
getCurrentLink: function() {
var instance = this;
return instance.getLink(
instance.get(CURRENT_INDEX)
);
},
loadImage: function(src) {
var instance = this;
var bodyNode = instance.bodyNode;
var loader = instance.get(LOADER);
instance.set(LOADING, true);
// the user could navigate to the next/prev image before the current image onLoad trigger
// detach load event from the activeImage before create the new image placeholder
if (instance.activeImage) {
instance.activeImage.detach('load');
}
// creating the placeholder image
instance.activeImage = instance.get(IMAGE).cloneNode(true);
var image = instance.activeImage;
// append the placeholder image to the loader div
loader.empty();
loader.append(image);
// bind the onLoad handler to the image, this handler should append the loaded image
// to the overlay and take care of all animations
image.on('load', A.bind(instance._onLoadImage, instance));
// set the src of the image to be loaded on the placeholder image
image.attr(SRC, src);
instance.fire('request', { image: image });
},
hasLink: function(currentIndex) {
var instance = this;
return instance.getLink(currentIndex);
},
hasNext: function() {
var instance = this;
return instance.hasLink(
instance.get(CURRENT_INDEX) + 1
);
},
hasPrev: function() {
var instance = this;
return instance.hasLink(
instance.get(CURRENT_INDEX) - 1
);
},
hideControls: function() {
var instance = this;
instance.get(ARROW_LEFT_EL).hide();
instance.get(ARROW_RIGHT_EL).hide();
instance.get(CLOSE_EL).hide();
},
hideMask: function() {
A.ImageViewerMask.hide();
},
lockScroll: function() {
var instance = this;
A.all('body,html').addClass(CSS_HELPER_SCROLL_LOCK);
},
next: function() {
var instance = this;
var currentIndex = instance.get(CURRENT_INDEX);
if (instance.hasNext()) {
instance.set(CURRENT_INDEX, currentIndex + 1);
instance.loadImage(
instance.getCurrentLink().attr(HREF)
);
}
},
preloadAllImages: function() {
var instance = this;
instance.get(LINKS).each(function(link, index) {
instance.preloadImage(index);
});
},
preloadImage: function(currentIndex) {
var instance = this;
var link = instance.getLink(currentIndex);
if (link) {
var src = link.attr(HREF);
instance.get(IMAGE).cloneNode(true).attr(SRC, src);
}
},
prev: function() {
var instance = this;
var currentIndex = instance.get(CURRENT_INDEX);
if (instance.hasPrev()) {
instance.set(CURRENT_INDEX, currentIndex - 1);
instance.loadImage(
instance.getCurrentLink().attr(HREF)
);
}
},
showLoading: function() {
var instance = this;
var bodyNode = instance.bodyNode;
instance.setStdModContent(
BODY,
instance.get(LOADING_EL)
);
},
showMask: function() {
var instance = this;
var modal = instance.get(MODAL);
if (isObject(modal)) {
A.each(modal, function(value, key) {
A.ImageViewerMask.set(key, value);
});
}
if (modal) {
A.ImageViewerMask.show();
}
},
show: function() {
var instance = this;
var currentLink = instance.getCurrentLink();
if (currentLink) {
instance.showMask();
ImageViewer.superclass.show.apply(this, arguments);
instance.loadImage(
currentLink.attr(HREF)
);
}
},
unlockScroll: function() {
var instance = this;
A.all('body,html').removeClass(CSS_HELPER_SCROLL_LOCK);
},
_renderControls: function() {
var instance = this;
var body = A.one(BODY);
body.append(
instance.get(ARROW_LEFT_EL).hide()
);
body.append(
instance.get(ARROW_RIGHT_EL).hide()
);
body.append(
instance.get(CLOSE_EL).hide()
);
},
_renderFooter: function() {
var instance = this;
var boundingBox = instance.get(BOUNDING_BOX);
var docFrag = boundingBox.get(OWNER_DOCUMENT).invoke(CREATE_DOCUMENT_FRAGMENT);
docFrag.append(
instance.get(CAPTION_EL)
);
docFrag.append(
instance.get(INFO_EL)
);
instance.setStdModContent(
FOOTER,
docFrag
);
},
_syncCaptionUI: function() {
var instance = this;
var caption = instance.get(CAPTION);
var captionEl = instance.get(CAPTION_EL);
var captionFromTitle = instance.get(CAPTION_FROM_TITLE);
if (captionFromTitle) {
var currentLink = instance.getCurrentLink();
if (currentLink) {
var title = currentLink.attr(TITLE);
if (title) {
caption = currentLink.attr(TITLE);
}
}
}
captionEl.html(caption);
},
_syncControlsUI: function() {
var instance = this;
var boundingBox = instance.get(BOUNDING_BOX);
var arrowLeftEl = instance.get(ARROW_LEFT_EL);
var arrowRightEl = instance.get(ARROW_RIGHT_EL);
var closeEl = instance.get(CLOSE_EL);
if (instance.get(VISIBLE)) {
if (instance.get(SHOW_ARROWS)) {
// get the viewportRegion to centralize the arrows on the middle of the window viewport
var viewportRegion = boundingBox.get(VIEWPORT_REGION);
var heightRegion = Math.floor(viewportRegion.height/2) + viewportRegion.top;
// show or hide arrows based on the hasPrev/hasNext information
arrowLeftEl[ instance.hasPrev() ? SHOW : HIDE ]();
arrowRightEl[ instance.hasNext() ? SHOW : HIDE ]();
// set style top of the arrows in the middle of the window viewport
arrowLeftEl.setStyle(TOP, heightRegion - arrowLeftEl.get(OFFSET_HEIGHT) + PX);
arrowRightEl.setStyle(TOP, heightRegion - arrowRightEl.get(OFFSET_HEIGHT) + PX);
}
// if SHOW_CLOSE is enables, show close icon
if (instance.get(SHOW_CLOSE)) {
closeEl.show();
}
if (instance.get(LOCK_SCROLL)) {
instance.lockScroll();
}
}
else {
// if the overlay is not visible hide all controls
instance.hideControls();
instance.unlockScroll();
}
},
_syncImageViewerUI: function() {
var instance = this;
instance._syncControlsUI();
instance._syncCaptionUI();
instance._syncInfoUI();
},
_syncInfoUI: function() {
var instance = this;
var infoEl = instance.get(INFO_EL);
infoEl.html(
instance.get(INFO_TEMPLATE)
);
},
/*
* Listeners
*/
_afterRender: function() {
var instance = this;
var bodyNode = instance.bodyNode;
bodyNode.addClass(CSS_IMAGE_VIEWER_BD);
if (instance.get(PRELOAD_ALL_IMAGES)) {
instance.preloadAllImages();
}
},
_afterLoadingChange: function(event) {
var instance = this;
if (event.newVal) {
instance.showLoading();
}
},
_afterVisibleChange: function(event) {
var instance = this;
// invoke A.Overlay _afterVisibleChange method
ImageViewer.superclass._afterVisibleChange.apply(this, arguments)
instance._syncControlsUI();
},
_onClickCloseEl: function(event) {
var instance = this;
instance.close();
event.halt()
},
_onClickLeftArrow: function(event) {
var instance = this;
instance.prev();
event.halt()
},
_onClickRightArrow: function(event) {
var instance = this;
instance.next();
event.halt()
},
_onClickLinks: function(event) {
var instance = this;
var target = event.currentTarget;
// set the current currentIndex of the clicked image
instance.set(
CURRENT_INDEX,
instance.get(LINKS).indexOf(target)
);
instance.show();
event.preventDefault();
},
_onKeyInteraction: function(event) {
var instance = this;
var keyCode = event.keyCode;
if (!instance.get(VISIBLE)) {
return false; // NOTE: return
}
if (keyCode == KEY_LEFT) {
instance.prev();
}
else if (keyCode == KEY_RIGHT) {
instance.next();
}
else if (keyCode == KEY_ESC) {
instance.close();
}
},
_onLoadImage: function(event) {
var instance = this;
var bodyNode = instance.bodyNode;
var image = event.currentTarget;
var offsetHeight = image.get(OFFSET_HEIGHT) + PX;
var offsetWidth = image.get(OFFSET_WIDTH) + PX;
var imageAnim = instance.get(IMAGE_ANIM);
if (instance.get(ANIM)) {
image.setStyle(OPACITY, 0);
// preparing node to the animation, pluging the NodeFX
image.unplug(NodeFx).plug(NodeFx);
image.fx.on('end', function(info) {
instance.fire('anim', { anim: info, image: image });
});
image.fx.setAttrs(imageAnim);
image.fx.stop().run();
}
instance.setStdModContent(BODY, image);
bodyNode.setStyles({
width: offsetWidth,
height: offsetHeight
});
instance._syncImageViewerUI();
instance.set(CENTERED, true);
instance.set(LOADING, false);
instance.fire('load', { image: image });
if (instance.get(PRELOAD_NEIGHBOR_IMAGES)) {
// preload neighbor images
var currentIndex = instance.get(CURRENT_INDEX);
instance.preloadImage(currentIndex + 1);
instance.preloadImage(currentIndex - 1);
}
}
});
A.ImageViewer = ImageViewer;
A.ImageViewerMask = new A.OverlayMask().render();
}, '@VERSION', { requires: [ 'aui-base', 'anim', 'overlay-mask', 'substitute', 'image-viewer-css' ] });
|
src/javascript/image-viewer.js
|
AUI.add('image-viewer', function(A) {
/*
* ImageViewer
*/
var L = A.Lang,
isBoolean = L.isBoolean,
isNumber = L.isNumber,
isObject = L.isObject,
isString = L.isString,
NodeFx = A.Plugin.NodeFX,
ANIM = 'anim',
ARROW = 'arrow',
ARROW_LEFT_EL = 'arrowLeftEl',
ARROW_RIGHT_EL = 'arrowRightEl',
BD = 'bd',
BLANK = 'blank',
BODY = 'body',
BOUNDING_BOX = 'boundingBox',
CAPTION = 'caption',
CAPTION_EL = 'captionEl',
CAPTION_FROM_TITLE = 'captionFromTitle',
CENTERED = 'centered',
CLOSE = 'close',
CLOSE_EL = 'closeEl',
CREATE_DOCUMENT_FRAGMENT = 'createDocumentFragment',
CURRENT_INDEX = 'currentIndex',
EASE_BOTH_STRONG = 'easeBothStrong',
FOOTER = 'footer',
HELPER = 'helper',
HIDDEN = 'hidden',
HIDE = 'hide',
HREF = 'href',
ICON = 'icon',
IMAGE = 'image',
IMAGE_ANIM = 'imageAnim',
IMAGE_VIEWER = 'image-viewer',
INFO = 'info',
INFO_EL = 'infoEl',
INFO_TEMPLATE = 'infoTemplate',
LEFT = 'left',
LINK = 'link',
LINKS = 'links',
LOADER = 'loader',
LOADING = 'loading',
LOADING_EL = 'loadingEl',
LOCK = 'lock',
LOCK_SCROLL = 'lockScroll',
MODAL = 'modal',
OFFSET_HEIGHT = 'offsetHeight',
OFFSET_WIDTH = 'offsetWidth',
OPACITY = 'opacity',
OVERLAY = 'overlay',
PRELOAD_ALL_IMAGES = 'preloadAllImages',
PRELOAD_NEIGHBOR_IMAGES = 'preloadNeighborImages',
PX = 'px',
RIGHT = 'right',
SCROLL = 'scroll',
SHOW = 'show',
SHOW_ARROWS = 'showArrows',
SHOW_CLOSE = 'showClose',
SPACE = ' ',
SRC = 'src',
TITLE = 'title',
TOP = 'top',
VIEWPORT_REGION = 'viewportRegion',
VISIBLE = 'visible',
OWNER_DOCUMENT = 'ownerDocument',
isNodeList = function(v) {
return (v instanceof A.NodeList);
},
concat = function() {
return Array.prototype.slice.call(arguments).join(SPACE);
},
KEY_ESC = 27,
KEY_RIGHT = 39,
KEY_LEFT = 37,
getCN = A.ClassNameManager.getClassName,
CSS_HELPER_SCROLL_LOCK = getCN(HELPER, SCROLL, LOCK),
CSS_ICON_LOADING = getCN(ICON, LOADING),
CSS_IMAGE_VIEWER_ARROW = getCN(IMAGE_VIEWER, ARROW),
CSS_IMAGE_VIEWER_ARROW_LEFT = getCN(IMAGE_VIEWER, ARROW, LEFT),
CSS_IMAGE_VIEWER_ARROW_RIGHT = getCN(IMAGE_VIEWER, ARROW, RIGHT),
CSS_IMAGE_VIEWER_BD = getCN(IMAGE_VIEWER, BD),
CSS_IMAGE_VIEWER_CAPTION = getCN(IMAGE_VIEWER, CAPTION),
CSS_IMAGE_VIEWER_CLOSE = getCN(IMAGE_VIEWER, CLOSE),
CSS_IMAGE_VIEWER_IMAGE = getCN(IMAGE_VIEWER, IMAGE),
CSS_IMAGE_VIEWER_INFO = getCN(IMAGE_VIEWER, INFO),
CSS_IMAGE_VIEWER_LINK = getCN(IMAGE_VIEWER, LINK),
CSS_OVERLAY_HIDDEN = getCN(OVERLAY, HIDDEN),
INFO_LABEL_TEMPLATE = 'Image {current} of {total}',
TPL_ARROW_LEFT = '<a href="#" class="'+concat(CSS_IMAGE_VIEWER_ARROW, CSS_IMAGE_VIEWER_ARROW_LEFT)+'"></a>',
TPL_ARROW_RIGHT = '<a href="#" class="'+concat(CSS_IMAGE_VIEWER_ARROW, CSS_IMAGE_VIEWER_ARROW_RIGHT)+'"></a>',
TPL_CAPTION = '<div class="' + CSS_IMAGE_VIEWER_CAPTION + '"></div>',
TPL_CLOSE = '<a href="#" class="'+ CSS_IMAGE_VIEWER_CLOSE +'"></a>',
TPL_IMAGE = '<img class="' + CSS_IMAGE_VIEWER_IMAGE + '" />',
TPL_INFO = '<div class="' + CSS_IMAGE_VIEWER_INFO + '"></div>',
TPL_LOADER = '<div class="' + CSS_OVERLAY_HIDDEN + '"></div>',
TPL_LOADING = '<div class="' + CSS_ICON_LOADING + '"></div>';
function ImageViewer(config) {
ImageViewer.superclass.constructor.apply(this, arguments);
}
A.mix(ImageViewer, {
NAME: IMAGE_VIEWER,
ATTRS: {
anim: {
value: true,
validator: isBoolean
},
bodyContent: {
value: SPACE
},
caption: {
value: BLANK,
validator: isString
},
captionFromTitle: {
value: true,
validator: isBoolean
},
centered: {
value: true
},
currentIndex: {
value: 0,
validator: isNumber
},
image: {
readyOnly: true,
valueFn: function() {
return A.Node.create(TPL_IMAGE);
}
},
imageAnim: {
value: {},
setter: function(value) {
return A.merge(
{
to: {
opacity: 1
},
easing: EASE_BOTH_STRONG,
duration: .8
},
value
);
},
validator: isObject
},
infoTemplate: {
getter: function(v) {
var instance = this;
var total = instance.get(LINKS).size();
var current = instance.get(CURRENT_INDEX) + 1;
return A.substitute(v, {
current: current,
total: total
});
},
value: INFO_LABEL_TEMPLATE,
validator: isString
},
links: {
setter: function(v) {
var instance = this;
if (isNodeList(v)) {
return v;
}
else if (isString(v)) {
return A.all(v);
}
return new A.NodeList([v]);
}
},
loading: {
value: false,
validator: isBoolean
},
lockScroll: {
value: true,
validator: isBoolean
},
modal: {
value: {
opacity: .8,
background: '#000'
}
},
preloadAllImages: {
value: false,
validator: isBoolean
},
preloadNeighborImages: {
value: true,
validator: isBoolean
},
showClose: {
value: true,
validator: isBoolean
},
showArrows: {
value: true,
validator: isBoolean
},
visible: {
value: false
},
zIndex: {
value: 2000
},
/*
* Static Attrs
*/
arrowLeftEl: {
readyOnly: true,
valueFn: function() {
return A.Node.create(TPL_ARROW_LEFT);
}
},
arrowRightEl: {
readyOnly: true,
valueFn: function() {
return A.Node.create(TPL_ARROW_RIGHT);
}
},
captionEl: {
readyOnly: true,
valueFn: function() {
return A.Node.create(TPL_CAPTION);
}
},
closeEl: {
readyOnly: true,
valueFn: function() {
return A.Node.create(TPL_CLOSE);
}
},
infoEl: {
readyOnly: true,
valueFn: function() {
return A.Node.create(TPL_INFO);
}
},
loader: {
readyOnly: true,
valueFn: function() {
return A.Node.create(TPL_LOADER).appendTo(document.body);
}
},
loadingEl: {
valueFn: function() {
return A.Node.create(TPL_LOADING);
}
}
}
});
A.extend(ImageViewer, A.ComponentOverlay, {
activeImage: 0,
_keyHandler: null,
/*
* Lifecycle
*/
renderUI: function() {
var instance = this;
instance._renderControls();
instance._renderFooter();
instance.get(LINKS).addClass(CSS_IMAGE_VIEWER_LINK);
},
bindUI: function() {
var instance = this;
var links = instance.get(LINKS);
var arrowLeftEl = instance.get(ARROW_LEFT_EL);
var arrowRightEl = instance.get(ARROW_RIGHT_EL);
var closeEl = instance.get(CLOSE_EL);
arrowLeftEl.on('click', A.bind(instance._onClickLeftArrow, instance));
arrowRightEl.on('click', A.bind(instance._onClickRightArrow, instance));
closeEl.on('click', A.bind(instance._onClickCloseEl, instance));
links.on('click', A.bind(instance._onClickLinks, instance));
instance._keyHandler = A.bind(instance._onKeyInteraction, instance);
// NOTE: using keydown to avoid keyCode bug on IE
A.getDoc().on('keydown', instance._keyHandler);
instance.after('render', instance._afterRender);
instance.after('loadingChange', instance._afterLoadingChange);
instance.after('visibleChange', instance._afterVisibleChange);
},
destroy: function() {
var instance = this;
var boundingBox = instance.get(BOUNDING_BOX);
var links = instance.get(LINKS);
instance.close();
links.detach('click');
links.removeClass(CSS_IMAGE_VIEWER_LINK);
// detach key global listener from the document
A.getDoc().detach('keydown', instance._keyHandler);
instance.get(ARROW_LEFT_EL).remove();
instance.get(ARROW_RIGHT_EL).remove();
instance.get(CLOSE_EL).remove();
instance.get(LOADER).remove();
boundingBox.remove();
},
/*
* Methods
*/
close: function() {
var instance = this;
instance.hide();
instance.hideMask();
},
getLink: function(currentIndex) {
var instance = this;
return instance.get(LINKS).item(currentIndex);
},
getCurrentLink: function() {
var instance = this;
return instance.getLink(
instance.get(CURRENT_INDEX)
);
},
loadImage: function(src) {
var instance = this;
var bodyNode = instance.bodyNode;
var loader = instance.get(LOADER);
instance.set(LOADING, true);
// the user could navigate to the next/prev image before the current image onLoad trigger
// detach load event from the activeImage before create the new image placeholder
if (instance.activeImage) {
instance.activeImage.detach('load');
}
// creating the placeholder image
instance.activeImage = instance.get(IMAGE).cloneNode(true);
var image = instance.activeImage;
// append the placeholder image to the loader div
loader.empty();
loader.append(image);
// bind the onLoad handler to the image, this handler should append the loaded image
// to the overlay and take care of all animations
image.on('load', A.bind(instance._onLoadImage, instance));
// set the src of the image to be loaded on the placeholder image
image.attr(SRC, src);
instance.fire('request', { image: image });
},
hasLink: function(currentIndex) {
var instance = this;
return instance.getLink(currentIndex);
},
hasNext: function() {
var instance = this;
return instance.hasLink(
instance.get(CURRENT_INDEX) + 1
);
},
hasPrev: function() {
var instance = this;
return instance.hasLink(
instance.get(CURRENT_INDEX) - 1
);
},
hideControls: function() {
var instance = this;
instance.get(ARROW_LEFT_EL).hide();
instance.get(ARROW_RIGHT_EL).hide();
instance.get(CLOSE_EL).hide();
},
hideMask: function() {
A.ImageViewerMask.hide();
},
lockScroll: function() {
var instance = this;
A.all('body,html').addClass(CSS_HELPER_SCROLL_LOCK);
},
next: function() {
var instance = this;
var currentIndex = instance.get(CURRENT_INDEX);
if (instance.hasNext()) {
instance.set(CURRENT_INDEX, currentIndex + 1);
instance.loadImage(
instance.getCurrentLink().attr(HREF)
);
}
},
preloadAllImages: function() {
var instance = this;
instance.get(LINKS).each(function(link, index) {
instance.preloadImage(index);
});
},
preloadImage: function(currentIndex) {
var instance = this;
var link = instance.getLink(currentIndex);
if (link) {
var src = link.attr(HREF);
instance.get(IMAGE).cloneNode(true).attr(SRC, src);
}
},
prev: function() {
var instance = this;
var currentIndex = instance.get(CURRENT_INDEX);
if (instance.hasPrev()) {
instance.set(CURRENT_INDEX, currentIndex - 1);
instance.loadImage(
instance.getCurrentLink().attr(HREF)
);
}
},
showLoading: function() {
var instance = this;
var bodyNode = instance.bodyNode;
instance.setStdModContent(
BODY,
instance.get(LOADING_EL)
);
},
showMask: function() {
var instance = this;
var modal = instance.get(MODAL);
if (isObject(modal)) {
A.each(modal, function(value, key) {
A.ImageViewerMask.set(key, value);
});
}
if (modal) {
A.ImageViewerMask.show();
}
},
show: function() {
var instance = this;
var currentLink = instance.getCurrentLink();
if (currentLink) {
instance.showMask();
ImageViewer.superclass.show.apply(this, arguments);
instance.loadImage(
currentLink.attr(HREF)
);
}
},
unlockScroll: function() {
var instance = this;
A.all('body,html').removeClass(CSS_HELPER_SCROLL_LOCK);
},
_renderControls: function() {
var instance = this;
var body = A.one(BODY);
body.append(
instance.get(ARROW_LEFT_EL).hide()
);
body.append(
instance.get(ARROW_RIGHT_EL).hide()
);
body.append(
instance.get(CLOSE_EL).hide()
);
},
_renderFooter: function() {
var instance = this;
var boundingBox = instance.get(BOUNDING_BOX);
var docFrag = boundingBox.get(OWNER_DOCUMENT).invoke(CREATE_DOCUMENT_FRAGMENT);
docFrag.append(
instance.get(CAPTION_EL)
);
docFrag.append(
instance.get(INFO_EL)
);
instance.setStdModContent(
FOOTER,
docFrag
);
},
_syncCaptionUI: function() {
var instance = this;
var caption = instance.get(CAPTION);
var captionEl = instance.get(CAPTION_EL);
var captionFromTitle = instance.get(CAPTION_FROM_TITLE);
if (captionFromTitle) {
var currentLink = instance.getCurrentLink();
if (currentLink) {
var title = currentLink.attr(TITLE);
if (title) {
caption = currentLink.attr(TITLE);
}
}
}
captionEl.html(caption);
},
_syncControlsUI: function() {
var instance = this;
var boundingBox = instance.get(BOUNDING_BOX);
var arrowLeftEl = instance.get(ARROW_LEFT_EL);
var arrowRightEl = instance.get(ARROW_RIGHT_EL);
var closeEl = instance.get(CLOSE_EL);
if (instance.get(VISIBLE)) {
if (instance.get(SHOW_ARROWS)) {
// get the viewportRegion to centralize the arrows on the middle of the window viewport
var viewportRegion = boundingBox.get(VIEWPORT_REGION);
var heightRegion = Math.floor(viewportRegion.height/2) + viewportRegion.top;
// show or hide arrows based on the hasPrev/hasNext information
arrowLeftEl[ instance.hasPrev() ? SHOW : HIDE ]();
arrowRightEl[ instance.hasNext() ? SHOW : HIDE ]();
// set style top of the arrows in the middle of the window viewport
arrowLeftEl.setStyle(TOP, heightRegion - arrowLeftEl.get(OFFSET_HEIGHT) + PX);
arrowRightEl.setStyle(TOP, heightRegion - arrowRightEl.get(OFFSET_HEIGHT) + PX);
}
// if SHOW_CLOSE is enables, show close icon
if (instance.get(SHOW_CLOSE)) {
closeEl.show();
}
if (instance.get(LOCK_SCROLL)) {
instance.lockScroll();
}
}
else {
// if the overlay is not visible hide all controls
instance.hideControls();
instance.unlockScroll();
}
},
_syncImageViewerUI: function() {
var instance = this;
instance._syncControlsUI();
instance._syncCaptionUI();
instance._syncInfoUI();
},
_syncInfoUI: function() {
var instance = this;
var infoEl = instance.get(INFO_EL);
infoEl.html(
instance.get(INFO_TEMPLATE)
);
},
/*
* Listeners
*/
_afterRender: function() {
var instance = this;
var bodyNode = instance.bodyNode;
bodyNode.addClass(CSS_IMAGE_VIEWER_BD);
if (instance.get(PRELOAD_ALL_IMAGES)) {
instance.preloadAllImages();
}
},
_afterLoadingChange: function(event) {
var instance = this;
if (event.newVal) {
instance.showLoading();
}
},
_afterVisibleChange: function(event) {
var instance = this;
// invoke A.Overlay _afterVisibleChange method
ImageViewer.superclass._afterVisibleChange.apply(this, arguments)
instance._syncControlsUI();
},
_onClickCloseEl: function(event) {
var instance = this;
instance.close();
event.halt()
},
_onClickLeftArrow: function(event) {
var instance = this;
instance.prev();
event.halt()
},
_onClickRightArrow: function(event) {
var instance = this;
instance.next();
event.halt()
},
_onClickLinks: function(event) {
var instance = this;
var target = event.currentTarget;
// set the current currentIndex of the clicked image
instance.set(
CURRENT_INDEX,
instance.get(LINKS).indexOf(target)
);
instance.show();
event.preventDefault();
},
_onKeyInteraction: function(event) {
var instance = this;
var keyCode = event.keyCode;
if (!instance.get(VISIBLE)) {
return false; // NOTE: return
}
if (keyCode == KEY_LEFT) {
instance.prev();
}
else if (keyCode == KEY_RIGHT) {
instance.next();
}
else if (keyCode == KEY_ESC) {
instance.close();
}
},
_onLoadImage: function(event) {
var instance = this;
var bodyNode = instance.bodyNode;
var image = event.currentTarget;
var offsetHeight = image.get(OFFSET_HEIGHT) + PX;
var offsetWidth = image.get(OFFSET_WIDTH) + PX;
var imageAnim = instance.get(IMAGE_ANIM);
if (instance.get(ANIM)) {
image.setStyle(OPACITY, 0);
// preparing node to the animation, pluging the NodeFX
image.unplug(NodeFx).plug(NodeFx);
image.fx.on('end', function(info) {
instance.fire('anim', { anim: info, image: image });
});
image.fx.setAttrs(imageAnim);
image.fx.stop().run();
}
instance.setStdModContent(BODY, image);
bodyNode.setStyles({
width: offsetWidth,
height: offsetHeight
});
instance._syncImageViewerUI();
instance.set(CENTERED, true);
instance.set(LOADING, false);
instance.fire('load', { image: image });
if (instance.get(PRELOAD_NEIGHBOR_IMAGES)) {
// preload neighbor images
var currentIndex = instance.get(CURRENT_INDEX);
instance.preloadImage(currentIndex + 1);
instance.preloadImage(currentIndex - 1);
}
}
});
A.ImageViewer = ImageViewer;
A.ImageViewerMask = new A.OverlayMask().render();
}, '@VERSION', { requires: [ 'aui-base', 'anim', 'overlay-mask', 'substitute', 'image-viewer-css' ] });
|
Fix typo
git-svn-id: eaac6977d0b6fa3343c402860739874625caf655@40955 05bdf26c-840f-0410-9ced-eb539d925f36
|
src/javascript/image-viewer.js
|
Fix typo
|
<ide><path>rc/javascript/image-viewer.js
<ide> },
<ide>
<ide> image: {
<del> readyOnly: true,
<add> readOnly: true,
<ide> valueFn: function() {
<ide> return A.Node.create(TPL_IMAGE);
<ide> }
<ide> * Static Attrs
<ide> */
<ide> arrowLeftEl: {
<del> readyOnly: true,
<add> readOnly: true,
<ide> valueFn: function() {
<ide> return A.Node.create(TPL_ARROW_LEFT);
<ide> }
<ide> },
<ide>
<ide> arrowRightEl: {
<del> readyOnly: true,
<add> readOnly: true,
<ide> valueFn: function() {
<ide> return A.Node.create(TPL_ARROW_RIGHT);
<ide> }
<ide> },
<ide>
<ide> captionEl: {
<del> readyOnly: true,
<add> readOnly: true,
<ide> valueFn: function() {
<ide> return A.Node.create(TPL_CAPTION);
<ide> }
<ide> },
<ide>
<ide> closeEl: {
<del> readyOnly: true,
<add> readOnly: true,
<ide> valueFn: function() {
<ide> return A.Node.create(TPL_CLOSE);
<ide> }
<ide> },
<ide>
<ide> infoEl: {
<del> readyOnly: true,
<add> readOnly: true,
<ide> valueFn: function() {
<ide> return A.Node.create(TPL_INFO);
<ide> }
<ide> },
<ide>
<ide> loader: {
<del> readyOnly: true,
<add> readOnly: true,
<ide> valueFn: function() {
<ide> return A.Node.create(TPL_LOADER).appendTo(document.body);
<ide> }
|
|
Java
|
apache-2.0
|
22eec4829abf317b50d17d536cd7fdca667225f6
| 0 |
halober/ovirt-engine,eayun/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,halober/ovirt-engine,walteryang47/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,derekhiggins/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,walteryang47/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,derekhiggins/ovirt-engine,derekhiggins/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,yapengsong/ovirt-engine,Dhandapani/gluster-ovirt,Dhandapani/gluster-ovirt,halober/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,yingyun001/ovirt-engine,derekhiggins/ovirt-engine,Dhandapani/gluster-ovirt,Dhandapani/gluster-ovirt,eayun/ovirt-engine,yapengsong/ovirt-engine,halober/ovirt-engine,Dhandapani/gluster-ovirt,zerodengxinchao/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,OpenUniversity/ovirt-engine
|
package org.ovirt.engine.core.config;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.security.InvalidParameterException;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.SubnodeConfiguration;
import org.apache.commons.configuration.tree.ConfigurationNode;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.ovirt.engine.core.config.db.ConfigDAO;
import org.ovirt.engine.core.config.db.ConfigDaoImpl;
import org.ovirt.engine.core.config.entity.ConfigKey;
import org.ovirt.engine.core.config.entity.ConfigKeyFactory;
import org.ovirt.engine.core.config.validation.ConfigActionType;
/**
* The <code>EngineConfigLogic</code> class is responsible for the logic of the EngineConfig tool.
*/
public class EngineConfigLogic {
private final static String ALTERNATE_KEY = "alternateKey";
private final static Logger log = Logger.getLogger(EngineConfigLogic.class);
private Configuration appConfig;
private HierarchicalConfiguration keysConfig;
private Map<String, String> alternateKeysMap;
private ConfigKeyFactory configKeyFactory;
private ConfigDAO configDAO;
private EngineConfigCLIParser parser;
public EngineConfigLogic(EngineConfigCLIParser parser) throws Exception {
this.parser = parser;
init();
}
/**
* Initiates the members of the class.
*
* @throws Exception
*/
private void init() throws Exception {
log.debug("init: beginning initiation of EngineConfigLogic");
appConfig = new AppConfig<PropertiesConfiguration>(parser.getAlternateConfigFile()).getFile();
keysConfig = new KeysConfig<HierarchicalConfiguration>(parser.getAlternatePropertiesFile()).getFile();
populateAlternateKeyMap(keysConfig);
ConfigKeyFactory.init(keysConfig, alternateKeysMap);
configKeyFactory = ConfigKeyFactory.getInstance();
try {
this.configDAO = new ConfigDaoImpl(appConfig);
} catch (SQLException se) {
log.debug("init: caught connection error. Error details: ", se);
throw new ConnectException("Connection to the Database failed. Please check that the hostname and port number are correct and that the Database service is up and running.");
}
}
private void populateAlternateKeyMap(HierarchicalConfiguration config) {
List<SubnodeConfiguration> configurationsAt = config.configurationsAt("/*/" + ALTERNATE_KEY);
alternateKeysMap = new HashMap<String, String>(configurationsAt.size());
for (SubnodeConfiguration node : configurationsAt) {
String rootKey = node.getRootNode()
.getParentNode().getName();
String[] alternateKeys = config.getStringArray("/" + rootKey + "/" + ALTERNATE_KEY);
for (String token : alternateKeys) {
alternateKeysMap.put(token, rootKey);
}
}
}
/**
* Executes desired action. Assumes the parser is now holding valid arguments.
*
* @throws Exception
*/
public void execute() throws Exception {
ConfigActionType actionType = parser.getConfigAction();
log.debug("execute: beginning execution of action " + actionType + ".");
switch (actionType) {
case ACTION_ALL:
printAllValues();
break;
case ACTION_LIST:
printAvailableKeys();
break;
case ACTION_GET:
printKey();
break;
case ACTION_SET:
persistValue();
break;
default: // Should have already been discovered before execute
log.debug("execute: unable to recognize action: " + actionType + ".");
throw new UnsupportedOperationException("Please tell me what to do: list? get? set? get-all?");
}
}
/**
* Prints the values of the given key from the DB.
*
* @throws Exception
*/
private void printAllValuesForKey(String key) throws Exception {
List<ConfigKey> keysForName = getConfigDAO().getKeysForName(key);
if (keysForName.size() == 0) {
log.debug("printKeyValues: failed to fetch key " + key + " value: no such entry with default version.");
throw new RuntimeException("Error fetching " + key + " value: no such entry with default version.");
}
StringBuilder buffer = new StringBuilder();
for (ConfigKey configKey : keysForName) {
buffer.append(String.format("%s: %s version: %s\n",
key,
configKey.getDisplayValue(),
configKey.getVersion())
);
}
buffer.deleteCharAt(buffer.length() - 1);
log.info(buffer);
}
/**
* Prints all configuration values. Is the actual execution of the 'get-all' action ('-a', '--all')
*/
private void printAllValues() {
List<ConfigurationNode> configNodes = keysConfig.getRootNode().getChildren();
for (ConfigurationNode node : configNodes) {
ConfigKey key = configKeyFactory.generateByPropertiesKey(node.getName());
// TODO - move to one statement for all - time permitting;
try {
printAllValuesForKey(key.getKey());
} catch (Exception e) {
log.error("Skipping " + key.getKey() + " due to an error: " + e.getMessage());
log.debug("details:", e);
}
}
}
/**
* Prints all available configuration keys. Is the actual execution of the 'list' action ('-l', '--list')
*/
public void printAvailableKeys() {
List<ConfigurationNode> configNodes = keysConfig.getRootNode().getChildren();
for (ConfigurationNode node : configNodes) {
ConfigKey key = configKeyFactory.generateByPropertiesKey(node.getName());
log.info(MessageFormat.format("{0}: {1} (Value Type: {2})",
key.getKey(),
key.getDescription(),
key.getType()));
}
}
/**
* If a version has been given, prints the specific value for the key and version, otherwise prints all the values
* for the key. Is the actual execution of the 'get' action ('-g', '--get')
* @throws Exception
*/
private void printKey() throws Exception {
String key = parser.getKey();
String version = parser.getVersion();
if (StringUtils.isBlank(version)) {
if (getConfigKey(key) == null) {
throw new RuntimeException("Error fetching " + key
+ " value: no such entry. Please verify key name and property file support.");
}
printAllValuesForKey(key);
} else {
printKeyWithSpecifiedVersion(key, version);
}
}
/**
* Fetches the given key with the given version from the DB and prints it.
*
* @param key
* @param version
* @throws Exception
*/
private void printKeyWithSpecifiedVersion(String key, String version) throws Exception {
ConfigKey configKey = fetchConfigKey(key, version);
if (configKey == null || configKey.getKey() == null) {
log.debug("getValue: error fetching " + key + " value: no such entry with version '" + version + "'.");
throw new RuntimeException("Error fetching " + key + " value: no such entry with version '" + version
+ "'.");
} else {
log.info(configKey.getDisplayValue());
}
}
/**
* Sets the value of the given key for the given version. Is the actual execution of the 'set' action ('-s',
* '--set')
*/
private void persistValue() throws Exception {
String key = parser.getKey();
String value = parser.getValue();
String version = parser.getVersion();
if (version == null) {
version = startVersionDialog(key);
}
boolean sucessUpdate = persist(key, value, version);
if (!sucessUpdate) {
log.debug("setValue: error setting " + key + "'s value. No such entry"
+ (version == null ? "" : " with version " + version) + ".");
throw new IllegalArgumentException("Error setting " + key + "'s value. No such entry"
+ (version == null ? "" : " with version " + version) + ".");
}
}
/**
* Is called when it is unclear which version is desired. If only one version exists for the given key, assumes that
* is the desired version, if more than one exist, prompts the user to choose one.
*
* @param key
* The version needs to be found for this key
* @return A version for the given key
* @throws IOException
* @throws SQLException
*/
private String startVersionDialog(String key) throws IOException, SQLException {
log.debug("starting version dialog.");
String version = null;
List<ConfigKey> keys = configDAO.getKeysForName(key);
if (keys.size() == 1) {
version = keys.get(0).getVersion();
} else if (keys.size() > 1) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Please select a version:");
for (int i = 0; i < keys.size(); i++) {
System.out.println(i + 1 + ". " + keys.get(i).getVersion());
}
int index = 0;
try {
index = Integer.valueOf(br.readLine());
} catch (NumberFormatException e) {
continue;
}
if (index >= 1 && index <= keys.size()) {
version = keys.get(index - 1).getVersion();
break;
}
}
}
return version;
}
/**
* Sets the given key with the given version to the given value. Is protected for test purposes.
*
* @param key
* @param value
* @param version
* @return
* @throws IllegalAccessException
*/
protected boolean persist(String key, String value, String version) throws IllegalAccessException {
ConfigKey configKey = configKeyFactory.generateByPropertiesKey(key);
configKey.setVersion(version);
String message = null;
boolean res = true;
try {
configKey.safeSetValue(value);
res = (getConfigDAO().updateKey(configKey) == 1);
} catch (InvalidParameterException ipe) {
message = (
"'" + value + "' is not a valid value for type " + configKey.getType() + ". " +
(configKey.getValidValues().isEmpty() ? "" : "Valid values are " + configKey.getValidValues())
);
} catch (Exception e) {
message = "Error setting " + key + "'s value. " + e.getMessage();
log.debug("Error details: ", e);
}
if (message != null) {
log.debug(message);
throw new IllegalAccessException(message);
}
return res;
}
public boolean persist(String key, String value) throws Exception {
return persist(key, value, "");
}
private ConfigKey getConfigKey(String key) {
ConfigKey ckReturn = null;
ckReturn = configKeyFactory.generateByPropertiesKey(key);
if (ckReturn == null || ckReturn.getKey() == null) {
ckReturn = null;
log.debug("getConfigKey: Unable to fetch the value of " + key + ".");
}
return ckReturn;
}
public ConfigKey fetchConfigKey(String key, String version) {
ConfigKey configKey = getConfigKey(key);
if (configKey == null || configKey.getKey() == null) {
log.debug("Unable to fetch the value of " + key + " in version " + version);
return null;
}
configKey.setVersion(version);
log.debug("Fetching key=" + configKey.getKey() + " ver=" + version);
try {
return getConfigDAO().getKey(configKey);
} catch (SQLException e) {
return null;
}
}
public ConfigDAO getConfigDAO() {
return configDAO;
}
}
|
backend/manager/tools/engine-config/src/main/java/org/ovirt/engine/core/config/EngineConfigLogic.java
|
package org.ovirt.engine.core.config;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.security.GeneralSecurityException;
import java.security.InvalidParameterException;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.SubnodeConfiguration;
import org.apache.commons.configuration.tree.ConfigurationNode;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.ovirt.engine.core.config.db.ConfigDAO;
import org.ovirt.engine.core.config.db.ConfigDaoImpl;
import org.ovirt.engine.core.config.entity.ConfigKey;
import org.ovirt.engine.core.config.entity.ConfigKeyFactory;
import org.ovirt.engine.core.config.validation.ConfigActionType;
/**
* The <code>EngineConfigLogic</code> class is responsible for the logic of the EngineConfig tool.
*/
public class EngineConfigLogic {
private final static String ALTERNATE_KEY = "alternateKey";
private final static Logger log = Logger.getLogger(EngineConfigLogic.class);
private Configuration appConfig;
private HierarchicalConfiguration keysConfig;
private Map<String, String> alternateKeysMap;
private ConfigKeyFactory configKeyFactory;
private ConfigDAO configDAO;
private EngineConfigCLIParser parser;
public EngineConfigLogic(EngineConfigCLIParser parser) throws Exception {
this.parser = parser;
init();
}
/**
* Initiates the members of the class.
*
* @throws Exception
*/
private void init() throws Exception {
log.debug("init: beginning initiation of EngineConfigLogic");
appConfig = new AppConfig<PropertiesConfiguration>(parser.getAlternateConfigFile()).getFile();
keysConfig = new KeysConfig<HierarchicalConfiguration>(parser.getAlternatePropertiesFile()).getFile();
populateAlternateKeyMap(keysConfig);
ConfigKeyFactory.init(keysConfig, alternateKeysMap);
configKeyFactory = ConfigKeyFactory.getInstance();
try {
this.configDAO = new ConfigDaoImpl(appConfig);
} catch (SQLException se) {
log.debug("init: caught connection error. Error details: ", se);
throw new ConnectException("Connection to the Database failed. Please check that the hostname and port number are correct and that the Database service is up and running.");
}
}
private void populateAlternateKeyMap(HierarchicalConfiguration config) {
List<SubnodeConfiguration> configurationsAt = config.configurationsAt("/*/" + ALTERNATE_KEY);
alternateKeysMap = new HashMap<String, String>(configurationsAt.size());
for (SubnodeConfiguration node : configurationsAt) {
String rootKey = node.getRootNode()
.getParentNode().getName();
String[] alternateKeys = config.getStringArray("/" + rootKey + "/" + ALTERNATE_KEY);
for (String token : alternateKeys) {
alternateKeysMap.put(token, rootKey);
}
}
}
/**
* Executes desired action. Assumes the parser is now holding valid arguments.
*
* @throws Exception
*/
public void execute() throws Exception {
ConfigActionType actionType = parser.getConfigAction();
log.debug("execute: beginning execution of action " + actionType + ".");
switch (actionType) {
case ACTION_ALL:
printAllValues();
break;
case ACTION_LIST:
printAvailableKeys();
break;
case ACTION_GET:
printKey();
break;
case ACTION_SET:
persistValue();
break;
default: // Should have already been discovered before execute
log.debug("execute: unable to recognize action: " + actionType + ".");
throw new UnsupportedOperationException("Please tell me what to do: list? get? set? get-all?");
}
}
/**
* Prints the values of the given key from the DB.
*
* @throws Exception
*/
private void printAllValuesForKey(String key) throws Exception {
List<ConfigKey> keysForName = getConfigDAO().getKeysForName(key);
if (keysForName.size() == 0) {
log.debug("printKeyValues: failed to fetch key " + key + " value: no such entry with default version.");
throw new RuntimeException("Error fetching " + key + " value: no such entry with default version.");
}
StringBuilder buffer = new StringBuilder();
for (ConfigKey configKey : keysForName) {
buffer.append(String.format("%s: %s version: %s\n",
key,
configKey.getDisplayValue(),
configKey.getVersion())
);
}
buffer.deleteCharAt(buffer.length() - 1);
log.info(buffer);
}
/**
* Prints all configuration values. Is the actual execution of the 'get-all' action ('-a', '--all')
*/
private void printAllValues() {
List<ConfigurationNode> configNodes = keysConfig.getRootNode().getChildren();
for (ConfigurationNode node : configNodes) {
ConfigKey key = configKeyFactory.generateByPropertiesKey(node.getName());
// TODO - move to one statement for all - time permitting;
try {
printAllValuesForKey(key.getKey());
} catch (Exception e) {
log.error("Skipping " + key.getKey() + " due to an error: " + e.getMessage());
log.debug("details:", e);
}
}
}
/**
* Prints all available configuration keys. Is the actual execution of the 'list' action ('-l', '--list')
*/
public void printAvailableKeys() {
List<ConfigurationNode> configNodes = keysConfig.getRootNode().getChildren();
for (ConfigurationNode node : configNodes) {
ConfigKey key = configKeyFactory.generateByPropertiesKey(node.getName());
log.info(MessageFormat.format("{0}: {1} (Value Type: {2})",
key.getKey(),
key.getDescription(),
key.getType()));
}
}
/**
* If a version has been given, prints the specific value for the key and version, otherwise prints all the values
* for the key. Is the actual execution of the 'get' action ('-g', '--get')
* @throws Exception
*/
private void printKey() throws Exception {
String key = parser.getKey();
String version = parser.getVersion();
if (StringUtils.isBlank(version)) {
if (getConfigKey(key) == null) {
throw new RuntimeException("Error fetching " + key
+ " value: no such entry. Please verify key name and property file support.");
}
printAllValuesForKey(key);
} else {
printKeyWithSpecifiedVersion(key, version);
}
}
/**
* Fetches the given key with the given version from the DB and prints it.
*
* @param key
* @param version
* @throws Exception
*/
private void printKeyWithSpecifiedVersion(String key, String version) throws Exception {
ConfigKey configKey = fetchConfigKey(key, version);
if (configKey == null || configKey.getKey() == null) {
log.debug("getValue: error fetching " + key + " value: no such entry with version '" + version + "'.");
throw new RuntimeException("Error fetching " + key + " value: no such entry with version '" + version
+ "'.");
} else {
log.info(configKey.getDisplayValue());
}
}
/**
* Sets the value of the given key for the given version. Is the actual execution of the 'set' action ('-s',
* '--set')
*/
private void persistValue() throws Exception {
String key = parser.getKey();
String value = parser.getValue();
String version = parser.getVersion();
if (version == null) {
version = startVersionDialog(key);
}
boolean sucessUpdate = persist(key, value, version);
if (!sucessUpdate) {
log.debug("setValue: error setting " + key + "'s value. No such entry"
+ (version == null ? "" : " with version " + version) + ".");
throw new IllegalArgumentException("Error setting " + key + "'s value. No such entry"
+ (version == null ? "" : " with version " + version) + ".");
}
}
/**
* Is called when it is unclear which version is desired. If only one version exists for the given key, assumes that
* is the desired version, if more than one exist, prompts the user to choose one.
*
* @param key
* The version needs to be found for this key
* @return A version for the given key
* @throws IOException
* @throws SQLException
*/
private String startVersionDialog(String key) throws IOException, SQLException {
log.debug("starting version dialog.");
String version = null;
List<ConfigKey> keys = configDAO.getKeysForName(key);
if (keys.size() == 1) {
version = keys.get(0).getVersion();
} else if (keys.size() > 1) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Please select a version:");
for (int i = 0; i < keys.size(); i++) {
System.out.println(i + 1 + ". " + keys.get(i).getVersion());
}
int index = 0;
try {
index = Integer.valueOf(br.readLine());
} catch (NumberFormatException e) {
continue;
}
if (index >= 1 && index <= keys.size()) {
version = keys.get(index - 1).getVersion();
break;
}
}
}
return version;
}
/**
* Sets the given key with the given version to the given value. Is protected for test purposes.
*
* @param key
* @param value
* @param version
* @return
* @throws IllegalAccessException
*/
protected boolean persist(String key, String value, String version) throws IllegalAccessException {
ConfigKey configKey = configKeyFactory.generateByPropertiesKey(key);
configKey.setVersion(version);
String message = null;
boolean res = true;
try {
configKey.safeSetValue(value);
res = (getConfigDAO().updateKey(configKey) == 1);
} catch (InvalidParameterException ipe) {
message = (
"'" + value + "' is not a valid value for type " + configKey.getType() + ". " +
(configKey.getValidValues().isEmpty() ? "" : "Valid values are " + configKey.getValidValues())
);
} catch (Exception e) {
message = (
"Error setting " + key +
"'s value. No such entry with version '" + version + "'."
);
log.debug("Error details: ", e);
}
if (message != null) {
log.debug(message);
throw new IllegalAccessException(message);
}
return res;
}
public boolean persist(String key, String value) throws Exception {
return persist(key, value, "");
}
private ConfigKey getConfigKey(String key) {
ConfigKey ckReturn = null;
ckReturn = configKeyFactory.generateByPropertiesKey(key);
if (ckReturn == null || ckReturn.getKey() == null) {
ckReturn = null;
log.debug("getConfigKey: Unable to fetch the value of " + key + ".");
}
return ckReturn;
}
public ConfigKey fetchConfigKey(String key, String version) {
ConfigKey configKey = getConfigKey(key);
if (configKey == null || configKey.getKey() == null) {
log.debug("Unable to fetch the value of " + key + " in version " + version);
return null;
}
configKey.setVersion(version);
log.debug("Fetching key=" + configKey.getKey() + " ver=" + version);
try {
return getConfigDAO().getKey(configKey);
} catch (SQLException e) {
return null;
}
}
public ConfigDAO getConfigDAO() {
return configDAO;
}
}
|
engine-config: improvement: report the right error message
Change-Id: Ib49ac372f00ddd6ca559207bf44e7a712eddd7cf
|
backend/manager/tools/engine-config/src/main/java/org/ovirt/engine/core/config/EngineConfigLogic.java
|
engine-config: improvement: report the right error message
|
<ide><path>ackend/manager/tools/engine-config/src/main/java/org/ovirt/engine/core/config/EngineConfigLogic.java
<ide> import java.io.IOException;
<ide> import java.io.InputStreamReader;
<ide> import java.net.ConnectException;
<del>import java.security.GeneralSecurityException;
<ide> import java.security.InvalidParameterException;
<ide> import java.sql.SQLException;
<ide> import java.text.MessageFormat;
<ide>
<ide> /**
<ide> * Prints the values of the given key from the DB.
<del> *
<add> *
<ide> * @throws Exception
<ide> */
<ide> private void printAllValuesForKey(String key) throws Exception {
<ide>
<ide> /**
<ide> * Fetches the given key with the given version from the DB and prints it.
<del> *
<add> *
<ide> * @param key
<ide> * @param version
<ide> * @throws Exception
<ide> (configKey.getValidValues().isEmpty() ? "" : "Valid values are " + configKey.getValidValues())
<ide> );
<ide> } catch (Exception e) {
<del> message = (
<del> "Error setting " + key +
<del> "'s value. No such entry with version '" + version + "'."
<del> );
<add> message = "Error setting " + key + "'s value. " + e.getMessage();
<ide> log.debug("Error details: ", e);
<ide> }
<ide> if (message != null) {
|
|
Java
|
apache-2.0
|
f9333410e38e9c98f7d91d5c73ffae8e49e78ce7
| 0 |
OpenHFT/Chronicle-Network
|
/*
* Copyright 2016-2020 Chronicle Software
*
* https://chronicle.software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.network;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.core.OS;
import net.openhft.chronicle.core.annotation.PackageLocal;
import net.openhft.chronicle.core.io.AbstractCloseable;
import net.openhft.chronicle.core.io.AbstractReferenceCounted;
import net.openhft.chronicle.core.io.Closeable;
import net.openhft.chronicle.core.io.IORuntimeException;
import net.openhft.chronicle.core.tcp.ISocketChannel;
import net.openhft.chronicle.core.threads.EventHandler;
import net.openhft.chronicle.core.threads.HandlerPriority;
import net.openhft.chronicle.core.threads.InvalidEventHandlerException;
import net.openhft.chronicle.network.api.TcpHandler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ClosedChannelException;
import java.util.concurrent.atomic.AtomicBoolean;
import static java.lang.Math.max;
import static net.openhft.chronicle.network.connection.TcpChannelHub.TCP_BUFFER;
public class TcpEventHandler<T extends NetworkContext<T>> extends AbstractCloseable implements EventHandler, TcpEventHandlerManager<T> {
private static final int MONITOR_POLL_EVERY_SEC = Integer.getInteger("tcp.event.monitor.secs", 10);
private static final long NBR_WARNING_NANOS = Long.getLong("tcp.nbr.warning.nanos", 2_000_000);
private static final long NBW_WARNING_NANOS = Long.getLong("tcp.nbw.warning.nanos", 2_000_000);
private static final Logger LOG = LoggerFactory.getLogger(TcpEventHandler.class);
private static final AtomicBoolean FIRST_HANDLER = new AtomicBoolean();
public static final int TARGET_WRITE_SIZE = Integer.getInteger("TcpEventHandler.targetWriteSize", 1024);
private static final int DEFAULT_MAX_MESSAGE_SIZE = 1 << 30;
public static boolean DISABLE_TCP_NODELAY = Jvm.getBoolean("disable.tcp_nodelay");
static {
if (DISABLE_TCP_NODELAY) System.out.println("tcpNoDelay disabled");
}
private TcpEventHandler.SocketReader reader = new DefaultSocketReader();
@NotNull
private final ISocketChannel sc;
private final String scToString;
@NotNull
private final T nc;
@NotNull
private final NetworkLog readLog, writeLog;
@NotNull
private final Bytes<ByteBuffer> inBBB;
@NotNull
private final Bytes<ByteBuffer> outBBB;
private final boolean fair;
private final boolean nbWarningEnabled;
private int oneInTen;
@Nullable
private volatile TcpHandler<T> tcpHandler;
private long lastTickReadTime = System.currentTimeMillis();
// monitoring
private int socketPollCount;
private long bytesReadCount;
private long bytesWriteCount;
private long lastMonitor;
public TcpEventHandler(@NotNull final T nc) {
this(nc, false);
}
public TcpEventHandler(@NotNull final T nc, final boolean fair) {
this.sc = ISocketChannel.wrapUnsafe(nc.socketChannel());
this.scToString = sc.toString();
this.nc = nc;
this.fair = fair;
try {
sc.configureBlocking(false);
Socket sock = sc.socket();
// TODO: should have a strategy for this like ConnectionNotifier
if (!DISABLE_TCP_NODELAY)
sock.setTcpNoDelay(true);
if (TCP_BUFFER >= 64 << 10) {
sock.setReceiveBufferSize(TCP_BUFFER);
sock.setSendBufferSize(TCP_BUFFER);
checkBufSize(sock.getReceiveBufferSize(), "recv");
checkBufSize(sock.getSendBufferSize(), "send");
}
} catch (IOException e) {
if (isClosed() || !sc.isOpen())
throw new IORuntimeException(e);
Jvm.warn().on(getClass(), e);
}
//We have to provide back pressure to restrict the buffer growing beyond,2GB because it reverts to
// being Native bytes, we should also provide back pressure if we are not able to keep up
inBBB = Bytes.elasticByteBuffer(TCP_BUFFER + OS.pageSize(), max(TCP_BUFFER + OS.pageSize(), DEFAULT_MAX_MESSAGE_SIZE));
outBBB = Bytes.elasticByteBuffer(TCP_BUFFER, max(TCP_BUFFER, DEFAULT_MAX_MESSAGE_SIZE));
// TODO Fix Chronicle-Queue-Enterprise tests so socket connections are closed cleanly.
AbstractReferenceCounted.unmonitor(inBBB);
AbstractReferenceCounted.unmonitor(outBBB);
// must be set after we take a slice();
outBBB.underlyingObject().limit(0);
readLog = new NetworkLog(this.sc, "read");
writeLog = new NetworkLog(this.sc, "write");
nbWarningEnabled = Jvm.warn().isEnabled(getClass());
if (FIRST_HANDLER.compareAndSet(false, true))
warmUp();
}
public void reader(@NotNull final TcpEventHandler.SocketReader reader) {
this.reader = reader;
}
@Override
public synchronized boolean action() throws InvalidEventHandlerException {
Jvm.optionalSafepoint();
if (isClosed())
throw new InvalidEventHandlerException();
if (tcpHandler == null)
return false;
if (!sc.isOpen()) {
tcpHandler.onEndOfConnection(false);
Closeable.closeQuietly(nc);
throw new InvalidEventHandlerException("socket is closed");
}
socketPollCount++;
boolean busy = false;
if (fair || oneInTen++ >= 8) {
oneInTen = 0;
try {
busy = writeAction();
} catch (Exception e) {
Jvm.warn().on(getClass(), e);
}
}
try {
ByteBuffer inBB = inBBB.underlyingObject();
int start = inBB.position();
assert !sc.isBlocking();
long time0 = System.nanoTime();
int read = inBB.remaining() > 0 ? reader.read(sc, inBBB) : Integer.MAX_VALUE;
// int read = inBB.remaining() > 0 ? sc.read(inBB) : Integer.MAX_VALUE;
long time1 = System.nanoTime() - time0;
if (nbWarningEnabled && time1 > NBR_WARNING_NANOS)
Jvm.warn().on(getClass(), "Non blocking read took " + time1 / 1000 + " us.");
if (read == Integer.MAX_VALUE)
onInBBFul();
if (read > 0) {
WanSimulator.dataRead(read);
tcpHandler.onReadTime(System.nanoTime(), inBB, start, inBB.position());
lastTickReadTime = System.currentTimeMillis();
readLog.log(inBB, start, inBB.position());
if (invokeHandler())
oneInTen++;
busy = true;
} else if (read == 0) {
if (outBBB.readRemaining() > 0) {
busy |= invokeHandler();
}
// check for timeout only here - in other branches we either just read something or are about to close socket anyway
if (nc.heartbeatTimeoutMs() > 0) {
long tickTime = System.currentTimeMillis();
if (tickTime > lastTickReadTime + nc.heartbeatTimeoutMs()) {
final HeartbeatListener heartbeatListener = nc.heartbeatListener();
if (heartbeatListener != null && heartbeatListener.onMissedHeartbeat()) {
// implementer tries to recover - do not disconnect for some time
lastTickReadTime += heartbeatListener.lingerTimeBeforeDisconnect();
} else {
tcpHandler.onEndOfConnection(true);
close();
throw new InvalidEventHandlerException("heartbeat timeout");
}
}
}
if (!busy)
monitorStats();
} else {
// read == -1, socketChannel has reached end-of-stream
close();
throw new InvalidEventHandlerException("socket closed " + sc);
}
return busy;
} catch (ClosedChannelException e) {
close();
throw new InvalidEventHandlerException(e);
} catch (IOException e) {
close();
handleIOE(e, tcpHandler.hasClientClosed(), nc.heartbeatListener());
throw new InvalidEventHandlerException();
} catch (InvalidEventHandlerException e) {
close();
throw e;
} catch (Exception e) {
close();
Jvm.warn().on(getClass(), "", e);
throw new InvalidEventHandlerException(e);
}
}
@Override
public String toString() {
return "TcpEventHandler{" +
"sc=" + scToString + ", " +
"tcpHandler=" + tcpHandler + ", " +
"closed=" + isClosed() +
'}';
}
public void warmUp() {
System.out.println(TcpEventHandler.class.getSimpleName() + " - Warming up...");
int runs = 12000;
long start = System.nanoTime();
for (int i = 0; i < runs; i++) {
inBBB.readPositionRemaining(8, 1024);
compactBuffer();
clearBuffer();
}
long time = System.nanoTime() - start;
System.out.println(TcpEventHandler.class.getSimpleName() + " - ... warmed up - took " + (time / runs / 1e3) + " us avg");
}
private void checkBufSize(int bufSize, String name) {
if (bufSize < TCP_BUFFER) {
LOG.warn("Attempted to set " + name + " tcp buffer to " + TCP_BUFFER + " but kernel only allowed " + bufSize);
}
}
public ISocketChannel socketChannel() {
return sc;
}
@NotNull
@Override
public HandlerPriority priority() {
ServerThreadingStrategy sts = nc.serverThreadingStrategy();
switch (sts) {
case SINGLE_THREADED:
return singleThreadedPriority();
case CONCURRENT:
return HandlerPriority.CONCURRENT;
default:
throw new UnsupportedOperationException("todo");
}
}
@NotNull
public HandlerPriority singleThreadedPriority() {
return HandlerPriority.MEDIUM;
}
@Nullable
public TcpHandler<T> tcpHandler() {
return tcpHandler;
}
@Override
public void tcpHandler(TcpHandler<T> tcpHandler) {
nc.onHandlerChanged(tcpHandler);
this.tcpHandler = tcpHandler;
}
@FunctionalInterface
public interface SocketReader {
/**
* Reads content from the provided {@code socketChannel} into the provided {@code bytes}.
*
* @param socketChannel to read from
* @param bytes to which content from the {@code socketChannel} is put
* @return the number of bytes read from the provided {@code socketChannel}.
* @throws IOException if there is a problem reading form the provided {@code socketChannel}.
*/
int read(@NotNull ISocketChannel socketChannel, @NotNull Bytes<ByteBuffer> bytes) throws IOException;
}
public static final class DefaultSocketReader implements SocketReader {
@Override
public int read(@NotNull final ISocketChannel socketChannel, @NotNull final Bytes<ByteBuffer> bytes) throws IOException {
return socketChannel.read(bytes.underlyingObject());
}
}
@Override
public void loopFinished() {
// Release unless already released
if (inBBB.refCount() > 0)
inBBB.releaseLast();
if (outBBB.refCount() > 0)
outBBB.releaseLast();
}
public void onInBBFul() {
LOG.trace("inBB is full, can't read from socketChannel");
}
private void monitorStats() {
// TODO: consider installing this on EventLoop using Timer
long now = System.currentTimeMillis();
if (now > lastMonitor + (MONITOR_POLL_EVERY_SEC * 1000)) {
final NetworkStatsListener<T> networkStatsListener = nc.networkStatsListener();
if (networkStatsListener != null) {
if (lastMonitor == 0) {
networkStatsListener.onNetworkStats(0, 0, 0);
} else {
networkStatsListener.onNetworkStats(
bytesWriteCount / MONITOR_POLL_EVERY_SEC,
bytesReadCount / MONITOR_POLL_EVERY_SEC,
socketPollCount / MONITOR_POLL_EVERY_SEC);
bytesWriteCount = bytesReadCount = socketPollCount = 0;
}
}
lastMonitor = now;
}
}
@PackageLocal
boolean invokeHandler() throws IOException {
Jvm.optionalSafepoint();
boolean busy = false;
final int position = inBBB.underlyingObject().position();
inBBB.readLimit(position);
outBBB.writePosition(outBBB.underlyingObject().limit());
long lastInBBBReadPosition;
do {
lastInBBBReadPosition = inBBB.readPosition();
tcpHandler.process(inBBB, outBBB, nc);
bytesReadCount += (inBBB.readPosition() - lastInBBBReadPosition);
// process method might change the underlying ByteBuffer by resizing it.
ByteBuffer outBB = outBBB.underlyingObject();
// did it write something?
int wpBBB = Maths.toUInt31(outBBB.writePosition());
int length = wpBBB - outBB.limit();
if (length >= TARGET_WRITE_SIZE) {
outBB.limit(wpBBB);
boolean busy2 = tryWrite(outBB);
if (busy2)
busy = busy2;
else
break;
}
} while (lastInBBBReadPosition != inBBB.readPosition());
ByteBuffer outBB = outBBB.underlyingObject();
if (outBBB.writePosition() > outBB.limit() || outBBB.writePosition() >= 4) {
outBB.limit(Maths.toInt32(outBBB.writePosition()));
busy |= tryWrite(outBB);
}
Jvm.optionalSafepoint();
if (inBBB.readRemaining() == 0) {
clearBuffer();
} else if (inBBB.readPosition() > TCP_BUFFER / 4) {
compactBuffer();
busy = true;
}
return busy;
}
private void clearBuffer() {
inBBB.clear();
@Nullable ByteBuffer inBB = inBBB.underlyingObject();
inBB.clear();
}
private void compactBuffer() {
// if it read some data compact();
@Nullable ByteBuffer inBB = inBBB.underlyingObject();
inBB.position((int) inBBB.readPosition());
inBB.limit((int) inBBB.readLimit());
Jvm.optionalSafepoint();
inBB.compact();
Jvm.optionalSafepoint();
inBBB.readPosition(0);
inBBB.readLimit(inBB.remaining());
}
private void handleIOE(@NotNull IOException e, final boolean clientIntentionallyClosed,
@Nullable HeartbeatListener heartbeatListener) {
try {
if (clientIntentionallyClosed)
return;
if (e.getMessage() != null && e.getMessage().startsWith("Connection reset by peer"))
LOG.trace(e.getMessage(), e);
else if (e.getMessage() != null && e.getMessage().startsWith("An existing connection " +
"was forcibly closed"))
Jvm.debug().on(getClass(), e.getMessage());
else if (!(e instanceof ClosedByInterruptException))
Jvm.warn().on(getClass(), "", e);
// The remote server has sent you a RST packet, which indicates an immediate dropping of the connection,
// rather than the usual handshake. This bypasses the normal half-closed state transition.
// I like this description: "Connection reset by peer" is the TCP/IP equivalent
// of slamming the phone back on the hook.
if (heartbeatListener != null)
heartbeatListener.onMissedHeartbeat();
} finally {
close();
}
}
@Override
protected void performClose() {
// NOTE Do not release buffers here as they might be in use. loopFinished() releases them and
// is called from event loop when it knows that the thread calling "action" is done
Closeable.closeQuietly(tcpHandler);
Closeable.closeQuietly(this.nc.networkStatsListener());
Closeable.closeQuietly(sc);
Closeable.closeQuietly(nc);
}
@PackageLocal
boolean tryWrite(ByteBuffer outBB) throws IOException {
if (outBB.remaining() <= 0)
return false;
int start = outBB.position();
long writeTime = System.nanoTime();
assert !sc.isBlocking();
int wrote = sc.write(outBB);
long time1 = System.nanoTime() - writeTime;
if (nbWarningEnabled && time1 > NBW_WARNING_NANOS)
Jvm.warn().on(getClass(), "Non blocking write took " + time1 / 1000 + " us.");
tcpHandler.onWriteTime(writeTime, outBB, start, outBB.position());
bytesWriteCount += (outBB.position() - start);
writeLog.log(outBB, start, outBB.position());
if (wrote < 0) {
close();
} else if (wrote > 0) {
outBB.compact().flip();
outBBB.writePosition(outBB.limit());
return true;
}
return false;
}
public static class Factory<T extends NetworkContext<T>> implements MarshallableFunction<T, TcpEventHandler<T>> {
public Factory() {
}
@NotNull
@Override
public TcpEventHandler<T> apply(@NotNull T nc) {
return new TcpEventHandler<T>(nc);
}
}
public boolean writeAction() {
Jvm.optionalSafepoint();
boolean busy = false;
try {
// get more data to write if the buffer was empty
// or we can write some of what is there
ByteBuffer outBB = outBBB.underlyingObject();
int remaining = outBB.remaining();
busy = remaining > 0;
if (busy)
tryWrite(outBB);
// has the remaining changed, i.e. did it write anything?
if (outBB.remaining() == remaining) {
busy |= invokeHandler();
if (!busy)
busy = tryWrite(outBB);
}
} catch (ClosedChannelException cce) {
close();
} catch (IOException e) {
if (!isClosed())
handleIOE(e, tcpHandler.hasClientClosed(), nc.heartbeatListener());
}
return busy;
}
}
|
src/main/java/net/openhft/chronicle/network/TcpEventHandler.java
|
/*
* Copyright 2016-2020 Chronicle Software
*
* https://chronicle.software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.network;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.core.OS;
import net.openhft.chronicle.core.annotation.PackageLocal;
import net.openhft.chronicle.core.io.AbstractCloseable;
import net.openhft.chronicle.core.io.AbstractReferenceCounted;
import net.openhft.chronicle.core.io.Closeable;
import net.openhft.chronicle.core.io.IORuntimeException;
import net.openhft.chronicle.core.tcp.ISocketChannel;
import net.openhft.chronicle.core.threads.EventHandler;
import net.openhft.chronicle.core.threads.HandlerPriority;
import net.openhft.chronicle.core.threads.InvalidEventHandlerException;
import net.openhft.chronicle.network.api.TcpHandler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ClosedChannelException;
import java.util.concurrent.atomic.AtomicBoolean;
import static java.lang.Math.max;
import static net.openhft.chronicle.network.connection.TcpChannelHub.TCP_BUFFER;
public class TcpEventHandler<T extends NetworkContext<T>> extends AbstractCloseable implements EventHandler, TcpEventHandlerManager<T> {
private static final int MONITOR_POLL_EVERY_SEC = Integer.getInteger("tcp.event.monitor.secs", 10);
private static final long NBR_WARNING_NANOS = Long.getLong("tcp.nbr.warning.nanos", 2_000_000);
private static final long NBW_WARNING_NANOS = Long.getLong("tcp.nbw.warning.nanos", 2_000_000);
private static final Logger LOG = LoggerFactory.getLogger(TcpEventHandler.class);
private static final AtomicBoolean FIRST_HANDLER = new AtomicBoolean();
public static final int TARGET_WRITE_SIZE = Integer.getInteger("TcpEventHandler.targetWriteSize", 1024);
private static final int DEFAULT_MAX_MESSAGE_SIZE = 1 << 30;
public static boolean DISABLE_TCP_NODELAY = Jvm.getBoolean("disable.tcp_nodelay");
static {
if (DISABLE_TCP_NODELAY) System.out.println("tcpNoDelay disabled");
}
private TcpEventHandler.SocketReader reader = new DefaultSocketReader();
@NotNull
private final ISocketChannel sc;
private final String scToString;
@NotNull
private final T nc;
@NotNull
private final NetworkLog readLog, writeLog;
@NotNull
private final Bytes<ByteBuffer> inBBB;
@NotNull
private final Bytes<ByteBuffer> outBBB;
private final boolean fair;
private int oneInTen;
@Nullable
private volatile TcpHandler<T> tcpHandler;
private long lastTickReadTime = System.currentTimeMillis();
// monitoring
private int socketPollCount;
private long bytesReadCount;
private long bytesWriteCount;
private long lastMonitor;
public TcpEventHandler(@NotNull final T nc) {
this(nc, false);
}
public TcpEventHandler(@NotNull final T nc, final boolean fair) {
this.sc = ISocketChannel.wrapUnsafe(nc.socketChannel());
this.scToString = sc.toString();
this.nc = nc;
this.fair = fair;
try {
sc.configureBlocking(false);
Socket sock = sc.socket();
// TODO: should have a strategy for this like ConnectionNotifier
if (!DISABLE_TCP_NODELAY)
sock.setTcpNoDelay(true);
if (TCP_BUFFER >= 64 << 10) {
sock.setReceiveBufferSize(TCP_BUFFER);
sock.setSendBufferSize(TCP_BUFFER);
checkBufSize(sock.getReceiveBufferSize(), "recv");
checkBufSize(sock.getSendBufferSize(), "send");
}
} catch (IOException e) {
if (isClosed() || !sc.isOpen())
throw new IORuntimeException(e);
Jvm.warn().on(getClass(), e);
}
//We have to provide back pressure to restrict the buffer growing beyond,2GB because it reverts to
// being Native bytes, we should also provide back pressure if we are not able to keep up
inBBB = Bytes.elasticByteBuffer(TCP_BUFFER + OS.pageSize(), max(TCP_BUFFER + OS.pageSize(), DEFAULT_MAX_MESSAGE_SIZE));
outBBB = Bytes.elasticByteBuffer(TCP_BUFFER, max(TCP_BUFFER, DEFAULT_MAX_MESSAGE_SIZE));
// TODO Fix Chronicle-Queue-Enterprise tests so socket connections are closed cleanly.
AbstractReferenceCounted.unmonitor(inBBB);
AbstractReferenceCounted.unmonitor(outBBB);
// must be set after we take a slice();
outBBB.underlyingObject().limit(0);
readLog = new NetworkLog(this.sc, "read");
writeLog = new NetworkLog(this.sc, "write");
if (FIRST_HANDLER.compareAndSet(false, true))
warmUp();
}
public void reader(@NotNull final TcpEventHandler.SocketReader reader) {
this.reader = reader;
}
@Override
public synchronized boolean action() throws InvalidEventHandlerException {
Jvm.optionalSafepoint();
if (isClosed())
throw new InvalidEventHandlerException();
if (tcpHandler == null)
return false;
if (!sc.isOpen()) {
tcpHandler.onEndOfConnection(false);
Closeable.closeQuietly(nc);
throw new InvalidEventHandlerException("socket is closed");
}
socketPollCount++;
boolean busy = false;
if (fair || oneInTen++ >= 8) {
oneInTen = 0;
try {
busy = writeAction();
} catch (Exception e) {
Jvm.warn().on(getClass(), e);
}
}
try {
ByteBuffer inBB = inBBB.underlyingObject();
int start = inBB.position();
assert !sc.isBlocking();
long time0 = System.nanoTime();
int read = inBB.remaining() > 0 ? reader.read(sc, inBBB) : Integer.MAX_VALUE;
// int read = inBB.remaining() > 0 ? sc.read(inBB) : Integer.MAX_VALUE;
long time1 = System.nanoTime() - time0;
if (time1 > NBR_WARNING_NANOS)
Jvm.warn().on(getClass(), "Non blocking read took " + time1 / 1000 + " us.");
if (read == Integer.MAX_VALUE)
onInBBFul();
if (read > 0) {
WanSimulator.dataRead(read);
tcpHandler.onReadTime(System.nanoTime(), inBB, start, inBB.position());
lastTickReadTime = System.currentTimeMillis();
readLog.log(inBB, start, inBB.position());
if (invokeHandler())
oneInTen++;
busy = true;
} else if (read == 0) {
if (outBBB.readRemaining() > 0) {
busy |= invokeHandler();
}
// check for timeout only here - in other branches we either just read something or are about to close socket anyway
if (nc.heartbeatTimeoutMs() > 0) {
long tickTime = System.currentTimeMillis();
if (tickTime > lastTickReadTime + nc.heartbeatTimeoutMs()) {
final HeartbeatListener heartbeatListener = nc.heartbeatListener();
if (heartbeatListener != null && heartbeatListener.onMissedHeartbeat()) {
// implementer tries to recover - do not disconnect for some time
lastTickReadTime += heartbeatListener.lingerTimeBeforeDisconnect();
} else {
tcpHandler.onEndOfConnection(true);
close();
throw new InvalidEventHandlerException("heartbeat timeout");
}
}
}
if (!busy)
monitorStats();
} else {
// read == -1, socketChannel has reached end-of-stream
close();
throw new InvalidEventHandlerException("socket closed " + sc);
}
return busy;
} catch (ClosedChannelException e) {
close();
throw new InvalidEventHandlerException(e);
} catch (IOException e) {
close();
handleIOE(e, tcpHandler.hasClientClosed(), nc.heartbeatListener());
throw new InvalidEventHandlerException();
} catch (InvalidEventHandlerException e) {
close();
throw e;
} catch (Exception e) {
close();
Jvm.warn().on(getClass(), "", e);
throw new InvalidEventHandlerException(e);
}
}
@Override
public String toString() {
return "TcpEventHandler{" +
"sc=" + scToString + ", " +
"tcpHandler=" + tcpHandler + ", " +
"closed=" + isClosed() +
'}';
}
public void warmUp() {
System.out.println(TcpEventHandler.class.getSimpleName() + " - Warming up...");
int runs = 12000;
long start = System.nanoTime();
for (int i = 0; i < runs; i++) {
inBBB.readPositionRemaining(8, 1024);
compactBuffer();
clearBuffer();
}
long time = System.nanoTime() - start;
System.out.println(TcpEventHandler.class.getSimpleName() + " - ... warmed up - took " + (time / runs / 1e3) + " us avg");
}
private void checkBufSize(int bufSize, String name) {
if (bufSize < TCP_BUFFER) {
LOG.warn("Attempted to set " + name + " tcp buffer to " + TCP_BUFFER + " but kernel only allowed " + bufSize);
}
}
public ISocketChannel socketChannel() {
return sc;
}
@NotNull
@Override
public HandlerPriority priority() {
ServerThreadingStrategy sts = nc.serverThreadingStrategy();
switch (sts) {
case SINGLE_THREADED:
return singleThreadedPriority();
case CONCURRENT:
return HandlerPriority.CONCURRENT;
default:
throw new UnsupportedOperationException("todo");
}
}
@NotNull
public HandlerPriority singleThreadedPriority() {
return HandlerPriority.MEDIUM;
}
@Nullable
public TcpHandler<T> tcpHandler() {
return tcpHandler;
}
@Override
public void tcpHandler(TcpHandler<T> tcpHandler) {
nc.onHandlerChanged(tcpHandler);
this.tcpHandler = tcpHandler;
}
@FunctionalInterface
public interface SocketReader {
/**
* Reads content from the provided {@code socketChannel} into the provided {@code bytes}.
*
* @param socketChannel to read from
* @param bytes to which content from the {@code socketChannel} is put
* @return the number of bytes read from the provided {@code socketChannel}.
* @throws IOException if there is a problem reading form the provided {@code socketChannel}.
*/
int read(@NotNull ISocketChannel socketChannel, @NotNull Bytes<ByteBuffer> bytes) throws IOException;
}
public static final class DefaultSocketReader implements SocketReader {
@Override
public int read(@NotNull final ISocketChannel socketChannel, @NotNull final Bytes<ByteBuffer> bytes) throws IOException {
return socketChannel.read(bytes.underlyingObject());
}
}
@Override
public void loopFinished() {
// Release unless already released
if (inBBB.refCount() > 0)
inBBB.releaseLast();
if (outBBB.refCount() > 0)
outBBB.releaseLast();
}
public void onInBBFul() {
LOG.trace("inBB is full, can't read from socketChannel");
}
private void monitorStats() {
// TODO: consider installing this on EventLoop using Timer
long now = System.currentTimeMillis();
if (now > lastMonitor + (MONITOR_POLL_EVERY_SEC * 1000)) {
final NetworkStatsListener<T> networkStatsListener = nc.networkStatsListener();
if (networkStatsListener != null) {
if (lastMonitor == 0) {
networkStatsListener.onNetworkStats(0, 0, 0);
} else {
networkStatsListener.onNetworkStats(
bytesWriteCount / MONITOR_POLL_EVERY_SEC,
bytesReadCount / MONITOR_POLL_EVERY_SEC,
socketPollCount / MONITOR_POLL_EVERY_SEC);
bytesWriteCount = bytesReadCount = socketPollCount = 0;
}
}
lastMonitor = now;
}
}
@PackageLocal
boolean invokeHandler() throws IOException {
Jvm.optionalSafepoint();
boolean busy = false;
final int position = inBBB.underlyingObject().position();
inBBB.readLimit(position);
outBBB.writePosition(outBBB.underlyingObject().limit());
long lastInBBBReadPosition;
do {
lastInBBBReadPosition = inBBB.readPosition();
tcpHandler.process(inBBB, outBBB, nc);
bytesReadCount += (inBBB.readPosition() - lastInBBBReadPosition);
// process method might change the underlying ByteBuffer by resizing it.
ByteBuffer outBB = outBBB.underlyingObject();
// did it write something?
int wpBBB = Maths.toUInt31(outBBB.writePosition());
int length = wpBBB - outBB.limit();
if (length >= TARGET_WRITE_SIZE) {
outBB.limit(wpBBB);
boolean busy2 = tryWrite(outBB);
if (busy2)
busy = busy2;
else
break;
}
} while (lastInBBBReadPosition != inBBB.readPosition());
ByteBuffer outBB = outBBB.underlyingObject();
if (outBBB.writePosition() > outBB.limit() || outBBB.writePosition() >= 4) {
outBB.limit(Maths.toInt32(outBBB.writePosition()));
busy |= tryWrite(outBB);
}
Jvm.optionalSafepoint();
if (inBBB.readRemaining() == 0) {
clearBuffer();
} else if (inBBB.readPosition() > TCP_BUFFER / 4) {
compactBuffer();
busy = true;
}
return busy;
}
private void clearBuffer() {
inBBB.clear();
@Nullable ByteBuffer inBB = inBBB.underlyingObject();
inBB.clear();
}
private void compactBuffer() {
// if it read some data compact();
@Nullable ByteBuffer inBB = inBBB.underlyingObject();
inBB.position((int) inBBB.readPosition());
inBB.limit((int) inBBB.readLimit());
Jvm.optionalSafepoint();
inBB.compact();
Jvm.optionalSafepoint();
inBBB.readPosition(0);
inBBB.readLimit(inBB.remaining());
}
private void handleIOE(@NotNull IOException e, final boolean clientIntentionallyClosed,
@Nullable HeartbeatListener heartbeatListener) {
try {
if (clientIntentionallyClosed)
return;
if (e.getMessage() != null && e.getMessage().startsWith("Connection reset by peer"))
LOG.trace(e.getMessage(), e);
else if (e.getMessage() != null && e.getMessage().startsWith("An existing connection " +
"was forcibly closed"))
Jvm.debug().on(getClass(), e.getMessage());
else if (!(e instanceof ClosedByInterruptException))
Jvm.warn().on(getClass(), "", e);
// The remote server has sent you a RST packet, which indicates an immediate dropping of the connection,
// rather than the usual handshake. This bypasses the normal half-closed state transition.
// I like this description: "Connection reset by peer" is the TCP/IP equivalent
// of slamming the phone back on the hook.
if (heartbeatListener != null)
heartbeatListener.onMissedHeartbeat();
} finally {
close();
}
}
@Override
protected void performClose() {
// NOTE Do not release buffers here as they might be in use. loopFinished() releases them and
// is called from event loop when it knows that the thread calling "action" is done
Closeable.closeQuietly(tcpHandler);
Closeable.closeQuietly(this.nc.networkStatsListener());
Closeable.closeQuietly(sc);
Closeable.closeQuietly(nc);
}
@PackageLocal
boolean tryWrite(ByteBuffer outBB) throws IOException {
if (outBB.remaining() <= 0)
return false;
int start = outBB.position();
long writeTime = System.nanoTime();
assert !sc.isBlocking();
int wrote = sc.write(outBB);
long time1 = System.nanoTime() - writeTime;
if (time1 > NBW_WARNING_NANOS)
Jvm.warn().on(getClass(), "Non blocking write took " + time1 / 1000 + " us.");
tcpHandler.onWriteTime(writeTime, outBB, start, outBB.position());
bytesWriteCount += (outBB.position() - start);
writeLog.log(outBB, start, outBB.position());
if (wrote < 0) {
close();
} else if (wrote > 0) {
outBB.compact().flip();
outBBB.writePosition(outBB.limit());
return true;
}
return false;
}
public static class Factory<T extends NetworkContext<T>> implements MarshallableFunction<T, TcpEventHandler<T>> {
public Factory() {
}
@NotNull
@Override
public TcpEventHandler<T> apply(@NotNull T nc) {
return new TcpEventHandler<T>(nc);
}
}
public boolean writeAction() {
Jvm.optionalSafepoint();
boolean busy = false;
try {
// get more data to write if the buffer was empty
// or we can write some of what is there
ByteBuffer outBB = outBBB.underlyingObject();
int remaining = outBB.remaining();
busy = remaining > 0;
if (busy)
tryWrite(outBB);
// has the remaining changed, i.e. did it write anything?
if (outBB.remaining() == remaining) {
busy |= invokeHandler();
if (!busy)
busy = tryWrite(outBB);
}
} catch (ClosedChannelException cce) {
close();
} catch (IOException e) {
if (!isClosed())
handleIOE(e, tcpHandler.hasClientClosed(), nc.heartbeatListener());
}
return busy;
}
}
|
Avoid redundant object creation, Fix #70
|
src/main/java/net/openhft/chronicle/network/TcpEventHandler.java
|
Avoid redundant object creation, Fix #70
|
<ide><path>rc/main/java/net/openhft/chronicle/network/TcpEventHandler.java
<ide> @NotNull
<ide> private final Bytes<ByteBuffer> outBBB;
<ide> private final boolean fair;
<add>
<add> private final boolean nbWarningEnabled;
<add>
<ide> private int oneInTen;
<ide> @Nullable
<ide> private volatile TcpHandler<T> tcpHandler;
<ide> outBBB.underlyingObject().limit(0);
<ide> readLog = new NetworkLog(this.sc, "read");
<ide> writeLog = new NetworkLog(this.sc, "write");
<add> nbWarningEnabled = Jvm.warn().isEnabled(getClass());
<ide> if (FIRST_HANDLER.compareAndSet(false, true))
<ide> warmUp();
<ide> }
<ide> int read = inBB.remaining() > 0 ? reader.read(sc, inBBB) : Integer.MAX_VALUE;
<ide> // int read = inBB.remaining() > 0 ? sc.read(inBB) : Integer.MAX_VALUE;
<ide> long time1 = System.nanoTime() - time0;
<del> if (time1 > NBR_WARNING_NANOS)
<add> if (nbWarningEnabled && time1 > NBR_WARNING_NANOS)
<ide> Jvm.warn().on(getClass(), "Non blocking read took " + time1 / 1000 + " us.");
<add>
<ide>
<ide> if (read == Integer.MAX_VALUE)
<ide> onInBBFul();
<ide> assert !sc.isBlocking();
<ide> int wrote = sc.write(outBB);
<ide> long time1 = System.nanoTime() - writeTime;
<del> if (time1 > NBW_WARNING_NANOS)
<add> if (nbWarningEnabled && time1 > NBW_WARNING_NANOS)
<ide> Jvm.warn().on(getClass(), "Non blocking write took " + time1 / 1000 + " us.");
<ide> tcpHandler.onWriteTime(writeTime, outBB, start, outBB.position());
<ide>
|
|
JavaScript
|
agpl-3.0
|
38c3b0b3c8491c4de37e895e67ac87ab8c89548c
| 0 |
foodcoopshop/foodcoopshop,foodcoopshop/foodcoopshop,foodcoopshop/foodcoopshop,foodcoopshop/foodcoopshop
|
/**
* FoodCoopShop - The open source software for your foodcoop
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @since FoodCoopShop 3.1.0
* @license https://opensource.org/licenses/mit-license.php MIT License
* @author Mario Rothauer <[email protected]>
* @copyright Copyright (c) Mario Rothauer, https://www.rothauer-it.com
* @link https://www.foodcoopshop.com
*/
foodcoopshop.ModalOrderDetailFeedbackAdd = {
init : function() {
$('a.product-feedback-button').on('click', function () {
var modalSelector = '#modal-order-detail-feedback-add';
foodcoopshop.Modal.appendModalToDom(
modalSelector,
foodcoopshop.LocalizedJs.admin.AddProductFeedback,
foodcoopshop.ModalOrderDetailFeedbackAdd.getHtml()
);
foodcoopshop.Modal.bindSuccessButton(modalSelector, function() {
foodcoopshop.ModalOrderDetailFeedbackAdd.getSuccessHandler(modalSelector);
});
$(modalSelector).on('hidden.bs.modal', function (e) {
foodcoopshop.ModalOrderDetailFeedbackAdd.getCloseHandler(modalSelector);
});
foodcoopshop.ModalOrderDetailFeedbackAdd.getOpenHandler($(this), modalSelector);
});
},
getHtml : function() {
var html = '<label></label>';
html += '<p class="small add-product-feedback-explanation-text"></p>';
html += '<div class="textarea-wrapper">';
html += '<textarea class="ckeditor" name="dialogOrderDetailFeedback" id="dialogOrderDetailFeedback"></textarea>';
html += '</div>';
html += '<input type="hidden" name="dialogOrderDetailId" id="dialogOrderDetailId" value="" />';
return html;
},
getCloseHandler : function(modalSelector) {
$(modalSelector).remove();
},
getSuccessHandler : function(modalSelector) {
if ($('#dialogOrderDetailId').val() == '') {
return false;
}
foodcoopshop.Helper.ajaxCall(
'/admin/order-details/addFeedback/',
{
orderDetailId: $('#dialogOrderDetailId').val(),
orderDetailFeedback: CKEDITOR.instances['dialogOrderDetailFeedback'].getData()
},
{
onOk: function (data) {
document.location.reload();
},
onError: function (data) {
foodcoopshop.Modal.appendFlashMessage(modalSelector, data.msg);
foodcoopshop.Modal.resetButtons(modalSelector);
}
}
);
},
getOpenHandler : function(button, modalSelector) {
foodcoopshop.Modal.removeTooltipster();
$(modalSelector).modal();
var row = button.closest('tr');
var orderDetailId = row.find('td:nth-child(2)').html();
var productName = row.find('.name-for-dialog').text();
var customerName = row.find('.customer-name-for-dialog').text();
var manufacturerName = row.find('td:nth-child(5) a').text();
foodcoopshop.Helper.ajaxCall(
'/admin/order-details/setElFinderUploadPath/' + orderDetailId,
{},
{
onOk: function (data) {
foodcoopshop.Helper.initCkeditorSmallWithUpload('dialogOrderDetailFeedback', true);
},
onError: function (data) {
foodcoopshop.Modal.appendFlashMessage(modalSelector, data.msg);
foodcoopshop.Modal.resetButtons(modalSelector);
}
}
);
$(modalSelector + ' #dialogOrderDetailId').val(orderDetailId);
$(modalSelector + ' label').html('<b>' + productName + '</b>' + ' (' + foodcoopshop.LocalizedJs.admin.orderedBy + ' ' + customerName + ')');
$(modalSelector + ' .add-product-feedback-explanation-text').html(
foodcoopshop.LocalizedJs.admin.AddProductFeedbackExplanationText0.replaceI18n(0, '<b>' + manufacturerName + '</b>')
);
}
};
|
plugins/Admin/webroot/js/modal/modal-order-detail-feedback-add.js
|
/**
* FoodCoopShop - The open source software for your foodcoop
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @since FoodCoopShop 3.1.0
* @license https://opensource.org/licenses/mit-license.php MIT License
* @author Mario Rothauer <[email protected]>
* @copyright Copyright (c) Mario Rothauer, https://www.rothauer-it.com
* @link https://www.foodcoopshop.com
*/
foodcoopshop.ModalOrderDetailFeedbackAdd = {
init : function() {
$('a.product-feedback-button').on('click', function () {
var modalSelector = '#modal-order-detail-feedback-add';
foodcoopshop.Modal.appendModalToDom(
modalSelector,
foodcoopshop.LocalizedJs.admin.AddProductFeedback,
foodcoopshop.ModalOrderDetailFeedbackAdd.getHtml()
);
foodcoopshop.Modal.bindSuccessButton(modalSelector, function() {
foodcoopshop.ModalOrderDetailFeedbackAdd.getSuccessHandler(modalSelector);
});
$(modalSelector).on('hidden.bs.modal', function (e) {
foodcoopshop.ModalOrderDetailFeedbackAdd.getCloseHandler(modalSelector);
});
foodcoopshop.ModalOrderDetailFeedbackAdd.getOpenHandler($(this), modalSelector);
});
},
getHtml : function() {
var html = '<label></label>';
html += '<p class="small add-product-feedback-explanation-text"></p>';
html += '<div class="textarea-wrapper">';
html += '<textarea class="ckeditor" name="dialogOrderDetailFeedback" id="dialogOrderDetailFeedback"></textarea>';
html += '</div>';
html += '<input type="hidden" name="dialogOrderDetailId" id="dialogOrderDetailId" value="" />';
return html;
},
getCloseHandler : function(modalSelector) {
$(modalSelector).remove();
},
getSuccessHandler : function(modalSelector) {
if ($('#dialogOrderDetailId').val() == '') {
return false;
}
foodcoopshop.Helper.ajaxCall(
'/admin/order-details/addFeedback/',
{
orderDetailId: $('#dialogOrderDetailId').val(),
orderDetailFeedback: CKEDITOR.instances['dialogOrderDetailFeedback'].getData()
},
{
onOk: function (data) {
document.location.reload();
},
onError: function (data) {
foodcoopshop.Modal.appendFlashMessage(modalSelector, data.msg);
foodcoopshop.Modal.resetButtons(modalSelector);
}
}
);
},
getOpenHandler : function(button, modalSelector) {
$(modalSelector).modal();
var row = button.closest('tr');
var orderDetailId = row.find('td:nth-child(2)').html();
var productName = row.find('.name-for-dialog').text();
var customerName = row.find('.customer-name-for-dialog').text();
var manufacturerName = row.find('td:nth-child(5) a').text();
foodcoopshop.Helper.ajaxCall(
'/admin/order-details/setElFinderUploadPath/' + orderDetailId,
{},
{
onOk: function (data) {
foodcoopshop.Helper.initCkeditorSmallWithUpload('dialogOrderDetailFeedback', true);
},
onError: function (data) {
foodcoopshop.Modal.appendFlashMessage(modalSelector, data.msg);
foodcoopshop.Modal.resetButtons(modalSelector);
}
}
);
$(modalSelector + ' #dialogOrderDetailId').val(orderDetailId);
$(modalSelector + ' label').html('<b>' + productName + '</b>' + ' (' + foodcoopshop.LocalizedJs.admin.orderedBy + ' ' + customerName + ')');
$(modalSelector + ' .add-product-feedback-explanation-text').html(
foodcoopshop.LocalizedJs.admin.AddProductFeedbackExplanationText0.replaceI18n(0, '<b>' + manufacturerName + '</b>')
);
}
};
|
remove tooltipster
|
plugins/Admin/webroot/js/modal/modal-order-detail-feedback-add.js
|
remove tooltipster
|
<ide><path>lugins/Admin/webroot/js/modal/modal-order-detail-feedback-add.js
<ide>
<ide> getOpenHandler : function(button, modalSelector) {
<ide>
<add> foodcoopshop.Modal.removeTooltipster();
<add>
<ide> $(modalSelector).modal();
<ide>
<ide> var row = button.closest('tr');
|
|
JavaScript
|
mit
|
bcb081e39758e257da802b67497788566a49b598
| 0 |
medikoo/dom-ext
|
// Credit: Fixed and cleaned version of @melux's demo-zoom:
// https://gist.github.com/melux/50c0f994bfa1caf2c1a0
'use strict';
var CustomError = require('es5-ext/lib/Error/custom')
, nextTick = require('next-tick')
, element = require('../valid-html-element')
, getDimensions = require('./get-dimensions')
, isImage = require('../../HTMLImageElement/is-html-image-element')
, imgPromise = require('../../HTMLImageElement/prototype/promise');
module.exports = function (/* options */) {
var wheelEventName, image, wrapDim, imageDim, onMove, zoom = 1, init
, options = Object(arguments[0]);
if (element(this).onmousewheel === undefined) {
if (this.onwheel === undefined) {
throw new CustomError('Wheel event not supported',
'WHEEL_EVENT_NOT_SUPPORTED');
}
wheelEventName = 'wheel';
} else {
wheelEventName = 'mousewheel';
}
image = element(this.firstElementChild);
init = function () {
imageDim = {
width: options.width || image.naturalWidth,
height: options.height || image.naturalHeight
};
if (!imageDim.width || !imageDim.height) {
throw new CustomError("No image dimensions detected", 'NO_DIMENSIONS');
}
wrapDim = getDimensions.call(this);
if (!wrapDim.width || !wrapDim.height) {
throw new CustomError("No wrap dimensions detected", 'NO_DIMENSIONS');
}
this.style.overflow = 'hidden';
this.style.position = 'relative';
this.style.cursor = 'crosshair';
this.addEventListener('mouseover', function () {
image.style.position = 'absolute';
image.style.top = '0';
image.style.left = '0';
image.style.width = (imageDim.width * zoom) + 'px';
image.style.height = (imageDim.height * zoom) + 'px';
image.style.maxWidth = 'none';
image.style.maxHeight = 'none';
}, false);
this.addEventListener('mousemove', onMove = function (e) {
var mX = e.pageX - this.offsetLeft
, mY = e.pageY - this.offsetTop
, ratioX = mX / wrapDim.width
, ratioY = mY / wrapDim.height
, iX = mX - imageDim.width * zoom * ratioX
, iY = mY - imageDim.height * zoom * ratioY;
image.style.left = iX + 'px';
image.style.top = iY + 'px';
}, false);
this.addEventListener('mouseout', function (e) {
image.style.position = '';
image.style.top = '';
image.style.left = '';
image.style.width = '';
image.style.height = '';
image.style.maxWidth = '';
image.style.maxHeight = '';
}, false);
this.addEventListener(wheelEventName, function (e) {
var deltaY = 0, delta;
e.preventDefault();
if (e.deltaY) {
deltaY = e.deltaY;
} else if (e.wheelDelta) {
deltaY = -e.wheelDelta;
}
delta = deltaY / 1200;
if (((zoom + delta) <= 1) && ((zoom + delta) > 0) &&
(((imageDim.width * (zoom + delta)) > wrapDim.width) ||
((imageDim.height * (zoom + delta)) > wrapDim.height))) {
zoom += delta;
image.style.width = (imageDim.width * zoom) + 'px';
image.style.height = (imageDim.height * zoom) + 'px';
}
onMove.call(this, e);
}, false);
}.bind(this);
if (isImage(image)) {
imgPromise.call(image).end(function () {
if (this.offsetWidth) init();
else nextTick(init);
}.bind(this));
} else if (this.offsetWidth) {
init();
} else {
nextTick(init);
}
return this;
};
|
lib/HTMLElement/prototype/zoom-on-hover.js
|
// Credit: Fixed and cleaned version of @melux's demo-zoom:
// https://gist.github.com/melux/50c0f994bfa1caf2c1a0
'use strict';
var CustomError = require('es5-ext/lib/Error/custom')
, nextTick = require('next-tick')
, element = require('../valid-html-element')
, getDimensions = require('./get-dimensions')
, isImage = require('../../HTMLImageElement/is-html-image-element')
, imgPromise = require('../../HTMLImageElement/prototype/promise');
module.exports = function (/* options */) {
var wheelEventName, image, wrapDim, imageDim, onMove, zoom = 1, init
, options = Object(arguments[0]);
if (element(this).onmousewheel === undefined) {
if (this.onwheel === undefined) {
throw new CustomError('Wheel event not supported',
'WHEEL_EVENT_NOT_SUPPORTED');
}
wheelEventName = 'wheel';
} else {
wheelEventName = 'mousewheel';
}
image = element(this.firstElementChild);
init = function () {
imageDim = {
width: options.width || image.naturalWidth,
height: options.height || image.naturalHeight
};
if (!imageDim.width || !imageDim.height) {
throw new CustomError("No image dimensions detected", 'NO_DIMENSIONS');
}
wrapDim = getDimensions.call(this);
if (!wrapDim.width || !wrapDim.height) {
throw new CustomError("No wrap dimensions detected", 'NO_DIMENSIONS');
}
this.style.overflow = 'hidden';
this.style.position = 'relative';
this.style.cursor = 'crosshair';
image.style.position = 'absolute';
image.style.top = '0';
image.style.left = '0';
this.addEventListener('mouseover', function () {
image.style.width = (imageDim.width * zoom) + 'px';
image.style.height = (imageDim.height * zoom) + 'px';
image.style.maxWidth = 'none';
}, false);
this.addEventListener('mousemove', onMove = function (e) {
var mX = e.pageX - this.offsetLeft
, mY = e.pageY - this.offsetTop
, ratioX = mX / wrapDim.width
, ratioY = mY / wrapDim.height
, iX = mX - imageDim.width * zoom * ratioX
, iY = mY - imageDim.height * zoom * ratioY;
image.style.left = iX + 'px';
image.style.top = iY + 'px';
}, false);
this.addEventListener('mouseout', function (e) {
image.style.width = '';
image.style.height = '';
image.style.left = '0';
image.style.top = '0';
image.style.maxWidth = '';
}, false);
this.addEventListener(wheelEventName, function (e) {
var deltaY = 0, delta;
e.preventDefault();
if (e.deltaY) {
deltaY = e.deltaY;
} else if (e.wheelDelta) {
deltaY = -e.wheelDelta;
}
delta = deltaY / 1200;
if (((zoom + delta) <= 1) && ((zoom + delta) > 0) &&
(((imageDim.width * (zoom + delta)) > wrapDim.width) ||
((imageDim.height * (zoom + delta)) > wrapDim.height))) {
zoom += delta;
image.style.width = (imageDim.width * zoom) + 'px';
image.style.height = (imageDim.height * zoom) + 'px';
}
onMove.call(this, e);
}, false);
}.bind(this);
if (isImage(image)) {
imgPromise.call(image).end(function () {
if (this.offsetWidth) init();
else nextTick(init);
}.bind(this));
} else if (this.offsetWidth) {
init();
} else {
nextTick(init);
}
return this;
};
|
Improve zoom on hover style logic
|
lib/HTMLElement/prototype/zoom-on-hover.js
|
Improve zoom on hover style logic
|
<ide><path>ib/HTMLElement/prototype/zoom-on-hover.js
<ide> this.style.overflow = 'hidden';
<ide> this.style.position = 'relative';
<ide> this.style.cursor = 'crosshair';
<del> image.style.position = 'absolute';
<del> image.style.top = '0';
<del> image.style.left = '0';
<ide>
<ide> this.addEventListener('mouseover', function () {
<add> image.style.position = 'absolute';
<add> image.style.top = '0';
<add> image.style.left = '0';
<ide> image.style.width = (imageDim.width * zoom) + 'px';
<ide> image.style.height = (imageDim.height * zoom) + 'px';
<ide> image.style.maxWidth = 'none';
<add> image.style.maxHeight = 'none';
<ide> }, false);
<ide>
<ide> this.addEventListener('mousemove', onMove = function (e) {
<ide> }, false);
<ide>
<ide> this.addEventListener('mouseout', function (e) {
<add> image.style.position = '';
<add> image.style.top = '';
<add> image.style.left = '';
<ide> image.style.width = '';
<ide> image.style.height = '';
<del> image.style.left = '0';
<del> image.style.top = '0';
<ide> image.style.maxWidth = '';
<add> image.style.maxHeight = '';
<ide> }, false);
<ide>
<ide> this.addEventListener(wheelEventName, function (e) {
|
|
Java
|
mit
|
7d0754964eb0921bd98ca3c970d8a3d1c24bba56
| 0 |
JavaCCSF2016/DrawBoard
|
//LeoYulinLi, califoxco(Jiaming Yang), qixin liu, and Tsoek Yin Lee Liu
package com.github.javaccsf2016.drawboard;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ControlPanel extends JPanel {
private JButton redPenButton;
private JButton bluePenButton;
private JButton greenPenButton;
private JButton eraserButton;
private JButton clearAllButton;
private JButton drawRectButton;
private DrawBoardDisplay drawingPanel;
public ControlPanel(DrawBoardDisplay drawingPanel) {
// set the background color
setBackground(Color.cyan);
this.drawingPanel = drawingPanel;
redPenButton = new JButton("Red Pen");
this.add(redPenButton);
redPenButton.addActionListener(new ButtonListener());
bluePenButton = new JButton("Blue Pen");
this.add(bluePenButton);
bluePenButton.addActionListener(new ButtonListener());
greenPenButton = new JButton("Green Pen");
this.add(greenPenButton);
greenPenButton.addActionListener(new ButtonListener());
eraserButton = new JButton("Eraser");
this.add(eraserButton);
eraserButton.addActionListener(new ButtonListener());
drawRectButton = new JButton("Rectangle Flash");
this.add(drawRectButton);
drawRectButton.addActionListener(new ButtonListener());
clearAllButton = new JButton("Clear All");
this.add(clearAllButton);
clearAllButton.addActionListener(new ButtonListener());
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if(event.getSource()==redPenButton) {
drawingPanel.redPen(); }
else if(event.getSource()==bluePenButton) {
drawingPanel.bluePen();}
else if (event.getSource()==greenPenButton){
drawingPanel.greenPen();}
else if(event.getSource()==eraserButton) {
drawingPanel.eraser();}
else if(event.getSource()==drawRectButton) {
drawingPanel.drawRect();}
else if(event.getSource()==clearAllButton) {
drawingPanel.clearAll();}
}
}
}
|
src/com/github/javaccsf2016/drawboard/ControlPanel.java
|
//LeoYulinLi, califoxco(Jiaming Yang), qixin liu, and Tsoek Yin Lee Liu
package com.github.javaccsf2016.drawboard;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ControlPanel extends JPanel {
private JButton redPenButton;
private JButton bluePenButton;
private JButton greenPenButton;
private JButton eraserButton;
private JButton clearAllButton;
private JButton drawRectButton;
private DrawBoardDisplay drawingPanel;
public ControlPanel(DrawBoardDisplay drawingPanel) {
// set the background color
setBackground(Color.cyan);
this.drawingPanel = drawingPanel;
redPenButton = new JButton("Red Pen");
this.add(redPenButton);
redPenButton.addActionListener(new ButtonListener());
bluePenButton = new JButton("Blue Pen");
this.add(bluePenButton);
bluePenButton.addActionListener(new ButtonListener());
greenPenButton = new JButton("Green Pen");
this.add(greenPenButton);
greenPenButton.addActionListener(new ButtonListener());
eraserButton = new JButton("Eraser");
this.add(eraserButton);
eraserButton.addActionListener(new ButtonListener());
drawRectButton = new JButton("Draw Rectangle");
this.add(drawRectButton);
drawRectButton.addActionListener(new ButtonListener());
clearAllButton = new JButton("Clear All");
this.add(clearAllButton);
clearAllButton.addActionListener(new ButtonListener());
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if(event.getSource()==redPenButton) {
drawingPanel.redPen(); }
else if(event.getSource()==bluePenButton) {
drawingPanel.bluePen();}
else if (event.getSource()==greenPenButton){
drawingPanel.greenPen();}
else if(event.getSource()==eraserButton) {
drawingPanel.eraser();}
else if(event.getSource()==drawRectButton) {
drawingPanel.drawRect();}
else if(event.getSource()==clearAllButton) {
drawingPanel.clearAll();}
}
}
}
|
random rectangle instead of rectangular brush
|
src/com/github/javaccsf2016/drawboard/ControlPanel.java
|
random rectangle instead of rectangular brush
|
<ide><path>rc/com/github/javaccsf2016/drawboard/ControlPanel.java
<ide> this.add(eraserButton);
<ide> eraserButton.addActionListener(new ButtonListener());
<ide>
<del> drawRectButton = new JButton("Draw Rectangle");
<add> drawRectButton = new JButton("Rectangle Flash");
<ide> this.add(drawRectButton);
<ide> drawRectButton.addActionListener(new ButtonListener());
<ide>
|
|
Java
|
lgpl-2.1
|
d5a665d659c52756d341ec176a90c802d3e72cb6
| 0 |
adamallo/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,4ment/beast-mcmc,4ment/beast-mcmc,beast-dev/beast-mcmc,4ment/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,4ment/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,4ment/beast-mcmc,4ment/beast-mcmc
|
/*
* FullyConjugateTreeTipsPotentialDerivative.java
*
* Copyright (c) 2002-2017 Alexei Drummond, Andrew Rambaut and Marc Suchard
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST 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
* of the License, or (at your option) any later version.
*
* BEAST 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 BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evomodel.continuous.hmc;
import dr.evomodel.continuous.FullyConjugateMultivariateTraitLikelihood;
import dr.inference.hmc.GradientWrtParameterProvider;
import dr.inference.model.Likelihood;
import dr.inference.model.Parameter;
import dr.xml.Reportable;
/**
* @author Max Tolkoff
* @author Marc A. Suchard
*/
@Deprecated
public class FullyConjugateTreeTipsPotentialDerivative implements GradientWrtParameterProvider, Reportable {
private final FullyConjugateMultivariateTraitLikelihood treeLikelihood;
private final Parameter traitParameter;
private final Parameter mask;
public FullyConjugateTreeTipsPotentialDerivative(FullyConjugateMultivariateTraitLikelihood treeLikelihood,
Parameter mask){
this.treeLikelihood = treeLikelihood;
traitParameter = treeLikelihood.getTraitParameter();
this.mask = mask;
if (mask != null) {
if (traitParameter.getDimension() != mask.getDimension()) {
throw new IllegalArgumentException("Trait and mask parameters have differing dimension");
}
}
}
@Override
public Likelihood getLikelihood() {
return treeLikelihood;
}
@Override
public Parameter getParameter() {
return traitParameter;
}
@Override
public int getDimension() {
return traitParameter.getDimension();
}
@Override
public double[] getGradientLogDensity() {
final int dimTraits = treeLikelihood.getDimTrait() * treeLikelihood.getNumData();
final int nTaxa = traitParameter.getDimension() / dimTraits;
final double[] derivative = new double[traitParameter.getDimension()];
final double[][] allMeans = treeLikelihood.getConditionalMeans();
final double[] allScalars = treeLikelihood.getPrecisionFactors();
final double[][] precisionMatrix = treeLikelihood.getDiffusionModel().getPrecisionmatrix();
for (int i = 0; i < nTaxa; ++i) {
final double[] mean = allMeans[i];
final double scale = allScalars[i];
for (int j = 0; j < dimTraits; ++j) {
double sum = 0.0;
for (int k = 0; k < dimTraits; ++k) {
sum += (mean[k] - traitParameter.getParameterValue(i * dimTraits + k)) *
scale * precisionMatrix[j][k];
}
derivative[i * dimTraits + j] = sum;
}
}
if (mask != null) {
for (int i = 0; i < mask.getDimension(); ++i) {
if (mask.getParameterValue(i) == 0.0) {
derivative[i] = 0.0;
}
}
}
return derivative;
}
@Override
public String getReport() {
return (new dr.math.matrixAlgebra.Vector(getGradientLogDensity())).toString();
}
}
|
src/dr/evomodel/continuous/hmc/FullyConjugateTreeTipsPotentialDerivative.java
|
/*
* FullyConjugateTreeTipsPotentialDerivative.java
*
* Copyright (c) 2002-2017 Alexei Drummond, Andrew Rambaut and Marc Suchard
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST 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
* of the License, or (at your option) any later version.
*
* BEAST 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 BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evomodel.continuous.hmc;
import dr.evomodel.continuous.FullyConjugateMultivariateTraitLikelihood;
import dr.inference.hmc.GradientWrtParameterProvider;
import dr.inference.model.Likelihood;
import dr.inference.model.Parameter;
import dr.xml.Reportable;
/**
* @author Max Tolkoff
* @author Marc A. Suchard
*/
public class FullyConjugateTreeTipsPotentialDerivative implements GradientWrtParameterProvider, Reportable {
private final FullyConjugateMultivariateTraitLikelihood treeLikelihood;
private final Parameter traitParameter;
private final Parameter mask;
public FullyConjugateTreeTipsPotentialDerivative(FullyConjugateMultivariateTraitLikelihood treeLikelihood,
Parameter mask){
this.treeLikelihood = treeLikelihood;
traitParameter = treeLikelihood.getTraitParameter();
this.mask = mask;
if (mask != null) {
if (traitParameter.getDimension() != mask.getDimension()) {
throw new IllegalArgumentException("Trait and mask parameters have differing dimension");
}
}
}
@Override
public Likelihood getLikelihood() {
return treeLikelihood;
}
@Override
public Parameter getParameter() {
return traitParameter;
}
@Override
public int getDimension() {
return traitParameter.getDimension();
}
@Override
public double[] getGradientLogDensity() {
final int dimTraits = treeLikelihood.getDimTrait() * treeLikelihood.getNumData();
final int ntaxa = traitParameter.getDimension() / dimTraits;
final double[] derivative = new double[traitParameter.getDimension()];
final double[][] allMeans = treeLikelihood.getConditionalMeans();
final double[] allScalars = treeLikelihood.getPrecisionFactors();
final double[][] precisionMatrix = treeLikelihood.getDiffusionModel().getPrecisionmatrix();
for (int i = 0; i < ntaxa; ++i) {
final double[] mean = allMeans[i];
final double scale = allScalars[i];
for (int j = 0; j < dimTraits; ++j) {
double sum = 0.0;
for (int k = 0; k < dimTraits; ++k) {
sum += (mean[k] - traitParameter.getParameterValue(i * dimTraits + k)) *
scale * precisionMatrix[j][k];
}
derivative[i * dimTraits + j] = sum;
}
}
if (mask != null) {
for (int i = 0; i < mask.getDimension(); ++i) {
if (mask.getParameterValue(i) == 0.0) {
derivative[i] = 0.0;
}
}
}
return derivative;
}
@Override
public String getReport() {
return (new dr.math.matrixAlgebra.Vector(getGradientLogDensity())).toString();
}
}
|
depricating old untested code
|
src/dr/evomodel/continuous/hmc/FullyConjugateTreeTipsPotentialDerivative.java
|
depricating old untested code
|
<ide><path>rc/dr/evomodel/continuous/hmc/FullyConjugateTreeTipsPotentialDerivative.java
<ide> * @author Max Tolkoff
<ide> * @author Marc A. Suchard
<ide> */
<add>@Deprecated
<ide> public class FullyConjugateTreeTipsPotentialDerivative implements GradientWrtParameterProvider, Reportable {
<ide>
<ide> private final FullyConjugateMultivariateTraitLikelihood treeLikelihood;
<ide> public double[] getGradientLogDensity() {
<ide>
<ide> final int dimTraits = treeLikelihood.getDimTrait() * treeLikelihood.getNumData();
<del> final int ntaxa = traitParameter.getDimension() / dimTraits;
<add> final int nTaxa = traitParameter.getDimension() / dimTraits;
<ide>
<ide> final double[] derivative = new double[traitParameter.getDimension()];
<ide>
<ide> final double[] allScalars = treeLikelihood.getPrecisionFactors();
<ide> final double[][] precisionMatrix = treeLikelihood.getDiffusionModel().getPrecisionmatrix();
<ide>
<del> for (int i = 0; i < ntaxa; ++i) {
<add> for (int i = 0; i < nTaxa; ++i) {
<ide>
<ide> final double[] mean = allMeans[i];
<ide> final double scale = allScalars[i];
|
|
Java
|
epl-1.0
|
c4888699cb978a29ee5c7ece5f8866bafbefca22
| 0 |
junit-team/junit-lambda,sbrannen/junit-lambda
|
/*
* Copyright 2015-2016 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 v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.junit.gen5.engine.junit5.discovery;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.gen5.api.Assertions.assertEquals;
import static org.junit.gen5.api.Assertions.assertSame;
import static org.junit.gen5.api.Assertions.assertTrue;
import static org.junit.gen5.api.Assertions.expectThrows;
import static org.junit.gen5.engine.junit5.discovery.JUnit5UniqueIdBuilder.engineId;
import static org.junit.gen5.engine.junit5.discovery.JUnit5UniqueIdBuilder.uniqueIdForClass;
import static org.junit.gen5.engine.junit5.discovery.JUnit5UniqueIdBuilder.uniqueIdForMethod;
import static org.junit.gen5.engine.junit5.discovery.JUnit5UniqueIdBuilder.uniqueIdForTestFactoryMethod;
import static org.junit.gen5.launcher.main.TestDiscoveryRequestBuilder.request;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.gen5.api.DynamicTest;
import org.junit.gen5.api.Nested;
import org.junit.gen5.api.Test;
import org.junit.gen5.api.TestFactory;
import org.junit.gen5.commons.JUnitException;
import org.junit.gen5.commons.util.PreconditionViolationException;
import org.junit.gen5.engine.DiscoverySelector;
import org.junit.gen5.engine.EngineDiscoveryRequest;
import org.junit.gen5.engine.TestDescriptor;
import org.junit.gen5.engine.UniqueId;
import org.junit.gen5.engine.discovery.ClassSelector;
import org.junit.gen5.engine.discovery.ClasspathSelector;
import org.junit.gen5.engine.discovery.MethodSelector;
import org.junit.gen5.engine.discovery.PackageSelector;
import org.junit.gen5.engine.discovery.UniqueIdSelector;
import org.junit.gen5.engine.junit5.descriptor.TestFactoryTestDescriptor;
/**
* @since 5.0
*/
public class DiscoverySelectorResolverTests {
private final JUnit5EngineDescriptor engineDescriptor = new JUnit5EngineDescriptor(engineId());
private DiscoverySelectorResolver resolver = new DiscoverySelectorResolver();
@Test
public void singleClassResolution() {
ClassSelector selector = ClassSelector.forClass(MyTestClass.class);
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(4, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(MyTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test1()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test2()")));
assertTrue(uniqueIds.contains(uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()")));
}
@Test
public void duplicateClassSelectorOnlyResolvesOnce() {
resolver.resolveSelectors(request().select( //
ClassSelector.forClass(MyTestClass.class), //
ClassSelector.forClass(MyTestClass.class) //
).build(), engineDescriptor);
assertEquals(4, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(MyTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test1()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test2()")));
assertTrue(uniqueIds.contains(uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()")));
}
@Test
public void twoClassesResolution() {
ClassSelector selector1 = ClassSelector.forClass(MyTestClass.class);
ClassSelector selector2 = ClassSelector.forClass(YourTestClass.class);
resolver.resolveSelectors(request().select(selector1, selector2).build(), engineDescriptor);
assertEquals(7, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(MyTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test1()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test2()")));
assertTrue(uniqueIds.contains(uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()")));
assertTrue(uniqueIds.contains(uniqueIdForClass(YourTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(YourTestClass.class, "test3()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(YourTestClass.class, "test4()")));
}
@Test
public void classResolutionOfStaticNestedClass() {
ClassSelector selector = ClassSelector.forClass(OtherTestClass.NestedTestClass.class);
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(3, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(OtherTestClass.NestedTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(OtherTestClass.NestedTestClass.class, "test5()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(OtherTestClass.NestedTestClass.class, "test6()")));
}
@Test
public void methodResolution() throws NoSuchMethodException {
Method test1 = MyTestClass.class.getDeclaredMethod("test1");
MethodSelector selector = MethodSelector.forMethod(test1.getDeclaringClass(), test1);
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(2, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(MyTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test1()")));
}
@Test
public void methodResolutionFromInheritedMethod() throws NoSuchMethodException {
MethodSelector selector = MethodSelector.forMethod(HerTestClass.class,
MyTestClass.class.getDeclaredMethod("test1"));
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(2, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(HerTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(HerTestClass.class, "test1()")));
}
@Test
public void resolvingSelectorOfNonTestMethodResolvesNothing() throws NoSuchMethodException {
Method notATest = MyTestClass.class.getDeclaredMethod("notATest");
MethodSelector selector = MethodSelector.forMethod(notATest.getDeclaringClass(), notATest);
EngineDiscoveryRequest request = request().select(selector).build();
resolver.resolveSelectors(request, engineDescriptor);
assertTrue(engineDescriptor.allDescendants().isEmpty());
}
@Test
public void classResolutionByUniqueId() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(uniqueIdForClass(MyTestClass.class).toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(4, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(MyTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test1()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test2()")));
assertTrue(uniqueIds.contains(uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()")));
}
@Test
public void staticNestedClassResolutionByUniqueId() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForClass(OtherTestClass.NestedTestClass.class).toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(3, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(OtherTestClass.NestedTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(OtherTestClass.NestedTestClass.class, "test5()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(OtherTestClass.NestedTestClass.class, "test6()")));
}
@Test
public void methodOfInnerClassByUniqueId() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(OtherTestClass.NestedTestClass.class, "test5()").toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(2, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(OtherTestClass.NestedTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(OtherTestClass.NestedTestClass.class, "test5()")));
}
@Test
public void resolvingUniqueIdWithUnknownSegmentTypeResolvesNothing() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(engineId().append("poops", "machine").toString());
EngineDiscoveryRequest request = request().select(selector).build();
resolver.resolveSelectors(request, engineDescriptor);
assertTrue(engineDescriptor.allDescendants().isEmpty());
}
@Test
public void resolvingUniqueIdOfNonTestMethodResolvesNothing() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(uniqueIdForMethod(MyTestClass.class, "notATest()"));
EngineDiscoveryRequest request = request().select(selector).build();
resolver.resolveSelectors(request, engineDescriptor);
assertTrue(engineDescriptor.allDescendants().isEmpty());
}
@Test
public void methodResolutionByUniqueIdWithNullInput() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(uniqueIdForMethod(getClass(), null));
assertMethodDoesNotMatchPattern(selector);
}
@Test
public void methodResolutionByUniqueIdWithEmptyInput() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(uniqueIdForMethod(getClass(), " "));
assertMethodDoesNotMatchPattern(selector);
}
@Test
public void methodResolutionByUniqueIdWithMissingMethodName() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(uniqueIdForMethod(getClass(), "()"));
assertMethodDoesNotMatchPattern(selector);
}
@Test
public void methodResolutionByUniqueIdWithMissingParameters() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(uniqueIdForMethod(getClass(), "methodName"));
assertMethodDoesNotMatchPattern(selector);
}
@Test
public void methodResolutionByUniqueIdWithBogusParameters() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(getClass(), "methodName(java.lang.String, junit.foo.Enigma)"));
Exception exception = expectThrows(JUnitException.class,
() -> resolver.resolveSelectors(request().select(selector).build(), engineDescriptor));
assertThat(exception).hasMessageStartingWith("Failed to load parameter type");
assertThat(exception).hasMessageContaining("junit.foo.Enigma");
}
private void assertMethodDoesNotMatchPattern(UniqueIdSelector selector) {
Exception exception = expectThrows(PreconditionViolationException.class,
() -> resolver.resolveSelectors(request().select(selector).build(), engineDescriptor));
assertThat(exception).hasMessageStartingWith("Method");
assertThat(exception).hasMessageContaining("does not match pattern");
}
@Test
public void methodResolutionByUniqueId() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(MyTestClass.class, "test1()").toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(2, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(MyTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test1()")));
}
@Test
public void methodResolutionByUniqueIdFromInheritedClass() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(HerTestClass.class, "test1()").toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(2, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(HerTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(HerTestClass.class, "test1()")));
}
@Test
public void methodResolutionByUniqueIdWithParams() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(HerTestClass.class, "test7(java.lang.String)").toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(2, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(HerTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(HerTestClass.class, "test7(java.lang.String)")));
}
@Test
public void resolvingUniqueIdWithWrongParamsResolvesNothing() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(HerTestClass.class, "test7(java.math.BigDecimal)").toString());
EngineDiscoveryRequest request = request().select(selector).build();
resolver.resolveSelectors(request, engineDescriptor);
assertTrue(engineDescriptor.allDescendants().isEmpty());
}
@Test
public void twoMethodResolutionsByUniqueId() {
UniqueIdSelector selector1 = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(MyTestClass.class, "test1()").toString());
UniqueIdSelector selector2 = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(MyTestClass.class, "test2()").toString());
// adding same selector twice should have no effect
resolver.resolveSelectors(request().select(selector1, selector2, selector2).build(), engineDescriptor);
assertEquals(3, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(MyTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test1()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test2()")));
TestDescriptor classFromMethod1 = descriptorByUniqueId(
uniqueIdForMethod(MyTestClass.class, "test1()")).getParent().get();
TestDescriptor classFromMethod2 = descriptorByUniqueId(
uniqueIdForMethod(MyTestClass.class, "test2()")).getParent().get();
assertEquals(classFromMethod1, classFromMethod2);
assertSame(classFromMethod1, classFromMethod2);
}
@Test
public void resolvingDynamicTestByUniqueIdResolvesOnlyUpToParentTestFactory() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()").append(
TestFactoryTestDescriptor.DYNAMIC_TEST_SEGMENT_TYPE, "%1"));
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertThat(engineDescriptor.allDescendants()).hasSize(2);
assertThat(uniqueIds()).containsSequence(uniqueIdForClass(MyTestClass.class),
uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()"));
}
@Test
public void resolvingTestFactoryMethodByUniqueId() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()"));
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertThat(engineDescriptor.allDescendants()).hasSize(2);
assertThat(uniqueIds()).containsSequence(uniqueIdForClass(MyTestClass.class),
uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()"));
}
@Test
public void packageResolution() {
PackageSelector selector = PackageSelector.forPackageName("org.junit.gen5.engine.junit5.descriptor.subpackage");
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(6, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(
uniqueIdForClass(org.junit.gen5.engine.junit5.descriptor.subpackage.Class1WithTestCases.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(
org.junit.gen5.engine.junit5.descriptor.subpackage.Class1WithTestCases.class, "test1()")));
assertTrue(uniqueIds.contains(
uniqueIdForClass(org.junit.gen5.engine.junit5.descriptor.subpackage.Class2WithTestCases.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(
org.junit.gen5.engine.junit5.descriptor.subpackage.Class2WithTestCases.class, "test2()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(
org.junit.gen5.engine.junit5.descriptor.subpackage.ClassWithStaticInnerTestCases.ShouldBeDiscovered.class,
"test1()")));
}
@Test
public void classpathResolution() {
File classpath = new File(
DiscoverySelectorResolverTests.class.getProtectionDomain().getCodeSource().getLocation().getPath());
List<DiscoverySelector> selector = ClasspathSelector.forPath(classpath.getAbsolutePath());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertTrue(engineDescriptor.allDescendants().size() > 500, "Too few test descriptors in classpath");
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(
uniqueIdForClass(org.junit.gen5.engine.junit5.descriptor.subpackage.Class1WithTestCases.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(
org.junit.gen5.engine.junit5.descriptor.subpackage.Class1WithTestCases.class, "test1()")));
assertTrue(uniqueIds.contains(
uniqueIdForClass(org.junit.gen5.engine.junit5.descriptor.subpackage.Class2WithTestCases.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(
org.junit.gen5.engine.junit5.descriptor.subpackage.Class2WithTestCases.class, "test2()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(
org.junit.gen5.engine.junit5.descriptor.subpackage.ClassWithStaticInnerTestCases.ShouldBeDiscovered.class,
"test1()")));
}
@Test
public void nestedTestResolutionFromBaseClass() {
ClassSelector selector = ClassSelector.forClass(TestCaseWithNesting.class);
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
List<UniqueId> uniqueIds = uniqueIds();
assertEquals(6, uniqueIds.size());
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.class, "testA()")));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.class, "testB()")));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class)));
assertTrue(uniqueIds.contains(
uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class, "testC()")));
}
@Test
public void nestedTestResolutionFromNestedTestClass() {
ClassSelector selector = ClassSelector.forClass(TestCaseWithNesting.NestedTestCase.class);
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
List<UniqueId> uniqueIds = uniqueIds();
assertEquals(5, uniqueIds.size());
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.class, "testB()")));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class)));
assertTrue(uniqueIds.contains(
uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class, "testC()")));
}
@Test
public void nestedTestResolutionFromUniqueId() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForClass(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class).toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
List<UniqueId> uniqueIds = uniqueIds();
assertEquals(4, uniqueIds.size());
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class)));
assertTrue(uniqueIds.contains(
uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class, "testC()")));
}
@Test
public void doubleNestedTestResolutionFromClass() {
ClassSelector selector = ClassSelector.forClass(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class);
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
List<UniqueId> uniqueIds = uniqueIds();
assertEquals(4, uniqueIds.size());
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class)));
assertTrue(uniqueIds.contains(
uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class, "testC()")));
}
@Test
public void methodResolutionInDoubleNestedTestClass() throws NoSuchMethodException {
MethodSelector selector = MethodSelector.forMethod(
TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class,
TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class.getDeclaredMethod("testC"));
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(4, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class)));
assertTrue(uniqueIds.contains(
uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class, "testC()")));
}
@Test
public void nestedTestResolutionFromUniqueIdToMethod() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.class, "testB()").toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
List<UniqueId> uniqueIds = uniqueIds();
assertEquals(3, uniqueIds.size());
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.class, "testB()")));
}
private TestDescriptor descriptorByUniqueId(UniqueId uniqueId) {
return engineDescriptor.allDescendants().stream().filter(
d -> d.getUniqueId().equals(uniqueId)).findFirst().get();
}
private List<UniqueId> uniqueIds() {
return engineDescriptor.allDescendants().stream().map(TestDescriptor::getUniqueId).collect(Collectors.toList());
}
}
class MyTestClass {
@Test
void test1() {
}
@Test
void test2() {
}
void notATest() {
}
@TestFactory
Stream<DynamicTest> dynamicTest() {
return new ArrayList<DynamicTest>().stream();
}
}
class YourTestClass {
@Test
void test3() {
}
@Test
void test4() {
}
}
class HerTestClass extends MyTestClass {
@Test
void test7(String param) {
}
}
class OtherTestClass {
static class NestedTestClass {
@Test
void test5() {
}
@Test
void test6() {
}
}
}
class TestCaseWithNesting {
@Test
void testA() {
}
@Nested
class NestedTestCase {
@Test
void testB() {
}
@Nested
class DoubleNestedTestCase {
@Test
void testC() {
}
}
}
}
|
junit-tests/src/test/java/org/junit/gen5/engine/junit5/discovery/DiscoverySelectorResolverTests.java
|
/*
* Copyright 2015-2016 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 v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.junit.gen5.engine.junit5.discovery;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.gen5.api.Assertions.assertEquals;
import static org.junit.gen5.api.Assertions.assertSame;
import static org.junit.gen5.api.Assertions.assertTrue;
import static org.junit.gen5.api.Assertions.expectThrows;
import static org.junit.gen5.engine.junit5.discovery.JUnit5UniqueIdBuilder.engineId;
import static org.junit.gen5.engine.junit5.discovery.JUnit5UniqueIdBuilder.uniqueIdForClass;
import static org.junit.gen5.engine.junit5.discovery.JUnit5UniqueIdBuilder.uniqueIdForMethod;
import static org.junit.gen5.engine.junit5.discovery.JUnit5UniqueIdBuilder.uniqueIdForTestFactoryMethod;
import static org.junit.gen5.launcher.main.TestDiscoveryRequestBuilder.request;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.gen5.api.DynamicTest;
import org.junit.gen5.api.Nested;
import org.junit.gen5.api.Test;
import org.junit.gen5.api.TestFactory;
import org.junit.gen5.commons.JUnitException;
import org.junit.gen5.commons.util.PreconditionViolationException;
import org.junit.gen5.engine.DiscoverySelector;
import org.junit.gen5.engine.EngineDiscoveryRequest;
import org.junit.gen5.engine.TestDescriptor;
import org.junit.gen5.engine.UniqueId;
import org.junit.gen5.engine.discovery.ClassSelector;
import org.junit.gen5.engine.discovery.ClasspathSelector;
import org.junit.gen5.engine.discovery.MethodSelector;
import org.junit.gen5.engine.discovery.PackageSelector;
import org.junit.gen5.engine.discovery.UniqueIdSelector;
import org.junit.gen5.engine.junit5.descriptor.TestFactoryTestDescriptor;
/**
* @since 5.0
*/
public class DiscoverySelectorResolverTests {
private final JUnit5EngineDescriptor engineDescriptor = new JUnit5EngineDescriptor(engineId());
private DiscoverySelectorResolver resolver = new DiscoverySelectorResolver();
@Test
public void singleClassResolution() {
ClassSelector selector = ClassSelector.forClass(MyTestClass.class);
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(4, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(MyTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test1()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test2()")));
assertTrue(uniqueIds.contains(uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()")));
}
@Test
public void duplicateClassSelectorOnlyResolvesOnce() {
resolver.resolveSelectors(request().select( //
ClassSelector.forClass(MyTestClass.class), //
ClassSelector.forClass(MyTestClass.class) //
).build(), engineDescriptor);
assertEquals(4, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(MyTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test1()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test2()")));
assertTrue(uniqueIds.contains(uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()")));
}
@Test
public void twoClassesResolution() {
ClassSelector selector1 = ClassSelector.forClass(MyTestClass.class);
ClassSelector selector2 = ClassSelector.forClass(YourTestClass.class);
resolver.resolveSelectors(request().select(selector1, selector2).build(), engineDescriptor);
assertEquals(7, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(MyTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test1()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test2()")));
assertTrue(uniqueIds.contains(uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()")));
assertTrue(uniqueIds.contains(uniqueIdForClass(YourTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(YourTestClass.class, "test3()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(YourTestClass.class, "test4()")));
}
@Test
public void classResolutionOfStaticNestedClass() {
ClassSelector selector = ClassSelector.forClass(OtherTestClass.NestedTestClass.class);
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(3, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(OtherTestClass.NestedTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(OtherTestClass.NestedTestClass.class, "test5()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(OtherTestClass.NestedTestClass.class, "test6()")));
}
@Test
public void methodResolution() throws NoSuchMethodException {
Method test1 = MyTestClass.class.getDeclaredMethod("test1");
MethodSelector selector = MethodSelector.forMethod(test1.getDeclaringClass(), test1);
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(2, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(MyTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test1()")));
}
@Test
public void methodResolutionFromInheritedMethod() throws NoSuchMethodException {
MethodSelector selector = MethodSelector.forMethod(HerTestClass.class,
MyTestClass.class.getDeclaredMethod("test1"));
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(2, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(HerTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(HerTestClass.class, "test1()")));
}
@Test
public void resolvingSelectorOfNonTestMethodResolvesNothing() throws NoSuchMethodException {
Method notATest = MyTestClass.class.getDeclaredMethod("notATest");
MethodSelector selector = MethodSelector.forMethod(notATest.getDeclaringClass(), notATest);
EngineDiscoveryRequest request = request().select(selector).build();
resolver.resolveSelectors(request, engineDescriptor);
assertTrue(engineDescriptor.allDescendants().isEmpty());
}
@Test
public void classResolutionByUniqueId() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(uniqueIdForClass(MyTestClass.class).toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(4, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(MyTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test1()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test2()")));
assertTrue(uniqueIds.contains(uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()")));
}
@Test
public void staticNestedClassResolutionByUniqueId() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForClass(OtherTestClass.NestedTestClass.class).toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(3, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(OtherTestClass.NestedTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(OtherTestClass.NestedTestClass.class, "test5()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(OtherTestClass.NestedTestClass.class, "test6()")));
}
@Test
public void methodOfInnerClassByUniqueId() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(OtherTestClass.NestedTestClass.class, "test5()").toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(2, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(OtherTestClass.NestedTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(OtherTestClass.NestedTestClass.class, "test5()")));
}
@Test
public void resolvingUniqueIdWithUnknownSegmentTypeResolvesNothing() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(engineId().append("poops", "machine").toString());
EngineDiscoveryRequest request = request().select(selector).build();
resolver.resolveSelectors(request, engineDescriptor);
assertTrue(engineDescriptor.allDescendants().isEmpty());
}
@Test
public void resolvingUniqueIdOfNonTestMethodResolvesNothing() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(uniqueIdForMethod(MyTestClass.class, "notATest()"));
EngineDiscoveryRequest request = request().select(selector).build();
resolver.resolveSelectors(request, engineDescriptor);
assertTrue(engineDescriptor.allDescendants().isEmpty());
}
@Test
public void methodResolutionByUniqueIdWithNullInput() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(uniqueIdForMethod(getClass(), null));
assertMethodDoesNotMatchPattern(selector);
}
@Test
public void methodResolutionByUniqueIdWithEmptyInput() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(uniqueIdForMethod(getClass(), " "));
assertMethodDoesNotMatchPattern(selector);
}
@Test
public void methodResolutionByUniqueIdWithMissingMethodName() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(uniqueIdForMethod(getClass(), "()"));
assertMethodDoesNotMatchPattern(selector);
}
@Test
public void methodResolutionByUniqueIdWithMissingParameters() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(uniqueIdForMethod(getClass(), "methodName"));
assertMethodDoesNotMatchPattern(selector);
}
@Test
public void methodResolutionByUniqueIdWithBogusParameters() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(getClass(), "methodName(java.lang.String, junit.foo.Enigma)"));
Exception exception = expectThrows(JUnitException.class,
() -> resolver.resolveSelectors(request().select(selector).build(), engineDescriptor));
assertThat(exception).hasMessageStartingWith("Failed to load parameter type");
assertThat(exception).hasMessageContaining("junit.foo.Enigma");
}
private void assertMethodDoesNotMatchPattern(UniqueIdSelector selector) {
Exception exception = expectThrows(PreconditionViolationException.class,
() -> resolver.resolveSelectors(request().select(selector).build(), engineDescriptor));
assertThat(exception).hasMessageStartingWith("Method");
assertThat(exception).hasMessageContaining("does not match pattern");
}
@Test
public void methodResolutionByUniqueId() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(MyTestClass.class, "test1()").toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(2, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(MyTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test1()")));
}
@Test
public void methodResolutionByUniqueIdFromInheritedClass() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(HerTestClass.class, "test1()").toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(2, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(HerTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(HerTestClass.class, "test1()")));
}
@Test
public void methodResolutionByUniqueIdWithParams() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(HerTestClass.class, "test7(java.lang.String)").toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(2, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(HerTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(HerTestClass.class, "test7(java.lang.String)")));
}
@Test
public void resolvingUniqueIdWithWrongParamsResolvesNothing() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(HerTestClass.class, "test7(java.math.BigDecimal)").toString());
EngineDiscoveryRequest request = request().select(selector).build();
resolver.resolveSelectors(request, engineDescriptor);
assertTrue(engineDescriptor.allDescendants().isEmpty());
}
@Test
public void twoMethodResolutionsByUniqueId() {
UniqueIdSelector selector1 = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(MyTestClass.class, "test1()").toString());
UniqueIdSelector selector2 = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(MyTestClass.class, "test2()").toString());
// adding same selector twice should have no effect
resolver.resolveSelectors(request().select(selector1, selector2, selector2).build(), engineDescriptor);
assertEquals(3, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(MyTestClass.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test1()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(MyTestClass.class, "test2()")));
TestDescriptor classFromMethod1 = descriptorByUniqueId(
uniqueIdForMethod(MyTestClass.class, "test1()")).getParent().get();
TestDescriptor classFromMethod2 = descriptorByUniqueId(
uniqueIdForMethod(MyTestClass.class, "test2()")).getParent().get();
assertEquals(classFromMethod1, classFromMethod2);
assertSame(classFromMethod1, classFromMethod2);
}
@Test
public void resolvingDynamicTestByUniqueIdResolvesOnlyUpToParentTestFactory() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()").append(
TestFactoryTestDescriptor.DYNAMIC_TEST_SEGMENT_TYPE, "%1"));
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertThat(engineDescriptor.allDescendants()).hasSize(2);
assertThat(uniqueIds()).containsSequence(uniqueIdForClass(MyTestClass.class),
uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()"));
}
@Test
public void resolvingTestFactoryMethodByUniqueId() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()"));
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertThat(engineDescriptor.allDescendants()).hasSize(2);
assertThat(uniqueIds()).containsSequence(uniqueIdForClass(MyTestClass.class),
uniqueIdForTestFactoryMethod(MyTestClass.class, "dynamicTest()"));
}
@Test
public void packageResolution() {
PackageSelector selector = PackageSelector.forPackageName("org.junit.gen5.engine.junit5.descriptor.subpackage");
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(6, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(
uniqueIdForClass(org.junit.gen5.engine.junit5.descriptor.subpackage.Class1WithTestCases.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(
org.junit.gen5.engine.junit5.descriptor.subpackage.Class1WithTestCases.class, "test1()")));
assertTrue(uniqueIds.contains(
uniqueIdForClass(org.junit.gen5.engine.junit5.descriptor.subpackage.Class2WithTestCases.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(
org.junit.gen5.engine.junit5.descriptor.subpackage.Class2WithTestCases.class, "test2()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(
org.junit.gen5.engine.junit5.descriptor.subpackage.ClassWithStaticInnerTestCases.ShouldBeDiscovered.class,
"test1()")));
}
@Test
public void classpathResolution() {
File classpath = new File(
DiscoverySelectorResolverTests.class.getProtectionDomain().getCodeSource().getLocation().getPath());
List<DiscoverySelector> selector = ClasspathSelector.forPath(classpath.getAbsolutePath());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertTrue(engineDescriptor.allDescendants().size() > 500, "Too few test descriptors in classpath");
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(
uniqueIdForClass(org.junit.gen5.engine.junit5.descriptor.subpackage.Class1WithTestCases.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(
org.junit.gen5.engine.junit5.descriptor.subpackage.Class1WithTestCases.class, "test1()")));
assertTrue(uniqueIds.contains(
uniqueIdForClass(org.junit.gen5.engine.junit5.descriptor.subpackage.Class2WithTestCases.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(
org.junit.gen5.engine.junit5.descriptor.subpackage.Class2WithTestCases.class, "test2()")));
assertTrue(uniqueIds.contains(uniqueIdForMethod(
org.junit.gen5.engine.junit5.descriptor.subpackage.ClassWithStaticInnerTestCases.ShouldBeDiscovered.class,
"test1()")));
}
@Test
public void nestedTestResolutionFromBaseClass() {
ClassSelector selector = ClassSelector.forClass(TestCaseWithNesting.class);
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
List<UniqueId> uniqueIds = uniqueIds();
assertEquals(6, uniqueIds.size());
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.class, "testA()")));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.class, "testB()")));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.DoubleNestedTest.class)));
assertTrue(
uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.DoubleNestedTest.class, "testC()")));
}
@Test
public void nestedTestResolutionFromNestedTestClass() {
ClassSelector selector = ClassSelector.forClass(TestCaseWithNesting.NestedTest.class);
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
List<UniqueId> uniqueIds = uniqueIds();
assertEquals(5, uniqueIds.size());
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.class, "testB()")));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.DoubleNestedTest.class)));
assertTrue(
uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.DoubleNestedTest.class, "testC()")));
}
@Test
public void nestedTestResolutionFromUniqueId() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForClass(TestCaseWithNesting.NestedTest.DoubleNestedTest.class).toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
List<UniqueId> uniqueIds = uniqueIds();
assertEquals(4, uniqueIds.size());
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.DoubleNestedTest.class)));
assertTrue(
uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.DoubleNestedTest.class, "testC()")));
}
@Test
public void doubleNestedTestResolutionFromClass() {
ClassSelector selector = ClassSelector.forClass(TestCaseWithNesting.NestedTest.DoubleNestedTest.class);
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
List<UniqueId> uniqueIds = uniqueIds();
assertEquals(4, uniqueIds.size());
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.DoubleNestedTest.class)));
assertTrue(
uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.DoubleNestedTest.class, "testC()")));
}
@Test
public void methodResolutionInDoubleNestedTestClass() throws NoSuchMethodException {
MethodSelector selector = MethodSelector.forMethod(TestCaseWithNesting.NestedTest.DoubleNestedTest.class,
TestCaseWithNesting.NestedTest.DoubleNestedTest.class.getDeclaredMethod("testC"));
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
assertEquals(4, engineDescriptor.allDescendants().size());
List<UniqueId> uniqueIds = uniqueIds();
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.DoubleNestedTest.class)));
assertTrue(
uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.DoubleNestedTest.class, "testC()")));
}
@Test
public void nestedTestResolutionFromUniqueIdToMethod() {
UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
uniqueIdForMethod(TestCaseWithNesting.NestedTest.class, "testB()").toString());
resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
List<UniqueId> uniqueIds = uniqueIds();
assertEquals(3, uniqueIds.size());
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.class)));
assertTrue(uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.class, "testB()")));
}
private TestDescriptor descriptorByUniqueId(UniqueId uniqueId) {
return engineDescriptor.allDescendants().stream().filter(
d -> d.getUniqueId().equals(uniqueId)).findFirst().get();
}
private List<UniqueId> uniqueIds() {
return engineDescriptor.allDescendants().stream().map(TestDescriptor::getUniqueId).collect(Collectors.toList());
}
}
class MyTestClass {
@Test
void test1() {
}
@Test
void test2() {
}
void notATest() {
}
@TestFactory
Stream<DynamicTest> dynamicTest() {
return new ArrayList<DynamicTest>().stream();
}
}
class YourTestClass {
@Test
void test3() {
}
@Test
void test4() {
}
}
class HerTestClass extends MyTestClass {
@Test
void test7(String param) {
}
}
class OtherTestClass {
static class NestedTestClass {
@Test
void test5() {
}
@Test
void test6() {
}
}
}
class TestCaseWithNesting {
@Test
void testA() {
}
@Nested
class NestedTest {
@Test
void testB() {
}
@Nested
class DoubleNestedTest {
@Test
void testC() {
}
}
}
}
|
Polishing
|
junit-tests/src/test/java/org/junit/gen5/engine/junit5/discovery/DiscoverySelectorResolverTests.java
|
Polishing
|
<ide><path>unit-tests/src/test/java/org/junit/gen5/engine/junit5/discovery/DiscoverySelectorResolverTests.java
<ide>
<ide> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
<ide> assertTrue(uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.class, "testA()")));
<del> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.class)));
<del> assertTrue(uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.class, "testB()")));
<del> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.DoubleNestedTest.class)));
<del> assertTrue(
<del> uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.DoubleNestedTest.class, "testC()")));
<add> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.class)));
<add> assertTrue(uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.class, "testB()")));
<add> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class)));
<add> assertTrue(uniqueIds.contains(
<add> uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class, "testC()")));
<ide> }
<ide>
<ide> @Test
<ide> public void nestedTestResolutionFromNestedTestClass() {
<del> ClassSelector selector = ClassSelector.forClass(TestCaseWithNesting.NestedTest.class);
<add> ClassSelector selector = ClassSelector.forClass(TestCaseWithNesting.NestedTestCase.class);
<ide>
<ide> resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
<ide>
<ide> assertEquals(5, uniqueIds.size());
<ide>
<ide> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
<del> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.class)));
<del> assertTrue(uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.class, "testB()")));
<del> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.DoubleNestedTest.class)));
<del> assertTrue(
<del> uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.DoubleNestedTest.class, "testC()")));
<add> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.class)));
<add> assertTrue(uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.class, "testB()")));
<add> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class)));
<add> assertTrue(uniqueIds.contains(
<add> uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class, "testC()")));
<ide> }
<ide>
<ide> @Test
<ide> public void nestedTestResolutionFromUniqueId() {
<ide> UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
<del> uniqueIdForClass(TestCaseWithNesting.NestedTest.DoubleNestedTest.class).toString());
<add> uniqueIdForClass(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class).toString());
<ide>
<ide> resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
<ide>
<ide> assertEquals(4, uniqueIds.size());
<ide>
<ide> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
<del> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.class)));
<del> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.DoubleNestedTest.class)));
<del> assertTrue(
<del> uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.DoubleNestedTest.class, "testC()")));
<add> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.class)));
<add> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class)));
<add> assertTrue(uniqueIds.contains(
<add> uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class, "testC()")));
<ide> }
<ide>
<ide> @Test
<ide> public void doubleNestedTestResolutionFromClass() {
<del> ClassSelector selector = ClassSelector.forClass(TestCaseWithNesting.NestedTest.DoubleNestedTest.class);
<add> ClassSelector selector = ClassSelector.forClass(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class);
<ide>
<ide> resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
<ide>
<ide> assertEquals(4, uniqueIds.size());
<ide>
<ide> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
<del> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.class)));
<del> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.DoubleNestedTest.class)));
<del> assertTrue(
<del> uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.DoubleNestedTest.class, "testC()")));
<add> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.class)));
<add> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class)));
<add> assertTrue(uniqueIds.contains(
<add> uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class, "testC()")));
<ide> }
<ide>
<ide> @Test
<ide> public void methodResolutionInDoubleNestedTestClass() throws NoSuchMethodException {
<del> MethodSelector selector = MethodSelector.forMethod(TestCaseWithNesting.NestedTest.DoubleNestedTest.class,
<del> TestCaseWithNesting.NestedTest.DoubleNestedTest.class.getDeclaredMethod("testC"));
<add> MethodSelector selector = MethodSelector.forMethod(
<add> TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class,
<add> TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class.getDeclaredMethod("testC"));
<ide>
<ide> resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
<ide>
<ide> assertEquals(4, engineDescriptor.allDescendants().size());
<ide> List<UniqueId> uniqueIds = uniqueIds();
<ide> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
<del> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.class)));
<del> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.DoubleNestedTest.class)));
<del> assertTrue(
<del> uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.DoubleNestedTest.class, "testC()")));
<add> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.class)));
<add> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class)));
<add> assertTrue(uniqueIds.contains(
<add> uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.DoubleNestedTestCase.class, "testC()")));
<ide> }
<ide>
<ide> @Test
<ide> public void nestedTestResolutionFromUniqueIdToMethod() {
<ide> UniqueIdSelector selector = UniqueIdSelector.forUniqueId(
<del> uniqueIdForMethod(TestCaseWithNesting.NestedTest.class, "testB()").toString());
<add> uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.class, "testB()").toString());
<ide>
<ide> resolver.resolveSelectors(request().select(selector).build(), engineDescriptor);
<ide>
<ide> List<UniqueId> uniqueIds = uniqueIds();
<ide> assertEquals(3, uniqueIds.size());
<ide> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.class)));
<del> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTest.class)));
<del> assertTrue(uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTest.class, "testB()")));
<add> assertTrue(uniqueIds.contains(uniqueIdForClass(TestCaseWithNesting.NestedTestCase.class)));
<add> assertTrue(uniqueIds.contains(uniqueIdForMethod(TestCaseWithNesting.NestedTestCase.class, "testB()")));
<ide> }
<ide>
<ide> private TestDescriptor descriptorByUniqueId(UniqueId uniqueId) {
<ide>
<ide> @Test
<ide> void test1() {
<del>
<ide> }
<ide>
<ide> @Test
<ide> void test2() {
<del>
<ide> }
<ide>
<ide> void notATest() {
<del>
<ide> }
<ide>
<ide> @TestFactory
<ide>
<ide> @Test
<ide> void test3() {
<del>
<ide> }
<ide>
<ide> @Test
<ide> void test4() {
<del>
<del> }
<del>
<add> }
<ide> }
<ide>
<ide> class HerTestClass extends MyTestClass {
<ide>
<ide> @Test
<ide> void test7(String param) {
<del>
<ide> }
<ide> }
<ide>
<ide>
<ide> @Test
<ide> void test5() {
<del>
<ide> }
<ide>
<ide> @Test
<ide> void test6() {
<del>
<ide> }
<del>
<ide> }
<ide> }
<ide>
<ide>
<ide> @Test
<ide> void testA() {
<del>
<ide> }
<ide>
<ide> @Nested
<del> class NestedTest {
<add> class NestedTestCase {
<ide>
<ide> @Test
<ide> void testB() {
<del>
<ide> }
<ide>
<ide> @Nested
<del> class DoubleNestedTest {
<add> class DoubleNestedTestCase {
<ide>
<ide> @Test
<ide> void testC() {
<del>
<ide> }
<del>
<ide> }
<del>
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
58d5173b2ef6825b03c322b883de3ed980d19a46
| 0 |
makszlo/zlobin
|
package ru.job4j.array;
import java.util.Arrays;
/**
* Class for bubble array duplicate task.
* @author Maxim Zlobin (mailto:[email protected])
* @since 14.11.2017
* @version 0.1
*/
public class ArrayDuplicate {
/**
* Метод удаляет дубликаты из массива String.
* @param array - массив String с дубликатами.
* @return - массив String без дубликатов.
*/
public String[] remove(String[] array) {
int uniqueCounter = array.length;
int i = 1;
String tmp;
while (i != uniqueCounter) {
for (int j = 0; j < i; j++) {
if (array[i].equals(array[j])) {
uniqueCounter--;
tmp = array[uniqueCounter];
array[uniqueCounter] = array[i];
array[i] = tmp;
break;
} else if (j == i - 1) {
i++;
break;
}
}
}
return Arrays.copyOf(array, uniqueCounter);
}
}
|
chapter_001/src/main/java/ru/job4j/array/ArrayDuplicate.java
|
package ru.job4j.array;
import java.util.Arrays;
/**
* Class for bubble array duplicate task.
* @author Maxim Zlobin (mailto:[email protected])
* @since 14.11.2017
* @version 0.1
*/
public class ArrayDuplicate {
/**
* Метод удаляет дубликаты из массива String.
* @param array - массив String с дубликатами.
* @return - массив String без дубликатов.
*/
public String[] remove(String[] array) {
int uniqueCounter = array.length;
int i = 1;
String tmp;
while ((i != uniqueCounter) || (i == 5)) {
for (int j = 0; j < i; j++) {
if (array[i].equals(array[j])) {
uniqueCounter--;
tmp = array[uniqueCounter];
array[uniqueCounter] = array[i];
array[i] = tmp;
break;
} else if (j == i - 1) {
i++;
break;
}
}
}
return Arrays.copyOf(array, uniqueCounter);
}
}
|
5.3. Удаление дубликатов в массиве. Удалил лишнее условие
|
chapter_001/src/main/java/ru/job4j/array/ArrayDuplicate.java
|
5.3. Удаление дубликатов в массиве. Удалил лишнее условие
|
<ide><path>hapter_001/src/main/java/ru/job4j/array/ArrayDuplicate.java
<ide> int uniqueCounter = array.length;
<ide> int i = 1;
<ide> String tmp;
<del> while ((i != uniqueCounter) || (i == 5)) {
<add> while (i != uniqueCounter) {
<ide> for (int j = 0; j < i; j++) {
<ide> if (array[i].equals(array[j])) {
<ide> uniqueCounter--;
|
|
JavaScript
|
cc0-1.0
|
527caa5559fc789fa9b5ee005bb6a1a4b4b29b06
| 0 |
pokemoncentral/wiki-macros,pokemoncentral/wiki-macros
|
'use strict';
/**
* Basic, uncategorized macros that are small enough to be packed
* in a single file
*/
(function(utils) {
const macros = utils.macros;
macros.tipi = function(str) {
return str
.replace(/\bgrass\b/g, 'erba').replace(/\bGrass\b/g, 'Erba')
.replace(/\bWater\b/g, 'Acqua').replace(/\bwater\b/g, 'acqua')
.replace(/\bFire\b/g, 'Fuoco').replace(/\bfire\b/g, 'fuoco')
.replace(/\bFlying\b/g, 'Volante').replace(/\bflying\b/g, 'volante')
.replace(/\bFighting\b/g, 'Lotta').replace(/\bfighting\b/g, 'lotta')
.replace(/\bGround\b/g, 'Terra').replace(/\bground\b/g, 'terra')
.replace(/\bDark\b/g, 'Buio').replace(/\bdark\b/g, 'buio')
.replace(/\bDragon\b/g, 'Drago').replace(/\bdragon\b/g, 'drago')
.replace(/\bRock\b/g, 'Roccia').replace(/\brock\b/g, 'roccia')
.replace(/\bPoison\b/g, 'Veleno').replace(/\bpoison\b/g, 'veleno')
.replace(/\bGhost\b/g, 'Spettro').replace(/\bghost\b/g, 'spettro')
.replace(/\bPsychic\b/g, 'Psico').replace(/\bpsychic\b/g, 'psico')
.replace(/\bElectric\b/g, 'Elettro').replace(/\belectric\b/g, 'elettro')
.replace(/\bSteel\b/g, 'Acciaio').replace(/\bsteel\b/g, 'acciaio')
.replace(/\bNormal\b/g, 'Normale').replace(/\bnormal\b/g, 'normale')
.replace(/\bBug\b/g, 'Coleottero').replace(/\bbug\b/g, 'coleottero')
.replace(/\bFairy\b/g, 'Folletto').replace(/\bfairy\b/g, 'folletto')
.replace(/\bUnknown\b/g, 'Sconosciuto').replace(/\bunknown\b/g, 'sconosciuto')
.replace(/\bShadow\b/g, 'Ombra').replace(/\bshadow\b/g, 'ombra')
.replace(/\bIce\b/g, 'Ghiaccio').replace(/\bice\b/g, 'ghiaccio')
// Categorie danno
.replace(/\bSpecial\b/g, 'Speciale').replace(/\bspecial\b/g, 'speciale')
.replace(/\bStatus\b/g, 'Stato').replace(/\bstatus\b/g, 'stato')
.replace(/\bPhysical\b/g, 'Fisico').replace(/\bphysical\b/g, 'fisico')
// Correzione errori
.replace(/Voloing/g, 'Volante').replace(/voloing/g, 'volante')
.replace(/[Pp]sichico\|[Ff]isico/g, 'Psico|Fisico')
.replace(/[Pp]sichico\|[Ss]peciale/g, 'Psico|Speciale')
.replace(/[Pp]sichico\|[Ss]tato/g, 'Psico|Stato')
.replace(/colore\s*\|?\s*(.+?)\s*\|?\s*buio\s*\}\}/gi,
'colore | $1 | dark }}')
};
macros.gare = function(str) {
// Statistiche gara
return str.replace(/Tough/gi, 'Grinta')
.replace(/Cool/gi, 'Classe')
.replace(/(Smart|Clever)/gi, 'Acume')
.replace(/Beaut(y|iful)/gi, 'Bellezza')
.replace(/Cute/gi, 'Grazia')
// Correzione errori
.replace(/TentaClasse/g, 'Tentacool')
.replace(/ExeggGrazia/g, 'Exeggcute');
};
macros.generazioni = function(str, lastConj) {
lastConj = lastConj || 'e';
var ordinals = {1 : 'prima', 2 : 'seconda',
3 : 'terza', 4 : 'quarta', 5 : 'quinta',
6 : 'sesta', I : 'prima', II : 'seconda',
III : 'terza', IV : 'quarta', V : 'quinta', VI: 'sesta'};
return str.replace(/gen(eration)? ([1-7IV]+[-/1-6IV]*)+/gi,
function(str, placeholder, gens) {
gens = gens.match(/[1-7IV]+/gi);
for (var k = 0; k < gens.length; ++k)
gens[k] = ordinals[gens[k]];
if (gens.length == 1)
return gens[0] + ' generazione';
var lastGen = gens.pop();
return gens.join(', ') + ' ' + lastConj + ' '
+ lastGen + ' generazione';
});
};
/*
Il secondo argomento deve essere true per far sì che vengano
tradotti HeartGold e SoulSilver in Oro HeartGold e Argento
SoulSilver
*/
macros.giochi = function(str, transHGSS) {
transHGSS = transHGSS == null || transHGSS;
// Eccezioni per i colori
str = str.replace(/firered color/gi, 'rossofuoco color')
.replace(/leafgreen color/gi, 'verdefoglia color')
.replace(/black2 color/gi, 'nero2 color')
.replace(/white2 color/gi, 'bianco2 color');
if (transHGSS) {
str = str.replace(/SoulSilver/g, 'Argento SoulSilver')
.replace(/HeartGold/g, 'Oro HeartGold')
// Correzione errori
.replace(/Argento Argento SoulSilver/g, 'Argento SoulSilver')
.replace(/Oro Oro HeartGold/g, 'Oro HeartGold');
}
// Traduzione nomi giochi
return str.replace(/FireRed/gi, 'Rosso Fuoco')
.replace(/LeafGreen/gi, 'Verde Foglia')
.replace(/Alpha Sapphire/gi, 'Zaffiro Alpha')
.replace(/Omega Ruby/gi, 'Rubino Omega')
.replace(/\bGold\b/gi, 'Oro')
.replace(/\bSilver\b/gi, 'Argento')
.replace(/\bRed\b/gi, 'Rosso')
.replace(/\bBlue\b/gi, 'Blu')
.replace(/\bGreen\b/gi, 'Verde')
.replace(/Crystal/gi, 'Cristallo')
.replace(/Yellow/gi, 'Giallo')
.replace(/\bRuby\b/gi, 'Rubino')
.replace(/Sapphire/gi, 'Zaffiro')
.replace(/Emerald/gi, 'Smeraldo')
.replace(/Diamond/gi, 'Diamante')
.replace(/\bPearl\b/gi, 'Perla')
.replace(/Platinum/gi, 'Platino')
.replace(/\bBlack\b/gi, 'Nero')
.replace(/\bWhite\b/gi, 'Bianco')
// Traduzione sigle dei giochi
.replace(/\bRG_/g, 'RV_')
.replace(/\bRG\b/g, 'RV')
.replace(/\bRGB_/g, 'RVB_')
.replace(/\bRGB\b/g, 'RVB')
.replace(/\bRGBY_/g, 'RVBG_')
.replace(/\bRGBY\b/g, 'RVBG')
.replace(/\bY\b/g, 'G')
.replace(/\bY_/g, 'G_')
.replace(/\bGS_/g, 'OA_')
.replace(/\bGS\b/g, 'OA')
.replace(/\bGSC_/g, 'OAC_')
.replace(/\bGSC\b/g, 'OAC')
.replace(/\bRu?Sa?_/g, 'RZ_')
.replace(/\bRu?Sa?\b/g, 'RZ')
.replace(/\bSa_/g, 'Z_')
.replace(/\bSa\b/g, 'Z')
.replace(/\bRSE_/g, 'RZS_')
.replace(/\bRSE\b/g, 'RZS')
.replace(/\bRE_/g, 'RS_')
.replace(/\bRE\b/g, 'RS')
.replace(/\bSE_/g, 'ZS_')
.replace(/\bSE\b/g, 'ZS')
.replace(/\bE_/g, 'S_')
.replace(/\bE\b/g, 'S')
.replace(/\bFR?LG?_/g, 'RFVF_')
.replace(/\bFR?LG?\b/g, 'RFVF')
.replace(/\bHS_/g, 'HGSS_')
.replace(/\bHS\b/g, 'HGSS')
.replace(/\bBW_/g, 'NB_')
.replace(/\bBW\b/g, 'NB')
.replace(/\bB2W2_/g, 'N2B2_')
.replace(/\bB2W2\b/g, 'N2B2')
.replace(/\bBl_/g, 'N_')
.replace(/\bBl\b/g, 'N')
.replace(/\bW_/g, 'Bi_')
.replace(/\bW\b/g, 'Bi')
.replace(/\bB2_/g, 'N2_')
.replace(/\bB2\b/g, 'N2')
.replace(/\bW2_/g, 'B2_')
.replace(/\bW2\b/g, 'B2')
.replace(/\bBWB2W2_/g, 'NBN2B2_')
.replace(/\bBWB2W2\b/g, 'NBN2B2')
.replace(/\by_/g, 'Y_')
.replace(/\by\b/g, 'Y')
.replace(/\bOR_/g, 'RO_')
.replace(/\bOR\b/g, 'RO')
.replace(/\bAS_/g, 'ZA_')
.replace(/\bAS\b/g, 'ZA')
.replace(/\bORAS_/g, 'ROZA_')
.replace(/\bORAS\b/g, 'ROZA')
.replace(/\bXYORAS_/g, 'XYROZA_')
.replace(/\bXYORAS\b/g, 'XYROZA')
.replace(/([\|=]\n?)Pokémon Stadium(\n?[\|=])/g, '$1St$2')
.replace(/([\|=]\n?)Pokémon Stadium 2(\n?[\|=])/g, '$1St2$2')
.replace(/\bSM_/g, 'SL_')
.replace(/\bSM\b/g, 'SL')
.replace(/\bUSUM_/g, 'USUL_')
.replace(/\bUSUM\b/g, 'USUL')
.replace(/\bSMUSUM_/g, 'SLUSUL_')
.replace(/\bSMUSUM\b/g, 'SLUSUL')
.replace(/\bSwSh_/g, 'SpSc_')
.replace(/\bSwSh\b/g, 'SpSc')
// Correzione errori
.replace(/Diamante\s?Storm/gi, 'Diamantempesta');
};
macros.colori = function(str) {
str = str.replace(/color buio/gi, 'color dark');
var matches = /\{\{([\s\w]+) color\s?[dark|light]?\}\}/gi.exec(str);
str = str.replace(/\{\{([\s\w]+) color\s?((dark|light))?\}\}/gi,
'{{#invoke: colore | $1 | $2 }}')
.replace(/(\{\{#invoke: colore \| .+? )\|\s*\}\}/gi, '$1| normale }}');
if (matches && matches.length)
for (var k = 1; k < matches.length; ++k)
str = str.replace(matches[k], matches[k].replace(/\s/g, '_'));
return str;
};
macros['nature'] = function(str) {
return str.replace(/Hardy/g, 'Ardita')
.replace(/Lonely/g, 'Schiva')
.replace(/Brave/g, 'Audace')
.replace(/Adamant/g, 'Decisa')
.replace(/Naughty/g, 'Birbona')
.replace(/Bold/g, 'Sicura')
// .replace(/Docile/g, 'Docile')
.replace(/Relaxed/g, 'Placida')
.replace(/Impish/g, 'Scaltra')
.replace(/Lax/g, 'Fiacca')
.replace(/Timid/g, 'Timida')
.replace(/Hasty/g, 'Lesta')
.replace(/Serious/g, 'Seria')
.replace(/Jolly/g, 'Allegra')
.replace(/Naive/g, 'Ingenua')
.replace(/Modest/g, 'Modesta')
.replace(/Mild/g, 'Mite')
.replace(/Quiet/g, 'Quieta')
.replace(/Bashful/g, 'Ritrosa')
.replace(/Rash/g, 'Ardente')
.replace(/Calm/g, 'Calma')
.replace(/Gentle/g, 'Gentile')
.replace(/Sassy/g, 'Vivace')
.replace(/Careful/g, 'Cauta')
.replace(/Quirky/g, 'Furba')
// Correzione errori
.replace(/Timidaa/g, 'Timida')
.replace(/Modestaa/g, 'Modesta')
.replace(/Quietaa/g, 'Quieta')
.replace(/Calmaa/g, 'Calma')
.replace(/Audace Bird/g, 'Brave Bird')
.replace(/Decisa Orb/g, 'Adamant Orb')
.replace(/Fiacca Incense/g, 'Lax Incense')
.replace(/Calma Mind/g, 'Calm Mind')
};
macros.date = function(str) {
return str
.replace(/January (\d+), (\d+)/g, '$1 gennaio $2')
.replace(/February (\d+), (\d+)/g, '$1 febbraio $2')
.replace(/March (\d+), (\d+)/g, '$1 marzo $2')
.replace(/April (\d+), (\d+)/g, '$1 aprile $2')
.replace(/May (\d+), (\d+)/g, '$1 maggio $2')
.replace(/June (\d+), (\d+)/g, '$1 giugno $2')
.replace(/July (\d+), (\d+)/g, '$1 luglio $2')
.replace(/August (\d+), (\d+)/g, '$1 agosto $2')
.replace(/September (\d+), (\d+)/g, '$1 settembre $2')
.replace(/October (\d+), (\d+)/g, '$1 ottobre $2')
.replace(/November (\d+), (\d+)/g, '$1 novembre $2')
.replace(/December (\d+), (\d+)/g, '$1 dicembre $2')
};
if (utils.updateMenu) { utils.updateMenu() } ;
}(utils || { macros: {} }));
|
macros/basic.js
|
'use strict';
/**
* Basic, uncategorized macros that are small enough to be packed
* in a single file
*/
(function(utils) {
const macros = utils.macros;
macros.tipi = function(str) {
return str
.replace(/\bgrass\b/g, 'erba').replace(/\bGrass\b/g, 'Erba')
.replace(/\bWater\b/g, 'Acqua').replace(/\bwater\b/g, 'acqua')
.replace(/\bFire\b/g, 'Fuoco').replace(/\bfire\b/g, 'fuoco')
.replace(/\bFlying\b/g, 'Volante').replace(/\bflying\b/g, 'volante')
.replace(/\bFighting\b/g, 'Lotta').replace(/\bfighting\b/g, 'lotta')
.replace(/\bGround\b/g, 'Terra').replace(/\bground\b/g, 'terra')
.replace(/\bDark\b/g, 'Buio').replace(/\bdark\b/g, 'buio')
.replace(/\bDragon\b/g, 'Drago').replace(/\bdragon\b/g, 'drago')
.replace(/\bRock\b/g, 'Roccia').replace(/\brock\b/g, 'roccia')
.replace(/\bPoison\b/g, 'Veleno').replace(/\bpoison\b/g, 'veleno')
.replace(/\bGhost\b/g, 'Spettro').replace(/\bghost\b/g, 'spettro')
.replace(/\bPsychic\b/g, 'Psico').replace(/\bpsychic\b/g, 'psico')
.replace(/\bElectric\b/g, 'Elettro').replace(/\belectric\b/g, 'elettro')
.replace(/\bSteel\b/g, 'Acciaio').replace(/\bsteel\b/g, 'acciaio')
.replace(/\bNormal\b/g, 'Normale').replace(/\bnormal\b/g, 'normale')
.replace(/\bBug\b/g, 'Coleottero').replace(/\bbug\b/g, 'coleottero')
.replace(/\bFairy\b/g, 'Folletto').replace(/\bfairy\b/g, 'folletto')
.replace(/\bUnknown\b/g, 'Sconosciuto').replace(/\bunknown\b/g, 'sconosciuto')
.replace(/\bShadow\b/g, 'Ombra').replace(/\bshadow\b/g, 'ombra')
.replace(/\bIce\b/g, 'Ghiaccio').replace(/\bice\b/g, 'ghiaccio')
// Categorie danno
.replace(/\bSpecial\b/g, 'Speciale').replace(/\bspecial\b/g, 'speciale')
.replace(/\bStatus\b/g, 'Stato').replace(/\bstatus\b/g, 'stato')
.replace(/\bPhysical\b/g, 'Fisico').replace(/\bphysical\b/g, 'fisico')
// Correzione errori
.replace(/Voloing/g, 'Volante').replace(/voloing/g, 'volante')
.replace(/[Pp]sichico\|[Ff]isico/g, 'Psico|Fisico')
.replace(/[Pp]sichico\|[Ss]peciale/g, 'Psico|Speciale')
.replace(/[Pp]sichico\|[Ss]tato/g, 'Psico|Stato')
.replace(/colore\s*\|?\s*(.+?)\s*\|?\s*buio\s*\}\}/gi,
'colore | $1 | dark }}')
};
macros.gare = function(str) {
// Statistiche gara
return str.replace(/Tough/gi, 'Grinta')
.replace(/Cool/gi, 'Classe')
.replace(/(Smart|Clever)/gi, 'Acume')
.replace(/Beaut(y|iful)/gi, 'Bellezza')
.replace(/Cute/gi, 'Grazia')
// Correzione errori
.replace(/TentaClasse/g, 'Tentacool')
.replace(/ExeggGrazia/g, 'Exeggcute');
};
macros.generazioni = function(str, lastConj) {
lastConj = lastConj || 'e';
var ordinals = {1 : 'prima', 2 : 'seconda',
3 : 'terza', 4 : 'quarta', 5 : 'quinta',
6 : 'sesta', I : 'prima', II : 'seconda',
III : 'terza', IV : 'quarta', V : 'quinta', VI: 'sesta'};
return str.replace(/gen(eration)? ([1-7IV]+[-/1-6IV]*)+/gi,
function(str, placeholder, gens) {
gens = gens.match(/[1-7IV]+/gi);
for (var k = 0; k < gens.length; ++k)
gens[k] = ordinals[gens[k]];
if (gens.length == 1)
return gens[0] + ' generazione';
var lastGen = gens.pop();
return gens.join(', ') + ' ' + lastConj + ' '
+ lastGen + ' generazione';
});
};
/*
Il secondo argomento deve essere true per far sì che vengano
tradotti HeartGold e SoulSilver in Oro HeartGold e Argento
SoulSilver
*/
macros.giochi = function(str, transHGSS) {
transHGSS = transHGSS == null || transHGSS;
// Eccezioni per i colori
str = str.replace(/firered color/gi, 'rossofuoco color')
.replace(/leafgreen color/gi, 'verdefoglia color')
.replace(/black2 color/gi, 'nero2 color')
.replace(/white2 color/gi, 'bianco2 color');
if (transHGSS) {
str = str.replace(/SoulSilver/g, 'Argento SoulSilver')
.replace(/HeartGold/g, 'Oro HeartGold')
// Correzione errori
.replace(/Argento Argento SoulSilver/g, 'Argento SoulSilver')
.replace(/Oro Oro HeartGold/g, 'Oro HeartGold');
}
// Traduzione nomi giochi
return str.replace(/FireRed/gi, 'Rosso Fuoco')
.replace(/LeafGreen/gi, 'Verde Foglia')
.replace(/Alpha Sapphire/gi, 'Zaffiro Alpha')
.replace(/Omega Ruby/gi, 'Rubino Omega')
.replace(/\bGold\b/gi, 'Oro')
.replace(/\bSilver\b/gi, 'Argento')
.replace(/\bRed\b/gi, 'Rosso')
.replace(/\bBlue\b/gi, 'Blu')
.replace(/\bGreen\b/gi, 'Verde')
.replace(/Crystal/gi, 'Cristallo')
.replace(/Yellow/gi, 'Giallo')
.replace(/\bRuby\b/gi, 'Rubino')
.replace(/Sapphire/gi, 'Zaffiro')
.replace(/Emerald/gi, 'Smeraldo')
.replace(/Diamond/gi, 'Diamante')
.replace(/\bPearl\b/gi, 'Perla')
.replace(/Platinum/gi, 'Platino')
.replace(/\bBlack\b/gi, 'Nero')
.replace(/\bWhite\b/gi, 'Bianco')
// Traduzione sigle dei giochi
.replace(/\bRG_/g, 'RV_')
.replace(/\bRG\b/g, 'RV')
.replace(/\bRGB_/g, 'RVB_')
.replace(/\bRGB\b/g, 'RVB')
.replace(/\bRGBY_/g, 'RVBG_')
.replace(/\bRGBY\b/g, 'RVBG')
.replace(/\bY\b/g, 'G')
.replace(/\bY_/g, 'G_')
.replace(/\bGS_/g, 'OA_')
.replace(/\bGS\b/g, 'OA')
.replace(/\bGSC_/g, 'OAC_')
.replace(/\bGSC\b/g, 'OAC')
.replace(/\bRu?Sa?_/g, 'RZ_')
.replace(/\bRu?Sa?\b/g, 'RZ')
.replace(/\bSa_/g, 'Z_')
.replace(/\bSa\b/g, 'Z')
.replace(/\bRSE_/g, 'RZS_')
.replace(/\bRSE\b/g, 'RZS')
.replace(/\bRE_/g, 'RS_')
.replace(/\bRE\b/g, 'RS')
.replace(/\bSE_/g, 'ZS_')
.replace(/\bSE\b/g, 'ZS')
.replace(/\bE_/g, 'S_')
.replace(/\bE\b/g, 'S')
.replace(/\bFR?LG?_/g, 'RFVF_')
.replace(/\bFR?LG?\b/g, 'RFVF')
.replace(/\bHS_/g, 'HGSS_')
.replace(/\bHS\b/g, 'HGSS')
.replace(/\bBW_/g, 'NB_')
.replace(/\bBW\b/g, 'NB')
.replace(/\bB2W2_/g, 'N2B2_')
.replace(/\bB2W2\b/g, 'N2B2')
.replace(/\bBl_/g, 'N_')
.replace(/\bBl\b/g, 'N')
.replace(/\bW_/g, 'Bi_')
.replace(/\bW\b/g, 'Bi')
.replace(/\bB2_/g, 'N2_')
.replace(/\bB2\b/g, 'N2')
.replace(/\bW2_/g, 'B2_')
.replace(/\bW2\b/g, 'B2')
.replace(/\bBWB2W2_/g, 'NBN2B2_')
.replace(/\bBWB2W2\b/g, 'NBN2B2')
.replace(/\by_/g, 'Y_')
.replace(/\by\b/g, 'Y')
.replace(/\bOR_/g, 'RO_')
.replace(/\bOR\b/g, 'RO')
.replace(/\bAS_/g, 'ZA_')
.replace(/\bAS\b/g, 'ZA')
.replace(/\bORAS_/g, 'ROZA_')
.replace(/\bORAS\b/g, 'ROZA')
.replace(/([\|=]\n?)Pokémon Stadium(\n?[\|=])/g, '$1St$2')
.replace(/([\|=]\n?)Pokémon Stadium 2(\n?[\|=])/g, '$1St2$2')
.replace(/\bSM_/g, 'SL_')
.replace(/\bSM\b/g, 'SL')
.replace(/\bUSUM_/g, 'USUL_')
.replace(/\bUSUM\b/g, 'USUL')
.replace(/\bSMUSUM_/g, 'SLUSUL_')
.replace(/\bSMUSUM\b/g, 'SLUSUL')
.replace(/\bSwSh_/g, 'SpSc_')
.replace(/\bSwSh\b/g, 'SpSc')
// Correzione errori
.replace(/Diamante\s?Storm/gi, 'Diamantempesta');
};
macros.colori = function(str) {
str = str.replace(/color buio/gi, 'color dark');
var matches = /\{\{([\s\w]+) color\s?[dark|light]?\}\}/gi.exec(str);
str = str.replace(/\{\{([\s\w]+) color\s?((dark|light))?\}\}/gi,
'{{#invoke: colore | $1 | $2 }}')
.replace(/(\{\{#invoke: colore \| .+? )\|\s*\}\}/gi, '$1| normale }}');
if (matches && matches.length)
for (var k = 1; k < matches.length; ++k)
str = str.replace(matches[k], matches[k].replace(/\s/g, '_'));
return str;
};
macros['nature'] = function(str) {
return str.replace(/Hardy/g, 'Ardita')
.replace(/Lonely/g, 'Schiva')
.replace(/Brave/g, 'Audace')
.replace(/Adamant/g, 'Decisa')
.replace(/Naughty/g, 'Birbona')
.replace(/Bold/g, 'Sicura')
// .replace(/Docile/g, 'Docile')
.replace(/Relaxed/g, 'Placida')
.replace(/Impish/g, 'Scaltra')
.replace(/Lax/g, 'Fiacca')
.replace(/Timid/g, 'Timida')
.replace(/Hasty/g, 'Lesta')
.replace(/Serious/g, 'Seria')
.replace(/Jolly/g, 'Allegra')
.replace(/Naive/g, 'Ingenua')
.replace(/Modest/g, 'Modesta')
.replace(/Mild/g, 'Mite')
.replace(/Quiet/g, 'Quieta')
.replace(/Bashful/g, 'Ritrosa')
.replace(/Rash/g, 'Ardente')
.replace(/Calm/g, 'Calma')
.replace(/Gentle/g, 'Gentile')
.replace(/Sassy/g, 'Vivace')
.replace(/Careful/g, 'Cauta')
.replace(/Quirky/g, 'Furba')
// Correzione errori
.replace(/Timidaa/g, 'Timida')
.replace(/Modestaa/g, 'Modesta')
.replace(/Quietaa/g, 'Quieta')
.replace(/Calmaa/g, 'Calma')
.replace(/Audace Bird/g, 'Brave Bird')
.replace(/Decisa Orb/g, 'Adamant Orb')
.replace(/Fiacca Incense/g, 'Lax Incense')
.replace(/Calma Mind/g, 'Calm Mind')
};
macros.date = function(str) {
return str
.replace(/January (\d+), (\d+)/g, '$1 gennaio $2')
.replace(/February (\d+), (\d+)/g, '$1 febbraio $2')
.replace(/March (\d+), (\d+)/g, '$1 marzo $2')
.replace(/April (\d+), (\d+)/g, '$1 aprile $2')
.replace(/May (\d+), (\d+)/g, '$1 maggio $2')
.replace(/June (\d+), (\d+)/g, '$1 giugno $2')
.replace(/July (\d+), (\d+)/g, '$1 luglio $2')
.replace(/August (\d+), (\d+)/g, '$1 agosto $2')
.replace(/September (\d+), (\d+)/g, '$1 settembre $2')
.replace(/October (\d+), (\d+)/g, '$1 ottobre $2')
.replace(/November (\d+), (\d+)/g, '$1 novembre $2')
.replace(/December (\d+), (\d+)/g, '$1 dicembre $2')
};
if (utils.updateMenu) { utils.updateMenu() } ;
}(utils || { macros: {} }));
|
Added XYORAS -> XYROZA
|
macros/basic.js
|
Added XYORAS -> XYROZA
|
<ide><path>acros/basic.js
<ide> .replace(/\bAS\b/g, 'ZA')
<ide> .replace(/\bORAS_/g, 'ROZA_')
<ide> .replace(/\bORAS\b/g, 'ROZA')
<add> .replace(/\bXYORAS_/g, 'XYROZA_')
<add> .replace(/\bXYORAS\b/g, 'XYROZA')
<ide> .replace(/([\|=]\n?)Pokémon Stadium(\n?[\|=])/g, '$1St$2')
<ide> .replace(/([\|=]\n?)Pokémon Stadium 2(\n?[\|=])/g, '$1St2$2')
<ide> .replace(/\bSM_/g, 'SL_')
|
|
Java
|
apache-2.0
|
c37661c0b3d8776121d6e6c2995285ceffc69cbd
| 0 |
gureronder/midpoint,Pardus-Engerek/engerek,sabriarabacioglu/engerek,PetrGasparik/midpoint,arnost-starosta/midpoint,Pardus-Engerek/engerek,arnost-starosta/midpoint,sabriarabacioglu/engerek,gureronder/midpoint,PetrGasparik/midpoint,gureronder/midpoint,Pardus-Engerek/engerek,rpudil/midpoint,Pardus-Engerek/engerek,rpudil/midpoint,PetrGasparik/midpoint,rpudil/midpoint,arnost-starosta/midpoint,sabriarabacioglu/engerek,rpudil/midpoint,arnost-starosta/midpoint,PetrGasparik/midpoint,arnost-starosta/midpoint,gureronder/midpoint
|
/*
* Copyright (c) 2011 Evolveum
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the License). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the License at
* http://www.opensource.org/licenses/cddl1 or
* CDDLv1.0.txt file in the source code distribution.
* See the License for the specific language governing
* permission and limitations under the License.
*
* If applicable, add the following below the CDDL Header,
* with the fields enclosed by brackets [] replaced by
* your own identifying information:
*
* Portions Copyrighted 2011 [name of copyright owner]
*/
package com.evolveum.midpoint.provisioning.util;
import com.evolveum.midpoint.common.QueryUtil;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.provisioning.ucf.impl.ConnectorFactoryIcfImpl;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.holder.XPathHolder;
import com.evolveum.midpoint.schema.holder.XPathSegment;
import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition;
import com.evolveum.midpoint.schema.processor.ResourceAttribute;
import com.evolveum.midpoint.schema.processor.ResourceAttributeContainer;
import com.evolveum.midpoint.schema.processor.ResourceSchema;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.schema.util.ResourceObjectShadowUtil;
import com.evolveum.midpoint.schema.util.ResourceTypeUtil;
import com.evolveum.midpoint.schema.util.SchemaDebugUtil;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_1.AccountShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ActivationType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceObjectShadowAttributesType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceObjectShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceType;
import com.evolveum.midpoint.xml.ns._public.resource.capabilities_1.ActivationCapabilityType;
import com.evolveum.prism.xml.ns._public.query_2.QueryType;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class ShadowCacheUtil {
private static final Trace LOGGER = TraceManager.getTrace(ShadowCacheUtil.class);
/**
* Make sure that the shadow is complete, e.g. that all the mandatory fields
* are filled (e.g name, resourceRef, ...) Also transforms the shadow with
* respect to simulated capabilities.
*/
public static <T extends ResourceObjectShadowType> T completeShadow(T resourceShadow, T repoShadow,
ResourceType resource, OperationResult parentResult) throws SchemaException {
// repoShadow is a result, we need to copy there everything that needs
// to be there
// If there is no repo shadow, use resource shadow instead
if (repoShadow == null) {
PrismObject<T> repoPrism = resourceShadow.asPrismObject().clone();
repoShadow = repoPrism.asObjectable();
}
ResourceAttributeContainer resourceAttributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(resourceShadow);
ResourceAttributeContainer repoAttributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(repoShadow);
if (repoShadow.getObjectClass() == null) {
repoShadow.setObjectClass(resourceAttributesContainer.getDefinition().getTypeName());
}
if (repoShadow.getName() == null) {
repoShadow.setName(determineShadowName(resourceShadow));
}
if (repoShadow.getResource() == null) {
repoShadow.setResourceRef(ObjectTypeUtil.createObjectRef(resource));
}
// Attributes
// If the shadows are the same then no copy is needed.
if (repoShadow != resourceShadow) {
repoAttributesContainer.getValue().clear();
for (ResourceAttribute resourceAttribute : resourceAttributesContainer.getAttributes()) {
// do not copy simulated activation attrbute
if (isSimulatedActivationAttribute(resourceAttribute, resourceShadow, resource)) {
continue;
}
repoAttributesContainer.add(resourceAttribute);
}
}
// Activation
// FIXME??? when there are not native capabilities for activation, the
// resourceShadow.getActivation is null and the activation for the repo
// shadow are not completed..therefore there need to be one more check,
// we must chceck not only if the activation is null, but if it is, also
// if the shadow doesn't have defined simulated activation capability
if (resourceShadow.getActivation() != null || ResourceTypeUtil.hasActivationCapability(resource)) {
ActivationType activationType = completeActivation(resourceShadow, resource, parentResult);
LOGGER.trace("Determined activation: {}", activationType.isEnabled());
repoShadow.setActivation(activationType);
} else {
repoShadow.setActivation(null);
}
if (repoShadow instanceof AccountShadowType) {
// Credentials
AccountShadowType repoAccountShadow = (AccountShadowType) repoShadow;
AccountShadowType resourceAccountShadow = (AccountShadowType) resourceShadow;
repoAccountShadow.setCredentials(resourceAccountShadow.getCredentials());
}
repoShadow.asPrismObject().checkConsistence();
return repoShadow;
}
private static boolean isSimulatedActivationAttribute(ResourceAttribute attribute,
ResourceObjectShadowType shadow, ResourceType resource) {
if (!ResourceTypeUtil.hasResourceNativeActivationCapability(resource)) {
ActivationCapabilityType activationCapability = ResourceTypeUtil.getEffectiveCapability(resource,
ActivationCapabilityType.class);
if (activationCapability == null) {
// TODO: maybe the warning message is needed that the resource
// does not have either simulater or native capabilities
return false;
}
ResourceAttributeContainer attributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(shadow);
ResourceAttribute activationProperty = attributesContainer.findAttribute(activationCapability
.getEnableDisable().getAttribute());
if (activationProperty != null && activationProperty.equals(attribute)) {
return true;
}
}
return false;
}
public static <T extends ResourceObjectShadowType> void normalizeShadow(T shadow, OperationResult result)
throws SchemaException {
if (shadow.getAttemptNumber() != null) {
shadow.setAttemptNumber(null);
}
if (shadow.getFailedOperationType() != null) {
shadow.setFailedOperationType(null);
}
if (shadow.getObjectChange() != null) {
shadow.setObjectChange(null);
}
if (shadow.getResult() != null) {
shadow.setResult(null);
}
ResourceAttributeContainer normalizedContainer = ResourceObjectShadowUtil
.getAttributesContainer(shadow);
ResourceAttributeContainer oldContainer = normalizedContainer.clone();
normalizedContainer.clear();
Collection<ResourceAttribute<?>> identifiers = oldContainer.getIdentifiers();
for (PrismProperty<?> p : identifiers) {
normalizedContainer.getValue().add(p);
}
Collection<ResourceAttribute<?>> secondaryIdentifiers = oldContainer.getSecondaryIdentifiers();
for (PrismProperty<?> p : secondaryIdentifiers) {
normalizedContainer.getValue().add(p);
}
}
/**
* Completes activation state by determinig simulated activation if
* necessary.
*
* TODO: The placement of this method is not correct. It should go back to
* ShadowConverter
*/
public static ActivationType completeActivation(ResourceObjectShadowType shadow, ResourceType resource,
OperationResult parentResult) {
// HACK to avoid NPE when called from the ICF layer
if (resource == null) {
return shadow.getActivation();
}
if (ResourceTypeUtil.hasResourceNativeActivationCapability(resource)) {
return shadow.getActivation();
} else if (ResourceTypeUtil.hasActivationCapability(resource)) {
return convertFromSimulatedActivationAttributes(shadow, resource, parentResult);
} else {
// No activation capability, nothing to do
return null;
}
}
private static ActivationType convertFromSimulatedActivationAttributes(ResourceObjectShadowType shadow,
ResourceType resource, OperationResult parentResult) {
// LOGGER.trace("Start converting activation type from simulated activation atribute");
ActivationCapabilityType activationCapability = ResourceTypeUtil.getEffectiveCapability(resource,
ActivationCapabilityType.class);
ResourceAttributeContainer attributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(shadow);
// List<Object> values =
// ResourceObjectShadowUtil.getAttributeValues(shadow,
// activationCapability
// .getEnableDisable().getAttribute());
ResourceAttribute activationProperty = attributesContainer.findAttribute(activationCapability
.getEnableDisable().getAttribute());
// LOGGER.trace("activation property: {}", activationProperty.dump());
// if (activationProperty == null) {
// LOGGER.debug("No simulated activation attribute was defined for the account.");
// return null;
// }
Collection<Object> values = null;
if (activationProperty != null) {
values = activationProperty.getRealValues(Object.class);
}
ActivationType activation = convertFromSimulatedActivationValues(resource, values, parentResult);
LOGGER.debug(
"Detected simulated activation attribute {} on {} with value {}, resolved into {}",
new Object[] {
SchemaDebugUtil.prettyPrint(activationCapability.getEnableDisable().getAttribute()),
ObjectTypeUtil.toShortString(resource), values,
activation == null ? "null" : activation.isEnabled() });
return activation;
}
private static ActivationType convertFromSimulatedActivationAttributes(ResourceType resource,
AccountShadowType shadow, OperationResult parentResult) {
// LOGGER.trace("Start converting activation type from simulated activation atribute");
ActivationCapabilityType activationCapability = ResourceTypeUtil.getEffectiveCapability(resource,
ActivationCapabilityType.class);
QName enableDisableAttribute = activationCapability.getEnableDisable().getAttribute();
List<Object> values = ResourceObjectShadowUtil.getAttributeValues(shadow, enableDisableAttribute);
ActivationType activation = convertFromSimulatedActivationValues(resource, values, parentResult);
LOGGER.debug(
"Detected simulated activation attribute {} on {} with value {}, resolved into {}",
new Object[] {
SchemaDebugUtil.prettyPrint(activationCapability.getEnableDisable().getAttribute()),
ObjectTypeUtil.toShortString(resource), values,
activation == null ? "null" : activation.isEnabled() });
return activation;
}
/**
* Make sure that the shadow is UCF-ready. That means that is has
* ResourceAttributeContainer as <attributes>, has definition, etc.
*/
public static void convertToUcfShadow(PrismObject<ResourceObjectShadowType> shadow,
ResourceSchema resourceSchema) throws SchemaException {
PrismContainer<?> attributesContainer = shadow.findContainer(ResourceObjectShadowType.F_ATTRIBUTES);
if (attributesContainer instanceof ResourceAttributeContainer) {
if (attributesContainer.getDefinition() != null) {
// Nothing to do. Everything is OK.
return;
} else {
// TODO: maybe we can apply the definition?
throw new SchemaException("No definition for attributes container in " + shadow);
}
}
ObjectClassComplexTypeDefinition objectClassDefinition = determineObjectClassDefinition(shadow,
resourceSchema);
// We need to convert <attributes> to ResourceAttributeContainer
ResourceAttributeContainer convertedContainer = ResourceAttributeContainer.convertFromContainer(
attributesContainer, objectClassDefinition);
shadow.getValue().replace(attributesContainer, convertedContainer);
}
private static ObjectClassComplexTypeDefinition determineObjectClassDefinition(
PrismObject<ResourceObjectShadowType> shadow, ResourceSchema resourceSchema)
throws SchemaException {
QName objectClassName = shadow.asObjectable().getObjectClass();
if (objectClassName == null) {
throw new SchemaException("No object class specified in shadow " + shadow);
}
ObjectClassComplexTypeDefinition objectClassDefinition = resourceSchema
.findObjectClassDefinition(objectClassName);
if (objectClassDefinition == null) {
throw new SchemaException("No definition for object class " + objectClassName
+ " as specified in shadow " + shadow);
}
return objectClassDefinition;
}
private static ActivationType convertFromSimulatedActivationValues(ResourceType resource,
Collection<Object> activationValues, OperationResult parentResult) {
ActivationCapabilityType activationCapability = ResourceTypeUtil.getEffectiveCapability(resource,
ActivationCapabilityType.class);
if (activationCapability == null) {
return null;
}
List<String> disableValues = activationCapability.getEnableDisable().getDisableValue();
List<String> enableValues = activationCapability.getEnableDisable().getEnableValue();
ActivationType activationType = new ActivationType();
if (isNoValue(activationValues)) {
if (hasNoValue(disableValues)) {
activationType.setEnabled(false);
return activationType;
}
if (hasNoValue(enableValues)) {
activationType.setEnabled(true);
return activationType;
}
// No activation information.
LOGGER.warn(
"The {} does not provide definition for null value of simulated activation attribute",
ObjectTypeUtil.toShortString(resource));
if (parentResult != null) {
parentResult
.recordPartialError("The "
+ ObjectTypeUtil.toShortString(resource)
+ " has native activation capability but noes not provide value for DISABLE attribute");
}
return null;
} else {
if (activationValues.size() > 1) {
LOGGER.warn("The {} provides {} values for DISABLE attribute, expecting just one value",
disableValues.size(), ObjectTypeUtil.toShortString(resource));
if (parentResult != null) {
parentResult.recordPartialError("The " + ObjectTypeUtil.toShortString(resource)
+ " provides " + disableValues.size()
+ " values for DISABLE attribute, expecting just one value");
}
}
Object disableObj = activationValues.iterator().next();
for (String disable : disableValues) {
if (disable.equals(String.valueOf(disableObj))) {
activationType.setEnabled(false);
return activationType;
}
}
for (String enable : enableValues) {
if ("".equals(enable) || enable.equals(String.valueOf(disableObj))) {
activationType.setEnabled(true);
return activationType;
}
}
}
return null;
}
private static boolean isNoValue(Collection<?> collection) {
if (collection == null)
return true;
if (collection.isEmpty())
return true;
for (Object val : collection) {
if (val == null)
continue;
if (val instanceof String && ((String) val).isEmpty())
continue;
return false;
}
return true;
}
private static boolean hasNoValue(Collection<?> collection) {
if (collection == null)
return true;
if (collection.isEmpty())
return true;
for (Object val : collection) {
if (val == null)
return true;
if (val instanceof String && ((String) val).isEmpty())
return true;
}
return false;
}
public static String determineShadowName(ResourceObjectShadowType shadow) throws SchemaException {
ResourceAttributeContainer attributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(shadow);
if (attributesContainer.getNamingAttribute() == null) {
// No naming attribute defined. Try to fall back to identifiers.
Collection<ResourceAttribute<?>> identifiers = attributesContainer.getIdentifiers();
// We can use only single identifiers (not composite)
if (identifiers.size() == 1) {
PrismProperty<?> identifier = identifiers.iterator().next();
// Only single-valued identifiers
Collection<PrismPropertyValue<?>> values = (Collection) identifier.getValues();
if (values.size() == 1) {
PrismPropertyValue<?> value = values.iterator().next();
// and only strings
if (value.getValue() instanceof String) {
return (String) value.getValue();
}
}
} else {
return attributesContainer.findAttribute(ConnectorFactoryIcfImpl.ICFS_NAME)
.getValue(String.class).getValue();
}
// Identifier is not usable as name
// TODO: better identification of a problem
throw new SchemaException("No naming attribute defined (and identifier not usable)");
}
// TODO: Error handling
return attributesContainer.getNamingAttribute().getValue().getValue();
}
/**
* Create a copy of a shadow that is suitable for repository storage.
*/
public static <T extends ResourceObjectShadowType> T createRepositoryShadow(T shadowType,
ResourceType resource) throws SchemaException {
PrismObject<T> shadow = shadowType.asPrismObject();
ResourceAttributeContainer attributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(shadow);
PrismObject<T> repoShadow = shadow.clone();
ResourceAttributeContainer repoAttributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(repoShadow);
// Clean all repoShadow attributes and add only those that should be
// there
repoAttributesContainer.getValue().clear();
Collection<ResourceAttribute<?>> identifiers = attributesContainer.getIdentifiers();
for (PrismProperty<?> p : identifiers) {
repoAttributesContainer.getValue().add(p);
}
Collection<ResourceAttribute<?>> secondaryIdentifiers = attributesContainer.getSecondaryIdentifiers();
for (PrismProperty<?> p : secondaryIdentifiers) {
repoAttributesContainer.getValue().add(p);
}
// We don't want to store credentials in the repo
T repoShadowType = repoShadow.asObjectable();
if (repoShadowType instanceof AccountShadowType) {
((AccountShadowType) repoShadowType).setCredentials(null);
}
// additional check if the shadow doesn't contain resource, if yes,
// convert to the resource reference.
if (repoShadowType.getResource() != null) {
repoShadowType.setResource(null);
repoShadowType.setResourceRef(ObjectTypeUtil.createObjectRef(resource));
}
// if shadow does not contain resource or resource reference, create it
// now
if (repoShadowType.getResourceRef() == null) {
repoShadowType.setResourceRef(ObjectTypeUtil.createObjectRef(resource));
}
if (repoShadowType.getName() == null) {
repoShadowType.setName(determineShadowName(shadowType));
}
if (repoShadowType.getObjectClass() == null) {
repoShadowType.setObjectClass(attributesContainer.getDefinition().getTypeName());
}
return repoShadowType;
}
public static QueryType createSearchShadowQuery(Collection<ResourceAttribute<?>> identifiers,
PrismContext prismContext, OperationResult parentResult) throws SchemaException {
XPathHolder xpath = createXpathHolder();
Document doc = DOMUtil.getDocument();
List<Object> values = new ArrayList<Object>();
for (PrismProperty<?> identifier : identifiers) {
List<Element> elements = prismContext.getPrismDomProcessor().serializeItemToDom(identifier, doc);
values.addAll(elements);
}
// TODO: fix for more than one identifier..The create equal filter must
// be fixed first..
if (values.size() > 1) {
throw new UnsupportedOperationException("More than one identifier not supported yet.");
}
Object identifier = values.get(0);
Element filter;
try {
filter = QueryUtil.createEqualFilter(doc, xpath, identifier);
} catch (SchemaException e) {
parentResult.recordFatalError(e);
throw e;
}
QueryType query = new QueryType();
query.setFilter(filter);
return query;
}
public static QueryType createSearchShadowQuery(ResourceObjectShadowType resourceShadow,
ResourceType resource, PrismContext prismContext, OperationResult parentResult)
throws SchemaException {
XPathHolder xpath = createXpathHolder();
ResourceAttributeContainer attributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(resourceShadow);
PrismProperty identifier = attributesContainer.getIdentifier();
Collection<PrismPropertyValue<Object>> idValues = identifier.getValues();
// Only one value is supported for an identifier
if (idValues.size() > 1) {
// LOGGER.error("More than one identifier value is not supported");
// TODO: This should probably be switched to checked exception later
throw new IllegalArgumentException("More than one identifier value is not supported");
}
if (idValues.size() < 1) {
// LOGGER.error("The identifier has no value");
// TODO: This should probably be switched to checked exception later
throw new IllegalArgumentException("The identifier has no value");
}
// We have all the data, we can construct the filter now
Document doc = DOMUtil.getDocument();
Element filter;
List<Element> identifierElements = prismContext.getPrismDomProcessor().serializeItemToDom(identifier,
doc);
try {
filter = QueryUtil.createAndFilter(doc, QueryUtil.createEqualRefFilter(doc, null,
SchemaConstants.I_RESOURCE_REF, resource.getOid()), QueryUtil
.createEqualFilterFromElements(doc, xpath, identifierElements, resourceShadow
.asPrismObject().getPrismContext()));
} catch (SchemaException e) {
// LOGGER.error("Schema error while creating search filter: {}",
// e.getMessage(), e);
throw new SchemaException("Schema error while creating search filter: " + e.getMessage(), e);
}
QueryType query = new QueryType();
query.setFilter(filter);
// LOGGER.trace("created query " + DOMUtil.printDom(filter));
return query;
}
private static XPathHolder createXpathHolder() {
XPathSegment xpathSegment = new XPathSegment(SchemaConstants.I_ATTRIBUTES);
List<XPathSegment> xpathSegments = new ArrayList<XPathSegment>();
xpathSegments.add(xpathSegment);
XPathHolder xpath = new XPathHolder(xpathSegments);
return xpath;
}
public static PrismObjectDefinition<ResourceObjectShadowType> getResourceObjectShadowDefinition(
PrismContext prismContext) {
return prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(
ResourceObjectShadowType.class);
}
}
|
provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/util/ShadowCacheUtil.java
|
/*
* Copyright (c) 2011 Evolveum
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the License). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the License at
* http://www.opensource.org/licenses/cddl1 or
* CDDLv1.0.txt file in the source code distribution.
* See the License for the specific language governing
* permission and limitations under the License.
*
* If applicable, add the following below the CDDL Header,
* with the fields enclosed by brackets [] replaced by
* your own identifying information:
*
* Portions Copyrighted 2011 [name of copyright owner]
*/
package com.evolveum.midpoint.provisioning.util;
import com.evolveum.midpoint.common.QueryUtil;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.provisioning.ucf.impl.ConnectorFactoryIcfImpl;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.holder.XPathHolder;
import com.evolveum.midpoint.schema.holder.XPathSegment;
import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition;
import com.evolveum.midpoint.schema.processor.ResourceAttribute;
import com.evolveum.midpoint.schema.processor.ResourceAttributeContainer;
import com.evolveum.midpoint.schema.processor.ResourceSchema;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.schema.util.ResourceObjectShadowUtil;
import com.evolveum.midpoint.schema.util.ResourceTypeUtil;
import com.evolveum.midpoint.schema.util.SchemaDebugUtil;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_1.AccountShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ActivationType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceObjectShadowAttributesType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceObjectShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceType;
import com.evolveum.midpoint.xml.ns._public.resource.capabilities_1.ActivationCapabilityType;
import com.evolveum.prism.xml.ns._public.query_2.QueryType;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class ShadowCacheUtil {
private static final Trace LOGGER = TraceManager.getTrace(ShadowCacheUtil.class);
/**
* Make sure that the shadow is complete, e.g. that all the mandatory fields
* are filled (e.g name, resourceRef, ...) Also transforms the shadow with
* respect to simulated capabilities.
*/
public static <T extends ResourceObjectShadowType> T completeShadow(T resourceShadow, T repoShadow,
ResourceType resource, OperationResult parentResult) throws SchemaException {
// repoShadow is a result, we need to copy there everything that needs
// to be there
// If there is no repo shadow, use resource shadow instead
if (repoShadow == null) {
PrismObject<T> repoPrism = resourceShadow.asPrismObject().clone();
repoShadow = repoPrism.asObjectable();
}
ResourceAttributeContainer resourceAttributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(resourceShadow);
ResourceAttributeContainer repoAttributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(repoShadow);
if (repoShadow.getObjectClass() == null) {
repoShadow.setObjectClass(resourceAttributesContainer.getDefinition().getTypeName());
}
if (repoShadow.getName() == null) {
repoShadow.setName(determineShadowName(resourceShadow));
}
if (repoShadow.getResource() == null) {
repoShadow.setResourceRef(ObjectTypeUtil.createObjectRef(resource));
}
// Attributes
// If the shadows are the same then no copy is needed.
if (repoShadow != resourceShadow) {
repoAttributesContainer.getValue().clear();
for (ResourceAttribute resourceAttribute : resourceAttributesContainer.getAttributes()) {
// do not copy simulated activation attrbute
if (isSimulatedActivationAttribute(resourceAttribute, resourceShadow, resource)) {
continue;
}
repoAttributesContainer.add(resourceAttribute);
}
}
// Activation
// FIXME??? when there are not native capabilities for activation, the
// resourceShadow.getActivation is null and the activation for the repo
// shadow are not completed..therefore there need to be one more check,
// we must chceck not only if the activation is null, but if it is, also
// if the shadow doesn't have defined simulated activation capability
if (resourceShadow.getActivation() != null || ResourceTypeUtil.hasActivationCapability(resource)) {
ActivationType activationType = completeActivation(resourceShadow, resource, parentResult);
LOGGER.trace("Determined activation: {}", activationType.isEnabled());
repoShadow.setActivation(activationType);
} else {
repoShadow.setActivation(null);
}
if (repoShadow instanceof AccountShadowType) {
// Credentials
AccountShadowType repoAccountShadow = (AccountShadowType) repoShadow;
AccountShadowType resourceAccountShadow = (AccountShadowType) resourceShadow;
repoAccountShadow.setCredentials(resourceAccountShadow.getCredentials());
}
repoShadow.asPrismObject().checkConsistence();
return repoShadow;
}
private static boolean isSimulatedActivationAttribute(ResourceAttribute attribute,
ResourceObjectShadowType shadow, ResourceType resource) {
if (!ResourceTypeUtil.hasResourceNativeActivationCapability(resource)) {
ActivationCapabilityType activationCapability = ResourceTypeUtil.getEffectiveCapability(resource,
ActivationCapabilityType.class);
ResourceAttributeContainer attributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(shadow);
ResourceAttribute activationProperty = attributesContainer.findAttribute(activationCapability
.getEnableDisable().getAttribute());
if (activationProperty != null && activationProperty.equals(attribute)) {
return true;
}
}
return false;
}
public static <T extends ResourceObjectShadowType> void normalizeShadow(T shadow, OperationResult result)
throws SchemaException {
if (shadow.getAttemptNumber() != null) {
shadow.setAttemptNumber(null);
}
if (shadow.getFailedOperationType() != null) {
shadow.setFailedOperationType(null);
}
if (shadow.getObjectChange() != null) {
shadow.setObjectChange(null);
}
if (shadow.getResult() != null) {
shadow.setResult(null);
}
ResourceAttributeContainer normalizedContainer = ResourceObjectShadowUtil
.getAttributesContainer(shadow);
ResourceAttributeContainer oldContainer = normalizedContainer.clone();
normalizedContainer.clear();
Collection<ResourceAttribute<?>> identifiers = oldContainer.getIdentifiers();
for (PrismProperty<?> p : identifiers) {
normalizedContainer.getValue().add(p);
}
Collection<ResourceAttribute<?>> secondaryIdentifiers = oldContainer.getSecondaryIdentifiers();
for (PrismProperty<?> p : secondaryIdentifiers) {
normalizedContainer.getValue().add(p);
}
}
/**
* Completes activation state by determinig simulated activation if
* necessary.
*
* TODO: The placement of this method is not correct. It should go back to
* ShadowConverter
*/
public static ActivationType completeActivation(ResourceObjectShadowType shadow, ResourceType resource,
OperationResult parentResult) {
// HACK to avoid NPE when called from the ICF layer
if (resource == null) {
return shadow.getActivation();
}
if (ResourceTypeUtil.hasResourceNativeActivationCapability(resource)) {
return shadow.getActivation();
} else if (ResourceTypeUtil.hasActivationCapability(resource)) {
return convertFromSimulatedActivationAttributes(shadow, resource, parentResult);
} else {
// No activation capability, nothing to do
return null;
}
}
private static ActivationType convertFromSimulatedActivationAttributes(ResourceObjectShadowType shadow,
ResourceType resource, OperationResult parentResult) {
// LOGGER.trace("Start converting activation type from simulated activation atribute");
ActivationCapabilityType activationCapability = ResourceTypeUtil.getEffectiveCapability(resource,
ActivationCapabilityType.class);
ResourceAttributeContainer attributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(shadow);
// List<Object> values =
// ResourceObjectShadowUtil.getAttributeValues(shadow,
// activationCapability
// .getEnableDisable().getAttribute());
ResourceAttribute activationProperty = attributesContainer.findAttribute(activationCapability
.getEnableDisable().getAttribute());
// LOGGER.trace("activation property: {}", activationProperty.dump());
// if (activationProperty == null) {
// LOGGER.debug("No simulated activation attribute was defined for the account.");
// return null;
// }
Collection<Object> values = null;
if (activationProperty != null) {
values = activationProperty.getRealValues(Object.class);
}
ActivationType activation = convertFromSimulatedActivationValues(resource, values, parentResult);
LOGGER.debug(
"Detected simulated activation attribute {} on {} with value {}, resolved into {}",
new Object[] {
SchemaDebugUtil.prettyPrint(activationCapability.getEnableDisable().getAttribute()),
ObjectTypeUtil.toShortString(resource), values,
activation == null ? "null" : activation.isEnabled() });
return activation;
}
private static ActivationType convertFromSimulatedActivationAttributes(ResourceType resource,
AccountShadowType shadow, OperationResult parentResult) {
// LOGGER.trace("Start converting activation type from simulated activation atribute");
ActivationCapabilityType activationCapability = ResourceTypeUtil.getEffectiveCapability(resource,
ActivationCapabilityType.class);
QName enableDisableAttribute = activationCapability.getEnableDisable().getAttribute();
List<Object> values = ResourceObjectShadowUtil.getAttributeValues(shadow, enableDisableAttribute);
ActivationType activation = convertFromSimulatedActivationValues(resource, values, parentResult);
LOGGER.debug(
"Detected simulated activation attribute {} on {} with value {}, resolved into {}",
new Object[] {
SchemaDebugUtil.prettyPrint(activationCapability.getEnableDisable().getAttribute()),
ObjectTypeUtil.toShortString(resource), values,
activation == null ? "null" : activation.isEnabled() });
return activation;
}
/**
* Make sure that the shadow is UCF-ready. That means that is has
* ResourceAttributeContainer as <attributes>, has definition, etc.
*/
public static void convertToUcfShadow(PrismObject<ResourceObjectShadowType> shadow,
ResourceSchema resourceSchema) throws SchemaException {
PrismContainer<?> attributesContainer = shadow.findContainer(ResourceObjectShadowType.F_ATTRIBUTES);
if (attributesContainer instanceof ResourceAttributeContainer) {
if (attributesContainer.getDefinition() != null) {
// Nothing to do. Everything is OK.
return;
} else {
// TODO: maybe we can apply the definition?
throw new SchemaException("No definition for attributes container in " + shadow);
}
}
ObjectClassComplexTypeDefinition objectClassDefinition = determineObjectClassDefinition(shadow,
resourceSchema);
// We need to convert <attributes> to ResourceAttributeContainer
ResourceAttributeContainer convertedContainer = ResourceAttributeContainer.convertFromContainer(
attributesContainer, objectClassDefinition);
shadow.getValue().replace(attributesContainer, convertedContainer);
}
private static ObjectClassComplexTypeDefinition determineObjectClassDefinition(
PrismObject<ResourceObjectShadowType> shadow, ResourceSchema resourceSchema)
throws SchemaException {
QName objectClassName = shadow.asObjectable().getObjectClass();
if (objectClassName == null) {
throw new SchemaException("No object class specified in shadow " + shadow);
}
ObjectClassComplexTypeDefinition objectClassDefinition = resourceSchema
.findObjectClassDefinition(objectClassName);
if (objectClassDefinition == null) {
throw new SchemaException("No definition for object class " + objectClassName
+ " as specified in shadow " + shadow);
}
return objectClassDefinition;
}
private static ActivationType convertFromSimulatedActivationValues(ResourceType resource,
Collection<Object> activationValues, OperationResult parentResult) {
ActivationCapabilityType activationCapability = ResourceTypeUtil.getEffectiveCapability(resource,
ActivationCapabilityType.class);
if (activationCapability == null) {
return null;
}
List<String> disableValues = activationCapability.getEnableDisable().getDisableValue();
List<String> enableValues = activationCapability.getEnableDisable().getEnableValue();
ActivationType activationType = new ActivationType();
if (isNoValue(activationValues)) {
if (hasNoValue(disableValues)) {
activationType.setEnabled(false);
return activationType;
}
if (hasNoValue(enableValues)) {
activationType.setEnabled(true);
return activationType;
}
// No activation information.
LOGGER.warn(
"The {} does not provide definition for null value of simulated activation attribute",
ObjectTypeUtil.toShortString(resource));
if (parentResult != null) {
parentResult
.recordPartialError("The "
+ ObjectTypeUtil.toShortString(resource)
+ " has native activation capability but noes not provide value for DISABLE attribute");
}
return null;
} else {
if (activationValues.size() > 1) {
LOGGER.warn("The {} provides {} values for DISABLE attribute, expecting just one value",
disableValues.size(), ObjectTypeUtil.toShortString(resource));
if (parentResult != null) {
parentResult.recordPartialError("The " + ObjectTypeUtil.toShortString(resource)
+ " provides " + disableValues.size()
+ " values for DISABLE attribute, expecting just one value");
}
}
Object disableObj = activationValues.iterator().next();
for (String disable : disableValues) {
if (disable.equals(String.valueOf(disableObj))) {
activationType.setEnabled(false);
return activationType;
}
}
for (String enable : enableValues) {
if ("".equals(enable) || enable.equals(String.valueOf(disableObj))) {
activationType.setEnabled(true);
return activationType;
}
}
}
return null;
}
private static boolean isNoValue(Collection<?> collection) {
if (collection == null)
return true;
if (collection.isEmpty())
return true;
for (Object val : collection) {
if (val == null)
continue;
if (val instanceof String && ((String) val).isEmpty())
continue;
return false;
}
return true;
}
private static boolean hasNoValue(Collection<?> collection) {
if (collection == null)
return true;
if (collection.isEmpty())
return true;
for (Object val : collection) {
if (val == null)
return true;
if (val instanceof String && ((String) val).isEmpty())
return true;
}
return false;
}
public static String determineShadowName(ResourceObjectShadowType shadow) throws SchemaException {
ResourceAttributeContainer attributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(shadow);
if (attributesContainer.getNamingAttribute() == null) {
// No naming attribute defined. Try to fall back to identifiers.
Collection<ResourceAttribute<?>> identifiers = attributesContainer.getIdentifiers();
// We can use only single identifiers (not composite)
if (identifiers.size() == 1) {
PrismProperty<?> identifier = identifiers.iterator().next();
// Only single-valued identifiers
Collection<PrismPropertyValue<?>> values = (Collection) identifier.getValues();
if (values.size() == 1) {
PrismPropertyValue<?> value = values.iterator().next();
// and only strings
if (value.getValue() instanceof String) {
return (String) value.getValue();
}
}
} else {
return attributesContainer.findAttribute(ConnectorFactoryIcfImpl.ICFS_NAME)
.getValue(String.class).getValue();
}
// Identifier is not usable as name
// TODO: better identification of a problem
throw new SchemaException("No naming attribute defined (and identifier not usable)");
}
// TODO: Error handling
return attributesContainer.getNamingAttribute().getValue().getValue();
}
/**
* Create a copy of a shadow that is suitable for repository storage.
*/
public static <T extends ResourceObjectShadowType> T createRepositoryShadow(T shadowType,
ResourceType resource) throws SchemaException {
PrismObject<T> shadow = shadowType.asPrismObject();
ResourceAttributeContainer attributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(shadow);
PrismObject<T> repoShadow = shadow.clone();
ResourceAttributeContainer repoAttributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(repoShadow);
// Clean all repoShadow attributes and add only those that should be
// there
repoAttributesContainer.getValue().clear();
Collection<ResourceAttribute<?>> identifiers = attributesContainer.getIdentifiers();
for (PrismProperty<?> p : identifiers) {
repoAttributesContainer.getValue().add(p);
}
Collection<ResourceAttribute<?>> secondaryIdentifiers = attributesContainer.getSecondaryIdentifiers();
for (PrismProperty<?> p : secondaryIdentifiers) {
repoAttributesContainer.getValue().add(p);
}
// We don't want to store credentials in the repo
T repoShadowType = repoShadow.asObjectable();
if (repoShadowType instanceof AccountShadowType) {
((AccountShadowType) repoShadowType).setCredentials(null);
}
// additional check if the shadow doesn't contain resource, if yes,
// convert to the resource reference.
if (repoShadowType.getResource() != null) {
repoShadowType.setResource(null);
repoShadowType.setResourceRef(ObjectTypeUtil.createObjectRef(resource));
}
// if shadow does not contain resource or resource reference, create it
// now
if (repoShadowType.getResourceRef() == null) {
repoShadowType.setResourceRef(ObjectTypeUtil.createObjectRef(resource));
}
if (repoShadowType.getName() == null) {
repoShadowType.setName(determineShadowName(shadowType));
}
if (repoShadowType.getObjectClass() == null) {
repoShadowType.setObjectClass(attributesContainer.getDefinition().getTypeName());
}
return repoShadowType;
}
public static QueryType createSearchShadowQuery(Collection<ResourceAttribute<?>> identifiers,
PrismContext prismContext, OperationResult parentResult) throws SchemaException {
XPathHolder xpath = createXpathHolder();
Document doc = DOMUtil.getDocument();
List<Object> values = new ArrayList<Object>();
for (PrismProperty<?> identifier : identifiers) {
List<Element> elements = prismContext.getPrismDomProcessor().serializeItemToDom(identifier, doc);
values.addAll(elements);
}
// TODO: fix for more than one identifier..The create equal filter must
// be fixed first..
if (values.size() > 1) {
throw new UnsupportedOperationException("More than one identifier not supported yet.");
}
Object identifier = values.get(0);
Element filter;
try {
filter = QueryUtil.createEqualFilter(doc, xpath, identifier);
} catch (SchemaException e) {
parentResult.recordFatalError(e);
throw e;
}
QueryType query = new QueryType();
query.setFilter(filter);
return query;
}
public static QueryType createSearchShadowQuery(ResourceObjectShadowType resourceShadow,
ResourceType resource, PrismContext prismContext, OperationResult parentResult)
throws SchemaException {
XPathHolder xpath = createXpathHolder();
ResourceAttributeContainer attributesContainer = ResourceObjectShadowUtil
.getAttributesContainer(resourceShadow);
PrismProperty identifier = attributesContainer.getIdentifier();
Collection<PrismPropertyValue<Object>> idValues = identifier.getValues();
// Only one value is supported for an identifier
if (idValues.size() > 1) {
// LOGGER.error("More than one identifier value is not supported");
// TODO: This should probably be switched to checked exception later
throw new IllegalArgumentException("More than one identifier value is not supported");
}
if (idValues.size() < 1) {
// LOGGER.error("The identifier has no value");
// TODO: This should probably be switched to checked exception later
throw new IllegalArgumentException("The identifier has no value");
}
// We have all the data, we can construct the filter now
Document doc = DOMUtil.getDocument();
Element filter;
List<Element> identifierElements = prismContext.getPrismDomProcessor().serializeItemToDom(identifier,
doc);
try {
filter = QueryUtil.createAndFilter(doc, QueryUtil.createEqualRefFilter(doc, null,
SchemaConstants.I_RESOURCE_REF, resource.getOid()), QueryUtil
.createEqualFilterFromElements(doc, xpath, identifierElements, resourceShadow
.asPrismObject().getPrismContext()));
} catch (SchemaException e) {
// LOGGER.error("Schema error while creating search filter: {}",
// e.getMessage(), e);
throw new SchemaException("Schema error while creating search filter: " + e.getMessage(), e);
}
QueryType query = new QueryType();
query.setFilter(filter);
// LOGGER.trace("created query " + DOMUtil.printDom(filter));
return query;
}
private static XPathHolder createXpathHolder() {
XPathSegment xpathSegment = new XPathSegment(SchemaConstants.I_ATTRIBUTES);
List<XPathSegment> xpathSegments = new ArrayList<XPathSegment>();
xpathSegments.add(xpathSegment);
XPathHolder xpath = new XPathHolder(xpathSegments);
return xpath;
}
public static PrismObjectDefinition<ResourceObjectShadowType> getResourceObjectShadowDefinition(
PrismContext prismContext) {
return prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(
ResourceObjectShadowType.class);
}
}
|
fixed NPE in ProvisioningServiceImptDBTest..
|
provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/util/ShadowCacheUtil.java
|
fixed NPE in ProvisioningServiceImptDBTest..
|
<ide><path>rovisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/util/ShadowCacheUtil.java
<ide>
<ide> ActivationCapabilityType activationCapability = ResourceTypeUtil.getEffectiveCapability(resource,
<ide> ActivationCapabilityType.class);
<add>
<add> if (activationCapability == null) {
<add> // TODO: maybe the warning message is needed that the resource
<add> // does not have either simulater or native capabilities
<add> return false;
<add> }
<add>
<ide> ResourceAttributeContainer attributesContainer = ResourceObjectShadowUtil
<ide> .getAttributesContainer(shadow);
<ide> ResourceAttribute activationProperty = attributesContainer.findAttribute(activationCapability
|
|
Java
|
agpl-3.0
|
51afcdfe23f1dd29cb0073c8be4a0619e328ee66
| 0 |
SoftInstigate/restheart,SoftInstigate/restheart,SoftInstigate/restheart,SoftInstigate/restheart
|
/*-
* ========================LICENSE_START=================================
* restheart-security
* %%
* Copyright (C) 2018 - 2020 SoftInstigate
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* =========================LICENSE_END==================================
*/
package org.restheart.services;
import java.util.Map;
import org.restheart.ConfigurationException;
import org.restheart.exchange.ByteArrayRequest;
import org.restheart.exchange.ByteArrayResponse;
import org.restheart.plugins.ByteArrayService;
import static org.restheart.plugins.ConfigurablePlugin.argValue;
import org.restheart.plugins.InjectConfiguration;
import org.restheart.plugins.RegisterPlugin;
import org.restheart.utils.HttpStatus;
/**
*
* @author Andrea Di Cesare {@literal <[email protected]>}
*/
@RegisterPlugin(name = "ping", description = "simple ping service", enabledByDefault = true, defaultURI = "/ping")
public class PingService implements ByteArrayService {
private String msg = null;
@InjectConfiguration
public void init(Map<String, Object> args) throws ConfigurationException {
this.msg = argValue(args, "msg");
}
/**
*
* @throws Exception
*/
@Override
public void handle(ByteArrayRequest request, ByteArrayResponse response) throws Exception {
if (!request.isGet()) {
response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
} else {
var accept = request.getHeader("Accept");
if (accept != null && accept.startsWith("text/html")) {
var content = "<div><h2>" + msg + "</h2></div>";
response.setContent(content.getBytes());
response.setContentType("text/html");
} else {
response.setContentType("text/plain");
response.setContent(msg.getBytes());
}
}
}
}
|
core/src/main/java/org/restheart/services/PingService.java
|
/*-
* ========================LICENSE_START=================================
* restheart-security
* %%
* Copyright (C) 2018 - 2020 SoftInstigate
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* =========================LICENSE_END==================================
*/
package org.restheart.services;
import java.util.Map;
import org.restheart.ConfigurationException;
import org.restheart.exchange.ByteArrayRequest;
import org.restheart.exchange.ByteArrayResponse;
import org.restheart.plugins.ByteArrayService;
import static org.restheart.plugins.ConfigurablePlugin.argValue;
import org.restheart.plugins.InjectConfiguration;
import org.restheart.plugins.RegisterPlugin;
import org.restheart.utils.HttpStatus;
/**
*
* @author Andrea Di Cesare {@literal <[email protected]>}
*/
@RegisterPlugin(
name = "ping",
description = "simple ping service",
enabledByDefault = true,
defaultURI = "/ping")
public class PingService implements ByteArrayService {
private String msg = null;
@InjectConfiguration
public void init(Map<String, Object> args) throws ConfigurationException {
this.msg = argValue(args, "msg");
}
/**
*
* @throws Exception
*/
@Override
public void handle(ByteArrayRequest request,
ByteArrayResponse response) throws Exception {
response.setContentType("text/plain");
if (request.isGet()) {
response.setStatusCode(HttpStatus.SC_OK);
response.setContent(msg.getBytes());
} else {
response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
}
}
}
|
PingService honors the header Accept=text/html
|
core/src/main/java/org/restheart/services/PingService.java
|
PingService honors the header Accept=text/html
|
<ide><path>ore/src/main/java/org/restheart/services/PingService.java
<ide> *
<ide> * @author Andrea Di Cesare {@literal <[email protected]>}
<ide> */
<del>@RegisterPlugin(
<del> name = "ping",
<del> description = "simple ping service",
<del> enabledByDefault = true,
<del> defaultURI = "/ping")
<add>@RegisterPlugin(name = "ping", description = "simple ping service", enabledByDefault = true, defaultURI = "/ping")
<ide> public class PingService implements ByteArrayService {
<ide>
<ide> private String msg = null;
<ide> * @throws Exception
<ide> */
<ide> @Override
<del> public void handle(ByteArrayRequest request,
<del> ByteArrayResponse response) throws Exception {
<del> response.setContentType("text/plain");
<add> public void handle(ByteArrayRequest request, ByteArrayResponse response) throws Exception {
<add> if (!request.isGet()) {
<add> response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
<add> } else {
<add> var accept = request.getHeader("Accept");
<ide>
<del> if (request.isGet()) {
<del> response.setStatusCode(HttpStatus.SC_OK);
<del> response.setContent(msg.getBytes());
<del> } else {
<del> response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
<add> if (accept != null && accept.startsWith("text/html")) {
<add> var content = "<div><h2>" + msg + "</h2></div>";
<add> response.setContent(content.getBytes());
<add> response.setContentType("text/html");
<add> } else {
<add> response.setContentType("text/plain");
<add> response.setContent(msg.getBytes());
<add> }
<ide> }
<ide> }
<ide> }
|
|
Java
|
mit
|
8e3bf4d45dfffce8c0b2b3af01b7a70487963eff
| 0 |
OnABerryTrip/TronAIComp
|
import java.util.Random;
public class TronGame {
private BoardItem[][] board;
private Biker[] bikers;
//TODO: implement
public TronGame(int boardSize, BikerAI[] players){
setupBoard(boardSize);
}
/**
* Sets up the board at the beginning of the game
* with blanks everywhere except on the edges where
* there will be streaks to act as walls
* @param boardSize size of the board
*/
private void setupBoard(int boardSize){
board = new BoardItem[boardSize][boardSize];
//Initialize the board to blanks
for (int i = 0;i < boardSize;i++){
for (int j = 0;j < boardSize;j++){
board[i][j] = BoardItem.BLANK;
}
}
//Fill the board edges with streaks to act as walls
//TODO: Make a faster implementation in a separate method
for (int i = 0;i < boardSize;i++){
for (int j = 0;j < boardSize;j++){
//Check to see if the index is an edge
if (i == 0 || (i == boardSize - 1) || j == 0 || (j == boardSize - 1)){
board[i][j] = BoardItem.STREAK;
}
}
}
}
private void placePlayers(BikerAI[] players) throws Exception{
if (board == null){
throw new Exception("You are an idiot");
}
Random generator = new Random();
bikers = new Biker[players.length];
//Initialize bikers to plausible positions
for (int i = 0;i < players.length ;i++){
int posX = generator.nextInt(board.length);
int posY = generator.nextInt(board.length);
bikers[i] = new Biker(posX,posY,players[i]);
}
}
/**
* Check to see if any of the players
* are in invalid positions where an
* in valid position is defined as being
* where a streak or another player should be.
*
* @return the index of the first player
* in an invalid position or -1 if all
* players are in valid positions
*/
private int checkForInvalidPos(){
return 0; //TODO Not Implemented
}
//TODO: implement
public void tick(){
}
public enum direction{
NORTH,SOUTH,EAST,WEST
}
}
|
src/TronGame.java
|
import java.util.Random;
public class TronGame {
private BoardItem[][] board;
private Biker[] bikers;
//TODO: implement
public TronGame(int boardSize, BikerAI[] players){
Random generator = new Random();
board = new BoardItem[boardSize][boardSize];
bikers = new Biker[players.length];
setupBoard(boardSize);
//Initialize bikers
for (int i = 0;i < players.length ;i++){
int posX = generator.nextInt(boardSize);
int posY = generator.nextInt(boardSize);
bikers[i] = new Biker(posX,posY,players[i]);
}
}
/**
* Sets up the board at the beginning of the game
* with blanks everywhere except on the edges where
* there will be streaks to act as walls
* @param boardSize size of the board
*/
private void setupBoard(int boardSize){
board = new BoardItem[boardSize][boardSize];
//Initialize the board to blanks
for (int i = 0;i < boardSize;i++){
for (int j = 0;j < boardSize;j++){
board[i][j] = BoardItem.BLANK;
}
}
//Fill the board edges with streaks to act as walls
//TODO: Make a faster implementation
for (int i = 0;i < boardSize;i++){
for (int j = 0;j < boardSize;j++){
//Check to see if the index is an edge
if (i == 0 || (i == boardSize - 1) || j == 0 || (j == boardSize - 1)){
board[i][j] = BoardItem.STREAK;
}
}
}
}
//TODO: implement
public void tick(){
}
public enum direction{
NORTH,SOUTH,EAST,WEST
}
}
|
finished checkForInvalidPos() method
|
src/TronGame.java
|
finished checkForInvalidPos() method
|
<ide><path>rc/TronGame.java
<ide>
<ide> //TODO: implement
<ide> public TronGame(int boardSize, BikerAI[] players){
<del> Random generator = new Random();
<ide>
<del> board = new BoardItem[boardSize][boardSize];
<del> bikers = new Biker[players.length];
<add>
<ide>
<ide>
<ide> setupBoard(boardSize);
<del>
<del>
<del> //Initialize bikers
<del> for (int i = 0;i < players.length ;i++){
<del> int posX = generator.nextInt(boardSize);
<del> int posY = generator.nextInt(boardSize);
<del> bikers[i] = new Biker(posX,posY,players[i]);
<del> }
<ide>
<ide> }
<ide> /**
<ide> }
<ide>
<ide> //Fill the board edges with streaks to act as walls
<del> //TODO: Make a faster implementation
<add> //TODO: Make a faster implementation in a separate method
<ide> for (int i = 0;i < boardSize;i++){
<ide> for (int j = 0;j < boardSize;j++){
<ide>
<ide> board[i][j] = BoardItem.STREAK;
<ide> }
<ide> }
<add> }
<add> }
<add>
<add> private void placePlayers(BikerAI[] players) throws Exception{
<add> if (board == null){
<add> throw new Exception("You are an idiot");
<ide> }
<add>
<add> Random generator = new Random();
<add> bikers = new Biker[players.length];
<add>
<add> //Initialize bikers to plausible positions
<add> for (int i = 0;i < players.length ;i++){
<add> int posX = generator.nextInt(board.length);
<add> int posY = generator.nextInt(board.length);
<add> bikers[i] = new Biker(posX,posY,players[i]);
<add> }
<add>
<ide> }
<add>
<add>
<add> /**
<add> * Check to see if any of the players
<add> * are in invalid positions where an
<add> * in valid position is defined as being
<add> * where a streak or another player should be.
<add> *
<add> * @return the index of the first player
<add> * in an invalid position or -1 if all
<add> * players are in valid positions
<add> */
<add> private int checkForInvalidPos(){
<add> return 0; //TODO Not Implemented
<add> }
<add>
<ide>
<ide> //TODO: implement
<ide> public void tick(){
|
|
Java
|
apache-2.0
|
2eb7152fce68ad995982a7608e83f4b673d44309
| 0 |
krishnakanthpps/pinpoint,hcapitaine/pinpoint,jaehong-kim/pinpoint,lioolli/pinpoint,InfomediaLtd/pinpoint,lioolli/pinpoint,Skkeem/pinpoint,citywander/pinpoint,dawidmalina/pinpoint,suraj-raturi/pinpoint,tsyma/pinpoint,barneykim/pinpoint,eBaoTech/pinpoint,Allive1/pinpoint,koo-taejin/pinpoint,barneykim/pinpoint,gspandy/pinpoint,chenguoxi1985/pinpoint,coupang/pinpoint,coupang/pinpoint,emeroad/pinpoint,krishnakanthpps/pinpoint,nstopkimsk/pinpoint,tsyma/pinpoint,Skkeem/pinpoint,Xylus/pinpoint,minwoo-jung/pinpoint,cit-lab/pinpoint,Allive1/pinpoint,jaehong-kim/pinpoint,suraj-raturi/pinpoint,suraj-raturi/pinpoint,sbcoba/pinpoint,breadval/pinpoint,philipz/pinpoint,sjmittal/pinpoint,breadval/pinpoint,andyspan/pinpoint,lioolli/pinpoint,philipz/pinpoint,andyspan/pinpoint,dawidmalina/pinpoint,masonmei/pinpoint,philipz/pinpoint,breadval/pinpoint,87439247/pinpoint,nstopkimsk/pinpoint,Allive1/pinpoint,barneykim/pinpoint,sbcoba/pinpoint,denzelsN/pinpoint,coupang/pinpoint,majinkai/pinpoint,hcapitaine/pinpoint,tsyma/pinpoint,majinkai/pinpoint,cit-lab/pinpoint,PerfGeeks/pinpoint,wziyong/pinpoint,shuvigoss/pinpoint,wziyong/pinpoint,wziyong/pinpoint,Xylus/pinpoint,87439247/pinpoint,PerfGeeks/pinpoint,masonmei/pinpoint,cijung/pinpoint,coupang/pinpoint,denzelsN/pinpoint,KimTaehee/pinpoint,jiaqifeng/pinpoint,naver/pinpoint,jaehong-kim/pinpoint,breadval/pinpoint,eBaoTech/pinpoint,Skkeem/pinpoint,InfomediaLtd/pinpoint,InfomediaLtd/pinpoint,Skkeem/pinpoint,Allive1/pinpoint,sbcoba/pinpoint,gspandy/pinpoint,citywander/pinpoint,denzelsN/pinpoint,eBaoTech/pinpoint,cit-lab/pinpoint,lioolli/pinpoint,krishnakanthpps/pinpoint,dawidmalina/pinpoint,KRDeNaT/pinpoint,Allive1/pinpoint,nstopkimsk/pinpoint,barneykim/pinpoint,KimTaehee/pinpoint,KRDeNaT/pinpoint,cijung/pinpoint,cit-lab/pinpoint,suraj-raturi/pinpoint,cijung/pinpoint,Allive1/pinpoint,majinkai/pinpoint,masonmei/pinpoint,breadval/pinpoint,carpedm20/pinpoint,philipz/pinpoint,hcapitaine/pinpoint,Xylus/pinpoint,PerfGeeks/pinpoint,masonmei/pinpoint,chenguoxi1985/pinpoint,chenguoxi1985/pinpoint,masonmei/pinpoint,philipz/pinpoint,hcapitaine/pinpoint,naver/pinpoint,andyspan/pinpoint,gspandy/pinpoint,krishnakanthpps/pinpoint,cijung/pinpoint,suraj-raturi/pinpoint,wziyong/pinpoint,carpedm20/pinpoint,denzelsN/pinpoint,emeroad/pinpoint,andyspan/pinpoint,chenguoxi1985/pinpoint,shuvigoss/pinpoint,sjmittal/pinpoint,jaehong-kim/pinpoint,shuvigoss/pinpoint,denzelsN/pinpoint,koo-taejin/pinpoint,nstopkimsk/pinpoint,tsyma/pinpoint,sbcoba/pinpoint,jiaqifeng/pinpoint,Xylus/pinpoint,eBaoTech/pinpoint,carpedm20/pinpoint,87439247/pinpoint,eBaoTech/pinpoint,coupang/pinpoint,koo-taejin/pinpoint,naver/pinpoint,dawidmalina/pinpoint,majinkai/pinpoint,KimTaehee/pinpoint,sbcoba/pinpoint,koo-taejin/pinpoint,PerfGeeks/pinpoint,nstopkimsk/pinpoint,koo-taejin/pinpoint,dawidmalina/pinpoint,philipz/pinpoint,InfomediaLtd/pinpoint,Skkeem/pinpoint,krishnakanthpps/pinpoint,tsyma/pinpoint,Xylus/pinpoint,cit-lab/pinpoint,majinkai/pinpoint,minwoo-jung/pinpoint,PerfGeeks/pinpoint,andyspan/pinpoint,jiaqifeng/pinpoint,InfomediaLtd/pinpoint,KimTaehee/pinpoint,tsyma/pinpoint,KimTaehee/pinpoint,majinkai/pinpoint,87439247/pinpoint,denzelsN/pinpoint,gspandy/pinpoint,wziyong/pinpoint,shuvigoss/pinpoint,jiaqifeng/pinpoint,sjmittal/pinpoint,coupang/pinpoint,Xylus/pinpoint,koo-taejin/pinpoint,emeroad/pinpoint,denzelsN/pinpoint,emeroad/pinpoint,jaehong-kim/pinpoint,breadval/pinpoint,minwoo-jung/pinpoint,citywander/pinpoint,jiaqifeng/pinpoint,jaehong-kim/pinpoint,dawidmalina/pinpoint,andyspan/pinpoint,gspandy/pinpoint,eBaoTech/pinpoint,suraj-raturi/pinpoint,citywander/pinpoint,gspandy/pinpoint,naver/pinpoint,lioolli/pinpoint,wziyong/pinpoint,KRDeNaT/pinpoint,hcapitaine/pinpoint,nstopkimsk/pinpoint,cijung/pinpoint,emeroad/pinpoint,KRDeNaT/pinpoint,minwoo-jung/pinpoint,minwoo-jung/pinpoint,carpedm20/pinpoint,KRDeNaT/pinpoint,Xylus/pinpoint,sjmittal/pinpoint,InfomediaLtd/pinpoint,PerfGeeks/pinpoint,lioolli/pinpoint,masonmei/pinpoint,citywander/pinpoint,87439247/pinpoint,Skkeem/pinpoint,sbcoba/pinpoint,naver/pinpoint,barneykim/pinpoint,hcapitaine/pinpoint,minwoo-jung/pinpoint,emeroad/pinpoint,cijung/pinpoint,carpedm20/pinpoint,sjmittal/pinpoint,chenguoxi1985/pinpoint,citywander/pinpoint,jiaqifeng/pinpoint,barneykim/pinpoint,shuvigoss/pinpoint,cit-lab/pinpoint,KimTaehee/pinpoint,shuvigoss/pinpoint,chenguoxi1985/pinpoint,KRDeNaT/pinpoint,krishnakanthpps/pinpoint,barneykim/pinpoint,87439247/pinpoint,sjmittal/pinpoint
|
/*
* Copyright 2014 NAVER Corp.
*
* 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.navercorp.pinpoint.profiler.modifier.spring.beans.interceptor;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;
public class TargetBeanFilter {
private static final int CACHE_SIZE = 1024;
private static final int CACHE_CONCURRENCY_LEVEL = Runtime.getRuntime().availableProcessors() * 2;
private static final Object EXIST = new Object();
private final Logger logger = LoggerFactory.getLogger(getClass());
private final List<Pattern> targetNamePatterns;
private final List<Pattern> targetClassPatterns;
private final List<String> targetAnnotationNames;
private final ConcurrentMap<ClassLoader, List<Class<? extends Annotation>>> targetAnnotationMap = new ConcurrentHashMap<ClassLoader, List<Class<? extends Annotation>>>();
private final Cache<Class<?>, Object> transformed = createCache();
private final Cache<Class<?>, Object> rejected = createCache();
private Cache<Class<?>, Object> createCache() {
final CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
builder.concurrencyLevel(CACHE_CONCURRENCY_LEVEL);
builder.maximumSize(CACHE_SIZE);
builder.weakKeys();
return builder.build();
}
public static TargetBeanFilter of(ProfilerConfig config) {
List<String> targetNamePatternStrings = split(config.getSpringBeansNamePatterns());
List<Pattern> beanNamePatterns = compilePattern(targetNamePatternStrings);
List<String> targetClassPatternStrings = split(config.getSpringBeansClassPatterns());
List<Pattern> beanClassPatterns = compilePattern(targetClassPatternStrings);
List<String> targetAnnotationNames = split(config.getSpringBeansAnnotations());
return new TargetBeanFilter(beanNamePatterns, beanClassPatterns, targetAnnotationNames);
}
private static List<Pattern> compilePattern(List<String> patternStrings) {
if (patternStrings == null || patternStrings.isEmpty()) {
return null;
}
List<Pattern> beanNamePatterns = new ArrayList<Pattern>(patternStrings.size());
for (String patternString : patternStrings) {
Pattern pattern = Pattern.compile(patternString);
beanNamePatterns.add(pattern);
}
return beanNamePatterns;
}
private TargetBeanFilter(List<Pattern> targetNamePatterns, List<Pattern> targetClassPatterns, List<String> targetAnnotationNames) {
this.targetNamePatterns = targetNamePatterns;
this.targetClassPatterns = targetClassPatterns;
this.targetAnnotationNames = targetAnnotationNames;
}
public boolean isTarget(String beanName, Class<?> clazz) {
if (transformed.getIfPresent(clazz) == EXIST) {
return false;
}
return isTarget(beanName) || isTarget(clazz);
}
private boolean isTarget(String beanName) {
if (targetNamePatterns != null) {
for (Pattern pattern : targetNamePatterns) {
if (pattern.matcher(beanName).matches()) {
return true;
}
}
}
return false;
}
private boolean isTarget(Class<?> clazz) {
if (rejected.getIfPresent(clazz) == EXIST) {
return false;
}
if (targetAnnotationNames != null) {
List<Class<? extends Annotation>> targetAnnotations = getTargetAnnotations(clazz.getClassLoader());
for (Class<? extends Annotation> a : targetAnnotations) {
if (clazz.isAnnotationPresent(a)) {
return true;
}
}
for (Annotation a : clazz.getAnnotations()) {
for (Class<? extends Annotation> ac : targetAnnotations) {
if (a.annotationType().isAnnotationPresent(ac)) {
return true;
}
}
}
}
if (targetClassPatterns != null) {
String className = clazz.getName();
for (Pattern pattern : targetClassPatterns) {
if (pattern.matcher(className).matches()) {
return true;
}
}
}
rejected.put(clazz, EXIST);
return false;
}
public void addTransformed(Class<?> clazz) {
transformed.put(clazz, EXIST);
}
private List<Class<? extends Annotation>> getTargetAnnotations(ClassLoader loader) {
List<Class<? extends Annotation>> targetAnnotations = targetAnnotationMap.get(loader);
if (targetAnnotations == null) {
targetAnnotations = loadTargetAnnotations(loader);
targetAnnotationMap.put(loader, targetAnnotations);
}
return targetAnnotations;
}
private List<Class<? extends Annotation>> loadTargetAnnotations(ClassLoader loader) {
if (targetAnnotationNames.isEmpty()) {
return Collections.emptyList();
}
List<Class<? extends Annotation>> targetAnnotationClasses = new ArrayList<Class<? extends Annotation>>(targetAnnotationNames.size());
for (String targetAnnotationName : targetAnnotationNames) {
try {
Class<?> clazz = loader.loadClass(targetAnnotationName);
Class<? extends Annotation> ac = clazz.asSubclass(Annotation.class);
targetAnnotationClasses.add(ac);
} catch (ClassNotFoundException e) {
logger.warn("Cannot find Spring beans profile target annotation class: {}. This configuration will be ignored.", targetAnnotationName, e);
} catch (ClassCastException e) {
logger.warn("Given Spring beans profile target annotation class is not subclass of Annotation: {}. This configuration will be ignored.", targetAnnotationName, e);
}
}
return targetAnnotationClasses;
}
private static List<String> split(String values) {
if (values == null) {
return Collections.emptyList();
}
String[] tokens = values.split(",");
List<String> result = new ArrayList<String>(tokens.length);
for (String token : tokens) {
String trimmed = token.trim();
if (!trimmed.isEmpty()) {
result.add(trimmed);
}
}
return result;
}
}
|
profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/spring/beans/interceptor/TargetBeanFilter.java
|
/*
* Copyright 2014 NAVER Corp.
*
* 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.navercorp.pinpoint.profiler.modifier.spring.beans.interceptor;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;
public class TargetBeanFilter {
private static final int CACHE_SIZE = 1024;
private static final int CACHE_CONCURRENCY_LEVEL = Runtime.getRuntime().availableProcessors() * 2;
private final Logger logger = LoggerFactory.getLogger(getClass());
private final List<Pattern> targetNamePatterns;
private final List<Pattern> targetClassPatterns;
private final List<String> targetAnnotationNames;
private final ConcurrentMap<ClassLoader, List<Class<? extends Annotation>>> targetAnnotationMap = new ConcurrentHashMap<ClassLoader, List<Class<? extends Annotation>>>();
private final Cache<Class<?>, Boolean> transformed = createCache();
private final Cache<Class<?>, Boolean> rejected = createCache();
private Cache<Class<?>, Boolean> createCache() {
final CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
builder.concurrencyLevel(CACHE_CONCURRENCY_LEVEL);
builder.maximumSize(CACHE_SIZE);
builder.weakKeys();
return builder.build();
}
public static TargetBeanFilter of(ProfilerConfig config) {
List<String> targetNamePatternStrings = split(config.getSpringBeansNamePatterns());
List<Pattern> beanNamePatterns = compilePattern(targetNamePatternStrings);
List<String> targetClassPatternStrings = split(config.getSpringBeansClassPatterns());
List<Pattern> beanClassPatterns = compilePattern(targetClassPatternStrings);
List<String> targetAnnotationNames = split(config.getSpringBeansAnnotations());
return new TargetBeanFilter(beanNamePatterns, beanClassPatterns, targetAnnotationNames);
}
private static List<Pattern> compilePattern(List<String> patternStrings) {
if (patternStrings == null || patternStrings.isEmpty()) {
return null;
}
List<Pattern> beanNamePatterns = new ArrayList<Pattern>(patternStrings.size());
for (String patternString : patternStrings) {
Pattern pattern = Pattern.compile(patternString);
beanNamePatterns.add(pattern);
}
return beanNamePatterns;
}
private TargetBeanFilter(List<Pattern> targetNamePatterns, List<Pattern> targetClassPatterns, List<String> targetAnnotationNames) {
this.targetNamePatterns = targetNamePatterns;
this.targetClassPatterns = targetClassPatterns;
this.targetAnnotationNames = targetAnnotationNames;
}
public boolean isTarget(String beanName, Class<?> clazz) {
if (transformed.getIfPresent(clazz) == Boolean.TRUE) {
return false;
}
return isTarget(beanName) || isTarget(clazz);
}
private boolean isTarget(String beanName) {
if (targetNamePatterns != null) {
for (Pattern pattern : targetNamePatterns) {
if (pattern.matcher(beanName).matches()) {
return true;
}
}
}
return false;
}
private boolean isTarget(Class<?> clazz) {
if (rejected.getIfPresent(clazz) == Boolean.TRUE) {
return false;
}
if (targetAnnotationNames != null) {
List<Class<? extends Annotation>> targetAnnotations = getTargetAnnotations(clazz.getClassLoader());
for (Class<? extends Annotation> a : targetAnnotations) {
if (clazz.isAnnotationPresent(a)) {
return true;
}
}
for (Annotation a : clazz.getAnnotations()) {
for (Class<? extends Annotation> ac : targetAnnotations) {
if (a.annotationType().isAnnotationPresent(ac)) {
return true;
}
}
}
}
if (targetClassPatterns != null) {
String className = clazz.getName();
for (Pattern pattern : targetClassPatterns) {
if (pattern.matcher(className).matches()) {
return true;
}
}
}
rejected.put(clazz, Boolean.TRUE);
return false;
}
public void addTransformed(Class<?> clazz) {
transformed.put(clazz, Boolean.TRUE);
}
private List<Class<? extends Annotation>> getTargetAnnotations(ClassLoader loader) {
List<Class<? extends Annotation>> targetAnnotations = targetAnnotationMap.get(loader);
if (targetAnnotations == null) {
targetAnnotations = loadTargetAnnotations(loader);
targetAnnotationMap.put(loader, targetAnnotations);
}
return targetAnnotations;
}
private List<Class<? extends Annotation>> loadTargetAnnotations(ClassLoader loader) {
if (targetAnnotationNames.isEmpty()) {
return Collections.emptyList();
}
List<Class<? extends Annotation>> targetAnnotationClasses = new ArrayList<Class<? extends Annotation>>(targetAnnotationNames.size());
for (String targetAnnotationName : targetAnnotationNames) {
try {
Class<?> clazz = loader.loadClass(targetAnnotationName);
Class<? extends Annotation> ac = clazz.asSubclass(Annotation.class);
targetAnnotationClasses.add(ac);
} catch (ClassNotFoundException e) {
logger.warn("Cannot find Spring beans profile target annotation class: {}. This configuration will be ignored.", targetAnnotationName, e);
} catch (ClassCastException e) {
logger.warn("Given Spring beans profile target annotation class is not subclass of Annotation: {}. This configuration will be ignored.", targetAnnotationName, e);
}
}
return targetAnnotationClasses;
}
private static List<String> split(String values) {
if (values == null) {
return Collections.emptyList();
}
String[] tokens = values.split(",");
List<String> result = new ArrayList<String>(tokens.length);
for (String token : tokens) {
String trimmed = token.trim();
if (!trimmed.isEmpty()) {
result.add(trimmed);
}
}
return result;
}
}
|
fix findbugs : comparison of Boolean references
|
profiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/spring/beans/interceptor/TargetBeanFilter.java
|
fix findbugs : comparison of Boolean references
|
<ide><path>rofiler/src/main/java/com/navercorp/pinpoint/profiler/modifier/spring/beans/interceptor/TargetBeanFilter.java
<ide> public class TargetBeanFilter {
<ide> private static final int CACHE_SIZE = 1024;
<ide> private static final int CACHE_CONCURRENCY_LEVEL = Runtime.getRuntime().availableProcessors() * 2;
<add> private static final Object EXIST = new Object();
<ide>
<ide> private final Logger logger = LoggerFactory.getLogger(getClass());
<ide>
<ide> private final List<String> targetAnnotationNames;
<ide> private final ConcurrentMap<ClassLoader, List<Class<? extends Annotation>>> targetAnnotationMap = new ConcurrentHashMap<ClassLoader, List<Class<? extends Annotation>>>();
<ide>
<del> private final Cache<Class<?>, Boolean> transformed = createCache();
<add> private final Cache<Class<?>, Object> transformed = createCache();
<ide>
<del> private final Cache<Class<?>, Boolean> rejected = createCache();
<add> private final Cache<Class<?>, Object> rejected = createCache();
<ide>
<del> private Cache<Class<?>, Boolean> createCache() {
<add> private Cache<Class<?>, Object> createCache() {
<ide> final CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
<ide> builder.concurrencyLevel(CACHE_CONCURRENCY_LEVEL);
<ide> builder.maximumSize(CACHE_SIZE);
<ide> }
<ide>
<ide> public boolean isTarget(String beanName, Class<?> clazz) {
<del> if (transformed.getIfPresent(clazz) == Boolean.TRUE) {
<add> if (transformed.getIfPresent(clazz) == EXIST) {
<ide> return false;
<ide> }
<ide>
<ide> }
<ide>
<ide> private boolean isTarget(Class<?> clazz) {
<del> if (rejected.getIfPresent(clazz) == Boolean.TRUE) {
<add> if (rejected.getIfPresent(clazz) == EXIST) {
<ide> return false;
<ide> }
<ide>
<ide> }
<ide> }
<ide>
<del> rejected.put(clazz, Boolean.TRUE);
<add> rejected.put(clazz, EXIST);
<ide> return false;
<ide> }
<ide>
<ide> public void addTransformed(Class<?> clazz) {
<del> transformed.put(clazz, Boolean.TRUE);
<add> transformed.put(clazz, EXIST);
<ide> }
<ide>
<ide> private List<Class<? extends Annotation>> getTargetAnnotations(ClassLoader loader) {
|
|
Java
|
mit
|
c1bd5c517d988a482f031405cd6286ee6f7a7455
| 0 |
Daytron/WebCrawler,novoselrok/WebCrawler
|
package com.redditprog.webcrawler;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @author Rok
* @author ryan
*/
public class SubRedditChecker {
private static final int CODE_OK = 1;
private static final int CODE_BUSY = 2;
private static final int CODE_INVALID = 0;
public static int verifySubReddit(String sub) {
int children_array_length = 0;
try {
// set the full url of the user input subreddit
final URL url = new URL(GlobalConfiguration.REDDIT_PRE_SUB_URL + sub + ".json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedReader bin = null;
bin = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder jsonString = new StringBuilder();
// below will print out bin
String line;
while ((line = bin.readLine()) != null) {
jsonString.append(line);
}
bin.close();
if (!jsonString.toString().startsWith(GlobalConfiguration.REDDIT_JSON_PATTERN)) {
return CODE_BUSY;
}
JSONObject obj = new JSONObject(jsonString.toString());
children_array_length = obj.getJSONObject("data").getJSONArray("children").length();
if (children_array_length > 0) {
return CODE_OK;
} else {
return CODE_INVALID;
}
} catch (java.net.SocketTimeoutException e) {
} catch (java.io.IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
// Return value for exceptions
return CODE_INVALID;
}
}
|
src/main/java/com/redditprog/webcrawler/SubRedditChecker.java
|
package com.redditprog.webcrawler;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @author Rok
* @author ryan
*/
public class SubRedditChecker {
private static final int CODE_OK = 1;
private static final int CODE_BUSY = 2;
private static final int CODE_INVALID = 0;
public static int verifySubReddit(String sub) {
int children_array_length = 0;
try {
// set the full url of the user input subreddit
final URL url = new URL(GlobalConfiguration.REDDIT_PRE_SUB_URL + sub + ".json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedReader bin = null;
bin = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder jsonString = new StringBuilder();
// below will print out bin
String line;
while ((line = bin.readLine()) != null) {
jsonString.append(line);
}
bin.close();
// For debugging, for inspection of the contents
// Delete after testing
System.out.println(jsonString);
if (!jsonString.toString().startsWith(GlobalConfiguration.REDDIT_JSON_PATTERN)) {
return CODE_BUSY;
}
JSONObject obj = new JSONObject(jsonString.toString());
children_array_length = obj.getJSONObject("data").getJSONArray("children").length();
if (children_array_length > 0) {
return CODE_OK;
} else {
return CODE_INVALID;
}
} catch (java.net.SocketTimeoutException e) {
} catch (java.io.IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
// Return value for exceptions
return CODE_INVALID;
}
}
|
Deleted a debugging print statement
|
src/main/java/com/redditprog/webcrawler/SubRedditChecker.java
|
Deleted a debugging print statement
|
<ide><path>rc/main/java/com/redditprog/webcrawler/SubRedditChecker.java
<ide>
<ide> bin.close();
<ide>
<del> // For debugging, for inspection of the contents
<del> // Delete after testing
<del> System.out.println(jsonString);
<del>
<ide> if (!jsonString.toString().startsWith(GlobalConfiguration.REDDIT_JSON_PATTERN)) {
<ide> return CODE_BUSY;
<ide> }
|
|
Java
|
artistic-2.0
|
8790a21d21d39a47e1fcf7725ac4729dce569fb6
| 0 |
sanjeevsuresh/ChordFinder
|
public class Intervals{
/* This is a comment
*/
public static final int MAJ3 = 4;
public static final int MIN3 = 3;
public static final int FIFTH = 7;
public static final int AUG5 = 8;
public static final int DIM5 = 6;
public static final int SUS4 = 5;
public static final int SUS2 = 2;
}
|
Intervals.java
|
public class Intervals{
public static final int MAJ3 = 4;
public static final int MIN3 = 3;
public static final int FIFTH = 7;
public static final int AUG5 = 8;
public static final int DIM5 = 6;
public static final int SUS4 = 5;
public static final int SUS2 = 2;
}
|
First Version
|
Intervals.java
|
First Version
|
<ide><path>ntervals.java
<ide> public class Intervals{
<del>
<add> /* This is a comment
<add> */
<ide> public static final int MAJ3 = 4;
<ide> public static final int MIN3 = 3;
<ide> public static final int FIFTH = 7;
|
|
JavaScript
|
agpl-3.0
|
bdd1c0eacf5f073d4d98b0c61ae69c7bd119d1a8
| 0 |
superdesk/liveblog,darconny/liveblog,ancafarcas/liveblog,hlmnrmr/liveblog,liveblog/liveblog,superdesk/liveblog,liveblog/liveblog,superdesk/liveblog,hlmnrmr/liveblog,hlmnrmr/liveblog,darconny/liveblog,ancafarcas/liveblog,superdesk/liveblog,darconny/liveblog,ancafarcas/liveblog,darconny/liveblog,liveblog/liveblog,liveblog/liveblog,liveblog/liveblog,hlmnrmr/liveblog,ancafarcas/liveblog
|
/**
* This file is part of Superdesk.
*
* Copyright 2013, 2014 Sourcefabric z.u. and contributors.
*
* For the full copyright and license information, please see the
* AUTHORS and LICENSE files distributed with this source code, or
* at https://www.sourcefabric.org/superdesk/license
*/
define([
'angular',
'ng-sir-trevor'
], function(angular) {
'use strict';
angular
.module('SirTrevorBlocks', [])
.config(['SirTrevorProvider', function(SirTrevor) {
// Add toMeta method to all blocks.
SirTrevor.Block.prototype.toMeta = function(){return;};
SirTrevor.Block.prototype.getOptions = function(){return SirTrevor.$get().getInstance(this.instanceID).options;};
SirTrevor.Blocks.Link = SirTrevor.Block.extend({
type: 'link',
title: function(){ return 'Link'; },
icon_name: 'link',
editorHTML: function() {
return [
'<div class="st-required st-link-block link-input"',
' placeholder="url" contenteditable="true"></div>'
].join('\n');
},
onBlockRender: function() {
var that = this;
// create and trigger a 'change' event for the $editor which is a contenteditable
this.$editor.filter('[contenteditable]').on('focus', function(ev) {
var $this = $(this);
$this.data('before', $this.html());
});
this.$editor.filter('[contenteditable]').on('blur keyup paste input', function(ev) {
var $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$this.trigger('change');
}
});
// when the link field changes
this.$editor.on('change', function() {
var url = $(this).text().trim();
// exit if the url is empty. Not needed to disturb the service
if (url === '') {
return false;
}
that.getOptions().embedService.get(url)
.then(function saveAndLoadData(data) {
that.data = data;
that.loadData(that.data);
}, function errorCallback(error) {
that.addMessage('an error occured: ' + error);
});
});
},
isEmpty: function() {
return _.isEmpty(this.retrieveData().url);
},
retrieveData: function() {
// retrieve new data from editor
var data = {
html: this.$('.embed-preview').html(),
title: this.$('.title-preview').text(),
description: this.$('.description-preview').text(),
url: this.$('.link-preview').attr('href')
};
if (this.$('.cover-preview-handler').hasClass('hidden')) {
delete data.thumbnail_url;
}
// remove empty string
_.forEach(data, function(value, key) {
if (typeof(value) === 'string' && value.trim() === '') {
delete data[key];
}
});
// add data which are not in the editor but has been saved before (like thumbnail_width)
_.merge(this.data, data);
return this.data;
},
renderCard: function(data, editable) {
if (editable === undefined) {editable = false;}
var card_class = 'liveblog--card';
var html = $([
'<div class="'+card_class+' hidden">',
' <div class="hidden st-link-block embed-preview"></div>',
' <div class="hidden st-link-block cover-preview-handler">',
' <div class="st-link-block cover-preview"></div>',
' </div>',
' <div class="st-link-block title-preview"></div>',
' <div class="st-link-block description-preview"></div>',
' <a class="st-link-block link-preview"></a>',
'</div>'
].join('\n'));
// but this html to the DOM (neeeded to use jquery)
$('body > .'+card_class).remove();
$('body').append(html);
html = $('body > .'+card_class);
// hide everything
html.find(
['.embed-preview',
'.cover-preview-handler'].join(', ')
).addClass('hidden');
// set the link
html.find('.link-preview')
.attr('href', data.url)
.html(data.url);
// set the embed code
if (data.html !== undefined) {
html.find('.embed-preview')
.html(data.html).removeClass('hidden');
}
// set the cover illustration
if (data.html === undefined && data.thumbnail_url !== undefined) {
var ratio = data.thumbnail_width / data.thumbnail_height;
var cover_width = Math.min(447, data.thumbnail_width);
var cover_height = cover_width / ratio;
html.find('.cover-preview').css({
'background-image': 'url('+data.thumbnail_url+')',
width: cover_width,
height: cover_height
});
html.find('.cover-preview-handler').removeClass('hidden');
}
// set the title
if (data.title !== undefined) {
html.find('.title-preview')
.html(data.title);
}
// set the description
if (data.description !== undefined) {
html.find('.description-preview')
.html(data.description);
}
// set editable if needed
if (editable) {
html.find('.title-preview').attr({
contenteditable: true,
placeholder: 'title'
});
html.find('.description-preview').attr({
contenteditable: true,
placeholder: 'description'
});
}
// retrieve the final html code
var html_to_return = '';
html_to_return = '<div class="'+card_class+'">';
html_to_return += html.get(0).innerHTML;
html_to_return += '</div>';
// remove html from the DOM
html.remove();
return html_to_return;
},
loadData: function(data) {
this.$('.link-input')
.addClass('hidden')
.after(this.renderCard(data, true));
},
focus: function() {
this.$('.link-input').focus();
},
// toMarkdown: function(markdown) {},
toHTML: function() {
var data = this.retrieveData();
return this.renderCard(data);
},
toMeta: function() {
return this.retrieveData();
}
});
SirTrevor.Blocks.Quote = SirTrevor.Block.extend({
type: 'quote',
title: function(){ return window.i18n.t('blocks:quote:title'); },
icon_name: 'quote',
editorHTML: function() {
var template = _.template([
'<div class="st-required st-quote-block quote-input" ',
' placeholder="quote" contenteditable="true"></div>',
'<div contenteditable="true" name="cite" placeholder="<%= i18n.t("blocks:quote:credit_field") %>"',
' class="js-cite-input st-quote-block"></div>'
].join('\n'));
return template(this);
},
focus: function() {
this.$('.quote-input').focus();
},
retrieveData: function() {
return {
quote: this.$('.quote-input').text() || undefined,
credit: this.$('.js-cite-input').text() || undefined
};
},
loadData: function(data){
this.$('.quote-input').text(SirTrevor.toHTML(data.text, this.type));
this.$('.js-cite-input').text(data.credit);
},
isEmpty: function() {
return _.isEmpty(this.retrieveData().quote);
},
toMarkdown: function(markdown) {
return markdown.replace(/^(.+)$/mg,'> $1');
},
toHTML: function(html) {
var data = this.retrieveData();
return [
'<blockquote><p>',
data.quote,
'</p><ul><li>',
data.credit,
'</li></ul></blockquote>'
].join('');
},
toMeta: function() {
return this.retrieveData();
}
});
// Image Block
var upload_options = {
// NOTE: responsive layout is currently disabled. so row and col-md-6 are useless
html: [
'<div class="row st-block__upload-container">',
' <input type="file" type="st-file-upload" />',
' <div class="col-md-6">',
' <button class="btn btn-default"><%= i18n.t("general:upload") %></button>',
' </div>',
'</div>'
].join('\n')
};
SirTrevor.DEFAULTS.Block.upload_options = upload_options;
SirTrevor.Locales.en.general.upload = 'Select from folder';
SirTrevor.Blocks.Image = SirTrevor.Block.extend({
type: 'image',
title: function() {
return 'Image';
},
droppable: true,
uploadable: true,
icon_name: 'image',
loadData: function(data) {
var file_url = (typeof(data.file) !== 'undefined') ? data.file.url : data.media._url;
this.$editor.html($('<img>', {
src: file_url
})).show();
this.$editor.append($('<div>', {
name: 'caption',
class: 'st-image-block',
contenteditable: true,
placeholder: 'Add a description'
}).html(data.caption));
this.$editor.append($('<div>', {
name: 'credit',
class: 'st-image-block',
contenteditable: true,
placeholder: 'Add author / photographer'
}).html(data.credit));
},
onBlockRender: function() {
// assert we have an uploader function in options
if (typeof(this.getOptions().uploader) !== 'function') {
throw 'Image block need an `uploader` function in options.';
}
// setup the upload button
this.$inputs.find('button').bind('click', function(ev) {
ev.preventDefault();
});
this.$inputs.find('input').on('change', _.bind(function(ev) {
this.onDrop(ev.currentTarget);
}, this));
},
onDrop: function(transferData) {
var that = this;
var file = transferData.files[0];
var urlAPI = window.URL;
if (typeof urlAPI === 'undefined') {
urlAPI = window.webkitURL;
}
// Handle one upload at a time
if (/image/.test(file.type)) {
this.loading();
// Show this image on here
this.$inputs.hide();
this.loadData({
file: {
url: urlAPI.createObjectURL(file)
}
});
this.getOptions().uploader(
file,
function(data) {
that.setData(data);
that.ready();
},
function(error) {
var message = error || window.i18n.t('blocks:image:upload_error');
that.addMessage(message);
that.ready();
}
);
}
},
retrieveData: function() {
return {
media: this.getData().media,
caption: this.$('[name=caption]').text(),
credit: this.$('[name=credit]').text()
};
},
toHTML: function() {
var data = this.retrieveData();
return [
'<figure>',
' <img src="' + data.media._url + '" alt="' + data.caption + '"/>',
' <figcaption>' + data.caption + (data.credit === '' ? '' : ' from ' + data.credit) +'</figcaption>',
'</figure>'
].join('');
},
toMeta: function() {
return this.retrieveData();
}
});
// Add toHTML to existing Text Block.
SirTrevor.Blocks.Text.prototype.toHTML = function() {
return this.getTextBlock().html();
};
var Strikethrough = SirTrevor.Formatter.extend({
title: 'strikethrough',
iconName: 'strikethrough',
cmd: 'strikeThrough',
text: 'S'
});
SirTrevor.Formatters.Strikethrough = new Strikethrough();
var OrderedList = SirTrevor.Formatter.extend({
title: 'orderedlist',
iconName: 'link',
cmd: 'insertOrderedList',
text: 'orderedlist'
});
SirTrevor.Formatters.NumberedList = new OrderedList();
var UnorderedList = SirTrevor.Formatter.extend({
title: 'unorderedlist',
iconName: 'link',
cmd: 'insertUnorderedList',
text: 'unorderedlist'
});
SirTrevor.Formatters.BulletList = new UnorderedList();
}]);
});
|
app/scripts/ng-sir-trevor-blocks.js
|
/**
* This file is part of Superdesk.
*
* Copyright 2013, 2014 Sourcefabric z.u. and contributors.
*
* For the full copyright and license information, please see the
* AUTHORS and LICENSE files distributed with this source code, or
* at https://www.sourcefabric.org/superdesk/license
*/
define([
'angular',
'ng-sir-trevor'
], function(angular) {
'use strict';
angular
.module('SirTrevorBlocks', [])
.config(['SirTrevorProvider', function(SirTrevor) {
// Add toMeta method to all blocks.
SirTrevor.Block.prototype.toMeta = function(){return;};
SirTrevor.Block.prototype.getOptions = function(){return SirTrevor.$get().getInstance(this.instanceID).options;};
SirTrevor.Blocks.Link = SirTrevor.Block.extend({
type: 'link',
title: function(){ return 'Link'; },
icon_name: 'link',
editorHTML: function() {
return [
'<div class="st-required st-link-block link-input"',
' placeholder="url" contenteditable="true"></div>'
].join('\n');
},
onBlockRender: function() {
var that = this;
// create and trigger a 'change' event for the $editor which is a contenteditable
this.$editor.filter('[contenteditable]').on('focus', function(ev) {
var $this = $(this);
$this.data('before', $this.html());
});
this.$editor.filter('[contenteditable]').on('blur keyup paste input', function(ev) {
var $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$this.trigger('change');
}
});
// when the link field changes
this.$editor.on('change', function() {
var url = $(this).text().trim();
// exit if the url is empty. Not needed to disturb the service
if (url === '') {
return false;
}
that.getOptions().embedService.get(url)
.then(function saveAndLoadData(data) {
that.data = data;
that.loadData(that.data);
}, function errorCallback(error) {
that.addMessage('an error occured: ' + error);
});
});
},
isEmpty: function() {
return _.isEmpty(this.retrieveData().url);
},
retrieveData: function() {
// retrieve new data from editor
var data = {
html: this.$('.embed-preview').html(),
title: this.$('.title-preview').text(),
description: this.$('.description-preview').text(),
url: this.$('.link-preview').attr('href')
};
if (this.$('.cover-preview-handler').hasClass('hidden')) {
delete data.thumbnail_url;
}
// remove empty string
_.forEach(data, function(value, key) {
if (typeof(value) === 'string' && value.trim() === '') {
delete data[key];
}
});
// add data which are not in the editor but has been saved before (like thumbnail_width)
_.merge(this.data, data);
return this.data;
},
renderCard: function(data) {
var card_class = 'liveblog--card';
var html = $([
'<div class="'+card_class+' hidden">',
' <div class="hidden st-link-block embed-preview"></div>',
' <div class="hidden st-link-block cover-preview-handler">',
' <div class="st-link-block cover-preview"></div>',
' </div>',
' <div class="hidden st-link-block title-preview" contenteditable="true"></div>',
' <div class="hidden st-link-block description-preview" contenteditable="true"></div>',
' <a class="hidden st-link-block link-preview"></a>',
'</div>'
].join('\n'));
// but this html to the DOM (neeeded to use jquery)
$('body > .'+card_class).remove();
$('body').append(html);
html = $('body > .'+card_class);
// hide everything
html.find(
['.embed-preview',
'.cover-preview-handler',
'.title-preview',
'.description-preview'].join(', ')
).addClass('hidden');
// set the link
html.find('.link-preview')
.attr('href', data.url)
.html(data.url)
.removeClass('hidden');
// set the embed code
if (data.html !== undefined) {
html.find('.embed-preview')
.html(data.html).removeClass('hidden');
}
// set the cover illustration
if (data.html === undefined && data.thumbnail_url !== undefined) {
var ratio = data.thumbnail_width / data.thumbnail_height;
var cover_width = Math.min(447, data.thumbnail_width);
var cover_height = cover_width / ratio;
html.find('.cover-preview').css({
'background-image': 'url('+data.thumbnail_url+')',
width: cover_width,
height: cover_height
});
html.find('.cover-preview-handler').removeClass('hidden');
}
// set the title
if (data.title !== undefined) {
html.find('.title-preview')
.html(data.title).removeClass('hidden');
}
// set the description
if (data.description !== undefined) {
html.find('.description-preview')
.html(data.description).removeClass('hidden');
}
// retrieve the final html code
var html_to_return = '';
html_to_return = '<div class="'+card_class+'">';
html_to_return += html.get(0).innerHTML;
html_to_return += '</div>';
// remove html from the DOM
html.remove();
return html_to_return;
},
loadData: function(data) {
this.$('.link-input')
.addClass('hidden')
.after(this.renderCard(data));
},
focus: function() {
this.$('.link-input').focus();
},
// toMarkdown: function(markdown) {},
toHTML: function() {
var data = this.retrieveData();
return this.renderCard(data);
},
toMeta: function() {
return this.retrieveData();
}
});
SirTrevor.Blocks.Quote = SirTrevor.Block.extend({
type: 'quote',
title: function(){ return window.i18n.t('blocks:quote:title'); },
icon_name: 'quote',
editorHTML: function() {
var template = _.template([
'<div class="st-required st-quote-block quote-input" ',
' placeholder="quote" contenteditable="true"></div>',
'<div contenteditable="true" name="cite" placeholder="<%= i18n.t("blocks:quote:credit_field") %>"',
' class="js-cite-input st-quote-block"></div>'
].join('\n'));
return template(this);
},
focus: function() {
this.$('.quote-input').focus();
},
retrieveData: function() {
return {
quote: this.$('.quote-input').text() || undefined,
credit: this.$('.js-cite-input').text() || undefined
};
},
loadData: function(data){
this.$('.quote-input').text(SirTrevor.toHTML(data.text, this.type));
this.$('.js-cite-input').text(data.credit);
},
isEmpty: function() {
return _.isEmpty(this.retrieveData().quote);
},
toMarkdown: function(markdown) {
return markdown.replace(/^(.+)$/mg,'> $1');
},
toHTML: function(html) {
var data = this.retrieveData();
return [
'<blockquote><p>',
data.quote,
'</p><ul><li>',
data.credit,
'</li></ul></blockquote>'
].join('');
},
toMeta: function() {
return this.retrieveData();
}
});
// Image Block
var upload_options = {
// NOTE: responsive layout is currently disabled. so row and col-md-6 are useless
html: [
'<div class="row st-block__upload-container">',
' <input type="file" type="st-file-upload" />',
' <div class="col-md-6">',
' <button class="btn btn-default"><%= i18n.t("general:upload") %></button>',
' </div>',
'</div>'
].join('\n')
};
SirTrevor.DEFAULTS.Block.upload_options = upload_options;
SirTrevor.Locales.en.general.upload = 'Select from folder';
SirTrevor.Blocks.Image = SirTrevor.Block.extend({
type: 'image',
title: function() {
return 'Image';
},
droppable: true,
uploadable: true,
icon_name: 'image',
loadData: function(data) {
var file_url = (typeof(data.file) !== 'undefined') ? data.file.url : data.media._url;
this.$editor.html($('<img>', {
src: file_url
})).show();
this.$editor.append($('<div>', {
name: 'caption',
class: 'st-image-block',
contenteditable: true,
placeholder: 'Add a description'
}).html(data.caption));
this.$editor.append($('<div>', {
name: 'credit',
class: 'st-image-block',
contenteditable: true,
placeholder: 'Add author / photographer'
}).html(data.credit));
},
onBlockRender: function() {
// assert we have an uploader function in options
if (typeof(this.getOptions().uploader) !== 'function') {
throw 'Image block need an `uploader` function in options.';
}
// setup the upload button
this.$inputs.find('button').bind('click', function(ev) {
ev.preventDefault();
});
this.$inputs.find('input').on('change', _.bind(function(ev) {
this.onDrop(ev.currentTarget);
}, this));
},
onDrop: function(transferData) {
var that = this;
var file = transferData.files[0];
var urlAPI = window.URL;
if (typeof urlAPI === 'undefined') {
urlAPI = window.webkitURL;
}
// Handle one upload at a time
if (/image/.test(file.type)) {
this.loading();
// Show this image on here
this.$inputs.hide();
this.loadData({
file: {
url: urlAPI.createObjectURL(file)
}
});
this.getOptions().uploader(
file,
function(data) {
that.setData(data);
that.ready();
},
function(error) {
var message = error || window.i18n.t('blocks:image:upload_error');
that.addMessage(message);
that.ready();
}
);
}
},
retrieveData: function() {
return {
media: this.getData().media,
caption: this.$('[name=caption]').text(),
credit: this.$('[name=credit]').text()
};
},
toHTML: function() {
var data = this.retrieveData();
return [
'<figure>',
' <img src="' + data.media._url + '" alt="' + data.caption + '"/>',
' <figcaption>' + data.caption + (data.credit === '' ? '' : ' from ' + data.credit) +'</figcaption>',
'</figure>'
].join('');
},
toMeta: function() {
return this.retrieveData();
}
});
// Add toHTML to existing Text Block.
SirTrevor.Blocks.Text.prototype.toHTML = function() {
return this.getTextBlock().html();
};
var Strikethrough = SirTrevor.Formatter.extend({
title: 'strikethrough',
iconName: 'strikethrough',
cmd: 'strikeThrough',
text: 'S'
});
SirTrevor.Formatters.Strikethrough = new Strikethrough();
var OrderedList = SirTrevor.Formatter.extend({
title: 'orderedlist',
iconName: 'link',
cmd: 'insertOrderedList',
text: 'orderedlist'
});
SirTrevor.Formatters.NumberedList = new OrderedList();
var UnorderedList = SirTrevor.Formatter.extend({
title: 'unorderedlist',
iconName: 'link',
cmd: 'insertUnorderedList',
text: 'unorderedlist'
});
SirTrevor.Formatters.BulletList = new UnorderedList();
}]);
});
|
SirTrevor-embed-block: renderCard with or without contenteditable
LBSD-280
|
app/scripts/ng-sir-trevor-blocks.js
|
SirTrevor-embed-block: renderCard with or without contenteditable
|
<ide><path>pp/scripts/ng-sir-trevor-blocks.js
<ide> _.merge(this.data, data);
<ide> return this.data;
<ide> },
<del> renderCard: function(data) {
<add> renderCard: function(data, editable) {
<add> if (editable === undefined) {editable = false;}
<ide> var card_class = 'liveblog--card';
<ide> var html = $([
<ide> '<div class="'+card_class+' hidden">',
<ide> ' <div class="hidden st-link-block cover-preview-handler">',
<ide> ' <div class="st-link-block cover-preview"></div>',
<ide> ' </div>',
<del> ' <div class="hidden st-link-block title-preview" contenteditable="true"></div>',
<del> ' <div class="hidden st-link-block description-preview" contenteditable="true"></div>',
<del> ' <a class="hidden st-link-block link-preview"></a>',
<add> ' <div class="st-link-block title-preview"></div>',
<add> ' <div class="st-link-block description-preview"></div>',
<add> ' <a class="st-link-block link-preview"></a>',
<ide> '</div>'
<ide> ].join('\n'));
<ide> // but this html to the DOM (neeeded to use jquery)
<ide> // hide everything
<ide> html.find(
<ide> ['.embed-preview',
<del> '.cover-preview-handler',
<del> '.title-preview',
<del> '.description-preview'].join(', ')
<add> '.cover-preview-handler'].join(', ')
<ide> ).addClass('hidden');
<ide> // set the link
<ide> html.find('.link-preview')
<ide> .attr('href', data.url)
<del> .html(data.url)
<del> .removeClass('hidden');
<add> .html(data.url);
<ide> // set the embed code
<ide> if (data.html !== undefined) {
<ide> html.find('.embed-preview')
<ide> // set the title
<ide> if (data.title !== undefined) {
<ide> html.find('.title-preview')
<del> .html(data.title).removeClass('hidden');
<add> .html(data.title);
<ide> }
<ide> // set the description
<ide> if (data.description !== undefined) {
<ide> html.find('.description-preview')
<del> .html(data.description).removeClass('hidden');
<add> .html(data.description);
<add> }
<add> // set editable if needed
<add> if (editable) {
<add> html.find('.title-preview').attr({
<add> contenteditable: true,
<add> placeholder: 'title'
<add> });
<add> html.find('.description-preview').attr({
<add> contenteditable: true,
<add> placeholder: 'description'
<add> });
<ide> }
<ide> // retrieve the final html code
<ide> var html_to_return = '';
<ide> loadData: function(data) {
<ide> this.$('.link-input')
<ide> .addClass('hidden')
<del> .after(this.renderCard(data));
<add> .after(this.renderCard(data, true));
<ide> },
<ide> focus: function() {
<ide> this.$('.link-input').focus();
|
|
JavaScript
|
mit
|
19421332402eaa099a20866f8057331dc7e3ee38
| 0 |
kyroskoh/JavaScript-Koans,kyroskoh/JavaScript-Koans,mayormcmatt/js_koans,hansenwt2/JavaScript-Koans,brod4910/JavaScript-Koans,brod4910/JavaScript-Koans,bryantt23/JavaScript-Koans,smstamm/JavaScript-Koans,zerolive/JavaScript_Koans,vvscode/js--js-qunit-koans,runewizard/JavaScript-Koans,MaciekBorkowski4/Koans-JavaScript,Drooids/JavaScript-Koans,Thapz123/JavaScript-Koans,dhiller/JavaScript-Koans,zerolive/JavaScript_Koans,BrianRod/JavaScript-Koans,okdonga/JavaScript-Koans,GemmaStiles/JavaScript-Koans,josl/JavaScript-Koans,supportbeam/javascript_koans,yuliya5/JavaScript-Koans-Answers,JadeInHand/JavaScript-Koans,josl/JavaScript-Koans,jonharlem/JavaScript-Koans,mrcosta/anotherjavascriptkoans,vvscode/js--js-qunit-koans,liammclennan/JavaScript-Koans,mikesprague/JavaScript-Koans,benms/kottans_js_koans,Ada-Developers-Academy/JavaScript-Koans,neilspencer85/js-koans,Vyivrain/JavaScriptkoans,cintiamh/JavaScript-Koans-1,olinares/JavaScript-Koans,liammclennan/JavaScript-Koans,hansenwt2/JavaScript-Koans,Ada-Developers-Academy/JavaScript-Koans,radavis/JavaScript-Koans,davidhay/js-koans,lawrence34/JavaScript-Koans,amysimmons/JavaScript-Koans,olinares/JavaScript-Koans,Thapz123/JavaScript-Koans,raphaelbn/JavaScript-Koans,Alxswan/JavaScript-Koans,smstamm/JavaScript-Koans,cintiamh/JavaScript-Koans-1,mikesprague/JavaScript-Koans,121watts/JavaScript-Koans,raphaelbn/JavaScript-Koans,Drooids/JavaScript-Koans,ricardorojass/javascriptkoans,runewizard/JavaScript-Koans,jonharlem/JavaScript-Koans,qakovalyov/js-koans,szerlak/JavaScript-Koans,bryantt23/JavaScript-Koans,Shakira4242/JavaScript-Koans,akbur/JavaScript-Koans,amysimmons/JavaScript-Koans,Ribeiro/JavaScript_Koans_Solved,gezafisch/JavaScript-Koans,Alxswan/JavaScript-Koans,Ribeiro/JavaScript_Koans_Solved,Cath-kb/JavaScript-Koans,alexeymazurik/js_koans,JadeInHand/JavaScript-Koans,okdonga/JavaScript-Koans,arachnegl/javascript-koans-qunit,thzt/JavaScript-Koans,ricardorojass/javascriptkoans,IIIRepublica/JavaScript-Koans,hugovila/my_javascript-koans_liammclennan,conniegiann/JavaScript-Koans,supportbeam/javascript_koans,neilspencer85/js-koans,Shakira4242/JavaScript-Koans,budapaul/javascript-koans,yuliya5/JavaScript-Koans-Answers,pabranch/JavaScript-Koans,betabrain/JavaScript-Koans,GemmaStiles/JavaScript-Koans,gezafisch/JavaScript-Koans,betabrain/JavaScript-Koans,conniegiann/JavaScript-Koans,szerlak/JavaScript-Koans,thzt/JavaScript-Koans,Ada-Developers-Academy/JavaScript-Koans,Cath-kb/JavaScript-Koans,dhiller/JavaScript-Koans,mrcosta/anotherjavascriptkoans,akbur/JavaScript-Koans,lawrence34/JavaScript-Koans,BrianRod/JavaScript-Koans,hugovila/my_javascript-koans_liammclennan,MaciekBorkowski4/Koans-JavaScript
|
$(document).ready(function(){
// demonstrate the effect of modifying an objects prototype before and after the object is constructed
module("About Prototypal Inheritance (topics/about_prototypal_inheritance.js)");
// this 'class' pattern defines a class by its constructor
var Mammal = function(name) {
this.name = name;
}
// things that don't need to be set in the constructor should be added to the constructor's prototype property.
Mammal.prototype = {
sayHi: function() {
return "Hello, my name is " + this.name;
}
}
test("defining a 'class'", function() {
var eric = new Mammal("Eric");
equals(eric.sayHi(), __, 'what will Eric say?');
});
// add another function to the Mammal 'type' that uses the sayHi function
Mammal.prototype.favouriteSaying = function() {
return this.name + "'s favourite saying is " + this.sayHi();
}
test("more functions", function() {
var bobby = new Mammal("Bobby");
equals(bobby.favouriteSaying(), __, "what is Bobby's favourite saying?");
});
test("calling functions added to a prototype after an object was created", function() {
var paul = new Mammal("Paul");
Mammal.prototype.numberOfLettersInName = function() {
return this.name.length;
};
// for the following statement asks the paul object to call a function that was added to the Mammal prototype after paul was constructed.
equals(paul.numberOfLettersInName(), __, "how long is Paul's name?");
});
// helper function for inheritance.
// From https://developer.mozilla.org/en/JavaScript/Guide/Inheritance_Revisited
function extend(child, supertype){
child.prototype.__proto__ = supertype.prototype;
}
// "Subclass" Mammal
function Bat(name, wingspan) {
Mammal.call(this, name);
this.wingspan = wingspan;
}
// configure inheritance
extend(Bat, Mammal);
test("Inheritance", function() {
var lenny = new Bat("Lenny", "1.5m");
equals(lenny.sayHi(), __, "what does Lenny say?");
equals(lenny.wingspan, __, "what is Lenny's wingspan?");
});
});
|
topics/about_prototypal_inheritance.js
|
$(document).ready(function(){
// demonstrate the effect of modifying an objects prototype before and after the object is constructed
module("About Prototypal Inheritance (topics/about_prototypal_inheritance.js)");
// this 'class' pattern defines a class by its constructor
var Mammal = function(name) {
this.name = name;
}
// things that don't need to be set in the constructor should beadded to the constructor's prototype property.
Mammal.prototype = {
sayHi: function() {
return "Hello, my name is " + this.name;
}
}
test("defining a 'class'", function() {
var eric = new Mammal("Eric");
equals(eric.sayHi(), __, 'what will Eric say?');
});
// add another function to the Mammal 'type' that uses the sayHi function
Mammal.prototype.favouriteSaying = function() {
return this.name + "'s favourite saying is " + this.sayHi();
}
test("more functions", function() {
var bobby = new Mammal("Bobby");
equals(bobby.favouriteSaying(), __, "what is Bobby's favourite saying?");
});
test("calling functions added to a prototype after an object was created", function() {
var paul = new Mammal("Paul");
Mammal.prototype.numberOfLettersInName = function() {
return this.name.length;
};
// for the following statement asks the paul object to call a function that was added to the Mammal prototype after paul was constructed.
equals(paul.numberOfLettersInName(), __, "how long is Paul's name?");
});
// helper function for inheritance.
// From https://developer.mozilla.org/en/JavaScript/Guide/Inheritance_Revisited
function extend(child, supertype){
child.prototype.__proto__ = supertype.prototype;
}
// "Subclass" Mammal
function Bat(name, wingspan) {
Mammal.call(this, name);
this.wingspan = wingspan;
}
// configure inheritance
extend(Bat, Mammal);
test("Inheritance", function() {
var lenny = new Bat("Lenny", "1.5m");
equals(lenny.sayHi(), __, "what does Lenny say?");
equals(lenny.wingspan, __, "what is Lenny's wingspan?");
});
});
|
fixed a typo
|
topics/about_prototypal_inheritance.js
|
fixed a typo
|
<ide><path>opics/about_prototypal_inheritance.js
<ide> var Mammal = function(name) {
<ide> this.name = name;
<ide> }
<del> // things that don't need to be set in the constructor should beadded to the constructor's prototype property.
<add> // things that don't need to be set in the constructor should be added to the constructor's prototype property.
<ide> Mammal.prototype = {
<ide> sayHi: function() {
<ide> return "Hello, my name is " + this.name;
|
|
Java
|
apache-2.0
|
6fcdc7eb2a87eb6ed0c971e8076aadd3895662c8
| 0 |
jacek-rzrz/RxJava,vqvu/RxJava,Godchin1990/RxJava,spoon-bot/RxJava,wrightm/RxJava,nurkiewicz/RxJava,shekarrex/RxJava,A-w-K/RxJava,HuangWenhuan0/RxJava,sunfei/RxJava,Ryan800/RxJava,wlrhnh-David/RxJava,ReactiveX/RxJava,ChenWenHuan/RxJava,ronenhamias/RxJava,ypresto/RxJava,yuhuayi/RxJava,aditya-chaturvedi/RxJava,sposam/RxJava,duqiao/RxJava,hyarlagadda/RxJava,weikipeng/RxJava,Ribeiro/RxJava,randall-mo/RxJava,suclike/RxJava,androidgilbert/RxJava,weikipeng/RxJava,eduardotrandafilov/RxJava,davidmoten/RxJava,southwolf/RxJava,Siddartha07/RxJava,wlrhnh-David/RxJava,lijunhuayc/RxJava,hyleung/RxJava,marcogarcia23/RxJava,HuangWenhuan0/RxJava,maugomez77/RxJava,vqvu/RxJava,cloudbearings/RxJava,Turbo87/RxJava,gjesse/RxJava,lijunhuayc/RxJava,cgpllx/RxJava,Godchin1990/RxJava,srayhunter/RxJava,tilal6991/RxJava,devagul93/RxJava,forsail/RxJava,artem-zinnatullin/RxJava,Ryan800/RxJava,picnic106/RxJava,sanxieryu/RxJava,sposam/RxJava,tilal6991/RxJava,zhongdj/RxJava,picnic106/RxJava,Shedings/RxJava,takecy/RxJava,sitexa/RxJava,Shedings/RxJava,KevinTCoughlin/RxJava,KevinTCoughlin/RxJava,androidyue/RxJava,stevegury/RxJava,jbripley/RxJava,wehjin/RxJava,YlJava110/RxJava,ChenWenHuan/RxJava,frodoking/RxJava,AttwellBrian/RxJava,sanxieryu/RxJava,klemzy/RxJava,cloudbearings/RxJava,aditya-chaturvedi/RxJava,AmberWhiteSky/RxJava,KevinTCoughlin/RxJava,ibaca/RxJava,runt18/RxJava,pitatensai/RxJava,simonbasle/RxJava,Eagles2F/RxJava,ypresto/RxJava,hzysoft/RxJava,ruhkopf/RxJava,ibaca/RxJava,Bobjoy/RxJava,wehjin/RxJava,Shedings/RxJava,java02014/RxJava,java02014/RxJava,kuanghao/RxJava,onepavel/RxJava,elijah513/RxJava,hzysoft/RxJava,tombujok/RxJava,dromato/RxJava,frodoking/RxJava,Turbo87/RxJava,hzysoft/RxJava,b-cuts/RxJava,ypresto/RxJava,zjrstar/RxJava,zsxwing/RxJava,ronenhamias/RxJava,forsail/RxJava,wlrhnh-David/RxJava,maugomez77/RxJava,akarnokd/RxJava,ReactiveX/RxJava,jacek-rzrz/RxJava,wrightm/RxJava,zhongdj/RxJava,randall-mo/RxJava,simonbasle/RxJava,srayhunter/RxJava,forsail/RxJava,southwolf/RxJava,duqiao/RxJava,AmberWhiteSky/RxJava,Ryan800/RxJava,tilal6991/RxJava,jbripley/RxJava,randall-mo/RxJava,ruhkopf/RxJava,gjesse/RxJava,ayushnvijay/RxJava,sitexa/RxJava,TracyLu/RxJava,reactivex/rxjava,tombujok/RxJava,YlJava110/RxJava,NiteshKant/RxJava,eduardotrandafilov/RxJava,sitexa/RxJava,ashwary/RxJava,nvoron23/RxJava,lncosie/RxJava,sunfei/RxJava,fjg1989/RxJava,nurkiewicz/RxJava,artem-zinnatullin/RxJava,lncosie/RxJava,runt18/RxJava,androidgilbert/RxJava,onepavel/RxJava,Siddartha07/RxJava,nkhuyu/RxJava,dromato/RxJava,tombujok/RxJava,davidmoten/RxJava,ashwary/RxJava,weikipeng/RxJava,zhongdj/RxJava,ppiech/RxJava,nkhuyu/RxJava,xfumihiro/RxJava,rabbitcount/RxJava,ayushnvijay/RxJava,androidgilbert/RxJava,suclike/RxJava,wehjin/RxJava,kuanghao/RxJava,Ribeiro/RxJava,wrightm/RxJava,pitatensai/RxJava,HuangWenhuan0/RxJava,zjrstar/RxJava,ronenhamias/RxJava,stevegury/RxJava,klemzy/RxJava,zsxwing/RxJava,onepavel/RxJava,pitatensai/RxJava,stevegury/RxJava,rabbitcount/RxJava,eduardotrandafilov/RxJava,jbripley/RxJava,sposam/RxJava,suclike/RxJava,Godchin1990/RxJava,shekarrex/RxJava,jacek-rzrz/RxJava,takecy/RxJava,shekarrex/RxJava,lijunhuayc/RxJava,cgpllx/RxJava,hyleung/RxJava,java02014/RxJava,maugomez77/RxJava,elijah513/RxJava,b-cuts/RxJava,reactivex/rxjava,davidmoten/RxJava,Eagles2F/RxJava,nkhuyu/RxJava,elijah513/RxJava,yuhuayi/RxJava,hyarlagadda/RxJava,fjg1989/RxJava,zjrstar/RxJava,devagul93/RxJava,Siddartha07/RxJava,ChenWenHuan/RxJava,YlJava110/RxJava,ibaca/RxJava,Eagles2F/RxJava,ruhkopf/RxJava,nurkiewicz/RxJava,hyarlagadda/RxJava,rabbitcount/RxJava,akarnokd/RxJava,A-w-K/RxJava,nvoron23/RxJava,AttwellBrian/RxJava,markrietveld/RxJava,fjg1989/RxJava,b-cuts/RxJava,TracyLu/RxJava,androidyue/RxJava,klemzy/RxJava,yuhuayi/RxJava,ppiech/RxJava,AmberWhiteSky/RxJava,Ribeiro/RxJava,aditya-chaturvedi/RxJava,runt18/RxJava,Bobjoy/RxJava,ppiech/RxJava,markrietveld/RxJava,duqiao/RxJava,zsxwing/RxJava,Turbo87/RxJava,sunfei/RxJava,TracyLu/RxJava,spoon-bot/RxJava,markrietveld/RxJava,marcogarcia23/RxJava,picnic106/RxJava,Bobjoy/RxJava,NiteshKant/RxJava,gjesse/RxJava,ashwary/RxJava,hyleung/RxJava,devagul93/RxJava,benjchristensen/RxJava,A-w-K/RxJava,xfumihiro/RxJava,frodoking/RxJava,vqvu/RxJava,xfumihiro/RxJava,simonbasle/RxJava,srayhunter/RxJava,marcogarcia23/RxJava,lncosie/RxJava,nvoron23/RxJava,southwolf/RxJava,sanxieryu/RxJava,kuanghao/RxJava,dromato/RxJava,ayushnvijay/RxJava,cgpllx/RxJava,cloudbearings/RxJava,androidyue/RxJava,takecy/RxJava
|
/**
* Copyright 2014 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 rx.internal.operators;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import org.junit.Test;
import org.mockito.*;
import rx.*;
import rx.Observable.OnSubscribe;
import rx.Observable;
import rx.Observer;
import rx.functions.*;
import rx.internal.util.RxRingBuffer;
import rx.observables.GroupedObservable;
import rx.observers.TestSubscriber;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
import rx.subscriptions.Subscriptions;
public class OperatorRetryTest {
@Test
public void iterativeBackoff() {
@SuppressWarnings("unchecked")
Observer<String> consumer = mock(Observer.class);
Observable<String> producer = Observable.create(new OnSubscribe<String>() {
private AtomicInteger count = new AtomicInteger(4);
long last = System.currentTimeMillis();
@Override
public void call(Subscriber<? super String> t1) {
System.out.println(count.get() + " @ " + String.valueOf(last - System.currentTimeMillis()));
last = System.currentTimeMillis();
if (count.getAndDecrement() == 0) {
t1.onNext("hello");
t1.onCompleted();
}
else
t1.onError(new RuntimeException());
}
});
TestSubscriber<String> ts = new TestSubscriber<String>(consumer);
producer.retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Throwable> attempts) {
// Worker w = Schedulers.computation().createWorker();
return attempts
.map(new Func1<Throwable, Tuple>() {
@Override
public Tuple call(Throwable n) {
return new Tuple(new Long(1), n);
}})
.scan(new Func2<Tuple, Tuple, Tuple>(){
@Override
public Tuple call(Tuple t, Tuple n) {
return new Tuple(t.count + n.count, n.n);
}})
.flatMap(new Func1<Tuple, Observable<Long>>() {
@Override
public Observable<Long> call(Tuple t) {
System.out.println("Retry # "+t.count);
return t.count > 20 ?
Observable.<Long>error(t.n) :
Observable.timer(t.count *1L, TimeUnit.MILLISECONDS);
}});
}
}).subscribe(ts);
ts.awaitTerminalEvent();
ts.assertNoErrors();
InOrder inOrder = inOrder(consumer);
inOrder.verify(consumer, never()).onError(any(Throwable.class));
inOrder.verify(consumer, times(1)).onNext("hello");
inOrder.verify(consumer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
public static class Tuple {
Long count;
Throwable n;
Tuple(Long c, Throwable n) {
count = c;
this.n = n;
}
}
@Test
public void testRetryIndefinitely() {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
int NUM_RETRIES = 20;
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_RETRIES));
origin.retry().unsafeSubscribe(new TestSubscriber<String>(observer));
InOrder inOrder = inOrder(observer);
// should show 3 attempts
inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime");
// should have no errors
inOrder.verify(observer, never()).onError(any(Throwable.class));
// should have a single success
inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testSchedulingNotificationHandler() {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
int NUM_RETRIES = 2;
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_RETRIES));
TestSubscriber<String> subscriber = new TestSubscriber<String>(observer);
origin.retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Throwable> t1) {
return t1.observeOn(Schedulers.computation()).map(new Func1<Throwable, Void>() {
@Override
public Void call(Throwable t1) {
return null;
}
}).startWith((Void) null);
}
}).subscribe(subscriber);
subscriber.awaitTerminalEvent();
InOrder inOrder = inOrder(observer);
// should show 3 attempts
inOrder.verify(observer, times(1 + NUM_RETRIES)).onNext("beginningEveryTime");
// should have no errors
inOrder.verify(observer, never()).onError(any(Throwable.class));
// should have a single success
inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testOnNextFromNotificationHandler() {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
int NUM_RETRIES = 2;
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_RETRIES));
origin.retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Throwable> t1) {
return t1.map(new Func1<Throwable, Void>() {
@Override
public Void call(Throwable t1) {
return null;
}
}).startWith((Void) null);
}
}).subscribe(observer);
InOrder inOrder = inOrder(observer);
// should show 3 attempts
inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime");
// should have no errors
inOrder.verify(observer, never()).onError(any(Throwable.class));
// should have a single success
inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testOnCompletedFromNotificationHandler() {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
Observable<String> origin = Observable.create(new FuncWithErrors(1));
TestSubscriber<String> subscriber = new TestSubscriber<String>(observer);
origin.retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Throwable> t1) {
return Observable.empty();
}
}).subscribe(subscriber);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, never()).onNext("beginningEveryTime");
inOrder.verify(observer, never()).onNext("onSuccessOnly");
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verify(observer, never()).onError(any(Exception.class));
inOrder.verifyNoMoreInteractions();
}
@Test
public void testOnErrorFromNotificationHandler() {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
Observable<String> origin = Observable.create(new FuncWithErrors(2));
origin.retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Throwable> t1) {
return Observable.error(new RuntimeException());
}
}).subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, never()).onNext("beginningEveryTime");
inOrder.verify(observer, never()).onNext("onSuccessOnly");
inOrder.verify(observer, never()).onCompleted();
inOrder.verify(observer, times(1)).onError(any(IllegalStateException.class));
inOrder.verifyNoMoreInteractions();
}
@Test
public void testSingleSubscriptionOnFirst() throws Exception {
final AtomicInteger inc = new AtomicInteger(0);
Observable.OnSubscribe<Integer> onSubscribe = new OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> subscriber) {
final int emit = inc.incrementAndGet();
subscriber.onNext(emit);
subscriber.onCompleted();
}
};
int first = Observable.create(onSubscribe)
.retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Throwable> attempt) {
return attempt.zipWith(Observable.just(1), new Func2<Throwable, Integer, Void>() {
@Override
public Void call(Throwable o, Integer integer) {
return null;
}
});
}
})
.toBlocking()
.first();
assertEquals("Observer did not receive the expected output", 1, first);
assertEquals("Subscribe was not called once", 1, inc.get());
}
@Test
public void testOriginFails() {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
Observable<String> origin = Observable.create(new FuncWithErrors(1));
origin.subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, times(1)).onNext("beginningEveryTime");
inOrder.verify(observer, times(1)).onError(any(RuntimeException.class));
inOrder.verify(observer, never()).onNext("onSuccessOnly");
inOrder.verify(observer, never()).onCompleted();
}
@Test
public void testRetryFail() {
int NUM_RETRIES = 1;
int NUM_FAILURES = 2;
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_FAILURES));
origin.retry(NUM_RETRIES).subscribe(observer);
InOrder inOrder = inOrder(observer);
// should show 2 attempts (first time fail, second time (1st retry) fail)
inOrder.verify(observer, times(1 + NUM_RETRIES)).onNext("beginningEveryTime");
// should only retry once, fail again and emit onError
inOrder.verify(observer, times(1)).onError(any(RuntimeException.class));
// no success
inOrder.verify(observer, never()).onNext("onSuccessOnly");
inOrder.verify(observer, never()).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testRetrySuccess() {
int NUM_FAILURES = 1;
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_FAILURES));
origin.retry(3).subscribe(observer);
InOrder inOrder = inOrder(observer);
// should show 3 attempts
inOrder.verify(observer, times(1 + NUM_FAILURES)).onNext("beginningEveryTime");
// should have no errors
inOrder.verify(observer, never()).onError(any(Throwable.class));
// should have a single success
inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testInfiniteRetry() {
int NUM_FAILURES = 20;
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_FAILURES));
origin.retry().subscribe(observer);
InOrder inOrder = inOrder(observer);
// should show 3 attempts
inOrder.verify(observer, times(1 + NUM_FAILURES)).onNext("beginningEveryTime");
// should have no errors
inOrder.verify(observer, never()).onError(any(Throwable.class));
// should have a single success
inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
/**
* Checks in a simple and synchronous way that retry resubscribes
* after error. This test fails against 0.16.1-0.17.4, hangs on 0.17.5 and
* passes in 0.17.6 thanks to fix for issue #1027.
*/
@SuppressWarnings("unchecked")
@Test
public void testRetrySubscribesAgainAfterError() {
// record emitted values with this action
Action1<Integer> record = mock(Action1.class);
InOrder inOrder = inOrder(record);
// always throw an exception with this action
Action1<Integer> throwException = mock(Action1.class);
doThrow(new RuntimeException()).when(throwException).call(Mockito.anyInt());
// create a retrying observable based on a PublishSubject
PublishSubject<Integer> subject = PublishSubject.create();
subject
// record item
.doOnNext(record)
// throw a RuntimeException
.doOnNext(throwException)
// retry on error
.retry()
// subscribe and ignore
.subscribe();
inOrder.verifyNoMoreInteractions();
subject.onNext(1);
inOrder.verify(record).call(1);
subject.onNext(2);
inOrder.verify(record).call(2);
subject.onNext(3);
inOrder.verify(record).call(3);
inOrder.verifyNoMoreInteractions();
}
public static class FuncWithErrors implements Observable.OnSubscribe<String> {
private final int numFailures;
private final AtomicInteger count = new AtomicInteger(0);
FuncWithErrors(int count) {
this.numFailures = count;
}
@Override
public void call(final Subscriber<? super String> o) {
o.setProducer(new Producer() {
final AtomicLong req = new AtomicLong();
@Override
public void request(long n) {
if (n == Long.MAX_VALUE) {
o.onNext("beginningEveryTime");
int i = count.getAndIncrement();
if (i < numFailures) {
o.onError(new RuntimeException("forced failure: " + (i + 1)));
} else {
o.onNext("onSuccessOnly");
o.onCompleted();
}
return;
}
if (n > 0 && req.getAndAdd(n) == 0) {
int i = count.getAndIncrement();
if (i < numFailures) {
o.onNext("beginningEveryTime");
o.onError(new RuntimeException("forced failure: " + (i + 1)));
} else {
do {
if (i == numFailures) {
o.onNext("beginningEveryTime");
} else
if (i > numFailures) {
o.onNext("onSuccessOnly");
o.onCompleted();
break;
}
i = count.getAndIncrement();
} while (req.decrementAndGet() > 0);
}
}
}
});
}
}
@Test
public void testUnsubscribeFromRetry() {
PublishSubject<Integer> subject = PublishSubject.create();
final AtomicInteger count = new AtomicInteger(0);
Subscription sub = subject.retry().subscribe(new Action1<Integer>() {
@Override
public void call(Integer n) {
count.incrementAndGet();
}
});
subject.onNext(1);
sub.unsubscribe();
subject.onNext(2);
assertEquals(1, count.get());
}
@Test
public void testRetryAllowsSubscriptionAfterAllSubscriptionsUnsubscribed() throws InterruptedException {
final AtomicInteger subsCount = new AtomicInteger(0);
OnSubscribe<String> onSubscribe = new OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> s) {
subsCount.incrementAndGet();
s.add(new Subscription() {
boolean unsubscribed = false;
@Override
public void unsubscribe() {
subsCount.decrementAndGet();
unsubscribed = true;
}
@Override
public boolean isUnsubscribed() {
return unsubscribed;
}
});
}
};
Observable<String> stream = Observable.create(onSubscribe);
Observable<String> streamWithRetry = stream.retry();
Subscription sub = streamWithRetry.subscribe();
assertEquals(1, subsCount.get());
sub.unsubscribe();
assertEquals(0, subsCount.get());
streamWithRetry.subscribe();
assertEquals(1, subsCount.get());
}
@Test
public void testSourceObservableCallsUnsubscribe() throws InterruptedException {
final AtomicInteger subsCount = new AtomicInteger(0);
final TestSubscriber<String> ts = new TestSubscriber<String>();
OnSubscribe<String> onSubscribe = new OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> s) {
// if isUnsubscribed is true that means we have a bug such as
// https://github.com/ReactiveX/RxJava/issues/1024
if (!s.isUnsubscribed()) {
subsCount.incrementAndGet();
s.onError(new RuntimeException("failed"));
// it unsubscribes the child directly
// this simulates various error/completion scenarios that could occur
// or just a source that proactively triggers cleanup
s.unsubscribe();
} else {
s.onError(new RuntimeException());
}
}
};
Observable.create(onSubscribe).retry(3).subscribe(ts);
assertEquals(4, subsCount.get()); // 1 + 3 retries
}
@Test
public void testSourceObservableRetry1() throws InterruptedException {
final AtomicInteger subsCount = new AtomicInteger(0);
final TestSubscriber<String> ts = new TestSubscriber<String>();
OnSubscribe<String> onSubscribe = new OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> s) {
subsCount.incrementAndGet();
s.onError(new RuntimeException("failed"));
}
};
Observable.create(onSubscribe).retry(1).subscribe(ts);
assertEquals(2, subsCount.get());
}
@Test
public void testSourceObservableRetry0() throws InterruptedException {
final AtomicInteger subsCount = new AtomicInteger(0);
final TestSubscriber<String> ts = new TestSubscriber<String>();
OnSubscribe<String> onSubscribe = new OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> s) {
subsCount.incrementAndGet();
s.onError(new RuntimeException("failed"));
}
};
Observable.create(onSubscribe).retry(0).subscribe(ts);
assertEquals(1, subsCount.get());
}
static final class SlowObservable implements Observable.OnSubscribe<Long> {
final AtomicInteger efforts = new AtomicInteger(0);
final AtomicInteger active = new AtomicInteger(0), maxActive = new AtomicInteger(0);
final AtomicInteger nextBeforeFailure;
private final int emitDelay;
public SlowObservable(int emitDelay, int countNext) {
this.emitDelay = emitDelay;
this.nextBeforeFailure = new AtomicInteger(countNext);
}
@Override
public void call(final Subscriber<? super Long> subscriber) {
final AtomicBoolean terminate = new AtomicBoolean(false);
efforts.getAndIncrement();
active.getAndIncrement();
maxActive.set(Math.max(active.get(), maxActive.get()));
final Thread thread = new Thread() {
@Override
public void run() {
long nr = 0;
try {
while (!terminate.get()) {
Thread.sleep(emitDelay);
if (nextBeforeFailure.getAndDecrement() > 0) {
subscriber.onNext(nr++);
} else {
subscriber.onError(new RuntimeException("expected-failed"));
}
}
} catch (InterruptedException t) {
}
}
};
thread.start();
subscriber.add(Subscriptions.create(new Action0() {
@Override
public void call() {
terminate.set(true);
active.decrementAndGet();
}
}));
}
}
/** Observer for listener on seperate thread */
static final class AsyncObserver<T> implements Observer<T> {
protected CountDownLatch latch = new CountDownLatch(1);
protected Observer<T> target;
/** Wrap existing Observer */
public AsyncObserver(Observer<T> target) {
this.target = target;
}
/** Wait */
public void await() {
try {
latch.await();
} catch (InterruptedException e) {
fail("Test interrupted");
}
}
// Observer implementation
@Override
public void onCompleted() {
target.onCompleted();
latch.countDown();
}
@Override
public void onError(Throwable t) {
target.onError(t);
latch.countDown();
}
@Override
public void onNext(T v) {
target.onNext(v);
}
}
@Test(timeout = 10000)
public void testUnsubscribeAfterError() {
@SuppressWarnings("unchecked")
Observer<Long> observer = mock(Observer.class);
// Observable that always fails after 100ms
SlowObservable so = new SlowObservable(100, 0);
Observable<Long> o = Observable.create(so).retry(5);
AsyncObserver<Long> async = new AsyncObserver<Long>(observer);
o.subscribe(async);
async.await();
InOrder inOrder = inOrder(observer);
// Should fail once
inOrder.verify(observer, times(1)).onError(any(Throwable.class));
inOrder.verify(observer, never()).onCompleted();
assertEquals("Start 6 threads, retry 5 then fail on 6", 6, so.efforts.get());
assertEquals("Only 1 active subscription", 1, so.maxActive.get());
}
@Test(timeout = 10000)
public void testTimeoutWithRetry() {
@SuppressWarnings("unchecked")
Observer<Long> observer = mock(Observer.class);
// Observable that sends every 100ms (timeout fails instead)
SlowObservable so = new SlowObservable(100, 10);
Observable<Long> o = Observable.create(so).timeout(80, TimeUnit.MILLISECONDS).retry(5);
AsyncObserver<Long> async = new AsyncObserver<Long>(observer);
o.subscribe(async);
async.await();
InOrder inOrder = inOrder(observer);
// Should fail once
inOrder.verify(observer, times(1)).onError(any(Throwable.class));
inOrder.verify(observer, never()).onCompleted();
assertEquals("Start 6 threads, retry 5 then fail on 6", 6, so.efforts.get());
}
@Test(timeout = 15000)
public void testRetryWithBackpressure() throws InterruptedException {
final int NUM_RETRIES = RxRingBuffer.SIZE * 2;
for (int i = 0; i < 400; i++) {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_RETRIES));
TestSubscriber<String> ts = new TestSubscriber<String>(observer);
origin.retry().observeOn(Schedulers.computation()).unsafeSubscribe(ts);
ts.awaitTerminalEvent(5, TimeUnit.SECONDS);
InOrder inOrder = inOrder(observer);
// should have no errors
verify(observer, never()).onError(any(Throwable.class));
// should show NUM_RETRIES attempts
inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime");
// should have a single success
inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
}
@Test(timeout = 15000)
public void testRetryWithBackpressureParallel() throws InterruptedException {
final int NUM_RETRIES = RxRingBuffer.SIZE * 2;
int ncpu = Runtime.getRuntime().availableProcessors();
ExecutorService exec = Executors.newFixedThreadPool(Math.max(ncpu / 2, 2));
final AtomicInteger timeouts = new AtomicInteger();
final Map<Integer, List<String>> data = new ConcurrentHashMap<Integer, List<String>>();
final Map<Integer, List<Throwable>> exceptions = new ConcurrentHashMap<Integer, List<Throwable>>();
final Map<Integer, Integer> completions = new ConcurrentHashMap<Integer, Integer>();
int m = 5000;
final CountDownLatch cdl = new CountDownLatch(m);
for (int i = 0; i < m; i++) {
final int j = i;
exec.execute(new Runnable() {
@Override
public void run() {
final AtomicInteger nexts = new AtomicInteger();
try {
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_RETRIES));
TestSubscriber<String> ts = new TestSubscriber<String>();
origin.retry()
.observeOn(Schedulers.computation()).unsafeSubscribe(ts);
ts.awaitTerminalEvent(2500, TimeUnit.MILLISECONDS);
if (ts.getOnCompletedEvents().size() != 1) {
completions.put(j, ts.getOnCompletedEvents().size());
}
if (ts.getOnErrorEvents().size() != 0) {
exceptions.put(j, ts.getOnErrorEvents());
}
if (ts.getOnNextEvents().size() != NUM_RETRIES + 2) {
data.put(j, ts.getOnNextEvents());
}
} catch (Throwable t) {
timeouts.incrementAndGet();
System.out.println(j + " | " + cdl.getCount() + " !!! " + nexts.get());
}
cdl.countDown();
}
});
}
exec.shutdown();
cdl.await();
assertEquals(0, timeouts.get());
if (data.size() > 0) {
System.out.println(allSequenceFrequency(data));
}
if (exceptions.size() > 0) {
System.out.println(exceptions);
}
if (completions.size() > 0) {
System.out.println(completions);
}
if (data.size() > 0) {
fail("Data content mismatch: " + allSequenceFrequency(data));
}
if (exceptions.size() > 0) {
fail("Exceptions received: " + exceptions);
}
if (completions.size() > 0) {
fail("Multiple completions received: " + completions);
}
}
static <T> StringBuilder allSequenceFrequency(Map<Integer, List<T>> its) {
StringBuilder b = new StringBuilder();
for (Map.Entry<Integer, List<T>> e : its.entrySet()) {
if (b.length() > 0) {
b.append(", ");
}
b.append(e.getKey()).append("={");
b.append(sequenceFrequency(e.getValue()));
b.append("}");
}
return b;
}
static <T> StringBuilder sequenceFrequency(Iterable<T> it) {
StringBuilder sb = new StringBuilder();
Object prev = null;
int cnt = 0;
for (Object curr : it) {
if (sb.length() > 0) {
if (!curr.equals(prev)) {
if (cnt > 1) {
sb.append(" x ").append(cnt);
cnt = 1;
}
sb.append(", ");
sb.append(curr);
} else {
cnt++;
}
} else {
sb.append(curr);
cnt++;
}
prev = curr;
}
return sb;
}
@Test(timeout = 3000)
public void testIssue1900() throws InterruptedException {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
final int NUM_MSG = 1034;
final AtomicInteger count = new AtomicInteger();
Observable<String> origin = Observable.range(0, NUM_MSG)
.map(new Func1<Integer, String>() {
@Override
public String call(Integer t1) {
return "msg: " + count.incrementAndGet();
}
});
origin.retry()
.groupBy(new Func1<String, String>() {
@Override
public String call(String t1) {
return t1;
}
})
.flatMap(new Func1<GroupedObservable<String,String>, Observable<String>>() {
@Override
public Observable<String> call(GroupedObservable<String, String> t1) {
return t1.take(1);
}
})
.unsafeSubscribe(new TestSubscriber<String>(observer));
InOrder inOrder = inOrder(observer);
// should show 3 attempts
inOrder.verify(observer, times(NUM_MSG)).onNext(any(java.lang.String.class));
// // should have no errors
inOrder.verify(observer, never()).onError(any(Throwable.class));
// should have a single success
//inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test(timeout = 3000)
public void testIssue1900SourceNotSupportingBackpressure() {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
final int NUM_MSG = 1034;
final AtomicInteger count = new AtomicInteger();
Observable<String> origin = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> o) {
for(int i=0; i<NUM_MSG; i++) {
o.onNext("msg:" + count.incrementAndGet());
}
o.onCompleted();
}
});
origin.retry()
.groupBy(new Func1<String, String>() {
@Override
public String call(String t1) {
return t1;
}
})
.flatMap(new Func1<GroupedObservable<String,String>, Observable<String>>() {
@Override
public Observable<String> call(GroupedObservable<String, String> t1) {
return t1.take(1);
}
})
.unsafeSubscribe(new TestSubscriber<String>(observer));
InOrder inOrder = inOrder(observer);
// should show 3 attempts
inOrder.verify(observer, times(NUM_MSG)).onNext(any(java.lang.String.class));
// // should have no errors
inOrder.verify(observer, never()).onError(any(Throwable.class));
// should have a single success
//inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
}
|
src/test/java/rx/internal/operators/OperatorRetryTest.java
|
/**
* Copyright 2014 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 rx.internal.operators;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import org.junit.Test;
import org.mockito.*;
import rx.*;
import rx.Observable.OnSubscribe;
import rx.Observable;
import rx.Observer;
import rx.functions.*;
import rx.internal.util.RxRingBuffer;
import rx.observables.GroupedObservable;
import rx.observers.TestSubscriber;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
import rx.subscriptions.Subscriptions;
public class OperatorRetryTest {
@Test
public void iterativeBackoff() {
@SuppressWarnings("unchecked")
Observer<String> consumer = mock(Observer.class);
Observable<String> producer = Observable.create(new OnSubscribe<String>() {
private AtomicInteger count = new AtomicInteger(4);
long last = System.currentTimeMillis();
@Override
public void call(Subscriber<? super String> t1) {
System.out.println(count.get() + " @ " + String.valueOf(last - System.currentTimeMillis()));
last = System.currentTimeMillis();
if (count.getAndDecrement() == 0) {
t1.onNext("hello");
t1.onCompleted();
}
else
t1.onError(new RuntimeException());
}
});
TestSubscriber<String> ts = new TestSubscriber<String>(consumer);
producer.retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Throwable> attempts) {
// Worker w = Schedulers.computation().createWorker();
return attempts
.map(new Func1<Throwable, Tuple>() {
@Override
public Tuple call(Throwable n) {
return new Tuple(new Long(1), n);
}})
.scan(new Func2<Tuple, Tuple, Tuple>(){
@Override
public Tuple call(Tuple t, Tuple n) {
return new Tuple(t.count + n.count, n.n);
}})
.flatMap(new Func1<Tuple, Observable<Long>>() {
@Override
public Observable<Long> call(Tuple t) {
System.out.println("Retry # "+t.count);
return t.count > 20 ?
Observable.<Long>error(t.n) :
Observable.timer(t.count *1L, TimeUnit.MILLISECONDS);
}});
}
}).subscribe(ts);
ts.awaitTerminalEvent();
ts.assertNoErrors();
InOrder inOrder = inOrder(consumer);
inOrder.verify(consumer, never()).onError(any(Throwable.class));
inOrder.verify(consumer, times(1)).onNext("hello");
inOrder.verify(consumer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
public static class Tuple {
Long count;
Throwable n;
Tuple(Long c, Throwable n) {
count = c;
this.n = n;
}
}
@Test
public void testRetryIndefinitely() {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
int NUM_RETRIES = 20;
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_RETRIES));
origin.retry().unsafeSubscribe(new TestSubscriber<String>(observer));
InOrder inOrder = inOrder(observer);
// should show 3 attempts
inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime");
// should have no errors
inOrder.verify(observer, never()).onError(any(Throwable.class));
// should have a single success
inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testSchedulingNotificationHandler() {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
int NUM_RETRIES = 2;
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_RETRIES));
TestSubscriber<String> subscriber = new TestSubscriber<String>(observer);
origin.retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Throwable> t1) {
return t1.observeOn(Schedulers.computation()).map(new Func1<Throwable, Void>() {
@Override
public Void call(Throwable t1) {
return null;
}
}).startWith((Void) null);
}
}).subscribe(subscriber);
subscriber.awaitTerminalEvent();
InOrder inOrder = inOrder(observer);
// should show 3 attempts
inOrder.verify(observer, times(1 + NUM_RETRIES)).onNext("beginningEveryTime");
// should have no errors
inOrder.verify(observer, never()).onError(any(Throwable.class));
// should have a single success
inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testOnNextFromNotificationHandler() {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
int NUM_RETRIES = 2;
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_RETRIES));
origin.retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Throwable> t1) {
return t1.map(new Func1<Throwable, Void>() {
@Override
public Void call(Throwable t1) {
return null;
}
}).startWith((Void) null);
}
}).subscribe(observer);
InOrder inOrder = inOrder(observer);
// should show 3 attempts
inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime");
// should have no errors
inOrder.verify(observer, never()).onError(any(Throwable.class));
// should have a single success
inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testOnCompletedFromNotificationHandler() {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
Observable<String> origin = Observable.create(new FuncWithErrors(1));
TestSubscriber<String> subscriber = new TestSubscriber<String>(observer);
origin.retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Throwable> t1) {
return Observable.empty();
}
}).subscribe(subscriber);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, never()).onNext("beginningEveryTime");
inOrder.verify(observer, never()).onNext("onSuccessOnly");
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verify(observer, never()).onError(any(Exception.class));
inOrder.verifyNoMoreInteractions();
}
@Test
public void testOnErrorFromNotificationHandler() {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
Observable<String> origin = Observable.create(new FuncWithErrors(2));
origin.retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Throwable> t1) {
return Observable.error(new RuntimeException());
}
}).subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, never()).onNext("beginningEveryTime");
inOrder.verify(observer, never()).onNext("onSuccessOnly");
inOrder.verify(observer, never()).onCompleted();
inOrder.verify(observer, times(1)).onError(any(IllegalStateException.class));
inOrder.verifyNoMoreInteractions();
}
@Test
public void testSingleSubscriptionOnFirst() throws Exception {
final AtomicInteger inc = new AtomicInteger(0);
Observable.OnSubscribe<Integer> onSubscribe = new OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> subscriber) {
final int emit = inc.incrementAndGet();
subscriber.onNext(emit);
subscriber.onCompleted();
}
};
int first = Observable.create(onSubscribe)
.retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Throwable> attempt) {
return attempt.zipWith(Observable.just(1), new Func2<Throwable, Integer, Void>() {
@Override
public Void call(Throwable o, Integer integer) {
return null;
}
});
}
})
.toBlocking()
.first();
assertEquals("Observer did not receive the expected output", 1, first);
assertEquals("Subscribe was not called once", 1, inc.get());
}
@Test
public void testOriginFails() {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
Observable<String> origin = Observable.create(new FuncWithErrors(1));
origin.subscribe(observer);
InOrder inOrder = inOrder(observer);
inOrder.verify(observer, times(1)).onNext("beginningEveryTime");
inOrder.verify(observer, times(1)).onError(any(RuntimeException.class));
inOrder.verify(observer, never()).onNext("onSuccessOnly");
inOrder.verify(observer, never()).onCompleted();
}
@Test
public void testRetryFail() {
int NUM_RETRIES = 1;
int NUM_FAILURES = 2;
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_FAILURES));
origin.retry(NUM_RETRIES).subscribe(observer);
InOrder inOrder = inOrder(observer);
// should show 2 attempts (first time fail, second time (1st retry) fail)
inOrder.verify(observer, times(1 + NUM_RETRIES)).onNext("beginningEveryTime");
// should only retry once, fail again and emit onError
inOrder.verify(observer, times(1)).onError(any(RuntimeException.class));
// no success
inOrder.verify(observer, never()).onNext("onSuccessOnly");
inOrder.verify(observer, never()).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testRetrySuccess() {
int NUM_FAILURES = 1;
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_FAILURES));
origin.retry(3).subscribe(observer);
InOrder inOrder = inOrder(observer);
// should show 3 attempts
inOrder.verify(observer, times(1 + NUM_FAILURES)).onNext("beginningEveryTime");
// should have no errors
inOrder.verify(observer, never()).onError(any(Throwable.class));
// should have a single success
inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testInfiniteRetry() {
int NUM_FAILURES = 20;
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_FAILURES));
origin.retry().subscribe(observer);
InOrder inOrder = inOrder(observer);
// should show 3 attempts
inOrder.verify(observer, times(1 + NUM_FAILURES)).onNext("beginningEveryTime");
// should have no errors
inOrder.verify(observer, never()).onError(any(Throwable.class));
// should have a single success
inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
/**
* Checks in a simple and synchronous way that retry resubscribes
* after error. This test fails against 0.16.1-0.17.4, hangs on 0.17.5 and
* passes in 0.17.6 thanks to fix for issue #1027.
*/
@SuppressWarnings("unchecked")
@Test
public void testRetrySubscribesAgainAfterError() {
// record emitted values with this action
Action1<Integer> record = mock(Action1.class);
InOrder inOrder = inOrder(record);
// always throw an exception with this action
Action1<Integer> throwException = mock(Action1.class);
doThrow(new RuntimeException()).when(throwException).call(Mockito.anyInt());
// create a retrying observable based on a PublishSubject
PublishSubject<Integer> subject = PublishSubject.create();
subject
// record item
.doOnNext(record)
// throw a RuntimeException
.doOnNext(throwException)
// retry on error
.retry()
// subscribe and ignore
.subscribe();
inOrder.verifyNoMoreInteractions();
subject.onNext(1);
inOrder.verify(record).call(1);
subject.onNext(2);
inOrder.verify(record).call(2);
subject.onNext(3);
inOrder.verify(record).call(3);
inOrder.verifyNoMoreInteractions();
}
public static class FuncWithErrors implements Observable.OnSubscribe<String> {
private final int numFailures;
private final AtomicInteger count = new AtomicInteger(0);
FuncWithErrors(int count) {
this.numFailures = count;
}
@Override
public void call(final Subscriber<? super String> o) {
o.setProducer(new Producer() {
final AtomicLong req = new AtomicLong();
@Override
public void request(long n) {
if (n == Long.MAX_VALUE) {
o.onNext("beginningEveryTime");
if (count.getAndIncrement() < numFailures) {
o.onError(new RuntimeException("forced failure: " + count.get()));
} else {
o.onNext("onSuccessOnly");
o.onCompleted();
}
return;
}
if (n > 0 && req.getAndAdd(n) == 0) {
int i = count.getAndIncrement();
if (i < numFailures) {
o.onNext("beginningEveryTime");
o.onError(new RuntimeException("forced failure: " + count.get()));
req.decrementAndGet();
} else {
do {
if (i == numFailures) {
o.onNext("beginningEveryTime");
} else
if (i > numFailures) {
o.onNext("onSuccessOnly");
o.onCompleted();
break;
}
i = count.getAndIncrement();
} while (req.decrementAndGet() > 0);
}
}
}
});
}
}
@Test
public void testUnsubscribeFromRetry() {
PublishSubject<Integer> subject = PublishSubject.create();
final AtomicInteger count = new AtomicInteger(0);
Subscription sub = subject.retry().subscribe(new Action1<Integer>() {
@Override
public void call(Integer n) {
count.incrementAndGet();
}
});
subject.onNext(1);
sub.unsubscribe();
subject.onNext(2);
assertEquals(1, count.get());
}
@Test
public void testRetryAllowsSubscriptionAfterAllSubscriptionsUnsubscribed() throws InterruptedException {
final AtomicInteger subsCount = new AtomicInteger(0);
OnSubscribe<String> onSubscribe = new OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> s) {
subsCount.incrementAndGet();
s.add(new Subscription() {
boolean unsubscribed = false;
@Override
public void unsubscribe() {
subsCount.decrementAndGet();
unsubscribed = true;
}
@Override
public boolean isUnsubscribed() {
return unsubscribed;
}
});
}
};
Observable<String> stream = Observable.create(onSubscribe);
Observable<String> streamWithRetry = stream.retry();
Subscription sub = streamWithRetry.subscribe();
assertEquals(1, subsCount.get());
sub.unsubscribe();
assertEquals(0, subsCount.get());
streamWithRetry.subscribe();
assertEquals(1, subsCount.get());
}
@Test
public void testSourceObservableCallsUnsubscribe() throws InterruptedException {
final AtomicInteger subsCount = new AtomicInteger(0);
final TestSubscriber<String> ts = new TestSubscriber<String>();
OnSubscribe<String> onSubscribe = new OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> s) {
// if isUnsubscribed is true that means we have a bug such as
// https://github.com/ReactiveX/RxJava/issues/1024
if (!s.isUnsubscribed()) {
subsCount.incrementAndGet();
s.onError(new RuntimeException("failed"));
// it unsubscribes the child directly
// this simulates various error/completion scenarios that could occur
// or just a source that proactively triggers cleanup
s.unsubscribe();
} else {
s.onError(new RuntimeException());
}
}
};
Observable.create(onSubscribe).retry(3).subscribe(ts);
assertEquals(4, subsCount.get()); // 1 + 3 retries
}
@Test
public void testSourceObservableRetry1() throws InterruptedException {
final AtomicInteger subsCount = new AtomicInteger(0);
final TestSubscriber<String> ts = new TestSubscriber<String>();
OnSubscribe<String> onSubscribe = new OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> s) {
subsCount.incrementAndGet();
s.onError(new RuntimeException("failed"));
}
};
Observable.create(onSubscribe).retry(1).subscribe(ts);
assertEquals(2, subsCount.get());
}
@Test
public void testSourceObservableRetry0() throws InterruptedException {
final AtomicInteger subsCount = new AtomicInteger(0);
final TestSubscriber<String> ts = new TestSubscriber<String>();
OnSubscribe<String> onSubscribe = new OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> s) {
subsCount.incrementAndGet();
s.onError(new RuntimeException("failed"));
}
};
Observable.create(onSubscribe).retry(0).subscribe(ts);
assertEquals(1, subsCount.get());
}
static final class SlowObservable implements Observable.OnSubscribe<Long> {
final AtomicInteger efforts = new AtomicInteger(0);
final AtomicInteger active = new AtomicInteger(0), maxActive = new AtomicInteger(0);
final AtomicInteger nextBeforeFailure;
private final int emitDelay;
public SlowObservable(int emitDelay, int countNext) {
this.emitDelay = emitDelay;
this.nextBeforeFailure = new AtomicInteger(countNext);
}
@Override
public void call(final Subscriber<? super Long> subscriber) {
final AtomicBoolean terminate = new AtomicBoolean(false);
efforts.getAndIncrement();
active.getAndIncrement();
maxActive.set(Math.max(active.get(), maxActive.get()));
final Thread thread = new Thread() {
@Override
public void run() {
long nr = 0;
try {
while (!terminate.get()) {
Thread.sleep(emitDelay);
if (nextBeforeFailure.getAndDecrement() > 0) {
subscriber.onNext(nr++);
} else {
subscriber.onError(new RuntimeException("expected-failed"));
}
}
} catch (InterruptedException t) {
}
}
};
thread.start();
subscriber.add(Subscriptions.create(new Action0() {
@Override
public void call() {
terminate.set(true);
active.decrementAndGet();
}
}));
}
}
/** Observer for listener on seperate thread */
static final class AsyncObserver<T> implements Observer<T> {
protected CountDownLatch latch = new CountDownLatch(1);
protected Observer<T> target;
/** Wrap existing Observer */
public AsyncObserver(Observer<T> target) {
this.target = target;
}
/** Wait */
public void await() {
try {
latch.await();
} catch (InterruptedException e) {
fail("Test interrupted");
}
}
// Observer implementation
@Override
public void onCompleted() {
target.onCompleted();
latch.countDown();
}
@Override
public void onError(Throwable t) {
target.onError(t);
latch.countDown();
}
@Override
public void onNext(T v) {
target.onNext(v);
}
}
@Test(timeout = 10000)
public void testUnsubscribeAfterError() {
@SuppressWarnings("unchecked")
Observer<Long> observer = mock(Observer.class);
// Observable that always fails after 100ms
SlowObservable so = new SlowObservable(100, 0);
Observable<Long> o = Observable.create(so).retry(5);
AsyncObserver<Long> async = new AsyncObserver<Long>(observer);
o.subscribe(async);
async.await();
InOrder inOrder = inOrder(observer);
// Should fail once
inOrder.verify(observer, times(1)).onError(any(Throwable.class));
inOrder.verify(observer, never()).onCompleted();
assertEquals("Start 6 threads, retry 5 then fail on 6", 6, so.efforts.get());
assertEquals("Only 1 active subscription", 1, so.maxActive.get());
}
@Test(timeout = 10000)
public void testTimeoutWithRetry() {
@SuppressWarnings("unchecked")
Observer<Long> observer = mock(Observer.class);
// Observable that sends every 100ms (timeout fails instead)
SlowObservable so = new SlowObservable(100, 10);
Observable<Long> o = Observable.create(so).timeout(80, TimeUnit.MILLISECONDS).retry(5);
AsyncObserver<Long> async = new AsyncObserver<Long>(observer);
o.subscribe(async);
async.await();
InOrder inOrder = inOrder(observer);
// Should fail once
inOrder.verify(observer, times(1)).onError(any(Throwable.class));
inOrder.verify(observer, never()).onCompleted();
assertEquals("Start 6 threads, retry 5 then fail on 6", 6, so.efforts.get());
}
@Test(timeout = 15000)
public void testRetryWithBackpressure() throws InterruptedException {
final int NUM_RETRIES = RxRingBuffer.SIZE * 2;
for (int i = 0; i < 400; i++) {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_RETRIES));
TestSubscriber<String> ts = new TestSubscriber<String>(observer);
origin.retry().observeOn(Schedulers.computation()).unsafeSubscribe(ts);
ts.awaitTerminalEvent(5, TimeUnit.SECONDS);
InOrder inOrder = inOrder(observer);
// should have no errors
verify(observer, never()).onError(any(Throwable.class));
// should show NUM_RETRIES attempts
inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime");
// should have a single success
inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
}
@Test(timeout = 15000)
public void testRetryWithBackpressureParallel() throws InterruptedException {
final int NUM_RETRIES = RxRingBuffer.SIZE * 2;
int ncpu = Runtime.getRuntime().availableProcessors();
ExecutorService exec = Executors.newFixedThreadPool(Math.max(ncpu / 2, 1));
final AtomicInteger timeouts = new AtomicInteger();
final Map<Integer, List<String>> data = new ConcurrentHashMap<Integer, List<String>>();
final Map<Integer, List<Throwable>> exceptions = new ConcurrentHashMap<Integer, List<Throwable>>();
final Map<Integer, Integer> completions = new ConcurrentHashMap<Integer, Integer>();
int m = 2000;
final CountDownLatch cdl = new CountDownLatch(m);
for (int i = 0; i < m; i++) {
final int j = i;
exec.execute(new Runnable() {
@Override
public void run() {
final AtomicInteger nexts = new AtomicInteger();
try {
Observable<String> origin = Observable.create(new FuncWithErrors(NUM_RETRIES));
TestSubscriber<String> ts = new TestSubscriber<String>();
origin.retry().observeOn(Schedulers.computation()).unsafeSubscribe(ts);
ts.awaitTerminalEvent(2, TimeUnit.SECONDS);
if (ts.getOnNextEvents().size() != NUM_RETRIES + 2) {
data.put(j, ts.getOnNextEvents());
}
if (ts.getOnErrorEvents().size() != 0) {
exceptions.put(j, ts.getOnErrorEvents());
}
if (ts.getOnCompletedEvents().size() != 1) {
completions.put(j, ts.getOnCompletedEvents().size());
}
} catch (Throwable t) {
timeouts.incrementAndGet();
System.out.println(j + " | " + cdl.getCount() + " !!! " + nexts.get());
}
cdl.countDown();
}
});
}
exec.shutdown();
cdl.await();
assertEquals(0, timeouts.get());
if (data.size() > 0) {
fail("Data content mismatch: " + data);
}
if (exceptions.size() > 0) {
fail("Exceptions received: " + exceptions);
}
if (completions.size() > 0) {
fail("Multiple completions received: " + completions);
}
}
@Test(timeout = 3000)
public void testIssue1900() throws InterruptedException {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
final int NUM_MSG = 1034;
final AtomicInteger count = new AtomicInteger();
Observable<String> origin = Observable.range(0, NUM_MSG)
.map(new Func1<Integer, String>() {
@Override
public String call(Integer t1) {
return "msg: " + count.incrementAndGet();
}
});
origin.retry()
.groupBy(new Func1<String, String>() {
@Override
public String call(String t1) {
return t1;
}
})
.flatMap(new Func1<GroupedObservable<String,String>, Observable<String>>() {
@Override
public Observable<String> call(GroupedObservable<String, String> t1) {
return t1.take(1);
}
})
.unsafeSubscribe(new TestSubscriber<String>(observer));
InOrder inOrder = inOrder(observer);
// should show 3 attempts
inOrder.verify(observer, times(NUM_MSG)).onNext(any(java.lang.String.class));
// // should have no errors
inOrder.verify(observer, never()).onError(any(Throwable.class));
// should have a single success
//inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
@Test(timeout = 3000)
public void testIssue1900SourceNotSupportingBackpressure() {
@SuppressWarnings("unchecked")
Observer<String> observer = mock(Observer.class);
final int NUM_MSG = 1034;
final AtomicInteger count = new AtomicInteger();
Observable<String> origin = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> o) {
for(int i=0; i<NUM_MSG; i++) {
o.onNext("msg:" + count.incrementAndGet());
}
o.onCompleted();
}
});
origin.retry()
.groupBy(new Func1<String, String>() {
@Override
public String call(String t1) {
return t1;
}
})
.flatMap(new Func1<GroupedObservable<String,String>, Observable<String>>() {
@Override
public Observable<String> call(GroupedObservable<String, String> t1) {
return t1.take(1);
}
})
.unsafeSubscribe(new TestSubscriber<String>(observer));
InOrder inOrder = inOrder(observer);
// should show 3 attempts
inOrder.verify(observer, times(NUM_MSG)).onNext(any(java.lang.String.class));
// // should have no errors
inOrder.verify(observer, never()).onError(any(Throwable.class));
// should have a single success
//inOrder.verify(observer, times(1)).onNext("onSuccessOnly");
// should have a single successful onCompleted
inOrder.verify(observer, times(1)).onCompleted();
inOrder.verifyNoMoreInteractions();
}
}
|
Fixed reentrancy issue with the error producer.
|
src/test/java/rx/internal/operators/OperatorRetryTest.java
|
Fixed reentrancy issue with the error producer.
|
<ide><path>rc/test/java/rx/internal/operators/OperatorRetryTest.java
<ide> public void request(long n) {
<ide> if (n == Long.MAX_VALUE) {
<ide> o.onNext("beginningEveryTime");
<del> if (count.getAndIncrement() < numFailures) {
<del> o.onError(new RuntimeException("forced failure: " + count.get()));
<add> int i = count.getAndIncrement();
<add> if (i < numFailures) {
<add> o.onError(new RuntimeException("forced failure: " + (i + 1)));
<ide> } else {
<ide> o.onNext("onSuccessOnly");
<ide> o.onCompleted();
<ide> int i = count.getAndIncrement();
<ide> if (i < numFailures) {
<ide> o.onNext("beginningEveryTime");
<del> o.onError(new RuntimeException("forced failure: " + count.get()));
<del> req.decrementAndGet();
<add> o.onError(new RuntimeException("forced failure: " + (i + 1)));
<ide> } else {
<ide> do {
<ide> if (i == numFailures) {
<ide> inOrder.verifyNoMoreInteractions();
<ide> }
<ide> }
<add>
<ide> @Test(timeout = 15000)
<ide> public void testRetryWithBackpressureParallel() throws InterruptedException {
<ide> final int NUM_RETRIES = RxRingBuffer.SIZE * 2;
<ide> int ncpu = Runtime.getRuntime().availableProcessors();
<del> ExecutorService exec = Executors.newFixedThreadPool(Math.max(ncpu / 2, 1));
<add> ExecutorService exec = Executors.newFixedThreadPool(Math.max(ncpu / 2, 2));
<ide> final AtomicInteger timeouts = new AtomicInteger();
<ide> final Map<Integer, List<String>> data = new ConcurrentHashMap<Integer, List<String>>();
<ide> final Map<Integer, List<Throwable>> exceptions = new ConcurrentHashMap<Integer, List<Throwable>>();
<ide> final Map<Integer, Integer> completions = new ConcurrentHashMap<Integer, Integer>();
<ide>
<del> int m = 2000;
<add> int m = 5000;
<ide> final CountDownLatch cdl = new CountDownLatch(m);
<ide> for (int i = 0; i < m; i++) {
<ide> final int j = i;
<ide> try {
<ide> Observable<String> origin = Observable.create(new FuncWithErrors(NUM_RETRIES));
<ide> TestSubscriber<String> ts = new TestSubscriber<String>();
<del> origin.retry().observeOn(Schedulers.computation()).unsafeSubscribe(ts);
<del> ts.awaitTerminalEvent(2, TimeUnit.SECONDS);
<del> if (ts.getOnNextEvents().size() != NUM_RETRIES + 2) {
<del> data.put(j, ts.getOnNextEvents());
<add> origin.retry()
<add> .observeOn(Schedulers.computation()).unsafeSubscribe(ts);
<add> ts.awaitTerminalEvent(2500, TimeUnit.MILLISECONDS);
<add> if (ts.getOnCompletedEvents().size() != 1) {
<add> completions.put(j, ts.getOnCompletedEvents().size());
<ide> }
<ide> if (ts.getOnErrorEvents().size() != 0) {
<ide> exceptions.put(j, ts.getOnErrorEvents());
<ide> }
<del> if (ts.getOnCompletedEvents().size() != 1) {
<del> completions.put(j, ts.getOnCompletedEvents().size());
<add> if (ts.getOnNextEvents().size() != NUM_RETRIES + 2) {
<add> data.put(j, ts.getOnNextEvents());
<ide> }
<ide> } catch (Throwable t) {
<ide> timeouts.incrementAndGet();
<ide> cdl.await();
<ide> assertEquals(0, timeouts.get());
<ide> if (data.size() > 0) {
<del> fail("Data content mismatch: " + data);
<add> System.out.println(allSequenceFrequency(data));
<add> }
<add> if (exceptions.size() > 0) {
<add> System.out.println(exceptions);
<add> }
<add> if (completions.size() > 0) {
<add> System.out.println(completions);
<add> }
<add> if (data.size() > 0) {
<add> fail("Data content mismatch: " + allSequenceFrequency(data));
<ide> }
<ide> if (exceptions.size() > 0) {
<ide> fail("Exceptions received: " + exceptions);
<ide> if (completions.size() > 0) {
<ide> fail("Multiple completions received: " + completions);
<ide> }
<add> }
<add> static <T> StringBuilder allSequenceFrequency(Map<Integer, List<T>> its) {
<add> StringBuilder b = new StringBuilder();
<add> for (Map.Entry<Integer, List<T>> e : its.entrySet()) {
<add> if (b.length() > 0) {
<add> b.append(", ");
<add> }
<add> b.append(e.getKey()).append("={");
<add> b.append(sequenceFrequency(e.getValue()));
<add> b.append("}");
<add> }
<add> return b;
<add> }
<add> static <T> StringBuilder sequenceFrequency(Iterable<T> it) {
<add> StringBuilder sb = new StringBuilder();
<add>
<add> Object prev = null;
<add> int cnt = 0;
<add>
<add> for (Object curr : it) {
<add> if (sb.length() > 0) {
<add> if (!curr.equals(prev)) {
<add> if (cnt > 1) {
<add> sb.append(" x ").append(cnt);
<add> cnt = 1;
<add> }
<add> sb.append(", ");
<add> sb.append(curr);
<add> } else {
<add> cnt++;
<add> }
<add> } else {
<add> sb.append(curr);
<add> cnt++;
<add> }
<add> prev = curr;
<add> }
<add>
<add> return sb;
<ide> }
<ide> @Test(timeout = 3000)
<ide> public void testIssue1900() throws InterruptedException {
|
|
Java
|
mit
|
error: pathspec 'src/main/java/com/blamejared/compat/thaumcraft/handlers/handlers/DustTrigger.java' did not match any file(s) known to git
|
9c1f76c0e5d8bf92d3529e6724180fb03b06cabc
| 1 |
jaredlll08/ModTweaker
|
package com.blamejared.compat.thaumcraft.handlers.handlers;
import com.blamejared.ModTweaker;
import crafttweaker.CraftTweakerAPI;
import crafttweaker.IAction;
import crafttweaker.annotations.ModOnly;
import crafttweaker.annotations.ZenRegister;
import crafttweaker.api.block.IBlock;
import crafttweaker.api.item.IIngredient;
import crafttweaker.api.item.IItemStack;
import crafttweaker.api.minecraft.CraftTweakerMC;
import crafttweaker.api.oredict.IOreDictEntry;
import net.minecraft.item.ItemStack;
import stanhebben.zenscript.annotations.Optional;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import thaumcraft.api.crafting.IDustTrigger;
import thaumcraft.common.lib.crafting.DustTriggerOre;
import thaumcraft.common.lib.crafting.DustTriggerSimple;
import java.lang.reflect.Field;
import java.util.Iterator;
@ZenClass("mods.thaumcraft.SalisMundus")
@ZenRegister
@ModOnly("thaumcraft")
public class DustTrigger {
private static final Field simpleTriggerResult;
private static final Field oredictTriggerResult;
static {
Field A = null;
Field B = null;
try {
A = DustTriggerSimple.class.getDeclaredField("result");
A.setAccessible(true);
B = DustTriggerOre.class.getDeclaredField("result");
B.setAccessible(true);
} catch(NoSuchFieldException e) {
e.printStackTrace();
}
simpleTriggerResult = A;
oredictTriggerResult = B;
}
private DustTrigger() {
}
@ZenMethod
public static void addSingleConversion(IBlock in, IItemStack out, @Optional String research) {
ModTweaker.LATE_ADDITIONS.add(new ActionAddTrigger(in, out, research));
}
@ZenMethod
public static void addSingleConversion(IOreDictEntry in, IItemStack out, @Optional String research) {
ModTweaker.LATE_ADDITIONS.add(new ActionAddTrigger(in, out, research));
}
@ZenMethod
public static void removeSingleConversion(IIngredient output) {
ModTweaker.LATE_REMOVALS.add(new ActionRemoveTrigger(output));
}
static final class ActionAddTrigger implements IAction {
private final IItemStack output;
private final IDustTrigger trigger;
ActionAddTrigger(IBlock in, IItemStack output, String research) {
this.output = output;
this.trigger = new DustTriggerSimple(research, CraftTweakerMC.getBlock(in), CraftTweakerMC.getItemStack(output));
}
ActionAddTrigger(IOreDictEntry in, IItemStack output, String research) {
this.output = output;
this.trigger = new DustTriggerOre(research, in.getName(), CraftTweakerMC.getItemStack(output));
}
@Override
public void apply() {
IDustTrigger.registerDustTrigger(this.trigger);
}
@Override
public String describe() {
return "Adding Salis mundus Conversion with output " + output.toCommandString();
}
}
static final class ActionRemoveTrigger implements IAction {
private final IIngredient output;
ActionRemoveTrigger(IIngredient output) {
this.output = output;
}
@Override
public void apply() {
final Iterator<IDustTrigger> iterator = IDustTrigger.triggers.iterator();
while(iterator.hasNext()) {
final IDustTrigger trigger = iterator.next();
try {
final IItemStack item;
if(trigger instanceof DustTriggerSimple && simpleTriggerResult != null)
item = CraftTweakerMC.getIItemStack((ItemStack) simpleTriggerResult.get(trigger));
else if(trigger instanceof DustTriggerOre && oredictTriggerResult != null)
item = CraftTweakerMC.getIItemStack((ItemStack) oredictTriggerResult.get(trigger));
else
continue;
if(output.contains(item))
iterator.remove();
} catch(IllegalAccessException e) {
CraftTweakerAPI.logError("Error while applying remove Salis mundus action: ", e);
}
}
}
@Override
public String describe() {
return "Removing all Single Salis mundus actions that return " + output.toCommandString();
}
}
}
|
src/main/java/com/blamejared/compat/thaumcraft/handlers/handlers/DustTrigger.java
|
Added Thaumcraft SalisMundus Handler
closes #700 (again)
|
src/main/java/com/blamejared/compat/thaumcraft/handlers/handlers/DustTrigger.java
|
Added Thaumcraft SalisMundus Handler closes #700 (again)
|
<ide><path>rc/main/java/com/blamejared/compat/thaumcraft/handlers/handlers/DustTrigger.java
<add>package com.blamejared.compat.thaumcraft.handlers.handlers;
<add>
<add>import com.blamejared.ModTweaker;
<add>import crafttweaker.CraftTweakerAPI;
<add>import crafttweaker.IAction;
<add>import crafttweaker.annotations.ModOnly;
<add>import crafttweaker.annotations.ZenRegister;
<add>import crafttweaker.api.block.IBlock;
<add>import crafttweaker.api.item.IIngredient;
<add>import crafttweaker.api.item.IItemStack;
<add>import crafttweaker.api.minecraft.CraftTweakerMC;
<add>import crafttweaker.api.oredict.IOreDictEntry;
<add>import net.minecraft.item.ItemStack;
<add>import stanhebben.zenscript.annotations.Optional;
<add>import stanhebben.zenscript.annotations.ZenClass;
<add>import stanhebben.zenscript.annotations.ZenMethod;
<add>import thaumcraft.api.crafting.IDustTrigger;
<add>import thaumcraft.common.lib.crafting.DustTriggerOre;
<add>import thaumcraft.common.lib.crafting.DustTriggerSimple;
<add>
<add>import java.lang.reflect.Field;
<add>import java.util.Iterator;
<add>
<add>@ZenClass("mods.thaumcraft.SalisMundus")
<add>@ZenRegister
<add>@ModOnly("thaumcraft")
<add>public class DustTrigger {
<add>
<add> private static final Field simpleTriggerResult;
<add> private static final Field oredictTriggerResult;
<add>
<add> static {
<add>
<add> Field A = null;
<add> Field B = null;
<add> try {
<add> A = DustTriggerSimple.class.getDeclaredField("result");
<add> A.setAccessible(true);
<add>
<add> B = DustTriggerOre.class.getDeclaredField("result");
<add> B.setAccessible(true);
<add> } catch(NoSuchFieldException e) {
<add> e.printStackTrace();
<add> }
<add>
<add> simpleTriggerResult = A;
<add> oredictTriggerResult = B;
<add> }
<add>
<add> private DustTrigger() {
<add> }
<add>
<add> @ZenMethod
<add> public static void addSingleConversion(IBlock in, IItemStack out, @Optional String research) {
<add> ModTweaker.LATE_ADDITIONS.add(new ActionAddTrigger(in, out, research));
<add> }
<add>
<add> @ZenMethod
<add> public static void addSingleConversion(IOreDictEntry in, IItemStack out, @Optional String research) {
<add> ModTweaker.LATE_ADDITIONS.add(new ActionAddTrigger(in, out, research));
<add> }
<add>
<add> @ZenMethod
<add> public static void removeSingleConversion(IIngredient output) {
<add> ModTweaker.LATE_REMOVALS.add(new ActionRemoveTrigger(output));
<add> }
<add>
<add> static final class ActionAddTrigger implements IAction {
<add>
<add> private final IItemStack output;
<add> private final IDustTrigger trigger;
<add>
<add> ActionAddTrigger(IBlock in, IItemStack output, String research) {
<add> this.output = output;
<add> this.trigger = new DustTriggerSimple(research, CraftTweakerMC.getBlock(in), CraftTweakerMC.getItemStack(output));
<add> }
<add>
<add> ActionAddTrigger(IOreDictEntry in, IItemStack output, String research) {
<add> this.output = output;
<add> this.trigger = new DustTriggerOre(research, in.getName(), CraftTweakerMC.getItemStack(output));
<add> }
<add>
<add> @Override
<add> public void apply() {
<add> IDustTrigger.registerDustTrigger(this.trigger);
<add> }
<add>
<add> @Override
<add> public String describe() {
<add> return "Adding Salis mundus Conversion with output " + output.toCommandString();
<add> }
<add> }
<add>
<add> static final class ActionRemoveTrigger implements IAction {
<add>
<add> private final IIngredient output;
<add>
<add> ActionRemoveTrigger(IIngredient output) {
<add> this.output = output;
<add> }
<add>
<add> @Override
<add> public void apply() {
<add> final Iterator<IDustTrigger> iterator = IDustTrigger.triggers.iterator();
<add> while(iterator.hasNext()) {
<add> final IDustTrigger trigger = iterator.next();
<add> try {
<add> final IItemStack item;
<add> if(trigger instanceof DustTriggerSimple && simpleTriggerResult != null)
<add> item = CraftTweakerMC.getIItemStack((ItemStack) simpleTriggerResult.get(trigger));
<add> else if(trigger instanceof DustTriggerOre && oredictTriggerResult != null)
<add> item = CraftTweakerMC.getIItemStack((ItemStack) oredictTriggerResult.get(trigger));
<add> else
<add> continue;
<add>
<add> if(output.contains(item))
<add> iterator.remove();
<add> } catch(IllegalAccessException e) {
<add> CraftTweakerAPI.logError("Error while applying remove Salis mundus action: ", e);
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public String describe() {
<add> return "Removing all Single Salis mundus actions that return " + output.toCommandString();
<add> }
<add> }
<add>
<add>
<add>}
|
|
Java
|
bsd-3-clause
|
eb02c0be7311261f8cba1feaea6e942f0c87906b
| 0 |
krishagni/openspecimen,krishagni/openspecimen,asamgir/openspecimen,asamgir/openspecimen,asamgir/openspecimen,krishagni/openspecimen,NCIP/catissue-core,NCIP/catissue-core,NCIP/catissue-core
|
/**
* <p>Title: Constants Class>
* <p>Description: This class stores the constants used in the operations in the application.</p>
* Copyright: Copyright (c) year
* Company: Washington University, School of Medicine, St. Louis.
* @author Gautam Shetty
* @version 1.00
* Created on Mar 16, 2005
*/
package edu.wustl.catissuecore.util.global;
/**
* This class stores the constants used in the operations in the application.
* @author gautam_shetty
*/
public class Constants extends edu.wustl.common.util.global.Constants
{
public static final String AND_JOIN_CONDITION = "AND";
public static final String OR_JOIN_CONDITION = "OR";
//Sri: Changed the format for displaying in Specimen Event list (#463)
public static final String TIMESTAMP_PATTERN = "MM-dd-yyyy HH:mm";
public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd";
// Mandar: Used for Date Validations in Validator Class
public static final String DATE_SEPARATOR = "-";
public static final String DATE_SEPARATOR_DOT = ".";
public static final String MIN_YEAR = "1900";
public static final String MAX_YEAR = "9999";
//Mysql Database constants.
/*public static final String MYSQL_DATE_PATTERN = "%m-%d-%Y";
public static final String MYSQL_TIME_PATTERN = "%H:%i:%s";
public static final String MYSQL_TIME_FORMAT_FUNCTION = "TIME_FORMAT";
public static final String MYSQL_DATE_FORMAT_FUNCTION = "DATE_FORMAT";
public static final String MYSQL_STR_TO_DATE_FUNCTION = "STR_TO_DATE";*/
public static final String VIEW = "view";
public static final String DELETE = "delete";
public static final String EXPORT = "export";
public static final String SHOPPING_CART_ADD = "shoppingCartAdd";
public static final String SHOPPING_CART_DELETE = "shoppingCartDelete";
public static final String SHOPPING_CART_EXPORT = "shoppingCartExport";
public static final String NEWUSERFORM = "newUserForm";
public static final String REDIRECT_TO_SPECIMEN = "specimenRedirect";
public static final String CALLED_FROM = "calledFrom";
//Constants required for Forgot Password
public static final String FORGOT_PASSWORD = "forgotpassword";
public static final String LOGINNAME = "loginName";
public static final String LASTNAME = "lastName";
public static final String FIRSTNAME = "firstName";
public static final String INSTITUTION = "institution";
public static final String EMAIL = "email";
public static final String DEPARTMENT = "department";
public static final String ADDRESS = "address";
public static final String CITY = "city";
public static final String STATE = "state";
public static final String COUNTRY = "country";
public static final String NEXT_CONTAINER_NO = "startNumber";
public static final String CSM_USER_ID = "csmUserId";
public static final String INSTITUTIONLIST = "institutionList";
public static final String DEPARTMENTLIST = "departmentList";
public static final String STATELIST = "stateList";
public static final String COUNTRYLIST = "countryList";
public static final String ROLELIST = "roleList";
public static final String ROLEIDLIST = "roleIdList";
public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList";
public static final String GENDER_LIST = "genderList";
public static final String GENOTYPE_LIST = "genotypeList";
public static final String ETHNICITY_LIST = "ethnicityList";
public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList";
public static final String RACELIST = "raceList";
public static final String VITAL_STATUS_LIST = "vitalStatusList";
public static final String PARTICIPANT_LIST = "participantList";
public static final String PARTICIPANT_ID_LIST = "participantIdList";
public static final String PROTOCOL_LIST = "protocolList";
public static final String TIMEHOURLIST = "timeHourList";
public static final String TIMEMINUTESLIST = "timeMinutesList";
public static final String TIMEAMPMLIST = "timeAMPMList";
public static final String RECEIVEDBYLIST = "receivedByList";
public static final String COLLECTEDBYLIST = "collectedByList";
public static final String COLLECTIONSITELIST = "collectionSiteList";
public static final String RECEIVEDSITELIST = "receivedSiteList";
public static final String RECEIVEDMODELIST = "receivedModeList";
public static final String ACTIVITYSTATUSLIST = "activityStatusList";
public static final String USERLIST = "userList";
public static final String SITETYPELIST = "siteTypeList";
public static final String STORAGETYPELIST="storageTypeList";
public static final String STORAGECONTAINERLIST="storageContainerList";
public static final String SITELIST="siteList";
// public static final String SITEIDLIST="siteIdList";
public static final String USERIDLIST = "userIdList";
public static final String STORAGETYPEIDLIST="storageTypeIdList";
public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList";
public static final String PARTICIPANT_IDENTIFIER_IN_CPR = "participant";
public static final String APPROVE_USER_STATUS_LIST = "statusList";
public static final String EVENT_PARAMETERS_LIST = "eventParametersList";
//New Specimen lists.
public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList";
public static final String SPECIMEN_TYPE_LIST = "specimenTypeList";
public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList";
public static final String TISSUE_SITE_LIST = "tissueSiteList";
public static final String TISSUE_SIDE_LIST = "tissueSideList";
public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList";
public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList";
public static final String BIOHAZARD_NAME_LIST = "biohazardNameList";
public static final String BIOHAZARD_ID_LIST = "biohazardIdList";
public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList";
public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList";
public static final String RECEIVED_QUALITY_LIST = "receivedQualityList";
//SpecimenCollecionGroup lists.
public static final String PROTOCOL_TITLE_LIST = "protocolTitleList";
public static final String PARTICIPANT_NAME_LIST = "participantNameList";
public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList";
//public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList";
public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList";
//public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList";
public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray";
//public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray";
public static final String SPECIMEN_COLLECTION_GROUP_ID = "specimenCollectionGroupId";
public static final String REQ_PATH = "redirectTo";
public static final String CLINICAL_STATUS_LIST = "cinicalStatusList";
public static final String SPECIMEN_CLASS_LIST = "specimenClassList";
public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList";
public static final String SPECIMEN_TYPE_MAP = "specimenTypeMap";
//Simple Query Interface Lists
public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList";
public static final String SIMPLE_QUERY_INTERFACE_TITLE = "simpleQueryInterfaceTitle";
public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject";
public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus";
public static final String START_NUMBER = "startNumber";
public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerSystemIdentifiers";
public static final int STORAGE_CONTAINER_FIRST_ROW = 1;
public static final int STORAGE_CONTAINER_FIRST_COLUMN = 1;
//event parameters lists
public static final String METHOD_LIST = "methodList";
public static final String HOUR_LIST = "hourList";
public static final String MINUTES_LIST = "minutesList";
public static final String EMBEDDING_MEDIUM_LIST = "embeddingMediumList";
public static final String PROCEDURE_LIST = "procedureList";
public static final String PROCEDUREIDLIST = "procedureIdList";
public static final String CONTAINER_LIST = "containerList";
public static final String CONTAINERIDLIST = "containerIdList";
public static final String FROMCONTAINERLIST="fromContainerList";
public static final String TOCONTAINERLIST="toContainerList";
public static final String FIXATION_LIST = "fixationList";
public static final String FROM_SITE_LIST="fromsiteList";
public static final String TO_SITE_LIST="tositeList";
public static final String ITEMLIST="itemList";
public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList";
public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList";
public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList";
public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList";
public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList";
public static final String STORAGE_STATUS_LIST="storageStatusList";
public static final String CLINICAL_DIAGNOSIS_LIST = "clinicalDiagnosisList";
public static final String HISTOLOGICAL_QUALITY_LIST="histologicalQualityList";
//For Specimen Event Parameters.
public static final String SPECIMEN_ID = "specimenId";
public static final String FROM_POSITION_DATA = "fromPositionData";
public static final String POS_ONE ="posOne";
public static final String POS_TWO ="posTwo";
public static final String STORAGE_CONTAINER_ID ="storContId";
public static final String IS_RNA = "isRNA";
public static final String RNA = "RNA";
// New Participant Event Parameters
public static final String PARTICIPANT_ID="participantId";
//Constants required in User.jsp Page
public static final String USER_SEARCH_ACTION = "UserSearch.do";
public static final String USER_ADD_ACTION = "UserAdd.do";
public static final String USER_EDIT_ACTION = "UserEdit.do";
public static final String APPROVE_USER_ADD_ACTION = "ApproveUserAdd.do";
public static final String APPROVE_USER_EDIT_ACTION = "ApproveUserEdit.do";
public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do";
public static final String USER_EDIT_PROFILE_ACTION = "UserEditProfile.do";
public static final String UPDATE_PASSWORD_ACTION = "UpdatePassword.do";
//Constants required in Accession.jsp Page
public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do";
public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do";
public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do";
//Constants required in StorageType.jsp Page
public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do";
public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do";
public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do";
//Constants required in StorageContainer.jsp Page
public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do";
public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do";
public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do";
//Constants required in Site.jsp Page
public static final String SITE_SEARCH_ACTION = "SiteSearch.do";
public static final String SITE_ADD_ACTION = "SiteAdd.do";
public static final String SITE_EDIT_ACTION = "SiteEdit.do";
//Constants required in Site.jsp Page
public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do";
public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do";
public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do";
//Constants required in Partcipant.jsp Page
public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do";
public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do";
public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do";
public static final String PARTICIPANT_LOOKUP_ACTION= "ParticipantLookup.do";
//Constants required in Institution.jsp Page
public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do";
public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do";
public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do";
//Constants required in Department.jsp Page
public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do";
public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do";
public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do";
//Constants required in CollectionProtocolRegistration.jsp Page
public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do";
public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do";
public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do";
//Constants required in CancerResearchGroup.jsp Page
public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do";
public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do";
public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do";
//Constants required for Approve user
public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do";
public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do";
//Reported Problem Constants
public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do";
public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do";
public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do";
public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do";
//Query Results view Actions
public static final String TREE_VIEW_ACTION = "TreeView.do";
public static final String DATA_VIEW_FRAME_ACTION = "SpreadsheetView.do";
public static final String SIMPLE_QUERY_INTERFACE_URL = "SimpleQueryInterface.do?pageOf=pageOfSimpleQueryInterface&menuSelected=17";
//New Specimen Data Actions.
public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do";
public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do";
public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do";
public static final String SPECIMEN_EVENT_PARAMETERS_ACTION = "ListSpecimenEventParameters.do";
//Create Specimen Data Actions.
public static final String CREATE_SPECIMEN_ADD_ACTION = "CreateSpecimenAdd.do";
public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do";
public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do";
//ShoppingCart Actions.
public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do";
public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do";
public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do";
public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do";
//Constants required in FrozenEventParameters.jsp Page
public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do";
public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do";
public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do";
//Constants required in CheckInCheckOutEventParameters.jsp Page
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do";
//Constants required in ReceivedEventParameters.jsp Page
public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "receivedEventParametersSearch.do";
public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do";
public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "receivedEventParametersEdit.do";
//Constants required in FluidSpecimenReviewEventParameters.jsp Page
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do";
//Constants required in CELLSPECIMENREVIEWParameters.jsp Page
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do";
//Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do";
// Constants required in DisposalEventParameters.jsp Page
public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do";
public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do";
public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do";
// Constants required in ThawEventParameters.jsp Page
public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do";
public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do";
public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do";
// Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do";
// Constants required in CollectionEventParameters.jsp Page
public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do";
public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do";
public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do";
// Constants required in SpunEventParameters.jsp Page
public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do";
public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do";
public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do";
// Constants required in EmbeddedEventParameters.jsp Page
public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do";
public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do";
public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do";
// Constants required in TransferEventParameters.jsp Page
public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do";
public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do";
public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do";
// Constants required in FixedEventParameters.jsp Page
public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do";
public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do";
public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do";
// Constants required in ProcedureEventParameters.jsp Page
public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do";
public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do";
public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do";
// Constants required in Distribution.jsp Page
public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do";
public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do";
public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do";
//Spreadsheet Export Action
public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do";
//Aliquots Action
public static final String ALIQUOT_ACTION = "Aliquots.do";
public static final String CREATE_ALIQUOT_ACTION = "CreateAliquots.do";
//Constants related to Aliquots functionality
public static final String PAGEOF_ALIQUOT = "pageOfAliquot";
public static final String PAGEOF_CREATE_ALIQUOT = "pageOfCreateAliquot";
public static final String AVAILABLE_CONTAINER_MAP = "availableContainerMap";
//Levels of nodes in query results tree.
public static final int MAX_LEVEL = 5;
public static final int MIN_LEVEL = 1;
public static final String[] DEFAULT_TREE_SELECT_COLUMNS = {
};
public static final String TABLE_NAME_COLUMN = "TABLE_NAME";
//Spreadsheet view Constants in DataViewAction.
public static final String PARTICIPANT = "Participant";
public static final String ACCESSION = "Accession";
public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?systemIdentifier=";
public static final String QUERY_PARTICIPANT_EDIT_ACTION = "QueryParticipantEdit.do";
public static final String QUERY_COLLECTION_PROTOCOL_SEARCH_ACTION = "QueryCollectionProtocolSearch.do?systemIdentifier=";
public static final String QUERY_COLLECTION_PROTOCOL_EDIT_ACTION = "QueryCollectionProtocolEdit.do";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "QuerySpecimenCollectionGroupSearch.do?systemIdentifier=";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "QuerySpecimenCollectionGroupEdit.do";
public static final String QUERY_SPECIMEN_SEARCH_ACTION = "QuerySpecimenSearch.do?systemIdentifier=";
public static final String QUERY_SPECIMEN_EDIT_ACTION = "QuerySpecimenEdit.do";
//public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?systemIdentifier=";
public static final String SPECIMEN = "Specimen";
public static final String SEGMENT = "Segment";
public static final String SAMPLE = "Sample";
public static final String COLLECTION_PROTOCOL_REGISTRATION = "CollectionProtocolRegistration";
public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID";
public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID";
public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID";
public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID";
public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID";
//For getting the tables for Simple Query and Fcon Query.
public static final int ADVANCE_QUERY_TABLES = 2;
//Identifiers for various Form beans
public static final int USER_FORM_ID = 1;
public static final int ACCESSION_FORM_ID = 3;
public static final int REPORTED_PROBLEM_FORM_ID = 4;
public static final int INSTITUTION_FORM_ID = 5;
public static final int APPROVE_USER_FORM_ID = 6;
public static final int ACTIVITY_STATUS_FORM_ID = 7;
public static final int DEPARTMENT_FORM_ID = 8;
public static final int COLLECTION_PROTOCOL_FORM_ID = 9;
public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10;
public static final int STORAGE_CONTAINER_FORM_ID = 11;
public static final int STORAGE_TYPE_FORM_ID = 12;
public static final int SITE_FORM_ID = 13;
public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14;
public static final int BIOHAZARD_FORM_ID = 15;
public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16;
public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17;
public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18;
public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21;
public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23;
public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24;
public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25;
public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26;
public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27;
public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28;
public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29;
public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30;
public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31;
public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32;
public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33;
public static final int CREATE_SPECIMEN_FORM_ID = 34;
public static final int FORGOT_PASSWORD_FORM_ID = 35;
public static final int SIGNUP_FORM_ID = 36;
public static final int DISTRIBUTION_FORM_ID = 37;
public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38;
public static final int SHOPPING_CART_FORM_ID = 39;
public static final int CONFIGURE_RESULT_VIEW_ID = 41;
public static final int ADVANCE_QUERY_INTERFACE_ID = 42;
public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19;
public static final int PARTICIPANT_FORM_ID = 2;
public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20;
public static final int NEW_SPECIMEN_FORM_ID = 22;
public static final int ALIQUOT_FORM_ID = 44;
//Misc
public static final String SEPARATOR = " : ";
//Identifiers for JDBC DAO.
public static final int QUERY_RESULT_TREE_JDBC_DAO = 1;
//Activity Status values
public static final String ACTIVITY_STATUS_APPROVE = "Approve";
public static final String ACTIVITY_STATUS_REJECT = "Reject";
public static final String ACTIVITY_STATUS_NEW = "New";
public static final String ACTIVITY_STATUS_PENDING = "Pending";
//Approve User status values.
public static final String APPROVE_USER_APPROVE_STATUS = "Approve";
public static final String APPROVE_USER_REJECT_STATUS = "Reject";
public static final String APPROVE_USER_PENDING_STATUS = "Pending";
//Approve User Constants
public static final int ZERO = 0;
public static final int START_PAGE = 1;
public static final int NUMBER_RESULTS_PER_PAGE = 5;
public static final String PAGE_NUMBER = "pageNum";
public static final String RESULTS_PER_PAGE = "numResultsPerPage";
public static final String TOTAL_RESULTS = "totalResults";
public static final String PREVIOUS_PAGE = "prevpage";
public static final String NEXT_PAGE = "nextPage";
public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList";
public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList";
public static final String USER_DETAILS = "details";
public static final String CURRENT_RECORD = "currentRecord";
public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core.";
//Edit Object Constants.
//Query Interface Results View Constants
public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser";
public static final String PAGEOF_SIGNUP = "pageOfSignUp";
public static final String PAGEOF_USERADD = "pageOfUserAdd";
public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin";
public static final String PAGEOF_USER_PROFILE = "pageOfUserProfile";
public static final String PAGEOF_CHANGE_PASSWORD = "pageOfChangePassword";
//For Simple Query Interface and Edit.
public static final String PAGEOF_EDIT_OBJECT = "pageOfEditObject";
//Query results view temporary table columns.
public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID";
public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID";
public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID";
public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE";
// Assign Privilege Constants.
public static final boolean PRIVILEGE_DEASSIGN = false;
public static final String OPERATION_DISALLOW = "Disallow";
//Constants for default column names to be shown for query result.
public static final String[] DEFAULT_SPREADSHEET_COLUMNS = {
// QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID,
// QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID,
// QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE
"IDENTIFIER","TYPE","ONE_DIMENSION_LABEL"
};
//Query results edit constants - MakeEditableAction.
public static final String EDITABLE = "editable";
//URL paths for Applet in TreeView.jsp
public static final String QUERY_TREE_APPLET = "edu/wustl/common/treeApplet/TreeApplet.class";
public static final String APPLET_CODEBASE = "Applet";
//Shopping Cart
public static final String SHOPPING_CART = "shoppingCart";
public static final int SELECT_OPTION_VALUE = -1;
// public static final String[] TISSUE_SITE_ARRAY = {
// SELECT_OPTION,"Sex","male","female",
// "Tissue","kidney","Left kidney","Right kidney"
// };
public static final String [] RECEIVEDMODEARRAY = {
SELECT_OPTION,
"by hand", "courier", "FedEX", "UPS"
};
public static final String [] GENDER_ARRAY = {
SELECT_OPTION,
"Male",
"Female"
};
public static final String [] GENOTYPE_ARRAY = {
SELECT_OPTION,
"XX",
"XY"
};
public static final String [] RACEARRAY = {
SELECT_OPTION,
"Asian",
"American"
};
public static final String [] PROTOCOLARRAY = {
SELECT_OPTION,
"aaaa",
"bbbb",
"cccc"
};
public static final String [] RECEIVEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] COLLECTEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] TIME_HOUR_ARRAY = {"1","2","3","4","5"};
public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"};
// Constants required in CollectionProtocol.jsp Page
public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do";
public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do";
public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do";
// Constants required in DistributionProtocol.jsp Page
public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do";
public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do";
public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do";
public static final String [] ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed",
"Disabled"
};
public static final String [] SITE_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] USER_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] APPROVE_USER_STATUS_VALUES = {
SELECT_OPTION,
APPROVE_USER_APPROVE_STATUS,
APPROVE_USER_REJECT_STATUS,
APPROVE_USER_PENDING_STATUS,
};
public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Closed",
"Pending"
};
public static final String TISSUE = "Tissue";
public static final String FLUID = "Fluid";
public static final String CELL = "Cell";
public static final String MOLECULAR = "Molecular";
public static final String [] SPECIMEN_TYPE_VALUES = {
SELECT_OPTION,
TISSUE,
FLUID,
CELL,
MOLECULAR
};
public static final String [] HOUR_ARRAY = {
"00",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23"
};
public static final String [] MINUTES_ARRAY = {
"00",
"01",
"02",
"03",
"04",
"05",
"06",
"07",
"08",
"09",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34",
"35",
"36",
"37",
"38",
"39",
"40",
"41",
"42",
"43",
"44",
"45",
"46",
"47",
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"55",
"56",
"57",
"58",
"59"
};
public static final String [] METHODARRAY = {
SELECT_OPTION,
"LN2",
"Dry Ice",
"Iso pentane"
};
public static final String [] EMBEDDINGMEDIUMARRAY = {
SELECT_OPTION,
"Plastic",
"Glass",
};
public static final String [] ITEMARRAY = {
SELECT_OPTION,
"Item1",
"Item2",
};
public static final String UNIT_GM = "gm";
public static final String UNIT_ML = "ml";
public static final String UNIT_CC = "cell count";
public static final String UNIT_MG = "g";
public static final String UNIT_CN = "count";
public static final String UNIT_CL = "cells";
public static final String [] PROCEDUREARRAY = {
SELECT_OPTION,
"Procedure 1",
"Procedure 2",
"Procedure 3"
};
public static final String [] CONTAINERARRAY = {
SELECT_OPTION,
"Container 1",
"Container 2",
"Container 3"
};
public static final String [] FIXATIONARRAY = {
SELECT_OPTION,
"FIXATION 1",
"FIXATION 2",
"FIXATION 3"
};
public static final String CDE_NAME_CLINICAL_STATUS = "Clinical Status";
public static final String CDE_NAME_GENDER = "Gender";
public static final String CDE_NAME_GENOTYPE = "Genotype";
public static final String CDE_NAME_SPECIMEN_CLASS = "Specimen";
public static final String CDE_NAME_SPECIMEN_TYPE = "Specimen Type";
public static final String CDE_NAME_TISSUE_SIDE = "Tissue Side";
public static final String CDE_NAME_PATHOLOGICAL_STATUS = "Pathological Status";
public static final String CDE_NAME_RECEIVED_QUALITY = "Received Quality";
public static final String CDE_NAME_FIXATION_TYPE = "Fixation Type";
public static final String CDE_NAME_COLLECTION_PROCEDURE = "Collection Procedure";
public static final String CDE_NAME_CONTAINER = "Container";
public static final String CDE_NAME_METHOD = "Method";
public static final String CDE_NAME_EMBEDDING_MEDIUM = "Embedding Medium";
public static final String CDE_NAME_BIOHAZARD = "Biohazard";
public static final String CDE_NAME_ETHNICITY = "Ethnicity";
public static final String CDE_NAME_RACE = "Race";
public static final String CDE_VITAL_STATUS = "Vital Status";
public static final String CDE_NAME_CLINICAL_DIAGNOSIS = "Clinical Diagnosis";
public static final String CDE_NAME_SITE_TYPE = "Site Type";
public static final String CDE_NAME_COUNTRY_LIST = "Countries";
public static final String CDE_NAME_STATE_LIST = "States";
public static final String CDE_NAME_HISTOLOGICAL_QUALITY = "Histological Quality";
//Constants for Advanced Search
public static final String STRING_OPERATORS = "StringOperators";
public static final String DATE_NUMERIC_OPERATORS = "DateNumericOperators";
public static final String ENUMERATED_OPERATORS = "EnumeratedOperators";
public static final String MULTI_ENUMERATED_OPERATORS = "MultiEnumeratedOperators";
public static final String [] STORAGE_STATUS_ARRAY = {
SELECT_OPTION,
"CHECK IN",
"CHECK OUT"
};
public static final String [] CLINICALDIAGNOSISARRAY = {
SELECT_OPTION,
"CLINICALDIAGNOSIS 1",
"CLINICALDIAGNOSIS 2",
"CLINICALDIAGNOSIS 3"
};
public static final String [] HISTOLOGICAL_QUALITY_ARRAY = {
SELECT_OPTION,
"GOOD",
"OK",
"DAMAGED"
};
// constants for Data required in query
public static final String ALIAS_NAME_TABLE_NAME_MAP="objectTableNames";
public static final String SYSTEM_IDENTIFIER_COLUMN_NAME = "IDENTIFIER";
public static final String NAME = "name";
public static final String EVENT_PARAMETERS[] = { Constants.SELECT_OPTION,
"Cell Specimen Review", "Check In Check Out", "Collection",
"Disposal", "Embedded", "Fixed", "Fluid Specimen Review",
"Frozen", "Molecular Specimen Review", "Procedure", "Received",
"Spun", "Thaw", "Tissue Specimen Review", "Transfer" };
public static final String EVENT_PARAMETERS_COLUMNS[] = { "Identifier",
"Event Parameter", "User", "Date / Time", "PageOf"};
public static final String [] SHOPPING_CART_COLUMNS = {"","Identifier",
"Type", "Subtype", "Tissue Site", "Tissue Side", "Pathological Status"};
//Constants required in AssignPrivileges.jsp
public static final String ASSIGN = "assignOperation";
public static final String PRIVILEGES = "privileges";
public static final String OBJECT_TYPES = "objectTypes";
public static final String OBJECT_TYPE_VALUES = "objectTypeValues";
public static final String RECORD_IDS = "recordIds";
public static final String ATTRIBUTES = "attributes";
public static final String GROUPS = "groups";
public static final String USERS_FOR_USE_PRIVILEGE = "usersForUsePrivilege";
public static final String USERS_FOR_READ_PRIVILEGE = "usersForReadPrivilege";
public static final String ASSIGN_PRIVILEGES_ACTION = "AssignPrivileges.do";
public static final int CONTAINER_IN_ANOTHER_CONTAINER = 2;
/**
* @param systemIdentifier
* @return
*/
public static String getUserPGName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
/**
* @param systemIdentifier
* @return
*/
public static String getUserGroupName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
//Mandar 25-Apr-06 : bug 1414 : Tissue units as per type
// tissue types with unit= count
public static final String FROZEN_TISSUE_BLOCK = "Frozen Tissue Block"; // PREVIOUS FROZEN BLOCK
public static final String FROZEN_TISSUE_SLIDE = "Frozen Tissue Slide"; // SLIDE
public static final String FIXED_TISSUE_BLOCK = "Fixed Tissue Block"; // PARAFFIN BLOCK
public static final String NOT_SPECIFIED = "Not Specified";
// tissue types with unit= g
public static final String FRESH_TISSUE = "Fresh Tissue";
public static final String FROZEN_TISSUE = "Frozen Tissue";
public static final String FIXED_TISSUE = "Fixed Tissue";
public static final String FIXED_TISSUE_SLIDE = "Fixed Tissue Slide";
//tissue types with unit= cc
public static final String MICRODISSECTED = "Microdissected";
// constants required for Distribution Report
public static final String CONFIGURATION_TABLES = "configurationTables";
public static final String DISTRIBUTION_TABLE_AlIAS[] = {"CollectionProtReg","Participant","Specimen",
"SpecimenCollectionGroup","DistributedItem"};
public static final String TABLE_COLUMN_DATA_MAP = "tableColumnDataMap";
public static final String CONFIGURE_RESULT_VIEW_ACTION = "ConfigureResultView.do";
public static final String TABLE_NAMES_LIST = "tableNamesList";
public static final String COLUMN_NAMES_LIST = "columnNamesList";
public static final String DISTRIBUTION_ID = "distributionId";
public static final String CONFIGURE_DISTRIBUTION_ACTION = "ConfigureDistribution.do";
public static final String DISTRIBUTION_REPORT_ACTION = "DistributionReport.do";
public static final String DISTRIBUTION_REPORT_SAVE_ACTION="DistributionReportSave.do";
public static final String SELECTED_COLUMNS[] = {"Specimen.IDENTIFIER.Identifier : Specimen",
"Specimen.TYPE.Type : Specimen",
"SpecimenCharacteristics.TISSUE_SITE.Tissue Site : Specimen",
"SpecimenCharacteristics.TISSUE_SIDE.Tissue Side : Specimen",
"SpecimenCharacteristics.PATHOLOGICAL_STATUS.Pathological Status : Specimen",
"DistributedItem.QUANTITY.Quantity : Distribution"};
public static final String SPECIMEN_ID_LIST = "specimenIdList";
public static final String DISTRIBUTION_ACTION = "Distribution.do?pageOf=pageOfDistribution";
public static final String DISTRIBUTION_REPORT_NAME = "Distribution Report.csv";
public static final String DISTRIBUTION_REPORT_FORM="distributionReportForm";
public static final String DISTRIBUTED_ITEMS_DATA = "distributedItemsData";
public static final String DISTRIBUTED_ITEM = "DistributedItem";
//constants for Simple Query Interface Configuration
public static final String CONFIGURE_SIMPLE_QUERY_ACTION = "ConfigureSimpleQuery.do";
public static final String CONFIGURE_SIMPLE_QUERY_VALIDATE_ACTION = "ConfigureSimpleQueryValidate.do";
public static final String CONFIGURE_SIMPLE_SEARCH_ACTION = "ConfigureSimpleSearch.do";
public static final String SIMPLE_SEARCH_ACTION = "SimpleSearch.do";
public static final String SIMPLE_SEARCH_AFTER_CONFIGURE_ACTION = "SimpleSearchAfterConfigure.do";
public static final String PAGEOF_DISTRIBUTION = "pageOfDistribution";
public static final String RESULT_VIEW_VECTOR = "resultViewVector";
public static final String SIMPLE_QUERY_COUNTER = "simpleQueryCount";
public static final String UNDEFINED = "Undefined";
public static final String UNKNOWN = "Unknown";
public static final String SEARCH_RESULT = "SearchResult.csv";
// Mandar : LightYellow and Green colors for CollectionProtocol SpecimenRequirements. Bug id: 587
// public static final String ODD_COLOR = "#FEFB85";
// public static final String EVEN_COLOR = "#A7FEAB";
// Light and dark shades of GREY.
public static final String ODD_COLOR = "#E5E5E5";
public static final String EVEN_COLOR = "#F7F7F7";
// TO FORWARD THE REQUEST ON SUBMIT IF STATUS IS DISABLED
public static final String BIO_SPECIMEN = "/ManageBioSpecimen.do";
public static final String ADMINISTRATIVE = "/ManageAdministrativeData.do";
public static final String PARENT_SPECIMEN_ID = "parentSpecimenId";
public static final String COLLECTION_REGISTRATION_ID = "collectionProtocolId";
public static final String FORWARDLIST = "forwardToList";
public static final String [][] SPECIMEN_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"Derive New From This Specimen", "createNew"},
{"Add Events", "eventParameters"},
{"Add More To Same Collection Group", "sameCollectionGroup"}
};
public static final String [][] SPECIMEN_COLLECTION_GROUP_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"Add New Specimen", "createNewSpecimen"}
};
public static final String [][] PROTOCOL_REGISTRATION_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"New Specimen Collection Group", "createSpecimenCollectionGroup"}
};
public static final String [][] PARTICIPANT_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"New Participant Registration", "createParticipantRegistration"}
};
//Constants Required for Advance Search
//Tree related
//public static final String PARTICIPANT ='Participant';
public static final String MENU_COLLECTION_PROTOCOL ="Collection Protocol";
public static final String MENU_SPECIMEN_COLLECTION_GROUP ="Specimen Collection Group";
public static final String MENU_DISTRIBUTION_PROTOCOL = "Distribution Protocol";
public static final String SPECIMEN_COLLECTION_GROUP ="SpecimenCollectionGroup";
public static final String DISTRIBUTION = "Distribution";
public static final String DISTRIBUTION_PROTOCOL = "DistributionProtocol";
public static final String CP = "CP";
public static final String SCG = "SCG";
public static final String D = "D";
public static final String DP = "DP";
public static final String C = "C";
public static final String S = "S";
public static final String P = "P";
public static final String ADVANCED_CONDITIONS_QUERY_VIEW = "advancedCondtionsQueryView";
public static final String ADVANCED_SEARCH_ACTION = "AdvanceSearch.do";
public static final String ADVANCED_SEARCH_RESULTS_ACTION = "AdvanceSearchResults.do";
public static final String CONFIGURE_ADVANCED_SEARCH_RESULTS_ACTION = "ConfigureAdvanceSearchResults.do";
public static final String ADVANCED_QUERY_ADD = "Add";
public static final String ADVANCED_QUERY_EDIT = "Edit";
public static final String ADVANCED_QUERY_DELETE = "Delete";
public static final String ADVANCED_QUERY_OPERATOR = "Operator";
public static final String ADVANCED_QUERY_OR = "OR";
public static final String ADVANCED_QUERY_AND = "pAND";
public static final String EVENT_CONDITIONS = "eventConditions";
public static final String IDENTIFIER_COLUMN_ID_MAP = "identifierColumnIdsMap";
public static final String PAGEOF_PARTICIPANT_QUERY_EDIT= "pageOfParticipantQueryEdit";
public static final String PAGEOF_COLLECTION_PROTOCOL_QUERY_EDIT= "pageOfCollectionProtocolQueryEdit";
public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP_QUERY_EDIT= "pageOfSpecimenCollectionGroupQueryEdit";
public static final String PAGEOF_SPECIMEN_QUERY_EDIT= "pageOfSpecimenQueryEdit";
public static final String PARTICIPANT_COLUMNS = "particpantColumns";
public static final String COLLECTION_PROTOCOL_COLUMNS = "collectionProtocolColumns";
public static final String SPECIMEN_COLLECTION_GROUP_COLUMNS = "SpecimenCollectionGroupColumns";
public static final String SPECIMEN_COLUMNS = "SpecimenColumns";
public static final String USER_ID_COLUMN = "USER_ID";
public static final String GENERIC_SECURITYMANAGER_ERROR = "The Security Violation error occured during a database operation. Please report this problem to the adminstrator";
public static final String BOOLEAN_YES = "Yes";
public static final String BOOLEAN_NO = "No";
public static final String PACKAGE_DOMAIN = "edu.wustl.catissuecore.domain";
//Constants for isAuditable and isSecureUpdate required for Dao methods in Bozlogic
public static final boolean IS_AUDITABLE_TRUE = true;
public static final boolean IS_SECURE_UPDATE_TRUE = true;
public static final boolean HAS_OBJECT_LEVEL_PRIVILEGE_FALSE = false;
//Constants for HTTP-API
public static final String CONTENT_TYPE = "CONTENT-TYPE";
// For StorageContainer isFull status
public static final String IS_CONTAINER_FULL_LIST = "isContainerFullList";
public static final String [] IS_CONTAINER_FULL_VALUES = {
SELECT_OPTION,
"True",
"False"
};
public static final String STORAGE_CONTAINER_DIM_ONE_LABEL = "oneDimLabel";
public static final String STORAGE_CONTAINER_DIM_TWO_LABEL = "twoDimLabel";
// public static final String SPECIMEN_TYPE_TISSUE = "Tissue";
// public static final String SPECIMEN_TYPE_FLUID = "Fluid";
// public static final String SPECIMEN_TYPE_CELL = "Cell";
// public static final String SPECIMEN_TYPE_MOL = "Molecular";
public static final String SPECIMEN_TYPE_COUNT = "Count";
public static final String SPECIMEN_TYPE_QUANTITY = "Quantity";
public static final String SPECIMEN_TYPE_DETAILS = "Details";
public static final String SPECIMEN_COUNT = "totalSpecimenCount";
public static final String TOTAL = "Total";
public static final String SPECIMENS = "Specimens";
//User Roles
public static final String TECHNICIAN = "Technician";
public static final String SUPERVISOR = "Supervisor";
public static final String SCIENTIST = "Scientist";
public static final String CHILD_CONTAINER_TYPE = "childContainerType";
public static final String UNUSED = "Unused";
public static final String TYPE = "Type";
//Mandar: 28-Apr-06 Bug 1129
public static final String DUPLICATE_SPECIMEN="duplicateSpecimen";
//Constants required in ParticipantLookupAction
public static final String PARTICIPANT_LOOKUP_PARAMETER="ParticipantLookupParameter";
public static final String PARTICIPANT_LOOKUP_ALGO="ParticipantLookupAlgo";
public static final String PARTICIPANT_LOOKUP_SUCCESS="success";
public static final String PARTICIPANT_ADD_FORWARD="participantAdd";
public static final String PARTICIPANT_SYSTEM_IDENTIFIER="System Identifier";
public static final String PARTICIPANT_LAST_NAME="Last Name";
public static final String PARTICIPANT_FIRST_NAME="First Name";
public static final String PARTICIPANT_MIDDLE_NAME="Middle Name";
public static final String PARTICIPANT_BIRTH_DATE="Birth Date";
public static final String PARTICIPANT_SOCIAL_SECURITY_NUMBER="SSN";
public static final String PARTICIPANT_PROBABLITY_MATCH="Probability";
//Constants for integration of caTies and CAE with caTissue Core
public static final String LINKED_DATA = "linkedData";
public static final String APPLICATION_ID = "applicationId";
public static final String CATIES = "caTies";
public static final String CAE = "cae";
// public static final String getCollectionProtocolPIGroupName(Long identifier)
// {
// if(identifier == null)
// {
// return "PI_COLLECTION_PROTOCOL_";
// }
// return "PI_COLLECTION_PROTOCOL_"+identifier;
// }
//
// public static final String getCollectionProtocolCoordinatorGroupName(Long identifier)
// {
// if(identifier == null)
// {
// return "COORDINATORS_COLLECTION_PROTOCOL_";
// }
// return "COORDINATORS_COLLECTION_PROTOCOL_"+identifier;
// }
//
// public static final String getDistributionProtocolPIGroupName(Long identifier)
// {
// if(identifier == null)
// {
// return "PI_DISTRIBUTION_PROTOCOL_";
// }
// return "PI_DISTRIBUTION_PROTOCOL_"+identifier;
// }
//
// public static final String getCollectionProtocolPGName(Long identifier)
// {
// if(identifier == null)
// {
// return "COLLECTION_PROTOCOL_";
// }
// return "COLLECTION_PROTOCOL_"+identifier;
// }
//
// public static final String getDistributionProtocolPGName(Long identifier)
// {
// if(identifier == null)
// {
// return "DISTRIBUTION_PROTOCOL_";
// }
// return "DISTRIBUTION_PROTOCOL_"+identifier;
// }
}
|
WEB-INF/src/edu/wustl/catissuecore/util/global/Constants.java
|
/**
* <p>Title: Constants Class>
* <p>Description: This class stores the constants used in the operations in the application.</p>
* Copyright: Copyright (c) year
* Company: Washington University, School of Medicine, St. Louis.
* @author Gautam Shetty
* @version 1.00
* Created on Mar 16, 2005
*/
package edu.wustl.catissuecore.util.global;
/**
* This class stores the constants used in the operations in the application.
* @author gautam_shetty
*/
public class Constants extends edu.wustl.common.util.global.Constants
{
public static final String AND_JOIN_CONDITION = "AND";
public static final String OR_JOIN_CONDITION = "OR";
//Sri: Changed the format for displaying in Specimen Event list (#463)
public static final String TIMESTAMP_PATTERN = "MM-dd-yyyy HH:mm";
public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd";
// Mandar: Used for Date Validations in Validator Class
public static final String DATE_SEPARATOR = "-";
public static final String DATE_SEPARATOR_DOT = ".";
public static final String MIN_YEAR = "1900";
public static final String MAX_YEAR = "9999";
//Mysql Database constants.
/*public static final String MYSQL_DATE_PATTERN = "%m-%d-%Y";
public static final String MYSQL_TIME_PATTERN = "%H:%i:%s";
public static final String MYSQL_TIME_FORMAT_FUNCTION = "TIME_FORMAT";
public static final String MYSQL_DATE_FORMAT_FUNCTION = "DATE_FORMAT";
public static final String MYSQL_STR_TO_DATE_FUNCTION = "STR_TO_DATE";*/
public static final String VIEW = "view";
public static final String DELETE = "delete";
public static final String EXPORT = "export";
public static final String SHOPPING_CART_ADD = "shoppingCartAdd";
public static final String SHOPPING_CART_DELETE = "shoppingCartDelete";
public static final String SHOPPING_CART_EXPORT = "shoppingCartExport";
public static final String NEWUSERFORM = "newUserForm";
public static final String REDIRECT_TO_SPECIMEN = "specimenRedirect";
public static final String CALLED_FROM = "calledFrom";
//Constants required for Forgot Password
public static final String FORGOT_PASSWORD = "forgotpassword";
public static final String LOGINNAME = "loginName";
public static final String LASTNAME = "lastName";
public static final String FIRSTNAME = "firstName";
public static final String INSTITUTION = "institution";
public static final String EMAIL = "email";
public static final String DEPARTMENT = "department";
public static final String ADDRESS = "address";
public static final String CITY = "city";
public static final String STATE = "state";
public static final String COUNTRY = "country";
public static final String NEXT_CONTAINER_NO = "startNumber";
public static final String CSM_USER_ID = "csmUserId";
public static final String INSTITUTIONLIST = "institutionList";
public static final String DEPARTMENTLIST = "departmentList";
public static final String STATELIST = "stateList";
public static final String COUNTRYLIST = "countryList";
public static final String ROLELIST = "roleList";
public static final String ROLEIDLIST = "roleIdList";
public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList";
public static final String GENDER_LIST = "genderList";
public static final String GENOTYPE_LIST = "genotypeList";
public static final String ETHNICITY_LIST = "ethnicityList";
public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList";
public static final String RACELIST = "raceList";
public static final String VITAL_STATUS_LIST = "vitalStatusList";
public static final String PARTICIPANT_LIST = "participantList";
public static final String PARTICIPANT_ID_LIST = "participantIdList";
public static final String PROTOCOL_LIST = "protocolList";
public static final String TIMEHOURLIST = "timeHourList";
public static final String TIMEMINUTESLIST = "timeMinutesList";
public static final String TIMEAMPMLIST = "timeAMPMList";
public static final String RECEIVEDBYLIST = "receivedByList";
public static final String COLLECTEDBYLIST = "collectedByList";
public static final String COLLECTIONSITELIST = "collectionSiteList";
public static final String RECEIVEDSITELIST = "receivedSiteList";
public static final String RECEIVEDMODELIST = "receivedModeList";
public static final String ACTIVITYSTATUSLIST = "activityStatusList";
public static final String USERLIST = "userList";
public static final String SITETYPELIST = "siteTypeList";
public static final String STORAGETYPELIST="storageTypeList";
public static final String STORAGECONTAINERLIST="storageContainerList";
public static final String SITELIST="siteList";
// public static final String SITEIDLIST="siteIdList";
public static final String USERIDLIST = "userIdList";
public static final String STORAGETYPEIDLIST="storageTypeIdList";
public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList";
public static final String PARTICIPANT_IDENTIFIER_IN_CPR = "participant";
public static final String APPROVE_USER_STATUS_LIST = "statusList";
public static final String EVENT_PARAMETERS_LIST = "eventParametersList";
//New Specimen lists.
public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList";
public static final String SPECIMEN_TYPE_LIST = "specimenTypeList";
public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList";
public static final String TISSUE_SITE_LIST = "tissueSiteList";
public static final String TISSUE_SIDE_LIST = "tissueSideList";
public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList";
public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList";
public static final String BIOHAZARD_NAME_LIST = "biohazardNameList";
public static final String BIOHAZARD_ID_LIST = "biohazardIdList";
public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList";
public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList";
public static final String RECEIVED_QUALITY_LIST = "receivedQualityList";
//SpecimenCollecionGroup lists.
public static final String PROTOCOL_TITLE_LIST = "protocolTitleList";
public static final String PARTICIPANT_NAME_LIST = "participantNameList";
public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList";
//public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList";
public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList";
//public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList";
public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray";
//public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray";
public static final String SPECIMEN_COLLECTION_GROUP_ID = "specimenCollectionGroupId";
public static final String REQ_PATH = "redirectTo";
public static final String CLINICAL_STATUS_LIST = "cinicalStatusList";
public static final String SPECIMEN_CLASS_LIST = "specimenClassList";
public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList";
public static final String SPECIMEN_TYPE_MAP = "specimenTypeMap";
//Simple Query Interface Lists
public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList";
public static final String SIMPLE_QUERY_INTERFACE_TITLE = "simpleQueryInterfaceTitle";
public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject";
public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus";
public static final String START_NUMBER = "startNumber";
public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerSystemIdentifiers";
public static final int STORAGE_CONTAINER_FIRST_ROW = 1;
public static final int STORAGE_CONTAINER_FIRST_COLUMN = 1;
//event parameters lists
public static final String METHOD_LIST = "methodList";
public static final String HOUR_LIST = "hourList";
public static final String MINUTES_LIST = "minutesList";
public static final String EMBEDDING_MEDIUM_LIST = "embeddingMediumList";
public static final String PROCEDURE_LIST = "procedureList";
public static final String PROCEDUREIDLIST = "procedureIdList";
public static final String CONTAINER_LIST = "containerList";
public static final String CONTAINERIDLIST = "containerIdList";
public static final String FROMCONTAINERLIST="fromContainerList";
public static final String TOCONTAINERLIST="toContainerList";
public static final String FIXATION_LIST = "fixationList";
public static final String FROM_SITE_LIST="fromsiteList";
public static final String TO_SITE_LIST="tositeList";
public static final String ITEMLIST="itemList";
public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList";
public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList";
public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList";
public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList";
public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList";
public static final String STORAGE_STATUS_LIST="storageStatusList";
public static final String CLINICAL_DIAGNOSIS_LIST = "clinicalDiagnosisList";
public static final String HISTOLOGICAL_QUALITY_LIST="histologicalQualityList";
//For Specimen Event Parameters.
public static final String SPECIMEN_ID = "specimenId";
public static final String FROM_POSITION_DATA = "fromPositionData";
public static final String POS_ONE ="posOne";
public static final String POS_TWO ="posTwo";
public static final String STORAGE_CONTAINER_ID ="storContId";
public static final String IS_RNA = "isRNA";
public static final String RNA = "RNA";
// New Participant Event Parameters
public static final String PARTICIPANT_ID="participantId";
//Constants required in User.jsp Page
public static final String USER_SEARCH_ACTION = "UserSearch.do";
public static final String USER_ADD_ACTION = "UserAdd.do";
public static final String USER_EDIT_ACTION = "UserEdit.do";
public static final String APPROVE_USER_ADD_ACTION = "ApproveUserAdd.do";
public static final String APPROVE_USER_EDIT_ACTION = "ApproveUserEdit.do";
public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do";
public static final String USER_EDIT_PROFILE_ACTION = "UserEditProfile.do";
public static final String UPDATE_PASSWORD_ACTION = "UpdatePassword.do";
//Constants required in Accession.jsp Page
public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do";
public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do";
public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do";
//Constants required in StorageType.jsp Page
public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do";
public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do";
public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do";
//Constants required in StorageContainer.jsp Page
public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do";
public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do";
public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do";
//Constants required in Site.jsp Page
public static final String SITE_SEARCH_ACTION = "SiteSearch.do";
public static final String SITE_ADD_ACTION = "SiteAdd.do";
public static final String SITE_EDIT_ACTION = "SiteEdit.do";
//Constants required in Site.jsp Page
public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do";
public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do";
public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do";
//Constants required in Partcipant.jsp Page
public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do";
public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do";
public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do";
public static final String PARTICIPANT_LOOKUP_ACTION= "ParticipantLookup.do";
//Constants required in Institution.jsp Page
public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do";
public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do";
public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do";
//Constants required in Department.jsp Page
public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do";
public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do";
public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do";
//Constants required in CollectionProtocolRegistration.jsp Page
public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do";
public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do";
public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do";
//Constants required in CancerResearchGroup.jsp Page
public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do";
public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do";
public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do";
//Constants required for Approve user
public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do";
public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do";
//Reported Problem Constants
public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do";
public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do";
public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do";
public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do";
//Query Results view Actions
public static final String TREE_VIEW_ACTION = "TreeView.do";
public static final String DATA_VIEW_FRAME_ACTION = "SpreadsheetView.do";
public static final String SIMPLE_QUERY_INTERFACE_URL = "SimpleQueryInterface.do?pageOf=pageOfSimpleQueryInterface&menuSelected=17";
//New Specimen Data Actions.
public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do";
public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do";
public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do";
public static final String SPECIMEN_EVENT_PARAMETERS_ACTION = "ListSpecimenEventParameters.do";
//Create Specimen Data Actions.
public static final String CREATE_SPECIMEN_ADD_ACTION = "CreateSpecimenAdd.do";
public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do";
public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do";
//ShoppingCart Actions.
public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do";
public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do";
public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do";
public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do";
//Constants required in FrozenEventParameters.jsp Page
public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do";
public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do";
public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do";
//Constants required in CheckInCheckOutEventParameters.jsp Page
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do";
//Constants required in ReceivedEventParameters.jsp Page
public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "receivedEventParametersSearch.do";
public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do";
public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "receivedEventParametersEdit.do";
//Constants required in FluidSpecimenReviewEventParameters.jsp Page
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do";
//Constants required in CELLSPECIMENREVIEWParameters.jsp Page
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do";
//Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do";
// Constants required in DisposalEventParameters.jsp Page
public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do";
public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do";
public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do";
// Constants required in ThawEventParameters.jsp Page
public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do";
public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do";
public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do";
// Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do";
// Constants required in CollectionEventParameters.jsp Page
public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do";
public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do";
public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do";
// Constants required in SpunEventParameters.jsp Page
public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do";
public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do";
public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do";
// Constants required in EmbeddedEventParameters.jsp Page
public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do";
public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do";
public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do";
// Constants required in TransferEventParameters.jsp Page
public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do";
public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do";
public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do";
// Constants required in FixedEventParameters.jsp Page
public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do";
public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do";
public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do";
// Constants required in ProcedureEventParameters.jsp Page
public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do";
public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do";
public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do";
// Constants required in Distribution.jsp Page
public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do";
public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do";
public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do";
//Spreadsheet Export Action
public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do";
//Levels of nodes in query results tree.
public static final int MAX_LEVEL = 5;
public static final int MIN_LEVEL = 1;
public static final String[] DEFAULT_TREE_SELECT_COLUMNS = {
};
public static final String TABLE_NAME_COLUMN = "TABLE_NAME";
//Spreadsheet view Constants in DataViewAction.
public static final String PARTICIPANT = "Participant";
public static final String ACCESSION = "Accession";
public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?systemIdentifier=";
public static final String QUERY_PARTICIPANT_EDIT_ACTION = "QueryParticipantEdit.do";
public static final String QUERY_COLLECTION_PROTOCOL_SEARCH_ACTION = "QueryCollectionProtocolSearch.do?systemIdentifier=";
public static final String QUERY_COLLECTION_PROTOCOL_EDIT_ACTION = "QueryCollectionProtocolEdit.do";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "QuerySpecimenCollectionGroupSearch.do?systemIdentifier=";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "QuerySpecimenCollectionGroupEdit.do";
public static final String QUERY_SPECIMEN_SEARCH_ACTION = "QuerySpecimenSearch.do?systemIdentifier=";
public static final String QUERY_SPECIMEN_EDIT_ACTION = "QuerySpecimenEdit.do";
//public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?systemIdentifier=";
public static final String SPECIMEN = "Specimen";
public static final String SEGMENT = "Segment";
public static final String SAMPLE = "Sample";
public static final String COLLECTION_PROTOCOL_REGISTRATION = "CollectionProtocolRegistration";
public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID";
public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID";
public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID";
public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID";
public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID";
//For getting the tables for Simple Query and Fcon Query.
public static final int ADVANCE_QUERY_TABLES = 2;
//Identifiers for various Form beans
public static final int USER_FORM_ID = 1;
public static final int ACCESSION_FORM_ID = 3;
public static final int REPORTED_PROBLEM_FORM_ID = 4;
public static final int INSTITUTION_FORM_ID = 5;
public static final int APPROVE_USER_FORM_ID = 6;
public static final int ACTIVITY_STATUS_FORM_ID = 7;
public static final int DEPARTMENT_FORM_ID = 8;
public static final int COLLECTION_PROTOCOL_FORM_ID = 9;
public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10;
public static final int STORAGE_CONTAINER_FORM_ID = 11;
public static final int STORAGE_TYPE_FORM_ID = 12;
public static final int SITE_FORM_ID = 13;
public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14;
public static final int BIOHAZARD_FORM_ID = 15;
public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16;
public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17;
public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18;
public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21;
public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23;
public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24;
public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25;
public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26;
public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27;
public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28;
public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29;
public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30;
public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31;
public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32;
public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33;
public static final int CREATE_SPECIMEN_FORM_ID = 34;
public static final int FORGOT_PASSWORD_FORM_ID = 35;
public static final int SIGNUP_FORM_ID = 36;
public static final int DISTRIBUTION_FORM_ID = 37;
public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38;
public static final int SHOPPING_CART_FORM_ID = 39;
public static final int CONFIGURE_RESULT_VIEW_ID = 41;
public static final int ADVANCE_QUERY_INTERFACE_ID = 42;
public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19;
public static final int PARTICIPANT_FORM_ID = 2;
public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20;
public static final int NEW_SPECIMEN_FORM_ID = 22;
//Misc
public static final String SEPARATOR = " : ";
//Identifiers for JDBC DAO.
public static final int QUERY_RESULT_TREE_JDBC_DAO = 1;
//Activity Status values
public static final String ACTIVITY_STATUS_APPROVE = "Approve";
public static final String ACTIVITY_STATUS_REJECT = "Reject";
public static final String ACTIVITY_STATUS_NEW = "New";
public static final String ACTIVITY_STATUS_PENDING = "Pending";
//Approve User status values.
public static final String APPROVE_USER_APPROVE_STATUS = "Approve";
public static final String APPROVE_USER_REJECT_STATUS = "Reject";
public static final String APPROVE_USER_PENDING_STATUS = "Pending";
//Approve User Constants
public static final int ZERO = 0;
public static final int START_PAGE = 1;
public static final int NUMBER_RESULTS_PER_PAGE = 5;
public static final String PAGE_NUMBER = "pageNum";
public static final String RESULTS_PER_PAGE = "numResultsPerPage";
public static final String TOTAL_RESULTS = "totalResults";
public static final String PREVIOUS_PAGE = "prevpage";
public static final String NEXT_PAGE = "nextPage";
public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList";
public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList";
public static final String USER_DETAILS = "details";
public static final String CURRENT_RECORD = "currentRecord";
public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core.";
//Edit Object Constants.
//Query Interface Results View Constants
public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser";
public static final String PAGEOF_SIGNUP = "pageOfSignUp";
public static final String PAGEOF_USERADD = "pageOfUserAdd";
public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin";
public static final String PAGEOF_USER_PROFILE = "pageOfUserProfile";
public static final String PAGEOF_CHANGE_PASSWORD = "pageOfChangePassword";
//For Simple Query Interface and Edit.
public static final String PAGEOF_EDIT_OBJECT = "pageOfEditObject";
//Query results view temporary table columns.
public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID";
public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID";
public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID";
public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE";
// Assign Privilege Constants.
public static final boolean PRIVILEGE_DEASSIGN = false;
public static final String OPERATION_DISALLOW = "Disallow";
//Constants for default column names to be shown for query result.
public static final String[] DEFAULT_SPREADSHEET_COLUMNS = {
// QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID,
// QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID,
// QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE
"IDENTIFIER","TYPE","ONE_DIMENSION_LABEL"
};
//Query results edit constants - MakeEditableAction.
public static final String EDITABLE = "editable";
//URL paths for Applet in TreeView.jsp
public static final String QUERY_TREE_APPLET = "edu/wustl/common/treeApplet/TreeApplet.class";
public static final String APPLET_CODEBASE = "Applet";
//Shopping Cart
public static final String SHOPPING_CART = "shoppingCart";
public static final int SELECT_OPTION_VALUE = -1;
// public static final String[] TISSUE_SITE_ARRAY = {
// SELECT_OPTION,"Sex","male","female",
// "Tissue","kidney","Left kidney","Right kidney"
// };
public static final String [] RECEIVEDMODEARRAY = {
SELECT_OPTION,
"by hand", "courier", "FedEX", "UPS"
};
public static final String [] GENDER_ARRAY = {
SELECT_OPTION,
"Male",
"Female"
};
public static final String [] GENOTYPE_ARRAY = {
SELECT_OPTION,
"XX",
"XY"
};
public static final String [] RACEARRAY = {
SELECT_OPTION,
"Asian",
"American"
};
public static final String [] PROTOCOLARRAY = {
SELECT_OPTION,
"aaaa",
"bbbb",
"cccc"
};
public static final String [] RECEIVEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] COLLECTEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] TIME_HOUR_ARRAY = {"1","2","3","4","5"};
public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"};
// Constants required in CollectionProtocol.jsp Page
public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do";
public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do";
public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do";
// Constants required in DistributionProtocol.jsp Page
public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do";
public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do";
public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do";
public static final String [] ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed",
"Disabled"
};
public static final String [] SITE_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] USER_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] APPROVE_USER_STATUS_VALUES = {
SELECT_OPTION,
APPROVE_USER_APPROVE_STATUS,
APPROVE_USER_REJECT_STATUS,
APPROVE_USER_PENDING_STATUS,
};
public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Closed",
"Pending"
};
public static final String TISSUE = "Tissue";
public static final String FLUID = "Fluid";
public static final String CELL = "Cell";
public static final String MOLECULAR = "Molecular";
public static final String [] SPECIMEN_TYPE_VALUES = {
SELECT_OPTION,
TISSUE,
FLUID,
CELL,
MOLECULAR
};
public static final String [] HOUR_ARRAY = {
"00",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23"
};
public static final String [] MINUTES_ARRAY = {
"00",
"01",
"02",
"03",
"04",
"05",
"06",
"07",
"08",
"09",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34",
"35",
"36",
"37",
"38",
"39",
"40",
"41",
"42",
"43",
"44",
"45",
"46",
"47",
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"55",
"56",
"57",
"58",
"59"
};
public static final String [] METHODARRAY = {
SELECT_OPTION,
"LN2",
"Dry Ice",
"Iso pentane"
};
public static final String [] EMBEDDINGMEDIUMARRAY = {
SELECT_OPTION,
"Plastic",
"Glass",
};
public static final String [] ITEMARRAY = {
SELECT_OPTION,
"Item1",
"Item2",
};
public static final String UNIT_GM = "gm";
public static final String UNIT_ML = "ml";
public static final String UNIT_CC = "cell count";
public static final String UNIT_MG = "g";
public static final String UNIT_CN = "count";
public static final String UNIT_CL = "cells";
public static final String [] PROCEDUREARRAY = {
SELECT_OPTION,
"Procedure 1",
"Procedure 2",
"Procedure 3"
};
public static final String [] CONTAINERARRAY = {
SELECT_OPTION,
"Container 1",
"Container 2",
"Container 3"
};
public static final String [] FIXATIONARRAY = {
SELECT_OPTION,
"FIXATION 1",
"FIXATION 2",
"FIXATION 3"
};
public static final String CDE_NAME_CLINICAL_STATUS = "Clinical Status";
public static final String CDE_NAME_GENDER = "Gender";
public static final String CDE_NAME_GENOTYPE = "Genotype";
public static final String CDE_NAME_SPECIMEN_CLASS = "Specimen";
public static final String CDE_NAME_SPECIMEN_TYPE = "Specimen Type";
public static final String CDE_NAME_TISSUE_SIDE = "Tissue Side";
public static final String CDE_NAME_PATHOLOGICAL_STATUS = "Pathological Status";
public static final String CDE_NAME_RECEIVED_QUALITY = "Received Quality";
public static final String CDE_NAME_FIXATION_TYPE = "Fixation Type";
public static final String CDE_NAME_COLLECTION_PROCEDURE = "Collection Procedure";
public static final String CDE_NAME_CONTAINER = "Container";
public static final String CDE_NAME_METHOD = "Method";
public static final String CDE_NAME_EMBEDDING_MEDIUM = "Embedding Medium";
public static final String CDE_NAME_BIOHAZARD = "Biohazard";
public static final String CDE_NAME_ETHNICITY = "Ethnicity";
public static final String CDE_NAME_RACE = "Race";
public static final String CDE_VITAL_STATUS = "Vital Status";
public static final String CDE_NAME_CLINICAL_DIAGNOSIS = "Clinical Diagnosis";
public static final String CDE_NAME_SITE_TYPE = "Site Type";
public static final String CDE_NAME_COUNTRY_LIST = "Countries";
public static final String CDE_NAME_STATE_LIST = "States";
public static final String CDE_NAME_HISTOLOGICAL_QUALITY = "Histological Quality";
//Constants for Advanced Search
public static final String STRING_OPERATORS = "StringOperators";
public static final String DATE_NUMERIC_OPERATORS = "DateNumericOperators";
public static final String ENUMERATED_OPERATORS = "EnumeratedOperators";
public static final String MULTI_ENUMERATED_OPERATORS = "MultiEnumeratedOperators";
public static final String [] STORAGE_STATUS_ARRAY = {
SELECT_OPTION,
"CHECK IN",
"CHECK OUT"
};
public static final String [] CLINICALDIAGNOSISARRAY = {
SELECT_OPTION,
"CLINICALDIAGNOSIS 1",
"CLINICALDIAGNOSIS 2",
"CLINICALDIAGNOSIS 3"
};
public static final String [] HISTOLOGICAL_QUALITY_ARRAY = {
SELECT_OPTION,
"GOOD",
"OK",
"DAMAGED"
};
// constants for Data required in query
public static final String ALIAS_NAME_TABLE_NAME_MAP="objectTableNames";
public static final String SYSTEM_IDENTIFIER_COLUMN_NAME = "IDENTIFIER";
public static final String NAME = "name";
public static final String EVENT_PARAMETERS[] = { Constants.SELECT_OPTION,
"Cell Specimen Review", "Check In Check Out", "Collection",
"Disposal", "Embedded", "Fixed", "Fluid Specimen Review",
"Frozen", "Molecular Specimen Review", "Procedure", "Received",
"Spun", "Thaw", "Tissue Specimen Review", "Transfer" };
public static final String EVENT_PARAMETERS_COLUMNS[] = { "Identifier",
"Event Parameter", "User", "Date / Time", "PageOf"};
public static final String [] SHOPPING_CART_COLUMNS = {"","Identifier",
"Type", "Subtype", "Tissue Site", "Tissue Side", "Pathological Status"};
//Constants required in AssignPrivileges.jsp
public static final String ASSIGN = "assignOperation";
public static final String PRIVILEGES = "privileges";
public static final String OBJECT_TYPES = "objectTypes";
public static final String OBJECT_TYPE_VALUES = "objectTypeValues";
public static final String RECORD_IDS = "recordIds";
public static final String ATTRIBUTES = "attributes";
public static final String GROUPS = "groups";
public static final String USERS_FOR_USE_PRIVILEGE = "usersForUsePrivilege";
public static final String USERS_FOR_READ_PRIVILEGE = "usersForReadPrivilege";
public static final String ASSIGN_PRIVILEGES_ACTION = "AssignPrivileges.do";
public static final int CONTAINER_IN_ANOTHER_CONTAINER = 2;
/**
* @param systemIdentifier
* @return
*/
public static String getUserPGName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
/**
* @param systemIdentifier
* @return
*/
public static String getUserGroupName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
//Mandar 25-Apr-06 : bug 1414 : Tissue units as per type
// tissue types with unit= count
public static final String FROZEN_TISSUE_BLOCK = "Frozen Tissue Block"; // PREVIOUS FROZEN BLOCK
public static final String FROZEN_TISSUE_SLIDE = "Frozen Tissue Slide"; // SLIDE
public static final String FIXED_TISSUE_BLOCK = "Fixed Tissue Block"; // PARAFFIN BLOCK
public static final String NOT_SPECIFIED = "Not Specified";
// tissue types with unit= g
public static final String FRESH_TISSUE = "Fresh Tissue";
public static final String FROZEN_TISSUE = "Frozen Tissue";
public static final String FIXED_TISSUE = "Fixed Tissue";
public static final String FIXED_TISSUE_SLIDE = "Fixed Tissue Slide";
//tissue types with unit= cc
public static final String MICRODISSECTED = "Microdissected";
// constants required for Distribution Report
public static final String CONFIGURATION_TABLES = "configurationTables";
public static final String DISTRIBUTION_TABLE_AlIAS[] = {"CollectionProtReg","Participant","Specimen",
"SpecimenCollectionGroup","DistributedItem"};
public static final String TABLE_COLUMN_DATA_MAP = "tableColumnDataMap";
public static final String CONFIGURE_RESULT_VIEW_ACTION = "ConfigureResultView.do";
public static final String TABLE_NAMES_LIST = "tableNamesList";
public static final String COLUMN_NAMES_LIST = "columnNamesList";
public static final String DISTRIBUTION_ID = "distributionId";
public static final String CONFIGURE_DISTRIBUTION_ACTION = "ConfigureDistribution.do";
public static final String DISTRIBUTION_REPORT_ACTION = "DistributionReport.do";
public static final String DISTRIBUTION_REPORT_SAVE_ACTION="DistributionReportSave.do";
public static final String SELECTED_COLUMNS[] = {"Specimen.IDENTIFIER.Identifier : Specimen",
"Specimen.TYPE.Type : Specimen",
"SpecimenCharacteristics.TISSUE_SITE.Tissue Site : Specimen",
"SpecimenCharacteristics.TISSUE_SIDE.Tissue Side : Specimen",
"SpecimenCharacteristics.PATHOLOGICAL_STATUS.Pathological Status : Specimen",
"DistributedItem.QUANTITY.Quantity : Distribution"};
public static final String SPECIMEN_ID_LIST = "specimenIdList";
public static final String DISTRIBUTION_ACTION = "Distribution.do?pageOf=pageOfDistribution";
public static final String DISTRIBUTION_REPORT_NAME = "Distribution Report.csv";
public static final String DISTRIBUTION_REPORT_FORM="distributionReportForm";
public static final String DISTRIBUTED_ITEMS_DATA = "distributedItemsData";
public static final String DISTRIBUTED_ITEM = "DistributedItem";
//constants for Simple Query Interface Configuration
public static final String CONFIGURE_SIMPLE_QUERY_ACTION = "ConfigureSimpleQuery.do";
public static final String CONFIGURE_SIMPLE_QUERY_VALIDATE_ACTION = "ConfigureSimpleQueryValidate.do";
public static final String CONFIGURE_SIMPLE_SEARCH_ACTION = "ConfigureSimpleSearch.do";
public static final String SIMPLE_SEARCH_ACTION = "SimpleSearch.do";
public static final String SIMPLE_SEARCH_AFTER_CONFIGURE_ACTION = "SimpleSearchAfterConfigure.do";
public static final String PAGEOF_DISTRIBUTION = "pageOfDistribution";
public static final String RESULT_VIEW_VECTOR = "resultViewVector";
public static final String SIMPLE_QUERY_COUNTER = "simpleQueryCount";
public static final String UNDEFINED = "Undefined";
public static final String UNKNOWN = "Unknown";
public static final String SEARCH_RESULT = "SearchResult.csv";
// Mandar : LightYellow and Green colors for CollectionProtocol SpecimenRequirements. Bug id: 587
// public static final String ODD_COLOR = "#FEFB85";
// public static final String EVEN_COLOR = "#A7FEAB";
// Light and dark shades of GREY.
public static final String ODD_COLOR = "#E5E5E5";
public static final String EVEN_COLOR = "#F7F7F7";
// TO FORWARD THE REQUEST ON SUBMIT IF STATUS IS DISABLED
public static final String BIO_SPECIMEN = "/ManageBioSpecimen.do";
public static final String ADMINISTRATIVE = "/ManageAdministrativeData.do";
public static final String PARENT_SPECIMEN_ID = "parentSpecimenId";
public static final String COLLECTION_REGISTRATION_ID = "collectionProtocolId";
public static final String FORWARDLIST = "forwardToList";
public static final String [][] SPECIMEN_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"Derive New From This Specimen", "createNew"},
{"Add Events", "eventParameters"},
{"Add More To Same Collection Group", "sameCollectionGroup"}
};
public static final String [][] SPECIMEN_COLLECTION_GROUP_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"Add New Specimen", "createNewSpecimen"}
};
public static final String [][] PROTOCOL_REGISTRATION_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"New Specimen Collection Group", "createSpecimenCollectionGroup"}
};
public static final String [][] PARTICIPANT_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"New Participant Registration", "createParticipantRegistration"}
};
//Constants Required for Advance Search
//Tree related
//public static final String PARTICIPANT ='Participant';
public static final String MENU_COLLECTION_PROTOCOL ="Collection Protocol";
public static final String MENU_SPECIMEN_COLLECTION_GROUP ="Specimen Collection Group";
public static final String MENU_DISTRIBUTION_PROTOCOL = "Distribution Protocol";
public static final String SPECIMEN_COLLECTION_GROUP ="SpecimenCollectionGroup";
public static final String DISTRIBUTION = "Distribution";
public static final String DISTRIBUTION_PROTOCOL = "DistributionProtocol";
public static final String CP = "CP";
public static final String SCG = "SCG";
public static final String D = "D";
public static final String DP = "DP";
public static final String C = "C";
public static final String S = "S";
public static final String P = "P";
public static final String ADVANCED_CONDITIONS_QUERY_VIEW = "advancedCondtionsQueryView";
public static final String ADVANCED_SEARCH_ACTION = "AdvanceSearch.do";
public static final String ADVANCED_SEARCH_RESULTS_ACTION = "AdvanceSearchResults.do";
public static final String CONFIGURE_ADVANCED_SEARCH_RESULTS_ACTION = "ConfigureAdvanceSearchResults.do";
public static final String ADVANCED_QUERY_ADD = "Add";
public static final String ADVANCED_QUERY_EDIT = "Edit";
public static final String ADVANCED_QUERY_DELETE = "Delete";
public static final String ADVANCED_QUERY_OPERATOR = "Operator";
public static final String ADVANCED_QUERY_OR = "OR";
public static final String ADVANCED_QUERY_AND = "pAND";
public static final String EVENT_CONDITIONS = "eventConditions";
public static final String IDENTIFIER_COLUMN_ID_MAP = "identifierColumnIdsMap";
public static final String PAGEOF_PARTICIPANT_QUERY_EDIT= "pageOfParticipantQueryEdit";
public static final String PAGEOF_COLLECTION_PROTOCOL_QUERY_EDIT= "pageOfCollectionProtocolQueryEdit";
public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP_QUERY_EDIT= "pageOfSpecimenCollectionGroupQueryEdit";
public static final String PAGEOF_SPECIMEN_QUERY_EDIT= "pageOfSpecimenQueryEdit";
public static final String PARTICIPANT_COLUMNS = "particpantColumns";
public static final String COLLECTION_PROTOCOL_COLUMNS = "collectionProtocolColumns";
public static final String SPECIMEN_COLLECTION_GROUP_COLUMNS = "SpecimenCollectionGroupColumns";
public static final String SPECIMEN_COLUMNS = "SpecimenColumns";
public static final String USER_ID_COLUMN = "USER_ID";
public static final String GENERIC_SECURITYMANAGER_ERROR = "The Security Violation error occured during a database operation. Please report this problem to the adminstrator";
public static final String BOOLEAN_YES = "Yes";
public static final String BOOLEAN_NO = "No";
public static final String PACKAGE_DOMAIN = "edu.wustl.catissuecore.domain";
//Constants for isAuditable and isSecureUpdate required for Dao methods in Bozlogic
public static final boolean IS_AUDITABLE_TRUE = true;
public static final boolean IS_SECURE_UPDATE_TRUE = true;
public static final boolean HAS_OBJECT_LEVEL_PRIVILEGE_FALSE = false;
//Constants for HTTP-API
public static final String CONTENT_TYPE = "CONTENT-TYPE";
// For StorageContainer isFull status
public static final String IS_CONTAINER_FULL_LIST = "isContainerFullList";
public static final String [] IS_CONTAINER_FULL_VALUES = {
SELECT_OPTION,
"True",
"False"
};
public static final String STORAGE_CONTAINER_DIM_ONE_LABEL = "oneDimLabel";
public static final String STORAGE_CONTAINER_DIM_TWO_LABEL = "twoDimLabel";
// public static final String SPECIMEN_TYPE_TISSUE = "Tissue";
// public static final String SPECIMEN_TYPE_FLUID = "Fluid";
// public static final String SPECIMEN_TYPE_CELL = "Cell";
// public static final String SPECIMEN_TYPE_MOL = "Molecular";
public static final String SPECIMEN_TYPE_COUNT = "Count";
public static final String SPECIMEN_TYPE_QUANTITY = "Quantity";
public static final String SPECIMEN_TYPE_DETAILS = "Details";
public static final String SPECIMEN_COUNT = "totalSpecimenCount";
public static final String TOTAL = "Total";
public static final String SPECIMENS = "Specimens";
//User Roles
public static final String TECHNICIAN = "Technician";
public static final String SUPERVISOR = "Supervisor";
public static final String SCIENTIST = "Scientist";
public static final String CHILD_CONTAINER_TYPE = "childContainerType";
public static final String UNUSED = "Unused";
public static final String TYPE = "Type";
//Mandar: 28-Apr-06 Bug 1129
public static final String DUPLICATE_SPECIMEN="duplicateSpecimen";
//Constants required in ParticipantLookupAction
public static final String PARTICIPANT_LOOKUP_PARAMETER="ParticipantLookupParameter";
public static final String PARTICIPANT_LOOKUP_ALGO="ParticipantLookupAlgo";
public static final String PARTICIPANT_LOOKUP_SUCCESS="success";
public static final String PARTICIPANT_ADD_FORWARD="participantAdd";
public static final String PARTICIPANT_SYSTEM_IDENTIFIER="System Identifier";
public static final String PARTICIPANT_LAST_NAME="Last Name";
public static final String PARTICIPANT_FIRST_NAME="First Name";
public static final String PARTICIPANT_MIDDLE_NAME="Middle Name";
public static final String PARTICIPANT_BIRTH_DATE="Birth Date";
public static final String PARTICIPANT_SOCIAL_SECURITY_NUMBER="SSN";
public static final String PARTICIPANT_PROBABLITY_MATCH="Probability";
//Constants for integration of caTies and CAE with caTissue Core
public static final String LINKED_DATA = "linkedData";
public static final String APPLICATION_ID = "applicationId";
public static final String CATIES = "caTies";
public static final String CAE = "cae";
// public static final String getCollectionProtocolPIGroupName(Long identifier)
// {
// if(identifier == null)
// {
// return "PI_COLLECTION_PROTOCOL_";
// }
// return "PI_COLLECTION_PROTOCOL_"+identifier;
// }
//
// public static final String getCollectionProtocolCoordinatorGroupName(Long identifier)
// {
// if(identifier == null)
// {
// return "COORDINATORS_COLLECTION_PROTOCOL_";
// }
// return "COORDINATORS_COLLECTION_PROTOCOL_"+identifier;
// }
//
// public static final String getDistributionProtocolPIGroupName(Long identifier)
// {
// if(identifier == null)
// {
// return "PI_DISTRIBUTION_PROTOCOL_";
// }
// return "PI_DISTRIBUTION_PROTOCOL_"+identifier;
// }
//
// public static final String getCollectionProtocolPGName(Long identifier)
// {
// if(identifier == null)
// {
// return "COLLECTION_PROTOCOL_";
// }
// return "COLLECTION_PROTOCOL_"+identifier;
// }
//
// public static final String getDistributionProtocolPGName(Long identifier)
// {
// if(identifier == null)
// {
// return "DISTRIBUTION_PROTOCOL_";
// }
// return "DISTRIBUTION_PROTOCOL_"+identifier;
// }
}
|
Constants for Specimen Aliquoting
SVN-Revision: 3515
|
WEB-INF/src/edu/wustl/catissuecore/util/global/Constants.java
|
Constants for Specimen Aliquoting
|
<ide><path>EB-INF/src/edu/wustl/catissuecore/util/global/Constants.java
<ide> //Spreadsheet Export Action
<ide> public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do";
<ide>
<add> //Aliquots Action
<add> public static final String ALIQUOT_ACTION = "Aliquots.do";
<add> public static final String CREATE_ALIQUOT_ACTION = "CreateAliquots.do";
<add>
<add> //Constants related to Aliquots functionality
<add> public static final String PAGEOF_ALIQUOT = "pageOfAliquot";
<add> public static final String PAGEOF_CREATE_ALIQUOT = "pageOfCreateAliquot";
<add> public static final String AVAILABLE_CONTAINER_MAP = "availableContainerMap";
<add>
<ide> //Levels of nodes in query results tree.
<ide> public static final int MAX_LEVEL = 5;
<ide> public static final int MIN_LEVEL = 1;
<ide> public static final int PARTICIPANT_FORM_ID = 2;
<ide> public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20;
<ide> public static final int NEW_SPECIMEN_FORM_ID = 22;
<add> public static final int ALIQUOT_FORM_ID = 44;
<ide>
<ide> //Misc
<ide> public static final String SEPARATOR = " : ";
|
|
JavaScript
|
mit
|
11524c9ca102da11affebf907482b78afe895d21
| 0 |
k-ori/algorithm-playground,k-ori/algorithm-playground,k-ori/algorithm-playground
|
var factorialZeros = function(n) {
var i=1, f5=0, m;
while((m=Math.pow(5,i))<n) {
f5+=Math.floor(n/m);
i+=1;
}
return f5;
};
console.log(factorialZeros(100));
// http://courses.csail.mit.edu/iap/interview/Hacking_a_Google_Interview_Practice_Questions_Person_A.pdf
// Question: Target Sum
var target_sum_hash = function(target, ar) {
var i=0, len=ar.length, hash = {};
for (; i<len; i+=1) {
if (hash[ar[i]]) return true;
hash[target-ar[i]] = true;
}
return false;
};
var target_sum_pointer = function(target, ar) {
var i=0, j=ar.length-1;
ar.sort(function(a,b) { return +a-(+b);});
while (i<j) {
while (ar[i]+ar[j]<target && ar[i]!=null) { i+=1; }
if (ar[i]==null) { return false; }
if (ar[i]+ar[j]==target) return true;
while (ar[i]+ar[j]>target && ar[j]!=null) { j-=1; }
if (ar[j]==null) { return false; }
if (ar[i]+ar[j]==target) return true;
}
return false;
};
var ar = [8,2,6,3,4,3,9,1];
console.log(target_sum_pointer(60,ar));
// http://courses.csail.mit.edu/iap/interview/Hacking_a_Google_Interview_Practice_Questions_Person_B.pdf
// Question: Odd Man Out 2014/4/13 16:00-16:16
var find_odd_hash = function(ar) {
var i=0, len=ar.length, hash = {};
for(; i<len; i+=1) {
if (hash[ar[i]]) {
delete hash[ar[i]];
} else {
hash[ar[i]] = true;
}
}
return Object.keys(hash).shift();
};
// Super awesome!!!
var find_odd_xor = function(ar) {
return ar.reduce(function(ac,n) {
return ac^n;
}, 0);
};
var ar2 = [0,9,5,7,9,2,3,5,0,2,3];
console.log(find_odd_hash(ar2));
// http://courses.csail.mit.edu/iap/interview/Hacking_a_Google_Interview_Practice_Questions_Person_B.pdf
// Question: Maximal Subarray 18:44-19:25
var max_subarray_memo = function(ar) {
var i=0, j, len=ar.length, prev, memo=[], m_end, m_start, max = Number.MIN_VALUE;
for (; i<len; i+=1) {
memo[i] = [];
for (j=0; j<=i; j+=1) {
prev = memo[i-1]==null? 0 : memo[i-1][j] || 0;
memo[i][j] = prev+ar[i];
}
}
memo.forEach(function(xs, end) {
xs.forEach(function(val, start) {
if (val>=max) {
m_start = start; m_end = end;
max = val;
}
});
});
return ar.slice(m_start, m_end+1);
};
var max_subarray = function(ar) {
var x, i=0, len=ar.length, max_ending_here = max_so_far = 0;
for (; i<len; i+=1) {
x = ar[i];
max_ending_here = Math.max(0, max_ending_here + x);
max_so_far = Math.max(max_so_far, max_ending_here);
}
return max_so_far;
};
var ar = [1, -3, 5, -2, 9, -8, -6, 4];
console.log(max_subarray(ar));
//ar2 = [-1, -3, -5, -2, -9, -8, -6, -4];
//console.log(max_subarray(ar2));
var factors = function(n) {
var i=2, result=[];
for (;i<=n/2; i+=1) {
if (n % i==0) { result.push(i); }
}
return result;
};
console.log(factors(20));
var isPower = function(_a, b) {
var a = _a
while(a % b ==0) {
a /= b;
}
return a==1 ? true : false;
};
console.log(isPower(10000,101));
// http://www.geeksforgeeks.org/find-number-zeroes/
// 2014/4/14 22:20?-22:43
// 1,1,1,*1,0,0,0 / len = 7
// mid = 3 5 4
// begin/end = 0/7 3/7 3/5
// 0,0,0,0,0,0,0 / len = 7
// mid = 3 1 0
// begin/end = 0/7 0/3 0/1
// 1,1,1,1,1,1,1 / len = 7
// mid = 3 5 6
// begin/end = 0/7 3/7 5/7
var zero_count = function(ar) {
var len = ar.length, n, begin=0, end=len, mid, head_0_i;
while (true) {
mid = begin + Math.floor((end-begin)/2);
n = ar[mid];
if (n===1) {
if (mid==len-1) { head_0_i = len; break; }
begin = mid;
} else {
if (mid==0 || ar[mid-1]==1) { head_0_i = mid; break; }
end = mid;
}
}
return len-head_0_i;
};
console.log(zero_count([1,1,1,1,0,0,0]));
// http://www.geeksforgeeks.org/find-if-there-is-a-subarray-with-0-sum/
// 2014/4/14 23:00-
var has_zero_sum = function(ar) {
var i=0, len=ar.length, j, sum;
for (; i<len; i+=1) {
sum = 0;
for (j=i; j<len; j+=1) {
sum += ar[j];
if (sum===0) { return true; }
}
}
return false;
};
console.log(has_zero_sum([-3, 2, 3, 1, 6]));
var merge_arrays = function(ars) {
return ars.reduce(function(acc, array) {
return _merge(array, acc);
}, []);
};
var _merge = function(ar1, ar2) {
var result = [], l_i=0, r_i=0, left, right, l_len=ar1.length, r_len=ar2.length;
while(l_i<l_len || r_i<r_len) {
left = ar1[l_i] || Number.MAX_VALUE;
right = ar2[r_i] || Number.MAX_VALUE;
if (left<=right) {
result.push(ar1[l_i]); l_i+=1;
} else {
result.push(ar2[r_i]); r_i+=1;
}
}
return result;
};
console.log(merge_arrays([
[2, 5, 10],
[25, 100, 105],
[7, 56, 42]
]));
|
src/number.js
|
var factorialZeros = function(n) {
var i=1, f5=0, m;
while((m=Math.pow(5,i))<n) {
f5+=Math.floor(n/m);
i+=1;
}
return f5;
};
console.log(factorialZeros(100));
// http://courses.csail.mit.edu/iap/interview/Hacking_a_Google_Interview_Practice_Questions_Person_A.pdf
// Question: Target Sum
var target_sum_hash = function(target, ar) {
var i=0, len=ar.length, hash = {};
for (; i<len; i+=1) {
if (hash[ar[i]]) return true;
hash[target-ar[i]] = true;
}
return false;
};
var target_sum_pointer = function(target, ar) {
var i=0, j=ar.length-1;
ar.sort(function(a,b) { return +a-(+b);});
while (i<j) {
while (ar[i]+ar[j]<target && ar[i]!=null) { i+=1; }
if (ar[i]==null) { return false; }
if (ar[i]+ar[j]==target) return true;
while (ar[i]+ar[j]>target && ar[j]!=null) { j-=1; }
if (ar[j]==null) { return false; }
if (ar[i]+ar[j]==target) return true;
}
return false;
};
var ar = [8,2,6,3,4,3,9,1];
console.log(target_sum_pointer(60,ar));
// http://courses.csail.mit.edu/iap/interview/Hacking_a_Google_Interview_Practice_Questions_Person_B.pdf
// Question: Odd Man Out 2014/4/13 16:00-16:16
var find_odd_hash = function(ar) {
var i=0, len=ar.length, hash = {};
for(; i<len; i+=1) {
if (hash[ar[i]]) {
delete hash[ar[i]];
} else {
hash[ar[i]] = true;
}
}
return Object.keys(hash).shift();
};
// Super awesome!!!
var find_odd_xor = function(ar) {
return ar.reduce(function(ac,n) {
return ac^n;
}, 0);
};
var ar2 = [0,9,5,7,9,2,3,5,0,2,3];
console.log(find_odd_(ar2));
// http://courses.csail.mit.edu/iap/interview/Hacking_a_Google_Interview_Practice_Questions_Person_B.pdf
// Question: Maximal Subarray 18:44-19:25
var max_subarray_memo = function(ar) {
var i=0, j, len=ar.length, prev, memo=[], m_end, m_start, max = Number.MIN_VALUE;
for (; i<len; i+=1) {
memo[i] = [];
for (j=0; j<=i; j+=1) {
prev = memo[i-1]==null? 0 : memo[i-1][j] || 0;
memo[i][j] = prev+ar[i];
}
}
memo.forEach(function(xs, end) {
xs.forEach(function(val, start) {
if (val>=max) {
m_start = start; m_end = end;
max = val;
}
});
});
return ar.slice(m_start, m_end+1);
};
var max_subarray = function(ar) {
var x, i=0, len=ar.length, max_ending_here = max_so_far = 0;
for (; i<len; i+=1) {
x = ar[i];
max_ending_here = Math.max(0, max_ending_here + x);
max_so_far = Math.max(max_so_far, max_ending_here);
}
return max_so_far;
};
var ar = [1, -3, 5, -2, 9, -8, -6, 4];
console.log(max_subarray_(ar));
//ar2 = [-1, -3, -5, -2, -9, -8, -6, -4];
//console.log(max_subarray(ar2));
var factors = function(n) {
var i=2, result=[];
for (;i<=n/2; i+=1) {
if (n % i==0) { result.push(i); }
}
return result;
};
console.log(factors(20));
var isPower = function(_a, b) {
var a = _a
while(a % b ==0) {
a /= b;
}
return a==1 ? true : false;
};
console.log(isPower(10000,101));
// http://www.geeksforgeeks.org/find-number-zeroes/
// 2014/4/14 22:20?-22:43
// 1,1,1,*1,0,0,0 / len = 7
// mid = 3 5 4
// begin/end = 0/7 3/7 3/5
// 0,0,0,0,0,0,0 / len = 7
// mid = 3 1 0
// begin/end = 0/7 0/3 0/1
// 1,1,1,1,1,1,1 / len = 7
// mid = 3 5 6
// begin/end = 0/7 3/7 5/7
var zero_count = function(ar) {
var len = ar.length, n, begin=0, end=len, mid, head_0_i;
while (true) {
mid = begin + Math.floor((end-begin)/2);
n = ar[mid];
if (n===1) {
if (mid==len-1) { head_0_i = len; break; }
begin = mid;
} else {
if (mid==0 || ar[mid-1]==1) { head_0_i = mid; break; }
end = mid;
}
}
return len-head_0_i;
};
console.log(zero_count([1,1,1,1,0,0,0]));
// http://www.geeksforgeeks.org/find-if-there-is-a-subarray-with-0-sum/
// 2014/4/14 23:00-
var has_zero_sum = function(ar) {
var i=0, len=ar.length, j, sum;
for (; i<len; i+=1) {
sum = 0;
for (j=i; j<len; j+=1) {
sum += ar[j];
if (sum===0) { return true; }
}
}
return false;
};
console.log(has_zero_sum([-3, 2, 3, 1, 6]));
|
Implemented merge in number problems
|
src/number.js
|
Implemented merge in number problems
|
<ide><path>rc/number.js
<ide> };
<ide>
<ide> var ar2 = [0,9,5,7,9,2,3,5,0,2,3];
<del>console.log(find_odd_(ar2));
<add>console.log(find_odd_hash(ar2));
<ide>
<ide> // http://courses.csail.mit.edu/iap/interview/Hacking_a_Google_Interview_Practice_Questions_Person_B.pdf
<ide> // Question: Maximal Subarray 18:44-19:25
<ide>
<ide> var ar = [1, -3, 5, -2, 9, -8, -6, 4];
<ide>
<del>console.log(max_subarray_(ar));
<add>console.log(max_subarray(ar));
<ide>
<ide> //ar2 = [-1, -3, -5, -2, -9, -8, -6, -4];
<ide> //console.log(max_subarray(ar2));
<ide> return false;
<ide> };
<ide> console.log(has_zero_sum([-3, 2, 3, 1, 6]));
<add>
<add>var merge_arrays = function(ars) {
<add> return ars.reduce(function(acc, array) {
<add> return _merge(array, acc);
<add> }, []);
<add>};
<add>var _merge = function(ar1, ar2) {
<add> var result = [], l_i=0, r_i=0, left, right, l_len=ar1.length, r_len=ar2.length;
<add> while(l_i<l_len || r_i<r_len) {
<add> left = ar1[l_i] || Number.MAX_VALUE;
<add> right = ar2[r_i] || Number.MAX_VALUE;
<add> if (left<=right) {
<add> result.push(ar1[l_i]); l_i+=1;
<add> } else {
<add> result.push(ar2[r_i]); r_i+=1;
<add> }
<add> }
<add> return result;
<add>};
<add>
<add>console.log(merge_arrays([
<add> [2, 5, 10],
<add> [25, 100, 105],
<add> [7, 56, 42]
<add>]));
|
|
Java
|
bsd-3-clause
|
ffce1eac98598ebd4e8514af4790f288a2e9df02
| 0 |
aic-sri-international/aic-util,aic-sri-international/aic-util
|
/*
* Copyright (c) 2013, SRI International
* All rights reserved.
* Licensed under the The BSD 3-Clause License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the aic-util 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.
*/
/* <b>Note:</b> Closely based on freely available version 'BigRational.java', developed
* by Eric Laroche, which can be found at: <a
* href="http://www.lrdev.com/lr/java/">http://www.lrdev.com/lr/java/</a>
* BigRational.java -- dynamically sized big rational numbers.
**
** Copyright (C) 2002-2010 Eric Laroche. All rights reserved.
**
** @author Eric Laroche <[email protected]>
** @version @(#)$Id: BigRational.java,v 1.3 2010/03/24 20:11:34 laroche Exp $
**
** This program is free software;
** you can redistribute it and/or modify it.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
**
*/
package com.sri.ai.util.math;
import java.math.BigInteger;
import com.google.common.annotations.Beta;
/**
* Rational implements dynamically sized arbitrary precision immutable rational
* numbers.<br>
* <br>
*
* <p>
* Dynamically sized means that (provided enough memory) the Rational numbers
* can't overflow (nor underflow); this characteristic is different from Java's
* data types int and long, but common with BigInteger (which implements only
* integer numbers, i.e. no fractions) and BigDecimal (which only implements
* precisely rational numbers with denominators that are products of 2 and 5
* [and implied 10]). Arbitrary precision means that there is no loss of
* precision with common arithmetic operations such as addition, subtraction,
* multiplication, and division (BigDecimal loses precision with division, if
* factors other than 2 or 5 are involved). [Doubles and floats can overflow and
* underflow, have a limited precision, and only implement precisely rationals
* with a denominator that is a power of 2.]
*
* <p>
* Rational provides most operations needed in rational number space
* calculations, including addition, subtraction, multiplication, division,
* integer power, remainder/modulus, comparison, and different roundings.
*
* <p>
* Rational provides conversion methods to and from the native types long, int,
* short, and byte (including support for unsigned values), double (binary64),
* float (binary32), quad (binary128, quadruple), half (binary16), and
* BigInteger. Rational can parse and print many string representations:
* rational, dot notations, with exponent, even mixtures thereof, and supports
* different radixes/bases (2 to typically 36 [limited by BigInteger parsing
* implementation]).
*
* <p>
* Rational uses java.math.BigInteger (JDK 1.1 and later) internally.
*
* <p>
* Binary operations (e.g. add, multiply) calculate their results from a
* Rational object ('this') and one [Rational or long] argument, returning a new
* immutable Rational object. Both the original object and the argument are left
* unchanged (hence immutable). Unary operations (e.g. negate, invert) calculate
* their result from the Rational object ('this'), returning a new immutable
* Rational object. The original object is left unchanged.
*
* <p>
* Most operations are precise (i.e. without loss of precision); exceptions are
* the conversion methods to limited precision types (doubleValue, floatValue),
* rounding (round), truncation (bigIntegerValue, floor, ceiling, truncate), as
* well as obviously the printing methods that include a precision parameter
* (toStringDot, toStringDotRelative, toStringExponent).
*
* <p>
* Rational doesn't provide a notion of "infinity" ([+-]Infinity) and
* "not a number" (NaN); IEEE 754 floating point Infinity and NaN are rejected
* (throwing a NumberFormatException). Operations such as 0/0 result in an
* ArithmeticException.
*
* <p>
* Rational internally uses private proxy functions for BigInteger
* functionality, including scanning and multiplying, to enhance speed and to
* realize fast checks for common values (1, 0, etc.).
*
* <p>
* Constructor samples: normal rational form, abbreviated form, fixed point
* form, abbreviated fixed point form, [exponential] floating point form,
* different radixes/bases different from 10, doubles/floats:
*
* <pre>
* Rational("-21/35") : rational -3/5
* Rational("/3") : rational 1/3
* Rational("3.4") : rational 17/5
* Rational(".7") : 0.7, rational 7/10
* Rational("-65.4E-3") : -327/5000
* Rational("f/37", 0x10) : 3/11
* Rational("f.37", 0x10) : 3895/256
* Rational("-dcba.efgh", 23) : -46112938320/279841
* Rational("1011101011010110", 2) : 47830
* Rational(StrictMath.E) : 6121026514868073/2251799813685248
* Rational((float)StrictMath.E) : 2850325/1048576
* </pre>
*
* <p>
* Also accepted are denormalized representations such as:
*
* <pre>
* Rational("2.5/-3.5"): -5/7
* Rational("12.34E-1/-56.78E-1") : -617/2839
* </pre>
*
* <p>
* Printing: rational form, fixed point (dot) forms with different absolute
* precisions (including negative precision), with relative precisions,
* exponential form, different radix:
*
* <pre>
* Rational("1234.5678") : "6172839/5000"
* Rational("1234.5678").toStringDot(6) : "1234.567800"
* Rational("1234.5678").toStringDot(2) : "1234.57"
* Rational("1234.5678").toStringDot(-2) : "1200"
* Rational("1234.5678").toStringDotRelative(6) : "1234.57"
* Rational("0.00012345678").toStringDotRelative(3) : "0.000123"
* Rational("1234.5678").toStringExponent(2) : "1.2E3"
* Rational("1011101011010110", 2).toString(0x10) : "bad6"
* </pre>
*
* <p>
* Usage: Rational operations can be conveniently chained (sample from Rational
* internal conversion from IEEE 754 bits):
*
* <pre>
* Rational.valueOf(2).power(exponent)
* .multiply(fraction.add(Rational.valueOfUnsigned(mantissa)))
* .multiply(sign);
* </pre>
*
* @author Eric Laroche <[email protected]>
* @author oreilly
*
*/
@Beta
public class Rational extends Number implements Cloneable, Comparable<Object> {
//
// PRIVATE CONSTANTS
// Note: Need to declare first as some of the public
// constants are dependent on these being initialized beforehand.
private static final long serialVersionUID = 1L;
//
// Note: following constants can't be constructed using
// Rational.bigIntegerValueOf().
// That one _uses_ the constants (avoid circular dependencies).
/**
* Constant internally used, for convenience and speed. Used as zero
* numerator. Used for fast checks.
*/
private final static BigInteger BIG_INTEGER_ZERO = BigInteger.valueOf(0);
/**
* Constant internally used, for convenience and speed. Used as neutral
* denominator. Used for fast checks.
*/
private final static BigInteger BIG_INTEGER_ONE = BigInteger.valueOf(1);
/**
* Constant internally used, for convenience and speed. Used for fast
* checks.
*/
private final static BigInteger BIG_INTEGER_MINUS_ONE = BigInteger
.valueOf(-1);
/**
* Constant internally used, for convenience and speed. Used in rounding
* zero numerator. _Not_ used for checks.
*/
private final static BigInteger BIG_INTEGER_TWO = BigInteger.valueOf(2);
/**
* Constant internally used, for convenience and speed. _Not_ used for
* checks.
*/
private final static BigInteger BIG_INTEGER_MINUS_TWO = BigInteger
.valueOf(-2);
/**
* Constant internally used, for convenience and speed. Corresponds to
* DEFAULT_RADIX, used in reading, scaling and printing. _Not_ used for
* checks.
*/
private final static BigInteger BIG_INTEGER_TEN = BigInteger.valueOf(10);
/**
* Constant internally used, for convenience and speed. Used in reading,
* scaling and printing. _Not_ used for checks.
*/
private final static BigInteger BIG_INTEGER_SIXTEEN = BigInteger
.valueOf(16);
/**
* The constant two to the power of 64 (18446744073709551616). Used is
* slicing larger [than double size] IEEE 754 values.
*/
private final static BigInteger BIG_INTEGER_TWO_POWER_64 = BigInteger
.valueOf(2).pow(64);
// some more constants, often used as radixes/bases
/**
* The constant two (2).
*/
private final static Rational TWO = new Rational(2);
/**
* The constant ten (10).
*/
private final static Rational TEN = new Rational(10);
/**
* The constant sixteen (16).
*/
private final static Rational SIXTEEN = new Rational(16);
/**
* The constant two to the power of 64 (18446744073709551616). Used is
* slicing larger [than double size] IEEE 754 values.
*/
private final static Rational TWO_POWER_64 = new Rational(
BIG_INTEGER_TWO_POWER_64);
/**
* Constant internally used, for speed.
*/
// calculated via Rational((float)(StrictMath.log(10)/StrictMath.log(2)))
// note: don't use float/double operations in this code though (except for
// test())
private final static Rational LOGARITHM_TEN_GUESS = new Rational(1741647,
524288);
/**
* Constant internally used, for speed.
*/
private final static Rational LOGARITHM_SIXTEEN = new Rational(4);
/**
* Number of explicit fraction bits in an IEEE 754 double (binary64) float,
* 52.
*/
private final static int DOUBLE_FLOAT_FRACTION_SIZE = 52;
/**
* Number of exponent bits in an IEEE 754 double (binary64) float, 11.
*/
private final static int DOUBLE_FLOAT_EXPONENT_SIZE = 11;
/**
* Number of explicit fraction bits in an IEEE 754 single (binary32) float,
* 23.
*/
private final static int SINGLE_FLOAT_FRACTION_SIZE = 23;
/**
* Number of exponent bits in an IEEE 754 single (binary32) float, 8.
*/
private final static int SINGLE_FLOAT_EXPONENT_SIZE = 8;
/**
* Number of explicit fraction bits in an IEEE 754 half (binary16) float,
* 10.
*/
private final static int HALF_FLOAT_FRACTION_SIZE = 10;
/**
* Number of exponent bits in an IEEE 754 half (binary16) float, 5.
*/
private final static int HALF_FLOAT_EXPONENT_SIZE = 5;
/**
* Number of explicit fraction bits in an IEEE 754 quad (binary128,
* quadruple) float, 112.
*/
private final static int QUAD_FLOAT_FRACTION_SIZE = 112;
/**
* Number of exponent bits in an IEEE 754 quad (binary128, quadruple) float,
* 15.
*/
private final static int QUAD_FLOAT_EXPONENT_SIZE = 15;
//
//
/**
* Numerator. Numerator may be negative. Numerator may be zero, in which
* case m_q must be one. [Conditions are put in place by normalize().]
*/
private BigInteger numerator;
/**
* Denominator (quotient). Denominator is never negative and never zero.
* [Conditions are put in place by normalize().]
*/
private BigInteger denominator;
// optimization, as instances are immmutable only
// calculate once when needed
private int hashCode = 0;
//
// PUBLIC CONSTANTS
//
/**
* Default radix, used in string printing and scanning, 10 (i.e. decimal by
* default).
*/
public final static int DEFAULT_RADIX = 10;
// Note: don't use valueOf() here; valueOf implementations use the constants
/**
* The constant zero (0).
*/
// [Constant name: see class BigInteger.]
public final static Rational ZERO = new Rational(0);
/**
* The constant one (1).
*/
// [Name: see class BigInteger.]
public final static Rational ONE = new Rational(1);
/**
* The constant minus-one (-1).
*/
public final static Rational MINUS_ONE = new Rational(-1);
/**
* Rounding mode to round away from zero.
*/
public final static int ROUND_UP = 0;
/**
* Rounding mode to round towards zero.
*/
public final static int ROUND_DOWN = 1;
/**
* Rounding mode to round towards positive infinity.
*/
public final static int ROUND_CEILING = 2;
/**
* Rounding mode to round towards negative infinity.
*/
public final static int ROUND_FLOOR = 3;
/**
* Rounding mode to round towards nearest neighbor unless both neighbors are
* equidistant, in which case to round up.
*/
public final static int ROUND_HALF_UP = 4;
/**
* Rounding mode to round towards nearest neighbor unless both neighbors are
* equidistant, in which case to round down.
*/
public final static int ROUND_HALF_DOWN = 5;
/**
* Rounding mode to round towards the nearest neighbor unless both neighbors
* are equidistant, in which case to round towards the even neighbor.
*/
public final static int ROUND_HALF_EVEN = 6;
/**
* Rounding mode to assert that the requested operation has an exact result,
* hence no rounding is necessary. If this rounding mode is specified on an
* operation that yields an inexact result, an ArithmeticException is
* thrown.
*/
public final static int ROUND_UNNECESSARY = 7;
/**
* Rounding mode to round towards nearest neighbor unless both neighbors are
* equidistant, in which case to round ceiling.
*/
public final static int ROUND_HALF_CEILING = 8;
/**
* Rounding mode to round towards nearest neighbor unless both neighbors are
* equidistant, in which case to round floor.
*/
public final static int ROUND_HALF_FLOOR = 9;
/**
* Rounding mode to round towards the nearest neighbor unless both neighbors
* are equidistant, in which case to round towards the odd neighbor.
*/
public final static int ROUND_HALF_ODD = 10;
/**
* Default round mode, ROUND_HALF_UP.
*/
public final static int DEFAULT_ROUND_MODE = ROUND_HALF_UP;
//
// PUBLIC METHODS
//
//
// START - Constructors
/**
* Construct a Rational from numerator and denominator. Both numerator and
* denominator may be negative. numerator/denominator may be denormalized
* (i.e. have common factors, or denominator being negative).
*
* @param numerator
* the rational's numerator.
* @param denominator
* the rational's denominator (quotient)
*/
public Rational(BigInteger numerator, BigInteger denominator) {
// note: check for denominator==null done later
if (denominator != null && bigIntegerIsZero(denominator)) {
throw new NumberFormatException("Denominator zero");
}
normalizeFrom(numerator, denominator);
}
/**
* Construct a Rational from a numerator only, denominator is defaulted to
* 1.
*
* @param numerator
* the rational's numerator.
*/
public Rational(BigInteger numerator) {
this(numerator, BIG_INTEGER_ONE);
}
/**
* Construct a Rational from long fix number integers representing numerator
* and denominator.
*
* @param numerator
* the rational's numerator.
* @param denominator
* the rational's denominator (quotient)
*/
public Rational(long numerator, long denominator) {
this(bigIntegerValueOf(numerator), bigIntegerValueOf(denominator));
}
/**
* Construct a Rational from a long fix number integer representing
* numerator, denominator is defaulted to 1.
*
* @param numerator
* the rational's numerator.
*/
public Rational(long numerator) {
this(bigIntegerValueOf(numerator), BIG_INTEGER_ONE);
}
/**
* Clone a Rational.
* <p>
* [As Rationals are immutable, this copy-constructor is not that useful.]
*/
public Rational(Rational that) {
normalizeFrom(that);
}
/**
* Construct a Rational from a string representation.
*
* <pre>
* The supported string formats are:
* "[+-]numerator"
* "[+-]numerator/[+-]denominator"
* "[+-]i.f"
* "[+-]i"
* "[+-]iE[+-]e"
* "[+-]i.fE[+-]e"
* (latter two only with radix <= 10, due to possible ambiguities);
* numerator and denominator can be any of the
* latter (i.e. mixed representations such as "-1.2E-3/-4.5E-6" are
* supported).
*
* Samples: "-21/35", "3.4", "-65.4E-3", "f/37" (base 16),
* "1011101011010110" (base 2).
* </pre>
*
* @param strRational
* a string prepresentation of a Rational number.
* @param radix
* the radix the string representation is meant to be in.
*/
public Rational(String strRational, int radix) {
if (strRational == null) {
throw new NumberFormatException("null");
}
// For simplicity remove leading and trailing white spaces.
strRational = strRational.trim();
// Within AIC-SMF we do not want rational to consider these
// as special legal default formats (original BigRational allowed these).
if (strRational.equals("+") || strRational.equals("-") || strRational.equals("/") ||
strRational.equals(".") || strRational.equals("") ||
strRational.startsWith("E") || strRational.startsWith("e")) {
throw new NumberFormatException("underspecificed rational:"+strRational);
}
// '/': least precedence, and left-to-right associative
// (therefore lastIndexOf and not indexOf: last slash has least
// precedence)
final int slash = strRational.lastIndexOf('/');
if (slash != -1) {
// "[+-]numerator/[+-]denominator"
String strNumerator = strRational.substring(0, slash);
String strDenominator = strRational.substring(slash + 1);
// suppress recursion: make stack-overflow attacks infeasible
if (strNumerator.indexOf('/') != -1) {
throw new NumberFormatException("can't nest '/'");
}
// handle "/x" as "1/x"
// [note: "1" and "-1" are treated specially and optimized
// in Rational.bigIntegerValueOf(String,int).]
if (strNumerator.equals("") || strNumerator.equals("+")) {
strNumerator = "1";
} else if (strNumerator.equals("-")) {
strNumerator = "-1";
}
// handle "x/" as "x"
// [note: "1" and "-1" are treated special and optimized
// in Rational.bigIntegerValueOf(String,int).]
if (strDenominator.equals("") || strDenominator.equals("+")) {
strDenominator = "1";
} else if (strDenominator.equals("-")) {
strDenominator = "-1";
}
// [recursion]
// [divide()'s outcome is already normalized,
// so there would be no need to normalize [again]]
normalizeFrom((new Rational(strNumerator, radix))
.divide(new Rational(strDenominator, radix)));
return;
}
checkRadix(radix);
// catch Java's string representations of
// doubles/floats unsupported by Rational
checkNaNAndInfinity(strRational, radix);
// [if radix<=10:] 'E': next higher precedence, not associative
// or right-to-left associative
int exp = -1;
// note: a distinction of exponent-'E' from large-base-digit-'e'
// would be unintuitive, since case doesn't matter with both uses
if (radix <= 10) {
// handle both [upper/lower] cases
final int exp1 = strRational.indexOf('E');
final int exp2 = strRational.indexOf('e');
exp = (exp1 == -1 || (exp2 != -1 && exp2 < exp1) ? exp2 : exp1);
}
if (exp != -1) {
String strMantissa = strRational.substring(0, exp);
String strExponent = strRational.substring(exp + 1);
// suppress recursion: make stack-overflow attacks infeasible
if (strExponent.indexOf('E') != -1
|| strExponent.indexOf('e') != -1) {
throw new NumberFormatException("can't nest 'E'");
}
// skip '+'
if (strExponent.length() > 0 && strExponent.charAt(0) == '+') {
strExponent = strExponent.substring(1);
}
// handle '-'
boolean negateTheExponent = false;
if (strExponent.length() > 0 && strExponent.charAt(0) == '-') {
negateTheExponent = true;
strExponent = strExponent.substring(1);
}
// handle "xE", "xE+", "xE-", as "xE0" aka "x"
if (strExponent.equals("")) {
strExponent = "0";
}
// [recursion]
Rational exponent = new Rational(strExponent, radix);
final int iexponent;
// transform possible [overflow/fraction] exception
try {
iexponent = exponent.intValueExact();
} catch (ArithmeticException e) {
final NumberFormatException e2 = new NumberFormatException(
e.getMessage());
// make sure this operation doesn't shadow the exception to be
// thrown
try {
e2.initCause(e);
} catch (Throwable e3) {
throw e2;
}
throw e2;
}
exponent = valueOf(radix).pow(iexponent);
if (negateTheExponent) {
exponent = exponent.invert();
}
// handle "Ex", "+Ex", "-Ex", as "1Ex"
if (strMantissa.equals("") || strMantissa.equals("+")) {
strMantissa = "1";
} else if (strMantissa.equals("-")) {
strMantissa = "-1";
}
// [multiply()'s outcome is already normalized,
// so there would be no need to normalize [again]]
normalizeFrom((new Rational(strMantissa, radix)).multiply(exponent));
return;
}
// '.': next higher precedence, not associative
// (can't have more than one dot)
String strIntegerPart, strFractionPart;
final int dot = strRational.indexOf('.');
if (dot != -1) {
// "[+-]i.f"
strIntegerPart = strRational.substring(0, dot);
strFractionPart = strRational.substring(dot + 1);
}
else {
// "[+-]i". [not just delegating to BigInteger.]
strIntegerPart = strRational;
strFractionPart = "";
}
// check for multiple signs or embedded signs
checkNumberFormat(strIntegerPart);
// skip '+'
// skip '+'. [BigInteger [likely] doesn't handle these.]
if (strIntegerPart.length() > 0 && strIntegerPart.charAt(0) == '+') {
strIntegerPart = strIntegerPart.substring(1);
}
// handle '-'
boolean negativeIntegerPart = false;
if (strIntegerPart.length() > 0 && strIntegerPart.charAt(0) == '-') {
negativeIntegerPart = true;
strIntegerPart = strIntegerPart.substring(1);
}
// handle ".x" as "0.x" ("." as "0.0")
// handle "" as "0"
// note: "0" is treated specially and optimized
// in Rational.bigIntegerValueOf(String,int).
if (strIntegerPart.equals("")) {
strIntegerPart = "0";
}
BigInteger numerator = bigIntegerValueOf(strIntegerPart, radix);
BigInteger denominator;
// includes the cases "x." and "."
if (!strFractionPart.equals("")) {
// check for signs
checkFractionFormat(strFractionPart);
final BigInteger fraction = bigIntegerValueOf(strFractionPart,
radix);
final int scale = strFractionPart.length();
denominator = bigIntegerPower(bigIntegerValueOf(radix), scale);
numerator = bigIntegerMultiply(numerator, denominator)
.add(fraction);
}
else {
denominator = BIG_INTEGER_ONE;
}
if (negativeIntegerPart) {
numerator = numerator.negate();
}
normalizeFrom(numerator, denominator);
}
/**
* Construct a Rational from a string representation using DEFAULT_RADIX.
*
* <pre>
* The supported string formats are:
* "[+-]numerator"
* "[+-]numerator/[+-]denominator"
* "[+-]i.f"
* "[+-]i"
* "[+-]iE[+-]e"
* "[+-]i.fE[+-]e"
* (latter two only with radix <= 10, due to possible ambiguities);
* numerator and denominator can be any of the
* latter (i.e. mixed representations such as "-1.2E-3/-4.5E-6" are
* supported).
*
* Samples: "-21/35", "3.4", "-65.4E-3", "f/37" (base 16),
* "1011101011010110" (base 2).
* </pre>
*
* @param strRational
* a string prepresentation of a Rational number.
*/
public Rational(String strRational) {
this(strRational, DEFAULT_RADIX);
}
/**
* Construct a Rational from an unscaled value and a scale value.
*
* @param unscaledValue
* an unscaled value representation of a Rational.
* @param scale
* the scale to be associated with the unscaledValue
* @param radix
* the radix the rational is meant to be in.
*/
public Rational(BigInteger unscaledValue, int scale, int radix) {
if (unscaledValue == null) {
throw new NumberFormatException("null");
}
final boolean negate = (scale < 0);
if (negate) {
scale = -scale;
}
checkRadix(radix);
final BigInteger scaleValue = bigIntegerPower(bigIntegerValueOf(radix),
scale);
normalizeFrom((negate ? bigIntegerMultiply(unscaledValue, scaleValue)
: unscaledValue), (negate ? BIG_INTEGER_ONE : scaleValue));
}
/**
* Construct a Rational from an unscaled value and a scale value, default
* radix (10).
*
* @param unscaledValue
* an unscaled value representation of a Rational.
* @param scale
* the scale to be associated with the unscaledValue
*/
public Rational(BigInteger unscaledValue, int scale) {
this(unscaledValue, scale, DEFAULT_RADIX);
}
/**
* Construct a Rational from an unscaled fix number value and a scale value.
*
* @param unscaledValue
* an unscaled value representation of a Rational.
* @param scale
* the scale to be associated with the unscaledValue
* @param radix
* the radix the rational is meant to be in.
*/
public Rational(long unscaledValue, int scale, int radix) {
this(bigIntegerValueOf(unscaledValue), scale, radix);
}
/**
* Construct a Rational from a [IEEE 754] double [size/precision] floating
* point number.
*
* @param value
* double value from which a Rational is to be constructed.
*/
public Rational(double value) {
normalizeFrom(valueOfDoubleBits(Double.doubleToLongBits(value)));
}
/**
* Construct a Rational from a [IEEE 754] single [size/precision] floating
* point number.
*
* @param value
* double value from which a Rational is to be constructed.
*/
public Rational(float value) {
normalizeFrom(valueOfFloatBits(Float.floatToIntBits(value)));
}
// END - Constructors
//
/**
* Positive predicate.
* <p>
* Indicates whether this Rational is larger than zero. Zero is not
* positive.
* <p>
* [For convenience.]
*/
public boolean isPositive() {
return (signum() > 0);
}
/**
* Negative predicate.
* <p>
* Indicates whether this Rational is smaller than zero. Zero isn't negative
* either.
* <p>
* [For convenience.]
*/
public boolean isNegative() {
return (signum() < 0);
}
/**
* Zero predicate.
* <p>
* Indicates whether this Rational is zero.
* <p>
* [For convenience and speed.]
*/
public boolean isZero() {
// optimization, first test is for speed.
if (this == ZERO || numerator == BIG_INTEGER_ZERO) {
return true;
}
// well, this is also optimized for speed a bit.
return (signum() == 0);
}
/**
* One predicate.
* <p>
* Indicates whether this Rational is 1.
* <p>
* [For convenience and speed.]
*/
public boolean isOne() {
// optimization
// first test is for speed.
if (this == ONE) {
return true;
}
return equals(ONE);
}
/**
* Minus-one predicate.
* <p>
* Indicates whether this Rational is -1.
* <p>
* [For convenience and speed.]
*/
public boolean isMinusOne() {
// optimization
// first test is for speed.
if (this == MINUS_ONE) {
return true;
}
return equals(MINUS_ONE);
}
/**
* Integer predicate.
* <p>
* Indicates whether this Rational convertible to a BigInteger without loss
* of precision. True iff denominator/quotient is one.
*/
public boolean isInteger() {
return bigIntegerIsOne(denominator);
}
/**
* Rational string representation, format "[-]numerator[/denominator]".
* <p>
* Sample output: "6172839/5000".
*/
public String toString(int radix) {
checkRadixArgument(radix);
final String s = stringValueOf(numerator, radix);
if (isInteger()) {
return s;
}
return s + "/" + stringValueOf(denominator, radix);
}
/**
* Rational string representation, format "[-]numerator[/denominator]",
* default radix (10).
* <p>
* Default string representation, as rational, not using an exponent.
* <p>
* Sample output: "6172839/5000".
* <p>
* Overwrites Object.toString().
*/
@Override
public String toString() {
return toString(DEFAULT_RADIX);
}
/**
* Fixed dot-format "[-]i.f" string representation, with a precision.
* <p>
* Precision may be negative, in which case the rounding affects digits left
* of the dot, i.e. the integer part of the number, as well.
* <p>
* Sample output: "1234.567800".
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public String toStringDot(int precision, int radix) {
return toStringDot(precision, radix, false);
}
/**
* Dot-format "[-]i.f" string representation, with a precision, default
* radix (10). Precision may be negative.
* <p>
* Sample output: "1234.567800".
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public String toStringDot(int precision) {
// [possible loss of precision step]
return toStringDot(precision, DEFAULT_RADIX, false);
}
// note: there is no 'default' precision.
/**
* Dot-format "[-]i.f" string representation, with a relative precision.
* <p>
* If the relative precision is zero or negative, "0" will be returned (i.e.
* total loss of precision).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public String toStringDotRelative(int precision, int radix) {
// kind of expensive, due to expensive logarithm implementation
// (with unusual radixes), and post processing
checkRadixArgument(radix);
// zero doesn't have any significant digits
if (isZero()) {
return "0";
}
// relative precision zero [or less means]: no significant digits at
// all, i.e. 0
// [loss of precision step]
if (precision <= 0) {
return "0";
}
// guessed [see below: rounding issues] length: sign doesn't matter;
// one digit more than logarithm
final int guessedLength = abs().logarithm(radix) + 1;
// [possible loss of precision step]
String s = toStringDot(precision - guessedLength, radix);
// [floor of] logarithm and [arithmetic] rounding [half-up]
// need post-processing:
// find first significant digit and check for dot
boolean dot = false;
int i;
for (i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (c == '.') {
dot = true;
}
// expecting nothing than '-', '.', and digits
if (c != '-' && c != '.' && c != '0') {
break;
}
}
// count digits / [still] check for dot
int digits = 0;
for (; i < s.length(); i++) {
if (s.charAt(i) == '.') {
dot = true;
}
else {
digits++;
}
}
// cut excess zeros
// expecting at most 1 excess zero, e.g. for "0.0099999"
final int excess = digits - precision;
if (dot && excess > 0) {
s = s.substring(0, s.length() - excess);
}
return s;
}
/**
* Dot-format "[-]i.f" string representation, with a relative precision,
* default radix (10).
* <p>
* If the relative precision is zero or negative, "0" will be returned (i.e.
* total loss of precision).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public String toStringDotRelative(int precision) {
// [possible loss of precision step]
return toStringDotRelative(precision, DEFAULT_RADIX);
}
/**
* Exponent-format string representation, with a relative precision,
* "[-]i[.f]E[-]e" (where i is one digit other than 0 exactly; f has no
* trailing 0);
* <p>
* Sample output: "1.2E3".
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public String toStringExponent(int precision, int radix) {
checkRadixArgument(radix);
// zero doesn't have any significant digits
if (isZero()) {
return "0";
}
// relative precision zero [or less means]: no significant digits at
// all, i.e. 0
// [loss of precision step]
if (precision <= 0) {
return "0";
}
// guessed [see below: rounding issues] length: sign doesn't matter;
// one digit more than logarithm
final int guessedLength = abs().logarithm(radix) + 1;
// [possible loss of precision step]
final String s = toStringDot(precision - guessedLength, radix, true);
return toExponentRepresentation(s, radix);
}
/**
* Exponent-format string representation, with a relative precision, default
* radix (10), "[-]i[.f]E[-]e" (where i is one digit other than 0 exactly; f
* has no trailing 0);
* <p>
* Sample output: "1.2E3".
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public String toStringExponent(int precision) {
// [possible loss of precision step]
return toStringExponent(precision, DEFAULT_RADIX);
}
/**
* Add a Rational to this Rational and return a new Rational.
* <p>
* If one of the operands is zero, [as an optimization] the other Rational
* is returned.
*/
// [Name: see class BigInteger.]
public Rational add(Rational that) {
// optimization: second operand is zero (i.e. neutral element).
if (that.isZero()) {
return this;
}
// optimization: first operand is zero (i.e. neutral element).
if (isZero()) {
return that;
}
// note: not checking for that.equals(negate()),
// since that would involve creation of a temporary object
// note: the calculated numerator/denominator may be denormalized,
// implicit normalize() is needed.
// optimization: same denominator.
if (bigIntegerEquals(denominator, that.denominator)) {
return new Rational(numerator.add(that.numerator), denominator);
}
// optimization: second operand is an integer.
if (that.isInteger()) {
return new Rational(numerator.add(that.numerator
.multiply(denominator)), denominator);
}
// optimization: first operand is an integer.
if (isInteger()) {
return new Rational(numerator.multiply(that.denominator).add(
that.numerator), that.denominator);
}
// default case. [this would handle all cases.]
return new Rational(numerator.multiply(that.denominator).add(
that.numerator.multiply(denominator)),
denominator.multiply(that.denominator));
}
/**
* Add a long fix number integer to this Rational and return a new Rational.
*/
public Rational add(long that) {
return add(valueOf(that));
}
/**
* Subtract a Rational from this Rational and return a new Rational.
* <p>
* If the second operand is zero, [as an optimization] this Rational is
* returned.
*/
// [Name: see class BigInteger.]
public Rational subtract(Rational that) {
// optimization: second operand is zero.
if (that.isZero()) {
return this;
}
// optimization: first operand is zero
if (isZero()) {
return that.negate();
}
// optimization: operands are equal
if (equals(that)) {
return ZERO;
}
// note: the calculated n/q may be denormalized,
// implicit normalize() is needed.
// optimization: same denominator.
if (bigIntegerEquals(denominator, that.denominator)) {
return new Rational(numerator.subtract(that.numerator), denominator);
}
// optimization: second operand is an integer.
if (that.isInteger()) {
return new Rational(numerator.subtract(that.numerator
.multiply(denominator)), denominator);
}
// optimization: first operand is an integer.
if (isInteger()) {
return new Rational(numerator.multiply(that.denominator).subtract(
that.numerator), that.denominator);
}
// default case. [this would handle all cases.]
return new Rational(numerator.multiply(that.denominator).subtract(
that.numerator.multiply(denominator)),
denominator.multiply(that.denominator));
}
/**
* Subtract a long fix number integer from this Rational and return a new
* Rational.
*/
public Rational subtract(long that) {
return subtract(valueOf(that));
}
/**
* Multiply a Rational to this Rational and return a new Rational.
* <p>
* If one of the operands is one, [as an optimization] the other Rational is
* returned.
*/
// [Name: see class BigInteger.]
public Rational multiply(Rational that) {
// optimization: one or both operands are zero.
if (that.isZero() || isZero()) {
return ZERO;
}
// optimization: second operand is 1.
if (that.isOne()) {
return this;
}
// optimization: first operand is 1.
if (isOne()) {
return that;
}
// optimization: second operand is -1.
if (that.isMinusOne()) {
return negate();
}
// optimization: first operand is -1.
if (isMinusOne()) {
return that.negate();
}
// note: the calculated numerator/denominator may be denormalized,
// implicit normalize() is needed.
return new Rational(bigIntegerMultiply(numerator, that.numerator),
bigIntegerMultiply(denominator, that.denominator));
}
/**
* Multiply a long fix number integer to this Rational and return a new
* Rational.
*/
public Rational multiply(long that) {
return multiply(valueOf(that));
}
/**
* Divide this Rational through another Rational and return a new Rational.
* <p>
* If the second operand is one, [as an optimization] this Rational is
* returned.
*/
// [Name: see class BigInteger.]
public Rational divide(Rational that) {
if (that.isZero()) {
throw new ArithmeticException("division by zero");
}
// optimization: first operand is zero.
if (isZero()) {
return ZERO;
}
// optimization: second operand is 1.
if (that.isOne()) {
return this;
}
// optimization: first operand is 1.
if (isOne()) {
return that.invert();
}
// optimization: second operand is -1.
if (that.isMinusOne()) {
return negate();
}
// optimization: first operand is -1.
if (isMinusOne()) {
return that.invert().negate();
}
// note: the calculated numerator/denominator may be denormalized,
// implicit normalize() is needed.
return new Rational(bigIntegerMultiply(numerator, that.denominator),
bigIntegerMultiply(denominator, that.numerator));
}
/**
* Divide this Rational through a long fix number integer and return a new
* Rational.
*/
public Rational divide(long that) {
return divide(valueOf(that));
}
/**
* Calculate this Rational's integer power and return a new Rational.
* <p>
* The integer exponent may be negative.
* <p>
* If the exponent is one, [as an optimization] this Rational is returned.
*/
// [Name: see classes Math, BigInteger.]
public Rational pow(int exponent) {
final boolean zero = isZero();
if (zero) {
if (exponent == 0) {
throw new ArithmeticException("zero exp zero");
}
if (exponent < 0) {
throw new ArithmeticException("division by zero");
}
}
// optimization
if (exponent == 0) {
return ONE;
}
// optimization
// test for exponent<=0 already done
if (zero) {
return ZERO;
}
// optimization
if (exponent == 1) {
return this;
}
// optimization
if (exponent == -1) {
return invert();
}
final boolean negate = (exponent < 0);
if (negate) {
exponent = -exponent;
}
final BigInteger numerator = bigIntegerPower(this.numerator, exponent);
final BigInteger denominator = bigIntegerPower(this.denominator,
exponent);
// note: the calculated numerator/denominator are not denormalized in
// the sense of having common factors, but numerator might be negative
// (and become denominator below)
return new Rational((negate ? denominator : numerator),
(negate ? numerator : denominator));
}
/**
* Calculate the remainder of this Rational and another Rational and return
* a new Rational.
* <p>
* The remainder result may be negative.
* <p>
* The remainder is based on round down (towards zero) / truncate. 5/3 == 1
* + 2/3 (remainder 2), 5/-3 == -1 + 2/-3 (remainder 2), -5/3 == -1 + -2/3
* (remainder -2), -5/-3 == 1 + -2/-3 (remainder -2).
*/
// [Name: see class BigInteger.]
public Rational remainder(Rational that) {
final int thisSignum = signum();
final int thatSignum = that.signum();
if (thatSignum == 0) {
throw new ArithmeticException("division by zero");
}
Rational a = this;
if (thisSignum < 0) {
a = a.negate();
}
// divisor's sign doesn't matter, as stated above.
// this is also BigInteger's behavior, but don't let us be
// dependent of a change in that.
Rational b = that;
if (thatSignum < 0) {
b = b.negate();
}
Rational r = a.remainderOrModulusOfPositive(b);
if (thisSignum < 0) {
r = r.negate();
}
return r;
}
/**
* Calculate the remainder of this Rational and a long fix number integer
* and return a new Rational.
*/
public Rational remainder(long that) {
return remainder(valueOf(that));
}
/**
* Calculate the modulus of this Rational and another Rational and return a
* new Rational.
* <p>
* The modulus result may be negative.
* <p>
* Modulus is based on round floor (towards negative). 5/3 == 1 + 2/3
* (modulus 2), 5/-3 == -2 + -1/-3 (modulus -1), -5/3 == -2 + 1/3 (modulus
* 1), -5/-3 == 1 + -2/-3 (modulus -2).
*/
// [Name: see class BigInteger.]
public Rational mod(Rational that) {
final int thisSignum = signum();
final int thatSignum = that.signum();
if (thatSignum == 0) {
throw new ArithmeticException("division by zero");
}
Rational a = this;
if (thisSignum < 0) {
a = a.negate();
}
Rational b = that;
if (thatSignum < 0) {
b = b.negate();
}
Rational r = a.remainderOrModulusOfPositive(b);
if (thisSignum < 0 && thatSignum < 0) {
r = r.negate();
} else if (thatSignum < 0) {
r = r.subtract(b);
} else if (thisSignum < 0) {
r = b.subtract(r);
}
return r;
}
/**
* Calculate the modulus of this Rational and a long fix number integer and
* return a new Rational.
*/
public Rational mod(long that) {
return mod(valueOf(that));
}
/**
* Signum. -1, 0, or 1.
* <p>
* If this Rational is negative, -1 is returned; if it is zero, 0 is
* returned; if it is positive, 1 is returned.
*/
// [Name: see class BigInteger.]
public int signum() {
// note: denominator is positive.
return numerator.signum();
}
/**
* Return a new Rational with the absolute value of this Rational.
* <p>
* If this Rational is zero or positive, [as an optimization] this Rational
* is returned.
*/
// [Name: see classes Math, BigInteger.]
public Rational abs() {
if (signum() >= 0) {
return this;
}
// optimization
if (isMinusOne()) {
return ONE;
}
// note: the calculated numerator/denominator are not denormalized,
// implicit normalize() would not be needed.
return new Rational(numerator.negate(), denominator);
}
/**
* Return a new Rational with the negative value of this.
*
*/
// [Name: see class BigInteger.]
public Rational negate() {
// optimization
if (isZero()) {
return ZERO;
}
// optimization
if (isOne()) {
return MINUS_ONE;
}
// optimization
if (isMinusOne()) {
return ONE;
}
// note: the calculated numerator/denominator are not denormalized,
// implicit normalize() would not be needed.
return new Rational(numerator.negate(), denominator);
}
/**
* Return a new Rational with the inverted (reciprocal) value of this.
*/
public Rational invert() {
if (isZero()) {
throw new ArithmeticException("division by zero");
}
// optimization
if (isOne() || isMinusOne()) {
return this;
}
// note: the calculated numerator/denominator are not denormalized in
// the sense of having common factors, but numerator might be negative
// (and become denominator below)
return new Rational(denominator, numerator);
}
/**
* Return the minimal value of two Rationals.
*/
// [Name: see classes Math, BigInteger.]
public Rational min(Rational that) {
return (compareTo(that) <= 0 ? this : that);
}
/**
* Return the minimal value of a Rational and a long fix number integer.
*/
public Rational min(long that) {
return min(valueOf(that));
}
/**
* Return the maximal value of two Rationals.
*/
// [Name: see classes Math, BigInteger.]
public Rational max(Rational that) {
return (compareTo(that) >= 0 ? this : that);
}
/**
* Return the maximum value of a Rational and a long fix number integer.
*/
public Rational max(long that) {
return max(valueOf(that));
}
/**
* Compare object for equality. Overwrites Object.equals(). Semantics is
* that only Rationals can be equal. Never throws.
* <p>
* Overwrites Object.equals(Object).
*/
@Override
public boolean equals(Object object) {
// optimization
if (object == this) {
return true;
}
// test includes null
if (!(object instanceof Rational)) {
return false;
}
final Rational that = (Rational) object;
// optimization
if (that.numerator == numerator && that.denominator == denominator) {
return true;
}
boolean result =
bigIntegerEquals(that.numerator, numerator) &&
bigIntegerEquals(that.denominator, denominator);
return result;
}
/**
* Hash code. Overwrites Object.hashCode().
* <p>
* Overwrites Object.hashCode().
*/
@Override
public int hashCode() {
// lazy init for optimization
if (hashCode == 0) {
hashCode = ((numerator.hashCode() + 1) * (denominator.hashCode() + 2));
}
return hashCode;
}
/**
* Compare this Rational to another Rational.
*/
public int compareTo(Rational that) {
// optimization
if (that == this) {
return 0;
}
final int thisSignum = signum();
final int thatSignum = that.signum();
if (thisSignum != thatSignum) {
return (thisSignum < thatSignum ? -1 : 1);
}
// optimization: both zero.
if (thisSignum == 0) {
return 0;
}
// note: both denominators are positive.
return bigIntegerMultiply(numerator, that.denominator)
.compareTo(
bigIntegerMultiply(that.numerator, denominator));
}
/**
* Compare this Rational to a BigInteger.
*/
public int compareTo(BigInteger that) {
return compareTo(valueOf(that));
}
/**
* Compare this Rational to a long.
*/
public int compareTo(long that) {
return compareTo(valueOf(that));
}
/**
* Compare this Rational to an Object.
* <p>
* Object can be Rational/BigInteger/Long/Integer/Short/Byte.
* <p>
* Implements Comparable.compareTo(Object) (JDK 1.2 and later).
* <p>
* A sample use is with a sorted map or set, e.g. TreeSet.
* <p>
* Only Rational/BigInteger/Long/Integer objects allowed, method will throw
* otherwise.
* <p>
* For backward compatibility reasons we keep compareTo(Object) additionally
* to compareTo(Rational). Comparable<Object> is declared to be
* implemented rather than Comparable<Rational>.
*/
public int compareTo(Object object) {
if (object instanceof Byte) {
return compareTo(((Byte) object).longValue());
}
if (object instanceof Short) {
return compareTo(((Short) object).longValue());
}
if (object instanceof Integer) {
return compareTo(((Integer) object).longValue());
}
if (object instanceof Long) {
return compareTo(((Long) object).longValue());
}
if (object instanceof BigInteger) {
return compareTo((BigInteger) object);
}
// now assuming that it's either 'instanceof Rational'
// or it'll throw a ClassCastException.
return compareTo((Rational) object);
}
/**
* Convert to BigInteger, by rounding.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public BigInteger bigIntegerValue() {
// [rounding step, possible loss of precision step]
return round().numerator;
}
/**
* Convert to long, by rounding and delegating to BigInteger. Implements
* Number.longValue(). As described with BigInteger.longValue(), this just
* returns the low-order [64] bits (losing information about magnitude and
* sign).
* <p>
* Possible loss of precision.
* <p>
* Overwrites Number.longValue().
*/
// @PrecisionLoss
@Override
public long longValue() {
// delegate to BigInteger.
// [rounding step, possible loss of precision step]
return bigIntegerValue().longValue();
}
/**
* Convert to int, by rounding and delegating to BigInteger. Implements
* Number.intValue(). As described with BigInteger.longValue(), this just
* returns the low-order [32] bits (losing information about magnitude and
* sign).
* <p>
* Possible loss of precision.
* <p>
* Overwrites Number.intValue().
*/
// @PrecisionLoss
@Override
public int intValue() {
// delegate to BigInteger.
// [rounding step, possible loss of precision step]
return bigIntegerValue().intValue();
}
/**
* Convert to double floating point value. Implements Number.doubleValue().
* <p>
* Possible loss of precision.
* <p>
* Overwrites Number.doubleValue().
*/
// @PrecisionLoss
@Override
public double doubleValue() {
return Double.longBitsToDouble(
// [rounding step, possible loss of precision step]
doubleBitsValue());
}
/**
* Convert to single floating point value. Implements Number.floatValue().
* <p>
* Note that Rational's [implicit] [default] rounding mode that applies
* [too] on indirect double to Rational to float rounding (round-half-up)
* may differ from what's done in a direct cast/coercion from double to
* float (e.g. round-half-even).
* <p>
* Possible loss of precision.
* <p>
* Overwrites Number.floatValue().
*/
// @PrecisionLoss
@Override
public float floatValue() {
return Float.intBitsToFloat(
// [rounding step, possible loss of precision step]
floatBitsValue());
}
/**
* Convert to IEEE 754 double float bits. The bits can be converted to a
* double by Double.longBitsToDouble().
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public long doubleBitsValue() {
// [rounding step, possible loss of precision step]
return (toIEEE754(this, DOUBLE_FLOAT_FRACTION_SIZE,
DOUBLE_FLOAT_EXPONENT_SIZE)[0]);
}
/**
* Convert to IEEE 754 single float bits. The bits can be converted to a
* float by Float.intBitsToFloat().
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public int floatBitsValue() {
// [rounding step, possible loss of precision step]
return (int) (toIEEE754(this, SINGLE_FLOAT_FRACTION_SIZE,
SINGLE_FLOAT_EXPONENT_SIZE)[0]);
}
/**
* Convert this Rational to IEEE 754 half float (binary16) bits.
* <p>
* As a short value is returned rather than a int, care has to be taken no
* unwanted sign expansion happens in subsequent operations, e.g. by masking
* (x.halfBitsValue()&0xffffl) or similar
* (x.halfBitsValue()==(short)0xbc00).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public short halfBitsValue() {
// [rounding step, possible loss of precision step]
return (short) (toIEEE754(this, HALF_FLOAT_FRACTION_SIZE,
HALF_FLOAT_EXPONENT_SIZE)[0]);
}
/**
* Convert this Rational to IEEE 754 quad float (binary128, quadruple) bits.
* <p>
* The bits are returned in an array of two longs, big endian (higher
* significant long first).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public long[] quadBitsValue() {
// [rounding step, possible loss of precision step]
return toIEEE754(this, QUAD_FLOAT_FRACTION_SIZE,
QUAD_FLOAT_EXPONENT_SIZE);
}
/**
* Convert this Rational to a long integer, either returning an exact result
* (no rounding or truncation needed), or throw an ArithmeticException.
*/
public long longValueExact() {
final long i = longValue();
// test is kind-of costly
if (!equals(valueOf(i))) {
throw new ArithmeticException(isInteger() ? "overflow"
: "rounding necessary");
}
return i;
}
/**
* Convert this Rational to an int, either returning an exact result (no
* rounding or truncation needed), or throw an ArithmeticException.
*/
public int intValueExact() {
final int i = intValue();
// test is kind-of costly
if (!equals(valueOf(i))) {
throw new ArithmeticException(isInteger() ? "overflow"
: "rounding necessary");
}
return i;
}
/**
* Convert this Rational to its constant (ONE, ZERO, MINUS_ONE) if possible.
*/
public static Rational valueOf(Rational value) {
if (value == null) {
throw new NumberFormatException("null");
}
// note: these tests are quite expensive,
// but they are minimized to a reasonable amount.
// priority in the tests: 1, 0, -1;
// two phase testing.
// cheap tests first.
// optimization
if (value == ONE) {
return value;
}
// optimization
if (value == ZERO) {
return value;
}
// optimization
if (value == MINUS_ONE) {
return value;
}
// more expensive tests later.
// optimization
if (value.equals(ONE)) {
return ONE;
}
// optimization
if (value.equals(ZERO)) {
return ZERO;
}
// optimization
if (value.equals(MINUS_ONE)) {
return MINUS_ONE;
}
// not a known constant
return value;
}
/**
* Build a Rational from a String.
* <p>
* [Roughly] equivalent to <CODE>new Rational(value)</CODE>.
*/
public static Rational valueOf(String value) {
if (value == null) {
throw new NumberFormatException("null");
}
// optimization
if (value.equals("0")) {
return ZERO;
}
// optimization
if (value.equals("1")) {
return ONE;
}
// optimization
if (value.equals("-1")) {
return MINUS_ONE;
}
return new Rational(value);
}
/**
* Build a Rational from a BigInteger.
* <p>
* Equivalent to <CODE>new Rational(value)</CODE>.
*/
public static Rational valueOf(BigInteger value) {
return new Rational(value);
}
/**
* Build a Rational from a long fix number integer.
* <p>
* [Roughly] equivalent to <CODE>new Rational(value)</CODE>.
* <p>
* As an optimization, commonly used numbers are returned as a reused
* constant.
*/
public static Rational valueOf(long value) {
// return the internal constants if possible
// optimization
// check whether it's outside int range.
// actually check a much narrower range, fitting the switch below.
if (value >= -16 && value <= 16) {
// note: test above needed to make the cast below safe
// jump table, for speed
switch ((int) value) {
case 0:
return ZERO;
case 1:
return ONE;
case -1:
return MINUS_ONE;
case 2:
return TWO;
case 10:
return TEN;
case 16:
return SIXTEEN;
}
}
return new Rational(value);
}
// note: byte/short/int implicitly upgraded to long,
// so strictly the additional implementations aren't needed;
// with unsigned (below) they however are
/**
* Build a Rational from an int.
*/
public static Rational valueOf(int value) {
return valueOf((long) value);
}
/**
* Build a Rational from a short.
*/
public static Rational valueOf(short value) {
return valueOf((long) value);
}
/**
* Build a Rational from a byte.
*/
public static Rational valueOf(byte value) {
return valueOf((long) value);
}
/**
* Build a Rational from a [IEEE 754] double [size/precision] floating point
* number.
*/
public static Rational valueOf(double value) {
return new Rational(value);
}
/**
* Build a Rational from a [IEEE 754] single [size/precision] floating point
* number.
*/
public static Rational valueOf(float value) {
return new Rational(value);
}
/**
* Build a Rational from an unsigned long fix number integer.
* <p>
* The resulting Rational is positive, i.e. the negative longs are mapped to
* 2**63..2**64 (exclusive).
*/
public static Rational valueOfUnsigned(long value) {
final Rational b = valueOf(value);
// mind the long being unsigned with highest significant
// bit (bit#63) set (interpreted as negative by valueOf(long))
return (b.isNegative() ? b.add(TWO_POWER_64) : b);
}
/**
* Build a Rational from an unsigned int.
* <p>
* The resulting Rational is positive, i.e. the negative ints are mapped to
* 2**31..2**32 (exclusive).
*/
public static Rational valueOfUnsigned(int value) {
// masking: suppress sign expansion
return valueOf(value & 0xffffffffl);
}
/**
* Build a Rational from an unsigned short.
* <p>
* The resulting Rational is positive, i.e. the negative shorts are mapped
* to 2**15..2**16 (exclusive).
*/
public static Rational valueOfUnsigned(short value) {
// masking: suppress sign expansion
return valueOf(value & 0xffffl);
}
/**
* Build a Rational from an unsigned byte.
* <p>
* The resulting Rational is positive, i.e. the negative bytes are mapped to
* 2**7..2**8 (exclusive).
*/
public static Rational valueOfUnsigned(byte value) {
// masking: suppress sign expansion
return valueOf(value & 0xffl);
}
/**
* Build a Rational from an IEEE 754 double size (double precision,
* binary64) floating point number represented as long.
* <p>
* An IEEE 754 double size (binary64) number uses 1 bit for the sign, 11
* bits for the exponent, and 52 bits (plus 1 implicit bit) for the
* fraction/mantissa. The minimal exponent encodes subnormal nubers; the
* maximal exponent encodes Infinities and NaNs.
* <p>
* Infinities and NaNs are not supported as Rationals.
* <p>
* The conversion from the bits to a Rational is done without loss of
* precision.
*/
public static Rational valueOfDoubleBits(long value) {
return fromIEEE754(new long[] { value, }, DOUBLE_FLOAT_FRACTION_SIZE,
DOUBLE_FLOAT_EXPONENT_SIZE);
}
/**
* Build a Rational from an IEEE 754 single size (single precision,
* binary32) floating point number represented as int.
* <p>
* An IEEE 754 single size (binary32) number uses 1 bit for the sign, 8 bits
* for the exponent, and 23 bits (plus 1 implicit bit) for the
* fraction/mantissa. The minimal exponent encodes subnormal nubers; the
* maximal exponent encodes Infinities and NaNs.
* <p>
* Infinities and NaNs are not supported as Rationals.
* <p>
* The conversion from the bits to a Rational is done without loss of
* precision.
*/
public static Rational valueOfFloatBits(int value) {
// [masking: suppress sign expansion, that leads to excess bits,
// that's not accepted by fromIeee754()]
return fromIEEE754(new long[] { value & 0xffffffffl, },
SINGLE_FLOAT_FRACTION_SIZE, SINGLE_FLOAT_EXPONENT_SIZE);
}
/**
* Build a Rational from an IEEE 754 half size (half precision, binary16)
* floating point number represented as short.
* <p>
* An IEEE 754 half size (binary16) number uses 1 bit for the sign, 5 bits
* for the exponent, and 10 bits (plus 1 implicit bit) for the
* fraction/mantissa. The minimal exponent encodes subnormal nubers; the
* maximal exponent encodes Infinities and NaNs.
* <p>
* Infinities and NaNs are not supported as Rationals.
* <p>
* The conversion from the bits to a Rational is done without loss of
* precision.
*/
public static Rational valueOfHalfBits(short value) {
// [masking: suppress sign expansion, that leads to excess bits,
// that's not accepted by fromIeee754()]
return fromIEEE754(new long[] { value & 0xffffl, },
HALF_FLOAT_FRACTION_SIZE, HALF_FLOAT_EXPONENT_SIZE);
}
/**
* Build a Rational from an IEEE 754 quad size (quadruple precision,
* binary128) floating point number represented as an array of two longs
* (big endian; higher significant long first).
* <p>
* An IEEE 754 quad size (binary128, quadruple) number uses 1 bit for the
* sign, 15 bits for the exponent, and 112 bits (plus 1 implicit bit) for
* the fraction/mantissa. The minimal exponent encodes subnormal nubers; the
* maximal exponent encodes Infinities and NaNs.
* <p>
* Infinities and NaNs are not supported as Rationals.
* <p>
* The conversion from the bits to a Rational is done without loss of
* precision.
*/
public static Rational valueOfQuadBits(long[] value) {
return fromIEEE754(value, QUAD_FLOAT_FRACTION_SIZE,
QUAD_FLOAT_EXPONENT_SIZE);
}
/**
* Compare two IEEE 754 quad size (quadruple precision, binary128) floating
* point numbers (each represented as two longs). NaNs are not considered;
* comparison is done by bits. [Convenience method.]
*/
// note: especially due the NaN issue commented above
// (a NaN maps to many bits representations),
// we call this method quadBitsEqual rather than quadEqual
public static boolean quadBitsEqual(long[] a, long[] b) {
if (a == null || b == null) {
throw new NumberFormatException("null");
}
if (a.length != 2 || b.length != 2) {
throw new NumberFormatException("not a quad");
}
return (a[1] == b[1] && a[0] == b[0]);
}
/**
* Round.
* <p>
* Round mode is one of {
* <code>ROUND_UP, ROUND_DOWN, ROUND_CEILING, ROUND_FLOOR,
* ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN,
* ROUND_HALF_CEILING, ROUND_HALF_FLOOR, ROUND_HALF_ODD,
* ROUND_UNNECESSARY, DEFAULT_ROUND_MODE (==ROUND_HALF_UP)</code> .
* <p>
* If rounding isn't necessary, i.e. this Rational is an integer, [as an
* optimization] this Rational is returned.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public Rational round(int roundMode) {
// optimization
// return self if we don't need to round, independent of rounding mode
if (isInteger()) {
return this;
}
return new Rational(
// [rounding step, possible loss of precision step]
roundToBigInteger(roundMode));
}
/**
* Round by default mode (ROUND_HALF_UP).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public Rational round() {
// [rounding step, possible loss of precision step]
return round(DEFAULT_ROUND_MODE);
}
/**
* Floor, round towards negative infinity.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public Rational floor() {
// [rounding step, possible loss of precision step]
return round(ROUND_FLOOR);
}
/**
* Ceiling, round towards positive infinity.
* <p>
* Possible loss of precision.
*/
// [Name: see class Math.]
// @PrecisionLoss
public Rational ceil() {
// [rounding step, possible loss of precision step]
return round(ROUND_CEILING);
}
/**
* Truncate, round towards zero.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public Rational truncate() {
// [rounding step, possible loss of precision step]
return round(ROUND_DOWN);
}
/**
* Integer part.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public Rational integerPart() {
// [rounding step, possible loss of precision step]
return round(ROUND_DOWN);
}
/**
* Fractional part.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public Rational fractionalPart() {
// this==ip+fp; sign(fp)==sign(this)
// [possible loss of precision step]
return subtract(integerPart());
}
/**
* Return an array of Rationals with both integer and fractional part.
* <p>
* Integer part is returned at offset 0; fractional part at offset 1.
*/
public Rational[] integerAndFractionalPart() {
// note: this duplicates fractionalPart() code, for speed.
final Rational[] pp = new Rational[2];
final Rational ip = integerPart();
pp[0] = ip;
pp[1] = subtract(ip);
return pp;
}
/**
* Clone the current Rational.
*/
@Override
public Rational clone() throws CloneNotSupportedException {
return (Rational) super.clone();
}
//
// PRIVATE METHODS
//
/**
* Normalize Rational. Denominator will be positive, numerator and
* denominator will have no common divisor. BigIntegers -1, 0, 1 will be set
* to constants for later comparison speed.
*/
private void normalize() {
// note: don't call anything that depends on a normalized this.
// i.e.: don't call most (or all) of the Rational methods.
if (numerator == null || denominator == null) {
throw new NumberFormatException("null");
}
// [these are typically cheap.]
int numeratorSignum = numerator.signum();
int denominatorSignum = denominator.signum();
// note: we don't throw on denominatorSignum==0. that'll be done
// elsewhere.
// if (denominatorSignum == 0) {
// throw new NumberFormatException("quotient zero");
// }
if (numeratorSignum == 0 && denominatorSignum == 0) {
// [typically not reached, due to earlier tests.]
// [both for speed]
numerator = BIG_INTEGER_ZERO;
denominator = BIG_INTEGER_ZERO;
return;
}
if (numeratorSignum == 0) {
denominator = BIG_INTEGER_ONE;
// [for speed]
numerator = BIG_INTEGER_ZERO;
return;
}
if (denominatorSignum == 0) {
// [typically not reached, due to earlier tests.]
numerator = BIG_INTEGER_ONE;
// [for speed]
denominator = BIG_INTEGER_ZERO;
return;
}
// optimization
// check the frequent case of denominator==1, for speed.
// note: this only covers the normalized-for-speed 1-case.
if (denominator == BIG_INTEGER_ONE) {
// [for [later] speed]
numerator = bigIntegerValueOf(numerator);
return;
}
// optimization
// check the symmetric case too, for speed.
// note: this only covers the normalized-for-speed 1-case.
if ((numerator == BIG_INTEGER_ONE || numerator == BIG_INTEGER_MINUS_ONE)
&& denominatorSignum > 0) {
// [for [later] speed]
denominator = bigIntegerValueOf(denominator);
return;
}
// setup torn apart for speed
BigInteger numeratorApart = numerator;
BigInteger denominatorApart = denominator;
if (denominatorSignum < 0) {
numerator = numerator.negate();
denominator = denominator.negate();
numeratorSignum = -numeratorSignum;
denominatorSignum = -denominatorSignum;
denominatorApart = denominator;
if (numeratorSignum > 0) {
numeratorApart = numerator;
}
}
else {
if (numeratorSignum < 0) {
numeratorApart = numerator.negate();
}
}
final BigInteger gcd = numeratorApart.gcd(denominatorApart);
// test: optimization (body: not)
if (!bigIntegerIsOne(gcd)) {
numerator = numerator.divide(gcd);
denominator = denominator.divide(gcd);
}
// for [later] speed, and normalization generally
numerator = bigIntegerValueOf(numerator);
denominator = bigIntegerValueOf(denominator);
}
/**
* Normalize Rational. [Convenience method to normalize(void).]
*/
private void normalizeFrom(BigInteger numerator, BigInteger denominator) {
this.numerator = numerator;
this.denominator = denominator;
normalize();
}
/**
* Normalize Rational. [Convenience method to normalize(void).]
*/
private void normalizeFrom(Rational that) {
if (that == null) {
throw new NumberFormatException("null");
}
normalizeFrom(that.numerator, that.denominator);
}
/**
* Check constraints on radixes. Radix may not be negative or less than two.
*/
private static void checkRadix(int radix) {
if (radix < 0) {
throw new NumberFormatException("radix negative");
}
if (radix < 2) {
throw new NumberFormatException("radix too small");
}
// note: we don't check for "radix too large";
// that's left to BigInteger.toString(radix)
// [i.e.: we don't really mind whether the underlying
// system supports base36, or base62, or even more]
}
/**
* Check some of the integer format constraints.
*/
private static void checkNumberFormat(String strNumber) {
// "x", "-x", "+x", "", "-", "+"
if (strNumber == null) {
throw new NumberFormatException("null");
}
// note: 'embedded sign' catches both-signs cases too.
final int p = strNumber.indexOf('+');
final int m = strNumber.indexOf('-');
final int pp = (p == -1 ? -1 : strNumber.indexOf('+', p + 1));
final int mm = (m == -1 ? -1 : strNumber.indexOf('-', m + 1));
if ((p != -1 && p != 0) || (m != -1 && m != 0) || pp != -1 || mm != -1) {
// embedded sign. this covers the both-signs case.
throw new NumberFormatException("embedded sign");
}
}
/**
* Check number format for fraction part.
*/
private static void checkFractionFormat(String strFraction) {
if (strFraction == null) {
throw new NumberFormatException("null");
}
if (strFraction.indexOf('+') != -1 || strFraction.indexOf('-') != -1) {
throw new NumberFormatException("sign in fraction");
}
}
/**
* Check number input for Java's string representations of doubles/floats
* that are unsupported: "NaN" and "Infinity" (with or without sign).
*/
private static void checkNaNAndInfinity(String strNumber, int radix) {
// the strings may actually be valid given a large enough radix
// (e.g. base 36), so limit the radix/check
if (radix > 16) {
return;
}
// [null and empty string check]
final int length = (strNumber == null ? 0 : strNumber.length());
if (length < 1) {
return;
}
// optimization (String.equals and even more String.equalsIgnoreCase
// are quite expensive, charAt and switch aren't)
// test for last character in strings below, both cases
switch (strNumber.charAt(length - 1)) {
case 'N':
case 'n':
case 'y':
case 'Y':
break;
default:
return;
}
if (strNumber.equalsIgnoreCase("NaN")
|| strNumber.equalsIgnoreCase("Infinity")
|| strNumber.equalsIgnoreCase("+Infinity")
|| strNumber.equalsIgnoreCase("-Infinity")) {
throw new NumberFormatException(strNumber);
}
}
/**
* Check constraints on radixes. [Convenience method to checkRadix(radix).]
*/
private static void checkRadixArgument(int radix) {
try {
checkRadix(radix);
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage());
}
}
/**
* Proxy to BigInteger.valueOf(). Speeds up comparisons by using constants.
*/
private static BigInteger bigIntegerValueOf(long number) {
// return the internal constants used for checks if possible.
// optimization
// check whether it's outside int range.
// actually check a much narrower range, fitting the switch below.
if (number >= -16 && number <= 16) {
// note: test above needed to make the cast below safe
// jump table, for speed
switch ((int) number) {
case 0:
return BIG_INTEGER_ZERO;
case 1:
return BIG_INTEGER_ONE;
case -1:
return BIG_INTEGER_MINUS_ONE;
case 2:
return BIG_INTEGER_TWO;
case -2:
return BIG_INTEGER_MINUS_TWO;
case 10:
return BIG_INTEGER_TEN;
case 16:
return BIG_INTEGER_SIXTEEN;
}
}
return BigInteger.valueOf(number);
}
/**
* Convert BigInteger to its constant if possible. Speeds up later
* comparisons by using constants.
*/
private static BigInteger bigIntegerValueOf(BigInteger number) {
// note: these tests are quite expensive,
// so they should be minimized to a reasonable amount.
// priority in the tests: 1, 0, -1;
// two phase testing.
// cheap tests first.
// optimization
if (number == BIG_INTEGER_ONE) {
return number;
}
// optimization
if (number == BIG_INTEGER_ZERO) {
// [typically not reached, since zero is handled specially.]
return number;
}
// optimization
if (number == BIG_INTEGER_MINUS_ONE) {
return number;
}
// more expensive tests later.
// optimization
if (number.equals(BIG_INTEGER_ONE)) {
return BIG_INTEGER_ONE;
}
// optimization
if (number.equals(BIG_INTEGER_ZERO)) {
// [typically not reached from normalize().]
return BIG_INTEGER_ZERO;
}
// optimization
if (number.equals(BIG_INTEGER_MINUS_ONE)) {
return BIG_INTEGER_MINUS_ONE;
}
// note: BIG_INTEGER_TWO et al. _not_ used for checks
// and therefore not replaced by constants_here_.
// this speeds up tests.
// not a known constant
return number;
}
/**
* Proxy to (new BigInteger()). Speeds up comparisons by using constants.
*/
private static BigInteger bigIntegerValueOf(String strNumber, int radix) {
// note: mind the radix.
// however, 0/1/-1 are not a problem.
// _often_ used strings (e.g. 0 for empty fraction and
// 1 for empty denominator), for speed.
// optimization
if (strNumber.equals("1")) {
return BIG_INTEGER_ONE;
}
// optimization
if (strNumber.equals("0")) {
return BIG_INTEGER_ZERO;
}
// optimization
if (strNumber.equals("-1")) {
// typically not reached, due to [private] usage pattern,
// i.e. the sign is cut before
return BIG_INTEGER_MINUS_ONE;
}
// note: BIG_INTEGER_TWO et al. _not_ used for checks
// and therefore even less valuable.
// there's a tradeoff between speeds of these tests
// and being consistent in using all constants
// (at least with the common radixes).
// optimization
if (radix > 2) {
if (strNumber.equals("2")) {
return BIG_INTEGER_TWO;
}
if (strNumber.equals("-2")) {
// typically not reached, due to [private] usage pattern,
// i.e. the sign is cut before
return BIG_INTEGER_MINUS_TWO;
}
}
// optimization
if (strNumber.equals("10")) {
switch (radix) {
case 2:
return BIG_INTEGER_TWO;
case 10:
return BIG_INTEGER_TEN;
case 16:
return BIG_INTEGER_SIXTEEN;
}
}
// optimization
if (radix == 10 && strNumber.equals("16")) {
return BIG_INTEGER_SIXTEEN;
}
// note: not directly finding the other [radix'] representations
// of 10 and 16 in the code above
// use the constants if possible
return bigIntegerValueOf(new BigInteger(strNumber, radix));
}
/**
* Proxy to BigInteger.equals(). For speed.
*/
private static boolean bigIntegerEquals(BigInteger n, BigInteger m) {
// optimization first test is for speed.
if (n == m) {
return true;
}
return n.equals(m);
}
/**
* Zero (0) value predicate. [For convenience and speed.]
*/
private static boolean bigIntegerIsZero(BigInteger n) {
// optimization first test is for speed.
if (n == BIG_INTEGER_ZERO) {
return true;
}
// well, this is also optimized for speed a bit.
return (n.signum() == 0);
}
/**
* One (1) value predicate. [For convenience and speed.]
*/
private static boolean bigIntegerIsOne(BigInteger n) {
// optimization first test is for speed.
if (n == BIG_INTEGER_ONE) {
return true;
}
return bigIntegerEquals(n, BIG_INTEGER_ONE);
}
/**
* Minus-one (-1) value predicate. [For convenience and speed.]
*/
private static boolean bigIntegerIsMinusOne(BigInteger n) {
// optimization
// first test is for speed.
if (n == BIG_INTEGER_MINUS_ONE) {
return true;
}
return bigIntegerEquals(n, BIG_INTEGER_MINUS_ONE);
}
/**
* Negative value predicate.
*/
private static boolean bigIntegerIsNegative(BigInteger n) {
return (n.signum() < 0);
}
/**
* Proxy to BigInteger.multiply().
*
* For speed. The more common cases of integers (denominator == 1) are
* optimized.
*/
private static BigInteger bigIntegerMultiply(BigInteger n, BigInteger m) {
// optimization: one or both operands are zero.
if (bigIntegerIsZero(n) || bigIntegerIsZero(m)) {
return BIG_INTEGER_ZERO;
}
// optimization: second operand is one (i.e. neutral element).
if (bigIntegerIsOne(m)) {
return n;
}
// optimization: first operand is one (i.e. neutral element).
if (bigIntegerIsOne(n)) {
return m;
}
// optimization
if (bigIntegerIsMinusOne(m)) {
// optimization
if (bigIntegerIsMinusOne(n)) {
// typically not reached due to earlier test(s)
return BIG_INTEGER_ONE;
}
return n.negate();
}
// optimization
if (bigIntegerIsMinusOne(n)) {
// [m is not -1, see test above]
return m.negate();
}
// default case. [this would handle all cases.]
return n.multiply(m);
}
/**
* Proxy to BigInteger.pow(). For speed.
*/
private static BigInteger bigIntegerPower(BigInteger n, int exponent) {
// generally expecting exponent>=0
// (there's nor much use in inverting in the integer domain)
// the checks for exponent<0 below are done all the same
// optimization jump table, for speed.
switch (exponent) {
case 0:
if (bigIntegerIsZero(n)) {
// typically not reached, due to earlier test / [private] usage
// pattern
throw new ArithmeticException("zero exp zero");
}
return BIG_INTEGER_ONE;
case 1:
return n;
}
// optimization
if (bigIntegerIsZero(n) && exponent > 0) {
// note: exponent==0 already handled above
// typically not reached, due to earlier test
return BIG_INTEGER_ZERO;
}
// optimization
if (bigIntegerIsOne(n)) {
return BIG_INTEGER_ONE;
}
// optimization
if (bigIntegerIsMinusOne(n)) {
return (exponent % 2 == 0 ? BIG_INTEGER_ONE : BIG_INTEGER_MINUS_ONE);
}
return n.pow(exponent);
}
/**
* Binary logarithm rounded towards floor (towards negative infinity).
*/
// @PrecisionLoss
private static int bigIntegerLogarithm2(BigInteger n) {
if (bigIntegerIsZero(n)) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of zero");
}
if (bigIntegerIsNegative(n)) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of negative number");
}
// take this as a start
// (don't wholly rely on bitLength() having the same meaning as log2)
int exponent = n.bitLength() - 1;
if (exponent < 0) {
exponent = 0;
}
BigInteger p = BIG_INTEGER_TWO.pow(exponent + 1);
while (n.compareTo(p) >= 0) {
// typically not reached
p = p.multiply(BIG_INTEGER_TWO);
exponent++;
}
p = p.divide(BIG_INTEGER_TWO);
while (n.compareTo(p) < 0) {
// typically not reached
p = p.divide(BIG_INTEGER_TWO);
exponent--;
}
// [possible loss of precision step]
return exponent;
}
/**
* Proxy to BigInteger.toString(int radix).
*/
private static String stringValueOf(BigInteger n, int radix) {
return n.toString(radix);
}
/**
* Proxy to stringValueOf(bigIntegerValueOf(long), radix); take the same
* route to format [long/bigint] integer numbers [despite the overhead].
*/
private static String stringValueOf(long n, int radix) {
return stringValueOf(bigIntegerValueOf(n), radix);
}
/**
* Convert a IEEE 754 floating point number (of different sizes, as array of
* longs, big endian) to a Rational.
*/
private static Rational fromIEEE754(long[] value0, int fractionSize,
int exponentSize) {
if (value0 == null) {
throw new NumberFormatException("null");
}
// note: the long(s) in the input array are considered unsigned,
// so expansion operations (to e.g. Rational) and [right-] shift
// operations
// (unlike assignment, equality-test, narrowing, and/or operations)
// must be appropriately chosen
Rational fraction0 = ZERO;
// start at the little end of the [bigendian] input
int i = value0.length - 1;
while (fractionSize >= 64) {
if (i < 0) {
throw new NumberFormatException("not enough bits");
}
// mind the long (value0[i]) being unsigned
fraction0 = fraction0.add(valueOfUnsigned(value0[i])).divide(
TWO_POWER_64);
fractionSize -= 64;
i--;
}
// the rest must now fit into value0[0] (a long),
// i.e. we don't support exponentSize > 63 at the moment;
// as the power() method accepts ints (not longs),
// the restriction is actually even on <= 31 bits
if (i < 0) {
throw new NumberFormatException("no bits");
}
if (i > 0) {
throw new NumberFormatException("excess bits");
}
long value = value0[0];
// [fractionSize [now is] < 64 by loop above]
final long fractionMask = ((long) 1 << fractionSize) - 1;
final long rawFraction = value & fractionMask;
value >>>= fractionSize;
// [exponentSize < 32 by [private] usage pattern; rawExponent < 2**31]
final int exponentMask = (1 << exponentSize) - 1;
final int exponentBias = (1 << (exponentSize - 1)) - 1;
final int rawExponent = (int) value & exponentMask;
value >>>= exponentSize;
final int signSize = 1;
final int signMask = (1 << signSize) - 1; // 1
final int rawSign = (int) value & signMask;
value >>>= signSize;
if (value != 0) {
throw new NumberFormatException("excess bits");
}
// check for Infinity and NaN (IEEE 754 rawExponent at its maximum)
if (rawExponent == exponentMask) {
// (no fraction bits means one of the Infinities; else NaN)
throw new NumberFormatException(rawFraction == 0
&& fraction0.isZero() ? (rawSign == 0 ? "Infinity"
: "-Infinity") : "NaN");
}
// optimization -- avoids power() calculation below
// (isZero and zero multiply) are cheap
// check for zero (IEEE 754 rawExponent zero and no fraction bits)
if (rawExponent == 0 && rawFraction == 0 && fraction0.isZero()) {
return ZERO;
}
// handle subnormal numbers too (with rawExponent==0)
// [fractionSize [still is] < 64]
final long mantissa1 = rawFraction
| (rawExponent == 0 ? (long) 0 : (long) 1 << fractionSize);
// mind mantissa1 being unsigned
final Rational mantissa = fraction0.add(valueOfUnsigned(mantissa1));
// (subnormal numbers; exponent is one off)
// [rawExponent < 2**31; exponentBias < 2**30]
final int exponent = rawExponent - exponentBias
+ (rawExponent == 0 ? 1 : 0) - fractionSize;
final int sign = (rawSign == 0 ? 1 : -1);
return valueOf(2).pow(exponent).multiply(mantissa).multiply(sign);
}
/**
* Convert a Rational to a IEEE 754 floating point number (of different
* sizes, as array of longs, big endian).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
private static long[] toIEEE754(Rational value, int fractionSize,
int exponentSize) {
if (value == null) {
throw new NumberFormatException("null");
}
// [needed size: fractionSize+exponentSize+1; round up bits to a
// multiple of 64]
final long[] out0 = new long[(fractionSize + exponentSize + 1 + (64 - 1)) / 64];
if (value.isZero()) {
// 0.0
// note: as we don't keep a sign with our ZERO,
// we never return IEEE 754 -0.0 here
for (int j = 0; j < out0.length; j++) {
out0[j] = 0;
}
return out0;
}
final boolean negate = value.isNegative();
if (negate) {
value = value.negate();
}
// need to scale to this to get the full mantissa
int exponent = fractionSize;
final Rational lower = valueOf(2).pow(fractionSize);
final Rational upper = lower.multiply(2);
// optimization, and a good guess (but not exact in all cases)
final int scale = lower.divide(value).logarithm2();
value = value.multiply(valueOf(2).pow(scale));
exponent -= scale;
while (value.compareTo(lower) < 0) {
// [typically done zero or one time]
value = value.multiply(2);
exponent--;
}
while (value.compareTo(upper) >= 0) {
// [typically not reached]
value = value.divide(2);
exponent++;
}
// [rounding step, possible loss of precision step]
BigInteger mantissa = value.bigIntegerValue();
// adjust after [unfortunate] mantissa rounding
if (upper.compareTo(mantissa) <= 0) {
mantissa = mantissa.divide(BIG_INTEGER_TWO);
exponent++;
}
// start [to fill] at the little end of the [bigendian] output
int i = out0.length - 1;
int fractionSize1 = fractionSize;
while (fractionSize1 >= 64) {
final BigInteger[] divrem = mantissa
.divideAndRemainder(BIG_INTEGER_TWO_POWER_64);
// [according to BigInteger javadoc] this takes the least
// significant 64 bits;
// i.e. in this case the long is considered unsigned, as we want it
out0[i] = divrem[1].longValue();
fractionSize1 -= 64;
mantissa = divrem[0];
i--;
}
// the rest must now fit into out0[0]
if (i < 0) {
// not reached
throw new NumberFormatException("too many bits");
}
if (i > 0) {
// not reached
throw new NumberFormatException("not enough bits");
}
long fraction = mantissa.longValue();
final int exponentBias = (1 << (exponentSize - 1)) - 1;
exponent += exponentBias;
final int maximalExponent = (1 << exponentSize) - 1;
if (exponent >= maximalExponent) {
// overflow
// throw new NumberFormatException("overflow");
// [positive or negative] infinity
exponent = maximalExponent;
fraction = 0;
for (int j = 1; j < out0.length; j++) {
out0[j] = 0;
}
// [keep sign]
} else if (exponent <= 0) {
// handle subnormal numbers too
// [with know loss of precision]
// drop one bit, while keeping the exponent
int s = 1;
// [need not shift more than fractionSize]
final int n = (-exponent > fractionSize ? fractionSize : -exponent);
s += n;
exponent += n;
// [possible loss of precision step]
fraction = shiftrx(fraction, out0, 1, s);
boolean zero = (fraction == 0);
for (int j = 1; zero && j < out0.length; j++) {
zero = (out0[j] == 0);
}
if (zero) {
// underflow
// throw new NumberFormatException("underflow");
// 0.0 or -0.0; i.e.: keep sign
exponent = 0;
// [nonzero == 0 implies the rest of the fraction is zero as
// well]
}
}
// cut implied most significant bit
// [unless with subnormal numbers]
if (exponent != 0) {
fraction &= ~((long) 1 << fractionSize1);
}
long out = 0;
out |= (negate ? 1 : 0);
out <<= exponentSize;
out |= exponent;
out <<= fractionSize1;
out |= fraction;
out0[0] = out;
return out0;
}
/**
* Shift right, while propagating shifted bits (long[] is bigendian).
*/
private static long shiftrx(long a, long[] b, int boff, int n) {
while (n > 0) {
final int n2 = (n < 63 ? n : 63);
final long m = ((long) 1 << n2) - 1;
long c = a & m;
a >>>= n2;
for (int i = boff; i < b.length; i++) {
final long t = b[i] & m;
b[i] >>>= n2;
b[i] |= (c << (64 - n2));
c = t;
}
n -= n2;
}
return a;
}
/**
* Fixed dot-format "[-]i.f" string representation, with a precision.
* <p>
* Precision may be negative, in which case the rounding affects digits left
* of the dot, i.e. the integer part of the number, as well.
* <p>
* The exponentFormat parameter allows for shorter [intermediate] string
* representation, an optimization, e.g. used with toStringExponent.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
private String toStringDot(int precision, int radix, boolean exponentFormat) {
checkRadixArgument(radix);
Rational scaleValue = new Rational(bigIntegerPower(
bigIntegerValueOf(radix), (precision < 0 ? -precision
: precision)));
if (precision < 0) {
scaleValue = scaleValue.invert();
}
// default round mode.
// [rounding step, possible loss of precision step]
Rational n = multiply(scaleValue).round();
final boolean negt = n.isNegative();
if (negt) {
n = n.negate();
}
String s = n.toString(radix);
if (exponentFormat) {
// note that this is _not_ the scientific notation
// (one digit left of the dot exactly),
// but some intermediate representation suited for post processing
// [leaving away the left/right padding steps
// is more performant in time and memory space]
s = s + "E" + stringValueOf(-precision, radix);
}
else {
if (precision >= 0) {
// left-pad with '0'
while (s.length() <= precision) {
s = "0" + s;
}
final int dot = s.length() - precision;
final String i = s.substring(0, dot);
final String f = s.substring(dot);
s = i;
if (f.length() > 0) {
s = s + "." + f;
}
}
else {
if (!s.equals("0")) {
// right-pad with '0'
for (int i = -precision; i > 0; i--) {
s = s + "0";
}
}
}
}
// add sign
if (negt) {
s = "-" + s;
}
return s;
}
/**
* Transform a [intermediate] dot representation to an exponent-format
* representation.
*/
private static String toExponentRepresentation(String s, int radix) {
// skip '+'
if (s.length() > 0 && s.charAt(0) == '+') {
// typically not reached, due to [private] usage pattern
s = s.substring(1);
}
// handle '-'
boolean negt = false;
if (s.length() > 0 && s.charAt(0) == '-') {
negt = true;
s = s.substring(1);
}
// skip initial zeros
while (s.length() > 0 && s.charAt(0) == '0') {
s = s.substring(1);
}
// check for and handle exponent
// handle only upper case 'E' (we know we use that in earlier steps);
// this allows any base using lower case characters
int exponent0 = 0;
final int exp = s.indexOf('E');
if (exp != -1) {
final String se = s.substring(exp + 1);
s = s.substring(0, exp);
exponent0 = (new Rational(se, radix)).intValueExact();
}
String si, sf;
int exponent;
final int dot = s.indexOf('.');
if (dot != -1) {
if (dot == 0) {
// possibly more insignificant digits
s = s.substring(1);
exponent = -1;
while (s.length() > 0 && s.charAt(0) == '0') {
s = s.substring(1);
exponent--;
}
if (s.equals("")) {
// typically not reached, due to [private] usage pattern
return "0";
}
// first significant digit
si = s.substring(0, 1);
sf = s.substring(1);
}
else {
// initial [significant] digit
si = s.substring(0, 1);
sf = s.substring(1, dot);
exponent = sf.length();
sf = sf + s.substring(dot + 1);
}
}
else {
// [note that we just cut the zeros above]
if (s.equals("")) {
return "0";
}
// initial [significant] digit
si = s.substring(0, 1);
// rest
sf = s.substring(1);
exponent = sf.length();
}
exponent += exponent0;
// drop trailing zeros
while (sf.length() > 0 && sf.charAt(sf.length() - 1) == '0') {
sf = sf.substring(0, sf.length() - 1);
}
s = si;
if (!sf.equals("")) {
s = s + "." + sf;
}
if (exponent != 0) {
s = s + "E" + stringValueOf(exponent, radix);
}
if (negt) {
s = "-" + s;
}
return s;
}
/**
* Return binary logarithm rounded towards floor (towards negative
* infinity).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
private int logarithm2() {
if (isZero()) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of zero");
}
if (isNegative()) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of negative number");
}
final boolean inverted = (compareTo(ONE) < 0);
final Rational a = (inverted ? invert() : this);
// [possible loss of precision step]
final int log = bigIntegerLogarithm2(a.bigIntegerValue());
return (inverted ? -(log + 1) : log);
}
/**
* Return logarithm rounded towards floor (towards negative infinity).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
private int logarithm(int base) {
// optimization
if (base == 2) {
return logarithm2();
}
if (isZero()) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of zero");
}
if (isNegative()) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of negative number");
}
// if (base < 2) {
// // [typically not reached, due to [private] usage pattern]
// throw new ArithmeticException("bad base");
// }
if (base < 0) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("negative base");
}
if (base < 2) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("base too small");
}
final boolean inverted = (compareTo(ONE) < 0);
Rational a = (inverted ? invert() : this);
final Rational bbase = valueOf(base);
// optimization -- we could start from n=0
// initial guess
// [base 2 handled earlier]
// [unusual bases are handled a bit less performant]
final Rational lbase = (base == 10 ? LOGARITHM_TEN_GUESS
: base == 16 ? LOGARITHM_SIXTEEN : valueOf(ilog2(base)));
int n = valueOf(a.logarithm2()).divide(lbase).intValue();
a = a.divide(bbase.pow(n));
// note that these steps are needed anyway:
// LOGARITHM_TEN_GUESS above e.g. is (as the name suggests)
// a guess only (since most logarithms usually can't be expressed
// as rationals generally); odd bases or off even worse
while (a.compareTo(bbase) >= 0) {
a = a.divide(bbase);
n++;
}
while (a.compareTo(ONE) < 0) {
a = a.multiply(bbase);
n--;
}
// [possible loss of precision step]
return (inverted ? -(n + 1) : n);
}
/**
* Return binary logarithm of an int.
*/
private static int ilog2(int n) {
if (n == 0) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of zero");
}
if (n < 0) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of negative number");
}
int i = 0;
// as this method is used in the context of [small] bases/radixes,
// we expect less than 8 iterations at most, so no need to optimize
while (n > 1) {
n /= 2;
i++;
}
return i;
}
/**
* Remainder or modulus of non-negative values. Helper function to
* remainder() and modulus().
*/
private Rational remainderOrModulusOfPositive(Rational that) {
final int thisSignum = signum();
final int thatSignum = that.signum();
if (thisSignum < 0 || thatSignum < 0) {
// typically not reached, due to [private] usage pattern
throw new IllegalArgumentException("negative values(s)");
}
if (thatSignum == 0) {
// typically not reached, due to [private] usage pattern
throw new ArithmeticException("division by zero");
}
// optimization
if (thisSignum == 0) {
return ZERO;
}
return new Rational(bigIntegerMultiply(numerator, that.denominator)
.remainder(bigIntegerMultiply(denominator, that.numerator)),
bigIntegerMultiply(denominator, that.denominator));
}
/**
* Round to BigInteger helper function. Internally used.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
private BigInteger roundToBigInteger(int roundMode) {
// note: remainder and its duplicate are calculated for all cases.
BigInteger numerator = this.numerator;
final BigInteger denominator = this.denominator;
final int signum = numerator.signum();
// optimization
if (signum == 0) {
// [typically not reached due to earlier test for integerp]
return BIG_INTEGER_ZERO;
}
// keep info on the sign
final boolean isPositive = (signum > 0);
// operate on positive values
if (!isPositive) {
numerator = numerator.negate();
}
final BigInteger[] divrem = numerator.divideAndRemainder(denominator);
BigInteger dv = divrem[0];
final BigInteger r = divrem[1];
// return if we don't need to round, independent of rounding mode
if (bigIntegerIsZero(r)) {
// [typically not reached since remainder is not zero
// with normalized that are not integerp]
if (!isPositive) {
dv = dv.negate();
}
return dv;
}
boolean up = false;
final int comp = r.multiply(BIG_INTEGER_TWO).compareTo(denominator);
switch (roundMode) {
// Rounding mode to round away from zero.
case ROUND_UP:
up = true;
break;
// Rounding mode to round towards zero.
case ROUND_DOWN:
up = false;
break;
// Rounding mode to round towards positive infinity.
case ROUND_CEILING:
up = isPositive;
break;
// Rounding mode to round towards negative infinity.
case ROUND_FLOOR:
up = !isPositive;
break;
// Rounding mode to round towards "nearest neighbor" unless both
// neighbors are equidistant, in which case round up.
case ROUND_HALF_UP:
up = (comp >= 0);
break;
// Rounding mode to round towards "nearest neighbor" unless both
// neighbors are equidistant, in which case round down.
case ROUND_HALF_DOWN:
up = (comp > 0);
break;
case ROUND_HALF_CEILING:
up = (comp != 0 ? comp > 0 : isPositive);
break;
case ROUND_HALF_FLOOR:
up = (comp != 0 ? comp > 0 : !isPositive);
break;
// Rounding mode to round towards the "nearest neighbor" unless both
// neighbors are equidistant, in which case, round towards the even
// neighbor.
case ROUND_HALF_EVEN:
up = (comp != 0 ? comp > 0 : !bigIntegerIsZero(dv
.remainder(BIG_INTEGER_TWO)));
break;
case ROUND_HALF_ODD:
up = (comp != 0 ? comp > 0 : bigIntegerIsZero(dv
.remainder(BIG_INTEGER_TWO)));
break;
// Rounding mode to assert that the requested operation has an exact
// result, hence no rounding is necessary. If this rounding mode is
// specified on an operation that yields an inexact result, an
// ArithmeticException is thrown.
case ROUND_UNNECESSARY:
if (!bigIntegerIsZero(r)) {
throw new ArithmeticException("rounding necessary");
}
// [typically not reached due to earlier test for integerp]
up = false;
break;
default:
throw new IllegalArgumentException("unsupported rounding mode");
}
if (up) {
dv = dv.add(BIG_INTEGER_ONE);
}
if (!isPositive) {
dv = dv.negate();
}
// [rounding step, possible loss of precision step]
return dv;
}
}
|
src/main/java/com/sri/ai/util/math/Rational.java
|
/*
* Copyright (c) 2013, SRI International
* All rights reserved.
* Licensed under the The BSD 3-Clause License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the aic-util 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.
*/
/* <b>Note:</b> Closely based on freely available version 'BigRational.java', developed
* by Eric Laroche, which can be found at: <a
* href="http://www.lrdev.com/lr/java/">http://www.lrdev.com/lr/java/</a>
* BigRational.java -- dynamically sized big rational numbers.
**
** Copyright (C) 2002-2010 Eric Laroche. All rights reserved.
**
** @author Eric Laroche <[email protected]>
** @version @(#)$Id: BigRational.java,v 1.3 2010/03/24 20:11:34 laroche Exp $
**
** This program is free software;
** you can redistribute it and/or modify it.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
**
*/
package com.sri.ai.util.math;
import java.math.BigInteger;
import com.google.common.annotations.Beta;
/**
* Rational implements dynamically sized arbitrary precision immutable rational
* numbers.<br>
* <br>
*
* <p>
* Dynamically sized means that (provided enough memory) the Rational numbers
* can't overflow (nor underflow); this characteristic is different from Java's
* data types int and long, but common with BigInteger (which implements only
* integer numbers, i.e. no fractions) and BigDecimal (which only implements
* precisely rational numbers with denominators that are products of 2 and 5
* [and implied 10]). Arbitrary precision means that there is no loss of
* precision with common arithmetic operations such as addition, subtraction,
* multiplication, and division (BigDecimal loses precision with division, if
* factors other than 2 or 5 are involved). [Doubles and floats can overflow and
* underflow, have a limited precision, and only implement precisely rationals
* with a denominator that is a power of 2.]
*
* <p>
* Rational provides most operations needed in rational number space
* calculations, including addition, subtraction, multiplication, division,
* integer power, remainder/modulus, comparison, and different roundings.
*
* <p>
* Rational provides conversion methods to and from the native types long, int,
* short, and byte (including support for unsigned values), double (binary64),
* float (binary32), quad (binary128, quadruple), half (binary16), and
* BigInteger. Rational can parse and print many string representations:
* rational, dot notations, with exponent, even mixtures thereof, and supports
* different radixes/bases (2 to typically 36 [limited by BigInteger parsing
* implementation]).
*
* <p>
* Rational uses java.math.BigInteger (JDK 1.1 and later) internally.
*
* <p>
* Binary operations (e.g. add, multiply) calculate their results from a
* Rational object ('this') and one [Rational or long] argument, returning a new
* immutable Rational object. Both the original object and the argument are left
* unchanged (hence immutable). Unary operations (e.g. negate, invert) calculate
* their result from the Rational object ('this'), returning a new immutable
* Rational object. The original object is left unchanged.
*
* <p>
* Most operations are precise (i.e. without loss of precision); exceptions are
* the conversion methods to limited precision types (doubleValue, floatValue),
* rounding (round), truncation (bigIntegerValue, floor, ceiling, truncate), as
* well as obviously the printing methods that include a precision parameter
* (toStringDot, toStringDotRelative, toStringExponent).
*
* <p>
* Rational doesn't provide a notion of "infinity" ([+-]Infinity) and
* "not a number" (NaN); IEEE 754 floating point Infinity and NaN are rejected
* (throwing a NumberFormatException). Operations such as 0/0 result in an
* ArithmeticException.
*
* <p>
* Rational internally uses private proxy functions for BigInteger
* functionality, including scanning and multiplying, to enhance speed and to
* realize fast checks for common values (1, 0, etc.).
*
* <p>
* Constructor samples: normal rational form, abbreviated form, fixed point
* form, abbreviated fixed point form, [exponential] floating point form,
* different radixes/bases different from 10, doubles/floats:
*
* <pre>
* Rational("-21/35") : rational -3/5
* Rational("/3") : rational 1/3
* Rational("3.4") : rational 17/5
* Rational(".7") : 0.7, rational 7/10
* Rational("-65.4E-3") : -327/5000
* Rational("f/37", 0x10) : 3/11
* Rational("f.37", 0x10) : 3895/256
* Rational("-dcba.efgh", 23) : -46112938320/279841
* Rational("1011101011010110", 2) : 47830
* Rational(StrictMath.E) : 6121026514868073/2251799813685248
* Rational((float)StrictMath.E) : 2850325/1048576
* </pre>
*
* <p>
* Also accepted are denormalized representations such as:
*
* <pre>
* Rational("2.5/-3.5"): -5/7
* Rational("12.34E-1/-56.78E-1") : -617/2839
* </pre>
*
* <p>
* Printing: rational form, fixed point (dot) forms with different absolute
* precisions (including negative precision), with relative precisions,
* exponential form, different radix:
*
* <pre>
* Rational("1234.5678") : "6172839/5000"
* Rational("1234.5678").toStringDot(6) : "1234.567800"
* Rational("1234.5678").toStringDot(2) : "1234.57"
* Rational("1234.5678").toStringDot(-2) : "1200"
* Rational("1234.5678").toStringDotRelative(6) : "1234.57"
* Rational("0.00012345678").toStringDotRelative(3) : "0.000123"
* Rational("1234.5678").toStringExponent(2) : "1.2E3"
* Rational("1011101011010110", 2).toString(0x10) : "bad6"
* </pre>
*
* <p>
* Usage: Rational operations can be conveniently chained (sample from Rational
* internal conversion from IEEE 754 bits):
*
* <pre>
* Rational.valueOf(2).power(exponent)
* .multiply(fraction.add(Rational.valueOfUnsigned(mantissa)))
* .multiply(sign);
* </pre>
*
* @author Eric Laroche <[email protected]>
* @author oreilly
*
*/
@Beta
public class Rational extends Number implements Cloneable, Comparable<Object> {
//
// PRIVATE CONSTANTS
// Note: Need to declare first as some of the public
// constants are dependent on these being initialized beforehand.
private static final long serialVersionUID = 1L;
//
// Note: following constants can't be constructed using
// Rational.bigIntegerValueOf().
// That one _uses_ the constants (avoid circular dependencies).
/**
* Constant internally used, for convenience and speed. Used as zero
* numerator. Used for fast checks.
*/
private final static BigInteger BIG_INTEGER_ZERO = BigInteger.valueOf(0);
/**
* Constant internally used, for convenience and speed. Used as neutral
* denominator. Used for fast checks.
*/
private final static BigInteger BIG_INTEGER_ONE = BigInteger.valueOf(1);
/**
* Constant internally used, for convenience and speed. Used for fast
* checks.
*/
private final static BigInteger BIG_INTEGER_MINUS_ONE = BigInteger
.valueOf(-1);
/**
* Constant internally used, for convenience and speed. Used in rounding
* zero numerator. _Not_ used for checks.
*/
private final static BigInteger BIG_INTEGER_TWO = BigInteger.valueOf(2);
/**
* Constant internally used, for convenience and speed. _Not_ used for
* checks.
*/
private final static BigInteger BIG_INTEGER_MINUS_TWO = BigInteger
.valueOf(-2);
/**
* Constant internally used, for convenience and speed. Corresponds to
* DEFAULT_RADIX, used in reading, scaling and printing. _Not_ used for
* checks.
*/
private final static BigInteger BIG_INTEGER_TEN = BigInteger.valueOf(10);
/**
* Constant internally used, for convenience and speed. Used in reading,
* scaling and printing. _Not_ used for checks.
*/
private final static BigInteger BIG_INTEGER_SIXTEEN = BigInteger
.valueOf(16);
/**
* The constant two to the power of 64 (18446744073709551616). Used is
* slicing larger [than double size] IEEE 754 values.
*/
private final static BigInteger BIG_INTEGER_TWO_POWER_64 = BigInteger
.valueOf(2).pow(64);
// some more constants, often used as radixes/bases
/**
* The constant two (2).
*/
private final static Rational TWO = new Rational(2);
/**
* The constant ten (10).
*/
private final static Rational TEN = new Rational(10);
/**
* The constant sixteen (16).
*/
private final static Rational SIXTEEN = new Rational(16);
/**
* The constant two to the power of 64 (18446744073709551616). Used is
* slicing larger [than double size] IEEE 754 values.
*/
private final static Rational TWO_POWER_64 = new Rational(
BIG_INTEGER_TWO_POWER_64);
/**
* Constant internally used, for speed.
*/
// calculated via Rational((float)(StrictMath.log(10)/StrictMath.log(2)))
// note: don't use float/double operations in this code though (except for
// test())
private final static Rational LOGARITHM_TEN_GUESS = new Rational(1741647,
524288);
/**
* Constant internally used, for speed.
*/
private final static Rational LOGARITHM_SIXTEEN = new Rational(4);
/**
* Number of explicit fraction bits in an IEEE 754 double (binary64) float,
* 52.
*/
private final static int DOUBLE_FLOAT_FRACTION_SIZE = 52;
/**
* Number of exponent bits in an IEEE 754 double (binary64) float, 11.
*/
private final static int DOUBLE_FLOAT_EXPONENT_SIZE = 11;
/**
* Number of explicit fraction bits in an IEEE 754 single (binary32) float,
* 23.
*/
private final static int SINGLE_FLOAT_FRACTION_SIZE = 23;
/**
* Number of exponent bits in an IEEE 754 single (binary32) float, 8.
*/
private final static int SINGLE_FLOAT_EXPONENT_SIZE = 8;
/**
* Number of explicit fraction bits in an IEEE 754 half (binary16) float,
* 10.
*/
private final static int HALF_FLOAT_FRACTION_SIZE = 10;
/**
* Number of exponent bits in an IEEE 754 half (binary16) float, 5.
*/
private final static int HALF_FLOAT_EXPONENT_SIZE = 5;
/**
* Number of explicit fraction bits in an IEEE 754 quad (binary128,
* quadruple) float, 112.
*/
private final static int QUAD_FLOAT_FRACTION_SIZE = 112;
/**
* Number of exponent bits in an IEEE 754 quad (binary128, quadruple) float,
* 15.
*/
private final static int QUAD_FLOAT_EXPONENT_SIZE = 15;
//
//
/**
* Numerator. Numerator may be negative. Numerator may be zero, in which
* case m_q must be one. [Conditions are put in place by normalize().]
*/
private BigInteger numerator;
/**
* Denominator (quotient). Denominator is never negative and never zero.
* [Conditions are put in place by normalize().]
*/
private BigInteger denominator;
// optimization, as instances are immmutable only
// calculate once when needed
private int hashCode = 0;
//
// PUBLIC CONSTANTS
//
/**
* Default radix, used in string printing and scanning, 10 (i.e. decimal by
* default).
*/
public final static int DEFAULT_RADIX = 10;
// Note: don't use valueOf() here; valueOf implementations use the constants
/**
* The constant zero (0).
*/
// [Constant name: see class BigInteger.]
public final static Rational ZERO = new Rational(0);
/**
* The constant one (1).
*/
// [Name: see class BigInteger.]
public final static Rational ONE = new Rational(1);
/**
* The constant minus-one (-1).
*/
public final static Rational MINUS_ONE = new Rational(-1);
/**
* Rounding mode to round away from zero.
*/
public final static int ROUND_UP = 0;
/**
* Rounding mode to round towards zero.
*/
public final static int ROUND_DOWN = 1;
/**
* Rounding mode to round towards positive infinity.
*/
public final static int ROUND_CEILING = 2;
/**
* Rounding mode to round towards negative infinity.
*/
public final static int ROUND_FLOOR = 3;
/**
* Rounding mode to round towards nearest neighbor unless both neighbors are
* equidistant, in which case to round up.
*/
public final static int ROUND_HALF_UP = 4;
/**
* Rounding mode to round towards nearest neighbor unless both neighbors are
* equidistant, in which case to round down.
*/
public final static int ROUND_HALF_DOWN = 5;
/**
* Rounding mode to round towards the nearest neighbor unless both neighbors
* are equidistant, in which case to round towards the even neighbor.
*/
public final static int ROUND_HALF_EVEN = 6;
/**
* Rounding mode to assert that the requested operation has an exact result,
* hence no rounding is necessary. If this rounding mode is specified on an
* operation that yields an inexact result, an ArithmeticException is
* thrown.
*/
public final static int ROUND_UNNECESSARY = 7;
/**
* Rounding mode to round towards nearest neighbor unless both neighbors are
* equidistant, in which case to round ceiling.
*/
public final static int ROUND_HALF_CEILING = 8;
/**
* Rounding mode to round towards nearest neighbor unless both neighbors are
* equidistant, in which case to round floor.
*/
public final static int ROUND_HALF_FLOOR = 9;
/**
* Rounding mode to round towards the nearest neighbor unless both neighbors
* are equidistant, in which case to round towards the odd neighbor.
*/
public final static int ROUND_HALF_ODD = 10;
/**
* Default round mode, ROUND_HALF_UP.
*/
public final static int DEFAULT_ROUND_MODE = ROUND_HALF_UP;
//
// PUBLIC METHODS
//
//
// START - Constructors
/**
* Construct a Rational from numerator and denominator. Both numerator and
* denominator may be negative. numerator/denominator may be denormalized
* (i.e. have common factors, or denominator being negative).
*
* @param numerator
* the rational's numerator.
* @param denominator
* the rational's denominator (quotient)
*/
public Rational(BigInteger numerator, BigInteger denominator) {
// note: check for denominator==null done later
if (denominator != null && bigIntegerIsZero(denominator)) {
throw new NumberFormatException("Denominator zero");
}
normalizeFrom(numerator, denominator);
}
/**
* Construct a Rational from a numerator only, denominator is defaulted to
* 1.
*
* @param numerator
* the rational's numerator.
*/
public Rational(BigInteger numerator) {
this(numerator, BIG_INTEGER_ONE);
}
/**
* Construct a Rational from long fix number integers representing numerator
* and denominator.
*
* @param numerator
* the rational's numerator.
* @param denominator
* the rational's denominator (quotient)
*/
public Rational(long numerator, long denominator) {
this(bigIntegerValueOf(numerator), bigIntegerValueOf(denominator));
}
/**
* Construct a Rational from a long fix number integer representing
* numerator, denominator is defaulted to 1.
*
* @param numerator
* the rational's numerator.
*/
public Rational(long numerator) {
this(bigIntegerValueOf(numerator), BIG_INTEGER_ONE);
}
/**
* Clone a Rational.
* <p>
* [As Rationals are immutable, this copy-constructor is not that useful.]
*/
public Rational(Rational that) {
normalizeFrom(that);
}
/**
* Construct a Rational from a string representation.
*
* <pre>
* The supported string formats are:
* "[+-]numerator"
* "[+-]numerator/[+-]denominator"
* "[+-]i.f"
* "[+-]i"
* "[+-]iE[+-]e"
* "[+-]i.fE[+-]e"
* (latter two only with radix <= 10, due to possible ambiguities);
* numerator and denominator can be any of the
* latter (i.e. mixed representations such as "-1.2E-3/-4.5E-6" are
* supported).
*
* Samples: "-21/35", "3.4", "-65.4E-3", "f/37" (base 16),
* "1011101011010110" (base 2).
* </pre>
*
* @param strRational
* a string prepresentation of a Rational number.
* @param radix
* the radix the string representation is meant to be in.
*/
public Rational(String strRational, int radix) {
if (strRational == null) {
throw new NumberFormatException("null");
}
// For simplicity remove leading and trailing white spaces.
strRational = strRational.trim();
// Within AIC-SMF we do not want rational to consider these
// as special legal default formats (original BigRational allowed these).
if (strRational.equals("+") || strRational.equals("-") || strRational.equals("/") ||
strRational.equals(".") || strRational.equals("") ||
strRational.startsWith("E") || strRational.startsWith("e")) {
throw new NumberFormatException("underspecificed rational:"+strRational);
}
// '/': least precedence, and left-to-right associative
// (therefore lastIndexOf and not indexOf: last slash has least
// precedence)
final int slash = strRational.lastIndexOf('/');
if (slash != -1) {
// "[+-]numerator/[+-]denominator"
String strNumerator = strRational.substring(0, slash);
String strDenominator = strRational.substring(slash + 1);
// suppress recursion: make stack-overflow attacks infeasible
if (strNumerator.indexOf('/') != -1) {
throw new NumberFormatException("can't nest '/'");
}
// handle "/x" as "1/x"
// [note: "1" and "-1" are treated specially and optimized
// in Rational.bigIntegerValueOf(String,int).]
if (strNumerator.equals("") || strNumerator.equals("+")) {
strNumerator = "1";
} else if (strNumerator.equals("-")) {
strNumerator = "-1";
}
// handle "x/" as "x"
// [note: "1" and "-1" are treated special and optimized
// in Rational.bigIntegerValueOf(String,int).]
if (strDenominator.equals("") || strDenominator.equals("+")) {
strDenominator = "1";
} else if (strDenominator.equals("-")) {
strDenominator = "-1";
}
// [recursion]
// [divide()'s outcome is already normalized,
// so there would be no need to normalize [again]]
normalizeFrom((new Rational(strNumerator, radix))
.divide(new Rational(strDenominator, radix)));
return;
}
checkRadix(radix);
// catch Java's string representations of
// doubles/floats unsupported by Rational
checkNaNAndInfinity(strRational, radix);
// [if radix<=10:] 'E': next higher precedence, not associative
// or right-to-left associative
int exp = -1;
// note: a distinction of exponent-'E' from large-base-digit-'e'
// would be unintuitive, since case doesn't matter with both uses
if (radix <= 10) {
// handle both [upper/lower] cases
final int exp1 = strRational.indexOf('E');
final int exp2 = strRational.indexOf('e');
exp = (exp1 == -1 || (exp2 != -1 && exp2 < exp1) ? exp2 : exp1);
}
if (exp != -1) {
String strMantissa = strRational.substring(0, exp);
String strExponent = strRational.substring(exp + 1);
// suppress recursion: make stack-overflow attacks infeasible
if (strExponent.indexOf('E') != -1
|| strExponent.indexOf('e') != -1) {
throw new NumberFormatException("can't nest 'E'");
}
// skip '+'
if (strExponent.length() > 0 && strExponent.charAt(0) == '+') {
strExponent = strExponent.substring(1);
}
// handle '-'
boolean negateTheExponent = false;
if (strExponent.length() > 0 && strExponent.charAt(0) == '-') {
negateTheExponent = true;
strExponent = strExponent.substring(1);
}
// handle "xE", "xE+", "xE-", as "xE0" aka "x"
if (strExponent.equals("")) {
strExponent = "0";
}
// [recursion]
Rational exponent = new Rational(strExponent, radix);
final int iexponent;
// transform possible [overflow/fraction] exception
try {
iexponent = exponent.intValueExact();
} catch (ArithmeticException e) {
final NumberFormatException e2 = new NumberFormatException(
e.getMessage());
// make sure this operation doesn't shadow the exception to be
// thrown
try {
e2.initCause(e);
} catch (Throwable e3) {
throw e2;
}
throw e2;
}
exponent = valueOf(radix).pow(iexponent);
if (negateTheExponent) {
exponent = exponent.invert();
}
// handle "Ex", "+Ex", "-Ex", as "1Ex"
if (strMantissa.equals("") || strMantissa.equals("+")) {
strMantissa = "1";
} else if (strMantissa.equals("-")) {
strMantissa = "-1";
}
// [multiply()'s outcome is already normalized,
// so there would be no need to normalize [again]]
normalizeFrom((new Rational(strMantissa, radix)).multiply(exponent));
return;
}
// '.': next higher precedence, not associative
// (can't have more than one dot)
String strIntegerPart, strFractionPart;
final int dot = strRational.indexOf('.');
if (dot != -1) {
// "[+-]i.f"
strIntegerPart = strRational.substring(0, dot);
strFractionPart = strRational.substring(dot + 1);
}
else {
// "[+-]i". [not just delegating to BigInteger.]
strIntegerPart = strRational;
strFractionPart = "";
}
// check for multiple signs or embedded signs
checkNumberFormat(strIntegerPart);
// skip '+'
// skip '+'. [BigInteger [likely] doesn't handle these.]
if (strIntegerPart.length() > 0 && strIntegerPart.charAt(0) == '+') {
strIntegerPart = strIntegerPart.substring(1);
}
// handle '-'
boolean negativeIntegerPart = false;
if (strIntegerPart.length() > 0 && strIntegerPart.charAt(0) == '-') {
negativeIntegerPart = true;
strIntegerPart = strIntegerPart.substring(1);
}
// handle ".x" as "0.x" ("." as "0.0")
// handle "" as "0"
// note: "0" is treated specially and optimized
// in Rational.bigIntegerValueOf(String,int).
if (strIntegerPart.equals("")) {
strIntegerPart = "0";
}
BigInteger numerator = bigIntegerValueOf(strIntegerPart, radix);
BigInteger denominator;
// includes the cases "x." and "."
if (!strFractionPart.equals("")) {
// check for signs
checkFractionFormat(strFractionPart);
final BigInteger fraction = bigIntegerValueOf(strFractionPart,
radix);
final int scale = strFractionPart.length();
denominator = bigIntegerPower(bigIntegerValueOf(radix), scale);
numerator = bigIntegerMultiply(numerator, denominator)
.add(fraction);
}
else {
denominator = BIG_INTEGER_ONE;
}
if (negativeIntegerPart) {
numerator = numerator.negate();
}
normalizeFrom(numerator, denominator);
}
/**
* Construct a Rational from a string representation using DEFAULT_RADIX.
*
* <pre>
* The supported string formats are:
* "[+-]numerator"
* "[+-]numerator/[+-]denominator"
* "[+-]i.f"
* "[+-]i"
* "[+-]iE[+-]e"
* "[+-]i.fE[+-]e"
* (latter two only with radix <= 10, due to possible ambiguities);
* numerator and denominator can be any of the
* latter (i.e. mixed representations such as "-1.2E-3/-4.5E-6" are
* supported).
*
* Samples: "-21/35", "3.4", "-65.4E-3", "f/37" (base 16),
* "1011101011010110" (base 2).
* </pre>
*
* @param strRational
* a string prepresentation of a Rational number.
*/
public Rational(String strRational) {
this(strRational, DEFAULT_RADIX);
}
/**
* Construct a Rational from an unscaled value and a scale value.
*
* @param unscaledValue
* an unscaled value representation of a Rational.
* @param scale
* the scale to be associated with the unscaledValue
* @param radix
* the radix the rational is meant to be in.
*/
public Rational(BigInteger unscaledValue, int scale, int radix) {
if (unscaledValue == null) {
throw new NumberFormatException("null");
}
final boolean negate = (scale < 0);
if (negate) {
scale = -scale;
}
checkRadix(radix);
final BigInteger scaleValue = bigIntegerPower(bigIntegerValueOf(radix),
scale);
normalizeFrom((negate ? bigIntegerMultiply(unscaledValue, scaleValue)
: unscaledValue), (negate ? BIG_INTEGER_ONE : scaleValue));
}
/**
* Construct a Rational from an unscaled value and a scale value, default
* radix (10).
*
* @param unscaledValue
* an unscaled value representation of a Rational.
* @param scale
* the scale to be associated with the unscaledValue
*/
public Rational(BigInteger unscaledValue, int scale) {
this(unscaledValue, scale, DEFAULT_RADIX);
}
/**
* Construct a Rational from an unscaled fix number value and a scale value.
*
* @param unscaledValue
* an unscaled value representation of a Rational.
* @param scale
* the scale to be associated with the unscaledValue
* @param radix
* the radix the rational is meant to be in.
*/
public Rational(long unscaledValue, int scale, int radix) {
this(bigIntegerValueOf(unscaledValue), scale, radix);
}
/**
* Construct a Rational from a [IEEE 754] double [size/precision] floating
* point number.
*
* @param value
* double value from which a Rational is to be constructed.
*/
public Rational(double value) {
normalizeFrom(valueOfDoubleBits(Double.doubleToLongBits(value)));
}
/**
* Construct a Rational from a [IEEE 754] single [size/precision] floating
* point number.
*
* @param value
* double value from which a Rational is to be constructed.
*/
public Rational(float value) {
normalizeFrom(valueOfFloatBits(Float.floatToIntBits(value)));
}
// END - Constructors
//
/**
* Positive predicate.
* <p>
* Indicates whether this Rational is larger than zero. Zero is not
* positive.
* <p>
* [For convenience.]
*/
public boolean isPositive() {
return (signum() > 0);
}
/**
* Negative predicate.
* <p>
* Indicates whether this Rational is smaller than zero. Zero isn't negative
* either.
* <p>
* [For convenience.]
*/
public boolean isNegative() {
return (signum() < 0);
}
/**
* Zero predicate.
* <p>
* Indicates whether this Rational is zero.
* <p>
* [For convenience and speed.]
*/
public boolean isZero() {
// optimization, first test is for speed.
if (this == ZERO || numerator == BIG_INTEGER_ZERO) {
return true;
}
// well, this is also optimized for speed a bit.
return (signum() == 0);
}
/**
* One predicate.
* <p>
* Indicates whether this Rational is 1.
* <p>
* [For convenience and speed.]
*/
public boolean isOne() {
// optimization
// first test is for speed.
if (this == ONE) {
return true;
}
return equals(ONE);
}
/**
* Minus-one predicate.
* <p>
* Indicates whether this Rational is -1.
* <p>
* [For convenience and speed.]
*/
public boolean isMinusOne() {
// optimization
// first test is for speed.
if (this == MINUS_ONE) {
return true;
}
return equals(MINUS_ONE);
}
/**
* Integer predicate.
* <p>
* Indicates whether this Rational convertible to a BigInteger without loss
* of precision. True iff denominator/quotient is one.
*/
public boolean isInteger() {
return bigIntegerIsOne(denominator);
}
/**
* Rational string representation, format "[-]numerator[/denominator]".
* <p>
* Sample output: "6172839/5000".
*/
public String toString(int radix) {
checkRadixArgument(radix);
final String s = stringValueOf(numerator, radix);
if (isInteger()) {
return s;
}
return s + "/" + stringValueOf(denominator, radix);
}
/**
* Rational string representation, format "[-]numerator[/denominator]",
* default radix (10).
* <p>
* Default string representation, as rational, not using an exponent.
* <p>
* Sample output: "6172839/5000".
* <p>
* Overwrites Object.toString().
*/
@Override
public String toString() {
return toString(DEFAULT_RADIX);
}
/**
* Fixed dot-format "[-]i.f" string representation, with a precision.
* <p>
* Precision may be negative, in which case the rounding affects digits left
* of the dot, i.e. the integer part of the number, as well.
* <p>
* Sample output: "1234.567800".
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public String toStringDot(int precision, int radix) {
return toStringDot(precision, radix, false);
}
/**
* Dot-format "[-]i.f" string representation, with a precision, default
* radix (10). Precision may be negative.
* <p>
* Sample output: "1234.567800".
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public String toStringDot(int precision) {
// [possible loss of precision step]
return toStringDot(precision, DEFAULT_RADIX, false);
}
// note: there is no 'default' precision.
/**
* Dot-format "[-]i.f" string representation, with a relative precision.
* <p>
* If the relative precision is zero or negative, "0" will be returned (i.e.
* total loss of precision).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public String toStringDotRelative(int precision, int radix) {
// kind of expensive, due to expensive logarithm implementation
// (with unusual radixes), and post processing
checkRadixArgument(radix);
// zero doesn't have any significant digits
if (isZero()) {
return "0";
}
// relative precision zero [or less means]: no significant digits at
// all, i.e. 0
// [loss of precision step]
if (precision <= 0) {
return "0";
}
// guessed [see below: rounding issues] length: sign doesn't matter;
// one digit more than logarithm
final int guessedLength = abs().logarithm(radix) + 1;
// [possible loss of precision step]
String s = toStringDot(precision - guessedLength, radix);
// [floor of] logarithm and [arithmetic] rounding [half-up]
// need post-processing:
// find first significant digit and check for dot
boolean dot = false;
int i;
for (i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (c == '.') {
dot = true;
}
// expecting nothing than '-', '.', and digits
if (c != '-' && c != '.' && c != '0') {
break;
}
}
// count digits / [still] check for dot
int digits = 0;
for (; i < s.length(); i++) {
if (s.charAt(i) == '.') {
dot = true;
}
else {
digits++;
}
}
// cut excess zeros
// expecting at most 1 excess zero, e.g. for "0.0099999"
final int excess = digits - precision;
if (dot && excess > 0) {
s = s.substring(0, s.length() - excess);
}
return s;
}
/**
* Dot-format "[-]i.f" string representation, with a relative precision,
* default radix (10).
* <p>
* If the relative precision is zero or negative, "0" will be returned (i.e.
* total loss of precision).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public String toStringDotRelative(int precision) {
// [possible loss of precision step]
return toStringDotRelative(precision, DEFAULT_RADIX);
}
/**
* Exponent-format string representation, with a relative precision,
* "[-]i[.f]E[-]e" (where i is one digit other than 0 exactly; f has no
* trailing 0);
* <p>
* Sample output: "1.2E3".
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public String toStringExponent(int precision, int radix) {
checkRadixArgument(radix);
// zero doesn't have any significant digits
if (isZero()) {
return "0";
}
// relative precision zero [or less means]: no significant digits at
// all, i.e. 0
// [loss of precision step]
if (precision <= 0) {
return "0";
}
// guessed [see below: rounding issues] length: sign doesn't matter;
// one digit more than logarithm
final int guessedLength = abs().logarithm(radix) + 1;
// [possible loss of precision step]
final String s = toStringDot(precision - guessedLength, radix, true);
return toExponentRepresentation(s, radix);
}
/**
* Exponent-format string representation, with a relative precision, default
* radix (10), "[-]i[.f]E[-]e" (where i is one digit other than 0 exactly; f
* has no trailing 0);
* <p>
* Sample output: "1.2E3".
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public String toStringExponent(int precision) {
// [possible loss of precision step]
return toStringExponent(precision, DEFAULT_RADIX);
}
/**
* Add a Rational to this Rational and return a new Rational.
* <p>
* If one of the operands is zero, [as an optimization] the other Rational
* is returned.
*/
// [Name: see class BigInteger.]
public Rational add(Rational that) {
// optimization: second operand is zero (i.e. neutral element).
if (that.isZero()) {
return this;
}
// optimization: first operand is zero (i.e. neutral element).
if (isZero()) {
return that;
}
// note: not checking for that.equals(negate()),
// since that would involve creation of a temporary object
// note: the calculated numerator/denominator may be denormalized,
// implicit normalize() is needed.
// optimization: same denominator.
if (bigIntegerEquals(denominator, that.denominator)) {
return new Rational(numerator.add(that.numerator), denominator);
}
// optimization: second operand is an integer.
if (that.isInteger()) {
return new Rational(numerator.add(that.numerator
.multiply(denominator)), denominator);
}
// optimization: first operand is an integer.
if (isInteger()) {
return new Rational(numerator.multiply(that.denominator).add(
that.numerator), that.denominator);
}
// default case. [this would handle all cases.]
return new Rational(numerator.multiply(that.denominator).add(
that.numerator.multiply(denominator)),
denominator.multiply(that.denominator));
}
/**
* Add a long fix number integer to this Rational and return a new Rational.
*/
public Rational add(long that) {
return add(valueOf(that));
}
/**
* Subtract a Rational from this Rational and return a new Rational.
* <p>
* If the second operand is zero, [as an optimization] this Rational is
* returned.
*/
// [Name: see class BigInteger.]
public Rational subtract(Rational that) {
// optimization: second operand is zero.
if (that.isZero()) {
return this;
}
// optimization: first operand is zero
if (isZero()) {
return that.negate();
}
// optimization: operands are equal
if (equals(that)) {
return ZERO;
}
// note: the calculated n/q may be denormalized,
// implicit normalize() is needed.
// optimization: same denominator.
if (bigIntegerEquals(denominator, that.denominator)) {
return new Rational(numerator.subtract(that.numerator), denominator);
}
// optimization: second operand is an integer.
if (that.isInteger()) {
return new Rational(numerator.subtract(that.numerator
.multiply(denominator)), denominator);
}
// optimization: first operand is an integer.
if (isInteger()) {
return new Rational(numerator.multiply(that.denominator).subtract(
that.numerator), that.denominator);
}
// default case. [this would handle all cases.]
return new Rational(numerator.multiply(that.denominator).subtract(
that.numerator.multiply(denominator)),
denominator.multiply(that.denominator));
}
/**
* Subtract a long fix number integer from this Rational and return a new
* Rational.
*/
public Rational subtract(long that) {
return subtract(valueOf(that));
}
/**
* Multiply a Rational to this Rational and return a new Rational.
* <p>
* If one of the operands is one, [as an optimization] the other Rational is
* returned.
*/
// [Name: see class BigInteger.]
public Rational multiply(Rational that) {
// optimization: one or both operands are zero.
if (that.isZero() || isZero()) {
return ZERO;
}
// optimization: second operand is 1.
if (that.isOne()) {
return this;
}
// optimization: first operand is 1.
if (isOne()) {
return that;
}
// optimization: second operand is -1.
if (that.isMinusOne()) {
return negate();
}
// optimization: first operand is -1.
if (isMinusOne()) {
return that.negate();
}
// note: the calculated numerator/denominator may be denormalized,
// implicit normalize() is needed.
return new Rational(bigIntegerMultiply(numerator, that.numerator),
bigIntegerMultiply(denominator, that.denominator));
}
/**
* Multiply a long fix number integer to this Rational and return a new
* Rational.
*/
public Rational multiply(long that) {
return multiply(valueOf(that));
}
/**
* Divide this Rational through another Rational and return a new Rational.
* <p>
* If the second operand is one, [as an optimization] this Rational is
* returned.
*/
// [Name: see class BigInteger.]
public Rational divide(Rational that) {
if (that.isZero()) {
throw new ArithmeticException("division by zero");
}
// optimization: first operand is zero.
if (isZero()) {
return ZERO;
}
// optimization: second operand is 1.
if (that.isOne()) {
return this;
}
// optimization: first operand is 1.
if (isOne()) {
return that.invert();
}
// optimization: second operand is -1.
if (that.isMinusOne()) {
return negate();
}
// optimization: first operand is -1.
if (isMinusOne()) {
return that.invert().negate();
}
// note: the calculated numerator/denominator may be denormalized,
// implicit normalize() is needed.
return new Rational(bigIntegerMultiply(numerator, that.denominator),
bigIntegerMultiply(denominator, that.numerator));
}
/**
* Divide this Rational through a long fix number integer and return a new
* Rational.
*/
public Rational divide(long that) {
return divide(valueOf(that));
}
/**
* Calculate this Rational's integer power and return a new Rational.
* <p>
* The integer exponent may be negative.
* <p>
* If the exponent is one, [as an optimization] this Rational is returned.
*/
// [Name: see classes Math, BigInteger.]
public Rational pow(int exponent) {
final boolean zero = isZero();
if (zero) {
if (exponent == 0) {
throw new ArithmeticException("zero exp zero");
}
if (exponent < 0) {
throw new ArithmeticException("division by zero");
}
}
// optimization
if (exponent == 0) {
return ONE;
}
// optimization
// test for exponent<=0 already done
if (zero) {
return ZERO;
}
// optimization
if (exponent == 1) {
return this;
}
// optimization
if (exponent == -1) {
return invert();
}
final boolean negate = (exponent < 0);
if (negate) {
exponent = -exponent;
}
final BigInteger numerator = bigIntegerPower(this.numerator, exponent);
final BigInteger denominator = bigIntegerPower(this.denominator,
exponent);
// note: the calculated numerator/denominator are not denormalized in
// the sense of having common factors, but numerator might be negative
// (and become denominator below)
return new Rational((negate ? denominator : numerator),
(negate ? numerator : denominator));
}
/**
* Calculate the remainder of this Rational and another Rational and return
* a new Rational.
* <p>
* The remainder result may be negative.
* <p>
* The remainder is based on round down (towards zero) / truncate. 5/3 == 1
* + 2/3 (remainder 2), 5/-3 == -1 + 2/-3 (remainder 2), -5/3 == -1 + -2/3
* (remainder -2), -5/-3 == 1 + -2/-3 (remainder -2).
*/
// [Name: see class BigInteger.]
public Rational remainder(Rational that) {
final int thisSignum = signum();
final int thatSignum = that.signum();
if (thatSignum == 0) {
throw new ArithmeticException("division by zero");
}
Rational a = this;
if (thisSignum < 0) {
a = a.negate();
}
// divisor's sign doesn't matter, as stated above.
// this is also BigInteger's behavior, but don't let us be
// dependent of a change in that.
Rational b = that;
if (thatSignum < 0) {
b = b.negate();
}
Rational r = a.remainderOrModulusOfPositive(b);
if (thisSignum < 0) {
r = r.negate();
}
return r;
}
/**
* Calculate the remainder of this Rational and a long fix number integer
* and return a new Rational.
*/
public Rational remainder(long that) {
return remainder(valueOf(that));
}
/**
* Calculate the modulus of this Rational and another Rational and return a
* new Rational.
* <p>
* The modulus result may be negative.
* <p>
* Modulus is based on round floor (towards negative). 5/3 == 1 + 2/3
* (modulus 2), 5/-3 == -2 + -1/-3 (modulus -1), -5/3 == -2 + 1/3 (modulus
* 1), -5/-3 == 1 + -2/-3 (modulus -2).
*/
// [Name: see class BigInteger.]
public Rational mod(Rational that) {
final int thisSignum = signum();
final int thatSignum = that.signum();
if (thatSignum == 0) {
throw new ArithmeticException("division by zero");
}
Rational a = this;
if (thisSignum < 0) {
a = a.negate();
}
Rational b = that;
if (thatSignum < 0) {
b = b.negate();
}
Rational r = a.remainderOrModulusOfPositive(b);
if (thisSignum < 0 && thatSignum < 0) {
r = r.negate();
} else if (thatSignum < 0) {
r = r.subtract(b);
} else if (thisSignum < 0) {
r = b.subtract(r);
}
return r;
}
/**
* Calculate the modulus of this Rational and a long fix number integer and
* return a new Rational.
*/
public Rational mod(long that) {
return mod(valueOf(that));
}
/**
* Signum. -1, 0, or 1.
* <p>
* If this Rational is negative, -1 is returned; if it is zero, 0 is
* returned; if it is positive, 1 is returned.
*/
// [Name: see class BigInteger.]
public int signum() {
// note: denominator is positive.
return numerator.signum();
}
/**
* Return a new Rational with the absolute value of this Rational.
* <p>
* If this Rational is zero or positive, [as an optimization] this Rational
* is returned.
*/
// [Name: see classes Math, BigInteger.]
public Rational abs() {
if (signum() >= 0) {
return this;
}
// optimization
if (isMinusOne()) {
return ONE;
}
// note: the calculated numerator/denominator are not denormalized,
// implicit normalize() would not be needed.
return new Rational(numerator.negate(), denominator);
}
/**
* Return a new Rational with the negative value of this.
*
*/
// [Name: see class BigInteger.]
public Rational negate() {
// optimization
if (isZero()) {
return ZERO;
}
// optimization
if (isOne()) {
return MINUS_ONE;
}
// optimization
if (isMinusOne()) {
return ONE;
}
// note: the calculated numerator/denominator are not denormalized,
// implicit normalize() would not be needed.
return new Rational(numerator.negate(), denominator);
}
/**
* Return a new Rational with the inverted (reciprocal) value of this.
*/
public Rational invert() {
if (isZero()) {
throw new ArithmeticException("division by zero");
}
// optimization
if (isOne() || isMinusOne()) {
return this;
}
// note: the calculated numerator/denominator are not denormalized in
// the sense of having common factors, but numerator might be negative
// (and become denominator below)
return new Rational(denominator, numerator);
}
/**
* Return the minimal value of two Rationals.
*/
// [Name: see classes Math, BigInteger.]
public Rational min(Rational that) {
return (compareTo(that) <= 0 ? this : that);
}
/**
* Return the minimal value of a Rational and a long fix number integer.
*/
public Rational min(long that) {
return min(valueOf(that));
}
/**
* Return the maximal value of two Rationals.
*/
// [Name: see classes Math, BigInteger.]
public Rational max(Rational that) {
return (compareTo(that) >= 0 ? this : that);
}
/**
* Return the maximum value of a Rational and a long fix number integer.
*/
public Rational max(long that) {
return max(valueOf(that));
}
/**
* Compare object for equality. Overwrites Object.equals(). Semantics is
* that only Rationals can be equal. Never throws.
* <p>
* Overwrites Object.equals(Object).
*/
@Override
public boolean equals(Object object) {
// optimization
if (object == this) {
return true;
}
// test includes null
if (!(object instanceof Rational)) {
return false;
}
final Rational that = (Rational) object;
// optimization
if (that.numerator == numerator && that.denominator == denominator) {
return true;
}
this.reduce(); // make sure they have the same fraction if representing the same value.
that.reduce();
boolean result =
bigIntegerEquals(that.numerator, numerator) &&
bigIntegerEquals(that.denominator, denominator);
return result;
}
/**
* Hash code. Overwrites Object.hashCode().
* <p>
* Overwrites Object.hashCode().
*/
@Override
public int hashCode() {
// lazy init for optimization
if (hashCode == 0) {
reduce(); // make sure all rationals with the same value have the hash code computed from the same fraction.
hashCode = ((numerator.hashCode() + 1) * (denominator.hashCode() + 2));
}
return hashCode;
}
/**
* Compare this Rational to another Rational.
*/
public int compareTo(Rational that) {
// optimization
if (that == this) {
return 0;
}
final int thisSignum = signum();
final int thatSignum = that.signum();
if (thisSignum != thatSignum) {
return (thisSignum < thatSignum ? -1 : 1);
}
// optimization: both zero.
if (thisSignum == 0) {
return 0;
}
// note: both denominators are positive.
return bigIntegerMultiply(numerator, that.denominator)
.compareTo(
bigIntegerMultiply(that.numerator, denominator));
}
/**
* Compare this Rational to a BigInteger.
*/
public int compareTo(BigInteger that) {
return compareTo(valueOf(that));
}
/**
* Compare this Rational to a long.
*/
public int compareTo(long that) {
return compareTo(valueOf(that));
}
/**
* Compare this Rational to an Object.
* <p>
* Object can be Rational/BigInteger/Long/Integer/Short/Byte.
* <p>
* Implements Comparable.compareTo(Object) (JDK 1.2 and later).
* <p>
* A sample use is with a sorted map or set, e.g. TreeSet.
* <p>
* Only Rational/BigInteger/Long/Integer objects allowed, method will throw
* otherwise.
* <p>
* For backward compatibility reasons we keep compareTo(Object) additionally
* to compareTo(Rational). Comparable<Object> is declared to be
* implemented rather than Comparable<Rational>.
*/
public int compareTo(Object object) {
if (object instanceof Byte) {
return compareTo(((Byte) object).longValue());
}
if (object instanceof Short) {
return compareTo(((Short) object).longValue());
}
if (object instanceof Integer) {
return compareTo(((Integer) object).longValue());
}
if (object instanceof Long) {
return compareTo(((Long) object).longValue());
}
if (object instanceof BigInteger) {
return compareTo((BigInteger) object);
}
// now assuming that it's either 'instanceof Rational'
// or it'll throw a ClassCastException.
return compareTo((Rational) object);
}
/**
* Convert to BigInteger, by rounding.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public BigInteger bigIntegerValue() {
// [rounding step, possible loss of precision step]
return round().numerator;
}
/**
* Convert to long, by rounding and delegating to BigInteger. Implements
* Number.longValue(). As described with BigInteger.longValue(), this just
* returns the low-order [64] bits (losing information about magnitude and
* sign).
* <p>
* Possible loss of precision.
* <p>
* Overwrites Number.longValue().
*/
// @PrecisionLoss
@Override
public long longValue() {
// delegate to BigInteger.
// [rounding step, possible loss of precision step]
return bigIntegerValue().longValue();
}
/**
* Convert to int, by rounding and delegating to BigInteger. Implements
* Number.intValue(). As described with BigInteger.longValue(), this just
* returns the low-order [32] bits (losing information about magnitude and
* sign).
* <p>
* Possible loss of precision.
* <p>
* Overwrites Number.intValue().
*/
// @PrecisionLoss
@Override
public int intValue() {
// delegate to BigInteger.
// [rounding step, possible loss of precision step]
return bigIntegerValue().intValue();
}
/**
* Convert to double floating point value. Implements Number.doubleValue().
* <p>
* Possible loss of precision.
* <p>
* Overwrites Number.doubleValue().
*/
// @PrecisionLoss
@Override
public double doubleValue() {
return Double.longBitsToDouble(
// [rounding step, possible loss of precision step]
doubleBitsValue());
}
/**
* Convert to single floating point value. Implements Number.floatValue().
* <p>
* Note that Rational's [implicit] [default] rounding mode that applies
* [too] on indirect double to Rational to float rounding (round-half-up)
* may differ from what's done in a direct cast/coercion from double to
* float (e.g. round-half-even).
* <p>
* Possible loss of precision.
* <p>
* Overwrites Number.floatValue().
*/
// @PrecisionLoss
@Override
public float floatValue() {
return Float.intBitsToFloat(
// [rounding step, possible loss of precision step]
floatBitsValue());
}
/**
* Convert to IEEE 754 double float bits. The bits can be converted to a
* double by Double.longBitsToDouble().
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public long doubleBitsValue() {
// [rounding step, possible loss of precision step]
return (toIEEE754(this, DOUBLE_FLOAT_FRACTION_SIZE,
DOUBLE_FLOAT_EXPONENT_SIZE)[0]);
}
/**
* Convert to IEEE 754 single float bits. The bits can be converted to a
* float by Float.intBitsToFloat().
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public int floatBitsValue() {
// [rounding step, possible loss of precision step]
return (int) (toIEEE754(this, SINGLE_FLOAT_FRACTION_SIZE,
SINGLE_FLOAT_EXPONENT_SIZE)[0]);
}
/**
* Convert this Rational to IEEE 754 half float (binary16) bits.
* <p>
* As a short value is returned rather than a int, care has to be taken no
* unwanted sign expansion happens in subsequent operations, e.g. by masking
* (x.halfBitsValue()&0xffffl) or similar
* (x.halfBitsValue()==(short)0xbc00).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public short halfBitsValue() {
// [rounding step, possible loss of precision step]
return (short) (toIEEE754(this, HALF_FLOAT_FRACTION_SIZE,
HALF_FLOAT_EXPONENT_SIZE)[0]);
}
/**
* Convert this Rational to IEEE 754 quad float (binary128, quadruple) bits.
* <p>
* The bits are returned in an array of two longs, big endian (higher
* significant long first).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public long[] quadBitsValue() {
// [rounding step, possible loss of precision step]
return toIEEE754(this, QUAD_FLOAT_FRACTION_SIZE,
QUAD_FLOAT_EXPONENT_SIZE);
}
/**
* Convert this Rational to a long integer, either returning an exact result
* (no rounding or truncation needed), or throw an ArithmeticException.
*/
public long longValueExact() {
final long i = longValue();
// test is kind-of costly
if (!equals(valueOf(i))) {
throw new ArithmeticException(isInteger() ? "overflow"
: "rounding necessary");
}
return i;
}
/**
* Convert this Rational to an int, either returning an exact result (no
* rounding or truncation needed), or throw an ArithmeticException.
*/
public int intValueExact() {
final int i = intValue();
// test is kind-of costly
if (!equals(valueOf(i))) {
throw new ArithmeticException(isInteger() ? "overflow"
: "rounding necessary");
}
return i;
}
/**
* Convert this Rational to its constant (ONE, ZERO, MINUS_ONE) if possible.
*/
public static Rational valueOf(Rational value) {
if (value == null) {
throw new NumberFormatException("null");
}
// note: these tests are quite expensive,
// but they are minimized to a reasonable amount.
// priority in the tests: 1, 0, -1;
// two phase testing.
// cheap tests first.
// optimization
if (value == ONE) {
return value;
}
// optimization
if (value == ZERO) {
return value;
}
// optimization
if (value == MINUS_ONE) {
return value;
}
// more expensive tests later.
// optimization
if (value.equals(ONE)) {
return ONE;
}
// optimization
if (value.equals(ZERO)) {
return ZERO;
}
// optimization
if (value.equals(MINUS_ONE)) {
return MINUS_ONE;
}
// not a known constant
return value;
}
/**
* Build a Rational from a String.
* <p>
* [Roughly] equivalent to <CODE>new Rational(value)</CODE>.
*/
public static Rational valueOf(String value) {
if (value == null) {
throw new NumberFormatException("null");
}
// optimization
if (value.equals("0")) {
return ZERO;
}
// optimization
if (value.equals("1")) {
return ONE;
}
// optimization
if (value.equals("-1")) {
return MINUS_ONE;
}
return new Rational(value);
}
/**
* Build a Rational from a BigInteger.
* <p>
* Equivalent to <CODE>new Rational(value)</CODE>.
*/
public static Rational valueOf(BigInteger value) {
return new Rational(value);
}
/**
* Build a Rational from a long fix number integer.
* <p>
* [Roughly] equivalent to <CODE>new Rational(value)</CODE>.
* <p>
* As an optimization, commonly used numbers are returned as a reused
* constant.
*/
public static Rational valueOf(long value) {
// return the internal constants if possible
// optimization
// check whether it's outside int range.
// actually check a much narrower range, fitting the switch below.
if (value >= -16 && value <= 16) {
// note: test above needed to make the cast below safe
// jump table, for speed
switch ((int) value) {
case 0:
return ZERO;
case 1:
return ONE;
case -1:
return MINUS_ONE;
case 2:
return TWO;
case 10:
return TEN;
case 16:
return SIXTEEN;
}
}
return new Rational(value);
}
// note: byte/short/int implicitly upgraded to long,
// so strictly the additional implementations aren't needed;
// with unsigned (below) they however are
/**
* Build a Rational from an int.
*/
public static Rational valueOf(int value) {
return valueOf((long) value);
}
/**
* Build a Rational from a short.
*/
public static Rational valueOf(short value) {
return valueOf((long) value);
}
/**
* Build a Rational from a byte.
*/
public static Rational valueOf(byte value) {
return valueOf((long) value);
}
/**
* Build a Rational from a [IEEE 754] double [size/precision] floating point
* number.
*/
public static Rational valueOf(double value) {
return new Rational(value);
}
/**
* Build a Rational from a [IEEE 754] single [size/precision] floating point
* number.
*/
public static Rational valueOf(float value) {
return new Rational(value);
}
/**
* Build a Rational from an unsigned long fix number integer.
* <p>
* The resulting Rational is positive, i.e. the negative longs are mapped to
* 2**63..2**64 (exclusive).
*/
public static Rational valueOfUnsigned(long value) {
final Rational b = valueOf(value);
// mind the long being unsigned with highest significant
// bit (bit#63) set (interpreted as negative by valueOf(long))
return (b.isNegative() ? b.add(TWO_POWER_64) : b);
}
/**
* Build a Rational from an unsigned int.
* <p>
* The resulting Rational is positive, i.e. the negative ints are mapped to
* 2**31..2**32 (exclusive).
*/
public static Rational valueOfUnsigned(int value) {
// masking: suppress sign expansion
return valueOf(value & 0xffffffffl);
}
/**
* Build a Rational from an unsigned short.
* <p>
* The resulting Rational is positive, i.e. the negative shorts are mapped
* to 2**15..2**16 (exclusive).
*/
public static Rational valueOfUnsigned(short value) {
// masking: suppress sign expansion
return valueOf(value & 0xffffl);
}
/**
* Build a Rational from an unsigned byte.
* <p>
* The resulting Rational is positive, i.e. the negative bytes are mapped to
* 2**7..2**8 (exclusive).
*/
public static Rational valueOfUnsigned(byte value) {
// masking: suppress sign expansion
return valueOf(value & 0xffl);
}
/**
* Build a Rational from an IEEE 754 double size (double precision,
* binary64) floating point number represented as long.
* <p>
* An IEEE 754 double size (binary64) number uses 1 bit for the sign, 11
* bits for the exponent, and 52 bits (plus 1 implicit bit) for the
* fraction/mantissa. The minimal exponent encodes subnormal nubers; the
* maximal exponent encodes Infinities and NaNs.
* <p>
* Infinities and NaNs are not supported as Rationals.
* <p>
* The conversion from the bits to a Rational is done without loss of
* precision.
*/
public static Rational valueOfDoubleBits(long value) {
return fromIEEE754(new long[] { value, }, DOUBLE_FLOAT_FRACTION_SIZE,
DOUBLE_FLOAT_EXPONENT_SIZE);
}
/**
* Build a Rational from an IEEE 754 single size (single precision,
* binary32) floating point number represented as int.
* <p>
* An IEEE 754 single size (binary32) number uses 1 bit for the sign, 8 bits
* for the exponent, and 23 bits (plus 1 implicit bit) for the
* fraction/mantissa. The minimal exponent encodes subnormal nubers; the
* maximal exponent encodes Infinities and NaNs.
* <p>
* Infinities and NaNs are not supported as Rationals.
* <p>
* The conversion from the bits to a Rational is done without loss of
* precision.
*/
public static Rational valueOfFloatBits(int value) {
// [masking: suppress sign expansion, that leads to excess bits,
// that's not accepted by fromIeee754()]
return fromIEEE754(new long[] { value & 0xffffffffl, },
SINGLE_FLOAT_FRACTION_SIZE, SINGLE_FLOAT_EXPONENT_SIZE);
}
/**
* Build a Rational from an IEEE 754 half size (half precision, binary16)
* floating point number represented as short.
* <p>
* An IEEE 754 half size (binary16) number uses 1 bit for the sign, 5 bits
* for the exponent, and 10 bits (plus 1 implicit bit) for the
* fraction/mantissa. The minimal exponent encodes subnormal nubers; the
* maximal exponent encodes Infinities and NaNs.
* <p>
* Infinities and NaNs are not supported as Rationals.
* <p>
* The conversion from the bits to a Rational is done without loss of
* precision.
*/
public static Rational valueOfHalfBits(short value) {
// [masking: suppress sign expansion, that leads to excess bits,
// that's not accepted by fromIeee754()]
return fromIEEE754(new long[] { value & 0xffffl, },
HALF_FLOAT_FRACTION_SIZE, HALF_FLOAT_EXPONENT_SIZE);
}
/**
* Build a Rational from an IEEE 754 quad size (quadruple precision,
* binary128) floating point number represented as an array of two longs
* (big endian; higher significant long first).
* <p>
* An IEEE 754 quad size (binary128, quadruple) number uses 1 bit for the
* sign, 15 bits for the exponent, and 112 bits (plus 1 implicit bit) for
* the fraction/mantissa. The minimal exponent encodes subnormal nubers; the
* maximal exponent encodes Infinities and NaNs.
* <p>
* Infinities and NaNs are not supported as Rationals.
* <p>
* The conversion from the bits to a Rational is done without loss of
* precision.
*/
public static Rational valueOfQuadBits(long[] value) {
return fromIEEE754(value, QUAD_FLOAT_FRACTION_SIZE,
QUAD_FLOAT_EXPONENT_SIZE);
}
/**
* Compare two IEEE 754 quad size (quadruple precision, binary128) floating
* point numbers (each represented as two longs). NaNs are not considered;
* comparison is done by bits. [Convenience method.]
*/
// note: especially due the NaN issue commented above
// (a NaN maps to many bits representations),
// we call this method quadBitsEqual rather than quadEqual
public static boolean quadBitsEqual(long[] a, long[] b) {
if (a == null || b == null) {
throw new NumberFormatException("null");
}
if (a.length != 2 || b.length != 2) {
throw new NumberFormatException("not a quad");
}
return (a[1] == b[1] && a[0] == b[0]);
}
/**
* Round.
* <p>
* Round mode is one of {
* <code>ROUND_UP, ROUND_DOWN, ROUND_CEILING, ROUND_FLOOR,
* ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN,
* ROUND_HALF_CEILING, ROUND_HALF_FLOOR, ROUND_HALF_ODD,
* ROUND_UNNECESSARY, DEFAULT_ROUND_MODE (==ROUND_HALF_UP)</code> .
* <p>
* If rounding isn't necessary, i.e. this Rational is an integer, [as an
* optimization] this Rational is returned.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public Rational round(int roundMode) {
// optimization
// return self if we don't need to round, independent of rounding mode
if (isInteger()) {
return this;
}
return new Rational(
// [rounding step, possible loss of precision step]
roundToBigInteger(roundMode));
}
/**
* Round by default mode (ROUND_HALF_UP).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public Rational round() {
// [rounding step, possible loss of precision step]
return round(DEFAULT_ROUND_MODE);
}
/**
* Floor, round towards negative infinity.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public Rational floor() {
// [rounding step, possible loss of precision step]
return round(ROUND_FLOOR);
}
/**
* Ceiling, round towards positive infinity.
* <p>
* Possible loss of precision.
*/
// [Name: see class Math.]
// @PrecisionLoss
public Rational ceil() {
// [rounding step, possible loss of precision step]
return round(ROUND_CEILING);
}
/**
* Truncate, round towards zero.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public Rational truncate() {
// [rounding step, possible loss of precision step]
return round(ROUND_DOWN);
}
/**
* Integer part.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public Rational integerPart() {
// [rounding step, possible loss of precision step]
return round(ROUND_DOWN);
}
/**
* Fractional part.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
public Rational fractionalPart() {
// this==ip+fp; sign(fp)==sign(this)
// [possible loss of precision step]
return subtract(integerPart());
}
/**
* Return an array of Rationals with both integer and fractional part.
* <p>
* Integer part is returned at offset 0; fractional part at offset 1.
*/
public Rational[] integerAndFractionalPart() {
// note: this duplicates fractionalPart() code, for speed.
final Rational[] pp = new Rational[2];
final Rational ip = integerPart();
pp[0] = ip;
pp[1] = subtract(ip);
return pp;
}
/**
* Clone the current Rational.
*/
@Override
public Rational clone() throws CloneNotSupportedException {
return (Rational) super.clone();
}
//
// PRIVATE METHODS
//
/**
* Normalize Rational. Denominator will be positive, numerator and
* denominator will have no common divisor. BigIntegers -1, 0, 1 will be set
* to constants for later comparison speed.
*/
private void normalize() {
// note: don't call anything that depends on a normalized this.
// i.e.: don't call most (or all) of the Rational methods.
if (numerator == null || denominator == null) {
throw new NumberFormatException("null");
}
// [these are typically cheap.]
int numeratorSignum = numerator.signum();
int denominatorSignum = denominator.signum();
// note: we don't throw on denominatorSignum==0. that'll be done
// elsewhere.
// if (denominatorSignum == 0) {
// throw new NumberFormatException("quotient zero");
// }
if (numeratorSignum == 0 && denominatorSignum == 0) {
// [typically not reached, due to earlier tests.]
// [both for speed]
numerator = BIG_INTEGER_ZERO;
denominator = BIG_INTEGER_ZERO;
return;
}
if (numeratorSignum == 0) {
denominator = BIG_INTEGER_ONE;
// [for speed]
numerator = BIG_INTEGER_ZERO;
return;
}
if (denominatorSignum == 0) {
// [typically not reached, due to earlier tests.]
numerator = BIG_INTEGER_ONE;
// [for speed]
denominator = BIG_INTEGER_ZERO;
return;
}
// optimization
// check the frequent case of denominator==1, for speed.
// note: this only covers the normalized-for-speed 1-case.
if (denominator == BIG_INTEGER_ONE) {
// [for [later] speed]
numerator = bigIntegerValueOf(numerator);
return;
}
// optimization
// check the symmetric case too, for speed.
// note: this only covers the normalized-for-speed 1-case.
if ((numerator == BIG_INTEGER_ONE || numerator == BIG_INTEGER_MINUS_ONE)
&& denominatorSignum > 0) {
// [for [later] speed]
denominator = bigIntegerValueOf(denominator);
return;
}
// setup torn apart for speed
BigInteger numeratorApart = numerator;
BigInteger denominatorApart = denominator;
if (denominatorSignum < 0) {
numerator = numerator.negate();
denominator = denominator.negate();
numeratorSignum = -numeratorSignum;
denominatorSignum = -denominatorSignum;
denominatorApart = denominator;
if (numeratorSignum > 0) {
numeratorApart = numerator;
}
}
else {
if (numeratorSignum < 0) {
numeratorApart = numerator.negate();
}
}
final BigInteger gcd = numeratorApart.gcd(denominatorApart);
// test: optimization (body: not)
if (!bigIntegerIsOne(gcd)) {
numerator = numerator.divide(gcd);
denominator = denominator.divide(gcd);
}
// for [later] speed, and normalization generally
numerator = bigIntegerValueOf(numerator);
denominator = bigIntegerValueOf(denominator);
}
/**
* Normalize Rational. [Convenience method to normalize(void).]
*/
private void normalizeFrom(BigInteger numerator, BigInteger denominator) {
this.numerator = numerator;
this.denominator = denominator;
normalize();
}
/**
* Normalize Rational. [Convenience method to normalize(void).]
*/
private void normalizeFrom(Rational that) {
if (that == null) {
throw new NumberFormatException("null");
}
normalizeFrom(that.numerator, that.denominator);
}
/**
* Check constraints on radixes. Radix may not be negative or less than two.
*/
private static void checkRadix(int radix) {
if (radix < 0) {
throw new NumberFormatException("radix negative");
}
if (radix < 2) {
throw new NumberFormatException("radix too small");
}
// note: we don't check for "radix too large";
// that's left to BigInteger.toString(radix)
// [i.e.: we don't really mind whether the underlying
// system supports base36, or base62, or even more]
}
/**
* Check some of the integer format constraints.
*/
private static void checkNumberFormat(String strNumber) {
// "x", "-x", "+x", "", "-", "+"
if (strNumber == null) {
throw new NumberFormatException("null");
}
// note: 'embedded sign' catches both-signs cases too.
final int p = strNumber.indexOf('+');
final int m = strNumber.indexOf('-');
final int pp = (p == -1 ? -1 : strNumber.indexOf('+', p + 1));
final int mm = (m == -1 ? -1 : strNumber.indexOf('-', m + 1));
if ((p != -1 && p != 0) || (m != -1 && m != 0) || pp != -1 || mm != -1) {
// embedded sign. this covers the both-signs case.
throw new NumberFormatException("embedded sign");
}
}
/**
* Check number format for fraction part.
*/
private static void checkFractionFormat(String strFraction) {
if (strFraction == null) {
throw new NumberFormatException("null");
}
if (strFraction.indexOf('+') != -1 || strFraction.indexOf('-') != -1) {
throw new NumberFormatException("sign in fraction");
}
}
/**
* Check number input for Java's string representations of doubles/floats
* that are unsupported: "NaN" and "Infinity" (with or without sign).
*/
private static void checkNaNAndInfinity(String strNumber, int radix) {
// the strings may actually be valid given a large enough radix
// (e.g. base 36), so limit the radix/check
if (radix > 16) {
return;
}
// [null and empty string check]
final int length = (strNumber == null ? 0 : strNumber.length());
if (length < 1) {
return;
}
// optimization (String.equals and even more String.equalsIgnoreCase
// are quite expensive, charAt and switch aren't)
// test for last character in strings below, both cases
switch (strNumber.charAt(length - 1)) {
case 'N':
case 'n':
case 'y':
case 'Y':
break;
default:
return;
}
if (strNumber.equalsIgnoreCase("NaN")
|| strNumber.equalsIgnoreCase("Infinity")
|| strNumber.equalsIgnoreCase("+Infinity")
|| strNumber.equalsIgnoreCase("-Infinity")) {
throw new NumberFormatException(strNumber);
}
}
/**
* Check constraints on radixes. [Convenience method to checkRadix(radix).]
*/
private static void checkRadixArgument(int radix) {
try {
checkRadix(radix);
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage());
}
}
/**
* Proxy to BigInteger.valueOf(). Speeds up comparisons by using constants.
*/
private static BigInteger bigIntegerValueOf(long number) {
// return the internal constants used for checks if possible.
// optimization
// check whether it's outside int range.
// actually check a much narrower range, fitting the switch below.
if (number >= -16 && number <= 16) {
// note: test above needed to make the cast below safe
// jump table, for speed
switch ((int) number) {
case 0:
return BIG_INTEGER_ZERO;
case 1:
return BIG_INTEGER_ONE;
case -1:
return BIG_INTEGER_MINUS_ONE;
case 2:
return BIG_INTEGER_TWO;
case -2:
return BIG_INTEGER_MINUS_TWO;
case 10:
return BIG_INTEGER_TEN;
case 16:
return BIG_INTEGER_SIXTEEN;
}
}
return BigInteger.valueOf(number);
}
/**
* Convert BigInteger to its constant if possible. Speeds up later
* comparisons by using constants.
*/
private static BigInteger bigIntegerValueOf(BigInteger number) {
// note: these tests are quite expensive,
// so they should be minimized to a reasonable amount.
// priority in the tests: 1, 0, -1;
// two phase testing.
// cheap tests first.
// optimization
if (number == BIG_INTEGER_ONE) {
return number;
}
// optimization
if (number == BIG_INTEGER_ZERO) {
// [typically not reached, since zero is handled specially.]
return number;
}
// optimization
if (number == BIG_INTEGER_MINUS_ONE) {
return number;
}
// more expensive tests later.
// optimization
if (number.equals(BIG_INTEGER_ONE)) {
return BIG_INTEGER_ONE;
}
// optimization
if (number.equals(BIG_INTEGER_ZERO)) {
// [typically not reached from normalize().]
return BIG_INTEGER_ZERO;
}
// optimization
if (number.equals(BIG_INTEGER_MINUS_ONE)) {
return BIG_INTEGER_MINUS_ONE;
}
// note: BIG_INTEGER_TWO et al. _not_ used for checks
// and therefore not replaced by constants_here_.
// this speeds up tests.
// not a known constant
return number;
}
/**
* Proxy to (new BigInteger()). Speeds up comparisons by using constants.
*/
private static BigInteger bigIntegerValueOf(String strNumber, int radix) {
// note: mind the radix.
// however, 0/1/-1 are not a problem.
// _often_ used strings (e.g. 0 for empty fraction and
// 1 for empty denominator), for speed.
// optimization
if (strNumber.equals("1")) {
return BIG_INTEGER_ONE;
}
// optimization
if (strNumber.equals("0")) {
return BIG_INTEGER_ZERO;
}
// optimization
if (strNumber.equals("-1")) {
// typically not reached, due to [private] usage pattern,
// i.e. the sign is cut before
return BIG_INTEGER_MINUS_ONE;
}
// note: BIG_INTEGER_TWO et al. _not_ used for checks
// and therefore even less valuable.
// there's a tradeoff between speeds of these tests
// and being consistent in using all constants
// (at least with the common radixes).
// optimization
if (radix > 2) {
if (strNumber.equals("2")) {
return BIG_INTEGER_TWO;
}
if (strNumber.equals("-2")) {
// typically not reached, due to [private] usage pattern,
// i.e. the sign is cut before
return BIG_INTEGER_MINUS_TWO;
}
}
// optimization
if (strNumber.equals("10")) {
switch (radix) {
case 2:
return BIG_INTEGER_TWO;
case 10:
return BIG_INTEGER_TEN;
case 16:
return BIG_INTEGER_SIXTEEN;
}
}
// optimization
if (radix == 10 && strNumber.equals("16")) {
return BIG_INTEGER_SIXTEEN;
}
// note: not directly finding the other [radix'] representations
// of 10 and 16 in the code above
// use the constants if possible
return bigIntegerValueOf(new BigInteger(strNumber, radix));
}
/**
* Proxy to BigInteger.equals(). For speed.
*/
private static boolean bigIntegerEquals(BigInteger n, BigInteger m) {
// optimization first test is for speed.
if (n == m) {
return true;
}
return n.equals(m);
}
/**
* Zero (0) value predicate. [For convenience and speed.]
*/
private static boolean bigIntegerIsZero(BigInteger n) {
// optimization first test is for speed.
if (n == BIG_INTEGER_ZERO) {
return true;
}
// well, this is also optimized for speed a bit.
return (n.signum() == 0);
}
/**
* One (1) value predicate. [For convenience and speed.]
*/
private static boolean bigIntegerIsOne(BigInteger n) {
// optimization first test is for speed.
if (n == BIG_INTEGER_ONE) {
return true;
}
return bigIntegerEquals(n, BIG_INTEGER_ONE);
}
/**
* Minus-one (-1) value predicate. [For convenience and speed.]
*/
private static boolean bigIntegerIsMinusOne(BigInteger n) {
// optimization
// first test is for speed.
if (n == BIG_INTEGER_MINUS_ONE) {
return true;
}
return bigIntegerEquals(n, BIG_INTEGER_MINUS_ONE);
}
/**
* Negative value predicate.
*/
private static boolean bigIntegerIsNegative(BigInteger n) {
return (n.signum() < 0);
}
/**
* Proxy to BigInteger.multiply().
*
* For speed. The more common cases of integers (denominator == 1) are
* optimized.
*/
private static BigInteger bigIntegerMultiply(BigInteger n, BigInteger m) {
// optimization: one or both operands are zero.
if (bigIntegerIsZero(n) || bigIntegerIsZero(m)) {
return BIG_INTEGER_ZERO;
}
// optimization: second operand is one (i.e. neutral element).
if (bigIntegerIsOne(m)) {
return n;
}
// optimization: first operand is one (i.e. neutral element).
if (bigIntegerIsOne(n)) {
return m;
}
// optimization
if (bigIntegerIsMinusOne(m)) {
// optimization
if (bigIntegerIsMinusOne(n)) {
// typically not reached due to earlier test(s)
return BIG_INTEGER_ONE;
}
return n.negate();
}
// optimization
if (bigIntegerIsMinusOne(n)) {
// [m is not -1, see test above]
return m.negate();
}
// default case. [this would handle all cases.]
return n.multiply(m);
}
/**
* Proxy to BigInteger.pow(). For speed.
*/
private static BigInteger bigIntegerPower(BigInteger n, int exponent) {
// generally expecting exponent>=0
// (there's nor much use in inverting in the integer domain)
// the checks for exponent<0 below are done all the same
// optimization jump table, for speed.
switch (exponent) {
case 0:
if (bigIntegerIsZero(n)) {
// typically not reached, due to earlier test / [private] usage
// pattern
throw new ArithmeticException("zero exp zero");
}
return BIG_INTEGER_ONE;
case 1:
return n;
}
// optimization
if (bigIntegerIsZero(n) && exponent > 0) {
// note: exponent==0 already handled above
// typically not reached, due to earlier test
return BIG_INTEGER_ZERO;
}
// optimization
if (bigIntegerIsOne(n)) {
return BIG_INTEGER_ONE;
}
// optimization
if (bigIntegerIsMinusOne(n)) {
return (exponent % 2 == 0 ? BIG_INTEGER_ONE : BIG_INTEGER_MINUS_ONE);
}
return n.pow(exponent);
}
/**
* Binary logarithm rounded towards floor (towards negative infinity).
*/
// @PrecisionLoss
private static int bigIntegerLogarithm2(BigInteger n) {
if (bigIntegerIsZero(n)) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of zero");
}
if (bigIntegerIsNegative(n)) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of negative number");
}
// take this as a start
// (don't wholly rely on bitLength() having the same meaning as log2)
int exponent = n.bitLength() - 1;
if (exponent < 0) {
exponent = 0;
}
BigInteger p = BIG_INTEGER_TWO.pow(exponent + 1);
while (n.compareTo(p) >= 0) {
// typically not reached
p = p.multiply(BIG_INTEGER_TWO);
exponent++;
}
p = p.divide(BIG_INTEGER_TWO);
while (n.compareTo(p) < 0) {
// typically not reached
p = p.divide(BIG_INTEGER_TWO);
exponent--;
}
// [possible loss of precision step]
return exponent;
}
/**
* Proxy to BigInteger.toString(int radix).
*/
private static String stringValueOf(BigInteger n, int radix) {
return n.toString(radix);
}
/**
* Proxy to stringValueOf(bigIntegerValueOf(long), radix); take the same
* route to format [long/bigint] integer numbers [despite the overhead].
*/
private static String stringValueOf(long n, int radix) {
return stringValueOf(bigIntegerValueOf(n), radix);
}
/**
* Convert a IEEE 754 floating point number (of different sizes, as array of
* longs, big endian) to a Rational.
*/
private static Rational fromIEEE754(long[] value0, int fractionSize,
int exponentSize) {
if (value0 == null) {
throw new NumberFormatException("null");
}
// note: the long(s) in the input array are considered unsigned,
// so expansion operations (to e.g. Rational) and [right-] shift
// operations
// (unlike assignment, equality-test, narrowing, and/or operations)
// must be appropriately chosen
Rational fraction0 = ZERO;
// start at the little end of the [bigendian] input
int i = value0.length - 1;
while (fractionSize >= 64) {
if (i < 0) {
throw new NumberFormatException("not enough bits");
}
// mind the long (value0[i]) being unsigned
fraction0 = fraction0.add(valueOfUnsigned(value0[i])).divide(
TWO_POWER_64);
fractionSize -= 64;
i--;
}
// the rest must now fit into value0[0] (a long),
// i.e. we don't support exponentSize > 63 at the moment;
// as the power() method accepts ints (not longs),
// the restriction is actually even on <= 31 bits
if (i < 0) {
throw new NumberFormatException("no bits");
}
if (i > 0) {
throw new NumberFormatException("excess bits");
}
long value = value0[0];
// [fractionSize [now is] < 64 by loop above]
final long fractionMask = ((long) 1 << fractionSize) - 1;
final long rawFraction = value & fractionMask;
value >>>= fractionSize;
// [exponentSize < 32 by [private] usage pattern; rawExponent < 2**31]
final int exponentMask = (1 << exponentSize) - 1;
final int exponentBias = (1 << (exponentSize - 1)) - 1;
final int rawExponent = (int) value & exponentMask;
value >>>= exponentSize;
final int signSize = 1;
final int signMask = (1 << signSize) - 1; // 1
final int rawSign = (int) value & signMask;
value >>>= signSize;
if (value != 0) {
throw new NumberFormatException("excess bits");
}
// check for Infinity and NaN (IEEE 754 rawExponent at its maximum)
if (rawExponent == exponentMask) {
// (no fraction bits means one of the Infinities; else NaN)
throw new NumberFormatException(rawFraction == 0
&& fraction0.isZero() ? (rawSign == 0 ? "Infinity"
: "-Infinity") : "NaN");
}
// optimization -- avoids power() calculation below
// (isZero and zero multiply) are cheap
// check for zero (IEEE 754 rawExponent zero and no fraction bits)
if (rawExponent == 0 && rawFraction == 0 && fraction0.isZero()) {
return ZERO;
}
// handle subnormal numbers too (with rawExponent==0)
// [fractionSize [still is] < 64]
final long mantissa1 = rawFraction
| (rawExponent == 0 ? (long) 0 : (long) 1 << fractionSize);
// mind mantissa1 being unsigned
final Rational mantissa = fraction0.add(valueOfUnsigned(mantissa1));
// (subnormal numbers; exponent is one off)
// [rawExponent < 2**31; exponentBias < 2**30]
final int exponent = rawExponent - exponentBias
+ (rawExponent == 0 ? 1 : 0) - fractionSize;
final int sign = (rawSign == 0 ? 1 : -1);
return valueOf(2).pow(exponent).multiply(mantissa).multiply(sign);
}
/**
* Convert a Rational to a IEEE 754 floating point number (of different
* sizes, as array of longs, big endian).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
private static long[] toIEEE754(Rational value, int fractionSize,
int exponentSize) {
if (value == null) {
throw new NumberFormatException("null");
}
// [needed size: fractionSize+exponentSize+1; round up bits to a
// multiple of 64]
final long[] out0 = new long[(fractionSize + exponentSize + 1 + (64 - 1)) / 64];
if (value.isZero()) {
// 0.0
// note: as we don't keep a sign with our ZERO,
// we never return IEEE 754 -0.0 here
for (int j = 0; j < out0.length; j++) {
out0[j] = 0;
}
return out0;
}
final boolean negate = value.isNegative();
if (negate) {
value = value.negate();
}
// need to scale to this to get the full mantissa
int exponent = fractionSize;
final Rational lower = valueOf(2).pow(fractionSize);
final Rational upper = lower.multiply(2);
// optimization, and a good guess (but not exact in all cases)
final int scale = lower.divide(value).logarithm2();
value = value.multiply(valueOf(2).pow(scale));
exponent -= scale;
while (value.compareTo(lower) < 0) {
// [typically done zero or one time]
value = value.multiply(2);
exponent--;
}
while (value.compareTo(upper) >= 0) {
// [typically not reached]
value = value.divide(2);
exponent++;
}
// [rounding step, possible loss of precision step]
BigInteger mantissa = value.bigIntegerValue();
// adjust after [unfortunate] mantissa rounding
if (upper.compareTo(mantissa) <= 0) {
mantissa = mantissa.divide(BIG_INTEGER_TWO);
exponent++;
}
// start [to fill] at the little end of the [bigendian] output
int i = out0.length - 1;
int fractionSize1 = fractionSize;
while (fractionSize1 >= 64) {
final BigInteger[] divrem = mantissa
.divideAndRemainder(BIG_INTEGER_TWO_POWER_64);
// [according to BigInteger javadoc] this takes the least
// significant 64 bits;
// i.e. in this case the long is considered unsigned, as we want it
out0[i] = divrem[1].longValue();
fractionSize1 -= 64;
mantissa = divrem[0];
i--;
}
// the rest must now fit into out0[0]
if (i < 0) {
// not reached
throw new NumberFormatException("too many bits");
}
if (i > 0) {
// not reached
throw new NumberFormatException("not enough bits");
}
long fraction = mantissa.longValue();
final int exponentBias = (1 << (exponentSize - 1)) - 1;
exponent += exponentBias;
final int maximalExponent = (1 << exponentSize) - 1;
if (exponent >= maximalExponent) {
// overflow
// throw new NumberFormatException("overflow");
// [positive or negative] infinity
exponent = maximalExponent;
fraction = 0;
for (int j = 1; j < out0.length; j++) {
out0[j] = 0;
}
// [keep sign]
} else if (exponent <= 0) {
// handle subnormal numbers too
// [with know loss of precision]
// drop one bit, while keeping the exponent
int s = 1;
// [need not shift more than fractionSize]
final int n = (-exponent > fractionSize ? fractionSize : -exponent);
s += n;
exponent += n;
// [possible loss of precision step]
fraction = shiftrx(fraction, out0, 1, s);
boolean zero = (fraction == 0);
for (int j = 1; zero && j < out0.length; j++) {
zero = (out0[j] == 0);
}
if (zero) {
// underflow
// throw new NumberFormatException("underflow");
// 0.0 or -0.0; i.e.: keep sign
exponent = 0;
// [nonzero == 0 implies the rest of the fraction is zero as
// well]
}
}
// cut implied most significant bit
// [unless with subnormal numbers]
if (exponent != 0) {
fraction &= ~((long) 1 << fractionSize1);
}
long out = 0;
out |= (negate ? 1 : 0);
out <<= exponentSize;
out |= exponent;
out <<= fractionSize1;
out |= fraction;
out0[0] = out;
return out0;
}
/**
* Shift right, while propagating shifted bits (long[] is bigendian).
*/
private static long shiftrx(long a, long[] b, int boff, int n) {
while (n > 0) {
final int n2 = (n < 63 ? n : 63);
final long m = ((long) 1 << n2) - 1;
long c = a & m;
a >>>= n2;
for (int i = boff; i < b.length; i++) {
final long t = b[i] & m;
b[i] >>>= n2;
b[i] |= (c << (64 - n2));
c = t;
}
n -= n2;
}
return a;
}
/**
* Fixed dot-format "[-]i.f" string representation, with a precision.
* <p>
* Precision may be negative, in which case the rounding affects digits left
* of the dot, i.e. the integer part of the number, as well.
* <p>
* The exponentFormat parameter allows for shorter [intermediate] string
* representation, an optimization, e.g. used with toStringExponent.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
private String toStringDot(int precision, int radix, boolean exponentFormat) {
checkRadixArgument(radix);
Rational scaleValue = new Rational(bigIntegerPower(
bigIntegerValueOf(radix), (precision < 0 ? -precision
: precision)));
if (precision < 0) {
scaleValue = scaleValue.invert();
}
// default round mode.
// [rounding step, possible loss of precision step]
Rational n = multiply(scaleValue).round();
final boolean negt = n.isNegative();
if (negt) {
n = n.negate();
}
String s = n.toString(radix);
if (exponentFormat) {
// note that this is _not_ the scientific notation
// (one digit left of the dot exactly),
// but some intermediate representation suited for post processing
// [leaving away the left/right padding steps
// is more performant in time and memory space]
s = s + "E" + stringValueOf(-precision, radix);
}
else {
if (precision >= 0) {
// left-pad with '0'
while (s.length() <= precision) {
s = "0" + s;
}
final int dot = s.length() - precision;
final String i = s.substring(0, dot);
final String f = s.substring(dot);
s = i;
if (f.length() > 0) {
s = s + "." + f;
}
}
else {
if (!s.equals("0")) {
// right-pad with '0'
for (int i = -precision; i > 0; i--) {
s = s + "0";
}
}
}
}
// add sign
if (negt) {
s = "-" + s;
}
return s;
}
/**
* Transform a [intermediate] dot representation to an exponent-format
* representation.
*/
private static String toExponentRepresentation(String s, int radix) {
// skip '+'
if (s.length() > 0 && s.charAt(0) == '+') {
// typically not reached, due to [private] usage pattern
s = s.substring(1);
}
// handle '-'
boolean negt = false;
if (s.length() > 0 && s.charAt(0) == '-') {
negt = true;
s = s.substring(1);
}
// skip initial zeros
while (s.length() > 0 && s.charAt(0) == '0') {
s = s.substring(1);
}
// check for and handle exponent
// handle only upper case 'E' (we know we use that in earlier steps);
// this allows any base using lower case characters
int exponent0 = 0;
final int exp = s.indexOf('E');
if (exp != -1) {
final String se = s.substring(exp + 1);
s = s.substring(0, exp);
exponent0 = (new Rational(se, radix)).intValueExact();
}
String si, sf;
int exponent;
final int dot = s.indexOf('.');
if (dot != -1) {
if (dot == 0) {
// possibly more insignificant digits
s = s.substring(1);
exponent = -1;
while (s.length() > 0 && s.charAt(0) == '0') {
s = s.substring(1);
exponent--;
}
if (s.equals("")) {
// typically not reached, due to [private] usage pattern
return "0";
}
// first significant digit
si = s.substring(0, 1);
sf = s.substring(1);
}
else {
// initial [significant] digit
si = s.substring(0, 1);
sf = s.substring(1, dot);
exponent = sf.length();
sf = sf + s.substring(dot + 1);
}
}
else {
// [note that we just cut the zeros above]
if (s.equals("")) {
return "0";
}
// initial [significant] digit
si = s.substring(0, 1);
// rest
sf = s.substring(1);
exponent = sf.length();
}
exponent += exponent0;
// drop trailing zeros
while (sf.length() > 0 && sf.charAt(sf.length() - 1) == '0') {
sf = sf.substring(0, sf.length() - 1);
}
s = si;
if (!sf.equals("")) {
s = s + "." + sf;
}
if (exponent != 0) {
s = s + "E" + stringValueOf(exponent, radix);
}
if (negt) {
s = "-" + s;
}
return s;
}
/**
* Return binary logarithm rounded towards floor (towards negative
* infinity).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
private int logarithm2() {
if (isZero()) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of zero");
}
if (isNegative()) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of negative number");
}
final boolean inverted = (compareTo(ONE) < 0);
final Rational a = (inverted ? invert() : this);
// [possible loss of precision step]
final int log = bigIntegerLogarithm2(a.bigIntegerValue());
return (inverted ? -(log + 1) : log);
}
/**
* Return logarithm rounded towards floor (towards negative infinity).
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
private int logarithm(int base) {
// optimization
if (base == 2) {
return logarithm2();
}
if (isZero()) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of zero");
}
if (isNegative()) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of negative number");
}
// if (base < 2) {
// // [typically not reached, due to [private] usage pattern]
// throw new ArithmeticException("bad base");
// }
if (base < 0) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("negative base");
}
if (base < 2) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("base too small");
}
final boolean inverted = (compareTo(ONE) < 0);
Rational a = (inverted ? invert() : this);
final Rational bbase = valueOf(base);
// optimization -- we could start from n=0
// initial guess
// [base 2 handled earlier]
// [unusual bases are handled a bit less performant]
final Rational lbase = (base == 10 ? LOGARITHM_TEN_GUESS
: base == 16 ? LOGARITHM_SIXTEEN : valueOf(ilog2(base)));
int n = valueOf(a.logarithm2()).divide(lbase).intValue();
a = a.divide(bbase.pow(n));
// note that these steps are needed anyway:
// LOGARITHM_TEN_GUESS above e.g. is (as the name suggests)
// a guess only (since most logarithms usually can't be expressed
// as rationals generally); odd bases or off even worse
while (a.compareTo(bbase) >= 0) {
a = a.divide(bbase);
n++;
}
while (a.compareTo(ONE) < 0) {
a = a.multiply(bbase);
n--;
}
// [possible loss of precision step]
return (inverted ? -(n + 1) : n);
}
/**
* Return binary logarithm of an int.
*/
private static int ilog2(int n) {
if (n == 0) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of zero");
}
if (n < 0) {
// [typically not reached, due to [private] usage pattern]
throw new ArithmeticException("logarithm of negative number");
}
int i = 0;
// as this method is used in the context of [small] bases/radixes,
// we expect less than 8 iterations at most, so no need to optimize
while (n > 1) {
n /= 2;
i++;
}
return i;
}
/**
* Remainder or modulus of non-negative values. Helper function to
* remainder() and modulus().
*/
private Rational remainderOrModulusOfPositive(Rational that) {
final int thisSignum = signum();
final int thatSignum = that.signum();
if (thisSignum < 0 || thatSignum < 0) {
// typically not reached, due to [private] usage pattern
throw new IllegalArgumentException("negative values(s)");
}
if (thatSignum == 0) {
// typically not reached, due to [private] usage pattern
throw new ArithmeticException("division by zero");
}
// optimization
if (thisSignum == 0) {
return ZERO;
}
return new Rational(bigIntegerMultiply(numerator, that.denominator)
.remainder(bigIntegerMultiply(denominator, that.numerator)),
bigIntegerMultiply(denominator, that.denominator));
}
/**
* Round to BigInteger helper function. Internally used.
* <p>
* Possible loss of precision.
*/
// @PrecisionLoss
private BigInteger roundToBigInteger(int roundMode) {
// note: remainder and its duplicate are calculated for all cases.
BigInteger numerator = this.numerator;
final BigInteger denominator = this.denominator;
final int signum = numerator.signum();
// optimization
if (signum == 0) {
// [typically not reached due to earlier test for integerp]
return BIG_INTEGER_ZERO;
}
// keep info on the sign
final boolean isPositive = (signum > 0);
// operate on positive values
if (!isPositive) {
numerator = numerator.negate();
}
final BigInteger[] divrem = numerator.divideAndRemainder(denominator);
BigInteger dv = divrem[0];
final BigInteger r = divrem[1];
// return if we don't need to round, independent of rounding mode
if (bigIntegerIsZero(r)) {
// [typically not reached since remainder is not zero
// with normalized that are not integerp]
if (!isPositive) {
dv = dv.negate();
}
return dv;
}
boolean up = false;
final int comp = r.multiply(BIG_INTEGER_TWO).compareTo(denominator);
switch (roundMode) {
// Rounding mode to round away from zero.
case ROUND_UP:
up = true;
break;
// Rounding mode to round towards zero.
case ROUND_DOWN:
up = false;
break;
// Rounding mode to round towards positive infinity.
case ROUND_CEILING:
up = isPositive;
break;
// Rounding mode to round towards negative infinity.
case ROUND_FLOOR:
up = !isPositive;
break;
// Rounding mode to round towards "nearest neighbor" unless both
// neighbors are equidistant, in which case round up.
case ROUND_HALF_UP:
up = (comp >= 0);
break;
// Rounding mode to round towards "nearest neighbor" unless both
// neighbors are equidistant, in which case round down.
case ROUND_HALF_DOWN:
up = (comp > 0);
break;
case ROUND_HALF_CEILING:
up = (comp != 0 ? comp > 0 : isPositive);
break;
case ROUND_HALF_FLOOR:
up = (comp != 0 ? comp > 0 : !isPositive);
break;
// Rounding mode to round towards the "nearest neighbor" unless both
// neighbors are equidistant, in which case, round towards the even
// neighbor.
case ROUND_HALF_EVEN:
up = (comp != 0 ? comp > 0 : !bigIntegerIsZero(dv
.remainder(BIG_INTEGER_TWO)));
break;
case ROUND_HALF_ODD:
up = (comp != 0 ? comp > 0 : bigIntegerIsZero(dv
.remainder(BIG_INTEGER_TWO)));
break;
// Rounding mode to assert that the requested operation has an exact
// result, hence no rounding is necessary. If this rounding mode is
// specified on an operation that yields an inexact result, an
// ArithmeticException is thrown.
case ROUND_UNNECESSARY:
if (!bigIntegerIsZero(r)) {
throw new ArithmeticException("rounding necessary");
}
// [typically not reached due to earlier test for integerp]
up = false;
break;
default:
throw new IllegalArgumentException("unsupported rounding mode");
}
if (up) {
dv = dv.add(BIG_INTEGER_ONE);
}
if (!isPositive) {
dv = dv.negate();
}
// [rounding step, possible loss of precision step]
return dv;
}
private boolean reduced = false;
private void reduce () {
if ( ! reduced && ! bigIntegerIsZero(numerator)) {
BigInteger common = numerator.gcd(denominator);
numerator = numerator.divide(common);
denominator = denominator.divide(common);
reduced = true;
}
}
}
|
- undid changes to Rational after realizing that fractions were already normalized at construction.
|
src/main/java/com/sri/ai/util/math/Rational.java
|
- undid changes to Rational after realizing that fractions were already normalized at construction.
|
<ide><path>rc/main/java/com/sri/ai/util/math/Rational.java
<ide> return true;
<ide> }
<ide>
<del> this.reduce(); // make sure they have the same fraction if representing the same value.
<del> that.reduce();
<del>
<ide> boolean result =
<ide> bigIntegerEquals(that.numerator, numerator) &&
<ide> bigIntegerEquals(that.denominator, denominator);
<ide> public int hashCode() {
<ide> // lazy init for optimization
<ide> if (hashCode == 0) {
<del> reduce(); // make sure all rationals with the same value have the hash code computed from the same fraction.
<ide> hashCode = ((numerator.hashCode() + 1) * (denominator.hashCode() + 2));
<ide> }
<ide> return hashCode;
<ide> // [rounding step, possible loss of precision step]
<ide> return dv;
<ide> }
<del>
<del> private boolean reduced = false;
<del>
<del> private void reduce () {
<del> if ( ! reduced && ! bigIntegerIsZero(numerator)) {
<del> BigInteger common = numerator.gcd(denominator);
<del> numerator = numerator.divide(common);
<del> denominator = denominator.divide(common);
<del> reduced = true;
<del> }
<del> }
<ide> }
|
|
Java
|
apache-2.0
|
dac4b5157f69cf7b37a0dd189d552c543a68d8b8
| 0 |
realityforge/replicant,realityforge/replicant
|
package org.realityforge.replicant.server.ee;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Collection;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.persistence.EntityManager;
import javax.transaction.TransactionSynchronizationRegistry;
import org.realityforge.replicant.server.Change;
import org.realityforge.replicant.server.ChangeSet;
import org.realityforge.replicant.server.EntityMessage;
import org.realityforge.replicant.server.EntityMessageEndpoint;
import org.realityforge.replicant.server.MessageTestUtil;
import org.realityforge.replicant.shared.transport.ReplicantContext;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
public class ReplicationInterceptorTest
{
@BeforeMethod
public void setup()
{
ReplicantContextHolder.clean();
}
@Test
public void ensureNoChangesDoesNotResultInSave()
throws Exception
{
final TestInvocationContext context = new TestInvocationContext();
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
when( em.isOpen() ).thenReturn( true );
final Object result = interceptor.businessIntercept( context );
verify( em ).flush();
assertTrue( context.isInvoked() );
assertEquals( result, TestInvocationContext.RESULT );
assertNull( interceptor._messages );
}
@Test
public void ensureClosedEntityManagerDoesNotResultInFlushOrSave()
throws Exception
{
final TestInvocationContext context = new TestInvocationContext();
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
when( em.isOpen() ).thenReturn( false );
final Object result = interceptor.businessIntercept( context );
verify( em, never() ).flush();
assertTrue( context.isInvoked() );
assertEquals( result, TestInvocationContext.RESULT );
assertNull( interceptor._messages );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "1" );
}
@Test
public void ensureChangesResultInSave()
throws Exception
{
final TestInvocationContext context = new TestInvocationContext();
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
final EntityMessage message = MessageTestUtil.createMessage( "ID", 1, 0, "r1", "r2", "a1", "a2" );
EntityMessageCacheUtil.getEntityMessageSet( registry ).merge( message );
when( em.isOpen() ).thenReturn( true );
ReplicantContextHolder.put( ReplicantContext.SESSION_ID_KEY, "s1" );
ReplicantContextHolder.put( ReplicantContext.REQUEST_ID_KEY, "r1" );
final Object result = interceptor.businessIntercept( context );
verify( em ).flush();
// Make sure clear is called
assertNull( ReplicantContextHolder.get( ReplicantContext.SESSION_ID_KEY ) );
assertTrue( context.isInvoked() );
assertEquals( result, TestInvocationContext.RESULT );
assertEquals( interceptor._sessionID, "s1" );
assertEquals( interceptor._requestID, "r1" );
assertNotNull( interceptor._messages );
assertTrue( interceptor._messages.contains( message ) );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "0" );
}
@Test
public void ensureUserCanOverrideRequestCompleteFlag()
throws Exception
{
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final TestInvocationContext context = new TestInvocationContext();
context.setRunnable( new Runnable()
{
@Override
public void run()
{
registry.putResource( ReplicantContext.REQUEST_COMPLETE_KEY, Boolean.FALSE );
}
} );
final EntityManager entityManager = mock( EntityManager.class );
final TestReplicationInterceptor interceptor =
createInterceptor( registry, entityManager );
ReplicantContextHolder.put( ReplicantContext.SESSION_ID_KEY, "s1" );
ReplicantContextHolder.put( ReplicantContext.REQUEST_ID_KEY, "r1" );
when( entityManager.isOpen() ).thenReturn( true );
interceptor.businessIntercept( context );
assertTrue( context.isInvoked() );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "0" );
}
@Test
public void ensureSessionChangesResultInSave()
throws Exception
{
final TestInvocationContext context = new TestInvocationContext();
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
final EntityMessage message = MessageTestUtil.createMessage( "ID", 1, 0, "r1", "r2", "a1", "a2" );
EntityMessageCacheUtil.getSessionChanges( registry ).merge( new Change( message, 44, 77 ) );
when( em.isOpen() ).thenReturn( true );
ReplicantContextHolder.put( ReplicantContext.SESSION_ID_KEY, "s1" );
ReplicantContextHolder.put( ReplicantContext.REQUEST_ID_KEY, "r1" );
final Object result = interceptor.businessIntercept( context );
verify( em ).flush();
// Make sure clear is called
assertNull( ReplicantContextHolder.get( ReplicantContext.SESSION_ID_KEY ) );
assertTrue( context.isInvoked() );
assertEquals( result, TestInvocationContext.RESULT );
assertEquals( interceptor._sessionID, "s1" );
assertEquals( interceptor._requestID, "r1" );
assertNotNull( interceptor._messages );
assertEquals( interceptor._changeSet.getChanges().size(), 1 );
final Change change = interceptor._changeSet.getChanges().iterator().next();
assertEquals( change.getEntityMessage().getID(), message.getID() );
final Serializable expected = 77;
assertEquals( change.getChannels().get( 44 ), expected );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "0" );
}
@Test
public void ensureChanges_willBeCompleteIfNotRoutedToInitiatingSession()
throws Exception
{
final TestInvocationContext context = new TestInvocationContext();
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em, false );
final EntityMessage message = MessageTestUtil.createMessage( "ID", 1, 0, "r1", "r2", "a1", "a2" );
EntityMessageCacheUtil.getEntityMessageSet( registry ).merge( message );
when( em.isOpen() ).thenReturn( true );
interceptor.businessIntercept( context );
assertTrue( context.isInvoked() );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "1" );
}
@Test
public void ensureNestedInvocationsShouldExcept()
throws Exception
{
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
final EntityMessage message = MessageTestUtil.createMessage( "ID", 1, 0, "r1", "r2", "a1", "a2" );
EntityMessageCacheUtil.getEntityMessageSet( registry ).merge( message );
final TestInvocationContext context = new TestInvocationContext()
{
public Object proceed()
throws Exception
{
final TestInvocationContext innerContext = new TestInvocationContext();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor innerInterceptor = createInterceptor( registry, em );
when( em.isOpen() ).thenReturn( true );
innerInterceptor.businessIntercept( innerContext );
return super.proceed();
}
};
when( em.isOpen() ).thenReturn( true );
ReplicantContextHolder.put( ReplicantContext.SESSION_ID_KEY, "s1" );
ReplicantContextHolder.put( ReplicantContext.REQUEST_ID_KEY, "r1" );
try
{
interceptor.businessIntercept( context );
}
catch ( Exception e )
{
return;
}
fail("Expected to generate session due to nested contexts");
}
@Test
public void ensureChangesResultInSaveEvenIfException()
throws Exception
{
final TestInvocationContext context = new TestInvocationContext()
{
public Object proceed()
throws Exception
{
super.proceed();
throw new IllegalStateException();
}
};
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
final EntityMessage message = MessageTestUtil.createMessage( "ID", 1, 0, "r1", "r2", "a1", "a2" );
EntityMessageCacheUtil.getEntityMessageSet( registry ).merge( message );
try
{
when( em.isOpen() ).thenReturn( true );
interceptor.businessIntercept( context );
fail( "Expected proceed to result in exception" );
}
catch ( final IllegalStateException ise )
{
assertNull( ise.getMessage() );
}
assertTrue( context.isInvoked() );
assertNull( interceptor._sessionID );
assertNull( interceptor._requestID );
assertNotNull( interceptor._messages );
assertTrue( interceptor._messages.contains( message ) );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "0" );
}
@Test
public void ensureNoChangesResultIfInRollback()
throws Exception
{
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final TestInvocationContext context = new TestInvocationContext()
{
public Object proceed()
throws Exception
{
registry.setRollbackOnly();
return super.proceed();
}
};
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
final EntityMessage message = MessageTestUtil.createMessage( "ID", 1, 0, "r1", "r2", "a1", "a2" );
EntityMessageCacheUtil.getEntityMessageSet( registry ).merge( message );
when( em.isOpen() ).thenReturn( true );
final Object result = interceptor.businessIntercept( context );
assertTrue( context.isInvoked() );
assertNull( interceptor._sessionID );
assertNull( interceptor._requestID );
assertNull( interceptor._messages );
assertEquals( result, TestInvocationContext.RESULT );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "1" );
}
@Test
public void ensureNoSaveIfNoChanges()
throws Exception
{
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final TestInvocationContext context = new TestInvocationContext();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
//Create registry but no changes
EntityMessageCacheUtil.getEntityMessageSet( registry );
when( em.isOpen() ).thenReturn( true );
final Object result = interceptor.businessIntercept( context );
verify( em ).flush();
assertTrue( context.isInvoked() );
assertNull( interceptor._sessionID );
assertNull( interceptor._requestID );
assertNull( interceptor._messages );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "1" );
assertEquals( result, TestInvocationContext.RESULT );
}
private TestReplicationInterceptor createInterceptor( final TransactionSynchronizationRegistry registry,
final EntityManager entityManager )
throws Exception
{
return createInterceptor( registry, entityManager, true );
}
private TestReplicationInterceptor createInterceptor( final TransactionSynchronizationRegistry registry,
final EntityManager entityManager,
final boolean routeToSession )
throws Exception
{
final TestReplicationInterceptor interceptor = new TestReplicationInterceptor( entityManager, routeToSession );
setField( interceptor, "_registry", registry );
return interceptor;
}
private static void setField( final TestReplicationInterceptor interceptor,
final String fieldName,
final Object value )
throws Exception
{
final Field field = interceptor.getClass().getSuperclass().getDeclaredField( fieldName );
field.setAccessible( true );
field.set( interceptor, value );
}
static class TestReplicationInterceptor
extends AbstractReplicationInterceptor
implements EntityMessageEndpoint
{
String _sessionID;
String _requestID;
Collection<EntityMessage> _messages;
EntityManager _entityManager;
private final boolean _routeToSession;
private ChangeSet _changeSet;
TestReplicationInterceptor( final EntityManager entityManager, final boolean routeToSession )
{
_entityManager = entityManager;
_routeToSession = routeToSession;
}
@Override
public boolean saveEntityMessages( @Nullable final String sessionID,
@Nullable final String requestID,
@Nonnull final Collection<EntityMessage> messages,
@Nullable final ChangeSet changeSet )
{
if ( null != _messages )
{
fail( "saveEntityMessages called multiple times" );
}
_sessionID = sessionID;
_requestID = requestID;
_messages = messages;
_changeSet = changeSet;
return _routeToSession;
}
@Override
protected EntityManager getEntityManager()
{
return _entityManager;
}
@Override
protected EntityMessageEndpoint getEndpoint()
{
return this;
}
}
}
|
src/test/java/org/realityforge/replicant/server/ee/ReplicationInterceptorTest.java
|
package org.realityforge.replicant.server.ee;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Collection;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.persistence.EntityManager;
import javax.transaction.TransactionSynchronizationRegistry;
import org.realityforge.replicant.server.Change;
import org.realityforge.replicant.server.ChangeSet;
import org.realityforge.replicant.server.EntityMessage;
import org.realityforge.replicant.server.EntityMessageEndpoint;
import org.realityforge.replicant.server.MessageTestUtil;
import org.realityforge.replicant.shared.transport.ReplicantContext;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
public class ReplicationInterceptorTest
{
@BeforeMethod
public void setup()
{
ReplicantContextHolder.clean();
}
@Test
public void ensureNoChangesDoesNotResultInSave()
throws Exception
{
final TestInvocationContext context = new TestInvocationContext();
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
when( em.isOpen() ).thenReturn( true );
final Object result = interceptor.businessIntercept( context );
verify( em ).flush();
assertTrue( context.isInvoked() );
assertEquals( result, TestInvocationContext.RESULT );
assertNull( interceptor._messages );
}
@Test
public void ensureClosedEntityManagerDoesNotResultInFlushOrSave()
throws Exception
{
final TestInvocationContext context = new TestInvocationContext();
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
when( em.isOpen() ).thenReturn( false );
final Object result = interceptor.businessIntercept( context );
verify( em, never() ).flush();
assertTrue( context.isInvoked() );
assertEquals( result, TestInvocationContext.RESULT );
assertNull( interceptor._messages );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "1" );
}
@Test
public void ensureChangesResultInSave()
throws Exception
{
final TestInvocationContext context = new TestInvocationContext();
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
final EntityMessage message = MessageTestUtil.createMessage( "ID", 1, 0, "r1", "r2", "a1", "a2" );
EntityMessageCacheUtil.getEntityMessageSet( registry ).merge( message );
when( em.isOpen() ).thenReturn( true );
ReplicantContextHolder.put( ReplicantContext.SESSION_ID_KEY, "s1" );
ReplicantContextHolder.put( ReplicantContext.REQUEST_ID_KEY, "r1" );
final Object result = interceptor.businessIntercept( context );
verify( em ).flush();
// Make sure clear is called
assertNull( ReplicantContextHolder.get( ReplicantContext.SESSION_ID_KEY ) );
assertTrue( context.isInvoked() );
assertEquals( result, TestInvocationContext.RESULT );
assertEquals( interceptor._sessionID, "s1" );
assertEquals( interceptor._requestID, "r1" );
assertNotNull( interceptor._messages );
assertTrue( interceptor._messages.contains( message ) );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "0" );
}
@Test
public void ensureUserCanOverrideRequestCompleteFlag()
throws Exception
{
final TestInvocationContext context = new TestInvocationContext();
context.setRunnable( new Runnable()
{
@Override
public void run()
{
ReplicantContextHolder.put( ReplicantContext.REQUEST_COMPLETE_KEY, "0" );
}
} );
final TestReplicationInterceptor interceptor =
createInterceptor( new TestTransactionSynchronizationRegistry(), mock( EntityManager.class ) );
ReplicantContextHolder.put( ReplicantContext.SESSION_ID_KEY, "s1" );
ReplicantContextHolder.put( ReplicantContext.REQUEST_ID_KEY, "r1" );
interceptor.businessIntercept( context );
assertTrue( context.isInvoked() );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "0" );
}
@Test
public void ensureSessionChangesResultInSave()
throws Exception
{
final TestInvocationContext context = new TestInvocationContext();
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
final EntityMessage message = MessageTestUtil.createMessage( "ID", 1, 0, "r1", "r2", "a1", "a2" );
EntityMessageCacheUtil.getSessionChanges( registry ).merge( new Change( message, 44, 77 ) );
when( em.isOpen() ).thenReturn( true );
ReplicantContextHolder.put( ReplicantContext.SESSION_ID_KEY, "s1" );
ReplicantContextHolder.put( ReplicantContext.REQUEST_ID_KEY, "r1" );
final Object result = interceptor.businessIntercept( context );
verify( em ).flush();
// Make sure clear is called
assertNull( ReplicantContextHolder.get( ReplicantContext.SESSION_ID_KEY ) );
assertTrue( context.isInvoked() );
assertEquals( result, TestInvocationContext.RESULT );
assertEquals( interceptor._sessionID, "s1" );
assertEquals( interceptor._requestID, "r1" );
assertNotNull( interceptor._messages );
assertEquals( interceptor._changeSet.getChanges().size(), 1 );
final Change change = interceptor._changeSet.getChanges().iterator().next();
assertEquals( change.getEntityMessage().getID(), message.getID() );
final Serializable expected = 77;
assertEquals( change.getChannels().get( 44 ), expected );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "0" );
}
@Test
public void ensureChanges_willBeCompleteIfNotRoutedToInitiatingSession()
throws Exception
{
final TestInvocationContext context = new TestInvocationContext();
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em, false );
final EntityMessage message = MessageTestUtil.createMessage( "ID", 1, 0, "r1", "r2", "a1", "a2" );
EntityMessageCacheUtil.getEntityMessageSet( registry ).merge( message );
when( em.isOpen() ).thenReturn( true );
interceptor.businessIntercept( context );
assertTrue( context.isInvoked() );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "1" );
}
@Test
public void ensureNestedInvokationDoNotCauseSave()
throws Exception
{
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
final EntityMessage message = MessageTestUtil.createMessage( "ID", 1, 0, "r1", "r2", "a1", "a2" );
EntityMessageCacheUtil.getEntityMessageSet( registry ).merge( message );
final TestInvocationContext context = new TestInvocationContext()
{
public Object proceed()
throws Exception
{
final TestInvocationContext innerContext = new TestInvocationContext();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor innerInterceptor = createInterceptor( registry, em );
when( em.isOpen() ).thenReturn( true );
innerInterceptor.businessIntercept( innerContext );
assertTrue( innerContext.isInvoked() );
assertNull( interceptor._sessionID );
assertNull( interceptor._requestID );
assertNull( innerInterceptor._messages );
assertNull( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ) );
return super.proceed();
}
};
when( em.isOpen() ).thenReturn( true );
ReplicantContextHolder.put( ReplicantContext.SESSION_ID_KEY, "s1" );
ReplicantContextHolder.put( ReplicantContext.REQUEST_ID_KEY, "r1" );
final Object result = interceptor.businessIntercept( context );
verify( em ).flush();
// Make sure clear is called
assertNull( ReplicantContextHolder.get( ReplicantContext.SESSION_ID_KEY ) );
assertTrue( context.isInvoked() );
assertEquals( result, TestInvocationContext.RESULT );
assertEquals( interceptor._sessionID, "s1" );
assertEquals( interceptor._requestID, "r1" );
assertNotNull( interceptor._messages );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "0" );
assertTrue( interceptor._messages.contains( message ) );
}
@Test
public void ensureChangesResultInSaveEvenIfException()
throws Exception
{
final TestInvocationContext context = new TestInvocationContext()
{
public Object proceed()
throws Exception
{
super.proceed();
throw new IllegalStateException();
}
};
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
final EntityMessage message = MessageTestUtil.createMessage( "ID", 1, 0, "r1", "r2", "a1", "a2" );
EntityMessageCacheUtil.getEntityMessageSet( registry ).merge( message );
try
{
when( em.isOpen() ).thenReturn( true );
interceptor.businessIntercept( context );
fail( "Expected proceed to result in exception" );
}
catch ( final IllegalStateException ise )
{
assertNull( ise.getMessage() );
}
assertTrue( context.isInvoked() );
assertNull( interceptor._sessionID );
assertNull( interceptor._requestID );
assertNotNull( interceptor._messages );
assertTrue( interceptor._messages.contains( message ) );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "0" );
}
@Test
public void ensureNoChangesResultIfInRollback()
throws Exception
{
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final TestInvocationContext context = new TestInvocationContext()
{
public Object proceed()
throws Exception
{
registry.setRollbackOnly();
return super.proceed();
}
};
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
final EntityMessage message = MessageTestUtil.createMessage( "ID", 1, 0, "r1", "r2", "a1", "a2" );
EntityMessageCacheUtil.getEntityMessageSet( registry ).merge( message );
when( em.isOpen() ).thenReturn( true );
final Object result = interceptor.businessIntercept( context );
assertTrue( context.isInvoked() );
assertNull( interceptor._sessionID );
assertNull( interceptor._requestID );
assertNull( interceptor._messages );
assertEquals( result, TestInvocationContext.RESULT );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "1" );
}
@Test
public void ensureNoSaveIfNoChanges()
throws Exception
{
final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
final TestInvocationContext context = new TestInvocationContext();
final EntityManager em = mock( EntityManager.class );
final TestReplicationInterceptor interceptor = createInterceptor( registry, em );
//Create registry but no changes
EntityMessageCacheUtil.getEntityMessageSet( registry );
when( em.isOpen() ).thenReturn( true );
final Object result = interceptor.businessIntercept( context );
verify( em ).flush();
assertTrue( context.isInvoked() );
assertNull( interceptor._sessionID );
assertNull( interceptor._requestID );
assertNull( interceptor._messages );
assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "1" );
assertEquals( result, TestInvocationContext.RESULT );
}
private TestReplicationInterceptor createInterceptor( final TransactionSynchronizationRegistry registry,
final EntityManager entityManager )
throws Exception
{
return createInterceptor( registry, entityManager, true );
}
private TestReplicationInterceptor createInterceptor( final TransactionSynchronizationRegistry registry,
final EntityManager entityManager,
final boolean routeToSession )
throws Exception
{
final TestReplicationInterceptor interceptor = new TestReplicationInterceptor( entityManager, routeToSession );
setField( interceptor, "_registry", registry );
return interceptor;
}
private static void setField( final TestReplicationInterceptor interceptor,
final String fieldName,
final Object value )
throws Exception
{
final Field field = interceptor.getClass().getSuperclass().getDeclaredField( fieldName );
field.setAccessible( true );
field.set( interceptor, value );
}
static class TestReplicationInterceptor
extends AbstractReplicationInterceptor
implements EntityMessageEndpoint
{
String _sessionID;
String _requestID;
Collection<EntityMessage> _messages;
EntityManager _entityManager;
private final boolean _routeToSession;
private ChangeSet _changeSet;
TestReplicationInterceptor( final EntityManager entityManager, final boolean routeToSession )
{
_entityManager = entityManager;
_routeToSession = routeToSession;
}
@Override
public boolean saveEntityMessages( @Nullable final String sessionID,
@Nullable final String requestID,
@Nonnull final Collection<EntityMessage> messages,
@Nullable final ChangeSet changeSet )
{
if ( null != _messages )
{
fail( "saveEntityMessages called multiple times" );
}
_sessionID = sessionID;
_requestID = requestID;
_messages = messages;
_changeSet = changeSet;
return _routeToSession;
}
@Override
protected EntityManager getEntityManager()
{
return _entityManager;
}
@Override
protected EntityMessageEndpoint getEndpoint()
{
return this;
}
}
}
|
Update tests to reflect implementation
|
src/test/java/org/realityforge/replicant/server/ee/ReplicationInterceptorTest.java
|
Update tests to reflect implementation
|
<ide><path>rc/test/java/org/realityforge/replicant/server/ee/ReplicationInterceptorTest.java
<ide> public void ensureUserCanOverrideRequestCompleteFlag()
<ide> throws Exception
<ide> {
<add> final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
<ide> final TestInvocationContext context = new TestInvocationContext();
<ide> context.setRunnable( new Runnable()
<ide> {
<ide> @Override
<ide> public void run()
<ide> {
<del> ReplicantContextHolder.put( ReplicantContext.REQUEST_COMPLETE_KEY, "0" );
<add> registry.putResource( ReplicantContext.REQUEST_COMPLETE_KEY, Boolean.FALSE );
<ide> }
<ide> } );
<add> final EntityManager entityManager = mock( EntityManager.class );
<ide> final TestReplicationInterceptor interceptor =
<del> createInterceptor( new TestTransactionSynchronizationRegistry(), mock( EntityManager.class ) );
<add> createInterceptor( registry, entityManager );
<ide>
<ide> ReplicantContextHolder.put( ReplicantContext.SESSION_ID_KEY, "s1" );
<ide> ReplicantContextHolder.put( ReplicantContext.REQUEST_ID_KEY, "r1" );
<add>
<add> when( entityManager.isOpen() ).thenReturn( true );
<ide>
<ide> interceptor.businessIntercept( context );
<ide>
<ide> }
<ide>
<ide> @Test
<del> public void ensureNestedInvokationDoNotCauseSave()
<add> public void ensureNestedInvocationsShouldExcept()
<ide> throws Exception
<ide> {
<ide> final TestTransactionSynchronizationRegistry registry = new TestTransactionSynchronizationRegistry();
<ide> final TestReplicationInterceptor innerInterceptor = createInterceptor( registry, em );
<ide> when( em.isOpen() ).thenReturn( true );
<ide> innerInterceptor.businessIntercept( innerContext );
<del> assertTrue( innerContext.isInvoked() );
<del> assertNull( interceptor._sessionID );
<del> assertNull( interceptor._requestID );
<del> assertNull( innerInterceptor._messages );
<del> assertNull( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ) );
<ide> return super.proceed();
<ide> }
<ide> };
<ide> when( em.isOpen() ).thenReturn( true );
<ide> ReplicantContextHolder.put( ReplicantContext.SESSION_ID_KEY, "s1" );
<ide> ReplicantContextHolder.put( ReplicantContext.REQUEST_ID_KEY, "r1" );
<del> final Object result = interceptor.businessIntercept( context );
<del> verify( em ).flush();
<del>
<del> // Make sure clear is called
<del> assertNull( ReplicantContextHolder.get( ReplicantContext.SESSION_ID_KEY ) );
<del>
<del> assertTrue( context.isInvoked() );
<del> assertEquals( result, TestInvocationContext.RESULT );
<del> assertEquals( interceptor._sessionID, "s1" );
<del> assertEquals( interceptor._requestID, "r1" );
<del> assertNotNull( interceptor._messages );
<del> assertEquals( ReplicantContextHolder.get( ReplicantContext.REQUEST_COMPLETE_KEY ), "0" );
<del> assertTrue( interceptor._messages.contains( message ) );
<add> try
<add> {
<add> interceptor.businessIntercept( context );
<add> }
<add> catch ( Exception e )
<add> {
<add> return;
<add> }
<add> fail("Expected to generate session due to nested contexts");
<ide> }
<ide>
<ide> @Test
|
|
Java
|
lgpl-2.1
|
e940f2e8c903b95afa5e4ddf1710219006035889
| 0 |
EnFlexIT/AgentWorkbench,EnFlexIT/AgentWorkbench,EnFlexIT/AgentWorkbench,EnFlexIT/AgentWorkbench
|
package gui.projectwindow.simsetup;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import mas.environment.ontology.ActiveObject;
import mas.environment.ontology.PassiveObject;
import mas.environment.ontology.Physical2DObject;
import mas.environment.ontology.PlaygroundObject;
import mas.environment.ontology.Position;
import mas.environment.ontology.Scale;
import mas.environment.ontology.Size;
import mas.environment.ontology.StaticObject;
import mas.environment.utils.SVGHelper;
import org.w3c.dom.Element;
import application.Language;
public class EnvironmentSetupObjectSettings extends JPanel{
private static final long serialVersionUID = 1L;
private JLabel lblId = null;
private JLabel lblMaxSpeed = null;
private JLabel lblType = null;
private JLabel lblPosition = null;
private JLabel lblSize = null;
private JButton btnApply = null;
private JButton btnRemove = null;
private JTextField tfWidth = null;
private JTextField tfHeight = null;
private JLabel lblSizeSeparator = null;
private JTextField tfXPos = null;
private JTextField tfYPos = null;
private JTextField tfMaxSpeed = null;
private JLabel lblPosSeparator = null;
private JTextField tfId = null;
private JComboBox cbType = null;
// private JComboBox cbClass = null;
private JLabel lblUnit1 = null;
private JLabel lblUnit2 = null;
public static final String SETTINGS_KEY_ID = "id";
public static final String SETTINGS_KEY_ONTO_CLASS = "ontologyClass";
public static final String SETTINGS_KEY_AGENT_MAX_SPEED = "agentMaxSpeed";
public static final String SETTINGS_KEY_POSITION = "position";
public static final String SETTINGS_KEY_SIZE = "size";
private static final String ACTIVE_OBJECT_TYPE_STRING = "Agent";
private static final String PASSIVE_OBJECT_TYPE_STRING = "Nutzlast";
private static final String STATIC_OBJECT_TYPE_STRING = "Hindernis";
private static final String PLAYGROUND_OBJECT_TYPE_STRING = "Spielfeld";
private static final String NO_OBJECT_TYPE_STRING = "Keiner";
/**
* This project's agent classes
*/
private HashMap<String, String> agentClassNames = null;
/**
* Defines which object type is linked to which environment ontology class
*/
private HashMap<String, Class<?>> typeClass = null;
private EnvironmentSetup parent = null;
/**
* This is the default constructor
*/
public EnvironmentSetupObjectSettings(EnvironmentSetup parent) {
super();
this.parent = parent;
initialize();
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
lblUnit2 = new JLabel();
lblUnit2.setText("m");
lblUnit2.setLocation(new Point(150, 197));
lblUnit2.setSize(lblUnit2.getPreferredSize());
lblUnit1 = new JLabel();
lblUnit1.setText("m");
lblUnit1.setLocation(new Point(145, 157));
lblUnit1.setSize(lblUnit1.getPreferredSize());
lblPosSeparator = new JLabel();
lblPosSeparator.setText(":");
lblPosSeparator.setLocation(new Point(70, 157));
lblPosSeparator.setSize(lblPosSeparator.getPreferredSize());
lblSizeSeparator = new JLabel();
lblSizeSeparator.setText("x");
lblSizeSeparator.setLocation(new Point(70, 197));
lblSizeSeparator.setSize(lblSizeSeparator.getPreferredSize());
lblSize = new JLabel();
lblSize.setText(Language.translate("Gre"));
lblSize.setLocation(new Point(15, 180));
lblSize.setSize(lblSize.getPreferredSize());
lblPosition = new JLabel();
lblPosition.setText(Language.translate("Position"));
lblPosition.setLocation(new Point(16, 140));
lblPosition.setSize(lblPosition.getPreferredSize());
lblType = new JLabel();
lblType.setText(Language.translate("Typ"));
lblType.setLocation(new Point(10, 50));
lblType.setSize(lblType.getPreferredSize());
lblMaxSpeed = new JLabel();
lblMaxSpeed.setText(Language.translate("Maximale Geschwindigkeit"));
lblMaxSpeed.setLocation(new Point(10, 80));
lblMaxSpeed.setSize(lblMaxSpeed.getPreferredSize());
lblId = new JLabel();
lblId.setText("ID");
lblId.setLocation(new Point(10, 15));
lblId.setSize(lblId.getPreferredSize());
this.setLayout(null);
this.add(lblId, null);
this.add(lblMaxSpeed, null);
this.add(lblType, null);
this.add(lblPosition, null);
this.add(lblSize, null);
this.add(getBtnApply(), null);
this.add(getBtnRemove(), null);
this.add(getTfWidth(), null);
this.add(getTfHeight(), null);
this.add(lblSizeSeparator, null);
this.add(getTfXPos(), null);
this.add(getTfYPos(), null);
this.add(lblPosSeparator, null);
this.add(getTfId(), null);
this.add(getCbType(), null);
this.add(getTfMaxSpeed(), null);
this.add(lblUnit1, null);
this.add(lblUnit2, null);
}
/**
* This method initializes btnApply
*
* @return javax.swing.JButton
*/
JButton getBtnApply() {
if (btnApply == null) {
btnApply = new JButton();
btnApply.setText(Language.translate("Anwenden"));
btnApply.setSize(new Dimension(150, 26));
btnApply.setLocation(new Point(25, 245));
btnApply.addActionListener(parent);
btnApply.setEnabled(false);
}
return btnApply;
}
/**
* This method initializes btnRemove
*
* @return javax.swing.JButton
*/
JButton getBtnRemove() {
if (btnRemove == null) {
btnRemove = new JButton();
btnRemove.setText(Language.translate("Objekt Entfernen"));
btnRemove.setSize(new Dimension(150, 26));
btnRemove.setLocation(new Point(25, 275));
btnRemove.setEnabled(false);
btnRemove.setSize(new Dimension(150, 26));
btnRemove.addActionListener(parent);
}
return btnRemove;
}
/**
* This method initializes tfWidth
*
* @return javax.swing.JTextField
*/
JTextField getTfWidth() {
if (tfWidth == null) {
tfWidth = new JTextField();
tfWidth.setSize(new Dimension(50, 25));
tfWidth.setLocation(new Point(16, 195));
tfWidth.setEnabled(false);
}
return tfWidth;
}
/**
* This method initializes tfHeight
*
* @return javax.swing.JTextField
*/
JTextField getTfHeight() {
if (tfHeight == null) {
tfHeight = new JTextField();
tfHeight.setSize(new Dimension(50, 25));
tfHeight.setLocation(new Point(80, 195));
tfHeight.setEnabled(false);
}
return tfHeight;
}
/**
* This method initializes tfXPos
*
* @return javax.swing.JTextField
*/
JTextField getTfXPos() {
if (tfXPos == null) {
tfXPos = new JTextField();
tfXPos.setLocation(new Point(16, 155));
tfXPos.setSize(new Dimension(50, 25));
tfXPos.setEnabled(false);
}
return tfXPos;
}
/**
* This method initializes tfYPos
*
* @return javax.swing.JTextField
*/
JTextField getTfYPos() {
if (tfYPos == null) {
tfYPos = new JTextField();
tfYPos.setLocation(new Point(80, 155));
tfYPos.setSize(new Dimension(50, 25));
tfYPos.setEnabled(false);
}
return tfYPos;
}
/**
* This method initializes tfId
*
* @return javax.swing.JTextField
*/
JTextField getTfId() {
if (tfId == null) {
tfId = new JTextField();
tfId.setLocation(new Point(78, 14));
tfId.setSize(new Dimension(100, 25));
tfId.setEnabled(false);
}
return tfId;
}
/**
* This method initializes cbType
*
* @return javax.swing.JComboBox
*/
JComboBox getCbType() {
if (cbType == null) {
cbType = new JComboBox();
cbType.setLocation(new Point(80, 47));
cbType.setSize(new Dimension(100, 25));
cbType.setEnabled(false);
typeClass = new HashMap<String, Class<?>>();
typeClass.put(Language.translate(NO_OBJECT_TYPE_STRING), null);
typeClass.put(Language.translate(ACTIVE_OBJECT_TYPE_STRING), ActiveObject.class);
typeClass.put(Language.translate(STATIC_OBJECT_TYPE_STRING), StaticObject.class);
typeClass.put(Language.translate(PASSIVE_OBJECT_TYPE_STRING), PassiveObject.class);
typeClass.put(Language.translate(PLAYGROUND_OBJECT_TYPE_STRING), PlaygroundObject.class);
cbType.setModel(new DefaultComboBoxModel(typeClass.keySet().toArray()));
cbType.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
if(cbType.getSelectedItem().equals(Language.translate(ACTIVE_OBJECT_TYPE_STRING))){
getTfMaxSpeed().setEnabled(true);
}else{
getTfMaxSpeed().setEnabled(false);
}
if(cbType.getSelectedItem().equals(Language.translate(NO_OBJECT_TYPE_STRING))){
getBtnApply().setEnabled(false);
}else{
getBtnApply().setEnabled(true);
}
}
});
}
return cbType;
}
JTextField getTfMaxSpeed(){
if(tfMaxSpeed == null){
tfMaxSpeed = new JTextField();
tfMaxSpeed.setLocation(new Point(16, 103));
tfMaxSpeed.setSize(new Dimension(100, 25));
tfMaxSpeed.setEnabled(false);
}
return tfMaxSpeed;
}
// /**
// * This method initializes cbClass
// *
// * @return javax.swing.JComboBox
// */
// JComboBox getCbClass() {
// if (cbClass == null) {
// cbClass = new JComboBox();
// cbClass.setLocation(new Point(80, 78));
// cbClass.setSize(new Dimension(100, 25));
// cbClass.setEnabled(false);
// Vector<Class<? extends Agent>> classes = parent.project.getProjectAgents();
// Vector<String> names = new Vector<String>();
//
// agentClassNames = new HashMap<String, String>();
//
// for(int i=0; i<classes.size(); i++){
// names.add(classes.get(i).getSimpleName());
// agentClassNames.put(classes.get(i).getSimpleName(), classes.get(i).getName());
//
// }
// cbClass.setModel(new DefaultComboBoxModel(names));
// }
// return cbClass;
// }
/**
* Sets the values of the input components according to the given SVG element
* @param elem
*/
void setInputValues(Element elem){
if(elem != null){
Scale scale = parent.controller.getEnvironment().getScale();
getTfId().setText(elem.getAttributeNS(null, "id"));
Size size = SVGHelper.getSizeFromElement(elem, scale);
getTfWidth().setText(""+size.getWidth());
getTfHeight().setText(""+size.getHeight());
Position pos = SVGHelper.getPosFromElement(elem, scale);
getTfXPos().setText(""+pos.getXPos());
getTfYPos().setText(""+pos.getYPos());
setObjectType(parent.controller.getEnvWrap().getObjectById(elem.getAttributeNS(null, "id")));
}else{
getTfId().setText("");
getTfXPos().setText("");
getTfYPos().setText("");
getTfWidth().setText("");
getTfHeight().setText("");
getCbType().setSelectedItem(Language.translate(NO_OBJECT_TYPE_STRING));
getTfMaxSpeed().setText("");
}
}
private void setObjectType(Physical2DObject object){
if(object == null){
getCbType().setSelectedItem(Language.translate(NO_OBJECT_TYPE_STRING));
}
else if(object instanceof ActiveObject){
getCbType().setSelectedItem(Language.translate(ACTIVE_OBJECT_TYPE_STRING));
getTfMaxSpeed().setText(""+((ActiveObject)object).getMaxSpeed());
}else if(object instanceof PassiveObject){
getCbType().setSelectedItem(Language.translate(PASSIVE_OBJECT_TYPE_STRING));
}else if(object instanceof StaticObject){
getCbType().setSelectedItem(Language.translate(STATIC_OBJECT_TYPE_STRING));
}else if(object instanceof PlaygroundObject){
getCbType().setSelectedItem(Language.translate(PLAYGROUND_OBJECT_TYPE_STRING));
}
}
/**
* This method returns a HashMap containing object settings defined by the input's current values
* @return HashMap containing object settings
*/
HashMap<String, Object> getObjectProperties(){
HashMap<String, Object> settings = new HashMap<String, Object>();
settings.put(SETTINGS_KEY_ID, tfId.getText());
settings.put(SETTINGS_KEY_ONTO_CLASS, typeClass.get(cbType.getSelectedItem()));
if(cbType.getSelectedItem().equals(Language.translate(ACTIVE_OBJECT_TYPE_STRING))){
settings.put(SETTINGS_KEY_AGENT_MAX_SPEED, tfMaxSpeed.getText());
}
Position pos = new Position();
pos.setXPos(Float.parseFloat(getTfXPos().getText()));
pos.setYPos(Float.parseFloat(getTfYPos().getText()));
settings.put(SETTINGS_KEY_POSITION, pos);
Size size = new Size();
size.setWidth(Float.parseFloat(getTfWidth().getText()));
size.setHeight(Float.parseFloat(getTfHeight().getText()));
settings.put(SETTINGS_KEY_SIZE, size);
return settings;
}
/**
* Enabling or disabling the major inputs
* @param enabled Enable or disable
*/
void enableControlls(boolean enabled){
getTfId().setEnabled(enabled);
getTfXPos().setEnabled(enabled);
getTfYPos().setEnabled(enabled);
getTfWidth().setEnabled(enabled);
getTfHeight().setEnabled(enabled);
getCbType().setEnabled(enabled);
}
}
|
src/gui/projectwindow/simsetup/EnvironmentSetupObjectSettings.java
|
package gui.projectwindow.simsetup;
import jade.core.Agent;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Point;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import org.w3c.dom.Element;
import application.Language;
import mas.environment.ontology.ActiveObject;
import mas.environment.ontology.Physical2DObject;
import mas.environment.ontology.Scale;
import mas.environment.ontology.StaticObject;
import mas.environment.ontology.PassiveObject;
import mas.environment.ontology.PlaygroundObject;
import mas.environment.ontology.Position;
import mas.environment.ontology.Size;
import mas.environment.utils.SVGHelper;
public class EnvironmentSetupObjectSettings extends JPanel{
private static final long serialVersionUID = 1L;
private JLabel lblId = null;
private JLabel lblMaxSpeed = null;
private JLabel lblType = null;
private JLabel lblPosition = null;
private JLabel lblSize = null;
private JButton btnApply = null;
private JButton btnRemove = null;
private JTextField tfWidth = null;
private JTextField tfHeight = null;
private JLabel lblSizeSeparator = null;
private JTextField tfXPos = null;
private JTextField tfYPos = null;
private JTextField tfMaxSpeed = null;
private JLabel lblPosSeparator = null;
private JTextField tfId = null;
private JComboBox cbType = null;
// private JComboBox cbClass = null;
private JLabel lblUnit1 = null;
private JLabel lblUnit2 = null;
public static final String SETTINGS_KEY_ID = "id";
public static final String SETTINGS_KEY_ONTO_CLASS = "ontologyClass";
public static final String SETTINGS_KEY_AGENT_MAX_SPEED = "agentMaxSpeed";
public static final String SETTINGS_KEY_POSITION = "position";
public static final String SETTINGS_KEY_SIZE = "size";
private static final String ACTIVE_OBJECT_TYPE_STRING = "Agent";
private static final String PASSIVE_OBJECT_TYPE_STRING = "Nutzlast";
private static final String STATIC_OBJECT_TYPE_STRING = "Hindernis";
private static final String PLAYGROUND_OBJECT_TYPE_STRING = "Spielfeld";
private static final String NO_OBJECT_TYPE_STRING = "Keiner";
/**
* This project's agent classes
*/
private HashMap<String, String> agentClassNames = null;
/**
* Defines which object type is linked to which environment ontology class
*/
private HashMap<String, Class<?>> typeClass = null;
private EnvironmentSetup parent = null;
/**
* This is the default constructor
*/
public EnvironmentSetupObjectSettings(EnvironmentSetup parent) {
super();
this.parent = parent;
initialize();
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
lblUnit2 = new JLabel();
lblUnit2.setText("m");
lblUnit2.setLocation(new Point(150, 197));
lblUnit2.setSize(lblUnit2.getPreferredSize());
lblUnit1 = new JLabel();
lblUnit1.setText("m");
lblUnit1.setLocation(new Point(145, 157));
lblUnit1.setSize(lblUnit1.getPreferredSize());
lblPosSeparator = new JLabel();
lblPosSeparator.setText(":");
lblPosSeparator.setLocation(new Point(70, 157));
lblPosSeparator.setSize(lblPosSeparator.getPreferredSize());
lblSizeSeparator = new JLabel();
lblSizeSeparator.setText("x");
lblSizeSeparator.setLocation(new Point(70, 197));
lblSizeSeparator.setSize(lblSizeSeparator.getPreferredSize());
lblSize = new JLabel();
lblSize.setText(Language.translate("Gre"));
lblSize.setLocation(new Point(15, 180));
lblSize.setSize(lblSize.getPreferredSize());
lblPosition = new JLabel();
lblPosition.setText(Language.translate("Position"));
lblPosition.setLocation(new Point(16, 140));
lblPosition.setSize(lblPosition.getPreferredSize());
lblType = new JLabel();
lblType.setText(Language.translate("Typ"));
lblType.setLocation(new Point(10, 50));
lblType.setSize(lblType.getPreferredSize());
lblMaxSpeed = new JLabel();
lblMaxSpeed.setText(Language.translate("Maximale Geschwindigkeit"));
lblMaxSpeed.setLocation(new Point(10, 80));
lblMaxSpeed.setSize(lblMaxSpeed.getPreferredSize());
lblId = new JLabel();
lblId.setText("ID");
lblId.setLocation(new Point(10, 15));
lblId.setSize(lblId.getPreferredSize());
this.setLayout(null);
this.add(lblId, null);
this.add(lblMaxSpeed, null);
this.add(lblType, null);
this.add(lblPosition, null);
this.add(lblSize, null);
this.add(getBtnApply(), null);
this.add(getBtnRemove(), null);
this.add(getTfWidth(), null);
this.add(getTfHeight(), null);
this.add(lblSizeSeparator, null);
this.add(getTfXPos(), null);
this.add(getTfYPos(), null);
this.add(lblPosSeparator, null);
this.add(getTfId(), null);
this.add(getCbType(), null);
this.add(getTfMaxSpeed(), null);
this.add(lblUnit1, null);
this.add(lblUnit2, null);
}
/**
* This method initializes btnApply
*
* @return javax.swing.JButton
*/
JButton getBtnApply() {
if (btnApply == null) {
btnApply = new JButton();
btnApply.setText(Language.translate("Anwenden"));
btnApply.setSize(new Dimension(150, 26));
btnApply.setLocation(new Point(25, 245));
btnApply.addActionListener(parent);
btnApply.setEnabled(false);
}
return btnApply;
}
/**
* This method initializes btnRemove
*
* @return javax.swing.JButton
*/
JButton getBtnRemove() {
if (btnRemove == null) {
btnRemove = new JButton();
btnRemove.setText(Language.translate("Objekt Entfernen"));
btnRemove.setSize(new Dimension(150, 26));
btnRemove.setLocation(new Point(25, 275));
btnRemove.setEnabled(false);
btnRemove.setSize(new Dimension(150, 26));
btnRemove.addActionListener(parent);
}
return btnRemove;
}
/**
* This method initializes tfWidth
*
* @return javax.swing.JTextField
*/
JTextField getTfWidth() {
if (tfWidth == null) {
tfWidth = new JTextField();
tfWidth.setSize(new Dimension(50, 25));
tfWidth.setLocation(new Point(16, 195));
tfWidth.setEnabled(false);
}
return tfWidth;
}
/**
* This method initializes tfHeight
*
* @return javax.swing.JTextField
*/
JTextField getTfHeight() {
if (tfHeight == null) {
tfHeight = new JTextField();
tfHeight.setSize(new Dimension(50, 25));
tfHeight.setLocation(new Point(80, 195));
tfHeight.setEnabled(false);
}
return tfHeight;
}
/**
* This method initializes tfXPos
*
* @return javax.swing.JTextField
*/
JTextField getTfXPos() {
if (tfXPos == null) {
tfXPos = new JTextField();
tfXPos.setLocation(new Point(16, 155));
tfXPos.setSize(new Dimension(50, 25));
tfXPos.setEnabled(false);
}
return tfXPos;
}
/**
* This method initializes tfYPos
*
* @return javax.swing.JTextField
*/
JTextField getTfYPos() {
if (tfYPos == null) {
tfYPos = new JTextField();
tfYPos.setLocation(new Point(80, 155));
tfYPos.setSize(new Dimension(50, 25));
tfYPos.setEnabled(false);
}
return tfYPos;
}
/**
* This method initializes tfId
*
* @return javax.swing.JTextField
*/
JTextField getTfId() {
if (tfId == null) {
tfId = new JTextField();
tfId.setLocation(new Point(78, 14));
tfId.setSize(new Dimension(100, 25));
tfId.setEnabled(false);
}
return tfId;
}
/**
* This method initializes cbType
*
* @return javax.swing.JComboBox
*/
JComboBox getCbType() {
if (cbType == null) {
cbType = new JComboBox();
cbType.setLocation(new Point(80, 47));
cbType.setSize(new Dimension(100, 25));
cbType.setEnabled(false);
typeClass = new HashMap<String, Class<?>>();
typeClass.put(Language.translate(NO_OBJECT_TYPE_STRING), null);
typeClass.put(Language.translate(ACTIVE_OBJECT_TYPE_STRING), ActiveObject.class);
typeClass.put(Language.translate(STATIC_OBJECT_TYPE_STRING), StaticObject.class);
typeClass.put(Language.translate(PASSIVE_OBJECT_TYPE_STRING), PassiveObject.class);
typeClass.put(Language.translate(PLAYGROUND_OBJECT_TYPE_STRING), PlaygroundObject.class);
cbType.setModel(new DefaultComboBoxModel(typeClass.keySet().toArray()));
cbType.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
if(cbType.getSelectedItem().equals(Language.translate(ACTIVE_OBJECT_TYPE_STRING))){
getTfMaxSpeed().setEnabled(true);
}else{
getTfMaxSpeed().setEnabled(false);
}
if(cbType.getSelectedItem().equals(Language.translate(NO_OBJECT_TYPE_STRING))){
getBtnApply().setEnabled(false);
}else{
getBtnApply().setEnabled(true);
}
}
});
}
return cbType;
}
JTextField getTfMaxSpeed(){
if(tfMaxSpeed == null){
tfMaxSpeed = new JTextField();
tfMaxSpeed.setLocation(new Point(16, 103));
tfMaxSpeed.setSize(new Dimension(100, 25));
tfMaxSpeed.setEnabled(false);
}
return tfMaxSpeed;
}
// /**
// * This method initializes cbClass
// *
// * @return javax.swing.JComboBox
// */
// JComboBox getCbClass() {
// if (cbClass == null) {
// cbClass = new JComboBox();
// cbClass.setLocation(new Point(80, 78));
// cbClass.setSize(new Dimension(100, 25));
// cbClass.setEnabled(false);
// Vector<Class<? extends Agent>> classes = parent.project.getProjectAgents();
// Vector<String> names = new Vector<String>();
//
// agentClassNames = new HashMap<String, String>();
//
// for(int i=0; i<classes.size(); i++){
// names.add(classes.get(i).getSimpleName());
// agentClassNames.put(classes.get(i).getSimpleName(), classes.get(i).getName());
//
// }
// cbClass.setModel(new DefaultComboBoxModel(names));
// }
// return cbClass;
// }
/**
* Sets the values of the input components according to the given SVG element
* @param elem
*/
void setInputValues(Element elem){
if(elem != null){
Scale scale = parent.controller.getEnvironment().getScale();
getTfId().setText(elem.getAttributeNS(null, "id"));
Size size = SVGHelper.getSizeFromElement(elem, scale);
getTfWidth().setText(""+size.getWidth());
getTfHeight().setText(""+size.getHeight());
Position pos = SVGHelper.getPosFromElement(elem, scale);
getTfXPos().setText(""+pos.getXPos());
getTfYPos().setText(""+pos.getYPos());
setObjectType(parent.controller.getEnvWrap().getObjectById(elem.getAttributeNS(null, "id")));
}else{
getTfId().setText("");
getTfXPos().setText("");
getTfYPos().setText("");
getTfWidth().setText("");
getTfHeight().setText("");
getCbType().setSelectedItem(Language.translate(NO_OBJECT_TYPE_STRING));
getTfMaxSpeed().setText("");
}
}
private void setObjectType(Physical2DObject object){
if(object == null){
getCbType().setSelectedItem(Language.translate(NO_OBJECT_TYPE_STRING));
}
else if(object instanceof ActiveObject){
getCbType().setSelectedItem(Language.translate(ACTIVE_OBJECT_TYPE_STRING));
getTfMaxSpeed().setText(""+((ActiveObject)object).getMaxSpeed());
}else if(object instanceof PassiveObject){
getCbType().setSelectedItem(Language.translate(PASSIVE_OBJECT_TYPE_STRING));
}else if(object instanceof StaticObject){
getCbType().setSelectedItem(Language.translate(STATIC_OBJECT_TYPE_STRING));
}else if(object instanceof PlaygroundObject){
getCbType().setSelectedItem(Language.translate(PLAYGROUND_OBJECT_TYPE_STRING));
}
}
/**
* This method returns a HashMap containing object settings defined by the input's current values
* @return HashMap containing object settings
*/
HashMap<String, Object> getObjectProperties(){
HashMap<String, Object> settings = new HashMap<String, Object>();
settings.put(SETTINGS_KEY_ID, tfId.getText());
settings.put(SETTINGS_KEY_ONTO_CLASS, typeClass.get(cbType.getSelectedItem()));
if(cbType.getSelectedItem().equals(Language.translate(ACTIVE_OBJECT_TYPE_STRING))){
settings.put(SETTINGS_KEY_AGENT_MAX_SPEED, tfMaxSpeed.getText());
}
Position pos = new Position();
pos.setXPos(Float.parseFloat(getTfXPos().getText()));
pos.setYPos(Float.parseFloat(getTfYPos().getText()));
settings.put(SETTINGS_KEY_POSITION, pos);
Size size = new Size();
size.setWidth(Float.parseFloat(getTfWidth().getText()));
size.setHeight(Float.parseFloat(getTfHeight().getText()));
settings.put(SETTINGS_KEY_SIZE, size);
return settings;
}
/**
* Enabling or disabling the major inputs
* @param enabled Enable or disable
*/
void enableControlls(boolean enabled){
getTfId().setEnabled(enabled);
getTfXPos().setEnabled(enabled);
getTfYPos().setEnabled(enabled);
getTfWidth().setEnabled(enabled);
getTfHeight().setEnabled(enabled);
getCbType().setEnabled(enabled);
}
}
|
BLUUUBBBB !!!
Also, was habe ich alles gemacht?
- den SimulationsService auf das Object EnvirontModel umgestellt (enthält das Umgebungsmodel und die aktuelle Zeit)
- Anzeige für die aktuelle Systemauslastung in den verschiedenen Rechnern/JVMs/Knoten
- Basisklasse für das 'load balancing' entworfen (hier ist die aktuelle Baustelle)
- viel Kleinkram ....
git-svn-id: 15e85767c710a19dc5a0ec45cd9b3838d1f9a0c8@473 014e83ad-c670-0410-b1a0-9290c87bb784
|
src/gui/projectwindow/simsetup/EnvironmentSetupObjectSettings.java
|
BLUUUBBBB !!! Also, was habe ich alles gemacht? - den SimulationsService auf das Object EnvirontModel umgestellt (enthält das Umgebungsmodel und die aktuelle Zeit) - Anzeige für die aktuelle Systemauslastung in den verschiedenen Rechnern/JVMs/Knoten - Basisklasse für das 'load balancing' entworfen (hier ist die aktuelle Baustelle) - viel Kleinkram ....
|
<ide><path>rc/gui/projectwindow/simsetup/EnvironmentSetupObjectSettings.java
<ide> package gui.projectwindow.simsetup;
<ide>
<del>import jade.core.Agent;
<del>
<del>import javax.swing.JPanel;
<del>import javax.swing.JLabel;
<add>import java.awt.Dimension;
<ide> import java.awt.Point;
<del>import java.awt.Dimension;
<ide> import java.awt.event.ActionEvent;
<ide> import java.awt.event.ActionListener;
<ide> import java.util.HashMap;
<del>import java.util.Vector;
<ide>
<ide> import javax.swing.DefaultComboBoxModel;
<ide> import javax.swing.JButton;
<add>import javax.swing.JComboBox;
<add>import javax.swing.JLabel;
<add>import javax.swing.JPanel;
<ide> import javax.swing.JTextField;
<del>import javax.swing.JComboBox;
<del>
<del>import org.w3c.dom.Element;
<del>
<del>
<del>import application.Language;
<ide>
<ide> import mas.environment.ontology.ActiveObject;
<add>import mas.environment.ontology.PassiveObject;
<ide> import mas.environment.ontology.Physical2DObject;
<del>import mas.environment.ontology.Scale;
<del>import mas.environment.ontology.StaticObject;
<del>import mas.environment.ontology.PassiveObject;
<ide> import mas.environment.ontology.PlaygroundObject;
<ide> import mas.environment.ontology.Position;
<add>import mas.environment.ontology.Scale;
<ide> import mas.environment.ontology.Size;
<add>import mas.environment.ontology.StaticObject;
<ide> import mas.environment.utils.SVGHelper;
<add>
<add>import org.w3c.dom.Element;
<add>
<add>import application.Language;
<ide>
<ide> public class EnvironmentSetupObjectSettings extends JPanel{
<ide>
|
|
Java
|
apache-2.0
|
6b94e3c3c0e03e1f59d1f8f53f5a27ce525ae26a
| 0 |
LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb
|
/*
// $Id$
// Package org.eigenbase is a class library of data management components.
// Copyright (C) 2005-2007 The Eigenbase Project
// Copyright (C) 2002-2007 Disruptive Tech
// Copyright (C) 2005-2007 LucidEra, Inc.
// Portions Copyright (C) 2003-2007 John V. Sichi
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version approved by The Eigenbase Project.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.eigenbase.util;
import java.io.*;
import java.math.*;
import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import junit.framework.*;
import junit.textui.*;
import org.eigenbase.runtime.*;
import org.eigenbase.test.DiffTestCase;
/**
* Unit test for {@link Util} and other classes in this package.
*
* @author jhyde
* @version $Id$
* @since Jul 12, 2004
*/
public class UtilTest
extends TestCase
{
//~ Constructors -----------------------------------------------------------
public UtilTest(String name)
{
super(name);
}
//~ Methods ----------------------------------------------------------------
public static Test suite()
throws Exception
{
TestSuite suite = new TestSuite();
suite.addTestSuite(UtilTest.class);
return suite;
}
public void testPrintEquals()
{
assertPrintEquals("\"x\"", "x", true);
}
public void testPrintEquals2()
{
assertPrintEquals("\"x\"", "x", false);
}
public void testPrintEquals3()
{
assertPrintEquals("null", null, true);
}
public void testPrintEquals4()
{
assertPrintEquals("", null, false);
}
public void testPrintEquals5()
{
assertPrintEquals("\"\\\\\\\"\\r\\n\"", "\\\"\r\n", true);
}
public void testScientificNotation()
{
BigDecimal bd;
bd = new BigDecimal("0.001234");
TestUtil.assertEqualsVerbose(
"1.234E-3",
Util.toScientificNotation(bd));
bd = new BigDecimal("0.001");
TestUtil.assertEqualsVerbose(
"1E-3",
Util.toScientificNotation(bd));
bd = new BigDecimal("-0.001");
TestUtil.assertEqualsVerbose(
"-1E-3",
Util.toScientificNotation(bd));
bd = new BigDecimal("1");
TestUtil.assertEqualsVerbose(
"1E0",
Util.toScientificNotation(bd));
bd = new BigDecimal("-1");
TestUtil.assertEqualsVerbose(
"-1E0",
Util.toScientificNotation(bd));
bd = new BigDecimal("1.0");
TestUtil.assertEqualsVerbose(
"1.0E0",
Util.toScientificNotation(bd));
bd = new BigDecimal("12345");
TestUtil.assertEqualsVerbose(
"1.2345E4",
Util.toScientificNotation(bd));
bd = new BigDecimal("12345.00");
TestUtil.assertEqualsVerbose(
"1.234500E4",
Util.toScientificNotation(bd));
bd = new BigDecimal("12345.001");
TestUtil.assertEqualsVerbose(
"1.2345001E4",
Util.toScientificNotation(bd));
//test truncate
bd = new BigDecimal("1.23456789012345678901");
TestUtil.assertEqualsVerbose(
"1.2345678901234567890E0",
Util.toScientificNotation(bd));
bd = new BigDecimal("-1.23456789012345678901");
TestUtil.assertEqualsVerbose(
"-1.2345678901234567890E0",
Util.toScientificNotation(bd));
}
public void testToJavaId()
throws UnsupportedEncodingException
{
assertEquals(
"ID$0$foo",
Util.toJavaId("foo", 0));
assertEquals(
"ID$0$foo_20_bar",
Util.toJavaId("foo bar", 0));
assertEquals(
"ID$0$foo__bar",
Util.toJavaId("foo_bar", 0));
assertEquals(
"ID$100$_30_bar",
Util.toJavaId("0bar", 100));
assertEquals(
"ID$0$foo0bar",
Util.toJavaId("foo0bar", 0));
assertEquals(
"ID$0$it_27_s_20_a_20_bird_2c__20_it_27_s_20_a_20_plane_21_",
Util.toJavaId("it's a bird, it's a plane!", 0));
// Try some funny non-ASCII charsets
assertEquals(
"ID$0$_f6__cb__c4__ca__ae__c1__f9__cb_",
Util.toJavaId(
"\u00f6\u00cb\u00c4\u00ca\u00ae\u00c1\u00f9\u00cb",
0));
assertEquals(
"ID$0$_f6cb__c4ca__aec1__f9cb_",
Util.toJavaId("\uf6cb\uc4ca\uaec1\uf9cb", 0));
byte [] bytes1 = { 3, 12, 54, 23, 33, 23, 45, 21, 127, -34, -92, -113 };
assertEquals(
"ID$0$_3__c_6_17__21__17__2d__15__7f__6cd9__fffd_",
Util.toJavaId(new String(bytes1, "EUC-JP"),
0));
byte [] bytes2 =
{ 64, 32, 43, -45, -23, 0, 43, 54, 119, -32, -56, -34 };
assertEquals(
"ID$0$_30c__3617__2117__2d15__7fde__a48f_",
Util.toJavaId(new String(bytes1, "UTF-16"),
0));
}
private void assertPrintEquals(
String expect,
String in,
boolean nullMeansNull)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Util.printJavaString(pw, in, nullMeansNull);
pw.flush();
String out = sw.toString();
assertEquals(expect, out);
}
/**
* Tests whether {@link EnumeratedValues} serialize correctly.
*/
public void testSerializeEnumeratedValues()
throws IOException, ClassNotFoundException
{
UnserializableEnum unser =
(UnserializableEnum) serializeAndDeserialize(
UnserializableEnum.Foo);
assertFalse(unser == UnserializableEnum.Foo);
SerializableEnum ser =
(SerializableEnum) serializeAndDeserialize(SerializableEnum.Foo);
assertTrue(ser == SerializableEnum.Foo);
}
private static Object serializeAndDeserialize(Object e1)
throws IOException, ClassNotFoundException
{
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(e1);
out.flush();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(bin);
Object o = in.readObject();
return o;
}
/**
* Unit-test for {@link BitString}.
*/
public void testBitString()
{
// Powers of two, minimal length.
final BitString b0 = new BitString("", 0);
final BitString b1 = new BitString("1", 1);
final BitString b2 = new BitString("10", 2);
final BitString b4 = new BitString("100", 3);
final BitString b8 = new BitString("1000", 4);
final BitString b16 = new BitString("10000", 5);
final BitString b32 = new BitString("100000", 6);
final BitString b64 = new BitString("1000000", 7);
final BitString b128 = new BitString("10000000", 8);
final BitString b256 = new BitString("100000000", 9);
// other strings
final BitString b0_1 = new BitString("", 1);
final BitString b0_12 = new BitString("", 12);
// conversion to hex strings
assertEquals(
"",
b0.toHexString());
assertEquals(
"1",
b1.toHexString());
assertEquals(
"2",
b2.toHexString());
assertEquals(
"4",
b4.toHexString());
assertEquals(
"8",
b8.toHexString());
assertEquals(
"10",
b16.toHexString());
assertEquals(
"20",
b32.toHexString());
assertEquals(
"40",
b64.toHexString());
assertEquals(
"80",
b128.toHexString());
assertEquals(
"100",
b256.toHexString());
assertEquals(
"0",
b0_1.toHexString());
assertEquals(
"000",
b0_12.toHexString());
// to byte array
assertByteArray("01", "1", 1);
assertByteArray("01", "1", 5);
assertByteArray("01", "1", 8);
assertByteArray("00, 01", "1", 9);
assertByteArray("", "", 0);
assertByteArray("00", "0", 1);
assertByteArray("00", "0000", 2); // bit count less than string
assertByteArray("00", "000", 5); // bit count larger than string
assertByteArray("00", "0", 8); // precisely 1 byte
assertByteArray("00, 00", "00", 9); // just over 1 byte
// from hex string
assertReversible("");
assertReversible("1");
assertReversible("10");
assertReversible("100");
assertReversible("1000");
assertReversible("10000");
assertReversible("100000");
assertReversible("1000000");
assertReversible("10000000");
assertReversible("100000000");
assertReversible("01");
assertReversible("001010");
assertReversible("000000000100");
}
private static void assertReversible(String s)
{
assertEquals(
s,
BitString.createFromBitString(s).toBitString(),
s);
assertEquals(
s,
BitString.createFromHexString(s).toHexString());
}
private void assertByteArray(
String expected,
String bits,
int bitCount)
{
byte [] bytes = BitString.toByteArrayFromBitString(bits, bitCount);
final String s = toString(bytes);
assertEquals(expected, s);
}
/**
* Converts a byte array to a hex string like "AB, CD".
*/
private String toString(byte [] bytes)
{
StringBuilder buf = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
if (i > 0) {
buf.append(", ");
}
String s = Integer.toString(b, 16);
buf.append((b < 16) ? ("0" + s) : s);
}
return buf.toString();
}
/**
* Tests {@link CastingList} and {@link Util#cast}.
*/
public void testCastingList()
{
final List<Number> numberList = new ArrayList<Number>();
numberList.add(new Integer(1));
numberList.add(null);
numberList.add(new Integer(2));
List<Integer> integerList = Util.cast(numberList, Integer.class);
assertEquals(3, integerList.size());
assertEquals(new Integer(2), integerList.get(2));
// Nulls are OK.
assertNull(integerList.get(1));
// Can update the underlying list.
integerList.set(1, 345);
assertEquals(new Integer(345), integerList.get(1));
integerList.set(1, null);
assertNull(integerList.get(1));
// Can add a member of the wrong type to the underlying list.
numberList.add(new Double(3.1415));
assertEquals(4, integerList.size());
// Access a member which is of the wrong type.
try {
integerList.get(3);
fail("expected exception");
} catch (ClassCastException e) {
// ok
}
}
public void testIterableProperties()
{
Properties properties = new Properties();
properties.put("foo", "george");
properties.put("bar", "ringo");
StringBuilder sb = new StringBuilder();
for (
Map.Entry<String, String> entry : Util.toMap(properties).entrySet())
{
sb.append(entry.getKey()).append("=").append(entry.getValue());
sb.append(";");
}
assertEquals("bar=ringo;foo=george;", sb.toString());
assertEquals(2, Util.toMap(properties).entrySet().size());
properties.put("nonString", 34);
try {
for (
Map.Entry<String, String> entry
: Util.toMap(properties).entrySet())
{
String s = entry.getValue();
Util.discard(s);
}
fail("expected exception");
} catch (ClassCastException e) {
// ok
}
}
/**
* Tests the difference engine, {@link DiffTestCase#diff}.
*/
public void testDiffLines() {
String[] before = {
"Get a dose of her in jackboots and kilt",
"She's killer-diller when she's dressed to the hilt",
"She's the kind of a girl that makes The News of The World",
"Yes you could say she was attractively built.",
"Yeah yeah yeah."
};
String[] after = {
"Get a dose of her in jackboots and kilt",
"(they call her \"Polythene Pam\")",
"She's killer-diller when she's dressed to the hilt",
"She's the kind of a girl that makes The Sunday Times",
"seem more interesting.",
"Yes you could say she was attractively built."
};
String diff = DiffTestCase.diffLines(
Arrays.asList(before), Arrays.asList(after));
assertEquals(
diff,
TestUtil.fold("1a2\n" +
"> (they call her \"Polythene Pam\")\n" +
"3c4,5\n" +
"< She's the kind of a girl that makes The News of The World\n" +
"---\n" +
"> She's the kind of a girl that makes The Sunday Times\n" +
"> seem more interesting.\n" +
"5d6\n" +
"< Yeah yeah yeah.\n"));
}
/**
* Tests the {@link Util#toPosix(TimeZone, boolean)} method.
*/
public void testPosixTimeZone()
{
// NOTE jvs 31-July-2007: First two tests are disabled since
// not everyone may have patched their system yet for recent
// DST change.
// Pacific Standard Time. Effective 2007, the local time changes from
// PST to PDT at 02:00 LST to 03:00 LDT on the second Sunday in March
// and returns at 02:00 LDT to 01:00 LST on the first Sunday in
// November.
if (false) {
assertEquals("PST-8PDT,M3.2.0,M11.1.0",
Util.toPosix(TimeZone.getTimeZone("PST"), false));
assertEquals("PST-8PDT1,M3.2.0/2,M11.1.0/2",
Util.toPosix(TimeZone.getTimeZone("PST"), true));
}
// Tokyo has +ve offset, no DST
assertEquals("JST9",
Util.toPosix(TimeZone.getTimeZone("Asia/Tokyo"), true));
// Sydney, Australia lies ten hours east of GMT and makes a one hour
// shift forward during daylight savings. Being located in the southern
// hemisphere, daylight savings begins on the last Sunday in October at
// 2am and ends on the last Sunday in March at 3am.
// (Uses STANDARD_TIME time-transition mode.)
try {
TimeZone timezone = TimeZone.getTimeZone("Australia/Sydney");
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date testDate = format.parse("2008-10-3");
if (timezone.inDaylightTime(testDate)) {
assertEquals("EST10EST1,M10.5.0/2,M3.5.0/3",
Util.toPosix(TimeZone.getTimeZone("Australia/Sydney"),
true));
} else {
assertEquals("EST10EST1,M10.1.0/2,M4.1.0/3",
Util.toPosix(TimeZone.getTimeZone("Australia/Sydney"),
true));
}
} catch (ParseException pe) { fail("Problem parsing test date"); }
// Paris, France. (Uses UTC_TIME time-transition mode.)
assertEquals("CET1CEST1,M3.5.0/2,M10.5.0/3",
Util.toPosix(TimeZone.getTimeZone("Europe/Paris"), true));
assertEquals("UTC0",
Util.toPosix(TimeZone.getTimeZone("UTC"), true));
}
/**
* Runs the test suite.
*/
public static void main(String [] args)
throws Exception
{
TestRunner.run(suite());
}
//~ Inner Classes ----------------------------------------------------------
/**
* Enumeration which extends BasicValue does NOT serialize correctly.
*/
private static class UnserializableEnum
extends EnumeratedValues.BasicValue
{
public static final UnserializableEnum Foo =
new UnserializableEnum("foo", 1);
public static final UnserializableEnum Bar =
new UnserializableEnum("bar", 2);
public UnserializableEnum(String name, int ordinal)
{
super(name, ordinal, null);
}
}
/**
* Enumeration which serializes correctly.
*/
private static class SerializableEnum
extends EnumeratedValues.SerializableValue
{
public static final SerializableEnum Foo =
new SerializableEnum("foo", 1);
public static final SerializableEnum Bar =
new SerializableEnum("bar", 2);
public SerializableEnum(String name, int ordinal)
{
super(name, ordinal, null);
}
protected Object readResolve()
throws ObjectStreamException
{
switch (_ordinal) {
case 1:
return Foo;
case 2:
return Bar;
default:
throw new IllegalArgumentException();
}
}
}
}
// End UtilTest.java
|
farrago/src/org/eigenbase/util/UtilTest.java
|
/*
// $Id$
// Package org.eigenbase is a class library of data management components.
// Copyright (C) 2005-2007 The Eigenbase Project
// Copyright (C) 2002-2007 Disruptive Tech
// Copyright (C) 2005-2007 LucidEra, Inc.
// Portions Copyright (C) 2003-2007 John V. Sichi
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version approved by The Eigenbase Project.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.eigenbase.util;
import java.io.*;
import java.math.*;
import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import junit.framework.*;
import junit.textui.*;
import org.eigenbase.runtime.*;
import org.eigenbase.test.DiffTestCase;
/**
* Unit test for {@link Util} and other classes in this package.
*
* @author jhyde
* @version $Id$
* @since Jul 12, 2004
*/
public class UtilTest
extends TestCase
{
//~ Constructors -----------------------------------------------------------
public UtilTest(String name)
{
super(name);
}
//~ Methods ----------------------------------------------------------------
public static Test suite()
throws Exception
{
TestSuite suite = new TestSuite();
suite.addTestSuite(UtilTest.class);
return suite;
}
public void testPrintEquals()
{
assertPrintEquals("\"x\"", "x", true);
}
public void testPrintEquals2()
{
assertPrintEquals("\"x\"", "x", false);
}
public void testPrintEquals3()
{
assertPrintEquals("null", null, true);
}
public void testPrintEquals4()
{
assertPrintEquals("", null, false);
}
public void testPrintEquals5()
{
assertPrintEquals("\"\\\\\\\"\\r\\n\"", "\\\"\r\n", true);
}
public void testScientificNotation()
{
BigDecimal bd;
bd = new BigDecimal("0.001234");
TestUtil.assertEqualsVerbose(
"1.234E-3",
Util.toScientificNotation(bd));
bd = new BigDecimal("0.001");
TestUtil.assertEqualsVerbose(
"1E-3",
Util.toScientificNotation(bd));
bd = new BigDecimal("-0.001");
TestUtil.assertEqualsVerbose(
"-1E-3",
Util.toScientificNotation(bd));
bd = new BigDecimal("1");
TestUtil.assertEqualsVerbose(
"1E0",
Util.toScientificNotation(bd));
bd = new BigDecimal("-1");
TestUtil.assertEqualsVerbose(
"-1E0",
Util.toScientificNotation(bd));
bd = new BigDecimal("1.0");
TestUtil.assertEqualsVerbose(
"1.0E0",
Util.toScientificNotation(bd));
bd = new BigDecimal("12345");
TestUtil.assertEqualsVerbose(
"1.2345E4",
Util.toScientificNotation(bd));
bd = new BigDecimal("12345.00");
TestUtil.assertEqualsVerbose(
"1.234500E4",
Util.toScientificNotation(bd));
bd = new BigDecimal("12345.001");
TestUtil.assertEqualsVerbose(
"1.2345001E4",
Util.toScientificNotation(bd));
//test truncate
bd = new BigDecimal("1.23456789012345678901");
TestUtil.assertEqualsVerbose(
"1.2345678901234567890E0",
Util.toScientificNotation(bd));
bd = new BigDecimal("-1.23456789012345678901");
TestUtil.assertEqualsVerbose(
"-1.2345678901234567890E0",
Util.toScientificNotation(bd));
}
public void testToJavaId()
throws UnsupportedEncodingException
{
assertEquals(
"ID$0$foo",
Util.toJavaId("foo", 0));
assertEquals(
"ID$0$foo_20_bar",
Util.toJavaId("foo bar", 0));
assertEquals(
"ID$0$foo__bar",
Util.toJavaId("foo_bar", 0));
assertEquals(
"ID$100$_30_bar",
Util.toJavaId("0bar", 100));
assertEquals(
"ID$0$foo0bar",
Util.toJavaId("foo0bar", 0));
assertEquals(
"ID$0$it_27_s_20_a_20_bird_2c__20_it_27_s_20_a_20_plane_21_",
Util.toJavaId("it's a bird, it's a plane!", 0));
// Try some funny non-ASCII charsets
assertEquals(
"ID$0$_f6__cb__c4__ca__ae__c1__f9__cb_",
Util.toJavaId(
"\u00f6\u00cb\u00c4\u00ca\u00ae\u00c1\u00f9\u00cb",
0));
assertEquals(
"ID$0$_f6cb__c4ca__aec1__f9cb_",
Util.toJavaId("\uf6cb\uc4ca\uaec1\uf9cb", 0));
byte [] bytes1 = { 3, 12, 54, 23, 33, 23, 45, 21, 127, -34, -92, -113 };
assertEquals(
"ID$0$_3__c_6_17__21__17__2d__15__7f__6cd9__fffd_",
Util.toJavaId(new String(bytes1, "EUC-JP"),
0));
byte [] bytes2 =
{ 64, 32, 43, -45, -23, 0, 43, 54, 119, -32, -56, -34 };
assertEquals(
"ID$0$_30c__3617__2117__2d15__7fde__a48f_",
Util.toJavaId(new String(bytes1, "UTF-16"),
0));
}
private void assertPrintEquals(
String expect,
String in,
boolean nullMeansNull)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Util.printJavaString(pw, in, nullMeansNull);
pw.flush();
String out = sw.toString();
assertEquals(expect, out);
}
/**
* Tests whether {@link EnumeratedValues} serialize correctly.
*/
public void testSerializeEnumeratedValues()
throws IOException, ClassNotFoundException
{
UnserializableEnum unser =
(UnserializableEnum) serializeAndDeserialize(
UnserializableEnum.Foo);
assertFalse(unser == UnserializableEnum.Foo);
SerializableEnum ser =
(SerializableEnum) serializeAndDeserialize(SerializableEnum.Foo);
assertTrue(ser == SerializableEnum.Foo);
}
private static Object serializeAndDeserialize(Object e1)
throws IOException, ClassNotFoundException
{
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(e1);
out.flush();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(bin);
Object o = in.readObject();
return o;
}
/**
* Unit-test for {@link BitString}.
*/
public void testBitString()
{
// Powers of two, minimal length.
final BitString b0 = new BitString("", 0);
final BitString b1 = new BitString("1", 1);
final BitString b2 = new BitString("10", 2);
final BitString b4 = new BitString("100", 3);
final BitString b8 = new BitString("1000", 4);
final BitString b16 = new BitString("10000", 5);
final BitString b32 = new BitString("100000", 6);
final BitString b64 = new BitString("1000000", 7);
final BitString b128 = new BitString("10000000", 8);
final BitString b256 = new BitString("100000000", 9);
// other strings
final BitString b0_1 = new BitString("", 1);
final BitString b0_12 = new BitString("", 12);
// conversion to hex strings
assertEquals(
"",
b0.toHexString());
assertEquals(
"1",
b1.toHexString());
assertEquals(
"2",
b2.toHexString());
assertEquals(
"4",
b4.toHexString());
assertEquals(
"8",
b8.toHexString());
assertEquals(
"10",
b16.toHexString());
assertEquals(
"20",
b32.toHexString());
assertEquals(
"40",
b64.toHexString());
assertEquals(
"80",
b128.toHexString());
assertEquals(
"100",
b256.toHexString());
assertEquals(
"0",
b0_1.toHexString());
assertEquals(
"000",
b0_12.toHexString());
// to byte array
assertByteArray("01", "1", 1);
assertByteArray("01", "1", 5);
assertByteArray("01", "1", 8);
assertByteArray("00, 01", "1", 9);
assertByteArray("", "", 0);
assertByteArray("00", "0", 1);
assertByteArray("00", "0000", 2); // bit count less than string
assertByteArray("00", "000", 5); // bit count larger than string
assertByteArray("00", "0", 8); // precisely 1 byte
assertByteArray("00, 00", "00", 9); // just over 1 byte
// from hex string
assertReversible("");
assertReversible("1");
assertReversible("10");
assertReversible("100");
assertReversible("1000");
assertReversible("10000");
assertReversible("100000");
assertReversible("1000000");
assertReversible("10000000");
assertReversible("100000000");
assertReversible("01");
assertReversible("001010");
assertReversible("000000000100");
}
private static void assertReversible(String s)
{
assertEquals(
s,
BitString.createFromBitString(s).toBitString(),
s);
assertEquals(
s,
BitString.createFromHexString(s).toHexString());
}
private void assertByteArray(
String expected,
String bits,
int bitCount)
{
byte [] bytes = BitString.toByteArrayFromBitString(bits, bitCount);
final String s = toString(bytes);
assertEquals(expected, s);
}
/**
* Converts a byte array to a hex string like "AB, CD".
*/
private String toString(byte [] bytes)
{
StringBuilder buf = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
if (i > 0) {
buf.append(", ");
}
String s = Integer.toString(b, 16);
buf.append((b < 16) ? ("0" + s) : s);
}
return buf.toString();
}
/**
* Tests {@link CastingList} and {@link Util#cast}.
*/
public void testCastingList()
{
final List<Number> numberList = new ArrayList<Number>();
numberList.add(new Integer(1));
numberList.add(null);
numberList.add(new Integer(2));
List<Integer> integerList = Util.cast(numberList, Integer.class);
assertEquals(3, integerList.size());
assertEquals(new Integer(2), integerList.get(2));
// Nulls are OK.
assertNull(integerList.get(1));
// Can update the underlying list.
integerList.set(1, 345);
assertEquals(new Integer(345), integerList.get(1));
integerList.set(1, null);
assertNull(integerList.get(1));
// Can add a member of the wrong type to the underlying list.
numberList.add(new Double(3.1415));
assertEquals(4, integerList.size());
// Access a member which is of the wrong type.
try {
integerList.get(3);
fail("expected exception");
} catch (ClassCastException e) {
// ok
}
}
public void testIterableProperties()
{
Properties properties = new Properties();
properties.put("foo", "george");
properties.put("bar", "ringo");
StringBuilder sb = new StringBuilder();
for (
Map.Entry<String, String> entry : Util.toMap(properties).entrySet())
{
sb.append(entry.getKey()).append("=").append(entry.getValue());
sb.append(";");
}
assertEquals("bar=ringo;foo=george;", sb.toString());
assertEquals(2, Util.toMap(properties).entrySet().size());
properties.put("nonString", 34);
try {
for (
Map.Entry<String, String> entry
: Util.toMap(properties).entrySet())
{
String s = entry.getValue();
Util.discard(s);
}
fail("expected exception");
} catch (ClassCastException e) {
// ok
}
}
/**
* Tests the difference engine, {@link DiffTestCase#diff}.
*/
public void testDiffLines() {
String[] before = {
"Get a dose of her in jackboots and kilt",
"She's killer-diller when she's dressed to the hilt",
"She's the kind of a girl that makes The News of The World",
"Yes you could say she was attractively built.",
"Yeah yeah yeah."
};
String[] after = {
"Get a dose of her in jackboots and kilt",
"(they call her \"Polythene Pam\")",
"She's killer-diller when she's dressed to the hilt",
"She's the kind of a girl that makes The Sunday Times",
"seem more interesting.",
"Yes you could say she was attractively built."
};
String diff = DiffTestCase.diffLines(
Arrays.asList(before), Arrays.asList(after));
assertEquals(
diff,
TestUtil.fold("1a2\n" +
"> (they call her \"Polythene Pam\")\n" +
"3c4,5\n" +
"< She's the kind of a girl that makes The News of The World\n" +
"---\n" +
"> She's the kind of a girl that makes The Sunday Times\n" +
"> seem more interesting.\n" +
"5d6\n" +
"< Yeah yeah yeah.\n"));
}
/**
* Tests the {@link Util#toPosix(TimeZone, boolean)} method.
*/
public void testPosixTimeZone()
{
// NOTE jvs 31-July-2007: First two tests are disabled since
// not everyone may have patched their system yet for recent
// DST change.
// Pacific Standard Time. Effective 2007, the local time changes from
// PST to PDT at 02:00 LST to 03:00 LDT on the second Sunday in March
// and returns at 02:00 LDT to 01:00 LST on the first Sunday in
// November.
if (false) {
assertEquals("PST-8PDT,M3.2.0,M11.1.0",
Util.toPosix(TimeZone.getTimeZone("PST"), false));
assertEquals("PST-8PDT1,M3.2.0/2,M11.1.0/2",
Util.toPosix(TimeZone.getTimeZone("PST"), true));
}
// Tokyo has +ve offset, no DST
assertEquals("JST9",
Util.toPosix(TimeZone.getTimeZone("Asia/Tokyo"), true));
// Sydney, Australia lies ten hours east of GMT and makes a one hour
// shift forward during daylight savings. Being located in the southern
// hemisphere, daylight savings begins on the last Sunday in October at
// 2am and ends on the last Sunday in March at 3am.
// (Uses STANDARD_TIME time-transition mode.)
try {
TimeZone timezone = TimeZone.getTimeZone("Australia/Sydney");
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date testDate = format.parse("2008-10-3");
if (timezone.inDaylightTime(testDate)) {
assertEquals(timezone.toString(),
"EST10EST1,M10.5.0/2,M3.5.0/3",
Util.toPosix(TimeZone.getTimeZone("Australia/Sydney"),
true));
} else {
assertEquals(timezone.toString(),
"EST10EST1,M10.1.0/2,M4.1.0/3",
Util.toPosix(TimeZone.getTimeZone("Australia/Sydney"),
true));
}
} catch (ParseException pe) { fail("Problem parsing test date"); }
// Paris, France. (Uses UTC_TIME time-transition mode.)
assertEquals("CET1CEST1,M3.5.0/2,M10.5.0/3",
Util.toPosix(TimeZone.getTimeZone("Europe/Paris"), true));
assertEquals("UTC0",
Util.toPosix(TimeZone.getTimeZone("UTC"), true));
}
/**
* Runs the test suite.
*/
public static void main(String [] args)
throws Exception
{
TestRunner.run(suite());
}
//~ Inner Classes ----------------------------------------------------------
/**
* Enumeration which extends BasicValue does NOT serialize correctly.
*/
private static class UnserializableEnum
extends EnumeratedValues.BasicValue
{
public static final UnserializableEnum Foo =
new UnserializableEnum("foo", 1);
public static final UnserializableEnum Bar =
new UnserializableEnum("bar", 2);
public UnserializableEnum(String name, int ordinal)
{
super(name, ordinal, null);
}
}
/**
* Enumeration which serializes correctly.
*/
private static class SerializableEnum
extends EnumeratedValues.SerializableValue
{
public static final SerializableEnum Foo =
new SerializableEnum("foo", 1);
public static final SerializableEnum Bar =
new SerializableEnum("bar", 2);
public SerializableEnum(String name, int ordinal)
{
super(name, ordinal, null);
}
protected Object readResolve()
throws ObjectStreamException
{
switch (_ordinal) {
case 1:
return Foo;
case 2:
return Bar;
default:
throw new IllegalArgumentException();
}
}
}
}
// End UtilTest.java
|
Removed some debugging
[git-p4: depot-paths = "//open/dt/dev/": change = 10655]
|
farrago/src/org/eigenbase/util/UtilTest.java
|
Removed some debugging
|
<ide><path>arrago/src/org/eigenbase/util/UtilTest.java
<ide>
<ide> if (timezone.inDaylightTime(testDate)) {
<ide>
<del> assertEquals(timezone.toString(),
<del> "EST10EST1,M10.5.0/2,M3.5.0/3",
<add> assertEquals("EST10EST1,M10.5.0/2,M3.5.0/3",
<ide> Util.toPosix(TimeZone.getTimeZone("Australia/Sydney"),
<ide> true));
<ide> } else {
<ide>
<del> assertEquals(timezone.toString(),
<del> "EST10EST1,M10.1.0/2,M4.1.0/3",
<add> assertEquals("EST10EST1,M10.1.0/2,M4.1.0/3",
<ide> Util.toPosix(TimeZone.getTimeZone("Australia/Sydney"),
<ide> true));
<ide> }
|
|
Java
|
apache-2.0
|
446aa283083beeaad011bf13a304ad7f08c5d638
| 0 |
rholder/esthree,rholder/esthree
|
/*
* Copyright 2014 Ray Holder
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.rholder.esthree.command;
import com.amazonaws.AmazonClientException;
import com.amazonaws.event.ProgressEvent;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.transfer.internal.TransferProgressImpl;
import com.amazonaws.util.BinaryUtils;
import com.github.rholder.esthree.progress.MutableProgressListener;
import com.github.rholder.esthree.progress.Progress;
import com.github.rholder.esthree.progress.TransferProgressWrapper;
import com.github.rholder.esthree.util.RetryUtils;
import com.github.rholder.retry.RetryException;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
public class Get implements Callable<Integer> {
public static final int DEFAULT_BUF_SIZE = 4096 * 4;
public AmazonS3Client amazonS3Client;
public String bucket;
public String key;
public RandomAccessFile output;
private MutableProgressListener progressListener;
private MessageDigest currentDigest;
private long contentLength;
private String fullETag;
public Get(AmazonS3Client amazonS3Client, String bucket, String key, File outputFile) throws FileNotFoundException {
this.amazonS3Client = amazonS3Client;
this.bucket = bucket;
this.key = key;
this.output = new RandomAccessFile(outputFile, "rw");
}
public Get withProgressListener(MutableProgressListener progressListener) {
this.progressListener = progressListener;
return this;
}
@Override
public Integer call() throws Exception {
// this is the most up to date digest, it's initialized here but later holds the most up to date valid digest
currentDigest = MessageDigest.getInstance("MD5");
currentDigest = retryingGet();
if(progressListener != null) {
progressListener.progressChanged(new ProgressEvent(ProgressEvent.COMPLETED_EVENT_CODE, 0));
}
if (!fullETag.contains("-")) {
byte[] expected = BinaryUtils.fromHex(fullETag);
byte[] current = currentDigest.digest();
if (!Arrays.equals(expected, current)) {
throw new AmazonClientException("Unable to verify integrity of data download. "
+ "Client calculated content hash didn't match hash calculated by Amazon S3. "
+ "The data may be corrupt.");
}
} else {
// TODO log warning that we can't validate the MD5
System.err.println("MD5 does not exist on AWS for file, calculated value: " + BinaryUtils.toHex(currentDigest.digest()));
}
// TODO add ability to resume from previously downloaded chunks
// TODO add rate limiter
return 0;
}
public MessageDigest retryingGet()
throws ExecutionException, RetryException {
return (MessageDigest) RetryUtils.AWS_RETRYER.call(new Callable<Object>() {
public MessageDigest call() throws Exception {
GetObjectRequest req = new GetObjectRequest(bucket, key);
S3Object s3Object = amazonS3Client.getObject(req);
contentLength = s3Object.getObjectMetadata().getContentLength();
fullETag = s3Object.getObjectMetadata().getETag();
Progress progress = new TransferProgressWrapper(new TransferProgressImpl());
progress.setTotalBytesToTransfer(contentLength);
if (progressListener != null) {
progressListener.withTransferProgress(progress)
.withCompleted(0.0)
.withMultiplier(1.0);
}
InputStream input = null;
try {
// seek to the start of the chunk in the file, just in case we're retrying
output.seek(0);
input = s3Object.getObjectContent();
return copyAndHash(input, contentLength, progress);
} finally {
IOUtils.closeQuietly(input);
}
}
});
}
public MessageDigest copyAndHash(InputStream input, long totalBytes, Progress progress)
throws IOException, CloneNotSupportedException {
// clone the current digest, such that it remains unchanged in this method
MessageDigest computedDigest = (MessageDigest) currentDigest.clone();
byte[] buffer = new byte[DEFAULT_BUF_SIZE];
long count = 0;
int n;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
if (progressListener != null) {
progress.updateProgress(n);
progressListener.progressChanged(new ProgressEvent(n));
}
computedDigest.update(buffer, 0, n);
count += n;
}
// verify that at least this many bytes were read
if (totalBytes != count) {
throw new IOException(String.format("%d bytes downloaded instead of expected %d bytes", count, totalBytes));
}
return computedDigest;
}
}
|
src/main/java/com/github/rholder/esthree/command/Get.java
|
/*
* Copyright 2014 Ray Holder
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.rholder.esthree.command;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.transfer.Download;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.github.rholder.esthree.progress.MutableProgressListener;
import com.github.rholder.esthree.progress.TransferProgressWrapper;
import java.io.File;
import java.util.concurrent.Callable;
public class Get implements Callable<Integer> {
public AmazonS3Client amazonS3Client;
public String bucket;
public String key;
public File outputFile;
private MutableProgressListener progressListener;
public Get(AmazonS3Client amazonS3Client, String bucket, String key, File outputFile) {
this.amazonS3Client = amazonS3Client;
this.bucket = bucket;
this.key = key;
this.outputFile = outputFile;
}
public Get withProgressListener(MutableProgressListener progressListener) {
this.progressListener = progressListener;
return this;
}
@Override
public Integer call() throws Exception {
TransferManager t = new TransferManager(amazonS3Client);
Download d = t.download(bucket, key, outputFile);
if (progressListener != null) {
progressListener.withTransferProgress(new TransferProgressWrapper(d.getProgress()));
d.addProgressListener(progressListener);
}
d.waitForCompletion();
String eTag = d.getObjectMetadata().getETag();
String contentMD5 = d.getObjectMetadata().getContentMD5();
if(eTag.equals(contentMD5)) {
return 0;
} else {
System.err.println("MD5's do not match :(");
return -1;
}
}
}
|
refactor non-multi Get since the high level AWS API doesn't auto-calculate an MD5 to verify
|
src/main/java/com/github/rholder/esthree/command/Get.java
|
refactor non-multi Get since the high level AWS API doesn't auto-calculate an MD5 to verify
|
<ide><path>rc/main/java/com/github/rholder/esthree/command/Get.java
<ide>
<ide> package com.github.rholder.esthree.command;
<ide>
<add>import com.amazonaws.AmazonClientException;
<add>import com.amazonaws.event.ProgressEvent;
<ide> import com.amazonaws.services.s3.AmazonS3Client;
<del>import com.amazonaws.services.s3.transfer.Download;
<del>import com.amazonaws.services.s3.transfer.TransferManager;
<add>import com.amazonaws.services.s3.model.GetObjectRequest;
<add>import com.amazonaws.services.s3.model.S3Object;
<add>import com.amazonaws.services.s3.transfer.internal.TransferProgressImpl;
<add>import com.amazonaws.util.BinaryUtils;
<ide> import com.github.rholder.esthree.progress.MutableProgressListener;
<add>import com.github.rholder.esthree.progress.Progress;
<ide> import com.github.rholder.esthree.progress.TransferProgressWrapper;
<add>import com.github.rholder.esthree.util.RetryUtils;
<add>import com.github.rholder.retry.RetryException;
<add>import org.apache.commons.io.IOUtils;
<ide>
<ide> import java.io.File;
<add>import java.io.FileNotFoundException;
<add>import java.io.IOException;
<add>import java.io.InputStream;
<add>import java.io.RandomAccessFile;
<add>import java.security.MessageDigest;
<add>import java.util.Arrays;
<ide> import java.util.concurrent.Callable;
<add>import java.util.concurrent.ExecutionException;
<ide>
<ide> public class Get implements Callable<Integer> {
<add>
<add> public static final int DEFAULT_BUF_SIZE = 4096 * 4;
<ide>
<ide> public AmazonS3Client amazonS3Client;
<ide> public String bucket;
<ide> public String key;
<del> public File outputFile;
<add> public RandomAccessFile output;
<ide>
<ide> private MutableProgressListener progressListener;
<add> private MessageDigest currentDigest;
<add> private long contentLength;
<add> private String fullETag;
<ide>
<del> public Get(AmazonS3Client amazonS3Client, String bucket, String key, File outputFile) {
<add> public Get(AmazonS3Client amazonS3Client, String bucket, String key, File outputFile) throws FileNotFoundException {
<ide> this.amazonS3Client = amazonS3Client;
<ide> this.bucket = bucket;
<ide> this.key = key;
<del> this.outputFile = outputFile;
<add> this.output = new RandomAccessFile(outputFile, "rw");
<ide> }
<ide>
<ide> public Get withProgressListener(MutableProgressListener progressListener) {
<ide>
<ide> @Override
<ide> public Integer call() throws Exception {
<del> TransferManager t = new TransferManager(amazonS3Client);
<del> Download d = t.download(bucket, key, outputFile);
<del> if (progressListener != null) {
<del> progressListener.withTransferProgress(new TransferProgressWrapper(d.getProgress()));
<del> d.addProgressListener(progressListener);
<add>
<add> // this is the most up to date digest, it's initialized here but later holds the most up to date valid digest
<add> currentDigest = MessageDigest.getInstance("MD5");
<add> currentDigest = retryingGet();
<add>
<add> if(progressListener != null) {
<add> progressListener.progressChanged(new ProgressEvent(ProgressEvent.COMPLETED_EVENT_CODE, 0));
<ide> }
<del> d.waitForCompletion();
<ide>
<del> String eTag = d.getObjectMetadata().getETag();
<del> String contentMD5 = d.getObjectMetadata().getContentMD5();
<del> if(eTag.equals(contentMD5)) {
<del> return 0;
<add> if (!fullETag.contains("-")) {
<add> byte[] expected = BinaryUtils.fromHex(fullETag);
<add> byte[] current = currentDigest.digest();
<add> if (!Arrays.equals(expected, current)) {
<add> throw new AmazonClientException("Unable to verify integrity of data download. "
<add> + "Client calculated content hash didn't match hash calculated by Amazon S3. "
<add> + "The data may be corrupt.");
<add> }
<ide> } else {
<del> System.err.println("MD5's do not match :(");
<del> return -1;
<add> // TODO log warning that we can't validate the MD5
<add> System.err.println("MD5 does not exist on AWS for file, calculated value: " + BinaryUtils.toHex(currentDigest.digest()));
<ide> }
<add> // TODO add ability to resume from previously downloaded chunks
<add> // TODO add rate limiter
<add>
<add> return 0;
<add>
<add> }
<add>
<add> public MessageDigest retryingGet()
<add> throws ExecutionException, RetryException {
<add>
<add> return (MessageDigest) RetryUtils.AWS_RETRYER.call(new Callable<Object>() {
<add> public MessageDigest call() throws Exception {
<add>
<add> GetObjectRequest req = new GetObjectRequest(bucket, key);
<add>
<add> S3Object s3Object = amazonS3Client.getObject(req);
<add> contentLength = s3Object.getObjectMetadata().getContentLength();
<add> fullETag = s3Object.getObjectMetadata().getETag();
<add>
<add> Progress progress = new TransferProgressWrapper(new TransferProgressImpl());
<add> progress.setTotalBytesToTransfer(contentLength);
<add> if (progressListener != null) {
<add> progressListener.withTransferProgress(progress)
<add> .withCompleted(0.0)
<add> .withMultiplier(1.0);
<add> }
<add>
<add> InputStream input = null;
<add> try {
<add> // seek to the start of the chunk in the file, just in case we're retrying
<add> output.seek(0);
<add> input = s3Object.getObjectContent();
<add>
<add> return copyAndHash(input, contentLength, progress);
<add> } finally {
<add> IOUtils.closeQuietly(input);
<add> }
<add> }
<add> });
<add> }
<add>
<add> public MessageDigest copyAndHash(InputStream input, long totalBytes, Progress progress)
<add> throws IOException, CloneNotSupportedException {
<add>
<add> // clone the current digest, such that it remains unchanged in this method
<add> MessageDigest computedDigest = (MessageDigest) currentDigest.clone();
<add> byte[] buffer = new byte[DEFAULT_BUF_SIZE];
<add>
<add> long count = 0;
<add> int n;
<add> while (-1 != (n = input.read(buffer))) {
<add> output.write(buffer, 0, n);
<add> if (progressListener != null) {
<add> progress.updateProgress(n);
<add> progressListener.progressChanged(new ProgressEvent(n));
<add> }
<add> computedDigest.update(buffer, 0, n);
<add> count += n;
<add> }
<add>
<add> // verify that at least this many bytes were read
<add> if (totalBytes != count) {
<add> throw new IOException(String.format("%d bytes downloaded instead of expected %d bytes", count, totalBytes));
<add> }
<add> return computedDigest;
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
65d474d8bb1c6c612c91bc76dc336234f4a64e93
| 0 |
facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho
|
/*
* Copyright 2014-present Facebook, 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.facebook.litho.widget;
import static android.support.v7.widget.OrientationHelper.HORIZONTAL;
import static android.support.v7.widget.OrientationHelper.VERTICAL;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static com.facebook.litho.MeasureComparisonUtils.isMeasureSpecCompatible;
import static com.facebook.litho.widget.ComponentTreeHolder.RENDER_UNINITIALIZED;
import static com.facebook.litho.widget.RenderInfoViewCreatorController.DEFAULT_COMPONENT_VIEW_TYPE;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.support.annotation.IntDef;
import android.support.annotation.UiThread;
import android.support.annotation.VisibleForTesting;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.LayoutManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import com.facebook.litho.Component;
import com.facebook.litho.ComponentContext;
import com.facebook.litho.ComponentTree;
import com.facebook.litho.ComponentTree.MeasureListener;
import com.facebook.litho.ComponentsSystrace;
import com.facebook.litho.EventHandler;
import com.facebook.litho.LayoutHandler;
import com.facebook.litho.LithoView;
import com.facebook.litho.MeasureComparisonUtils;
import com.facebook.litho.RenderCompleteEvent;
import com.facebook.litho.Size;
import com.facebook.litho.SizeSpec;
import com.facebook.litho.ThreadUtils;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.utils.DisplayListUtils;
import com.facebook.litho.viewcompat.ViewBinder;
import com.facebook.litho.viewcompat.ViewCreator;
import com.facebook.litho.widget.ComponentTreeHolder.ComponentTreeMeasureListenerFactory;
import com.facebook.litho.widget.ComponentTreeHolder.RenderState;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
/**
* This binder class is used to asynchronously layout Components given a list of {@link Component}
* and attaching them to a {@link RecyclerSpec}.
*/
@ThreadSafe
public class RecyclerBinder
implements Binder<RecyclerView>, LayoutInfo.RenderInfoCollection, HasStickyHeader {
private static final int UNINITIALIZED = -1;
private static final Size sDummySize = new Size();
private static final String TAG = RecyclerBinder.class.getSimpleName();
private static final int POST_UPDATE_VIEWPORT_AND_COMPUTE_RANGE_MAX_ATTEMPTS = 3;
@GuardedBy("this")
private final List<ComponentTreeHolder> mComponentTreeHolders = new ArrayList<>();
@GuardedBy("this")
private final List<ComponentTreeHolder> mAsyncComponentTreeHolders = new ArrayList<>();
private final LayoutInfo mLayoutInfo;
private final RecyclerView.Adapter mInternalAdapter;
private final ComponentContext mComponentContext;
private final RangeScrollListener mRangeScrollListener = new RangeScrollListener();
private final LayoutHandlerFactory mLayoutHandlerFactory;
private final @Nullable LithoViewFactory mLithoViewFactory;
private final ComponentTreeHolderFactory mComponentTreeHolderFactory;
private final Handler mMainThreadHandler = new Handler(Looper.getMainLooper());
private final float mRangeRatio;
private final AtomicBoolean mIsMeasured = new AtomicBoolean(false);
private final AtomicBoolean mRequiresRemeasure = new AtomicBoolean(false);
@GuardedBy("this")
private final ArrayList<AsyncInsertOperation> mInsertsWaitingForInitialMeasure =
new ArrayList<>();
@GuardedBy("this")
private final Deque<AsyncBatch> mAsyncBatches = new ArrayDeque<>();
@VisibleForTesting
final Runnable mRemeasureRunnable =
new Runnable() {
@Override
public void run() {
if (mReMeasureEventEventHandler != null) {
mReMeasureEventEventHandler.dispatchEvent(new ReMeasureEvent());
}
}
};
private final Runnable mNotifyDatasetChangedRunnable = new Runnable() {
@Override
public void run() {
mInternalAdapter.notifyDataSetChanged();
}
};
private final ComponentTreeMeasureListenerFactory mComponentTreeMeasureListenerFactory =
new ComponentTreeMeasureListenerFactory() {
@Override
public MeasureListener create(final ComponentTreeHolder holder) {
return getMeasureListener(holder);
}
};
private String mSplitLayoutTag;
private MeasureListener getMeasureListener(final ComponentTreeHolder holder) {
return new MeasureListener() {
@Override
public void onSetRootAndSizeSpec(int width, int height) {
if (holder.getMeasuredHeight() == height) {
return;
}
holder.setMeasuredHeight(height);
final RangeCalculationResult range = RecyclerBinder.this.mRange;
if (range != null
&& holder.getMeasuredHeight() <= RecyclerBinder.this.mRange.measuredSize) {
return;
}
synchronized (RecyclerBinder.this) {
resetMeasuredSize(width);
}
requestRemeasure();
}
};
}
private final ComponentTree.NewLayoutStateReadyListener mAsyncLayoutReadyListener =
new ComponentTree.NewLayoutStateReadyListener() {
@UiThread
@Override
public void onNewLayoutStateReady(ComponentTree componentTree) {
if (mMountedView == null) {
applyReadyBatches();
} else {
// When mounted, always apply binder mutations on frame boundaries
ViewCompat.postOnAnimation(mMountedView, mApplyReadyBatchesRunnable);
}
}
};
@VisibleForTesting
final Runnable mApplyReadyBatchesRunnable =
new Runnable() {
@UiThread
@Override
public void run() {
applyReadyBatches();
}
};
private final boolean mIsCircular;
private final boolean mHasDynamicItemHeight;
private final boolean mWrapContent;
private int mLastWidthSpec = UNINITIALIZED;
private int mLastHeightSpec = UNINITIALIZED;
private Size mMeasuredSize;
private RecyclerView mMountedView;
@VisibleForTesting int mCurrentFirstVisiblePosition = RecyclerView.NO_POSITION;
@VisibleForTesting int mCurrentLastVisiblePosition = RecyclerView.NO_POSITION;
private int mCurrentOffset;
private @Nullable RangeCalculationResult mRange;
private StickyHeaderController mStickyHeaderController;
private final boolean mCanPrefetchDisplayLists;
private final boolean mCanCacheDrawingDisplayLists;
private EventHandler<ReMeasureEvent> mReMeasureEventEventHandler;
private volatile boolean mHasAsyncOperations = false;
private volatile boolean mAsyncInsertsShouldWaitForMeasure = true;
private volatile boolean mHasFilledViewport = false;
private String mInvalidStateLogId;
@GuardedBy("this")
private @Nullable AsyncBatch mCurrentBatch = null;
@VisibleForTesting final ViewportManager mViewportManager;
private final ViewportChanged mViewportChangedListener =
new ViewportChanged() {
@Override
public void viewportChanged(
int firstVisibleIndex,
int lastVisibleIndex,
int firstFullyVisibleIndex,
int lastFullyVisibleIndex,
int state) {
onNewVisibleRange(firstVisibleIndex, lastVisibleIndex);
onNewWorkingRange(
firstVisibleIndex, lastVisibleIndex, firstFullyVisibleIndex, lastFullyVisibleIndex);
}
};
private int mPostUpdateViewportAndComputeRangeAttempts;
@VisibleForTesting final RenderInfoViewCreatorController mRenderInfoViewCreatorController;
// todo T30260224
private final Runnable mUpdateViewportAndComputeRangeRunnable =
new Runnable() {
@Override
public void run() {
// If mount hasn't happened or we don't have any pending updates, we're ready to compute
// range.
if (mMountedView == null || !mMountedView.hasPendingAdapterUpdates()) {
if (mViewportManager.shouldUpdate()) {
mViewportManager.onViewportChanged(State.DATA_CHANGES);
}
mPostUpdateViewportAndComputeRangeAttempts = 0;
computeRange(mCurrentFirstVisiblePosition, mCurrentLastVisiblePosition);
return;
}
// If the view gets detached, we can still have pending updates.
// If the view's visibility is GONE, layout won't happen until it becomes visible. We have
// to exit here, otherwise we keep posting this runnable to the next frame until it
// becomes visible.
if (!mMountedView.isAttachedToWindow() || mMountedView.getVisibility() == View.GONE) {
mPostUpdateViewportAndComputeRangeAttempts = 0;
return;
}
if (mPostUpdateViewportAndComputeRangeAttempts
>= POST_UPDATE_VIEWPORT_AND_COMPUTE_RANGE_MAX_ATTEMPTS) {
mPostUpdateViewportAndComputeRangeAttempts = 0;
if (mViewportManager.shouldUpdate()) {
mViewportManager.onViewportChanged(State.DATA_CHANGES);
}
final int size = mComponentTreeHolders.size();
if (size == 0) {
return;
}
/**
* We only update first and last visible positions after the RecyclerView triggers a
* layout for its pending updates. If consuming updates is posted to the next frame,
* which the RecyclerView can do, then we go into this runnable after the component tree
* holders have been modified but before first/last indexes were updated. This can make
* these positions get out of bounds, so we make sure we access valid indexes before
* computing range.
*/
final int first = Math.min(mCurrentFirstVisiblePosition, size - 1);
final int last = Math.min(mCurrentLastVisiblePosition, size - 1);
computeRange(first, last);
return;
}
// If we have pending updates, wait until the sync operations are finished and try again
// in the next frame.
mPostUpdateViewportAndComputeRangeAttempts++;
ViewCompat.postOnAnimation(mMountedView, mUpdateViewportAndComputeRangeRunnable);
}
};
static class RenderCompleteRunnable implements Runnable {
private final EventHandler<RenderCompleteEvent> renderCompleteEventHandler;
private final boolean hasMounted;
private final long timestampMillis;
RenderCompleteRunnable(
EventHandler<RenderCompleteEvent> renderCompleteEventHandler,
boolean hasMounted,
long timestampMillis) {
this.renderCompleteEventHandler = renderCompleteEventHandler;
this.hasMounted = hasMounted;
this.timestampMillis = timestampMillis;
}
@Override
public void run() {
dispatchRenderCompleteEvent(renderCompleteEventHandler, hasMounted, timestampMillis);
}
}
interface ComponentTreeHolderFactory {
ComponentTreeHolder create(
RenderInfo renderInfo,
LayoutHandler layoutHandler,
boolean canPrefetchDisplayLists,
boolean canCacheDrawingDisplayLists,
ComponentTreeMeasureListenerFactory measureListenerFactory,
String splitLayoutTag);
}
static final ComponentTreeHolderFactory DEFAULT_COMPONENT_TREE_HOLDER_FACTORY =
new ComponentTreeHolderFactory() {
@Override
public ComponentTreeHolder create(
RenderInfo renderInfo,
LayoutHandler layoutHandler,
boolean canPrefetchDisplayLists,
boolean canCacheDrawingDisplayLists,
ComponentTreeMeasureListenerFactory measureListenerFactory,
String splitLayoutTag) {
return ComponentTreeHolder.acquire(
renderInfo,
layoutHandler,
canPrefetchDisplayLists,
canCacheDrawingDisplayLists,
measureListenerFactory,
splitLayoutTag);
}
};
public static class Builder {
private float rangeRatio = 4f;
private LayoutInfo layoutInfo;
private @Nullable LayoutHandlerFactory layoutHandlerFactory;
private boolean canPrefetchDisplayLists;
private boolean canCacheDrawingDisplayLists;
private ComponentTreeHolderFactory componentTreeHolderFactory =
DEFAULT_COMPONENT_TREE_HOLDER_FACTORY;
private ComponentContext componentContext;
private LithoViewFactory lithoViewFactory;
private boolean isCircular;
private boolean hasDynamicItemHeight;
private boolean wrapContent;
private boolean customViewTypeEnabled;
private int componentViewType;
private @Nullable RecyclerView.Adapter overrideInternalAdapter;
private String splitLayoutTag;
/**
* @param rangeRatio specifies how big a range this binder should try to compute. The range is
* computed as number of items in the viewport (when the binder is measured) multiplied by the
* range ratio. The ratio is to be intended in both directions. For example a ratio of 1 means
* that if there are currently N components on screen, the binder should try to compute the
* layout for the N components before the first component on screen and for the N components
* after the last component on screen. If not set, defaults to 4f.
*/
public Builder rangeRatio(float rangeRatio) {
this.rangeRatio = rangeRatio;
return this;
}
/**
* @param layoutInfo an implementation of {@link LayoutInfo} that will expose information about
* the {@link LayoutManager} this RecyclerBinder will use. If not set, it will default to a
* vertical list.
*/
public Builder layoutInfo(LayoutInfo layoutInfo) {
this.layoutInfo = layoutInfo;
return this;
}
/**
* @param layoutHandlerFactory the RecyclerBinder will use this layoutHandlerFactory when
* creating {@link ComponentTree}s in order to specify on which thread layout calculation
* should happen.
*/
public Builder layoutHandlerFactory(LayoutHandlerFactory layoutHandlerFactory) {
this.layoutHandlerFactory = layoutHandlerFactory;
return this;
}
public Builder lithoViewFactory(LithoViewFactory lithoViewFactory) {
this.lithoViewFactory = lithoViewFactory;
return this;
}
public Builder canPrefetchDisplayLists(boolean canPrefetchDisplayLists) {
this.canPrefetchDisplayLists = canPrefetchDisplayLists;
return this;
}
public Builder canCacheDrawingDisplayLists(boolean canCacheDrawingDisplayLists) {
this.canCacheDrawingDisplayLists = canCacheDrawingDisplayLists;
return this;
}
/**
* Whether the underlying RecyclerBinder will have a circular behaviour. Defaults to false.
* Note: circular lists DO NOT support any operation that changes the size of items like insert,
* remove, insert range, remove range
*/
public Builder isCircular(boolean isCircular) {
this.isCircular = isCircular;
return this;
}
/**
* If true, the underlying RecyclerBinder will measure the parent height by the height of
* children if the orientation is vertical, or measure the parent width by the width of children
* if the orientation is horizontal.
*/
public Builder wrapContent(boolean wrapContent) {
this.wrapContent = wrapContent;
return this;
}
/**
* @param componentTreeHolderFactory Factory to acquire a new ComponentTreeHolder. Defaults to
* {@link #DEFAULT_COMPONENT_TREE_HOLDER_FACTORY}.
*/
public Builder componentTreeHolderFactory(
ComponentTreeHolderFactory componentTreeHolderFactory) {
this.componentTreeHolderFactory = componentTreeHolderFactory;
return this;
}
/**
* Do not enable this. This is an experimental feature and your Section surface will take a perf
* hit if you use it.
*
* <p>Whether the items of this RecyclerBinder can change height after the initial measure. Only
* applicable to horizontally scrolling RecyclerBinders. If true, the children of this h-scroll
* are all measured with unspecified height. When the ComponentTree of a child is remeasured,
* this will cause the RecyclerBinder to remeasure in case the height of the child changed and
* the RecyclerView needs to have a different height to account for it. This only supports
* changing the height of the item that triggered the remeasuring, not the height of all items
* in the h-scroll.
*/
public Builder hasDynamicItemHeight(boolean hasDynamicItemHeight) {
this.hasDynamicItemHeight = hasDynamicItemHeight;
return this;
}
/**
* Enable setting custom viewTypes on {@link ViewRenderInfo}s.
*
* <p>After this is set, all {@link ViewRenderInfo}s must be built with a custom viewType
* through {@link ViewRenderInfo.Builder#customViewType(int)}, otherwise exception will be
* thrown.
*
* @param componentViewType the viewType to be used for Component types, provided through {@link
* ComponentRenderInfo}. Set this to a value that won't conflict with your custom viewTypes.
*/
public Builder enableCustomViewType(int componentViewType) {
this.customViewTypeEnabled = true;
this.componentViewType = componentViewType;
return this;
}
/**
* Method for tests to allow mocking of the InternalAdapter to verify interaction with the
* RecyclerView.
*/
@VisibleForTesting
Builder overrideInternalAdapter(RecyclerView.Adapter overrideInternalAdapter) {
this.overrideInternalAdapter = overrideInternalAdapter;
return this;
}
public Builder splitLayoutTag(String splitLayoutTag) {
this.splitLayoutTag = splitLayoutTag;
return this;
}
/** @param c The {@link ComponentContext} the RecyclerBinder will use. */
public RecyclerBinder build(ComponentContext c) {
componentContext = new ComponentContext(c);
if (layoutInfo == null) {
layoutInfo = new LinearLayoutInfo(c, VERTICAL, false);
}
return new RecyclerBinder(this);
}
}
@Override
public boolean isWrapContent() {
return mWrapContent;
}
@UiThread
public void notifyItemRenderCompleteAt(int position, final long timestampMillis) {
final ComponentTreeHolder holder = mComponentTreeHolders.get(position);
final EventHandler<RenderCompleteEvent> renderCompleteEventHandler =
holder.getRenderInfo().getRenderCompleteEventHandler();
if (renderCompleteEventHandler == null) {
return;
}
final @RenderState int state = holder.getRenderState();
if (state == ComponentTreeHolder.RENDER_DRAWN) {
return;
}
// Dispatch a RenderCompleteEvent asynchronously.
ViewCompat.postOnAnimation(
mMountedView,
new RenderCompleteRunnable(renderCompleteEventHandler, true, timestampMillis));
// Update the state to prevent dispatch an event again for the same holder.
holder.setRenderState(ComponentTreeHolder.RENDER_DRAWN);
}
@UiThread
private static void dispatchRenderCompleteEvent(
EventHandler<RenderCompleteEvent> renderCompleteEventHandler,
boolean hasMounted,
long timestampMillis) {
ThreadUtils.assertMainThread();
final RenderCompleteEvent event = new RenderCompleteEvent();
event.hasMounted = hasMounted;
event.timestampMillis = timestampMillis;
renderCompleteEventHandler.dispatchEvent(event);
}
private RecyclerBinder(Builder builder) {
mComponentContext = builder.componentContext;
mComponentTreeHolderFactory = builder.componentTreeHolderFactory;
mInternalAdapter =
builder.overrideInternalAdapter != null
? builder.overrideInternalAdapter
: new InternalAdapter();
mRangeRatio = builder.rangeRatio;
mLayoutInfo = builder.layoutInfo;
mLayoutHandlerFactory = builder.layoutHandlerFactory;
mLithoViewFactory = builder.lithoViewFactory;
mCanPrefetchDisplayLists = builder.canPrefetchDisplayLists;
mCanCacheDrawingDisplayLists = builder.canCacheDrawingDisplayLists;
mRenderInfoViewCreatorController =
new RenderInfoViewCreatorController(
builder.customViewTypeEnabled,
builder.customViewTypeEnabled
? builder.componentViewType
: DEFAULT_COMPONENT_VIEW_TYPE);
mIsCircular = builder.isCircular;
mHasDynamicItemHeight =
mLayoutInfo.getScrollDirection() == HORIZONTAL ? builder.hasDynamicItemHeight : false;
mWrapContent = builder.wrapContent;
mViewportManager =
new ViewportManager(
mCurrentFirstVisiblePosition, mCurrentLastVisiblePosition, builder.layoutInfo);
mSplitLayoutTag = builder.splitLayoutTag;
}
/**
* Update the item at index position. The {@link RecyclerView} will only be notified of the item
* being updated after a layout calculation has been completed for the new {@link Component}.
*/
@UiThread
public final void updateItemAtAsync(int position, RenderInfo renderInfo) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(SectionsDebug.TAG, "(" + hashCode() + ") updateItemAtAsync " + position);
}
updateItemAtAsyncInner(position, renderInfo);
}
/**
* Update the items starting from the given index position. The {@link RecyclerView} will only be
* notified of the item being updated after a layout calculation has been completed for the new
* {@link Component}.
*/
@UiThread
public final void updateRangeAtAsync(int position, List<RenderInfo> renderInfos) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG,
"(" + hashCode() + ") updateRangeAtAsync " + position + ", count: " + renderInfos.size());
}
for (int i = 0, size = renderInfos.size(); i < size; i++) {
updateItemAtAsyncInner(position + i, renderInfos.get(i));
}
}
@UiThread
private void updateItemAtAsyncInner(int position, RenderInfo renderInfo) {
final ComponentTreeHolder holder;
final boolean renderInfoWasView;
final int indexInComponentTreeHolders;
synchronized (this) {
holder = mAsyncComponentTreeHolders.get(position);
renderInfoWasView = holder.getRenderInfo().rendersView();
mRenderInfoViewCreatorController.maybeTrackViewCreator(renderInfo);
holder.setRenderInfo(renderInfo);
if (holder.isInserted()) {
// If it's inserted, we can just count on the normal range computation re-computing this
indexInComponentTreeHolders = mComponentTreeHolders.indexOf(holder);
mViewportManager.setShouldUpdate(
mViewportManager.updateAffectsVisibleRange(indexInComponentTreeHolders, 1));
} else {
indexInComponentTreeHolders = -1;
// TODO(T28668712): Handle updates outside of range
computeLayoutAsync(holder);
}
}
if (indexInComponentTreeHolders >= 0
&& (renderInfoWasView || holder.getRenderInfo().rendersView())) {
mInternalAdapter.notifyItemChanged(indexInComponentTreeHolders);
}
}
/**
* Inserts an item at position. The {@link RecyclerView} will only be notified of the item being
* inserted after a layout calculation has been completed for the new {@link Component}.
*/
@UiThread
public final void insertItemAtAsync(int position, RenderInfo renderInfo) {
ThreadUtils.assertMainThread();
assertNoInsertOperationIfCircular();
final AsyncInsertOperation operation = createAsyncInsertOperation(position, renderInfo);
synchronized (this) {
mHasAsyncOperations = true;
mAsyncComponentTreeHolders.add(position, operation.mHolder);
// If the binder has not been measured yet, we will compute an initial page of content based
// on the measured size of this RecyclerBinder synchronously during measure, and the rest will
// be kicked off as async inserts.
if (mAsyncInsertsShouldWaitForMeasure) {
registerAsyncInsertBeforeInitialMeasure(operation);
} else {
registerAsyncInsert(operation);
}
}
}
/**
* Inserts the new items starting from position. The {@link RecyclerView} will only be notified of
* the items being inserted after a layout calculation has been completed for the new {@link
* Component}s. There is not a guarantee that the {@link RecyclerView} will be notified about all
* the items in the range at the same time.
*/
@UiThread
public final void insertRangeAtAsync(int position, List<RenderInfo> renderInfos) {
ThreadUtils.assertMainThread();
assertNoInsertOperationIfCircular();
synchronized (this) {
mHasAsyncOperations = true;
for (int i = 0, size = renderInfos.size(); i < size; i++) {
final AsyncInsertOperation operation =
createAsyncInsertOperation(position + i, renderInfos.get(i));
mAsyncComponentTreeHolders.add(position + i, operation.mHolder);
// If the binder has not been measured yet, we will compute an initial page of content based
// on the measured size of this RecyclerBinder synchronously during measure, and the rest
// will be kicked off as async inserts.
if (mAsyncInsertsShouldWaitForMeasure) {
registerAsyncInsertBeforeInitialMeasure(operation);
} else {
registerAsyncInsert(operation);
}
}
}
}
@UiThread
private void applyReadyBatches() {
ThreadUtils.assertMainThread();
synchronized (this) {
boolean appliedBatch = false;
while (!mAsyncBatches.isEmpty()) {
final AsyncBatch batch = mAsyncBatches.peekFirst();
if (!isBatchReady(batch)) {
break;
}
mAsyncBatches.pollFirst();
applyBatch(batch);
appliedBatch = true;
}
if (appliedBatch) {
maybeUpdateRangeOrRemeasureForMutation();
}
}
}
private static boolean isBatchReady(AsyncBatch batch) {
for (int i = 0, size = batch.mOperations.size(); i < size; i++) {
final AsyncOperation operation = batch.mOperations.get(i);
if (operation instanceof AsyncInsertOperation
&& !((AsyncInsertOperation) operation).mHolder.hasCompletedLatestLayout()) {
return false;
}
}
return true;
}
@GuardedBy("this")
@UiThread
private void applyBatch(AsyncBatch batch) {
for (int i = 0, size = batch.mOperations.size(); i < size; i++) {
final AsyncOperation operation = batch.mOperations.get(i);
switch (operation.mOperation) {
case Operation.INSERT:
applyAsyncInsert((AsyncInsertOperation) operation);
break;
case Operation.REMOVE:
removeItemAt(((AsyncRemoveOperation) operation).mPosition);
break;
case Operation.REMOVE_RANGE:
final AsyncRemoveRangeOperation removeRangeOperation =
(AsyncRemoveRangeOperation) operation;
removeRangeAt(removeRangeOperation.mPosition, removeRangeOperation.mCount);
break;
case Operation.MOVE:
final AsyncMoveOperation moveOperation = (AsyncMoveOperation) operation;
moveItem(moveOperation.mFromPosition, moveOperation.mToPosition);
break;
default:
throw new RuntimeException("Unhandled operation type: " + operation.mOperation);
}
}
batch.mOnDataBoundListener.onDataBound();
}
@GuardedBy("this")
@UiThread
private void applyAsyncInsert(AsyncInsertOperation operation) {
if (operation.mHolder.isInserted()) {
return;
}
mComponentTreeHolders.add(operation.mPosition, operation.mHolder);
operation.mHolder.setInserted(true);
mInternalAdapter.notifyItemInserted(operation.mPosition);
mViewportManager.insertAffectsVisibleRange(
operation.mPosition, 1, mRange != null ? mRange.estimatedViewportCount : -1);
}
@GuardedBy("this")
private void registerAsyncInsert(AsyncInsertOperation operation) {
addToCurrentBatch(operation);
startAsyncLayout(operation);
}
@GuardedBy("this")
private void registerAsyncInsertBeforeInitialMeasure(AsyncInsertOperation operation) {
mInsertsWaitingForInitialMeasure.add(operation.mPosition, operation);
addToCurrentBatch(operation);
}
private void startAsyncLayout(AsyncInsertOperation operation) {
final ComponentTreeHolder holder = operation.mHolder;
holder.setNewLayoutReadyListener(mAsyncLayoutReadyListener);
holder.computeLayoutAsync(
mComponentContext, getActualChildrenWidthSpec(holder), getActualChildrenHeightSpec(holder));
}
/**
* Moves an item from fromPosition to toPostion. If there are other pending operations on this
* binder this will only be executed when all the operations have been completed (to ensure index
* consistency).
*/
@UiThread
public final void moveItemAsync(int fromPosition, int toPosition) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG,
"(" + hashCode() + ") moveItemAsync " + fromPosition + " to " + toPosition);
}
final AsyncMoveOperation operation = new AsyncMoveOperation(fromPosition, toPosition);
synchronized (this) {
mHasAsyncOperations = true;
mAsyncComponentTreeHolders.add(toPosition, mAsyncComponentTreeHolders.remove(fromPosition));
// TODO(t28619782): When moving a CT into range, do an async prepare
addToCurrentBatch(operation);
}
}
/**
* Removes an item from position. If there are other pending operations on this binder this will
* only be executed when all the operations have been completed (to ensure index consistency).
*/
@UiThread
public final void removeItemAtAsync(int position) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(SectionsDebug.TAG, "(" + hashCode() + ") removeItemAtAsync " + position);
}
final AsyncRemoveOperation asyncRemoveOperation = new AsyncRemoveOperation(position);
synchronized (this) {
mHasAsyncOperations = true;
mAsyncComponentTreeHolders.remove(position);
addToCurrentBatch(asyncRemoveOperation);
}
}
/**
* Removes count items starting from position. If there are other pending operations on this
* binder this will only be executed when all the operations have been completed (to ensure index
* consistency).
*/
@UiThread
public final void removeRangeAtAsync(int position, int count) {
ThreadUtils.assertMainThread();
assertNoRemoveOperationIfCircular(count);
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG,
"(" + hashCode() + ") removeRangeAtAsync " + position + ", size: " + count);
}
final AsyncRemoveRangeOperation operation = new AsyncRemoveRangeOperation(position, count);
synchronized (this) {
mHasAsyncOperations = true;
for (int i = 0; i < count; i++) {
// TODO(t28712163): Cancel pending layouts for async inserts
mAsyncComponentTreeHolders.remove(position);
}
addToCurrentBatch(operation);
}
}
/** Removes all items in this binder async. */
@UiThread
public final void clearAsync() {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(SectionsDebug.TAG, "(" + hashCode() + ") clear");
}
synchronized (this) {
mHasAsyncOperations = true;
final int count = mAsyncComponentTreeHolders.size();
// TODO(t28712163): Cancel pending layouts for async inserts
mAsyncComponentTreeHolders.clear();
final AsyncRemoveRangeOperation operation = new AsyncRemoveRangeOperation(0, count);
addToCurrentBatch(operation);
}
}
@GuardedBy("this")
private void addToCurrentBatch(AsyncOperation operation) {
if (mCurrentBatch == null) {
mCurrentBatch = new AsyncBatch();
}
mCurrentBatch.mOperations.add(operation);
}
/**
* See {@link RecyclerBinder#appendItem(RenderInfo)}.
*/
@UiThread
public final void appendItem(Component component) {
insertItemAt(getItemCount(), component);
}
/**
* Inserts a new item at tail. The {@link RecyclerView} gets notified immediately about the
* new item being inserted. If the item's position falls within the currently visible range, the
* layout is immediately computed on the] UiThread.
* The RenderInfo contains the component that will be inserted in the Binder and extra info
* like isSticky or spanCount.
*/
@UiThread
public final void appendItem(RenderInfo renderInfo) {
insertItemAt(getItemCount(), renderInfo);
}
/**
* See {@link RecyclerBinder#insertItemAt(int, RenderInfo)}.
*/
@UiThread
public final void insertItemAt(int position, Component component) {
insertItemAt(position, ComponentRenderInfo.create().component(component).build());
}
/**
* Inserts a new item at position. The {@link RecyclerView} gets notified immediately about the
* new item being inserted. If the item's position falls within the currently visible range, the
* layout is immediately computed on the] UiThread. The RenderInfo contains the component that
* will be inserted in the Binder and extra info like isSticky or spanCount.
*/
@UiThread
public final void insertItemAt(int position, RenderInfo renderInfo) {
ThreadUtils.assertMainThread();
assertNoInsertOperationIfCircular();
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG,
"(" + hashCode() + ") insertItemAt " + position + ", name: " + renderInfo.getName());
}
final ComponentTreeHolder holder = createComponentTreeHolder(renderInfo);
synchronized (this) {
if (mHasAsyncOperations) {
throw new RuntimeException("Trying to do a sync insert when using asynchronous mutations!");
}
mComponentTreeHolders.add(position, holder);
mRenderInfoViewCreatorController.maybeTrackViewCreator(renderInfo);
}
mInternalAdapter.notifyItemInserted(position);
mViewportManager.setShouldUpdate(
mViewportManager.insertAffectsVisibleRange(
position, 1, mRange != null ? mRange.estimatedViewportCount : -1));
}
private void requestRemeasure() {
if (SectionsDebug.ENABLED) {
Log.d(SectionsDebug.TAG, "(" + hashCode() + ") requestRemeasure");
}
if (mMountedView != null) {
mMainThreadHandler.removeCallbacks(mRemeasureRunnable);
mMountedView.removeCallbacks(mRemeasureRunnable);
ViewCompat.postOnAnimation(mMountedView, mRemeasureRunnable);
} else {
// We are not mounted but we still need to post this. Just post on the main thread.
mMainThreadHandler.removeCallbacks(mRemeasureRunnable);
mMainThreadHandler.post(mRemeasureRunnable);
}
}
/**
* Inserts the new items starting from position. The {@link RecyclerView} gets notified
* immediately about the new item being inserted. The RenderInfo contains the component that will
* be inserted in the Binder and extra info like isSticky or spanCount.
*/
@UiThread
public final void insertRangeAt(int position, List<RenderInfo> renderInfos) {
ThreadUtils.assertMainThread();
assertNoInsertOperationIfCircular();
if (SectionsDebug.ENABLED) {
final String[] names = new String[renderInfos.size()];
for (int i = 0; i < renderInfos.size(); i++) {
names[i] = renderInfos.get(i).getName();
}
Log.d(
SectionsDebug.TAG,
"("
+ hashCode()
+ ") insertRangeAt "
+ position
+ ", size: "
+ renderInfos.size()
+ ", names: "
+ Arrays.toString(names));
}
for (int i = 0, size = renderInfos.size(); i < size; i++) {
synchronized (this) {
final RenderInfo renderInfo = renderInfos.get(i);
final ComponentTreeHolder holder = createComponentTreeHolder(renderInfo);
if (mHasAsyncOperations) {
throw new RuntimeException(
"Trying to do a sync insert when using asynchronous mutations!");
}
mComponentTreeHolders.add(position + i, holder);
mRenderInfoViewCreatorController.maybeTrackViewCreator(renderInfo);
}
}
mInternalAdapter.notifyItemRangeInserted(position, renderInfos.size());
mViewportManager.setShouldUpdate(
mViewportManager.insertAffectsVisibleRange(
position, renderInfos.size(), mRange != null ? mRange.estimatedViewportCount : -1));
}
/**
* See {@link RecyclerBinder#updateItemAt(int, Component)}.
*/
@UiThread
public final void updateItemAt(int position, Component component) {
updateItemAt(position, ComponentRenderInfo.create().component(component).build());
}
/**
* Updates the item at position. The {@link RecyclerView} gets notified immediately about the item
* being updated. If the item's position falls within the currently visible range, the layout is
* immediately computed on the UiThread.
*/
@UiThread
public final void updateItemAt(int position, RenderInfo renderInfo) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG,
"(" + hashCode() + ") updateItemAt " + position + ", name: " + renderInfo.getName());
}
final ComponentTreeHolder holder;
final boolean renderInfoWasView;
synchronized (this) {
holder = mComponentTreeHolders.get(position);
renderInfoWasView = holder.getRenderInfo().rendersView();
mRenderInfoViewCreatorController.maybeTrackViewCreator(renderInfo);
holder.setRenderInfo(renderInfo);
}
// If this item is rendered with a view (or was rendered with a view before now) we need to
// notify the RecyclerView's adapter that something changed.
if (renderInfoWasView || renderInfo.rendersView()) {
mInternalAdapter.notifyItemChanged(position);
}
mViewportManager.setShouldUpdate(mViewportManager.updateAffectsVisibleRange(position, 1));
}
/**
* Updates the range of items starting at position. The {@link RecyclerView} gets notified
* immediately about the item being updated.
*/
@UiThread
public final void updateRangeAt(int position, List<RenderInfo> renderInfos) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
final String[] names = new String[renderInfos.size()];
for (int i = 0; i < renderInfos.size(); i++) {
names[i] = renderInfos.get(i).getName();
}
Log.d(
SectionsDebug.TAG,
"("
+ hashCode()
+ ") updateRangeAt "
+ position
+ ", size: "
+ renderInfos.size()
+ ", names: "
+ Arrays.toString(names));
}
for (int i = 0, size = renderInfos.size(); i < size; i++) {
synchronized (this) {
final ComponentTreeHolder holder = mComponentTreeHolders.get(position + i);
final RenderInfo newRenderInfo = renderInfos.get(i);
// If this item is rendered with a view (or was rendered with a view before now) we still
// need to notify the RecyclerView's adapter that something changed.
if (newRenderInfo.rendersView() || holder.getRenderInfo().rendersView()) {
mInternalAdapter.notifyItemChanged(position + i);
}
mRenderInfoViewCreatorController.maybeTrackViewCreator(newRenderInfo);
holder.setRenderInfo(newRenderInfo);
}
}
mViewportManager.setShouldUpdate(
mViewportManager.updateAffectsVisibleRange(position, renderInfos.size()));
}
/**
* Moves an item from fromPosition to toPosition. If the new position of the item is within the
* currently visible range, a layout is calculated immediately on the UI Thread.
*/
@UiThread
public final void moveItem(int fromPosition, int toPosition) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG, "(" + hashCode() + ") moveItem " + fromPosition + " to " + toPosition);
}
final ComponentTreeHolder holder;
final boolean isNewPositionInRange;
final int mRangeSize = mRange != null ? mRange.estimatedViewportCount : -1;
synchronized (this) {
holder = mComponentTreeHolders.remove(fromPosition);
mComponentTreeHolders.add(toPosition, holder);
isNewPositionInRange = mRangeSize > 0 &&
toPosition >= mCurrentFirstVisiblePosition - (mRangeSize * mRangeRatio) &&
toPosition <= mCurrentFirstVisiblePosition + mRangeSize + (mRangeSize * mRangeRatio);
}
final boolean isTreeValid = holder.isTreeValid();
if (isTreeValid && !isNewPositionInRange) {
holder.acquireStateAndReleaseTree();
}
mInternalAdapter.notifyItemMoved(fromPosition, toPosition);
mViewportManager.setShouldUpdate(
mViewportManager.moveAffectsVisibleRange(fromPosition, toPosition, mRangeSize));
}
/**
* Removes an item from index position.
*/
@UiThread
public final void removeItemAt(int position) {
ThreadUtils.assertMainThread();
assertNoRemoveOperationIfCircular(1);
if (SectionsDebug.ENABLED) {
Log.d(SectionsDebug.TAG, "(" + hashCode() + ") removeItemAt " + position);
}
final ComponentTreeHolder holder;
synchronized (this) {
holder = mComponentTreeHolders.remove(position);
}
mInternalAdapter.notifyItemRemoved(position);
holder.release();
mViewportManager.setShouldUpdate(mViewportManager.removeAffectsVisibleRange(position, 1));
}
/**
* Removes count items starting from position.
*/
@UiThread
public final void removeRangeAt(int position, int count) {
ThreadUtils.assertMainThread();
assertNoRemoveOperationIfCircular(count);
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG, "(" + hashCode() + ") removeRangeAt " + position + ", size: " + count);
}
synchronized (this) {
for (int i = 0; i < count; i++) {
final ComponentTreeHolder holder = mComponentTreeHolders.remove(position);
holder.release();
}
}
mInternalAdapter.notifyItemRangeRemoved(position, count);
mViewportManager.setShouldUpdate(mViewportManager.removeAffectsVisibleRange(position, count));
}
/**
* Called after all the change set operations (inserts, removes, etc.) in a batch have completed.
*/
@UiThread
public void notifyChangeSetComplete(OnDataBoundListener onDataBoundListener) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(SectionsDebug.TAG, "(" + hashCode() + ") notifyChangeSetComplete");
}
if (!mHasAsyncOperations) {
onDataBoundListener.onDataBound();
} else {
closeCurrentBatch(onDataBoundListener);
applyReadyBatches();
}
maybeUpdateRangeOrRemeasureForMutation();
}
private synchronized void closeCurrentBatch(OnDataBoundListener onDataBoundListener) {
if (mCurrentBatch == null) {
// We create a batch here even if it doesn't have any operations: this is so we can still
// invoke the OnDataBoundListener at the appropriate time (after all preceding batches
// complete)
mCurrentBatch = new AsyncBatch();
}
mCurrentBatch.mOnDataBoundListener = onDataBoundListener;
mAsyncBatches.addLast(mCurrentBatch);
mCurrentBatch = null;
}
private synchronized void maybeUpdateRangeOrRemeasureForMutation() {
synchronized (this) {
if (!mIsMeasured.get()) {
return;
}
if (mRequiresRemeasure.get()) {
requestRemeasure();
return;
}
if (mRange == null) {
int firstComponent = findFirstComponentPosition(mComponentTreeHolders);
if (firstComponent >= 0) {
final ComponentTreeHolder holder = mComponentTreeHolders.get(firstComponent);
initRange(
mMeasuredSize.width,
mMeasuredSize.height,
holder,
getActualChildrenWidthSpec(holder),
getActualChildrenHeightSpec(holder),
mLayoutInfo.getScrollDirection());
if (!mHasFilledViewport && shouldFillListViewport()) {
if (SectionsDebug.ENABLED) {
Log.d(SectionsDebug.TAG, "(" + hashCode() + ") filling viewport for mutation");
}
fillListViewport(mMeasuredSize.width, mMeasuredSize.height, null);
}
}
}
}
maybePostUpdateViewportAndComputeRange();
}
/**
* Returns the {@link ComponentTree} for the item at index position. TODO 16212132 remove
* getComponentAt from binder
*/
@Nullable
@Override
public final synchronized ComponentTree getComponentAt(int position) {
return mComponentTreeHolders.get(position).getComponentTree();
}
@Override
public final synchronized ComponentTree getComponentForStickyHeaderAt(int position) {
final ComponentTreeHolder holder = mComponentTreeHolders.get(position);
if (holder.isTreeValid()) {
return holder.getComponentTree();
}
// This could happen when RecyclerView is populated with new data, and first position is not 0.
// It is possible that sticky header is above the first visible position and also it is outside
// calculated range and its layout has not been calculated yet.
final int childrenWidthSpec = getActualChildrenWidthSpec(holder);
final int childrenHeightSpec = getActualChildrenHeightSpec(holder);
holder.computeLayoutSync(mComponentContext, childrenWidthSpec, childrenHeightSpec, null);
return holder.getComponentTree();
}
@Override
public final synchronized RenderInfo getRenderInfoAt(int position) {
return mComponentTreeHolders.get(position).getRenderInfo();
}
@VisibleForTesting
final synchronized ComponentTreeHolder getComponentTreeHolderAt(int position) {
return mComponentTreeHolders.get(position);
}
@Override
public void bind(RecyclerView view) {
// Nothing to do here.
}
@Override
public void unbind(RecyclerView view) {
// Nothing to do here.
}
/**
* A component mounting a RecyclerView can use this method to determine its size. A Recycler that
* scrolls horizontally will leave the width unconstrained and will measure its children with a
* sizeSpec for the height matching the heightSpec passed to this method.
*
* If padding is defined on the parent component it should be subtracted from the parent size
* specs before passing them to this method.
*
* Currently we can't support the equivalent of MATCH_PARENT on the scrollDirection (so for
* example we don't support MATCH_PARENT on width in an horizontal RecyclerView). This is mainly
* because we don't have the equivalent of LayoutParams in components. We can extend the api of
* the binder in the future to provide some more layout hints in order to support this.
*
* @param outSize will be populated with the measured dimensions for this Binder.
* @param widthSpec the widthSpec to be used to measure the RecyclerView.
* @param heightSpec the heightSpec to be used to measure the RecyclerView.
* @param reMeasureEventHandler the EventHandler to invoke in order to trigger a re-measure.
*/
@Override
public synchronized void measure(
Size outSize,
int widthSpec,
int heightSpec,
@Nullable EventHandler<ReMeasureEvent> reMeasureEventHandler) {
final int scrollDirection = mLayoutInfo.getScrollDirection();
switch (scrollDirection) {
case HORIZONTAL:
if (SizeSpec.getMode(widthSpec) == SizeSpec.UNSPECIFIED) {
throw new IllegalStateException(
"Width mode has to be EXACTLY OR AT MOST for an horizontal scrolling RecyclerView");
}
break;
case VERTICAL:
if (SizeSpec.getMode(heightSpec) == SizeSpec.UNSPECIFIED) {
throw new IllegalStateException(
"Height mode has to be EXACTLY OR AT MOST for a vertical scrolling RecyclerView");
}
break;
default:
throw new UnsupportedOperationException(
"The orientation defined by LayoutInfo should be" +
" either OrientationHelper.HORIZONTAL or OrientationHelper.VERTICAL");
}
if (mLastWidthSpec != UNINITIALIZED && !mRequiresRemeasure.get()) {
switch (scrollDirection) {
case VERTICAL:
if (MeasureComparisonUtils.isMeasureSpecCompatible(
mLastWidthSpec,
widthSpec,
mMeasuredSize.width)) {
outSize.width = mMeasuredSize.width;
outSize.height = mWrapContent ? mMeasuredSize.height : SizeSpec.getSize(heightSpec);
return;
}
break;
default:
if (MeasureComparisonUtils.isMeasureSpecCompatible(
mLastHeightSpec,
heightSpec,
mMeasuredSize.height)) {
outSize.width = mWrapContent ? mMeasuredSize.width : SizeSpec.getSize(widthSpec);
outSize.height = mMeasuredSize.height;
return;
}
}
mIsMeasured.set(false);
invalidateLayoutData();
}
// We have never measured before or the measures are not valid so we need to measure now.
mLastWidthSpec = widthSpec;
mLastHeightSpec = heightSpec;
if (!mInsertsWaitingForInitialMeasure.isEmpty() && !mComponentTreeHolders.isEmpty()) {
throw new IllegalStateException(
"One of InsertsWaitingForInitialMeasure or ComponentTreeHolders should be empty!");
}
// We now need to compute the size of the non scrolling side. We try to do this by using the
// calculated range (if we have one) or computing one.
boolean doFillViewportAfterFinishingMeasure = false;
if (mRange == null) {
ComponentTreeHolder holderForRange = null;
if (!mComponentTreeHolders.isEmpty()) {
final int positionToComputeLayout = findFirstComponentPosition(mComponentTreeHolders);
if (mCurrentFirstVisiblePosition < mComponentTreeHolders.size()
&& positionToComputeLayout >= 0) {
holderForRange = mComponentTreeHolders.get(positionToComputeLayout);
}
} else if (!mInsertsWaitingForInitialMeasure.isEmpty()) {
final int positionToComputeLayout =
findFirstAsyncComponentInsert(mInsertsWaitingForInitialMeasure);
if (positionToComputeLayout >= 0) {
holderForRange = mInsertsWaitingForInitialMeasure.get(positionToComputeLayout).mHolder;
}
}
if (holderForRange != null) {
initRange(
SizeSpec.getSize(widthSpec),
SizeSpec.getSize(heightSpec),
holderForRange,
getActualChildrenWidthSpec(holderForRange),
getActualChildrenHeightSpec(holderForRange),
scrollDirection);
doFillViewportAfterFinishingMeasure = true;
}
}
// At this point we might still not have a range. In this situation we should return the best
// size we can detect from the size spec and update it when the first item comes in.
final boolean canMeasure = reMeasureEventHandler != null;
final int measuredWidth;
final int measuredHeight;
switch (scrollDirection) {
case OrientationHelper.VERTICAL:
if (!canMeasure && SizeSpec.getMode(widthSpec) == SizeSpec.UNSPECIFIED) {
throw new IllegalStateException("Can't use Unspecified width on a vertical scrolling " +
"Recycler if dynamic measurement is not allowed");
}
measuredHeight = SizeSpec.getSize(heightSpec);
if (SizeSpec.getMode(widthSpec) == SizeSpec.EXACTLY || !canMeasure) {
measuredWidth = SizeSpec.getSize(widthSpec);
mReMeasureEventEventHandler = mWrapContent ? reMeasureEventHandler : null;
mRequiresRemeasure.set(mWrapContent);
mAsyncInsertsShouldWaitForMeasure = false;
} else if (mRange != null) {
measuredWidth = mRange.measuredSize;
mReMeasureEventEventHandler = mWrapContent ? reMeasureEventHandler : null;
mRequiresRemeasure.set(mWrapContent);
mAsyncInsertsShouldWaitForMeasure = false;
} else {
measuredWidth = 0;
mRequiresRemeasure.set(true);
mReMeasureEventEventHandler = reMeasureEventHandler;
}
break;
case OrientationHelper.HORIZONTAL:
default:
if (!canMeasure && SizeSpec.getMode(heightSpec) == SizeSpec.UNSPECIFIED) {
throw new IllegalStateException("Can't use Unspecified height on an horizontal " +
"scrolling Recycler if dynamic measurement is not allowed");
}
measuredWidth = SizeSpec.getSize(widthSpec);
if (SizeSpec.getMode(heightSpec) == SizeSpec.EXACTLY || !canMeasure) {
measuredHeight = SizeSpec.getSize(heightSpec);
mReMeasureEventEventHandler =
(mHasDynamicItemHeight || mWrapContent) ? reMeasureEventHandler : null;
mRequiresRemeasure.set(mHasDynamicItemHeight || mWrapContent);
mAsyncInsertsShouldWaitForMeasure = false;
} else if (mRange != null) {
measuredHeight = mRange.measuredSize;
mReMeasureEventEventHandler =
(mHasDynamicItemHeight || mWrapContent) ? reMeasureEventHandler : null;
mRequiresRemeasure.set(mHasDynamicItemHeight || mWrapContent);
mAsyncInsertsShouldWaitForMeasure = false;
} else {
measuredHeight = 0;
mRequiresRemeasure.set(true);
mReMeasureEventEventHandler = reMeasureEventHandler;
}
break;
}
final boolean fillListViewport =
doFillViewportAfterFinishingMeasure && !mHasFilledViewport && shouldFillListViewport();
final Size wrapSize = mWrapContent ? new Size() : null;
// If we were in a position to recompute range, we are also in a position to re-fill the
// viewport
if (doFillViewportAfterFinishingMeasure && !mInsertsWaitingForInitialMeasure.isEmpty()) {
fillAdapterWithInitialLayouts(measuredWidth, measuredHeight, wrapSize);
} else if (mWrapContent || fillListViewport) {
fillListViewport(measuredWidth, measuredHeight, wrapSize);
} else if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG,
"("
+ hashCode()
+ ") Not filling viewport from measure - requested: "
+ doFillViewportAfterFinishingMeasure
+ ", supported: "
+ shouldFillListViewport()
+ ", isMainThread: "
+ ThreadUtils.isMainThread());
}
outSize.width = mWrapContent ? wrapSize.width : measuredWidth;
outSize.height = mWrapContent ? wrapSize.height : measuredHeight;
mMeasuredSize = new Size(outSize.width, outSize.height);
mIsMeasured.set(true);
updateAsyncInsertOperations();
if (mRange != null) {
computeRange(mCurrentFirstVisiblePosition, mCurrentLastVisiblePosition);
}
}
private boolean shouldFillListViewport() {
return ComponentsConfiguration.fillListViewport
|| (ComponentsConfiguration.fillListViewportHScrollOnly
&& mLayoutInfo.getScrollDirection() == OrientationHelper.HORIZONTAL);
}
@GuardedBy("this")
private void fillListViewport(int maxWidth, int maxHeight, @Nullable Size outSize) {
ComponentsSystrace.beginSection("fillListViewport");
final int firstVisiblePosition = mLayoutInfo.findFirstVisibleItemPosition();
// NB: This does not handle 1) partially visible items 2) item decorations
final int startIndex =
firstVisiblePosition != RecyclerView.NO_POSITION ? firstVisiblePosition : 0;
computeLayoutsToFillListViewport(
mComponentTreeHolders, startIndex, maxWidth, maxHeight, outSize);
mHasFilledViewport = true;
ComponentsSystrace.endSection();
}
@GuardedBy("this")
private void fillAdapterWithInitialLayouts(int maxWidth, int maxHeight, @Nullable Size outSize) {
ComponentsSystrace.beginSection("fillAdapterWithInitialLayouts");
if (mComponentTreeHolders.size() > 0) {
throw new RuntimeException(
"Should only fill adapter with initial layouts when there are no existing items in adapter!");
}
if (mAsyncInsertsShouldWaitForMeasure) {
throw new IllegalStateException(
"mAsyncInsertsShouldWaitForMeasure must be false to ensure no other inserts are added to those waiting for measure.");
}
final int numInserts = mInsertsWaitingForInitialMeasure.size();
final ArrayList<ComponentTreeHolder> holdersForInsert = new ArrayList<>(numInserts);
for (int i = 0; i < numInserts; i++) {
holdersForInsert.add(mInsertsWaitingForInitialMeasure.get(i).mHolder);
}
final int numComputed =
computeLayoutsToFillListViewport(holdersForInsert, 0, maxWidth, maxHeight, outSize);
if (numComputed > 0) {
maybePostInsertInitialLayoutsIntoAdapter(holdersForInsert.subList(0, numComputed));
}
for (int i = numComputed; i < numInserts; i++) {
startAsyncLayout(mInsertsWaitingForInitialMeasure.get(i));
}
mInsertsWaitingForInitialMeasure.clear();
mHasFilledViewport = true;
ComponentsSystrace.endSection();
}
@GuardedBy("this")
private int computeLayoutsToFillListViewport(
List<ComponentTreeHolder> holders,
int offset,
int maxWidth,
int maxHeight,
@Nullable Size outputSize) {
final LayoutInfo.ViewportFiller filler = mLayoutInfo.createViewportFiller(maxWidth, maxHeight);
if (filler == null) {
return 0;
}
ComponentsSystrace.beginSection("computeLayoutsToFillListViewport");
final int widthSpec = SizeSpec.makeSizeSpec(maxWidth, SizeSpec.EXACTLY);
final int heightSpec = SizeSpec.makeSizeSpec(maxHeight, SizeSpec.EXACTLY);
final Size outSize = new Size();
int numInserted = 0;
int index = offset;
while (filler.wantsMore() && index < holders.size()) {
final ComponentTreeHolder holder = holders.get(index);
final RenderInfo renderInfo = holder.getRenderInfo();
// Bail as soon as we see a View since we can't tell what height it is and don't want to
// layout too much :(
if (renderInfo.rendersView()) {
break;
}
holder.computeLayoutSync(
mComponentContext,
mLayoutInfo.getChildWidthSpec(widthSpec, renderInfo),
mLayoutInfo.getChildHeightSpec(heightSpec, renderInfo),
outSize);
filler.add(renderInfo, outSize.width, outSize.height);
index++;
numInserted++;
}
if (outputSize != null) {
final int fill = filler.getFill();
if (mLayoutInfo.getScrollDirection() == VERTICAL) {
outputSize.width = maxWidth;
outputSize.height = Math.min(fill, maxHeight);
} else {
outputSize.width = Math.min(fill, maxWidth);
outputSize.height = maxHeight;
}
}
ComponentsSystrace.endSection();
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG,
"("
+ hashCode()
+ ") filled viewport with "
+ numInserted
+ " items (holder.size() = "
+ holders.size()
+ ")");
}
return numInserted;
}
private void maybePostInsertInitialLayoutsIntoAdapter(final List<ComponentTreeHolder> toInsert) {
if (ThreadUtils.isMainThread()) {
insertInitialLayoutsIntoAdapter(toInsert);
} else {
mMainThreadHandler.post(
new Runnable() {
@Override
public void run() {
insertInitialLayoutsIntoAdapter(toInsert);
}
});
}
}
private void insertInitialLayoutsIntoAdapter(List<ComponentTreeHolder> toInsert) {
ThreadUtils.assertMainThread();
synchronized (this) {
for (int i = 0, size = toInsert.size(); i < size; i++) {
final ComponentTreeHolder holder = toInsert.get(i);
holder.setInserted(true);
mComponentTreeHolders.add(i, holder);
mInternalAdapter.notifyItemInserted(i);
}
// Computing the initial layouts may have completed one or more batches - update and dispatch
// them
applyReadyBatches();
}
}
@GuardedBy("this")
private void updateAsyncInsertOperations() {
for (AsyncBatch batch : mAsyncBatches) {
updateBatch(batch);
}
if (mCurrentBatch != null) {
updateBatch(mCurrentBatch);
}
}
@GuardedBy("this")
private void updateBatch(AsyncBatch batch) {
for (AsyncOperation operation : batch.mOperations) {
if (!(operation instanceof AsyncInsertOperation)) {
continue;
}
final ComponentTreeHolder holder = ((AsyncInsertOperation) operation).mHolder;
computeLayoutAsync(holder);
}
}
@GuardedBy("this")
private void computeLayoutAsync(ComponentTreeHolder holder) {
// If there's an existing async layout that's compatible, this is a no-op. Otherwise, that
// computation will be canceled (if it hasn't started) and this new one will run.
final int widthSpec = getActualChildrenWidthSpec(holder);
final int heightSpec = getActualChildrenHeightSpec(holder);
holder.computeLayoutAsync(mComponentContext, widthSpec, heightSpec);
}
private static int findFirstComponentPosition(List<ComponentTreeHolder> holders) {
for (int i = 0, size = holders.size(); i < size; i++) {
if (holders.get(i).getRenderInfo().rendersComponent()) {
return i;
}
}
return -1;
}
private static int findFirstAsyncComponentInsert(List<AsyncInsertOperation> operations) {
for (int i = 0, size = operations.size(); i < size; i++) {
final AsyncInsertOperation operation = operations.get(i);
if (operation.mHolder.getRenderInfo().rendersComponent()) {
return i;
}
}
return -1;
}
/**
* Gets the number of items currently in the adapter attached to this binder (i.e. the number of
* items the underlying RecyclerView knows about).
*/
@Override
public int getItemCount() {
return mInternalAdapter.getItemCount();
}
/**
* Insert operation is not supported in case of circular recycler unless it is initial insert
* because the indexes universe gets messed.
*/
private void assertNoInsertOperationIfCircular() {
if (mIsCircular && !mComponentTreeHolders.isEmpty()) {
// Initialization of a list happens using insertRangeAt() or insertAt() operations,
// so skip this check when mComponentTreeHolders was not populated yet
throw new UnsupportedOperationException("Circular lists do not support insert operation");
}
}
/**
* Remove operation is not supported in case of circular recycler unless it's a removal if all
* items because indexes universe gets messed.
*/
@GuardedBy("this")
private void assertNoRemoveOperationIfCircular(int removeCount) {
if (mIsCircular
&& !mComponentTreeHolders.isEmpty()
&& mComponentTreeHolders.size() != removeCount) {
// Allow only removal of all elements in case on notifyDataSetChanged() call
throw new UnsupportedOperationException("Circular lists do not support insert operation");
}
}
@GuardedBy("this")
private void invalidateLayoutData() {
mRange = null;
for (int i = 0, size = mComponentTreeHolders.size(); i < size; i++) {
mComponentTreeHolders.get(i).invalidateTree();
}
// We need to call this as we want to make sure everything is re-bound since we need new sizes
// on all rows.
if (Looper.myLooper() == Looper.getMainLooper()) {
mInternalAdapter.notifyDataSetChanged();
} else {
mMainThreadHandler.removeCallbacks(mNotifyDatasetChangedRunnable);
mMainThreadHandler.post(mNotifyDatasetChangedRunnable);
}
}
/**
* If non-null logId is provided we will log invalid state of the LithoView like height being 0
* while non-0 value was expected and similar other invalid cases.
*/
@UiThread
public void setInvalidStateLogId(String logId) {
mInvalidStateLogId = logId;
}
@GuardedBy("this")
private void initRange(
int width,
int height,
ComponentTreeHolder holder,
int childrenWidthSpec,
int childrenHeightSpec,
int scrollDirection) {
ComponentsSystrace.beginSection("initRange");
try {
final Size size = new Size();
holder.computeLayoutSync(mComponentContext, childrenWidthSpec, childrenHeightSpec, size);
final int rangeSize =
Math.max(mLayoutInfo.approximateRangeSize(size.width, size.height, width, height), 1);
mRange = new RangeCalculationResult();
mRange.measuredSize = scrollDirection == HORIZONTAL ? size.height : size.width;
mRange.estimatedViewportCount = rangeSize;
} finally {
ComponentsSystrace.endSection();
}
}
@GuardedBy("this")
private void resetMeasuredSize(int width) {
// we will set a range anyway if it's null, no need to do this now.
if (mRange == null) {
return;
}
int maxHeight = 0;
for (int i = 0, size = mComponentTreeHolders.size(); i < size; i++) {
final ComponentTreeHolder holder = mComponentTreeHolders.get(i);
final int measuredItemHeight = holder.getMeasuredHeight();
if (measuredItemHeight > maxHeight) {
maxHeight = measuredItemHeight;
}
}
if (maxHeight == mRange.measuredSize) {
return;
}
final int rangeSize =
Math.max(
mLayoutInfo.approximateRangeSize(
SizeSpec.getSize(mLastWidthSpec),
SizeSpec.getSize(mLastHeightSpec),
width,
maxHeight),
1);
mRange.measuredSize = maxHeight;
mRange.estimatedViewportCount = rangeSize;
}
/**
* This should be called when the owner {@link Component}'s onBoundsDefined is called. It will
* inform the binder of the final measured size. The binder might decide to re-compute its
* children layouts if the measures provided here are not compatible with the ones receive in
* onMeasure.
*/
@Override
public synchronized void setSize(int width, int height) {
if (mLastWidthSpec == UNINITIALIZED || !isCompatibleSize(
SizeSpec.makeSizeSpec(width, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(height, SizeSpec.EXACTLY))) {
measure(
sDummySize,
SizeSpec.makeSizeSpec(width, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(height, SizeSpec.EXACTLY),
mReMeasureEventEventHandler);
}
}
/**
* Call from the owning {@link Component}'s onMount. This is where the adapter is assigned to the
* {@link RecyclerView}.
*
* @param view the {@link RecyclerView} being mounted.
*/
@UiThread
@Override
public void mount(RecyclerView view) {
ThreadUtils.assertMainThread();
if (mMountedView == view) {
return;
}
if (mMountedView != null) {
unmount(mMountedView);
}
mMountedView = view;
final LayoutManager layoutManager = mLayoutInfo.getLayoutManager();
view.setLayoutManager(layoutManager);
if (ComponentsConfiguration.enableSwapAdapter) {
view.swapAdapter(mInternalAdapter, false);
} else {
view.setAdapter(mInternalAdapter);
}
view.addOnScrollListener(mRangeScrollListener);
view.addOnScrollListener(mViewportManager.getScrollListener());
mLayoutInfo.setRenderInfoCollection(this);
mViewportManager.addViewportChangedListener(mViewportChangedListener);
if (mCurrentFirstVisiblePosition != RecyclerView.NO_POSITION &&
mCurrentFirstVisiblePosition >= 0) {
if (layoutManager instanceof LinearLayoutManager) {
((LinearLayoutManager) layoutManager)
.scrollToPositionWithOffset(mCurrentFirstVisiblePosition, mCurrentOffset);
} else {
view.scrollToPosition(mCurrentFirstVisiblePosition);
}
} else if (mIsCircular) {
// Initialize circular RecyclerView position
final int jumpToMiddle = Integer.MAX_VALUE / 2;
final int offsetFirstItem =
mComponentTreeHolders.isEmpty() ? 0 : jumpToMiddle % mComponentTreeHolders.size();
view.scrollToPosition(jumpToMiddle - offsetFirstItem);
}
enableStickyHeader(mMountedView);
}
private void enableStickyHeader(RecyclerView recyclerView) {
if (mIsCircular) {
Log.w(TAG, "Sticky header is not supported for circular RecyclerViews");
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// Sticky header needs view translation APIs which are not available in Gingerbread and below.
Log.w(TAG, "Sticky header is supported only on ICS (API14) and above");
return;
}
if (recyclerView == null) {
return;
}
SectionsRecyclerView sectionsRecycler = SectionsRecyclerView.getParentRecycler(recyclerView);
if (sectionsRecycler == null) {
return;
}
if (mStickyHeaderController == null) {
mStickyHeaderController = new StickyHeaderController(this);
}
mStickyHeaderController.init(sectionsRecycler);
}
/**
* Call from the owning {@link Component}'s onUnmount. This is where the adapter is removed from
* the {@link RecyclerView}.
*
* @param view the {@link RecyclerView} being unmounted.
*/
@UiThread
@Override
public void unmount(RecyclerView view) {
ThreadUtils.assertMainThread();
final LayoutManager layoutManager = mLayoutInfo.getLayoutManager();
final View firstView = layoutManager.findViewByPosition(mCurrentFirstVisiblePosition);
if (firstView != null) {
final boolean reverseLayout;
if (layoutManager instanceof LinearLayoutManager) {
reverseLayout = ((LinearLayoutManager) layoutManager).getReverseLayout();
} else {
reverseLayout = false;
}
if (mLayoutInfo.getScrollDirection() == HORIZONTAL) {
mCurrentOffset =
reverseLayout
? view.getWidth()
- layoutManager.getPaddingRight()
- layoutManager.getDecoratedRight(firstView)
: layoutManager.getDecoratedLeft(firstView) - layoutManager.getPaddingLeft();
} else {
mCurrentOffset =
reverseLayout
? view.getHeight()
- layoutManager.getPaddingBottom()
- layoutManager.getDecoratedBottom(firstView)
: layoutManager.getDecoratedTop(firstView) - layoutManager.getPaddingTop();
}
} else {
mCurrentOffset = 0;
}
view.removeOnScrollListener(mRangeScrollListener);
view.removeOnScrollListener(mViewportManager.getScrollListener());
if (ComponentsConfiguration.enableSwapAdapter) {
view.swapAdapter(null, false);
} else {
view.setAdapter(null);
}
view.setLayoutManager(null);
mViewportManager.removeViewportChangedListener(mViewportChangedListener);
// We might have already unmounted this view when calling mount with a different view. In this
// case we can just return here.
if (mMountedView != view) {
return;
}
mMountedView = null;
if (mStickyHeaderController != null) {
mStickyHeaderController.reset();
}
mLayoutInfo.setRenderInfoCollection(null);
}
@UiThread
public void scrollToPosition(int position, boolean smoothScroll) {
if (mMountedView == null) {
mCurrentFirstVisiblePosition = position;
return;
}
if (smoothScroll) {
mMountedView.smoothScrollToPosition(position);
} else {
mMountedView.scrollToPosition(position);
}
}
@UiThread
public void scrollToPositionWithOffset(int position, int offset) {
if (mMountedView == null || !(mMountedView.getLayoutManager() instanceof LinearLayoutManager)) {
mCurrentFirstVisiblePosition = position;
mCurrentOffset = offset;
return;
}
((LinearLayoutManager) mMountedView.getLayoutManager()).scrollToPositionWithOffset(
position,
offset);
}
@GuardedBy("this")
private boolean isCompatibleSize(int widthSpec, int heightSpec) {
final int scrollDirection = mLayoutInfo.getScrollDirection();
if (mLastWidthSpec != UNINITIALIZED) {
switch (scrollDirection) {
case HORIZONTAL:
return isMeasureSpecCompatible(
mLastHeightSpec,
heightSpec,
mMeasuredSize.height);
case VERTICAL:
return isMeasureSpecCompatible(
mLastWidthSpec,
widthSpec,
mMeasuredSize.width);
}
}
return false;
}
@Override
public int findFirstVisibleItemPosition() {
return mLayoutInfo.findFirstVisibleItemPosition();
}
@Override
public int findFirstFullyVisibleItemPosition() {
return mLayoutInfo.findFirstFullyVisibleItemPosition();
}
@Override
public int findLastVisibleItemPosition() {
return mLayoutInfo.findLastVisibleItemPosition();
}
@Override
public int findLastFullyVisibleItemPosition() {
return mLayoutInfo.findLastFullyVisibleItemPosition();
}
@Override
@UiThread
@GuardedBy("this")
public boolean isSticky(int position) {
return mComponentTreeHolders.get(position).getRenderInfo().isSticky();
}
@Override
@UiThread
@GuardedBy("this")
public boolean isValidPosition(int position) {
return position >= 0 && position < mComponentTreeHolders.size();
}
private static class RangeCalculationResult {
// The estimated number of items needed to fill the viewport.
private int estimatedViewportCount;
// The size computed for the first Component.
private int measuredSize;
}
@Override
@UiThread
public void setViewportChangedListener(@Nullable ViewportChanged viewportChangedListener) {
mViewportManager.addViewportChangedListener(viewportChangedListener);
}
@VisibleForTesting
void onNewVisibleRange(int firstVisiblePosition, int lastVisiblePosition) {
mCurrentFirstVisiblePosition = firstVisiblePosition;
mCurrentLastVisiblePosition = lastVisiblePosition;
mViewportManager.resetShouldUpdate();
maybePostUpdateViewportAndComputeRange();
}
@VisibleForTesting
void onNewWorkingRange(
int firstVisibleIndex,
int lastVisibleIndex,
int firstFullyVisibleIndex,
int lastFullyVisibleIndex) {
if (mRange == null
|| firstVisibleIndex == RecyclerView.NO_POSITION
|| lastVisibleIndex == RecyclerView.NO_POSITION) {
return;
}
final int rangeSize =
Math.max(mRange.estimatedViewportCount, lastVisibleIndex - firstVisibleIndex);
final int layoutRangeSize = (int) (rangeSize * mRangeRatio);
final int rangeStart = Math.max(0, firstVisibleIndex - layoutRangeSize);
final int rangeEnd =
Math.min(firstVisibleIndex + rangeSize + layoutRangeSize, mComponentTreeHolders.size() - 1);
for (int position = rangeStart; position <= rangeEnd; position++) {
final ComponentTreeHolder holder = mComponentTreeHolders.get(position);
holder.checkWorkingRangeAndDispatch(
position,
firstVisibleIndex,
lastVisibleIndex,
firstFullyVisibleIndex,
lastFullyVisibleIndex);
}
}
private void maybePostUpdateViewportAndComputeRange() {
if (mMountedView != null
&& (ComponentsConfiguration.insertPostAsyncLayout
|| mViewportManager.shouldUpdate())) {
mPostUpdateViewportAndComputeRangeAttempts = 0;
mMountedView.removeCallbacks(mUpdateViewportAndComputeRangeRunnable);
ViewCompat.postOnAnimation(mMountedView, mUpdateViewportAndComputeRangeRunnable);
} else {
computeRange(mCurrentFirstVisiblePosition, mCurrentLastVisiblePosition);
}
}
private void computeRange(int firstVisible, int lastVisible) {
final int rangeSize;
final int rangeStart;
final int rangeEnd;
final int treeHoldersSize;
synchronized (this) {
if (!mIsMeasured.get() || mRange == null) {
return;
}
if (firstVisible == RecyclerView.NO_POSITION || lastVisible == RecyclerView.NO_POSITION) {
firstVisible = lastVisible = 0;
}
rangeSize = Math.max(mRange.estimatedViewportCount, lastVisible - firstVisible);
rangeStart = firstVisible - (int) (rangeSize * mRangeRatio);
rangeEnd = firstVisible + rangeSize + (int) (rangeSize * mRangeRatio);
treeHoldersSize = mComponentTreeHolders.size();
}
computeRangeLayout(treeHoldersSize, rangeStart, rangeEnd, mIsCircular);
}
private void computeRangeLayout(
int treeHoldersSize, int rangeStart, int rangeEnd, boolean ignoreRange) {
// TODO 16212153 optimize computeRange loop.
for (int i = 0; i < treeHoldersSize; i++) {
final ComponentTreeHolder holder;
final int childrenWidthSpec, childrenHeightSpec;
synchronized (this) {
// Someone modified the ComponentsTreeHolders while we were computing this range. We
// can just bail as another range will be computed.
if (treeHoldersSize != mComponentTreeHolders.size()) {
return;
}
holder = mComponentTreeHolders.get(i);
if (holder.getRenderInfo().rendersView()) {
continue;
}
childrenWidthSpec = getActualChildrenWidthSpec(holder);
childrenHeightSpec = getActualChildrenHeightSpec(holder);
}
if (ignoreRange) {
if (!holder.isTreeValid()) {
holder.computeLayoutAsync(mComponentContext, childrenWidthSpec, childrenHeightSpec);
}
} else {
if (i >= rangeStart && i <= rangeEnd) {
if (!holder.isTreeValid()) {
holder.computeLayoutAsync(mComponentContext, childrenWidthSpec, childrenHeightSpec);
}
} else if (holder.isTreeValid()
&& !holder.getRenderInfo().isSticky()
&& (holder.getComponentTree() != null
&& holder.getComponentTree().getLithoView() == null)) {
holder.acquireStateAndReleaseTree();
}
}
}
}
@VisibleForTesting
@Nullable
RangeCalculationResult getRangeCalculationResult() {
return mRange;
}
@GuardedBy("this")
private int getActualChildrenWidthSpec(final ComponentTreeHolder treeHolder) {
if (mIsMeasured.get() && !mRequiresRemeasure.get()) {
return mLayoutInfo.getChildWidthSpec(
SizeSpec.makeSizeSpec(mMeasuredSize.width, SizeSpec.EXACTLY),
treeHolder.getRenderInfo());
}
return mLayoutInfo.getChildWidthSpec(mLastWidthSpec, treeHolder.getRenderInfo());
}
@GuardedBy("this")
private int getActualChildrenHeightSpec(final ComponentTreeHolder treeHolder) {
if (mHasDynamicItemHeight) {
return SizeSpec.UNSPECIFIED;
}
if (mIsMeasured.get() && !mRequiresRemeasure.get()) {
return mLayoutInfo.getChildHeightSpec(
SizeSpec.makeSizeSpec(mMeasuredSize.height, SizeSpec.EXACTLY),
treeHolder.getRenderInfo());
}
return mLayoutInfo.getChildHeightSpec(mLastHeightSpec, treeHolder.getRenderInfo());
}
private AsyncInsertOperation createAsyncInsertOperation(int position, RenderInfo renderInfo) {
final ComponentTreeHolder holder = createComponentTreeHolder(renderInfo);
holder.setInserted(false);
return new AsyncInsertOperation(position, holder);
}
/** Async operation types. */
@IntDef({Operation.INSERT, Operation.REMOVE, Operation.REMOVE_RANGE, Operation.MOVE})
@Retention(RetentionPolicy.SOURCE)
private @interface Operation {
int INSERT = 0;
int REMOVE = 1;
int REMOVE_RANGE = 2;
int MOVE = 3;
}
/** An operation received from one of the *Async methods, pending execution. */
private abstract static class AsyncOperation {
private final int mOperation;
public AsyncOperation(int operation) {
mOperation = operation;
}
}
private static final class AsyncInsertOperation extends AsyncOperation {
private final int mPosition;
private final ComponentTreeHolder mHolder;
public AsyncInsertOperation(int position, ComponentTreeHolder holder) {
super(Operation.INSERT);
mPosition = position;
mHolder = holder;
}
}
private static final class AsyncRemoveOperation extends AsyncOperation {
private final int mPosition;
public AsyncRemoveOperation(int position) {
super(Operation.REMOVE);
mPosition = position;
}
}
private static final class AsyncRemoveRangeOperation extends AsyncOperation {
private final int mPosition;
private final int mCount;
public AsyncRemoveRangeOperation(int position, int count) {
super(Operation.REMOVE_RANGE);
mPosition = position;
mCount = count;
}
}
private static final class AsyncMoveOperation extends AsyncOperation {
private final int mFromPosition;
private final int mToPosition;
public AsyncMoveOperation(int fromPosition, int toPosition) {
super(Operation.MOVE);
mFromPosition = fromPosition;
mToPosition = toPosition;
}
}
/**
* A batch of {@link AsyncOperation}s that should be applied all at once. The OnDataBoundListener
* should be called once all these operations are applied.
*/
private static final class AsyncBatch {
private final ArrayList<AsyncOperation> mOperations = new ArrayList<>();
private @Nullable OnDataBoundListener mOnDataBoundListener;
}
private class RangeScrollListener extends RecyclerView.OnScrollListener {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (mCanPrefetchDisplayLists) {
DisplayListUtils.prefetchDisplayLists(recyclerView);
}
}
}
private static class BaseViewHolder extends RecyclerView.ViewHolder {
private final boolean isLithoViewType;
@Nullable private ViewBinder viewBinder;
public BaseViewHolder(View view, boolean isLithoViewType) {
super(view);
this.isLithoViewType = isLithoViewType;
}
}
private class InternalAdapter extends RecyclerView.Adapter<BaseViewHolder> {
@Override
public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final ViewCreator viewCreator = mRenderInfoViewCreatorController.getViewCreator(viewType);
if (viewCreator != null) {
final View view = viewCreator.createView(mComponentContext, parent);
return new BaseViewHolder(view, false);
} else {
final LithoView lithoView =
mLithoViewFactory == null
? new LithoView(mComponentContext, null)
: mLithoViewFactory.createLithoView(mComponentContext);
return new BaseViewHolder(lithoView, true);
}
}
@Override
@GuardedBy("RecyclerBinder.this")
public void onBindViewHolder(BaseViewHolder holder, int position) {
final int normalizedPosition = getNormalizedPosition(position);
// We can ignore the synchronization here. We'll only add to this from the UiThread.
// This read only happens on the UiThread as well and we are never writing this here.
final ComponentTreeHolder componentTreeHolder = mComponentTreeHolders.get(normalizedPosition);
final RenderInfo renderInfo = componentTreeHolder.getRenderInfo();
if (renderInfo.rendersComponent()) {
final LithoView lithoView = (LithoView) holder.itemView;
lithoView.setInvalidStateLogId(mInvalidStateLogId);
final int childrenWidthSpec = getActualChildrenWidthSpec(componentTreeHolder);
final int childrenHeightSpec = getActualChildrenHeightSpec(componentTreeHolder);
if (!componentTreeHolder.isTreeValid()) {
componentTreeHolder.computeLayoutSync(
mComponentContext, childrenWidthSpec, childrenHeightSpec, null);
}
final boolean isOrientationVertical =
mLayoutInfo.getScrollDirection() == OrientationHelper.VERTICAL;
final int width;
final int height;
if (SizeSpec.getMode(childrenWidthSpec) == SizeSpec.EXACTLY) {
width = SizeSpec.getSize(childrenWidthSpec);
} else if (isOrientationVertical) {
width = MATCH_PARENT;
} else {
width = WRAP_CONTENT;
}
if (SizeSpec.getMode(childrenHeightSpec) == SizeSpec.EXACTLY) {
height = SizeSpec.getSize(childrenHeightSpec);
} else if (isOrientationVertical) {
height = WRAP_CONTENT;
} else {
height = MATCH_PARENT;
}
final RecyclerViewLayoutManagerOverrideParams layoutParams =
new RecyclerViewLayoutManagerOverrideParams(
width, height, childrenWidthSpec, childrenHeightSpec, renderInfo.isFullSpan());
lithoView.setLayoutParams(layoutParams);
lithoView.setComponentTree(componentTreeHolder.getComponentTree());
if (componentTreeHolder.getRenderInfo().getRenderCompleteEventHandler() != null
&& componentTreeHolder.getRenderState() == RENDER_UNINITIALIZED) {
lithoView.setOnPostDrawListener(
new LithoView.OnPostDrawListener() {
@Override
public void onPostDraw() {
notifyItemRenderCompleteAt(normalizedPosition, SystemClock.uptimeMillis());
lithoView.setOnPostDrawListener(null);
}
});
}
} else {
final ViewBinder viewBinder = renderInfo.getViewBinder();
holder.viewBinder = viewBinder;
viewBinder.bind(holder.itemView);
}
}
@Override
@GuardedBy("RecyclerBinder.this")
public int getItemViewType(int position) {
final RenderInfo renderInfo =
mComponentTreeHolders.get(getNormalizedPosition(position)).getRenderInfo();
if (renderInfo.rendersComponent()) {
// Special value for LithoViews
return mRenderInfoViewCreatorController.getComponentViewType();
} else {
return renderInfo.getViewType();
}
}
@Override
@GuardedBy("RecyclerBinder.this")
public int getItemCount() {
// We can ignore the synchronization here. We'll only add to this from the UiThread.
// This read only happens on the UiThread as well and we are never writing this here.
// If the recycler is circular, we have to simulate having an infinite number of items in the
// adapter by returning Integer.MAX_VALUE.
return mIsCircular ? Integer.MAX_VALUE : mComponentTreeHolders.size();
}
@Override
public void onViewRecycled(BaseViewHolder holder) {
if (holder.isLithoViewType) {
final LithoView lithoView = (LithoView) holder.itemView;
lithoView.unmountAllItems();
lithoView.setComponentTree(null);
lithoView.setInvalidStateLogId(null);
} else {
final ViewBinder viewBinder = holder.viewBinder;
if (viewBinder != null) {
viewBinder.unbind(holder.itemView);
holder.viewBinder = null;
}
}
}
}
/**
* If the recycler is circular, returns the position of the {@link ComponentTreeHolder} that is
* used to render the item at given position. Otherwise, it returns the position passed as
* parameter, which is the same as the index of the {@link ComponentTreeHolder}.
*/
@GuardedBy("this")
private int getNormalizedPosition(int position) {
return mIsCircular ? position % mComponentTreeHolders.size() : position;
}
public static class RecyclerViewLayoutManagerOverrideParams extends RecyclerView.LayoutParams
implements LithoView.LayoutManagerOverrideParams {
private final int mWidthMeasureSpec;
private final int mHeightMeasureSpec;
private final boolean mIsFullSpan;
private RecyclerViewLayoutManagerOverrideParams(
int width,
int height,
int overrideWidthMeasureSpec,
int overrideHeightMeasureSpec,
boolean isFullSpan) {
super(width, height);
mWidthMeasureSpec = overrideWidthMeasureSpec;
mHeightMeasureSpec = overrideHeightMeasureSpec;
mIsFullSpan = isFullSpan;
}
@Override
public int getWidthMeasureSpec() {
return mWidthMeasureSpec;
}
@Override
public int getHeightMeasureSpec() {
return mHeightMeasureSpec;
}
public boolean isFullSpan() {
return mIsFullSpan;
}
}
private ComponentTreeHolder createComponentTreeHolder(RenderInfo renderInfo) {
return mComponentTreeHolderFactory.create(
renderInfo,
mLayoutHandlerFactory != null
? mLayoutHandlerFactory.createLayoutCalculationHandler(renderInfo)
: null,
mCanPrefetchDisplayLists,
mCanCacheDrawingDisplayLists,
mHasDynamicItemHeight ? mComponentTreeMeasureListenerFactory : null,
mSplitLayoutTag);
}
}
|
litho-widget/src/main/java/com/facebook/litho/widget/RecyclerBinder.java
|
/*
* Copyright 2014-present Facebook, 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.facebook.litho.widget;
import static android.support.v7.widget.OrientationHelper.HORIZONTAL;
import static android.support.v7.widget.OrientationHelper.VERTICAL;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static com.facebook.litho.MeasureComparisonUtils.isMeasureSpecCompatible;
import static com.facebook.litho.widget.ComponentTreeHolder.RENDER_UNINITIALIZED;
import static com.facebook.litho.widget.RenderInfoViewCreatorController.DEFAULT_COMPONENT_VIEW_TYPE;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.support.annotation.IntDef;
import android.support.annotation.UiThread;
import android.support.annotation.VisibleForTesting;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.LayoutManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import com.facebook.litho.Component;
import com.facebook.litho.ComponentContext;
import com.facebook.litho.ComponentTree;
import com.facebook.litho.ComponentTree.MeasureListener;
import com.facebook.litho.ComponentsSystrace;
import com.facebook.litho.EventHandler;
import com.facebook.litho.LayoutHandler;
import com.facebook.litho.LithoView;
import com.facebook.litho.MeasureComparisonUtils;
import com.facebook.litho.RenderCompleteEvent;
import com.facebook.litho.Size;
import com.facebook.litho.SizeSpec;
import com.facebook.litho.ThreadUtils;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.utils.DisplayListUtils;
import com.facebook.litho.viewcompat.ViewBinder;
import com.facebook.litho.viewcompat.ViewCreator;
import com.facebook.litho.widget.ComponentTreeHolder.ComponentTreeMeasureListenerFactory;
import com.facebook.litho.widget.ComponentTreeHolder.RenderState;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
/**
* This binder class is used to asynchronously layout Components given a list of {@link Component}
* and attaching them to a {@link RecyclerSpec}.
*/
@ThreadSafe
public class RecyclerBinder
implements Binder<RecyclerView>, LayoutInfo.RenderInfoCollection, HasStickyHeader {
private static final int UNINITIALIZED = -1;
private static final Size sDummySize = new Size();
private static final String TAG = RecyclerBinder.class.getSimpleName();
private static final int POST_UPDATE_VIEWPORT_AND_COMPUTE_RANGE_MAX_ATTEMPTS = 3;
@GuardedBy("this")
private final List<ComponentTreeHolder> mComponentTreeHolders = new ArrayList<>();
@GuardedBy("this")
private final List<ComponentTreeHolder> mAsyncComponentTreeHolders = new ArrayList<>();
private final LayoutInfo mLayoutInfo;
private final RecyclerView.Adapter mInternalAdapter;
private final ComponentContext mComponentContext;
private final RangeScrollListener mRangeScrollListener = new RangeScrollListener();
private final LayoutHandlerFactory mLayoutHandlerFactory;
private final @Nullable LithoViewFactory mLithoViewFactory;
private final ComponentTreeHolderFactory mComponentTreeHolderFactory;
private final Handler mMainThreadHandler = new Handler(Looper.getMainLooper());
private final float mRangeRatio;
private final AtomicBoolean mIsMeasured = new AtomicBoolean(false);
private final AtomicBoolean mRequiresRemeasure = new AtomicBoolean(false);
@GuardedBy("this")
private final ArrayList<AsyncInsertOperation> mInsertsWaitingForInitialMeasure =
new ArrayList<>();
@GuardedBy("this")
private final Deque<AsyncBatch> mAsyncBatches = new ArrayDeque<>();
@VisibleForTesting
final Runnable mRemeasureRunnable =
new Runnable() {
@Override
public void run() {
if (mReMeasureEventEventHandler != null) {
mReMeasureEventEventHandler.dispatchEvent(new ReMeasureEvent());
}
}
};
private final Runnable mNotifyDatasetChangedRunnable = new Runnable() {
@Override
public void run() {
mInternalAdapter.notifyDataSetChanged();
}
};
private final ComponentTreeMeasureListenerFactory mComponentTreeMeasureListenerFactory =
new ComponentTreeMeasureListenerFactory() {
@Override
public MeasureListener create(final ComponentTreeHolder holder) {
return getMeasureListener(holder);
}
};
private String mSplitLayoutTag;
private MeasureListener getMeasureListener(final ComponentTreeHolder holder) {
return new MeasureListener() {
@Override
public void onSetRootAndSizeSpec(int width, int height) {
if (holder.getMeasuredHeight() == height) {
return;
}
holder.setMeasuredHeight(height);
final RangeCalculationResult range = RecyclerBinder.this.mRange;
if (range != null
&& holder.getMeasuredHeight() <= RecyclerBinder.this.mRange.measuredSize) {
return;
}
synchronized (RecyclerBinder.this) {
resetMeasuredSize(width);
}
requestRemeasure();
}
};
}
private final ComponentTree.NewLayoutStateReadyListener mAsyncLayoutReadyListener =
new ComponentTree.NewLayoutStateReadyListener() {
@UiThread
@Override
public void onNewLayoutStateReady(ComponentTree componentTree) {
if (mMountedView == null) {
applyReadyBatches();
} else {
// When mounted, always apply binder mutations on frame boundaries
ViewCompat.postOnAnimation(mMountedView, mApplyReadyBatchesRunnable);
}
}
};
@VisibleForTesting
final Runnable mApplyReadyBatchesRunnable =
new Runnable() {
@UiThread
@Override
public void run() {
applyReadyBatches();
}
};
private final boolean mIsCircular;
private final boolean mHasDynamicItemHeight;
private final boolean mWrapContent;
private int mLastWidthSpec = UNINITIALIZED;
private int mLastHeightSpec = UNINITIALIZED;
private Size mMeasuredSize;
private RecyclerView mMountedView;
@VisibleForTesting int mCurrentFirstVisiblePosition = RecyclerView.NO_POSITION;
@VisibleForTesting int mCurrentLastVisiblePosition = RecyclerView.NO_POSITION;
private int mCurrentOffset;
private @Nullable RangeCalculationResult mRange;
private StickyHeaderController mStickyHeaderController;
private final boolean mCanPrefetchDisplayLists;
private final boolean mCanCacheDrawingDisplayLists;
private EventHandler<ReMeasureEvent> mReMeasureEventEventHandler;
private volatile boolean mHasAsyncOperations = false;
private volatile boolean mAsyncInsertsShouldWaitForMeasure = true;
private volatile boolean mHasFilledViewport = false;
private String mInvalidStateLogId;
@GuardedBy("this")
private @Nullable AsyncBatch mCurrentBatch = null;
@VisibleForTesting final ViewportManager mViewportManager;
private final ViewportChanged mViewportChangedListener =
new ViewportChanged() {
@Override
public void viewportChanged(
int firstVisibleIndex,
int lastVisibleIndex,
int firstFullyVisibleIndex,
int lastFullyVisibleIndex,
int state) {
onNewVisibleRange(firstVisibleIndex, lastVisibleIndex);
onNewWorkingRange(
firstVisibleIndex, lastVisibleIndex, firstFullyVisibleIndex, lastFullyVisibleIndex);
}
};
private int mPostUpdateViewportAndComputeRangeAttempts;
@VisibleForTesting final RenderInfoViewCreatorController mRenderInfoViewCreatorController;
// todo T30260224
private final Runnable mUpdateViewportAndComputeRangeRunnable =
new Runnable() {
@Override
public void run() {
// If mount hasn't happened or we don't have any pending updates, we're ready to compute
// range.
if (mMountedView == null || !mMountedView.hasPendingAdapterUpdates()) {
if (mViewportManager.shouldUpdate()) {
mViewportManager.onViewportChanged(State.DATA_CHANGES);
}
mPostUpdateViewportAndComputeRangeAttempts = 0;
computeRange(mCurrentFirstVisiblePosition, mCurrentLastVisiblePosition);
return;
}
// If the view gets detached, we can still have pending updates.
// If the view's visibility is GONE, layout won't happen until it becomes visible. We have
// to exit here, otherwise we keep posting this runnable to the next frame until it
// becomes visible.
if (!mMountedView.isAttachedToWindow() || mMountedView.getVisibility() == View.GONE) {
mPostUpdateViewportAndComputeRangeAttempts = 0;
return;
}
if (mPostUpdateViewportAndComputeRangeAttempts
>= POST_UPDATE_VIEWPORT_AND_COMPUTE_RANGE_MAX_ATTEMPTS) {
mPostUpdateViewportAndComputeRangeAttempts = 0;
if (mViewportManager.shouldUpdate()) {
mViewportManager.onViewportChanged(State.DATA_CHANGES);
}
final int size = mComponentTreeHolders.size();
if (size == 0) {
return;
}
/**
* We only update first and last visible positions after the RecyclerView triggers a
* layout for its pending updates. If consuming updates is posted to the next frame,
* which the RecyclerView can do, then we go into this runnable after the component tree
* holders have been modified but before first/last indexes were updated. This can make
* these positions get out of bounds, so we make sure we access valid indexes before
* computing range.
*/
final int first = Math.min(mCurrentFirstVisiblePosition, size - 1);
final int last = Math.min(mCurrentLastVisiblePosition, size - 1);
computeRange(first, last);
return;
}
// If we have pending updates, wait until the sync operations are finished and try again
// in the next frame.
mPostUpdateViewportAndComputeRangeAttempts++;
ViewCompat.postOnAnimation(mMountedView, mUpdateViewportAndComputeRangeRunnable);
}
};
static class RenderCompleteRunnable implements Runnable {
private final EventHandler<RenderCompleteEvent> renderCompleteEventHandler;
private final boolean hasMounted;
private final long timestampMillis;
RenderCompleteRunnable(
EventHandler<RenderCompleteEvent> renderCompleteEventHandler,
boolean hasMounted,
long timestampMillis) {
this.renderCompleteEventHandler = renderCompleteEventHandler;
this.hasMounted = hasMounted;
this.timestampMillis = timestampMillis;
}
@Override
public void run() {
dispatchRenderCompleteEvent(renderCompleteEventHandler, hasMounted, timestampMillis);
}
}
interface ComponentTreeHolderFactory {
ComponentTreeHolder create(
RenderInfo renderInfo,
LayoutHandler layoutHandler,
boolean canPrefetchDisplayLists,
boolean canCacheDrawingDisplayLists,
ComponentTreeMeasureListenerFactory measureListenerFactory,
String splitLayoutTag);
}
static final ComponentTreeHolderFactory DEFAULT_COMPONENT_TREE_HOLDER_FACTORY =
new ComponentTreeHolderFactory() {
@Override
public ComponentTreeHolder create(
RenderInfo renderInfo,
LayoutHandler layoutHandler,
boolean canPrefetchDisplayLists,
boolean canCacheDrawingDisplayLists,
ComponentTreeMeasureListenerFactory measureListenerFactory,
String splitLayoutTag) {
return ComponentTreeHolder.acquire(
renderInfo,
layoutHandler,
canPrefetchDisplayLists,
canCacheDrawingDisplayLists,
measureListenerFactory,
splitLayoutTag);
}
};
public static class Builder {
private float rangeRatio = 4f;
private LayoutInfo layoutInfo;
private @Nullable LayoutHandlerFactory layoutHandlerFactory;
private boolean canPrefetchDisplayLists;
private boolean canCacheDrawingDisplayLists;
private ComponentTreeHolderFactory componentTreeHolderFactory =
DEFAULT_COMPONENT_TREE_HOLDER_FACTORY;
private ComponentContext componentContext;
private LithoViewFactory lithoViewFactory;
private boolean isCircular;
private boolean hasDynamicItemHeight;
private boolean wrapContent;
private boolean customViewTypeEnabled;
private int componentViewType;
private @Nullable RecyclerView.Adapter overrideInternalAdapter;
private String splitLayoutTag;
/**
* @param rangeRatio specifies how big a range this binder should try to compute. The range is
* computed as number of items in the viewport (when the binder is measured) multiplied by the
* range ratio. The ratio is to be intended in both directions. For example a ratio of 1 means
* that if there are currently N components on screen, the binder should try to compute the
* layout for the N components before the first component on screen and for the N components
* after the last component on screen. If not set, defaults to 4f.
*/
public Builder rangeRatio(float rangeRatio) {
this.rangeRatio = rangeRatio;
return this;
}
/**
* @param layoutInfo an implementation of {@link LayoutInfo} that will expose information about
* the {@link LayoutManager} this RecyclerBinder will use. If not set, it will default to a
* vertical list.
*/
public Builder layoutInfo(LayoutInfo layoutInfo) {
this.layoutInfo = layoutInfo;
return this;
}
/**
* @param layoutHandlerFactory the RecyclerBinder will use this layoutHandlerFactory when
* creating {@link ComponentTree}s in order to specify on which thread layout calculation
* should happen.
*/
public Builder layoutHandlerFactory(LayoutHandlerFactory layoutHandlerFactory) {
this.layoutHandlerFactory = layoutHandlerFactory;
return this;
}
public Builder lithoViewFactory(LithoViewFactory lithoViewFactory) {
this.lithoViewFactory = lithoViewFactory;
return this;
}
public Builder canPrefetchDisplayLists(boolean canPrefetchDisplayLists) {
this.canPrefetchDisplayLists = canPrefetchDisplayLists;
return this;
}
public Builder canCacheDrawingDisplayLists(boolean canCacheDrawingDisplayLists) {
this.canCacheDrawingDisplayLists = canCacheDrawingDisplayLists;
return this;
}
/**
* Whether the underlying RecyclerBinder will have a circular behaviour. Defaults to false.
* Note: circular lists DO NOT support any operation that changes the size of items like insert,
* remove, insert range, remove range
*/
public Builder isCircular(boolean isCircular) {
this.isCircular = isCircular;
return this;
}
/**
* If true, the underlying RecyclerBinder will measure the parent height by the height of
* children if the orientation is vertical, or measure the parent width by the width of children
* if the orientation is horizontal.
*/
public Builder wrapContent(boolean wrapContent) {
this.wrapContent = wrapContent;
return this;
}
/**
* @param componentTreeHolderFactory Factory to acquire a new ComponentTreeHolder. Defaults to
* {@link #DEFAULT_COMPONENT_TREE_HOLDER_FACTORY}.
*/
public Builder componentTreeHolderFactory(
ComponentTreeHolderFactory componentTreeHolderFactory) {
this.componentTreeHolderFactory = componentTreeHolderFactory;
return this;
}
/**
* Do not enable this. This is an experimental feature and your Section surface will take a perf
* hit if you use it.
*
* <p>Whether the items of this RecyclerBinder can change height after the initial measure. Only
* applicable to horizontally scrolling RecyclerBinders. If true, the children of this h-scroll
* are all measured with unspecified height. When the ComponentTree of a child is remeasured,
* this will cause the RecyclerBinder to remeasure in case the height of the child changed and
* the RecyclerView needs to have a different height to account for it. This only supports
* changing the height of the item that triggered the remeasuring, not the height of all items
* in the h-scroll.
*/
public Builder hasDynamicItemHeight(boolean hasDynamicItemHeight) {
this.hasDynamicItemHeight = hasDynamicItemHeight;
return this;
}
/**
* Enable setting custom viewTypes on {@link ViewRenderInfo}s.
*
* <p>After this is set, all {@link ViewRenderInfo}s must be built with a custom viewType
* through {@link ViewRenderInfo.Builder#customViewType(int)}, otherwise exception will be
* thrown.
*
* @param componentViewType the viewType to be used for Component types, provided through {@link
* ComponentRenderInfo}. Set this to a value that won't conflict with your custom viewTypes.
*/
public Builder enableCustomViewType(int componentViewType) {
this.customViewTypeEnabled = true;
this.componentViewType = componentViewType;
return this;
}
/**
* Method for tests to allow mocking of the InternalAdapter to verify interaction with the
* RecyclerView.
*/
@VisibleForTesting
Builder overrideInternalAdapter(RecyclerView.Adapter overrideInternalAdapter) {
this.overrideInternalAdapter = overrideInternalAdapter;
return this;
}
public Builder splitLayoutTag(String splitLayoutTag) {
this.splitLayoutTag = splitLayoutTag;
return this;
}
/** @param c The {@link ComponentContext} the RecyclerBinder will use. */
public RecyclerBinder build(ComponentContext c) {
componentContext = new ComponentContext(c);
if (layoutInfo == null) {
layoutInfo = new LinearLayoutInfo(c, VERTICAL, false);
}
return new RecyclerBinder(this);
}
}
@Override
public boolean isWrapContent() {
return mWrapContent;
}
@UiThread
public void notifyItemRenderCompleteAt(int position, final long timestampMillis) {
final ComponentTreeHolder holder = mComponentTreeHolders.get(position);
final EventHandler<RenderCompleteEvent> renderCompleteEventHandler =
holder.getRenderInfo().getRenderCompleteEventHandler();
if (renderCompleteEventHandler == null) {
return;
}
final @RenderState int state = holder.getRenderState();
if (state == ComponentTreeHolder.RENDER_DRAWN) {
return;
}
// Dispatch a RenderCompleteEvent asynchronously.
ViewCompat.postOnAnimation(
mMountedView,
new RenderCompleteRunnable(renderCompleteEventHandler, true, timestampMillis));
// Update the state to prevent dispatch an event again for the same holder.
holder.setRenderState(ComponentTreeHolder.RENDER_DRAWN);
}
@UiThread
private static void dispatchRenderCompleteEvent(
EventHandler<RenderCompleteEvent> renderCompleteEventHandler,
boolean hasMounted,
long timestampMillis) {
ThreadUtils.assertMainThread();
final RenderCompleteEvent event = new RenderCompleteEvent();
event.hasMounted = hasMounted;
event.timestampMillis = timestampMillis;
renderCompleteEventHandler.dispatchEvent(event);
}
private RecyclerBinder(Builder builder) {
mComponentContext = builder.componentContext;
mComponentTreeHolderFactory = builder.componentTreeHolderFactory;
mInternalAdapter =
builder.overrideInternalAdapter != null
? builder.overrideInternalAdapter
: new InternalAdapter();
mRangeRatio = builder.rangeRatio;
mLayoutInfo = builder.layoutInfo;
mLayoutHandlerFactory = builder.layoutHandlerFactory;
mLithoViewFactory = builder.lithoViewFactory;
mCanPrefetchDisplayLists = builder.canPrefetchDisplayLists;
mCanCacheDrawingDisplayLists = builder.canCacheDrawingDisplayLists;
mRenderInfoViewCreatorController =
new RenderInfoViewCreatorController(
builder.customViewTypeEnabled,
builder.customViewTypeEnabled
? builder.componentViewType
: DEFAULT_COMPONENT_VIEW_TYPE);
mIsCircular = builder.isCircular;
mHasDynamicItemHeight =
mLayoutInfo.getScrollDirection() == HORIZONTAL ? builder.hasDynamicItemHeight : false;
mWrapContent = builder.wrapContent;
mViewportManager =
new ViewportManager(
mCurrentFirstVisiblePosition, mCurrentLastVisiblePosition, builder.layoutInfo);
mSplitLayoutTag = builder.splitLayoutTag;
}
/**
* Update the item at index position. The {@link RecyclerView} will only be notified of the item
* being updated after a layout calculation has been completed for the new {@link Component}.
*/
@UiThread
public final void updateItemAtAsync(int position, RenderInfo renderInfo) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(SectionsDebug.TAG, "(" + hashCode() + ") updateItemAtAsync " + position);
}
updateItemAtAsyncInner(position, renderInfo);
}
/**
* Update the items starting from the given index position. The {@link RecyclerView} will only be
* notified of the item being updated after a layout calculation has been completed for the new
* {@link Component}.
*/
@UiThread
public final void updateRangeAtAsync(int position, List<RenderInfo> renderInfos) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG,
"(" + hashCode() + ") updateRangeAtAsync " + position + ", count: " + renderInfos.size());
}
for (int i = 0, size = renderInfos.size(); i < size; i++) {
updateItemAtAsyncInner(position + i, renderInfos.get(i));
}
}
@UiThread
private void updateItemAtAsyncInner(int position, RenderInfo renderInfo) {
final ComponentTreeHolder holder;
final boolean renderInfoWasView;
final int indexInComponentTreeHolders;
synchronized (this) {
holder = mAsyncComponentTreeHolders.get(position);
renderInfoWasView = holder.getRenderInfo().rendersView();
mRenderInfoViewCreatorController.maybeTrackViewCreator(renderInfo);
holder.setRenderInfo(renderInfo);
if (holder.isInserted()) {
// If it's inserted, we can just count on the normal range computation re-computing this
indexInComponentTreeHolders = mComponentTreeHolders.indexOf(holder);
mViewportManager.setShouldUpdate(
mViewportManager.updateAffectsVisibleRange(indexInComponentTreeHolders, 1));
} else {
indexInComponentTreeHolders = -1;
// TODO(T28668712): Handle updates outside of range
computeLayoutAsync(holder);
}
}
if (indexInComponentTreeHolders >= 0
&& (renderInfoWasView || holder.getRenderInfo().rendersView())) {
mInternalAdapter.notifyItemChanged(indexInComponentTreeHolders);
}
}
/**
* Inserts an item at position. The {@link RecyclerView} will only be notified of the item being
* inserted after a layout calculation has been completed for the new {@link Component}.
*/
@UiThread
public final void insertItemAtAsync(int position, RenderInfo renderInfo) {
ThreadUtils.assertMainThread();
assertNoInsertOperationIfCircular();
final AsyncInsertOperation operation = createAsyncInsertOperation(position, renderInfo);
synchronized (this) {
mHasAsyncOperations = true;
mAsyncComponentTreeHolders.add(position, operation.mHolder);
// If the binder has not been measured yet, we will compute an initial page of content based
// on the measured size of this RecyclerBinder synchronously during measure, and the rest will
// be kicked off as async inserts.
if (mAsyncInsertsShouldWaitForMeasure) {
registerAsyncInsertBeforeInitialMeasure(operation);
} else {
registerAsyncInsert(operation);
}
}
}
/**
* Inserts the new items starting from position. The {@link RecyclerView} will only be notified of
* the items being inserted after a layout calculation has been completed for the new {@link
* Component}s. There is not a guarantee that the {@link RecyclerView} will be notified about all
* the items in the range at the same time.
*/
@UiThread
public final void insertRangeAtAsync(int position, List<RenderInfo> renderInfos) {
ThreadUtils.assertMainThread();
assertNoInsertOperationIfCircular();
synchronized (this) {
mHasAsyncOperations = true;
for (int i = 0, size = renderInfos.size(); i < size; i++) {
final AsyncInsertOperation operation =
createAsyncInsertOperation(position + i, renderInfos.get(i));
mAsyncComponentTreeHolders.add(position + i, operation.mHolder);
// If the binder has not been measured yet, we will compute an initial page of content based
// on the measured size of this RecyclerBinder synchronously during measure, and the rest
// will be kicked off as async inserts.
if (mAsyncInsertsShouldWaitForMeasure) {
registerAsyncInsertBeforeInitialMeasure(operation);
} else {
registerAsyncInsert(operation);
}
}
}
}
@UiThread
private void applyReadyBatches() {
ThreadUtils.assertMainThread();
synchronized (this) {
boolean appliedBatch = false;
while (!mAsyncBatches.isEmpty()) {
final AsyncBatch batch = mAsyncBatches.peekFirst();
if (!isBatchReady(batch)) {
break;
}
mAsyncBatches.pollFirst();
applyBatch(batch);
appliedBatch = true;
}
if (appliedBatch) {
maybeUpdateRangeOrRemeasureForMutation();
}
}
}
private static boolean isBatchReady(AsyncBatch batch) {
for (int i = 0, size = batch.mOperations.size(); i < size; i++) {
final AsyncOperation operation = batch.mOperations.get(i);
if (operation instanceof AsyncInsertOperation
&& !((AsyncInsertOperation) operation).mHolder.hasCompletedLatestLayout()) {
return false;
}
}
return true;
}
@GuardedBy("this")
@UiThread
private void applyBatch(AsyncBatch batch) {
for (int i = 0, size = batch.mOperations.size(); i < size; i++) {
final AsyncOperation operation = batch.mOperations.get(i);
switch (operation.mOperation) {
case Operation.INSERT:
applyAsyncInsert((AsyncInsertOperation) operation);
break;
case Operation.REMOVE:
removeItemAt(((AsyncRemoveOperation) operation).mPosition);
break;
case Operation.REMOVE_RANGE:
final AsyncRemoveRangeOperation removeRangeOperation =
(AsyncRemoveRangeOperation) operation;
removeRangeAt(removeRangeOperation.mPosition, removeRangeOperation.mCount);
break;
case Operation.MOVE:
final AsyncMoveOperation moveOperation = (AsyncMoveOperation) operation;
moveItem(moveOperation.mFromPosition, moveOperation.mToPosition);
break;
default:
throw new RuntimeException("Unhandled operation type: " + operation.mOperation);
}
}
batch.mOnDataBoundListener.onDataBound();
}
@GuardedBy("this")
@UiThread
private void applyAsyncInsert(AsyncInsertOperation operation) {
if (operation.mHolder.isInserted()) {
return;
}
mComponentTreeHolders.add(operation.mPosition, operation.mHolder);
operation.mHolder.setInserted(true);
mInternalAdapter.notifyItemInserted(operation.mPosition);
mViewportManager.insertAffectsVisibleRange(
operation.mPosition, 1, mRange != null ? mRange.estimatedViewportCount : -1);
}
@GuardedBy("this")
private void registerAsyncInsert(AsyncInsertOperation operation) {
addToCurrentBatch(operation);
startAsyncLayout(operation);
}
@GuardedBy("this")
private void registerAsyncInsertBeforeInitialMeasure(AsyncInsertOperation operation) {
mInsertsWaitingForInitialMeasure.add(operation.mPosition, operation);
addToCurrentBatch(operation);
}
private void startAsyncLayout(AsyncInsertOperation operation) {
final ComponentTreeHolder holder = operation.mHolder;
holder.setNewLayoutReadyListener(mAsyncLayoutReadyListener);
holder.computeLayoutAsync(
mComponentContext, getActualChildrenWidthSpec(holder), getActualChildrenHeightSpec(holder));
}
/**
* Moves an item from fromPosition to toPostion. If there are other pending operations on this
* binder this will only be executed when all the operations have been completed (to ensure index
* consistency).
*/
@UiThread
public final void moveItemAsync(int fromPosition, int toPosition) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG,
"(" + hashCode() + ") moveItemAsync " + fromPosition + " to " + toPosition);
}
final AsyncMoveOperation operation = new AsyncMoveOperation(fromPosition, toPosition);
synchronized (this) {
mAsyncComponentTreeHolders.add(toPosition, mAsyncComponentTreeHolders.remove(fromPosition));
// TODO(t28619782): When moving a CT into range, do an async prepare
addToCurrentBatch(operation);
}
}
/**
* Removes an item from position. If there are other pending operations on this binder this will
* only be executed when all the operations have been completed (to ensure index consistency).
*/
@UiThread
public final void removeItemAtAsync(int position) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(SectionsDebug.TAG, "(" + hashCode() + ") removeItemAtAsync " + position);
}
final AsyncRemoveOperation asyncRemoveOperation = new AsyncRemoveOperation(position);
synchronized (this) {
mAsyncComponentTreeHolders.remove(position);
addToCurrentBatch(asyncRemoveOperation);
}
}
/**
* Removes count items starting from position. If there are other pending operations on this
* binder this will only be executed when all the operations have been completed (to ensure index
* consistency).
*/
@UiThread
public final void removeRangeAtAsync(int position, int count) {
ThreadUtils.assertMainThread();
assertNoRemoveOperationIfCircular(count);
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG,
"(" + hashCode() + ") removeRangeAtAsync " + position + ", size: " + count);
}
final AsyncRemoveRangeOperation operation = new AsyncRemoveRangeOperation(position, count);
synchronized (this) {
for (int i = 0; i < count; i++) {
// TODO(t28712163): Cancel pending layouts for async inserts
mAsyncComponentTreeHolders.remove(position);
}
addToCurrentBatch(operation);
}
}
/** Removes all items in this binder async. */
@UiThread
public final void clearAsync() {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(SectionsDebug.TAG, "(" + hashCode() + ") clear");
}
synchronized (this) {
mHasAsyncOperations = true;
final int count = mAsyncComponentTreeHolders.size();
// TODO(t28712163): Cancel pending layouts for async inserts
mAsyncComponentTreeHolders.clear();
final AsyncRemoveRangeOperation operation = new AsyncRemoveRangeOperation(0, count);
addToCurrentBatch(operation);
}
}
@GuardedBy("this")
private void addToCurrentBatch(AsyncOperation operation) {
if (mCurrentBatch == null) {
mCurrentBatch = new AsyncBatch();
}
mCurrentBatch.mOperations.add(operation);
}
/**
* See {@link RecyclerBinder#appendItem(RenderInfo)}.
*/
@UiThread
public final void appendItem(Component component) {
insertItemAt(getItemCount(), component);
}
/**
* Inserts a new item at tail. The {@link RecyclerView} gets notified immediately about the
* new item being inserted. If the item's position falls within the currently visible range, the
* layout is immediately computed on the] UiThread.
* The RenderInfo contains the component that will be inserted in the Binder and extra info
* like isSticky or spanCount.
*/
@UiThread
public final void appendItem(RenderInfo renderInfo) {
insertItemAt(getItemCount(), renderInfo);
}
/**
* See {@link RecyclerBinder#insertItemAt(int, RenderInfo)}.
*/
@UiThread
public final void insertItemAt(int position, Component component) {
insertItemAt(position, ComponentRenderInfo.create().component(component).build());
}
/**
* Inserts a new item at position. The {@link RecyclerView} gets notified immediately about the
* new item being inserted. If the item's position falls within the currently visible range, the
* layout is immediately computed on the] UiThread. The RenderInfo contains the component that
* will be inserted in the Binder and extra info like isSticky or spanCount.
*/
@UiThread
public final void insertItemAt(int position, RenderInfo renderInfo) {
ThreadUtils.assertMainThread();
assertNoInsertOperationIfCircular();
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG,
"(" + hashCode() + ") insertItemAt " + position + ", name: " + renderInfo.getName());
}
final ComponentTreeHolder holder = createComponentTreeHolder(renderInfo);
synchronized (this) {
if (mHasAsyncOperations) {
throw new RuntimeException("Trying to do a sync insert when using asynchronous mutations!");
}
mComponentTreeHolders.add(position, holder);
mRenderInfoViewCreatorController.maybeTrackViewCreator(renderInfo);
}
mInternalAdapter.notifyItemInserted(position);
mViewportManager.setShouldUpdate(
mViewportManager.insertAffectsVisibleRange(
position, 1, mRange != null ? mRange.estimatedViewportCount : -1));
}
private void requestRemeasure() {
if (SectionsDebug.ENABLED) {
Log.d(SectionsDebug.TAG, "(" + hashCode() + ") requestRemeasure");
}
if (mMountedView != null) {
mMainThreadHandler.removeCallbacks(mRemeasureRunnable);
mMountedView.removeCallbacks(mRemeasureRunnable);
ViewCompat.postOnAnimation(mMountedView, mRemeasureRunnable);
} else {
// We are not mounted but we still need to post this. Just post on the main thread.
mMainThreadHandler.removeCallbacks(mRemeasureRunnable);
mMainThreadHandler.post(mRemeasureRunnable);
}
}
/**
* Inserts the new items starting from position. The {@link RecyclerView} gets notified
* immediately about the new item being inserted. The RenderInfo contains the component that will
* be inserted in the Binder and extra info like isSticky or spanCount.
*/
@UiThread
public final void insertRangeAt(int position, List<RenderInfo> renderInfos) {
ThreadUtils.assertMainThread();
assertNoInsertOperationIfCircular();
if (SectionsDebug.ENABLED) {
final String[] names = new String[renderInfos.size()];
for (int i = 0; i < renderInfos.size(); i++) {
names[i] = renderInfos.get(i).getName();
}
Log.d(
SectionsDebug.TAG,
"("
+ hashCode()
+ ") insertRangeAt "
+ position
+ ", size: "
+ renderInfos.size()
+ ", names: "
+ Arrays.toString(names));
}
for (int i = 0, size = renderInfos.size(); i < size; i++) {
synchronized (this) {
final RenderInfo renderInfo = renderInfos.get(i);
final ComponentTreeHolder holder = createComponentTreeHolder(renderInfo);
if (mHasAsyncOperations) {
throw new RuntimeException(
"Trying to do a sync insert when using asynchronous mutations!");
}
mComponentTreeHolders.add(position + i, holder);
mRenderInfoViewCreatorController.maybeTrackViewCreator(renderInfo);
}
}
mInternalAdapter.notifyItemRangeInserted(position, renderInfos.size());
mViewportManager.setShouldUpdate(
mViewportManager.insertAffectsVisibleRange(
position, renderInfos.size(), mRange != null ? mRange.estimatedViewportCount : -1));
}
/**
* See {@link RecyclerBinder#updateItemAt(int, Component)}.
*/
@UiThread
public final void updateItemAt(int position, Component component) {
updateItemAt(position, ComponentRenderInfo.create().component(component).build());
}
/**
* Updates the item at position. The {@link RecyclerView} gets notified immediately about the item
* being updated. If the item's position falls within the currently visible range, the layout is
* immediately computed on the UiThread.
*/
@UiThread
public final void updateItemAt(int position, RenderInfo renderInfo) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG,
"(" + hashCode() + ") updateItemAt " + position + ", name: " + renderInfo.getName());
}
final ComponentTreeHolder holder;
final boolean renderInfoWasView;
synchronized (this) {
holder = mComponentTreeHolders.get(position);
renderInfoWasView = holder.getRenderInfo().rendersView();
mRenderInfoViewCreatorController.maybeTrackViewCreator(renderInfo);
holder.setRenderInfo(renderInfo);
}
// If this item is rendered with a view (or was rendered with a view before now) we need to
// notify the RecyclerView's adapter that something changed.
if (renderInfoWasView || renderInfo.rendersView()) {
mInternalAdapter.notifyItemChanged(position);
}
mViewportManager.setShouldUpdate(mViewportManager.updateAffectsVisibleRange(position, 1));
}
/**
* Updates the range of items starting at position. The {@link RecyclerView} gets notified
* immediately about the item being updated.
*/
@UiThread
public final void updateRangeAt(int position, List<RenderInfo> renderInfos) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
final String[] names = new String[renderInfos.size()];
for (int i = 0; i < renderInfos.size(); i++) {
names[i] = renderInfos.get(i).getName();
}
Log.d(
SectionsDebug.TAG,
"("
+ hashCode()
+ ") updateRangeAt "
+ position
+ ", size: "
+ renderInfos.size()
+ ", names: "
+ Arrays.toString(names));
}
for (int i = 0, size = renderInfos.size(); i < size; i++) {
synchronized (this) {
final ComponentTreeHolder holder = mComponentTreeHolders.get(position + i);
final RenderInfo newRenderInfo = renderInfos.get(i);
// If this item is rendered with a view (or was rendered with a view before now) we still
// need to notify the RecyclerView's adapter that something changed.
if (newRenderInfo.rendersView() || holder.getRenderInfo().rendersView()) {
mInternalAdapter.notifyItemChanged(position + i);
}
mRenderInfoViewCreatorController.maybeTrackViewCreator(newRenderInfo);
holder.setRenderInfo(newRenderInfo);
}
}
mViewportManager.setShouldUpdate(
mViewportManager.updateAffectsVisibleRange(position, renderInfos.size()));
}
/**
* Moves an item from fromPosition to toPosition. If the new position of the item is within the
* currently visible range, a layout is calculated immediately on the UI Thread.
*/
@UiThread
public final void moveItem(int fromPosition, int toPosition) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG, "(" + hashCode() + ") moveItem " + fromPosition + " to " + toPosition);
}
final ComponentTreeHolder holder;
final boolean isNewPositionInRange;
final int mRangeSize = mRange != null ? mRange.estimatedViewportCount : -1;
synchronized (this) {
holder = mComponentTreeHolders.remove(fromPosition);
mComponentTreeHolders.add(toPosition, holder);
isNewPositionInRange = mRangeSize > 0 &&
toPosition >= mCurrentFirstVisiblePosition - (mRangeSize * mRangeRatio) &&
toPosition <= mCurrentFirstVisiblePosition + mRangeSize + (mRangeSize * mRangeRatio);
}
final boolean isTreeValid = holder.isTreeValid();
if (isTreeValid && !isNewPositionInRange) {
holder.acquireStateAndReleaseTree();
}
mInternalAdapter.notifyItemMoved(fromPosition, toPosition);
mViewportManager.setShouldUpdate(
mViewportManager.moveAffectsVisibleRange(fromPosition, toPosition, mRangeSize));
}
/**
* Removes an item from index position.
*/
@UiThread
public final void removeItemAt(int position) {
ThreadUtils.assertMainThread();
assertNoRemoveOperationIfCircular(1);
if (SectionsDebug.ENABLED) {
Log.d(SectionsDebug.TAG, "(" + hashCode() + ") removeItemAt " + position);
}
final ComponentTreeHolder holder;
synchronized (this) {
holder = mComponentTreeHolders.remove(position);
}
mInternalAdapter.notifyItemRemoved(position);
holder.release();
mViewportManager.setShouldUpdate(mViewportManager.removeAffectsVisibleRange(position, 1));
}
/**
* Removes count items starting from position.
*/
@UiThread
public final void removeRangeAt(int position, int count) {
ThreadUtils.assertMainThread();
assertNoRemoveOperationIfCircular(count);
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG, "(" + hashCode() + ") removeRangeAt " + position + ", size: " + count);
}
synchronized (this) {
for (int i = 0; i < count; i++) {
final ComponentTreeHolder holder = mComponentTreeHolders.remove(position);
holder.release();
}
}
mInternalAdapter.notifyItemRangeRemoved(position, count);
mViewportManager.setShouldUpdate(mViewportManager.removeAffectsVisibleRange(position, count));
}
/**
* Called after all the change set operations (inserts, removes, etc.) in a batch have completed.
*/
@UiThread
public void notifyChangeSetComplete(OnDataBoundListener onDataBoundListener) {
ThreadUtils.assertMainThread();
if (SectionsDebug.ENABLED) {
Log.d(SectionsDebug.TAG, "(" + hashCode() + ") notifyChangeSetComplete");
}
if (!mHasAsyncOperations) {
onDataBoundListener.onDataBound();
} else {
closeCurrentBatch(onDataBoundListener);
applyReadyBatches();
}
maybeUpdateRangeOrRemeasureForMutation();
}
private synchronized void closeCurrentBatch(OnDataBoundListener onDataBoundListener) {
if (mCurrentBatch == null) {
// We create a batch here even if it doesn't have any operations: this is so we can still
// invoke the OnDataBoundListener at the appropriate time (after all preceding batches
// complete)
mCurrentBatch = new AsyncBatch();
}
mCurrentBatch.mOnDataBoundListener = onDataBoundListener;
mAsyncBatches.addLast(mCurrentBatch);
mCurrentBatch = null;
}
private synchronized void maybeUpdateRangeOrRemeasureForMutation() {
synchronized (this) {
if (!mIsMeasured.get()) {
return;
}
if (mRequiresRemeasure.get()) {
requestRemeasure();
return;
}
if (mRange == null) {
int firstComponent = findFirstComponentPosition(mComponentTreeHolders);
if (firstComponent >= 0) {
final ComponentTreeHolder holder = mComponentTreeHolders.get(firstComponent);
initRange(
mMeasuredSize.width,
mMeasuredSize.height,
holder,
getActualChildrenWidthSpec(holder),
getActualChildrenHeightSpec(holder),
mLayoutInfo.getScrollDirection());
if (!mHasFilledViewport && shouldFillListViewport()) {
if (SectionsDebug.ENABLED) {
Log.d(SectionsDebug.TAG, "(" + hashCode() + ") filling viewport for mutation");
}
fillListViewport(mMeasuredSize.width, mMeasuredSize.height, null);
}
}
}
}
maybePostUpdateViewportAndComputeRange();
}
/**
* Returns the {@link ComponentTree} for the item at index position. TODO 16212132 remove
* getComponentAt from binder
*/
@Nullable
@Override
public final synchronized ComponentTree getComponentAt(int position) {
return mComponentTreeHolders.get(position).getComponentTree();
}
@Override
public final synchronized ComponentTree getComponentForStickyHeaderAt(int position) {
final ComponentTreeHolder holder = mComponentTreeHolders.get(position);
if (holder.isTreeValid()) {
return holder.getComponentTree();
}
// This could happen when RecyclerView is populated with new data, and first position is not 0.
// It is possible that sticky header is above the first visible position and also it is outside
// calculated range and its layout has not been calculated yet.
final int childrenWidthSpec = getActualChildrenWidthSpec(holder);
final int childrenHeightSpec = getActualChildrenHeightSpec(holder);
holder.computeLayoutSync(mComponentContext, childrenWidthSpec, childrenHeightSpec, null);
return holder.getComponentTree();
}
@Override
public final synchronized RenderInfo getRenderInfoAt(int position) {
return mComponentTreeHolders.get(position).getRenderInfo();
}
@VisibleForTesting
final synchronized ComponentTreeHolder getComponentTreeHolderAt(int position) {
return mComponentTreeHolders.get(position);
}
@Override
public void bind(RecyclerView view) {
// Nothing to do here.
}
@Override
public void unbind(RecyclerView view) {
// Nothing to do here.
}
/**
* A component mounting a RecyclerView can use this method to determine its size. A Recycler that
* scrolls horizontally will leave the width unconstrained and will measure its children with a
* sizeSpec for the height matching the heightSpec passed to this method.
*
* If padding is defined on the parent component it should be subtracted from the parent size
* specs before passing them to this method.
*
* Currently we can't support the equivalent of MATCH_PARENT on the scrollDirection (so for
* example we don't support MATCH_PARENT on width in an horizontal RecyclerView). This is mainly
* because we don't have the equivalent of LayoutParams in components. We can extend the api of
* the binder in the future to provide some more layout hints in order to support this.
*
* @param outSize will be populated with the measured dimensions for this Binder.
* @param widthSpec the widthSpec to be used to measure the RecyclerView.
* @param heightSpec the heightSpec to be used to measure the RecyclerView.
* @param reMeasureEventHandler the EventHandler to invoke in order to trigger a re-measure.
*/
@Override
public synchronized void measure(
Size outSize,
int widthSpec,
int heightSpec,
@Nullable EventHandler<ReMeasureEvent> reMeasureEventHandler) {
final int scrollDirection = mLayoutInfo.getScrollDirection();
switch (scrollDirection) {
case HORIZONTAL:
if (SizeSpec.getMode(widthSpec) == SizeSpec.UNSPECIFIED) {
throw new IllegalStateException(
"Width mode has to be EXACTLY OR AT MOST for an horizontal scrolling RecyclerView");
}
break;
case VERTICAL:
if (SizeSpec.getMode(heightSpec) == SizeSpec.UNSPECIFIED) {
throw new IllegalStateException(
"Height mode has to be EXACTLY OR AT MOST for a vertical scrolling RecyclerView");
}
break;
default:
throw new UnsupportedOperationException(
"The orientation defined by LayoutInfo should be" +
" either OrientationHelper.HORIZONTAL or OrientationHelper.VERTICAL");
}
if (mLastWidthSpec != UNINITIALIZED && !mRequiresRemeasure.get()) {
switch (scrollDirection) {
case VERTICAL:
if (MeasureComparisonUtils.isMeasureSpecCompatible(
mLastWidthSpec,
widthSpec,
mMeasuredSize.width)) {
outSize.width = mMeasuredSize.width;
outSize.height = mWrapContent ? mMeasuredSize.height : SizeSpec.getSize(heightSpec);
return;
}
break;
default:
if (MeasureComparisonUtils.isMeasureSpecCompatible(
mLastHeightSpec,
heightSpec,
mMeasuredSize.height)) {
outSize.width = mWrapContent ? mMeasuredSize.width : SizeSpec.getSize(widthSpec);
outSize.height = mMeasuredSize.height;
return;
}
}
mIsMeasured.set(false);
invalidateLayoutData();
}
// We have never measured before or the measures are not valid so we need to measure now.
mLastWidthSpec = widthSpec;
mLastHeightSpec = heightSpec;
if (!mInsertsWaitingForInitialMeasure.isEmpty() && !mComponentTreeHolders.isEmpty()) {
throw new IllegalStateException(
"One of InsertsWaitingForInitialMeasure or ComponentTreeHolders should be empty!");
}
// We now need to compute the size of the non scrolling side. We try to do this by using the
// calculated range (if we have one) or computing one.
boolean doFillViewportAfterFinishingMeasure = false;
if (mRange == null) {
ComponentTreeHolder holderForRange = null;
if (!mComponentTreeHolders.isEmpty()) {
final int positionToComputeLayout = findFirstComponentPosition(mComponentTreeHolders);
if (mCurrentFirstVisiblePosition < mComponentTreeHolders.size()
&& positionToComputeLayout >= 0) {
holderForRange = mComponentTreeHolders.get(positionToComputeLayout);
}
} else if (!mInsertsWaitingForInitialMeasure.isEmpty()) {
final int positionToComputeLayout =
findFirstAsyncComponentInsert(mInsertsWaitingForInitialMeasure);
if (positionToComputeLayout >= 0) {
holderForRange = mInsertsWaitingForInitialMeasure.get(positionToComputeLayout).mHolder;
}
}
if (holderForRange != null) {
initRange(
SizeSpec.getSize(widthSpec),
SizeSpec.getSize(heightSpec),
holderForRange,
getActualChildrenWidthSpec(holderForRange),
getActualChildrenHeightSpec(holderForRange),
scrollDirection);
doFillViewportAfterFinishingMeasure = true;
}
}
// At this point we might still not have a range. In this situation we should return the best
// size we can detect from the size spec and update it when the first item comes in.
final boolean canMeasure = reMeasureEventHandler != null;
final int measuredWidth;
final int measuredHeight;
switch (scrollDirection) {
case OrientationHelper.VERTICAL:
if (!canMeasure && SizeSpec.getMode(widthSpec) == SizeSpec.UNSPECIFIED) {
throw new IllegalStateException("Can't use Unspecified width on a vertical scrolling " +
"Recycler if dynamic measurement is not allowed");
}
measuredHeight = SizeSpec.getSize(heightSpec);
if (SizeSpec.getMode(widthSpec) == SizeSpec.EXACTLY || !canMeasure) {
measuredWidth = SizeSpec.getSize(widthSpec);
mReMeasureEventEventHandler = mWrapContent ? reMeasureEventHandler : null;
mRequiresRemeasure.set(mWrapContent);
mAsyncInsertsShouldWaitForMeasure = false;
} else if (mRange != null) {
measuredWidth = mRange.measuredSize;
mReMeasureEventEventHandler = mWrapContent ? reMeasureEventHandler : null;
mRequiresRemeasure.set(mWrapContent);
mAsyncInsertsShouldWaitForMeasure = false;
} else {
measuredWidth = 0;
mRequiresRemeasure.set(true);
mReMeasureEventEventHandler = reMeasureEventHandler;
}
break;
case OrientationHelper.HORIZONTAL:
default:
if (!canMeasure && SizeSpec.getMode(heightSpec) == SizeSpec.UNSPECIFIED) {
throw new IllegalStateException("Can't use Unspecified height on an horizontal " +
"scrolling Recycler if dynamic measurement is not allowed");
}
measuredWidth = SizeSpec.getSize(widthSpec);
if (SizeSpec.getMode(heightSpec) == SizeSpec.EXACTLY || !canMeasure) {
measuredHeight = SizeSpec.getSize(heightSpec);
mReMeasureEventEventHandler =
(mHasDynamicItemHeight || mWrapContent) ? reMeasureEventHandler : null;
mRequiresRemeasure.set(mHasDynamicItemHeight || mWrapContent);
mAsyncInsertsShouldWaitForMeasure = false;
} else if (mRange != null) {
measuredHeight = mRange.measuredSize;
mReMeasureEventEventHandler =
(mHasDynamicItemHeight || mWrapContent) ? reMeasureEventHandler : null;
mRequiresRemeasure.set(mHasDynamicItemHeight || mWrapContent);
mAsyncInsertsShouldWaitForMeasure = false;
} else {
measuredHeight = 0;
mRequiresRemeasure.set(true);
mReMeasureEventEventHandler = reMeasureEventHandler;
}
break;
}
final boolean fillListViewport =
doFillViewportAfterFinishingMeasure && !mHasFilledViewport && shouldFillListViewport();
final Size wrapSize = mWrapContent ? new Size() : null;
// If we were in a position to recompute range, we are also in a position to re-fill the
// viewport
if (doFillViewportAfterFinishingMeasure && !mInsertsWaitingForInitialMeasure.isEmpty()) {
fillAdapterWithInitialLayouts(measuredWidth, measuredHeight, wrapSize);
} else if (mWrapContent || fillListViewport) {
fillListViewport(measuredWidth, measuredHeight, wrapSize);
} else if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG,
"("
+ hashCode()
+ ") Not filling viewport from measure - requested: "
+ doFillViewportAfterFinishingMeasure
+ ", supported: "
+ shouldFillListViewport()
+ ", isMainThread: "
+ ThreadUtils.isMainThread());
}
outSize.width = mWrapContent ? wrapSize.width : measuredWidth;
outSize.height = mWrapContent ? wrapSize.height : measuredHeight;
mMeasuredSize = new Size(outSize.width, outSize.height);
mIsMeasured.set(true);
updateAsyncInsertOperations();
if (mRange != null) {
computeRange(mCurrentFirstVisiblePosition, mCurrentLastVisiblePosition);
}
}
private boolean shouldFillListViewport() {
return ComponentsConfiguration.fillListViewport
|| (ComponentsConfiguration.fillListViewportHScrollOnly
&& mLayoutInfo.getScrollDirection() == OrientationHelper.HORIZONTAL);
}
@GuardedBy("this")
private void fillListViewport(int maxWidth, int maxHeight, @Nullable Size outSize) {
ComponentsSystrace.beginSection("fillListViewport");
final int firstVisiblePosition = mLayoutInfo.findFirstVisibleItemPosition();
// NB: This does not handle 1) partially visible items 2) item decorations
final int startIndex =
firstVisiblePosition != RecyclerView.NO_POSITION ? firstVisiblePosition : 0;
computeLayoutsToFillListViewport(
mComponentTreeHolders, startIndex, maxWidth, maxHeight, outSize);
mHasFilledViewport = true;
ComponentsSystrace.endSection();
}
@GuardedBy("this")
private void fillAdapterWithInitialLayouts(int maxWidth, int maxHeight, @Nullable Size outSize) {
ComponentsSystrace.beginSection("fillAdapterWithInitialLayouts");
if (mComponentTreeHolders.size() > 0) {
throw new RuntimeException(
"Should only fill adapter with initial layouts when there are no existing items in adapter!");
}
if (mAsyncInsertsShouldWaitForMeasure) {
throw new IllegalStateException(
"mAsyncInsertsShouldWaitForMeasure must be false to ensure no other inserts are added to those waiting for measure.");
}
final int numInserts = mInsertsWaitingForInitialMeasure.size();
final ArrayList<ComponentTreeHolder> holdersForInsert = new ArrayList<>(numInserts);
for (int i = 0; i < numInserts; i++) {
holdersForInsert.add(mInsertsWaitingForInitialMeasure.get(i).mHolder);
}
final int numComputed =
computeLayoutsToFillListViewport(holdersForInsert, 0, maxWidth, maxHeight, outSize);
if (numComputed > 0) {
maybePostInsertInitialLayoutsIntoAdapter(holdersForInsert.subList(0, numComputed));
}
for (int i = numComputed; i < numInserts; i++) {
startAsyncLayout(mInsertsWaitingForInitialMeasure.get(i));
}
mInsertsWaitingForInitialMeasure.clear();
mHasFilledViewport = true;
ComponentsSystrace.endSection();
}
@GuardedBy("this")
private int computeLayoutsToFillListViewport(
List<ComponentTreeHolder> holders,
int offset,
int maxWidth,
int maxHeight,
@Nullable Size outputSize) {
final LayoutInfo.ViewportFiller filler = mLayoutInfo.createViewportFiller(maxWidth, maxHeight);
if (filler == null) {
return 0;
}
ComponentsSystrace.beginSection("computeLayoutsToFillListViewport");
final int widthSpec = SizeSpec.makeSizeSpec(maxWidth, SizeSpec.EXACTLY);
final int heightSpec = SizeSpec.makeSizeSpec(maxHeight, SizeSpec.EXACTLY);
final Size outSize = new Size();
int numInserted = 0;
int index = offset;
while (filler.wantsMore() && index < holders.size()) {
final ComponentTreeHolder holder = holders.get(index);
final RenderInfo renderInfo = holder.getRenderInfo();
// Bail as soon as we see a View since we can't tell what height it is and don't want to
// layout too much :(
if (renderInfo.rendersView()) {
break;
}
holder.computeLayoutSync(
mComponentContext,
mLayoutInfo.getChildWidthSpec(widthSpec, renderInfo),
mLayoutInfo.getChildHeightSpec(heightSpec, renderInfo),
outSize);
filler.add(renderInfo, outSize.width, outSize.height);
index++;
numInserted++;
}
if (outputSize != null) {
final int fill = filler.getFill();
if (mLayoutInfo.getScrollDirection() == VERTICAL) {
outputSize.width = maxWidth;
outputSize.height = Math.min(fill, maxHeight);
} else {
outputSize.width = Math.min(fill, maxWidth);
outputSize.height = maxHeight;
}
}
ComponentsSystrace.endSection();
if (SectionsDebug.ENABLED) {
Log.d(
SectionsDebug.TAG,
"("
+ hashCode()
+ ") filled viewport with "
+ numInserted
+ " items (holder.size() = "
+ holders.size()
+ ")");
}
return numInserted;
}
private void maybePostInsertInitialLayoutsIntoAdapter(final List<ComponentTreeHolder> toInsert) {
if (ThreadUtils.isMainThread()) {
insertInitialLayoutsIntoAdapter(toInsert);
} else {
mMainThreadHandler.post(
new Runnable() {
@Override
public void run() {
insertInitialLayoutsIntoAdapter(toInsert);
}
});
}
}
private void insertInitialLayoutsIntoAdapter(List<ComponentTreeHolder> toInsert) {
ThreadUtils.assertMainThread();
synchronized (this) {
for (int i = 0, size = toInsert.size(); i < size; i++) {
final ComponentTreeHolder holder = toInsert.get(i);
holder.setInserted(true);
mComponentTreeHolders.add(i, holder);
mInternalAdapter.notifyItemInserted(i);
}
// Computing the initial layouts may have completed one or more batches - update and dispatch
// them
applyReadyBatches();
}
}
@GuardedBy("this")
private void updateAsyncInsertOperations() {
for (AsyncBatch batch : mAsyncBatches) {
updateBatch(batch);
}
if (mCurrentBatch != null) {
updateBatch(mCurrentBatch);
}
}
@GuardedBy("this")
private void updateBatch(AsyncBatch batch) {
for (AsyncOperation operation : batch.mOperations) {
if (!(operation instanceof AsyncInsertOperation)) {
continue;
}
final ComponentTreeHolder holder = ((AsyncInsertOperation) operation).mHolder;
computeLayoutAsync(holder);
}
}
@GuardedBy("this")
private void computeLayoutAsync(ComponentTreeHolder holder) {
// If there's an existing async layout that's compatible, this is a no-op. Otherwise, that
// computation will be canceled (if it hasn't started) and this new one will run.
final int widthSpec = getActualChildrenWidthSpec(holder);
final int heightSpec = getActualChildrenHeightSpec(holder);
holder.computeLayoutAsync(mComponentContext, widthSpec, heightSpec);
}
private static int findFirstComponentPosition(List<ComponentTreeHolder> holders) {
for (int i = 0, size = holders.size(); i < size; i++) {
if (holders.get(i).getRenderInfo().rendersComponent()) {
return i;
}
}
return -1;
}
private static int findFirstAsyncComponentInsert(List<AsyncInsertOperation> operations) {
for (int i = 0, size = operations.size(); i < size; i++) {
final AsyncInsertOperation operation = operations.get(i);
if (operation.mHolder.getRenderInfo().rendersComponent()) {
return i;
}
}
return -1;
}
/**
* Gets the number of items currently in the adapter attached to this binder (i.e. the number of
* items the underlying RecyclerView knows about).
*/
@Override
public int getItemCount() {
return mInternalAdapter.getItemCount();
}
/**
* Insert operation is not supported in case of circular recycler unless it is initial insert
* because the indexes universe gets messed.
*/
private void assertNoInsertOperationIfCircular() {
if (mIsCircular && !mComponentTreeHolders.isEmpty()) {
// Initialization of a list happens using insertRangeAt() or insertAt() operations,
// so skip this check when mComponentTreeHolders was not populated yet
throw new UnsupportedOperationException("Circular lists do not support insert operation");
}
}
/**
* Remove operation is not supported in case of circular recycler unless it's a removal if all
* items because indexes universe gets messed.
*/
@GuardedBy("this")
private void assertNoRemoveOperationIfCircular(int removeCount) {
if (mIsCircular
&& !mComponentTreeHolders.isEmpty()
&& mComponentTreeHolders.size() != removeCount) {
// Allow only removal of all elements in case on notifyDataSetChanged() call
throw new UnsupportedOperationException("Circular lists do not support insert operation");
}
}
@GuardedBy("this")
private void invalidateLayoutData() {
mRange = null;
for (int i = 0, size = mComponentTreeHolders.size(); i < size; i++) {
mComponentTreeHolders.get(i).invalidateTree();
}
// We need to call this as we want to make sure everything is re-bound since we need new sizes
// on all rows.
if (Looper.myLooper() == Looper.getMainLooper()) {
mInternalAdapter.notifyDataSetChanged();
} else {
mMainThreadHandler.removeCallbacks(mNotifyDatasetChangedRunnable);
mMainThreadHandler.post(mNotifyDatasetChangedRunnable);
}
}
/**
* If non-null logId is provided we will log invalid state of the LithoView like height being 0
* while non-0 value was expected and similar other invalid cases.
*/
@UiThread
public void setInvalidStateLogId(String logId) {
mInvalidStateLogId = logId;
}
@GuardedBy("this")
private void initRange(
int width,
int height,
ComponentTreeHolder holder,
int childrenWidthSpec,
int childrenHeightSpec,
int scrollDirection) {
ComponentsSystrace.beginSection("initRange");
try {
final Size size = new Size();
holder.computeLayoutSync(mComponentContext, childrenWidthSpec, childrenHeightSpec, size);
final int rangeSize =
Math.max(mLayoutInfo.approximateRangeSize(size.width, size.height, width, height), 1);
mRange = new RangeCalculationResult();
mRange.measuredSize = scrollDirection == HORIZONTAL ? size.height : size.width;
mRange.estimatedViewportCount = rangeSize;
} finally {
ComponentsSystrace.endSection();
}
}
@GuardedBy("this")
private void resetMeasuredSize(int width) {
// we will set a range anyway if it's null, no need to do this now.
if (mRange == null) {
return;
}
int maxHeight = 0;
for (int i = 0, size = mComponentTreeHolders.size(); i < size; i++) {
final ComponentTreeHolder holder = mComponentTreeHolders.get(i);
final int measuredItemHeight = holder.getMeasuredHeight();
if (measuredItemHeight > maxHeight) {
maxHeight = measuredItemHeight;
}
}
if (maxHeight == mRange.measuredSize) {
return;
}
final int rangeSize =
Math.max(
mLayoutInfo.approximateRangeSize(
SizeSpec.getSize(mLastWidthSpec),
SizeSpec.getSize(mLastHeightSpec),
width,
maxHeight),
1);
mRange.measuredSize = maxHeight;
mRange.estimatedViewportCount = rangeSize;
}
/**
* This should be called when the owner {@link Component}'s onBoundsDefined is called. It will
* inform the binder of the final measured size. The binder might decide to re-compute its
* children layouts if the measures provided here are not compatible with the ones receive in
* onMeasure.
*/
@Override
public synchronized void setSize(int width, int height) {
if (mLastWidthSpec == UNINITIALIZED || !isCompatibleSize(
SizeSpec.makeSizeSpec(width, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(height, SizeSpec.EXACTLY))) {
measure(
sDummySize,
SizeSpec.makeSizeSpec(width, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(height, SizeSpec.EXACTLY),
mReMeasureEventEventHandler);
}
}
/**
* Call from the owning {@link Component}'s onMount. This is where the adapter is assigned to the
* {@link RecyclerView}.
*
* @param view the {@link RecyclerView} being mounted.
*/
@UiThread
@Override
public void mount(RecyclerView view) {
ThreadUtils.assertMainThread();
if (mMountedView == view) {
return;
}
if (mMountedView != null) {
unmount(mMountedView);
}
mMountedView = view;
final LayoutManager layoutManager = mLayoutInfo.getLayoutManager();
view.setLayoutManager(layoutManager);
if (ComponentsConfiguration.enableSwapAdapter) {
view.swapAdapter(mInternalAdapter, false);
} else {
view.setAdapter(mInternalAdapter);
}
view.addOnScrollListener(mRangeScrollListener);
view.addOnScrollListener(mViewportManager.getScrollListener());
mLayoutInfo.setRenderInfoCollection(this);
mViewportManager.addViewportChangedListener(mViewportChangedListener);
if (mCurrentFirstVisiblePosition != RecyclerView.NO_POSITION &&
mCurrentFirstVisiblePosition >= 0) {
if (layoutManager instanceof LinearLayoutManager) {
((LinearLayoutManager) layoutManager)
.scrollToPositionWithOffset(mCurrentFirstVisiblePosition, mCurrentOffset);
} else {
view.scrollToPosition(mCurrentFirstVisiblePosition);
}
} else if (mIsCircular) {
// Initialize circular RecyclerView position
final int jumpToMiddle = Integer.MAX_VALUE / 2;
final int offsetFirstItem =
mComponentTreeHolders.isEmpty() ? 0 : jumpToMiddle % mComponentTreeHolders.size();
view.scrollToPosition(jumpToMiddle - offsetFirstItem);
}
enableStickyHeader(mMountedView);
}
private void enableStickyHeader(RecyclerView recyclerView) {
if (mIsCircular) {
Log.w(TAG, "Sticky header is not supported for circular RecyclerViews");
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// Sticky header needs view translation APIs which are not available in Gingerbread and below.
Log.w(TAG, "Sticky header is supported only on ICS (API14) and above");
return;
}
if (recyclerView == null) {
return;
}
SectionsRecyclerView sectionsRecycler = SectionsRecyclerView.getParentRecycler(recyclerView);
if (sectionsRecycler == null) {
return;
}
if (mStickyHeaderController == null) {
mStickyHeaderController = new StickyHeaderController(this);
}
mStickyHeaderController.init(sectionsRecycler);
}
/**
* Call from the owning {@link Component}'s onUnmount. This is where the adapter is removed from
* the {@link RecyclerView}.
*
* @param view the {@link RecyclerView} being unmounted.
*/
@UiThread
@Override
public void unmount(RecyclerView view) {
ThreadUtils.assertMainThread();
final LayoutManager layoutManager = mLayoutInfo.getLayoutManager();
final View firstView = layoutManager.findViewByPosition(mCurrentFirstVisiblePosition);
if (firstView != null) {
final boolean reverseLayout;
if (layoutManager instanceof LinearLayoutManager) {
reverseLayout = ((LinearLayoutManager) layoutManager).getReverseLayout();
} else {
reverseLayout = false;
}
if (mLayoutInfo.getScrollDirection() == HORIZONTAL) {
mCurrentOffset =
reverseLayout
? view.getWidth()
- layoutManager.getPaddingRight()
- layoutManager.getDecoratedRight(firstView)
: layoutManager.getDecoratedLeft(firstView) - layoutManager.getPaddingLeft();
} else {
mCurrentOffset =
reverseLayout
? view.getHeight()
- layoutManager.getPaddingBottom()
- layoutManager.getDecoratedBottom(firstView)
: layoutManager.getDecoratedTop(firstView) - layoutManager.getPaddingTop();
}
} else {
mCurrentOffset = 0;
}
view.removeOnScrollListener(mRangeScrollListener);
view.removeOnScrollListener(mViewportManager.getScrollListener());
if (ComponentsConfiguration.enableSwapAdapter) {
view.swapAdapter(null, false);
} else {
view.setAdapter(null);
}
view.setLayoutManager(null);
mViewportManager.removeViewportChangedListener(mViewportChangedListener);
// We might have already unmounted this view when calling mount with a different view. In this
// case we can just return here.
if (mMountedView != view) {
return;
}
mMountedView = null;
if (mStickyHeaderController != null) {
mStickyHeaderController.reset();
}
mLayoutInfo.setRenderInfoCollection(null);
}
@UiThread
public void scrollToPosition(int position, boolean smoothScroll) {
if (mMountedView == null) {
mCurrentFirstVisiblePosition = position;
return;
}
if (smoothScroll) {
mMountedView.smoothScrollToPosition(position);
} else {
mMountedView.scrollToPosition(position);
}
}
@UiThread
public void scrollToPositionWithOffset(int position, int offset) {
if (mMountedView == null || !(mMountedView.getLayoutManager() instanceof LinearLayoutManager)) {
mCurrentFirstVisiblePosition = position;
mCurrentOffset = offset;
return;
}
((LinearLayoutManager) mMountedView.getLayoutManager()).scrollToPositionWithOffset(
position,
offset);
}
@GuardedBy("this")
private boolean isCompatibleSize(int widthSpec, int heightSpec) {
final int scrollDirection = mLayoutInfo.getScrollDirection();
if (mLastWidthSpec != UNINITIALIZED) {
switch (scrollDirection) {
case HORIZONTAL:
return isMeasureSpecCompatible(
mLastHeightSpec,
heightSpec,
mMeasuredSize.height);
case VERTICAL:
return isMeasureSpecCompatible(
mLastWidthSpec,
widthSpec,
mMeasuredSize.width);
}
}
return false;
}
@Override
public int findFirstVisibleItemPosition() {
return mLayoutInfo.findFirstVisibleItemPosition();
}
@Override
public int findFirstFullyVisibleItemPosition() {
return mLayoutInfo.findFirstFullyVisibleItemPosition();
}
@Override
public int findLastVisibleItemPosition() {
return mLayoutInfo.findLastVisibleItemPosition();
}
@Override
public int findLastFullyVisibleItemPosition() {
return mLayoutInfo.findLastFullyVisibleItemPosition();
}
@Override
@UiThread
@GuardedBy("this")
public boolean isSticky(int position) {
return mComponentTreeHolders.get(position).getRenderInfo().isSticky();
}
@Override
@UiThread
@GuardedBy("this")
public boolean isValidPosition(int position) {
return position >= 0 && position < mComponentTreeHolders.size();
}
private static class RangeCalculationResult {
// The estimated number of items needed to fill the viewport.
private int estimatedViewportCount;
// The size computed for the first Component.
private int measuredSize;
}
@Override
@UiThread
public void setViewportChangedListener(@Nullable ViewportChanged viewportChangedListener) {
mViewportManager.addViewportChangedListener(viewportChangedListener);
}
@VisibleForTesting
void onNewVisibleRange(int firstVisiblePosition, int lastVisiblePosition) {
mCurrentFirstVisiblePosition = firstVisiblePosition;
mCurrentLastVisiblePosition = lastVisiblePosition;
mViewportManager.resetShouldUpdate();
maybePostUpdateViewportAndComputeRange();
}
@VisibleForTesting
void onNewWorkingRange(
int firstVisibleIndex,
int lastVisibleIndex,
int firstFullyVisibleIndex,
int lastFullyVisibleIndex) {
if (mRange == null
|| firstVisibleIndex == RecyclerView.NO_POSITION
|| lastVisibleIndex == RecyclerView.NO_POSITION) {
return;
}
final int rangeSize =
Math.max(mRange.estimatedViewportCount, lastVisibleIndex - firstVisibleIndex);
final int layoutRangeSize = (int) (rangeSize * mRangeRatio);
final int rangeStart = Math.max(0, firstVisibleIndex - layoutRangeSize);
final int rangeEnd =
Math.min(firstVisibleIndex + rangeSize + layoutRangeSize, mComponentTreeHolders.size() - 1);
for (int position = rangeStart; position <= rangeEnd; position++) {
final ComponentTreeHolder holder = mComponentTreeHolders.get(position);
holder.checkWorkingRangeAndDispatch(
position,
firstVisibleIndex,
lastVisibleIndex,
firstFullyVisibleIndex,
lastFullyVisibleIndex);
}
}
private void maybePostUpdateViewportAndComputeRange() {
if (mMountedView != null
&& (ComponentsConfiguration.insertPostAsyncLayout
|| mViewportManager.shouldUpdate())) {
mPostUpdateViewportAndComputeRangeAttempts = 0;
mMountedView.removeCallbacks(mUpdateViewportAndComputeRangeRunnable);
ViewCompat.postOnAnimation(mMountedView, mUpdateViewportAndComputeRangeRunnable);
} else {
computeRange(mCurrentFirstVisiblePosition, mCurrentLastVisiblePosition);
}
}
private void computeRange(int firstVisible, int lastVisible) {
final int rangeSize;
final int rangeStart;
final int rangeEnd;
final int treeHoldersSize;
synchronized (this) {
if (!mIsMeasured.get() || mRange == null) {
return;
}
if (firstVisible == RecyclerView.NO_POSITION || lastVisible == RecyclerView.NO_POSITION) {
firstVisible = lastVisible = 0;
}
rangeSize = Math.max(mRange.estimatedViewportCount, lastVisible - firstVisible);
rangeStart = firstVisible - (int) (rangeSize * mRangeRatio);
rangeEnd = firstVisible + rangeSize + (int) (rangeSize * mRangeRatio);
treeHoldersSize = mComponentTreeHolders.size();
}
computeRangeLayout(treeHoldersSize, rangeStart, rangeEnd, mIsCircular);
}
private void computeRangeLayout(
int treeHoldersSize, int rangeStart, int rangeEnd, boolean ignoreRange) {
// TODO 16212153 optimize computeRange loop.
for (int i = 0; i < treeHoldersSize; i++) {
final ComponentTreeHolder holder;
final int childrenWidthSpec, childrenHeightSpec;
synchronized (this) {
// Someone modified the ComponentsTreeHolders while we were computing this range. We
// can just bail as another range will be computed.
if (treeHoldersSize != mComponentTreeHolders.size()) {
return;
}
holder = mComponentTreeHolders.get(i);
if (holder.getRenderInfo().rendersView()) {
continue;
}
childrenWidthSpec = getActualChildrenWidthSpec(holder);
childrenHeightSpec = getActualChildrenHeightSpec(holder);
}
if (ignoreRange) {
if (!holder.isTreeValid()) {
holder.computeLayoutAsync(mComponentContext, childrenWidthSpec, childrenHeightSpec);
}
} else {
if (i >= rangeStart && i <= rangeEnd) {
if (!holder.isTreeValid()) {
holder.computeLayoutAsync(mComponentContext, childrenWidthSpec, childrenHeightSpec);
}
} else if (holder.isTreeValid()
&& !holder.getRenderInfo().isSticky()
&& (holder.getComponentTree() != null
&& holder.getComponentTree().getLithoView() == null)) {
holder.acquireStateAndReleaseTree();
}
}
}
}
@VisibleForTesting
@Nullable
RangeCalculationResult getRangeCalculationResult() {
return mRange;
}
@GuardedBy("this")
private int getActualChildrenWidthSpec(final ComponentTreeHolder treeHolder) {
if (mIsMeasured.get() && !mRequiresRemeasure.get()) {
return mLayoutInfo.getChildWidthSpec(
SizeSpec.makeSizeSpec(mMeasuredSize.width, SizeSpec.EXACTLY),
treeHolder.getRenderInfo());
}
return mLayoutInfo.getChildWidthSpec(mLastWidthSpec, treeHolder.getRenderInfo());
}
@GuardedBy("this")
private int getActualChildrenHeightSpec(final ComponentTreeHolder treeHolder) {
if (mHasDynamicItemHeight) {
return SizeSpec.UNSPECIFIED;
}
if (mIsMeasured.get() && !mRequiresRemeasure.get()) {
return mLayoutInfo.getChildHeightSpec(
SizeSpec.makeSizeSpec(mMeasuredSize.height, SizeSpec.EXACTLY),
treeHolder.getRenderInfo());
}
return mLayoutInfo.getChildHeightSpec(mLastHeightSpec, treeHolder.getRenderInfo());
}
private AsyncInsertOperation createAsyncInsertOperation(int position, RenderInfo renderInfo) {
final ComponentTreeHolder holder = createComponentTreeHolder(renderInfo);
holder.setInserted(false);
return new AsyncInsertOperation(position, holder);
}
/** Async operation types. */
@IntDef({Operation.INSERT, Operation.REMOVE, Operation.REMOVE_RANGE, Operation.MOVE})
@Retention(RetentionPolicy.SOURCE)
private @interface Operation {
int INSERT = 0;
int REMOVE = 1;
int REMOVE_RANGE = 2;
int MOVE = 3;
}
/** An operation received from one of the *Async methods, pending execution. */
private abstract static class AsyncOperation {
private final int mOperation;
public AsyncOperation(int operation) {
mOperation = operation;
}
}
private static final class AsyncInsertOperation extends AsyncOperation {
private final int mPosition;
private final ComponentTreeHolder mHolder;
public AsyncInsertOperation(int position, ComponentTreeHolder holder) {
super(Operation.INSERT);
mPosition = position;
mHolder = holder;
}
}
private static final class AsyncRemoveOperation extends AsyncOperation {
private final int mPosition;
public AsyncRemoveOperation(int position) {
super(Operation.REMOVE);
mPosition = position;
}
}
private static final class AsyncRemoveRangeOperation extends AsyncOperation {
private final int mPosition;
private final int mCount;
public AsyncRemoveRangeOperation(int position, int count) {
super(Operation.REMOVE_RANGE);
mPosition = position;
mCount = count;
}
}
private static final class AsyncMoveOperation extends AsyncOperation {
private final int mFromPosition;
private final int mToPosition;
public AsyncMoveOperation(int fromPosition, int toPosition) {
super(Operation.MOVE);
mFromPosition = fromPosition;
mToPosition = toPosition;
}
}
/**
* A batch of {@link AsyncOperation}s that should be applied all at once. The OnDataBoundListener
* should be called once all these operations are applied.
*/
private static final class AsyncBatch {
private final ArrayList<AsyncOperation> mOperations = new ArrayList<>();
private @Nullable OnDataBoundListener mOnDataBoundListener;
}
private class RangeScrollListener extends RecyclerView.OnScrollListener {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (mCanPrefetchDisplayLists) {
DisplayListUtils.prefetchDisplayLists(recyclerView);
}
}
}
private static class BaseViewHolder extends RecyclerView.ViewHolder {
private final boolean isLithoViewType;
@Nullable private ViewBinder viewBinder;
public BaseViewHolder(View view, boolean isLithoViewType) {
super(view);
this.isLithoViewType = isLithoViewType;
}
}
private class InternalAdapter extends RecyclerView.Adapter<BaseViewHolder> {
@Override
public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final ViewCreator viewCreator = mRenderInfoViewCreatorController.getViewCreator(viewType);
if (viewCreator != null) {
final View view = viewCreator.createView(mComponentContext, parent);
return new BaseViewHolder(view, false);
} else {
final LithoView lithoView =
mLithoViewFactory == null
? new LithoView(mComponentContext, null)
: mLithoViewFactory.createLithoView(mComponentContext);
return new BaseViewHolder(lithoView, true);
}
}
@Override
@GuardedBy("RecyclerBinder.this")
public void onBindViewHolder(BaseViewHolder holder, int position) {
final int normalizedPosition = getNormalizedPosition(position);
// We can ignore the synchronization here. We'll only add to this from the UiThread.
// This read only happens on the UiThread as well and we are never writing this here.
final ComponentTreeHolder componentTreeHolder = mComponentTreeHolders.get(normalizedPosition);
final RenderInfo renderInfo = componentTreeHolder.getRenderInfo();
if (renderInfo.rendersComponent()) {
final LithoView lithoView = (LithoView) holder.itemView;
lithoView.setInvalidStateLogId(mInvalidStateLogId);
final int childrenWidthSpec = getActualChildrenWidthSpec(componentTreeHolder);
final int childrenHeightSpec = getActualChildrenHeightSpec(componentTreeHolder);
if (!componentTreeHolder.isTreeValid()) {
componentTreeHolder.computeLayoutSync(
mComponentContext, childrenWidthSpec, childrenHeightSpec, null);
}
final boolean isOrientationVertical =
mLayoutInfo.getScrollDirection() == OrientationHelper.VERTICAL;
final int width;
final int height;
if (SizeSpec.getMode(childrenWidthSpec) == SizeSpec.EXACTLY) {
width = SizeSpec.getSize(childrenWidthSpec);
} else if (isOrientationVertical) {
width = MATCH_PARENT;
} else {
width = WRAP_CONTENT;
}
if (SizeSpec.getMode(childrenHeightSpec) == SizeSpec.EXACTLY) {
height = SizeSpec.getSize(childrenHeightSpec);
} else if (isOrientationVertical) {
height = WRAP_CONTENT;
} else {
height = MATCH_PARENT;
}
final RecyclerViewLayoutManagerOverrideParams layoutParams =
new RecyclerViewLayoutManagerOverrideParams(
width, height, childrenWidthSpec, childrenHeightSpec, renderInfo.isFullSpan());
lithoView.setLayoutParams(layoutParams);
lithoView.setComponentTree(componentTreeHolder.getComponentTree());
if (componentTreeHolder.getRenderInfo().getRenderCompleteEventHandler() != null
&& componentTreeHolder.getRenderState() == RENDER_UNINITIALIZED) {
lithoView.setOnPostDrawListener(
new LithoView.OnPostDrawListener() {
@Override
public void onPostDraw() {
notifyItemRenderCompleteAt(normalizedPosition, SystemClock.uptimeMillis());
lithoView.setOnPostDrawListener(null);
}
});
}
} else {
final ViewBinder viewBinder = renderInfo.getViewBinder();
holder.viewBinder = viewBinder;
viewBinder.bind(holder.itemView);
}
}
@Override
@GuardedBy("RecyclerBinder.this")
public int getItemViewType(int position) {
final RenderInfo renderInfo =
mComponentTreeHolders.get(getNormalizedPosition(position)).getRenderInfo();
if (renderInfo.rendersComponent()) {
// Special value for LithoViews
return mRenderInfoViewCreatorController.getComponentViewType();
} else {
return renderInfo.getViewType();
}
}
@Override
@GuardedBy("RecyclerBinder.this")
public int getItemCount() {
// We can ignore the synchronization here. We'll only add to this from the UiThread.
// This read only happens on the UiThread as well and we are never writing this here.
// If the recycler is circular, we have to simulate having an infinite number of items in the
// adapter by returning Integer.MAX_VALUE.
return mIsCircular ? Integer.MAX_VALUE : mComponentTreeHolders.size();
}
@Override
public void onViewRecycled(BaseViewHolder holder) {
if (holder.isLithoViewType) {
final LithoView lithoView = (LithoView) holder.itemView;
lithoView.unmountAllItems();
lithoView.setComponentTree(null);
lithoView.setInvalidStateLogId(null);
} else {
final ViewBinder viewBinder = holder.viewBinder;
if (viewBinder != null) {
viewBinder.unbind(holder.itemView);
holder.viewBinder = null;
}
}
}
}
/**
* If the recycler is circular, returns the position of the {@link ComponentTreeHolder} that is
* used to render the item at given position. Otherwise, it returns the position passed as
* parameter, which is the same as the index of the {@link ComponentTreeHolder}.
*/
@GuardedBy("this")
private int getNormalizedPosition(int position) {
return mIsCircular ? position % mComponentTreeHolders.size() : position;
}
public static class RecyclerViewLayoutManagerOverrideParams extends RecyclerView.LayoutParams
implements LithoView.LayoutManagerOverrideParams {
private final int mWidthMeasureSpec;
private final int mHeightMeasureSpec;
private final boolean mIsFullSpan;
private RecyclerViewLayoutManagerOverrideParams(
int width,
int height,
int overrideWidthMeasureSpec,
int overrideHeightMeasureSpec,
boolean isFullSpan) {
super(width, height);
mWidthMeasureSpec = overrideWidthMeasureSpec;
mHeightMeasureSpec = overrideHeightMeasureSpec;
mIsFullSpan = isFullSpan;
}
@Override
public int getWidthMeasureSpec() {
return mWidthMeasureSpec;
}
@Override
public int getHeightMeasureSpec() {
return mHeightMeasureSpec;
}
public boolean isFullSpan() {
return mIsFullSpan;
}
}
private ComponentTreeHolder createComponentTreeHolder(RenderInfo renderInfo) {
return mComponentTreeHolderFactory.create(
renderInfo,
mLayoutHandlerFactory != null
? mLayoutHandlerFactory.createLayoutCalculationHandler(renderInfo)
: null,
mCanPrefetchDisplayLists,
mCanCacheDrawingDisplayLists,
mHasDynamicItemHeight ? mComponentTreeMeasureListenerFactory : null,
mSplitLayoutTag);
}
}
|
Set mHasAsyncOperations for asyncMove/remove/removeRangeAt
Summary: These should have been set
Reviewed By: pasqualeanatriello
Differential Revision: D8379277
fbshipit-source-id: fdef24b70267bb9bdbe7fe48f483f489b8bb6af1
|
litho-widget/src/main/java/com/facebook/litho/widget/RecyclerBinder.java
|
Set mHasAsyncOperations for asyncMove/remove/removeRangeAt
|
<ide><path>itho-widget/src/main/java/com/facebook/litho/widget/RecyclerBinder.java
<ide>
<ide> final AsyncMoveOperation operation = new AsyncMoveOperation(fromPosition, toPosition);
<ide> synchronized (this) {
<add> mHasAsyncOperations = true;
<add>
<ide> mAsyncComponentTreeHolders.add(toPosition, mAsyncComponentTreeHolders.remove(fromPosition));
<ide>
<ide> // TODO(t28619782): When moving a CT into range, do an async prepare
<ide>
<ide> final AsyncRemoveOperation asyncRemoveOperation = new AsyncRemoveOperation(position);
<ide> synchronized (this) {
<add> mHasAsyncOperations = true;
<add>
<ide> mAsyncComponentTreeHolders.remove(position);
<ide> addToCurrentBatch(asyncRemoveOperation);
<ide> }
<ide>
<ide> final AsyncRemoveRangeOperation operation = new AsyncRemoveRangeOperation(position, count);
<ide> synchronized (this) {
<add> mHasAsyncOperations = true;
<add>
<ide> for (int i = 0; i < count; i++) {
<ide> // TODO(t28712163): Cancel pending layouts for async inserts
<ide> mAsyncComponentTreeHolders.remove(position);
|
|
Java
|
apache-2.0
|
159bb5f57b2bb0e8e95a0f720e85d69e2049ed40
| 0 |
psadusumilli/solr,cnfire/solr,minted/solr,MichaelMaGG/solr,minted/solr,Vam85/solr,Vam85/solr,psadusumilli/solr,Vam85/solr,cnfire/solr,MichaelMaGG/solr,minted/solr,psadusumilli/solr,minted/solr,MetSystem/solr,cnfire/solr,lzo/solr,MetSystem/solr,Vam85/solr,psadusumilli/solr,lzo/solr,MichaelMaGG/solr,MetSystem/solr,MetSystem/solr,RaoPisay/solr,lzo/solr,MichaelMaGG/solr,cnfire/solr,lzo/solr,RaoPisay/solr,RaoPisay/solr
|
/**
* Copyright 2006 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.request;
import org.apache.solr.core.SolrCore;
import org.apache.solr.core.SolrInfoMBean;
import org.apache.solr.core.SolrException;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.search.DocList;
import org.apache.solr.search.DocSet;
import org.apache.solr.search.DocListAndSet;
import org.apache.solr.search.SolrQueryParser;
import org.apache.solr.search.QueryParsing;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrQueryResponse;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.util.NamedList;
import org.apache.solr.util.HighlightingUtils;
import org.apache.solr.util.SolrPluginUtils;
import org.apache.solr.util.DisMaxParams;
import static org.apache.solr.request.SolrParams.*;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.queryParser.QueryParser;
/* this is the standard logging framework for Solr */
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.net.URL;
/**
* <p>
* A Generic query plugin designed to be given a simple query expression
* from a user, which it will then query against a variety of
* pre-configured fields, in a variety of ways, using BooleanQueries,
* DisjunctionMaxQueries, and PhraseQueries.
* </p>
*
* <p>
* All of the following options may be configured for this plugin
* in the solrconfig as defaults, and may be overriden as request parameters
* </p>
*
* <ul>
* <li>tie - (Tie breaker) float value to use as tiebreaker in
* DisjunctionMaxQueries (should be something much less than 1)
* </li>
* <li> qf - (Query Fields) fields and boosts to use when building
* DisjunctionMaxQueries from the users query. Format is:
* "<code>fieldA^1.0 fieldB^2.2</code>".
* </li>
* <li> mm - (Minimum Match) this supports a wide variety of
* complex expressions.
* read {@link SolrPluginUtils#setMinShouldMatch SolrPluginUtils.setMinShouldMatch} for full details.
* </li>
* <li> pf - (Phrase Fields) fields/boosts to make phrase queries out
* of, to boost the users query for exact matches on the specified fields.
* Format is: "<code>fieldA^1.0 fieldB^2.2</code>".
* </li>
* <li> ps - (Phrase Slop) amount of slop on phrase queries built for pf
* fields.
* </li>
* <li> bq - (Boost Query) a raw lucene query that will be included in the
* users query to influence the score. If this is a BooleanQuery
* with a default boost (1.0f), then the individual clauses will be
* added directly to the main query. Otherwise, the query will be
* included as is.
* </li>
* <li> bf - (Boost Functions) functions (with optional boosts) that will be
* included in the users query to influence the score.
* Format is: "<code>funcA(arg1,arg2)^1.2
* funcB(arg3,arg4)^2.2</code>". NOTE: Whitespace is not allowed
* in the function arguments.
* </li>
* <li> fq - (Filter Query) a raw lucene query that can be used
* to restrict the super set of products we are interested in - more
* efficient then using bq, but doesn't influence score.
* This param can be specified multiple times, and the filters
* are additive.
* </li>
* </ul>
*
* <p>
* The following options are only available as request params...
* </p>
*
* <ul>
* <li> q - (Query) the raw unparsed, unescaped, query from the user.
* </li>
* <li>sort - (Order By) list of fields and direction to sort on.
* </li>
* </ul>
*
* <pre>
* :TODO: document facet param support
*
* :TODO: make bf,pf,qf multival params now that SolrParams supports them
* </pre>
*/
public class DisMaxRequestHandler
implements SolrRequestHandler, SolrInfoMBean {
/**
* A field we can't ever find in any schema, so we can safely tell
* DisjunctionMaxQueryParser to use it as our defaultField, and
* map aliases from it to any field in our schema.
*/
private static String IMPOSSIBLE_FIELD_NAME = "\uFFFC\uFFFC\uFFFC";
// statistics
// TODO: should we bother synchronizing these, or is an off-by-one error
// acceptable every million requests or so?
long numRequests;
long numErrors;
SolrParams defaults;
SolrParams appends;
SolrParams invariants;
/** shorten the class references for utilities */
private static class U extends SolrPluginUtils {
/* :NOOP */
}
/** shorten the class references for utilities */
private static class DMP extends DisMaxParams {
/* :NOOP */
}
public DisMaxRequestHandler() {
super();
}
/* returns URLs to the Wiki pages */
public URL[] getDocs() {
/* :TODO: need docs */
return new URL[0];
}
public String getName() {
return this.getClass().getName();
}
public NamedList getStatistics() {
NamedList lst = new NamedList();
lst.add("requests", numRequests);
lst.add("errors", numErrors);
return lst;
}
public String getVersion() {
return "$Revision:$";
}
public String getDescription() {
return "DisjunctionMax Request Handler: Does relevancy based queries "
+ "accross a variety of fields using configured boosts";
}
public Category getCategory() {
return Category.QUERYHANDLER;
}
public String getSourceId() {
return "$Id:$";
}
public String getSource() {
return "$URL:$";
}
/** sets the default variables for any usefull info it finds in the config
* if a config option is not inthe format expected, logs an warning
* and ignores it..
*/
public void init(NamedList args) {
if (-1 == args.indexOf("defaults",0)) {
// no explict defaults list, use all args implicitly
// indexOf so "<null name="defaults"/> is valid indicator of no defaults
defaults = SolrParams.toSolrParams(args);
} else {
Object o = args.get("defaults");
if (o != null && o instanceof NamedList) {
defaults = SolrParams.toSolrParams((NamedList)o);
}
o = args.get("appends");
if (o != null && o instanceof NamedList) {
appends = SolrParams.toSolrParams((NamedList)o);
}
o = args.get("invariants");
if (o != null && o instanceof NamedList) {
invariants = SolrParams.toSolrParams((NamedList)o);
}
}
}
public void handleRequest(SolrQueryRequest req, SolrQueryResponse rsp) {
numRequests++;
try {
U.setDefaults(req,defaults,appends,invariants);
SolrParams params = req.getParams();
int flags = 0;
SolrIndexSearcher s = req.getSearcher();
IndexSchema schema = req.getSchema();
Map<String,Float> queryFields = U.parseFieldBoosts(params.get(DMP.QF));
Map<String,Float> phraseFields = U.parseFieldBoosts(params.get(DMP.PF));
float tiebreaker = params.getFloat(DMP.TIE, 0.0f);
int pslop = params.getInt(DMP.PS, 0);
/* a generic parser for parsing regular lucene queries */
QueryParser p = new SolrQueryParser(schema, null);
/* a parser for dealing with user input, which will convert
* things to DisjunctionMaxQueries
*/
U.DisjunctionMaxQueryParser up =
new U.DisjunctionMaxQueryParser(schema, IMPOSSIBLE_FIELD_NAME);
up.addAlias(IMPOSSIBLE_FIELD_NAME,
tiebreaker, queryFields);
/* for parsing slopy phrases using DisjunctionMaxQueries */
U.DisjunctionMaxQueryParser pp =
new U.DisjunctionMaxQueryParser(schema, IMPOSSIBLE_FIELD_NAME);
pp.addAlias(IMPOSSIBLE_FIELD_NAME,
tiebreaker, phraseFields);
pp.setPhraseSlop(pslop);
/* * * Main User Query * * */
String userQuery = U.partialEscape
(U.stripUnbalancedQuotes(params.get(Q))).toString();
/* the main query we will execute. we disable the coord because
* this query is an artificial construct
*/
BooleanQuery query = new BooleanQuery(true);
String minShouldMatch = params.get(DMP.MM, "100%");
Query dis = up.parse(userQuery);
if (dis instanceof BooleanQuery) {
BooleanQuery t = new BooleanQuery();
U.flattenBooleanQuery(t, (BooleanQuery)dis);
U.setMinShouldMatch(t, minShouldMatch);
query.add(t, Occur.MUST);
} else {
query.add(dis, Occur.MUST);
}
/* * * Add on Phrases for the Query * * */
/* build up phrase boosting queries */
/* if the userQuery already has some quotes, stip them out.
* we've already done the phrases they asked for in the main
* part of the query, this is to boost docs that may not have
* matched those phrases but do match looser phrases.
*/
String userPhraseQuery = userQuery.replace("\"","");
Query phrase = pp.parse("\"" + userPhraseQuery + "\"");
if (null != phrase) {
query.add(phrase, Occur.SHOULD);
}
/* * * Boosting Query * * */
String boostQuery = params.get(DMP.BQ);
if (null != boostQuery && !boostQuery.equals("")) {
Query tmp = p.parse(boostQuery);
/* if the default boost was used, and we've got a BooleanQuery
* extract the subqueries out and use them directly
*/
if (1.0f == tmp.getBoost() && tmp instanceof BooleanQuery) {
for (BooleanClause c : ((BooleanQuery)tmp).getClauses()) {
query.add(c);
}
} else {
query.add(tmp, BooleanClause.Occur.SHOULD);
}
}
/* * * Boosting Functions * * */
String boostFunc = params.get(DMP.BF);
if (null != boostFunc && !boostFunc.equals("")) {
List<Query> funcs = U.parseFuncs(schema, boostFunc);
for (Query f : funcs) {
query.add(f, Occur.SHOULD);
}
}
/* * * Restrict Results * * */
List<Query> restrictions = U.parseFilterQueries(req);
/* * * Generate Main Results * * */
flags |= U.setReturnFields(req,rsp);
DocListAndSet results = new DocListAndSet();
NamedList facetInfo = null;
if (params.getBool(FACET,false)) {
results = s.getDocListAndSet(query, restrictions,
SolrPluginUtils.getSort(req),
req.getStart(), req.getLimit(),
flags);
facetInfo = getFacetInfo(req, rsp, results.docSet);
} else {
results.docList = s.getDocList(query, restrictions,
SolrPluginUtils.getSort(req),
req.getStart(), req.getLimit(),
flags);
}
rsp.add("search-results",results.docList);
if (null != facetInfo) rsp.add("facet_counts", facetInfo);
/* * * Debugging Info * * */
try {
NamedList debug = U.doStandardDebug(req, userQuery, query, results.docList);
if (null != debug) {
debug.add("boostquery", boostQuery);
debug.add("boostfunc", boostFunc);
if (null != restrictions) {
debug.add("filter_queries", params.getParams(FQ));
List<String> fqs = new ArrayList<String>(restrictions.size());
for (Query fq : restrictions) {
fqs.add(QueryParsing.toString(fq, req.getSchema()));
}
debug.add("parsed_filter_queries",fqs);
}
rsp.add("debug", debug);
}
} catch (Exception e) {
SolrException.logOnce(SolrCore.log,
"Exception durring debug", e);
rsp.add("exception_during_debug", SolrException.toStr(e));
}
/* * * Highlighting/Summarizing * * */
if(HighlightingUtils.isHighlightingEnabled(req)) {
BooleanQuery highlightQuery = new BooleanQuery();
U.flattenBooleanQuery(highlightQuery, query);
String[] highFields = queryFields.keySet().toArray(new String[0]);
NamedList sumData =
HighlightingUtils.doHighlighting(results.docList, highlightQuery,
req, highFields);
if(sumData != null)
rsp.add("highlighting", sumData);
}
} catch (Exception e) {
SolrException.log(SolrCore.log,e);
rsp.setException(e);
numErrors++;
}
}
/**
* Fetches information about Facets for this request.
*
* Subclasses may with to override this method to provide more
* advanced faceting behavior.
* @see SimpleFacets#getFacetCounts
*/
protected NamedList getFacetInfo(SolrQueryRequest req,
SolrQueryResponse rsp,
DocSet mainSet) {
SimpleFacets f = new SimpleFacets(req.getSearcher(),
mainSet,
req.getParams());
return f.getFacetCounts();
}
}
|
src/java/org/apache/solr/request/DisMaxRequestHandler.java
|
/**
* Copyright 2006 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.request;
import org.apache.solr.core.SolrCore;
import org.apache.solr.core.SolrInfoMBean;
import org.apache.solr.core.SolrException;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.search.DocList;
import org.apache.solr.search.DocSet;
import org.apache.solr.search.DocListAndSet;
import org.apache.solr.search.SolrQueryParser;
import org.apache.solr.search.QueryParsing;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrQueryResponse;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.util.NamedList;
import org.apache.solr.util.HighlightingUtils;
import org.apache.solr.util.SolrPluginUtils;
import org.apache.solr.util.DisMaxParams;
import static org.apache.solr.request.SolrParams.*;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.queryParser.QueryParser;
/* this is the standard logging framework for Solr */
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.net.URL;
/**
* <p>
* A Generic query plugin designed to be given a simple query expression
* from a user, which it will then query agaisnt a variety of
* pre-configured fields, in a variety of ways, using BooleanQueries,
* DisjunctionMaxQueries, and PhraseQueries.
* </p>
*
* <p>
* All of the following options may be configured for this plugin
* in the solrconfig as defaults, and may be overriden as request parameters
* </p>
*
* <ul>
* <li>tie - (Tie breaker) float value to use as tiebreaker in
* DisjunctionMaxQueries (should be something much less then 1)
* </li>
* <li> qf - (Query Fields) fields and boosts to use when building
* DisjunctionMaxQueries from the users query. Format is:
* "<code>fieldA^1.0 fieldB^2.2</code>".
* </li>
* <li> mm - (Minimum Match) this supports a wide variety of
* complex expressions.
* read {@link SolrPluginUtils#setMinShouldMatch SolrPluginUtils.setMinShouldMatch} for full details.
* </li>
* <li> pf - (Phrase Fields) fields/boosts to make phrase queries out
* of to boost
* the users query for exact matches on the specified fields.
* Format is: "<code>fieldA^1.0 fieldB^2.2</code>".
* </li>
* <li> ps - (Phrase Slop) amount of slop on phrase queries built for pf
* fields.
* </li>
* <li> bq - (Boost Query) a raw lucene query that will be included in the
* users query to influcene the score. If this is a BooleanQuery
* with a default boost (1.0f) then the individual clauses will be
* added directly to the main query. Otherwise the query will be
* included as is.
* </li>
* <li> bf - (Boost Functions) functions (with optional boosts) that will be
* included in the users query to influcene the score.
* Format is: "<code>funcA(arg1,arg2)^1.2
* funcB(arg3,arg4)^2.2</code>". NOTE: Whitespace is not allowed
* in the function arguments.
* </li>
* <li> fq - (Filter Query) a raw lucene query that can be used
* to restrict the super set of products we are interested in - more
* efficient then using bq, but doesn't influence score.
* This param can be specified multiple times, and the filters
* are addative.
* </li>
* </ul>
*
* <p>
* The following options are only available as request params...
* </p>
*
* <ul>
* <li> q - (Query) the raw unparsed, unescaped, query from the user.
* </li>
* <li>sort - (Order By) list of fields and direction to sort on.
* </li>
* </ul>
*
* <pre>
* :TODO: document facet param support
*
* :TODO: make bf,pf,qf multival params now that SolrParams supports them
* </pre>
*/
public class DisMaxRequestHandler
implements SolrRequestHandler, SolrInfoMBean {
/**
* A field we can't ever find in any schema, so we can safely tell
* DisjunctionMaxQueryParser to use it as our defaultField, and
* map aliases from it to any field in our schema.
*/
private static String IMPOSSIBLE_FIELD_NAME = "\uFFFC\uFFFC\uFFFC";
// statistics
// TODO: should we bother synchronizing these, or is an off-by-one error
// acceptable every million requests or so?
long numRequests;
long numErrors;
SolrParams defaults;
SolrParams appends;
SolrParams invariants;
/** shorten the class referneces for utilities */
private static class U extends SolrPluginUtils {
/* :NOOP */
}
/** shorten the class referneces for utilities */
private static class DMP extends DisMaxParams {
/* :NOOP */
}
public DisMaxRequestHandler() {
super();
}
/* returns URLs to the Wiki pages */
public URL[] getDocs() {
/* :TODO: need docs */
return new URL[0];
}
public String getName() {
return this.getClass().getName();
}
public NamedList getStatistics() {
NamedList lst = new NamedList();
lst.add("requests", numRequests);
lst.add("errors", numErrors);
return lst;
}
public String getVersion() {
return "$Revision:$";
}
public String getDescription() {
return "DisjunctionMax Request Handler: Does relevancy based queries "
+ "accross a variety of fields using configured boosts";
}
public Category getCategory() {
return Category.QUERYHANDLER;
}
public String getSourceId() {
return "$Id:$";
}
public String getSource() {
return "$URL:$";
}
/** sets the default variables for any usefull info it finds in the config
* if a config option is not inthe format expected, logs an warning
* and ignores it..
*/
public void init(NamedList args) {
if (-1 == args.indexOf("defaults",0)) {
// no explict defaults list, use all args implicitly
// indexOf so "<null name="defaults"/> is valid indicator of no defaults
defaults = SolrParams.toSolrParams(args);
} else {
Object o = args.get("defaults");
if (o != null && o instanceof NamedList) {
defaults = SolrParams.toSolrParams((NamedList)o);
}
o = args.get("appends");
if (o != null && o instanceof NamedList) {
appends = SolrParams.toSolrParams((NamedList)o);
}
o = args.get("invariants");
if (o != null && o instanceof NamedList) {
invariants = SolrParams.toSolrParams((NamedList)o);
}
}
}
public void handleRequest(SolrQueryRequest req, SolrQueryResponse rsp) {
numRequests++;
try {
U.setDefaults(req,defaults,appends,invariants);
SolrParams params = req.getParams();
int flags = 0;
SolrIndexSearcher s = req.getSearcher();
IndexSchema schema = req.getSchema();
Map<String,Float> queryFields = U.parseFieldBoosts(params.get(DMP.QF));
Map<String,Float> phraseFields = U.parseFieldBoosts(params.get(DMP.PF));
float tiebreaker = params.getFloat(DMP.TIE, 0.0f);
int pslop = params.getInt(DMP.PS, 0);
/* a generic parser for parsing regular lucene queries */
QueryParser p = new SolrQueryParser(schema, null);
/* a parser for dealing with user input, which will convert
* things to DisjunctionMaxQueries
*/
U.DisjunctionMaxQueryParser up =
new U.DisjunctionMaxQueryParser(schema, IMPOSSIBLE_FIELD_NAME);
up.addAlias(IMPOSSIBLE_FIELD_NAME,
tiebreaker, queryFields);
/* for parsing slopy phrases using DisjunctionMaxQueries */
U.DisjunctionMaxQueryParser pp =
new U.DisjunctionMaxQueryParser(schema, IMPOSSIBLE_FIELD_NAME);
pp.addAlias(IMPOSSIBLE_FIELD_NAME,
tiebreaker, phraseFields);
pp.setPhraseSlop(pslop);
/* * * Main User Query * * */
String userQuery = U.partialEscape
(U.stripUnbalancedQuotes(params.get(Q))).toString();
/* the main query we will execute. we disable the coord because
* this query is an artificial construct
*/
BooleanQuery query = new BooleanQuery(true);
String minShouldMatch = params.get(DMP.MM, "100%");
Query dis = up.parse(userQuery);
if (dis instanceof BooleanQuery) {
BooleanQuery t = new BooleanQuery();
U.flattenBooleanQuery(t, (BooleanQuery)dis);
U.setMinShouldMatch(t, minShouldMatch);
query.add(t, Occur.MUST);
} else {
query.add(dis, Occur.MUST);
}
/* * * Add on Phrases for the Query * * */
/* build up phrase boosting queries */
/* if the userQuery already has some quotes, stip them out.
* we've already done the phrases they asked for in the main
* part of the query, this is to boost docs that may not have
* matched those phrases but do match looser phrases.
*/
String userPhraseQuery = userQuery.replace("\"","");
Query phrase = pp.parse("\"" + userPhraseQuery + "\"");
if (null != phrase) {
query.add(phrase, Occur.SHOULD);
}
/* * * Boosting Query * * */
String boostQuery = params.get(DMP.BQ);
if (null != boostQuery && !boostQuery.equals("")) {
Query tmp = p.parse(boostQuery);
/* if the default boost was used, and we've got a BooleanQuery
* extract the subqueries out and use them directly
*/
if (1.0f == tmp.getBoost() && tmp instanceof BooleanQuery) {
for (BooleanClause c : ((BooleanQuery)tmp).getClauses()) {
query.add(c);
}
} else {
query.add(tmp, BooleanClause.Occur.SHOULD);
}
}
/* * * Boosting Functions * * */
String boostFunc = params.get(DMP.BF);
if (null != boostFunc && !boostFunc.equals("")) {
List<Query> funcs = U.parseFuncs(schema, boostFunc);
for (Query f : funcs) {
query.add(f, Occur.SHOULD);
}
}
/* * * Restrict Results * * */
List<Query> restrictions = U.parseFilterQueries(req);
/* * * Generate Main Results * * */
flags |= U.setReturnFields(req,rsp);
DocListAndSet results = new DocListAndSet();
NamedList facetInfo = null;
if (params.getBool(FACET,false)) {
results = s.getDocListAndSet(query, restrictions,
SolrPluginUtils.getSort(req),
req.getStart(), req.getLimit(),
flags);
facetInfo = getFacetInfo(req, rsp, results.docSet);
} else {
results.docList = s.getDocList(query, restrictions,
SolrPluginUtils.getSort(req),
req.getStart(), req.getLimit(),
flags);
}
rsp.add("search-results",results.docList);
if (null != facetInfo) rsp.add("facet_counts", facetInfo);
/* * * Debugging Info * * */
try {
NamedList debug = U.doStandardDebug(req, userQuery, query, results.docList);
if (null != debug) {
debug.add("boostquery", boostQuery);
debug.add("boostfunc", boostFunc);
if (null != restrictions) {
debug.add("filter_queries", params.getParams(FQ));
List<String> fqs = new ArrayList<String>(restrictions.size());
for (Query fq : restrictions) {
fqs.add(QueryParsing.toString(fq, req.getSchema()));
}
debug.add("parsed_filter_queries",fqs);
}
rsp.add("debug", debug);
}
} catch (Exception e) {
SolrException.logOnce(SolrCore.log,
"Exception durring debug", e);
rsp.add("exception_during_debug", SolrException.toStr(e));
}
/* * * Highlighting/Summarizing * * */
if(HighlightingUtils.isHighlightingEnabled(req)) {
BooleanQuery highlightQuery = new BooleanQuery();
U.flattenBooleanQuery(highlightQuery, query);
String[] highFields = queryFields.keySet().toArray(new String[0]);
NamedList sumData =
HighlightingUtils.doHighlighting(results.docList, highlightQuery,
req, highFields);
if(sumData != null)
rsp.add("highlighting", sumData);
}
} catch (Exception e) {
SolrException.log(SolrCore.log,e);
rsp.setException(e);
numErrors++;
}
}
/**
* Fetches information about Facets for this request.
*
* Subclasses may with to override this method to provide more
* advanced faceting behavior.
* @see SimpleFacets#getFacetCounts
*/
protected NamedList getFacetInfo(SolrQueryRequest req,
SolrQueryResponse rsp,
DocSet mainSet) {
SimpleFacets f = new SimpleFacets(req.getSearcher(),
mainSet,
req.getParams());
return f.getFacetCounts();
}
}
|
- Typo fixes
git-svn-id: 9c10db2ffc3a5912653d34876e3a537be687889a@448448 13f79535-47bb-0310-9956-ffa450edef68
|
src/java/org/apache/solr/request/DisMaxRequestHandler.java
|
- Typo fixes
|
<ide><path>rc/java/org/apache/solr/request/DisMaxRequestHandler.java
<ide> /**
<ide> * <p>
<ide> * A Generic query plugin designed to be given a simple query expression
<del> * from a user, which it will then query agaisnt a variety of
<add> * from a user, which it will then query against a variety of
<ide> * pre-configured fields, in a variety of ways, using BooleanQueries,
<ide> * DisjunctionMaxQueries, and PhraseQueries.
<ide> * </p>
<ide> *
<ide> * <ul>
<ide> * <li>tie - (Tie breaker) float value to use as tiebreaker in
<del> * DisjunctionMaxQueries (should be something much less then 1)
<add> * DisjunctionMaxQueries (should be something much less than 1)
<ide> * </li>
<ide> * <li> qf - (Query Fields) fields and boosts to use when building
<ide> * DisjunctionMaxQueries from the users query. Format is:
<ide> * read {@link SolrPluginUtils#setMinShouldMatch SolrPluginUtils.setMinShouldMatch} for full details.
<ide> * </li>
<ide> * <li> pf - (Phrase Fields) fields/boosts to make phrase queries out
<del> * of to boost
<del> * the users query for exact matches on the specified fields.
<add> * of, to boost the users query for exact matches on the specified fields.
<ide> * Format is: "<code>fieldA^1.0 fieldB^2.2</code>".
<ide> * </li>
<ide> * <li> ps - (Phrase Slop) amount of slop on phrase queries built for pf
<ide> * fields.
<ide> * </li>
<ide> * <li> bq - (Boost Query) a raw lucene query that will be included in the
<del> * users query to influcene the score. If this is a BooleanQuery
<del> * with a default boost (1.0f) then the individual clauses will be
<del> * added directly to the main query. Otherwise the query will be
<add> * users query to influence the score. If this is a BooleanQuery
<add> * with a default boost (1.0f), then the individual clauses will be
<add> * added directly to the main query. Otherwise, the query will be
<ide> * included as is.
<ide> * </li>
<ide> * <li> bf - (Boost Functions) functions (with optional boosts) that will be
<del> * included in the users query to influcene the score.
<add> * included in the users query to influence the score.
<ide> * Format is: "<code>funcA(arg1,arg2)^1.2
<ide> * funcB(arg3,arg4)^2.2</code>". NOTE: Whitespace is not allowed
<ide> * in the function arguments.
<ide> * to restrict the super set of products we are interested in - more
<ide> * efficient then using bq, but doesn't influence score.
<ide> * This param can be specified multiple times, and the filters
<del> * are addative.
<add> * are additive.
<ide> * </li>
<ide> * </ul>
<ide> *
<ide> SolrParams appends;
<ide> SolrParams invariants;
<ide>
<del> /** shorten the class referneces for utilities */
<add> /** shorten the class references for utilities */
<ide> private static class U extends SolrPluginUtils {
<ide> /* :NOOP */
<ide> }
<del> /** shorten the class referneces for utilities */
<add> /** shorten the class references for utilities */
<ide> private static class DMP extends DisMaxParams {
<ide> /* :NOOP */
<ide> }
|
|
Java
|
mit
|
d993987b278fd32d11595ab06edf3ea50b1f9220
| 0 |
fomenyesu/photo-picker-plus-android,ChaosJohn/photo-picker-plus-android,chute/photo-picker-plus-android,newtonker/photo-picker-plus-android
|
package com.chute.photopickerplustutorial.app;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import com.chute.android.photopickerplus.util.intent.PhotoActivityIntentWrapper;
import com.chute.photopickerplustutorial.R;
import com.chute.photopickerplustutorial.intent.PhotoPickerPlusIntentWrapper;
import com.darko.imagedownloader.ImageLoader;
public class PhotoPickerPlusTutorialActivity extends Activity {
public static final String TAG = PhotoPickerPlusTutorialActivity.class.getSimpleName();
private ImageView image;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_picker_plus_activity);
findViewById(R.id.btnPhotoPicker).setOnClickListener(new OnChooseClickListener());
image = (ImageView) findViewById(R.id.imageView);
}
private class OnChooseClickListener implements OnClickListener {
@Override
public void onClick(View v) {
PhotoPickerPlusIntentWrapper.startSlideChute(PhotoPickerPlusTutorialActivity.this);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return;
}
final PhotoActivityIntentWrapper wrapper = new PhotoActivityIntentWrapper(data);
ImageLoader.get(this).displayImage(wrapper.getMediaModel().getUrl(), image);
Log.d(TAG, wrapper.toString());
String path;
Uri uri = Uri.parse(wrapper.getMediaModel().getUrl());
if (uri.getScheme().contentEquals("http")) {
path = uri.toString();
} else {
path = uri.getPath();
}
Log.d(TAG, "The Path or url of the file " + path);
}
}
|
PhotoPickerPlusTutorial/src/com/chute/photopickerplustutorial/app/PhotoPickerPlusTutorialActivity.java
|
package com.chute.photopickerplustutorial.app;
import com.chute.android.photopickerplus.util.intent.PhotoActivityIntentWrapper;
import com.chute.photopickerplustutorial.R;
import com.chute.photopickerplustutorial.R.id;
import com.chute.photopickerplustutorial.R.layout;
import com.chute.photopickerplustutorial.intent.PhotoPickerPlusIntentWrapper;
import com.darko.imagedownloader.ImageLoader;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class PhotoPickerPlusTutorialActivity extends Activity {
public static final String TAG = PhotoPickerPlusTutorialActivity.class.getSimpleName();
private ImageView image;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_picker_plus_activity);
findViewById(R.id.btnPhotoPicker).setOnClickListener(new OnChooseClickListener());
image = (ImageView) findViewById(R.id.imageView);
}
private class OnChooseClickListener implements OnClickListener {
@Override
public void onClick(View v) {
PhotoPickerPlusIntentWrapper.startSlideChute(PhotoPickerPlusTutorialActivity.this);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return;
}
final PhotoActivityIntentWrapper wrapper = new PhotoActivityIntentWrapper(data);
ImageLoader.get(this).displayImage(wrapper.getMediaModel().getUrl(), image);
Log.d(TAG, wrapper.toString());
}
}
|
Notification messages.
|
PhotoPickerPlusTutorial/src/com/chute/photopickerplustutorial/app/PhotoPickerPlusTutorialActivity.java
|
Notification messages.
|
<ide><path>hotoPickerPlusTutorial/src/com/chute/photopickerplustutorial/app/PhotoPickerPlusTutorialActivity.java
<ide> package com.chute.photopickerplustutorial.app;
<del>
<del>import com.chute.android.photopickerplus.util.intent.PhotoActivityIntentWrapper;
<del>import com.chute.photopickerplustutorial.R;
<del>import com.chute.photopickerplustutorial.R.id;
<del>import com.chute.photopickerplustutorial.R.layout;
<del>import com.chute.photopickerplustutorial.intent.PhotoPickerPlusIntentWrapper;
<del>import com.darko.imagedownloader.ImageLoader;
<ide>
<ide> import android.app.Activity;
<ide> import android.content.Intent;
<add>import android.net.Uri;
<ide> import android.os.Bundle;
<ide> import android.util.Log;
<ide> import android.view.View;
<ide> import android.view.View.OnClickListener;
<ide> import android.widget.ImageView;
<ide>
<add>import com.chute.android.photopickerplus.util.intent.PhotoActivityIntentWrapper;
<add>import com.chute.photopickerplustutorial.R;
<add>import com.chute.photopickerplustutorial.intent.PhotoPickerPlusIntentWrapper;
<add>import com.darko.imagedownloader.ImageLoader;
<add>
<ide> public class PhotoPickerPlusTutorialActivity extends Activity {
<ide>
<ide> public static final String TAG = PhotoPickerPlusTutorialActivity.class.getSimpleName();
<del> private ImageView image;
<add> private ImageView image;
<ide>
<ide> @Override
<ide> public void onCreate(Bundle savedInstanceState) {
<ide>
<ide> findViewById(R.id.btnPhotoPicker).setOnClickListener(new OnChooseClickListener());
<ide> image = (ImageView) findViewById(R.id.imageView);
<del>
<add>
<ide> }
<ide>
<ide> private class OnChooseClickListener implements OnClickListener {
<ide> final PhotoActivityIntentWrapper wrapper = new PhotoActivityIntentWrapper(data);
<ide> ImageLoader.get(this).displayImage(wrapper.getMediaModel().getUrl(), image);
<ide> Log.d(TAG, wrapper.toString());
<add>
<add> String path;
<add> Uri uri = Uri.parse(wrapper.getMediaModel().getUrl());
<add> if (uri.getScheme().contentEquals("http")) {
<add> path = uri.toString();
<add> } else {
<add> path = uri.getPath();
<add> }
<add> Log.d(TAG, "The Path or url of the file " + path);
<ide> }
<ide> }
|
|
JavaScript
|
apache-2.0
|
38c99408270f72ade7724dab66400fa7459f7565
| 0 |
Flipkart/foxtrot,Flipkart/foxtrot,Flipkart/foxtrot,Flipkart/foxtrot,Flipkart/foxtrot
|
/**
* Copyright 2014 Flipkart Internet Pvt. Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function Queue() {
this.requests = {};
this.refreshTime = 5;
this.timeout = 4000;
}
Queue.prototype.enqueue = function (key, ajaxRequest) {
console.log("Adding: " + key);
this.requests[key] = ajaxRequest;
};
Queue.prototype.remove = function (key) {
console.log("Removing: " + key);
delete this.requests[key];
};
Queue.prototype.start = function () {
setInterval($.proxy(this.executeCalls, this), this.refreshTime * 1000);
};
Queue.prototype.executeCalls = function () {
for (var property in this.requests) {
if (this.requests.hasOwnProperty(property)) {
this.requests[property]();
}
}
};
function Tile() {}
function TileFactory() {
this.tileObject = "";
}
function refereshTiles() {
for (var key in tileData) {
if (tileData.hasOwnProperty(key)) {
var a = new TileFactory();
a.createGraph(tileData[key], $("#"+ key));
}
}
}
setInterval(function () {
refereshTiles();
}, 6000);
function pushTilesObject(object) {
tileData[object.id] = object;
var tabName = (object.tileContext.tabName == undefined ? $(".tab .active").attr('id') : object.tileContext.tabName) ;
var tempObject = {
"id":tabName.trim().toLowerCase().split(' ').join("_"),
"name": tabName,
"tileList": tileList
, "tileData": tileData
}
if (tileList.length > 0) {
var deleteIndex = globalData.findIndex(x => x.id == tabName.trim().toLowerCase().split(' ').join("_"));
if (deleteIndex >= 0) {
globalData.splice(deleteIndex, 1);
globalData.splice(deleteIndex, 0, tempObject);
//tileList = [];
}
else {
globalData.push(tempObject);
}
}
}
TileFactory.prototype.updateTileData = function () {
var selectedTile = $("#" + this.tileObject.id);
selectedTile.find(".tile-title").text(this.tileObject.title);
var tileid = this.tileObject.id;
this.createGraph(this.tileObject, selectedTile);
var tileListIndex = tileList.indexOf(this.tileObject.id);
var tileDataIndex = tileData[this.tileObject.id];
delete tileData[tileDataIndex.id];
tileData[this.tileObject.id] = this.tileObject;
}
TileFactory.prototype.createTileData = function (object) {
var selectedTile = $("#" + object.id);
selectedTile.find(".tile-title").text(object.title);
var tileid = object.id;
var prepareTileData = {};
prepareTileData[object.id] = object;
pushTilesObject(object);
}
TileFactory.prototype.getTileFormValue = function (form, modal, object) {
var tileFormValue = {};
tileFormValue.title = form.find(".tile-title").val();
tileFormValue.table = form.find(".tile-table").val();
tileFormValue.id = form.find(".tileId").val();
tileFormValue.timeUnit = form.find(".tile-time-unit").val();
tileFormValue.timeValue = form.find(".tile-time-value").val();
tileFormValue.chartType = form.find(".tile-chart-type").val();
//updateTile(tileFormValue, modal);
}
function setConfigValue(object) {
if (currentChartType == "gauge") {
setGaugeChartFormValues(object);
}
else if (currentChartType == "line") {
setLineChartFormValues(object);
}
else if (currentChartType == "trend") {
setTrendChartFormValues(object);
}
else if (currentChartType == "stacked") {
setStackedChartFormValues(object);
}
else if (currentChartType == "radar") {
setRadarChartFormValues(object);
}
else if (currentChartType == "stackedBar") {
setStackedBarChartFormValues(object);
}
else if (currentChartType == "pie") {
setPieChartFormValues(object);
}
else if (currentChartType == "statsTrend") {
setStatsTrendTileChartFormValues(object);
}
else if (currentChartType == "bar") {
setBarChartFormValues(object);
}
}
function newBtnElement() {
return "<div class='col-md-2 custom-btn-div'><button data-target='#addWidgetModal' class='tile-add-btn tile-add-btn btn btn-primary filter-nav-button glyphicon glyphicon-plus custom-add-btn'onClick='setClicketData(this)' data-toggle='modal' id='row-" + row + "'></button><div>"
}
// create new div
TileFactory.prototype.createNewRow = function (tileElement) {
tileElement.addClass("col-md-12"); // add class for div which is full width
if (panelRow.length == 0) { // initial page
row = 1;
panelRow.push({
widgetType: this.tileObject.tileContext.widgetType
, id: this.tileObject.id
});
tileElement.addClass("row-" + row);
}
else { // incremetn row value by one
panelRow.push({
widgetType: this.tileObject.tileContext.widgetType
, id: this.tileObject.id
});
row = panelRow.length;
tileElement.addClass("row-" + row);
}
if (this.tileObject.tileContext.widgetType != "full" && currentConsoleName == undefined) // dont add row add button for full widget
tileElement.append(newBtnElement());
return tileElement;
}
TileFactory.prototype.updateFilterCreation = function (object) {
currentChartType = object.tileContext.chartType;
removeFilters();
var tileListIndex = tileList.indexOf(object.id);
var tileDataIndex = tileData[tileListIndex];
var selectedTileObject = tileData[object.id];
if (object.tileContext.tableFields != undefined) { // this is for without console
currentFieldList = object.tileContext.tableFields;
}
else { // with console
currentFieldList = tableFiledsArray[object.tileContext.table].mappings;
}
var form = $("#sidebar").find("form");
form.find(".tile-title").val(object.title);
if (object.tileContext.tableDropdownIndex == undefined) {
form.find(".tile-table").val(parseInt(tableNameList.indexOf(object.tileContext.table)));
}
else {
form.find(".tile-table").val(parseInt(object.tileContext.tableDropdownIndex));
}
$('.tile-table').selectpicker('refresh');
$(".chart-type").val(object.tileContext.chartType)
clickedChartType($(".chart-type"));
if (selectedTileObject) {
setConfigValue(selectedTileObject);
}
if (object.tileContext.filters.length > 0) {
filterRowArray = [];
for (var invokeFilter = 0; invokeFilter < selectedTileObject.tileContext.filters.length; invokeFilter++) {
addFitlers();
}
//setFilters(object);
setTimeout(function () { //calls click event after a certain time
setFilters(selectedTileObject.tileContext.filters);
}, 1000);
}
}
TileFactory.prototype.updateFilters = function (filters) {
var instanceVar = this;
var temp = [];
instanceVar.tileObject.tileContext.uiFiltersSelectedList = arr_diff(instanceVar.tileObject.tileContext.uiFiltersList, filters)
}
// Filter configuration
TileFactory.prototype.triggerFilter = function (tileElement, object) {
if(object.tileContext.chartType != "radar" && object.tileContext.chartType != "line" && object.tileContext.chartType != "stacked") {
var instanceVar = this;
tileElement.find(".widget-toolbox").find(".filter").click(function () {
clearFilterValues();
var modal = $("#setupFiltersModal").modal('show');
var fv = $("#setupFiltersModal").find(".filter_values");
fv.multiselect('refresh');
var form = modal.find("form");
form.off('submit');
form.on('submit', $.proxy(function (e) {
instanceVar.updateFilters($("#filter_values").val());
$("#setupFiltersModal").modal('hide');
e.preventDefault();
}));
var options = [];
if (object.tileContext.uiFiltersList == undefined) return;
for (var i = 0; i < object.tileContext.uiFiltersList.length; i++) {
var value = object.tileContext.uiFiltersList[i];
var index = $.inArray( value, object.tileContext.uiFiltersSelectedList)
options.push({
label: value
, title: value
, value: value
, selected: (index == -1 ? true : false)
});
}
fv.multiselect('dataprovider', options);
fv.multiselect('refresh');
});
}
}
// Add click event for tile config icon
TileFactory.prototype.triggerConfig = function (tileElement, object) {
var instanceVar = this;
tileElement.find(".widget-toolbox").find(".glyphicon-cog").click(function () {
showHideSideBar();
//$("#addWidgetModal").modal('show');
$("#sidebar").find(".tileId").val(object.id);
$("#sidebar").find("#modal-heading").hide();
$(".vizualization-type").hide();
$(".chart-type").hide();
setTimeout(function() { instanceVar.updateFilterCreation(object); }, 2000);
});
}
TileFactory.prototype.triggerChildBtn = function (tileElement, object) {
var instanceVar = this;
tileElement.find(".add-child-btn").find(".child-btn").click(function () {
$("#addWidgetModal").modal('show');
$("#addWidgetModal").find(".child-tile").val('true');
$(".vizualization-type").hide();
instanceVar.updateFilterCreation(object);
});
}
// Save action for tile config save button
TileFactory.prototype.saveTileConfig = function (object) {
$("#tile-configuration").find(".save-changes").click(function () {
var form = $("#tile-configuration").find("form");
form.off('submit');
form.on('submit', $.proxy(function (e) {
this.getTileFormValue(form, "tile-configuration", object)
$("#tile-configuration").modal('hide');
e.preventDefault();
}, object));
});
}
TileFactory.prototype.createGraph = function (object, tileElement) {
if (object.tileContext.chartType == "line") {
var lineGraph = new LineTile();
//lineGraph.render(tileElement, object);
lineGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "radar") {
tileElement.find(".chart-item").append('<div id="radar-' + object.id + '" style="width:200;height:200"></div>');
var radarGraph = new RadarTile();
radarGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "trend") {
var trendGraph = new TrendTile();
trendGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "gauge") {
var gaugeGraph = new GaugeTile();
gaugeGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "stacked") {
var stackedGraph = new StackedTile();
stackedGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "stackedBar") {
var stackedBarGraph = new StackedBarTile();
stackedBarGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "pie") {
var pieGraph = new PieTile();
pieGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "statsTrend") {
var statsTrendGraph = new StatsTrendTile();
statsTrendGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "bar") {
var barGraph = new BarTile();
barGraph.getQuery(tileElement, object);
}
}
TileFactory.prototype.create = function () {
var tileElement = $(handlebars("#tile-template", {
tileId: this.tileObject.id
, title: this.tileObject.title
}));
var clickedRow; // clicked row
if(this.tileObject.tileContext.isnewRow) {
tileElement = this.createNewRow(tileElement);
row = this.tileObject.tileContext.row;
} else {
row = this.tileObject.tileContext.row;
if (this.tileObject.tileContext.widgetType == 'small') {
if(customBtn != undefined) {
var findElement = $("." + customBtn.id);
var column1Length = findElement.find(".row-col-1").length;
if (column1Length == 0 || column1Length == 2) {
if (column1Length == 0) {
tileElement.addClass('row-col-1');
}
else if (column1Length == 2) {
tileElement.addClass('row-col-2');
}
var rowCol2Length = findElement.find(".row-col-2").length;
if (rowCol2Length == 0) tileElement.append("<div class='widget-add-btn'><button data-target='#addWidgetModal' class='tile-add-btn tile-add-btn btn btn-primary filter-nav-button glyphicon glyphicon-plus custom-add-btn row-col-1'onClick='setClicketData(this)' data-toggle='modal' id='row-" + row + "'></button><div>");
}
}
}
}
if (this.tileObject.tileContext.widgetType == "full") {
tileElement.find(".tile").addClass('col-sm-12');
}
else if (this.tileObject.tileContext.widgetType == "medium") {
tileElement.find(".tile").addClass('col-sm-6 medium-widget');
tileElement.find(".tile").height(500);
tileElement.find(".widget-header").css("background-color", "#fff");
}
else if (this.tileObject.tileContext.widgetType == "small") {
tileElement.find(".tile").addClass('col-sm-3 small-widget');
tileElement.find(".tile").height(220);
tileElement.find(".widget-header").css("background-color", "#fff");
tileElement.find(".widget-header").height(68);
tileElement.find(".widget-header > .tile-title").css("font-size", "12px");
tileElement.find(".widget-header > .tile-title").css("width", "112px");
}
if (this.tileObject.tileContext.chartType == "radar") {
tileElement.find(".trend-chart").remove();
tileElement.find(".chart-item").addClass("radar-chart");
}
else if (this.tileObject.tileContext.chartType == "line" || this.tileObject.tileContext.chartType == "stacked" || this.tileObject.tileContext.chartType == "stackedBar" || this.tileObject.tileContext.chartType == "pie" || this.tileObject.tileContext.chartType == "statsTrend" || this.tileObject.tileContext.chartType == "bar") {
/*tileElement.find(".widget-header").append('<div id="' + this.tileObject.id + '-health-text" class="lineGraph-health-text">No Data available</div>');*/
tileElement.find(".widget-header").append('<div id="' + this.tileObject.id + '-health" style=""></div>');
tileElement.find(".chart-item").append('<div id="' + this.tileObject.id + '"></div>');
tileElement.find(".chart-item").append("<div class='legend col-sm-12'></div>")
}
if (this.tileObject.tileContext.chartType == "pie") {
tileElement.append("<div class='legend'></div>")
}
if (this.tileObject.tileContext.isnewRow) { // new row
tileElement.insertBefore('.float-clear');
}
else { // remove row btn and add new div based on type
if(customBtn) {
customBtn.remove();
$(".custom-btn-div").remove();
}
$('.row-' + row).append(tileElement);
}
if (this.tileObject.tileContext.widgetType == "small") {
tileElement.find(".settings").addClass('reduce-filter-size');
tileElement.find(".widget-timeframe").addClass('reduce-filter-option');
tileElement.find(".period-select").addClass('reduce-period-select');
tileElement.find(".settings-icon").addClass('reduce-settings-icon');
tileElement.find(".filter").hide();
}
else if (this.tileObject.tileContext.widgetType == "medium") {
tileElement.find(".widget-header").addClass('reduce-widget-header-size');
}
this.createGraph(this.tileObject, tileElement);
this.triggerConfig(tileElement, this.tileObject); // add event for tile config
this.triggerFilter(tileElement, this.tileObject);
//this.triggerChildBtn(tileElement,this.tileObject);
this.createTileData(this.tileObject);
this.saveTileConfig(this.tileObject); // add event for tile save btn
};
|
foxtrot-server/src/main/resources/console/echo/js/tiles/tile.js
|
/**
* Copyright 2014 Flipkart Internet Pvt. Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function Queue() {
this.requests = {};
this.refreshTime = 5;
this.timeout = 4000;
}
Queue.prototype.enqueue = function (key, ajaxRequest) {
console.log("Adding: " + key);
this.requests[key] = ajaxRequest;
};
Queue.prototype.remove = function (key) {
console.log("Removing: " + key);
delete this.requests[key];
};
Queue.prototype.start = function () {
setInterval($.proxy(this.executeCalls, this), this.refreshTime * 1000);
};
Queue.prototype.executeCalls = function () {
for (var property in this.requests) {
if (this.requests.hasOwnProperty(property)) {
this.requests[property]();
}
}
};
function Tile() {}
function TileFactory() {
this.tileObject = "";
}
function refereshTiles() {
for (var key in tileData) {
if (tileData.hasOwnProperty(key)) {
var a = new TileFactory();
a.createGraph(tileData[key], $("#"+ key));
}
}
}
setInterval(function () {
refereshTiles();
}, 6000);
function pushTilesObject(object) {
tileData[object.id] = object;
var tabName = (object.tileContext.tabName == undefined ? $(".tab .active").attr('id') : object.tileContext.tabName) ;
var tempObject = {
"id":tabName.trim().toLowerCase().split(' ').join("_"),
"name": tabName,
"tileList": tileList
, "tileData": tileData
}
if (tileList.length > 0) {
var deleteIndex = globalData.findIndex(x => x.id == tabName.trim().toLowerCase().split(' ').join("_"));
if (deleteIndex >= 0) {
globalData.splice(deleteIndex, 1);
globalData.splice(deleteIndex, 0, tempObject);
//tileList = [];
}
else {
globalData.push(tempObject);
}
}
}
TileFactory.prototype.updateTileData = function () {
var selectedTile = $("#" + this.tileObject.id);
selectedTile.find(".tile-title").text(this.tileObject.title);
var tileid = this.tileObject.id;
this.createGraph(this.tileObject, selectedTile);
var tileListIndex = tileList.indexOf(this.tileObject.id);
var tileDataIndex = tileData[this.tileObject.id];
delete tileData[tileDataIndex.id];
tileData[this.tileObject.id] = this.tileObject;
}
TileFactory.prototype.createTileData = function (object) {
var selectedTile = $("#" + object.id);
selectedTile.find(".tile-title").text(object.title);
var tileid = object.id;
var prepareTileData = {};
prepareTileData[object.id] = object;
pushTilesObject(object);
}
TileFactory.prototype.getTileFormValue = function (form, modal, object) {
var tileFormValue = {};
tileFormValue.title = form.find(".tile-title").val();
tileFormValue.table = form.find(".tile-table").val();
tileFormValue.id = form.find(".tileId").val();
tileFormValue.timeUnit = form.find(".tile-time-unit").val();
tileFormValue.timeValue = form.find(".tile-time-value").val();
tileFormValue.chartType = form.find(".tile-chart-type").val();
//updateTile(tileFormValue, modal);
}
function setConfigValue(object) {
if (currentChartType == "gauge") {
setGaugeChartFormValues(object);
}
else if (currentChartType == "line") {
setLineChartFormValues(object);
}
else if (currentChartType == "trend") {
setTrendChartFormValues(object);
}
else if (currentChartType == "stacked") {
setStackedChartFormValues(object);
}
else if (currentChartType == "radar") {
setRadarChartFormValues(object);
}
else if (currentChartType == "stackedBar") {
setStackedBarChartFormValues(object);
}
else if (currentChartType == "pie") {
setPieChartFormValues(object);
}
else if (currentChartType == "statsTrend") {
setStatsTrendTileChartFormValues(object);
}
else if (currentChartType == "bar") {
setBarChartFormValues(object);
}
}
function newBtnElement() {
return "<div class='col-md-2 custom-btn-div'><button data-target='#addWidgetModal' class='tile-add-btn tile-add-btn btn btn-primary filter-nav-button glyphicon glyphicon-plus custom-add-btn'onClick='setClicketData(this)' data-toggle='modal' id='row-" + row + "'></button><div>"
}
// create new div
TileFactory.prototype.createNewRow = function (tileElement) {
tileElement.addClass("col-md-12"); // add class for div which is full width
if (panelRow.length == 0) { // initial page
row = 1;
panelRow.push({
widgetType: this.tileObject.tileContext.widgetType
, id: this.tileObject.id
});
tileElement.addClass("row-" + row);
}
else { // incremetn row value by one
panelRow.push({
widgetType: this.tileObject.tileContext.widgetType
, id: this.tileObject.id
});
row = panelRow.length;
tileElement.addClass("row-" + row);
}
if (this.tileObject.tileContext.widgetType != "full" && currentConsoleName == undefined) // dont add row add button for full widget
tileElement.append(newBtnElement());
return tileElement;
}
TileFactory.prototype.updateFilterCreation = function (object) {
currentChartType = object.tileContext.chartType;
removeFilters();
var tileListIndex = tileList.indexOf(object.id);
var tileDataIndex = tileData[tileListIndex];
var selectedTileObject = tileData[object.id];
if ($("#listConsole").val() == "none") { // this is for without console
currentFieldList = object.tileContext.tableFields;
}
else { // with console
currentFieldList = tableFiledsArray[object.tileContext.table].mappings;
}
var form = $("#sidebar").find("form");
form.find(".tile-title").val(object.title);
if (object.tileContext.tableDropdownIndex == undefined) {
form.find(".tile-table").val(parseInt(tableNameList.indexOf(object.tileContext.table)));
}
else {
form.find(".tile-table").val(parseInt(object.tileContext.tableDropdownIndex));
}
$('.tile-table').selectpicker('refresh');
$(".chart-type").val(object.tileContext.chartType)
clickedChartType($(".chart-type"));
if (selectedTileObject) {
setConfigValue(selectedTileObject);
}
if (object.tileContext.filters.length > 0) {
filterRowArray = [];
for (var invokeFilter = 0; invokeFilter < selectedTileObject.tileContext.filters.length; invokeFilter++) {
addFitlers();
}
//setFilters(object);
setTimeout(function () { //calls click event after a certain time
setFilters(selectedTileObject.tileContext.filters);
}, 1000);
}
}
TileFactory.prototype.updateFilters = function (filters) {
var instanceVar = this;
var temp = [];
instanceVar.tileObject.tileContext.uiFiltersSelectedList = arr_diff(instanceVar.tileObject.tileContext.uiFiltersList, filters)
}
// Filter configuration
TileFactory.prototype.triggerFilter = function (tileElement, object) {
if(object.tileContext.chartType != "radar" && object.tileContext.chartType != "line" && object.tileContext.chartType != "stacked") {
var instanceVar = this;
tileElement.find(".widget-toolbox").find(".filter").click(function () {
clearFilterValues();
var modal = $("#setupFiltersModal").modal('show');
var fv = $("#setupFiltersModal").find(".filter_values");
fv.multiselect('refresh');
var form = modal.find("form");
form.off('submit');
form.on('submit', $.proxy(function (e) {
instanceVar.updateFilters($("#filter_values").val());
$("#setupFiltersModal").modal('hide');
e.preventDefault();
}));
var options = [];
if (object.tileContext.uiFiltersList == undefined) return;
for (var i = 0; i < object.tileContext.uiFiltersList.length; i++) {
var value = object.tileContext.uiFiltersList[i];
var index = $.inArray( value, object.tileContext.uiFiltersSelectedList)
options.push({
label: value
, title: value
, value: value
, selected: (index == -1 ? true : false)
});
}
fv.multiselect('dataprovider', options);
fv.multiselect('refresh');
});
}
}
// Add click event for tile config icon
TileFactory.prototype.triggerConfig = function (tileElement, object) {
var instanceVar = this;
tileElement.find(".widget-toolbox").find(".glyphicon-cog").click(function () {
showHideSideBar();
//$("#addWidgetModal").modal('show');
$("#sidebar").find(".tileId").val(object.id);
$("#sidebar").find("#modal-heading").hide();
$(".vizualization-type").hide();
$(".chart-type").hide();
setTimeout(function() { instanceVar.updateFilterCreation(object); }, 2000);
});
}
TileFactory.prototype.triggerChildBtn = function (tileElement, object) {
var instanceVar = this;
tileElement.find(".add-child-btn").find(".child-btn").click(function () {
$("#addWidgetModal").modal('show');
$("#addWidgetModal").find(".child-tile").val('true');
$(".vizualization-type").hide();
instanceVar.updateFilterCreation(object);
});
}
// Save action for tile config save button
TileFactory.prototype.saveTileConfig = function (object) {
$("#tile-configuration").find(".save-changes").click(function () {
var form = $("#tile-configuration").find("form");
form.off('submit');
form.on('submit', $.proxy(function (e) {
this.getTileFormValue(form, "tile-configuration", object)
$("#tile-configuration").modal('hide');
e.preventDefault();
}, object));
});
}
TileFactory.prototype.createGraph = function (object, tileElement) {
if (object.tileContext.chartType == "line") {
var lineGraph = new LineTile();
//lineGraph.render(tileElement, object);
lineGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "radar") {
tileElement.find(".chart-item").append('<div id="radar-' + object.id + '" style="width:200;height:200"></div>');
var radarGraph = new RadarTile();
radarGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "trend") {
var trendGraph = new TrendTile();
trendGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "gauge") {
var gaugeGraph = new GaugeTile();
gaugeGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "stacked") {
var stackedGraph = new StackedTile();
stackedGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "stackedBar") {
var stackedBarGraph = new StackedBarTile();
stackedBarGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "pie") {
var pieGraph = new PieTile();
pieGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "statsTrend") {
var statsTrendGraph = new StatsTrendTile();
statsTrendGraph.getQuery(tileElement, object);
}
else if (object.tileContext.chartType == "bar") {
var barGraph = new BarTile();
barGraph.getQuery(tileElement, object);
}
}
TileFactory.prototype.create = function () {
var tileElement = $(handlebars("#tile-template", {
tileId: this.tileObject.id
, title: this.tileObject.title
}));
var clickedRow; // clicked row
if(this.tileObject.tileContext.isnewRow) {
tileElement = this.createNewRow(tileElement);
row = this.tileObject.tileContext.row;
} else {
row = this.tileObject.tileContext.row;
if (this.tileObject.tileContext.widgetType == 'small') {
if(customBtn != undefined) {
var findElement = $("." + customBtn.id);
var column1Length = findElement.find(".row-col-1").length;
if (column1Length == 0 || column1Length == 2) {
if (column1Length == 0) {
tileElement.addClass('row-col-1');
}
else if (column1Length == 2) {
tileElement.addClass('row-col-2');
}
var rowCol2Length = findElement.find(".row-col-2").length;
if (rowCol2Length == 0) tileElement.append("<div class='widget-add-btn'><button data-target='#addWidgetModal' class='tile-add-btn tile-add-btn btn btn-primary filter-nav-button glyphicon glyphicon-plus custom-add-btn row-col-1'onClick='setClicketData(this)' data-toggle='modal' id='row-" + row + "'></button><div>");
}
}
}
}
if (this.tileObject.tileContext.widgetType == "full") {
tileElement.find(".tile").addClass('col-sm-12');
}
else if (this.tileObject.tileContext.widgetType == "medium") {
tileElement.find(".tile").addClass('col-sm-6 medium-widget');
tileElement.find(".tile").height(500);
tileElement.find(".widget-header").css("background-color", "#fff");
}
else if (this.tileObject.tileContext.widgetType == "small") {
tileElement.find(".tile").addClass('col-sm-3 small-widget');
tileElement.find(".tile").height(220);
tileElement.find(".widget-header").css("background-color", "#fff");
tileElement.find(".widget-header").height(68);
tileElement.find(".widget-header > .tile-title").css("font-size", "12px");
tileElement.find(".widget-header > .tile-title").css("width", "112px");
}
if (this.tileObject.tileContext.chartType == "radar") {
tileElement.find(".trend-chart").remove();
tileElement.find(".chart-item").addClass("radar-chart");
}
else if (this.tileObject.tileContext.chartType == "line" || this.tileObject.tileContext.chartType == "stacked" || this.tileObject.tileContext.chartType == "stackedBar" || this.tileObject.tileContext.chartType == "pie" || this.tileObject.tileContext.chartType == "statsTrend" || this.tileObject.tileContext.chartType == "bar") {
/*tileElement.find(".widget-header").append('<div id="' + this.tileObject.id + '-health-text" class="lineGraph-health-text">No Data available</div>');*/
tileElement.find(".widget-header").append('<div id="' + this.tileObject.id + '-health" style=""></div>');
tileElement.find(".chart-item").append('<div id="' + this.tileObject.id + '"></div>');
tileElement.find(".chart-item").append("<div class='legend col-sm-12'></div>")
}
if (this.tileObject.tileContext.chartType == "pie") {
tileElement.append("<div class='legend'></div>")
}
if (this.tileObject.tileContext.isnewRow) { // new row
tileElement.insertBefore('.float-clear');
}
else { // remove row btn and add new div based on type
if(customBtn) {
customBtn.remove();
$(".custom-btn-div").remove();
}
$('.row-' + row).append(tileElement);
}
if (this.tileObject.tileContext.widgetType == "small") {
tileElement.find(".settings").addClass('reduce-filter-size');
tileElement.find(".widget-timeframe").addClass('reduce-filter-option');
tileElement.find(".period-select").addClass('reduce-period-select');
tileElement.find(".settings-icon").addClass('reduce-settings-icon');
tileElement.find(".filter").hide();
}
else if (this.tileObject.tileContext.widgetType == "medium") {
tileElement.find(".widget-header").addClass('reduce-widget-header-size');
}
this.createGraph(this.tileObject, tileElement);
this.triggerConfig(tileElement, this.tileObject); // add event for tile config
this.triggerFilter(tileElement, this.tileObject);
//this.triggerChildBtn(tileElement,this.tileObject);
this.createTileData(this.tileObject);
this.saveTileConfig(this.tileObject); // add event for tile save btn
};
|
fixed edit tile not working for existing console
|
foxtrot-server/src/main/resources/console/echo/js/tiles/tile.js
|
fixed edit tile not working for existing console
|
<ide><path>oxtrot-server/src/main/resources/console/echo/js/tiles/tile.js
<ide> var tileListIndex = tileList.indexOf(object.id);
<ide> var tileDataIndex = tileData[tileListIndex];
<ide> var selectedTileObject = tileData[object.id];
<del> if ($("#listConsole").val() == "none") { // this is for without console
<add> if (object.tileContext.tableFields != undefined) { // this is for without console
<ide> currentFieldList = object.tileContext.tableFields;
<ide> }
<ide> else { // with console
|
|
Java
|
epl-1.0
|
error: pathspec 'src/java/com/hypirion/beckon/SignalFolder.java' did not match any file(s) known to git
|
315a8fc6662492bdc07cef86520a4016b89f8993
| 1 |
hyPiRion/beckon
|
package com.hyprion.beckon;
public class SignalFolder {
}
|
src/java/com/hypirion/beckon/SignalFolder.java
|
Add in signal folder class.
|
src/java/com/hypirion/beckon/SignalFolder.java
|
Add in signal folder class.
|
<ide><path>rc/java/com/hypirion/beckon/SignalFolder.java
<add>package com.hyprion.beckon;
<add>
<add>public class SignalFolder {
<add>
<add>}
|
|
Java
|
mit
|
ffaadc0fb996bd132774ec430a4dfa34d8728d39
| 0 |
phirschbeck/settlers-remake,andreasb242/settlers-remake,andreas-eberle/settlers-remake,phirschbeck/settlers-remake,phirschbeck/settlers-remake,andreas-eberle/settlers-remake,jsettlers/settlers-remake,Peter-Maximilian/settlers-remake,jsettlers/settlers-remake,jsettlers/settlers-remake,andreas-eberle/settlers-remake,andreasb242/settlers-remake,andreasb242/settlers-remake,JKatzwinkel/settlers-remake
|
package jsettlers.graphics.map.controls.original.panel.content;
import go.graphics.GLDrawContext;
import go.graphics.text.EFontSize;
import jsettlers.common.buildings.IBuilding;
import jsettlers.common.buildings.OccupyerPlace;
import jsettlers.common.buildings.OccupyerPlace.ESoldierType;
import jsettlers.common.images.EImageLinkType;
import jsettlers.common.images.ImageLink;
import jsettlers.graphics.action.Action;
import jsettlers.graphics.action.EActionType;
import jsettlers.graphics.localization.Labels;
import jsettlers.graphics.map.controls.original.panel.IContextListener;
import jsettlers.graphics.map.draw.ImageProvider;
import jsettlers.graphics.map.selection.BuildingSelection;
import jsettlers.graphics.utils.Button;
import jsettlers.graphics.utils.UIPanel;
public class BuildingSelectionPanel implements IContentProvider {
private static final ImageLink SOILDER_MISSING = new ImageLink(EImageLinkType.GUI, 3, 45, 0);
private static final ImageLink SOILDER_COMMING = new ImageLink(EImageLinkType.GUI, 3, 48, 0);
private IBuilding building;
private UIPanel panel;
private static ImageLink SET_WORK_AREA = new ImageLink(EImageLinkType.GUI,
3, 201, 0);
private static ImageLink START_WORKING = new ImageLink(EImageLinkType.GUI,
3, 196, 0);
private static ImageLink STOP_WORKING = new ImageLink(EImageLinkType.GUI,
3, 192, 0);
private static ImageLink DESTROY = new ImageLink(EImageLinkType.GUI, 3,
198, 0);
public BuildingSelectionPanel(BuildingSelection selection) {
building = selection.getSelectedBuilding();
ImageLink[] images = building.getBuildingType().getImages();
panel = new BuidlingBackgroundPanel(images);
UIPanel changeWorking;
if (building.isWorking()) {
changeWorking =
new Button(new Action(EActionType.STOP_WORKING),
STOP_WORKING, STOP_WORKING, Labels.getName(EActionType.STOP_WORKING));
} else {
changeWorking =
new Button(new Action(EActionType.START_WORKING),
START_WORKING, START_WORKING, Labels.getName(EActionType.START_WORKING));
}
panel.addChild(changeWorking, 0, .9f, .2f, 1);
if (building.getBuildingType().getWorkradius() > 0) {
Button setWorkcenter = new Button(new Action(EActionType.SET_WORK_AREA),
SET_WORK_AREA, SET_WORK_AREA, Labels.getName(EActionType.SET_WORK_AREA));
panel.addChild(setWorkcenter, .4f, .9f, .6f, 1);
}
Button destroy = new Button(new Action(EActionType.DESTROY),
DESTROY, DESTROY, Labels.getName(EActionType.DESTROY));
panel.addChild(destroy, .8f, .9f, 1, 1);
UIPanel namePanel = new UIPanel() {
public void drawAt(GLDrawContext gl) {
gl.getTextDrawer(EFontSize.HEADLINE).renderCentered(getPosition().getCenterX(), getPosition().getCenterY(), Labels.getName(building.getBuildingType()));
}
};
panel.addChild(namePanel, 0, .8f, 1, .9f);
OccupyerPlace[] occupyerPlaces = building.getBuildingType().getOccupyerPlaces();
if (occupyerPlaces.length > 0) {
drawOccupyerPlaces(occupyerPlaces);
}
}
private void drawOccupyerPlaces(OccupyerPlace[] occupyerPlaces) {
int bottomindex = 0;
int topindex = 0;
for (OccupyerPlace place : occupyerPlaces) {
ImageLink link = SOILDER_MISSING;
Button button = new Button(null, link, link, "");
if (place.getType() == ESoldierType.BOWMAN) {
float left = topindex * .1f + .3f;
panel.addChild(button, left, .6f, left + .1f, .65f);
topindex++;
} else {
float left = bottomindex * .1f + .1f;
panel.addChild(button, left, .4f, left + .1f, .45f);
bottomindex++;
}
}
}
private static class BuidlingBackgroundPanel extends UIPanel {
private final ImageLink[] links;
public BuidlingBackgroundPanel(ImageLink[] links) {
this.links = links;
}
@Override
protected void drawBackground(GLDrawContext gl) {
float cx = getPosition().getCenterX();
float cy = getPosition().getCenterY();
for (ImageLink link : links) {
ImageProvider.getInstance().getImage(link).drawAt(gl, cx, cy);
}
}
}
@Override
public UIPanel getPanel() {
return panel;
}
@Override
public IContextListener getContextListener() {
return null;
}
@Override
public ESecondaryTabType getTabs() {
return null;
}
}
|
src/jsettlers/graphics/map/controls/original/panel/content/BuildingSelectionPanel.java
|
package jsettlers.graphics.map.controls.original.panel.content;
import go.graphics.GLDrawContext;
import go.graphics.text.EFontSize;
import jsettlers.common.buildings.IBuilding;
import jsettlers.common.buildings.OccupyerPlace;
import jsettlers.common.buildings.OccupyerPlace.EType;
import jsettlers.common.images.EImageLinkType;
import jsettlers.common.images.ImageLink;
import jsettlers.graphics.action.Action;
import jsettlers.graphics.action.EActionType;
import jsettlers.graphics.localization.Labels;
import jsettlers.graphics.map.controls.original.panel.IContextListener;
import jsettlers.graphics.map.draw.ImageProvider;
import jsettlers.graphics.map.selection.BuildingSelection;
import jsettlers.graphics.utils.Button;
import jsettlers.graphics.utils.UIPanel;
public class BuildingSelectionPanel implements IContentProvider {
private static final ImageLink SOILDER_MISSING = new ImageLink(EImageLinkType.GUI, 3, 45, 0);
private static final ImageLink SOILDER_COMMING = new ImageLink(EImageLinkType.GUI, 3, 48, 0);
private IBuilding building;
private UIPanel panel;
private static ImageLink SET_WORK_AREA = new ImageLink(EImageLinkType.GUI,
3, 201, 0);
private static ImageLink START_WORKING = new ImageLink(EImageLinkType.GUI,
3, 196, 0);
private static ImageLink STOP_WORKING = new ImageLink(EImageLinkType.GUI,
3, 192, 0);
private static ImageLink DESTROY = new ImageLink(EImageLinkType.GUI, 3,
198, 0);
public BuildingSelectionPanel(BuildingSelection selection) {
building = selection.getSelectedBuilding();
ImageLink[] images = building.getBuildingType().getImages();
panel = new BuidlingBackgroundPanel(images);
UIPanel changeWorking;
if (building.isWorking()) {
changeWorking =
new Button(new Action(EActionType.STOP_WORKING),
STOP_WORKING, STOP_WORKING, Labels.getName(EActionType.STOP_WORKING));
} else {
changeWorking =
new Button(new Action(EActionType.START_WORKING),
START_WORKING, START_WORKING, Labels.getName(EActionType.START_WORKING));
}
panel.addChild(changeWorking, 0, .9f, .2f, 1);
if (building.getBuildingType().getWorkradius() > 0) {
Button setWorkcenter = new Button(new Action(EActionType.SET_WORK_AREA),
SET_WORK_AREA, SET_WORK_AREA, Labels.getName(EActionType.SET_WORK_AREA));
panel.addChild(setWorkcenter, .4f, .9f, .6f, 1);
}
Button destroy = new Button(new Action(EActionType.DESTROY),
DESTROY, DESTROY, Labels.getName(EActionType.DESTROY));
panel.addChild(destroy, .8f, .9f, 1, 1);
UIPanel namePanel = new UIPanel() {
public void drawAt(GLDrawContext gl) {
gl.getTextDrawer(EFontSize.HEADLINE).renderCentered(getPosition().getCenterX(), getPosition().getCenterY(), Labels.getName(building.getBuildingType()));
}
};
panel.addChild(namePanel, 0, .8f, 1, .9f);
OccupyerPlace[] occupyerPlaces = building.getBuildingType().getOccupyerPlaces();
if (occupyerPlaces.length > 0) {
drawOccupyerPlaces(occupyerPlaces);
}
}
private void drawOccupyerPlaces(OccupyerPlace[] occupyerPlaces) {
int bottomindex = 0;
int topindex = 0;
for (OccupyerPlace place : occupyerPlaces) {
ImageLink link = SOILDER_MISSING;
Button button = new Button(null, link, link, "");
if (place.getType() == EType.BOWMAN) {
float left = topindex * .1f + .3f;
panel.addChild(button, left, .6f, left + .1f, .65f);
topindex++;
} else {
float left = bottomindex * .1f + .1f;
panel.addChild(button, left, .4f, left + .1f, .45f);
bottomindex++;
}
}
}
private static class BuidlingBackgroundPanel extends UIPanel {
private final ImageLink[] links;
public BuidlingBackgroundPanel(ImageLink[] links) {
this.links = links;
}
@Override
protected void drawBackground(GLDrawContext gl) {
float cx = getPosition().getCenterX();
float cy = getPosition().getCenterY();
for (ImageLink link : links) {
ImageProvider.getInstance().getImage(link).drawAt(gl, cx, cy);
}
}
}
@Override
public UIPanel getPanel() {
return panel;
}
@Override
public IContextListener getContextListener() {
return null;
}
@Override
public ESecondaryTabType getTabs() {
return null;
}
}
|
- towers can now request movables
- dijkstra can be executed partly
- for testing every tower requests two bowmans
- every tower initially placed on the map will be occupied by one swordsman
|
src/jsettlers/graphics/map/controls/original/panel/content/BuildingSelectionPanel.java
|
- towers can now request movables - dijkstra can be executed partly - for testing every tower requests two bowmans - every tower initially placed on the map will be occupied by one swordsman
|
<ide><path>rc/jsettlers/graphics/map/controls/original/panel/content/BuildingSelectionPanel.java
<ide> import go.graphics.text.EFontSize;
<ide> import jsettlers.common.buildings.IBuilding;
<ide> import jsettlers.common.buildings.OccupyerPlace;
<del>import jsettlers.common.buildings.OccupyerPlace.EType;
<add>import jsettlers.common.buildings.OccupyerPlace.ESoldierType;
<ide> import jsettlers.common.images.EImageLinkType;
<ide> import jsettlers.common.images.ImageLink;
<ide> import jsettlers.graphics.action.Action;
<ide> for (OccupyerPlace place : occupyerPlaces) {
<ide> ImageLink link = SOILDER_MISSING;
<ide> Button button = new Button(null, link, link, "");
<del> if (place.getType() == EType.BOWMAN) {
<add> if (place.getType() == ESoldierType.BOWMAN) {
<ide> float left = topindex * .1f + .3f;
<ide> panel.addChild(button, left, .6f, left + .1f, .65f);
<ide> topindex++;
|
|
Java
|
lgpl-2.1
|
9391de2a9a422f38abea57f54bf4a861bec700ce
| 0 |
wsnavely/soot-infoflow-android,xph906/FlowDroidInfoflowNew,jgarci40/soot-infoflow,secure-software-engineering/soot-infoflow,lilicoding/soot-infoflow,johspaeth/soot-infoflow
|
package soot.jimple.infoflow.util;
import soot.ArrayType;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.LongType;
import soot.PrimType;
import soot.RefType;
import soot.Scene;
import soot.ShortType;
import soot.SootClass;
import soot.Type;
import soot.jimple.infoflow.InfoflowManager;
import soot.jimple.infoflow.data.AccessPath;
/**
* Class containing various utility methods for dealing with type information
*
* @author Steven Arzt
*
*/
public class TypeUtils {
private final InfoflowManager manager;
public TypeUtils(InfoflowManager manager) {
this.manager = manager;
}
/**
* Checks whether the given type is a string
* @param tp The type of check
* @return True if the given type is a string, otherwise false
*/
public static boolean isStringType(Type tp) {
if (!(tp instanceof RefType))
return false;
RefType refType = (RefType) tp;
return refType.getClassName().equals("java.lang.String");
}
/**
* Checks whether the given type is java.lang.Object, java.io.Serializable,
* or java.lang.Cloneable.
* @param tp The type to check
* @return True if the given type is one of the three "object-like" types,
* otherwise false
*/
public static boolean isObjectLikeType(Type tp) {
if (!(tp instanceof RefType))
return false;
RefType rt = (RefType) tp;
return rt.equals(Scene.v().getObjectType())
|| rt.getSootClass().getName().equals("java.io.Serializable")
|| rt.getSootClass().getName().equals("java.lang.Cloneable");
}
/**
* Checks whether the given source type can be cast to the given destination
* type
* @param destType The destination type to which to cast
* @param sourceType The source type from which to cast
* @return True if the given types are cast-compatible, otherwise false
*/
public boolean checkCast(Type destType, Type sourceType) {
if (!manager.getConfig().getEnableTypeChecking())
return true;
// If we don't have a source type, we generally allow the cast
if (sourceType == null)
return true;
// If both types are equal, we allow the cast
if (sourceType == destType)
return true;
// If we have a reference type, we use the Soot hierarchy
if (Scene.v().getFastHierarchy().canStoreType(destType, sourceType) // cast-up, i.e. Object to String
|| Scene.v().getFastHierarchy().canStoreType(sourceType, destType)) // cast-down, i.e. String to Object
return true;
// If both types are primitive, they can be cast unless a boolean type
// is involved
if (destType instanceof PrimType && sourceType instanceof PrimType)
if (destType != BooleanType.v() && sourceType != BooleanType.v())
return true;
return false;
}
/**
* Checks whether the type of the given taint can be cast to the given
* target type
* @param accessPath The access path of the taint to be cast
* @param type The target type to which to cast the taint
* @return True if the cast is possible, otherwise false
*/
public boolean checkCast(AccessPath accessPath, Type type) {
if (!manager.getConfig().getEnableTypeChecking())
return true;
if (accessPath.isStaticFieldRef()) {
if (!checkCast(type, accessPath.getFirstFieldType()))
return false;
// If the target type is a primitive array, we cannot have any
// subsequent field
if (isPrimitiveArray(type))
return accessPath.getFieldCount() == 1;
return true;
}
else {
if (!checkCast(type, accessPath.getBaseType()))
return false;
// If the target type is a primitive array, we cannot have any
// subsequent fields
if (isPrimitiveArray(type))
return accessPath.isLocal();
return true;
}
}
public static boolean isPrimitiveArray(Type type) {
if (type instanceof ArrayType) {
ArrayType at = (ArrayType) type;
if (at.getArrayElementType() instanceof PrimType)
return true;
}
return false;
}
public boolean hasCompatibleTypesForCall(AccessPath apBase, SootClass dest) {
if (!manager.getConfig().getEnableTypeChecking())
return true;
// Cannot invoke a method on a primitive type
if (apBase.getBaseType() instanceof PrimType)
return false;
// Cannot invoke a method on an array
if (apBase.getBaseType() instanceof ArrayType)
return dest.getName().equals("java.lang.Object");
return Scene.v().getOrMakeFastHierarchy().canStoreType(apBase.getBaseType(), dest.getType())
|| Scene.v().getOrMakeFastHierarchy().canStoreType(dest.getType(), apBase.getBaseType());
}
/**
* Gets the more precise one of the two given types. If there is no ordering
* (i.e., the two types are not cast-compatible) null is returned.
* @param tp1 The first type
* @param tp2 The second type
* @return The more precise one of the two given types
*/
public static Type getMorePreciseType(Type tp1, Type tp2) {
if (tp1 == null)
return tp2;
else if (tp2 == null)
return tp1;
else if (tp1 == tp2)
return tp1;
else if (TypeUtils.isObjectLikeType(tp1))
return tp2;
else if (TypeUtils.isObjectLikeType(tp2))
return tp1;
else if (Scene.v().getFastHierarchy().canStoreType(tp2, tp1))
return tp2;
else if (Scene.v().getFastHierarchy().canStoreType(tp1, tp2))
return tp1;
else
return null;
}
/**
* Gets the more precise one of the two given types
* @param tp1 The first type
* @param tp2 The second type
* @return The more precise one of the two given types
*/
public static String getMorePreciseType(String tp1, String tp2) {
Type newType = getMorePreciseType(getTypeFromString(tp1),
getTypeFromString(tp2));
return newType == null ? null : "" + newType;
}
/**
* Creates a Soot Type from the given string
* @param type A string representing a Soot type
* @return The Soot Type corresponding to the given string
*/
public static Type getTypeFromString(String type) {
// Reduce arrays
int numDimensions = 0;
while (type.endsWith("[]")) {
numDimensions++;
type = type.substring(0, type.length() - 2);
}
// Generate the target type
final Type t;
if (type.equals("int"))
t = IntType.v();
else if (type.equals("long"))
t = LongType.v();
else if (type.equals("float"))
t = FloatType.v();
else if (type.equals("double"))
t = DoubleType.v();
else if (type.equals("boolean"))
t = BooleanType.v();
else if (type.equals("char"))
t = CharType.v();
else if (type.equals("short"))
t = ShortType.v();
else if (type.equals("byte"))
t = ByteType.v();
else
t = RefType.v(type);
if (numDimensions == 0)
return t;
return ArrayType.v(t, numDimensions);
}
}
|
src/soot/jimple/infoflow/util/TypeUtils.java
|
package soot.jimple.infoflow.util;
import soot.ArrayType;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.LongType;
import soot.PrimType;
import soot.RefType;
import soot.Scene;
import soot.ShortType;
import soot.SootClass;
import soot.Type;
import soot.jimple.infoflow.InfoflowManager;
import soot.jimple.infoflow.data.AccessPath;
/**
* Class containing various utility methods for dealing with type information
*
* @author Steven Arzt
*
*/
public class TypeUtils {
private final InfoflowManager manager;
public TypeUtils(InfoflowManager manager) {
this.manager = manager;
}
/**
* Checks whether the given type is a string
* @param tp The type of check
* @return True if the given type is a string, otherwise false
*/
public static boolean isStringType(Type tp) {
if (!(tp instanceof RefType))
return false;
RefType refType = (RefType) tp;
return refType.getClassName().equals("java.lang.String");
}
/**
* Checks whether the given type is java.lang.Object, java.io.Serializable,
* or java.lang.Cloneable.
* @param tp The type to check
* @return True if the given type is one of the three "object-like" types,
* otherwise false
*/
public static boolean isObjectLikeType(Type tp) {
if (!(tp instanceof RefType))
return false;
RefType rt = (RefType) tp;
return rt.equals(Scene.v().getObjectType())
|| rt.getSootClass().getName().equals("java.io.Serializable")
|| rt.getSootClass().getName().equals("java.lang.Cloneable");
}
/**
* Checks whether the given source type can be cast to the given destination
* type
* @param destType The destination type to which to cast
* @param sourceType The source type from which to cast
* @return True if the given types are cast-compatible, otherwise false
*/
public boolean checkCast(Type destType, Type sourceType) {
if (!manager.getConfig().getEnableTypeChecking())
return true;
// If we don't have a source type, we generally allow the cast
if (sourceType == null)
return true;
// If both types are equal, we allow the cast
if (sourceType == destType)
return true;
// If we have a reference type, we use the Soot hierarchy
if (Scene.v().getFastHierarchy().canStoreType(destType, sourceType) // cast-up, i.e. Object to String
|| Scene.v().getFastHierarchy().canStoreType(sourceType, destType)) // cast-down, i.e. String to Object
return true;
// If both types are primitive, they can be cast unless a boolean type
// is involved
if (destType instanceof PrimType && sourceType instanceof PrimType)
if (destType != BooleanType.v() && sourceType != BooleanType.v())
return true;
return false;
}
/**
* Checks whether the type of the given taint can be cast to the given
* target type
* @param accessPath The access path of the taint to be cast
* @param type The target type to which to cast the taint
* @return True if the cast is possible, otherwise false
*/
public boolean checkCast(AccessPath accessPath, Type type) {
if (!manager.getConfig().getEnableTypeChecking())
return true;
if (accessPath.isStaticFieldRef()) {
if (!checkCast(type, accessPath.getFirstFieldType()))
return false;
// If the target type is a primitive array, we cannot have any
// subsequent field
if (isPrimitiveArray(type))
return accessPath.getFieldCount() == 1;
return true;
}
else {
if (!checkCast(type, accessPath.getBaseType()))
return false;
// If the target type is a primitive array, we cannot have any
// subsequent fields
if (isPrimitiveArray(type))
return accessPath.isLocal();
return true;
}
}
public static boolean isPrimitiveArray(Type type) {
if (type instanceof ArrayType) {
ArrayType at = (ArrayType) type;
if (at.getArrayElementType() instanceof PrimType)
return true;
}
return false;
}
public boolean hasCompatibleTypesForCall(AccessPath apBase, SootClass dest) {
if (!manager.getConfig().getEnableTypeChecking())
return true;
// Cannot invoke a method on a primitive type
if (apBase.getBaseType() instanceof PrimType)
return false;
// Cannot invoke a method on an array
if (apBase.getBaseType() instanceof ArrayType)
return dest.getName().equals("java.lang.Object");
return Scene.v().getOrMakeFastHierarchy().canStoreType(apBase.getBaseType(), dest.getType())
|| Scene.v().getOrMakeFastHierarchy().canStoreType(dest.getType(), apBase.getBaseType());
}
/**
* Gets the more precise one of the two given types. If there is no ordering
* (i.e., the two types are not cast-compatible) null is returned.
* @param tp1 The first type
* @param tp2 The second type
* @return The more precise one of the two given types
*/
public static Type getMorePreciseType(Type tp1, Type tp2) {
if (tp1 == null)
return tp2;
else if (tp2 == null)
return tp1;
else if (tp1 == tp2)
return tp1;
else if (TypeUtils.isObjectLikeType(tp1))
return tp2;
else if (TypeUtils.isObjectLikeType(tp2))
return tp1;
else if (Scene.v().getFastHierarchy().canStoreType(tp2, tp1))
return tp2;
else if (Scene.v().getFastHierarchy().canStoreType(tp1, tp2))
return tp1;
else
return null;
}
/**
* Gets the more precise one of the two given types
* @param tp1 The first type
* @param tp2 The second type
* @return The more precise one of the two given types
*/
public static String getMorePreciseType(String tp1, String tp2) {
return "" + getMorePreciseType(getTypeFromString(tp1),
getTypeFromString(tp2));
}
/**
* Creates a Soot Type from the given string
* @param type A string representing a Soot type
* @return The Soot Type corresponding to the given string
*/
public static Type getTypeFromString(String type) {
// Reduce arrays
int numDimensions = 0;
while (type.endsWith("[]")) {
numDimensions++;
type = type.substring(0, type.length() - 2);
}
// Generate the target type
final Type t;
if (type.equals("int"))
t = IntType.v();
else if (type.equals("long"))
t = LongType.v();
else if (type.equals("float"))
t = FloatType.v();
else if (type.equals("double"))
t = DoubleType.v();
else if (type.equals("boolean"))
t = BooleanType.v();
else if (type.equals("char"))
t = CharType.v();
else if (type.equals("short"))
t = ShortType.v();
else if (type.equals("byte"))
t = ByteType.v();
else
t = RefType.v(type);
if (numDimensions == 0)
return t;
return ArrayType.v(t, numDimensions);
}
}
|
fixed an NPE
|
src/soot/jimple/infoflow/util/TypeUtils.java
|
fixed an NPE
|
<ide><path>rc/soot/jimple/infoflow/util/TypeUtils.java
<ide> * @return The more precise one of the two given types
<ide> */
<ide> public static String getMorePreciseType(String tp1, String tp2) {
<del> return "" + getMorePreciseType(getTypeFromString(tp1),
<add> Type newType = getMorePreciseType(getTypeFromString(tp1),
<ide> getTypeFromString(tp2));
<add> return newType == null ? null : "" + newType;
<ide> }
<ide>
<ide> /**
|
|
Java
|
bsd-3-clause
|
a7671bd00908200e0efa00ef3e7c58f0512a7088
| 0 |
Speiger/Nuclear-Control,Ghostlyr/Nuclear-Control,Adaptivity/Nuclear-Control
|
package shedar.mods.ic2.nuclearcontrol.items;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.Vector;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChunkCoordinates;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidTankInfo;
import shedar.mods.ic2.nuclearcontrol.api.CardState;
import shedar.mods.ic2.nuclearcontrol.api.ICardWrapper;
import shedar.mods.ic2.nuclearcontrol.api.PanelSetting;
import shedar.mods.ic2.nuclearcontrol.api.PanelString;
import shedar.mods.ic2.nuclearcontrol.panel.CardWrapperImpl;
import shedar.mods.ic2.nuclearcontrol.utils.LangHelper;
import shedar.mods.ic2.nuclearcontrol.utils.LiquidStorageHelper;
import shedar.mods.ic2.nuclearcontrol.utils.StringUtils;
public class ItemCardLiquidArrayLocation extends ItemCardBase {
public static final int DISPLAY_NAME = 1;
public static final int DISPLAY_AMOUNT = 2;
public static final int DISPLAY_FREE = 4;
public static final int DISPLAY_CAPACITY = 8;
public static final int DISPLAY_PERCENTAGE = 16;
public static final int DISPLAY_EACH = 32;
public static final int DISPLAY_TOTAL = 64;
private static final int STATUS_NOT_FOUND = Integer.MIN_VALUE;
private static final int STATUS_OUT_OF_RANGE = Integer.MIN_VALUE + 1;
public static final UUID CARD_TYPE = new UUID(0, 3);
public ItemCardLiquidArrayLocation() {
super("cardLiquidArray");
}
private int[] getCoordinates(ICardWrapper card, int cardNumber) {
int cardCount = card.getInt("cardCount");
if (cardNumber >= cardCount)
return null;
int[] coordinates = new int[] {
card.getInt(String.format("_%dx", cardNumber)),
card.getInt(String.format("_%dy", cardNumber)),
card.getInt(String.format("_%dz", cardNumber)) };
return coordinates;
}
public static int getCardCount(ICardWrapper card) {
return card.getInt("cardCount");
}
public static void initArray(CardWrapperImpl card, Vector<ItemStack> cards) {
int cardCount = getCardCount(card);
for (ItemStack subCard : cards) {
CardWrapperImpl wrapper = new CardWrapperImpl(subCard, -1);
ChunkCoordinates target = wrapper.getTarget();
if (target == null)
continue;
card.setInt(String.format("_%dx", cardCount), target.posX);
card.setInt(String.format("_%dy", cardCount), target.posY);
card.setInt(String.format("_%dz", cardCount), target.posZ);
card.setInt(String.format("_%dtargetType", cardCount),
wrapper.getInt("targetType"));
cardCount++;
}
card.setInt("cardCount", cardCount);
}
@Override
public CardState update(TileEntity panel, ICardWrapper card, int range) {
int cardCount = getCardCount(card);
double totalAmount = 0.0;
if (cardCount == 0) {
return CardState.INVALID_CARD;
} else {
boolean foundAny = false;
boolean outOfRange = false;
int liquidId = 0;
for (int i = 0; i < cardCount; i++) {
int[] coordinates = getCoordinates(card, i);
int dx = coordinates[0] - panel.xCoord;
int dy = coordinates[1] - panel.yCoord;
int dz = coordinates[2] - panel.zCoord;
if (Math.abs(dx) <= range && Math.abs(dy) <= range
&& Math.abs(dz) <= range) {
FluidTankInfo storage = LiquidStorageHelper.getStorageAt(
panel.getWorldObj(), coordinates[0],
coordinates[1], coordinates[2]);
if (storage != null) {
if (storage.fluid != null) {
totalAmount += storage.fluid.amount;
card.setInt(String.format("_%damount", i),
storage.fluid.amount);
if (storage.fluid.getFluidID() != 0
&& storage.fluid.amount > 0) {
liquidId = storage.fluid.getFluidID();
}
if (liquidId == 0)
card.setString(String.format("_%dname", i), LangHelper.translate("msg.nc.None"));
else
card.setString(String.format("_%dname", i), FluidRegistry.getFluidName(storage.fluid));
}
card.setInt(String.format("_%dcapacity", i),
storage.capacity);
foundAny = true;
} else {
card.setInt(String.format("_%damount", i),
STATUS_NOT_FOUND);
}
} else {
card.setInt(String.format("_%damount", i),
STATUS_OUT_OF_RANGE);
outOfRange = true;
}
}
card.setDouble("energyL", totalAmount);
if (!foundAny) {
if (outOfRange)
return CardState.OUT_OF_RANGE;
else
return CardState.NO_TARGET;
}
return CardState.OK;
}
}
@Override
public UUID getCardType() {
return CARD_TYPE;
}
@Override
public List<PanelString> getStringData(int displaySettings, ICardWrapper card, boolean showLabels) {
List<PanelString> result = new LinkedList<PanelString>();
PanelString line;
double totalAmount = 0;
double totalCapacity = 0;
boolean showEach = (displaySettings & DISPLAY_EACH) > 0;
boolean showSummary = (displaySettings & DISPLAY_TOTAL) > 0;
boolean showName = (displaySettings & DISPLAY_NAME) > 0;
boolean showAmount = true;// (displaySettings & DISPLAY_AMOUNT) > 0;
boolean showFree = (displaySettings & DISPLAY_FREE) > 0;
boolean showCapacity = (displaySettings & DISPLAY_CAPACITY) > 0;
boolean showPercentage = (displaySettings & DISPLAY_PERCENTAGE) > 0;
int cardCount = getCardCount(card);
for (int i = 0; i < cardCount; i++) {
int amount = card.getInt(String.format("_%damount", i));
int capacity = card.getInt(String.format("_%dcapacity", i));
boolean isOutOfRange = amount == STATUS_OUT_OF_RANGE;
boolean isNotFound = amount == STATUS_NOT_FOUND;
if (showSummary && !isOutOfRange && !isNotFound) {
totalAmount += amount;
totalCapacity += capacity;
}
if (showEach) {
if (isOutOfRange) {
line = new PanelString();
line.textLeft = StringUtils.getFormattedKey("msg.nc.InfoPanelOutOfRangeN", i + 1);
result.add(line);
} else if (isNotFound) {
line = new PanelString();
line.textLeft = StringUtils.getFormattedKey("msg.nc.InfoPanelNotFoundN", i + 1);
result.add(line);
} else {
if (showName) {
line = new PanelString();
if (showLabels)
line.textLeft = StringUtils.getFormattedKey("msg.nc.InfoPanelLiquidNameN",
i + 1, card.getString(String.format("_%dname", i)));
else
line.textLeft = StringUtils.getFormatted("", amount, false);
result.add(line);
}
if (showAmount) {
line = new PanelString();
if (showLabels)
line.textLeft = StringUtils.getFormattedKey("msg.nc.InfoPanelLiquidN",
i + 1, StringUtils.getFormatted("", amount, false));
else
line.textLeft = StringUtils.getFormatted("", amount, false);
result.add(line);
}
if (showFree) {
line = new PanelString();
if (showLabels)
line.textLeft = StringUtils.getFormattedKey("msg.nc.InfoPanelLiquidFreeN",
i + 1, StringUtils.getFormatted("", capacity - amount, false));
else
line.textLeft = StringUtils.getFormatted("", capacity - amount, false);
result.add(line);
}
if (showCapacity) {
line = new PanelString();
if (showLabels)
line.textLeft = StringUtils.getFormattedKey("msg.nc.InfoPanelLiquidCapacityN",
i + 1, StringUtils.getFormatted("", capacity, false));
else
line.textLeft = StringUtils.getFormatted("", capacity, false);
result.add(line);
}
if (showPercentage) {
line = new PanelString();
if (showLabels)
line.textLeft = StringUtils.getFormattedKey("msg.nc.InfoPanelLiquidPercentageN",
i + 1, StringUtils.getFormatted("",
capacity == 0 ? 100 : (((double) amount) * 100L / capacity), false));
else
line.textLeft = StringUtils.getFormatted("",
capacity == 0 ? 100 : (((double) amount) * 100L / capacity), false);
result.add(line);
}
}
}
}
if (showSummary) {
if (showAmount) {
line = new PanelString();
line.textLeft = StringUtils.getFormatted("msg.nc.InfoPanelLiquidAmount", totalAmount, showLabels);
result.add(line);
}
if (showFree) {
line = new PanelString();
line.textLeft = StringUtils.getFormatted("msg.nc.InfoPanelLiquidFree",
totalCapacity - totalAmount, showLabels);
result.add(line);
}
if (showName) {
line = new PanelString();
line.textLeft = StringUtils.getFormatted("msg.nc.InfoPanelLiquidCapacity", totalCapacity, showLabels);
result.add(line);
}
if (showPercentage) {
line = new PanelString();
line.textLeft = StringUtils.getFormatted("msg.nc.InfoPanelLiquidPercentage",
totalCapacity == 0 ? 100 : (totalAmount * 100 / totalCapacity), showLabels);
result.add(line);
}
}
return result;
}
@Override
public List<PanelSetting> getSettingsList() {
List<PanelSetting> result = new ArrayList<PanelSetting>(3);
result.add(new PanelSetting(LangHelper.translate("msg.nc.cbInfoPanelLiquidName"), DISPLAY_NAME, CARD_TYPE));
// result.add(new
// PanelSetting(LanguageHelper.translate("msg.nc.cbInfoPanelLiquidAmount"),
// DISPLAY_AMOUNT, CARD_TYPE));
result.add(new PanelSetting(LangHelper.translate("msg.nc.cbInfoPanelLiquidFree"), DISPLAY_FREE, CARD_TYPE));
result.add(new PanelSetting(LangHelper.translate("msg.nc.cbInfoPanelLiquidCapacity"), DISPLAY_CAPACITY, CARD_TYPE));
result.add(new PanelSetting(LangHelper.translate("msg.nc.cbInfoPanelLiquidPercentage"), DISPLAY_PERCENTAGE, CARD_TYPE));
result.add(new PanelSetting(LangHelper.translate("msg.nc.cbInfoPanelLiquidEach"), DISPLAY_EACH, CARD_TYPE));
result.add(new PanelSetting(LangHelper.translate("msg.nc.cbInfoPanelLiquidTotal"), DISPLAY_TOTAL, CARD_TYPE));
return result;
}
@Override
@SideOnly(Side.CLIENT)
@SuppressWarnings({ "rawtypes", "unchecked" })
public void addInformation(ItemStack itemStack, EntityPlayer player, List info, boolean advanced) {
CardWrapperImpl card = new CardWrapperImpl(itemStack, -1);
int cardCount = getCardCount(card);
if (cardCount > 0) {
String title = card.getTitle();
if (title != null && !title.isEmpty()) {
info.add(title);
}
String hint = String.format(LangHelper.translate("msg.nc.LiquidCardQuantity"), cardCount);
info.add(hint);
}
}
}
|
src/main/java/shedar/mods/ic2/nuclearcontrol/items/ItemCardLiquidArrayLocation.java
|
package shedar.mods.ic2.nuclearcontrol.items;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.Vector;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChunkCoordinates;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidTankInfo;
import shedar.mods.ic2.nuclearcontrol.api.CardState;
import shedar.mods.ic2.nuclearcontrol.api.ICardWrapper;
import shedar.mods.ic2.nuclearcontrol.api.PanelSetting;
import shedar.mods.ic2.nuclearcontrol.api.PanelString;
import shedar.mods.ic2.nuclearcontrol.panel.CardWrapperImpl;
import shedar.mods.ic2.nuclearcontrol.utils.LangHelper;
import shedar.mods.ic2.nuclearcontrol.utils.LiquidStorageHelper;
import shedar.mods.ic2.nuclearcontrol.utils.StringUtils;
public class ItemCardLiquidArrayLocation extends ItemCardBase {
public static final int DISPLAY_NAME = 1;
public static final int DISPLAY_AMOUNT = 2;
public static final int DISPLAY_FREE = 4;
public static final int DISPLAY_CAPACITY = 8;
public static final int DISPLAY_PERCENTAGE = 16;
public static final int DISPLAY_EACH = 32;
public static final int DISPLAY_TOTAL = 64;
private static final int STATUS_NOT_FOUND = Integer.MIN_VALUE;
private static final int STATUS_OUT_OF_RANGE = Integer.MIN_VALUE + 1;
public static final UUID CARD_TYPE = new UUID(0, 3);
public ItemCardLiquidArrayLocation() {
super("cardLiquidArray");
}
private int[] getCoordinates(ICardWrapper card, int cardNumber) {
int cardCount = card.getInt("cardCount");
if (cardNumber >= cardCount)
return null;
int[] coordinates = new int[] {
card.getInt(String.format("_%dx", cardNumber)),
card.getInt(String.format("_%dy", cardNumber)),
card.getInt(String.format("_%dz", cardNumber)) };
return coordinates;
}
public static int getCardCount(ICardWrapper card) {
return card.getInt("cardCount");
}
public static void initArray(CardWrapperImpl card, Vector<ItemStack> cards) {
int cardCount = getCardCount(card);
for (ItemStack subCard : cards) {
CardWrapperImpl wrapper = new CardWrapperImpl(subCard, -1);
ChunkCoordinates target = wrapper.getTarget();
if (target == null)
continue;
card.setInt(String.format("_%dx", cardCount), target.posX);
card.setInt(String.format("_%dy", cardCount), target.posY);
card.setInt(String.format("_%dz", cardCount), target.posZ);
card.setInt(String.format("_%dtargetType", cardCount),
wrapper.getInt("targetType"));
cardCount++;
}
card.setInt("cardCount", cardCount);
}
@Override
public CardState update(TileEntity panel, ICardWrapper card, int range) {
int cardCount = getCardCount(card);
double totalAmount = 0.0;
if (cardCount == 0) {
return CardState.INVALID_CARD;
} else {
boolean foundAny = false;
boolean outOfRange = false;
int liquidId = 0;
for (int i = 0; i < cardCount; i++) {
int[] coordinates = getCoordinates(card, i);
int dx = coordinates[0] - panel.xCoord;
int dy = coordinates[1] - panel.yCoord;
int dz = coordinates[2] - panel.zCoord;
if (Math.abs(dx) <= range && Math.abs(dy) <= range
&& Math.abs(dz) <= range) {
FluidTankInfo storage = LiquidStorageHelper.getStorageAt(
panel.getWorldObj(), coordinates[0],
coordinates[1], coordinates[2]);
if (storage != null) {
if (storage.fluid != null) {
totalAmount += storage.fluid.amount;
card.setInt(String.format("_%damount", i),
storage.fluid.amount);
if (storage.fluid.fluidID != 0
&& storage.fluid.amount > 0) {
liquidId = storage.fluid.fluidID;
}
if (liquidId == 0)
card.setString(String.format("_%dname", i),
LangHelper.translate("msg.nc.None"));
else
card.setString(String.format("_%dname", i),
FluidRegistry.getFluidName(liquidId));
}
card.setInt(String.format("_%dcapacity", i),
storage.capacity);
foundAny = true;
} else {
card.setInt(String.format("_%damount", i),
STATUS_NOT_FOUND);
}
} else {
card.setInt(String.format("_%damount", i),
STATUS_OUT_OF_RANGE);
outOfRange = true;
}
}
card.setDouble("energyL", totalAmount);
if (!foundAny) {
if (outOfRange)
return CardState.OUT_OF_RANGE;
else
return CardState.NO_TARGET;
}
return CardState.OK;
}
}
@Override
public UUID getCardType() {
return CARD_TYPE;
}
@Override
public List<PanelString> getStringData(int displaySettings, ICardWrapper card, boolean showLabels) {
List<PanelString> result = new LinkedList<PanelString>();
PanelString line;
double totalAmount = 0;
double totalCapacity = 0;
boolean showEach = (displaySettings & DISPLAY_EACH) > 0;
boolean showSummary = (displaySettings & DISPLAY_TOTAL) > 0;
boolean showName = (displaySettings & DISPLAY_NAME) > 0;
boolean showAmount = true;// (displaySettings & DISPLAY_AMOUNT) > 0;
boolean showFree = (displaySettings & DISPLAY_FREE) > 0;
boolean showCapacity = (displaySettings & DISPLAY_CAPACITY) > 0;
boolean showPercentage = (displaySettings & DISPLAY_PERCENTAGE) > 0;
int cardCount = getCardCount(card);
for (int i = 0; i < cardCount; i++) {
int amount = card.getInt(String.format("_%damount", i));
int capacity = card.getInt(String.format("_%dcapacity", i));
boolean isOutOfRange = amount == STATUS_OUT_OF_RANGE;
boolean isNotFound = amount == STATUS_NOT_FOUND;
if (showSummary && !isOutOfRange && !isNotFound) {
totalAmount += amount;
totalCapacity += capacity;
}
if (showEach) {
if (isOutOfRange) {
line = new PanelString();
line.textLeft = StringUtils.getFormattedKey("msg.nc.InfoPanelOutOfRangeN", i + 1);
result.add(line);
} else if (isNotFound) {
line = new PanelString();
line.textLeft = StringUtils.getFormattedKey("msg.nc.InfoPanelNotFoundN", i + 1);
result.add(line);
} else {
if (showName) {
line = new PanelString();
if (showLabels)
line.textLeft = StringUtils.getFormattedKey("msg.nc.InfoPanelLiquidNameN",
i + 1, card.getString(String.format("_%dname", i)));
else
line.textLeft = StringUtils.getFormatted("", amount, false);
result.add(line);
}
if (showAmount) {
line = new PanelString();
if (showLabels)
line.textLeft = StringUtils.getFormattedKey("msg.nc.InfoPanelLiquidN",
i + 1, StringUtils.getFormatted("", amount, false));
else
line.textLeft = StringUtils.getFormatted("", amount, false);
result.add(line);
}
if (showFree) {
line = new PanelString();
if (showLabels)
line.textLeft = StringUtils.getFormattedKey("msg.nc.InfoPanelLiquidFreeN",
i + 1, StringUtils.getFormatted("", capacity - amount, false));
else
line.textLeft = StringUtils.getFormatted("", capacity - amount, false);
result.add(line);
}
if (showCapacity) {
line = new PanelString();
if (showLabels)
line.textLeft = StringUtils.getFormattedKey("msg.nc.InfoPanelLiquidCapacityN",
i + 1, StringUtils.getFormatted("", capacity, false));
else
line.textLeft = StringUtils.getFormatted("", capacity, false);
result.add(line);
}
if (showPercentage) {
line = new PanelString();
if (showLabels)
line.textLeft = StringUtils.getFormattedKey("msg.nc.InfoPanelLiquidPercentageN",
i + 1, StringUtils.getFormatted("",
capacity == 0 ? 100 : (((double) amount) * 100L / capacity), false));
else
line.textLeft = StringUtils.getFormatted("",
capacity == 0 ? 100 : (((double) amount) * 100L / capacity), false);
result.add(line);
}
}
}
}
if (showSummary) {
if (showAmount) {
line = new PanelString();
line.textLeft = StringUtils.getFormatted("msg.nc.InfoPanelLiquidAmount", totalAmount, showLabels);
result.add(line);
}
if (showFree) {
line = new PanelString();
line.textLeft = StringUtils.getFormatted("msg.nc.InfoPanelLiquidFree",
totalCapacity - totalAmount, showLabels);
result.add(line);
}
if (showName) {
line = new PanelString();
line.textLeft = StringUtils.getFormatted("msg.nc.InfoPanelLiquidCapacity", totalCapacity, showLabels);
result.add(line);
}
if (showPercentage) {
line = new PanelString();
line.textLeft = StringUtils.getFormatted("msg.nc.InfoPanelLiquidPercentage",
totalCapacity == 0 ? 100 : (totalAmount * 100 / totalCapacity), showLabels);
result.add(line);
}
}
return result;
}
@Override
public List<PanelSetting> getSettingsList() {
List<PanelSetting> result = new ArrayList<PanelSetting>(3);
result.add(new PanelSetting(LangHelper.translate("msg.nc.cbInfoPanelLiquidName"), DISPLAY_NAME, CARD_TYPE));
// result.add(new
// PanelSetting(LanguageHelper.translate("msg.nc.cbInfoPanelLiquidAmount"),
// DISPLAY_AMOUNT, CARD_TYPE));
result.add(new PanelSetting(LangHelper.translate("msg.nc.cbInfoPanelLiquidFree"), DISPLAY_FREE, CARD_TYPE));
result.add(new PanelSetting(LangHelper.translate("msg.nc.cbInfoPanelLiquidCapacity"), DISPLAY_CAPACITY, CARD_TYPE));
result.add(new PanelSetting(LangHelper.translate("msg.nc.cbInfoPanelLiquidPercentage"), DISPLAY_PERCENTAGE, CARD_TYPE));
result.add(new PanelSetting(LangHelper.translate("msg.nc.cbInfoPanelLiquidEach"), DISPLAY_EACH, CARD_TYPE));
result.add(new PanelSetting(LangHelper.translate("msg.nc.cbInfoPanelLiquidTotal"), DISPLAY_TOTAL, CARD_TYPE));
return result;
}
@Override
@SideOnly(Side.CLIENT)
@SuppressWarnings({ "rawtypes", "unchecked" })
public void addInformation(ItemStack itemStack, EntityPlayer player, List info, boolean advanced) {
CardWrapperImpl card = new CardWrapperImpl(itemStack, -1);
int cardCount = getCardCount(card);
if (cardCount > 0) {
String title = card.getTitle();
if (title != null && !title.isEmpty()) {
info.add(title);
}
String hint = String.format(LangHelper.translate("msg.nc.LiquidCardQuantity"), cardCount);
info.add(hint);
}
}
}
|
fixes liquid issues
|
src/main/java/shedar/mods/ic2/nuclearcontrol/items/ItemCardLiquidArrayLocation.java
|
fixes liquid issues
|
<ide><path>rc/main/java/shedar/mods/ic2/nuclearcontrol/items/ItemCardLiquidArrayLocation.java
<ide> card.setInt(String.format("_%damount", i),
<ide> storage.fluid.amount);
<ide>
<del> if (storage.fluid.fluidID != 0
<add> if (storage.fluid.getFluidID() != 0
<ide> && storage.fluid.amount > 0) {
<del> liquidId = storage.fluid.fluidID;
<add> liquidId = storage.fluid.getFluidID();
<ide> }
<ide> if (liquidId == 0)
<del> card.setString(String.format("_%dname", i),
<del> LangHelper.translate("msg.nc.None"));
<add> card.setString(String.format("_%dname", i), LangHelper.translate("msg.nc.None"));
<ide> else
<del> card.setString(String.format("_%dname", i),
<del> FluidRegistry.getFluidName(liquidId));
<add> card.setString(String.format("_%dname", i), FluidRegistry.getFluidName(storage.fluid));
<ide> }
<ide> card.setInt(String.format("_%dcapacity", i),
<ide> storage.capacity);
|
|
Java
|
unlicense
|
error: pathspec 'RabinKarp.java' did not match any file(s) known to git
|
e6c7fe82fa6c111cfd233b2708f7b85366c59070
| 1 |
rchen8/Algorithms,rchen8/Algorithms
|
public class RabinKarp {
private static final int BASE = 101;
private static final int MOD = 1_000_007;
private static int hash(String pattern) {
int hashCode = 0;
for (int i = 0; i < pattern.length(); i++)
hashCode += (pattern.charAt(i) * Math.round(Math.pow(BASE,
pattern.length() - i)))
% MOD;
return hashCode;
}
private static int rabinKarp(String s, String pattern) {
int hpattern = hash(pattern);
int hs = hash(s.substring(0, pattern.length()));
for (int i = 0; i < s.length() - pattern.length(); i++) {
if (hs == hpattern)
if (s.substring(i, i + pattern.length()).equals(pattern))
return i;
hs = hash(s.substring(i + 1, i + 1 + pattern.length()));
}
return -1;
}
public static void main(String[] args) {
System.out.println(rabinKarp("ABC ABCDAB ABCDABCDABDE", "ABCDABD"));
}
}
|
RabinKarp.java
|
Create RabinKarp.java
|
RabinKarp.java
|
Create RabinKarp.java
|
<ide><path>abinKarp.java
<add>public class RabinKarp {
<add>
<add> private static final int BASE = 101;
<add> private static final int MOD = 1_000_007;
<add>
<add> private static int hash(String pattern) {
<add> int hashCode = 0;
<add> for (int i = 0; i < pattern.length(); i++)
<add> hashCode += (pattern.charAt(i) * Math.round(Math.pow(BASE,
<add> pattern.length() - i)))
<add> % MOD;
<add> return hashCode;
<add> }
<add>
<add> private static int rabinKarp(String s, String pattern) {
<add> int hpattern = hash(pattern);
<add> int hs = hash(s.substring(0, pattern.length()));
<add> for (int i = 0; i < s.length() - pattern.length(); i++) {
<add> if (hs == hpattern)
<add> if (s.substring(i, i + pattern.length()).equals(pattern))
<add> return i;
<add> hs = hash(s.substring(i + 1, i + 1 + pattern.length()));
<add> }
<add> return -1;
<add> }
<add>
<add> public static void main(String[] args) {
<add> System.out.println(rabinKarp("ABC ABCDAB ABCDABCDABDE", "ABCDABD"));
<add> }
<add>
<add>}
|
|
Java
|
apache-2.0
|
3fe2edefab3afefa1f581651662de4be900f17ed
| 0 |
henrichg/PhoneProfilesPlus
|
package sk.henrichg.phoneprofilesplus;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.WallpaperManager;
import android.app.admin.DevicePolicyManager;
import android.appwidget.AppWidgetManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Icon;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.provider.Settings.Global;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.RemoteViews;
import com.stericson.RootShell.execution.Command;
import com.stericson.RootShell.execution.Shell;
import com.stericson.RootTools.RootTools;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.List;
import static android.content.Context.DEVICE_POLICY_SERVICE;
public class ActivateProfileHelper {
private DataWrapper dataWrapper;
private Context context;
private NotificationManager notificationManager;
private Handler brightnessHandler;
//private int networkType = -1;
static boolean lockRefresh = false;
static final String ADAPTIVE_BRIGHTNESS_SETTING_NAME = "screen_auto_brightness_adj";
// Setting.Global "zen_mode"
static final int ZENMODE_ALL = 0;
static final int ZENMODE_PRIORITY = 1;
static final int ZENMODE_NONE = 2;
static final int ZENMODE_ALARMS = 3;
@SuppressWarnings("WeakerAccess")
static final int ZENMODE_SILENT = 99;
public ActivateProfileHelper()
{
}
public void initialize(DataWrapper dataWrapper, Context c)
{
this.dataWrapper = dataWrapper;
initializeNoNotificationManager(c);
notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
}
private void initializeNoNotificationManager(Context c)
{
context = c;
}
void deinitialize()
{
dataWrapper = null;
context = null;
notificationManager = null;
}
void setBrightnessHandler(Handler handler)
{
brightnessHandler = handler;
}
@SuppressWarnings("deprecation")
private void doExecuteForRadios(Profile profile)
{
PPApplication.sleep(300);
// nahodenie network type
if (profile._deviceNetworkType >= 100) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_NETWORK_TYPE, context) == PPApplication.PREFERENCE_ALLOWED) {
setPreferredNetworkType(context, profile._deviceNetworkType - 100);
//try { Thread.sleep(200); } catch (InterruptedException e) { }
//SystemClock.sleep(200);
PPApplication.sleep(200);
}
}
// nahodenie mobilnych dat
if (profile._deviceMobileData != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_MOBILE_DATA, context) == PPApplication.PREFERENCE_ALLOWED) {
boolean _isMobileData = isMobileData(context);
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios","_isMobileData="+_isMobileData);
boolean _setMobileData = false;
switch (profile._deviceMobileData) {
case 1:
if (!_isMobileData) {
_isMobileData = true;
_setMobileData = true;
}
break;
case 2:
if (_isMobileData) {
_isMobileData = false;
_setMobileData = true;
}
break;
case 3:
_isMobileData = !_isMobileData;
_setMobileData = true;
break;
}
if (_setMobileData) {
setMobileData(context, _isMobileData);
//try { Thread.sleep(200); } catch (InterruptedException e) { }
//SystemClock.sleep(200);
PPApplication.sleep(200);
}
}
}
// nahodenie WiFi AP
boolean canChangeWifi = true;
if (profile._deviceWiFiAP != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_WIFI_AP, context) == PPApplication.PREFERENCE_ALLOWED) {
WifiApManager wifiApManager = null;
try {
wifiApManager = new WifiApManager(context);
} catch (Exception ignored) {
}
if (wifiApManager != null) {
boolean setWifiAPState = false;
boolean isWifiAPEnabled = wifiApManager.isWifiAPEnabled();
switch (profile._deviceWiFiAP) {
case 1:
if (!isWifiAPEnabled) {
isWifiAPEnabled = true;
setWifiAPState = true;
canChangeWifi = false;
}
break;
case 2:
if (isWifiAPEnabled) {
isWifiAPEnabled = false;
setWifiAPState = true;
canChangeWifi = true;
}
break;
case 3:
isWifiAPEnabled = !isWifiAPEnabled;
setWifiAPState = true;
canChangeWifi = !isWifiAPEnabled;
break;
}
if (setWifiAPState) {
wifiApManager.setWifiApState(isWifiAPEnabled);
//try { Thread.sleep(200); } catch (InterruptedException e) { }
//SystemClock.sleep(200);
PPApplication.sleep(200);
}
}
}
}
if (canChangeWifi) {
// nahodenie WiFi
if (profile._deviceWiFi != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_WIFI, context) == PPApplication.PREFERENCE_ALLOWED) {
boolean isWifiAPEnabled = WifiApManager.isWifiAPEnabled(context);
if (!isWifiAPEnabled) { // only when wifi AP is not enabled, change wifi
PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.doExecuteForRadios-isWifiAPEnabled=false");
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int wifiState = wifiManager.getWifiState();
boolean isWifiEnabled = ((wifiState == WifiManager.WIFI_STATE_ENABLED) || (wifiState == WifiManager.WIFI_STATE_ENABLING));
boolean setWifiState = false;
switch (profile._deviceWiFi) {
case 1:
if (!isWifiEnabled) {
isWifiEnabled = true;
setWifiState = true;
}
break;
case 2:
if (isWifiEnabled) {
isWifiEnabled = false;
setWifiState = true;
}
break;
case 3:
isWifiEnabled = !isWifiEnabled;
setWifiState = true;
break;
}
if (isWifiEnabled)
// when wifi is enabled from profile, no disable wifi after scan
WifiScanAlarmBroadcastReceiver.setWifiEnabledForScan(context, false);
if (setWifiState) {
try {
wifiManager.setWifiEnabled(isWifiEnabled);
} catch (Exception e) {
wifiManager.setWifiEnabled(isWifiEnabled);
}
//try { Thread.sleep(200); } catch (InterruptedException e) { }
//SystemClock.sleep(200);
PPApplication.sleep(200);
}
}
}
}
// connect to SSID
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_CONNECT_TO_SSID, context) == PPApplication.PREFERENCE_ALLOWED) {
if (!profile._deviceConnectToSSID.equals(Profile.CONNECTTOSSID_JUSTANY)) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int wifiState = wifiManager.getWifiState();
if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
// check if wifi is connected
ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connManager.getActiveNetworkInfo();
boolean wifiConnected = (activeNetwork != null) &&
(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) &&
activeNetwork.isConnected();
WifiInfo wifiInfo = null;
if (wifiConnected)
wifiInfo = wifiManager.getConnectionInfo();
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals(profile._deviceConnectToSSID)) {
if (wifiConnected) {
if (!wifiInfo.getSSID().equals(i.SSID)) {
PhoneProfilesService.connectToSSIDStarted = true;
// conected to another SSID
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
}
} else
wifiManager.enableNetwork(i.networkId, true);
break;
}
}
}
}
//else {
// WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
// int wifiState = wifiManager.getWifiState();
// if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
// wifiManager.disconnect();
// wifiManager.reconnect();
// }
//}
PhoneProfilesService.connectToSSID = profile._deviceConnectToSSID;
}
}
// nahodenie bluetooth
if (profile._deviceBluetooth != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_BLUETOOTH, context) == PPApplication.PREFERENCE_ALLOWED) {
PPApplication.logE("ActivateProfileHelper.doExecuteForRadios","setBluetooth");
BluetoothAdapter bluetoothAdapter = BluetoothScanAlarmBroadcastReceiver.getBluetoothAdapter(context);
if (bluetoothAdapter != null) {
boolean isBluetoothEnabled = bluetoothAdapter.isEnabled();
boolean setBluetoothState = false;
switch (profile._deviceBluetooth) {
case 1:
if (!isBluetoothEnabled) {
isBluetoothEnabled = true;
setBluetoothState = true;
}
break;
case 2:
if (isBluetoothEnabled) {
isBluetoothEnabled = false;
setBluetoothState = true;
}
break;
case 3:
isBluetoothEnabled = !isBluetoothEnabled;
setBluetoothState = true;
break;
}
PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "setBluetoothState="+setBluetoothState);
PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "isBluetoothEnabled="+isBluetoothEnabled);
if (isBluetoothEnabled) {
// when bluetooth is enabled from profile, no disable bluetooth after scan
PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "isBluetoothEnabled=true; setBluetoothEnabledForScan=false");
BluetoothScanAlarmBroadcastReceiver.setBluetoothEnabledForScan(context, false);
}
if (setBluetoothState) {
if (isBluetoothEnabled)
bluetoothAdapter.enable();
else
bluetoothAdapter.disable();
}
}
}
}
// nahodenie GPS
if (profile._deviceGPS != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_GPS, context) == PPApplication.PREFERENCE_ALLOWED) {
//String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
boolean isEnabled;
if (android.os.Build.VERSION.SDK_INT < 19)
isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
else {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "isEnabled=" + isEnabled);
switch (profile._deviceGPS) {
case 1:
setGPS(context, true);
break;
case 2:
setGPS(context, false);
break;
case 3:
if (!isEnabled) {
setGPS(context, true);
} else {
setGPS(context, false);
}
break;
}
}
}
// nahodenie NFC
if (profile._deviceNFC != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_NFC, context) == PPApplication.PREFERENCE_ALLOWED) {
//Log.e("ActivateProfileHelper.doExecuteForRadios", "allowed");
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
if (nfcAdapter != null) {
switch (profile._deviceNFC) {
case 1:
setNFC(context, true);
break;
case 2:
setNFC(context, false);
break;
case 3:
if (!nfcAdapter.isEnabled()) {
setNFC(context, true);
} else if (nfcAdapter.isEnabled()) {
setNFC(context, false);
}
break;
}
}
}
//else
// Log.e("ActivateProfileHelper.doExecuteForRadios", "not allowed");
}
}
void executeForRadios(Profile profile)
{
boolean _isAirplaneMode = false;
boolean _setAirplaneMode = false;
if (profile._deviceAirplaneMode != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_AIRPLANE_MODE, context) == PPApplication.PREFERENCE_ALLOWED) {
_isAirplaneMode = isAirplaneMode(context);
switch (profile._deviceAirplaneMode) {
case 1:
if (!_isAirplaneMode) {
_isAirplaneMode = true;
_setAirplaneMode = true;
}
break;
case 2:
if (_isAirplaneMode) {
_isAirplaneMode = false;
_setAirplaneMode = true;
}
break;
case 3:
_isAirplaneMode = !_isAirplaneMode;
_setAirplaneMode = true;
break;
}
}
}
if (_setAirplaneMode /*&& _isAirplaneMode*/) {
// switch ON airplane mode, set it before executeForRadios
setAirplaneMode(context, _isAirplaneMode);
PPApplication.sleep(2000);
}
doExecuteForRadios(profile);
/*if (_setAirplaneMode && (!_isAirplaneMode)) {
// 200 miliseconds is in doExecuteForRadios
PPApplication.sleep(1800);
// switch OFF airplane mode, set if after executeForRadios
setAirplaneMode(context, _isAirplaneMode);
}*/
}
static boolean isAudibleRinging(int ringerMode, int zenMode) {
return (!((ringerMode == 3) || (ringerMode == 4) ||
((ringerMode == 5) && ((zenMode == 3) || (zenMode == 4) || (zenMode == 5) || (zenMode == 6)))
));
}
private boolean isVibrateRingerMode(int ringerMode, int zenMode) {
return (ringerMode == 3);
}
/*
private void correctVolume0(AudioManager audioManager) {
int ringerMode, zenMode;
ringerMode = PPApplication.getRingerMode(context);
zenMode = PPApplication.getZenMode(context);
if ((ringerMode == 1) || (ringerMode == 2) || (ringerMode == 4) ||
((ringerMode == 5) && ((zenMode == 1) || (zenMode == 2)))) {
// any "nonVIBRATE" ringer mode is selected
if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
// actual system ringer mode = vibrate
// volume changed it to vibrate
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_RING, 1, 0);
PhoneProfilesService.ringingVolume = 1;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, 1);
}
}
}
*/
@SuppressLint("NewApi")
void setVolumes(Profile profile, AudioManager audioManager, int linkUnlink, boolean forProfileActivation)
{
if (profile.getVolumeRingtoneChange()) {
if (forProfileActivation)
PPApplication.setRingerVolume(context, profile.getVolumeRingtoneValue());
}
if (profile.getVolumeNotificationChange()) {
if (forProfileActivation)
PPApplication.setNotificationVolume(context, profile.getVolumeNotificationValue());
}
int ringerMode = PPApplication.getRingerMode(context);
int zenMode = PPApplication.getZenMode(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "ringerMode=" + ringerMode);
PPApplication.logE("ActivateProfileHelper.setVolumes", "zenMode=" + zenMode);
PPApplication.logE("ActivateProfileHelper.setVolumes", "linkUnlink=" + linkUnlink);
PPApplication.logE("ActivateProfileHelper.setVolumes", "forProfileActivation=" + forProfileActivation);
// for ringer mode VIBRATE or SILENT or
// for interruption types NONE and ONLY_ALARMS
// not set system, ringer, notification volume
// (Android 6 - priority mode = ONLY_ALARMS)
if (isAudibleRinging(ringerMode, zenMode)) {
PPApplication.logE("ActivateProfileHelper.setVolumes", "ringer/notif/system change");
//if (Permissions.checkAccessNotificationPolicy(context)) {
if (forProfileActivation) {
if (profile.getVolumeSystemChange()) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, profile.getVolumeSystemValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_SYSTEM, profile.getVolumeSystemValue());
//correctVolume0(audioManager);
} catch (Exception ignored) { }
}
}
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
int callState = telephony.getCallState();
boolean volumesSet = false;
if (PPApplication.getMergedRingNotificationVolumes(context) && PPApplication.applicationUnlinkRingerNotificationVolumes) {
//if (doUnlink) {
//if (linkUnlink == PhoneCallBroadcastReceiver.LINKMODE_UNLINK) {
if (callState == TelephonyManager.CALL_STATE_RINGING) {
// for separating ringing and notification
// in ringing state ringer volumes must by set
// and notification volumes must not by set
int volume = PPApplication.getRingerVolume(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-RINGING ringer volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0);
PhoneProfilesService.ringingVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
//correctVolume0(audioManager);
} catch (Exception ignored) { }
}
volumesSet = true;
} else if (linkUnlink == PhoneCallService.LINKMODE_LINK) {
// for separating ringing and notification
// in not ringing state ringer and notification volume must by change
//Log.e("ActivateProfileHelper","setVolumes get audio mode="+audioManager.getMode());
int volume = PPApplication.getRingerVolume(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING-link ringer volume=" + volume);
if (volume != -999) {
//Log.e("ActivateProfileHelper","setVolumes set ring volume="+volume);
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0);
PhoneProfilesService.ringingVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
} catch (Exception ignored) { }
}
volume = PPApplication.getNotificationVolume(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING-link notification volume=" + volume);
if (volume != -999) {
//Log.e("ActivateProfileHelper","setVolumes set notification volume="+volume);
try {
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
} catch (Exception ignored) { }
}
//correctVolume0(audioManager);
volumesSet = true;
} else {
int volume = PPApplication.getRingerVolume(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING ringer volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0);
PhoneProfilesService.ringingVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, volume);
//correctVolume0(audioManager);
} catch (Exception ignored) { }
}
volume = PPApplication.getNotificationVolume(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING notification volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, volume);
//correctVolume0(audioManager);
} catch (Exception ignored) { }
}
volumesSet = true;
}
/*}
else {
if (callState == TelephonyManager.CALL_STATE_RINGING) {
int volume = PPApplication.getRingerVolume(context);
if (volume == -999)
volume = audioManager.getStreamVolume(AudioManager.STREAM_RING);
PhoneProfilesService.ringingVolume = volume;
}
}*/
}
if (!volumesSet) {
// reverted order for disabled unlink
int volume;
if (!PPApplication.getMergedRingNotificationVolumes(context)) {
volume = PPApplication.getNotificationVolume(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "no doUnlink notification volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, volume);
//correctVolume0(audioManager);
} catch (Exception ignored) { }
}
}
volume = PPApplication.getRingerVolume(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "no doUnlink ringer volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0);
PhoneProfilesService.ringingVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, volume);
//correctVolume0(audioManager);
} catch (Exception ignored) { }
}
}
//}
//else
// PPApplication.logE("ActivateProfileHelper.setVolumes", "not granted");
}
if (forProfileActivation) {
if (profile.getVolumeMediaChange()) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, profile.getVolumeMediaValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_MUSIC, profile.getVolumeMediaValue());
}
if (profile.getVolumeAlarmChange()) {
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, profile.getVolumeAlarmValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_ALARM, profile.getVolumeAlarmValue());
}
if (profile.getVolumeVoiceChange()) {
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, profile.getVolumeVoiceValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_VOICE, profile.getVolumeVoiceValue());
}
}
}
private void setZenMode(int zenMode, AudioManager audioManager, int ringerMode)
{
if (android.os.Build.VERSION.SDK_INT >= 21)
{
int _zenMode = PPApplication.getSystemZenMode(context, -1);
PPApplication.logE("ActivateProfileHelper.setZenMode", "_zenMode=" + _zenMode);
int _ringerMode = audioManager.getRingerMode();
PPApplication.logE("ActivateProfileHelper.setZenMode", "_ringerMode=" + _ringerMode);
if ((zenMode != ZENMODE_SILENT) && PPApplication.canChangeZenMode(context, false)) {
audioManager.setRingerMode(ringerMode);
//try { Thread.sleep(500); } catch (InterruptedException e) { }
//SystemClock.sleep(500);
PPApplication.sleep(500);
if ((zenMode != _zenMode) || (zenMode == ZENMODE_PRIORITY)) {
PPNotificationListenerService.requestInterruptionFilter(context, zenMode);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(context, zenMode);
}
} else {
switch (zenMode) {
case ZENMODE_SILENT:
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
//try { Thread.sleep(1000); } catch (InterruptedException e) { }
//SystemClock.sleep(1000);
PPApplication.sleep(1000);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
break;
default:
audioManager.setRingerMode(ringerMode);
}
}
}
else
audioManager.setRingerMode(ringerMode);
}
private void setVibrateWhenRinging(Profile profile, int value) {
int lValue = value;
if (profile != null) {
switch (profile._vibrateWhenRinging) {
case 1:
lValue = 1;
break;
case 2:
lValue = 0;
break;
}
}
if (lValue != -1) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_VIBRATE_WHEN_RINGING, context)
== PPApplication.PREFERENCE_ALLOWED) {
if (Permissions.checkProfileVibrateWhenRinging(context, profile)) {
if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception)
Settings.System.putInt(context.getContentResolver(), "vibrate_when_ringing", lValue);
else {
try {
Settings.System.putInt(context.getContentResolver(), Settings.System.VIBRATE_WHEN_RINGING, lValue);
} catch (Exception ee) {
String command1 = "settings put system " + Settings.System.VIBRATE_WHEN_RINGING + " " + lValue;
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setVibrateWhenRinging", "Error on run su: " + e.toString());
}
}
}
}
}
}
}
void setTones(Profile profile) {
if (Permissions.checkProfileRingtones(context, profile)) {
if (profile._soundRingtoneChange == 1) {
if (!profile._soundRingtone.isEmpty()) {
try {
//Settings.System.putString(context.getContentResolver(), Settings.System.RINGTONE, profile._soundRingtone);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, Uri.parse(profile._soundRingtone));
}
catch (Exception ignored){ }
} else {
// selected is None tone
try {
//Settings.System.putString(context.getContentResolver(), Settings.System.RINGTONE, null);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, null);
}
catch (Exception ignored){ }
}
}
if (profile._soundNotificationChange == 1) {
if (!profile._soundNotification.isEmpty()) {
try {
//Settings.System.putString(context.getContentResolver(), Settings.System.NOTIFICATION_SOUND, profile._soundNotification);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, Uri.parse(profile._soundNotification));
}
catch (Exception ignored){ }
} else {
// selected is None tone
try {
//Settings.System.putString(context.getContentResolver(), Settings.System.NOTIFICATION_SOUND, null);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, null);
}
catch (Exception ignored){ }
}
}
if (profile._soundAlarmChange == 1) {
if (!profile._soundAlarm.isEmpty()) {
try {
//Settings.System.putString(context.getContentResolver(), Settings.System.ALARM_ALERT, profile._soundAlarm);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, Uri.parse(profile._soundAlarm));
}
catch (Exception ignored){ }
} else {
// selected is None tone
try {
//Settings.System.putString(context.getContentResolver(), Settings.System.ALARM_ALERT, null);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, null);
}
catch (Exception ignored){ }
}
}
}
}
private void setNotificationLed(int value) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_NOTIFICATION_LED, context)
== PPApplication.PREFERENCE_ALLOWED) {
if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception)
Settings.System.putInt(context.getContentResolver(), "notification_light_pulse", value);
else {
String command1 = "settings put system " + "notification_light_pulse" + " " + value;
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setNotificationLed", "Error on run su: " + e.toString());
}
}
}
}
void changeRingerModeForVolumeEqual0(Profile profile) {
if (profile.getVolumeRingtoneChange()) {
//int ringerMode = PPApplication.getRingerMode(context);
//int zenMode = PPApplication.getZenMode(context);
//PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "ringerMode=" + ringerMode);
//PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "zenMode=" + zenMode);
if (profile.getVolumeRingtoneValue() == 0) {
profile.setVolumeRingtoneValue(1);
// for profile ringer/zen mode = "only vibrate" do not change ringer mode to Silent
if (!isVibrateRingerMode(profile._volumeRingerMode, profile._volumeZenMode)) {
// for ringer mode VIBRATE or SILENT or
// for interruption types NONE and ONLY_ALARMS
// not change ringer mode
// (Android 6 - priority mode = ONLY_ALARMS)
if (isAudibleRinging(profile._volumeRingerMode, profile._volumeZenMode)) {
// change ringer mode to Silent
PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "changed to silent");
profile._volumeRingerMode = 4;
}
}
}
}
}
void changeNotificationVolumeForVolumeEqual0(Profile profile) {
if (profile.getVolumeNotificationChange() && PPApplication.getMergedRingNotificationVolumes(context)) {
if (profile.getVolumeNotificationValue() == 0) {
PPApplication.logE("ActivateProfileHelper.changeNotificationVolumeForVolumeEqual0", "changed notification value to 1");
profile.setVolumeNotificationValue(1);
}
}
}
@SuppressWarnings("deprecation")
void setRingerMode(Profile profile, AudioManager audioManager, boolean firstCall, boolean forProfileActivation)
{
//PPApplication.logE("@@@ ActivateProfileHelper.setRingerMode", "andioM.ringerMode=" + audioManager.getRingerMode());
int ringerMode;
int zenMode;
if (forProfileActivation) {
if (profile._volumeRingerMode != 0) {
PPApplication.setRingerMode(context, profile._volumeRingerMode);
if ((profile._volumeRingerMode == 5) && (profile._volumeZenMode != 0))
PPApplication.setZenMode(context, profile._volumeZenMode);
}
}
if (firstCall)
return;
ringerMode = PPApplication.getRingerMode(context);
zenMode = PPApplication.getZenMode(context);
PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringerMode=" + ringerMode);
PPApplication.logE("ActivateProfileHelper.setRingerMode", "zenMode=" + zenMode);
if (forProfileActivation) {
PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringer mode change");
switch (ringerMode) {
case 1: // Ring
setZenMode(ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); not needed, called from setZenMode
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ignored) {
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ignored) {
}
setVibrateWhenRinging(null, 0);
break;
case 2: // Ring & Vibrate
setZenMode(ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); not needed, called from setZenMode
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ignored) {
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ignored) {
}
setVibrateWhenRinging(null, 1);
break;
case 3: // Vibrate
setZenMode(ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_VIBRATE);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); not needed, called from setZenMode
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ignored) {
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ignored) {
}
setVibrateWhenRinging(null, 1);
break;
case 4: // Silent
if (android.os.Build.VERSION.SDK_INT >= 21) {
//setZenMode(ZENMODE_SILENT, audioManager, AudioManager.RINGER_MODE_SILENT);
setZenMode(ZENMODE_SILENT, audioManager, AudioManager.RINGER_MODE_NORMAL);
}
else {
setZenMode(ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_SILENT);
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ignored) {
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ignored) {
}
}
setVibrateWhenRinging(null, 0);
break;
case 5: // Zen mode
switch (zenMode) {
case 1:
setZenMode(ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL);
setVibrateWhenRinging(profile, -1);
break;
case 2:
setZenMode(ZENMODE_PRIORITY, audioManager, AudioManager.RINGER_MODE_NORMAL);
setVibrateWhenRinging(profile, -1);
break;
case 3:
// must be AudioManager.RINGER_MODE_SILENT, because, ZENMODE_NONE set it to silent
// without this, duplicate set this zen mode not working
setZenMode(ZENMODE_NONE, audioManager, AudioManager.RINGER_MODE_SILENT);
break;
case 4:
setZenMode(ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_VIBRATE);
setVibrateWhenRinging(null, 1);
break;
case 5:
setZenMode(ZENMODE_PRIORITY, audioManager, AudioManager.RINGER_MODE_VIBRATE);
setVibrateWhenRinging(null, 1);
break;
case 6:
// must be AudioManager.RINGER_MODE_SILENT, because, ZENMODE_ALARMS set it to silent
// without this, duplicate set this zen mode not working
setZenMode(ZENMODE_ALARMS, audioManager, AudioManager.RINGER_MODE_SILENT);
break;
}
break;
}
}
}
void executeForWallpaper(Profile profile) {
if (profile._deviceWallpaperChange == 1)
{
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
if (android.os.Build.VERSION.SDK_INT >= 17)
display.getRealMetrics(displayMetrics);
else
display.getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
//noinspection SuspiciousNameCombination
height = displayMetrics.widthPixels;
//noinspection SuspiciousNameCombination
width = displayMetrics.heightPixels;
}
//Log.d("ActivateProfileHelper.executeForWallpaper", "height="+height);
//Log.d("ActivateProfileHelper.executeForWallpaper", "width="+width);
// for lock screen no double width
if ((android.os.Build.VERSION.SDK_INT < 24) || (profile._deviceWallpaperFor != 2))
width = width << 1; // best wallpaper width is twice screen width
Bitmap decodedSampleBitmap = BitmapManipulator.resampleBitmap(profile.getDeviceWallpaperIdentifier(), width, height, context);
if (decodedSampleBitmap != null)
{
// set wallpaper
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
try {
if (android.os.Build.VERSION.SDK_INT >= 24) {
int flags = WallpaperManager.FLAG_SYSTEM | WallpaperManager.FLAG_LOCK;
Rect visibleCropHint = null;
if (profile._deviceWallpaperFor == 1)
flags = WallpaperManager.FLAG_SYSTEM;
if (profile._deviceWallpaperFor == 2) {
flags = WallpaperManager.FLAG_LOCK;
int left = 0;
int right = decodedSampleBitmap.getWidth();
if (decodedSampleBitmap.getWidth() > width) {
left = (decodedSampleBitmap.getWidth() / 2) - (width / 2);
right = (decodedSampleBitmap.getWidth() / 2) + (width / 2);
}
visibleCropHint = new Rect(left, 0, right, decodedSampleBitmap.getHeight());
}
//noinspection WrongConstant
wallpaperManager.setBitmap(decodedSampleBitmap, visibleCropHint, true, flags);
}
else
wallpaperManager.setBitmap(decodedSampleBitmap);
} catch (IOException e) {
Log.e("ActivateProfileHelper.executeForWallpaper", "Cannot set wallpaper. Image="+profile.getDeviceWallpaperIdentifier());
}
}
}
}
// not working, returns only calling process :-/
// http://stackoverflow.com/questions/30619349/android-5-1-1-and-above-getrunningappprocesses-returns-my-application-packag
/*private boolean isRunning(List<ActivityManager.RunningAppProcessInfo> procInfos, String packageName) {
PPApplication.logE("ActivateProfileHelper.executeForRunApplications", "procInfos.size()="+procInfos.size());
for(int i = 0; i < procInfos.size(); i++)
{
ActivityManager.RunningAppProcessInfo procInfo = procInfos.get(i);
PPApplication.logE("ActivateProfileHelper.executeForRunApplications", "procInfo.processName="+procInfo.processName);
if (procInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
PPApplication.logE("ActivateProfileHelper.executeForRunApplications", "procInfo.importance=IMPORTANCE_FOREGROUND");
for (String pkgName : procInfo.pkgList) {
PPApplication.logE("ActivateProfileHelper.executeForRunApplications", "pkgName="+pkgName);
if (pkgName.equals(packageName))
return true;
}
}
}
return false;
}*/
void executeForRunApplications(Profile profile) {
if (profile._deviceRunApplicationChange == 1)
{
String[] splits = profile._deviceRunApplicationPackageName.split("\\|");
Intent intent;
PackageManager packageManager = context.getPackageManager();
//ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
for (int i = 0; i < splits.length; i++) {
//Log.d("ActivateProfileHelper.executeForRunApplications","app data="+splits[i]);
if (!ApplicationsCache.isShortcut(splits[i])) {
//Log.d("ActivateProfileHelper.executeForRunApplications","no shortcut");
String packageName = ApplicationsCache.getPackageName(splits[i]);
intent = packageManager.getLaunchIntentForPackage(packageName);
if (intent != null) {
//if (!isRunning(procInfos, packageName)) {
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName+": not running");
//Log.d("ActivateProfileHelper.executeForRunApplications","intent="+intent);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (Exception ignored) {
}
//try { Thread.sleep(1000); } catch (InterruptedException e) { }
//SystemClock.sleep(1000);
PPApplication.sleep(1000);
//}
//else
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName+": running");
}
}
else {
//Log.d("ActivateProfileHelper.executeForRunApplications","shortcut");
long shortcutId = ApplicationsCache.getShortcutId(splits[i]);
//Log.d("ActivateProfileHelper.executeForRunApplications","shortcutId="+shortcutId);
if (shortcutId > 0) {
Shortcut shortcut = dataWrapper.getDatabaseHandler().getShortcut(shortcutId);
if (shortcut != null) {
try {
intent = Intent.parseUri(shortcut._intent, 0);
if (intent != null) {
//String packageName = intent.getPackage();
//if (!isRunning(procInfos, packageName)) {
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName + ": not running");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//Log.d("ActivateProfileHelper.executeForRunApplications","intent="+intent);
try {
context.startActivity(intent);
} catch (Exception ignored) {
}
//try { Thread.sleep(1000); } catch (InterruptedException e) { }
//SystemClock.sleep(1000);
PPApplication.sleep(1000);
//} else
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName + ": running");
}
} catch (Exception ignored) {
}
}
}
}
}
}
}
public void execute(Profile _profile, boolean merged, boolean _interactive)
{
// rozdelit zvonenie a notifikacie - zial je to oznacene ako @Hide :-(
//Settings.System.putInt(context.getContentResolver(), Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 0);
Profile profile = PPApplication.getMappedProfile(_profile, context);
// nahodenie volume
// run service for execute volumes
PPApplication.logE("ActivateProfileHelper.execute", "ExecuteVolumeProfilePrefsService");
Intent volumeServiceIntent = new Intent(context, ExecuteVolumeProfilePrefsService.class);
volumeServiceIntent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);
volumeServiceIntent.putExtra(PPApplication.EXTRA_MERGED_PROFILE, merged);
volumeServiceIntent.putExtra(PPApplication.EXTRA_FOR_PROFILE_ACTIVATION, true);
context.startService(volumeServiceIntent);
/*AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
// nahodenie ringer modu - aby sa mohli nastavit hlasitosti
setRingerMode(profile, audioManager);
setVolumes(profile, audioManager);
// nahodenie ringer modu - hlasitosti zmenia silent/vibrate
setRingerMode(profile, audioManager);*/
// set vibration on touch
if (Permissions.checkProfileVibrationOnTouch(context, profile)) {
switch (profile._vibrationOnTouch) {
case 1:
Settings.System.putInt(context.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 1);
break;
case 2:
Settings.System.putInt(context.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 0);
break;
}
}
// nahodenie tonov
// moved to ExecuteVolumeProfilePrefsService
//setTones(profile);
//// nahodenie radio preferences
// run service for execute radios
Intent radioServiceIntent = new Intent(context, ExecuteRadioProfilePrefsService.class);
radioServiceIntent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);
radioServiceIntent.putExtra(PPApplication.EXTRA_MERGED_PROFILE, merged);
context.startService(radioServiceIntent);
// nahodenie auto-sync
boolean _isAutosync = ContentResolver.getMasterSyncAutomatically();
boolean _setAutosync = false;
switch (profile._deviceAutosync) {
case 1:
if (!_isAutosync)
{
_isAutosync = true;
_setAutosync = true;
}
break;
case 2:
if (_isAutosync)
{
_isAutosync = false;
_setAutosync = true;
}
break;
case 3:
_isAutosync = !_isAutosync;
_setAutosync = true;
break;
}
if (_setAutosync)
ContentResolver.setMasterSyncAutomatically(_isAutosync);
// screen timeout
if (Permissions.checkProfileScreenTimeout(context, profile)) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//noinspection deprecation
if (pm.isScreenOn()) {
//Log.d("ActivateProfileHelper.execute","screen on");
setScreenTimeout(profile._deviceScreenTimeout);
}
else {
//Log.d("ActivateProfileHelper.execute","screen off");
PPApplication.setActivatedProfileScreenTimeout(context, profile._deviceScreenTimeout);
}
}
//else
// PPApplication.setActivatedProfileScreenTimeout(context, 0);
// zapnutie/vypnutie lockscreenu
//PPApplication.logE("$$$ ActivateProfileHelper.execute","keyguard");
boolean setLockscreen = false;
switch (profile._deviceKeyguard) {
case 1:
// enable lockscreen
PPApplication.logE("$$$ ActivateProfileHelper.execute","keyguard=ON");
PPApplication.setLockscreenDisabled(context, false);
setLockscreen = true;
break;
case 2:
// disable lockscreen
PPApplication.logE("$$$ ActivateProfileHelper.execute","keyguard=OFF");
PPApplication.setLockscreenDisabled(context, true);
setLockscreen = true;
break;
}
if (setLockscreen) {
boolean isScreenOn;
//if (android.os.Build.VERSION.SDK_INT >= 20)
//{
// Display display = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
// isScreenOn = display.getState() != Display.STATE_OFF;
//}
//else
//{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//noinspection deprecation
isScreenOn = pm.isScreenOn();
//}
PPApplication.logE("$$$ ActivateProfileHelper.execute","isScreenOn="+isScreenOn);
boolean keyguardShowing;
KeyguardManager kgMgr = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 16)
keyguardShowing = kgMgr.isKeyguardLocked();
else
keyguardShowing = kgMgr.inKeyguardRestrictedInputMode();
PPApplication.logE("$$$ ActivateProfileHelper.execute","keyguardShowing="+keyguardShowing);
if (isScreenOn && !keyguardShowing) {
Intent keyguardService = new Intent(context.getApplicationContext(), KeyguardService.class);
context.startService(keyguardService);
}
}
// nahodenie podsvietenia
if (Permissions.checkProfileScreenBrightness(context, profile)) {
if (profile.getDeviceBrightnessChange()) {
PPApplication.logE("ActivateProfileHelper.execute", "set brightness: profile=" + profile._name);
PPApplication.logE("ActivateProfileHelper.execute", "set brightness: _deviceBrightness=" + profile._deviceBrightness);
if (profile.getDeviceBrightnessAutomatic()) {
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
profile.getDeviceBrightnessManualValue(context));
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_ADAPTIVE_BRIGHTNESS, context)
== PPApplication.PREFERENCE_ALLOWED) {
if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception)
Settings.System.putFloat(context.getContentResolver(),
ADAPTIVE_BRIGHTNESS_SETTING_NAME,
profile.getDeviceBrightnessAdaptiveValue(context));
else {
try {
Settings.System.putFloat(context.getContentResolver(),
ADAPTIVE_BRIGHTNESS_SETTING_NAME,
profile.getDeviceBrightnessAdaptiveValue(context));
} catch (Exception ee) {
String command1 = "settings put system " + ADAPTIVE_BRIGHTNESS_SETTING_NAME + " " +
Float.toString(profile.getDeviceBrightnessAdaptiveValue(context));
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.execute", "Error on run su: " + e.toString());
}
}
}
}
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
} else {
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
profile.getDeviceBrightnessManualValue(context));
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
}
if (brightnessHandler != null) {
final Context __context = context;
brightnessHandler.post(new Runnable() {
public void run() {
createBrightnessView(__context);
}
});
} else
createBrightnessView(context);
}
}
// nahodenie rotate
if (Permissions.checkProfileAutoRotation(context, profile)) {
switch (profile._deviceAutoRotate) {
case 1:
// set autorotate on
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 2:
// set autorotate off
// degree 0
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 3:
// set autorotate off
// degree 90
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_90);
break;
case 4:
// set autorotate off
// degree 180
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_180);
break;
case 5:
// set autorotate off
// degree 270
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_270);
break;
}
}
// set notification led
if (profile._notificationLed != 0) {
//if (Permissions.checkProfileNotificationLed(context, profile)) { not needed for Android 6+, because root is required
switch (profile._notificationLed) {
case 1:
setNotificationLed(1);
break;
case 2:
setNotificationLed(0);
break;
}
//}
}
// nahodenie pozadia
if (Permissions.checkProfileWallpaper(context, profile)) {
if (profile._deviceWallpaperChange == 1) {
Intent wallpaperServiceIntent = new Intent(context, ExecuteWallpaperProfilePrefsService.class);
wallpaperServiceIntent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);
wallpaperServiceIntent.putExtra(PPApplication.EXTRA_MERGED_PROFILE, merged);
context.startService(wallpaperServiceIntent);
}
}
// set power save mode
if (profile._devicePowerSaveMode != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_POWER_SAVE_MODE, context) == PPApplication.PREFERENCE_ALLOWED) {
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean _isPowerSaveMode = false;
if (Build.VERSION.SDK_INT >= 21)
_isPowerSaveMode = powerManager.isPowerSaveMode();
boolean _setPowerSaveMode = false;
switch (profile._devicePowerSaveMode) {
case 1:
if (!_isPowerSaveMode) {
_isPowerSaveMode = true;
_setPowerSaveMode = true;
}
break;
case 2:
if (_isPowerSaveMode) {
_isPowerSaveMode = false;
_setPowerSaveMode = true;
}
break;
case 3:
_isPowerSaveMode = !_isPowerSaveMode;
_setPowerSaveMode = true;
break;
}
if (_setPowerSaveMode) {
setPowerSaveMode(_isPowerSaveMode);
}
}
}
if (Permissions.checkProfileLockDevice(context, profile)) {
if (profile._lockDevice != 0) {
lockDevice(profile);
}
}
if (_interactive)
{
// preferences, ktore vyzaduju interakciu uzivatela
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_MOBILE_DATA_PREFS, context) == PPApplication.PREFERENCE_ALLOWED)
{
if (profile._deviceMobileDataPrefs == 1)
{
/*try {
final Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
final ComponentName componentName = new ComponentName("com.android.phone", "com.android.phone.Settings");
intent.setComponent(componentName);
context.startActivity(intent);
PPApplication.logE("#### ActivateProfileHelper.execute","mobile data prefs. 1");
} catch (Exception e) {
PPApplication.logE("#### ActivateProfileHelper.execute","mobile data prefs. 1 E="+e);
try {
final Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
PPApplication.logE("#### ActivateProfileHelper.execute","mobile data prefs. 2");
} catch (Exception e2) {
e2.printStackTrace();
PPApplication.logE("#### ActivateProfileHelper.execute","mobile data prefs. 2 E="+e2);
}
}*/
try {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setComponent(new ComponentName("com.android.settings","com.android.settings.Settings$DataUsageSummaryActivity"));
context.startActivity(intent);
} catch (Exception ignored) {
}
}
}
//if (PPApplication.hardwareCheck(PPApplication.PREF_PROFILE_DEVICE_GPS, context))
//{ No check only GPS
if (profile._deviceLocationServicePrefs == 1)
{
try {
final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} catch (Exception ignored) {
}
}
//}
if (profile._deviceRunApplicationChange == 1)
{
Intent runApplicationsServiceIntent = new Intent(context, ExecuteRunApplicationsProfilePrefsService.class);
runApplicationsServiceIntent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);
runApplicationsServiceIntent.putExtra(PPApplication.EXTRA_MERGED_PROFILE, merged);
context.startService(runApplicationsServiceIntent);
}
}
}
void setScreenTimeout(int screenTimeout) {
DisableScreenTimeoutInternalChangeReceiver.internalChange = true;
//Log.d("ActivateProfileHelper.setScreenTimeout", "current="+Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 0));
switch (screenTimeout) {
case 1:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 15000);
break;
case 2:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000);
break;
case 3:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 60000);
break;
case 4:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 120000);
break;
case 5:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 600000);
break;
case 6:
//2147483647 = Integer.MAX_VALUE
//18000000 = 5 hours
//86400000 = 24 hounrs
//43200000 = 12 hours
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 86400000); //18000000);
break;
case 7:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 300000);
break;
case 8:
screenTimeoutUnlock(context);
//if (android.os.Build.VERSION.SDK_INT < 19) // not working in Sony
// Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, -1);
//else
screenTimeoutLock(context);
break;
}
PPApplication.setActivatedProfileScreenTimeout(context, 0);
DisableScreenTimeoutInternalChangeReceiver.setAlarm(context);
}
private static void screenTimeoutLock(Context context)
{
//Log.d("ActivateProfileHelper.screenTimeoutLock","xxx");
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
screenTimeoutUnlock(context);
int type;
if (android.os.Build.VERSION.SDK_INT < 25)
type = WindowManager.LayoutParams.TYPE_TOAST;
else
type = LayoutParams.TYPE_SYSTEM_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
type,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | /*WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |*/ WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
PixelFormat.TRANSLUCENT
);
/*if (android.os.Build.VERSION.SDK_INT < 17)
params.gravity = Gravity.RIGHT | Gravity.TOP;
else
params.gravity = Gravity.END | Gravity.TOP;*/
GlobalGUIRoutines.keepScreenOnView = new BrightnessView(context);
try {
windowManager.addView(GlobalGUIRoutines.keepScreenOnView, params);
} catch (Exception e) {
GlobalGUIRoutines.keepScreenOnView = null;
//e.printStackTrace();
}
//Log.d("ActivateProfileHelper.screenTimeoutLock","-- end");
}
static void screenTimeoutUnlock(Context context)
{
//Log.d("ActivateProfileHelper.screenTimeoutUnlock","xxx");
if (GlobalGUIRoutines.keepScreenOnView != null)
{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
try {
windowManager.removeView(GlobalGUIRoutines.keepScreenOnView);
} catch (Exception ignored) {
}
GlobalGUIRoutines.keepScreenOnView = null;
}
//Log.d("ActivateProfileHelper.screenTimeoutUnlock","-- end");
}
@SuppressLint("RtlHardcoded")
private void createBrightnessView(Context context)
{
//Log.d("ActivateProfileHelper.createBrightnessView","xxx");
//if (dataWrapper.context != null)
//{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
if (GlobalGUIRoutines.brightneesView != null)
{
//Log.d("ActivateProfileHelper.createBrightnessView","GlobalGUIRoutines.brightneesView != null");
try {
windowManager.removeView(GlobalGUIRoutines.brightneesView);
} catch (Exception ignored) {
}
GlobalGUIRoutines.brightneesView = null;
}
int type;
if (android.os.Build.VERSION.SDK_INT < 25)
type = WindowManager.LayoutParams.TYPE_TOAST;
else
type = LayoutParams.TYPE_SYSTEM_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
type,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE /*| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE*/,
PixelFormat.TRANSLUCENT
);
GlobalGUIRoutines.brightneesView = new BrightnessView(context);
try {
windowManager.addView(GlobalGUIRoutines.brightneesView, params);
} catch (Exception e) {
GlobalGUIRoutines.brightneesView = null;
//e.printStackTrace();
}
RemoveBrightnessViewBroadcastReceiver.setAlarm(context);
//Log.d("ActivateProfileHelper.createBrightnessView","-- end");
//}
}
static void removeBrightnessView(Context context) {
if (GlobalGUIRoutines.brightneesView != null)
{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
try {
windowManager.removeView(GlobalGUIRoutines.brightneesView);
} catch (Exception ignored) {
}
GlobalGUIRoutines.brightneesView = null;
}
}
@SuppressLint("NewApi")
public void showNotification(Profile profile)
{
if (lockRefresh)
// no refres notification
return;
if (PPApplication.notificationStatusBar)
{
PPApplication.logE("ActivateProfileHelper.showNotification", "show");
boolean notificationShowInStatusBar = PPApplication.notificationShowInStatusBar;
boolean notificationStatusBarPermanent = PPApplication.notificationStatusBarPermanent;
// close showed notification
//notificationManager.cancel(PPApplication.PROFILE_NOTIFICATION_ID);
// vytvorenie intentu na aktivitu, ktora sa otvori na kliknutie na notifikaciu
Intent intent = new Intent(context, LauncherActivity.class);
// clear all opened activities
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
// nastavime, ze aktivita sa spusti z notifikacnej listy
intent.putExtra(PPApplication.EXTRA_STARTUP_SOURCE, PPApplication.STARTUP_SOURCE_NOTIFICATION);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
// vytvorenie intentu na restart events
Intent intentRE = new Intent(context, RestartEventsFromNotificationActivity.class);
PendingIntent pIntentRE = PendingIntent.getActivity(context, 0, intentRE, PendingIntent.FLAG_CANCEL_CURRENT);
// vytvorenie samotnej notifikacie
Notification.Builder notificationBuilder;
RemoteViews contentView;
if (PPApplication.notificationTheme.equals("1"))
contentView = new RemoteViews(context.getPackageName(), R.layout.notification_drawer_dark);
else
if (PPApplication.notificationTheme.equals("2"))
contentView = new RemoteViews(context.getPackageName(), R.layout.notification_drawer_light);
else
contentView = new RemoteViews(context.getPackageName(), R.layout.notification_drawer);
boolean isIconResourceID;
String iconIdentifier;
String profileName;
Bitmap iconBitmap;
Bitmap preferencesIndicator;
if (profile != null)
{
isIconResourceID = profile.getIsIconResourceID();
iconIdentifier = profile.getIconIdentifier();
profileName = dataWrapper.getProfileNameWithManualIndicator(profile, true, true, false);
iconBitmap = profile._iconBitmap;
preferencesIndicator = profile._preferencesIndicator;
}
else
{
isIconResourceID = true;
iconIdentifier = PPApplication.PROFILE_ICON_DEFAULT;
profileName = context.getResources().getString(R.string.profiles_header_profile_name_no_activated);
iconBitmap = null;
preferencesIndicator = null;
}
notificationBuilder = new Notification.Builder(context)
.setContentIntent(pIntent);
if (Build.VERSION.SDK_INT >= 16) {
if (notificationShowInStatusBar) {
boolean screenUnlocked = PPApplication.getScreenUnlocked(context);
if ((PPApplication.notificationHideInLockscreen && (!screenUnlocked)) ||
((profile != null) && profile._hideStatusBarIcon))
notificationBuilder.setPriority(Notification.PRIORITY_MIN);
else
notificationBuilder.setPriority(Notification.PRIORITY_DEFAULT);
}
else
notificationBuilder.setPriority(Notification.PRIORITY_MIN);
//notificationBuilder.setPriority(Notification.PRIORITY_HIGH); // for heads-up in Android 5.0
}
if (Build.VERSION.SDK_INT >= 21)
{
notificationBuilder.setCategory(Notification.CATEGORY_STATUS);
notificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
}
notificationBuilder.setTicker(profileName);
if (isIconResourceID)
{
int iconSmallResource;
if (iconBitmap != null) {
if (PPApplication.notificationStatusBarStyle.equals("0")) {
// colorful icon
// FC in Note 4, 6.0.1 :-/
String manufacturer = PPApplication.getROMManufacturer();
boolean isNote4 = (manufacturer != null) && (manufacturer.compareTo("samsung") == 0) &&
/*(Build.MODEL.startsWith("SM-N910") || // Samsung Note 4
Build.MODEL.startsWith("SM-G900") // Samsung Galaxy S5
) &&*/
(android.os.Build.VERSION.SDK_INT == 23);
//Log.d("ActivateProfileHelper.showNotification","isNote4="+isNote4);
if ((android.os.Build.VERSION.SDK_INT >= 23) && (!isNote4)) {
notificationBuilder.setSmallIcon(Icon.createWithBitmap(iconBitmap));
}
else {
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify_color", "drawable", context.getPackageName());
if (iconSmallResource == 0)
iconSmallResource = R.drawable.ic_profile_default;
notificationBuilder.setSmallIcon(iconSmallResource);
}
}
else {
// native icon
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify", "drawable", context.getPackageName());
if (iconSmallResource == 0)
iconSmallResource = R.drawable.ic_profile_default_notify;
notificationBuilder.setSmallIcon(iconSmallResource);
}
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, iconBitmap);
}
else {
if (PPApplication.notificationStatusBarStyle.equals("0")) {
// colorful icon
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify_color", "drawable", context.getPackageName());
if (iconSmallResource == 0)
iconSmallResource = R.drawable.ic_profile_default;
notificationBuilder.setSmallIcon(iconSmallResource);
int iconLargeResource = context.getResources().getIdentifier(iconIdentifier, "drawable", context.getPackageName());
if (iconLargeResource == 0)
iconLargeResource = R.drawable.ic_profile_default;
Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), iconLargeResource);
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, largeIcon);
} else {
// native icon
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify", "drawable", context.getPackageName());
if (iconSmallResource == 0)
iconSmallResource = R.drawable.ic_profile_default_notify;
notificationBuilder.setSmallIcon(iconSmallResource);
int iconLargeResource = context.getResources().getIdentifier(iconIdentifier, "drawable", context.getPackageName());
if (iconLargeResource == 0)
iconLargeResource = R.drawable.ic_profile_default;
Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), iconLargeResource);
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, largeIcon);
}
}
}
else {
// FC in Note 4, 6.0.1 :-/
String manufacturer = PPApplication.getROMManufacturer();
boolean isNote4 = (manufacturer != null) && (manufacturer.compareTo("samsung") == 0) &&
/*(Build.MODEL.startsWith("SM-N910") || // Samsung Note 4
Build.MODEL.startsWith("SM-G900") // Samsung Galaxy S5
) &&*/
(android.os.Build.VERSION.SDK_INT == 23);
//Log.d("ActivateProfileHelper.showNotification","isNote4="+isNote4);
if ((Build.VERSION.SDK_INT >= 23) && (!isNote4) && (iconBitmap != null)) {
notificationBuilder.setSmallIcon(Icon.createWithBitmap(iconBitmap));
}
else {
int iconSmallResource;
if (PPApplication.notificationStatusBarStyle.equals("0"))
iconSmallResource = R.drawable.ic_profile_default;
else
iconSmallResource = R.drawable.ic_profile_default_notify;
notificationBuilder.setSmallIcon(iconSmallResource);
}
if (iconBitmap != null)
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, iconBitmap);
else
contentView.setImageViewResource(R.id.notification_activated_profile_icon, R.drawable.ic_profile_default);
}
// workaround for LG G4, Android 6.0
if (Build.VERSION.SDK_INT < 24)
contentView.setInt(R.id.notification_activated_app_root, "setVisibility", View.GONE);
if (PPApplication.notificationTextColor.equals("1")) {
contentView.setTextColor(R.id.notification_activated_profile_name, Color.BLACK);
if (Build.VERSION.SDK_INT >= 24)
contentView.setTextColor(R.id.notification_activated_app_name, Color.BLACK);
}
else
if (PPApplication.notificationTextColor.equals("2")) {
contentView.setTextColor(R.id.notification_activated_profile_name, Color.WHITE);
if (Build.VERSION.SDK_INT >= 24)
contentView.setTextColor(R.id.notification_activated_app_name, Color.WHITE);
}
contentView.setTextViewText(R.id.notification_activated_profile_name, profileName);
//contentView.setImageViewBitmap(R.id.notification_activated_profile_pref_indicator,
// ProfilePreferencesIndicator.paint(profile, context));
if ((preferencesIndicator != null) && (PPApplication.notificationPrefIndicator))
contentView.setImageViewBitmap(R.id.notification_activated_profile_pref_indicator, preferencesIndicator);
else
contentView.setImageViewResource(R.id.notification_activated_profile_pref_indicator, R.drawable.ic_empty);
if (PPApplication.notificationTextColor.equals("1"))
contentView.setImageViewResource(R.id.notification_activated_profile_restart_events, R.drawable.ic_action_events_restart);
else
if (PPApplication.notificationTextColor.equals("2"))
contentView.setImageViewResource(R.id.notification_activated_profile_restart_events, R.drawable.ic_action_events_restart_dark);
contentView.setOnClickPendingIntent(R.id.notification_activated_profile_restart_events, pIntentRE);
//if (android.os.Build.VERSION.SDK_INT >= 24) {
// notificationBuilder.setStyle(new Notification.DecoratedCustomViewStyle());
// notificationBuilder.setCustomContentView(contentView);
//}
//else
notificationBuilder.setContent(contentView);
PPApplication.phoneProfilesNotification = notificationBuilder.build();
if (notificationStatusBarPermanent)
{
//notification.flags |= Notification.FLAG_NO_CLEAR;
PPApplication.phoneProfilesNotification.flags |= Notification.FLAG_ONGOING_EVENT;
}
else
{
setAlarmForNotificationCancel();
}
if (PhoneProfilesService.instance != null)
PhoneProfilesService.instance.startForeground(PPApplication.PROFILE_NOTIFICATION_ID, PPApplication.phoneProfilesNotification);
else
notificationManager.notify(PPApplication.PROFILE_NOTIFICATION_ID, PPApplication.phoneProfilesNotification);
}
else
{
if (PhoneProfilesService.instance != null)
PhoneProfilesService.instance.stopForeground(true);
else
notificationManager.cancel(PPApplication.PROFILE_NOTIFICATION_ID);
}
}
void removeNotification()
{
removeAlarmForRecreateNotification();
if (PhoneProfilesService.instance != null)
PhoneProfilesService.instance.stopForeground(true);
else
if (notificationManager != null)
notificationManager.cancel(PPApplication.PROFILE_NOTIFICATION_ID);
}
private void setAlarmForNotificationCancel()
{
if (PPApplication.notificationStatusBarCancel.isEmpty() || PPApplication.notificationStatusBarCancel.equals("0"))
return;
int notificationStatusBarCancel = Integer.valueOf(PPApplication.notificationStatusBarCancel);
Intent intent = new Intent(context, NotificationCancelAlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);
Calendar now = Calendar.getInstance();
long time = now.getTimeInMillis() + notificationStatusBarCancel * 1000;
// not needed exact for removing notification
/*if (PPApplication.exactAlarms && (android.os.Build.VERSION.SDK_INT >= 23))
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, pendingIntent);
if (PPApplication.exactAlarms && (android.os.Build.VERSION.SDK_INT >= 19))
alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
else*/
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
//alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 24 * 60 * 60 * 1000 , pendingIntent);
//alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 24 * 60 * 60 * 1000 , pendingIntent);
}
void setAlarmForRecreateNotification()
{
Intent intent = new Intent(context, RecreateNotificationBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);
Calendar now = Calendar.getInstance();
long time = now.getTimeInMillis() + 500;
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
}
private void removeAlarmForRecreateNotification() {
Intent intent = new Intent(context, RecreateNotificationBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_NO_CREATE);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);
if (pendingIntent != null)
{
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
}
}
void updateWidget()
{
if (lockRefresh)
// no refres widgets
return;
// icon widget
Intent intent = new Intent(context, IconWidgetProvider.class);
intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
int ids[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, IconWidgetProvider.class));
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
context.sendBroadcast(intent);
// one row widget
Intent intent4 = new Intent(context, OneRowWidgetProvider.class);
intent4.setAction("android.appwidget.action.APPWIDGET_UPDATE");
int ids4[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, OneRowWidgetProvider.class));
intent4.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids4);
context.sendBroadcast(intent4);
// list widget
Intent intent2 = new Intent(context, ProfileListWidgetProvider.class);
intent2.setAction(ProfileListWidgetProvider.INTENT_REFRESH_LISTWIDGET);
int ids2[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, ProfileListWidgetProvider.class));
intent2.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids2);
context.sendBroadcast(intent2);
// dashclock extension
Intent intent3 = new Intent();
intent3.setAction(DashClockBroadcastReceiver.INTENT_REFRESH_DASHCLOCK);
context.sendBroadcast(intent3);
// activities
Intent intent5 = new Intent();
intent5.setAction(RefreshGUIBroadcastReceiver.INTENT_REFRESH_GUI);
context.sendBroadcast(intent5);
}
static boolean isAirplaneMode(Context context)
{
if (android.os.Build.VERSION.SDK_INT >= 17)
return Settings.Global.getInt(context.getContentResolver(), Global.AIRPLANE_MODE_ON, 0) != 0;
else
//noinspection deprecation
return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
private void setAirplaneMode(Context context, boolean mode)
{
if (android.os.Build.VERSION.SDK_INT >= 17)
setAirplaneMode_SDK17(/*context, */mode);
else
setAirplaneMode_SDK8(context, mode);
}
/*
private boolean isMobileData(Context context)
{
if (android.os.Build.VERSION.SDK_INT >= 21)
{
return Settings.Global.getInt(context.getContentResolver(), "mobile_data", 0) == 1;
}
else
{
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method getMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled");
getMobileDataEnabledMethod.setAccessible(true);
return (Boolean)getMobileDataEnabledMethod.invoke(connectivityManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (NoSuchMethodException e) {
e.printStackTrace();
return false;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return false;
} catch (IllegalAccessException e) {
e.printStackTrace();
return false;
} catch (InvocationTargetException e) {
e.printStackTrace();
return false;
}
}
}
*/
static boolean isMobileData(Context context)
{
if (android.os.Build.VERSION.SDK_INT < 21)
{
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method getMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled");
getMobileDataEnabledMethod.setAccessible(true);
return (Boolean)getMobileDataEnabledMethod.invoke(connectivityManager);
} catch (Exception e) {
//e.printStackTrace();
return false;
}
}
else
if (android.os.Build.VERSION.SDK_INT < 22)
{
Method getDataEnabledMethod;
Class<?> telephonyManagerClass;
Object ITelephonyStub;
Class<?> ITelephonyClass;
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
try {
telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");
getITelephonyMethod.setAccessible(true);
ITelephonyStub = getITelephonyMethod.invoke(telephonyManager);
ITelephonyClass = Class.forName(ITelephonyStub.getClass().getName());
getDataEnabledMethod = ITelephonyClass.getDeclaredMethod("getDataEnabled");
getDataEnabledMethod.setAccessible(true);
return (Boolean)getDataEnabledMethod.invoke(ITelephonyStub);
} catch (Exception e) {
//e.printStackTrace();
return false;
}
}
else
{
Method getDataEnabledMethod;
Class<?> telephonyManagerClass;
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
try {
telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
getDataEnabledMethod = telephonyManagerClass.getDeclaredMethod("getDataEnabled");
getDataEnabledMethod.setAccessible(true);
return (Boolean)getDataEnabledMethod.invoke(telephonyManager);
} catch (Exception e) {
//e.printStackTrace();
return false;
}
}
}
private void setMobileData(Context context, boolean enable)
{
if (android.os.Build.VERSION.SDK_INT >= 21)
{
if (PPApplication.isRooted()/*PPApplication.isRootGranted()*/)
{
String command1 = "svc data " + (enable ? "enable" : "disable");
PPApplication.logE("ActivateProfileHelper.setMobileData","command="+command1);
Command command = new Command(0, false, command1)/* {
@Override
public void commandOutput(int id, String line) {
super.commandOutput(id, line);
PPApplication.logE("ActivateProfileHelper.setMobileData","shell output="+line);
}
@Override
public void commandTerminated(int id, String reason) {
super.commandTerminated(id, reason);
PPApplication.logE("ActivateProfileHelper.setMobileData","terminated="+reason);
}
@Override
public void commandCompleted(int id, int exitcode) {
super.commandCompleted(id, exitcode);
PPApplication.logE("ActivateProfileHelper.setMobileData","completed="+exitcode);
}
}*/;
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SHELL).add(command);
commandWait(command);
//RootToolsSmall.runSuCommand(command1);
PPApplication.logE("ActivateProfileHelper.setMobileData","after wait");
} catch (Exception e) {
Log.e("ActivateProfileHelper.setMobileData", "Error on run su");
}
/*
int state = 0;
try {
// Get the current state of the mobile network.
state = enable ? 1 : 0;
// Get the value of the "TRANSACTION_setDataEnabled" field.
String transactionCode = PPApplication.getTransactionCode(context, "TRANSACTION_setDataEnabled");
//Log.e("ActivateProfileHelper.setMobileData", "transactionCode="+transactionCode);
// Android 5.1+ (API 22) and later.
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
//Log.e("ActivateProfileHelper.setMobileData", "dual SIM?");
SubscriptionManager mSubscriptionManager = SubscriptionManager.from(context);
// Loop through the subscription list i.e. SIM list.
for (int i = 0; i < mSubscriptionManager.getActiveSubscriptionInfoCountMax(); i++) {
if (transactionCode != null && transactionCode.length() > 0) {
// Get the active subscription ID for a given SIM card.
int subscriptionId = mSubscriptionManager.getActiveSubscriptionInfoList().get(i).getSubscriptionId();
//Log.e("ActivateProfileHelper.setMobileData", "subscriptionId="+subscriptionId);
String command1 = "service call phone " + transactionCode + " i32 " + subscriptionId + " i32 " + state;
Command command = new Command(0, false, command1);
try {
RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setMobileData", "Error on run su");
}
}
}
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
//Log.e("ActivateProfileHelper.setMobileData", "NO dual SIM?");
// Android 5.0 (API 21) only.
if (transactionCode != null && transactionCode.length() > 0) {
String command1 = "service call phone " + transactionCode + " i32 " + state;
Command command = new Command(0, false, command1);
try {
RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setMobileData", "Error on run su");
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
*/
}
}
else
{
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean OK = false;
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Field iConnectivityManagerField = connectivityManagerClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(connectivityManager);
final Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enable);
OK = true;
} catch (Exception ignored) {
}
if (!OK)
{
try {
Method setMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(connectivityManager, enable);
//OK = true;
} catch (Exception ignored) {
}
}
}
}
/*
private int getPreferredNetworkType(Context context) {
if (PPApplication.isRooted())
{
try {
// Get the value of the "TRANSACTION_setPreferredNetworkType" field.
String transactionCode = PPApplication.getTransactionCode(context, "TRANSACTION_getPreferredNetworkType");
if (transactionCode != null && transactionCode.length() > 0) {
String command1 = "service call phone " + transactionCode + " i32";
Command command = new Command(0, false, command1) {
@Override
public void commandOutput(int id, String line) {
super.commandOutput(id, line);
String splits[] = line.split(" ");
try {
networkType = Integer.parseInt(splits[2]);
} catch (Exception e) {
networkType = -1;
}
}
@Override
public void commandTerminated(int id, String reason) {
super.commandTerminated(id, reason);
}
@Override
public void commandCompleted(int id, int exitcode) {
super.commandCompleted(id, exitcode);
}
};
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPreferredNetworkType", "Error on run su");
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
else
networkType = -1;
return networkType;
}
*/
private void setPreferredNetworkType(Context context, int networkType)
{
if (PPApplication.isRooted()/*PPApplication.isRootGranted()*/)
{
try {
// Get the value of the "TRANSACTION_setPreferredNetworkType" field.
String transactionCode = PPApplication.getTransactionCode(context, "TRANSACTION_setPreferredNetworkType");
// Android 6?
if (Build.VERSION.SDK_INT >= 23) {
SubscriptionManager mSubscriptionManager = SubscriptionManager.from(context);
// Loop through the subscription list i.e. SIM list.
List<SubscriptionInfo> subscriptionList = mSubscriptionManager.getActiveSubscriptionInfoList();
if (subscriptionList != null) {
for (int i = 0; i < mSubscriptionManager.getActiveSubscriptionInfoCountMax(); i++) {
if (transactionCode.length() > 0) {
// Get the active subscription ID for a given SIM card.
SubscriptionInfo subscriptionInfo = subscriptionList.get(i);
if (subscriptionInfo != null) {
int subscriptionId = subscriptionInfo.getSubscriptionId();
String command1 = "service call phone " + transactionCode + " i32 " + subscriptionId + " i32 " + networkType;
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPreferredNetworkType", "Error on run su");
}
}
}
}
}
} else {
if (transactionCode.length() > 0) {
String command1 = "service call phone " + transactionCode + " i32 " + networkType;
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPreferredNetworkType", "Error on run su");
}
}
}
} catch(Exception ignored) {
}
}
}
private void setNFC(Context context, boolean enable)
{
/*
Not working in debug version of application !!!!
Test with release version.
*/
//Log.e("ActivateProfileHelper.setNFC", "xxx");
/*if (Permissions.checkNFC(context)) {
Log.e("ActivateProfileHelper.setNFC", "permission granted!!");
CmdNfc.run(enable);
}
else */
if (PPApplication.isRooted()/*PPApplication.isRootGranted()*/) {
String command1 = PPApplication.getJavaCommandFile(CmdNfc.class, "nfc", context, enable);
//Log.e("ActivateProfileHelper.setNFC", "command1="+command1);
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.NORMAL).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setNFC", "Error on run su");
}
//String command = PPApplication.getJavaCommandFile(CmdNfc.class, "nfc", context, enable);
//RootToolsSmall.runSuCommand(command);
}
}
@SuppressWarnings("deprecation")
private void setGPS(Context context, boolean enable)
{
//boolean isEnabled;
//int locationMode = -1;
//if (android.os.Build.VERSION.SDK_INT < 19)
// isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
/*else {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE, -1);
isEnabled = (locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY) ||
(locationMode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY);
}*/
boolean isEnabled;
if (android.os.Build.VERSION.SDK_INT < 19)
isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
else {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
PPApplication.logE("ActivateProfileHelper.setGPS", "isEnabled="+isEnabled);
//if(!provider.contains(LocationManager.GPS_PROVIDER) && enable)
if ((!isEnabled) && enable)
{
if ((android.os.Build.VERSION.SDK_INT >= 16) && PPApplication.isRooted()/*PPApplication.isRootGranted()*/)
{
// zariadenie je rootnute
PPApplication.logE("ActivateProfileHelper.setGPS", "rooted");
String command1;
//String command2;
if (android.os.Build.VERSION.SDK_INT < 23) {
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
PPApplication.logE("ActivateProfileHelper.setGPS", "provider="+provider);
String newSet;
if (provider.isEmpty())
newSet = LocationManager.GPS_PROVIDER;
else
newSet = String.format("%s,%s", provider, LocationManager.GPS_PROVIDER);
PPApplication.logE("ActivateProfileHelper.setGPS", "newSet="+newSet);
command1 = "settings put secure location_providers_allowed \"" + newSet + "\"";
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
//command2 = "am broadcast -a android.location.GPS_ENABLED_CHANGE --ez state true";
Command command = new Command(0, false, command1); //, command2);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
//Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
PPApplication.logE("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
else {
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
PPApplication.logE("ActivateProfileHelper.setGPS", "provider="+provider);
command1 = "settings put secure location_providers_allowed +gps";
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
}
else
if (PPApplication.canExploitGPS(context))
{
PPApplication.logE("ActivateProfileHelper.setGPS", "exploit");
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
context.sendBroadcast(poke);
}
//else
//{
/*PPApplication.logE("ActivateProfileHelper.setGPS", "old method");
try {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", enable);
context.sendBroadcast(intent);
} catch (SecurityException e) {
e.printStackTrace();
}*/
// for normal apps it is only possible to open the system settings dialog
/* Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent); */
//}
}
else
//if(provider.contains(LocationManager.GPS_PROVIDER) && (!enable))
if (isEnabled && (!enable))
{
if ((android.os.Build.VERSION.SDK_INT >= 16) && PPApplication.isRooted()/*PPApplication.isRootGranted()*/)
{
// zariadenie je rootnute
PPApplication.logE("ActivateProfileHelper.setGPS", "rooted");
String command1;
//String command2;
if (android.os.Build.VERSION.SDK_INT < 23) {
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
PPApplication.logE("ActivateProfileHelper.setGPS", "provider="+provider);
String[] list = provider.split(",");
String newSet = "";
int j = 0;
for (int i = 0; i < list.length; i++) {
if (!list[i].equals(LocationManager.GPS_PROVIDER)) {
if (j > 0)
newSet += ",";
newSet += list[i];
j++;
}
}
PPApplication.logE("ActivateProfileHelper.setGPS", "newSet="+newSet);
command1 = "settings put secure location_providers_allowed \"" + newSet + "\"";
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
//command2 = "am broadcast -a android.location.GPS_ENABLED_CHANGE --ez state false";
Command command = new Command(0, false, command1);//, command2);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
//Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
PPApplication.logE("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
else {
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
PPApplication.logE("ActivateProfileHelper.setGPS", "provider="+provider);
command1 = "settings put secure location_providers_allowed -gps";
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
}
else
if (PPApplication.canExploitGPS(context))
{
PPApplication.logE("ActivateProfileHelper.setGPS", "exploit");
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
context.sendBroadcast(poke);
}
//else
//{
//PPApplication.logE("ActivateProfileHelper.setGPS", "old method");
/*try {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", enable);
context.sendBroadcast(intent);
} catch (SecurityException e) {
e.printStackTrace();
}*/
// for normal apps it is only possible to open the system settings dialog
/* Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent); */
//}
}
}
private void setAirplaneMode_SDK17(/*Context context, */boolean mode)
{
if (PPApplication.isRooted()/*PPApplication.isRootGranted()*/)
{
// zariadenie je rootnute
String command1;
String command2;
if (mode)
{
command1 = "settings put global airplane_mode_on 1";
command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true";
}
else
{
command1 = "settings put global airplane_mode_on 0";
command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false";
}
//if (PPApplication.isSELinuxEnforcing())
//{
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
// command2 = PPApplication.getSELinuxEnforceCommand(command2, Shell.ShellContext.SYSTEM_APP);
//}
Command command = new Command(0, false, command1, command2);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("AirPlaneMode_SDK17.setAirplaneMode", "Error on run su");
}
}
//else
//{
// for normal apps it is only possible to open the system settings dialog
/* Intent intent = new Intent(android.provider.Settings.ACTION_AIRPLANE_MODE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent); */
//}
}
@SuppressWarnings("deprecation")
private void setAirplaneMode_SDK8(Context context, boolean mode)
{
Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, mode ? 1 : 0);
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", mode);
context.sendBroadcast(intent);
}
private void setPowerSaveMode(boolean enable) {
String command1 = "settings put global low_power " + ((enable) ? 1 : 0);
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPowerSaveMode", "Error on run su: " + e.toString());
}
}
private void lockDevice(Profile profile) {
if (PPApplication.startedOnBoot)
// not lock device after boot
return;
switch (profile._lockDevice) {
case 3:
DevicePolicyManager manager = (DevicePolicyManager)context.getSystemService(DEVICE_POLICY_SERVICE);
final ComponentName component = new ComponentName(context, PPDeviceAdminReceiver.class);
if (manager.isAdminActive(component))
manager.lockNow();
break;
case 2:
/*if (PPApplication.isRooted()) {
//String command1 = "input keyevent 26";
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.lockDevice", "Error on run su: " + e.toString());
}
}*/
if (PPApplication.isRooted() && PPApplication.serviceBinaryExists())
{
String command1 = PPApplication.getJavaCommandFile(CmdGoToSleep.class, "power", context, 0);
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.NORMAL).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.lockDevice", "Error on run su");
}
}
/*if (PPApplication.isRooted()) {
try {
// Get the value of the "TRANSACTION_goToSleep" field.
String transactionCode = PPApplication.getTransactionCode("android.os.IPowerManager", "TRANSACTION_goToSleep");
String command1 = "service call power " + transactionCode + " i64 " + SystemClock.uptimeMillis();
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.lockDevice", "Error on run su");
}
} catch(Exception ignored) {
}
*/
break;
case 1:
Intent intent = new Intent(context, LockDeviceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
break;
}
}
private static void commandWait(Command cmd) throws Exception {
int waitTill = 50;
int waitTillMultiplier = 2;
int waitTillLimit = 3200; //7 tries, 6350 msec
while (!cmd.isFinished() && waitTill<=waitTillLimit) {
synchronized (cmd) {
try {
if (!cmd.isFinished()) {
cmd.wait(waitTill);
waitTill *= waitTillMultiplier;
}
} catch (Exception ignored) {
}
}
}
if (!cmd.isFinished()){
Log.e("ActivateProfileHelper", "Could not finish root command in " + (waitTill/waitTillMultiplier));
}
}
}
|
phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/ActivateProfileHelper.java
|
package sk.henrichg.phoneprofilesplus;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.WallpaperManager;
import android.app.admin.DevicePolicyManager;
import android.appwidget.AppWidgetManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Icon;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.provider.Settings.Global;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.RemoteViews;
import com.stericson.RootShell.execution.Command;
import com.stericson.RootShell.execution.Shell;
import com.stericson.RootTools.RootTools;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.List;
import static android.content.Context.DEVICE_POLICY_SERVICE;
public class ActivateProfileHelper {
private DataWrapper dataWrapper;
private Context context;
private NotificationManager notificationManager;
private Handler brightnessHandler;
//private int networkType = -1;
static boolean lockRefresh = false;
static final String ADAPTIVE_BRIGHTNESS_SETTING_NAME = "screen_auto_brightness_adj";
// Setting.Global "zen_mode"
static final int ZENMODE_ALL = 0;
static final int ZENMODE_PRIORITY = 1;
static final int ZENMODE_NONE = 2;
static final int ZENMODE_ALARMS = 3;
@SuppressWarnings("WeakerAccess")
static final int ZENMODE_SILENT = 99;
public ActivateProfileHelper()
{
}
public void initialize(DataWrapper dataWrapper, Context c)
{
this.dataWrapper = dataWrapper;
initializeNoNotificationManager(c);
notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
}
private void initializeNoNotificationManager(Context c)
{
context = c;
}
void deinitialize()
{
dataWrapper = null;
context = null;
notificationManager = null;
}
void setBrightnessHandler(Handler handler)
{
brightnessHandler = handler;
}
@SuppressWarnings("deprecation")
private void doExecuteForRadios(Profile profile)
{
PPApplication.sleep(300);
// nahodenie network type
if (profile._deviceNetworkType >= 100) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_NETWORK_TYPE, context) == PPApplication.PREFERENCE_ALLOWED) {
setPreferredNetworkType(context, profile._deviceNetworkType - 100);
//try { Thread.sleep(200); } catch (InterruptedException e) { }
//SystemClock.sleep(200);
PPApplication.sleep(200);
}
}
// nahodenie mobilnych dat
if (profile._deviceMobileData != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_MOBILE_DATA, context) == PPApplication.PREFERENCE_ALLOWED) {
boolean _isMobileData = isMobileData(context);
//PPApplication.logE("ActivateProfileHelper.doExecuteForRadios","_isMobileData="+_isMobileData);
boolean _setMobileData = false;
switch (profile._deviceMobileData) {
case 1:
if (!_isMobileData) {
_isMobileData = true;
_setMobileData = true;
}
break;
case 2:
if (_isMobileData) {
_isMobileData = false;
_setMobileData = true;
}
break;
case 3:
_isMobileData = !_isMobileData;
_setMobileData = true;
break;
}
if (_setMobileData) {
setMobileData(context, _isMobileData);
//try { Thread.sleep(200); } catch (InterruptedException e) { }
//SystemClock.sleep(200);
PPApplication.sleep(200);
}
}
}
// nahodenie WiFi AP
boolean canChangeWifi = true;
if (profile._deviceWiFiAP != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_WIFI_AP, context) == PPApplication.PREFERENCE_ALLOWED) {
WifiApManager wifiApManager = null;
try {
wifiApManager = new WifiApManager(context);
} catch (Exception ignored) {
}
if (wifiApManager != null) {
boolean setWifiAPState = false;
boolean isWifiAPEnabled = wifiApManager.isWifiAPEnabled();
switch (profile._deviceWiFiAP) {
case 1:
if (!isWifiAPEnabled) {
isWifiAPEnabled = true;
setWifiAPState = true;
canChangeWifi = false;
}
break;
case 2:
if (isWifiAPEnabled) {
isWifiAPEnabled = false;
setWifiAPState = true;
canChangeWifi = true;
}
break;
case 3:
isWifiAPEnabled = !isWifiAPEnabled;
setWifiAPState = true;
canChangeWifi = !isWifiAPEnabled;
break;
}
if (setWifiAPState) {
wifiApManager.setWifiApState(isWifiAPEnabled);
//try { Thread.sleep(200); } catch (InterruptedException e) { }
//SystemClock.sleep(200);
PPApplication.sleep(200);
}
}
}
}
if (canChangeWifi) {
// nahodenie WiFi
if (profile._deviceWiFi != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_WIFI, context) == PPApplication.PREFERENCE_ALLOWED) {
boolean isWifiAPEnabled = WifiApManager.isWifiAPEnabled(context);
if (!isWifiAPEnabled) { // only when wifi AP is not enabled, change wifi
PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.doExecuteForRadios-isWifiAPEnabled=false");
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int wifiState = wifiManager.getWifiState();
boolean isWifiEnabled = ((wifiState == WifiManager.WIFI_STATE_ENABLED) || (wifiState == WifiManager.WIFI_STATE_ENABLING));
boolean setWifiState = false;
switch (profile._deviceWiFi) {
case 1:
if (!isWifiEnabled) {
isWifiEnabled = true;
setWifiState = true;
}
break;
case 2:
if (isWifiEnabled) {
isWifiEnabled = false;
setWifiState = true;
}
break;
case 3:
isWifiEnabled = !isWifiEnabled;
setWifiState = true;
break;
}
if (isWifiEnabled)
// when wifi is enabled from profile, no disable wifi after scan
WifiScanAlarmBroadcastReceiver.setWifiEnabledForScan(context, false);
if (setWifiState) {
try {
wifiManager.setWifiEnabled(isWifiEnabled);
} catch (Exception e) {
wifiManager.setWifiEnabled(isWifiEnabled);
}
//try { Thread.sleep(200); } catch (InterruptedException e) { }
//SystemClock.sleep(200);
PPApplication.sleep(200);
}
}
}
}
// connect to SSID
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_CONNECT_TO_SSID, context) == PPApplication.PREFERENCE_ALLOWED) {
if (!profile._deviceConnectToSSID.equals(Profile.CONNECTTOSSID_JUSTANY)) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int wifiState = wifiManager.getWifiState();
if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
// check if wifi is connected
ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connManager.getActiveNetworkInfo();
boolean wifiConnected = (activeNetwork != null) &&
(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) &&
activeNetwork.isConnected();
WifiInfo wifiInfo = null;
if (wifiConnected)
wifiInfo = wifiManager.getConnectionInfo();
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals(profile._deviceConnectToSSID)) {
if (wifiConnected) {
if (!wifiInfo.getSSID().equals(i.SSID)) {
PhoneProfilesService.connectToSSIDStarted = true;
// conected to another SSID
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
}
} else
wifiManager.enableNetwork(i.networkId, true);
break;
}
}
}
}
//else {
// WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
// int wifiState = wifiManager.getWifiState();
// if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
// wifiManager.disconnect();
// wifiManager.reconnect();
// }
//}
PhoneProfilesService.connectToSSID = profile._deviceConnectToSSID;
}
}
// nahodenie bluetooth
if (profile._deviceBluetooth != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_BLUETOOTH, context) == PPApplication.PREFERENCE_ALLOWED) {
PPApplication.logE("ActivateProfileHelper.doExecuteForRadios","setBluetooth");
BluetoothAdapter bluetoothAdapter = BluetoothScanAlarmBroadcastReceiver.getBluetoothAdapter(context);
if (bluetoothAdapter != null) {
boolean isBluetoothEnabled = bluetoothAdapter.isEnabled();
boolean setBluetoothState = false;
switch (profile._deviceBluetooth) {
case 1:
if (!isBluetoothEnabled) {
isBluetoothEnabled = true;
setBluetoothState = true;
}
break;
case 2:
if (isBluetoothEnabled) {
isBluetoothEnabled = false;
setBluetoothState = true;
}
break;
case 3:
isBluetoothEnabled = !isBluetoothEnabled;
setBluetoothState = true;
break;
}
PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "setBluetoothState="+setBluetoothState);
PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "isBluetoothEnabled="+isBluetoothEnabled);
if (isBluetoothEnabled) {
// when bluetooth is enabled from profile, no disable bluetooth after scan
PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "isBluetoothEnabled=true; setBluetoothEnabledForScan=false");
BluetoothScanAlarmBroadcastReceiver.setBluetoothEnabledForScan(context, false);
}
if (setBluetoothState) {
if (isBluetoothEnabled)
bluetoothAdapter.enable();
else
bluetoothAdapter.disable();
}
}
}
}
// nahodenie GPS
if (profile._deviceGPS != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_GPS, context) == PPApplication.PREFERENCE_ALLOWED) {
//String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
boolean isEnabled;
if (android.os.Build.VERSION.SDK_INT < 19)
isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
else {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "isEnabled=" + isEnabled);
switch (profile._deviceGPS) {
case 1:
setGPS(context, true);
break;
case 2:
setGPS(context, false);
break;
case 3:
if (!isEnabled) {
setGPS(context, true);
} else {
setGPS(context, false);
}
break;
}
}
}
// nahodenie NFC
if (profile._deviceNFC != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_NFC, context) == PPApplication.PREFERENCE_ALLOWED) {
//Log.e("ActivateProfileHelper.doExecuteForRadios", "allowed");
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
if (nfcAdapter != null) {
switch (profile._deviceNFC) {
case 1:
setNFC(context, true);
break;
case 2:
setNFC(context, false);
break;
case 3:
if (!nfcAdapter.isEnabled()) {
setNFC(context, true);
} else if (nfcAdapter.isEnabled()) {
setNFC(context, false);
}
break;
}
}
}
//else
// Log.e("ActivateProfileHelper.doExecuteForRadios", "not allowed");
}
}
void executeForRadios(Profile profile)
{
boolean _isAirplaneMode = false;
boolean _setAirplaneMode = false;
if (profile._deviceAirplaneMode != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_AIRPLANE_MODE, context) == PPApplication.PREFERENCE_ALLOWED) {
_isAirplaneMode = isAirplaneMode(context);
switch (profile._deviceAirplaneMode) {
case 1:
if (!_isAirplaneMode) {
_isAirplaneMode = true;
_setAirplaneMode = true;
}
break;
case 2:
if (_isAirplaneMode) {
_isAirplaneMode = false;
_setAirplaneMode = true;
}
break;
case 3:
_isAirplaneMode = !_isAirplaneMode;
_setAirplaneMode = true;
break;
}
}
}
if (_setAirplaneMode /*&& _isAirplaneMode*/) {
// switch ON airplane mode, set it before executeForRadios
setAirplaneMode(context, _isAirplaneMode);
PPApplication.sleep(2000);
}
doExecuteForRadios(profile);
/*if (_setAirplaneMode && (!_isAirplaneMode)) {
// 200 miliseconds is in doExecuteForRadios
PPApplication.sleep(1800);
// switch OFF airplane mode, set if after executeForRadios
setAirplaneMode(context, _isAirplaneMode);
}*/
}
static boolean isAudibleRinging(int ringerMode, int zenMode) {
return (!((ringerMode == 3) || (ringerMode == 4) ||
((ringerMode == 5) && ((zenMode == 3) || (zenMode == 4) || (zenMode == 5) || (zenMode == 6)))
));
}
private boolean isVibrateRingerMode(int ringerMode, int zenMode) {
return (ringerMode == 3);
}
/*
private void correctVolume0(AudioManager audioManager) {
int ringerMode, zenMode;
ringerMode = PPApplication.getRingerMode(context);
zenMode = PPApplication.getZenMode(context);
if ((ringerMode == 1) || (ringerMode == 2) || (ringerMode == 4) ||
((ringerMode == 5) && ((zenMode == 1) || (zenMode == 2)))) {
// any "nonVIBRATE" ringer mode is selected
if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
// actual system ringer mode = vibrate
// volume changed it to vibrate
//RingerModeChangeReceiver.internalChange = true;
audioManager.setStreamVolume(AudioManager.STREAM_RING, 1, 0);
PhoneProfilesService.ringingVolume = 1;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, 1);
}
}
}
*/
@SuppressLint("NewApi")
void setVolumes(Profile profile, AudioManager audioManager, int linkUnlink, boolean forProfileActivation)
{
if (profile.getVolumeRingtoneChange()) {
if (forProfileActivation)
PPApplication.setRingerVolume(context, profile.getVolumeRingtoneValue());
}
if (profile.getVolumeNotificationChange()) {
if (forProfileActivation)
PPApplication.setNotificationVolume(context, profile.getVolumeNotificationValue());
}
int ringerMode = PPApplication.getRingerMode(context);
int zenMode = PPApplication.getZenMode(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "ringerMode=" + ringerMode);
PPApplication.logE("ActivateProfileHelper.setVolumes", "zenMode=" + zenMode);
PPApplication.logE("ActivateProfileHelper.setVolumes", "linkUnlink=" + linkUnlink);
PPApplication.logE("ActivateProfileHelper.setVolumes", "forProfileActivation=" + forProfileActivation);
// for ringer mode VIBRATE or SILENT or
// for interruption types NONE and ONLY_ALARMS
// not set system, ringer, notification volume
// (Android 6 - priority mode = ONLY_ALARMS)
if (isAudibleRinging(ringerMode, zenMode)) {
PPApplication.logE("ActivateProfileHelper.setVolumes", "ringer/notif/system change");
//if (Permissions.checkAccessNotificationPolicy(context)) {
if (forProfileActivation) {
if (profile.getVolumeSystemChange()) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, profile.getVolumeSystemValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_SYSTEM, profile.getVolumeSystemValue());
//correctVolume0(audioManager);
} catch (Exception ignored) { }
}
}
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
int callState = telephony.getCallState();
boolean volumesSet = false;
if (PPApplication.getMergedRingNotificationVolumes(context) && PPApplication.applicationUnlinkRingerNotificationVolumes) {
//if (doUnlink) {
//if (linkUnlink == PhoneCallBroadcastReceiver.LINKMODE_UNLINK) {
if (callState == TelephonyManager.CALL_STATE_RINGING) {
// for separating ringing and notification
// in ringing state ringer volumes must by set
// and notification volumes must not by set
int volume = PPApplication.getRingerVolume(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-RINGING ringer volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0);
PhoneProfilesService.ringingVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
//correctVolume0(audioManager);
} catch (Exception ignored) { }
}
volumesSet = true;
} else if (linkUnlink == PhoneCallService.LINKMODE_LINK) {
// for separating ringing and notification
// in not ringing state ringer and notification volume must by change
//Log.e("ActivateProfileHelper","setVolumes get audio mode="+audioManager.getMode());
int volume = PPApplication.getRingerVolume(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING-link ringer volume=" + volume);
if (volume != -999) {
//Log.e("ActivateProfileHelper","setVolumes set ring volume="+volume);
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0);
PhoneProfilesService.ringingVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, profile.getVolumeRingtoneValue());
} catch (Exception ignored) { }
}
volume = PPApplication.getNotificationVolume(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING-link notification volume=" + volume);
if (volume != -999) {
//Log.e("ActivateProfileHelper","setVolumes set notification volume="+volume);
try {
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, profile.getVolumeNotificationValue());
} catch (Exception ignored) { }
}
//correctVolume0(audioManager);
volumesSet = true;
} else {
int volume = PPApplication.getRingerVolume(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING ringer volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0);
PhoneProfilesService.ringingVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, volume);
//correctVolume0(audioManager);
} catch (Exception ignored) { }
}
volume = PPApplication.getNotificationVolume(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "doUnlink-NOT RINGING notification volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, volume);
//correctVolume0(audioManager);
} catch (Exception ignored) { }
}
volumesSet = true;
}
/*}
else {
if (callState == TelephonyManager.CALL_STATE_RINGING) {
int volume = PPApplication.getRingerVolume(context);
if (volume == -999)
volume = audioManager.getStreamVolume(AudioManager.STREAM_RING);
PhoneProfilesService.ringingVolume = volume;
}
}*/
}
if (!volumesSet) {
// reverted order for disabled unlink
int volume;
if (!PPApplication.getMergedRingNotificationVolumes(context)) {
volume = PPApplication.getNotificationVolume(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "no doUnlink notification volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, volume, 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_NOTIFICATION, volume);
//correctVolume0(audioManager);
} catch (Exception ignored) { }
}
}
volume = PPApplication.getRingerVolume(context);
PPApplication.logE("ActivateProfileHelper.setVolumes", "no doUnlink ringer volume=" + volume);
if (volume != -999) {
try {
audioManager.setStreamVolume(AudioManager.STREAM_RING, volume, 0);
PhoneProfilesService.ringingVolume = volume;
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_RING, volume);
//correctVolume0(audioManager);
} catch (Exception ignored) { }
}
}
//}
//else
// PPApplication.logE("ActivateProfileHelper.setVolumes", "not granted");
}
if (forProfileActivation) {
if (profile.getVolumeMediaChange()) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, profile.getVolumeMediaValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_MUSIC, profile.getVolumeMediaValue());
}
if (profile.getVolumeAlarmChange()) {
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, profile.getVolumeAlarmValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_ALARM, profile.getVolumeAlarmValue());
}
if (profile.getVolumeVoiceChange()) {
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, profile.getVolumeVoiceValue(), 0);
//Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_VOICE, profile.getVolumeVoiceValue());
}
}
}
private void setZenMode(int zenMode, AudioManager audioManager, int ringerMode)
{
if (android.os.Build.VERSION.SDK_INT >= 21)
{
int _zenMode = PPApplication.getSystemZenMode(context, -1);
PPApplication.logE("ActivateProfileHelper.setZenMode", "_zenMode=" + _zenMode);
int _ringerMode = audioManager.getRingerMode();
PPApplication.logE("ActivateProfileHelper.setZenMode", "_ringerMode=" + _ringerMode);
if ((zenMode != ZENMODE_SILENT) && PPApplication.canChangeZenMode(context, false)) {
audioManager.setRingerMode(ringerMode);
//try { Thread.sleep(500); } catch (InterruptedException e) { }
//SystemClock.sleep(500);
PPApplication.sleep(500);
if ((zenMode != _zenMode) || (zenMode == ZENMODE_PRIORITY)) {
PPNotificationListenerService.requestInterruptionFilter(context, zenMode);
InterruptionFilterChangedBroadcastReceiver.requestInterruptionFilter(context, zenMode);
}
} else {
switch (zenMode) {
case ZENMODE_SILENT:
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
//try { Thread.sleep(1000); } catch (InterruptedException e) { }
//SystemClock.sleep(1000);
PPApplication.sleep(1000);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
break;
default:
audioManager.setRingerMode(ringerMode);
}
}
}
else
audioManager.setRingerMode(ringerMode);
}
private void setVibrateWhenRinging(Profile profile, int value) {
int lValue = value;
if (profile != null) {
switch (profile._vibrateWhenRinging) {
case 1:
lValue = 1;
break;
case 2:
lValue = 0;
break;
}
}
if (lValue != -1) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_VIBRATE_WHEN_RINGING, context)
== PPApplication.PREFERENCE_ALLOWED) {
if (Permissions.checkProfileVibrateWhenRinging(context, profile)) {
if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception)
Settings.System.putInt(context.getContentResolver(), "vibrate_when_ringing", lValue);
else {
try {
Settings.System.putInt(context.getContentResolver(), Settings.System.VIBRATE_WHEN_RINGING, lValue);
} catch (Exception ee) {
String command1 = "settings put system " + Settings.System.VIBRATE_WHEN_RINGING + " " + lValue;
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setVibrateWhenRinging", "Error on run su: " + e.toString());
}
}
}
}
}
}
}
void setTones(Profile profile) {
if (Permissions.checkProfileRingtones(context, profile)) {
if (profile._soundRingtoneChange == 1) {
if (!profile._soundRingtone.isEmpty()) {
try {
//Settings.System.putString(context.getContentResolver(), Settings.System.RINGTONE, profile._soundRingtone);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, Uri.parse(profile._soundRingtone));
}
catch (Exception ignored){ }
} else {
// selected is None tone
try {
//Settings.System.putString(context.getContentResolver(), Settings.System.RINGTONE, null);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, null);
}
catch (Exception ignored){ }
}
}
if (profile._soundNotificationChange == 1) {
if (!profile._soundNotification.isEmpty()) {
try {
//Settings.System.putString(context.getContentResolver(), Settings.System.NOTIFICATION_SOUND, profile._soundNotification);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, Uri.parse(profile._soundNotification));
}
catch (Exception ignored){ }
} else {
// selected is None tone
try {
//Settings.System.putString(context.getContentResolver(), Settings.System.NOTIFICATION_SOUND, null);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, null);
}
catch (Exception ignored){ }
}
}
if (profile._soundAlarmChange == 1) {
if (!profile._soundAlarm.isEmpty()) {
try {
//Settings.System.putString(context.getContentResolver(), Settings.System.ALARM_ALERT, profile._soundAlarm);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, Uri.parse(profile._soundAlarm));
}
catch (Exception ignored){ }
} else {
// selected is None tone
try {
//Settings.System.putString(context.getContentResolver(), Settings.System.ALARM_ALERT, null);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, null);
}
catch (Exception ignored){ }
}
}
}
}
private void setNotificationLed(int value) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_NOTIFICATION_LED, context)
== PPApplication.PREFERENCE_ALLOWED) {
if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception)
Settings.System.putInt(context.getContentResolver(), "notification_light_pulse", value);
else {
String command1 = "settings put system " + "notification_light_pulse" + " " + value;
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setNotificationLed", "Error on run su: " + e.toString());
}
}
}
}
void changeRingerModeForVolumeEqual0(Profile profile) {
if (profile.getVolumeRingtoneChange()) {
//int ringerMode = PPApplication.getRingerMode(context);
//int zenMode = PPApplication.getZenMode(context);
//PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "ringerMode=" + ringerMode);
//PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "zenMode=" + zenMode);
if (profile.getVolumeRingtoneValue() == 0) {
profile.setVolumeRingtoneValue(1);
// for profile ringer/zen mode = "only vibrate" do not change ringer mode to Silent
if (!isVibrateRingerMode(profile._volumeRingerMode, profile._volumeZenMode)) {
// for ringer mode VIBRATE or SILENT or
// for interruption types NONE and ONLY_ALARMS
// not change ringer mode
// (Android 6 - priority mode = ONLY_ALARMS)
if (isAudibleRinging(profile._volumeRingerMode, profile._volumeZenMode)) {
// change ringer mode to Silent
PPApplication.logE("ActivateProfileHelper.changeRingerModeForVolumeEqual0", "changed to silent");
profile._volumeRingerMode = 4;
}
}
}
}
}
void changeNotificationVolumeForVolumeEqual0(Profile profile) {
if (profile.getVolumeNotificationChange() && PPApplication.getMergedRingNotificationVolumes(context)) {
if (profile.getVolumeNotificationValue() == 0) {
PPApplication.logE("ActivateProfileHelper.changeNotificationVolumeForVolumeEqual0", "changed notification value to 1");
profile.setVolumeNotificationValue(1);
}
}
}
@SuppressWarnings("deprecation")
void setRingerMode(Profile profile, AudioManager audioManager, boolean firstCall, boolean forProfileActivation)
{
//PPApplication.logE("@@@ ActivateProfileHelper.setRingerMode", "andioM.ringerMode=" + audioManager.getRingerMode());
int ringerMode;
int zenMode;
if (forProfileActivation) {
if (profile._volumeRingerMode != 0) {
PPApplication.setRingerMode(context, profile._volumeRingerMode);
if ((profile._volumeRingerMode == 5) && (profile._volumeZenMode != 0))
PPApplication.setZenMode(context, profile._volumeZenMode);
}
}
if (firstCall)
return;
ringerMode = PPApplication.getRingerMode(context);
zenMode = PPApplication.getZenMode(context);
PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringerMode=" + ringerMode);
PPApplication.logE("ActivateProfileHelper.setRingerMode", "zenMode=" + zenMode);
if (forProfileActivation) {
PPApplication.logE("ActivateProfileHelper.setRingerMode", "ringer mode change");
switch (ringerMode) {
case 1: // Ring
setZenMode(ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); not needed, called from setZenMode
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ignored) {
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ignored) {
}
setVibrateWhenRinging(null, 0);
break;
case 2: // Ring & Vibrate
setZenMode(ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); not needed, called from setZenMode
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ignored) {
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ignored) {
}
setVibrateWhenRinging(null, 1);
break;
case 3: // Vibrate
setZenMode(ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_VIBRATE);
//audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); not needed, called from setZenMode
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ignored) {
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
} catch (Exception ignored) {
}
setVibrateWhenRinging(null, 1);
break;
case 4: // Silent
if (android.os.Build.VERSION.SDK_INT >= 21) {
//setZenMode(ZENMODE_SILENT, audioManager, AudioManager.RINGER_MODE_SILENT);
setZenMode(ZENMODE_SILENT, audioManager, AudioManager.RINGER_MODE_NORMAL);
}
else {
setZenMode(ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_SILENT);
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ignored) {
}
try {
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
} catch (Exception ignored) {
}
}
setVibrateWhenRinging(null, 0);
break;
case 5: // Zen mode
switch (zenMode) {
case 1:
setZenMode(ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_NORMAL);
setVibrateWhenRinging(profile, -1);
break;
case 2:
setZenMode(ZENMODE_PRIORITY, audioManager, AudioManager.RINGER_MODE_NORMAL);
setVibrateWhenRinging(profile, -1);
break;
case 3:
// must be AudioManager.RINGER_MODE_SILENT, because, ZENMODE_NONE set it to silent
// without this, duplicate set this zen mode not working
setZenMode(ZENMODE_NONE, audioManager, AudioManager.RINGER_MODE_SILENT);
break;
case 4:
setZenMode(ZENMODE_ALL, audioManager, AudioManager.RINGER_MODE_VIBRATE);
setVibrateWhenRinging(null, 1);
break;
case 5:
setZenMode(ZENMODE_PRIORITY, audioManager, AudioManager.RINGER_MODE_VIBRATE);
setVibrateWhenRinging(null, 1);
break;
case 6:
// must be AudioManager.RINGER_MODE_SILENT, because, ZENMODE_ALARMS set it to silent
// without this, duplicate set this zen mode not working
setZenMode(ZENMODE_ALARMS, audioManager, AudioManager.RINGER_MODE_SILENT);
break;
}
break;
}
}
}
void executeForWallpaper(Profile profile) {
if (profile._deviceWallpaperChange == 1)
{
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
if (android.os.Build.VERSION.SDK_INT >= 17)
display.getRealMetrics(displayMetrics);
else
display.getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
//noinspection SuspiciousNameCombination
height = displayMetrics.widthPixels;
//noinspection SuspiciousNameCombination
width = displayMetrics.heightPixels;
}
//Log.d("ActivateProfileHelper.executeForWallpaper", "height="+height);
//Log.d("ActivateProfileHelper.executeForWallpaper", "width="+width);
// for lock screen no double width
if ((android.os.Build.VERSION.SDK_INT < 24) || (profile._deviceWallpaperFor != 2))
width = width << 1; // best wallpaper width is twice screen width
Bitmap decodedSampleBitmap = BitmapManipulator.resampleBitmap(profile.getDeviceWallpaperIdentifier(), width, height, context);
if (decodedSampleBitmap != null)
{
// set wallpaper
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
try {
if (android.os.Build.VERSION.SDK_INT >= 24) {
int flags = WallpaperManager.FLAG_SYSTEM | WallpaperManager.FLAG_LOCK;
Rect visibleCropHint = null;
if (profile._deviceWallpaperFor == 1)
flags = WallpaperManager.FLAG_SYSTEM;
if (profile._deviceWallpaperFor == 2) {
flags = WallpaperManager.FLAG_LOCK;
int left = 0;
int right = decodedSampleBitmap.getWidth();
if (decodedSampleBitmap.getWidth() > width) {
left = (decodedSampleBitmap.getWidth() / 2) - (width / 2);
right = (decodedSampleBitmap.getWidth() / 2) + (width / 2);
}
visibleCropHint = new Rect(left, 0, right, decodedSampleBitmap.getHeight());
}
//noinspection WrongConstant
wallpaperManager.setBitmap(decodedSampleBitmap, visibleCropHint, true, flags);
}
else
wallpaperManager.setBitmap(decodedSampleBitmap);
} catch (IOException e) {
Log.e("ActivateProfileHelper.executeForWallpaper", "Cannot set wallpaper. Image="+profile.getDeviceWallpaperIdentifier());
}
}
}
}
// not working, returns only calling process :-/
// http://stackoverflow.com/questions/30619349/android-5-1-1-and-above-getrunningappprocesses-returns-my-application-packag
/*private boolean isRunning(List<ActivityManager.RunningAppProcessInfo> procInfos, String packageName) {
PPApplication.logE("ActivateProfileHelper.executeForRunApplications", "procInfos.size()="+procInfos.size());
for(int i = 0; i < procInfos.size(); i++)
{
ActivityManager.RunningAppProcessInfo procInfo = procInfos.get(i);
PPApplication.logE("ActivateProfileHelper.executeForRunApplications", "procInfo.processName="+procInfo.processName);
if (procInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
PPApplication.logE("ActivateProfileHelper.executeForRunApplications", "procInfo.importance=IMPORTANCE_FOREGROUND");
for (String pkgName : procInfo.pkgList) {
PPApplication.logE("ActivateProfileHelper.executeForRunApplications", "pkgName="+pkgName);
if (pkgName.equals(packageName))
return true;
}
}
}
return false;
}*/
void executeForRunApplications(Profile profile) {
if (profile._deviceRunApplicationChange == 1)
{
String[] splits = profile._deviceRunApplicationPackageName.split("\\|");
Intent intent;
PackageManager packageManager = context.getPackageManager();
//ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
for (int i = 0; i < splits.length; i++) {
//Log.d("ActivateProfileHelper.executeForRunApplications","app data="+splits[i]);
if (!ApplicationsCache.isShortcut(splits[i])) {
//Log.d("ActivateProfileHelper.executeForRunApplications","no shortcut");
String packageName = ApplicationsCache.getPackageName(splits[i]);
intent = packageManager.getLaunchIntentForPackage(packageName);
if (intent != null) {
//if (!isRunning(procInfos, packageName)) {
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName+": not running");
//Log.d("ActivateProfileHelper.executeForRunApplications","intent="+intent);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (Exception ignored) {
}
//try { Thread.sleep(1000); } catch (InterruptedException e) { }
//SystemClock.sleep(1000);
PPApplication.sleep(1000);
//}
//else
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName+": running");
}
}
else {
//Log.d("ActivateProfileHelper.executeForRunApplications","shortcut");
long shortcutId = ApplicationsCache.getShortcutId(splits[i]);
//Log.d("ActivateProfileHelper.executeForRunApplications","shortcutId="+shortcutId);
if (shortcutId > 0) {
Shortcut shortcut = dataWrapper.getDatabaseHandler().getShortcut(shortcutId);
if (shortcut != null) {
try {
intent = Intent.parseUri(shortcut._intent, 0);
if (intent != null) {
//String packageName = intent.getPackage();
//if (!isRunning(procInfos, packageName)) {
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName + ": not running");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//Log.d("ActivateProfileHelper.executeForRunApplications","intent="+intent);
try {
context.startActivity(intent);
} catch (Exception ignored) {
}
//try { Thread.sleep(1000); } catch (InterruptedException e) { }
//SystemClock.sleep(1000);
PPApplication.sleep(1000);
//} else
// PPApplication.logE("ActivateProfileHelper.executeForRunApplications", packageName + ": running");
}
} catch (Exception ignored) {
}
}
}
}
}
}
}
public void execute(Profile _profile, boolean merged, boolean _interactive)
{
// rozdelit zvonenie a notifikacie - zial je to oznacene ako @Hide :-(
//Settings.System.putInt(context.getContentResolver(), Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 0);
Profile profile = PPApplication.getMappedProfile(_profile, context);
// nahodenie volume
// run service for execute volumes
PPApplication.logE("ActivateProfileHelper.execute", "ExecuteVolumeProfilePrefsService");
Intent volumeServiceIntent = new Intent(context, ExecuteVolumeProfilePrefsService.class);
volumeServiceIntent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);
volumeServiceIntent.putExtra(PPApplication.EXTRA_MERGED_PROFILE, merged);
volumeServiceIntent.putExtra(PPApplication.EXTRA_FOR_PROFILE_ACTIVATION, true);
context.startService(volumeServiceIntent);
/*AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
// nahodenie ringer modu - aby sa mohli nastavit hlasitosti
setRingerMode(profile, audioManager);
setVolumes(profile, audioManager);
// nahodenie ringer modu - hlasitosti zmenia silent/vibrate
setRingerMode(profile, audioManager);*/
// set vibration on touch
if (Permissions.checkProfileVibrationOnTouch(context, profile)) {
switch (profile._vibrationOnTouch) {
case 1:
Settings.System.putInt(context.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 1);
break;
case 2:
Settings.System.putInt(context.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 0);
break;
}
}
// nahodenie tonov
// moved to ExecuteVolumeProfilePrefsService
//setTones(profile);
//// nahodenie radio preferences
// run service for execute radios
Intent radioServiceIntent = new Intent(context, ExecuteRadioProfilePrefsService.class);
radioServiceIntent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);
radioServiceIntent.putExtra(PPApplication.EXTRA_MERGED_PROFILE, merged);
context.startService(radioServiceIntent);
// nahodenie auto-sync
boolean _isAutosync = ContentResolver.getMasterSyncAutomatically();
boolean _setAutosync = false;
switch (profile._deviceAutosync) {
case 1:
if (!_isAutosync)
{
_isAutosync = true;
_setAutosync = true;
}
break;
case 2:
if (_isAutosync)
{
_isAutosync = false;
_setAutosync = true;
}
break;
case 3:
_isAutosync = !_isAutosync;
_setAutosync = true;
break;
}
if (_setAutosync)
ContentResolver.setMasterSyncAutomatically(_isAutosync);
// screen timeout
if (Permissions.checkProfileScreenTimeout(context, profile)) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//noinspection deprecation
if (pm.isScreenOn()) {
//Log.d("ActivateProfileHelper.execute","screen on");
setScreenTimeout(profile._deviceScreenTimeout);
}
else {
//Log.d("ActivateProfileHelper.execute","screen off");
PPApplication.setActivatedProfileScreenTimeout(context, profile._deviceScreenTimeout);
}
}
//else
// PPApplication.setActivatedProfileScreenTimeout(context, 0);
// zapnutie/vypnutie lockscreenu
//PPApplication.logE("$$$ ActivateProfileHelper.execute","keyguard");
boolean setLockscreen = false;
switch (profile._deviceKeyguard) {
case 1:
// enable lockscreen
PPApplication.logE("$$$ ActivateProfileHelper.execute","keyguard=ON");
PPApplication.setLockscreenDisabled(context, false);
setLockscreen = true;
break;
case 2:
// disable lockscreen
PPApplication.logE("$$$ ActivateProfileHelper.execute","keyguard=OFF");
PPApplication.setLockscreenDisabled(context, true);
setLockscreen = true;
break;
}
if (setLockscreen) {
boolean isScreenOn;
//if (android.os.Build.VERSION.SDK_INT >= 20)
//{
// Display display = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
// isScreenOn = display.getState() != Display.STATE_OFF;
//}
//else
//{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//noinspection deprecation
isScreenOn = pm.isScreenOn();
//}
PPApplication.logE("$$$ ActivateProfileHelper.execute","isScreenOn="+isScreenOn);
boolean keyguardShowing;
KeyguardManager kgMgr = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 16)
keyguardShowing = kgMgr.isKeyguardLocked();
else
keyguardShowing = kgMgr.inKeyguardRestrictedInputMode();
PPApplication.logE("$$$ ActivateProfileHelper.execute","keyguardShowing="+keyguardShowing);
if (isScreenOn && !keyguardShowing) {
Intent keyguardService = new Intent(context.getApplicationContext(), KeyguardService.class);
context.startService(keyguardService);
}
}
// nahodenie podsvietenia
if (Permissions.checkProfileScreenBrightness(context, profile)) {
if (profile.getDeviceBrightnessChange()) {
PPApplication.logE("ActivateProfileHelper.execute", "set brightness: profile=" + profile._name);
PPApplication.logE("ActivateProfileHelper.execute", "set brightness: _deviceBrightness=" + profile._deviceBrightness);
if (profile.getDeviceBrightnessAutomatic()) {
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
profile.getDeviceBrightnessManualValue(context));
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_ADAPTIVE_BRIGHTNESS, context)
== PPApplication.PREFERENCE_ALLOWED) {
if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception)
Settings.System.putFloat(context.getContentResolver(),
ADAPTIVE_BRIGHTNESS_SETTING_NAME,
profile.getDeviceBrightnessAdaptiveValue(context));
else {
try {
Settings.System.putFloat(context.getContentResolver(),
ADAPTIVE_BRIGHTNESS_SETTING_NAME,
profile.getDeviceBrightnessAdaptiveValue(context));
} catch (Exception ee) {
String command1 = "settings put system " + ADAPTIVE_BRIGHTNESS_SETTING_NAME + " " +
Float.toString(profile.getDeviceBrightnessAdaptiveValue(context));
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
Command command = new Command(0, false, command1); //, command2);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.execute", "Error on run su: " + e.toString());
}
}
}
}
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
} else {
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
profile.getDeviceBrightnessManualValue(context));
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
}
if (brightnessHandler != null) {
final Context __context = context;
brightnessHandler.post(new Runnable() {
public void run() {
createBrightnessView(__context);
}
});
} else
createBrightnessView(context);
}
}
// nahodenie rotate
if (Permissions.checkProfileAutoRotation(context, profile)) {
switch (profile._deviceAutoRotate) {
case 1:
// set autorotate on
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 2:
// set autorotate off
// degree 0
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0);
break;
case 3:
// set autorotate off
// degree 90
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_90);
break;
case 4:
// set autorotate off
// degree 180
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_180);
break;
case 5:
// set autorotate off
// degree 270
Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_270);
break;
}
}
// set notification led
if (profile._notificationLed != 0) {
//if (Permissions.checkProfileNotificationLed(context, profile)) { not needed for Android 6+, because root is required
switch (profile._notificationLed) {
case 1:
setNotificationLed(1);
break;
case 2:
setNotificationLed(0);
break;
}
//}
}
// nahodenie pozadia
if (Permissions.checkProfileWallpaper(context, profile)) {
if (profile._deviceWallpaperChange == 1) {
Intent wallpaperServiceIntent = new Intent(context, ExecuteWallpaperProfilePrefsService.class);
wallpaperServiceIntent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);
wallpaperServiceIntent.putExtra(PPApplication.EXTRA_MERGED_PROFILE, merged);
context.startService(wallpaperServiceIntent);
}
}
// set power save mode
if (profile._devicePowerSaveMode != 0) {
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_POWER_SAVE_MODE, context) == PPApplication.PREFERENCE_ALLOWED) {
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean _isPowerSaveMode = false;
if (Build.VERSION.SDK_INT >= 21)
_isPowerSaveMode = powerManager.isPowerSaveMode();
boolean _setPowerSaveMode = false;
switch (profile._devicePowerSaveMode) {
case 1:
if (!_isPowerSaveMode) {
_isPowerSaveMode = true;
_setPowerSaveMode = true;
}
break;
case 2:
if (_isPowerSaveMode) {
_isPowerSaveMode = false;
_setPowerSaveMode = true;
}
break;
case 3:
_isPowerSaveMode = !_isPowerSaveMode;
_setPowerSaveMode = true;
break;
}
if (_setPowerSaveMode) {
setPowerSaveMode(_isPowerSaveMode);
}
}
}
if (Permissions.checkProfileLockDevice(context, profile)) {
if (profile._lockDevice != 0) {
lockDevice(profile);
}
}
if (_interactive)
{
// preferences, ktore vyzaduju interakciu uzivatela
if (PPApplication.isProfilePreferenceAllowed(PPApplication.PREF_PROFILE_DEVICE_MOBILE_DATA_PREFS, context) == PPApplication.PREFERENCE_ALLOWED)
{
if (profile._deviceMobileDataPrefs == 1)
{
/*try {
final Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
final ComponentName componentName = new ComponentName("com.android.phone", "com.android.phone.Settings");
intent.setComponent(componentName);
context.startActivity(intent);
PPApplication.logE("#### ActivateProfileHelper.execute","mobile data prefs. 1");
} catch (Exception e) {
PPApplication.logE("#### ActivateProfileHelper.execute","mobile data prefs. 1 E="+e);
try {
final Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
PPApplication.logE("#### ActivateProfileHelper.execute","mobile data prefs. 2");
} catch (Exception e2) {
e2.printStackTrace();
PPApplication.logE("#### ActivateProfileHelper.execute","mobile data prefs. 2 E="+e2);
}
}*/
try {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setComponent(new ComponentName("com.android.settings","com.android.settings.Settings$DataUsageSummaryActivity"));
context.startActivity(intent);
} catch (Exception ignored) {
}
}
}
//if (PPApplication.hardwareCheck(PPApplication.PREF_PROFILE_DEVICE_GPS, context))
//{ No check only GPS
if (profile._deviceLocationServicePrefs == 1)
{
try {
final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} catch (Exception ignored) {
}
}
//}
if (profile._deviceRunApplicationChange == 1)
{
Intent runApplicationsServiceIntent = new Intent(context, ExecuteRunApplicationsProfilePrefsService.class);
runApplicationsServiceIntent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);
runApplicationsServiceIntent.putExtra(PPApplication.EXTRA_MERGED_PROFILE, merged);
context.startService(runApplicationsServiceIntent);
}
}
}
void setScreenTimeout(int screenTimeout) {
DisableScreenTimeoutInternalChangeReceiver.internalChange = true;
//Log.d("ActivateProfileHelper.setScreenTimeout", "current="+Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 0));
switch (screenTimeout) {
case 1:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 15000);
break;
case 2:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000);
break;
case 3:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 60000);
break;
case 4:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 120000);
break;
case 5:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 600000);
break;
case 6:
//2147483647 = Integer.MAX_VALUE
//18000000 = 5 hours
//86400000 = 24 hounrs
//43200000 = 12 hours
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 86400000); //18000000);
break;
case 7:
screenTimeoutUnlock(context);
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 300000);
break;
case 8:
screenTimeoutUnlock(context);
//if (android.os.Build.VERSION.SDK_INT < 19) // not working in Sony
// Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, -1);
//else
screenTimeoutLock(context);
break;
}
PPApplication.setActivatedProfileScreenTimeout(context, 0);
DisableScreenTimeoutInternalChangeReceiver.setAlarm(context);
}
private static void screenTimeoutLock(Context context)
{
//Log.d("ActivateProfileHelper.screenTimeoutLock","xxx");
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
screenTimeoutUnlock(context);
int type;
if (android.os.Build.VERSION.SDK_INT < 25)
type = WindowManager.LayoutParams.TYPE_TOAST;
else
type = LayoutParams.TYPE_SYSTEM_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
type,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | /*WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |*/ WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
PixelFormat.TRANSLUCENT
);
/*if (android.os.Build.VERSION.SDK_INT < 17)
params.gravity = Gravity.RIGHT | Gravity.TOP;
else
params.gravity = Gravity.END | Gravity.TOP;*/
GlobalGUIRoutines.keepScreenOnView = new BrightnessView(context);
try {
windowManager.addView(GlobalGUIRoutines.keepScreenOnView, params);
} catch (Exception e) {
GlobalGUIRoutines.keepScreenOnView = null;
//e.printStackTrace();
}
//Log.d("ActivateProfileHelper.screenTimeoutLock","-- end");
}
static void screenTimeoutUnlock(Context context)
{
//Log.d("ActivateProfileHelper.screenTimeoutUnlock","xxx");
if (GlobalGUIRoutines.keepScreenOnView != null)
{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
try {
windowManager.removeView(GlobalGUIRoutines.keepScreenOnView);
} catch (Exception ignored) {
}
GlobalGUIRoutines.keepScreenOnView = null;
}
//Log.d("ActivateProfileHelper.screenTimeoutUnlock","-- end");
}
@SuppressLint("RtlHardcoded")
private void createBrightnessView(Context context)
{
//Log.d("ActivateProfileHelper.createBrightnessView","xxx");
//if (dataWrapper.context != null)
//{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
if (GlobalGUIRoutines.brightneesView != null)
{
//Log.d("ActivateProfileHelper.createBrightnessView","GlobalGUIRoutines.brightneesView != null");
try {
windowManager.removeView(GlobalGUIRoutines.brightneesView);
} catch (Exception ignored) {
}
GlobalGUIRoutines.brightneesView = null;
}
int type;
if (android.os.Build.VERSION.SDK_INT < 25)
type = WindowManager.LayoutParams.TYPE_TOAST;
else
type = LayoutParams.TYPE_SYSTEM_OVERLAY; // add show ACTION_MANAGE_OVERLAY_PERMISSION to Permissions app Settings
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1,
type,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE /*| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE*/,
PixelFormat.TRANSLUCENT
);
GlobalGUIRoutines.brightneesView = new BrightnessView(context);
try {
windowManager.addView(GlobalGUIRoutines.brightneesView, params);
} catch (Exception e) {
GlobalGUIRoutines.brightneesView = null;
//e.printStackTrace();
}
RemoveBrightnessViewBroadcastReceiver.setAlarm(context);
//Log.d("ActivateProfileHelper.createBrightnessView","-- end");
//}
}
static void removeBrightnessView(Context context) {
if (GlobalGUIRoutines.brightneesView != null)
{
WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
try {
windowManager.removeView(GlobalGUIRoutines.brightneesView);
} catch (Exception ignored) {
}
GlobalGUIRoutines.brightneesView = null;
}
}
@SuppressLint("NewApi")
public void showNotification(Profile profile)
{
if (lockRefresh)
// no refres notification
return;
if (PPApplication.notificationStatusBar)
{
PPApplication.logE("ActivateProfileHelper.showNotification", "show");
boolean notificationShowInStatusBar = PPApplication.notificationShowInStatusBar;
boolean notificationStatusBarPermanent = PPApplication.notificationStatusBarPermanent;
// close showed notification
//notificationManager.cancel(PPApplication.PROFILE_NOTIFICATION_ID);
// vytvorenie intentu na aktivitu, ktora sa otvori na kliknutie na notifikaciu
Intent intent = new Intent(context, LauncherActivity.class);
// clear all opened activities
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
// nastavime, ze aktivita sa spusti z notifikacnej listy
intent.putExtra(PPApplication.EXTRA_STARTUP_SOURCE, PPApplication.STARTUP_SOURCE_NOTIFICATION);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
// vytvorenie intentu na restart events
Intent intentRE = new Intent(context, RestartEventsFromNotificationActivity.class);
PendingIntent pIntentRE = PendingIntent.getActivity(context, 0, intentRE, PendingIntent.FLAG_CANCEL_CURRENT);
// vytvorenie samotnej notifikacie
Notification.Builder notificationBuilder;
RemoteViews contentView;
if (PPApplication.notificationTheme.equals("1"))
contentView = new RemoteViews(context.getPackageName(), R.layout.notification_drawer_dark);
else
if (PPApplication.notificationTheme.equals("2"))
contentView = new RemoteViews(context.getPackageName(), R.layout.notification_drawer_light);
else
contentView = new RemoteViews(context.getPackageName(), R.layout.notification_drawer);
boolean isIconResourceID;
String iconIdentifier;
String profileName;
Bitmap iconBitmap;
Bitmap preferencesIndicator;
if (profile != null)
{
isIconResourceID = profile.getIsIconResourceID();
iconIdentifier = profile.getIconIdentifier();
profileName = dataWrapper.getProfileNameWithManualIndicator(profile, true, true, false);
iconBitmap = profile._iconBitmap;
preferencesIndicator = profile._preferencesIndicator;
}
else
{
isIconResourceID = true;
iconIdentifier = PPApplication.PROFILE_ICON_DEFAULT;
profileName = context.getResources().getString(R.string.profiles_header_profile_name_no_activated);
iconBitmap = null;
preferencesIndicator = null;
}
notificationBuilder = new Notification.Builder(context)
.setContentIntent(pIntent);
if (Build.VERSION.SDK_INT >= 16) {
if (notificationShowInStatusBar) {
boolean screenUnlocked = PPApplication.getScreenUnlocked(context);
if ((PPApplication.notificationHideInLockscreen && (!screenUnlocked)) ||
((profile != null) && profile._hideStatusBarIcon))
notificationBuilder.setPriority(Notification.PRIORITY_MIN);
else
notificationBuilder.setPriority(Notification.PRIORITY_DEFAULT);
}
else
notificationBuilder.setPriority(Notification.PRIORITY_MIN);
//notificationBuilder.setPriority(Notification.PRIORITY_HIGH); // for heads-up in Android 5.0
}
if (Build.VERSION.SDK_INT >= 21)
{
notificationBuilder.setCategory(Notification.CATEGORY_STATUS);
notificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
}
notificationBuilder.setTicker(profileName);
if (isIconResourceID)
{
int iconSmallResource;
if (iconBitmap != null) {
if (PPApplication.notificationStatusBarStyle.equals("0")) {
// colorful icon
// FC in Note 4, 6.0.1 :-/
String manufacturer = PPApplication.getROMManufacturer();
boolean isNote4 = (manufacturer != null) && (manufacturer.compareTo("samsung") == 0) &&
(Build.MODEL.startsWith("SM-N910") || // Samsung Note 4
Build.MODEL.startsWith("SM-G900") // Samsung Galaxy S5
) &&
(android.os.Build.VERSION.SDK_INT == 23);
//Log.d("ActivateProfileHelper.showNotification","isNote4="+isNote4);
if ((android.os.Build.VERSION.SDK_INT >= 23) && (!isNote4)) {
notificationBuilder.setSmallIcon(Icon.createWithBitmap(iconBitmap));
}
else {
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify_color", "drawable", context.getPackageName());
if (iconSmallResource == 0)
iconSmallResource = R.drawable.ic_profile_default;
notificationBuilder.setSmallIcon(iconSmallResource);
}
}
else {
// native icon
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify", "drawable", context.getPackageName());
if (iconSmallResource == 0)
iconSmallResource = R.drawable.ic_profile_default_notify;
notificationBuilder.setSmallIcon(iconSmallResource);
}
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, iconBitmap);
}
else {
if (PPApplication.notificationStatusBarStyle.equals("0")) {
// colorful icon
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify_color", "drawable", context.getPackageName());
if (iconSmallResource == 0)
iconSmallResource = R.drawable.ic_profile_default;
notificationBuilder.setSmallIcon(iconSmallResource);
int iconLargeResource = context.getResources().getIdentifier(iconIdentifier, "drawable", context.getPackageName());
if (iconLargeResource == 0)
iconLargeResource = R.drawable.ic_profile_default;
Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), iconLargeResource);
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, largeIcon);
} else {
// native icon
iconSmallResource = context.getResources().getIdentifier(iconIdentifier + "_notify", "drawable", context.getPackageName());
if (iconSmallResource == 0)
iconSmallResource = R.drawable.ic_profile_default_notify;
notificationBuilder.setSmallIcon(iconSmallResource);
int iconLargeResource = context.getResources().getIdentifier(iconIdentifier, "drawable", context.getPackageName());
if (iconLargeResource == 0)
iconLargeResource = R.drawable.ic_profile_default;
Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), iconLargeResource);
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, largeIcon);
}
}
}
else {
// FC in Note 4, 6.0.1 :-/
String manufacturer = PPApplication.getROMManufacturer();
boolean isNote4 = (manufacturer != null) && (manufacturer.compareTo("samsung") == 0) &&
(Build.MODEL.startsWith("SM-N910") || // Samsung Note 4
Build.MODEL.startsWith("SM-G900") // Samsung Galaxy S5
) &&
(android.os.Build.VERSION.SDK_INT == 23);
//Log.d("ActivateProfileHelper.showNotification","isNote4="+isNote4);
if ((Build.VERSION.SDK_INT >= 23) && (!isNote4) && (iconBitmap != null)) {
notificationBuilder.setSmallIcon(Icon.createWithBitmap(iconBitmap));
}
else {
int iconSmallResource;
if (PPApplication.notificationStatusBarStyle.equals("0"))
iconSmallResource = R.drawable.ic_profile_default;
else
iconSmallResource = R.drawable.ic_profile_default_notify;
notificationBuilder.setSmallIcon(iconSmallResource);
}
if (iconBitmap != null)
contentView.setImageViewBitmap(R.id.notification_activated_profile_icon, iconBitmap);
else
contentView.setImageViewResource(R.id.notification_activated_profile_icon, R.drawable.ic_profile_default);
}
// workaround for LG G4, Android 6.0
if (Build.VERSION.SDK_INT < 24)
contentView.setInt(R.id.notification_activated_app_root, "setVisibility", View.GONE);
if (PPApplication.notificationTextColor.equals("1")) {
contentView.setTextColor(R.id.notification_activated_profile_name, Color.BLACK);
if (Build.VERSION.SDK_INT >= 24)
contentView.setTextColor(R.id.notification_activated_app_name, Color.BLACK);
}
else
if (PPApplication.notificationTextColor.equals("2")) {
contentView.setTextColor(R.id.notification_activated_profile_name, Color.WHITE);
if (Build.VERSION.SDK_INT >= 24)
contentView.setTextColor(R.id.notification_activated_app_name, Color.WHITE);
}
contentView.setTextViewText(R.id.notification_activated_profile_name, profileName);
//contentView.setImageViewBitmap(R.id.notification_activated_profile_pref_indicator,
// ProfilePreferencesIndicator.paint(profile, context));
if ((preferencesIndicator != null) && (PPApplication.notificationPrefIndicator))
contentView.setImageViewBitmap(R.id.notification_activated_profile_pref_indicator, preferencesIndicator);
else
contentView.setImageViewResource(R.id.notification_activated_profile_pref_indicator, R.drawable.ic_empty);
if (PPApplication.notificationTextColor.equals("1"))
contentView.setImageViewResource(R.id.notification_activated_profile_restart_events, R.drawable.ic_action_events_restart);
else
if (PPApplication.notificationTextColor.equals("2"))
contentView.setImageViewResource(R.id.notification_activated_profile_restart_events, R.drawable.ic_action_events_restart_dark);
contentView.setOnClickPendingIntent(R.id.notification_activated_profile_restart_events, pIntentRE);
//if (android.os.Build.VERSION.SDK_INT >= 24) {
// notificationBuilder.setStyle(new Notification.DecoratedCustomViewStyle());
// notificationBuilder.setCustomContentView(contentView);
//}
//else
notificationBuilder.setContent(contentView);
PPApplication.phoneProfilesNotification = notificationBuilder.build();
if (notificationStatusBarPermanent)
{
//notification.flags |= Notification.FLAG_NO_CLEAR;
PPApplication.phoneProfilesNotification.flags |= Notification.FLAG_ONGOING_EVENT;
}
else
{
setAlarmForNotificationCancel();
}
if (PhoneProfilesService.instance != null)
PhoneProfilesService.instance.startForeground(PPApplication.PROFILE_NOTIFICATION_ID, PPApplication.phoneProfilesNotification);
else
notificationManager.notify(PPApplication.PROFILE_NOTIFICATION_ID, PPApplication.phoneProfilesNotification);
}
else
{
if (PhoneProfilesService.instance != null)
PhoneProfilesService.instance.stopForeground(true);
else
notificationManager.cancel(PPApplication.PROFILE_NOTIFICATION_ID);
}
}
void removeNotification()
{
removeAlarmForRecreateNotification();
if (PhoneProfilesService.instance != null)
PhoneProfilesService.instance.stopForeground(true);
else
if (notificationManager != null)
notificationManager.cancel(PPApplication.PROFILE_NOTIFICATION_ID);
}
private void setAlarmForNotificationCancel()
{
if (PPApplication.notificationStatusBarCancel.isEmpty() || PPApplication.notificationStatusBarCancel.equals("0"))
return;
int notificationStatusBarCancel = Integer.valueOf(PPApplication.notificationStatusBarCancel);
Intent intent = new Intent(context, NotificationCancelAlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);
Calendar now = Calendar.getInstance();
long time = now.getTimeInMillis() + notificationStatusBarCancel * 1000;
// not needed exact for removing notification
/*if (PPApplication.exactAlarms && (android.os.Build.VERSION.SDK_INT >= 23))
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, pendingIntent);
if (PPApplication.exactAlarms && (android.os.Build.VERSION.SDK_INT >= 19))
alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
else*/
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
//alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 24 * 60 * 60 * 1000 , pendingIntent);
//alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 24 * 60 * 60 * 1000 , pendingIntent);
}
void setAlarmForRecreateNotification()
{
Intent intent = new Intent(context, RecreateNotificationBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);
Calendar now = Calendar.getInstance();
long time = now.getTimeInMillis() + 500;
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
}
private void removeAlarmForRecreateNotification() {
Intent intent = new Intent(context, RecreateNotificationBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_NO_CREATE);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);
if (pendingIntent != null)
{
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
}
}
void updateWidget()
{
if (lockRefresh)
// no refres widgets
return;
// icon widget
Intent intent = new Intent(context, IconWidgetProvider.class);
intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
int ids[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, IconWidgetProvider.class));
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
context.sendBroadcast(intent);
// one row widget
Intent intent4 = new Intent(context, OneRowWidgetProvider.class);
intent4.setAction("android.appwidget.action.APPWIDGET_UPDATE");
int ids4[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, OneRowWidgetProvider.class));
intent4.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids4);
context.sendBroadcast(intent4);
// list widget
Intent intent2 = new Intent(context, ProfileListWidgetProvider.class);
intent2.setAction(ProfileListWidgetProvider.INTENT_REFRESH_LISTWIDGET);
int ids2[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, ProfileListWidgetProvider.class));
intent2.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids2);
context.sendBroadcast(intent2);
// dashclock extension
Intent intent3 = new Intent();
intent3.setAction(DashClockBroadcastReceiver.INTENT_REFRESH_DASHCLOCK);
context.sendBroadcast(intent3);
// activities
Intent intent5 = new Intent();
intent5.setAction(RefreshGUIBroadcastReceiver.INTENT_REFRESH_GUI);
context.sendBroadcast(intent5);
}
static boolean isAirplaneMode(Context context)
{
if (android.os.Build.VERSION.SDK_INT >= 17)
return Settings.Global.getInt(context.getContentResolver(), Global.AIRPLANE_MODE_ON, 0) != 0;
else
//noinspection deprecation
return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
private void setAirplaneMode(Context context, boolean mode)
{
if (android.os.Build.VERSION.SDK_INT >= 17)
setAirplaneMode_SDK17(/*context, */mode);
else
setAirplaneMode_SDK8(context, mode);
}
/*
private boolean isMobileData(Context context)
{
if (android.os.Build.VERSION.SDK_INT >= 21)
{
return Settings.Global.getInt(context.getContentResolver(), "mobile_data", 0) == 1;
}
else
{
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method getMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled");
getMobileDataEnabledMethod.setAccessible(true);
return (Boolean)getMobileDataEnabledMethod.invoke(connectivityManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (NoSuchMethodException e) {
e.printStackTrace();
return false;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return false;
} catch (IllegalAccessException e) {
e.printStackTrace();
return false;
} catch (InvocationTargetException e) {
e.printStackTrace();
return false;
}
}
}
*/
static boolean isMobileData(Context context)
{
if (android.os.Build.VERSION.SDK_INT < 21)
{
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method getMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled");
getMobileDataEnabledMethod.setAccessible(true);
return (Boolean)getMobileDataEnabledMethod.invoke(connectivityManager);
} catch (Exception e) {
//e.printStackTrace();
return false;
}
}
else
if (android.os.Build.VERSION.SDK_INT < 22)
{
Method getDataEnabledMethod;
Class<?> telephonyManagerClass;
Object ITelephonyStub;
Class<?> ITelephonyClass;
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
try {
telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");
getITelephonyMethod.setAccessible(true);
ITelephonyStub = getITelephonyMethod.invoke(telephonyManager);
ITelephonyClass = Class.forName(ITelephonyStub.getClass().getName());
getDataEnabledMethod = ITelephonyClass.getDeclaredMethod("getDataEnabled");
getDataEnabledMethod.setAccessible(true);
return (Boolean)getDataEnabledMethod.invoke(ITelephonyStub);
} catch (Exception e) {
//e.printStackTrace();
return false;
}
}
else
{
Method getDataEnabledMethod;
Class<?> telephonyManagerClass;
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
try {
telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
getDataEnabledMethod = telephonyManagerClass.getDeclaredMethod("getDataEnabled");
getDataEnabledMethod.setAccessible(true);
return (Boolean)getDataEnabledMethod.invoke(telephonyManager);
} catch (Exception e) {
//e.printStackTrace();
return false;
}
}
}
private void setMobileData(Context context, boolean enable)
{
if (android.os.Build.VERSION.SDK_INT >= 21)
{
if (PPApplication.isRooted()/*PPApplication.isRootGranted()*/)
{
String command1 = "svc data " + (enable ? "enable" : "disable");
PPApplication.logE("ActivateProfileHelper.setMobileData","command="+command1);
Command command = new Command(0, false, command1)/* {
@Override
public void commandOutput(int id, String line) {
super.commandOutput(id, line);
PPApplication.logE("ActivateProfileHelper.setMobileData","shell output="+line);
}
@Override
public void commandTerminated(int id, String reason) {
super.commandTerminated(id, reason);
PPApplication.logE("ActivateProfileHelper.setMobileData","terminated="+reason);
}
@Override
public void commandCompleted(int id, int exitcode) {
super.commandCompleted(id, exitcode);
PPApplication.logE("ActivateProfileHelper.setMobileData","completed="+exitcode);
}
}*/;
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SHELL).add(command);
commandWait(command);
//RootToolsSmall.runSuCommand(command1);
PPApplication.logE("ActivateProfileHelper.setMobileData","after wait");
} catch (Exception e) {
Log.e("ActivateProfileHelper.setMobileData", "Error on run su");
}
/*
int state = 0;
try {
// Get the current state of the mobile network.
state = enable ? 1 : 0;
// Get the value of the "TRANSACTION_setDataEnabled" field.
String transactionCode = PPApplication.getTransactionCode(context, "TRANSACTION_setDataEnabled");
//Log.e("ActivateProfileHelper.setMobileData", "transactionCode="+transactionCode);
// Android 5.1+ (API 22) and later.
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
//Log.e("ActivateProfileHelper.setMobileData", "dual SIM?");
SubscriptionManager mSubscriptionManager = SubscriptionManager.from(context);
// Loop through the subscription list i.e. SIM list.
for (int i = 0; i < mSubscriptionManager.getActiveSubscriptionInfoCountMax(); i++) {
if (transactionCode != null && transactionCode.length() > 0) {
// Get the active subscription ID for a given SIM card.
int subscriptionId = mSubscriptionManager.getActiveSubscriptionInfoList().get(i).getSubscriptionId();
//Log.e("ActivateProfileHelper.setMobileData", "subscriptionId="+subscriptionId);
String command1 = "service call phone " + transactionCode + " i32 " + subscriptionId + " i32 " + state;
Command command = new Command(0, false, command1);
try {
RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setMobileData", "Error on run su");
}
}
}
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
//Log.e("ActivateProfileHelper.setMobileData", "NO dual SIM?");
// Android 5.0 (API 21) only.
if (transactionCode != null && transactionCode.length() > 0) {
String command1 = "service call phone " + transactionCode + " i32 " + state;
Command command = new Command(0, false, command1);
try {
RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setMobileData", "Error on run su");
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
*/
}
}
else
{
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean OK = false;
try {
final Class<?> connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Field iConnectivityManagerField = connectivityManagerClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(connectivityManager);
final Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enable);
OK = true;
} catch (Exception ignored) {
}
if (!OK)
{
try {
Method setMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(connectivityManager, enable);
//OK = true;
} catch (Exception ignored) {
}
}
}
}
/*
private int getPreferredNetworkType(Context context) {
if (PPApplication.isRooted())
{
try {
// Get the value of the "TRANSACTION_setPreferredNetworkType" field.
String transactionCode = PPApplication.getTransactionCode(context, "TRANSACTION_getPreferredNetworkType");
if (transactionCode != null && transactionCode.length() > 0) {
String command1 = "service call phone " + transactionCode + " i32";
Command command = new Command(0, false, command1) {
@Override
public void commandOutput(int id, String line) {
super.commandOutput(id, line);
String splits[] = line.split(" ");
try {
networkType = Integer.parseInt(splits[2]);
} catch (Exception e) {
networkType = -1;
}
}
@Override
public void commandTerminated(int id, String reason) {
super.commandTerminated(id, reason);
}
@Override
public void commandCompleted(int id, int exitcode) {
super.commandCompleted(id, exitcode);
}
};
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPreferredNetworkType", "Error on run su");
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
else
networkType = -1;
return networkType;
}
*/
private void setPreferredNetworkType(Context context, int networkType)
{
if (PPApplication.isRooted()/*PPApplication.isRootGranted()*/)
{
try {
// Get the value of the "TRANSACTION_setPreferredNetworkType" field.
String transactionCode = PPApplication.getTransactionCode(context, "TRANSACTION_setPreferredNetworkType");
// Android 6?
if (Build.VERSION.SDK_INT >= 23) {
SubscriptionManager mSubscriptionManager = SubscriptionManager.from(context);
// Loop through the subscription list i.e. SIM list.
List<SubscriptionInfo> subscriptionList = mSubscriptionManager.getActiveSubscriptionInfoList();
if (subscriptionList != null) {
for (int i = 0; i < mSubscriptionManager.getActiveSubscriptionInfoCountMax(); i++) {
if (transactionCode.length() > 0) {
// Get the active subscription ID for a given SIM card.
SubscriptionInfo subscriptionInfo = subscriptionList.get(i);
if (subscriptionInfo != null) {
int subscriptionId = subscriptionInfo.getSubscriptionId();
String command1 = "service call phone " + transactionCode + " i32 " + subscriptionId + " i32 " + networkType;
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPreferredNetworkType", "Error on run su");
}
}
}
}
}
} else {
if (transactionCode.length() > 0) {
String command1 = "service call phone " + transactionCode + " i32 " + networkType;
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPreferredNetworkType", "Error on run su");
}
}
}
} catch(Exception ignored) {
}
}
}
private void setNFC(Context context, boolean enable)
{
/*
Not working in debug version of application !!!!
Test with release version.
*/
//Log.e("ActivateProfileHelper.setNFC", "xxx");
/*if (Permissions.checkNFC(context)) {
Log.e("ActivateProfileHelper.setNFC", "permission granted!!");
CmdNfc.run(enable);
}
else */
if (PPApplication.isRooted()/*PPApplication.isRootGranted()*/) {
String command1 = PPApplication.getJavaCommandFile(CmdNfc.class, "nfc", context, enable);
//Log.e("ActivateProfileHelper.setNFC", "command1="+command1);
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.NORMAL).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setNFC", "Error on run su");
}
//String command = PPApplication.getJavaCommandFile(CmdNfc.class, "nfc", context, enable);
//RootToolsSmall.runSuCommand(command);
}
}
@SuppressWarnings("deprecation")
private void setGPS(Context context, boolean enable)
{
//boolean isEnabled;
//int locationMode = -1;
//if (android.os.Build.VERSION.SDK_INT < 19)
// isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
/*else {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE, -1);
isEnabled = (locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY) ||
(locationMode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY);
}*/
boolean isEnabled;
if (android.os.Build.VERSION.SDK_INT < 19)
isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
else {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
PPApplication.logE("ActivateProfileHelper.setGPS", "isEnabled="+isEnabled);
//if(!provider.contains(LocationManager.GPS_PROVIDER) && enable)
if ((!isEnabled) && enable)
{
if ((android.os.Build.VERSION.SDK_INT >= 16) && PPApplication.isRooted()/*PPApplication.isRootGranted()*/)
{
// zariadenie je rootnute
PPApplication.logE("ActivateProfileHelper.setGPS", "rooted");
String command1;
//String command2;
if (android.os.Build.VERSION.SDK_INT < 23) {
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
PPApplication.logE("ActivateProfileHelper.setGPS", "provider="+provider);
String newSet;
if (provider.isEmpty())
newSet = LocationManager.GPS_PROVIDER;
else
newSet = String.format("%s,%s", provider, LocationManager.GPS_PROVIDER);
PPApplication.logE("ActivateProfileHelper.setGPS", "newSet="+newSet);
command1 = "settings put secure location_providers_allowed \"" + newSet + "\"";
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
//command2 = "am broadcast -a android.location.GPS_ENABLED_CHANGE --ez state true";
Command command = new Command(0, false, command1); //, command2);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
//Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
PPApplication.logE("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
else {
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
PPApplication.logE("ActivateProfileHelper.setGPS", "provider="+provider);
command1 = "settings put secure location_providers_allowed +gps";
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
}
else
if (PPApplication.canExploitGPS(context))
{
PPApplication.logE("ActivateProfileHelper.setGPS", "exploit");
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
context.sendBroadcast(poke);
}
//else
//{
/*PPApplication.logE("ActivateProfileHelper.setGPS", "old method");
try {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", enable);
context.sendBroadcast(intent);
} catch (SecurityException e) {
e.printStackTrace();
}*/
// for normal apps it is only possible to open the system settings dialog
/* Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent); */
//}
}
else
//if(provider.contains(LocationManager.GPS_PROVIDER) && (!enable))
if (isEnabled && (!enable))
{
if ((android.os.Build.VERSION.SDK_INT >= 16) && PPApplication.isRooted()/*PPApplication.isRootGranted()*/)
{
// zariadenie je rootnute
PPApplication.logE("ActivateProfileHelper.setGPS", "rooted");
String command1;
//String command2;
if (android.os.Build.VERSION.SDK_INT < 23) {
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
PPApplication.logE("ActivateProfileHelper.setGPS", "provider="+provider);
String[] list = provider.split(",");
String newSet = "";
int j = 0;
for (int i = 0; i < list.length; i++) {
if (!list[i].equals(LocationManager.GPS_PROVIDER)) {
if (j > 0)
newSet += ",";
newSet += list[i];
j++;
}
}
PPApplication.logE("ActivateProfileHelper.setGPS", "newSet="+newSet);
command1 = "settings put secure location_providers_allowed \"" + newSet + "\"";
//if (PPApplication.isSELinuxEnforcing())
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
//command2 = "am broadcast -a android.location.GPS_ENABLED_CHANGE --ez state false";
Command command = new Command(0, false, command1);//, command2);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
//Log.e("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
PPApplication.logE("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
else {
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
PPApplication.logE("ActivateProfileHelper.setGPS", "provider="+provider);
command1 = "settings put secure location_providers_allowed -gps";
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
PPApplication.logE("ActivateProfileHelper.setGPS", "Error on run su: " + e.toString());
}
}
}
else
if (PPApplication.canExploitGPS(context))
{
PPApplication.logE("ActivateProfileHelper.setGPS", "exploit");
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
context.sendBroadcast(poke);
}
//else
//{
//PPApplication.logE("ActivateProfileHelper.setGPS", "old method");
/*try {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", enable);
context.sendBroadcast(intent);
} catch (SecurityException e) {
e.printStackTrace();
}*/
// for normal apps it is only possible to open the system settings dialog
/* Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent); */
//}
}
}
private void setAirplaneMode_SDK17(/*Context context, */boolean mode)
{
if (PPApplication.isRooted()/*PPApplication.isRootGranted()*/)
{
// zariadenie je rootnute
String command1;
String command2;
if (mode)
{
command1 = "settings put global airplane_mode_on 1";
command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true";
}
else
{
command1 = "settings put global airplane_mode_on 0";
command2 = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false";
}
//if (PPApplication.isSELinuxEnforcing())
//{
// command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP);
// command2 = PPApplication.getSELinuxEnforceCommand(command2, Shell.ShellContext.SYSTEM_APP);
//}
Command command = new Command(0, false, command1, command2);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("AirPlaneMode_SDK17.setAirplaneMode", "Error on run su");
}
}
//else
//{
// for normal apps it is only possible to open the system settings dialog
/* Intent intent = new Intent(android.provider.Settings.ACTION_AIRPLANE_MODE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent); */
//}
}
@SuppressWarnings("deprecation")
private void setAirplaneMode_SDK8(Context context, boolean mode)
{
Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, mode ? 1 : 0);
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", mode);
context.sendBroadcast(intent);
}
private void setPowerSaveMode(boolean enable) {
String command1 = "settings put global low_power " + ((enable) ? 1 : 0);
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.setPowerSaveMode", "Error on run su: " + e.toString());
}
}
private void lockDevice(Profile profile) {
if (PPApplication.startedOnBoot)
// not lock device after boot
return;
switch (profile._lockDevice) {
case 3:
DevicePolicyManager manager = (DevicePolicyManager)context.getSystemService(DEVICE_POLICY_SERVICE);
final ComponentName component = new ComponentName(context, PPDeviceAdminReceiver.class);
if (manager.isAdminActive(component))
manager.lockNow();
break;
case 2:
/*if (PPApplication.isRooted()) {
//String command1 = "input keyevent 26";
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.lockDevice", "Error on run su: " + e.toString());
}
}*/
if (PPApplication.isRooted() && PPApplication.serviceBinaryExists())
{
String command1 = PPApplication.getJavaCommandFile(CmdGoToSleep.class, "power", context, 0);
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.NORMAL).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.lockDevice", "Error on run su");
}
}
/*if (PPApplication.isRooted()) {
try {
// Get the value of the "TRANSACTION_goToSleep" field.
String transactionCode = PPApplication.getTransactionCode("android.os.IPowerManager", "TRANSACTION_goToSleep");
String command1 = "service call power " + transactionCode + " i64 " + SystemClock.uptimeMillis();
Command command = new Command(0, false, command1);
try {
//RootTools.closeAllShells();
RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP).add(command);
commandWait(command);
} catch (Exception e) {
Log.e("ActivateProfileHelper.lockDevice", "Error on run su");
}
} catch(Exception ignored) {
}
*/
break;
case 1:
Intent intent = new Intent(context, LockDeviceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
break;
}
}
private static void commandWait(Command cmd) throws Exception {
int waitTill = 50;
int waitTillMultiplier = 2;
int waitTillLimit = 3200; //7 tries, 6350 msec
while (!cmd.isFinished() && waitTill<=waitTillLimit) {
synchronized (cmd) {
try {
if (!cmd.isFinished()) {
cmd.wait(waitTill);
waitTill *= waitTillMultiplier;
}
} catch (Exception ignored) {
}
}
}
if (!cmd.isFinished()){
Log.e("ActivateProfileHelper", "Could not finish root command in " + (waitTill/waitTillMultiplier));
}
}
}
|
Not use color status bar icon for alll Samsung devices.
|
phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/ActivateProfileHelper.java
|
Not use color status bar icon for alll Samsung devices.
|
<ide><path>honeProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/ActivateProfileHelper.java
<ide> // FC in Note 4, 6.0.1 :-/
<ide> String manufacturer = PPApplication.getROMManufacturer();
<ide> boolean isNote4 = (manufacturer != null) && (manufacturer.compareTo("samsung") == 0) &&
<del> (Build.MODEL.startsWith("SM-N910") || // Samsung Note 4
<add> /*(Build.MODEL.startsWith("SM-N910") || // Samsung Note 4
<ide> Build.MODEL.startsWith("SM-G900") // Samsung Galaxy S5
<del> ) &&
<add> ) &&*/
<ide> (android.os.Build.VERSION.SDK_INT == 23);
<ide> //Log.d("ActivateProfileHelper.showNotification","isNote4="+isNote4);
<ide> if ((android.os.Build.VERSION.SDK_INT >= 23) && (!isNote4)) {
<ide> // FC in Note 4, 6.0.1 :-/
<ide> String manufacturer = PPApplication.getROMManufacturer();
<ide> boolean isNote4 = (manufacturer != null) && (manufacturer.compareTo("samsung") == 0) &&
<del> (Build.MODEL.startsWith("SM-N910") || // Samsung Note 4
<add> /*(Build.MODEL.startsWith("SM-N910") || // Samsung Note 4
<ide> Build.MODEL.startsWith("SM-G900") // Samsung Galaxy S5
<del> ) &&
<add> ) &&*/
<ide> (android.os.Build.VERSION.SDK_INT == 23);
<ide> //Log.d("ActivateProfileHelper.showNotification","isNote4="+isNote4);
<ide> if ((Build.VERSION.SDK_INT >= 23) && (!isNote4) && (iconBitmap != null)) {
|
|
Java
|
apache-2.0
|
2cb95e254042a36f1a75c29aa33c56322aa817de
| 0 |
senseidb/bobo,javasoze/bobo
|
package com.browseengine.bobo.sort;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import org.apache.log4j.Logger;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.SortField;
import com.browseengine.bobo.api.BoboCustomSortField;
import com.browseengine.bobo.api.BoboSegmentReader;
import com.browseengine.bobo.api.Browsable;
import com.browseengine.bobo.api.BrowseHit;
import com.browseengine.bobo.api.FacetAccessible;
import com.browseengine.bobo.facets.FacetHandler;
import com.browseengine.bobo.facets.RuntimeFacetHandler;
import com.browseengine.bobo.jmx.JMXUtil;
import com.browseengine.bobo.sort.DocComparatorSource.DocIdDocComparatorSource;
import com.browseengine.bobo.sort.DocComparatorSource.RelevanceDocComparatorSource;
import com.browseengine.bobo.util.MemoryManager;
import com.browseengine.bobo.util.MemoryManagerAdminMBean;
public abstract class SortCollector extends Collector {
private static final Logger logger = Logger.getLogger(SortCollector.class);
protected static MemoryManager<int[]> intarraymgr = new MemoryManager<int[]>(
new MemoryManager.Initializer<int[]>() {
@Override
public void init(int[] buf) {
Arrays.fill(buf, 0);
}
@Override
public int[] newInstance(int size) {
return new int[size];
}
@Override
public int size(int[] buf) {
assert buf != null;
return buf.length;
}
});
protected static MemoryManager<float[]> floatarraymgr = new MemoryManager<float[]>(
new MemoryManager.Initializer<float[]>() {
@Override
public void init(float[] buf) {
Arrays.fill(buf, 0);
}
@Override
public float[] newInstance(int size) {
return new float[size];
}
@Override
public int size(float[] buf) {
assert buf != null;
return buf.length;
}
});
static {
try {
// register memory manager mbean
MBeanServer mbeanServer = java.lang.management.ManagementFactory.getPlatformMBeanServer();
ObjectName mbeanName = new ObjectName(JMXUtil.JMX_DOMAIN, "name",
"SortCollectorImpl-MemoryManager-Int");
StandardMBean mbean = new StandardMBean(intarraymgr.getAdminMBean(),
MemoryManagerAdminMBean.class);
mbeanServer.registerMBean(mbean, mbeanName);
mbeanName = new ObjectName(JMXUtil.JMX_DOMAIN, "name",
"SortCollectorImpl-MemoryManager-Float");
mbean = new StandardMBean(floatarraymgr.getAdminMBean(), MemoryManagerAdminMBean.class);
mbeanServer.registerMBean(mbean, mbeanName);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
public static class CollectorContext {
public BoboSegmentReader reader;
public int base;
public DocComparator comparator;
public int length;
private Map<String, RuntimeFacetHandler<?>> _runtimeFacetMap;
private Map<String, Object> _runtimeFacetDataMap;
public CollectorContext(BoboSegmentReader reader, int base, DocComparator comparator) {
this.reader = reader;
this.base = base;
this.comparator = comparator;
_runtimeFacetMap = reader.getRuntimeFacetHandlerMap();
_runtimeFacetDataMap = reader.getRuntimeFacetDataMap();
}
public void restoreRuntimeFacets() {
reader.setRuntimeFacetHandlerMap(_runtimeFacetMap);
reader.setRuntimeFacetDataMap(_runtimeFacetDataMap);
}
public void clearRuntimeFacetData() {
reader.clearRuntimeFacetData();
reader.clearRuntimeFacetHandler();
_runtimeFacetDataMap = null;
_runtimeFacetMap = null;
}
}
public FacetHandler<?> groupBy = null; // Point to the first element of groupByMulti to avoid
// array lookups.
public FacetHandler<?>[] groupByMulti = null;
public LinkedList<CollectorContext> contextList;
public LinkedList<int[]> docidarraylist;
public LinkedList<float[]> scorearraylist;
public static int BLOCK_SIZE = 4096;
protected Collector _collector = null;
protected final SortField[] _sortFields;
protected final boolean _fetchStoredFields;
protected boolean _closed = false;
protected SortCollector(SortField[] sortFields, boolean fetchStoredFields) {
_sortFields = sortFields;
_fetchStoredFields = fetchStoredFields;
}
abstract public BrowseHit[] topDocs() throws IOException;
abstract public int getTotalHits();
abstract public int getTotalGroups();
abstract public FacetAccessible[] getGroupAccessibles();
private static DocComparatorSource getNonFacetComparatorSource(SortField sf) {
String fieldname = sf.getField();
SortField.Type type = sf.getType();
switch (type) {
case INT:
return new DocComparatorSource.IntDocComparatorSource(fieldname);
case FLOAT:
return new DocComparatorSource.FloatDocComparatorSource(fieldname);
case LONG:
return new DocComparatorSource.LongDocComparatorSource(fieldname);
case DOUBLE:
return new DocComparatorSource.DoubleDocComparatorSource(fieldname);
case BYTE:
return new DocComparatorSource.ByteDocComparatorSource(fieldname);
case SHORT:
return new DocComparatorSource.ShortDocComparatorSource(fieldname);
case STRING:
return new DocComparatorSource.StringOrdComparatorSource(fieldname);
case STRING_VAL:
return new DocComparatorSource.StringValComparatorSource(fieldname);
case CUSTOM:
throw new IllegalArgumentException("lucene custom sort no longer supported: " + fieldname);
default:
throw new IllegalStateException("Illegal sort type: " + type + ", for field: " + fieldname);
}
}
private static DocComparatorSource getComparatorSource(Browsable browser, SortField sf) {
DocComparatorSource compSource = null;
if (SortField.FIELD_DOC.equals(sf)) {
compSource = new DocIdDocComparatorSource();
} else if (SortField.FIELD_SCORE.equals(sf) || sf.getType() == SortField.Type.SCORE) {
// we want to do reverse sorting regardless for relevance
compSource = new ReverseDocComparatorSource(new RelevanceDocComparatorSource());
} else if (sf instanceof BoboCustomSortField) {
BoboCustomSortField custField = (BoboCustomSortField) sf;
DocComparatorSource src = custField.getCustomComparatorSource();
assert src != null;
compSource = src;
} else {
Set<String> facetNames = browser.getFacetNames();
String sortName = sf.getField();
if (facetNames.contains(sortName)) {
FacetHandler<?> handler = browser.getFacetHandler(sortName);
assert handler != null;
compSource = handler.getDocComparatorSource();
} else { // default lucene field
logger.info("doing default lucene sort for: " + sf);
compSource = getNonFacetComparatorSource(sf);
}
}
boolean reverse = sf.getReverse();
if (reverse) {
compSource = new ReverseDocComparatorSource(compSource);
}
compSource.setReverse(reverse);
return compSource;
}
private static SortField convert(Browsable browser, SortField sort) {
String field = sort.getField();
FacetHandler<?> facetHandler = browser.getFacetHandler(field);
if (facetHandler != null) {
browser.getFacetHandler(field);
BoboCustomSortField sortField = new BoboCustomSortField(field, sort.getReverse(),
facetHandler.getDocComparatorSource());
return sortField;
} else {
return sort;
}
}
public static SortCollector buildSortCollector(Browsable browser, Query q, SortField[] sort,
int offset, int count, boolean fetchStoredFields, Set<String> termVectorsToFetch,
String[] groupBy, int maxPerGroup, boolean collectDocIdCache) {
if (sort == null || sort.length == 0) {
if (q != null && !(q instanceof MatchAllDocsQuery)) {
sort = new SortField[] { SortField.FIELD_SCORE };
} else {
sort = new SortField[] { SortField.FIELD_DOC };
}
}
boolean doScoring = false;
for (SortField sf : sort) {
if (sf.getType() == SortField.Type.SCORE) {
doScoring = true;
break;
}
}
DocComparatorSource compSource;
if (sort.length == 1) {
SortField sf = convert(browser, sort[0]);
compSource = getComparatorSource(browser, sf);
} else {
DocComparatorSource[] compSources = new DocComparatorSource[sort.length];
for (int i = 0; i < sort.length; ++i) {
compSources[i] = getComparatorSource(browser, convert(browser, sort[i]));
}
compSource = new MultiDocIdComparatorSource(compSources);
}
return new SortCollectorImpl(compSource, sort, browser, offset, count, doScoring,
fetchStoredFields, termVectorsToFetch, groupBy, maxPerGroup, collectDocIdCache);
}
public SortCollector setCollector(Collector collector) {
_collector = collector;
return this;
}
public Collector getCollector() {
return _collector;
}
public void close() {
if (!_closed) {
_closed = true;
if (contextList != null) {
for (CollectorContext context : contextList) {
context.clearRuntimeFacetData();
}
}
if (docidarraylist != null) {
while (!docidarraylist.isEmpty()) {
intarraymgr.release(docidarraylist.poll());
}
}
if (scorearraylist != null) {
while (!scorearraylist.isEmpty()) {
floatarraymgr.release(scorearraylist.poll());
}
}
}
}
}
|
bobo-browse/src/main/java/com/browseengine/bobo/sort/SortCollector.java
|
package com.browseengine.bobo.sort;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import org.apache.log4j.Logger;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.SortField;
import com.browseengine.bobo.api.BoboCustomSortField;
import com.browseengine.bobo.api.BoboSegmentReader;
import com.browseengine.bobo.api.Browsable;
import com.browseengine.bobo.api.BrowseHit;
import com.browseengine.bobo.api.FacetAccessible;
import com.browseengine.bobo.facets.FacetHandler;
import com.browseengine.bobo.facets.RuntimeFacetHandler;
import com.browseengine.bobo.jmx.JMXUtil;
import com.browseengine.bobo.sort.DocComparatorSource.DocIdDocComparatorSource;
import com.browseengine.bobo.sort.DocComparatorSource.RelevanceDocComparatorSource;
import com.browseengine.bobo.util.MemoryManager;
import com.browseengine.bobo.util.MemoryManagerAdminMBean;
public abstract class SortCollector extends Collector {
private static final Logger logger = Logger.getLogger(SortCollector.class);
protected static MemoryManager<int[]> intarraymgr = new MemoryManager<int[]>(
new MemoryManager.Initializer<int[]>() {
@Override
public void init(int[] buf) {
Arrays.fill(buf, 0);
}
@Override
public int[] newInstance(int size) {
return new int[size];
}
@Override
public int size(int[] buf) {
assert buf != null;
return buf.length;
}
});
protected static MemoryManager<float[]> floatarraymgr = new MemoryManager<float[]>(
new MemoryManager.Initializer<float[]>() {
@Override
public void init(float[] buf) {
Arrays.fill(buf, 0);
}
@Override
public float[] newInstance(int size) {
return new float[size];
}
@Override
public int size(float[] buf) {
assert buf != null;
return buf.length;
}
});
static {
try {
// register memory manager mbean
MBeanServer mbeanServer = java.lang.management.ManagementFactory.getPlatformMBeanServer();
ObjectName mbeanName = new ObjectName(JMXUtil.JMX_DOMAIN, "name",
"SortCollectorImpl-MemoryManager-Int");
StandardMBean mbean = new StandardMBean(intarraymgr.getAdminMBean(),
MemoryManagerAdminMBean.class);
mbeanServer.registerMBean(mbean, mbeanName);
mbeanName = new ObjectName(JMXUtil.JMX_DOMAIN, "name",
"SortCollectorImpl-MemoryManager-Float");
mbean = new StandardMBean(floatarraymgr.getAdminMBean(), MemoryManagerAdminMBean.class);
mbeanServer.registerMBean(mbean, mbeanName);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
public static class CollectorContext {
public BoboSegmentReader reader;
public int base;
public DocComparator comparator;
public int length;
private Map<String, RuntimeFacetHandler<?>> _runtimeFacetMap;
private Map<String, Object> _runtimeFacetDataMap;
public CollectorContext(BoboSegmentReader reader, int base, DocComparator comparator) {
this.reader = reader;
this.base = base;
this.comparator = comparator;
_runtimeFacetMap = reader.getRuntimeFacetHandlerMap();
_runtimeFacetDataMap = reader.getRuntimeFacetDataMap();
}
public void restoreRuntimeFacets() {
reader.setRuntimeFacetHandlerMap(_runtimeFacetMap);
reader.setRuntimeFacetDataMap(_runtimeFacetDataMap);
}
public void clearRuntimeFacetData() {
reader.clearRuntimeFacetData();
reader.clearRuntimeFacetHandler();
_runtimeFacetDataMap = null;
_runtimeFacetMap = null;
}
}
public FacetHandler<?> groupBy = null; // Point to the first element of groupByMulti to avoid
// array lookups.
public FacetHandler<?>[] groupByMulti = null;
public LinkedList<CollectorContext> contextList;
public LinkedList<int[]> docidarraylist;
public LinkedList<float[]> scorearraylist;
public static int BLOCK_SIZE = 4096;
protected Collector _collector = null;
protected final SortField[] _sortFields;
protected final boolean _fetchStoredFields;
protected boolean _closed = false;
protected SortCollector(SortField[] sortFields, boolean fetchStoredFields) {
_sortFields = sortFields;
_fetchStoredFields = fetchStoredFields;
}
abstract public BrowseHit[] topDocs() throws IOException;
abstract public int getTotalHits();
abstract public int getTotalGroups();
abstract public FacetAccessible[] getGroupAccessibles();
private static DocComparatorSource getNonFacetComparatorSource(SortField sf) {
String fieldname = sf.getField();
SortField.Type type = sf.getType();
switch (type) {
case INT:
return new DocComparatorSource.IntDocComparatorSource(fieldname);
case FLOAT:
return new DocComparatorSource.FloatDocComparatorSource(fieldname);
case LONG:
return new DocComparatorSource.LongDocComparatorSource(fieldname);
case DOUBLE:
return new DocComparatorSource.LongDocComparatorSource(fieldname);
case BYTE:
return new DocComparatorSource.ByteDocComparatorSource(fieldname);
case SHORT:
return new DocComparatorSource.ShortDocComparatorSource(fieldname);
case STRING:
return new DocComparatorSource.StringOrdComparatorSource(fieldname);
case STRING_VAL:
return new DocComparatorSource.StringValComparatorSource(fieldname);
case CUSTOM:
throw new IllegalArgumentException("lucene custom sort no longer supported: " + fieldname);
default:
throw new IllegalStateException("Illegal sort type: " + type + ", for field: " + fieldname);
}
}
private static DocComparatorSource getComparatorSource(Browsable browser, SortField sf) {
DocComparatorSource compSource = null;
if (SortField.FIELD_DOC.equals(sf)) {
compSource = new DocIdDocComparatorSource();
} else if (SortField.FIELD_SCORE.equals(sf) || sf.getType() == SortField.Type.SCORE) {
// we want to do reverse sorting regardless for relevance
compSource = new ReverseDocComparatorSource(new RelevanceDocComparatorSource());
} else if (sf instanceof BoboCustomSortField) {
BoboCustomSortField custField = (BoboCustomSortField) sf;
DocComparatorSource src = custField.getCustomComparatorSource();
assert src != null;
compSource = src;
} else {
Set<String> facetNames = browser.getFacetNames();
String sortName = sf.getField();
if (facetNames.contains(sortName)) {
FacetHandler<?> handler = browser.getFacetHandler(sortName);
assert handler != null;
compSource = handler.getDocComparatorSource();
} else { // default lucene field
logger.info("doing default lucene sort for: " + sf);
compSource = getNonFacetComparatorSource(sf);
}
}
boolean reverse = sf.getReverse();
if (reverse) {
compSource = new ReverseDocComparatorSource(compSource);
}
compSource.setReverse(reverse);
return compSource;
}
private static SortField convert(Browsable browser, SortField sort) {
String field = sort.getField();
FacetHandler<?> facetHandler = browser.getFacetHandler(field);
if (facetHandler != null) {
browser.getFacetHandler(field);
BoboCustomSortField sortField = new BoboCustomSortField(field, sort.getReverse(),
facetHandler.getDocComparatorSource());
return sortField;
} else {
return sort;
}
}
public static SortCollector buildSortCollector(Browsable browser, Query q, SortField[] sort,
int offset, int count, boolean fetchStoredFields, Set<String> termVectorsToFetch,
String[] groupBy, int maxPerGroup, boolean collectDocIdCache) {
if (sort == null || sort.length == 0) {
if (q != null && !(q instanceof MatchAllDocsQuery)) {
sort = new SortField[] { SortField.FIELD_SCORE };
} else {
sort = new SortField[] { SortField.FIELD_DOC };
}
}
boolean doScoring = false;
for (SortField sf : sort) {
if (sf.getType() == SortField.Type.SCORE) {
doScoring = true;
break;
}
}
DocComparatorSource compSource;
if (sort.length == 1) {
SortField sf = convert(browser, sort[0]);
compSource = getComparatorSource(browser, sf);
} else {
DocComparatorSource[] compSources = new DocComparatorSource[sort.length];
for (int i = 0; i < sort.length; ++i) {
compSources[i] = getComparatorSource(browser, convert(browser, sort[i]));
}
compSource = new MultiDocIdComparatorSource(compSources);
}
return new SortCollectorImpl(compSource, sort, browser, offset, count, doScoring,
fetchStoredFields, termVectorsToFetch, groupBy, maxPerGroup, collectDocIdCache);
}
public SortCollector setCollector(Collector collector) {
_collector = collector;
return this;
}
public Collector getCollector() {
return _collector;
}
public void close() {
if (!_closed) {
_closed = true;
if (contextList != null) {
for (CollectorContext context : contextList) {
context.clearRuntimeFacetData();
}
}
if (docidarraylist != null) {
while (!docidarraylist.isEmpty()) {
intarraymgr.release(docidarraylist.poll());
}
}
if (scorearraylist != null) {
while (!scorearraylist.isEmpty()) {
floatarraymgr.release(scorearraylist.poll());
}
}
}
}
}
|
Bobo browser doesn't order by double correctly
|
bobo-browse/src/main/java/com/browseengine/bobo/sort/SortCollector.java
|
Bobo browser doesn't order by double correctly
|
<ide><path>obo-browse/src/main/java/com/browseengine/bobo/sort/SortCollector.java
<ide> return new DocComparatorSource.LongDocComparatorSource(fieldname);
<ide>
<ide> case DOUBLE:
<del> return new DocComparatorSource.LongDocComparatorSource(fieldname);
<add> return new DocComparatorSource.DoubleDocComparatorSource(fieldname);
<ide>
<ide> case BYTE:
<ide> return new DocComparatorSource.ByteDocComparatorSource(fieldname);
|
|
Java
|
mit
|
a2ae3b2cdb024e32b0a02250cd51ba8b902f3d3c
| 0 |
chenav/orufeo
|
package orufeo.ia.facebook;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.cloud.language.v1.Sentiment;
import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.Version;
import com.restfb.FacebookClient.AccessToken;
import com.restfb.types.Comment;
import com.restfb.types.Page;
import com.restfb.types.Post;
import com.restfb.types.User;
import orufeo.ia.ConfigurationObject;
import orufeo.ia.gcloud.NplAnalyzer;
import orufeo.ia.gcloud.VisionAnalyzer;
public class FacebookBoImpl implements FacebookBo {
private static final Logger log = LogManager.getLogger(FacebookBoImpl.class);
private ObjectMapper mapper = new ObjectMapper();
private Connection<Post> collectFeed(String pagename) {
AccessToken accessToken = new DefaultFacebookClient(Version.VERSION_2_3).obtainAppAccessToken(ConfigurationObject.MY_APP_ID, ConfigurationObject.MY_APP_SECRET);
FacebookClient facebookClient23 = new DefaultFacebookClient(accessToken.getAccessToken(), Version.VERSION_2_3);
//User user = facebookClient23.fetchObject("me", User.class);
Page page = facebookClient23.fetchObject(pagename, Page.class, Parameter.with("fields","name,id, picture, likes"));
return facebookClient23.fetchConnection(page.getId()+"/feed", Post.class, Parameter.with("fields", "comments, full_picture")); //message,picture, likes, from,
}
@Override
public void analyzeImages(String pagename) {
Connection<Post> myFeed = collectFeed(pagename);
for (List<Post> myFeedPage : myFeed) {
for (Post post : myFeedPage) {
String urlPicture = post.getFullPicture();
if (null!=urlPicture) {
System.out.println("Picture :"+urlPicture);
VisionAnalyzer.getInstance().analyzeLabels(urlPicture);
}
}
}
}
@Override
public void searchPage(String pagename) {
Connection<Post> myFeed = collectFeed(pagename);
for (List<Post> myFeedPage : myFeed) { //paging made in facebook api
// Iterate over the list of contained data
// to access the individual object
for (Post post : myFeedPage) {
if (null!=post.getComments() && post.getComments().getData()!=null) {
for ( Comment comment : post.getComments().getData()) {
try {
NplAnalyzer analyzer = NplAnalyzer.getInstance();
Sentiment feeling = analyzer.analyze(comment.getMessage());
if (feeling.getScore() < 0 && feeling.getMagnitude()>1) {
System.out.println("**********************************");
System.out.println("Date :"+comment.getCreatedTime());
System.out.println("User :"+comment.getFrom().getName());
System.out.println("UserId :"+comment.getFrom().getId());
System.out.println("Message :"+comment.getMessage());
System.out.println("Sentiment: score="+ feeling.getScore()+", magnitude="+ feeling.getMagnitude());
}
} catch (Exception e) {
System.out.println("ERROR in analysis: "+e.getMessage());
}
}
}
}
}
}
private User searchUser(String id) {
AccessToken accessToken = new DefaultFacebookClient(Version.VERSION_2_3).obtainAppAccessToken(ConfigurationObject.MY_APP_ID, ConfigurationObject.MY_APP_SECRET);
FacebookClient facebookClient23 = new DefaultFacebookClient(accessToken.getAccessToken(), Version.VERSION_2_3);
User user = facebookClient23.fetchObject(id, User.class, Parameter.with("fields","about,age_range, birthday,context, education,email,gender, first_name, last_name, relationship_status, work"));
return user;
}
}
|
ia/src/main/java/orufeo/ia/facebook/FacebookBoImpl.java
|
package orufeo.ia.facebook;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.cloud.language.v1.Sentiment;
import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.Version;
import com.restfb.FacebookClient.AccessToken;
import com.restfb.types.Comment;
import com.restfb.types.Page;
import com.restfb.types.Post;
import com.restfb.types.User;
import orufeo.ia.ConfigurationObject;
import orufeo.ia.gcloud.NplAnalyzer;
import orufeo.ia.gcloud.VisionAnalyzer;
public class FacebookBoImpl implements FacebookBo {
private static final Logger log = LogManager.getLogger(FacebookBoImpl.class);
private ObjectMapper mapper = new ObjectMapper();
private Connection<Post> collectFeed(String pagename) {
AccessToken accessToken = new DefaultFacebookClient(Version.VERSION_2_3).obtainAppAccessToken(ConfigurationObject.MY_APP_ID, ConfigurationObject.MY_APP_SECRET);
FacebookClient facebookClient23 = new DefaultFacebookClient(accessToken.getAccessToken(), Version.VERSION_2_3);
//User user = facebookClient23.fetchObject("me", User.class);
Page page = facebookClient23.fetchObject(pagename, Page.class, Parameter.with("fields","name,id, picture, likes"));
return facebookClient23.fetchConnection(page.getId()+"/feed", Post.class, Parameter.with("fields", "comments, full_picture")); //message,picture, likes, from,
}
@Override
public void analyzeImages(String pagename) {
Connection<Post> myFeed = collectFeed(pagename);
for (List<Post> myFeedPage : myFeed) {
for (Post post : myFeedPage) {
String urlPicture = post.getFullPicture();
if (null!=urlPicture) {
System.out.println("Picture :"+urlPicture);
VisionAnalyzer.getInstance().analyzeLabels(urlPicture);
}
}
}
}
@Override
public void searchPage(String pagename) {
Connection<Post> myFeed = collectFeed(pagename);
for (List<Post> myFeedPage : myFeed) { //paging made in facebook api
// Iterate over the list of contained data
// to access the individual object
for (Post post : myFeedPage) {
/*try {
System.out.println("**********************************");
System.out.println("POST : "+ mapper.writeValueAsString(post));
} catch (Exception e) {
System.out.println("Impossible de lire le JSON");
}
*/
if (null!=post.getComments() && post.getComments().getData()!=null) {
for ( Comment comment : post.getComments().getData()) {
try {
NplAnalyzer analyzer = NplAnalyzer.getInstance();
Sentiment feeling = analyzer.analyze(comment.getMessage());
if (feeling.getScore() < 0 && feeling.getMagnitude()>1) {
System.out.println("**********************************");
System.out.println("Date :"+comment.getCreatedTime());
System.out.println("User :"+comment.getFrom().getName());
System.out.println("UserId :"+comment.getFrom().getId());
System.out.println("Message :"+comment.getMessage());
System.out.println("Sentiment: score="+ feeling.getScore()+", magnitude="+ feeling.getMagnitude());
}
} catch (Exception e) {
System.out.println("ERROR in analysis: "+e.getMessage());
}
}
}
}
}
}
private User searchUser(String id) {
AccessToken accessToken = new DefaultFacebookClient(Version.VERSION_2_3).obtainAppAccessToken(ConfigurationObject.MY_APP_ID, ConfigurationObject.MY_APP_SECRET);
FacebookClient facebookClient23 = new DefaultFacebookClient(accessToken.getAccessToken(), Version.VERSION_2_3);
User user = facebookClient23.fetchObject(id, User.class, Parameter.with("fields","about,age_range, birthday,context, education,email,gender, first_name, last_name, relationship_status, work"));
return user;
}
}
|
refactoring
|
ia/src/main/java/orufeo/ia/facebook/FacebookBoImpl.java
|
refactoring
|
<ide><path>a/src/main/java/orufeo/ia/facebook/FacebookBoImpl.java
<ide> // to access the individual object
<ide> for (Post post : myFeedPage) {
<ide>
<del> /*try {
<del> System.out.println("**********************************");
<del> System.out.println("POST : "+ mapper.writeValueAsString(post));
<del> } catch (Exception e) {
<del> System.out.println("Impossible de lire le JSON");
<del> }
<del> */
<del>
<ide> if (null!=post.getComments() && post.getComments().getData()!=null) {
<ide>
<ide> for ( Comment comment : post.getComments().getData()) {
<ide> System.out.println("UserId :"+comment.getFrom().getId());
<ide> System.out.println("Message :"+comment.getMessage());
<ide> System.out.println("Sentiment: score="+ feeling.getScore()+", magnitude="+ feeling.getMagnitude());
<del>
<ide>
<ide> }
<ide> } catch (Exception e) {
|
|
Java
|
mit
|
ad162bb91ac90ac9acab16eb043e00d741758658
| 0 |
sebastianstock/chimp
|
package dispatching;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.logging.Logger;
import org.metacsp.framework.Constraint;
import org.metacsp.framework.ConstraintNetwork;
import org.metacsp.framework.Variable;
import org.metacsp.multi.allenInterval.AllenIntervalConstraint;
import org.metacsp.time.Bounds;
import org.metacsp.utility.logging.MetaCSPLogging;
import fluentSolver.Fluent;
import fluentSolver.FluentNetworkSolver;
import sensing.FluentConstraintNetworkAnimator;
public class FluentDispatcher extends Thread {
public static enum ACTIVITY_STATE {PLANNED, STARTED, FINISHING, FINISHED, SKIP_BECAUSE_UNIFICATION, FAILED};
private ConstraintNetwork cn;
private FluentNetworkSolver fns;
private long period;
private HashMap<Fluent,ACTIVITY_STATE> acts;
private HashMap<Fluent,AllenIntervalConstraint> overlapFutureConstraints;
private HashMap<String,FluentDispatchingFunction> dfs;
private Fluent future;
private transient Logger logger = MetaCSPLogging.getLogger(this.getClass());
public FluentDispatcher(FluentNetworkSolver fns, long period, Fluent future) {
this.fns = fns;
cn = fns.getConstraintNetwork();
this.period = period;
acts = new HashMap<Fluent, ACTIVITY_STATE>();
overlapFutureConstraints = new HashMap<Fluent, AllenIntervalConstraint>();
dfs = new HashMap<String, FluentDispatchingFunction>();
this.future = future;
}
@Override
public void run() {
while (! isInterrupted()) {
try { Thread.sleep(period); } // TODO put this to the end to prevent sleeping right at the beginning?
catch (InterruptedException e) {
interrupt();
}
synchronized(fns) {
for (String component : dfs.keySet()) {
// go through all activity fluents
Variable[] vars = cn.getVariables(component);
Arrays.sort(vars, new Comparator<Variable>() {
@Override
public int compare(Variable o1, Variable o2) {
if (o1 instanceof Fluent && o2 instanceof Fluent) {
long o1_est = ((Fluent) o1).getAllenInterval().getEST();
long o2_est = ((Fluent) o2).getAllenInterval().getEST();
int c = Long.compare(o1_est, o2_est);
if (c == 0) {
c = o1.compareTo(o2);
}
return c;
} else {
return o1.compareTo(o2);
}
}
});
for (Variable var : vars) {
if (var instanceof Fluent) {
Fluent act = (Fluent)var;
if (dfs.get(component).skip(act)) continue;
//New act, tag as not dispatched
if (!acts.containsKey(act)) {
boolean skip = false;
//... but test if activity is a unification - if so, ignore it!
Constraint[] outgoing = fns.getConstraintNetwork().getOutgoingEdges(act);
for (Constraint con : outgoing) {
if (con instanceof AllenIntervalConstraint) {
AllenIntervalConstraint aic = (AllenIntervalConstraint)con;
Fluent to = (Fluent)aic.getTo();
if (to.getComponent().equals(act.getComponent()) &&
to.getCompoundSymbolicVariable().getName().equals(act.getCompoundSymbolicVariable().getName()) &&
aic.getTypes()[0].equals(AllenIntervalConstraint.Type.Equals)) {
skip = true;
logger.info("IGNORED UNIFICATION " + aic);
break;
}
}
}
if (!skip) acts.put(act, ACTIVITY_STATE.PLANNED);
else acts.put(act, ACTIVITY_STATE.SKIP_BECAUSE_UNIFICATION);
}
//Not dispatched, check if need to dispatch
if (acts.get(act).equals(ACTIVITY_STATE.PLANNED)) {
//time to dispatch, do it!
if (act.getTemporalVariable().getEST() < future.getTemporalVariable().getEST()) {
acts.put(act, ACTIVITY_STATE.STARTED);
AllenIntervalConstraint overlapsFuture = new AllenIntervalConstraint(AllenIntervalConstraint.Type.Overlaps);
overlapsFuture.setFrom(act);
overlapsFuture.setTo(future);
boolean ret = fns.addConstraint(overlapsFuture);
if(!ret){
logger.info("IGNORED: " + act);
// System.out.println(" CONSTRAINTS IN: " + Arrays.toString(fns.getConstraintNetwork().getIncidentEdges(act)));
// System.out.println(" CONSTRAINTS OUT: " + Arrays.toString(fns.getConstraintNetwork().getOutgoingEdges(act)));
// CopyOfTestProblemParsing.extractPlan(fns);
}
else {
overlapFutureConstraints.put(act, overlapsFuture);
this.dfs.get(component).dispatch(act);
}
}
}
//If finished, tag as finished
else if (acts.get(act).equals(ACTIVITY_STATE.FINISHING)) {
acts.put(act, ACTIVITY_STATE.FINISHED);
fns.removeConstraint(overlapFutureConstraints.get(act));
AllenIntervalConstraint deadline = new AllenIntervalConstraint(AllenIntervalConstraint.Type.Deadline, new Bounds(future.getTemporalVariable().getEST(),future.getTemporalVariable().getEST()));
deadline.setFrom(act);
deadline.setTo(act);
if (!fns.addConstraint(deadline)) {
AllenIntervalConstraint defaultDeadline = new AllenIntervalConstraint(AllenIntervalConstraint.Type.Deadline, new Bounds(act.getTemporalVariable().getEET(),act.getTemporalVariable().getEET()));
defaultDeadline.setFrom(act);
defaultDeadline.setTo(act);
fns.addConstraint(defaultDeadline);
//System.out.println("++++++++++++++++++++ SHIT: " + act + " DAEDLINE AT " + future.getTemporalVariable().getEST());
}
}
}
}
}
}
synchronized(this) {
if (this.isFinished()) {
logger.info("dispatching finished: notifying all waiting threads");
this.notifyAll();
}
if (this.failed()) {
logger.info("dispatching failed: notifying all waiting threads");
this.notifyAll();
}
}
}
}
/**
* Check if all activities have been finished.
* @return true if all activities have been finished, i.e., no started or planned activites exist, otherwise false
*/
public boolean isFinished() {
for (ACTIVITY_STATE state : acts.values()) {
if (state.equals(ACTIVITY_STATE.PLANNED) || state.equals(ACTIVITY_STATE.STARTED) || state.equals(ACTIVITY_STATE.FINISHING)) {
return false;
}
}
logger.fine("Acts.size: " + acts.size());
return true;
}
/**
* Check if any activity has failed.
* @return true if any activity has failed, otherwise false
*/
public boolean failed() {
for (ACTIVITY_STATE state : acts.values()) {
if (state.equals(ACTIVITY_STATE.FAILED)) {
return true;
}
}
return false;
}
public void addDispatchingFunction(String component, FluentDispatchingFunction df) {
df.registerDispatcher(this);
this.dfs.put(component, df);
}
public void finish(Fluent act) { acts.put(act, ACTIVITY_STATE.FINISHING); }
public void fail(Fluent act) {acts.put(act, ACTIVITY_STATE.FAILED); }
public ConstraintNetwork getConstraintNetwork() {
return fns.getConstraintNetwork();
}
}
|
src/main/java/dispatching/FluentDispatcher.java
|
package dispatching;
import java.util.HashMap;
import java.util.logging.Logger;
import org.metacsp.framework.Constraint;
import org.metacsp.framework.ConstraintNetwork;
import org.metacsp.framework.Variable;
import org.metacsp.multi.allenInterval.AllenIntervalConstraint;
import org.metacsp.time.Bounds;
import org.metacsp.utility.logging.MetaCSPLogging;
import fluentSolver.Fluent;
import fluentSolver.FluentNetworkSolver;
import sensing.FluentConstraintNetworkAnimator;
public class FluentDispatcher extends Thread {
public static enum ACTIVITY_STATE {PLANNED, STARTED, FINISHING, FINISHED, SKIP_BECAUSE_UNIFICATION, FAILED};
private ConstraintNetwork cn;
private FluentNetworkSolver fns;
private long period;
private HashMap<Fluent,ACTIVITY_STATE> acts;
private HashMap<Fluent,AllenIntervalConstraint> overlapFutureConstraints;
private HashMap<String,FluentDispatchingFunction> dfs;
private Fluent future;
private transient Logger logger = MetaCSPLogging.getLogger(this.getClass());
public FluentDispatcher(FluentNetworkSolver fns, long period, Fluent future) {
this.fns = fns;
cn = fns.getConstraintNetwork();
this.period = period;
acts = new HashMap<Fluent, ACTIVITY_STATE>();
overlapFutureConstraints = new HashMap<Fluent, AllenIntervalConstraint>();
dfs = new HashMap<String, FluentDispatchingFunction>();
this.future = future;
}
@Override
public void run() {
while (! isInterrupted()) {
try { Thread.sleep(period); } // TODO put this to the end to prevent sleeping right at the beginning?
catch (InterruptedException e) {
interrupt();
}
synchronized(fns) {
for (String component : dfs.keySet()) {
// go through all activity fluents
for (Variable var : cn.getVariables(component)) {
if (var instanceof Fluent) {
Fluent act = (Fluent)var;
if (dfs.get(component).skip(act)) continue;
//New act, tag as not dispatched
if (!acts.containsKey(act)) {
boolean skip = false;
//... but test if activity is a unification - if so, ignore it!
Constraint[] outgoing = fns.getConstraintNetwork().getOutgoingEdges(act);
for (Constraint con : outgoing) {
if (con instanceof AllenIntervalConstraint) {
AllenIntervalConstraint aic = (AllenIntervalConstraint)con;
Fluent to = (Fluent)aic.getTo();
if (to.getComponent().equals(act.getComponent()) &&
to.getCompoundSymbolicVariable().getName().equals(act.getCompoundSymbolicVariable().getName()) &&
aic.getTypes()[0].equals(AllenIntervalConstraint.Type.Equals)) {
skip = true;
logger.info("IGNORED UNIFICATION " + aic);
break;
}
}
}
if (!skip) acts.put(act, ACTIVITY_STATE.PLANNED);
else acts.put(act, ACTIVITY_STATE.SKIP_BECAUSE_UNIFICATION);
}
//Not dispatched, check if need to dispatch
if (acts.get(act).equals(ACTIVITY_STATE.PLANNED)) {
//time to dispatch, do it!
if (act.getTemporalVariable().getEST() < future.getTemporalVariable().getEST()) {
acts.put(act, ACTIVITY_STATE.STARTED);
AllenIntervalConstraint overlapsFuture = new AllenIntervalConstraint(AllenIntervalConstraint.Type.Overlaps);
overlapsFuture.setFrom(act);
overlapsFuture.setTo(future);
boolean ret = fns.addConstraint(overlapsFuture);
if(!ret){
logger.info("IGNORED: " + act);
// System.out.println(" CONSTRAINTS IN: " + Arrays.toString(fns.getConstraintNetwork().getIncidentEdges(act)));
// System.out.println(" CONSTRAINTS OUT: " + Arrays.toString(fns.getConstraintNetwork().getOutgoingEdges(act)));
// CopyOfTestProblemParsing.extractPlan(fns);
}
else {
overlapFutureConstraints.put(act, overlapsFuture);
this.dfs.get(component).dispatch(act);
}
}
}
//If finished, tag as finished
else if (acts.get(act).equals(ACTIVITY_STATE.FINISHING)) {
acts.put(act, ACTIVITY_STATE.FINISHED);
fns.removeConstraint(overlapFutureConstraints.get(act));
AllenIntervalConstraint deadline = new AllenIntervalConstraint(AllenIntervalConstraint.Type.Deadline, new Bounds(future.getTemporalVariable().getEST(),future.getTemporalVariable().getEST()));
deadline.setFrom(act);
deadline.setTo(act);
if (!fns.addConstraint(deadline)) {
AllenIntervalConstraint defaultDeadline = new AllenIntervalConstraint(AllenIntervalConstraint.Type.Deadline, new Bounds(act.getTemporalVariable().getEET(),act.getTemporalVariable().getEET()));
defaultDeadline.setFrom(act);
defaultDeadline.setTo(act);
fns.addConstraint(defaultDeadline);
//System.out.println("++++++++++++++++++++ SHIT: " + act + " DAEDLINE AT " + future.getTemporalVariable().getEST());
}
}
}
}
}
}
synchronized(this) {
if (this.isFinished()) {
logger.info("dispatching finished: notifying all waiting threads");
this.notifyAll();
}
if (this.failed()) {
logger.info("dispatching failed: notifying all waiting threads");
this.notifyAll();
}
}
}
}
/**
* Check if all activities have been finished.
* @return true if all activities have been finished, i.e., no started or planned activites exist, otherwise false
*/
public boolean isFinished() {
for (ACTIVITY_STATE state : acts.values()) {
if (state.equals(ACTIVITY_STATE.PLANNED) || state.equals(ACTIVITY_STATE.STARTED) || state.equals(ACTIVITY_STATE.FINISHING)) {
return false;
}
}
logger.fine("Acts.size: " + acts.size());
return true;
}
/**
* Check if any activity has failed.
* @return true if any activity has failed, otherwise false
*/
public boolean failed() {
for (ACTIVITY_STATE state : acts.values()) {
if (state.equals(ACTIVITY_STATE.FAILED)) {
return true;
}
}
return false;
}
public void addDispatchingFunction(String component, FluentDispatchingFunction df) {
df.registerDispatcher(this);
this.dfs.put(component, df);
}
public void finish(Fluent act) { acts.put(act, ACTIVITY_STATE.FINISHING); }
public void fail(Fluent act) {acts.put(act, ACTIVITY_STATE.FAILED); }
public ConstraintNetwork getConstraintNetwork() {
return fns.getConstraintNetwork();
}
}
|
Fixed ignored activities in dispatching.
Sometimes activities that would have been ready for dispatching where ignored, because, both the
activity and their successor activity could be dispatched given a long update interval of the
FluentDispatcher.
This is solved by ordering the acitivities temporally before checking which can be dispatched.
|
src/main/java/dispatching/FluentDispatcher.java
|
Fixed ignored activities in dispatching.
|
<ide><path>rc/main/java/dispatching/FluentDispatcher.java
<ide> package dispatching;
<ide>
<add>import java.util.Arrays;
<add>import java.util.Comparator;
<ide> import java.util.HashMap;
<ide> import java.util.logging.Logger;
<ide>
<ide> synchronized(fns) {
<ide> for (String component : dfs.keySet()) {
<ide> // go through all activity fluents
<del> for (Variable var : cn.getVariables(component)) {
<add> Variable[] vars = cn.getVariables(component);
<add> Arrays.sort(vars, new Comparator<Variable>() {
<add>
<add> @Override
<add> public int compare(Variable o1, Variable o2) {
<add> if (o1 instanceof Fluent && o2 instanceof Fluent) {
<add> long o1_est = ((Fluent) o1).getAllenInterval().getEST();
<add> long o2_est = ((Fluent) o2).getAllenInterval().getEST();
<add> int c = Long.compare(o1_est, o2_est);
<add> if (c == 0) {
<add> c = o1.compareTo(o2);
<add> }
<add> return c;
<add> } else {
<add> return o1.compareTo(o2);
<add> }
<add> }
<add> });
<add>
<add> for (Variable var : vars) {
<ide> if (var instanceof Fluent) {
<ide> Fluent act = (Fluent)var;
<ide> if (dfs.get(component).skip(act)) continue;
|
|
Java
|
apache-2.0
|
c67caf5e8be8b623d567a8d0a0f0b7e5a96625d4
| 0 |
tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki
|
/*
JSPWiki - a JSP-based WikiWiki clone.
Copyright (C) 2002 Janne Jalkanen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.ecyrd.jspwiki.plugin;
import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.providers.ProviderException;
import org.apache.log4j.Category;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.*;
/**
* Builds a simple weblog.
* <P>
* The pageformat can use the following params:<br>
* %p - Page name<br>
*
* <B>Parameters</B>
* <UL>
* <LI>days - how many days the weblog aggregator should show.
* <LI>pageformat - What the entries should look like.
* <LI>startDate - Date when to start. Format is "ddMMyy";
* </UL>
*
* The "days" and "startDate" can also be sent in HTTP parameters,
* and the names are "weblog.days" and "weblog.startDate", respectively.
*
* @since 1.9.21
*/
// FIXME: Add "entries" param as an alternative to "days".
// FIXME: Entries arrive in wrong order.
public class WeblogPlugin implements WikiPlugin
{
private static Category log = Category.getInstance(WeblogPlugin.class);
public static final int DEFAULT_DAYS = 7;
public static final String DEFAULT_PAGEFORMAT = "%p_blogentry_";
public static final String DEFAULT_DATEFORMAT = "ddMMyy";
public static final String PARAM_STARTDATE = "startDate";
public static final String PARAM_DAYS = "days";
public static final String PARAM_ALLOWCOMMENTS = "allowComments";
public static String makeEntryPage( String pageName,
String date,
String entryNum )
{
return TextUtil.replaceString(DEFAULT_PAGEFORMAT,"%p",pageName)+date+"_"+entryNum;
}
public static String makeEntryPage( String pageName )
{
return TextUtil.replaceString(DEFAULT_PAGEFORMAT,"%p",pageName);
}
public static String makeEntryPage( String pageName, String date )
{
return TextUtil.replaceString(DEFAULT_PAGEFORMAT,"%p",pageName)+date;
}
public String execute( WikiContext context, Map params )
throws PluginException
{
String weblogName = context.getPage().getName();
Calendar startTime;
Calendar stopTime;
int numDays;
WikiEngine engine = context.getEngine();
//
// Parse parameters.
//
String days;
String startDay = null;
boolean hasComments = false;
if( (days = context.getHttpParameter( "weblog."+PARAM_DAYS )) == null )
{
days = (String) params.get( PARAM_DAYS );
}
numDays = TextUtil.parseIntParameter( days, DEFAULT_DAYS );
if( (startDay = (String)params.get(PARAM_STARTDATE)) == null )
{
startDay = context.getHttpParameter( "weblog."+PARAM_STARTDATE );
}
if( TextUtil.isPositive( (String)params.get(PARAM_ALLOWCOMMENTS) ) )
{
hasComments = true;
}
//
// Determine the date range which to include.
//
startTime = Calendar.getInstance();
stopTime = Calendar.getInstance();
if( startDay != null )
{
SimpleDateFormat fmt = new SimpleDateFormat( DEFAULT_DATEFORMAT );
try
{
Date d = fmt.parse( startDay );
startTime.setTime( d );
stopTime.setTime( d );
}
catch( ParseException e )
{
return "Illegal time format: "+startDay;
}
}
//
// We make a wild guess here that nobody can do millisecond
// accuracy here.
//
startTime.add( Calendar.DAY_OF_MONTH, -numDays );
startTime.set( Calendar.HOUR, 0 );
startTime.set( Calendar.MINUTE, 0 );
startTime.set( Calendar.SECOND, 0 );
stopTime.set( Calendar.HOUR, 23 );
stopTime.set( Calendar.MINUTE, 59 );
stopTime.set( Calendar.SECOND, 59 );
StringBuffer sb = new StringBuffer();
try
{
List blogEntries = findBlogEntries( context.getEngine().getPageManager(),
weblogName,
startTime.getTime(),
stopTime.getTime() );
Collections.sort( blogEntries, new PageDateComparator() );
SimpleDateFormat entryDateFmt = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
sb.append("<DIV CLASS=\"weblog\">\n");
for( Iterator i = blogEntries.iterator(); i.hasNext(); )
{
WikiPage p = (WikiPage) i.next();
sb.append("<DIV CLASS=\"weblogheading\">");
Date entryDate = p.getLastModified();
sb.append( entryDateFmt.format(entryDate) );
sb.append("</DIV>\n");
sb.append("<DIV CLASS=\"weblogentry\">");
//
// Append the text of the latest version.
//
sb.append( engine.getHTML( context,
engine.getPage(p.getName()) ) );
sb.append("</DIV>\n");
sb.append("<div class=\"weblogpermalink\">");
sb.append( "<a href=\""+engine.getViewURL(p.getName())+"\">Permalink</a>" );
String commentPageName = TextUtil.replaceString( p.getName(),
"blogentry",
"comments" );
if( engine.pageExists( commentPageName ) )
{
sb.append( " " );
sb.append( "<a href=\""+engine.getViewURL(commentPageName)+"\">View Comments</a>" );
}
if( hasComments )
{
sb.append( " " );
sb.append( "<a href=\""+engine.getEditURL(commentPageName)+"&comment=true\">Comment this entry</a>" );
}
sb.append("</div>");
}
sb.append("</DIV>\n");
}
catch( ProviderException e )
{
log.error( "Could not locate blog entries", e );
throw new PluginException( "Could not locate blog entries: "+e.getMessage() );
}
return sb.toString();
}
/**
* Attempts to locate all pages that correspond to the
* blog entry pattern.
*
* Returns a list of pages with their FIRST revisions.
*/
public List findBlogEntries( PageManager mgr,
String baseName, Date start, Date end )
throws ProviderException
{
Collection everyone = mgr.getAllPages();
ArrayList result = new ArrayList();
baseName = makeEntryPage( baseName );
SimpleDateFormat fmt = new SimpleDateFormat(DEFAULT_DATEFORMAT);
for( Iterator i = everyone.iterator(); i.hasNext(); )
{
WikiPage p = (WikiPage)i.next();
String pageName = p.getName();
if( pageName.startsWith( baseName ) )
{
WikiPage firstVersion = mgr.getPageInfo( pageName, 1 );
Date pageDay = firstVersion.getLastModified();
if( pageDay != null )
{
if( pageDay.after(start) && pageDay.before(end) )
{
result.add( firstVersion );
}
}
}
}
return result;
}
/**
* Reverse comparison.
*/
private class PageDateComparator implements Comparator
{
public int compare( Object o1, Object o2 )
{
if( o1 == null || o2 == null )
{
return 0;
}
WikiPage page1 = (WikiPage)o1;
WikiPage page2 = (WikiPage)o2;
return page2.getLastModified().compareTo( page1.getLastModified() );
}
}
}
|
src/com/ecyrd/jspwiki/plugin/WeblogPlugin.java
|
/*
JSPWiki - a JSP-based WikiWiki clone.
Copyright (C) 2002 Janne Jalkanen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.ecyrd.jspwiki.plugin;
import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.providers.ProviderException;
import org.apache.log4j.Category;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.*;
/**
* Builds a simple weblog.
* <P>
* The pageformat can use the following params:<br>
* %p - Page name<br>
*
* <B>Parameters</B>
* <UL>
* <LI>days - how many days the weblog aggregator should show.
* <LI>pageformat - What the entries should look like.
* <LI>startDate - Date when to start. Format is "ddMMyy";
* </UL>
*
* The "days" and "startDate" can also be sent in HTTP parameters,
* and the names are "weblog.days" and "weblog.startDate", respectively.
*
* @since 1.9.21
*/
// FIXME: Add "entries" param as an alternative to "days".
// FIXME: Entries arrive in wrong order.
public class WeblogPlugin implements WikiPlugin
{
private static Category log = Category.getInstance(WeblogPlugin.class);
public static final int DEFAULT_DAYS = 7;
public static final String DEFAULT_PAGEFORMAT = "%p_blogentry_";
public static final String DEFAULT_DATEFORMAT = "ddMMyy";
public static final String PARAM_STARTDATE = "startDate";
public static final String PARAM_DAYS = "days";
public static final String PARAM_ALLOWCOMMENTS = "allowComments";
public static String makeEntryPage( String pageName,
String date,
String entryNum )
{
return TextUtil.replaceString(DEFAULT_PAGEFORMAT,"%p",pageName)+date+"_"+entryNum;
}
public static String makeEntryPage( String pageName )
{
return TextUtil.replaceString(DEFAULT_PAGEFORMAT,"%p",pageName);
}
public static String makeEntryPage( String pageName, String date )
{
return TextUtil.replaceString(DEFAULT_PAGEFORMAT,"%p",pageName)+date;
}
public String execute( WikiContext context, Map params )
throws PluginException
{
String weblogName = context.getPage().getName();
Calendar startTime;
Calendar stopTime;
int numDays;
WikiEngine engine = context.getEngine();
//
// Parse parameters.
//
String days;
String startDay = null;
boolean hasComments = false;
if( (days = context.getHttpParameter( "weblog."+PARAM_DAYS )) == null )
{
days = (String) params.get( PARAM_DAYS );
}
numDays = TextUtil.parseIntParameter( days, DEFAULT_DAYS );
if( (startDay = (String)params.get(PARAM_STARTDATE)) == null )
{
startDay = context.getHttpParameter( "weblog."+PARAM_STARTDATE );
}
if( TextUtil.isPositive( (String)params.get(PARAM_ALLOWCOMMENTS) ) )
{
hasComments = true;
}
//
// Determine the date range which to include.
//
startTime = Calendar.getInstance();
stopTime = Calendar.getInstance();
if( startDay != null )
{
SimpleDateFormat fmt = new SimpleDateFormat( DEFAULT_DATEFORMAT );
try
{
Date d = fmt.parse( startDay );
startTime.setTime( d );
stopTime.setTime( d );
}
catch( ParseException e )
{
return "Illegal time format: "+startDay;
}
}
//
// We make a wild guess here that nobody can do millisecond
// accuracy here.
//
startTime.add( Calendar.DAY_OF_MONTH, -numDays );
startTime.set( Calendar.HOUR, 0 );
startTime.set( Calendar.MINUTE, 0 );
startTime.set( Calendar.SECOND, 0 );
stopTime.set( Calendar.HOUR, 23 );
stopTime.set( Calendar.MINUTE, 59 );
stopTime.set( Calendar.SECOND, 59 );
StringBuffer sb = new StringBuffer();
try
{
List blogEntries = findBlogEntries( context.getEngine().getPageManager(),
weblogName,
startTime.getTime(),
stopTime.getTime() );
Collections.sort( blogEntries, new PageDateComparator() );
SimpleDateFormat entryDateFmt = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
sb.append("<DIV CLASS=\"weblog\">\n");
for( Iterator i = blogEntries.iterator(); i.hasNext(); )
{
WikiPage p = (WikiPage) i.next();
sb.append("<DIV CLASS=\"weblogheading\">");
Date entryDate = p.getLastModified();
sb.append( entryDateFmt.format(entryDate) );
sb.append("</DIV>\n");
sb.append("<DIV CLASS=\"weblogentry\">");
//
// Append the text of the latest version.
//
sb.append( engine.getHTML( context,
engine.getPage(p.getName()) ) );
sb.append("</DIV>\n");
sb.append("<div class=\"weblogpermalink\">");
sb.append( "<a href=\""+engine.getViewURL(p.getName())+"\">Permalink</a>" );
String commentPageName = TextUtil.replaceString( p.getName(),
"blogentry",
"comments" );
if( engine.pageExists( commentPageName ) )
{
sb.append( " " );
sb.append( "<a href=\""+engine.getViewURL(commentPageName)+"\">View Comments</a>" );
}
sb.append( " " );
sb.append( "<a href=\""+engine.getEditURL(commentPageName)+"&comment=true\">Comment this entry</a>" );
sb.append("</div>");
}
sb.append("</DIV>\n");
}
catch( ProviderException e )
{
log.error( "Could not locate blog entries", e );
throw new PluginException( "Could not locate blog entries: "+e.getMessage() );
}
return sb.toString();
}
/**
* Attempts to locate all pages that correspond to the
* blog entry pattern.
*
* Returns a list of pages with their FIRST revisions.
*/
public List findBlogEntries( PageManager mgr,
String baseName, Date start, Date end )
throws ProviderException
{
Collection everyone = mgr.getAllPages();
ArrayList result = new ArrayList();
baseName = makeEntryPage( baseName );
SimpleDateFormat fmt = new SimpleDateFormat(DEFAULT_DATEFORMAT);
for( Iterator i = everyone.iterator(); i.hasNext(); )
{
WikiPage p = (WikiPage)i.next();
String pageName = p.getName();
if( pageName.startsWith( baseName ) )
{
WikiPage firstVersion = mgr.getPageInfo( pageName, 1 );
Date pageDay = firstVersion.getLastModified();
if( pageDay != null )
{
if( pageDay.after(start) && pageDay.before(end) )
{
result.add( firstVersion );
}
}
}
}
return result;
}
/**
* Reverse comparison.
*/
private class PageDateComparator implements Comparator
{
public int compare( Object o1, Object o2 )
{
if( o1 == null || o2 == null )
{
return 0;
}
WikiPage page1 = (WikiPage)o1;
WikiPage page2 = (WikiPage)o2;
return page2.getLastModified().compareTo( page1.getLastModified() );
}
}
}
|
Forgot to check if comments were allowed...
git-svn-id: 6c0206e3b9edd104850923da33ebd73b435d374d@622647 13f79535-47bb-0310-9956-ffa450edef68
|
src/com/ecyrd/jspwiki/plugin/WeblogPlugin.java
|
Forgot to check if comments were allowed...
|
<ide><path>rc/com/ecyrd/jspwiki/plugin/WeblogPlugin.java
<ide> sb.append( "<a href=\""+engine.getViewURL(commentPageName)+"\">View Comments</a>" );
<ide> }
<ide>
<del> sb.append( " " );
<del> sb.append( "<a href=\""+engine.getEditURL(commentPageName)+"&comment=true\">Comment this entry</a>" );
<add> if( hasComments )
<add> {
<add> sb.append( " " );
<add> sb.append( "<a href=\""+engine.getEditURL(commentPageName)+"&comment=true\">Comment this entry</a>" );
<add> }
<ide>
<ide> sb.append("</div>");
<ide> }
|
|
Java
|
mpl-2.0
|
4990937ab419e2cb1184755a1a67b920e6a8a4a2
| 0 |
ShwethaThammaiah/muzima-android-1,sthaiya/muzima-android,vijayakumarn/muzima-android,ShwethaThammaiah/muzima-android-1,sthaiya/muzima-android,ShwethaThammaiah/muzima-android-1,ShwethaThammaiah/muzima-android-1,vijayakumarn/muzima-android,vijayakumarn/muzima-android,vijayakumarn/muzima-android,sthaiya/muzima-android
|
/*
* Copyright (c) 2014. The Trustees of Indiana University.
*
* This version of the code is licensed under the MPL 2.0 Open Source license with additional
* healthcare disclaimer. If the user is an entity intending to commercialize any application
* that uses this code in a for-profit venture, please contact the copyright holder.
*/
package com.muzima.view.preferences;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.util.Log;
import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.muzima.MuzimaApplication;
import com.muzima.R;
import com.muzima.search.api.util.StringUtil;
import com.muzima.tasks.ValidateURLTask;
import com.muzima.utils.NetworkUtils;
import com.muzima.view.login.LoginActivity;
import com.muzima.view.preferences.settings.ResetDataTask;
import com.muzima.view.preferences.settings.SyncFormDataTask;
public class SettingsActivity extends SherlockPreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private String serverPreferenceKey;
private String usernamePreferenceKey;
private String timeoutPreferenceKey;
private String passwordPreferenceKey;
private EditTextPreference serverPreference;
private EditTextPreference usernamePreference;
private EditTextPreference timeoutPreference;
private EditTextPreference passwordPreference;
private String newURL;
@Override
public void onUserInteraction() {
((MuzimaApplication) getApplication()).restartTimer();
super.onUserInteraction();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
serverPreferenceKey = getResources().getString(R.string.preference_server);
serverPreference = (EditTextPreference) getPreferenceScreen().findPreference(serverPreferenceKey);
serverPreference.setSummary(serverPreference.getText());
serverPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(final Preference preference, final Object newValue) {
newURL = newValue.toString();
if (!serverPreference.getText().equalsIgnoreCase(newURL)) {
AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
builder
.setCancelable(true)
.setIcon(getResources().getDrawable(R.drawable.ic_warning))
.setTitle(getResources().getString(R.string.caution))
.setMessage(getResources().getString(R.string.switch_server_message))
.setPositiveButton("Yes", positiveClickListener())
.setNegativeButton("No", null).create().show();
}
return false;
}
});
usernamePreferenceKey = getResources().getString(R.string.preference_username);
usernamePreference = (EditTextPreference) getPreferenceScreen().findPreference(usernamePreferenceKey);
usernamePreference.setSummary(usernamePreference.getText());
usernamePreference.setEnabled(false);
usernamePreference.setSelectable(false);
timeoutPreferenceKey = getResources().getString(R.string.preference_timeout);
timeoutPreference = (EditTextPreference) getPreferenceScreen().findPreference(timeoutPreferenceKey);
timeoutPreference.setSummary(timeoutPreference.getText());
timeoutPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
Integer timeOutInMin = Integer.valueOf(o.toString());
((MuzimaApplication) getApplication()).resetTimer(timeOutInMin);
return true;
}
});
passwordPreferenceKey = getResources().getString(R.string.preference_password);
passwordPreference = (EditTextPreference) getPreferenceScreen().findPreference(passwordPreferenceKey);
if (passwordPreference.getText() != null) {
passwordPreference.setSummary(passwordPreference.getText().replaceAll(".", "*"));
}
passwordPreference.setEnabled(false);
passwordPreference.setSelectable(false);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Called when a shared preference is changed, added, or removed. This
* may be called even if a preference is set to its existing value.
* <p/>
* <p>This callback will be run on your main thread.
*
* @param sharedPreferences The {@link android.content.SharedPreferences} that received
* the change.
* @param key The key of the preference that was changed, added, or
* removed.
*/
@Override
public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key) {
if (key.equalsIgnoreCase("wizardFinished")) {
return;
}
String value = sharedPreferences.getString(key, StringUtil.EMPTY);
if (StringUtil.equals(key, serverPreferenceKey)) {
serverPreference.setSummary(value);
} else if (StringUtil.equals(key, usernamePreferenceKey)) {
usernamePreference.setSummary(value);
} else if (StringUtil.equals(key, passwordPreferenceKey)) {
passwordPreference.setSummary(value.replaceAll(".", "*"));
} else if (StringUtil.equals(key, timeoutPreferenceKey)) {
Log.e("Tag","Inside shared pref");
timeoutPreference.setSummary(value);
}
}
public void validationURLResult(boolean result) {
if (result) {
new SyncFormDataTask(this).execute();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setCancelable(true)
.setIcon(getResources().getDrawable(R.drawable.ic_warning))
.setTitle("Invalid")
.setMessage("The URL you have provided is invalid")
.setPositiveButton("Ok", null);
builder.create().show();
}
}
public void syncedFormData(boolean result) {
if (result) {
new ResetDataTask(this, newURL).execute();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setCancelable(true)
.setIcon(getResources().getDrawable(R.drawable.ic_warning))
.setTitle("Failure")
.setMessage("Failed to Sync Form data to the current server. Do you still want to continue?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new ResetDataTask(SettingsActivity.this, newURL).execute();
}
})
.setNegativeButton("No", null);
builder.create().show();
}
}
private Dialog.OnClickListener positiveClickListener() {
return new Dialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
changeServerURL(dialog);
}
};
}
private void changeServerURL(DialogInterface dialog) {
dialog.dismiss();
if (NetworkUtils.isConnectedToNetwork(this)) {
new ValidateURLTask(this).execute(newURL);
}
}
/**
* Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
* {@link #onPause}, for your activity to start interacting with the user.
* This is a good place to begin animations, open exclusive-access devices
* (such as the camera), etc.
* <p/>
* <p>Keep in mind that onResume is not the best indicator that your activity
* is visible to the user; a system window such as the keyguard may be in
* front. Use {@link #onWindowFocusChanged} to know for certain that your
* activity is visible to the user (for example, to resume a game).
* <p/>
* <p><em>Derived classes must call through to the super class's
* implementation of this method. If they do not, an exception will be
* thrown.</em></p>
*
* @see #onRestoreInstanceState
* @see #onRestart
* @see #onPostResume
* @see #onPause
*/
@Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
/**
* Set up the {@link android.app.ActionBar}.
*/
private void setupActionBar() {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportMenuInflater().inflate(R.menu.settings, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public void launchLoginActivity(boolean isFirstLaunch) {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(LoginActivity.isFirstLaunch, isFirstLaunch);
startActivity(intent);
finish();
}
}
|
src/main/java/com/muzima/view/preferences/SettingsActivity.java
|
/*
* Copyright (c) 2014. The Trustees of Indiana University.
*
* This version of the code is licensed under the MPL 2.0 Open Source license with additional
* healthcare disclaimer. If the user is an entity intending to commercialize any application
* that uses this code in a for-profit venture, please contact the copyright holder.
*/
package com.muzima.view.preferences;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.util.Log;
import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.muzima.MuzimaApplication;
import com.muzima.R;
import com.muzima.search.api.util.StringUtil;
import com.muzima.tasks.ValidateURLTask;
import com.muzima.utils.NetworkUtils;
import com.muzima.view.login.LoginActivity;
import com.muzima.view.preferences.settings.ResetDataTask;
import com.muzima.view.preferences.settings.SyncFormDataTask;
public class SettingsActivity extends SherlockPreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private String serverPreferenceKey;
private String usernamePreferenceKey;
private String timeoutPreferenceKey;
private String passwordPreferenceKey;
private EditTextPreference serverPreference;
private EditTextPreference usernamePreference;
private EditTextPreference timeoutPreference;
private EditTextPreference passwordPreference;
private String newURL;
@Override
public void onUserInteraction() {
((MuzimaApplication) getApplication()).restartTimer();
super.onUserInteraction();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
serverPreferenceKey = getResources().getString(R.string.preference_server);
serverPreference = (EditTextPreference) getPreferenceScreen().findPreference(serverPreferenceKey);
serverPreference.setSummary(serverPreference.getText());
serverPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(final Preference preference, final Object newValue) {
newURL = newValue.toString();
if (!serverPreference.getText().equalsIgnoreCase(newURL)) {
AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
builder
.setCancelable(true)
.setIcon(getResources().getDrawable(R.drawable.ic_warning))
.setTitle(getResources().getString(R.string.caution))
.setMessage(getResources().getString(R.string.switch_server_message))
.setPositiveButton("Yes", positiveClickListener())
.setNegativeButton("No", null).create().show();
}
return false;
}
});
usernamePreferenceKey = getResources().getString(R.string.preference_username);
usernamePreference = (EditTextPreference) getPreferenceScreen().findPreference(usernamePreferenceKey);
usernamePreference.setSummary(usernamePreference.getText());
timeoutPreferenceKey = getResources().getString(R.string.preference_timeout);
timeoutPreference = (EditTextPreference) getPreferenceScreen().findPreference(timeoutPreferenceKey);
timeoutPreference.setSummary(timeoutPreference.getText());
timeoutPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
Integer timeOutInMin = Integer.valueOf(o.toString());
((MuzimaApplication) getApplication()).resetTimer(timeOutInMin);
return true;
}
});
passwordPreferenceKey = getResources().getString(R.string.preference_password);
passwordPreference = (EditTextPreference) getPreferenceScreen().findPreference(passwordPreferenceKey);
if (passwordPreference.getText() != null) {
passwordPreference.setSummary(passwordPreference.getText().replaceAll(".", "*"));
}
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Called when a shared preference is changed, added, or removed. This
* may be called even if a preference is set to its existing value.
* <p/>
* <p>This callback will be run on your main thread.
*
* @param sharedPreferences The {@link android.content.SharedPreferences} that received
* the change.
* @param key The key of the preference that was changed, added, or
* removed.
*/
@Override
public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key) {
if (key.equalsIgnoreCase("wizardFinished")) {
return;
}
String value = sharedPreferences.getString(key, StringUtil.EMPTY);
if (StringUtil.equals(key, serverPreferenceKey)) {
serverPreference.setSummary(value);
} else if (StringUtil.equals(key, usernamePreferenceKey)) {
usernamePreference.setSummary(value);
} else if (StringUtil.equals(key, passwordPreferenceKey)) {
passwordPreference.setSummary(value.replaceAll(".", "*"));
} else if (StringUtil.equals(key, timeoutPreferenceKey)) {
Log.e("Tag","Inside shared pref");
timeoutPreference.setSummary(value);
}
}
public void validationURLResult(boolean result) {
if (result) {
new SyncFormDataTask(this).execute();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setCancelable(true)
.setIcon(getResources().getDrawable(R.drawable.ic_warning))
.setTitle("Invalid")
.setMessage("The URL you have provided is invalid")
.setPositiveButton("Ok", null);
builder.create().show();
}
}
public void syncedFormData(boolean result) {
if (result) {
new ResetDataTask(this, newURL).execute();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setCancelable(true)
.setIcon(getResources().getDrawable(R.drawable.ic_warning))
.setTitle("Failure")
.setMessage("Failed to Sync Form data to the current server. Do you still want to continue?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new ResetDataTask(SettingsActivity.this, newURL).execute();
}
})
.setNegativeButton("No", null);
builder.create().show();
}
}
private Dialog.OnClickListener positiveClickListener() {
return new Dialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
changeServerURL(dialog);
}
};
}
private void changeServerURL(DialogInterface dialog) {
dialog.dismiss();
if (NetworkUtils.isConnectedToNetwork(this)) {
new ValidateURLTask(this).execute(newURL);
}
}
/**
* Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
* {@link #onPause}, for your activity to start interacting with the user.
* This is a good place to begin animations, open exclusive-access devices
* (such as the camera), etc.
* <p/>
* <p>Keep in mind that onResume is not the best indicator that your activity
* is visible to the user; a system window such as the keyguard may be in
* front. Use {@link #onWindowFocusChanged} to know for certain that your
* activity is visible to the user (for example, to resume a game).
* <p/>
* <p><em>Derived classes must call through to the super class's
* implementation of this method. If they do not, an exception will be
* thrown.</em></p>
*
* @see #onRestoreInstanceState
* @see #onRestart
* @see #onPostResume
* @see #onPause
*/
@Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
/**
* Set up the {@link android.app.ActionBar}.
*/
private void setupActionBar() {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportMenuInflater().inflate(R.menu.settings, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public void launchLoginActivity(boolean isFirstLaunch) {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(LoginActivity.isFirstLaunch, isFirstLaunch);
startActivity(intent);
finish();
}
}
|
Muzima-107 Disabled edit feature for username and password in Settings menu
|
src/main/java/com/muzima/view/preferences/SettingsActivity.java
|
Muzima-107 Disabled edit feature for username and password in Settings menu
|
<ide><path>rc/main/java/com/muzima/view/preferences/SettingsActivity.java
<ide> usernamePreferenceKey = getResources().getString(R.string.preference_username);
<ide> usernamePreference = (EditTextPreference) getPreferenceScreen().findPreference(usernamePreferenceKey);
<ide> usernamePreference.setSummary(usernamePreference.getText());
<add> usernamePreference.setEnabled(false);
<add> usernamePreference.setSelectable(false);
<ide>
<ide> timeoutPreferenceKey = getResources().getString(R.string.preference_timeout);
<ide> timeoutPreference = (EditTextPreference) getPreferenceScreen().findPreference(timeoutPreferenceKey);
<ide> if (passwordPreference.getText() != null) {
<ide> passwordPreference.setSummary(passwordPreference.getText().replaceAll(".", "*"));
<ide> }
<add> passwordPreference.setEnabled(false);
<add> passwordPreference.setSelectable(false);
<ide>
<ide> // Show the Up button in the action bar.
<ide> setupActionBar();
|
|
Java
|
bsd-2-clause
|
3df6c58db38078f95abd41488c3459337cc3f18c
| 0 |
monikadrajer/CCDA-Score-CARD,siteadmin/CCDA-Score-CARD,siteadmin/CCDA-Score-CARD,monikadrajer/CCDA-Score-CARD,monikadrajer/CCDA-Score-CARD,siteadmin/CCDA-Score-CARD
|
package org.sitenv.service.ccda.smartscorecard.model;
import java.util.ArrayList;
import java.util.List;
public class Category {
public Category(boolean isFailingConformance, String categoryName)
{
this.isFailingConformance = isFailingConformance;
this.categoryName = categoryName;
this.categoryRubrics = new ArrayList<CCDAScoreCardRubrics>();
}
public Category()
{
}
// scorecard properties
private String categoryName;
private String categoryGrade;
private int categoryNumericalScore;
private List<CCDAScoreCardRubrics> categoryRubrics;
private int numberOfIssues;
// referenceccdavalidator properties
private boolean isFailingConformance;
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryGrade() {
return categoryGrade;
}
public void setCategoryGrade(String categoryGrade) {
this.categoryGrade = categoryGrade;
}
public List<CCDAScoreCardRubrics> getCategoryRubrics() {
return categoryRubrics;
}
public void setCategoryRubrics(List<CCDAScoreCardRubrics> categoryRubrics) {
this.categoryRubrics = categoryRubrics;
}
public int getNumberOfIssues() {
return numberOfIssues;
}
public void setNumberOfIssues(int numberOfIssues) {
this.numberOfIssues = numberOfIssues;
}
public int getCategoryNumericalScore() {
return categoryNumericalScore;
}
public void setCategoryNumericalScore(int categoryNumericalScore) {
this.categoryNumericalScore = categoryNumericalScore;
}
public boolean isFailingConformance() {
return isFailingConformance;
}
public void setFailingConformance(boolean isFailingConformance) {
this.isFailingConformance = isFailingConformance;
}
}
|
src/main/java/org/sitenv/service/ccda/smartscorecard/model/Category.java
|
package org.sitenv.service.ccda.smartscorecard.model;
import java.util.List;
public class Category {
public Category(boolean isFailingConformance,String categoryName)
{
this.isFailingConformance = isFailingConformance;
this.categoryName = categoryName;
}
public Category()
{
}
// scorecard properties
private String categoryName;
private String categoryGrade;
private int categoryNumericalScore;
private List<CCDAScoreCardRubrics> categoryRubrics;
private int numberOfIssues;
// referenceccdavalidator properties
private boolean isFailingConformance;
// e.g. description, xPath, Line Number, etc.
// TODO: this is convenient here but we don't NEED it but it makes for less front-end processing
// Options:
// 1. We populate this (referenceErrors)
// 2. We override categoryRubrics with the related reference results
// 3. We do not populate this, and delete it from the class. Instead, we have the front end
// loop the results in the current ReferenceResult instance and match the section name to populate
private List<ReferenceError> referenceErrors;
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryGrade() {
return categoryGrade;
}
public void setCategoryGrade(String categoryGrade) {
this.categoryGrade = categoryGrade;
}
public List<CCDAScoreCardRubrics> getCategoryRubrics() {
return categoryRubrics;
}
public void setCategoryRubrics(List<CCDAScoreCardRubrics> categoryRubrics) {
this.categoryRubrics = categoryRubrics;
}
public int getNumberOfIssues() {
return numberOfIssues;
}
public void setNumberOfIssues(int numberOfIssues) {
this.numberOfIssues = numberOfIssues;
}
public int getCategoryNumericalScore() {
return categoryNumericalScore;
}
public void setCategoryNumericalScore(int categoryNumericalScore) {
this.categoryNumericalScore = categoryNumericalScore;
}
public boolean isFailingConformance() {
return isFailingConformance;
}
public void setFailingConformance(boolean isFailingConformance) {
this.isFailingConformance = isFailingConformance;
}
public List<ReferenceError> getReferenceErrors() {
return referenceErrors;
}
public void setReferenceErrors(List<ReferenceError> referenceErrors) {
this.referenceErrors = referenceErrors;
}
}
|
Set categoryRubrics to empty array for failing sections to match format
|
src/main/java/org/sitenv/service/ccda/smartscorecard/model/Category.java
|
Set categoryRubrics to empty array for failing sections to match format
|
<ide><path>rc/main/java/org/sitenv/service/ccda/smartscorecard/model/Category.java
<ide> package org.sitenv.service.ccda.smartscorecard.model;
<ide>
<add>import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<ide> public class Category {
<ide>
<ide>
<del> public Category(boolean isFailingConformance,String categoryName)
<add> public Category(boolean isFailingConformance, String categoryName)
<ide> {
<ide> this.isFailingConformance = isFailingConformance;
<ide> this.categoryName = categoryName;
<add> this.categoryRubrics = new ArrayList<CCDAScoreCardRubrics>();
<ide> }
<ide>
<ide> public Category()
<ide>
<ide> // referenceccdavalidator properties
<ide> private boolean isFailingConformance;
<del> // e.g. description, xPath, Line Number, etc.
<del> // TODO: this is convenient here but we don't NEED it but it makes for less front-end processing
<del> // Options:
<del> // 1. We populate this (referenceErrors)
<del> // 2. We override categoryRubrics with the related reference results
<del> // 3. We do not populate this, and delete it from the class. Instead, we have the front end
<del> // loop the results in the current ReferenceResult instance and match the section name to populate
<del> private List<ReferenceError> referenceErrors;
<ide>
<ide> public String getCategoryName() {
<ide> return categoryName;
<ide> }
<ide> public void setFailingConformance(boolean isFailingConformance) {
<ide> this.isFailingConformance = isFailingConformance;
<del> }
<del> public List<ReferenceError> getReferenceErrors() {
<del> return referenceErrors;
<del> }
<del> public void setReferenceErrors(List<ReferenceError> referenceErrors) {
<del> this.referenceErrors = referenceErrors;
<ide> }
<ide>
<ide> }
|
|
Java
|
bsd-3-clause
|
9b8b9d0e1520d3d0e8d28ffc6e72ad4ec5045dcd
| 0 |
bdezonia/zorbage,bdezonia/zorbage
|
/*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (C) 2016-2019 Barry DeZonia
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package nom.bdezonia.zorbage.type.data.float64.real;
import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.algorithm.Round.Mode;
import nom.bdezonia.zorbage.algorithm.SequenceIsInf;
import nom.bdezonia.zorbage.algorithm.SequenceIsNan;
import nom.bdezonia.zorbage.algorithm.SequenceIsZero;
import nom.bdezonia.zorbage.function.Function1;
import nom.bdezonia.zorbage.function.Function2;
import nom.bdezonia.zorbage.procedure.Procedure1;
import nom.bdezonia.zorbage.procedure.Procedure2;
import nom.bdezonia.zorbage.procedure.Procedure3;
import nom.bdezonia.zorbage.procedure.Procedure4;
import nom.bdezonia.zorbage.sampling.IntegerIndex;
import nom.bdezonia.zorbage.type.algebra.Infinite;
import nom.bdezonia.zorbage.type.algebra.NaN;
import nom.bdezonia.zorbage.type.algebra.Norm;
import nom.bdezonia.zorbage.type.algebra.Rounding;
import nom.bdezonia.zorbage.type.algebra.Scale;
//note that many implementations of tensors on the internet treat them as generalized matrices.
//they do not worry about upper and lower indices or even matching shapes. They do element by
//element ops like sin() of each elem.
//do I skip Vector and Matrix and even Scalar?
//TODO: make one tensor/member pair for each of float64, complex64, quat64, oct64
//TODO: determine if this is a field or something else or two things for float/complex vs. quat/oct
// this implies it is an OrderedField. Do tensors have an ordering? abs() exists in TensorFlow.
//@Override
//public void abs(TensorMember a, TensorMember b) {}
// tensorflow also has trigonometric and hyperbolic
//public void contract(int i, int j, TensorMember a, TensorMember b, TensorMember c) {}
//public void takeDiagonal(TensorMember a, Object b) {} // change Object to Vector
//many more
import nom.bdezonia.zorbage.type.algebra.TensorProduct;
import nom.bdezonia.zorbage.type.ctor.ConstructibleNdLong;
import nom.bdezonia.zorbage.type.ctor.StorageConstruction;
// Note that for now the implementation is only for Cartesian tensors
/**
*
* @author Barry DeZonia
*
*/
public class Float64TensorProduct
implements
TensorProduct<Float64TensorProduct,Float64TensorProductMember,Float64Algebra,Float64Member>,
ConstructibleNdLong<Float64TensorProductMember>,
Norm<Float64TensorProductMember,Float64Member>,
Scale<Float64TensorProductMember,Float64Member>,
Rounding<Float64Member,Float64TensorProductMember>,
Infinite<Float64TensorProductMember>,
NaN<Float64TensorProductMember>
{
@Override
public Float64TensorProductMember construct() {
return new Float64TensorProductMember();
}
@Override
public Float64TensorProductMember construct(Float64TensorProductMember other) {
return new Float64TensorProductMember(other);
}
@Override
public Float64TensorProductMember construct(String s) {
return new Float64TensorProductMember(s);
}
@Override
public Float64TensorProductMember construct(StorageConstruction s, long[] nd) {
return new Float64TensorProductMember(s, nd);
}
private final Function2<Boolean,Float64TensorProductMember,Float64TensorProductMember> EQ =
new Function2<Boolean,Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public Boolean call(Float64TensorProductMember a, Float64TensorProductMember b) {
if (!shapesMatch(a,b))
return false;
Float64Member aTmp = new Float64Member();
Float64Member bTmp = new Float64Member();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, aTmp);
b.v(i, bTmp);
if (G.DBL.isNotEqual().call(aTmp, bTmp))
return false;
}
return true;
}
};
@Override
public Function2<Boolean,Float64TensorProductMember,Float64TensorProductMember> isEqual() {
return EQ;
}
private final Function2<Boolean,Float64TensorProductMember,Float64TensorProductMember> NEQ =
new Function2<Boolean,Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public Boolean call(Float64TensorProductMember a, Float64TensorProductMember b) {
return !isEqual().call(a,b);
}
};
@Override
public Function2<Boolean,Float64TensorProductMember,Float64TensorProductMember> isNotEqual() {
return NEQ;
}
private final Procedure2<Float64TensorProductMember,Float64TensorProductMember> ASSIGN =
new Procedure2<Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember from, Float64TensorProductMember to) {
if (to == from) return;
Float64Member tmp = new Float64Member();
long[] dims = new long[from.numDimensions()];
for (int i = 0; i < dims.length; i++) {
dims[i] = from.dimension(i);
}
to.alloc(dims);
long numElems = from.numElems();
for (long i = 0; i < numElems; i++) {
from.v(i, tmp);
to.setV(i, tmp);
}
}
};
@Override
public Procedure2<Float64TensorProductMember,Float64TensorProductMember> assign() {
return ASSIGN;
}
private final Procedure1<Float64TensorProductMember> ZER =
new Procedure1<Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a) {
Float64Member tmp = new Float64Member();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.setV(i, tmp);
}
}
};
@Override
public Procedure1<Float64TensorProductMember> zero() {
return ZER;
}
private final Procedure2<Float64TensorProductMember,Float64TensorProductMember> NEG =
new Procedure2<Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a, Float64TensorProductMember b) {
Float64Member tmp = new Float64Member();
shapeResult(a, b);
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, tmp);
G.DBL.negate().call(tmp, tmp);
b.setV(i, tmp);
}
}
};
@Override
public Procedure2<Float64TensorProductMember,Float64TensorProductMember> negate() {
return NEG;
}
private final Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> ADD =
new Procedure3<Float64TensorProductMember, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) {
if (!shapesMatch(a,b))
throw new IllegalArgumentException("tensor add shape mismatch");
long[] newDims = new long[a.numDimensions()];
for (int i = 0; i < newDims.length; i++) {
newDims[i] = a.dimension(i);
}
c.alloc(newDims);
Float64Member aTmp = new Float64Member();
Float64Member bTmp = new Float64Member();
Float64Member cTmp = new Float64Member();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, aTmp);
b.v(i, bTmp);
G.DBL.add().call(aTmp, bTmp, cTmp);
c.setV(i, cTmp);
}
}
};
@Override
public Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> add() {
return ADD;
}
private final Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> SUB =
new Procedure3<Float64TensorProductMember, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) {
if (!shapesMatch(a,b))
throw new IllegalArgumentException("tensor subtract shape mismatch");
long[] newDims = new long[a.numDimensions()];
for (int i = 0; i < newDims.length; i++) {
newDims[i] = a.dimension(i);
}
c.alloc(newDims);
Float64Member aTmp = new Float64Member();
Float64Member bTmp = new Float64Member();
Float64Member cTmp = new Float64Member();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, aTmp);
b.v(i, bTmp);
G.DBL.subtract().call(aTmp, bTmp, cTmp);
c.setV(i, cTmp);
}
}
};
@Override
public Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> subtract() {
return SUB;
}
private final Procedure2<Float64TensorProductMember,Float64Member> NORM =
new Procedure2<Float64TensorProductMember, Float64Member>()
{
@Override
public void call(Float64TensorProductMember a, Float64Member b) {
// TODO: to port to complex, quat, oct do I need to multiply() not by self but by the
// conjugate of self. We need to transform a comp, quat, oct into a real.
Float64Member max = new Float64Member();
Float64Member value = new Float64Member();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, value);
G.DBL.norm().call(value, value);
if (G.DBL.isGreater().call(value, max))
G.DBL.assign().call(value, max);
}
Float64Member sum = new Float64Member();
for (long i = 0; i < numElems; i++) {
a.v(i, value);
G.DBL.divide().call(value, max, value);
G.DBL.multiply().call(value, value, value); // See TODO above
G.DBL.add().call(sum, value, sum);
}
G.DBL.sqrt().call(sum, sum);
G.DBL.multiply().call(max, sum, sum);
G.DBL.assign().call(sum, b);
}
};
@Override
public Procedure2<Float64TensorProductMember,Float64Member> norm() {
return NORM;
}
@Override
public Procedure2<Float64TensorProductMember,Float64TensorProductMember> conjugate() {
return ASSIGN;
}
private final Procedure3<Float64Member,Float64TensorProductMember,Float64TensorProductMember> SCALE =
new Procedure3<Float64Member, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64Member scalar, Float64TensorProductMember a, Float64TensorProductMember b) {
Float64Member tmp = new Float64Member();
shapeResult(a, b);
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, tmp);
G.DBL.multiply().call(scalar, tmp, tmp);
b.setV(i, tmp);
}
}
};
@Override
public Procedure3<Float64Member,Float64TensorProductMember,Float64TensorProductMember> scale() {
return SCALE;
}
private final Procedure3<Float64Member,Float64TensorProductMember,Float64TensorProductMember> ADDEL =
new Procedure3<Float64Member, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64Member scalar, Float64TensorProductMember a, Float64TensorProductMember b) {
Float64Member tmp = new Float64Member();
shapeResult(a, b);
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, tmp);
G.DBL.add().call(scalar, tmp, tmp);
b.setV(i, tmp);
}
}
};
@Override
public Procedure3<Float64Member,Float64TensorProductMember,Float64TensorProductMember> addToElements() {
return ADDEL;
}
private Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> MULEL =
new Procedure3<Float64TensorProductMember, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) {
if (!shapesMatch(a,b))
throw new IllegalArgumentException("mismatched shapes");
long[] newDims = new long[a.numDimensions()];
for (int i = 0; i < newDims.length; i++) {
newDims[i] = a.dimension(i);
}
c.alloc(newDims);
Float64Member aTmp = new Float64Member();
Float64Member bTmp = new Float64Member();
Float64Member cTmp = new Float64Member();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, aTmp);
b.v(i, bTmp);
G.DBL.multiply().call(aTmp, bTmp, cTmp);
c.setV(i, cTmp);
}
}
};
@Override
public Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> multiplyElements() {
return MULEL;
}
private Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> DIVIDEEL =
new Procedure3<Float64TensorProductMember, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) {
if (!shapesMatch(a,b))
throw new IllegalArgumentException("mismatched shapes");
long[] newDims = new long[a.numDimensions()];
for (int i = 0; i < newDims.length; i++) {
newDims[i] = a.dimension(i);
}
c.alloc(newDims);
Float64Member aTmp = new Float64Member();
Float64Member bTmp = new Float64Member();
Float64Member cTmp = new Float64Member();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, aTmp);
b.v(i, bTmp);
G.DBL.divide().call(aTmp, bTmp, cTmp);
c.setV(i, cTmp);
}
}
};
@Override
public Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> divideElements() {
return DIVIDEEL;
}
// TODO citation needed. I wrote this long ago and no longer can tell if it makes sense.
private final Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> MUL =
new Procedure3<Float64TensorProductMember, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) {
if (c == a || c == b)
throw new IllegalArgumentException("destination tensor cannot be one of the inputs");
long dimA = a.dimension(0);
long dimB = b.dimension(0);
if (dimA != dimB)
throw new IllegalArgumentException("dimension of tensors must match");
int rankA = a.numDimensions();
int rankB = b.numDimensions();
int rankC = rankA + rankB;
long[] cDims = new long[rankC];
for (int i = 0; i < cDims.length; i++) {
cDims[i] = dimA;
}
c.alloc(cDims);
Float64Member aTmp = new Float64Member();
Float64Member bTmp = new Float64Member();
Float64Member cTmp = new Float64Member();
long k = 0;
long numElemsA = a.numElems();
long numElemsB = b.numElems();
for (long i = 0; i < numElemsA; i++) {
a.v(i, aTmp);
for (long j = 0; j < numElemsB; j++) {
b.v(j, bTmp);
G.DBL.multiply().call(aTmp, bTmp, cTmp);
c.setV(k, cTmp);
k++;
}
}
}
};
@Override
public Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> multiply() {
return MUL;
}
// https://en.wikipedia.org/wiki/Tensor_contraction
// TODO
private final Procedure4<java.lang.Integer,java.lang.Integer,Float64TensorProductMember,Float64TensorProductMember> CONTRACT =
new Procedure4<Integer, Integer, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Integer i, Integer j, Float64TensorProductMember a, Float64TensorProductMember b) {
if (a.rank() < 2)
throw new IllegalArgumentException("input tensor must be rank 2 or greater to contract");
if (i < 0 || j < 0 || i >= a.rank() || j >= a.rank())
throw new IllegalArgumentException("bad contraction indices given");
if (i == j)
throw new IllegalArgumentException("cannot contract along a single axis");
if (a == b)
throw new IllegalArgumentException("destination tensor cannot be one of the inputs");
int rank = a.rank() - 2;
long[] newDims = new long[rank];
for (int k = 0; k < newDims.length; k++) {
newDims[k] = a.dimension(0);
}
b.alloc(newDims);
throw new IllegalArgumentException("TODO");
}
};
@Override
public Procedure4<java.lang.Integer,java.lang.Integer,Float64TensorProductMember,Float64TensorProductMember> contract() {
return CONTRACT;
}
// http://mathworld.wolfram.com/CovariantDerivative.html
// TODO
private final Procedure1<java.lang.Integer> SEMI =
new Procedure1<Integer>()
{
@Override
public void call(Integer a) {
throw new IllegalArgumentException("TODO");
}
};
@Override
public Procedure1<java.lang.Integer> semicolonDerivative() {
return SEMI;
}
// http://mathworld.wolfram.com/CommaDerivative.html
// TODO
private final Procedure1<java.lang.Integer> COMMA =
new Procedure1<Integer>()
{
@Override
public void call(Integer a) {
throw new IllegalArgumentException("TODO");
}
};
@Override
public Procedure1<java.lang.Integer> commaDerivative() {
return COMMA;
}
private boolean shapesMatch(Float64TensorProductMember a, Float64TensorProductMember b) {
if (a.numDimensions() != b.numDimensions())
return false;
for (int i = 0; i < a.numDimensions(); i++) {
if (a.dimension(i) != b.dimension(i))
return false;
}
return true;
}
/* future version
private boolean shapesMatch(Float64TensorProductMember a, Float64TensorProductMember b) {
int i = 0;
int j = 0;
while (i < a.numDimensions() && j < b.numDimensions()) {
while (i < a.numDimensions() && a.dimension(i) == 1) i++;
while (j < b.numDimensions() && b.dimension(i) == 1) j++;
if (i < a.numDimensions() && j < b.numDimensions() && a.dimension(i) != b.dimension(j))
return false;
else {
i++;
j++;
}
}
while (i < a.numDimensions() && a.dimension(i) == 1) i++;
while (j < b.numDimensions() && b.dimension(i) == 1) j++;
if (i != a.numDimensions() || j != b.numDimensions())
return false;
return true;
}
*/
// TODO - make much more efficient by copying style of MatrixMultiply algorithm
private final Procedure3<java.lang.Integer,Float64TensorProductMember,Float64TensorProductMember> POWER =
new Procedure3<Integer, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Integer power, Float64TensorProductMember a, Float64TensorProductMember b) {
if (power < 0) {
// TODO: is this a valid limitation?
throw new IllegalArgumentException("negative powers not supported");
}
else if (power == 0) {
if (isZero().call(a)) {
throw new IllegalArgumentException("0^0 is not a number");
}
shapeResult(a, b); // set the shape of result
unity().call(b); // and make it have value 1
}
else if (power == 1) {
assign().call(a, b);
}
else {
Float64TensorProductMember tmp1 = new Float64TensorProductMember();
Float64TensorProductMember tmp2 = new Float64TensorProductMember();
multiply().call(a,a,tmp1);
for (int i = 2; i < (power/2)*2; i += 2) {
multiply().call(tmp1, a, tmp2);
multiply().call(tmp2, a, tmp1);
}
// an odd power
if (power > 2 && (power&1)==1) {
assign().call(tmp1, tmp2);
multiply().call(tmp2, a, tmp1);
}
assign().call(tmp1, b);
}
}
};
@Override
public Procedure3<java.lang.Integer,Float64TensorProductMember,Float64TensorProductMember> power() {
return POWER;
}
private final Procedure1<Float64TensorProductMember> UNITY =
new Procedure1<Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember result) {
Float64Member one = new Float64Member();
G.DBL.unity().call(one);
zero().call(result);
IntegerIndex index = new IntegerIndex(result.rank());
for (long d = 0; d < result.dimension(0); d++) {
for (int r = 0; r < result.rank(); r++) {
index.set(r, d);
}
result.setV(index, one);
}
}
};
@Override
public Procedure1<Float64TensorProductMember> unity() {
return UNITY;
}
private final Function1<Boolean, Float64TensorProductMember> ISNAN =
new Function1<Boolean, Float64TensorProductMember>()
{
@Override
public Boolean call(Float64TensorProductMember a) {
return SequenceIsNan.compute(G.DBL, a.rawData());
}
};
@Override
public Function1<Boolean, Float64TensorProductMember> isNaN() {
return ISNAN;
}
private final Procedure1<Float64TensorProductMember> NAN =
new Procedure1<Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a) {
Float64Member value = G.DBL.construct();
G.DBL.nan().call(value);
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.setV(i, value);
}
}
};
@Override
public Procedure1<Float64TensorProductMember> nan() {
return NAN;
}
private final Function1<Boolean, Float64TensorProductMember> ISINF =
new Function1<Boolean, Float64TensorProductMember>()
{
@Override
public Boolean call(Float64TensorProductMember a) {
return SequenceIsInf.compute(G.DBL, a.rawData());
}
};
@Override
public Function1<Boolean, Float64TensorProductMember> isInfinite() {
return ISINF;
}
private final Procedure1<Float64TensorProductMember> INF =
new Procedure1<Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a) {
Float64Member value = G.DBL.construct();
G.DBL.infinite().call(value);
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.setV(i, value);
}
}
};
@Override
public Procedure1<Float64TensorProductMember> infinite() {
return INF;
}
private final Procedure4<Mode, Float64Member, Float64TensorProductMember, Float64TensorProductMember> ROUND =
new Procedure4<Mode, Float64Member, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Mode mode, Float64Member delta, Float64TensorProductMember a, Float64TensorProductMember b) {
if (a != b) {
long[] newDims = new long[a.numDimensions()];
for (int i = 0; i < newDims.length; i++) {
newDims[i] = a.dimension(i);
}
b.alloc(newDims);
}
Float64Member tmp = G.DBL.construct();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, tmp);
G.DBL.round().call(mode, delta, tmp, tmp);
b.setV(i, tmp);
}
}
};
@Override
public Procedure4<Mode, Float64Member, Float64TensorProductMember, Float64TensorProductMember> round() {
return ROUND;
}
private final Function1<Boolean, Float64TensorProductMember> ISZERO =
new Function1<Boolean, Float64TensorProductMember>()
{
@Override
public Boolean call(Float64TensorProductMember a) {
return SequenceIsZero.compute(G.DBL, a.rawData());
}
};
@Override
public Function1<Boolean, Float64TensorProductMember> isZero() {
return ISZERO;
}
private void shapeResult(Float64TensorProductMember from, Float64TensorProductMember to) {
if (from == to) return;
long[] dims = new long[from.numDimensions()];
for (int i = 0; i < dims.length; i++) {
dims[i] = from.dimension(i);
}
to.alloc(dims);
}
}
|
src/main/java/nom/bdezonia/zorbage/type/data/float64/real/Float64TensorProduct.java
|
/*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (C) 2016-2019 Barry DeZonia
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package nom.bdezonia.zorbage.type.data.float64.real;
import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.algorithm.Round.Mode;
import nom.bdezonia.zorbage.algorithm.SequenceIsInf;
import nom.bdezonia.zorbage.algorithm.SequenceIsNan;
import nom.bdezonia.zorbage.function.Function1;
import nom.bdezonia.zorbage.function.Function2;
import nom.bdezonia.zorbage.procedure.Procedure1;
import nom.bdezonia.zorbage.procedure.Procedure2;
import nom.bdezonia.zorbage.procedure.Procedure3;
import nom.bdezonia.zorbage.procedure.Procedure4;
import nom.bdezonia.zorbage.sampling.IntegerIndex;
import nom.bdezonia.zorbage.type.algebra.Infinite;
import nom.bdezonia.zorbage.type.algebra.NaN;
import nom.bdezonia.zorbage.type.algebra.Norm;
import nom.bdezonia.zorbage.type.algebra.Rounding;
import nom.bdezonia.zorbage.type.algebra.Scale;
//note that many implementations of tensors on the internet treat them as generalized matrices.
//they do not worry about upper and lower indices or even matching shapes. They do element by
//element ops like sin() of each elem.
//do I skip Vector and Matrix and even Scalar?
//TODO: make one tensor/member pair for each of float64, complex64, quat64, oct64
//TODO: determine if this is a field or something else or two things for float/complex vs. quat/oct
// this implies it is an OrderedField. Do tensors have an ordering? abs() exists in TensorFlow.
//@Override
//public void abs(TensorMember a, TensorMember b) {}
// tensorflow also has trigonometric and hyperbolic
//public void contract(int i, int j, TensorMember a, TensorMember b, TensorMember c) {}
//public void takeDiagonal(TensorMember a, Object b) {} // change Object to Vector
//many more
import nom.bdezonia.zorbage.type.algebra.TensorProduct;
import nom.bdezonia.zorbage.type.ctor.ConstructibleNdLong;
import nom.bdezonia.zorbage.type.ctor.StorageConstruction;
// Note that for now the implementation is only for Cartesian tensors
/**
*
* @author Barry DeZonia
*
*/
public class Float64TensorProduct
implements
TensorProduct<Float64TensorProduct,Float64TensorProductMember,Float64Algebra,Float64Member>,
ConstructibleNdLong<Float64TensorProductMember>,
Norm<Float64TensorProductMember,Float64Member>,
Scale<Float64TensorProductMember,Float64Member>,
Rounding<Float64Member,Float64TensorProductMember>,
Infinite<Float64TensorProductMember>,
NaN<Float64TensorProductMember>
{
@Override
public Float64TensorProductMember construct() {
return new Float64TensorProductMember();
}
@Override
public Float64TensorProductMember construct(Float64TensorProductMember other) {
return new Float64TensorProductMember(other);
}
@Override
public Float64TensorProductMember construct(String s) {
return new Float64TensorProductMember(s);
}
@Override
public Float64TensorProductMember construct(StorageConstruction s, long[] nd) {
return new Float64TensorProductMember(s, nd);
}
private final Function2<Boolean,Float64TensorProductMember,Float64TensorProductMember> EQ =
new Function2<Boolean,Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public Boolean call(Float64TensorProductMember a, Float64TensorProductMember b) {
if (!shapesMatch(a,b))
return false;
Float64Member aTmp = new Float64Member();
Float64Member bTmp = new Float64Member();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, aTmp);
b.v(i, bTmp);
if (G.DBL.isNotEqual().call(aTmp, bTmp))
return false;
}
return true;
}
};
@Override
public Function2<Boolean,Float64TensorProductMember,Float64TensorProductMember> isEqual() {
return EQ;
}
private final Function2<Boolean,Float64TensorProductMember,Float64TensorProductMember> NEQ =
new Function2<Boolean,Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public Boolean call(Float64TensorProductMember a, Float64TensorProductMember b) {
return !isEqual().call(a,b);
}
};
@Override
public Function2<Boolean,Float64TensorProductMember,Float64TensorProductMember> isNotEqual() {
return NEQ;
}
private final Procedure2<Float64TensorProductMember,Float64TensorProductMember> ASSIGN =
new Procedure2<Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember from, Float64TensorProductMember to) {
if (to == from) return;
Float64Member tmp = new Float64Member();
long[] dims = new long[from.numDimensions()];
for (int i = 0; i < dims.length; i++) {
dims[i] = from.dimension(i);
}
to.alloc(dims);
long numElems = from.numElems();
for (long i = 0; i < numElems; i++) {
from.v(i, tmp);
to.setV(i, tmp);
}
}
};
@Override
public Procedure2<Float64TensorProductMember,Float64TensorProductMember> assign() {
return ASSIGN;
}
private final Procedure1<Float64TensorProductMember> ZER =
new Procedure1<Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a) {
Float64Member tmp = new Float64Member();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.setV(i, tmp);
}
}
};
@Override
public Procedure1<Float64TensorProductMember> zero() {
return ZER;
}
private final Procedure2<Float64TensorProductMember,Float64TensorProductMember> NEG =
new Procedure2<Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a, Float64TensorProductMember b) {
Float64Member tmp = new Float64Member();
shapeResult(a, b);
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, tmp);
G.DBL.negate().call(tmp, tmp);
b.setV(i, tmp);
}
}
};
@Override
public Procedure2<Float64TensorProductMember,Float64TensorProductMember> negate() {
return NEG;
}
private final Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> ADD =
new Procedure3<Float64TensorProductMember, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) {
if (!shapesMatch(a,b))
throw new IllegalArgumentException("tensor add shape mismatch");
long[] newDims = new long[a.numDimensions()];
for (int i = 0; i < newDims.length; i++) {
newDims[i] = a.dimension(i);
}
c.alloc(newDims);
Float64Member aTmp = new Float64Member();
Float64Member bTmp = new Float64Member();
Float64Member cTmp = new Float64Member();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, aTmp);
b.v(i, bTmp);
G.DBL.add().call(aTmp, bTmp, cTmp);
c.setV(i, cTmp);
}
}
};
@Override
public Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> add() {
return ADD;
}
private final Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> SUB =
new Procedure3<Float64TensorProductMember, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) {
if (!shapesMatch(a,b))
throw new IllegalArgumentException("tensor subtract shape mismatch");
long[] newDims = new long[a.numDimensions()];
for (int i = 0; i < newDims.length; i++) {
newDims[i] = a.dimension(i);
}
c.alloc(newDims);
Float64Member aTmp = new Float64Member();
Float64Member bTmp = new Float64Member();
Float64Member cTmp = new Float64Member();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, aTmp);
b.v(i, bTmp);
G.DBL.subtract().call(aTmp, bTmp, cTmp);
c.setV(i, cTmp);
}
}
};
@Override
public Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> subtract() {
return SUB;
}
private final Procedure2<Float64TensorProductMember,Float64Member> NORM =
new Procedure2<Float64TensorProductMember, Float64Member>()
{
@Override
public void call(Float64TensorProductMember a, Float64Member b) {
// TODO: to port to complex, quat, oct do I need to multiply() not by self but by the
// conjugate of self. We need to transform a comp, quat, oct into a real.
Float64Member max = new Float64Member();
Float64Member value = new Float64Member();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, value);
G.DBL.norm().call(value, value);
if (G.DBL.isGreater().call(value, max))
G.DBL.assign().call(value, max);
}
Float64Member sum = new Float64Member();
for (long i = 0; i < numElems; i++) {
a.v(i, value);
G.DBL.divide().call(value, max, value);
G.DBL.multiply().call(value, value, value); // See TODO above
G.DBL.add().call(sum, value, sum);
}
G.DBL.sqrt().call(sum, sum);
G.DBL.multiply().call(max, sum, sum);
G.DBL.assign().call(sum, b);
}
};
@Override
public Procedure2<Float64TensorProductMember,Float64Member> norm() {
return NORM;
}
@Override
public Procedure2<Float64TensorProductMember,Float64TensorProductMember> conjugate() {
return ASSIGN;
}
private final Procedure3<Float64Member,Float64TensorProductMember,Float64TensorProductMember> SCALE =
new Procedure3<Float64Member, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64Member scalar, Float64TensorProductMember a, Float64TensorProductMember b) {
Float64Member tmp = new Float64Member();
shapeResult(a, b);
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, tmp);
G.DBL.multiply().call(scalar, tmp, tmp);
b.setV(i, tmp);
}
}
};
@Override
public Procedure3<Float64Member,Float64TensorProductMember,Float64TensorProductMember> scale() {
return SCALE;
}
private final Procedure3<Float64Member,Float64TensorProductMember,Float64TensorProductMember> ADDEL =
new Procedure3<Float64Member, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64Member scalar, Float64TensorProductMember a, Float64TensorProductMember b) {
Float64Member tmp = new Float64Member();
shapeResult(a, b);
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, tmp);
G.DBL.add().call(scalar, tmp, tmp);
b.setV(i, tmp);
}
}
};
@Override
public Procedure3<Float64Member,Float64TensorProductMember,Float64TensorProductMember> addToElements() {
return ADDEL;
}
private Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> MULEL =
new Procedure3<Float64TensorProductMember, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) {
if (!shapesMatch(a,b))
throw new IllegalArgumentException("mismatched shapes");
long[] newDims = new long[a.numDimensions()];
for (int i = 0; i < newDims.length; i++) {
newDims[i] = a.dimension(i);
}
c.alloc(newDims);
Float64Member aTmp = new Float64Member();
Float64Member bTmp = new Float64Member();
Float64Member cTmp = new Float64Member();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, aTmp);
b.v(i, bTmp);
G.DBL.multiply().call(aTmp, bTmp, cTmp);
c.setV(i, cTmp);
}
}
};
@Override
public Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> multiplyElements() {
return MULEL;
}
private Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> DIVIDEEL =
new Procedure3<Float64TensorProductMember, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) {
if (!shapesMatch(a,b))
throw new IllegalArgumentException("mismatched shapes");
long[] newDims = new long[a.numDimensions()];
for (int i = 0; i < newDims.length; i++) {
newDims[i] = a.dimension(i);
}
c.alloc(newDims);
Float64Member aTmp = new Float64Member();
Float64Member bTmp = new Float64Member();
Float64Member cTmp = new Float64Member();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, aTmp);
b.v(i, bTmp);
G.DBL.divide().call(aTmp, bTmp, cTmp);
c.setV(i, cTmp);
}
}
};
@Override
public Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> divideElements() {
return DIVIDEEL;
}
// TODO citation needed. I wrote this long ago and no longer can tell if it makes sense.
private final Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> MUL =
new Procedure3<Float64TensorProductMember, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a, Float64TensorProductMember b, Float64TensorProductMember c) {
if (c == a || c == b)
throw new IllegalArgumentException("destination tensor cannot be one of the inputs");
long dimA = a.dimension(0);
long dimB = b.dimension(0);
if (dimA != dimB)
throw new IllegalArgumentException("dimension of tensors must match");
int rankA = a.numDimensions();
int rankB = b.numDimensions();
int rankC = rankA + rankB;
long[] cDims = new long[rankC];
for (int i = 0; i < cDims.length; i++) {
cDims[i] = dimA;
}
c.alloc(cDims);
Float64Member aTmp = new Float64Member();
Float64Member bTmp = new Float64Member();
Float64Member cTmp = new Float64Member();
long k = 0;
long numElemsA = a.numElems();
long numElemsB = b.numElems();
for (long i = 0; i < numElemsA; i++) {
a.v(i, aTmp);
for (long j = 0; j < numElemsB; j++) {
b.v(j, bTmp);
G.DBL.multiply().call(aTmp, bTmp, cTmp);
c.setV(k, cTmp);
k++;
}
}
}
};
@Override
public Procedure3<Float64TensorProductMember,Float64TensorProductMember,Float64TensorProductMember> multiply() {
return MUL;
}
// https://en.wikipedia.org/wiki/Tensor_contraction
// TODO
private final Procedure4<java.lang.Integer,java.lang.Integer,Float64TensorProductMember,Float64TensorProductMember> CONTRACT =
new Procedure4<Integer, Integer, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Integer i, Integer j, Float64TensorProductMember a, Float64TensorProductMember b) {
if (a.rank() < 2)
throw new IllegalArgumentException("input tensor must be rank 2 or greater to contract");
if (i < 0 || j < 0 || i >= a.rank() || j >= a.rank())
throw new IllegalArgumentException("bad contraction indices given");
if (i == j)
throw new IllegalArgumentException("cannot contract along a single axis");
if (a == b)
throw new IllegalArgumentException("destination tensor cannot be one of the inputs");
int rank = a.rank() - 2;
long[] newDims = new long[rank];
for (int k = 0; k < newDims.length; k++) {
newDims[k] = a.dimension(0);
}
b.alloc(newDims);
throw new IllegalArgumentException("TODO");
}
};
@Override
public Procedure4<java.lang.Integer,java.lang.Integer,Float64TensorProductMember,Float64TensorProductMember> contract() {
return CONTRACT;
}
// http://mathworld.wolfram.com/CovariantDerivative.html
// TODO
private final Procedure1<java.lang.Integer> SEMI =
new Procedure1<Integer>()
{
@Override
public void call(Integer a) {
throw new IllegalArgumentException("TODO");
}
};
@Override
public Procedure1<java.lang.Integer> semicolonDerivative() {
return SEMI;
}
// http://mathworld.wolfram.com/CommaDerivative.html
// TODO
private final Procedure1<java.lang.Integer> COMMA =
new Procedure1<Integer>()
{
@Override
public void call(Integer a) {
throw new IllegalArgumentException("TODO");
}
};
@Override
public Procedure1<java.lang.Integer> commaDerivative() {
return COMMA;
}
private boolean shapesMatch(Float64TensorProductMember a, Float64TensorProductMember b) {
if (a.numDimensions() != b.numDimensions())
return false;
for (int i = 0; i < a.numDimensions(); i++) {
if (a.dimension(i) != b.dimension(i))
return false;
}
return true;
}
/* future version
private boolean shapesMatch(Float64TensorProductMember a, Float64TensorProductMember b) {
int i = 0;
int j = 0;
while (i < a.numDimensions() && j < b.numDimensions()) {
while (i < a.numDimensions() && a.dimension(i) == 1) i++;
while (j < b.numDimensions() && b.dimension(i) == 1) j++;
if (i < a.numDimensions() && j < b.numDimensions() && a.dimension(i) != b.dimension(j))
return false;
else {
i++;
j++;
}
}
while (i < a.numDimensions() && a.dimension(i) == 1) i++;
while (j < b.numDimensions() && b.dimension(i) == 1) j++;
if (i != a.numDimensions() || j != b.numDimensions())
return false;
return true;
}
*/
// TODO - make much more efficient by copying style of MatrixMultiply algorithm
private final Procedure3<java.lang.Integer,Float64TensorProductMember,Float64TensorProductMember> POWER =
new Procedure3<Integer, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Integer power, Float64TensorProductMember a, Float64TensorProductMember b) {
if (power < 0) {
// TODO: is this a valid limitation?
throw new IllegalArgumentException("negative powers not supported");
}
else if (power == 0) {
if (isZero().call(a)) {
throw new IllegalArgumentException("0^0 is not a number");
}
shapeResult(a, b); // set the shape of result
unity().call(b); // and make it have value 1
}
else if (power == 1) {
assign().call(a, b);
}
else {
Float64TensorProductMember tmp1 = new Float64TensorProductMember();
Float64TensorProductMember tmp2 = new Float64TensorProductMember();
multiply().call(a,a,tmp1);
for (int i = 2; i < (power/2)*2; i += 2) {
multiply().call(tmp1, a, tmp2);
multiply().call(tmp2, a, tmp1);
}
// an odd power
if (power > 2 && (power&1)==1) {
assign().call(tmp1, tmp2);
multiply().call(tmp2, a, tmp1);
}
assign().call(tmp1, b);
}
}
};
@Override
public Procedure3<java.lang.Integer,Float64TensorProductMember,Float64TensorProductMember> power() {
return POWER;
}
private final Procedure1<Float64TensorProductMember> UNITY =
new Procedure1<Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember result) {
Float64Member one = new Float64Member();
G.DBL.unity().call(one);
zero().call(result);
IntegerIndex index = new IntegerIndex(result.rank());
for (long d = 0; d < result.dimension(0); d++) {
for (int r = 0; r < result.rank(); r++) {
index.set(r, d);
}
result.setV(index, one);
}
}
};
@Override
public Procedure1<Float64TensorProductMember> unity() {
return UNITY;
}
private final Function1<Boolean, Float64TensorProductMember> ISNAN =
new Function1<Boolean, Float64TensorProductMember>()
{
@Override
public Boolean call(Float64TensorProductMember a) {
return SequenceIsNan.compute(G.DBL, a.rawData());
}
};
@Override
public Function1<Boolean, Float64TensorProductMember> isNaN() {
return ISNAN;
}
private final Procedure1<Float64TensorProductMember> NAN =
new Procedure1<Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a) {
Float64Member value = G.DBL.construct();
G.DBL.nan().call(value);
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.setV(i, value);
}
}
};
@Override
public Procedure1<Float64TensorProductMember> nan() {
return NAN;
}
private final Function1<Boolean, Float64TensorProductMember> ISINF =
new Function1<Boolean, Float64TensorProductMember>()
{
@Override
public Boolean call(Float64TensorProductMember a) {
return SequenceIsInf.compute(G.DBL, a.rawData());
}
};
@Override
public Function1<Boolean, Float64TensorProductMember> isInfinite() {
return ISINF;
}
private final Procedure1<Float64TensorProductMember> INF =
new Procedure1<Float64TensorProductMember>()
{
@Override
public void call(Float64TensorProductMember a) {
Float64Member value = G.DBL.construct();
G.DBL.infinite().call(value);
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.setV(i, value);
}
}
};
@Override
public Procedure1<Float64TensorProductMember> infinite() {
return INF;
}
private final Procedure4<Mode, Float64Member, Float64TensorProductMember, Float64TensorProductMember> ROUND =
new Procedure4<Mode, Float64Member, Float64TensorProductMember, Float64TensorProductMember>()
{
@Override
public void call(Mode mode, Float64Member delta, Float64TensorProductMember a, Float64TensorProductMember b) {
if (a != b) {
long[] newDims = new long[a.numDimensions()];
for (int i = 0; i < newDims.length; i++) {
newDims[i] = a.dimension(i);
}
b.alloc(newDims);
}
Float64Member tmp = G.DBL.construct();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, tmp);
G.DBL.round().call(mode, delta, tmp, tmp);
b.setV(i, tmp);
}
}
};
@Override
public Procedure4<Mode, Float64Member, Float64TensorProductMember, Float64TensorProductMember> round() {
return ROUND;
}
private final Function1<Boolean, Float64TensorProductMember> ISZERO =
new Function1<Boolean, Float64TensorProductMember>()
{
@Override
public Boolean call(Float64TensorProductMember a) {
Float64Member value = G.DBL.construct();
long numElems = a.numElems();
for (long i = 0; i < numElems; i++) {
a.v(i, value);
if (!G.DBL.isZero().call(value))
return false;
}
return true;
}
};
@Override
public Function1<Boolean, Float64TensorProductMember> isZero() {
return ISZERO;
}
private void shapeResult(Float64TensorProductMember from, Float64TensorProductMember to) {
if (from == to) return;
long[] dims = new long[from.numDimensions()];
for (int i = 0; i < dims.length; i++) {
dims[i] = from.dimension(i);
}
to.alloc(dims);
}
}
|
Simplify some code
|
src/main/java/nom/bdezonia/zorbage/type/data/float64/real/Float64TensorProduct.java
|
Simplify some code
|
<ide><path>rc/main/java/nom/bdezonia/zorbage/type/data/float64/real/Float64TensorProduct.java
<ide> import nom.bdezonia.zorbage.algorithm.Round.Mode;
<ide> import nom.bdezonia.zorbage.algorithm.SequenceIsInf;
<ide> import nom.bdezonia.zorbage.algorithm.SequenceIsNan;
<add>import nom.bdezonia.zorbage.algorithm.SequenceIsZero;
<ide> import nom.bdezonia.zorbage.function.Function1;
<ide> import nom.bdezonia.zorbage.function.Function2;
<ide> import nom.bdezonia.zorbage.procedure.Procedure1;
<ide> {
<ide> @Override
<ide> public Boolean call(Float64TensorProductMember a) {
<del> Float64Member value = G.DBL.construct();
<del> long numElems = a.numElems();
<del> for (long i = 0; i < numElems; i++) {
<del> a.v(i, value);
<del> if (!G.DBL.isZero().call(value))
<del> return false;
<del> }
<del> return true;
<add> return SequenceIsZero.compute(G.DBL, a.rawData());
<ide> }
<ide> };
<ide>
|
|
Java
|
apache-2.0
|
4d7b94e2a1d1905d05ea6c40b15a138ebfd49f83
| 0 |
MissionCriticalCloud/cosmic,MissionCriticalCloud/cosmic,MissionCriticalCloud/cosmic,MissionCriticalCloud/cosmic,MissionCriticalCloud/cosmic
|
package com.cloud.network;
import com.cloud.acl.ControlledEntity.ACLType;
import com.cloud.acl.SecurityChecker.AccessType;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.command.admin.network.DedicateGuestVlanRangeCmd;
import com.cloud.api.command.admin.network.ListDedicatedGuestVlanRangesCmd;
import com.cloud.api.command.user.network.CreateNetworkCmd;
import com.cloud.api.command.user.network.ListNetworksCmd;
import com.cloud.api.command.user.network.RestartNetworkCmd;
import com.cloud.api.command.user.vm.ListNicsCmd;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.Resource;
import com.cloud.context.CallContext;
import com.cloud.dao.EntityManager;
import com.cloud.db.model.Zone;
import com.cloud.db.repository.ZoneRepository;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.DataCenterVnetVO;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.DataCenterVnetDao;
import com.cloud.dc.dao.VlanDao;
import com.cloud.deploy.DeployDestination;
import com.cloud.domain.Domain;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.engine.orchestration.service.NetworkOrchestrationService;
import com.cloud.event.ActionEvent;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.UnsupportedServiceException;
import com.cloud.framework.config.dao.ConfigurationDao;
import com.cloud.model.enumeration.AllocationState;
import com.cloud.model.enumeration.NetworkType;
import com.cloud.network.IpAddress.State;
import com.cloud.network.Network.Capability;
import com.cloud.network.Network.GuestType;
import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.PhysicalNetwork.BroadcastDomainRange;
import com.cloud.network.VirtualRouterProvider.Type;
import com.cloud.network.addr.PublicIp;
import com.cloud.network.dao.AccountGuestVlanMapDao;
import com.cloud.network.dao.AccountGuestVlanMapVO;
import com.cloud.network.dao.FirewallRulesDao;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.dao.IPAddressVO;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkDomainDao;
import com.cloud.network.dao.NetworkDomainVO;
import com.cloud.network.dao.NetworkServiceMapDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.dao.PhysicalNetworkDao;
import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
import com.cloud.network.dao.PhysicalNetworkServiceProviderVO;
import com.cloud.network.dao.PhysicalNetworkTrafficTypeDao;
import com.cloud.network.dao.PhysicalNetworkTrafficTypeVO;
import com.cloud.network.dao.PhysicalNetworkVO;
import com.cloud.network.element.NetworkElement;
import com.cloud.network.element.VirtualRouterElement;
import com.cloud.network.element.VpcVirtualRouterElement;
import com.cloud.network.guru.NetworkGuru;
import com.cloud.network.lb.LoadBalancingRulesService;
import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.network.rules.FirewallRuleVO;
import com.cloud.network.rules.RulesManager;
import com.cloud.network.rules.dao.PortForwardingRulesDao;
import com.cloud.network.vpc.NetworkACL;
import com.cloud.network.vpc.PrivateIpVO;
import com.cloud.network.vpc.StaticRoute;
import com.cloud.network.vpc.Vpc;
import com.cloud.network.vpc.VpcManager;
import com.cloud.network.vpc.dao.NetworkACLDao;
import com.cloud.network.vpc.dao.PrivateIpDao;
import com.cloud.network.vpc.dao.StaticRouteDao;
import com.cloud.offering.NetworkOffering;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
import com.cloud.projects.Project;
import com.cloud.projects.ProjectManager;
import com.cloud.server.ResourceTag.ResourceObjectType;
import com.cloud.tags.ResourceTagVO;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO;
import com.cloud.user.DomainManager;
import com.cloud.user.ResourceLimitService;
import com.cloud.user.User;
import com.cloud.user.UserVO;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.Journal;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.StringUtils;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallback;
import com.cloud.utils.db.TransactionCallbackNoReturn;
import com.cloud.utils.db.TransactionCallbackWithException;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.exception.ExceptionUtil;
import com.cloud.utils.exception.InvalidParameterValueException;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.Nic;
import com.cloud.vm.NicSecondaryIp;
import com.cloud.vm.NicVO;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.ReservationContextImpl;
import com.cloud.vm.SecondaryStorageVmVO;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.NicSecondaryIpDao;
import com.cloud.vm.dao.NicSecondaryIpVO;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.security.InvalidParameterException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* NetworkServiceImpl implements NetworkService.
*/
public class NetworkServiceImpl extends ManagerBase implements NetworkService {
private static final Logger s_logger = LoggerFactory.getLogger(NetworkServiceImpl.class);
private static final long MIN_VLAN_ID = 0L;
private static final long MAX_VLAN_ID = 4095L; // 2^12 - 1
private static final long MIN_GRE_KEY = 0L;
private static final long MAX_GRE_KEY = 4294967295L; // 2^32 -1
private static final long MIN_VXLAN_VNI = 0L;
private static final long MAX_VXLAN_VNI = 16777214L; // 2^24 -2
// MAX_VXLAN_VNI should be 16777215L (2^24-1), but Linux vxlan interface doesn't accept VNI:2^24-1 now.
// It seems a bug.
@Inject
DataCenterDao _dcDao = null;
@Inject
private
VlanDao _vlanDao = null;
@Inject
private
IPAddressDao _ipAddressDao = null;
@Inject
AccountDao _accountDao = null;
@Inject
private
DomainDao _domainDao = null;
@Inject
private
UserDao _userDao = null;
@Inject
private
ConfigurationDao _configDao;
@Inject
private
UserVmDao _userVmDao = null;
@Inject
AccountManager _accountMgr;
@Inject
private
ConfigurationManager _configMgr;
@Inject
NetworkOfferingDao _networkOfferingDao = null;
@Inject
NetworkDao _networksDao = null;
@Inject
private
NicDao _nicDao = null;
@Inject
private
RulesManager _rulesMgr;
@Inject
private
NetworkDomainDao _networkDomainDao;
@Inject
private
VMInstanceDao _vmDao;
@Inject
private
FirewallRulesDao _firewallDao;
@Inject
private
ResourceLimitService _resourceLimitMgr;
@Inject
private
DomainManager _domainMgr;
@Inject
ProjectManager _projectMgr;
@Inject
private
NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao;
@Inject
PhysicalNetworkDao _physicalNetworkDao;
@Inject
private
PhysicalNetworkServiceProviderDao _pNSPDao;
@Inject
private
PhysicalNetworkTrafficTypeDao _pNTrafficTypeDao;
@Inject
private
NetworkServiceMapDao _ntwkSrvcDao;
@Inject
private
StorageNetworkManager _stnwMgr;
@Inject
private
VpcManager _vpcMgr;
@Inject
PrivateIpDao _privateIpDao;
@Inject
private
ResourceTagDao _resourceTagDao;
@Inject
NetworkOrchestrationService _networkMgr;
@Inject
private
NetworkModel _networkModel;
@Inject
private
NicSecondaryIpDao _nicSecondaryIpDao;
@Inject
private
PortForwardingRulesDao _portForwardingDao;
@Inject
DataCenterVnetDao _datacneterVnet;
@Inject
AccountGuestVlanMapDao _accountGuestVlanMapDao;
@Inject
private
NetworkACLDao _networkACLDao;
@Inject
private
IpAddressManager _ipAddrMgr;
@Inject
private
EntityManager _entityMgr;
@Inject
private
StaticRouteDao _staticRouteDao;
@Inject
private
LoadBalancingRulesService _lbService;
@Inject
private
ZoneRepository zoneRepository;
private int _cidrLimit;
private boolean _allowSubdomainNetworkAccess;
private List<NetworkGuru> _networkGurus;
private Map<String, String> _configs;
NetworkServiceImpl() {
}
/* Get a list of IPs, classify them by service */
protected Map<PublicIp, Set<Service>> getIpToServices(final List<PublicIp> publicIps, final boolean rulesRevoked, final boolean includingFirewall) {
final Map<PublicIp, Set<Service>> ipToServices = new HashMap<>();
if (publicIps != null && !publicIps.isEmpty()) {
final Set<Long> networkSNAT = new HashSet<>();
for (final PublicIp ip : publicIps) {
Set<Service> services = ipToServices.get(ip);
if (services == null) {
services = new HashSet<>();
}
if (ip.isSourceNat()) {
if (!networkSNAT.contains(ip.getAssociatedWithNetworkId())) {
services.add(Service.SourceNat);
networkSNAT.add(ip.getAssociatedWithNetworkId());
} else {
final CloudRuntimeException ex = new CloudRuntimeException("Multiple generic soure NAT IPs provided for network");
// see the IPAddressVO.java class.
final IPAddressVO ipAddr = ApiDBUtils.findIpAddressById(ip.getAssociatedWithNetworkId());
String ipAddrUuid = ip.getAssociatedWithNetworkId().toString();
if (ipAddr != null) {
ipAddrUuid = ipAddr.getUuid();
}
ex.addProxyObject(ipAddrUuid, "networkId");
throw ex;
}
}
ipToServices.put(ip, services);
// if IP in allocating state then it will not have any rules attached so skip IPAssoc to network service
// provider
if (ip.getState() == State.Allocating) {
continue;
}
// check if any active rules are applied on the public IP
Set<Purpose> purposes = getPublicIpPurposeInRules(ip, false, includingFirewall);
// Firewall rules didn't cover static NAT
if (ip.isOneToOneNat() && ip.getAssociatedWithVmId() != null) {
if (purposes == null) {
purposes = new HashSet<>();
}
purposes.add(Purpose.StaticNat);
}
if (purposes == null || purposes.isEmpty()) {
// since no active rules are there check if any rules are applied on the public IP but are in
// revoking state
purposes = getPublicIpPurposeInRules(ip, true, includingFirewall);
if (ip.isOneToOneNat()) {
if (purposes == null) {
purposes = new HashSet<>();
}
purposes.add(Purpose.StaticNat);
}
if (purposes == null || purposes.isEmpty()) {
// IP is not being used for any purpose so skip IPAssoc to network service provider
continue;
} else {
if (rulesRevoked) {
// no active rules/revoked rules are associated with this public IP, so remove the
// association with the provider
ip.setState(State.Releasing);
} else {
if (ip.getState() == State.Releasing) {
// rules are not revoked yet, so don't let the network service provider revoke the IP
// association
// mark IP is allocated so that IP association will not be removed from the provider
ip.setState(State.Allocated);
}
}
}
}
if (purposes.contains(Purpose.StaticNat)) {
services.add(Service.StaticNat);
}
if (purposes.contains(Purpose.LoadBalancing)) {
services.add(Service.Lb);
}
if (purposes.contains(Purpose.PortForwarding)) {
services.add(Service.PortForwarding);
}
if (purposes.contains(Purpose.Vpn)) {
services.add(Service.Vpn);
}
if (purposes.contains(Purpose.Firewall)) {
services.add(Service.Firewall);
}
if (services.isEmpty()) {
continue;
}
ipToServices.put(ip, services);
}
}
return ipToServices;
}
private boolean canIpUsedForNonConserveService(final PublicIp ip, final Service service) {
// If it's non-conserve mode, then the new ip should not be used by any other services
final List<PublicIp> ipList = new ArrayList<>();
ipList.add(ip);
final Map<PublicIp, Set<Service>> ipToServices = getIpToServices(ipList, false, false);
final Set<Service> services = ipToServices.get(ip);
// Not used currently, safe
if (services == null || services.isEmpty()) {
return true;
}
return true;
}
private boolean canIpsUsedForNonConserve(final List<PublicIp> publicIps) {
boolean result = true;
for (final PublicIp ip : publicIps) {
result = canIpUsedForNonConserveService(ip, null);
if (!result) {
break;
}
}
return result;
}
private boolean canIpsUseOffering(final List<PublicIp> publicIps, final long offeringId) {
final Map<PublicIp, Set<Service>> ipToServices = getIpToServices(publicIps, false, true);
final Map<Service, Set<Provider>> serviceToProviders = _networkModel.getNetworkOfferingServiceProvidersMap(offeringId);
final NetworkOfferingVO offering = _networkOfferingDao.findById(offeringId);
//For inline mode checking, using firewall provider for LB instead, because public ip would apply on firewall provider
if (offering.isInline()) {
Provider firewallProvider = null;
if (serviceToProviders.containsKey(Service.Firewall)) {
firewallProvider = (Provider) serviceToProviders.get(Service.Firewall).toArray()[0];
}
final Set<Provider> p = new HashSet<>();
p.add(firewallProvider);
serviceToProviders.remove(Service.Lb);
serviceToProviders.put(Service.Lb, p);
}
for (final PublicIp ip : ipToServices.keySet()) {
final Set<Service> services = ipToServices.get(ip);
Provider provider = null;
for (final Service service : services) {
final Set<Provider> curProviders = serviceToProviders.get(service);
if (curProviders == null || curProviders.isEmpty()) {
continue;
}
final Provider curProvider = (Provider) curProviders.toArray()[0];
if (provider == null) {
provider = curProvider;
continue;
}
// We don't support multiple providers for one service now
if (!provider.equals(curProvider)) {
throw new InvalidParameterException("There would be multiple providers for IP " + ip.getAddress() + " with the new network offering!");
}
}
}
return true;
}
private Set<Purpose> getPublicIpPurposeInRules(final PublicIp ip, final boolean includeRevoked, final boolean includingFirewall) {
final Set<Purpose> result = new HashSet<>();
List<FirewallRuleVO> rules = null;
if (includeRevoked) {
rules = _firewallDao.listByIp(ip.getId());
} else {
rules = _firewallDao.listByIpAndNotRevoked(ip.getId());
}
if (rules == null || rules.isEmpty()) {
return null;
}
for (final FirewallRuleVO rule : rules) {
if (rule.getPurpose() != Purpose.Firewall || includingFirewall) {
result.add(rule.getPurpose());
}
}
return result;
}
@Override
public List<? extends Network> getIsolatedNetworksOwnedByAccountInZone(final long zoneId, final Account owner) {
return _networksDao.listByZoneAndGuestType(owner.getId(), zoneId, Network.GuestType.Isolated, false);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "allocating Ip", create = true)
public IpAddress allocateIP(final Account ipOwner, final long zoneId, final Long networkId, final Boolean displayIp) throws ResourceAllocationException,
InsufficientAddressCapacityException,
ConcurrentOperationException {
final Account caller = CallContext.current().getCallingAccount();
final long callerUserId = CallContext.current().getCallingUserId();
final DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId);
if (networkId != null) {
final Network network = _networksDao.findById(networkId);
if (network == null) {
throw new InvalidParameterValueException("Invalid network id is given");
}
if (network.getGuestType() == Network.GuestType.Shared) {
if (zone == null) {
throw new InvalidParameterValueException("Invalid zone Id is given");
}
// if shared network in the advanced zone, then check the caller against the network for 'AccessType.UseNetwork'
if (zone.getNetworkType() == NetworkType.Advanced) {
if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) {
_accountMgr.checkAccess(caller, AccessType.UseEntry, false, network);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId());
}
return _ipAddrMgr.allocateIp(ipOwner, false, caller, callerUserId, zone, displayIp);
} else {
throw new InvalidParameterValueException("Associate IP address can only be called on the shared networks in the advanced zone"
+ " with Firewall/Source Nat/Static Nat/Port Forwarding/Load balancing services enabled");
}
}
}
} else {
_accountMgr.checkAccess(caller, null, false, ipOwner);
}
return _ipAddrMgr.allocateIp(ipOwner, false, caller, callerUserId, zone, displayIp);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_IP_RELEASE, eventDescription = "disassociating Ip", async = true)
public boolean releaseIpAddress(final long ipAddressId) throws InsufficientAddressCapacityException {
return releaseIpAddressInternal(ipAddressId);
}
@DB
private boolean releaseIpAddressInternal(final long ipAddressId) throws InsufficientAddressCapacityException {
final Long userId = CallContext.current().getCallingUserId();
final Account caller = CallContext.current().getCallingAccount();
// Verify input parameters
final IPAddressVO ipVO = _ipAddressDao.findById(ipAddressId);
if (ipVO == null) {
throw new InvalidParameterValueException("Unable to find ip address by id");
}
if (ipVO.getAllocatedTime() == null) {
s_logger.debug("Ip Address id= " + ipAddressId + " is not allocated, so do nothing.");
return true;
}
// verify permissions
if (ipVO.getAllocatedToAccountId() != null) {
_accountMgr.checkAccess(caller, null, true, ipVO);
}
if (ipVO.isSourceNat()) {
throw new IllegalArgumentException("ip address is used for source nat purposes and can not be disassociated.");
}
final VlanVO vlan = _vlanDao.findById(ipVO.getVlanId());
if (!vlan.getVlanType().equals(VlanType.VirtualNetwork)) {
throw new IllegalArgumentException("only ip addresses that belong to a virtual network may be disassociated.");
}
// don't allow releasing system ip address
if (ipVO.getSystem()) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't release system IP address with specified id");
ex.addProxyObject(ipVO.getUuid(), "systemIpAddrId");
throw ex;
}
final boolean success = _ipAddrMgr.disassociatePublicIpAddress(ipAddressId, userId, caller);
if (success) {
final Long networkId = ipVO.getAssociatedWithNetworkId();
if (networkId != null) {
final Network guestNetwork = getNetwork(networkId);
final NetworkOffering offering = _entityMgr.findById(NetworkOffering.class, guestNetwork.getNetworkOfferingId());
final Long vmId = ipVO.getAssociatedWithVmId();
if (offering.getElasticIp() && vmId != null) {
_rulesMgr.getSystemIpAndEnableStaticNatForVm(_userVmDao.findById(vmId), true);
return true;
}
}
} else {
s_logger.warn("Failed to release public ip address id=" + ipAddressId);
}
return success;
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_CREATE, eventDescription = "creating network")
public Network createGuestNetwork(final CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException {
final Long networkOfferingId = cmd.getNetworkOfferingId();
String gateway = cmd.getGateway();
final String startIP = cmd.getStartIp();
String endIP = cmd.getEndIp();
final String netmask = cmd.getNetmask();
final String networkDomain = cmd.getNetworkDomain();
final String vlanId = cmd.getVlan();
final String name = cmd.getNetworkName();
final String displayText = cmd.getDisplayText();
final Account caller = CallContext.current().getCallingAccount();
final Long physicalNetworkId = cmd.getPhysicalNetworkId();
Long zoneId = cmd.getZoneId();
final String aclTypeStr = cmd.getAclType();
final Long domainId = cmd.getDomainId();
boolean isDomainSpecific = false;
final Boolean subdomainAccess = cmd.getSubdomainAccess();
final Long vpcId = cmd.getVpcId();
final String startIPv6 = cmd.getStartIpv6();
String endIPv6 = cmd.getEndIpv6();
String ip6Gateway = cmd.getIp6Gateway();
final String ip6Cidr = cmd.getIp6Cidr();
Boolean displayNetwork = cmd.getDisplayNetwork();
final Long aclId = cmd.getAclId();
final String isolatedPvlan = cmd.getIsolatedPvlan();
final String dns1 = cmd.getDns1();
final String dns2 = cmd.getDns2();
final String ipExclusionList = cmd.getIpExclusionList();
// Validate network offering
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
if (ntwkOff == null || ntwkOff.isSystemOnly()) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering by specified id");
if (ntwkOff != null) {
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
}
throw ex;
}
if (!GuestType.Private.equals(ntwkOff.getGuestType()) && vpcId == null) {
throw new InvalidParameterValueException("VPC ID is required");
}
if (GuestType.Private.equals(ntwkOff.getGuestType()) && (startIP != null || endIP != null || vpcId != null || gateway != null || netmask != null)) {
throw new InvalidParameterValueException("StartIp/endIp/vpcId/gateway/netmask can't be specified for guest type " + GuestType.Private);
}
// validate physical network and zone
// Check if physical network exists
PhysicalNetwork pNtwk = null;
if (physicalNetworkId != null) {
pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
if (pNtwk == null) {
throw new InvalidParameterValueException("Unable to find a physical network having the specified physical network id");
}
}
if (zoneId == null) {
zoneId = pNtwk.getDataCenterId();
}
if (displayNetwork == null) {
displayNetwork = true;
}
final Zone zone = zoneRepository.findById(zoneId).orElse(null);
if (zone == null) {
throw new InvalidParameterValueException("Specified zone id was not found");
}
if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
// See DataCenterVO.java
final PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation since specified Zone is currently disabled");
ex.addProxyObject(zone.getUuid(), "zoneId");
throw ex;
}
// Only domain and account ACL types are supported in Acton.
ACLType aclType = null;
if (aclTypeStr != null) {
if (aclTypeStr.equalsIgnoreCase(ACLType.Account.toString())) {
aclType = ACLType.Account;
} else if (aclTypeStr.equalsIgnoreCase(ACLType.Domain.toString())) {
aclType = ACLType.Domain;
} else {
throw new InvalidParameterValueException("Incorrect aclType specified. Check the API documentation for supported types");
}
// In 3.0 all Shared networks should have aclType == Domain, all Isolated networks aclType==Account
if (ntwkOff.getGuestType() != GuestType.Shared) {
if (aclType != ACLType.Account) {
throw new InvalidParameterValueException("AclType should be " + ACLType.Account + " for network of type " + ntwkOff.getGuestType());
}
} else if (ntwkOff.getGuestType() == GuestType.Shared) {
if (!(aclType == ACLType.Domain || aclType == ACLType.Account)) {
throw new InvalidParameterValueException("AclType should be " + ACLType.Domain + " or " + ACLType.Account + " for network of type " + Network.GuestType.Shared);
}
}
} else {
aclType = (ntwkOff.getGuestType() == GuestType.Shared)
? ACLType.Domain
: ACLType.Account;
}
// Only Admin can create Shared networks
if (ntwkOff.getGuestType() == GuestType.Shared && !_accountMgr.isAdmin(caller.getId())) {
throw new InvalidParameterValueException("Only Admins can create network with guest type " + GuestType.Shared);
}
// Check if the network is domain specific
if (aclType == ACLType.Domain) {
// only Admin can create domain with aclType=Domain
if (!_accountMgr.isAdmin(caller.getId())) {
throw new PermissionDeniedException("Only admin can create networks with aclType=Domain");
}
// only shared networks can be Domain specific
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only " + GuestType.Shared + " networks can have aclType=" + ACLType.Domain);
}
if (domainId != null) {
if (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Shared) {
throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and guest type "
+ Network.GuestType.Shared);
}
final DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Unable to find domain by specified id");
}
_accountMgr.checkAccess(caller, domain);
}
isDomainSpecific = true;
} else if (subdomainAccess != null) {
throw new InvalidParameterValueException("Parameter subDomainAccess can be specified only with aclType=Domain");
}
Account owner = null;
if (cmd.getAccountName() != null && domainId != null || cmd.getProjectId() != null) {
owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), domainId, cmd.getProjectId());
} else {
owner = caller;
}
boolean ipv4 = true, ipv6 = false;
if (startIP != null) {
ipv4 = true;
}
if (startIPv6 != null) {
ipv6 = true;
}
if (gateway != null) {
try {
// getByName on a literal representation will only check validity of the address
// http://docs.oracle.com/javase/6/docs/api/java/net/InetAddress.html#getByName(java.lang.String)
final InetAddress gatewayAddress = InetAddress.getByName(gateway);
if (gatewayAddress instanceof Inet6Address) {
ipv6 = true;
} else {
ipv4 = true;
}
} catch (final UnknownHostException e) {
s_logger.error("Unable to convert gateway IP to a InetAddress", e);
throw new InvalidParameterValueException("Gateway parameter is invalid");
}
}
String cidr = cmd.getCidr();
if (ipv4) {
// validate the CIDR
if (cidr != null && !NetUtils.isValidIp4Cidr(cidr)) {
throw new InvalidParameterValueException("Invalid format for the CIDR parameter");
}
// validate gateway with cidr
if (cidr != null && gateway != null && !NetUtils.isIpWithtInCidrRange(gateway, cidr)) {
throw new InvalidParameterValueException("The gateway ip " + gateway + " should be part of the CIDR of the network " + cidr);
}
// if end ip is not specified, default it to startIp
if (startIP != null) {
if (!NetUtils.isValidIp4(startIP)) {
throw new InvalidParameterValueException("Invalid format for the startIp parameter");
}
if (endIP == null) {
endIP = startIP;
} else if (!NetUtils.isValidIp4(endIP)) {
throw new InvalidParameterValueException("Invalid format for the endIp parameter");
}
}
if (startIP != null && endIP != null) {
if (!(gateway != null && netmask != null)) {
throw new InvalidParameterValueException("gateway and netmask should be defined when startIP/endIP are passed in");
}
}
if (gateway != null && netmask != null) {
if (NetUtils.isNetworkorBroadcastIP(gateway, netmask)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("The gateway IP provided is " + gateway + " and netmask is " + netmask + ". The IP is either broadcast or network IP.");
}
throw new InvalidParameterValueException("Invalid gateway IP provided. Either the IP is broadcast or network IP.");
}
if (!NetUtils.isValidIp4(gateway)) {
throw new InvalidParameterValueException("Invalid gateway");
}
if (!NetUtils.isValidIp4Netmask(netmask)) {
throw new InvalidParameterValueException("Invalid netmask");
}
cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
}
checkIpExclusionList(ipExclusionList, cidr, null);
}
if (ipv6) {
// validate the ipv6 CIDR
if (ip6Cidr != null && !NetUtils.isValidIp4Cidr(ip6Cidr)) {
throw new InvalidParameterValueException("Invalid format for the CIDR parameter");
}
if (endIPv6 == null) {
endIPv6 = startIPv6;
}
_networkModel.checkIp6Parameters(startIPv6, endIPv6, ip6Gateway, ip6Cidr);
if (zone.getNetworkType() != NetworkType.Advanced || ntwkOff.getGuestType() != Network.GuestType.Shared) {
throw new InvalidParameterValueException("Can only support create IPv6 network with advance shared network!");
}
}
if (isolatedPvlan != null && (zone.getNetworkType() != NetworkType.Advanced || ntwkOff.getGuestType() != Network.GuestType.Shared)) {
throw new InvalidParameterValueException("Can only support create Private VLAN network with advance shared network!");
}
if (isolatedPvlan != null && ipv6) {
throw new InvalidParameterValueException("Can only support create Private VLAN network with IPv4!");
}
// Regular user can create Guest Isolated Source Nat enabled network only
if (_accountMgr.isNormalUser(caller.getId())
&& (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Isolated
&& areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("Regular user can create a network only from the network offering having traffic type " + TrafficType.Guest
+ " and network type " + Network.GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled");
}
// Don't allow to specify vlan if the caller is a normal user
if (_accountMgr.isNormalUser(caller.getId()) && (ntwkOff.getSpecifyVlan() || vlanId != null)) {
throw new InvalidParameterValueException("Only ROOT admin and domain admins are allowed to specify vlanId");
}
if (ipv4) {
// For non-root admins check cidr limit - if it's allowed by global config value
if (!_accountMgr.isRootAdmin(caller.getId()) && cidr != null) {
final String[] cidrPair = cidr.split("\\/");
final int cidrSize = Integer.parseInt(cidrPair[1]);
if (cidrSize < _cidrLimit) {
throw new InvalidParameterValueException("Cidr size can't be less than " + _cidrLimit);
}
}
}
// Vlan is created in 1 cases - works in Advance zone only:
// 1) GuestType is Shared
boolean createVlan = startIP != null && endIP != null && zone.getNetworkType() == NetworkType.Advanced
&& (ntwkOff.getGuestType() == Network.GuestType.Shared || !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat));
if (!createVlan) {
// Only support advance shared network in IPv6, which means createVlan is a must
if (ipv6) {
createVlan = true;
}
}
// Can add vlan range only to the network which allows it
if (createVlan && !ntwkOff.getSpecifyIpRanges()) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id doesn't support adding multiple ip ranges");
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
if (ntwkOff.getGuestType() != GuestType.Private && gateway == null && cidr != null) {
gateway = NetUtils.getCidrHostAddress(cidr);
}
if (ntwkOff.getGuestType() != GuestType.Private && ip6Gateway == null && ip6Cidr != null) {
ip6Gateway = NetUtils.getCidrHostAddress6(ip6Cidr);
}
Network network = commitNetwork(networkOfferingId, gateway, startIP, endIP, netmask, networkDomain, vlanId, name, displayText, caller, physicalNetworkId, zoneId, domainId,
isDomainSpecific, subdomainAccess, vpcId, startIPv6, endIPv6, ip6Gateway, ip6Cidr, displayNetwork, aclId, isolatedPvlan, ntwkOff, pNtwk, aclType, owner, cidr,
createVlan, dns1, dns2, ipExclusionList);
// if the network offering has persistent set to true, implement the network
if (ntwkOff.getIsPersistent()) {
try {
if (network.getState() == Network.State.Setup) {
s_logger.debug("Network id=" + network.getId() + " is already provisioned");
return network;
}
final DeployDestination dest = new DeployDestination(zone, null, null, null);
final UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
final Journal journal = new Journal.LogJournal("Implementing " + network, s_logger);
final ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(), journal, callerUser, caller);
s_logger.debug("Implementing network " + network + " as a part of network provision for persistent network");
final Pair<? extends NetworkGuru, ? extends Network> implementedNetwork = _networkMgr.implementNetwork(network.getId(), dest, context);
if (implementedNetwork == null || implementedNetwork.first() == null) {
s_logger.warn("Failed to provision the network " + network);
}
network = implementedNetwork.second();
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to implement persistent guest network " + network + "due to: " + ex.getMessage());
final CloudRuntimeException e = new CloudRuntimeException("Failed to implement persistent guest network", ex);
e.addProxyObject(network.getUuid(), "networkId");
throw e;
}
}
return network;
}
private void checkIpExclusionList(final String ipExclusionList, final String cidr, final List<NicVO> nicsPresent) {
if (StringUtils.isNotBlank(ipExclusionList)) {
// validate ipExclusionList
// Perform a "syntax" check on the list
if (!NetUtils.validIpRangeList(ipExclusionList)) {
throw new InvalidParameterValueException("Syntax error in ipExclusionList");
}
final List<String> excludedIps = NetUtils.getAllIpsFromRangeList(ipExclusionList);
if (cidr != null) {
//Check that ipExclusionList (delimiters) is within the CIDR
if (!NetUtils.isIpRangeListInCidr(ipExclusionList, cidr)) {
throw new InvalidParameterValueException("An IP in the ipExclusionList is not part of the CIDR of the network " + cidr);
}
//Check that at least one IP is available after exclusion for the router interface
final SortedSet<Long> allPossibleIps = NetUtils.getAllIpsFromCidr(cidr, NetUtils.listIp2LongList(excludedIps));
if (allPossibleIps.isEmpty()) {
throw new InvalidParameterValueException("The ipExclusionList excludes all IPs in the CIDR; at least one needs to be available");
}
}
if (nicsPresent != null) {
// Check that no existing nics/ips are part of the exclusion list
for (final NicVO nic : nicsPresent) {
final String nicIp = nic.getIPv4Address();
//check if nic IP is exclusionList
if (excludedIps.contains(nicIp) && !(Nic.State.Deallocating.equals(nic.getState()))) {
throw new InvalidParameterValueException("Active IP " + nic.getIPv4Address() + " exist in ipExclusionList.");
}
}
}
}
}
@Override
public Pair<List<? extends Network>, Integer> searchForNetworks(final ListNetworksCmd cmd) {
final Long id = cmd.getId();
final String keyword = cmd.getKeyword();
final Long zoneId = cmd.getZoneId();
final Account caller = CallContext.current().getCallingAccount();
Long domainId = cmd.getDomainId();
final String accountName = cmd.getAccountName();
final String guestIpType = cmd.getGuestIpType();
final String trafficType = cmd.getTrafficType();
Boolean isSystem = cmd.getIsSystem();
final String aclType = cmd.getAclType();
final Long projectId = cmd.getProjectId();
final List<Long> permittedAccounts = new ArrayList<>();
String path = null;
final Long physicalNetworkId = cmd.getPhysicalNetworkId();
final List<String> supportedServicesStr = cmd.getSupportedServices();
final Boolean restartRequired = cmd.getRestartRequired();
final boolean listAll = cmd.listAll();
boolean isRecursive = cmd.isRecursive();
final Boolean specifyIpRanges = cmd.getSpecifyIpRanges();
final Long vpcId = cmd.getVpcId();
final Boolean canUseForDeploy = cmd.canUseForDeploy();
final Map<String, String> tags = cmd.getTags();
final Boolean forVpc = cmd.getForVpc();
final Boolean display = cmd.getDisplay();
// 1) default is system to false if not specified
// 2) reset parameter to false if it's specified by the regular user
if ((isSystem == null || _accountMgr.isNormalUser(caller.getId())) && id == null) {
isSystem = false;
}
// Account/domainId parameters and isSystem are mutually exclusive
if (isSystem != null && isSystem && (accountName != null || domainId != null)) {
throw new InvalidParameterValueException("System network belongs to system, account and domainId parameters can't be specified");
}
if (domainId != null) {
final DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
// see DomainVO.java
throw new InvalidParameterValueException("Specified domain id doesn't exist in the system");
}
_accountMgr.checkAccess(caller, domain);
if (accountName != null) {
final Account owner = _accountMgr.getActiveAccountByName(accountName, domainId);
if (owner == null) {
// see DomainVO.java
throw new InvalidParameterValueException("Unable to find account " + accountName + " in specified domain");
}
_accountMgr.checkAccess(caller, null, true, owner);
permittedAccounts.add(owner.getId());
}
}
if (!_accountMgr.isAdmin(caller.getId()) || projectId != null && projectId.longValue() != -1 && domainId == null) {
permittedAccounts.add(caller.getId());
domainId = caller.getDomainId();
}
// set project information
boolean skipProjectNetworks = true;
if (projectId != null) {
if (projectId.longValue() == -1) {
if (!_accountMgr.isAdmin(caller.getId())) {
permittedAccounts.addAll(_projectMgr.listPermittedProjectAccounts(caller.getId()));
}
} else {
permittedAccounts.clear();
final Project project = _projectMgr.getProject(projectId);
if (project == null) {
throw new InvalidParameterValueException("Unable to find project by specified id");
}
if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) {
// getProject() returns type ProjectVO.
final InvalidParameterValueException ex = new InvalidParameterValueException("Account " + caller + " cannot access specified project id");
ex.addProxyObject(project.getUuid(), "projectId");
throw ex;
}
//add project account
permittedAccounts.add(project.getProjectAccountId());
//add caller account (if admin)
if (_accountMgr.isAdmin(caller.getId())) {
permittedAccounts.add(caller.getId());
}
}
skipProjectNetworks = false;
}
if (domainId != null) {
path = _domainDao.findById(domainId).getPath();
} else {
path = _domainDao.findById(caller.getDomainId()).getPath();
}
if (listAll && domainId == null) {
isRecursive = true;
}
final Filter searchFilter = new Filter(NetworkVO.class, "id", false, null, null);
final SearchBuilder<NetworkVO> sb = _networksDao.createSearchBuilder();
if (forVpc != null) {
if (forVpc) {
sb.and("vpc", sb.entity().getVpcId(), Op.NNULL);
} else {
sb.and("vpc", sb.entity().getVpcId(), Op.NULL);
}
}
// Don't display networks created of system network offerings
final SearchBuilder<NetworkOfferingVO> networkOfferingSearch = _networkOfferingDao.createSearchBuilder();
networkOfferingSearch.and("systemOnly", networkOfferingSearch.entity().isSystemOnly(), SearchCriteria.Op.EQ);
if (isSystem != null && isSystem) {
networkOfferingSearch.and("trafficType", networkOfferingSearch.entity().getTrafficType(), SearchCriteria.Op.EQ);
}
sb.join("networkOfferingSearch", networkOfferingSearch, sb.entity().getNetworkOfferingId(), networkOfferingSearch.entity().getId(), JoinBuilder.JoinType.INNER);
final SearchBuilder<DataCenterVO> zoneSearch = _dcDao.createSearchBuilder();
zoneSearch.and("networkType", zoneSearch.entity().getNetworkType(), SearchCriteria.Op.EQ);
sb.join("zoneSearch", zoneSearch, sb.entity().getDataCenterId(), zoneSearch.entity().getId(), JoinBuilder.JoinType.INNER);
sb.and("removed", sb.entity().getRemoved(), Op.NULL);
if (tags != null && !tags.isEmpty()) {
final SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
for (int count = 0; count < tags.size(); count++) {
tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
tagSearch.cp();
}
tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
sb.groupBy(sb.entity().getId());
sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
}
if (permittedAccounts.isEmpty()) {
final SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder();
domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
}
final SearchBuilder<AccountVO> accountSearch = _accountDao.createSearchBuilder();
accountSearch.and("typeNEQ", accountSearch.entity().getType(), SearchCriteria.Op.NEQ);
accountSearch.and("typeEQ", accountSearch.entity().getType(), SearchCriteria.Op.EQ);
sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER);
List<NetworkVO> networksToReturn = new ArrayList<>();
if (isSystem == null || !isSystem) {
if (!permittedAccounts.isEmpty()) {
//get account level networks
networksToReturn.addAll(listAccountSpecificNetworks(
buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired,
specifyIpRanges, vpcId, tags, display), searchFilter, permittedAccounts));
//get domain level networks
if (domainId != null) {
networksToReturn.addAll(listDomainLevelNetworks(
buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, restartRequired,
specifyIpRanges, vpcId, tags, display), searchFilter, domainId, false));
}
} else {
//add account specific networks
networksToReturn.addAll(listAccountSpecificNetworksByDomainPath(
buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired,
specifyIpRanges, vpcId, tags, display), searchFilter, path, isRecursive));
//add domain specific networks of domain + parent domains
networksToReturn.addAll(listDomainSpecificNetworksByDomainPath(
buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired,
specifyIpRanges, vpcId, tags, display), searchFilter, path, isRecursive));
//add networks of subdomains
if (domainId == null) {
networksToReturn.addAll(listDomainLevelNetworks(
buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, restartRequired,
specifyIpRanges, vpcId, tags, display), searchFilter, caller.getDomainId(), true));
}
}
} else {
networksToReturn = _networksDao.search(
buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, null, skipProjectNetworks, restartRequired,
specifyIpRanges, vpcId, tags, display), searchFilter);
}
if (supportedServicesStr != null && !supportedServicesStr.isEmpty() && !networksToReturn.isEmpty()) {
final List<NetworkVO> supportedNetworks = new ArrayList<>();
final Service[] suppportedServices = new Service[supportedServicesStr.size()];
int i = 0;
for (final String supportedServiceStr : supportedServicesStr) {
final Service service = Service.getService(supportedServiceStr);
if (service == null) {
throw new InvalidParameterValueException("Invalid service specified " + supportedServiceStr);
} else {
suppportedServices[i] = service;
}
i++;
}
for (final NetworkVO network : networksToReturn) {
if (areServicesSupportedInNetwork(network.getId(), suppportedServices)) {
supportedNetworks.add(network);
}
}
networksToReturn = supportedNetworks;
}
if (canUseForDeploy != null) {
final List<NetworkVO> networksForDeploy = new ArrayList<>();
for (final NetworkVO network : networksToReturn) {
if (_networkModel.canUseForDeploy(network) == canUseForDeploy) {
networksForDeploy.add(network);
}
}
networksToReturn = networksForDeploy;
}
//Now apply pagination
final List<? extends Network> wPagination = StringUtils.applyPagination(networksToReturn, cmd.getStartIndex(), cmd.getPageSizeVal());
if (wPagination != null) {
final Pair<List<? extends Network>, Integer> listWPagination = new Pair<>(wPagination, networksToReturn.size());
return listWPagination;
}
return new Pair<>(networksToReturn, networksToReturn.size());
}
private List<NetworkVO> listAccountSpecificNetworks(final SearchCriteria<NetworkVO> sc, final Filter searchFilter, final List<Long> permittedAccounts) {
final SearchCriteria<NetworkVO> accountSC = _networksDao.createSearchCriteria();
if (!permittedAccounts.isEmpty()) {
accountSC.addAnd("accountId", SearchCriteria.Op.IN, permittedAccounts.toArray());
}
accountSC.addAnd("aclType", SearchCriteria.Op.EQ, ACLType.Account.toString());
sc.addAnd("id", SearchCriteria.Op.SC, accountSC);
return _networksDao.search(sc, searchFilter);
}
private SearchCriteria<NetworkVO> buildNetworkSearchCriteria(final SearchBuilder<NetworkVO> sb, final String keyword, final Long id, final Boolean isSystem, final Long
zoneId, final String guestIpType,
final String trafficType, final Long physicalNetworkId, final String aclType, final boolean skipProjectNetworks,
final Boolean restartRequired, final Boolean specifyIpRanges, final Long vpcId,
final Map<String, String> tags, final Boolean display) {
final SearchCriteria<NetworkVO> sc = sb.create();
if (isSystem != null) {
sc.setJoinParameters("networkOfferingSearch", "systemOnly", isSystem);
}
if (keyword != null) {
final SearchCriteria<NetworkVO> ssc = _networksDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (display != null) {
sc.addAnd("displayNetwork", SearchCriteria.Op.EQ, display);
}
if (id != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, id);
}
if (zoneId != null) {
sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
}
if (guestIpType != null) {
sc.addAnd("guestType", SearchCriteria.Op.EQ, guestIpType);
}
if (trafficType != null) {
sc.addAnd("trafficType", SearchCriteria.Op.EQ, trafficType);
}
if (aclType != null) {
sc.addAnd("aclType", SearchCriteria.Op.EQ, aclType.toString());
}
if (physicalNetworkId != null) {
sc.addAnd("physicalNetworkId", SearchCriteria.Op.EQ, physicalNetworkId);
}
if (skipProjectNetworks) {
sc.setJoinParameters("accountSearch", "typeNEQ", Account.ACCOUNT_TYPE_PROJECT);
} else {
sc.setJoinParameters("accountSearch", "typeEQ", Account.ACCOUNT_TYPE_PROJECT);
}
if (restartRequired != null) {
sc.addAnd("restartRequired", SearchCriteria.Op.EQ, restartRequired);
}
if (specifyIpRanges != null) {
sc.addAnd("specifyIpRanges", SearchCriteria.Op.EQ, specifyIpRanges);
}
if (vpcId != null) {
sc.addAnd("vpcId", SearchCriteria.Op.EQ, vpcId);
}
if (tags != null && !tags.isEmpty()) {
int count = 0;
sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.Network.toString());
for (final Map.Entry<String, String> entry : tags.entrySet()) {
sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), entry.getKey());
sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), entry.getValue());
count++;
}
}
return sc;
}
private List<NetworkVO> listDomainLevelNetworks(final SearchCriteria<NetworkVO> sc, final Filter searchFilter, final long domainId, final boolean parentDomainsOnly) {
final List<Long> networkIds = new ArrayList<>();
final Set<Long> allowedDomains = _domainMgr.getDomainParentIds(domainId);
final List<NetworkDomainVO> maps = _networkDomainDao.listDomainNetworkMapByDomain(allowedDomains.toArray());
for (final NetworkDomainVO map : maps) {
if (map.getDomainId() == domainId && parentDomainsOnly) {
continue;
}
final boolean subdomainAccess = map.isSubdomainAccess() != null ? map.isSubdomainAccess() : getAllowSubdomainAccessGlobal();
if (map.getDomainId() == domainId || subdomainAccess) {
networkIds.add(map.getNetworkId());
}
}
if (!networkIds.isEmpty()) {
final SearchCriteria<NetworkVO> domainSC = _networksDao.createSearchCriteria();
domainSC.addAnd("id", SearchCriteria.Op.IN, networkIds.toArray());
domainSC.addAnd("aclType", SearchCriteria.Op.EQ, ACLType.Domain.toString());
sc.addAnd("id", SearchCriteria.Op.SC, domainSC);
return _networksDao.search(sc, searchFilter);
} else {
return new ArrayList<>();
}
}
private List<NetworkVO> listAccountSpecificNetworksByDomainPath(final SearchCriteria<NetworkVO> sc, final Filter searchFilter, final String path, final boolean isRecursive) {
final SearchCriteria<NetworkVO> accountSC = _networksDao.createSearchCriteria();
accountSC.addAnd("aclType", SearchCriteria.Op.EQ, ACLType.Account.toString());
if (path != null) {
if (isRecursive) {
sc.setJoinParameters("domainSearch", "path", path + "%");
} else {
sc.setJoinParameters("domainSearch", "path", path);
}
}
sc.addAnd("id", SearchCriteria.Op.SC, accountSC);
return _networksDao.search(sc, searchFilter);
}
private List<NetworkVO> listDomainSpecificNetworksByDomainPath(final SearchCriteria<NetworkVO> sc, final Filter searchFilter, final String path, final boolean isRecursive) {
Set<Long> allowedDomains = new HashSet<>();
if (path != null) {
if (isRecursive) {
allowedDomains = _domainMgr.getDomainChildrenIds(path);
} else {
final Domain domain = _domainDao.findDomainByPath(path);
allowedDomains.add(domain.getId());
}
}
final List<Long> networkIds = new ArrayList<>();
final List<NetworkDomainVO> maps = _networkDomainDao.listDomainNetworkMapByDomain(allowedDomains.toArray());
for (final NetworkDomainVO map : maps) {
networkIds.add(map.getNetworkId());
}
if (!networkIds.isEmpty()) {
final SearchCriteria<NetworkVO> domainSC = _networksDao.createSearchCriteria();
domainSC.addAnd("id", SearchCriteria.Op.IN, networkIds.toArray());
domainSC.addAnd("aclType", SearchCriteria.Op.EQ, ACLType.Domain.toString());
sc.addAnd("id", SearchCriteria.Op.SC, domainSC);
return _networksDao.search(sc, searchFilter);
} else {
return new ArrayList<>();
}
}
protected boolean areServicesSupportedInNetwork(final long networkId, final Service... services) {
return _ntwkSrvcDao.areServicesSupportedInNetwork(networkId, services);
}
private boolean getAllowSubdomainAccessGlobal() {
return _allowSubdomainNetworkAccess;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_DELETE, eventDescription = "deleting network", async = true)
public boolean deleteNetwork(final long networkId, final boolean forced) {
final Account caller = CallContext.current().getCallingAccount();
// Verify network id
final NetworkVO network = _networksDao.findById(networkId);
if (network == null) {
// see NetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("unable to find network with specified id");
ex.addProxyObject(String.valueOf(networkId), "networkId");
throw ex;
}
// don't allow to delete system network
if (isNetworkSystem(network)) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Network with specified id is system and can't be removed");
ex.addProxyObject(network.getUuid(), "networkId");
throw ex;
}
final Account owner = _accountMgr.getAccount(network.getAccountId());
// Only Admin can delete Shared networks
if (network.getGuestType() == GuestType.Shared && !_accountMgr.isAdmin(caller.getId())) {
throw new InvalidParameterValueException("Only Admins can delete network with guest type " + GuestType.Shared);
}
// Perform permission check
_accountMgr.checkAccess(caller, null, true, network);
if (forced && !_accountMgr.isRootAdmin(caller.getId())) {
throw new InvalidParameterValueException("Delete network with 'forced' option can only be called by root admins");
}
// VPC networks should be checked for static routes before deletion
if (network.getVpcId() != null) {
// don't allow to remove network tier when there are static routes pointing to an ipaddress in the tier CIDR.
final List<? extends StaticRoute> routes = _staticRouteDao.listByVpcIdAndNotRevoked(network.getVpcId());
for (final StaticRoute route : routes) {
if (NetUtils.isIpWithtInCidrRange(route.getGwIpAddress(), network.getCidr())) {
throw new CloudRuntimeException("Can't delete network " + network.getName() + " as it has static routes " +
"applied pointing to the CIDR of the network (" + network.getCidr() + "). Example static route: " +
route.getCidr() + " to " + route.getGwIpAddress() + ". Please remove all the routes pointing to the " +
"network tier CIDR before attempting to delete it.");
}
}
}
final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
final ReservationContext context = new ReservationContextImpl(null, null, callerUser, owner);
return _networkMgr.destroyNetwork(networkId, context, forced);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_RESTART, eventDescription = "restarting network", async = true)
public boolean restartNetwork(final RestartNetworkCmd cmd, final boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException {
// This method restarts all network elements belonging to the network and re-applies all the rules
final Long networkId = cmd.getNetworkId();
final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
final Account callerAccount = _accountMgr.getActiveAccountById(callerUser.getAccountId());
// Check if network exists
final NetworkVO network = _networksDao.findById(networkId);
if (network == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Network with specified id doesn't exist");
ex.addProxyObject(networkId.toString(), "networkId");
throw ex;
}
// Don't allow to restart network if it's not in Implemented/Setup state
if (!(network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup)) {
throw new InvalidParameterValueException("Network is not in the right state to be restarted. Correct states are: " + Network.State.Implemented + ", "
+ Network.State.Setup);
}
_accountMgr.checkAccess(callerAccount, null, true, network);
final boolean success = _networkMgr.restartNetwork(networkId, callerAccount, callerUser, cleanup);
if (success) {
s_logger.debug("Network id=" + networkId + " is restarted successfully.");
} else {
s_logger.warn("Network id=" + networkId + " failed to restart.");
}
return success;
}
@Override
@DB
public Network getNetwork(final long id) {
return _networksDao.findById(id);
}
@Override
public Network getNetwork(final String networkUuid) {
return _networksDao.findByUuid(networkUuid);
}
@Override
public IpAddress getIp(final long ipAddressId) {
return _ipAddressDao.findById(ipAddressId);
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_UPDATE, eventDescription = "updating network", async = true)
public Network updateGuestNetwork(final long networkId, final String name, final String displayText, final Account callerAccount, final User callerUser,
final String domainSuffix, final Long networkOfferingId, final Boolean changeCidr, final String guestVmCidr, final Boolean displayNetwork,
final String customId, final String dns1, final String dns2, final String ipExclusionList) {
// verify input parameters
final NetworkVO network = _networksDao.findById(networkId);
if (network == null) {
// see NetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified network id doesn't exist in the system");
ex.addProxyObject(String.valueOf(networkId), "networkId");
throw ex;
}
//perform below validation if the network is vpc network
if (network.getVpcId() != null && networkOfferingId != null) {
final Vpc vpc = _entityMgr.findById(Vpc.class, network.getVpcId());
_vpcMgr.validateNtwkOffForNtwkInVpc(networkId, networkOfferingId, null, null, vpc, null, _accountMgr.getAccount(network.getAccountId()), null);
}
// don't allow to update network in Destroy state
if (network.getState() == Network.State.Destroy) {
throw new InvalidParameterValueException("Don't allow to update network in state " + Network.State.Destroy);
}
// Don't allow to update system network
final NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId());
if (offering.isSystemOnly()) {
throw new InvalidParameterValueException("Can't update system networks");
}
// allow to upgrade only Guest networks
if (network.getTrafficType() != Networks.TrafficType.Guest) {
throw new InvalidParameterValueException("Can't allow networks which traffic type is not " + TrafficType.Guest);
}
_accountMgr.checkAccess(callerAccount, null, true, network);
if (name != null) {
network.setName(name);
}
if (displayText != null) {
network.setDisplayText(displayText);
}
if (customId != null) {
network.setUuid(customId);
}
if (dns1 != null) {
network.setDns1(dns1);
}
if (dns2 != null) {
network.setDns2(dns2);
}
if (ipExclusionList != null) {
String networkCidr = null;
if (guestVmCidr == null) {
networkCidr = network.getNetworkCidr();
}
final List<NicVO> nicsPresent = _nicDao.listByNetworkId(networkId);
checkIpExclusionList(ipExclusionList, networkCidr, nicsPresent);
network.setIpExclusionList(ipExclusionList);
}
// display flag is not null and has changed
if (displayNetwork != null && displayNetwork != network.getDisplayNetwork()) {
// Update resource count if it needs to be updated
final NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());
if (_networkMgr.resourceCountNeedsUpdate(networkOffering, network.getAclType())) {
_resourceLimitMgr.changeResourceCount(network.getAccountId(), Resource.ResourceType.network, displayNetwork);
}
network.setDisplayNetwork(displayNetwork);
}
// network offering and domain suffix can be updated for Isolated networks only in 3.0
if ((networkOfferingId != null || domainSuffix != null) && network.getGuestType() != GuestType.Isolated) {
throw new InvalidParameterValueException("NetworkOffering and domain suffix upgrade can be perfomed for Isolated networks only");
}
boolean networkOfferingChanged = false;
final long oldNetworkOfferingId = network.getNetworkOfferingId();
final NetworkOffering oldNtwkOff = _networkOfferingDao.findByIdIncludingRemoved(oldNetworkOfferingId);
final NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId);
if (networkOfferingId != null) {
if (networkOffering == null || networkOffering.isSystemOnly()) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering with specified id");
ex.addProxyObject(networkOfferingId.toString(), "networkOfferingId");
throw ex;
}
// network offering should be in Enabled state
if (networkOffering.getState() != NetworkOffering.State.Enabled) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id is not in " + NetworkOffering.State.Enabled
+ " state, can't upgrade to it");
ex.addProxyObject(networkOffering.getUuid(), "networkOfferingId");
throw ex;
}
//can't update from vpc to non-vpc network offering
final boolean forVpcNew = _configMgr.isOfferingForVpc(networkOffering);
final boolean vorVpcOriginal = _configMgr.isOfferingForVpc(_entityMgr.findById(NetworkOffering.class, oldNetworkOfferingId));
if (forVpcNew != vorVpcOriginal) {
final String errMsg = forVpcNew ? "a vpc offering " : "not a vpc offering";
throw new InvalidParameterValueException("Can't update as the new offering is " + errMsg);
}
if (networkOfferingId != oldNetworkOfferingId) {
if (changeCidr) {
if (!checkForNonStoppedVmInNetwork(network.getId())) {
final InvalidParameterValueException ex = new InvalidParameterValueException("All user vm of network of specified id should be stopped before changing " +
"CIDR!");
ex.addProxyObject(network.getUuid(), "networkId");
throw ex;
}
}
// check if the network is upgradable
if (!canUpgrade(network, oldNetworkOfferingId, networkOfferingId)) {
throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNtwkOff.getUuid() + " to " + networkOffering.getUuid()
+ "; check logs for more information");
}
networkOfferingChanged = true;
//Setting the new network's isRedundant to the new network offering's RedundantRouter.
network.setIsRedundant(_networkOfferingDao.findById(networkOfferingId).getRedundantRouter());
}
}
final Map<String, String> newSvcProviders = networkOfferingChanged ? _networkMgr.finalizeServicesAndProvidersForNetwork(
_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()) : new HashMap<>();
// don't allow to modify network domain if the service is not supported
if (domainSuffix != null) {
// validate network domain
if (!NetUtils.verifyDomainName(domainSuffix)) {
throw new InvalidParameterValueException(
"Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters " +
"'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
long offeringId = oldNetworkOfferingId;
if (networkOfferingId != null) {
offeringId = networkOfferingId;
}
final Map<Network.Capability, String> dnsCapabilities = getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, offeringId), Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
// TBD: use uuid instead of networkOfferingId. May need to hardcode tablename in call to addProxyObject().
throw new InvalidParameterValueException("Domain name change is not supported by the network offering id=" + networkOfferingId);
}
network.setNetworkDomain(domainSuffix);
}
//IP reservation checks
// allow reservation only to Isolated Guest networks
final DataCenter dc = _dcDao.findById(network.getDataCenterId());
final String networkCidr = network.getNetworkCidr();
if (guestVmCidr != null) {
if (dc.getNetworkType() == NetworkType.Basic) {
throw new InvalidParameterValueException("Guest VM CIDR can't be specified for zone with " + NetworkType.Basic + " networking");
}
if (network.getGuestType() != GuestType.Isolated) {
throw new InvalidParameterValueException("Can only allow IP Reservation in networks with guest type " + GuestType.Isolated);
}
if (networkOfferingChanged == true) {
throw new InvalidParameterValueException("Cannot specify this network offering change and guestVmCidr at same time. Specify only one.");
}
if (!(network.getState() == Network.State.Implemented)) {
throw new InvalidParameterValueException("The network must be in " + Network.State.Implemented + " state. IP Reservation cannot be applied in "
+ network.getState() + " state");
}
if (!NetUtils.isValidIp4Cidr(guestVmCidr)) {
throw new InvalidParameterValueException("Invalid format of Guest VM CIDR.");
}
if (!NetUtils.validateGuestCidr(guestVmCidr)) {
throw new InvalidParameterValueException("Invalid format of Guest VM CIDR. Make sure it is RFC1918 compliant. ");
}
// If networkCidr is null it implies that there was no prior IP reservation, so the network cidr is network.getCidr()
// But in case networkCidr is a non null value (IP reservation already exists), it implies network cidr is networkCidr
if (networkCidr != null) {
if (!NetUtils.isNetworkAWithinNetworkB(guestVmCidr, networkCidr)) {
throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR should be a subset of network CIDR : "
+ networkCidr);
}
} else {
if (!NetUtils.isNetworkAWithinNetworkB(guestVmCidr, network.getCidr())) {
throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR should be a subset of network CIDR : "
+ network.getCidr());
}
}
// This check makes sure there are no active IPs existing outside the guestVmCidr in the network
final String[] guestVmCidrPair = guestVmCidr.split("\\/");
final Long size = Long.valueOf(guestVmCidrPair[1]);
final List<NicVO> nicsPresent = _nicDao.listByNetworkId(networkId);
final String cidrIpRange[] = NetUtils.getIpRangeFromCidr(guestVmCidrPair[0], size);
s_logger.info("The start IP of the specified guest vm cidr is: " + cidrIpRange[0] + " and end IP is: " + cidrIpRange[1]);
final long startIp = NetUtils.ip2Long(cidrIpRange[0]);
final long endIp = NetUtils.ip2Long(cidrIpRange[1]);
final long range = endIp - startIp + 1;
s_logger.info("The specified guest vm cidr has " + range + " IPs");
for (final NicVO nic : nicsPresent) {
final long nicIp = NetUtils.ip2Long(nic.getIPv4Address());
//check if nic IP is outside the guest vm cidr
if (nicIp < startIp || nicIp > endIp) {
if (!(nic.getState() == Nic.State.Deallocating)) {
throw new InvalidParameterValueException("Active IPs like " + nic.getIPv4Address() + " exist outside the Guest VM CIDR. Cannot apply reservation ");
}
}
}
// In some scenarios even though guesVmCidr and network CIDR do not appear similar but
// the IP ranges exactly matches, in these special cases make sure no Reservation gets applied
if (network.getNetworkCidr() == null) {
if (NetUtils.isSameIpRange(guestVmCidr, network.getCidr()) && !guestVmCidr.equals(network.getCidr())) {
throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and CIDR: " + network.getCidr() + " are same, "
+ "even though both the cidrs appear to be different. As a precaution no IP Reservation will be applied.");
}
} else {
if (NetUtils.isSameIpRange(guestVmCidr, network.getNetworkCidr()) && !guestVmCidr.equals(network.getNetworkCidr())) {
throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and Network CIDR: " + network.getNetworkCidr()
+ " are same, "
+ "even though both the cidrs appear to be different. As a precaution IP Reservation will not be affected. If you want to reset IP Reservation, "
+ "specify guestVmCidr to be: " + network.getNetworkCidr());
}
}
// When reservation is applied for the first time, network_cidr will be null
// Populate it with the actual network cidr
if (network.getNetworkCidr() == null) {
network.setNetworkCidr(network.getCidr());
}
// Condition for IP Reservation reset : guestVmCidr and network CIDR are same
if (network.getNetworkCidr().equals(guestVmCidr)) {
s_logger.warn("Guest VM CIDR and Network CIDR both are same, reservation will reset.");
network.setNetworkCidr(null);
}
checkIpExclusionList(ipExclusionList, guestVmCidr, null);
// Finally update "cidr" with the guestVmCidr
// which becomes the effective address space for CloudStack guest VMs
network.setCidr(guestVmCidr);
_networksDao.update(networkId, network);
s_logger.info("IP Reservation has been applied. The new CIDR for Guests Vms is " + guestVmCidr);
}
final ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount);
if (networkOfferingId != null) {
if (networkOfferingChanged) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
network.setNetworkOfferingId(networkOfferingId);
_networksDao.update(networkId, network, newSvcProviders);
// get all nics using this network
// log remove usage events for old offering
// log assign usage events for new offering
final List<NicVO> nics = _nicDao.listByNetworkId(networkId);
for (final NicVO nic : nics) {
final long vmId = nic.getInstanceId();
final VMInstanceVO vm = _vmDao.findById(vmId);
if (vm == null) {
s_logger.error("Vm for nic " + nic.getId() + " not found with Vm Id:" + vmId);
continue;
}
}
}
});
} else {
network.setNetworkOfferingId(networkOfferingId);
_networksDao.update(networkId, network,
_networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()));
}
} else {
_networksDao.update(networkId, network);
}
// if network has been upgraded from a non persistent ntwk offering to a persistent ntwk offering, implement the network if its not already
if (networkOfferingChanged && !oldNtwkOff.getIsPersistent() && networkOffering.getIsPersistent()) {
if (network.getState() == Network.State.Allocated) {
try {
final DeployDestination dest = new DeployDestination(zoneRepository.findById(network.getDataCenterId()).orElse(null), null, null, null);
_networkMgr.implementNetwork(network.getId(), dest, context);
} catch (final Exception ex) {
s_logger.warn("Failed to implement network " + network + " elements and resources as a part o" + "f network update due to ", ex);
final CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified" + " id) elements and resources as a part of network " +
"update");
e.addProxyObject(network.getUuid(), "networkId");
throw e;
}
}
}
return getNetwork(network.getId());
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_CREATE, eventDescription = "Creating Physical Network", create = true)
public PhysicalNetwork createPhysicalNetwork(final Long zoneId, final String vnetRange, final String networkSpeed, final List<String> isolationMethods,
final String broadcastDomainRangeStr, final Long domainId, final List<String> tags, final String name) {
// Check if zone exists
if (zoneId == null) {
throw new InvalidParameterValueException("Please specify a valid zone.");
}
final Zone zone = zoneRepository.findById(zoneId).orElse(null);
if (zone == null) {
throw new InvalidParameterValueException("Please specify a valid zone.");
}
if (AllocationState.Enabled == zone.getAllocationState()) {
// TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject().
throw new PermissionDeniedException("Cannot create PhysicalNetwork since the Zone is currently enabled, zone Id: " + zoneId);
}
final NetworkType zoneType = zone.getNetworkType();
if (zoneType == NetworkType.Basic) {
if (!_physicalNetworkDao.listByZone(zoneId).isEmpty()) {
// TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject().
throw new CloudRuntimeException("Cannot add the physical network to basic zone id: " + zoneId + ", there is a physical network already existing in this basic " +
"Zone");
}
}
if (tags != null && tags.size() > 1) {
throw new InvalidParameterException("Only one tag can be specified for a physical network at this time");
}
if (isolationMethods != null && isolationMethods.size() > 1) {
throw new InvalidParameterException("Only one isolationMethod can be specified for a physical network at this time");
}
if (vnetRange != null) {
// Verify zone type
if (zoneType == NetworkType.Basic) {
throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zoneType + " network");
}
}
BroadcastDomainRange broadcastDomainRange = null;
if (broadcastDomainRangeStr != null && !broadcastDomainRangeStr.isEmpty()) {
try {
broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.valueOf(broadcastDomainRangeStr.toUpperCase());
} catch (final IllegalArgumentException ex) {
throw new InvalidParameterValueException("Unable to resolve broadcastDomainRange '" + broadcastDomainRangeStr + "' to a supported value {Pod or Zone}");
}
// in Acton release you can specify only Zone broadcastdomain type in Advance zone, and Pod in Basic
if (zoneType == NetworkType.Basic && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.POD) {
throw new InvalidParameterValueException("Basic zone can have broadcast domain type of value " + BroadcastDomainRange.POD + " only");
} else if (zoneType == NetworkType.Advanced && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.ZONE) {
throw new InvalidParameterValueException("Advance zone can have broadcast domain type of value " + BroadcastDomainRange.ZONE + " only");
}
}
if (broadcastDomainRange == null) {
if (zoneType == NetworkType.Basic) {
broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.POD;
} else {
broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.ZONE;
}
}
try {
final BroadcastDomainRange broadcastDomainRangeFinal = broadcastDomainRange;
return Transaction.execute(new TransactionCallback<PhysicalNetworkVO>() {
@Override
public PhysicalNetworkVO doInTransaction(final TransactionStatus status) {
// Create the new physical network in the database
final long id = _physicalNetworkDao.getNextInSequence(Long.class, "id");
PhysicalNetworkVO pNetwork = new PhysicalNetworkVO(id, zoneId, vnetRange, networkSpeed, domainId, broadcastDomainRangeFinal, name);
pNetwork.setTags(tags);
pNetwork.setIsolationMethods(isolationMethods);
pNetwork = _physicalNetworkDao.persist(pNetwork);
// Add vnet entries for the new zone if zone type is Advanced
if (vnetRange != null) {
addOrRemoveVnets(vnetRange.split(","), pNetwork);
}
// add VirtualRouter as the default network service provider
addDefaultVirtualRouterToPhysicalNetwork(pNetwork.getId());
// add VPCVirtualRouter as the default network service provider
addDefaultVpcVirtualRouterToPhysicalNetwork(pNetwork.getId());
return pNetwork;
}
});
} catch (final Exception ex) {
s_logger.warn("Exception: ", ex);
throw new CloudRuntimeException("Fail to create a physical network");
}
}
@Override
public Pair<List<? extends PhysicalNetwork>, Integer> searchPhysicalNetworks(final Long id, final Long zoneId, final String keyword, final Long startIndex, final Long
pageSize, final String name) {
final Filter searchFilter = new Filter(PhysicalNetworkVO.class, "id", Boolean.TRUE, startIndex, pageSize);
final SearchCriteria<PhysicalNetworkVO> sc = _physicalNetworkDao.createSearchCriteria();
if (id != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, id);
}
if (zoneId != null) {
sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
}
if (name != null) {
sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%");
}
final Pair<List<PhysicalNetworkVO>, Integer> result = _physicalNetworkDao.searchAndCount(sc, searchFilter);
return new Pair<>(result.first(), result.second());
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_UPDATE, eventDescription = "updating physical network", async = true)
public PhysicalNetwork updatePhysicalNetwork(final Long id, final String networkSpeed, final List<String> tags, final String newVnetRange, final String state) {
// verify input parameters
final PhysicalNetworkVO network = _physicalNetworkDao.findById(id);
if (network == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system");
ex.addProxyObject(id.toString(), "physicalNetworkId");
throw ex;
}
// if zone is of Basic type, don't allow to add vnet range
final DataCenter zone = _dcDao.findById(network.getDataCenterId());
if (zone == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Zone with id=" + network.getDataCenterId() + " doesn't exist in the system");
ex.addProxyObject(String.valueOf(network.getDataCenterId()), "dataCenterId");
throw ex;
}
if (newVnetRange != null) {
if (zone.getNetworkType() == NetworkType.Basic) {
throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zone.getNetworkType() + " network");
}
}
if (tags != null && tags.size() > 1) {
throw new InvalidParameterException("Unable to support more than one tag on network yet");
}
PhysicalNetwork.State networkState = null;
if (state != null && !state.isEmpty()) {
try {
networkState = PhysicalNetwork.State.valueOf(state);
} catch (final IllegalArgumentException ex) {
throw new InvalidParameterValueException("Unable to resolve state '" + state + "' to a supported value {Enabled or Disabled}");
}
}
if (state != null) {
network.setState(networkState);
}
if (tags != null) {
network.setTags(tags);
}
if (networkSpeed != null) {
network.setSpeed(networkSpeed);
}
if (newVnetRange != null) {
final String[] listOfRanges = newVnetRange.split(",");
addOrRemoveVnets(listOfRanges, network);
}
_physicalNetworkDao.update(id, network);
return network;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_DELETE, eventDescription = "deleting physical network", async = true)
@DB
public boolean deletePhysicalNetwork(final Long physicalNetworkId) {
// verify input parameters
final PhysicalNetworkVO pNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (pNetwork == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system");
ex.addProxyObject(physicalNetworkId.toString(), "physicalNetworkId");
throw ex;
}
checkIfPhysicalNetworkIsDeletable(physicalNetworkId);
return Transaction.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(final TransactionStatus status) {
// delete vlans for this zone
final List<VlanVO> vlans = _vlanDao.listVlansByPhysicalNetworkId(physicalNetworkId);
for (final VlanVO vlan : vlans) {
_vlanDao.remove(vlan.getId());
}
// Delete networks
final List<NetworkVO> networks = _networksDao.listByPhysicalNetwork(physicalNetworkId);
if (networks != null && !networks.isEmpty()) {
for (final NetworkVO network : networks) {
_networksDao.remove(network.getId());
}
}
// delete vnets
_dcDao.deleteVnet(physicalNetworkId);
// delete service providers
final List<PhysicalNetworkServiceProviderVO> providers = _pNSPDao.listBy(physicalNetworkId);
for (final PhysicalNetworkServiceProviderVO provider : providers) {
try {
deleteNetworkServiceProvider(provider.getId());
} catch (final ResourceUnavailableException e) {
s_logger.warn("Unable to complete destroy of the physical network provider: " + provider.getProviderName() + ", id: " + provider.getId(), e);
return false;
} catch (final ConcurrentOperationException e) {
s_logger.warn("Unable to complete destroy of the physical network provider: " + provider.getProviderName() + ", id: " + provider.getId(), e);
return false;
}
}
// delete traffic types
_pNTrafficTypeDao.deleteTrafficTypes(physicalNetworkId);
return _physicalNetworkDao.remove(physicalNetworkId);
}
});
}
@DB
private void checkIfPhysicalNetworkIsDeletable(final Long physicalNetworkId) {
final List<List<String>> tablesToCheck = new ArrayList<>();
final List<String> vnet = new ArrayList<>();
vnet.add(0, "op_dc_vnet_alloc");
vnet.add(1, "physical_network_id");
vnet.add(2, "there are allocated vnets for this physical network");
tablesToCheck.add(vnet);
final List<String> networks = new ArrayList<>();
networks.add(0, "networks");
networks.add(1, "physical_network_id");
networks.add(2, "there are networks associated to this physical network");
tablesToCheck.add(networks);
/*
* List<String> privateIP = new ArrayList<String>();
* privateIP.add(0, "op_dc_ip_address_alloc");
* privateIP.add(1, "data_center_id");
* privateIP.add(2, "there are private IP addresses allocated for this zone");
* tablesToCheck.add(privateIP);
*/
final List<String> publicIP = new ArrayList<>();
publicIP.add(0, "user_ip_address");
publicIP.add(1, "physical_network_id");
publicIP.add(2, "there are public IP addresses allocated for this physical network");
tablesToCheck.add(publicIP);
for (final List<String> table : tablesToCheck) {
final String tableName = table.get(0);
final String column = table.get(1);
final String errorMsg = table.get(2);
final String dbName = "cloud";
String selectSql = "SELECT * FROM `" + dbName + "`.`" + tableName + "` WHERE " + column + " = ?";
if (tableName.equals("networks")) {
selectSql += " AND removed is NULL";
}
if (tableName.equals("op_dc_vnet_alloc")) {
selectSql += " AND taken IS NOT NULL";
}
if (tableName.equals("user_ip_address")) {
selectSql += " AND state!='Free'";
}
if (tableName.equals("op_dc_ip_address_alloc")) {
selectSql += " AND taken IS NOT NULL";
}
final TransactionLegacy txn = TransactionLegacy.currentTxn();
try {
final PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql);
stmt.setLong(1, physicalNetworkId);
final ResultSet rs = stmt.executeQuery();
if (rs != null && rs.next()) {
throw new CloudRuntimeException("The Physical Network is not deletable because " + errorMsg);
}
} catch (final SQLException ex) {
throw new CloudRuntimeException("The Management Server failed to detect if physical network is deletable. Please contact Cloud Support.");
}
}
}
@Override
public List<? extends Service> listNetworkServices(final String providerName) {
Provider provider = null;
if (providerName != null) {
provider = Network.Provider.getProvider(providerName);
if (provider == null) {
throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName);
}
}
if (provider != null) {
final NetworkElement element = _networkModel.getElementImplementingProvider(providerName);
if (element == null) {
throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + providerName + "'");
}
return new ArrayList<>(element.getCapabilities().keySet());
} else {
return Service.listAllServices();
}
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_CREATE, eventDescription = "Creating Physical Network ServiceProvider", create = true)
public PhysicalNetworkServiceProvider addProviderToPhysicalNetwork(final Long physicalNetworkId, final String providerName, final Long destinationPhysicalNetworkId, final
List<String> enabledServices) {
// verify input parameters
final PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId);
if (network == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system");
ex.addProxyObject(physicalNetworkId.toString(), "physicalNetworkId");
throw ex;
}
// verify input parameters
if (destinationPhysicalNetworkId != null) {
final PhysicalNetworkVO destNetwork = _physicalNetworkDao.findById(destinationPhysicalNetworkId);
if (destNetwork == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Destination Physical Network with specified id doesn't exist in the system");
ex.addProxyObject(destinationPhysicalNetworkId.toString(), "destinationPhysicalNetworkId");
throw ex;
}
}
if (providerName != null) {
final Provider provider = Network.Provider.getProvider(providerName);
if (provider == null) {
throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName);
}
}
if (_pNSPDao.findByServiceProvider(physicalNetworkId, providerName) != null) {
// TBD: send uuid instead of physicalNetworkId.
throw new CloudRuntimeException("The '" + providerName + "' provider already exists on physical network : " + physicalNetworkId);
}
// check if services can be turned off
final NetworkElement element = _networkModel.getElementImplementingProvider(providerName);
if (element == null) {
throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + providerName + "'");
}
List<Service> services = new ArrayList<>();
if (enabledServices != null) {
if (!element.canEnableIndividualServices()) {
if (enabledServices.size() != element.getCapabilities().keySet().size()) {
throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services for this Service Provider '"
+ providerName + "'");
}
}
// validate Services
boolean addGatewayService = false;
for (final String serviceName : enabledServices) {
final Network.Service service = Network.Service.getService(serviceName);
if (service == null || service == Service.Gateway) {
throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName);
} else if (service == Service.SourceNat) {
addGatewayService = true;
}
// check if the service is provided by this Provider
if (!element.getCapabilities().containsKey(service)) {
throw new InvalidParameterValueException(providerName + " Provider cannot provide this Service specified=" + serviceName);
}
services.add(service);
}
if (addGatewayService) {
services.add(Service.Gateway);
}
} else {
// enable all the default services supported by this element.
services = new ArrayList<>(element.getCapabilities().keySet());
}
try {
// Create the new physical network in the database
PhysicalNetworkServiceProviderVO nsp = new PhysicalNetworkServiceProviderVO(physicalNetworkId, providerName);
// set enabled services
nsp.setEnabledServices(services);
if (destinationPhysicalNetworkId != null) {
nsp.setDestinationPhysicalNetworkId(destinationPhysicalNetworkId);
}
nsp = _pNSPDao.persist(nsp);
return nsp;
} catch (final Exception ex) {
s_logger.warn("Exception: ", ex);
throw new CloudRuntimeException("Fail to add a provider to physical network");
}
}
@Override
public Pair<List<? extends PhysicalNetworkServiceProvider>, Integer> listNetworkServiceProviders(final Long physicalNetworkId, final String name, final String state, final
Long startIndex,
final Long pageSize) {
final Filter searchFilter = new Filter(PhysicalNetworkServiceProviderVO.class, "id", false, startIndex, pageSize);
final SearchBuilder<PhysicalNetworkServiceProviderVO> sb = _pNSPDao.createSearchBuilder();
final SearchCriteria<PhysicalNetworkServiceProviderVO> sc = sb.create();
if (physicalNetworkId != null) {
sc.addAnd("physicalNetworkId", Op.EQ, physicalNetworkId);
}
if (name != null) {
sc.addAnd("providerName", Op.EQ, name);
}
if (state != null) {
sc.addAnd("state", Op.EQ, state);
}
final Pair<List<PhysicalNetworkServiceProviderVO>, Integer> result = _pNSPDao.searchAndCount(sc, searchFilter);
return new Pair<>(result.first(), result.second());
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_UPDATE, eventDescription = "Updating physical network ServiceProvider", async = true)
public PhysicalNetworkServiceProvider updateNetworkServiceProvider(final Long id, final String stateStr, final List<String> enabledServices) {
final PhysicalNetworkServiceProviderVO provider = _pNSPDao.findById(id);
if (provider == null) {
throw new InvalidParameterValueException("Network Service Provider id=" + id + "doesn't exist in the system");
}
final NetworkElement element = _networkModel.getElementImplementingProvider(provider.getProviderName());
if (element == null) {
throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getProviderName() + "'");
}
PhysicalNetworkServiceProvider.State state = null;
if (stateStr != null && !stateStr.isEmpty()) {
try {
state = PhysicalNetworkServiceProvider.State.valueOf(stateStr);
} catch (final IllegalArgumentException ex) {
throw new InvalidParameterValueException("Unable to resolve state '" + stateStr + "' to a supported value {Enabled or Disabled}");
}
}
boolean update = false;
if (state != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("trying to update the state of the service provider id=" + id + " on physical network: " + provider.getPhysicalNetworkId() + " to state: "
+ stateStr);
}
switch (state) {
case Enabled:
if (element != null && element.isReady(provider)) {
provider.setState(PhysicalNetworkServiceProvider.State.Enabled);
update = true;
} else {
throw new CloudRuntimeException("Provider is not ready, cannot Enable the provider, please configure the provider first");
}
break;
case Disabled:
// do we need to do anything for the provider instances before disabling?
provider.setState(PhysicalNetworkServiceProvider.State.Disabled);
update = true;
break;
case Shutdown:
throw new InvalidParameterValueException("Updating the provider state to 'Shutdown' is not supported");
}
}
if (enabledServices != null) {
// check if services can be turned of
if (!element.canEnableIndividualServices()) {
throw new InvalidParameterValueException("Cannot update set of Services for this Service Provider '" + provider.getProviderName() + "'");
}
// validate Services
final List<Service> services = new ArrayList<>();
for (final String serviceName : enabledServices) {
final Network.Service service = Network.Service.getService(serviceName);
if (service == null) {
throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName);
}
services.add(service);
}
// set enabled services
provider.setEnabledServices(services);
update = true;
}
if (update) {
_pNSPDao.update(id, provider);
}
return provider;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_DELETE, eventDescription = "Deleting physical network ServiceProvider", async = true)
public boolean deleteNetworkServiceProvider(final Long id) throws ConcurrentOperationException, ResourceUnavailableException {
final PhysicalNetworkServiceProviderVO provider = _pNSPDao.findById(id);
if (provider == null) {
throw new InvalidParameterValueException("Network Service Provider id=" + id + "doesn't exist in the system");
}
// check if there are networks using this provider
final List<NetworkVO> networks = _networksDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), provider.getProviderName());
if (networks != null && !networks.isEmpty()) {
throw new CloudRuntimeException(
"Provider is not deletable because there are active networks using this provider, please upgrade these networks to new network offerings");
}
final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
final Account callerAccount = _accountMgr.getActiveAccountById(callerUser.getAccountId());
// shutdown the provider instances
final ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Shutting down the service provider id=" + id + " on physical network: " + provider.getPhysicalNetworkId());
}
final NetworkElement element = _networkModel.getElementImplementingProvider(provider.getProviderName());
if (element == null) {
throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getProviderName() + "'");
}
if (element != null && element.shutdownProviderInstances(provider, context)) {
provider.setState(PhysicalNetworkServiceProvider.State.Shutdown);
}
return _pNSPDao.remove(id);
}
@Override
public PhysicalNetwork getPhysicalNetwork(final Long physicalNetworkId) {
return _physicalNetworkDao.findById(physicalNetworkId);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_CREATE, eventDescription = "Creating Physical Network", async = true)
public PhysicalNetwork getCreatedPhysicalNetwork(final Long physicalNetworkId) {
return getPhysicalNetwork(physicalNetworkId);
}
@Override
public PhysicalNetworkServiceProvider getPhysicalNetworkServiceProvider(final Long providerId) {
return _pNSPDao.findById(providerId);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_CREATE, eventDescription = "Creating Physical Network ServiceProvider", async = true)
public PhysicalNetworkServiceProvider getCreatedPhysicalNetworkServiceProvider(final Long providerId) {
return getPhysicalNetworkServiceProvider(providerId);
}
@Override
public long findPhysicalNetworkId(final long zoneId, final String tag, final TrafficType trafficType) {
List<PhysicalNetworkVO> pNtwks = new ArrayList<>();
if (trafficType != null) {
pNtwks = _physicalNetworkDao.listByZoneAndTrafficType(zoneId, trafficType);
} else {
pNtwks = _physicalNetworkDao.listByZone(zoneId);
}
if (pNtwks.isEmpty()) {
throw new InvalidParameterValueException("Unable to find physical network in zone id=" + zoneId);
}
if (pNtwks.size() > 1) {
if (tag == null) {
throw new InvalidParameterValueException("More than one physical networks exist in zone id=" + zoneId + " and no tags are specified in order to make a choice");
}
Long pNtwkId = null;
for (final PhysicalNetwork pNtwk : pNtwks) {
if (pNtwk.getTags().contains(tag)) {
s_logger.debug("Found physical network id=" + pNtwk.getId() + " based on requested tags " + tag);
pNtwkId = pNtwk.getId();
break;
}
}
if (pNtwkId == null) {
throw new InvalidParameterValueException("Unable to find physical network which match the tags " + tag);
}
return pNtwkId;
} else {
return pNtwks.get(0).getId();
}
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_TRAFFIC_TYPE_CREATE, eventDescription = "Creating Physical Network TrafficType", create = true)
public PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(final Long physicalNetworkId, final String trafficTypeStr, final String isolationMethod, String xenLabel,
final String kvmLabel, final String vlan) {
// verify input parameters
final PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId);
if (network == null) {
throw new InvalidParameterValueException("Physical Network id=" + physicalNetworkId + "doesn't exist in the system");
}
Networks.TrafficType trafficType = null;
if (trafficTypeStr != null && !trafficTypeStr.isEmpty()) {
try {
trafficType = Networks.TrafficType.valueOf(trafficTypeStr);
} catch (final IllegalArgumentException ex) {
throw new InvalidParameterValueException("Unable to resolve trafficType '" + trafficTypeStr + "' to a supported value");
}
}
if (_pNTrafficTypeDao.isTrafficTypeSupported(physicalNetworkId, trafficType)) {
throw new CloudRuntimeException("This physical network already supports the traffic type: " + trafficType);
}
// For Storage, Control, Management, Public check if the zone has any other physical network with this
// traffictype already present
// If yes, we cant add these traffics to one more physical network in the zone.
if (TrafficType.isSystemNetwork(trafficType) || TrafficType.Public.equals(trafficType) || TrafficType.Storage.equals(trafficType)) {
if (!_physicalNetworkDao.listByZoneAndTrafficType(network.getDataCenterId(), trafficType).isEmpty()) {
throw new CloudRuntimeException("Fail to add the traffic type to physical network because Zone already has a physical network with this traffic type: "
+ trafficType);
}
}
if (TrafficType.Storage.equals(trafficType)) {
final List<SecondaryStorageVmVO> ssvms = _stnwMgr.getSSVMWithNoStorageNetwork(network.getDataCenterId());
if (!ssvms.isEmpty()) {
final StringBuilder sb = new StringBuilder(
"Cannot add "
+ trafficType
+ " traffic type as there are below secondary storage vm still running. Please stop them all and add Storage traffic type again, then destory " +
"them all to allow CloudStack recreate them with storage network(If you have added storage network ip range)");
sb.append("SSVMs:");
for (final SecondaryStorageVmVO ssvm : ssvms) {
sb.append(ssvm.getInstanceName()).append(":").append(ssvm.getState());
}
throw new CloudRuntimeException(sb.toString());
}
}
try {
// Create the new traffic type in the database
if (xenLabel == null) {
xenLabel = getDefaultXenNetworkLabel(trafficType);
}
PhysicalNetworkTrafficTypeVO pNetworktrafficType = new PhysicalNetworkTrafficTypeVO(physicalNetworkId, trafficType, xenLabel, kvmLabel, vlan);
pNetworktrafficType = _pNTrafficTypeDao.persist(pNetworktrafficType);
// For public traffic, get isolation method of physical network and update the public network accordingly
// each broadcast type will individually need to be qualified for support of public traffic
if (TrafficType.Public.equals(trafficType)) {
final List<String> isolationMethods = network.getIsolationMethods();
if (isolationMethods.size() == 1 && isolationMethods.get(0).toLowerCase().equals("vxlan")
|| isolationMethod != null && isolationMethods.contains(isolationMethod) && isolationMethod.toLowerCase().equals("vxlan")) {
// find row in networks table that is defined as 'Public', created when zone was deployed
final NetworkVO publicNetwork = _networksDao.listByZoneAndTrafficType(network.getDataCenterId(), TrafficType.Public).get(0);
if (publicNetwork != null) {
s_logger.debug("setting public network " + publicNetwork + " to broadcast type vxlan");
publicNetwork.setBroadcastDomainType(BroadcastDomainType.Vxlan);
_networksDao.persist(publicNetwork);
}
}
}
return pNetworktrafficType;
} catch (final Exception ex) {
s_logger.warn("Exception: ", ex);
throw new CloudRuntimeException("Fail to add a traffic type to physical network");
}
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_TRAFFIC_TYPE_CREATE, eventDescription = "Creating Physical Network TrafficType", async = true)
public PhysicalNetworkTrafficType getPhysicalNetworkTrafficType(final Long id) {
return _pNTrafficTypeDao.findById(id);
}
public boolean deletePhysicalNetworkTrafficType(final Long id) {
final PhysicalNetworkTrafficTypeVO trafficType = _pNTrafficTypeDao.findById(id);
if (trafficType == null) {
throw new InvalidParameterValueException("Traffic Type with id=" + id + "doesn't exist in the system");
}
// check if there are any networks associated to this physical network with this traffic type
if (TrafficType.Guest.equals(trafficType.getTrafficType())) {
if (!_networksDao.listByPhysicalNetworkTrafficType(trafficType.getPhysicalNetworkId(), trafficType.getTrafficType()).isEmpty()) {
throw new CloudRuntimeException("The Traffic Type is not deletable because there are existing networks with this traffic type:" + trafficType.getTrafficType());
}
} else if (TrafficType.Storage.equals(trafficType.getTrafficType())) {
final PhysicalNetworkVO pn = _physicalNetworkDao.findById(trafficType.getPhysicalNetworkId());
if (_stnwMgr.isAnyStorageIpInUseInZone(pn.getDataCenterId())) {
throw new CloudRuntimeException("The Traffic Type is not deletable because there are still some storage network ip addresses in use:"
+ trafficType.getTrafficType());
}
}
return _pNTrafficTypeDao.remove(id);
}
private String getDefaultXenNetworkLabel(final TrafficType trafficType) {
String xenLabel = null;
switch (trafficType) {
case Public:
xenLabel = _configDao.getValue(Config.XenServerPublicNetwork.key());
break;
case Guest:
xenLabel = _configDao.getValue(Config.XenServerGuestNetwork.key());
break;
case Storage:
xenLabel = _configDao.getValue(Config.XenServerStorageNetwork1.key());
break;
case Management:
xenLabel = _configDao.getValue(Config.XenServerPrivateNetwork.key());
break;
case Control:
xenLabel = "cloud_link_local_network";
break;
case Vpn:
case None:
break;
}
return xenLabel;
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_GUEST_VLAN_RANGE_DEDICATE, eventDescription = "dedicating guest vlan range", async = false)
public GuestVlan dedicateGuestVlanRange(final DedicateGuestVlanRangeCmd cmd) {
final String vlan = cmd.getVlan();
final String accountName = cmd.getAccountName();
final Long domainId = cmd.getDomainId();
final Long physicalNetworkId = cmd.getPhysicalNetworkId();
final Long projectId = cmd.getProjectId();
final int startVlan;
final int endVlan;
String updatedVlanRange = null;
long guestVlanMapId = 0;
long guestVlanMapAccountId = 0;
long vlanOwnerId = 0;
// Verify account is valid
Account vlanOwner = null;
if (projectId != null) {
if (accountName != null) {
throw new InvalidParameterValueException("accountName and projectId are mutually exclusive");
}
final Project project = _projectMgr.getProject(projectId);
if (project == null) {
throw new InvalidParameterValueException("Unable to find project by id " + projectId);
}
vlanOwner = _accountMgr.getAccount(project.getProjectAccountId());
}
if (accountName != null && domainId != null) {
vlanOwner = _accountDao.findActiveAccount(accountName, domainId);
}
if (vlanOwner == null) {
throw new InvalidParameterValueException("Unable to find account by name " + accountName);
}
vlanOwnerId = vlanOwner.getAccountId();
// Verify physical network isolation type is VLAN
final PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (physicalNetwork == null) {
throw new InvalidParameterValueException("Unable to find physical network by id " + physicalNetworkId);
} else if (!physicalNetwork.getIsolationMethods().isEmpty() && !physicalNetwork.getIsolationMethods().contains("VLAN")) {
throw new InvalidParameterValueException("Cannot dedicate guest vlan range. " + "Physical isolation type of network " + physicalNetworkId + " is not VLAN");
}
// Get the start and end vlan
final String[] vlanRange = vlan.split("-");
if (vlanRange.length != 2) {
throw new InvalidParameterValueException("Invalid format for parameter value vlan " + vlan + " .Vlan should be specified as 'startvlan-endvlan'");
}
try {
startVlan = Integer.parseInt(vlanRange[0]);
endVlan = Integer.parseInt(vlanRange[1]);
} catch (final NumberFormatException e) {
s_logger.warn("Unable to parse guest vlan range:", e);
throw new InvalidParameterValueException("Please provide valid guest vlan range");
}
// Verify guest vlan range exists in the system
final List<Pair<Integer, Integer>> existingRanges = physicalNetwork.getVnet();
Boolean exists = false;
if (!existingRanges.isEmpty()) {
for (int i = 0; i < existingRanges.size(); i++) {
final int existingStartVlan = existingRanges.get(i).first();
final int existingEndVlan = existingRanges.get(i).second();
if (startVlan <= endVlan && startVlan >= existingStartVlan && endVlan <= existingEndVlan) {
exists = true;
break;
}
}
if (!exists) {
throw new InvalidParameterValueException("Unable to find guest vlan by range " + vlan);
}
}
// Verify guest vlans in the range don't belong to a network of a different account
for (int i = startVlan; i <= endVlan; i++) {
final List<DataCenterVnetVO> allocatedVlans = _datacneterVnet.listAllocatedVnetsInRange(physicalNetwork.getDataCenterId(), physicalNetwork.getId(), startVlan, endVlan);
if (allocatedVlans != null && !allocatedVlans.isEmpty()) {
for (final DataCenterVnetVO allocatedVlan : allocatedVlans) {
if (allocatedVlan.getAccountId() != vlanOwner.getAccountId()) {
throw new InvalidParameterValueException("Guest vlan from this range " + allocatedVlan.getVnet() + " is allocated to a different account."
+ " Can only dedicate a range which has no allocated vlans or has vlans allocated to the same account ");
}
}
}
}
final List<AccountGuestVlanMapVO> guestVlanMaps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByPhysicalNetwork(physicalNetworkId);
// Verify if vlan range is already dedicated
for (final AccountGuestVlanMapVO guestVlanMap : guestVlanMaps) {
final List<Integer> vlanTokens = getVlanFromRange(guestVlanMap.getGuestVlanRange());
final int dedicatedStartVlan = vlanTokens.get(0).intValue();
final int dedicatedEndVlan = vlanTokens.get(1).intValue();
if (startVlan < dedicatedStartVlan & endVlan >= dedicatedStartVlan || startVlan >= dedicatedStartVlan & startVlan <= dedicatedEndVlan) {
throw new InvalidParameterValueException("Vlan range is already dedicated. Cannot" + " dedicate guest vlan range " + vlan);
}
}
// Sort the existing dedicated vlan ranges
Collections.sort(guestVlanMaps, new Comparator<AccountGuestVlanMapVO>() {
@Override
public int compare(final AccountGuestVlanMapVO obj1, final AccountGuestVlanMapVO obj2) {
final List<Integer> vlanTokens1 = getVlanFromRange(obj1.getGuestVlanRange());
final List<Integer> vlanTokens2 = getVlanFromRange(obj2.getGuestVlanRange());
return vlanTokens1.get(0).compareTo(vlanTokens2.get(0));
}
});
// Verify if vlan range extends an already dedicated range
for (int i = 0; i < guestVlanMaps.size(); i++) {
guestVlanMapId = guestVlanMaps.get(i).getId();
guestVlanMapAccountId = guestVlanMaps.get(i).getAccountId();
final List<Integer> vlanTokens1 = getVlanFromRange(guestVlanMaps.get(i).getGuestVlanRange());
// Range extends a dedicated vlan range to the left
if (endVlan == vlanTokens1.get(0).intValue() - 1) {
if (guestVlanMapAccountId == vlanOwnerId) {
updatedVlanRange = startVlan + "-" + vlanTokens1.get(1).intValue();
}
break;
}
// Range extends a dedicated vlan range to the right
if (startVlan == vlanTokens1.get(1).intValue() + 1 & guestVlanMapAccountId == vlanOwnerId) {
if (i != guestVlanMaps.size() - 1) {
final List<Integer> vlanTokens2 = getVlanFromRange(guestVlanMaps.get(i + 1).getGuestVlanRange());
// Range extends 2 vlan ranges, both to the right and left
if (endVlan == vlanTokens2.get(0).intValue() - 1 && guestVlanMaps.get(i + 1).getAccountId() == vlanOwnerId) {
_datacneterVnet.releaseDedicatedGuestVlans(guestVlanMaps.get(i + 1).getId());
_accountGuestVlanMapDao.remove(guestVlanMaps.get(i + 1).getId());
updatedVlanRange = vlanTokens1.get(0).intValue() + "-" + vlanTokens2.get(1).intValue();
break;
}
}
updatedVlanRange = vlanTokens1.get(0).intValue() + "-" + endVlan;
break;
}
}
// Dedicate vlan range
final AccountGuestVlanMapVO accountGuestVlanMapVO;
if (updatedVlanRange != null) {
accountGuestVlanMapVO = _accountGuestVlanMapDao.findById(guestVlanMapId);
accountGuestVlanMapVO.setGuestVlanRange(updatedVlanRange);
_accountGuestVlanMapDao.update(guestVlanMapId, accountGuestVlanMapVO);
} else {
accountGuestVlanMapVO = new AccountGuestVlanMapVO(vlanOwner.getAccountId(), physicalNetworkId);
accountGuestVlanMapVO.setGuestVlanRange(startVlan + "-" + endVlan);
_accountGuestVlanMapDao.persist(accountGuestVlanMapVO);
}
// For every guest vlan set the corresponding account guest vlan map id
final List<Integer> finaVlanTokens = getVlanFromRange(accountGuestVlanMapVO.getGuestVlanRange());
for (int i = finaVlanTokens.get(0).intValue(); i <= finaVlanTokens.get(1).intValue(); i++) {
final List<DataCenterVnetVO> dataCenterVnet = _datacneterVnet.findVnet(physicalNetwork.getDataCenterId(), physicalNetworkId, Integer.toString(i));
dataCenterVnet.get(0).setAccountGuestVlanMapId(accountGuestVlanMapVO.getId());
_datacneterVnet.update(dataCenterVnet.get(0).getId(), dataCenterVnet.get(0));
}
return accountGuestVlanMapVO;
}
private List<Integer> getVlanFromRange(final String vlanRange) {
// Get the start and end vlan
final String[] vlanTokens = vlanRange.split("-");
final List<Integer> tokens = new ArrayList<>();
try {
final int startVlan = Integer.parseInt(vlanTokens[0]);
final int endVlan = Integer.parseInt(vlanTokens[1]);
tokens.add(startVlan);
tokens.add(endVlan);
} catch (final NumberFormatException e) {
s_logger.warn("Unable to parse guest vlan range:", e);
throw new InvalidParameterValueException("Please provide valid guest vlan range");
}
return tokens;
}
@Override
public Pair<List<? extends GuestVlan>, Integer> listDedicatedGuestVlanRanges(final ListDedicatedGuestVlanRangesCmd cmd) {
final Long id = cmd.getId();
final String accountName = cmd.getAccountName();
final Long domainId = cmd.getDomainId();
final Long projectId = cmd.getProjectId();
final String guestVlanRange = cmd.getGuestVlanRange();
final Long physicalNetworkId = cmd.getPhysicalNetworkId();
final Long zoneId = cmd.getZoneId();
Long accountId = null;
if (accountName != null && domainId != null) {
if (projectId != null) {
throw new InvalidParameterValueException("Account and projectId can't be specified together");
}
final Account account = _accountDao.findActiveAccount(accountName, domainId);
if (account == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account " + accountName);
final DomainVO domain = ApiDBUtils.findDomainById(domainId);
String domainUuid = domainId.toString();
if (domain != null) {
domainUuid = domain.getUuid();
}
ex.addProxyObject(domainUuid, "domainId");
throw ex;
} else {
accountId = account.getId();
}
}
// set project information
if (projectId != null) {
final Project project = _projectMgr.getProject(projectId);
if (project == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project by id " + projectId);
ex.addProxyObject(projectId.toString(), "projectId");
throw ex;
}
accountId = project.getProjectAccountId();
}
final SearchBuilder<AccountGuestVlanMapVO> sb = _accountGuestVlanMapDao.createSearchBuilder();
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
sb.and("guestVlanRange", sb.entity().getGuestVlanRange(), SearchCriteria.Op.EQ);
sb.and("physicalNetworkId", sb.entity().getPhysicalNetworkId(), SearchCriteria.Op.EQ);
if (zoneId != null) {
final SearchBuilder<PhysicalNetworkVO> physicalnetworkSearch = _physicalNetworkDao.createSearchBuilder();
physicalnetworkSearch.and("zoneId", physicalnetworkSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
sb.join("physicalnetworkSearch", physicalnetworkSearch, sb.entity().getPhysicalNetworkId(), physicalnetworkSearch.entity().getId(), JoinBuilder.JoinType.INNER);
}
final SearchCriteria<AccountGuestVlanMapVO> sc = sb.create();
if (id != null) {
sc.setParameters("id", id);
}
if (accountId != null) {
sc.setParameters("accountId", accountId);
}
if (guestVlanRange != null) {
sc.setParameters("guestVlanRange", guestVlanRange);
}
if (physicalNetworkId != null) {
sc.setParameters("physicalNetworkId", physicalNetworkId);
}
if (zoneId != null) {
sc.setJoinParameters("physicalnetworkSearch", "zoneId", zoneId);
}
final Filter searchFilter = new Filter(AccountGuestVlanMapVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
final Pair<List<AccountGuestVlanMapVO>, Integer> result = _accountGuestVlanMapDao.searchAndCount(sc, searchFilter);
return new Pair<>(result.first(), result.second());
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_DEDICATED_GUEST_VLAN_RANGE_RELEASE, eventDescription = "releasing" + " dedicated guest vlan range", async = true)
@DB
public boolean releaseDedicatedGuestVlanRange(final Long dedicatedGuestVlanRangeId) {
// Verify dedicated range exists
final AccountGuestVlanMapVO dedicatedGuestVlan = _accountGuestVlanMapDao.findById(dedicatedGuestVlanRangeId);
if (dedicatedGuestVlan == null) {
throw new InvalidParameterValueException("Dedicated guest vlan with specified" + " id doesn't exist in the system");
}
// Remove dedication for the guest vlan
_datacneterVnet.releaseDedicatedGuestVlans(dedicatedGuestVlan.getId());
if (_accountGuestVlanMapDao.remove(dedicatedGuestVlanRangeId)) {
return true;
} else {
return false;
}
}
@Override
public Pair<List<? extends PhysicalNetworkTrafficType>, Integer> listTrafficTypes(final Long physicalNetworkId) {
final PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId);
if (network == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system");
ex.addProxyObject(physicalNetworkId.toString(), "physicalNetworkId");
throw ex;
}
final Pair<List<PhysicalNetworkTrafficTypeVO>, Integer> result = _pNTrafficTypeDao.listAndCountBy(physicalNetworkId);
return new Pair<>(result.first(), result.second());
}
@Override
//TODO: duplicated in NetworkModel
public NetworkVO getExclusiveGuestNetwork(final long zoneId) {
final List<NetworkVO> networks = _networksDao.listBy(Account.ACCOUNT_ID_SYSTEM, zoneId, GuestType.Shared, TrafficType.Guest);
if (networks == null || networks.isEmpty()) {
throw new InvalidParameterValueException("Unable to find network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone " + zoneId);
}
if (networks.size() > 1) {
throw new InvalidParameterValueException("Found more than 1 network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone "
+ zoneId);
}
return networks.get(0);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "associating Ip", async = true)
public IpAddress associateIPToNetwork(final long ipId, final long networkId) throws InsufficientAddressCapacityException, ResourceAllocationException,
ResourceUnavailableException,
ConcurrentOperationException {
final Network network = _networksDao.findById(networkId);
if (network == null) {
// release the acquired IP addrress before throwing the exception
// else it will always be in allocating state
releaseIpAddress(ipId);
throw new InvalidParameterValueException("Invalid network id is given");
}
if (network.getVpcId() != null) {
// release the acquired IP addrress before throwing the exception
// else it will always be in allocating state
releaseIpAddress(ipId);
throw new InvalidParameterValueException("Can't assign ip to the network directly when network belongs" + " to VPC.Specify vpcId to associate ip address to VPC");
}
return _ipAddrMgr.associateIPToGuestNetwork(ipId, networkId, true);
}
@Override
@DB
public Network createPrivateNetwork(final String networkName, final String displayText, final long physicalNetworkId, final String broadcastUriString, final String startIp,
String endIp, final String gateway, final String netmask, final long networkOwnerId, final Long vpcId, final Boolean sourceNat,
final Long networkOfferingId)
throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
final Account owner = _accountMgr.getAccount(networkOwnerId);
// Get system network offering
NetworkOfferingVO ntwkOff = null;
if (networkOfferingId != null) {
ntwkOff = _networkOfferingDao.findById(networkOfferingId);
}
if (ntwkOff == null) {
ntwkOff = findSystemNetworkOffering(NetworkOffering.DefaultPrivateGatewayNetworkOffering);
}
// Validate physical network
final PhysicalNetwork pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
if (pNtwk == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a physical network" + " having the given id");
ex.addProxyObject(String.valueOf(physicalNetworkId), "physicalNetworkId");
throw ex;
}
// VALIDATE IP INFO
// if end ip is not specified, default it to startIp
if (!NetUtils.isValidIp4(startIp)) {
throw new InvalidParameterValueException("Invalid format for the ip address parameter");
}
if (endIp == null) {
endIp = startIp;
} else if (!NetUtils.isValidIp4(endIp)) {
throw new InvalidParameterValueException("Invalid format for the endIp address parameter");
}
if (!NetUtils.isValidIp4(gateway)) {
throw new InvalidParameterValueException("Invalid gateway");
}
if (!NetUtils.isValidIp4Netmask(netmask)) {
throw new InvalidParameterValueException("Invalid netmask");
}
final String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
final URI uri = BroadcastDomainType.fromString(broadcastUriString);
final String uriString = uri.toString();
final BroadcastDomainType tiep = BroadcastDomainType.getSchemeValue(uri);
// numeric vlan or vlan uri are ok for now
// TODO make a test for any supported scheme
if (!(tiep == BroadcastDomainType.Vlan || tiep == BroadcastDomainType.Lswitch)) {
throw new InvalidParameterValueException("unsupported type of broadcastUri specified: " + broadcastUriString);
}
final NetworkOfferingVO ntwkOffFinal = ntwkOff;
try {
return Transaction.execute(new TransactionCallbackWithException<Network, Exception>() {
@Override
public Network doInTransaction(final TransactionStatus status) throws ResourceAllocationException, InsufficientCapacityException {
//lock datacenter as we need to get mac address seq from there
final DataCenterVO dc = _dcDao.lockRow(pNtwk.getDataCenterId(), true);
//check if we need to create guest network
Network privateNetwork = _networksDao.getPrivateNetwork(uriString, cidr, networkOwnerId, pNtwk.getDataCenterId(), networkOfferingId);
if (privateNetwork == null) {
//create Guest network
privateNetwork = _networkMgr.createGuestNetwork(ntwkOffFinal.getId(), networkName, displayText, gateway, cidr, uriString, null, owner, null, pNtwk,
pNtwk.getDataCenterId(), ACLType.Account, null, vpcId, null, null, true, null,
dc.getDns1(), dc.getDns2(), null);
if (privateNetwork != null) {
s_logger.debug("Successfully created guest network " + privateNetwork);
} else {
throw new CloudRuntimeException("Creating guest network failed");
}
} else {
s_logger.debug("Private network already exists: " + privateNetwork);
//Do not allow multiple private gateways with same Vlan within a VPC
if (vpcId != null && vpcId.equals(privateNetwork.getVpcId())) {
throw new InvalidParameterValueException("Private network for the vlan: " + uriString + " and cidr " + cidr + " already exists " + "for Vpc " + vpcId
+ " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
}
}
if (vpcId != null) {
//add entry to private_ip_address table
PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkIdAndVpcId(privateNetwork.getId(), startIp, vpcId);
if (privateIp != null) {
throw new InvalidParameterValueException("Private ip address " + startIp + " already used for private gateway" + " in zone "
+ _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
}
final Long mac = dc.getMacAddress();
final Long nextMac = mac + 1;
dc.setMacAddress(nextMac);
privateIp = new PrivateIpVO(startIp, privateNetwork.getId(), nextMac, vpcId, sourceNat);
_privateIpDao.persist(privateIp);
_dcDao.update(dc.getId(), dc);
}
s_logger.debug("Private network " + privateNetwork + " is created");
return privateNetwork;
}
});
} catch (final Exception e) {
ExceptionUtil.rethrowRuntime(e);
ExceptionUtil.rethrow(e, ResourceAllocationException.class);
ExceptionUtil.rethrow(e, InsufficientCapacityException.class);
throw new IllegalStateException(e);
}
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NIC_SECONDARY_IP_ASSIGN, eventDescription = "assigning secondary ip to nic", create = true)
public NicSecondaryIp allocateSecondaryGuestIP(final long nicId, final String requestedIp) throws InsufficientAddressCapacityException {
final Account caller = CallContext.current().getCallingAccount();
//check whether the nic belongs to user vm.
final NicVO nicVO = _nicDao.findById(nicId);
if (nicVO == null) {
throw new InvalidParameterValueException("There is no nic for the " + nicId);
}
if (nicVO.getVmType() != VirtualMachine.Type.User) {
throw new InvalidParameterValueException("The nic is not belongs to user vm");
}
final VirtualMachine vm = _userVmDao.findById(nicVO.getInstanceId());
if (vm == null) {
throw new InvalidParameterValueException("There is no vm with the nic");
}
final long networkId = nicVO.getNetworkId();
final Account ipOwner = _accountMgr.getAccount(vm.getAccountId());
// verify permissions
_accountMgr.checkAccess(caller, null, true, vm);
final Network network = _networksDao.findById(networkId);
if (network == null) {
throw new InvalidParameterValueException("Invalid network id is given");
}
final int maxAllowedIpsPerNic = NumbersUtil.parseInt(_configDao.getValue(Config.MaxNumberOfSecondaryIPsPerNIC.key()), 10);
final Long nicWiseIpCount = _nicSecondaryIpDao.countByNicId(nicId);
if (nicWiseIpCount.intValue() >= maxAllowedIpsPerNic) {
s_logger.error("Maximum Number of Ips \"vm.network.nic.max.secondary.ipaddresses = \"" + maxAllowedIpsPerNic + " per Nic has been crossed for the nic " + nicId + ".");
throw new InsufficientAddressCapacityException("Maximum Number of Ips per Nic has been crossed.", Nic.class, nicId);
}
s_logger.debug("Calling the ip allocation ...");
String ipaddr = null;
//Isolated network can exist in Basic zone only, so no need to verify the zone type
if (network.getGuestType() == Network.GuestType.Isolated) {
try {
ipaddr = _ipAddrMgr.allocateGuestIP(network, requestedIp);
} catch (final InsufficientAddressCapacityException e) {
throw new InvalidParameterValueException("Allocating guest ip for nic failed");
}
} else if (network.getGuestType() == Network.GuestType.Shared) {
//for basic zone, need to provide the podId to ensure proper ip alloation
Long podId = null;
final DataCenter dc = _dcDao.findById(network.getDataCenterId());
if (dc.getNetworkType() == NetworkType.Basic) {
final VMInstanceVO vmi = (VMInstanceVO) vm;
podId = vmi.getPodIdToDeployIn();
if (podId == null) {
throw new InvalidParameterValueException("vm pod id is null in Basic zone; can't decide the range for ip allocation");
}
}
try {
ipaddr = _ipAddrMgr.allocatePublicIpForGuestNic(network, podId, ipOwner, requestedIp);
if (ipaddr == null) {
throw new InvalidParameterValueException("Allocating ip to guest nic " + nicId + " failed");
}
} catch (final InsufficientAddressCapacityException e) {
s_logger.error("Allocating ip to guest nic " + nicId + " failed");
return null;
}
} else if (network.getTrafficType() == TrafficType.Public) {
try {
final PublicIp ip = _ipAddrMgr.assignPublicIpAddress(vm.getDataCenterId(), null, ipOwner, VlanType.VirtualNetwork, null, requestedIp, false);
ipaddr = ip.getAddress().toString();
} catch (final InsufficientAddressCapacityException e) {
throw new InvalidParameterValueException("Allocating public ip for nic failed");
}
} else {
s_logger.error("AddIpToVMNic is not supported in this network...");
return null;
}
if (ipaddr != null) {
// we got the ip addr so up the nics table and secondary ip
final String addrFinal = ipaddr;
final long id = Transaction.execute(new TransactionCallback<Long>() {
@Override
public Long doInTransaction(final TransactionStatus status) {
final boolean nicSecondaryIpSet = nicVO.getSecondaryIp();
if (!nicSecondaryIpSet) {
nicVO.setSecondaryIp(true);
// commit when previously set ??
s_logger.debug("Setting nics table ...");
_nicDao.update(nicId, nicVO);
}
s_logger.debug("Setting nic_secondary_ip table ...");
final Long vmId = nicVO.getInstanceId();
final NicSecondaryIpVO secondaryIpVO = new NicSecondaryIpVO(nicId, addrFinal, vmId, ipOwner.getId(), ipOwner.getDomainId(), networkId);
_nicSecondaryIpDao.persist(secondaryIpVO);
return secondaryIpVO.getId();
}
});
return getNicSecondaryIp(id);
} else {
return null;
}
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NIC_SECONDARY_IP_UNASSIGN, eventDescription = "Removing secondary ip " +
"from nic", async = true)
public boolean releaseSecondaryIpFromNic(final long ipAddressId) {
final Account caller = CallContext.current().getCallingAccount();
boolean success = false;
// Verify input parameters
final NicSecondaryIpVO secIpVO = _nicSecondaryIpDao.findById(ipAddressId);
if (secIpVO == null) {
throw new InvalidParameterValueException("Unable to find secondary ip address by id");
}
final VirtualMachine vm = _userVmDao.findById(secIpVO.getVmId());
if (vm == null) {
throw new InvalidParameterValueException("There is no vm with the given secondary ip");
}
// verify permissions
_accountMgr.checkAccess(caller, null, true, vm);
final Network network = _networksDao.findById(secIpVO.getNetworkId());
if (network == null) {
throw new InvalidParameterValueException("Invalid network id is given");
}
// Validate network offering
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(network.getNetworkOfferingId());
final Long nicId = secIpVO.getNicId();
s_logger.debug("ip id = " + ipAddressId + " nic id = " + nicId);
//check is this the last secondary ip for NIC
final List<NicSecondaryIpVO> ipList = _nicSecondaryIpDao.listByNicId(nicId);
boolean lastIp = false;
if (ipList.size() == 1) {
// this is the last secondary ip to nic
lastIp = true;
}
final DataCenter dc = _dcDao.findById(network.getDataCenterId());
if (dc == null) {
throw new InvalidParameterValueException("Invalid zone Id is given");
}
s_logger.debug("Calling secondary ip " + secIpVO.getIp4Address() + " release ");
if (dc.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Isolated) {
//check PF or static NAT is configured on this ip address
final String secondaryIp = secIpVO.getIp4Address();
final List<FirewallRuleVO> fwRulesList = _firewallDao.listByNetworkAndPurpose(network.getId(), Purpose.PortForwarding);
if (fwRulesList.size() != 0) {
for (final FirewallRuleVO rule : fwRulesList) {
if (_portForwardingDao.findByIdAndIp(rule.getId(), secondaryIp) != null) {
s_logger.debug("VM nic IP " + secondaryIp + " is associated with the port forwarding rule");
throw new InvalidParameterValueException("Can't remove the secondary ip " + secondaryIp + " is associate with the port forwarding rule");
}
}
}
//check if the secondary ip associated with any static nat rule
final IPAddressVO publicIpVO = _ipAddressDao.findByIpAndNetworkId(secIpVO.getNetworkId(), secondaryIp);
if (publicIpVO != null) {
s_logger.debug("VM nic IP " + secondaryIp + " is associated with the static NAT rule public IP address id " + publicIpVO.getId());
throw new InvalidParameterValueException("Can' remove the ip " + secondaryIp + "is associate with static NAT rule public IP address id " + publicIpVO.getId());
}
if (_lbService.isLbRuleMappedToVmGuestIp(secondaryIp)) {
s_logger.debug("VM nic IP " + secondaryIp + " is mapped to load balancing rule");
throw new InvalidParameterValueException("Can't remove the secondary ip " + secondaryIp + " is mapped to load balancing rule");
}
} else if (dc.getNetworkType() == NetworkType.Basic || ntwkOff.getGuestType() == Network.GuestType.Shared) {
final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(secIpVO.getNetworkId(), secIpVO.getIp4Address());
if (ip != null) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
_ipAddrMgr.markIpAsUnavailable(ip.getId());
_ipAddressDao.unassignIpAddress(ip.getId());
}
});
}
} else if (network.getTrafficType() == TrafficType.Public) {
final IPAddressVO publicIpVO = _ipAddressDao.findByIpAndSourceNetworkId(secIpVO.getNetworkId(), secIpVO.getIp4Address());
final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
final Account callerAccount = _accountMgr.getActiveAccountById(callerUser.getAccountId());
_ipAddrMgr.disassociatePublicIpAddress(publicIpVO.getId(), callerUser.getId(), callerAccount);
} else {
throw new InvalidParameterValueException("Not supported for this network now");
}
success = removeNicSecondaryIP(secIpVO, lastIp);
return success;
}
private boolean removeNicSecondaryIP(final NicSecondaryIpVO ipVO, final boolean lastIp) {
final long nicId = ipVO.getNicId();
final NicVO nic = _nicDao.findById(nicId);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
if (lastIp) {
nic.setSecondaryIp(false);
s_logger.debug("Setting nics secondary ip to false ...");
_nicDao.update(nicId, nic);
}
s_logger.debug("Revoving nic secondary ip entry ...");
_nicSecondaryIpDao.remove(ipVO.getId());
}
});
return true;
}
@Override
public List<? extends Nic> listNics(final ListNicsCmd cmd) {
final Account caller = CallContext.current().getCallingAccount();
final Long nicId = cmd.getNicId();
final long vmId = cmd.getVmId();
final Long networkId = cmd.getNetworkId();
final UserVmVO userVm = _userVmDao.findById(vmId);
if (userVm == null || !userVm.isDisplayVm() && caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Virtual mahine id does not exist");
ex.addProxyObject(Long.valueOf(vmId).toString(), "vmId");
throw ex;
}
_accountMgr.checkAccess(caller, null, true, userVm);
return _networkMgr.listVmNics(vmId, nicId, networkId);
}
@Override
public Map<Capability, String> getNetworkOfferingServiceCapabilities(final NetworkOffering offering, final Service service) {
if (!areServicesSupportedByNetworkOffering(offering.getId(), service)) {
// TBD: We should be sending networkOfferingId and not the offering object itself.
throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the network offering " + offering);
}
Map<Capability, String> serviceCapabilities = new HashMap<>();
// get the Provider for this Service for this offering
final List<String> providers = _ntwkOfferingSrvcDao.listProvidersForServiceForNetworkOffering(offering.getId(), service);
if (providers.isEmpty()) {
// TBD: We should be sending networkOfferingId and not the offering object itself.
throw new InvalidParameterValueException("Service " + service.getName() + " is not supported by the network offering " + offering);
}
// FIXME - in post 3.0 we are going to support multiple providers for the same service per network offering, so
// we have to calculate capabilities for all of them
final String provider = providers.get(0);
// FIXME we return the capabilities of the first provider of the service - what if we have multiple providers
// for same Service?
final NetworkElement element = _networkModel.getElementImplementingProvider(provider);
if (element != null) {
final Map<Service, Map<Capability, String>> elementCapabilities = element.getCapabilities();
if (elementCapabilities == null || !elementCapabilities.containsKey(service)) {
// TBD: We should be sending providerId and not the offering object itself.
throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider="
+ provider);
}
serviceCapabilities = elementCapabilities.get(service);
}
return serviceCapabilities;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_IP_UPDATE, eventDescription = "updating public ip address", async = true)
public IpAddress updateIP(final Long id, final String customId, final Boolean displayIp) {
final Account caller = CallContext.current().getCallingAccount();
final IPAddressVO ipVO = _ipAddressDao.findById(id);
if (ipVO == null) {
throw new InvalidParameterValueException("Unable to find ip address by id");
}
// verify permissions
if (ipVO.getAllocatedToAccountId() != null) {
_accountMgr.checkAccess(caller, null, true, ipVO);
} else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
throw new PermissionDeniedException("Only Root admin can update non-allocated ip addresses");
}
if (customId != null) {
ipVO.setUuid(customId);
}
if (displayIp != null) {
ipVO.setDisplay(displayIp);
}
_ipAddressDao.update(id, ipVO);
return _ipAddressDao.findById(id);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NIC_SECONDARY_IP_CONFIGURE, eventDescription = "Configuring secondary ip rules", async = true)
public boolean configureNicSecondaryIp(final NicSecondaryIp secIp) {
return true;
}
private NicSecondaryIp getNicSecondaryIp(final long id) {
final NicSecondaryIp nicSecIp = _nicSecondaryIpDao.findById(id);
if (nicSecIp == null) {
return null;
}
return nicSecIp;
}
private NetworkOfferingVO findSystemNetworkOffering(final String offeringName) {
final List<NetworkOfferingVO> allOfferings = _networkOfferingDao.listSystemNetworkOfferings();
for (final NetworkOfferingVO offer : allOfferings) {
if (offer.getName().equals(offeringName)) {
return offer;
}
}
return null;
}
@DB
private void addOrRemoveVnets(final String[] listOfRanges, final PhysicalNetworkVO network) {
List<String> addVnets = null;
List<String> removeVnets = null;
final HashSet<String> tempVnets = new HashSet<>();
final HashSet<String> vnetsInDb = new HashSet<>();
List<Pair<Integer, Integer>> vnetranges = null;
String comaSeperatedStingOfVnetRanges = null;
int i = 0;
if (listOfRanges.length != 0) {
_physicalNetworkDao.acquireInLockTable(network.getId(), 10);
vnetranges = validateVlanRange(network, listOfRanges);
//computing vnets to be removed.
removeVnets = getVnetsToremove(network, vnetranges);
//computing vnets to add
vnetsInDb.addAll(_datacneterVnet.listVnetsByPhysicalNetworkAndDataCenter(network.getDataCenterId(), network.getId()));
tempVnets.addAll(vnetsInDb);
for (final Pair<Integer, Integer> vlan : vnetranges) {
for (i = vlan.first(); i <= vlan.second(); i++) {
tempVnets.add(Integer.toString(i));
}
}
tempVnets.removeAll(vnetsInDb);
//vnets to add in tempVnets.
//adding and removing vnets from vnetsInDb
if (removeVnets != null && removeVnets.size() != 0) {
vnetsInDb.removeAll(removeVnets);
}
if (tempVnets.size() != 0) {
addVnets = new ArrayList<>();
addVnets.addAll(tempVnets);
vnetsInDb.addAll(tempVnets);
}
//sorting the vnets in Db to generate a coma seperated list of the vnet string.
if (vnetsInDb.size() != 0) {
comaSeperatedStingOfVnetRanges = generateVnetString(new ArrayList<>(vnetsInDb));
}
network.setVnet(comaSeperatedStingOfVnetRanges);
final List<String> addVnetsFinal = addVnets;
final List<String> removeVnetsFinal = removeVnets;
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
if (addVnetsFinal != null) {
s_logger.debug("Adding vnet range " + addVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id="
+ network.getDataCenterId() + " as a part of updatePhysicalNetwork call");
//add vnet takes a list of strings to be added. each string is a vnet.
_dcDao.addVnet(network.getDataCenterId(), network.getId(), addVnetsFinal);
}
if (removeVnetsFinal != null) {
s_logger.debug("removing vnet range " + removeVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id="
+ network.getDataCenterId() + " as a part of updatePhysicalNetwork call");
//deleteVnets takes a list of strings to be removed. each string is a vnet.
_datacneterVnet.deleteVnets(TransactionLegacy.currentTxn(), network.getDataCenterId(), network.getId(), removeVnetsFinal);
}
_physicalNetworkDao.update(network.getId(), network);
}
});
_physicalNetworkDao.releaseFromLockTable(network.getId());
}
}
private PhysicalNetworkServiceProvider addDefaultVirtualRouterToPhysicalNetwork(final long physicalNetworkId) {
final PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId, Network.Provider.VirtualRouter.getName(), null, null);
// add instance of the provider
final NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.VirtualRouter.getName());
if (networkElement == null) {
throw new CloudRuntimeException("Unable to find the Network Element implementing the VirtualRouter Provider");
}
final VirtualRouterElement element = (VirtualRouterElement) networkElement;
element.addElement(nsp.getId(), Type.VirtualRouter);
return nsp;
}
private PhysicalNetworkServiceProvider addDefaultVpcVirtualRouterToPhysicalNetwork(final long physicalNetworkId) {
final PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId, Network.Provider.VPCVirtualRouter.getName(), null, null);
final NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.VPCVirtualRouter.getName());
if (networkElement == null) {
throw new CloudRuntimeException("Unable to find the Network Element implementing the VPCVirtualRouter Provider");
}
final VpcVirtualRouterElement element = (VpcVirtualRouterElement) networkElement;
element.addElement(nsp.getId(), Type.VPCVirtualRouter);
return nsp;
}
private List<Pair<Integer, Integer>> validateVlanRange(final PhysicalNetworkVO network, final String[] listOfRanges) {
Integer StartVnet;
Integer EndVnet;
final List<Pair<Integer, Integer>> vlanTokens = new ArrayList<>();
for (final String vlanRange : listOfRanges) {
final String[] VnetRange = vlanRange.split("-");
// Init with [min,max] of VLAN. Actually 0x000 and 0xFFF are reserved by IEEE, shoudn't be used.
long minVnet = MIN_VLAN_ID;
long maxVnet = MAX_VLAN_ID;
// for GRE phynets allow up to 32bits
// TODO: Not happy about this test.
// What about guru-like objects for physical networs?
s_logger.debug("ISOLATION METHODS:" + network.getIsolationMethods());
// Java does not have unsigned types...
if (network.getIsolationMethods().contains("GRE")) {
minVnet = MIN_GRE_KEY;
maxVnet = MAX_GRE_KEY;
} else if (network.getIsolationMethods().contains("VXLAN")) {
minVnet = MIN_VXLAN_VNI;
maxVnet = MAX_VXLAN_VNI;
// fail if zone already contains VNI, need to be unique per zone.
// since adding a range adds each VNI to the database, need only check min/max
for (final String vnet : VnetRange) {
s_logger.debug("Looking to see if VNI " + vnet + " already exists on another network in zone " + network.getDataCenterId());
final List<DataCenterVnetVO> vnis = _datacneterVnet.findVnet(network.getDataCenterId(), vnet);
if (vnis != null && !vnis.isEmpty()) {
for (final DataCenterVnetVO vni : vnis) {
if (vni.getPhysicalNetworkId() != network.getId()) {
s_logger.debug("VNI " + vnet + " already exists on another network in zone, please specify a unique range");
throw new InvalidParameterValueException("VNI " + vnet + " already exists on another network in zone, please specify a unique range");
}
}
}
}
}
final String rangeMessage = " between " + minVnet + " and " + maxVnet;
if (VnetRange.length == 1 && VnetRange[0].equals("")) {
return vlanTokens;
}
if (VnetRange.length < 2) {
throw new InvalidParameterValueException("Please provide valid vnet range. vnet range should be a coma seperated list of vlan ranges. example 500-500,600-601"
+ rangeMessage);
}
if (VnetRange[0] == null || VnetRange[1] == null) {
throw new InvalidParameterValueException("Please provide valid vnet range" + rangeMessage);
}
try {
StartVnet = Integer.parseInt(VnetRange[0]);
EndVnet = Integer.parseInt(VnetRange[1]);
} catch (final NumberFormatException e) {
s_logger.warn("Unable to parse vnet range:", e);
throw new InvalidParameterValueException("Please provide valid vnet range. The vnet range should be a coma seperated list example 2001-2012,3000-3005."
+ rangeMessage);
}
if (StartVnet < minVnet || EndVnet > maxVnet) {
throw new InvalidParameterValueException("Vnet range has to be" + rangeMessage);
}
if (StartVnet > EndVnet) {
throw new InvalidParameterValueException("Vnet range has to be" + rangeMessage + " and start range should be lesser than or equal to stop range");
}
vlanTokens.add(new Pair<>(StartVnet, EndVnet));
}
return vlanTokens;
}
private List<String> getVnetsToremove(final PhysicalNetworkVO network, final List<Pair<Integer, Integer>> vnetRanges) {
int i;
final List<String> removeVnets = new ArrayList<>();
final HashSet<String> vnetsInDb = new HashSet<>();
vnetsInDb.addAll(_datacneterVnet.listVnetsByPhysicalNetworkAndDataCenter(network.getDataCenterId(), network.getId()));
//remove all the vnets from vnets in db to check if there are any vnets that are not there in given list.
//remove all the vnets not in the list of vnets passed by the user.
if (vnetRanges.size() == 0) {
//this implies remove all vlans.
removeVnets.addAll(vnetsInDb);
final int allocated_vnets = _datacneterVnet.countAllocatedVnets(network.getId());
if (allocated_vnets > 0) {
throw new InvalidParameterValueException("physicalnetwork " + network.getId() + " has " + allocated_vnets + " vnets in use");
}
return removeVnets;
}
for (final Pair<Integer, Integer> vlan : vnetRanges) {
for (i = vlan.first(); i <= vlan.second(); i++) {
vnetsInDb.remove(Integer.toString(i));
}
}
String vnetRange = null;
if (vnetsInDb.size() != 0) {
removeVnets.addAll(vnetsInDb);
vnetRange = generateVnetString(removeVnets);
} else {
return removeVnets;
}
for (final String vnet : vnetRange.split(",")) {
final String[] range = vnet.split("-");
final Integer start = Integer.parseInt(range[0]);
final Integer end = Integer.parseInt(range[1]);
_datacneterVnet.lockRange(network.getDataCenterId(), network.getId(), start, end);
final List<DataCenterVnetVO> result = _datacneterVnet.listAllocatedVnetsInRange(network.getDataCenterId(), network.getId(), start, end);
if (!result.isEmpty()) {
throw new InvalidParameterValueException("physicalnetwork " + network.getId() + " has allocated vnets in the range " + start + "-" + end);
}
// If the range is partially dedicated to an account fail the request
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByPhysicalNetwork(network.getId());
for (final AccountGuestVlanMapVO map : maps) {
final String[] vlans = map.getGuestVlanRange().split("-");
final Integer dedicatedStartVlan = Integer.parseInt(vlans[0]);
final Integer dedicatedEndVlan = Integer.parseInt(vlans[1]);
if (start >= dedicatedStartVlan && start <= dedicatedEndVlan || end >= dedicatedStartVlan && end <= dedicatedEndVlan) {
throw new InvalidParameterValueException("Vnet range " + map.getGuestVlanRange() + " is dedicated" + " to an account. The specified range " + start + "-" + end
+ " overlaps with the dedicated range " + " Please release the overlapping dedicated range before deleting the range");
}
}
}
return removeVnets;
}
private String generateVnetString(final List<String> vnetList) {
Collections.sort(vnetList, new Comparator<String>() {
@Override
public int compare(final String s1, final String s2) {
return Integer.valueOf(s1).compareTo(Integer.valueOf(s2));
}
});
int i;
//build the vlan string form the sorted list.
String vnetRange = "";
String startvnet = vnetList.get(0);
String endvnet = "";
for (i = 0; i < vnetList.size() - 1; i++) {
if (Integer.parseInt(vnetList.get(i + 1)) - Integer.parseInt(vnetList.get(i)) > 1) {
endvnet = vnetList.get(i);
vnetRange = vnetRange + startvnet + "-" + endvnet + ",";
startvnet = vnetList.get(i + 1);
}
}
endvnet = vnetList.get(vnetList.size() - 1);
vnetRange = vnetRange + startvnet + "-" + endvnet + ",";
vnetRange = vnetRange.substring(0, vnetRange.length() - 1);
return vnetRange;
}
private boolean isNetworkSystem(final Network network) {
final NetworkOffering no = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId());
if (no.isSystemOnly()) {
return true;
} else {
return false;
}
}
private Network commitNetwork(final Long networkOfferingId, final String gateway, final String startIP, final String endIP, final String netmask, final String networkDomain,
final String vlanId, final String name, final String displayText, final Account caller, final Long physicalNetworkId, final Long zoneId,
final Long domainId, final boolean isDomainSpecific, final Boolean subdomainAccessFinal, final Long vpcId, final String startIPv6,
final String endIPv6, final String ip6Gateway, final String ip6Cidr, final Boolean displayNetwork, final Long aclId, final String isolatedPvlan,
final NetworkOfferingVO ntwkOff, final PhysicalNetwork pNtwk, final ACLType aclType, final Account ownerFinal, final String cidr,
final boolean createVlan, final String dns1, final String dns2, final String ipExclusionList) throws InsufficientCapacityException,
ResourceAllocationException {
try {
final Network network = Transaction.execute(new TransactionCallbackWithException<Network, Exception>() {
@Override
public Network doInTransaction(final TransactionStatus status) throws InsufficientCapacityException, ResourceAllocationException {
Account owner = ownerFinal;
Boolean subdomainAccess = subdomainAccessFinal;
Long sharedDomainId = null;
if (isDomainSpecific) {
if (domainId != null) {
sharedDomainId = domainId;
} else {
sharedDomainId = _domainMgr.getDomain(Domain.ROOT_DOMAIN).getId();
subdomainAccess = true;
}
}
// default owner to system if network has aclType=Domain
if (aclType == ACLType.Domain) {
owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM);
}
// Create guest network
Network network;
if (vpcId != null) {
if (!_configMgr.isOfferingForVpc(ntwkOff)) {
throw new InvalidParameterValueException("Network offering can't be used for VPC networks");
}
if (aclId != null) {
final NetworkACL acl = _networkACLDao.findById(aclId);
if (acl == null) {
throw new InvalidParameterValueException("Unable to find specified NetworkACL");
}
if (aclId != NetworkACL.DEFAULT_DENY && aclId != NetworkACL.DEFAULT_ALLOW) {
// ACL is not default DENY/ALLOW
// ACL should be associated with a VPC
if (!vpcId.equals(acl.getVpcId())) {
throw new InvalidParameterValueException("ACL: " + aclId + " do not belong to the VPC");
}
}
}
network = _vpcMgr.createVpcGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, zoneId,
aclType, subdomainAccess, vpcId, aclId, caller, displayNetwork, dns1, dns2, ipExclusionList);
} else {
if (_configMgr.isOfferingForVpc(ntwkOff)) {
throw new InvalidParameterValueException("Network offering can be used for VPC networks only");
}
network = _networkMgr.createGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, zoneId,
aclType, subdomainAccess, vpcId, ip6Gateway, ip6Cidr, displayNetwork, isolatedPvlan, dns1, dns2, ipExclusionList);
}
if (_accountMgr.isRootAdmin(caller.getId()) && createVlan && network != null) {
// Create vlan ip range
_configMgr.createVlanAndPublicIpRange(pNtwk.getDataCenterId(), network.getId(), physicalNetworkId, false, null, startIP, endIP, gateway, netmask, vlanId,
null, null, startIPv6, endIPv6, ip6Gateway, ip6Cidr);
}
return network;
}
});
return network;
} catch (final Exception e) {
ExceptionUtil.rethrowRuntime(e);
ExceptionUtil.rethrow(e, InsufficientCapacityException.class);
ExceptionUtil.rethrow(e, ResourceAllocationException.class);
throw new IllegalStateException(e);
}
}
private boolean isSharedNetworkOfferingWithServices(final long networkOfferingId) {
final NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId);
if (networkOffering.getGuestType() == Network.GuestType.Shared
&& (areServicesSupportedByNetworkOffering(networkOfferingId, Service.SourceNat) || areServicesSupportedByNetworkOffering(networkOfferingId, Service.StaticNat)
|| areServicesSupportedByNetworkOffering(networkOfferingId, Service.Firewall)
|| areServicesSupportedByNetworkOffering(networkOfferingId, Service.PortForwarding) || areServicesSupportedByNetworkOffering(networkOfferingId, Service.Lb))) {
return true;
}
return false;
}
protected boolean areServicesSupportedByNetworkOffering(final long networkOfferingId, final Service... services) {
return _ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(networkOfferingId, services);
}
@Override
@DB
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_configs = _configDao.getConfiguration("Network", params);
_cidrLimit = NumbersUtil.parseInt(_configs.get(Config.NetworkGuestCidrLimit.key()), 22);
_allowSubdomainNetworkAccess = Boolean.valueOf(_configs.get(Config.SubDomainNetworkAccess.key()));
s_logger.info("Network Service is configured.");
return true;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
private boolean checkForNonStoppedVmInNetwork(final long networkId) {
final List<UserVmVO> vms = _userVmDao.listByNetworkIdAndStates(networkId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Migrating,
VirtualMachine.State.Stopping);
return vms.isEmpty();
}
private boolean canUpgrade(final Network network, final long oldNetworkOfferingId, final long newNetworkOfferingId) {
final NetworkOffering oldNetworkOffering = _networkOfferingDao.findByIdIncludingRemoved(oldNetworkOfferingId);
final NetworkOffering newNetworkOffering = _networkOfferingDao.findById(newNetworkOfferingId);
// can upgrade only Isolated networks
if (oldNetworkOffering.getGuestType() != GuestType.Isolated) {
throw new InvalidParameterValueException("NetworkOfferingId can be upgraded only for the network of type " + GuestType.Isolated);
}
// Type of the network should be the same
if (oldNetworkOffering.getGuestType() != newNetworkOffering.getGuestType()) {
s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " are of different types, can't upgrade");
return false;
}
// tags should be the same
if (newNetworkOffering.getTags() != null) {
if (oldNetworkOffering.getTags() == null) {
s_logger.debug("New network offering id=" + newNetworkOfferingId + " has tags and old network offering id=" + oldNetworkOfferingId + " doesn't, can't upgrade");
return false;
}
if (!StringUtils.areTagsEqual(oldNetworkOffering.getTags(), newNetworkOffering.getTags())) {
s_logger.debug("Network offerings " + newNetworkOffering.getUuid() + " and " + oldNetworkOffering.getUuid() + " have different tags, can't upgrade");
return false;
}
}
// Traffic types should be the same
if (oldNetworkOffering.getTrafficType() != newNetworkOffering.getTrafficType()) {
s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different traffic types, can't upgrade");
return false;
}
// specify vlan should be the same
if (oldNetworkOffering.getSpecifyVlan() != newNetworkOffering.getSpecifyVlan()) {
s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different values for specifyVlan, can't upgrade");
return false;
}
// specify ipRanges should be the same
if (oldNetworkOffering.getSpecifyIpRanges() != newNetworkOffering.getSpecifyIpRanges()) {
s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different values for specifyIpRangess, can't upgrade");
return false;
}
// Check all ips
final List<IPAddressVO> userIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), null);
final List<PublicIp> publicIps = new ArrayList<>();
if (userIps != null && !userIps.isEmpty()) {
for (final IPAddressVO userIp : userIps) {
final PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
publicIps.add(publicIp);
}
}
if (oldNetworkOffering.isConserveMode() && !newNetworkOffering.isConserveMode()) {
if (!canIpsUsedForNonConserve(publicIps)) {
return false;
}
}
return canIpsUseOffering(publicIps, newNetworkOfferingId);
}
@Inject
public void setNetworkGurus(final List<NetworkGuru> networkGurus) {
_networkGurus = networkGurus;
}
}
|
cosmic-core/server/src/main/java/com/cloud/network/NetworkServiceImpl.java
|
package com.cloud.network;
import com.cloud.acl.ControlledEntity.ACLType;
import com.cloud.acl.SecurityChecker.AccessType;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.command.admin.network.DedicateGuestVlanRangeCmd;
import com.cloud.api.command.admin.network.ListDedicatedGuestVlanRangesCmd;
import com.cloud.api.command.user.network.CreateNetworkCmd;
import com.cloud.api.command.user.network.ListNetworksCmd;
import com.cloud.api.command.user.network.RestartNetworkCmd;
import com.cloud.api.command.user.vm.ListNicsCmd;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.Resource;
import com.cloud.context.CallContext;
import com.cloud.dao.EntityManager;
import com.cloud.db.model.Zone;
import com.cloud.db.repository.ZoneRepository;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.DataCenterVnetVO;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.DataCenterVnetDao;
import com.cloud.dc.dao.VlanDao;
import com.cloud.deploy.DeployDestination;
import com.cloud.domain.Domain;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.engine.orchestration.service.NetworkOrchestrationService;
import com.cloud.event.ActionEvent;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.UnsupportedServiceException;
import com.cloud.framework.config.dao.ConfigurationDao;
import com.cloud.model.enumeration.AllocationState;
import com.cloud.model.enumeration.NetworkType;
import com.cloud.network.IpAddress.State;
import com.cloud.network.Network.Capability;
import com.cloud.network.Network.GuestType;
import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.PhysicalNetwork.BroadcastDomainRange;
import com.cloud.network.VirtualRouterProvider.Type;
import com.cloud.network.addr.PublicIp;
import com.cloud.network.dao.AccountGuestVlanMapDao;
import com.cloud.network.dao.AccountGuestVlanMapVO;
import com.cloud.network.dao.FirewallRulesDao;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.dao.IPAddressVO;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkDomainDao;
import com.cloud.network.dao.NetworkDomainVO;
import com.cloud.network.dao.NetworkServiceMapDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.dao.PhysicalNetworkDao;
import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
import com.cloud.network.dao.PhysicalNetworkServiceProviderVO;
import com.cloud.network.dao.PhysicalNetworkTrafficTypeDao;
import com.cloud.network.dao.PhysicalNetworkTrafficTypeVO;
import com.cloud.network.dao.PhysicalNetworkVO;
import com.cloud.network.element.NetworkElement;
import com.cloud.network.element.VirtualRouterElement;
import com.cloud.network.element.VpcVirtualRouterElement;
import com.cloud.network.guru.NetworkGuru;
import com.cloud.network.lb.LoadBalancingRulesService;
import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.network.rules.FirewallRuleVO;
import com.cloud.network.rules.RulesManager;
import com.cloud.network.rules.dao.PortForwardingRulesDao;
import com.cloud.network.vpc.NetworkACL;
import com.cloud.network.vpc.PrivateIpVO;
import com.cloud.network.vpc.StaticRoute;
import com.cloud.network.vpc.Vpc;
import com.cloud.network.vpc.VpcManager;
import com.cloud.network.vpc.dao.NetworkACLDao;
import com.cloud.network.vpc.dao.PrivateIpDao;
import com.cloud.network.vpc.dao.StaticRouteDao;
import com.cloud.offering.NetworkOffering;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
import com.cloud.projects.Project;
import com.cloud.projects.ProjectManager;
import com.cloud.server.ResourceTag.ResourceObjectType;
import com.cloud.tags.ResourceTagVO;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO;
import com.cloud.user.DomainManager;
import com.cloud.user.ResourceLimitService;
import com.cloud.user.User;
import com.cloud.user.UserVO;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.Journal;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.StringUtils;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallback;
import com.cloud.utils.db.TransactionCallbackNoReturn;
import com.cloud.utils.db.TransactionCallbackWithException;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.exception.ExceptionUtil;
import com.cloud.utils.exception.InvalidParameterValueException;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.Nic;
import com.cloud.vm.NicSecondaryIp;
import com.cloud.vm.NicVO;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.ReservationContextImpl;
import com.cloud.vm.SecondaryStorageVmVO;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.NicSecondaryIpDao;
import com.cloud.vm.dao.NicSecondaryIpVO;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.security.InvalidParameterException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* NetworkServiceImpl implements NetworkService.
*/
public class NetworkServiceImpl extends ManagerBase implements NetworkService {
private static final Logger s_logger = LoggerFactory.getLogger(NetworkServiceImpl.class);
private static final long MIN_VLAN_ID = 0L;
private static final long MAX_VLAN_ID = 4095L; // 2^12 - 1
private static final long MIN_GRE_KEY = 0L;
private static final long MAX_GRE_KEY = 4294967295L; // 2^32 -1
private static final long MIN_VXLAN_VNI = 0L;
private static final long MAX_VXLAN_VNI = 16777214L; // 2^24 -2
// MAX_VXLAN_VNI should be 16777215L (2^24-1), but Linux vxlan interface doesn't accept VNI:2^24-1 now.
// It seems a bug.
@Inject
DataCenterDao _dcDao = null;
@Inject
private
VlanDao _vlanDao = null;
@Inject
private
IPAddressDao _ipAddressDao = null;
@Inject
AccountDao _accountDao = null;
@Inject
private
DomainDao _domainDao = null;
@Inject
private
UserDao _userDao = null;
@Inject
private
ConfigurationDao _configDao;
@Inject
private
UserVmDao _userVmDao = null;
@Inject
AccountManager _accountMgr;
@Inject
private
ConfigurationManager _configMgr;
@Inject
NetworkOfferingDao _networkOfferingDao = null;
@Inject
NetworkDao _networksDao = null;
@Inject
private
NicDao _nicDao = null;
@Inject
private
RulesManager _rulesMgr;
@Inject
private
NetworkDomainDao _networkDomainDao;
@Inject
private
VMInstanceDao _vmDao;
@Inject
private
FirewallRulesDao _firewallDao;
@Inject
private
ResourceLimitService _resourceLimitMgr;
@Inject
private
DomainManager _domainMgr;
@Inject
ProjectManager _projectMgr;
@Inject
private
NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao;
@Inject
PhysicalNetworkDao _physicalNetworkDao;
@Inject
private
PhysicalNetworkServiceProviderDao _pNSPDao;
@Inject
private
PhysicalNetworkTrafficTypeDao _pNTrafficTypeDao;
@Inject
private
NetworkServiceMapDao _ntwkSrvcDao;
@Inject
private
StorageNetworkManager _stnwMgr;
@Inject
private
VpcManager _vpcMgr;
@Inject
PrivateIpDao _privateIpDao;
@Inject
private
ResourceTagDao _resourceTagDao;
@Inject
NetworkOrchestrationService _networkMgr;
@Inject
private
NetworkModel _networkModel;
@Inject
private
NicSecondaryIpDao _nicSecondaryIpDao;
@Inject
private
PortForwardingRulesDao _portForwardingDao;
@Inject
DataCenterVnetDao _datacneterVnet;
@Inject
AccountGuestVlanMapDao _accountGuestVlanMapDao;
@Inject
private
NetworkACLDao _networkACLDao;
@Inject
private
IpAddressManager _ipAddrMgr;
@Inject
private
EntityManager _entityMgr;
@Inject
private
StaticRouteDao _staticRouteDao;
@Inject
private
LoadBalancingRulesService _lbService;
@Inject
private
ZoneRepository zoneRepository;
private int _cidrLimit;
private boolean _allowSubdomainNetworkAccess;
private List<NetworkGuru> _networkGurus;
private Map<String, String> _configs;
NetworkServiceImpl() {
}
/* Get a list of IPs, classify them by service */
protected Map<PublicIp, Set<Service>> getIpToServices(final List<PublicIp> publicIps, final boolean rulesRevoked, final boolean includingFirewall) {
final Map<PublicIp, Set<Service>> ipToServices = new HashMap<>();
if (publicIps != null && !publicIps.isEmpty()) {
final Set<Long> networkSNAT = new HashSet<>();
for (final PublicIp ip : publicIps) {
Set<Service> services = ipToServices.get(ip);
if (services == null) {
services = new HashSet<>();
}
if (ip.isSourceNat()) {
if (!networkSNAT.contains(ip.getAssociatedWithNetworkId())) {
services.add(Service.SourceNat);
networkSNAT.add(ip.getAssociatedWithNetworkId());
} else {
final CloudRuntimeException ex = new CloudRuntimeException("Multiple generic soure NAT IPs provided for network");
// see the IPAddressVO.java class.
final IPAddressVO ipAddr = ApiDBUtils.findIpAddressById(ip.getAssociatedWithNetworkId());
String ipAddrUuid = ip.getAssociatedWithNetworkId().toString();
if (ipAddr != null) {
ipAddrUuid = ipAddr.getUuid();
}
ex.addProxyObject(ipAddrUuid, "networkId");
throw ex;
}
}
ipToServices.put(ip, services);
// if IP in allocating state then it will not have any rules attached so skip IPAssoc to network service
// provider
if (ip.getState() == State.Allocating) {
continue;
}
// check if any active rules are applied on the public IP
Set<Purpose> purposes = getPublicIpPurposeInRules(ip, false, includingFirewall);
// Firewall rules didn't cover static NAT
if (ip.isOneToOneNat() && ip.getAssociatedWithVmId() != null) {
if (purposes == null) {
purposes = new HashSet<>();
}
purposes.add(Purpose.StaticNat);
}
if (purposes == null || purposes.isEmpty()) {
// since no active rules are there check if any rules are applied on the public IP but are in
// revoking state
purposes = getPublicIpPurposeInRules(ip, true, includingFirewall);
if (ip.isOneToOneNat()) {
if (purposes == null) {
purposes = new HashSet<>();
}
purposes.add(Purpose.StaticNat);
}
if (purposes == null || purposes.isEmpty()) {
// IP is not being used for any purpose so skip IPAssoc to network service provider
continue;
} else {
if (rulesRevoked) {
// no active rules/revoked rules are associated with this public IP, so remove the
// association with the provider
ip.setState(State.Releasing);
} else {
if (ip.getState() == State.Releasing) {
// rules are not revoked yet, so don't let the network service provider revoke the IP
// association
// mark IP is allocated so that IP association will not be removed from the provider
ip.setState(State.Allocated);
}
}
}
}
if (purposes.contains(Purpose.StaticNat)) {
services.add(Service.StaticNat);
}
if (purposes.contains(Purpose.LoadBalancing)) {
services.add(Service.Lb);
}
if (purposes.contains(Purpose.PortForwarding)) {
services.add(Service.PortForwarding);
}
if (purposes.contains(Purpose.Vpn)) {
services.add(Service.Vpn);
}
if (purposes.contains(Purpose.Firewall)) {
services.add(Service.Firewall);
}
if (services.isEmpty()) {
continue;
}
ipToServices.put(ip, services);
}
}
return ipToServices;
}
private boolean canIpUsedForNonConserveService(final PublicIp ip, final Service service) {
// If it's non-conserve mode, then the new ip should not be used by any other services
final List<PublicIp> ipList = new ArrayList<>();
ipList.add(ip);
final Map<PublicIp, Set<Service>> ipToServices = getIpToServices(ipList, false, false);
final Set<Service> services = ipToServices.get(ip);
// Not used currently, safe
if (services == null || services.isEmpty()) {
return true;
}
return true;
}
private boolean canIpsUsedForNonConserve(final List<PublicIp> publicIps) {
boolean result = true;
for (final PublicIp ip : publicIps) {
result = canIpUsedForNonConserveService(ip, null);
if (!result) {
break;
}
}
return result;
}
private boolean canIpsUseOffering(final List<PublicIp> publicIps, final long offeringId) {
final Map<PublicIp, Set<Service>> ipToServices = getIpToServices(publicIps, false, true);
final Map<Service, Set<Provider>> serviceToProviders = _networkModel.getNetworkOfferingServiceProvidersMap(offeringId);
final NetworkOfferingVO offering = _networkOfferingDao.findById(offeringId);
//For inline mode checking, using firewall provider for LB instead, because public ip would apply on firewall provider
if (offering.isInline()) {
Provider firewallProvider = null;
if (serviceToProviders.containsKey(Service.Firewall)) {
firewallProvider = (Provider) serviceToProviders.get(Service.Firewall).toArray()[0];
}
final Set<Provider> p = new HashSet<>();
p.add(firewallProvider);
serviceToProviders.remove(Service.Lb);
serviceToProviders.put(Service.Lb, p);
}
for (final PublicIp ip : ipToServices.keySet()) {
final Set<Service> services = ipToServices.get(ip);
Provider provider = null;
for (final Service service : services) {
final Set<Provider> curProviders = serviceToProviders.get(service);
if (curProviders == null || curProviders.isEmpty()) {
continue;
}
final Provider curProvider = (Provider) curProviders.toArray()[0];
if (provider == null) {
provider = curProvider;
continue;
}
// We don't support multiple providers for one service now
if (!provider.equals(curProvider)) {
throw new InvalidParameterException("There would be multiple providers for IP " + ip.getAddress() + " with the new network offering!");
}
}
}
return true;
}
private Set<Purpose> getPublicIpPurposeInRules(final PublicIp ip, final boolean includeRevoked, final boolean includingFirewall) {
final Set<Purpose> result = new HashSet<>();
List<FirewallRuleVO> rules = null;
if (includeRevoked) {
rules = _firewallDao.listByIp(ip.getId());
} else {
rules = _firewallDao.listByIpAndNotRevoked(ip.getId());
}
if (rules == null || rules.isEmpty()) {
return null;
}
for (final FirewallRuleVO rule : rules) {
if (rule.getPurpose() != Purpose.Firewall || includingFirewall) {
result.add(rule.getPurpose());
}
}
return result;
}
@Override
public List<? extends Network> getIsolatedNetworksOwnedByAccountInZone(final long zoneId, final Account owner) {
return _networksDao.listByZoneAndGuestType(owner.getId(), zoneId, Network.GuestType.Isolated, false);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "allocating Ip", create = true)
public IpAddress allocateIP(final Account ipOwner, final long zoneId, final Long networkId, final Boolean displayIp) throws ResourceAllocationException,
InsufficientAddressCapacityException,
ConcurrentOperationException {
final Account caller = CallContext.current().getCallingAccount();
final long callerUserId = CallContext.current().getCallingUserId();
final DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId);
if (networkId != null) {
final Network network = _networksDao.findById(networkId);
if (network == null) {
throw new InvalidParameterValueException("Invalid network id is given");
}
if (network.getGuestType() == Network.GuestType.Shared) {
if (zone == null) {
throw new InvalidParameterValueException("Invalid zone Id is given");
}
// if shared network in the advanced zone, then check the caller against the network for 'AccessType.UseNetwork'
if (zone.getNetworkType() == NetworkType.Advanced) {
if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) {
_accountMgr.checkAccess(caller, AccessType.UseEntry, false, network);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId());
}
return _ipAddrMgr.allocateIp(ipOwner, false, caller, callerUserId, zone, displayIp);
} else {
throw new InvalidParameterValueException("Associate IP address can only be called on the shared networks in the advanced zone"
+ " with Firewall/Source Nat/Static Nat/Port Forwarding/Load balancing services enabled");
}
}
}
} else {
_accountMgr.checkAccess(caller, null, false, ipOwner);
}
return _ipAddrMgr.allocateIp(ipOwner, false, caller, callerUserId, zone, displayIp);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_IP_RELEASE, eventDescription = "disassociating Ip", async = true)
public boolean releaseIpAddress(final long ipAddressId) throws InsufficientAddressCapacityException {
return releaseIpAddressInternal(ipAddressId);
}
@DB
private boolean releaseIpAddressInternal(final long ipAddressId) throws InsufficientAddressCapacityException {
final Long userId = CallContext.current().getCallingUserId();
final Account caller = CallContext.current().getCallingAccount();
// Verify input parameters
final IPAddressVO ipVO = _ipAddressDao.findById(ipAddressId);
if (ipVO == null) {
throw new InvalidParameterValueException("Unable to find ip address by id");
}
if (ipVO.getAllocatedTime() == null) {
s_logger.debug("Ip Address id= " + ipAddressId + " is not allocated, so do nothing.");
return true;
}
// verify permissions
if (ipVO.getAllocatedToAccountId() != null) {
_accountMgr.checkAccess(caller, null, true, ipVO);
}
if (ipVO.isSourceNat()) {
throw new IllegalArgumentException("ip address is used for source nat purposes and can not be disassociated.");
}
final VlanVO vlan = _vlanDao.findById(ipVO.getVlanId());
if (!vlan.getVlanType().equals(VlanType.VirtualNetwork)) {
throw new IllegalArgumentException("only ip addresses that belong to a virtual network may be disassociated.");
}
// don't allow releasing system ip address
if (ipVO.getSystem()) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't release system IP address with specified id");
ex.addProxyObject(ipVO.getUuid(), "systemIpAddrId");
throw ex;
}
final boolean success = _ipAddrMgr.disassociatePublicIpAddress(ipAddressId, userId, caller);
if (success) {
final Long networkId = ipVO.getAssociatedWithNetworkId();
if (networkId != null) {
final Network guestNetwork = getNetwork(networkId);
final NetworkOffering offering = _entityMgr.findById(NetworkOffering.class, guestNetwork.getNetworkOfferingId());
final Long vmId = ipVO.getAssociatedWithVmId();
if (offering.getElasticIp() && vmId != null) {
_rulesMgr.getSystemIpAndEnableStaticNatForVm(_userVmDao.findById(vmId), true);
return true;
}
}
} else {
s_logger.warn("Failed to release public ip address id=" + ipAddressId);
}
return success;
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_CREATE, eventDescription = "creating network")
public Network createGuestNetwork(final CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException {
final Long networkOfferingId = cmd.getNetworkOfferingId();
String gateway = cmd.getGateway();
final String startIP = cmd.getStartIp();
String endIP = cmd.getEndIp();
final String netmask = cmd.getNetmask();
final String networkDomain = cmd.getNetworkDomain();
final String vlanId = cmd.getVlan();
final String name = cmd.getNetworkName();
final String displayText = cmd.getDisplayText();
final Account caller = CallContext.current().getCallingAccount();
final Long physicalNetworkId = cmd.getPhysicalNetworkId();
Long zoneId = cmd.getZoneId();
final String aclTypeStr = cmd.getAclType();
final Long domainId = cmd.getDomainId();
boolean isDomainSpecific = false;
final Boolean subdomainAccess = cmd.getSubdomainAccess();
final Long vpcId = cmd.getVpcId();
final String startIPv6 = cmd.getStartIpv6();
String endIPv6 = cmd.getEndIpv6();
String ip6Gateway = cmd.getIp6Gateway();
final String ip6Cidr = cmd.getIp6Cidr();
Boolean displayNetwork = cmd.getDisplayNetwork();
final Long aclId = cmd.getAclId();
final String isolatedPvlan = cmd.getIsolatedPvlan();
final String dns1 = cmd.getDns1();
final String dns2 = cmd.getDns2();
final String ipExclusionList = cmd.getIpExclusionList();
// Validate network offering
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
if (ntwkOff == null || ntwkOff.isSystemOnly()) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering by specified id");
if (ntwkOff != null) {
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
}
throw ex;
}
if (!GuestType.Private.equals(ntwkOff.getGuestType()) && vpcId == null) {
throw new InvalidParameterValueException("VPC ID is required");
}
if (GuestType.Private.equals(ntwkOff.getGuestType()) && (startIP != null || endIP != null || vpcId != null || gateway != null || netmask != null)) {
throw new InvalidParameterValueException("StartIp/endIp/vpcId/gateway/netmask can't be specified for guest type " + GuestType.Private);
}
// validate physical network and zone
// Check if physical network exists
PhysicalNetwork pNtwk = null;
if (physicalNetworkId != null) {
pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
if (pNtwk == null) {
throw new InvalidParameterValueException("Unable to find a physical network having the specified physical network id");
}
}
if (zoneId == null) {
zoneId = pNtwk.getDataCenterId();
}
if (displayNetwork == null) {
displayNetwork = true;
}
final Zone zone = zoneRepository.findById(zoneId).orElse(null);
if (zone == null) {
throw new InvalidParameterValueException("Specified zone id was not found");
}
if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
// See DataCenterVO.java
final PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation since specified Zone is currently disabled");
ex.addProxyObject(zone.getUuid(), "zoneId");
throw ex;
}
// Only domain and account ACL types are supported in Acton.
ACLType aclType = null;
if (aclTypeStr != null) {
if (aclTypeStr.equalsIgnoreCase(ACLType.Account.toString())) {
aclType = ACLType.Account;
} else if (aclTypeStr.equalsIgnoreCase(ACLType.Domain.toString())) {
aclType = ACLType.Domain;
} else {
throw new InvalidParameterValueException("Incorrect aclType specified. Check the API documentation for supported types");
}
// In 3.0 all Shared networks should have aclType == Domain, all Isolated networks aclType==Account
if (ntwkOff.getGuestType() != GuestType.Shared) {
if (aclType != ACLType.Account) {
throw new InvalidParameterValueException("AclType should be " + ACLType.Account + " for network of type " + ntwkOff.getGuestType());
}
} else if (ntwkOff.getGuestType() == GuestType.Shared) {
if (!(aclType == ACLType.Domain || aclType == ACLType.Account)) {
throw new InvalidParameterValueException("AclType should be " + ACLType.Domain + " or " + ACLType.Account + " for network of type " + Network.GuestType.Shared);
}
}
} else {
aclType = (ntwkOff.getGuestType() == GuestType.Shared)
? ACLType.Domain
: ACLType.Account;
}
// Only Admin can create Shared networks
if (ntwkOff.getGuestType() == GuestType.Shared && !_accountMgr.isAdmin(caller.getId())) {
throw new InvalidParameterValueException("Only Admins can create network with guest type " + GuestType.Shared);
}
// Check if the network is domain specific
if (aclType == ACLType.Domain) {
// only Admin can create domain with aclType=Domain
if (!_accountMgr.isAdmin(caller.getId())) {
throw new PermissionDeniedException("Only admin can create networks with aclType=Domain");
}
// only shared networks can be Domain specific
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only " + GuestType.Shared + " networks can have aclType=" + ACLType.Domain);
}
if (domainId != null) {
if (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Shared) {
throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and guest type "
+ Network.GuestType.Shared);
}
final DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Unable to find domain by specified id");
}
_accountMgr.checkAccess(caller, domain);
}
isDomainSpecific = true;
} else if (subdomainAccess != null) {
throw new InvalidParameterValueException("Parameter subDomainAccess can be specified only with aclType=Domain");
}
Account owner = null;
if (cmd.getAccountName() != null && domainId != null || cmd.getProjectId() != null) {
owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), domainId, cmd.getProjectId());
} else {
owner = caller;
}
boolean ipv4 = true, ipv6 = false;
if (startIP != null) {
ipv4 = true;
}
if (startIPv6 != null) {
ipv6 = true;
}
if (gateway != null) {
try {
// getByName on a literal representation will only check validity of the address
// http://docs.oracle.com/javase/6/docs/api/java/net/InetAddress.html#getByName(java.lang.String)
final InetAddress gatewayAddress = InetAddress.getByName(gateway);
if (gatewayAddress instanceof Inet6Address) {
ipv6 = true;
} else {
ipv4 = true;
}
} catch (final UnknownHostException e) {
s_logger.error("Unable to convert gateway IP to a InetAddress", e);
throw new InvalidParameterValueException("Gateway parameter is invalid");
}
}
String cidr = cmd.getCidr();
if (ipv4) {
// validate the CIDR
if (cidr != null && !NetUtils.isValidIp4Cidr(cidr)) {
throw new InvalidParameterValueException("Invalid format for the CIDR parameter");
}
// validate gateway with cidr
if (cidr != null && gateway != null && !NetUtils.isIpWithtInCidrRange(gateway, cidr)) {
throw new InvalidParameterValueException("The gateway ip " + gateway + " should be part of the CIDR of the network " + cidr);
}
// if end ip is not specified, default it to startIp
if (startIP != null) {
if (!NetUtils.isValidIp4(startIP)) {
throw new InvalidParameterValueException("Invalid format for the startIp parameter");
}
if (endIP == null) {
endIP = startIP;
} else if (!NetUtils.isValidIp4(endIP)) {
throw new InvalidParameterValueException("Invalid format for the endIp parameter");
}
}
if (startIP != null && endIP != null) {
if (!(gateway != null && netmask != null)) {
throw new InvalidParameterValueException("gateway and netmask should be defined when startIP/endIP are passed in");
}
}
if (gateway != null && netmask != null) {
if (NetUtils.isNetworkorBroadcastIP(gateway, netmask)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("The gateway IP provided is " + gateway + " and netmask is " + netmask + ". The IP is either broadcast or network IP.");
}
throw new InvalidParameterValueException("Invalid gateway IP provided. Either the IP is broadcast or network IP.");
}
if (!NetUtils.isValidIp4(gateway)) {
throw new InvalidParameterValueException("Invalid gateway");
}
if (!NetUtils.isValidIp4Netmask(netmask)) {
throw new InvalidParameterValueException("Invalid netmask");
}
cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
}
checkIpExclusionList(ipExclusionList, cidr, null);
}
if (ipv6) {
// validate the ipv6 CIDR
if (ip6Cidr != null && !NetUtils.isValidIp4Cidr(ip6Cidr)) {
throw new InvalidParameterValueException("Invalid format for the CIDR parameter");
}
if (endIPv6 == null) {
endIPv6 = startIPv6;
}
_networkModel.checkIp6Parameters(startIPv6, endIPv6, ip6Gateway, ip6Cidr);
if (zone.getNetworkType() != NetworkType.Advanced || ntwkOff.getGuestType() != Network.GuestType.Shared) {
throw new InvalidParameterValueException("Can only support create IPv6 network with advance shared network!");
}
}
if (isolatedPvlan != null && (zone.getNetworkType() != NetworkType.Advanced || ntwkOff.getGuestType() != Network.GuestType.Shared)) {
throw new InvalidParameterValueException("Can only support create Private VLAN network with advance shared network!");
}
if (isolatedPvlan != null && ipv6) {
throw new InvalidParameterValueException("Can only support create Private VLAN network with IPv4!");
}
// Regular user can create Guest Isolated Source Nat enabled network only
if (_accountMgr.isNormalUser(caller.getId())
&& (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Isolated
&& areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("Regular user can create a network only from the network offering having traffic type " + TrafficType.Guest
+ " and network type " + Network.GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled");
}
// Don't allow to specify vlan if the caller is a normal user
if (_accountMgr.isNormalUser(caller.getId()) && (ntwkOff.getSpecifyVlan() || vlanId != null)) {
throw new InvalidParameterValueException("Only ROOT admin and domain admins are allowed to specify vlanId");
}
if (ipv4) {
// For non-root admins check cidr limit - if it's allowed by global config value
if (!_accountMgr.isRootAdmin(caller.getId()) && cidr != null) {
final String[] cidrPair = cidr.split("\\/");
final int cidrSize = Integer.parseInt(cidrPair[1]);
if (cidrSize < _cidrLimit) {
throw new InvalidParameterValueException("Cidr size can't be less than " + _cidrLimit);
}
}
}
// Vlan is created in 1 cases - works in Advance zone only:
// 1) GuestType is Shared
boolean createVlan = startIP != null && endIP != null && zone.getNetworkType() == NetworkType.Advanced
&& (ntwkOff.getGuestType() == Network.GuestType.Shared || !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat));
if (!createVlan) {
// Only support advance shared network in IPv6, which means createVlan is a must
if (ipv6) {
createVlan = true;
}
}
// Can add vlan range only to the network which allows it
if (createVlan && !ntwkOff.getSpecifyIpRanges()) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id doesn't support adding multiple ip ranges");
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
if (ntwkOff.getGuestType() != GuestType.Private && gateway == null && cidr != null) {
gateway = NetUtils.getCidrHostAddress(cidr);
}
if (ntwkOff.getGuestType() != GuestType.Private && ip6Gateway == null && ip6Cidr != null) {
ip6Gateway = NetUtils.getCidrHostAddress6(ip6Cidr);
}
Network network = commitNetwork(networkOfferingId, gateway, startIP, endIP, netmask, networkDomain, vlanId, name, displayText, caller, physicalNetworkId, zoneId, domainId,
isDomainSpecific, subdomainAccess, vpcId, startIPv6, endIPv6, ip6Gateway, ip6Cidr, displayNetwork, aclId, isolatedPvlan, ntwkOff, pNtwk, aclType, owner, cidr,
createVlan, dns1, dns2, ipExclusionList);
// if the network offering has persistent set to true, implement the network
if (ntwkOff.getIsPersistent()) {
try {
if (network.getState() == Network.State.Setup) {
s_logger.debug("Network id=" + network.getId() + " is already provisioned");
return network;
}
final DeployDestination dest = new DeployDestination(zone, null, null, null);
final UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
final Journal journal = new Journal.LogJournal("Implementing " + network, s_logger);
final ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(), journal, callerUser, caller);
s_logger.debug("Implementing network " + network + " as a part of network provision for persistent network");
final Pair<? extends NetworkGuru, ? extends Network> implementedNetwork = _networkMgr.implementNetwork(network.getId(), dest, context);
if (implementedNetwork == null || implementedNetwork.first() == null) {
s_logger.warn("Failed to provision the network " + network);
}
network = implementedNetwork.second();
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to implement persistent guest network " + network + "due to: " + ex.getMessage());
final CloudRuntimeException e = new CloudRuntimeException("Failed to implement persistent guest network", ex);
e.addProxyObject(network.getUuid(), "networkId");
throw e;
}
}
return network;
}
private void checkIpExclusionList(final String ipExclusionList, final String cidr, final List<NicVO> nicsPresent) {
if (StringUtils.isNotBlank(ipExclusionList)) {
// validate ipExclusionList
// Perform a "syntax" check on the list
if (!NetUtils.validIpRangeList(ipExclusionList)) {
throw new InvalidParameterValueException("Syntax error in ipExclusionList");
}
final List<String> excludedIps = NetUtils.getAllIpsFromRangeList(ipExclusionList);
if (cidr != null) {
//Check that ipExclusionList (delimiters) is within the CIDR
if (!NetUtils.isIpRangeListInCidr(ipExclusionList, cidr)) {
throw new InvalidParameterValueException("An IP in the ipExclusionList is not part of the CIDR of the network " + cidr);
}
//Check that at least one IP is available after exclusion for the router interface
final SortedSet<Long> allPossibleIps = NetUtils.getAllIpsFromCidr(cidr, NetUtils.listIp2LongList(excludedIps));
if (allPossibleIps.isEmpty()) {
throw new InvalidParameterValueException("The ipExclusionList excludes all IPs in the CIDR; at least one needs to be available");
}
}
if (nicsPresent != null) {
// Check that no existing nics/ips are part of the exclusion list
for (final NicVO nic : nicsPresent) {
final String nicIp = nic.getIPv4Address();
//check if nic IP is exclusionList
if (excludedIps.contains(nicIp) && !(Nic.State.Deallocating.equals(nic.getState()))) {
throw new InvalidParameterValueException("Active IP " + nic.getIPv4Address() + " exist in ipExclusionList.");
}
}
}
}
}
@Override
public Pair<List<? extends Network>, Integer> searchForNetworks(final ListNetworksCmd cmd) {
final Long id = cmd.getId();
final String keyword = cmd.getKeyword();
final Long zoneId = cmd.getZoneId();
final Account caller = CallContext.current().getCallingAccount();
Long domainId = cmd.getDomainId();
final String accountName = cmd.getAccountName();
final String guestIpType = cmd.getGuestIpType();
final String trafficType = cmd.getTrafficType();
Boolean isSystem = cmd.getIsSystem();
final String aclType = cmd.getAclType();
final Long projectId = cmd.getProjectId();
final List<Long> permittedAccounts = new ArrayList<>();
String path = null;
final Long physicalNetworkId = cmd.getPhysicalNetworkId();
final List<String> supportedServicesStr = cmd.getSupportedServices();
final Boolean restartRequired = cmd.getRestartRequired();
final boolean listAll = cmd.listAll();
boolean isRecursive = cmd.isRecursive();
final Boolean specifyIpRanges = cmd.getSpecifyIpRanges();
final Long vpcId = cmd.getVpcId();
final Boolean canUseForDeploy = cmd.canUseForDeploy();
final Map<String, String> tags = cmd.getTags();
final Boolean forVpc = cmd.getForVpc();
final Boolean display = cmd.getDisplay();
// 1) default is system to false if not specified
// 2) reset parameter to false if it's specified by the regular user
if ((isSystem == null || _accountMgr.isNormalUser(caller.getId())) && id == null) {
isSystem = false;
}
// Account/domainId parameters and isSystem are mutually exclusive
if (isSystem != null && isSystem && (accountName != null || domainId != null)) {
throw new InvalidParameterValueException("System network belongs to system, account and domainId parameters can't be specified");
}
if (domainId != null) {
final DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
// see DomainVO.java
throw new InvalidParameterValueException("Specified domain id doesn't exist in the system");
}
_accountMgr.checkAccess(caller, domain);
if (accountName != null) {
final Account owner = _accountMgr.getActiveAccountByName(accountName, domainId);
if (owner == null) {
// see DomainVO.java
throw new InvalidParameterValueException("Unable to find account " + accountName + " in specified domain");
}
_accountMgr.checkAccess(caller, null, true, owner);
permittedAccounts.add(owner.getId());
}
}
if (!_accountMgr.isAdmin(caller.getId()) || projectId != null && projectId.longValue() != -1 && domainId == null) {
permittedAccounts.add(caller.getId());
domainId = caller.getDomainId();
}
// set project information
boolean skipProjectNetworks = true;
if (projectId != null) {
if (projectId.longValue() == -1) {
if (!_accountMgr.isAdmin(caller.getId())) {
permittedAccounts.addAll(_projectMgr.listPermittedProjectAccounts(caller.getId()));
}
} else {
permittedAccounts.clear();
final Project project = _projectMgr.getProject(projectId);
if (project == null) {
throw new InvalidParameterValueException("Unable to find project by specified id");
}
if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) {
// getProject() returns type ProjectVO.
final InvalidParameterValueException ex = new InvalidParameterValueException("Account " + caller + " cannot access specified project id");
ex.addProxyObject(project.getUuid(), "projectId");
throw ex;
}
//add project account
permittedAccounts.add(project.getProjectAccountId());
//add caller account (if admin)
if (_accountMgr.isAdmin(caller.getId())) {
permittedAccounts.add(caller.getId());
}
}
skipProjectNetworks = false;
}
if (domainId != null) {
path = _domainDao.findById(domainId).getPath();
} else {
path = _domainDao.findById(caller.getDomainId()).getPath();
}
if (listAll && domainId == null) {
isRecursive = true;
}
final Filter searchFilter = new Filter(NetworkVO.class, "id", false, null, null);
final SearchBuilder<NetworkVO> sb = _networksDao.createSearchBuilder();
if (forVpc != null) {
if (forVpc) {
sb.and("vpc", sb.entity().getVpcId(), Op.NNULL);
} else {
sb.and("vpc", sb.entity().getVpcId(), Op.NULL);
}
}
// Don't display networks created of system network offerings
final SearchBuilder<NetworkOfferingVO> networkOfferingSearch = _networkOfferingDao.createSearchBuilder();
networkOfferingSearch.and("systemOnly", networkOfferingSearch.entity().isSystemOnly(), SearchCriteria.Op.EQ);
if (isSystem != null && isSystem) {
networkOfferingSearch.and("trafficType", networkOfferingSearch.entity().getTrafficType(), SearchCriteria.Op.EQ);
}
sb.join("networkOfferingSearch", networkOfferingSearch, sb.entity().getNetworkOfferingId(), networkOfferingSearch.entity().getId(), JoinBuilder.JoinType.INNER);
final SearchBuilder<DataCenterVO> zoneSearch = _dcDao.createSearchBuilder();
zoneSearch.and("networkType", zoneSearch.entity().getNetworkType(), SearchCriteria.Op.EQ);
sb.join("zoneSearch", zoneSearch, sb.entity().getDataCenterId(), zoneSearch.entity().getId(), JoinBuilder.JoinType.INNER);
sb.and("removed", sb.entity().getRemoved(), Op.NULL);
if (tags != null && !tags.isEmpty()) {
final SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
for (int count = 0; count < tags.size(); count++) {
tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
tagSearch.cp();
}
tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
sb.groupBy(sb.entity().getId());
sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
}
if (permittedAccounts.isEmpty()) {
final SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder();
domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
}
final SearchBuilder<AccountVO> accountSearch = _accountDao.createSearchBuilder();
accountSearch.and("typeNEQ", accountSearch.entity().getType(), SearchCriteria.Op.NEQ);
accountSearch.and("typeEQ", accountSearch.entity().getType(), SearchCriteria.Op.EQ);
sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER);
List<NetworkVO> networksToReturn = new ArrayList<>();
if (isSystem == null || !isSystem) {
if (!permittedAccounts.isEmpty()) {
//get account level networks
networksToReturn.addAll(listAccountSpecificNetworks(
buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired,
specifyIpRanges, vpcId, tags, display), searchFilter, permittedAccounts));
//get domain level networks
if (domainId != null) {
networksToReturn.addAll(listDomainLevelNetworks(
buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, restartRequired,
specifyIpRanges, vpcId, tags, display), searchFilter, domainId, false));
}
} else {
//add account specific networks
networksToReturn.addAll(listAccountSpecificNetworksByDomainPath(
buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired,
specifyIpRanges, vpcId, tags, display), searchFilter, path, isRecursive));
//add domain specific networks of domain + parent domains
networksToReturn.addAll(listDomainSpecificNetworksByDomainPath(
buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired,
specifyIpRanges, vpcId, tags, display), searchFilter, path, isRecursive));
//add networks of subdomains
if (domainId == null) {
networksToReturn.addAll(listDomainLevelNetworks(
buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, restartRequired,
specifyIpRanges, vpcId, tags, display), searchFilter, caller.getDomainId(), true));
}
}
} else {
networksToReturn = _networksDao.search(
buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, null, skipProjectNetworks, restartRequired,
specifyIpRanges, vpcId, tags, display), searchFilter);
}
if (supportedServicesStr != null && !supportedServicesStr.isEmpty() && !networksToReturn.isEmpty()) {
final List<NetworkVO> supportedNetworks = new ArrayList<>();
final Service[] suppportedServices = new Service[supportedServicesStr.size()];
int i = 0;
for (final String supportedServiceStr : supportedServicesStr) {
final Service service = Service.getService(supportedServiceStr);
if (service == null) {
throw new InvalidParameterValueException("Invalid service specified " + supportedServiceStr);
} else {
suppportedServices[i] = service;
}
i++;
}
for (final NetworkVO network : networksToReturn) {
if (areServicesSupportedInNetwork(network.getId(), suppportedServices)) {
supportedNetworks.add(network);
}
}
networksToReturn = supportedNetworks;
}
if (canUseForDeploy != null) {
final List<NetworkVO> networksForDeploy = new ArrayList<>();
for (final NetworkVO network : networksToReturn) {
if (_networkModel.canUseForDeploy(network) == canUseForDeploy) {
networksForDeploy.add(network);
}
}
networksToReturn = networksForDeploy;
}
//Now apply pagination
final List<? extends Network> wPagination = StringUtils.applyPagination(networksToReturn, cmd.getStartIndex(), cmd.getPageSizeVal());
if (wPagination != null) {
final Pair<List<? extends Network>, Integer> listWPagination = new Pair<>(wPagination, networksToReturn.size());
return listWPagination;
}
return new Pair<>(networksToReturn, networksToReturn.size());
}
private List<NetworkVO> listAccountSpecificNetworks(final SearchCriteria<NetworkVO> sc, final Filter searchFilter, final List<Long> permittedAccounts) {
final SearchCriteria<NetworkVO> accountSC = _networksDao.createSearchCriteria();
if (!permittedAccounts.isEmpty()) {
accountSC.addAnd("accountId", SearchCriteria.Op.IN, permittedAccounts.toArray());
}
accountSC.addAnd("aclType", SearchCriteria.Op.EQ, ACLType.Account.toString());
sc.addAnd("id", SearchCriteria.Op.SC, accountSC);
return _networksDao.search(sc, searchFilter);
}
private SearchCriteria<NetworkVO> buildNetworkSearchCriteria(final SearchBuilder<NetworkVO> sb, final String keyword, final Long id, final Boolean isSystem, final Long
zoneId, final String guestIpType,
final String trafficType, final Long physicalNetworkId, final String aclType, final boolean skipProjectNetworks,
final Boolean restartRequired, final Boolean specifyIpRanges, final Long vpcId,
final Map<String, String> tags, final Boolean display) {
final SearchCriteria<NetworkVO> sc = sb.create();
if (isSystem != null) {
sc.setJoinParameters("networkOfferingSearch", "systemOnly", isSystem);
}
if (keyword != null) {
final SearchCriteria<NetworkVO> ssc = _networksDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (display != null) {
sc.addAnd("displayNetwork", SearchCriteria.Op.EQ, display);
}
if (id != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, id);
}
if (zoneId != null) {
sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
}
if (guestIpType != null) {
sc.addAnd("guestType", SearchCriteria.Op.EQ, guestIpType);
}
if (trafficType != null) {
sc.addAnd("trafficType", SearchCriteria.Op.EQ, trafficType);
}
if (aclType != null) {
sc.addAnd("aclType", SearchCriteria.Op.EQ, aclType.toString());
}
if (physicalNetworkId != null) {
sc.addAnd("physicalNetworkId", SearchCriteria.Op.EQ, physicalNetworkId);
}
if (skipProjectNetworks) {
sc.setJoinParameters("accountSearch", "typeNEQ", Account.ACCOUNT_TYPE_PROJECT);
} else {
sc.setJoinParameters("accountSearch", "typeEQ", Account.ACCOUNT_TYPE_PROJECT);
}
if (restartRequired != null) {
sc.addAnd("restartRequired", SearchCriteria.Op.EQ, restartRequired);
}
if (specifyIpRanges != null) {
sc.addAnd("specifyIpRanges", SearchCriteria.Op.EQ, specifyIpRanges);
}
if (vpcId != null) {
sc.addAnd("vpcId", SearchCriteria.Op.EQ, vpcId);
}
if (tags != null && !tags.isEmpty()) {
int count = 0;
sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.Network.toString());
for (final Map.Entry<String, String> entry : tags.entrySet()) {
sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), entry.getKey());
sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), entry.getValue());
count++;
}
}
return sc;
}
private List<NetworkVO> listDomainLevelNetworks(final SearchCriteria<NetworkVO> sc, final Filter searchFilter, final long domainId, final boolean parentDomainsOnly) {
final List<Long> networkIds = new ArrayList<>();
final Set<Long> allowedDomains = _domainMgr.getDomainParentIds(domainId);
final List<NetworkDomainVO> maps = _networkDomainDao.listDomainNetworkMapByDomain(allowedDomains.toArray());
for (final NetworkDomainVO map : maps) {
if (map.getDomainId() == domainId && parentDomainsOnly) {
continue;
}
final boolean subdomainAccess = map.isSubdomainAccess() != null ? map.isSubdomainAccess() : getAllowSubdomainAccessGlobal();
if (map.getDomainId() == domainId || subdomainAccess) {
networkIds.add(map.getNetworkId());
}
}
if (!networkIds.isEmpty()) {
final SearchCriteria<NetworkVO> domainSC = _networksDao.createSearchCriteria();
domainSC.addAnd("id", SearchCriteria.Op.IN, networkIds.toArray());
domainSC.addAnd("aclType", SearchCriteria.Op.EQ, ACLType.Domain.toString());
sc.addAnd("id", SearchCriteria.Op.SC, domainSC);
return _networksDao.search(sc, searchFilter);
} else {
return new ArrayList<>();
}
}
private List<NetworkVO> listAccountSpecificNetworksByDomainPath(final SearchCriteria<NetworkVO> sc, final Filter searchFilter, final String path, final boolean isRecursive) {
final SearchCriteria<NetworkVO> accountSC = _networksDao.createSearchCriteria();
accountSC.addAnd("aclType", SearchCriteria.Op.EQ, ACLType.Account.toString());
if (path != null) {
if (isRecursive) {
sc.setJoinParameters("domainSearch", "path", path + "%");
} else {
sc.setJoinParameters("domainSearch", "path", path);
}
}
sc.addAnd("id", SearchCriteria.Op.SC, accountSC);
return _networksDao.search(sc, searchFilter);
}
private List<NetworkVO> listDomainSpecificNetworksByDomainPath(final SearchCriteria<NetworkVO> sc, final Filter searchFilter, final String path, final boolean isRecursive) {
Set<Long> allowedDomains = new HashSet<>();
if (path != null) {
if (isRecursive) {
allowedDomains = _domainMgr.getDomainChildrenIds(path);
} else {
final Domain domain = _domainDao.findDomainByPath(path);
allowedDomains.add(domain.getId());
}
}
final List<Long> networkIds = new ArrayList<>();
final List<NetworkDomainVO> maps = _networkDomainDao.listDomainNetworkMapByDomain(allowedDomains.toArray());
for (final NetworkDomainVO map : maps) {
networkIds.add(map.getNetworkId());
}
if (!networkIds.isEmpty()) {
final SearchCriteria<NetworkVO> domainSC = _networksDao.createSearchCriteria();
domainSC.addAnd("id", SearchCriteria.Op.IN, networkIds.toArray());
domainSC.addAnd("aclType", SearchCriteria.Op.EQ, ACLType.Domain.toString());
sc.addAnd("id", SearchCriteria.Op.SC, domainSC);
return _networksDao.search(sc, searchFilter);
} else {
return new ArrayList<>();
}
}
protected boolean areServicesSupportedInNetwork(final long networkId, final Service... services) {
return _ntwkSrvcDao.areServicesSupportedInNetwork(networkId, services);
}
private boolean getAllowSubdomainAccessGlobal() {
return _allowSubdomainNetworkAccess;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_DELETE, eventDescription = "deleting network", async = true)
public boolean deleteNetwork(final long networkId, final boolean forced) {
final Account caller = CallContext.current().getCallingAccount();
// Verify network id
final NetworkVO network = _networksDao.findById(networkId);
if (network == null) {
// see NetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("unable to find network with specified id");
ex.addProxyObject(String.valueOf(networkId), "networkId");
throw ex;
}
// don't allow to delete system network
if (isNetworkSystem(network)) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Network with specified id is system and can't be removed");
ex.addProxyObject(network.getUuid(), "networkId");
throw ex;
}
final Account owner = _accountMgr.getAccount(network.getAccountId());
// Only Admin can delete Shared networks
if (network.getGuestType() == GuestType.Shared && !_accountMgr.isAdmin(caller.getId())) {
throw new InvalidParameterValueException("Only Admins can delete network with guest type " + GuestType.Shared);
}
// Perform permission check
_accountMgr.checkAccess(caller, null, true, network);
if (forced && !_accountMgr.isRootAdmin(caller.getId())) {
throw new InvalidParameterValueException("Delete network with 'forced' option can only be called by root admins");
}
// VPC networks should be checked for static routes before deletion
if (network.getVpcId() != null) {
// don't allow to remove network tier when there are static routes pointing to an ipaddress in the tier CIDR.
final List<? extends StaticRoute> routes = _staticRouteDao.listByVpcIdAndNotRevoked(network.getVpcId());
for (final StaticRoute route : routes) {
if (NetUtils.isIpWithtInCidrRange(route.getGwIpAddress(), network.getCidr())) {
throw new CloudRuntimeException("Can't delete network " + network.getName() + " as it has static routes " +
"applied pointing to the CIDR of the network (" + network.getCidr() + "). Example static route: " +
route.getCidr() + " to " + route.getGwIpAddress() + ". Please remove all the routes pointing to the " +
"network tier CIDR before attempting to delete it.");
}
}
}
final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
final ReservationContext context = new ReservationContextImpl(null, null, callerUser, owner);
return _networkMgr.destroyNetwork(networkId, context, forced);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_RESTART, eventDescription = "restarting network", async = true)
public boolean restartNetwork(final RestartNetworkCmd cmd, final boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException {
// This method restarts all network elements belonging to the network and re-applies all the rules
final Long networkId = cmd.getNetworkId();
final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
final Account callerAccount = _accountMgr.getActiveAccountById(callerUser.getAccountId());
// Check if network exists
final NetworkVO network = _networksDao.findById(networkId);
if (network == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Network with specified id doesn't exist");
ex.addProxyObject(networkId.toString(), "networkId");
throw ex;
}
// Don't allow to restart network if it's not in Implemented/Setup state
if (!(network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup)) {
throw new InvalidParameterValueException("Network is not in the right state to be restarted. Correct states are: " + Network.State.Implemented + ", "
+ Network.State.Setup);
}
_accountMgr.checkAccess(callerAccount, null, true, network);
final boolean success = _networkMgr.restartNetwork(networkId, callerAccount, callerUser, cleanup);
if (success) {
s_logger.debug("Network id=" + networkId + " is restarted successfully.");
} else {
s_logger.warn("Network id=" + networkId + " failed to restart.");
}
return success;
}
@Override
@DB
public Network getNetwork(final long id) {
return _networksDao.findById(id);
}
@Override
public Network getNetwork(final String networkUuid) {
return _networksDao.findByUuid(networkUuid);
}
@Override
public IpAddress getIp(final long ipAddressId) {
return _ipAddressDao.findById(ipAddressId);
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_UPDATE, eventDescription = "updating network", async = true)
public Network updateGuestNetwork(final long networkId, final String name, final String displayText, final Account callerAccount, final User callerUser,
final String domainSuffix, final Long networkOfferingId, final Boolean changeCidr, final String guestVmCidr, final Boolean displayNetwork,
final String customId, final String dns1, final String dns2, final String ipExclusionList) {
boolean restartNetwork = false;
// verify input parameters
final NetworkVO network = _networksDao.findById(networkId);
if (network == null) {
// see NetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified network id doesn't exist in the system");
ex.addProxyObject(String.valueOf(networkId), "networkId");
throw ex;
}
//perform below validation if the network is vpc network
if (network.getVpcId() != null && networkOfferingId != null) {
final Vpc vpc = _entityMgr.findById(Vpc.class, network.getVpcId());
_vpcMgr.validateNtwkOffForNtwkInVpc(networkId, networkOfferingId, null, null, vpc, null, _accountMgr.getAccount(network.getAccountId()), null);
}
// don't allow to update network in Destroy state
if (network.getState() == Network.State.Destroy) {
throw new InvalidParameterValueException("Don't allow to update network in state " + Network.State.Destroy);
}
// Don't allow to update system network
final NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId());
if (offering.isSystemOnly()) {
throw new InvalidParameterValueException("Can't update system networks");
}
// allow to upgrade only Guest networks
if (network.getTrafficType() != Networks.TrafficType.Guest) {
throw new InvalidParameterValueException("Can't allow networks which traffic type is not " + TrafficType.Guest);
}
_accountMgr.checkAccess(callerAccount, null, true, network);
if (name != null) {
network.setName(name);
}
if (displayText != null) {
network.setDisplayText(displayText);
}
if (customId != null) {
network.setUuid(customId);
}
if (dns1 != null) {
network.setDns1(dns1);
restartNetwork = true;
}
if (dns2 != null) {
network.setDns2(dns2);
restartNetwork = true;
}
if (ipExclusionList != null) {
String networkCidr = null;
if (guestVmCidr == null) {
networkCidr = network.getNetworkCidr();
}
final List<NicVO> nicsPresent = _nicDao.listByNetworkId(networkId);
checkIpExclusionList(ipExclusionList, networkCidr, nicsPresent);
network.setIpExclusionList(ipExclusionList);
}
// display flag is not null and has changed
if (displayNetwork != null && displayNetwork != network.getDisplayNetwork()) {
// Update resource count if it needs to be updated
final NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());
if (_networkMgr.resourceCountNeedsUpdate(networkOffering, network.getAclType())) {
_resourceLimitMgr.changeResourceCount(network.getAccountId(), Resource.ResourceType.network, displayNetwork);
}
network.setDisplayNetwork(displayNetwork);
}
// network offering and domain suffix can be updated for Isolated networks only in 3.0
if ((networkOfferingId != null || domainSuffix != null) && network.getGuestType() != GuestType.Isolated) {
throw new InvalidParameterValueException("NetworkOffering and domain suffix upgrade can be perfomed for Isolated networks only");
}
boolean networkOfferingChanged = false;
final long oldNetworkOfferingId = network.getNetworkOfferingId();
final NetworkOffering oldNtwkOff = _networkOfferingDao.findByIdIncludingRemoved(oldNetworkOfferingId);
final NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId);
if (networkOfferingId != null) {
if (networkOffering == null || networkOffering.isSystemOnly()) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering with specified id");
ex.addProxyObject(networkOfferingId.toString(), "networkOfferingId");
throw ex;
}
// network offering should be in Enabled state
if (networkOffering.getState() != NetworkOffering.State.Enabled) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id is not in " + NetworkOffering.State.Enabled
+ " state, can't upgrade to it");
ex.addProxyObject(networkOffering.getUuid(), "networkOfferingId");
throw ex;
}
//can't update from vpc to non-vpc network offering
final boolean forVpcNew = _configMgr.isOfferingForVpc(networkOffering);
final boolean vorVpcOriginal = _configMgr.isOfferingForVpc(_entityMgr.findById(NetworkOffering.class, oldNetworkOfferingId));
if (forVpcNew != vorVpcOriginal) {
final String errMsg = forVpcNew ? "a vpc offering " : "not a vpc offering";
throw new InvalidParameterValueException("Can't update as the new offering is " + errMsg);
}
if (networkOfferingId != oldNetworkOfferingId) {
if (changeCidr) {
if (!checkForNonStoppedVmInNetwork(network.getId())) {
final InvalidParameterValueException ex = new InvalidParameterValueException("All user vm of network of specified id should be stopped before changing " +
"CIDR!");
ex.addProxyObject(network.getUuid(), "networkId");
throw ex;
}
}
// check if the network is upgradable
if (!canUpgrade(network, oldNetworkOfferingId, networkOfferingId)) {
throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNtwkOff.getUuid() + " to " + networkOffering.getUuid()
+ "; check logs for more information");
}
networkOfferingChanged = true;
//Setting the new network's isRedundant to the new network offering's RedundantRouter.
network.setIsRedundant(_networkOfferingDao.findById(networkOfferingId).getRedundantRouter());
}
}
final Map<String, String> newSvcProviders = networkOfferingChanged ? _networkMgr.finalizeServicesAndProvidersForNetwork(
_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()) : new HashMap<>();
// don't allow to modify network domain if the service is not supported
if (domainSuffix != null) {
// validate network domain
if (!NetUtils.verifyDomainName(domainSuffix)) {
throw new InvalidParameterValueException(
"Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters " +
"'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
long offeringId = oldNetworkOfferingId;
if (networkOfferingId != null) {
offeringId = networkOfferingId;
}
final Map<Network.Capability, String> dnsCapabilities = getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, offeringId), Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
// TBD: use uuid instead of networkOfferingId. May need to hardcode tablename in call to addProxyObject().
throw new InvalidParameterValueException("Domain name change is not supported by the network offering id=" + networkOfferingId);
}
network.setNetworkDomain(domainSuffix);
}
//IP reservation checks
// allow reservation only to Isolated Guest networks
final DataCenter dc = _dcDao.findById(network.getDataCenterId());
final String networkCidr = network.getNetworkCidr();
if (guestVmCidr != null) {
if (dc.getNetworkType() == NetworkType.Basic) {
throw new InvalidParameterValueException("Guest VM CIDR can't be specified for zone with " + NetworkType.Basic + " networking");
}
if (network.getGuestType() != GuestType.Isolated) {
throw new InvalidParameterValueException("Can only allow IP Reservation in networks with guest type " + GuestType.Isolated);
}
if (networkOfferingChanged == true) {
throw new InvalidParameterValueException("Cannot specify this network offering change and guestVmCidr at same time. Specify only one.");
}
if (!(network.getState() == Network.State.Implemented)) {
throw new InvalidParameterValueException("The network must be in " + Network.State.Implemented + " state. IP Reservation cannot be applied in "
+ network.getState() + " state");
}
if (!NetUtils.isValidIp4Cidr(guestVmCidr)) {
throw new InvalidParameterValueException("Invalid format of Guest VM CIDR.");
}
if (!NetUtils.validateGuestCidr(guestVmCidr)) {
throw new InvalidParameterValueException("Invalid format of Guest VM CIDR. Make sure it is RFC1918 compliant. ");
}
// If networkCidr is null it implies that there was no prior IP reservation, so the network cidr is network.getCidr()
// But in case networkCidr is a non null value (IP reservation already exists), it implies network cidr is networkCidr
if (networkCidr != null) {
if (!NetUtils.isNetworkAWithinNetworkB(guestVmCidr, networkCidr)) {
throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR should be a subset of network CIDR : "
+ networkCidr);
}
} else {
if (!NetUtils.isNetworkAWithinNetworkB(guestVmCidr, network.getCidr())) {
throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR should be a subset of network CIDR : "
+ network.getCidr());
}
}
// This check makes sure there are no active IPs existing outside the guestVmCidr in the network
final String[] guestVmCidrPair = guestVmCidr.split("\\/");
final Long size = Long.valueOf(guestVmCidrPair[1]);
final List<NicVO> nicsPresent = _nicDao.listByNetworkId(networkId);
final String cidrIpRange[] = NetUtils.getIpRangeFromCidr(guestVmCidrPair[0], size);
s_logger.info("The start IP of the specified guest vm cidr is: " + cidrIpRange[0] + " and end IP is: " + cidrIpRange[1]);
final long startIp = NetUtils.ip2Long(cidrIpRange[0]);
final long endIp = NetUtils.ip2Long(cidrIpRange[1]);
final long range = endIp - startIp + 1;
s_logger.info("The specified guest vm cidr has " + range + " IPs");
for (final NicVO nic : nicsPresent) {
final long nicIp = NetUtils.ip2Long(nic.getIPv4Address());
//check if nic IP is outside the guest vm cidr
if (nicIp < startIp || nicIp > endIp) {
if (!(nic.getState() == Nic.State.Deallocating)) {
throw new InvalidParameterValueException("Active IPs like " + nic.getIPv4Address() + " exist outside the Guest VM CIDR. Cannot apply reservation ");
}
}
}
// In some scenarios even though guesVmCidr and network CIDR do not appear similar but
// the IP ranges exactly matches, in these special cases make sure no Reservation gets applied
if (network.getNetworkCidr() == null) {
if (NetUtils.isSameIpRange(guestVmCidr, network.getCidr()) && !guestVmCidr.equals(network.getCidr())) {
throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and CIDR: " + network.getCidr() + " are same, "
+ "even though both the cidrs appear to be different. As a precaution no IP Reservation will be applied.");
}
} else {
if (NetUtils.isSameIpRange(guestVmCidr, network.getNetworkCidr()) && !guestVmCidr.equals(network.getNetworkCidr())) {
throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and Network CIDR: " + network.getNetworkCidr()
+ " are same, "
+ "even though both the cidrs appear to be different. As a precaution IP Reservation will not be affected. If you want to reset IP Reservation, "
+ "specify guestVmCidr to be: " + network.getNetworkCidr());
}
}
// When reservation is applied for the first time, network_cidr will be null
// Populate it with the actual network cidr
if (network.getNetworkCidr() == null) {
network.setNetworkCidr(network.getCidr());
}
// Condition for IP Reservation reset : guestVmCidr and network CIDR are same
if (network.getNetworkCidr().equals(guestVmCidr)) {
s_logger.warn("Guest VM CIDR and Network CIDR both are same, reservation will reset.");
network.setNetworkCidr(null);
}
checkIpExclusionList(ipExclusionList, guestVmCidr, null);
// Finally update "cidr" with the guestVmCidr
// which becomes the effective address space for CloudStack guest VMs
network.setCidr(guestVmCidr);
_networksDao.update(networkId, network);
s_logger.info("IP Reservation has been applied. The new CIDR for Guests Vms is " + guestVmCidr);
}
final ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount);
// 1) Shutdown all the elements and cleanup all the rules. Don't allow to shutdown network in intermediate
// states - Shutdown and Implementing
final boolean validStateToShutdown = network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup || network.getState() == Network.State
.Allocated;
if (restartNetwork) {
if (validStateToShutdown) {
if (!changeCidr) {
s_logger.debug("Shutting down elements and resources for network id=" + networkId + " as a part of network update");
if (!_networkMgr.shutdownNetworkElementsAndResources(context, true, network)) {
s_logger.warn("Failed to shutdown the network elements and resources as a part of network restart: " + network);
final CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of update to network of " +
"specified id");
ex.addProxyObject(network.getUuid(), "networkId");
throw ex;
}
} else {
// We need to shutdown the network, since we want to re-implement the network.
s_logger.debug("Shutting down network id=" + networkId + " as a part of network update");
//check if network has reservation
if (NetUtils.isNetworkAWithinNetworkB(network.getCidr(), network.getNetworkCidr())) {
s_logger.warn("Existing IP reservation will become ineffective for the network with id = " + networkId
+ " You need to reapply reservation after network reimplementation.");
//set cidr to the newtork cidr
network.setCidr(network.getNetworkCidr());
//set networkCidr to null to bring network back to no IP reservation state
network.setNetworkCidr(null);
}
if (!_networkMgr.shutdownNetwork(network.getId(), context, true)) {
s_logger.warn("Failed to shutdown the network as a part of update to network with specified id");
final CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network as a part of update of specified network id");
ex.addProxyObject(network.getUuid(), "networkId");
throw ex;
}
}
} else {
final CloudRuntimeException ex = new CloudRuntimeException(
"Failed to shutdown the network elements and resources as a part of update to network with specified id; network is in wrong state: " + network.getState());
ex.addProxyObject(network.getUuid(), "networkId");
throw ex;
}
}
// 2) Only after all the elements and rules are shutdown properly, update the network VO
// get updated network
final Network.State networkState = _networksDao.findById(networkId).getState();
final boolean validStateToImplement = networkState == Network.State.Implemented || networkState == Network.State.Setup || networkState == Network.State.Allocated;
if (restartNetwork && !validStateToImplement) {
final CloudRuntimeException ex = new CloudRuntimeException(
"Failed to implement the network elements and resources as a part of update to network with specified id; network is in wrong state: " + networkState);
ex.addProxyObject(network.getUuid(), "networkId");
throw ex;
}
if (networkOfferingId != null) {
if (networkOfferingChanged) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
network.setNetworkOfferingId(networkOfferingId);
_networksDao.update(networkId, network, newSvcProviders);
// get all nics using this network
// log remove usage events for old offering
// log assign usage events for new offering
final List<NicVO> nics = _nicDao.listByNetworkId(networkId);
for (final NicVO nic : nics) {
final long vmId = nic.getInstanceId();
final VMInstanceVO vm = _vmDao.findById(vmId);
if (vm == null) {
s_logger.error("Vm for nic " + nic.getId() + " not found with Vm Id:" + vmId);
continue;
}
final long isDefault = nic.isDefaultNic() ? 1 : 0;
final String nicIdString = Long.toString(nic.getId());
}
}
});
} else {
network.setNetworkOfferingId(networkOfferingId);
_networksDao.update(networkId, network,
_networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()));
}
} else {
_networksDao.update(networkId, network);
}
// 3) Implement the elements and rules again
if (restartNetwork) {
if (network.getState() != Network.State.Allocated) {
final DeployDestination dest = new DeployDestination(zoneRepository.findById(network.getDataCenterId()).orElse(null), null, null, null);
s_logger.debug("Implementing the network " + network + " elements and resources as a part of network update");
try {
if (!changeCidr) {
_networkMgr.implementNetworkElementsAndResources(dest, context, network, _networkOfferingDao.findById(network.getNetworkOfferingId()));
} else {
_networkMgr.implementNetwork(network.getId(), dest, context);
}
} catch (final Exception ex) {
s_logger.warn("Failed to implement network " + network + " elements and resources as a part of network update due to ", ex);
final CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified id) elements and resources as a part of network update");
e.addProxyObject(network.getUuid(), "networkId");
throw e;
}
}
}
// 4) if network has been upgraded from a non persistent ntwk offering to a persistent ntwk offering,
// implement the network if its not already
if (networkOfferingChanged && !oldNtwkOff.getIsPersistent() && networkOffering.getIsPersistent()) {
if (network.getState() == Network.State.Allocated) {
try {
final DeployDestination dest = new DeployDestination(zoneRepository.findById(network.getDataCenterId()).orElse(null), null, null, null);
_networkMgr.implementNetwork(network.getId(), dest, context);
} catch (final Exception ex) {
s_logger.warn("Failed to implement network " + network + " elements and resources as a part o" + "f network update due to ", ex);
final CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified" + " id) elements and resources as a part of network " +
"update");
e.addProxyObject(network.getUuid(), "networkId");
throw e;
}
}
}
return getNetwork(network.getId());
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_CREATE, eventDescription = "Creating Physical Network", create = true)
public PhysicalNetwork createPhysicalNetwork(final Long zoneId, final String vnetRange, final String networkSpeed, final List<String> isolationMethods,
final String broadcastDomainRangeStr, final Long domainId, final List<String> tags, final String name) {
// Check if zone exists
if (zoneId == null) {
throw new InvalidParameterValueException("Please specify a valid zone.");
}
final Zone zone = zoneRepository.findById(zoneId).orElse(null);
if (zone == null) {
throw new InvalidParameterValueException("Please specify a valid zone.");
}
if (AllocationState.Enabled == zone.getAllocationState()) {
// TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject().
throw new PermissionDeniedException("Cannot create PhysicalNetwork since the Zone is currently enabled, zone Id: " + zoneId);
}
final NetworkType zoneType = zone.getNetworkType();
if (zoneType == NetworkType.Basic) {
if (!_physicalNetworkDao.listByZone(zoneId).isEmpty()) {
// TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject().
throw new CloudRuntimeException("Cannot add the physical network to basic zone id: " + zoneId + ", there is a physical network already existing in this basic " +
"Zone");
}
}
if (tags != null && tags.size() > 1) {
throw new InvalidParameterException("Only one tag can be specified for a physical network at this time");
}
if (isolationMethods != null && isolationMethods.size() > 1) {
throw new InvalidParameterException("Only one isolationMethod can be specified for a physical network at this time");
}
if (vnetRange != null) {
// Verify zone type
if (zoneType == NetworkType.Basic) {
throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zoneType + " network");
}
}
BroadcastDomainRange broadcastDomainRange = null;
if (broadcastDomainRangeStr != null && !broadcastDomainRangeStr.isEmpty()) {
try {
broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.valueOf(broadcastDomainRangeStr.toUpperCase());
} catch (final IllegalArgumentException ex) {
throw new InvalidParameterValueException("Unable to resolve broadcastDomainRange '" + broadcastDomainRangeStr + "' to a supported value {Pod or Zone}");
}
// in Acton release you can specify only Zone broadcastdomain type in Advance zone, and Pod in Basic
if (zoneType == NetworkType.Basic && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.POD) {
throw new InvalidParameterValueException("Basic zone can have broadcast domain type of value " + BroadcastDomainRange.POD + " only");
} else if (zoneType == NetworkType.Advanced && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.ZONE) {
throw new InvalidParameterValueException("Advance zone can have broadcast domain type of value " + BroadcastDomainRange.ZONE + " only");
}
}
if (broadcastDomainRange == null) {
if (zoneType == NetworkType.Basic) {
broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.POD;
} else {
broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.ZONE;
}
}
try {
final BroadcastDomainRange broadcastDomainRangeFinal = broadcastDomainRange;
return Transaction.execute(new TransactionCallback<PhysicalNetworkVO>() {
@Override
public PhysicalNetworkVO doInTransaction(final TransactionStatus status) {
// Create the new physical network in the database
final long id = _physicalNetworkDao.getNextInSequence(Long.class, "id");
PhysicalNetworkVO pNetwork = new PhysicalNetworkVO(id, zoneId, vnetRange, networkSpeed, domainId, broadcastDomainRangeFinal, name);
pNetwork.setTags(tags);
pNetwork.setIsolationMethods(isolationMethods);
pNetwork = _physicalNetworkDao.persist(pNetwork);
// Add vnet entries for the new zone if zone type is Advanced
if (vnetRange != null) {
addOrRemoveVnets(vnetRange.split(","), pNetwork);
}
// add VirtualRouter as the default network service provider
addDefaultVirtualRouterToPhysicalNetwork(pNetwork.getId());
// add VPCVirtualRouter as the default network service provider
addDefaultVpcVirtualRouterToPhysicalNetwork(pNetwork.getId());
return pNetwork;
}
});
} catch (final Exception ex) {
s_logger.warn("Exception: ", ex);
throw new CloudRuntimeException("Fail to create a physical network");
}
}
@Override
public Pair<List<? extends PhysicalNetwork>, Integer> searchPhysicalNetworks(final Long id, final Long zoneId, final String keyword, final Long startIndex, final Long
pageSize, final String name) {
final Filter searchFilter = new Filter(PhysicalNetworkVO.class, "id", Boolean.TRUE, startIndex, pageSize);
final SearchCriteria<PhysicalNetworkVO> sc = _physicalNetworkDao.createSearchCriteria();
if (id != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, id);
}
if (zoneId != null) {
sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
}
if (name != null) {
sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%");
}
final Pair<List<PhysicalNetworkVO>, Integer> result = _physicalNetworkDao.searchAndCount(sc, searchFilter);
return new Pair<>(result.first(), result.second());
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_UPDATE, eventDescription = "updating physical network", async = true)
public PhysicalNetwork updatePhysicalNetwork(final Long id, final String networkSpeed, final List<String> tags, final String newVnetRange, final String state) {
// verify input parameters
final PhysicalNetworkVO network = _physicalNetworkDao.findById(id);
if (network == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system");
ex.addProxyObject(id.toString(), "physicalNetworkId");
throw ex;
}
// if zone is of Basic type, don't allow to add vnet range
final DataCenter zone = _dcDao.findById(network.getDataCenterId());
if (zone == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Zone with id=" + network.getDataCenterId() + " doesn't exist in the system");
ex.addProxyObject(String.valueOf(network.getDataCenterId()), "dataCenterId");
throw ex;
}
if (newVnetRange != null) {
if (zone.getNetworkType() == NetworkType.Basic) {
throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zone.getNetworkType() + " network");
}
}
if (tags != null && tags.size() > 1) {
throw new InvalidParameterException("Unable to support more than one tag on network yet");
}
PhysicalNetwork.State networkState = null;
if (state != null && !state.isEmpty()) {
try {
networkState = PhysicalNetwork.State.valueOf(state);
} catch (final IllegalArgumentException ex) {
throw new InvalidParameterValueException("Unable to resolve state '" + state + "' to a supported value {Enabled or Disabled}");
}
}
if (state != null) {
network.setState(networkState);
}
if (tags != null) {
network.setTags(tags);
}
if (networkSpeed != null) {
network.setSpeed(networkSpeed);
}
if (newVnetRange != null) {
final String[] listOfRanges = newVnetRange.split(",");
addOrRemoveVnets(listOfRanges, network);
}
_physicalNetworkDao.update(id, network);
return network;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_DELETE, eventDescription = "deleting physical network", async = true)
@DB
public boolean deletePhysicalNetwork(final Long physicalNetworkId) {
// verify input parameters
final PhysicalNetworkVO pNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (pNetwork == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system");
ex.addProxyObject(physicalNetworkId.toString(), "physicalNetworkId");
throw ex;
}
checkIfPhysicalNetworkIsDeletable(physicalNetworkId);
return Transaction.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(final TransactionStatus status) {
// delete vlans for this zone
final List<VlanVO> vlans = _vlanDao.listVlansByPhysicalNetworkId(physicalNetworkId);
for (final VlanVO vlan : vlans) {
_vlanDao.remove(vlan.getId());
}
// Delete networks
final List<NetworkVO> networks = _networksDao.listByPhysicalNetwork(physicalNetworkId);
if (networks != null && !networks.isEmpty()) {
for (final NetworkVO network : networks) {
_networksDao.remove(network.getId());
}
}
// delete vnets
_dcDao.deleteVnet(physicalNetworkId);
// delete service providers
final List<PhysicalNetworkServiceProviderVO> providers = _pNSPDao.listBy(physicalNetworkId);
for (final PhysicalNetworkServiceProviderVO provider : providers) {
try {
deleteNetworkServiceProvider(provider.getId());
} catch (final ResourceUnavailableException e) {
s_logger.warn("Unable to complete destroy of the physical network provider: " + provider.getProviderName() + ", id: " + provider.getId(), e);
return false;
} catch (final ConcurrentOperationException e) {
s_logger.warn("Unable to complete destroy of the physical network provider: " + provider.getProviderName() + ", id: " + provider.getId(), e);
return false;
}
}
// delete traffic types
_pNTrafficTypeDao.deleteTrafficTypes(physicalNetworkId);
return _physicalNetworkDao.remove(physicalNetworkId);
}
});
}
@DB
private void checkIfPhysicalNetworkIsDeletable(final Long physicalNetworkId) {
final List<List<String>> tablesToCheck = new ArrayList<>();
final List<String> vnet = new ArrayList<>();
vnet.add(0, "op_dc_vnet_alloc");
vnet.add(1, "physical_network_id");
vnet.add(2, "there are allocated vnets for this physical network");
tablesToCheck.add(vnet);
final List<String> networks = new ArrayList<>();
networks.add(0, "networks");
networks.add(1, "physical_network_id");
networks.add(2, "there are networks associated to this physical network");
tablesToCheck.add(networks);
/*
* List<String> privateIP = new ArrayList<String>();
* privateIP.add(0, "op_dc_ip_address_alloc");
* privateIP.add(1, "data_center_id");
* privateIP.add(2, "there are private IP addresses allocated for this zone");
* tablesToCheck.add(privateIP);
*/
final List<String> publicIP = new ArrayList<>();
publicIP.add(0, "user_ip_address");
publicIP.add(1, "physical_network_id");
publicIP.add(2, "there are public IP addresses allocated for this physical network");
tablesToCheck.add(publicIP);
for (final List<String> table : tablesToCheck) {
final String tableName = table.get(0);
final String column = table.get(1);
final String errorMsg = table.get(2);
final String dbName = "cloud";
String selectSql = "SELECT * FROM `" + dbName + "`.`" + tableName + "` WHERE " + column + " = ?";
if (tableName.equals("networks")) {
selectSql += " AND removed is NULL";
}
if (tableName.equals("op_dc_vnet_alloc")) {
selectSql += " AND taken IS NOT NULL";
}
if (tableName.equals("user_ip_address")) {
selectSql += " AND state!='Free'";
}
if (tableName.equals("op_dc_ip_address_alloc")) {
selectSql += " AND taken IS NOT NULL";
}
final TransactionLegacy txn = TransactionLegacy.currentTxn();
try {
final PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql);
stmt.setLong(1, physicalNetworkId);
final ResultSet rs = stmt.executeQuery();
if (rs != null && rs.next()) {
throw new CloudRuntimeException("The Physical Network is not deletable because " + errorMsg);
}
} catch (final SQLException ex) {
throw new CloudRuntimeException("The Management Server failed to detect if physical network is deletable. Please contact Cloud Support.");
}
}
}
@Override
public List<? extends Service> listNetworkServices(final String providerName) {
Provider provider = null;
if (providerName != null) {
provider = Network.Provider.getProvider(providerName);
if (provider == null) {
throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName);
}
}
if (provider != null) {
final NetworkElement element = _networkModel.getElementImplementingProvider(providerName);
if (element == null) {
throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + providerName + "'");
}
return new ArrayList<>(element.getCapabilities().keySet());
} else {
return Service.listAllServices();
}
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_CREATE, eventDescription = "Creating Physical Network ServiceProvider", create = true)
public PhysicalNetworkServiceProvider addProviderToPhysicalNetwork(final Long physicalNetworkId, final String providerName, final Long destinationPhysicalNetworkId, final
List<String> enabledServices) {
// verify input parameters
final PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId);
if (network == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system");
ex.addProxyObject(physicalNetworkId.toString(), "physicalNetworkId");
throw ex;
}
// verify input parameters
if (destinationPhysicalNetworkId != null) {
final PhysicalNetworkVO destNetwork = _physicalNetworkDao.findById(destinationPhysicalNetworkId);
if (destNetwork == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Destination Physical Network with specified id doesn't exist in the system");
ex.addProxyObject(destinationPhysicalNetworkId.toString(), "destinationPhysicalNetworkId");
throw ex;
}
}
if (providerName != null) {
final Provider provider = Network.Provider.getProvider(providerName);
if (provider == null) {
throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName);
}
}
if (_pNSPDao.findByServiceProvider(physicalNetworkId, providerName) != null) {
// TBD: send uuid instead of physicalNetworkId.
throw new CloudRuntimeException("The '" + providerName + "' provider already exists on physical network : " + physicalNetworkId);
}
// check if services can be turned off
final NetworkElement element = _networkModel.getElementImplementingProvider(providerName);
if (element == null) {
throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + providerName + "'");
}
List<Service> services = new ArrayList<>();
if (enabledServices != null) {
if (!element.canEnableIndividualServices()) {
if (enabledServices.size() != element.getCapabilities().keySet().size()) {
throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services for this Service Provider '"
+ providerName + "'");
}
}
// validate Services
boolean addGatewayService = false;
for (final String serviceName : enabledServices) {
final Network.Service service = Network.Service.getService(serviceName);
if (service == null || service == Service.Gateway) {
throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName);
} else if (service == Service.SourceNat) {
addGatewayService = true;
}
// check if the service is provided by this Provider
if (!element.getCapabilities().containsKey(service)) {
throw new InvalidParameterValueException(providerName + " Provider cannot provide this Service specified=" + serviceName);
}
services.add(service);
}
if (addGatewayService) {
services.add(Service.Gateway);
}
} else {
// enable all the default services supported by this element.
services = new ArrayList<>(element.getCapabilities().keySet());
}
try {
// Create the new physical network in the database
PhysicalNetworkServiceProviderVO nsp = new PhysicalNetworkServiceProviderVO(physicalNetworkId, providerName);
// set enabled services
nsp.setEnabledServices(services);
if (destinationPhysicalNetworkId != null) {
nsp.setDestinationPhysicalNetworkId(destinationPhysicalNetworkId);
}
nsp = _pNSPDao.persist(nsp);
return nsp;
} catch (final Exception ex) {
s_logger.warn("Exception: ", ex);
throw new CloudRuntimeException("Fail to add a provider to physical network");
}
}
@Override
public Pair<List<? extends PhysicalNetworkServiceProvider>, Integer> listNetworkServiceProviders(final Long physicalNetworkId, final String name, final String state, final
Long startIndex,
final Long pageSize) {
final Filter searchFilter = new Filter(PhysicalNetworkServiceProviderVO.class, "id", false, startIndex, pageSize);
final SearchBuilder<PhysicalNetworkServiceProviderVO> sb = _pNSPDao.createSearchBuilder();
final SearchCriteria<PhysicalNetworkServiceProviderVO> sc = sb.create();
if (physicalNetworkId != null) {
sc.addAnd("physicalNetworkId", Op.EQ, physicalNetworkId);
}
if (name != null) {
sc.addAnd("providerName", Op.EQ, name);
}
if (state != null) {
sc.addAnd("state", Op.EQ, state);
}
final Pair<List<PhysicalNetworkServiceProviderVO>, Integer> result = _pNSPDao.searchAndCount(sc, searchFilter);
return new Pair<>(result.first(), result.second());
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_UPDATE, eventDescription = "Updating physical network ServiceProvider", async = true)
public PhysicalNetworkServiceProvider updateNetworkServiceProvider(final Long id, final String stateStr, final List<String> enabledServices) {
final PhysicalNetworkServiceProviderVO provider = _pNSPDao.findById(id);
if (provider == null) {
throw new InvalidParameterValueException("Network Service Provider id=" + id + "doesn't exist in the system");
}
final NetworkElement element = _networkModel.getElementImplementingProvider(provider.getProviderName());
if (element == null) {
throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getProviderName() + "'");
}
PhysicalNetworkServiceProvider.State state = null;
if (stateStr != null && !stateStr.isEmpty()) {
try {
state = PhysicalNetworkServiceProvider.State.valueOf(stateStr);
} catch (final IllegalArgumentException ex) {
throw new InvalidParameterValueException("Unable to resolve state '" + stateStr + "' to a supported value {Enabled or Disabled}");
}
}
boolean update = false;
if (state != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("trying to update the state of the service provider id=" + id + " on physical network: " + provider.getPhysicalNetworkId() + " to state: "
+ stateStr);
}
switch (state) {
case Enabled:
if (element != null && element.isReady(provider)) {
provider.setState(PhysicalNetworkServiceProvider.State.Enabled);
update = true;
} else {
throw new CloudRuntimeException("Provider is not ready, cannot Enable the provider, please configure the provider first");
}
break;
case Disabled:
// do we need to do anything for the provider instances before disabling?
provider.setState(PhysicalNetworkServiceProvider.State.Disabled);
update = true;
break;
case Shutdown:
throw new InvalidParameterValueException("Updating the provider state to 'Shutdown' is not supported");
}
}
if (enabledServices != null) {
// check if services can be turned of
if (!element.canEnableIndividualServices()) {
throw new InvalidParameterValueException("Cannot update set of Services for this Service Provider '" + provider.getProviderName() + "'");
}
// validate Services
final List<Service> services = new ArrayList<>();
for (final String serviceName : enabledServices) {
final Network.Service service = Network.Service.getService(serviceName);
if (service == null) {
throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName);
}
services.add(service);
}
// set enabled services
provider.setEnabledServices(services);
update = true;
}
if (update) {
_pNSPDao.update(id, provider);
}
return provider;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_DELETE, eventDescription = "Deleting physical network ServiceProvider", async = true)
public boolean deleteNetworkServiceProvider(final Long id) throws ConcurrentOperationException, ResourceUnavailableException {
final PhysicalNetworkServiceProviderVO provider = _pNSPDao.findById(id);
if (provider == null) {
throw new InvalidParameterValueException("Network Service Provider id=" + id + "doesn't exist in the system");
}
// check if there are networks using this provider
final List<NetworkVO> networks = _networksDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), provider.getProviderName());
if (networks != null && !networks.isEmpty()) {
throw new CloudRuntimeException(
"Provider is not deletable because there are active networks using this provider, please upgrade these networks to new network offerings");
}
final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
final Account callerAccount = _accountMgr.getActiveAccountById(callerUser.getAccountId());
// shutdown the provider instances
final ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Shutting down the service provider id=" + id + " on physical network: " + provider.getPhysicalNetworkId());
}
final NetworkElement element = _networkModel.getElementImplementingProvider(provider.getProviderName());
if (element == null) {
throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getProviderName() + "'");
}
if (element != null && element.shutdownProviderInstances(provider, context)) {
provider.setState(PhysicalNetworkServiceProvider.State.Shutdown);
}
return _pNSPDao.remove(id);
}
@Override
public PhysicalNetwork getPhysicalNetwork(final Long physicalNetworkId) {
return _physicalNetworkDao.findById(physicalNetworkId);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_CREATE, eventDescription = "Creating Physical Network", async = true)
public PhysicalNetwork getCreatedPhysicalNetwork(final Long physicalNetworkId) {
return getPhysicalNetwork(physicalNetworkId);
}
@Override
public PhysicalNetworkServiceProvider getPhysicalNetworkServiceProvider(final Long providerId) {
return _pNSPDao.findById(providerId);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_CREATE, eventDescription = "Creating Physical Network ServiceProvider", async = true)
public PhysicalNetworkServiceProvider getCreatedPhysicalNetworkServiceProvider(final Long providerId) {
return getPhysicalNetworkServiceProvider(providerId);
}
@Override
public long findPhysicalNetworkId(final long zoneId, final String tag, final TrafficType trafficType) {
List<PhysicalNetworkVO> pNtwks = new ArrayList<>();
if (trafficType != null) {
pNtwks = _physicalNetworkDao.listByZoneAndTrafficType(zoneId, trafficType);
} else {
pNtwks = _physicalNetworkDao.listByZone(zoneId);
}
if (pNtwks.isEmpty()) {
throw new InvalidParameterValueException("Unable to find physical network in zone id=" + zoneId);
}
if (pNtwks.size() > 1) {
if (tag == null) {
throw new InvalidParameterValueException("More than one physical networks exist in zone id=" + zoneId + " and no tags are specified in order to make a choice");
}
Long pNtwkId = null;
for (final PhysicalNetwork pNtwk : pNtwks) {
if (pNtwk.getTags().contains(tag)) {
s_logger.debug("Found physical network id=" + pNtwk.getId() + " based on requested tags " + tag);
pNtwkId = pNtwk.getId();
break;
}
}
if (pNtwkId == null) {
throw new InvalidParameterValueException("Unable to find physical network which match the tags " + tag);
}
return pNtwkId;
} else {
return pNtwks.get(0).getId();
}
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_TRAFFIC_TYPE_CREATE, eventDescription = "Creating Physical Network TrafficType", create = true)
public PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(final Long physicalNetworkId, final String trafficTypeStr, final String isolationMethod, String xenLabel,
final String kvmLabel, final String vlan) {
// verify input parameters
final PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId);
if (network == null) {
throw new InvalidParameterValueException("Physical Network id=" + physicalNetworkId + "doesn't exist in the system");
}
Networks.TrafficType trafficType = null;
if (trafficTypeStr != null && !trafficTypeStr.isEmpty()) {
try {
trafficType = Networks.TrafficType.valueOf(trafficTypeStr);
} catch (final IllegalArgumentException ex) {
throw new InvalidParameterValueException("Unable to resolve trafficType '" + trafficTypeStr + "' to a supported value");
}
}
if (_pNTrafficTypeDao.isTrafficTypeSupported(physicalNetworkId, trafficType)) {
throw new CloudRuntimeException("This physical network already supports the traffic type: " + trafficType);
}
// For Storage, Control, Management, Public check if the zone has any other physical network with this
// traffictype already present
// If yes, we cant add these traffics to one more physical network in the zone.
if (TrafficType.isSystemNetwork(trafficType) || TrafficType.Public.equals(trafficType) || TrafficType.Storage.equals(trafficType)) {
if (!_physicalNetworkDao.listByZoneAndTrafficType(network.getDataCenterId(), trafficType).isEmpty()) {
throw new CloudRuntimeException("Fail to add the traffic type to physical network because Zone already has a physical network with this traffic type: "
+ trafficType);
}
}
if (TrafficType.Storage.equals(trafficType)) {
final List<SecondaryStorageVmVO> ssvms = _stnwMgr.getSSVMWithNoStorageNetwork(network.getDataCenterId());
if (!ssvms.isEmpty()) {
final StringBuilder sb = new StringBuilder(
"Cannot add "
+ trafficType
+ " traffic type as there are below secondary storage vm still running. Please stop them all and add Storage traffic type again, then destory " +
"them all to allow CloudStack recreate them with storage network(If you have added storage network ip range)");
sb.append("SSVMs:");
for (final SecondaryStorageVmVO ssvm : ssvms) {
sb.append(ssvm.getInstanceName()).append(":").append(ssvm.getState());
}
throw new CloudRuntimeException(sb.toString());
}
}
try {
// Create the new traffic type in the database
if (xenLabel == null) {
xenLabel = getDefaultXenNetworkLabel(trafficType);
}
PhysicalNetworkTrafficTypeVO pNetworktrafficType = new PhysicalNetworkTrafficTypeVO(physicalNetworkId, trafficType, xenLabel, kvmLabel, vlan);
pNetworktrafficType = _pNTrafficTypeDao.persist(pNetworktrafficType);
// For public traffic, get isolation method of physical network and update the public network accordingly
// each broadcast type will individually need to be qualified for support of public traffic
if (TrafficType.Public.equals(trafficType)) {
final List<String> isolationMethods = network.getIsolationMethods();
if (isolationMethods.size() == 1 && isolationMethods.get(0).toLowerCase().equals("vxlan")
|| isolationMethod != null && isolationMethods.contains(isolationMethod) && isolationMethod.toLowerCase().equals("vxlan")) {
// find row in networks table that is defined as 'Public', created when zone was deployed
final NetworkVO publicNetwork = _networksDao.listByZoneAndTrafficType(network.getDataCenterId(), TrafficType.Public).get(0);
if (publicNetwork != null) {
s_logger.debug("setting public network " + publicNetwork + " to broadcast type vxlan");
publicNetwork.setBroadcastDomainType(BroadcastDomainType.Vxlan);
_networksDao.persist(publicNetwork);
}
}
}
return pNetworktrafficType;
} catch (final Exception ex) {
s_logger.warn("Exception: ", ex);
throw new CloudRuntimeException("Fail to add a traffic type to physical network");
}
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_TRAFFIC_TYPE_CREATE, eventDescription = "Creating Physical Network TrafficType", async = true)
public PhysicalNetworkTrafficType getPhysicalNetworkTrafficType(final Long id) {
return _pNTrafficTypeDao.findById(id);
}
public boolean deletePhysicalNetworkTrafficType(final Long id) {
final PhysicalNetworkTrafficTypeVO trafficType = _pNTrafficTypeDao.findById(id);
if (trafficType == null) {
throw new InvalidParameterValueException("Traffic Type with id=" + id + "doesn't exist in the system");
}
// check if there are any networks associated to this physical network with this traffic type
if (TrafficType.Guest.equals(trafficType.getTrafficType())) {
if (!_networksDao.listByPhysicalNetworkTrafficType(trafficType.getPhysicalNetworkId(), trafficType.getTrafficType()).isEmpty()) {
throw new CloudRuntimeException("The Traffic Type is not deletable because there are existing networks with this traffic type:" + trafficType.getTrafficType());
}
} else if (TrafficType.Storage.equals(trafficType.getTrafficType())) {
final PhysicalNetworkVO pn = _physicalNetworkDao.findById(trafficType.getPhysicalNetworkId());
if (_stnwMgr.isAnyStorageIpInUseInZone(pn.getDataCenterId())) {
throw new CloudRuntimeException("The Traffic Type is not deletable because there are still some storage network ip addresses in use:"
+ trafficType.getTrafficType());
}
}
return _pNTrafficTypeDao.remove(id);
}
private String getDefaultXenNetworkLabel(final TrafficType trafficType) {
String xenLabel = null;
switch (trafficType) {
case Public:
xenLabel = _configDao.getValue(Config.XenServerPublicNetwork.key());
break;
case Guest:
xenLabel = _configDao.getValue(Config.XenServerGuestNetwork.key());
break;
case Storage:
xenLabel = _configDao.getValue(Config.XenServerStorageNetwork1.key());
break;
case Management:
xenLabel = _configDao.getValue(Config.XenServerPrivateNetwork.key());
break;
case Control:
xenLabel = "cloud_link_local_network";
break;
case Vpn:
case None:
break;
}
return xenLabel;
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_GUEST_VLAN_RANGE_DEDICATE, eventDescription = "dedicating guest vlan range", async = false)
public GuestVlan dedicateGuestVlanRange(final DedicateGuestVlanRangeCmd cmd) {
final String vlan = cmd.getVlan();
final String accountName = cmd.getAccountName();
final Long domainId = cmd.getDomainId();
final Long physicalNetworkId = cmd.getPhysicalNetworkId();
final Long projectId = cmd.getProjectId();
final int startVlan;
final int endVlan;
String updatedVlanRange = null;
long guestVlanMapId = 0;
long guestVlanMapAccountId = 0;
long vlanOwnerId = 0;
// Verify account is valid
Account vlanOwner = null;
if (projectId != null) {
if (accountName != null) {
throw new InvalidParameterValueException("accountName and projectId are mutually exclusive");
}
final Project project = _projectMgr.getProject(projectId);
if (project == null) {
throw new InvalidParameterValueException("Unable to find project by id " + projectId);
}
vlanOwner = _accountMgr.getAccount(project.getProjectAccountId());
}
if (accountName != null && domainId != null) {
vlanOwner = _accountDao.findActiveAccount(accountName, domainId);
}
if (vlanOwner == null) {
throw new InvalidParameterValueException("Unable to find account by name " + accountName);
}
vlanOwnerId = vlanOwner.getAccountId();
// Verify physical network isolation type is VLAN
final PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (physicalNetwork == null) {
throw new InvalidParameterValueException("Unable to find physical network by id " + physicalNetworkId);
} else if (!physicalNetwork.getIsolationMethods().isEmpty() && !physicalNetwork.getIsolationMethods().contains("VLAN")) {
throw new InvalidParameterValueException("Cannot dedicate guest vlan range. " + "Physical isolation type of network " + physicalNetworkId + " is not VLAN");
}
// Get the start and end vlan
final String[] vlanRange = vlan.split("-");
if (vlanRange.length != 2) {
throw new InvalidParameterValueException("Invalid format for parameter value vlan " + vlan + " .Vlan should be specified as 'startvlan-endvlan'");
}
try {
startVlan = Integer.parseInt(vlanRange[0]);
endVlan = Integer.parseInt(vlanRange[1]);
} catch (final NumberFormatException e) {
s_logger.warn("Unable to parse guest vlan range:", e);
throw new InvalidParameterValueException("Please provide valid guest vlan range");
}
// Verify guest vlan range exists in the system
final List<Pair<Integer, Integer>> existingRanges = physicalNetwork.getVnet();
Boolean exists = false;
if (!existingRanges.isEmpty()) {
for (int i = 0; i < existingRanges.size(); i++) {
final int existingStartVlan = existingRanges.get(i).first();
final int existingEndVlan = existingRanges.get(i).second();
if (startVlan <= endVlan && startVlan >= existingStartVlan && endVlan <= existingEndVlan) {
exists = true;
break;
}
}
if (!exists) {
throw new InvalidParameterValueException("Unable to find guest vlan by range " + vlan);
}
}
// Verify guest vlans in the range don't belong to a network of a different account
for (int i = startVlan; i <= endVlan; i++) {
final List<DataCenterVnetVO> allocatedVlans = _datacneterVnet.listAllocatedVnetsInRange(physicalNetwork.getDataCenterId(), physicalNetwork.getId(), startVlan, endVlan);
if (allocatedVlans != null && !allocatedVlans.isEmpty()) {
for (final DataCenterVnetVO allocatedVlan : allocatedVlans) {
if (allocatedVlan.getAccountId() != vlanOwner.getAccountId()) {
throw new InvalidParameterValueException("Guest vlan from this range " + allocatedVlan.getVnet() + " is allocated to a different account."
+ " Can only dedicate a range which has no allocated vlans or has vlans allocated to the same account ");
}
}
}
}
final List<AccountGuestVlanMapVO> guestVlanMaps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByPhysicalNetwork(physicalNetworkId);
// Verify if vlan range is already dedicated
for (final AccountGuestVlanMapVO guestVlanMap : guestVlanMaps) {
final List<Integer> vlanTokens = getVlanFromRange(guestVlanMap.getGuestVlanRange());
final int dedicatedStartVlan = vlanTokens.get(0).intValue();
final int dedicatedEndVlan = vlanTokens.get(1).intValue();
if (startVlan < dedicatedStartVlan & endVlan >= dedicatedStartVlan || startVlan >= dedicatedStartVlan & startVlan <= dedicatedEndVlan) {
throw new InvalidParameterValueException("Vlan range is already dedicated. Cannot" + " dedicate guest vlan range " + vlan);
}
}
// Sort the existing dedicated vlan ranges
Collections.sort(guestVlanMaps, new Comparator<AccountGuestVlanMapVO>() {
@Override
public int compare(final AccountGuestVlanMapVO obj1, final AccountGuestVlanMapVO obj2) {
final List<Integer> vlanTokens1 = getVlanFromRange(obj1.getGuestVlanRange());
final List<Integer> vlanTokens2 = getVlanFromRange(obj2.getGuestVlanRange());
return vlanTokens1.get(0).compareTo(vlanTokens2.get(0));
}
});
// Verify if vlan range extends an already dedicated range
for (int i = 0; i < guestVlanMaps.size(); i++) {
guestVlanMapId = guestVlanMaps.get(i).getId();
guestVlanMapAccountId = guestVlanMaps.get(i).getAccountId();
final List<Integer> vlanTokens1 = getVlanFromRange(guestVlanMaps.get(i).getGuestVlanRange());
// Range extends a dedicated vlan range to the left
if (endVlan == vlanTokens1.get(0).intValue() - 1) {
if (guestVlanMapAccountId == vlanOwnerId) {
updatedVlanRange = startVlan + "-" + vlanTokens1.get(1).intValue();
}
break;
}
// Range extends a dedicated vlan range to the right
if (startVlan == vlanTokens1.get(1).intValue() + 1 & guestVlanMapAccountId == vlanOwnerId) {
if (i != guestVlanMaps.size() - 1) {
final List<Integer> vlanTokens2 = getVlanFromRange(guestVlanMaps.get(i + 1).getGuestVlanRange());
// Range extends 2 vlan ranges, both to the right and left
if (endVlan == vlanTokens2.get(0).intValue() - 1 && guestVlanMaps.get(i + 1).getAccountId() == vlanOwnerId) {
_datacneterVnet.releaseDedicatedGuestVlans(guestVlanMaps.get(i + 1).getId());
_accountGuestVlanMapDao.remove(guestVlanMaps.get(i + 1).getId());
updatedVlanRange = vlanTokens1.get(0).intValue() + "-" + vlanTokens2.get(1).intValue();
break;
}
}
updatedVlanRange = vlanTokens1.get(0).intValue() + "-" + endVlan;
break;
}
}
// Dedicate vlan range
final AccountGuestVlanMapVO accountGuestVlanMapVO;
if (updatedVlanRange != null) {
accountGuestVlanMapVO = _accountGuestVlanMapDao.findById(guestVlanMapId);
accountGuestVlanMapVO.setGuestVlanRange(updatedVlanRange);
_accountGuestVlanMapDao.update(guestVlanMapId, accountGuestVlanMapVO);
} else {
accountGuestVlanMapVO = new AccountGuestVlanMapVO(vlanOwner.getAccountId(), physicalNetworkId);
accountGuestVlanMapVO.setGuestVlanRange(startVlan + "-" + endVlan);
_accountGuestVlanMapDao.persist(accountGuestVlanMapVO);
}
// For every guest vlan set the corresponding account guest vlan map id
final List<Integer> finaVlanTokens = getVlanFromRange(accountGuestVlanMapVO.getGuestVlanRange());
for (int i = finaVlanTokens.get(0).intValue(); i <= finaVlanTokens.get(1).intValue(); i++) {
final List<DataCenterVnetVO> dataCenterVnet = _datacneterVnet.findVnet(physicalNetwork.getDataCenterId(), physicalNetworkId, Integer.toString(i));
dataCenterVnet.get(0).setAccountGuestVlanMapId(accountGuestVlanMapVO.getId());
_datacneterVnet.update(dataCenterVnet.get(0).getId(), dataCenterVnet.get(0));
}
return accountGuestVlanMapVO;
}
private List<Integer> getVlanFromRange(final String vlanRange) {
// Get the start and end vlan
final String[] vlanTokens = vlanRange.split("-");
final List<Integer> tokens = new ArrayList<>();
try {
final int startVlan = Integer.parseInt(vlanTokens[0]);
final int endVlan = Integer.parseInt(vlanTokens[1]);
tokens.add(startVlan);
tokens.add(endVlan);
} catch (final NumberFormatException e) {
s_logger.warn("Unable to parse guest vlan range:", e);
throw new InvalidParameterValueException("Please provide valid guest vlan range");
}
return tokens;
}
@Override
public Pair<List<? extends GuestVlan>, Integer> listDedicatedGuestVlanRanges(final ListDedicatedGuestVlanRangesCmd cmd) {
final Long id = cmd.getId();
final String accountName = cmd.getAccountName();
final Long domainId = cmd.getDomainId();
final Long projectId = cmd.getProjectId();
final String guestVlanRange = cmd.getGuestVlanRange();
final Long physicalNetworkId = cmd.getPhysicalNetworkId();
final Long zoneId = cmd.getZoneId();
Long accountId = null;
if (accountName != null && domainId != null) {
if (projectId != null) {
throw new InvalidParameterValueException("Account and projectId can't be specified together");
}
final Account account = _accountDao.findActiveAccount(accountName, domainId);
if (account == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account " + accountName);
final DomainVO domain = ApiDBUtils.findDomainById(domainId);
String domainUuid = domainId.toString();
if (domain != null) {
domainUuid = domain.getUuid();
}
ex.addProxyObject(domainUuid, "domainId");
throw ex;
} else {
accountId = account.getId();
}
}
// set project information
if (projectId != null) {
final Project project = _projectMgr.getProject(projectId);
if (project == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project by id " + projectId);
ex.addProxyObject(projectId.toString(), "projectId");
throw ex;
}
accountId = project.getProjectAccountId();
}
final SearchBuilder<AccountGuestVlanMapVO> sb = _accountGuestVlanMapDao.createSearchBuilder();
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
sb.and("guestVlanRange", sb.entity().getGuestVlanRange(), SearchCriteria.Op.EQ);
sb.and("physicalNetworkId", sb.entity().getPhysicalNetworkId(), SearchCriteria.Op.EQ);
if (zoneId != null) {
final SearchBuilder<PhysicalNetworkVO> physicalnetworkSearch = _physicalNetworkDao.createSearchBuilder();
physicalnetworkSearch.and("zoneId", physicalnetworkSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
sb.join("physicalnetworkSearch", physicalnetworkSearch, sb.entity().getPhysicalNetworkId(), physicalnetworkSearch.entity().getId(), JoinBuilder.JoinType.INNER);
}
final SearchCriteria<AccountGuestVlanMapVO> sc = sb.create();
if (id != null) {
sc.setParameters("id", id);
}
if (accountId != null) {
sc.setParameters("accountId", accountId);
}
if (guestVlanRange != null) {
sc.setParameters("guestVlanRange", guestVlanRange);
}
if (physicalNetworkId != null) {
sc.setParameters("physicalNetworkId", physicalNetworkId);
}
if (zoneId != null) {
sc.setJoinParameters("physicalnetworkSearch", "zoneId", zoneId);
}
final Filter searchFilter = new Filter(AccountGuestVlanMapVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
final Pair<List<AccountGuestVlanMapVO>, Integer> result = _accountGuestVlanMapDao.searchAndCount(sc, searchFilter);
return new Pair<>(result.first(), result.second());
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_DEDICATED_GUEST_VLAN_RANGE_RELEASE, eventDescription = "releasing" + " dedicated guest vlan range", async = true)
@DB
public boolean releaseDedicatedGuestVlanRange(final Long dedicatedGuestVlanRangeId) {
// Verify dedicated range exists
final AccountGuestVlanMapVO dedicatedGuestVlan = _accountGuestVlanMapDao.findById(dedicatedGuestVlanRangeId);
if (dedicatedGuestVlan == null) {
throw new InvalidParameterValueException("Dedicated guest vlan with specified" + " id doesn't exist in the system");
}
// Remove dedication for the guest vlan
_datacneterVnet.releaseDedicatedGuestVlans(dedicatedGuestVlan.getId());
if (_accountGuestVlanMapDao.remove(dedicatedGuestVlanRangeId)) {
return true;
} else {
return false;
}
}
@Override
public Pair<List<? extends PhysicalNetworkTrafficType>, Integer> listTrafficTypes(final Long physicalNetworkId) {
final PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId);
if (network == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system");
ex.addProxyObject(physicalNetworkId.toString(), "physicalNetworkId");
throw ex;
}
final Pair<List<PhysicalNetworkTrafficTypeVO>, Integer> result = _pNTrafficTypeDao.listAndCountBy(physicalNetworkId);
return new Pair<>(result.first(), result.second());
}
@Override
//TODO: duplicated in NetworkModel
public NetworkVO getExclusiveGuestNetwork(final long zoneId) {
final List<NetworkVO> networks = _networksDao.listBy(Account.ACCOUNT_ID_SYSTEM, zoneId, GuestType.Shared, TrafficType.Guest);
if (networks == null || networks.isEmpty()) {
throw new InvalidParameterValueException("Unable to find network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone " + zoneId);
}
if (networks.size() > 1) {
throw new InvalidParameterValueException("Found more than 1 network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone "
+ zoneId);
}
return networks.get(0);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "associating Ip", async = true)
public IpAddress associateIPToNetwork(final long ipId, final long networkId) throws InsufficientAddressCapacityException, ResourceAllocationException,
ResourceUnavailableException,
ConcurrentOperationException {
final Network network = _networksDao.findById(networkId);
if (network == null) {
// release the acquired IP addrress before throwing the exception
// else it will always be in allocating state
releaseIpAddress(ipId);
throw new InvalidParameterValueException("Invalid network id is given");
}
if (network.getVpcId() != null) {
// release the acquired IP addrress before throwing the exception
// else it will always be in allocating state
releaseIpAddress(ipId);
throw new InvalidParameterValueException("Can't assign ip to the network directly when network belongs" + " to VPC.Specify vpcId to associate ip address to VPC");
}
return _ipAddrMgr.associateIPToGuestNetwork(ipId, networkId, true);
}
@Override
@DB
public Network createPrivateNetwork(final String networkName, final String displayText, final long physicalNetworkId, final String broadcastUriString, final String startIp,
String endIp, final String gateway, final String netmask, final long networkOwnerId, final Long vpcId, final Boolean sourceNat,
final Long networkOfferingId)
throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
final Account owner = _accountMgr.getAccount(networkOwnerId);
// Get system network offering
NetworkOfferingVO ntwkOff = null;
if (networkOfferingId != null) {
ntwkOff = _networkOfferingDao.findById(networkOfferingId);
}
if (ntwkOff == null) {
ntwkOff = findSystemNetworkOffering(NetworkOffering.DefaultPrivateGatewayNetworkOffering);
}
// Validate physical network
final PhysicalNetwork pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
if (pNtwk == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a physical network" + " having the given id");
ex.addProxyObject(String.valueOf(physicalNetworkId), "physicalNetworkId");
throw ex;
}
// VALIDATE IP INFO
// if end ip is not specified, default it to startIp
if (!NetUtils.isValidIp4(startIp)) {
throw new InvalidParameterValueException("Invalid format for the ip address parameter");
}
if (endIp == null) {
endIp = startIp;
} else if (!NetUtils.isValidIp4(endIp)) {
throw new InvalidParameterValueException("Invalid format for the endIp address parameter");
}
if (!NetUtils.isValidIp4(gateway)) {
throw new InvalidParameterValueException("Invalid gateway");
}
if (!NetUtils.isValidIp4Netmask(netmask)) {
throw new InvalidParameterValueException("Invalid netmask");
}
final String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
final URI uri = BroadcastDomainType.fromString(broadcastUriString);
final String uriString = uri.toString();
final BroadcastDomainType tiep = BroadcastDomainType.getSchemeValue(uri);
// numeric vlan or vlan uri are ok for now
// TODO make a test for any supported scheme
if (!(tiep == BroadcastDomainType.Vlan || tiep == BroadcastDomainType.Lswitch)) {
throw new InvalidParameterValueException("unsupported type of broadcastUri specified: " + broadcastUriString);
}
final NetworkOfferingVO ntwkOffFinal = ntwkOff;
try {
return Transaction.execute(new TransactionCallbackWithException<Network, Exception>() {
@Override
public Network doInTransaction(final TransactionStatus status) throws ResourceAllocationException, InsufficientCapacityException {
//lock datacenter as we need to get mac address seq from there
final DataCenterVO dc = _dcDao.lockRow(pNtwk.getDataCenterId(), true);
//check if we need to create guest network
Network privateNetwork = _networksDao.getPrivateNetwork(uriString, cidr, networkOwnerId, pNtwk.getDataCenterId(), networkOfferingId);
if (privateNetwork == null) {
//create Guest network
privateNetwork = _networkMgr.createGuestNetwork(ntwkOffFinal.getId(), networkName, displayText, gateway, cidr, uriString, null, owner, null, pNtwk,
pNtwk.getDataCenterId(), ACLType.Account, null, vpcId, null, null, true, null,
dc.getDns1(), dc.getDns2(), null);
if (privateNetwork != null) {
s_logger.debug("Successfully created guest network " + privateNetwork);
} else {
throw new CloudRuntimeException("Creating guest network failed");
}
} else {
s_logger.debug("Private network already exists: " + privateNetwork);
//Do not allow multiple private gateways with same Vlan within a VPC
if (vpcId != null && vpcId.equals(privateNetwork.getVpcId())) {
throw new InvalidParameterValueException("Private network for the vlan: " + uriString + " and cidr " + cidr + " already exists " + "for Vpc " + vpcId
+ " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
}
}
if (vpcId != null) {
//add entry to private_ip_address table
PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkIdAndVpcId(privateNetwork.getId(), startIp, vpcId);
if (privateIp != null) {
throw new InvalidParameterValueException("Private ip address " + startIp + " already used for private gateway" + " in zone "
+ _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
}
final Long mac = dc.getMacAddress();
final Long nextMac = mac + 1;
dc.setMacAddress(nextMac);
privateIp = new PrivateIpVO(startIp, privateNetwork.getId(), nextMac, vpcId, sourceNat);
_privateIpDao.persist(privateIp);
_dcDao.update(dc.getId(), dc);
}
s_logger.debug("Private network " + privateNetwork + " is created");
return privateNetwork;
}
});
} catch (final Exception e) {
ExceptionUtil.rethrowRuntime(e);
ExceptionUtil.rethrow(e, ResourceAllocationException.class);
ExceptionUtil.rethrow(e, InsufficientCapacityException.class);
throw new IllegalStateException(e);
}
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NIC_SECONDARY_IP_ASSIGN, eventDescription = "assigning secondary ip to nic", create = true)
public NicSecondaryIp allocateSecondaryGuestIP(final long nicId, final String requestedIp) throws InsufficientAddressCapacityException {
final Account caller = CallContext.current().getCallingAccount();
//check whether the nic belongs to user vm.
final NicVO nicVO = _nicDao.findById(nicId);
if (nicVO == null) {
throw new InvalidParameterValueException("There is no nic for the " + nicId);
}
if (nicVO.getVmType() != VirtualMachine.Type.User) {
throw new InvalidParameterValueException("The nic is not belongs to user vm");
}
final VirtualMachine vm = _userVmDao.findById(nicVO.getInstanceId());
if (vm == null) {
throw new InvalidParameterValueException("There is no vm with the nic");
}
final long networkId = nicVO.getNetworkId();
final Account ipOwner = _accountMgr.getAccount(vm.getAccountId());
// verify permissions
_accountMgr.checkAccess(caller, null, true, vm);
final Network network = _networksDao.findById(networkId);
if (network == null) {
throw new InvalidParameterValueException("Invalid network id is given");
}
final int maxAllowedIpsPerNic = NumbersUtil.parseInt(_configDao.getValue(Config.MaxNumberOfSecondaryIPsPerNIC.key()), 10);
final Long nicWiseIpCount = _nicSecondaryIpDao.countByNicId(nicId);
if (nicWiseIpCount.intValue() >= maxAllowedIpsPerNic) {
s_logger.error("Maximum Number of Ips \"vm.network.nic.max.secondary.ipaddresses = \"" + maxAllowedIpsPerNic + " per Nic has been crossed for the nic " + nicId + ".");
throw new InsufficientAddressCapacityException("Maximum Number of Ips per Nic has been crossed.", Nic.class, nicId);
}
s_logger.debug("Calling the ip allocation ...");
String ipaddr = null;
//Isolated network can exist in Basic zone only, so no need to verify the zone type
if (network.getGuestType() == Network.GuestType.Isolated) {
try {
ipaddr = _ipAddrMgr.allocateGuestIP(network, requestedIp);
} catch (final InsufficientAddressCapacityException e) {
throw new InvalidParameterValueException("Allocating guest ip for nic failed");
}
} else if (network.getGuestType() == Network.GuestType.Shared) {
//for basic zone, need to provide the podId to ensure proper ip alloation
Long podId = null;
final DataCenter dc = _dcDao.findById(network.getDataCenterId());
if (dc.getNetworkType() == NetworkType.Basic) {
final VMInstanceVO vmi = (VMInstanceVO) vm;
podId = vmi.getPodIdToDeployIn();
if (podId == null) {
throw new InvalidParameterValueException("vm pod id is null in Basic zone; can't decide the range for ip allocation");
}
}
try {
ipaddr = _ipAddrMgr.allocatePublicIpForGuestNic(network, podId, ipOwner, requestedIp);
if (ipaddr == null) {
throw new InvalidParameterValueException("Allocating ip to guest nic " + nicId + " failed");
}
} catch (final InsufficientAddressCapacityException e) {
s_logger.error("Allocating ip to guest nic " + nicId + " failed");
return null;
}
} else if (network.getTrafficType() == TrafficType.Public) {
try {
final PublicIp ip = _ipAddrMgr.assignPublicIpAddress(vm.getDataCenterId(), null, ipOwner, VlanType.VirtualNetwork, null, requestedIp, false);
ipaddr = ip.getAddress().toString();
} catch (final InsufficientAddressCapacityException e) {
throw new InvalidParameterValueException("Allocating public ip for nic failed");
}
} else {
s_logger.error("AddIpToVMNic is not supported in this network...");
return null;
}
if (ipaddr != null) {
// we got the ip addr so up the nics table and secondary ip
final String addrFinal = ipaddr;
final long id = Transaction.execute(new TransactionCallback<Long>() {
@Override
public Long doInTransaction(final TransactionStatus status) {
final boolean nicSecondaryIpSet = nicVO.getSecondaryIp();
if (!nicSecondaryIpSet) {
nicVO.setSecondaryIp(true);
// commit when previously set ??
s_logger.debug("Setting nics table ...");
_nicDao.update(nicId, nicVO);
}
s_logger.debug("Setting nic_secondary_ip table ...");
final Long vmId = nicVO.getInstanceId();
final NicSecondaryIpVO secondaryIpVO = new NicSecondaryIpVO(nicId, addrFinal, vmId, ipOwner.getId(), ipOwner.getDomainId(), networkId);
_nicSecondaryIpDao.persist(secondaryIpVO);
return secondaryIpVO.getId();
}
});
return getNicSecondaryIp(id);
} else {
return null;
}
}
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NIC_SECONDARY_IP_UNASSIGN, eventDescription = "Removing secondary ip " +
"from nic", async = true)
public boolean releaseSecondaryIpFromNic(final long ipAddressId) {
final Account caller = CallContext.current().getCallingAccount();
boolean success = false;
// Verify input parameters
final NicSecondaryIpVO secIpVO = _nicSecondaryIpDao.findById(ipAddressId);
if (secIpVO == null) {
throw new InvalidParameterValueException("Unable to find secondary ip address by id");
}
final VirtualMachine vm = _userVmDao.findById(secIpVO.getVmId());
if (vm == null) {
throw new InvalidParameterValueException("There is no vm with the given secondary ip");
}
// verify permissions
_accountMgr.checkAccess(caller, null, true, vm);
final Network network = _networksDao.findById(secIpVO.getNetworkId());
if (network == null) {
throw new InvalidParameterValueException("Invalid network id is given");
}
// Validate network offering
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(network.getNetworkOfferingId());
final Long nicId = secIpVO.getNicId();
s_logger.debug("ip id = " + ipAddressId + " nic id = " + nicId);
//check is this the last secondary ip for NIC
final List<NicSecondaryIpVO> ipList = _nicSecondaryIpDao.listByNicId(nicId);
boolean lastIp = false;
if (ipList.size() == 1) {
// this is the last secondary ip to nic
lastIp = true;
}
final DataCenter dc = _dcDao.findById(network.getDataCenterId());
if (dc == null) {
throw new InvalidParameterValueException("Invalid zone Id is given");
}
s_logger.debug("Calling secondary ip " + secIpVO.getIp4Address() + " release ");
if (dc.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Isolated) {
//check PF or static NAT is configured on this ip address
final String secondaryIp = secIpVO.getIp4Address();
final List<FirewallRuleVO> fwRulesList = _firewallDao.listByNetworkAndPurpose(network.getId(), Purpose.PortForwarding);
if (fwRulesList.size() != 0) {
for (final FirewallRuleVO rule : fwRulesList) {
if (_portForwardingDao.findByIdAndIp(rule.getId(), secondaryIp) != null) {
s_logger.debug("VM nic IP " + secondaryIp + " is associated with the port forwarding rule");
throw new InvalidParameterValueException("Can't remove the secondary ip " + secondaryIp + " is associate with the port forwarding rule");
}
}
}
//check if the secondary ip associated with any static nat rule
final IPAddressVO publicIpVO = _ipAddressDao.findByIpAndNetworkId(secIpVO.getNetworkId(), secondaryIp);
if (publicIpVO != null) {
s_logger.debug("VM nic IP " + secondaryIp + " is associated with the static NAT rule public IP address id " + publicIpVO.getId());
throw new InvalidParameterValueException("Can' remove the ip " + secondaryIp + "is associate with static NAT rule public IP address id " + publicIpVO.getId());
}
if (_lbService.isLbRuleMappedToVmGuestIp(secondaryIp)) {
s_logger.debug("VM nic IP " + secondaryIp + " is mapped to load balancing rule");
throw new InvalidParameterValueException("Can't remove the secondary ip " + secondaryIp + " is mapped to load balancing rule");
}
} else if (dc.getNetworkType() == NetworkType.Basic || ntwkOff.getGuestType() == Network.GuestType.Shared) {
final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(secIpVO.getNetworkId(), secIpVO.getIp4Address());
if (ip != null) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
_ipAddrMgr.markIpAsUnavailable(ip.getId());
_ipAddressDao.unassignIpAddress(ip.getId());
}
});
}
} else if (network.getTrafficType() == TrafficType.Public) {
final IPAddressVO publicIpVO = _ipAddressDao.findByIpAndSourceNetworkId(secIpVO.getNetworkId(), secIpVO.getIp4Address());
final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
final Account callerAccount = _accountMgr.getActiveAccountById(callerUser.getAccountId());
_ipAddrMgr.disassociatePublicIpAddress(publicIpVO.getId(), callerUser.getId(), callerAccount);
} else {
throw new InvalidParameterValueException("Not supported for this network now");
}
success = removeNicSecondaryIP(secIpVO, lastIp);
return success;
}
private boolean removeNicSecondaryIP(final NicSecondaryIpVO ipVO, final boolean lastIp) {
final long nicId = ipVO.getNicId();
final NicVO nic = _nicDao.findById(nicId);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
if (lastIp) {
nic.setSecondaryIp(false);
s_logger.debug("Setting nics secondary ip to false ...");
_nicDao.update(nicId, nic);
}
s_logger.debug("Revoving nic secondary ip entry ...");
_nicSecondaryIpDao.remove(ipVO.getId());
}
});
return true;
}
@Override
public List<? extends Nic> listNics(final ListNicsCmd cmd) {
final Account caller = CallContext.current().getCallingAccount();
final Long nicId = cmd.getNicId();
final long vmId = cmd.getVmId();
final Long networkId = cmd.getNetworkId();
final UserVmVO userVm = _userVmDao.findById(vmId);
if (userVm == null || !userVm.isDisplayVm() && caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Virtual mahine id does not exist");
ex.addProxyObject(Long.valueOf(vmId).toString(), "vmId");
throw ex;
}
_accountMgr.checkAccess(caller, null, true, userVm);
return _networkMgr.listVmNics(vmId, nicId, networkId);
}
@Override
public Map<Capability, String> getNetworkOfferingServiceCapabilities(final NetworkOffering offering, final Service service) {
if (!areServicesSupportedByNetworkOffering(offering.getId(), service)) {
// TBD: We should be sending networkOfferingId and not the offering object itself.
throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the network offering " + offering);
}
Map<Capability, String> serviceCapabilities = new HashMap<>();
// get the Provider for this Service for this offering
final List<String> providers = _ntwkOfferingSrvcDao.listProvidersForServiceForNetworkOffering(offering.getId(), service);
if (providers.isEmpty()) {
// TBD: We should be sending networkOfferingId and not the offering object itself.
throw new InvalidParameterValueException("Service " + service.getName() + " is not supported by the network offering " + offering);
}
// FIXME - in post 3.0 we are going to support multiple providers for the same service per network offering, so
// we have to calculate capabilities for all of them
final String provider = providers.get(0);
// FIXME we return the capabilities of the first provider of the service - what if we have multiple providers
// for same Service?
final NetworkElement element = _networkModel.getElementImplementingProvider(provider);
if (element != null) {
final Map<Service, Map<Capability, String>> elementCapabilities = element.getCapabilities();
if (elementCapabilities == null || !elementCapabilities.containsKey(service)) {
// TBD: We should be sending providerId and not the offering object itself.
throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider="
+ provider);
}
serviceCapabilities = elementCapabilities.get(service);
}
return serviceCapabilities;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_IP_UPDATE, eventDescription = "updating public ip address", async = true)
public IpAddress updateIP(final Long id, final String customId, final Boolean displayIp) {
final Account caller = CallContext.current().getCallingAccount();
final IPAddressVO ipVO = _ipAddressDao.findById(id);
if (ipVO == null) {
throw new InvalidParameterValueException("Unable to find ip address by id");
}
// verify permissions
if (ipVO.getAllocatedToAccountId() != null) {
_accountMgr.checkAccess(caller, null, true, ipVO);
} else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
throw new PermissionDeniedException("Only Root admin can update non-allocated ip addresses");
}
if (customId != null) {
ipVO.setUuid(customId);
}
if (displayIp != null) {
ipVO.setDisplay(displayIp);
}
_ipAddressDao.update(id, ipVO);
return _ipAddressDao.findById(id);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NIC_SECONDARY_IP_CONFIGURE, eventDescription = "Configuring secondary ip rules", async = true)
public boolean configureNicSecondaryIp(final NicSecondaryIp secIp) {
return true;
}
private NicSecondaryIp getNicSecondaryIp(final long id) {
final NicSecondaryIp nicSecIp = _nicSecondaryIpDao.findById(id);
if (nicSecIp == null) {
return null;
}
return nicSecIp;
}
private NetworkOfferingVO findSystemNetworkOffering(final String offeringName) {
final List<NetworkOfferingVO> allOfferings = _networkOfferingDao.listSystemNetworkOfferings();
for (final NetworkOfferingVO offer : allOfferings) {
if (offer.getName().equals(offeringName)) {
return offer;
}
}
return null;
}
@DB
private void addOrRemoveVnets(final String[] listOfRanges, final PhysicalNetworkVO network) {
List<String> addVnets = null;
List<String> removeVnets = null;
final HashSet<String> tempVnets = new HashSet<>();
final HashSet<String> vnetsInDb = new HashSet<>();
List<Pair<Integer, Integer>> vnetranges = null;
String comaSeperatedStingOfVnetRanges = null;
int i = 0;
if (listOfRanges.length != 0) {
_physicalNetworkDao.acquireInLockTable(network.getId(), 10);
vnetranges = validateVlanRange(network, listOfRanges);
//computing vnets to be removed.
removeVnets = getVnetsToremove(network, vnetranges);
//computing vnets to add
vnetsInDb.addAll(_datacneterVnet.listVnetsByPhysicalNetworkAndDataCenter(network.getDataCenterId(), network.getId()));
tempVnets.addAll(vnetsInDb);
for (final Pair<Integer, Integer> vlan : vnetranges) {
for (i = vlan.first(); i <= vlan.second(); i++) {
tempVnets.add(Integer.toString(i));
}
}
tempVnets.removeAll(vnetsInDb);
//vnets to add in tempVnets.
//adding and removing vnets from vnetsInDb
if (removeVnets != null && removeVnets.size() != 0) {
vnetsInDb.removeAll(removeVnets);
}
if (tempVnets.size() != 0) {
addVnets = new ArrayList<>();
addVnets.addAll(tempVnets);
vnetsInDb.addAll(tempVnets);
}
//sorting the vnets in Db to generate a coma seperated list of the vnet string.
if (vnetsInDb.size() != 0) {
comaSeperatedStingOfVnetRanges = generateVnetString(new ArrayList<>(vnetsInDb));
}
network.setVnet(comaSeperatedStingOfVnetRanges);
final List<String> addVnetsFinal = addVnets;
final List<String> removeVnetsFinal = removeVnets;
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
if (addVnetsFinal != null) {
s_logger.debug("Adding vnet range " + addVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id="
+ network.getDataCenterId() + " as a part of updatePhysicalNetwork call");
//add vnet takes a list of strings to be added. each string is a vnet.
_dcDao.addVnet(network.getDataCenterId(), network.getId(), addVnetsFinal);
}
if (removeVnetsFinal != null) {
s_logger.debug("removing vnet range " + removeVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id="
+ network.getDataCenterId() + " as a part of updatePhysicalNetwork call");
//deleteVnets takes a list of strings to be removed. each string is a vnet.
_datacneterVnet.deleteVnets(TransactionLegacy.currentTxn(), network.getDataCenterId(), network.getId(), removeVnetsFinal);
}
_physicalNetworkDao.update(network.getId(), network);
}
});
_physicalNetworkDao.releaseFromLockTable(network.getId());
}
}
private PhysicalNetworkServiceProvider addDefaultVirtualRouterToPhysicalNetwork(final long physicalNetworkId) {
final PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId, Network.Provider.VirtualRouter.getName(), null, null);
// add instance of the provider
final NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.VirtualRouter.getName());
if (networkElement == null) {
throw new CloudRuntimeException("Unable to find the Network Element implementing the VirtualRouter Provider");
}
final VirtualRouterElement element = (VirtualRouterElement) networkElement;
element.addElement(nsp.getId(), Type.VirtualRouter);
return nsp;
}
private PhysicalNetworkServiceProvider addDefaultVpcVirtualRouterToPhysicalNetwork(final long physicalNetworkId) {
final PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId, Network.Provider.VPCVirtualRouter.getName(), null, null);
final NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.VPCVirtualRouter.getName());
if (networkElement == null) {
throw new CloudRuntimeException("Unable to find the Network Element implementing the VPCVirtualRouter Provider");
}
final VpcVirtualRouterElement element = (VpcVirtualRouterElement) networkElement;
element.addElement(nsp.getId(), Type.VPCVirtualRouter);
return nsp;
}
private List<Pair<Integer, Integer>> validateVlanRange(final PhysicalNetworkVO network, final String[] listOfRanges) {
Integer StartVnet;
Integer EndVnet;
final List<Pair<Integer, Integer>> vlanTokens = new ArrayList<>();
for (final String vlanRange : listOfRanges) {
final String[] VnetRange = vlanRange.split("-");
// Init with [min,max] of VLAN. Actually 0x000 and 0xFFF are reserved by IEEE, shoudn't be used.
long minVnet = MIN_VLAN_ID;
long maxVnet = MAX_VLAN_ID;
// for GRE phynets allow up to 32bits
// TODO: Not happy about this test.
// What about guru-like objects for physical networs?
s_logger.debug("ISOLATION METHODS:" + network.getIsolationMethods());
// Java does not have unsigned types...
if (network.getIsolationMethods().contains("GRE")) {
minVnet = MIN_GRE_KEY;
maxVnet = MAX_GRE_KEY;
} else if (network.getIsolationMethods().contains("VXLAN")) {
minVnet = MIN_VXLAN_VNI;
maxVnet = MAX_VXLAN_VNI;
// fail if zone already contains VNI, need to be unique per zone.
// since adding a range adds each VNI to the database, need only check min/max
for (final String vnet : VnetRange) {
s_logger.debug("Looking to see if VNI " + vnet + " already exists on another network in zone " + network.getDataCenterId());
final List<DataCenterVnetVO> vnis = _datacneterVnet.findVnet(network.getDataCenterId(), vnet);
if (vnis != null && !vnis.isEmpty()) {
for (final DataCenterVnetVO vni : vnis) {
if (vni.getPhysicalNetworkId() != network.getId()) {
s_logger.debug("VNI " + vnet + " already exists on another network in zone, please specify a unique range");
throw new InvalidParameterValueException("VNI " + vnet + " already exists on another network in zone, please specify a unique range");
}
}
}
}
}
final String rangeMessage = " between " + minVnet + " and " + maxVnet;
if (VnetRange.length == 1 && VnetRange[0].equals("")) {
return vlanTokens;
}
if (VnetRange.length < 2) {
throw new InvalidParameterValueException("Please provide valid vnet range. vnet range should be a coma seperated list of vlan ranges. example 500-500,600-601"
+ rangeMessage);
}
if (VnetRange[0] == null || VnetRange[1] == null) {
throw new InvalidParameterValueException("Please provide valid vnet range" + rangeMessage);
}
try {
StartVnet = Integer.parseInt(VnetRange[0]);
EndVnet = Integer.parseInt(VnetRange[1]);
} catch (final NumberFormatException e) {
s_logger.warn("Unable to parse vnet range:", e);
throw new InvalidParameterValueException("Please provide valid vnet range. The vnet range should be a coma seperated list example 2001-2012,3000-3005."
+ rangeMessage);
}
if (StartVnet < minVnet || EndVnet > maxVnet) {
throw new InvalidParameterValueException("Vnet range has to be" + rangeMessage);
}
if (StartVnet > EndVnet) {
throw new InvalidParameterValueException("Vnet range has to be" + rangeMessage + " and start range should be lesser than or equal to stop range");
}
vlanTokens.add(new Pair<>(StartVnet, EndVnet));
}
return vlanTokens;
}
private List<String> getVnetsToremove(final PhysicalNetworkVO network, final List<Pair<Integer, Integer>> vnetRanges) {
int i;
final List<String> removeVnets = new ArrayList<>();
final HashSet<String> vnetsInDb = new HashSet<>();
vnetsInDb.addAll(_datacneterVnet.listVnetsByPhysicalNetworkAndDataCenter(network.getDataCenterId(), network.getId()));
//remove all the vnets from vnets in db to check if there are any vnets that are not there in given list.
//remove all the vnets not in the list of vnets passed by the user.
if (vnetRanges.size() == 0) {
//this implies remove all vlans.
removeVnets.addAll(vnetsInDb);
final int allocated_vnets = _datacneterVnet.countAllocatedVnets(network.getId());
if (allocated_vnets > 0) {
throw new InvalidParameterValueException("physicalnetwork " + network.getId() + " has " + allocated_vnets + " vnets in use");
}
return removeVnets;
}
for (final Pair<Integer, Integer> vlan : vnetRanges) {
for (i = vlan.first(); i <= vlan.second(); i++) {
vnetsInDb.remove(Integer.toString(i));
}
}
String vnetRange = null;
if (vnetsInDb.size() != 0) {
removeVnets.addAll(vnetsInDb);
vnetRange = generateVnetString(removeVnets);
} else {
return removeVnets;
}
for (final String vnet : vnetRange.split(",")) {
final String[] range = vnet.split("-");
final Integer start = Integer.parseInt(range[0]);
final Integer end = Integer.parseInt(range[1]);
_datacneterVnet.lockRange(network.getDataCenterId(), network.getId(), start, end);
final List<DataCenterVnetVO> result = _datacneterVnet.listAllocatedVnetsInRange(network.getDataCenterId(), network.getId(), start, end);
if (!result.isEmpty()) {
throw new InvalidParameterValueException("physicalnetwork " + network.getId() + " has allocated vnets in the range " + start + "-" + end);
}
// If the range is partially dedicated to an account fail the request
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByPhysicalNetwork(network.getId());
for (final AccountGuestVlanMapVO map : maps) {
final String[] vlans = map.getGuestVlanRange().split("-");
final Integer dedicatedStartVlan = Integer.parseInt(vlans[0]);
final Integer dedicatedEndVlan = Integer.parseInt(vlans[1]);
if (start >= dedicatedStartVlan && start <= dedicatedEndVlan || end >= dedicatedStartVlan && end <= dedicatedEndVlan) {
throw new InvalidParameterValueException("Vnet range " + map.getGuestVlanRange() + " is dedicated" + " to an account. The specified range " + start + "-" + end
+ " overlaps with the dedicated range " + " Please release the overlapping dedicated range before deleting the range");
}
}
}
return removeVnets;
}
private String generateVnetString(final List<String> vnetList) {
Collections.sort(vnetList, new Comparator<String>() {
@Override
public int compare(final String s1, final String s2) {
return Integer.valueOf(s1).compareTo(Integer.valueOf(s2));
}
});
int i;
//build the vlan string form the sorted list.
String vnetRange = "";
String startvnet = vnetList.get(0);
String endvnet = "";
for (i = 0; i < vnetList.size() - 1; i++) {
if (Integer.parseInt(vnetList.get(i + 1)) - Integer.parseInt(vnetList.get(i)) > 1) {
endvnet = vnetList.get(i);
vnetRange = vnetRange + startvnet + "-" + endvnet + ",";
startvnet = vnetList.get(i + 1);
}
}
endvnet = vnetList.get(vnetList.size() - 1);
vnetRange = vnetRange + startvnet + "-" + endvnet + ",";
vnetRange = vnetRange.substring(0, vnetRange.length() - 1);
return vnetRange;
}
private boolean isNetworkSystem(final Network network) {
final NetworkOffering no = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId());
if (no.isSystemOnly()) {
return true;
} else {
return false;
}
}
private Network commitNetwork(final Long networkOfferingId, final String gateway, final String startIP, final String endIP, final String netmask, final String networkDomain,
final String vlanId, final String name, final String displayText, final Account caller, final Long physicalNetworkId, final Long zoneId,
final Long domainId, final boolean isDomainSpecific, final Boolean subdomainAccessFinal, final Long vpcId, final String startIPv6,
final String endIPv6, final String ip6Gateway, final String ip6Cidr, final Boolean displayNetwork, final Long aclId, final String isolatedPvlan,
final NetworkOfferingVO ntwkOff, final PhysicalNetwork pNtwk, final ACLType aclType, final Account ownerFinal, final String cidr,
final boolean createVlan, final String dns1, final String dns2, final String ipExclusionList) throws InsufficientCapacityException,
ResourceAllocationException {
try {
final Network network = Transaction.execute(new TransactionCallbackWithException<Network, Exception>() {
@Override
public Network doInTransaction(final TransactionStatus status) throws InsufficientCapacityException, ResourceAllocationException {
Account owner = ownerFinal;
Boolean subdomainAccess = subdomainAccessFinal;
Long sharedDomainId = null;
if (isDomainSpecific) {
if (domainId != null) {
sharedDomainId = domainId;
} else {
sharedDomainId = _domainMgr.getDomain(Domain.ROOT_DOMAIN).getId();
subdomainAccess = true;
}
}
// default owner to system if network has aclType=Domain
if (aclType == ACLType.Domain) {
owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM);
}
// Create guest network
Network network;
if (vpcId != null) {
if (!_configMgr.isOfferingForVpc(ntwkOff)) {
throw new InvalidParameterValueException("Network offering can't be used for VPC networks");
}
if (aclId != null) {
final NetworkACL acl = _networkACLDao.findById(aclId);
if (acl == null) {
throw new InvalidParameterValueException("Unable to find specified NetworkACL");
}
if (aclId != NetworkACL.DEFAULT_DENY && aclId != NetworkACL.DEFAULT_ALLOW) {
// ACL is not default DENY/ALLOW
// ACL should be associated with a VPC
if (!vpcId.equals(acl.getVpcId())) {
throw new InvalidParameterValueException("ACL: " + aclId + " do not belong to the VPC");
}
}
}
network = _vpcMgr.createVpcGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, zoneId,
aclType, subdomainAccess, vpcId, aclId, caller, displayNetwork, dns1, dns2, ipExclusionList);
} else {
if (_configMgr.isOfferingForVpc(ntwkOff)) {
throw new InvalidParameterValueException("Network offering can be used for VPC networks only");
}
network = _networkMgr.createGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, zoneId,
aclType, subdomainAccess, vpcId, ip6Gateway, ip6Cidr, displayNetwork, isolatedPvlan, dns1, dns2, ipExclusionList);
}
if (_accountMgr.isRootAdmin(caller.getId()) && createVlan && network != null) {
// Create vlan ip range
_configMgr.createVlanAndPublicIpRange(pNtwk.getDataCenterId(), network.getId(), physicalNetworkId, false, null, startIP, endIP, gateway, netmask, vlanId,
null, null, startIPv6, endIPv6, ip6Gateway, ip6Cidr);
}
return network;
}
});
return network;
} catch (final Exception e) {
ExceptionUtil.rethrowRuntime(e);
ExceptionUtil.rethrow(e, InsufficientCapacityException.class);
ExceptionUtil.rethrow(e, ResourceAllocationException.class);
throw new IllegalStateException(e);
}
}
private boolean isSharedNetworkOfferingWithServices(final long networkOfferingId) {
final NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId);
if (networkOffering.getGuestType() == Network.GuestType.Shared
&& (areServicesSupportedByNetworkOffering(networkOfferingId, Service.SourceNat) || areServicesSupportedByNetworkOffering(networkOfferingId, Service.StaticNat)
|| areServicesSupportedByNetworkOffering(networkOfferingId, Service.Firewall)
|| areServicesSupportedByNetworkOffering(networkOfferingId, Service.PortForwarding) || areServicesSupportedByNetworkOffering(networkOfferingId, Service.Lb))) {
return true;
}
return false;
}
protected boolean areServicesSupportedByNetworkOffering(final long networkOfferingId, final Service... services) {
return _ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(networkOfferingId, services);
}
@Override
@DB
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_configs = _configDao.getConfiguration("Network", params);
_cidrLimit = NumbersUtil.parseInt(_configs.get(Config.NetworkGuestCidrLimit.key()), 22);
_allowSubdomainNetworkAccess = Boolean.valueOf(_configs.get(Config.SubDomainNetworkAccess.key()));
s_logger.info("Network Service is configured.");
return true;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
private boolean checkForNonStoppedVmInNetwork(final long networkId) {
final List<UserVmVO> vms = _userVmDao.listByNetworkIdAndStates(networkId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Migrating,
VirtualMachine.State.Stopping);
return vms.isEmpty();
}
private boolean canUpgrade(final Network network, final long oldNetworkOfferingId, final long newNetworkOfferingId) {
final NetworkOffering oldNetworkOffering = _networkOfferingDao.findByIdIncludingRemoved(oldNetworkOfferingId);
final NetworkOffering newNetworkOffering = _networkOfferingDao.findById(newNetworkOfferingId);
// can upgrade only Isolated networks
if (oldNetworkOffering.getGuestType() != GuestType.Isolated) {
throw new InvalidParameterValueException("NetworkOfferingId can be upgraded only for the network of type " + GuestType.Isolated);
}
// Type of the network should be the same
if (oldNetworkOffering.getGuestType() != newNetworkOffering.getGuestType()) {
s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " are of different types, can't upgrade");
return false;
}
// tags should be the same
if (newNetworkOffering.getTags() != null) {
if (oldNetworkOffering.getTags() == null) {
s_logger.debug("New network offering id=" + newNetworkOfferingId + " has tags and old network offering id=" + oldNetworkOfferingId + " doesn't, can't upgrade");
return false;
}
if (!StringUtils.areTagsEqual(oldNetworkOffering.getTags(), newNetworkOffering.getTags())) {
s_logger.debug("Network offerings " + newNetworkOffering.getUuid() + " and " + oldNetworkOffering.getUuid() + " have different tags, can't upgrade");
return false;
}
}
// Traffic types should be the same
if (oldNetworkOffering.getTrafficType() != newNetworkOffering.getTrafficType()) {
s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different traffic types, can't upgrade");
return false;
}
// specify vlan should be the same
if (oldNetworkOffering.getSpecifyVlan() != newNetworkOffering.getSpecifyVlan()) {
s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different values for specifyVlan, can't upgrade");
return false;
}
// specify ipRanges should be the same
if (oldNetworkOffering.getSpecifyIpRanges() != newNetworkOffering.getSpecifyIpRanges()) {
s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different values for specifyIpRangess, can't upgrade");
return false;
}
// Check all ips
final List<IPAddressVO> userIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), null);
final List<PublicIp> publicIps = new ArrayList<>();
if (userIps != null && !userIps.isEmpty()) {
for (final IPAddressVO userIp : userIps) {
final PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
publicIps.add(publicIp);
}
}
if (oldNetworkOffering.isConserveMode() && !newNetworkOffering.isConserveMode()) {
if (!canIpsUsedForNonConserve(publicIps)) {
return false;
}
}
return canIpsUseOffering(publicIps, newNetworkOfferingId);
}
@Inject
public void setNetworkGurus(final List<NetworkGuru> networkGurus) {
_networkGurus = networkGurus;
}
}
|
Removed remaining restartNetwork references as we will never restart a network.
|
cosmic-core/server/src/main/java/com/cloud/network/NetworkServiceImpl.java
|
Removed remaining restartNetwork references as we will never restart a network.
|
<ide><path>osmic-core/server/src/main/java/com/cloud/network/NetworkServiceImpl.java
<ide> final String domainSuffix, final Long networkOfferingId, final Boolean changeCidr, final String guestVmCidr, final Boolean displayNetwork,
<ide> final String customId, final String dns1, final String dns2, final String ipExclusionList) {
<ide>
<del> boolean restartNetwork = false;
<del>
<ide> // verify input parameters
<ide> final NetworkVO network = _networksDao.findById(networkId);
<ide> if (network == null) {
<ide>
<ide> if (dns1 != null) {
<ide> network.setDns1(dns1);
<del> restartNetwork = true;
<ide> }
<ide>
<ide> if (dns2 != null) {
<ide> network.setDns2(dns2);
<del> restartNetwork = true;
<ide> }
<ide>
<ide> if (ipExclusionList != null) {
<ide> }
<ide>
<ide> final ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount);
<del> // 1) Shutdown all the elements and cleanup all the rules. Don't allow to shutdown network in intermediate
<del> // states - Shutdown and Implementing
<del> final boolean validStateToShutdown = network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup || network.getState() == Network.State
<del> .Allocated;
<del> if (restartNetwork) {
<del> if (validStateToShutdown) {
<del> if (!changeCidr) {
<del> s_logger.debug("Shutting down elements and resources for network id=" + networkId + " as a part of network update");
<del>
<del> if (!_networkMgr.shutdownNetworkElementsAndResources(context, true, network)) {
<del> s_logger.warn("Failed to shutdown the network elements and resources as a part of network restart: " + network);
<del> final CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of update to network of " +
<del> "specified id");
<del> ex.addProxyObject(network.getUuid(), "networkId");
<del> throw ex;
<del> }
<del> } else {
<del> // We need to shutdown the network, since we want to re-implement the network.
<del> s_logger.debug("Shutting down network id=" + networkId + " as a part of network update");
<del>
<del> //check if network has reservation
<del> if (NetUtils.isNetworkAWithinNetworkB(network.getCidr(), network.getNetworkCidr())) {
<del> s_logger.warn("Existing IP reservation will become ineffective for the network with id = " + networkId
<del> + " You need to reapply reservation after network reimplementation.");
<del> //set cidr to the newtork cidr
<del> network.setCidr(network.getNetworkCidr());
<del> //set networkCidr to null to bring network back to no IP reservation state
<del> network.setNetworkCidr(null);
<del> }
<del>
<del> if (!_networkMgr.shutdownNetwork(network.getId(), context, true)) {
<del> s_logger.warn("Failed to shutdown the network as a part of update to network with specified id");
<del> final CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network as a part of update of specified network id");
<del> ex.addProxyObject(network.getUuid(), "networkId");
<del> throw ex;
<del> }
<del> }
<del> } else {
<del> final CloudRuntimeException ex = new CloudRuntimeException(
<del> "Failed to shutdown the network elements and resources as a part of update to network with specified id; network is in wrong state: " + network.getState());
<del> ex.addProxyObject(network.getUuid(), "networkId");
<del> throw ex;
<del> }
<del> }
<del>
<del> // 2) Only after all the elements and rules are shutdown properly, update the network VO
<del> // get updated network
<del> final Network.State networkState = _networksDao.findById(networkId).getState();
<del> final boolean validStateToImplement = networkState == Network.State.Implemented || networkState == Network.State.Setup || networkState == Network.State.Allocated;
<del> if (restartNetwork && !validStateToImplement) {
<del> final CloudRuntimeException ex = new CloudRuntimeException(
<del> "Failed to implement the network elements and resources as a part of update to network with specified id; network is in wrong state: " + networkState);
<del> ex.addProxyObject(network.getUuid(), "networkId");
<del> throw ex;
<del> }
<ide>
<ide> if (networkOfferingId != null) {
<ide> if (networkOfferingChanged) {
<ide> s_logger.error("Vm for nic " + nic.getId() + " not found with Vm Id:" + vmId);
<ide> continue;
<ide> }
<del> final long isDefault = nic.isDefaultNic() ? 1 : 0;
<del> final String nicIdString = Long.toString(nic.getId());
<ide> }
<ide> }
<ide> });
<ide> _networksDao.update(networkId, network);
<ide> }
<ide>
<del> // 3) Implement the elements and rules again
<del> if (restartNetwork) {
<del> if (network.getState() != Network.State.Allocated) {
<del> final DeployDestination dest = new DeployDestination(zoneRepository.findById(network.getDataCenterId()).orElse(null), null, null, null);
<del> s_logger.debug("Implementing the network " + network + " elements and resources as a part of network update");
<del> try {
<del> if (!changeCidr) {
<del> _networkMgr.implementNetworkElementsAndResources(dest, context, network, _networkOfferingDao.findById(network.getNetworkOfferingId()));
<del> } else {
<del> _networkMgr.implementNetwork(network.getId(), dest, context);
<del> }
<del> } catch (final Exception ex) {
<del> s_logger.warn("Failed to implement network " + network + " elements and resources as a part of network update due to ", ex);
<del> final CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified id) elements and resources as a part of network update");
<del> e.addProxyObject(network.getUuid(), "networkId");
<del> throw e;
<del> }
<del> }
<del> }
<del>
<del> // 4) if network has been upgraded from a non persistent ntwk offering to a persistent ntwk offering,
<del> // implement the network if its not already
<add> // if network has been upgraded from a non persistent ntwk offering to a persistent ntwk offering, implement the network if its not already
<ide> if (networkOfferingChanged && !oldNtwkOff.getIsPersistent() && networkOffering.getIsPersistent()) {
<ide> if (network.getState() == Network.State.Allocated) {
<ide> try {
|
|
JavaScript
|
apache-2.0
|
fbb5b35a163ffc79b2458fc7d54bafb0065e5a9e
| 0 |
dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui
|
import { Trans } from "@lingui/macro";
import { i18nMark } from "@lingui/react";
import browserInfo from "browser-info";
import classNames from "classnames";
import { Modal } from "reactjs-components";
import PropTypes from "prop-types";
import React from "react";
import { Icon } from "@dcos/ui-kit";
import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum";
import { iconSizeXs } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens";
import ClickToSelect from "../ClickToSelect";
import MetadataStore from "../../stores/MetadataStore";
import ModalHeading from "../modals/ModalHeading";
const METHODS_TO_BIND = ["onClose"];
const osTypes = {
Windows: "windows",
"OS X": "darwin",
Linux: "linux"
};
class CliInstallModal extends React.Component {
constructor() {
super(...arguments);
let selectedOS = browserInfo().os;
if (!Object.keys(osTypes).includes(selectedOS)) {
selectedOS = "Linux";
}
this.state = { selectedOS };
METHODS_TO_BIND.forEach(method => {
this[method] = this[method].bind(this);
});
}
handleSelectedOSChange(selectedOS) {
this.setState({ selectedOS });
}
onClose() {
this.props.onClose();
}
getSubHeader() {
if (!this.props.subHeaderContent) {
return false;
}
return (
<p className="text-align-center flush-bottom">
{this.props.subHeaderContent}
</p>
);
}
getCliInstructions() {
const hostname = global.location.hostname;
const protocol = global.location.protocol.replace(/[^\w]/g, "");
let port = "";
if (global.location.port) {
port = ":" + global.location.port;
}
const clusterUrl = `${protocol}://${hostname}${port}`;
const { selectedOS } = this.state;
const downloadUrl = `https://downloads.dcos.io/binaries/cli/${
osTypes[selectedOS]
}/x86-64/dcos-1.13/dcos`;
if (selectedOS === "Windows") {
return this.getWindowsInstallInstruction(clusterUrl, downloadUrl);
}
const instructions = [
`curl ${downloadUrl} -o dcos`,
`chmod +x ./dcos`,
`sudo mv dcos /usr/local/bin`,
`dcos cluster setup ${clusterUrl}`,
`dcos`
].filter(instruction => instruction !== undefined);
return (
<div>
<Trans render="p" className="short-bottom">
Copy and paste the code snippet into the terminal:
</Trans>
<div className="flush-top snippet-wrapper">
<ClickToSelect>
<pre className="prettyprint flush-bottom">
{instructions.join(" && \n")}
</pre>
</ClickToSelect>
</div>
</div>
);
}
getWindowsInstallInstruction(clusterUrl, downloadUrl) {
const steps = [
`cd path/to/download/directory`,
`dcos cluster setup ${clusterUrl}`,
`dcos`
]
.filter(instruction => instruction !== undefined)
.map((instruction, index) => {
const helpText =
index === 0
? i18nMark("In Command Prompt, enter")
: i18nMark("Enter");
return (
<li key={index}>
<Trans render="p" className="short-bottom" id={helpText} />
<div className="flush-top snippet-wrapper">
<ClickToSelect>
<pre className="prettyprint flush-bottom prettyprinted">
{instruction}
</pre>
</ClickToSelect>
</div>
</li>
);
});
return (
<ol>
<Trans render="li">
Download and install:{" "}
<a href={downloadUrl + ".exe"}>
<Icon
shape={SystemIcons.Download}
size={iconSizeXs}
color="currentColor"
/>
Download dcos.exe
</a>
.
</Trans>
{steps}
</ol>
);
}
getOSButtons() {
const { selectedOS } = this.state;
return Object.keys(osTypes).map((name, index) => {
const classSet = classNames({
"button button-outline": true,
active: name === selectedOS
});
return (
<button
className={classSet}
key={index}
onClick={this.handleSelectedOSChange.bind(this, name)}
>
{name}
</button>
);
});
}
getContent() {
return (
<div className="install-cli-modal-content">
<Trans render="p">
Choose your operating system and follow the instructions. For any
issues or questions, please refer to our{" "}
<a href={MetadataStore.buildDocsURI("/cli/install")} target="_blank">
documentation
</a>
.
</Trans>
<div className="button-group">{this.getOSButtons()}</div>
{this.getCliInstructions()}
</div>
);
}
render() {
const { footer, open, showFooter, title } = this.props;
const header = (
<ModalHeading>
<Trans id={title} render="span" />
</ModalHeading>
);
return (
<Modal
header={header}
footer={footer}
modalClass="modal"
onClose={this.onClose}
open={open}
showHeader={true}
showFooter={showFooter}
subHeader={this.getSubHeader()}
>
{this.getContent()}
</Modal>
);
}
}
CliInstallModal.propTypes = {
title: PropTypes.string.isRequired,
subHeaderContent: PropTypes.string,
showFooter: PropTypes.bool.isRequired,
footer: PropTypes.node,
onClose: PropTypes.func.isRequired
};
module.exports = CliInstallModal;
|
src/js/components/modals/CliInstallModal.js
|
import { Trans } from "@lingui/macro";
import { i18nMark } from "@lingui/react";
import browserInfo from "browser-info";
import classNames from "classnames";
import { Modal } from "reactjs-components";
import PropTypes from "prop-types";
import React from "react";
import { Icon } from "@dcos/ui-kit";
import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum";
import { iconSizeXs } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens";
import ClickToSelect from "../ClickToSelect";
import MetadataStore from "../../stores/MetadataStore";
import ModalHeading from "../modals/ModalHeading";
const METHODS_TO_BIND = ["onClose"];
const osTypes = {
Windows: "windows",
"OS X": "darwin",
Linux: "linux"
};
class CliInstallModal extends React.Component {
constructor() {
super(...arguments);
let selectedOS = browserInfo().os;
if (!Object.keys(osTypes).includes(selectedOS)) {
selectedOS = "Linux";
}
this.state = { selectedOS };
METHODS_TO_BIND.forEach(method => {
this[method] = this[method].bind(this);
});
}
handleSelectedOSChange(selectedOS) {
this.setState({ selectedOS });
}
onClose() {
this.props.onClose();
}
getSubHeader() {
if (!this.props.subHeaderContent) {
return false;
}
return (
<p className="text-align-center flush-bottom">
{this.props.subHeaderContent}
</p>
);
}
getCliInstructions() {
const hostname = global.location.hostname;
const protocol = global.location.protocol.replace(/[^\w]/g, "");
let port = "";
if (global.location.port) {
port = ":" + global.location.port;
}
const clusterUrl = `${protocol}://${hostname}${port}`;
const { selectedOS } = this.state;
const downloadUrl = `https://downloads.dcos.io/binaries/cli/${
osTypes[selectedOS]
}/x86-64/dcos-1.13/dcos`;
if (selectedOS === "Windows") {
return this.getWindowsInstallInstruction(clusterUrl, downloadUrl);
}
const instructions = [
`[ -d /usr/local/bin ] || sudo mkdir -p /usr/local/bin`,
`curl ${downloadUrl} -o dcos`,
`sudo mv dcos /usr/local/bin`,
`sudo chmod +x /usr/local/bin/dcos`,
`dcos cluster setup ${clusterUrl}`,
`dcos`
].filter(instruction => instruction !== undefined);
return (
<div>
<Trans render="p" className="short-bottom">
Copy and paste the code snippet into the terminal:
</Trans>
<div className="flush-top snippet-wrapper">
<ClickToSelect>
<pre className="prettyprint flush-bottom">
{instructions.join(" && \n")}
</pre>
</ClickToSelect>
</div>
</div>
);
}
getWindowsInstallInstruction(clusterUrl, downloadUrl) {
const steps = [
`cd path/to/download/directory`,
`dcos cluster setup ${clusterUrl}`,
`dcos`
]
.filter(instruction => instruction !== undefined)
.map((instruction, index) => {
const helpText =
index === 0
? i18nMark("In Command Prompt, enter")
: i18nMark("Enter");
return (
<li key={index}>
<Trans render="p" className="short-bottom" id={helpText} />
<div className="flush-top snippet-wrapper">
<ClickToSelect>
<pre className="prettyprint flush-bottom prettyprinted">
{instruction}
</pre>
</ClickToSelect>
</div>
</li>
);
});
return (
<ol>
<Trans render="li">
Download and install:{" "}
<a href={downloadUrl + ".exe"}>
<Icon
shape={SystemIcons.Download}
size={iconSizeXs}
color="currentColor"
/>
Download dcos.exe
</a>
.
</Trans>
{steps}
</ol>
);
}
getOSButtons() {
const { selectedOS } = this.state;
return Object.keys(osTypes).map((name, index) => {
const classSet = classNames({
"button button-outline": true,
active: name === selectedOS
});
return (
<button
className={classSet}
key={index}
onClick={this.handleSelectedOSChange.bind(this, name)}
>
{name}
</button>
);
});
}
getContent() {
return (
<div className="install-cli-modal-content">
<Trans render="p">
Choose your operating system and follow the instructions. For any
issues or questions, please refer to our{" "}
<a href={MetadataStore.buildDocsURI("/cli/install")} target="_blank">
documentation
</a>
.
</Trans>
<div className="button-group">{this.getOSButtons()}</div>
{this.getCliInstructions()}
</div>
);
}
render() {
const { footer, open, showFooter, title } = this.props;
const header = (
<ModalHeading>
<Trans id={title} render="span" />
</ModalHeading>
);
return (
<Modal
header={header}
footer={footer}
modalClass="modal"
onClose={this.onClose}
open={open}
showHeader={true}
showFooter={showFooter}
subHeader={this.getSubHeader()}
>
{this.getContent()}
</Modal>
);
}
}
CliInstallModal.propTypes = {
title: PropTypes.string.isRequired,
subHeaderContent: PropTypes.string,
showFooter: PropTypes.bool.isRequired,
footer: PropTypes.node,
onClose: PropTypes.func.isRequired
};
module.exports = CliInstallModal;
|
chore: simplify cli instructions
Simplify CLI installation instructions on UNIX.
This removes the need to have `sudo` 2 times,
by running `chmod` before moving the file.
It also removes the creation of `/usr/local/bin`
directory, it should be present in any UNIX
installation. Having this line is not really useful,
if the directory is missing it's most likely
not in the $PATH either, so the subsequent
`dcos cluster setup` command would still fail anyways.
|
src/js/components/modals/CliInstallModal.js
|
chore: simplify cli instructions
|
<ide><path>rc/js/components/modals/CliInstallModal.js
<ide> }
<ide>
<ide> const instructions = [
<del> `[ -d /usr/local/bin ] || sudo mkdir -p /usr/local/bin`,
<ide> `curl ${downloadUrl} -o dcos`,
<add> `chmod +x ./dcos`,
<ide> `sudo mv dcos /usr/local/bin`,
<del> `sudo chmod +x /usr/local/bin/dcos`,
<ide> `dcos cluster setup ${clusterUrl}`,
<ide> `dcos`
<ide> ].filter(instruction => instruction !== undefined);
|
|
JavaScript
|
mit
|
cf49503111b1d76b7f0b2978a5f4e1d3efd07e45
| 0 |
denwilliams/client,ninjablocks/client,ninjablocks/client,denwilliams/client
|
var
path = require('path')
, util = require('util')
, upnode = require('upnode')
, logger = require(path.resolve(__dirname, '..', 'lib', 'logger'))
, stream = require('stream')
, tls = require('tls')
, net = require('net')
, fs = require('fs')
;
function client(opts, credentials, app) {
var
modules = {}
;
stream.call(this);
this.log = app.log;
/** waiting for credentials abstraction
if((!credentials) || !credentials.id) {
app.log.error('Unable to create client, no ninja serial specified.');
return false;
}
*/
this.addModule = function addModule(name, opts, mod, app) {
var newModule = new mod(opts, app);
if(!modules[name]) { modules[name] = {}; }
modules[name][opts.id] = newModule;
newModule.on('error', this.moduleError.bind(newModule));
return modules[name][opts.id];
};
this.moduleError = function moduleError(err) {
this.log.error("Module error: %s", err);
};
this.opts = opts || {};
this.node = undefined; // upnode
this.parameters = this.getParameters(opts);
this.transport = opts.secure ? tls : net;
};
util.inherits(client, stream);
client.prototype.handlers = {
revokeCredentials : function revokeCredentials() {
this.log.info('Invalid token, restarting.');
this.emit('device::invalidToken', true);
// invalidate token
process.exit(1);
}
, execute : function execute(cmd, cb) {
// execute command
}
, update : function update(to) {
// update client
}
};
client.prototype.connect = function connect() {
var client = this;
this.node = upnode(this.handlers).connect(this.parameters);
this.node.on('up', client.up.bind(client));
this.node.on('reconnect', client.reconnect.bind(client));
};
client.prototype.up = function up() {
console.log(this);
this.emit('device::up', true);
this.log.info("Client connected to cloud.");
};
client.prototype.down = function down() {
this.emit('device::down', true);
this.log.info("Client disconnected from cloud.");
};
client.prototype.reconnect = function reconnect() {
this.emit('device::reconnecting', true);
this.log.info("Connecting to cloud...");
};
client.prototype.getParameters = function getParameters(opts) {
var parameters = {
ping : 10000
, timeout : 5000
, reconnect : 2000
, createStream : function createStream() {
return this.transport.connect(
this.opts.cloudPort
, this.opts.cloudHost
)
}
, block : this.block
};
};
client.prototype.block = function block(remote, conn) {
var
token = this.credentials.token || undefined
, params = {
//TODO: better client default/detection?
client : opts.client || 'beagle'
, id : opts.id
, version : {
// node, arduino, utilities & system versions
}
}
, handshake = function handshake(err, res) {
if(err) {
this.log.error("Error in remote handshake: %s", err);
return;
}
conn.emit('up', res);
this.emit('device::authed', res);
}.bind(this)
;
if(token) {
remote.handshake(params, token, handshake);
}
else {
this.emit('device::needsActivation', res);
this.log.info("Ready to be activated.");
// activate
}
};
client.prototype.loadModule = function loadModule(name, opts, app) {
if(!name) {
this.log.error("loadModule error: invalid module name");
return false;
}
try {
var
file = path.resolve(__dirname, 'ninja_modules', name)
;
if(fs.existsSync(file)) {
var mod = require(file);
}
else {
this.log.error("loadModule error: No such module '%s'", name);
return null;
}
}
catch(e) {
this.log.error("loadModule error: %s", e);
return false;
}
this.log.info("loadModule success: %s", name);
return this.addModule(name, opts, mod, app);
};
module.exports = client;
|
app/client.js
|
var
upnode = require('upnode')
, path = require('path')
, logger = require(path.resolve(__dirname, '..', 'lib', 'logger'))
, tls = require('tls')
, net = require('net')
, fs = require('fs')
;
function client(opts, credentials, app) {
var
modules = {}
;
this.log = app.log;
/** waiting for credentials abstraction
if((!credentials) || !credentials.id) {
app.log.error('Unable to create client, no ninja serial specified.');
return false;
}
*/
this.addModule = function addModule(name, opts, mod, app) {
var newModule = new mod(opts, app);
if(!modules[name]) { modules[name] = {}; }
modules[name][opts.id] = newModule;
newModule.on('error', this.moduleError.bind(newModule));
return modules[name][opts.id];
};
this.moduleError = function moduleError(err) {
this.log.error("Module error: %s", err);
};
this.opts = opts || {};
this.node = undefined; // upnode
this.parameters = this.getParameters(opts);
this.transport = opts.secure ? tls : net;
};
client.prototype.handlers = {
revokeCredentials : function revokeCredentials() {
this.log.info('Invalid token, restarting.');
this.emit('device::invalidToken', true);
// invalidate token
process.exit(1);
}
, execute : function execute(cmd, cb) {
// execute command
}
, update : function update(to) {
// update client
}
};
client.prototype.connect = function connect() {
this.node = upnode(this.handlers).connect(this.parameters);
this.node.on('up', this.up);
this.node.on('reconnect', this.reconnect);
};
client.prototype.up = function up() {
this.emit('device::up', true);
this.log.info("Client connected to cloud.");
};
client.prototype.down = function down() {
this.emit('device::down', true);
this.log.info("Client disconnected from cloud.");
};
client.prototype.reconnect = function reconnect() {
this.emit('device::reconnecting', true);
this.log.info("Reconnecting to cloud...");
};
client.prototype.getParameters = function getParameters(opts) {
var parameters = {
ping : 10000
, timeout : 5000
, reconnect : 2000
, createStream : function createStream() {
return this.transport.connect(
this.opts.cloudPort
, this.opts.cloudHost
)
}
, block : this.block
};
};
client.prototype.block = function block(remote, conn) {
var
token = this.credentials.token || undefined
, params = {
//TODO: better client default/detection?
client : opts.client || 'beagle'
, id : opts.id
, version : {
// node, arduino, utilities & system versions
}
}
;
if(token) {
remote.handshake(params, token, function handshake(err, res) {
if(err) {
this.log.error("Error in remote handshake: %s", err);
return;
}
conn.emit('up', res);
this.emit('device::authed', res);
});
}
else {
this.emit('device::needsActivation', res);
this.log.info("Ready to be activated.");
// activate
}
};
client.prototype.loadModule = function loadModule(name, opts, app) {
if(!name) {
this.log.error("loadModule error: invalid module name");
return false;
}
try {
var
file = path.resolve(__dirname, 'ninja_modules', name)
;
if(fs.existsSync(file)) {
var mod = require(file);
}
else {
this.log.error("loadModule error: No such module '%s'", name);
return null;
}
}
catch(e) {
this.log.error("loadModule error: %s", e);
return false;
}
this.log.info("loadModule success: %s", name);
return this.addModule(name, opts, mod, app);
};
module.exports = client;
|
Ninja client is now a stream.
|
app/client.js
|
Ninja client is now a stream.
|
<ide><path>pp/client.js
<ide> var
<del> upnode = require('upnode')
<del> , path = require('path')
<add> path = require('path')
<add> , util = require('util')
<add> , upnode = require('upnode')
<ide> , logger = require(path.resolve(__dirname, '..', 'lib', 'logger'))
<add> , stream = require('stream')
<ide> , tls = require('tls')
<ide> , net = require('net')
<ide> , fs = require('fs')
<ide> var
<ide> modules = {}
<ide> ;
<add>
<add> stream.call(this);
<ide>
<ide> this.log = app.log;
<ide>
<ide> this.transport = opts.secure ? tls : net;
<ide> };
<ide>
<add>util.inherits(client, stream);
<add>
<ide> client.prototype.handlers = {
<ide>
<ide> revokeCredentials : function revokeCredentials() {
<ide>
<ide> client.prototype.connect = function connect() {
<ide>
<add> var client = this;
<ide> this.node = upnode(this.handlers).connect(this.parameters);
<ide>
<del> this.node.on('up', this.up);
<del> this.node.on('reconnect', this.reconnect);
<add> this.node.on('up', client.up.bind(client));
<add>
<add> this.node.on('reconnect', client.reconnect.bind(client));
<ide> };
<ide>
<ide> client.prototype.up = function up() {
<ide>
<add> console.log(this);
<ide> this.emit('device::up', true);
<ide> this.log.info("Client connected to cloud.");
<ide> };
<ide> client.prototype.reconnect = function reconnect() {
<ide>
<ide> this.emit('device::reconnecting', true);
<del> this.log.info("Reconnecting to cloud...");
<add> this.log.info("Connecting to cloud...");
<ide> };
<ide>
<ide> client.prototype.getParameters = function getParameters(opts) {
<ide> // node, arduino, utilities & system versions
<ide> }
<ide> }
<del> ;
<del>
<del> if(token) {
<del>
<del> remote.handshake(params, token, function handshake(err, res) {
<add> , handshake = function handshake(err, res) {
<ide>
<ide> if(err) {
<ide>
<ide> this.log.error("Error in remote handshake: %s", err);
<ide> return;
<ide> }
<add>
<ide> conn.emit('up', res);
<ide> this.emit('device::authed', res);
<del> });
<add>
<add> }.bind(this)
<add> ;
<add>
<add> if(token) {
<add>
<add> remote.handshake(params, token, handshake);
<ide> }
<ide> else {
<ide>
|
|
Java
|
apache-2.0
|
956481c7b62e6848dac351118a613959f9a4081b
| 0 |
inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service
|
package org.slc.sli.api.security.aspects;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slc.sli.api.security.enums.DefaultRoles;
import org.slc.sli.api.security.enums.Rights;
import org.slc.sli.api.service.EntityService;
import org.slc.sli.validation.EntitySchemaRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* Aspect for handling Entity Service operations.
*
* @author shalka
*/
@Aspect
public class EntityServiceAspect {
private static final Logger LOG = LoggerFactory.getLogger(EntityServiceAspect.class);
private static List<String> entitiesAlwaysAllow = Arrays.asList("realm");
private static List<String> methodsAlwaysAllow = Arrays.asList("getEntityDefinition");
private static Map<String, Rights> neededRights = new HashMap<String, Rights>();
private EntitySchemaRegistry schemaRegistry;
public void setSchemaRegistry(EntitySchemaRegistry schemaRegistry) {
this.schemaRegistry = schemaRegistry;
}
static {
neededRights.put("get", Rights.READ_GENERAL);
neededRights.put("list", Rights.READ_GENERAL);
neededRights.put("exists", Rights.READ_GENERAL);
neededRights.put("create", Rights.WRITE_GENERAL);
neededRights.put("update", Rights.WRITE_GENERAL);
neededRights.put("delete", Rights.WRITE_GENERAL);
}
@Around("call(* EntityService.*(..)) && !within(EntityServiceAspect) && !withincode(* *.mock*(..))")
public Object controlAccess(ProceedingJoinPoint pjp) throws Throwable {
boolean hasAccess = false;
Rights neededRight = null;
Signature entitySignature = pjp.getSignature();
String entityFunctionName = entitySignature.getName();
EntityService service = (EntityService) pjp.getTarget();
String entityDefinitionType = service.getEntityDefinition().getType();
if (entitiesAlwaysAllow.contains(entityDefinitionType) || methodsAlwaysAllow.contains(entityFunctionName)) {
LOG.debug("granting access to user for entity");
hasAccess = true;
} else {
neededRight = neededRights.get(entityFunctionName);
LOG.debug("attempted access of {} function", entitySignature.toString());
Collection<GrantedAuthority> myAuthorities = SecurityContextHolder.getContext().getAuthentication()
.getAuthorities();
LOG.debug("user rights: {}", myAuthorities.toString());
for (GrantedAuthority auth : myAuthorities) {
LOG.debug("checking rights for role: {}", auth.getAuthority());
try {
for (DefaultRoles role : DefaultRoles.values()) {
if (role.getSpringRoleName().equals(auth.getAuthority()) && role.hasRight(neededRight)) {
LOG.debug("granting access to user for entity");
hasAccess = true;
break;
}
}
if (hasAccess) {
break;
}
} catch (IllegalArgumentException ex) {
LOG.debug("could not find role. skipping current entry...");
continue;
}
}
}
if (hasAccess) {
LOG.debug("entering {} function [using Around]", entitySignature.toString());
Object entityReturned = pjp.proceed();
LOG.debug("exiting {} function [using Around]", entitySignature.toString());
return entityReturned;
} else {
LOG.debug("user was denied access due to insufficient permissions.");
throw new BadCredentialsException("User does not have authority to access entity.");
}
}
}
|
sli/api/src/main/java/org/slc/sli/api/security/aspects/EntityServiceAspect.java
|
package org.slc.sli.api.security.aspects;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slc.sli.api.security.enums.DefaultRoles;
import org.slc.sli.api.security.enums.Rights;
import org.slc.sli.api.service.EntityService;
import org.slc.sli.validation.EntitySchemaRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* Aspect for handling Entity Service operations.
*
* @author shalka
*/
@Aspect
public class EntityServiceAspect {
private static final Logger LOG = LoggerFactory.getLogger(EntityServiceAspect.class);
private static List<String> entitiesAlwaysAllow = Arrays.asList("realm");
private static List<String> methodsAlwaysAllow = Arrays.asList("getEntityDefinition");
private static Map<String, Rights> neededRights = new HashMap<String, Rights>();
private EntitySchemaRegistry schemaRegistry;
public void setSchemaRegistry(EntitySchemaRegistry schemaRegistry) {
this.schemaRegistry = schemaRegistry;
}
static {
neededRights.put("get", Rights.READ_GENERAL);
neededRights.put("list", Rights.READ_GENERAL);
neededRights.put("exists", Rights.READ_GENERAL);
neededRights.put("create", Rights.WRITE_GENERAL);
neededRights.put("update", Rights.WRITE_GENERAL);
neededRights.put("delete", Rights.WRITE_GENERAL);
}
@Around("call(* EntityService.*(..)) && !within(EntityServiceAspect) && !withincode(* *.mock*())")
public Object controlAccess(ProceedingJoinPoint pjp) throws Throwable {
boolean hasAccess = false;
Rights neededRight = null;
Signature entitySignature = pjp.getSignature();
String entityFunctionName = entitySignature.getName();
EntityService service = (EntityService) pjp.getTarget();
String entityDefinitionType = service.getEntityDefinition().getType();
if (entitiesAlwaysAllow.contains(entityDefinitionType) || methodsAlwaysAllow.contains(entityFunctionName)) {
LOG.debug("granting access to user for entity");
hasAccess = true;
} else {
neededRight = neededRights.get(entityFunctionName);
LOG.debug("attempted access of {} function", entitySignature.toString());
Collection<GrantedAuthority> myAuthorities = SecurityContextHolder.getContext().getAuthentication()
.getAuthorities();
LOG.debug("user rights: {}", myAuthorities.toString());
for (GrantedAuthority auth : myAuthorities) {
LOG.debug("checking rights for role: {}", auth.getAuthority());
try {
for (DefaultRoles role : DefaultRoles.values()) {
if (role.getSpringRoleName().equals(auth.getAuthority()) && role.hasRight(neededRight)) {
LOG.debug("granting access to user for entity");
hasAccess = true;
break;
}
}
if (hasAccess) {
break;
}
} catch (IllegalArgumentException ex) {
LOG.debug("could not find role. skipping current entry...");
continue;
}
}
}
if (hasAccess) {
LOG.debug("entering {} function [using Around]", entitySignature.toString());
Object entityReturned = pjp.proceed();
LOG.debug("exiting {} function [using Around]", entitySignature.toString());
return entityReturned;
} else {
LOG.debug("user was denied access due to insufficient permissions.");
throw new BadCredentialsException("User does not have authority to access entity.");
}
}
}
|
updated aspect ignore list to include mock* functions that take arguments
|
sli/api/src/main/java/org/slc/sli/api/security/aspects/EntityServiceAspect.java
|
updated aspect ignore list to include mock* functions that take arguments
|
<ide><path>li/api/src/main/java/org/slc/sli/api/security/aspects/EntityServiceAspect.java
<ide> neededRights.put("delete", Rights.WRITE_GENERAL);
<ide> }
<ide>
<del> @Around("call(* EntityService.*(..)) && !within(EntityServiceAspect) && !withincode(* *.mock*())")
<add> @Around("call(* EntityService.*(..)) && !within(EntityServiceAspect) && !withincode(* *.mock*(..))")
<ide> public Object controlAccess(ProceedingJoinPoint pjp) throws Throwable {
<ide>
<ide> boolean hasAccess = false;
|
|
Java
|
bsd-3-clause
|
a94ac01f015876cedf7e4e96317189658f8b8d13
| 0 |
MengZhang/translator-dssat,agmip/translator-dssat
|
package org.agmip.translators.dssat;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.agmip.translators.dssat.DssatCommonInput.copyItem;
import static org.agmip.util.MapUtil.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* DSSAT Experiment Data I/O API Class
*
* @author Meng Zhang
* @version 1.0
*/
public class DssatXFileOutput extends DssatCommonOutput {
private static final Logger LOG = LoggerFactory.getLogger(DssatXFileOutput.class);
// public static final DssatCRIDHelper crHelper = new DssatCRIDHelper();
/**
* DSSAT Experiment Data Output method
*
* @param arg0 file output path
* @param result data holder object
*/
@Override
public void writeFile(String arg0, Map result) {
// Initial variables
HashMap expData = (HashMap) result;
ArrayList<HashMap> soilArr = readSWData(expData, "soil");
ArrayList<HashMap> wthArr = readSWData(expData, "weather");
HashMap soilData;
HashMap wthData;
BufferedWriter bwX; // output object
StringBuilder sbGenData = new StringBuilder(); // construct the data info in the output
StringBuilder sbDomeData = new StringBuilder(); // construct the dome info in the output
StringBuilder sbNotesData = new StringBuilder(); // construct the data info in the output
StringBuilder sbData = new StringBuilder(); // construct the data info in the output
StringBuilder eventPart2 = new StringBuilder(); // output string for second part of event data
HashMap sqData;
ArrayList<HashMap> evtArr; // Arraylist for section data holder
ArrayList<HashMap> adjArr;
HashMap evtData;
// int trmnNum; // total numbers of treatment in the data holder
int cuNum; // total numbers of cultivars in the data holder
int flNum; // total numbers of fields in the data holder
int saNum; // total numbers of soil analysis in the data holder
int icNum; // total numbers of initial conditions in the data holder
int mpNum; // total numbers of plaintings in the data holder
int miNum; // total numbers of irrigations in the data holder
int mfNum; // total numbers of fertilizers in the data holder
int mrNum; // total numbers of residues in the data holder
int mcNum; // total numbers of chemical in the data holder
int mtNum; // total numbers of tillage in the data holder
int meNum; // total numbers of enveronment modification in the data holder
int mhNum; // total numbers of harvest in the data holder
int smNum; // total numbers of simulation controll record
ArrayList<HashMap> sqArr; // array for treatment record
ArrayList<HashMap> cuArr = new ArrayList(); // array for cultivars record
ArrayList<HashMap> flArr = new ArrayList(); // array for fields record
ArrayList<HashMap> saArr = new ArrayList(); // array for soil analysis record
ArrayList<HashMap> icArr = new ArrayList(); // array for initial conditions record
ArrayList<HashMap> mpArr = new ArrayList(); // array for plaintings record
ArrayList<ArrayList<HashMap>> miArr = new ArrayList(); // array for irrigations record
ArrayList<ArrayList<HashMap>> mfArr = new ArrayList(); // array for fertilizers record
ArrayList<ArrayList<HashMap>> mrArr = new ArrayList(); // array for residues record
ArrayList<ArrayList<HashMap>> mcArr = new ArrayList(); // array for chemical record
ArrayList<ArrayList<HashMap>> mtArr = new ArrayList(); // array for tillage record
ArrayList<ArrayList<HashMap>> meArr = new ArrayList(); // array for enveronment modification record
ArrayList<ArrayList<HashMap>> mhArr = new ArrayList(); // array for harvest record
ArrayList<HashMap> smArr = new ArrayList(); // array for simulation control record
// String exName;
boolean isFallow = false;
try {
// Set default value for missing data
if (expData == null || expData.isEmpty()) {
return;
}
// decompressData((HashMap) result);
setDefVal();
// Initial BufferedWriter
String fileName = getFileName(result, "X");
arg0 = revisePath(arg0);
outputFile = new File(arg0 + fileName);
bwX = new BufferedWriter(new FileWriter(outputFile));
// Output XFile
// EXP.DETAILS Section
sbError.append(String.format("*EXP.DETAILS: %1$-10s %2$s\r\n\r\n",
getFileName(result, "").replaceAll("\\.", ""),
getObjectOr(expData, "local_name", defValBlank)));
// GENERAL Section
sbGenData.append("*GENERAL\r\n");
// People
if (!getObjectOr(expData, "person_notes", "").equals("")) {
sbGenData.append(String.format("@PEOPLE\r\n %1$s\r\n", getObjectOr(expData, "person_notes", defValBlank)));
}
// Address
if (getObjectOr(expData, "institution", "").equals("")) {
// if (!getObjectOr(expData, "fl_loc_1", "").equals("")
// && getObjectOr(expData, "fl_loc_2", "").equals("")
// && getObjectOr(expData, "fl_loc_3", "").equals("")) {
// sbGenData.append(String.format("@ADDRESS\r\n %3$s, %2$s, %1$s\r\n",
// getObjectOr(expData, "fl_loc_1", defValBlank).toString(),
// getObjectOr(expData, "fl_loc_2", defValBlank).toString(),
// getObjectOr(expData, "fl_loc_3", defValBlank).toString()));
// }
} else {
sbGenData.append(String.format("@ADDRESS\r\n %1$s\r\n", getObjectOr(expData, "institution", defValBlank)));
}
// Site
if (!getObjectOr(expData, "site_name", "").equals("")) {
sbGenData.append(String.format("@SITE\r\n %1$s\r\n", getObjectOr(expData, "site_name", defValBlank)));
}
// Plot Info
if (isPlotInfoExist(expData)) {
sbGenData.append("@ PAREA PRNO PLEN PLDR PLSP PLAY HAREA HRNO HLEN HARM.........\r\n");
sbGenData.append(String.format(" %1$6s %2$5s %3$5s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$5s %10$-15s\r\n",
formatNumStr(6, expData, "plta", defValR),
formatNumStr(5, expData, "pltr#", defValI),
formatNumStr(5, expData, "pltln", defValR),
formatNumStr(5, expData, "pldr", defValI),
formatNumStr(5, expData, "pltsp", defValI),
getObjectOr(expData, "pllay", defValC),
formatNumStr(5, expData, "pltha", defValR),
formatNumStr(5, expData, "plth#", defValI),
formatNumStr(5, expData, "plthl", defValR),
getObjectOr(expData, "plthm", defValC)));
}
// Notes
if (!getObjectOr(expData, "tr_notes", "").equals("")) {
sbNotesData.append("@NOTES\r\n");
String notes = getObjectOr(expData, "tr_notes", defValC);
notes = notes.replaceAll("\\\\r\\\\n", "\r\n");
// If notes contain newline code, then write directly
if (notes.contains("\r\n")) {
// sbData.append(String.format(" %1$s\r\n", notes));
sbNotesData.append(notes);
} // Otherwise, add newline for every 75-bits charactors
else {
while (notes.length() > 75) {
sbNotesData.append(" ").append(notes.substring(0, 75)).append("\r\n");
notes = notes.substring(75);
}
sbNotesData.append(" ").append(notes).append("\r\n");
}
}
sbData.append("\r\n");
// TREATMENT Section
sqArr = getDataList(expData, "dssat_sequence", "data");
evtArr = getDataList(expData, "management", "events");
adjArr = getObjectOr(expData, "adjustments", new ArrayList());
ArrayList<HashMap> rootArr = getObjectOr(expData, "dssat_root", new ArrayList());
ArrayList<HashMap> meOrgArr = getDataList(expData, "dssat_environment_modification", "data");
ArrayList<HashMap> smOrgArr = getDataList(expData, "dssat_simulation_control", "data");
String seqId;
String em;
String sm;
boolean isAnyDomeApplied = false;
LinkedHashMap<String, String> appliedDomes = new LinkedHashMap<String, String>();
sbData.append("*TREATMENTS -------------FACTOR LEVELS------------\r\n");
sbData.append("@N R O C TNAME.................... CU FL SA IC MP MI MF MR MC MT ME MH SM\r\n");
// if there is no sequence info, create dummy data
if (sqArr.isEmpty()) {
sqArr.add(new HashMap());
}
// Set sequence related block info
for (int i = 0; i < sqArr.size(); i++) {
sqData = sqArr.get(i);
seqId = getValueOr(sqData, "seqid", defValBlank);
em = getValueOr(sqData, "em", defValBlank);
sm = getValueOr(sqData, "sm", defValBlank);
if (i < soilArr.size()) {
soilData = soilArr.get(i);
} else if (soilArr.isEmpty()) {
soilData = new HashMap();
} else {
soilData = soilArr.get(0);
}
if (soilData == null) {
soilData = new HashMap();
}
if (i < wthArr.size()) {
wthData = wthArr.get(i);
} else if (wthArr.isEmpty()) {
wthData = new HashMap();
} else {
wthData = wthArr.get(0);
}
if (wthData == null) {
wthData = new HashMap();
}
HashMap cuData = new HashMap();
HashMap flData = new HashMap();
HashMap mpData = new HashMap();
ArrayList<HashMap> miSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mfSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mrSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mcSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mtSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> meSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mhSubArr = new ArrayList<HashMap>();
HashMap smData = new HashMap();
HashMap rootData;
// Set exp root info
if (i < rootArr.size()) {
rootData = rootArr.get(i);
} else {
rootData = expData;
}
// Applied DOME Info
String trt_name = getValueOr(sqData, "trt_name", getValueOr(rootData, "trt_name", getValueOr(rootData, "exname", defValC)));
if (getValueOr(rootData, "dome_applied", "").equals("Y")) {
// If it comes with seasonal exname style
if (trt_name.matches(".+[^_]__\\d+$")) {
trt_name = trt_name.replaceAll("__\\d+$", "_*");
if (appliedDomes.get(trt_name + " Field ") == null) {
appliedDomes.put(trt_name + " Field ", getAppliedDomes(rootData, "field"));
}
if (appliedDomes.get(trt_name + " Seasonal ") == null) {
appliedDomes.put(trt_name + " Seasonal ", getAppliedDomes(rootData, "seasonal"));
}
} else {
appliedDomes.put(trt_name + " Field ", getAppliedDomes(rootData, "field"));
appliedDomes.put(trt_name + " Seasonal ", getAppliedDomes(rootData, "seasonal"));
}
isAnyDomeApplied = true;
} else {
appliedDomes.put(trt_name, "");
}
// Set field info
copyItem(flData, rootData, "id_field");
String dssat_wst_id = getValueOr(rootData, "dssat_wst_id", "");
// Weather data is missing plus dssat_wst_id is available
if (!dssat_wst_id.equals("") && wthData.isEmpty()) {
flData.put("wst_id", dssat_wst_id);
} else {
flData.put("wst_id", getWthFileName(rootData));
}
copyItem(flData, rootData, "flsl");
copyItem(flData, rootData, "flob");
copyItem(flData, rootData, "fl_drntype");
copyItem(flData, rootData, "fldrd");
copyItem(flData, rootData, "fldrs");
copyItem(flData, rootData, "flst");
if (soilData.get("sltx") != null) {
copyItem(flData, soilData, "sltx");
} else {
copyItem(flData, rootData, "sltx");
}
copyItem(flData, soilData, "sldp");
copyItem(flData, rootData, "soil_id");
copyItem(flData, rootData, "fl_name");
copyItem(flData, rootData, "fl_lat");
copyItem(flData, rootData, "fl_long");
copyItem(flData, rootData, "flele");
copyItem(flData, rootData, "farea");
copyItem(flData, rootData, "fllwr");
copyItem(flData, rootData, "flsla");
copyItem(flData, getObjectOr(rootData, "dssat_info", new HashMap()), "flhst");
copyItem(flData, getObjectOr(rootData, "dssat_info", new HashMap()), "fhdur");
// remove the "_trno" in the soil_id when soil analysis is available
String soilId = getValueOr(flData, "soil_id", "");
if (soilId.length() > 10 && soilId.matches("\\w+_\\d+") || soilId.length() < 8) {
flData.put("soil_id", getSoilID(flData));
}
flNum = setSecDataArr(flData, flArr);
// Set initial condition info
icNum = setSecDataArr(getObjectOr(rootData, "initial_conditions", new HashMap()), icArr);
// Set environment modification info
for (HashMap meOrgArr1 : meOrgArr) {
if (em.equals(meOrgArr1.get("em"))) {
HashMap tmp = new HashMap();
tmp.putAll(meOrgArr1);
tmp.remove("em");
meSubArr.add(tmp);
}
}
if (!adjArr.isEmpty()) {
ArrayList<HashMap<String, String>> startArr = new ArrayList();
ArrayList<HashMap<String, String>> endArr = new ArrayList();
String sdat = getValueOr(rootData, "sdat", "");
if (sdat.equals("")) {
sdat = getPdate(result);
}
final List<String> vars = Arrays.asList(new String[]{"tmax", "tmin", "srad", "wind", "rain", "co2y", "tdew"});
final List<String> emVars = Arrays.asList(new String[]{"emmax", "emmin", "emrad", "emwnd", "emrai", "emco2", "emdew"});
final List<String> emcVars = Arrays.asList(new String[]{"ecmax", "ecmin", "ecrad", "ecwnd", "ecrai", "ecco2", "ecdew"});
for (HashMap adjData : adjArr) {
if (getValueOr(adjData, "seqid", defValBlank).equals(seqId)) {
String var = getValueOr(adjData, "variable", "");
String ecVar;
String val = getValueOr(adjData, "value", "");
String method = getValueOr(adjData, "method", "");
String startDate = getValueOr(adjData, "startdate", sdat);
String endDate = getValueOr(adjData, "enddate", "");
int idx = vars.indexOf(var);
if (idx < 0) {
LOG.warn("Found unsupported adjusment variable [" + var + "], will be ignored.");
sbError.append("Found unsupported adjusment variable [").append(var).append("], will be ignored.");
continue;
} else {
var = emVars.get(idx);
ecVar = emcVars.get(idx);
}
if (method.equals("substitute")) {
method = "R";
} else if (method.equals("delta")) {
if (val.startsWith("-")) {
val = val.substring(1);
method = "S";
} else {
method = "A";
}
} else if (method.equals("multiply")) {
method = "M";
} else {
LOG.warn("Found unsupported adjusment method [" + method + "] for [" + var + "], will be ignored.");
sbError.append("Found unsupported adjusment method [").append(method).append("] for [").append(var).append("], will be ignored.");
continue;
}
HashMap tmp = DssatCommonInput.getSectionDataWithNocopy(startArr, "date", startDate);
if (tmp == null) {
tmp = new HashMap();
startArr.add(tmp);
}
tmp.put(var, val);
tmp.put(ecVar, method);
tmp.put("date", startDate);
if (!endDate.equals("")) {
tmp = DssatCommonInput.getSectionDataWithNocopy(endArr, "date", endDate);
if (tmp == null) {
tmp = new HashMap();
endArr.add(tmp);
}
tmp.put(var, "0");
tmp.put(ecVar, "A");
tmp.put("date", endDate);
}
}
}
meSubArr.addAll(startArr);
meSubArr.addAll(endArr);
}
// Set soil analysis info
// ArrayList<HashMap> icSubArr = getDataList(expData, "initial_condition", "soilLayer");
ArrayList<HashMap> soilLarys = getObjectOr(soilData, "soilLayer", new ArrayList());
// // If it is stored in the initial condition block
// if (isSoilAnalysisExist(icSubArr)) {
// HashMap saData = new HashMap();
// ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
// HashMap saSubData;
// for (int i = 0; i < icSubArr.size(); i++) {
// saSubData = new HashMap();
// copyItem(saSubData, icSubArr.get(i), "sabl", "icbl", false);
// copyItem(saSubData, icSubArr.get(i), "sasc", "slsc", false);
// saSubArr.add(saSubData);
// }
// copyItem(saData, soilData, "sadat");
// saData.put("soilLayer", saSubArr);
// saNum = setSecDataArr(saData, saArr);
// } else
// If it is stored in the soil block
if (isSoilAnalysisExist(soilLarys)) {
HashMap saData = new HashMap();
ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
HashMap saSubData;
for (HashMap soilLary : soilLarys) {
saSubData = new HashMap();
copyItem(saSubData, soilLary, "sabl", "sllb", false);
copyItem(saSubData, soilLary, "saoc", "sloc", false);
copyItem(saSubData, soilLary, "sasc", "slsc", false);
saSubArr.add(saSubData);
}
copyItem(saData, soilData, "sadat");
saData.put("soilLayer", saSubArr);
saNum = setSecDataArr(saData, saArr, true);
} else {
saNum = 0;
}
// Set simulation control info
for (HashMap smOrgArr1 : smOrgArr) {
if (sm.equals(smOrgArr1.get("sm"))) {
smData.putAll(smOrgArr1);
smData.remove("sm");
break;
}
}
// if (smData.isEmpty()) {
// smData.put("fertilizer", mfSubArr);
// smData.put("irrigation", miSubArr);
// smData.put("planting", mpData);
// }
copyItem(smData, rootData, "sdat");
copyItem(smData, rootData, "dssat_model");
copyItem(smData, getObjectOr(wthData, "weather", new HashMap()), "co2y");
// Loop all event data
for (HashMap evtArr1 : evtArr) {
evtData = new HashMap();
evtData.putAll(evtArr1);
// Check if it has same sequence number
if (getValueOr(evtData, "seqid", defValBlank).equals(seqId)) {
evtData.remove("seqid");
// Planting event
if (getValueOr(evtData, "event", defValBlank).equals("planting")) {
// Set cultivals info
copyItem(cuData, evtData, "cul_name");
copyItem(cuData, evtData, "crid");
copyItem(cuData, evtData, "cul_id");
copyItem(cuData, evtData, "dssat_cul_id");
copyItem(cuData, evtData, "rm");
copyItem(cuData, evtData, "cul_notes");
translateTo2BitCrid(cuData);
// Set planting info
// To make comparision only on the planting information (without crop data), use HashMap to rebuild pure planting map
copyItem(mpData, evtData, "date");
copyItem(mpData, evtData, "edate");
copyItem(mpData, evtData, "plpop");
copyItem(mpData, evtData, "plpoe");
copyItem(mpData, evtData, "plma");
copyItem(mpData, evtData, "plds");
copyItem(mpData, evtData, "plrs");
copyItem(mpData, evtData, "plrd");
copyItem(mpData, evtData, "pldp");
copyItem(mpData, evtData, "plmwt");
copyItem(mpData, evtData, "page");
copyItem(mpData, evtData, "plenv");
copyItem(mpData, evtData, "plph");
copyItem(mpData, evtData, "plspl");
copyItem(mpData, evtData, "pl_name");
} // irrigation event
else if (getValueOr(evtData, "event", "").equals("irrigation")) {
miSubArr.add(evtData);
} // fertilizer event
else if (getValueOr(evtData, "event", "").equals("fertilizer")) {
mfSubArr.add(evtData);
} // organic_matter event
else if (getValueOr(evtData, "event", "").equals("organic_matter")) { // P.S. change event name to organic-materials; Back to organic_matter again.
mrSubArr.add(evtData);
} // chemical event
else if (getValueOr(evtData, "event", "").equals("chemical")) {
mcSubArr.add(evtData);
} // tillage event
else if (getValueOr(evtData, "event", "").equals("tillage")) {
mtSubArr.add(evtData);
// } // environment_modification event
// else if (getValueOr(evtData, "event", "").equals("environment_modification")) {
// meSubArr.add(evtData);
} // harvest event
else if (getValueOr(evtData, "event", "").equals("harvest")) {
mhSubArr.add(evtData);
if (!getValueOr(evtData, "date", "").trim().equals("")) {
smData.put("hadat_valid", "Y");
}
// copyItem(smData, evtData, "hadat", "date", false);
} else {
}
} else {
}
}
// Cancel for assume default value handling
// // If alternative fields are avaiable for fertilizer data
// if (mfSubArr.isEmpty()) {
// if (!getObjectOr(result, "fen_tot", "").equals("")
// || !getObjectOr(result, "fep_tot", "").equals("")
// || !getObjectOr(result, "fek_tot", "").equals("")) {
// mfSubArr.add(new HashMap());
// }
// }
// Specila handling for fallow experiment
if (mpData.isEmpty()) {
isFallow = true;
cuData.put("crid", "FA");
cuData.put("dssat_cul_id", "IB0001");
cuData.put("cul_name", "Fallow");
if (mhSubArr.isEmpty()) {
HashMap mhData = new HashMap();
copyItem(mhData, rootData, "date", "endat", false);
// mhData.put("hastg", "GS000");
mhSubArr.add(mhData);
smData.put("hadat_valid", "Y");
}
}
cuNum = setSecDataArr(cuData, cuArr);
mpNum = setSecDataArr(mpData, mpArr, true);
miNum = setSecDataArr(miSubArr, miArr, true);
mfNum = setSecDataArr(mfSubArr, mfArr, true);
mrNum = setSecDataArr(mrSubArr, mrArr, true);
mcNum = setSecDataArr(mcSubArr, mcArr, true);
mtNum = setSecDataArr(mtSubArr, mtArr, true);
meNum = setSecDataArr(meSubArr, meArr); // Since old format of EM might exist, skip the check for EM
mhNum = setSecDataArr(mhSubArr, mhArr, true);
smNum = setSecDataArr(smData, smArr);
if (smNum == 0) {
smNum = 1;
}
StringBuilder sbBadEventRrrMsg = new StringBuilder();
boolean badEventFlg = false;
if (saNum < 0) {
saNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("SA ");
}
if (icNum < 0) {
icNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("IC ");
}
if (mpNum < 0) {
mpNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("MP ");
}
if (miNum < 0) {
miNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("MI ");
}
if (mfNum < 0) {
mfNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("MF ");
}
if (mrNum < 0) {
mrNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("MR ");
}
if (mcNum < 0) {
mcNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("MC ");
}
if (mtNum < 0) {
mtNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("MT ");
}
if (meNum < 0) {
meNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("ME ");
}
if (mhNum < 0) {
mhNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("MH ");
}
if (badEventFlg) {
String tmp = sbBadEventRrrMsg.toString();
sbBadEventRrrMsg = new StringBuilder();
sbBadEventRrrMsg.append(" ! Bad Event detected for ").append(tmp);
}
sbData.append(String.format("%1$-3s%2$1s %3$1s %4$1s %5$-25s %6$2s %7$2s %8$2s %9$2s %10$2s %11$2s %12$2s %13$2s %14$2s %15$2s %16$2s %17$2s %18$2s%19$s\r\n",
String.format("%2s", getValueOr(sqData, "trno", "1")), // For 3-bit treatment number
getValueOr(sqData, "sq", "1"), // P.S. default value here is based on document DSSAT vol2.pdf
getValueOr(sqData, "op", "1"),
getValueOr(sqData, "co", "0"),
formatStr(25, sqData, "trt_name", getValueOr(rootData, "trt_name", getValueOr(rootData, "exname", defValC))),
cuNum, //getObjectOr(data, "ge", defValI).toString(),
flNum, //getObjectOr(data, "fl", defValI).toString(),
saNum, //getObjectOr(data, "sa", defValI).toString(),
icNum, //getObjectOr(data, "ic", defValI).toString(),
mpNum, //getObjectOr(data, "pl", defValI).toString(),
miNum, //getObjectOr(data, "ir", defValI).toString(),
mfNum, //getObjectOr(data, "fe", defValI).toString(),
mrNum, //getObjectOr(data, "om", defValI).toString(),
mcNum, //getObjectOr(data, "ch", defValI).toString(),
mtNum, //getObjectOr(data, "ti", defValI).toString(),
meNum, //getObjectOr(data, "em", defValI).toString(),
mhNum, //getObjectOr(data, "ha", defValI).toString(),
smNum, // 1
sbBadEventRrrMsg.toString()));
}
sbData.append("\r\n");
// CULTIVARS Section
if (!cuArr.isEmpty()) {
sbData.append("*CULTIVARS\r\n");
sbData.append("@C CR INGENO CNAME\r\n");
for (int idx = 0; idx < cuArr.size(); idx++) {
HashMap secData = cuArr.get(idx);
// String cul_id = defValC;
String crid = getValueOr(secData, "crid", "");
// Checl if necessary data is missing
if (crid.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [crid]\r\n");
// } else {
// // Set cultivar id a default value deponds on the crop id
// if (crid.equals("MZ")) {
// cul_id = "990002";
// } else {
// cul_id = "999999";
// }
// }
// if (getObjectOr(secData, "cul_id", "").equals("")) {
// sbError.append("! Warning: Incompleted record because missing data : [cul_id], and will use default value '").append(cul_id).append("'\r\n");
}
sbData.append(String.format("%1$2s %2$-2s %3$-6s %4$s\r\n",
idx + 1,
formatStr(2, secData, "crid", defValBlank), // P.S. if missing, default value use blank string
formatStr(6, secData, "dssat_cul_id", getValueOr(secData, "cul_id", defValC)), // P.S. Set default value which is deponds on crid(Cancelled)
getValueOr(secData, "cul_name", defValC)));
if (!getValueOr(secData, "rm", "").equals("") || !getValueOr(secData, "cul_notes", "").equals("")) {
if (sbNotesData.toString().equals("")) {
sbNotesData.append("@NOTES\r\n");
}
sbNotesData.append(" Cultivar Additional Info\r\n");
sbNotesData.append(" C RM CNAME CUL_NOTES\r\n");
sbNotesData.append(String.format("%1$2s %2$4s %3$s\r\n",
idx + 1,
getValueOr(secData, "rm", defValC),
getValueOr(secData, "cul_notes", defValC)));
}
}
sbData.append("\r\n");
} else if (!isFallow) {
sbError.append("! Warning: There is no cultivar data in the experiment.\r\n");
}
// FIELDS Section
if (!flArr.isEmpty()) {
sbData.append("*FIELDS\r\n");
sbData.append("@L ID_FIELD WSTA.... FLSA FLOB FLDT FLDD FLDS FLST SLTX SLDP ID_SOIL FLNAME\r\n");
eventPart2 = new StringBuilder();
eventPart2.append("@L ...........XCRD ...........YCRD .....ELEV .............AREA .SLEN .FLWR .SLAS FLHST FHDUR\r\n");
} else {
sbError.append("! Warning: There is no field data in the experiment.\r\n");
}
for (int idx = 0; idx < flArr.size(); idx++) {
HashMap secData = flArr.get(idx);
// Check if the necessary is missing
if (getObjectOr(secData, "wst_id", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [wst_id]\r\n");
}
String soil_id = getValueOr(secData, "soil_id", defValC);
if (soil_id.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [soil_id]\r\n");
} else if (soil_id.length() > 10) {
sbError.append("! Warning: Oversized data : [soil_id] ").append(soil_id).append("\r\n");
}
sbData.append(String.format("%1$2s %2$-8s %3$-8s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$-5s %10$-5s%11$5s %12$-10s %13$s\r\n", // P.S. change length definition to match current way
idx + 1,
formatStr(8, secData, "id_field", defValC),
formatStr(8, secData, "wst_id", defValC),
formatStr(4, secData, "flsl", defValC),
formatNumStr(5, secData, "flob", defValR),
formatStr(5, secData, "fl_drntype", defValC),
formatNumStr(5, secData, "fldrd", defValR),
formatNumStr(5, secData, "fldrs", defValR),
formatStr(5, secData, "flst", defValC),
formatStr(5, transSltx(getValueOr(secData, "sltx", defValC)), "sltx"),
formatNumStr(5, secData, "sldp", defValR),
soil_id,
getValueOr(secData, "fl_name", defValC)));
eventPart2.append(String.format("%1$2s %2$15s %3$15s %4$9s %5$17s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1,
formatNumStr(15, secData, "fl_long", defValR),
formatNumStr(15, secData, "fl_lat", defValR),
formatNumStr(9, secData, "flele", defValR),
formatNumStr(17, secData, "farea", defValR),
"-99", // P.S. SLEN keeps -99
formatNumStr(5, secData, "fllwr", defValR),
formatNumStr(5, secData, "flsla", defValR),
formatStr(5, secData, "flhst", defValC),
formatNumStr(5, secData, "fhdur", defValR)));
}
if (!flArr.isEmpty()) {
sbData.append(eventPart2.toString()).append("\r\n");
}
// SOIL ANALYSIS Section
if (!saArr.isEmpty()) {
sbData.append("*SOIL ANALYSIS\r\n");
for (int idx = 0; idx < saArr.size(); idx++) {
HashMap secData = (HashMap) saArr.get(idx);
String brokenMark = "";
if (getValueOr(secData, "sadat", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append("@A SADAT SMHB SMPX SMKE SANAME\r\n");
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "sadat", defValD)),
getValueOr(secData, "samhb", defValC),
getValueOr(secData, "sampx", defValC),
getValueOr(secData, "samke", defValC),
getValueOr(secData, "sa_name", defValC)));
ArrayList<HashMap> subDataArr = getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append(brokenMark).append("@A SABL SADM SAOC SANI SAPHW SAPHB SAPX SAKE SASC\r\n");
}
for (HashMap subData : subDataArr) {
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1,
formatNumStr(5, subData, "sabl", defValR),
formatNumStr(5, subData, "sabdm", defValR),
formatNumStr(5, subData, "saoc", defValR),
formatNumStr(5, subData, "sani", defValR),
formatNumStr(5, subData, "saphw", defValR),
formatNumStr(5, subData, "saphb", defValR),
formatNumStr(5, subData, "sapx", defValR),
formatNumStr(5, subData, "sake", defValR),
formatNumStr(5, subData, "sasc", defValR)));
}
}
sbData.append("\r\n");
}
// INITIAL CONDITIONS Section
if (!icArr.isEmpty()) {
sbData.append("*INITIAL CONDITIONS\r\n");
for (int idx = 0; idx < icArr.size(); idx++) {
HashMap secData = icArr.get(idx);
String brokenMark = "";
if (getValueOr(secData, "icdat", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append("@C PCR ICDAT ICRT ICND ICRN ICRE ICWD ICRES ICREN ICREP ICRIP ICRID ICNAME\r\n");
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$s\r\n",
idx + 1,
translateTo2BitCrid(secData, "icpcr", defValC),
formatDateStr(getValueOr(secData, "icdat", getPdate(result))),
formatNumStr(5, secData, "icrt", defValR),
formatNumStr(5, secData, "icnd", defValR),
formatNumStr(5, secData, "icrz#", defValR),
formatNumStr(5, secData, "icrze", defValR),
formatNumStr(5, secData, "icwt", defValR),
formatNumStr(5, secData, "icrag", defValR),
formatNumStr(5, secData, "icrn", defValR),
formatNumStr(5, secData, "icrp", defValR),
formatNumStr(5, secData, "icrip", defValR),
formatNumStr(5, secData, "icrdp", defValR),
getValueOr(secData, "ic_name", defValC)));
ArrayList<HashMap> subDataArr = getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append(brokenMark).append("@C ICBL SH2O SNH4 SNO3\r\n");
}
for (HashMap subData : subDataArr) {
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s\r\n",
idx + 1,
formatNumStr(5, subData, "icbl", defValR),
formatNumStr(5, subData, "ich2o", defValR),
formatNumStr(5, subData, "icnh4", defValR),
formatNumStr(5, subData, "icno3", defValR)));
}
}
sbData.append("\r\n");
}
// PLANTING DETAILS Section
if (!mpArr.isEmpty()) {
sbData.append("*PLANTING DETAILS\r\n");
sbData.append("@P PDATE EDATE PPOP PPOE PLME PLDS PLRS PLRD PLDP PLWT PAGE PENV PLPH SPRL PLNAME\r\n");
for (int idx = 0; idx < mpArr.size(); idx++) {
HashMap secData = mpArr.get(idx);
// Check if necessary data is missing
String pdate = getValueOr(secData, "date", "");
if (pdate.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [pdate]\r\n");
} else if (formatDateStr(pdate).equals(defValD)) {
sbError.append("! Warning: Incompleted record because variable [pdate] with invalid value [").append(pdate).append("]\r\n");
}
if (getValueOr(secData, "plpop", getValueOr(secData, "plpoe", "")).equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plpop] and [plpoe]\r\n");
}
if (getValueOr(secData, "plrs", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plrs]\r\n");
}
// if (getValueOr(secData, "plma", "").equals("")) {
// sbError.append("! Warning: missing data : [plma], and will automatically use default value 'S'\r\n");
// }
// if (getValueOr(secData, "plds", "").equals("")) {
// sbError.append("! Warning: missing data : [plds], and will automatically use default value 'R'\r\n");
// }
// if (getValueOr(secData, "pldp", "").equals("")) {
// sbError.append("! Warning: missing data : [pldp], and will automatically use default value '7'\r\n");
// }
// mm -> cm
String pldp = getValueOr(secData, "pldp", "");
if (!pldp.equals("")) {
try {
BigDecimal pldpBD = new BigDecimal(pldp);
pldpBD = pldpBD.divide(new BigDecimal("10"));
secData.put("pldp", pldpBD.toString());
} catch (NumberFormatException e) {
}
}
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "date", defValD)),
formatDateStr(getValueOr(secData, "edate", defValD)),
formatNumStr(5, secData, "plpop", getValueOr(secData, "plpoe", defValR)),
formatNumStr(5, secData, "plpoe", getValueOr(secData, "plpop", defValR)),
getValueOr(secData, "plma", defValC), // P.S. Set default value as "S"(Cancelled)
getValueOr(secData, "plds", defValC), // P.S. Set default value as "R"(Cancelled)
formatNumStr(5, secData, "plrs", defValR),
formatNumStr(5, secData, "plrd", defValR),
formatNumStr(5, secData, "pldp", defValR), // P.S. Set default value as "7"(Cancelled)
formatNumStr(5, secData, "plmwt", defValR),
formatNumStr(5, secData, "page", defValR),
formatNumStr(5, secData, "plenv", defValR),
formatNumStr(5, secData, "plph", defValR),
formatNumStr(5, secData, "plspl", defValR),
getValueOr(secData, "pl_name", defValC)));
}
sbData.append("\r\n");
} else if (!isFallow) {
sbError.append("! Warning: There is no plainting data in the experiment.\r\n");
}
// IRRIGATION AND WATER MANAGEMENT Section
if (!miArr.isEmpty()) {
sbData.append("*IRRIGATION AND WATER MANAGEMENT\r\n");
for (int idx = 0; idx < miArr.size(); idx++) {
// secData = (ArrayList) miArr.get(idx);
ArrayList<HashMap> subDataArr = miArr.get(idx);
HashMap subData;
if (!subDataArr.isEmpty()) {
subData = subDataArr.get(0);
} else {
subData = new HashMap();
}
sbData.append("@I EFIR IDEP ITHR IEPT IOFF IAME IAMT IRNAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$s\r\n",
idx + 1,
formatNumStr(5, subData, "ireff", defValR),
formatNumStr(5, subData, "irmdp", defValR),
formatNumStr(5, subData, "irthr", defValR),
formatNumStr(5, subData, "irept", defValR),
getValueOr(subData, "irstg", defValC),
getValueOr(subData, "iame", defValC),
formatNumStr(5, subData, "iamt", defValR),
getValueOr(subData, "ir_name", defValC)));
if (!subDataArr.isEmpty()) {
sbData.append("@I IDATE IROP IRVAL\r\n");
}
for (HashMap subDataArr1 : subDataArr) {
subData = subDataArr1;
String brokenMark = "";
if (getValueOr(subData, "date", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$-5s %4$5s\r\n",
idx + 1,
formatDateStr(getValueOr(subData, "date", defValD)), // P.S. idate -> date
getValueOr(subData, "irop", defValC),
formatNumStr(5, subData, "irval", defValR)));
}
}
sbData.append("\r\n");
}
// FERTILIZERS (INORGANIC) Section
if (!mfArr.isEmpty()) {
sbData.append("*FERTILIZERS (INORGANIC)\r\n");
sbData.append("@F FDATE FMCD FACD FDEP FAMN FAMP FAMK FAMC FAMO FOCD FERNAME\r\n");
// String fen_tot = getValueOr(result, "fen_tot", defValR);
// String fep_tot = getValueOr(result, "fep_tot", defValR);
// String fek_tot = getValueOr(result, "fek_tot", defValR);
// String pdate = getPdate(result);
// if (pdate.equals("")) {
// pdate = defValD;
// }
for (int idx = 0; idx < mfArr.size(); idx++) {
ArrayList<HashMap> secDataArr = mfArr.get(idx);
for (HashMap secData : secDataArr) {
// if (getValueOr(secData, "fdate", "").equals("")) {
// sbError.append("! Warning: missing data : [fdate], and will automatically use planting value '").append(pdate).append("'\r\n");
// }
// if (getValueOr(secData, "fecd", "").equals("")) {
// sbError.append("! Warning: missing data : [fecd], and will automatically use default value 'FE001'\r\n");
// }
// if (getValueOr(secData, "feacd", "").equals("")) {
// sbError.append("! Warning: missing data : [feacd], and will automatically use default value 'AP002'\r\n");
// }
// if (getValueOr(secData, "fedep", "").equals("")) {
// sbError.append("! Warning: missing data : [fedep], and will automatically use default value '10'\r\n");
// }
// if (getValueOr(secData, "feamn", "").equals("")) {
// sbError.append("! Warning: missing data : [feamn], and will automatically use the value of FEN_TOT, '").append(fen_tot).append("'\r\n");
// }
// if (getValueOr(secData, "feamp", "").equals("")) {
// sbError.append("! Warning: missing data : [feamp], and will automatically use the value of FEP_TOT, '").append(fep_tot).append("'\r\n");
// }
// if (getValueOr(secData, "feamk", "").equals("")) {
// sbError.append("! Warning: missing data : [feamk], and will automatically use the value of FEK_TOT, '").append(fek_tot).append("'\r\n");
// }
String brokenMark = "";
if (getValueOr(secData, "date", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "date", defValD)), // P.S. fdate -> date
getValueOr(secData, "fecd", defValC), // P.S. Set default value as "FE005"(Cancelled)
getValueOr(secData, "feacd", defValC), // P.S. Set default value as "AP002"(Cancelled)
formatNumStr(5, secData, "fedep", defValR), // P.S. Set default value as "10"(Cancelled)
formatNumStr(5, secData, "feamn", "0"), // P.S. Set default value to use 0 instead of -99
formatNumStr(5, secData, "feamp", defValR), // P.S. Set default value to use the value of FEP_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamk", defValR), // P.S. Set default value to use the value of FEK_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamc", defValR),
formatNumStr(5, secData, "feamo", defValR),
getValueOr(secData, "feocd", defValC),
getValueOr(secData, "fe_name", defValC)));
}
}
sbData.append("\r\n");
}
// RESIDUES AND ORGANIC FERTILIZER Section
if (!mrArr.isEmpty()) {
sbData.append("*RESIDUES AND ORGANIC FERTILIZER\r\n");
sbData.append("@R RDATE RCOD RAMT RESN RESP RESK RINP RDEP RMET RENAME\r\n");
for (int idx = 0; idx < mrArr.size(); idx++) {
ArrayList<HashMap> secDataArr = mrArr.get(idx);
for (HashMap secData : secDataArr) {
String brokenMark = "";
if (getValueOr(secData, "date", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$-5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "date", defValD)), // P.S. omdat -> date
getValueOr(secData, "omcd", defValC),
formatNumStr(5, secData, "omamt", defValR),
formatNumStr(5, secData, "omn%", defValR),
formatNumStr(5, secData, "omp%", defValR),
formatNumStr(5, secData, "omk%", defValR),
formatNumStr(5, secData, "ominp", defValR),
formatNumStr(5, secData, "omdep", defValR),
formatNumStr(5, secData, "omacd", defValR),
getValueOr(secData, "om_name", defValC)));
}
}
sbData.append("\r\n");
}
// CHEMICAL APPLICATIONS Section
if (!mcArr.isEmpty()) {
sbData.append("*CHEMICAL APPLICATIONS\r\n");
sbData.append("@C CDATE CHCOD CHAMT CHME CHDEP CHT..CHNAME\r\n");
for (int idx = 0; idx < mcArr.size(); idx++) {
ArrayList<HashMap> secDataArr = mcArr.get(idx);
for (HashMap secData : secDataArr) {
String brokenMark = "";
if (getValueOr(secData, "date", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "date", defValD)), // P.S. cdate -> date
getValueOr(secData, "chcd", defValC),
formatNumStr(5, secData, "chamt", defValR),
getValueOr(secData, "chacd", defValC),
getValueOr(secData, "chdep", defValC),
getValueOr(secData, "ch_targets", defValC),
getValueOr(secData, "ch_name", defValC)));
}
}
sbData.append("\r\n");
}
// TILLAGE Section
if (!mtArr.isEmpty()) {
sbData.append("*TILLAGE AND ROTATIONS\r\n");
sbData.append("@T TDATE TIMPL TDEP TNAME\r\n");
for (int idx = 0; idx < mtArr.size(); idx++) {
ArrayList<HashMap> secDataArr = mtArr.get(idx);
for (HashMap secData : secDataArr) {
String brokenMark = "";
if (getValueOr(secData, "date", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$5s %4$5s %5$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "date", defValD)), // P.S. tdate -> date
getValueOr(secData, "tiimp", defValC),
formatNumStr(5, secData, "tidep", defValR),
getValueOr(secData, "ti_name", defValC)));
}
}
sbData.append("\r\n");
}
// ENVIRONMENT MODIFICATIONS Section
if (!meArr.isEmpty()) {
sbData.append("*ENVIRONMENT MODIFICATIONS\r\n");
sbData.append("@E ODATE EDAY ERAD EMAX EMIN ERAIN ECO2 EDEW EWIND ENVNAME\r\n");
for (int idx = 0, cnt = 1; idx < meArr.size(); idx++) {
ArrayList<HashMap> secDataArr = meArr.get(idx);
for (HashMap secData : secDataArr) {
if (secData.containsKey("em_data")) {
sbData.append(String.format("%1$2s %2$s\r\n",
cnt,
getValueOr(secData, "em_data", "").trim()));
} else {
String brokenMark = "";
if (getValueOr(secData, "date", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$-1s%4$4s %5$-1s%6$4s %7$-1s%8$4s %9$-1s%10$4s %11$-1s%12$4s %13$-1s%14$4s %15$-1s%16$4s %17$-1s%18$4s %19$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "date", defValD)), // P.S. emday -> date
getValueOr(secData, "ecdyl", "A"),
formatNumStr(4, secData, "emdyl", "0"),
getValueOr(secData, "ecrad", "A"),
formatNumStr(4, secData, "emrad", "0"),
getValueOr(secData, "ecmax", "A"),
formatNumStr(4, secData, "emmax", "0"),
getValueOr(secData, "ecmin", "A"),
formatNumStr(4, secData, "emmin", "0"),
getValueOr(secData, "ecrai", "A"),
formatNumStr(4, secData, "emrai", "0"),
getValueOr(secData, "ecco2", "A"),
formatNumStr(4, secData, "emco2", "0"),
getValueOr(secData, "ecdew", "A"),
formatNumStr(4, secData, "emdew", "0"),
getValueOr(secData, "ecwnd", "A"),
formatNumStr(4, secData, "emwnd", "0"),
getValueOr(secData, "em_name", defValC)));
}
}
}
sbData.append("\r\n");
}
// HARVEST DETAILS Section
if (!mhArr.isEmpty()) {
sbData.append("*HARVEST DETAILS\r\n");
sbData.append("@H HDATE HSTG HCOM HSIZE HPC HBPC HNAME\r\n");
for (int idx = 0; idx < mhArr.size(); idx++) {
ArrayList<HashMap> secDataArr = mhArr.get(idx);
for (HashMap secData : secDataArr) {
String brokenMark = "";
if (getValueOr(secData, "date", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$-5s %4$-5s %5$-5s %6$5s %7$5s %8$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "date", defValD)), // P.S. hdate -> date
getValueOr(secData, "hastg", defValC),
getValueOr(secData, "hacom", defValC),
getValueOr(secData, "hasiz", defValC),
formatNumStr(5, secData, "hap%", defValR),
formatNumStr(5, secData, "hab%", defValR),
getValueOr(secData, "ha_name", defValC)));
}
}
sbData.append("\r\n");
}
// SIMULATION CONTROLS and AUTOMATIC MANAGEMENT Section
if (!smArr.isEmpty()) {
// Loop all the simulation control records
sbData.append("*SIMULATION CONTROLS\r\n");
for (int idx = 0; idx < smArr.size(); idx++) {
HashMap secData = smArr.get(idx);
sbData.append(createSMMAStr(idx + 1, secData));
}
} else {
sbData.append("*SIMULATION CONTROLS\r\n");
sbData.append(createSMMAStr(1, new HashMap()));
}
// DOME Info Section
if (isAnyDomeApplied) {
sbDomeData.append("! APPLIED DOME INFO\r\n");
for (String exname : appliedDomes.keySet()) {
if (!getValueOr(appliedDomes, exname, "").equals("")) {
sbDomeData.append("! ").append(exname).append("\t");
sbDomeData.append(appliedDomes.get(exname));
sbDomeData.append("\r\n");
}
}
sbDomeData.append("\r\n");
}
// Output finish
bwX.write(sbError.toString());
bwX.write(sbDomeData.toString());
bwX.write(sbGenData.toString());
bwX.write(sbNotesData.toString());
bwX.write(sbData.toString());
bwX.close();
} catch (IOException e) {
LOG.error(DssatCommonOutput.getStackTrace(e));
}
}
/**
* Create string of Simulation Control and Automatic Management Section
*
* @param smid simulation index number
* @param trData date holder for one treatment data
* @return date string with format of "yyddd"
*/
private String createSMMAStr(int smid, HashMap trData) {
StringBuilder sb = new StringBuilder();
String nitro = "Y";
String water = "Y";
String co2 = "M";
String harOpt = "M";
String sdate;
String sm = String.format("%2d", smid);
// ArrayList<HashMap> dataArr;
HashMap subData;
// // Check if the meta data of fertilizer is not "N" ("Y" or null)
// if (!getValueOr(expData, "fertilizer", "").equals("N")) {
//
// // Check if necessary data is missing in all the event records
// // P.S. rule changed since all the necessary data has a default value for it
// dataArr = getObjectOr(trData, "fertilizer", new ArrayList());
// if (dataArr.isEmpty()) {
// nitro = "N";
// }
//// for (int i = 0; i < dataArr.size(); i++) {
//// subData = dataArr.get(i);
//// if (getValueOr(subData, "date", "").equals("")
//// || getValueOr(subData, "fecd", "").equals("")
//// || getValueOr(subData, "feacd", "").equals("")
//// || getValueOr(subData, "feamn", "").equals("")) {
//// nitro = "N";
//// break;
//// }
//// }
// }
// // Check if the meta data of irrigation is not "N" ("Y" or null)
// if (!getValueOr(expData, "irrigation", "").equals("N")) {
//
// // Check if necessary data is missing in all the event records
// dataArr = getObjectOr(trData, "irrigation", new ArrayList());
// for (int i = 0; i < dataArr.size(); i++) {
// subData = dataArr.get(i);
// if (getValueOr(subData, "date", "").equals("")
// || getValueOr(subData, "irval", "").equals("")) {
// water = "N";
// break;
// }
// }
// }
// Check if CO2Y value is provided and the value is positive, then set CO2 switch to W
String co2y = getValueOr(trData, "co2y", "").trim();
if (!co2y.equals("") && !co2y.startsWith("-")) {
co2 = "W";
}
sdate = getValueOr(trData, "sdat", "");
if (sdate.equals("")) {
subData = getObjectOr(trData, "planting", new HashMap());
sdate = getValueOr(subData, "date", defValD);
}
sdate = formatDateStr(sdate);
sdate = String.format("%5s", sdate);
if (!getValueOr(trData, "hadat_valid", "").trim().equals("")) {
harOpt = "R";
}
String smStr;
HashMap smData;
// GENERAL
sb.append("@N GENERAL NYERS NREPS START SDATE RSEED SNAME.................... SMODEL\r\n");
if (!(smStr = getValueOr(trData, "sm_general", "")).equals("")) {
if (!sdate.trim().equals("-99") && !sdate.trim().equals("")) {
smStr = replaceSMStr(smStr, sdate, 30);
}
smStr = replaceSMStr(smStr, getValueOr(trData, "dssat_model", ""), 68);
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "general", new HashMap())).isEmpty()) {
if (sdate.trim().equals("-99") || sdate.trim().equals("")) {
sdate = String.format("%1$02d%2$03d", Integer.parseInt(formatNumStr(2, smData, "sdyer", "0").trim()), Integer.parseInt(formatNumStr(3, smData, "sdday", "0").trim()));
}
sb.append(String.format("%1$2s %2$-11s %3$5s %4$5s %5$-1s %6$5s %7$5s %8$-25s %9$s\r\n",
sm,
"GE",
getValueOr(smData, "nyers", "1"),
getValueOr(smData, "nreps", "1"),
getValueOr(smData, "start", "S"),
sdate,
getValueOr(smData, "rseed", "250"),
getValueOr(smData, "sname", defValC),
getValueOr(trData, "dssat_model", getValueOr(smData, "model", ""))));
} else {
sb.append(sm).append(" GE 1 1 S ").append(sdate).append(" 2150 DEFAULT SIMULATION CONTRL ").append(getValueOr(trData, "dssat_model", "")).append("\r\n");
}
// OPTIONS
sb.append("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n");
if (!(smStr = getValueOr(trData, "sm_options", "")).equals("")) {
// smStr = replaceSMStr(smStr, co2, 64);
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "options", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$-1s %4$-1s %5$-1s %6$-1s %7$-1s %8$-1s %9$-1s %10$-1s %11$-1s\r\n",
sm,
"OP",
getValueOr(smData, "water", water),
getValueOr(smData, "nitro", nitro),
getValueOr(smData, "symbi", "Y"),
getValueOr(smData, "phosp", "N"),
getValueOr(smData, "potas", "N"),
getValueOr(smData, "dises", "N"),
getValueOr(smData, "chem", "N"),
getValueOr(smData, "till", "Y"),
getValueOr(smData, "co2", co2)));
} else {
sb.append(sm).append(" OP ").append(water).append(" ").append(nitro).append(" Y N N N N Y ").append(co2).append("\r\n");
}
// METHODS
sb.append("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n");
if (!(smStr = getValueOr(trData, "sm_methods", "")).equals("")) {
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "methods", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$-1s %4$-1s %5$-1s %6$-1s %7$-1s %8$-1s %9$-1s %10$-1s %11$-1s %12$-1s %13$-1s\r\n",
sm,
"ME",
getValueOr(smData, "wther", "M"),
getValueOr(smData, "incon", "M"),
getValueOr(smData, "light", "E"),
getValueOr(smData, "evapo", "R"),
getValueOr(smData, "infil", "S"),
getValueOr(smData, "photo", "L"),
getValueOr(smData, "hydro", "R"),
getValueOr(smData, "nswit", "1"),
getValueOr(smData, "mesom", "P"),
getValueOr(smData, "mesev", "S"),
getValueOr(smData, "mesol", "2")));
} else {
sb.append(sm).append(" ME M M E R S L R 1 P S 2\r\n"); // P.S. 2012/09/02 MESOM "G" -> "P"
}
// MANAGEMENT
sb.append("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n");
if (!(smStr = getValueOr(trData, "sm_management", "")).equals("")) {
// smStr = smStr.replaceAll(" D", " R");
// smStr = replaceSMStr(smStr, harOpt, 40);
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "management", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$-1s %4$-1s %5$-1s %6$-1s %7$-1s\r\n",
sm,
"MA",
getValueOr(smData, "plant", "R"),
getValueOr(smData, "irrig", "R"),
getValueOr(smData, "ferti", "R"),
getValueOr(smData, "resid", "R"),
getValueOr(smData, "harvs", harOpt)));
} else {
sb.append(sm).append(" MA R R R R ").append(harOpt).append("\r\n");
}
// OUTPUTS
sb.append("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n");
if (!(smStr = getValueOr(trData, "sm_outputs", "")).equals("")) {
sb.append(sm).append(" ").append(smStr).append("\r\n\r\n");
} else if (!(smData = getObjectOr(trData, "outputs", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$-1s %4$-1s %5$-1s %6$5s %7$-1s %8$-1s %9$-1s %10$-1s %11$-1s %12$-1s %13$-1s %14$-1s %15$-1s\r\n\r\n",
sm,
"OU",
getValueOr(smData, "fname", "N"),
getValueOr(smData, "ovvew", "Y"),
getValueOr(smData, "sumry", "Y"),
getValueOr(smData, "fropt", "1"),
getValueOr(smData, "grout", "Y"),
getValueOr(smData, "caout", "Y"),
getValueOr(smData, "waout", "N"),
getValueOr(smData, "niout", "N"),
getValueOr(smData, "miout", "N"),
getValueOr(smData, "diout", "N"),
getValueOr(smData, "vbose", "0"),
getValueOr(smData, "chout", "N"),
getValueOr(smData, "opout", "N")));
} else {
sb.append(sm).append(" OU N Y Y 1 Y Y N N N N 0 N N\r\n\r\n");
}
// PLANTING
sb.append("@ AUTOMATIC MANAGEMENT\r\n");
sb.append("@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n");
if (!(smStr = getValueOr(trData, "sm_planting", "")).equals("")) {
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "planting", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$02d%4$03d %5$02d%6$03d %7$5s %8$5s %9$5s %10$5s %11$5s\r\n",
sm,
"PL",
Integer.parseInt(formatNumStr(2, smData, "pfyer", "82")),
Integer.parseInt(formatNumStr(3, smData, "pfday", "050")),
Integer.parseInt(formatNumStr(2, smData, "plyer", "82")),
Integer.parseInt(formatNumStr(3, smData, "plday", "064")),
getValueOr(smData, "ph2ol", "40"),
getValueOr(smData, "ph2ou", "100"),
getValueOr(smData, "ph2od", "30"),
getValueOr(smData, "pstmx", "40"),
getValueOr(smData, "pstmn", "10")));
} else {
sb.append(sm).append(" PL 82050 82064 40 100 30 40 10\r\n");
}
// IRRIGATION
sb.append("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n");
if (!(smStr = getValueOr(trData, "sm_irrigation", "")).equals("")) {
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "irrigation", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$5s %4$5s %5$5s %6$-5s %7$-5s %8$5s %9$5s\r\n",
sm,
"IR",
getValueOr(smData, "imdep", "30"),
getValueOr(smData, "ithrl", "50"),
getValueOr(smData, "ithru", "100"),
getValueOr(smData, "iroff", "GS000"),
getValueOr(smData, "imeth", "IR001"),
getValueOr(smData, "iramt", "10"),
getValueOr(smData, "ireff", "1.00")));
} else {
sb.append(sm).append(" IR 30 50 100 GS000 IR001 10 1.00\r\n");
}
// NITROGEN
sb.append("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n");
if (!(smStr = getValueOr(trData, "sm_nitrogen", "")).equals("")) {
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "nitrogen", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$5s %4$5s %5$5s %6$-5s %7$-5s\r\n",
sm,
"NI",
getValueOr(smData, "nmdep", "30"),
getValueOr(smData, "nmthr", "50"),
getValueOr(smData, "namnt", "25"),
getValueOr(smData, "ncode", "FE001"),
getValueOr(smData, "naoff", "GS000")));
} else {
sb.append(sm).append(" NI 30 50 25 FE001 GS000\r\n");
}
// RESIDUES
sb.append("@N RESIDUES RIPCN RTIME RIDEP\r\n");
if (!(smStr = getValueOr(trData, "sm_residues", "")).equals("")) {
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "residues", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$5s %4$5s %5$5s\r\n",
sm,
"RE",
getValueOr(smData, "ripcn", "100"),
getValueOr(smData, "rtime", "1"),
getValueOr(smData, "ridep", "20")));
} else {
sb.append(sm).append(" RE 100 1 20\r\n");
}
// HARVEST
sb.append("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n");
if (!(smStr = getValueOr(trData, "sm_harvests", "")).equals("")) {
sb.append(sm).append(" ").append(smStr).append("\r\n\r\n");
} else if (!(smData = getObjectOr(trData, "harvests", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$5s %4$02d%5$03d %6$5s %7$5s\r\n\r\n",
sm,
"HA",
getValueOr(smData, "hfrst", "0"),
Integer.parseInt(formatNumStr(2, smData, "hlyer", "83")),
Integer.parseInt(formatNumStr(3, smData, "hlday", "057")),
getValueOr(smData, "hpcnp", "100"),
getValueOr(smData, "hpcnr", "0")));
} else {
sb.append(sm).append(" HA 0 83057 100 0\r\n\r\n");
}
return sb.toString();
}
/**
* Get index value of the record and set new id value in the array.
* In addition, it will check if the event date is available. If not, then
* return 0.
*
* @param m sub data
* @param arr array of sub data
* @return current index value of the sub data
*/
private int setSecDataArr(HashMap m, ArrayList arr, boolean isEvent) {
int idx = setSecDataArr(m, arr);
if (idx != 0 && isEvent && getValueOr(m, "date", "").equals("")) {
return -1;
} else {
return idx;
}
}
/**
* Get index value of the record and set new id value in the array
*
* @param m sub data
* @param arr array of sub data
* @return current index value of the sub data
*/
private int setSecDataArr(HashMap m, ArrayList arr) {
if (!m.isEmpty()) {
for (int j = 0; j < arr.size(); j++) {
if (arr.get(j).equals(m)) {
return j + 1;
}
}
arr.add(m);
return arr.size();
} else {
return 0;
}
}
private int setSecDataArr(ArrayList inArr, ArrayList outArr, boolean isEvent) {
int idx = setSecDataArr(inArr, outArr);
if (idx != 0 && isEvent && !checkEventDate(inArr)) {
return -1;
} else {
return idx;
}
}
private boolean checkEventDate(ArrayList arr) {
for (Object o : arr) {
if (getValueOr((HashMap) o, "date", "").equals("")) {
return false;
}
}
return true;
}
/**
* Get index value of the record and set new id value in the array
*
* @param inArr sub array of data
* @param outArr array of sub data
* @return current index value of the sub data
*/
private int setSecDataArr(ArrayList inArr, ArrayList outArr) {
if (!inArr.isEmpty()) {
for (int j = 0; j < outArr.size(); j++) {
if (outArr.get(j).equals(inArr)) {
return j + 1;
}
}
outArr.add(inArr);
return outArr.size();
} else {
return 0;
}
}
/**
* To check if there is plot info data existed in the experiment
*
* @param expData experiment data holder
* @return the boolean value for if plot info exists
*/
private boolean isPlotInfoExist(Map expData) {
String[] plotIds = {"plta", "pltr#", "pltln", "pldr", "pltsp", "pllay", "pltha", "plth#", "plthl", "plthm"};
for (String plotId : plotIds) {
if (!getValueOr(expData, plotId, "").equals("")) {
return true;
}
}
return false;
}
/**
* To check if there is soil analysis info data existed in the experiment
*
* @param expData initial condition layer data array
* @return the boolean value for if soil analysis info exists
*/
private boolean isSoilAnalysisExist(ArrayList<HashMap> icSubArr) {
for (HashMap icSubData : icSubArr) {
if (!getValueOr(icSubData, "slsc", "").equals("")) {
return true;
}
}
return false;
}
/**
* Get sub data array from experiment data object
*
* @param expData experiment data holder
* @param blockName top level block name
* @param dataListName sub array name
* @return sub data array
*/
private ArrayList<HashMap> getDataList(Map expData, String blockName, String dataListName) {
HashMap dataBlock = getObjectOr(expData, blockName, new HashMap());
return getObjectOr(dataBlock, dataListName, new ArrayList<HashMap>());
}
/**
* Try to translate 3-bit CRID to 2-bit version stored in the map
*
* @param cuData the cultivar data record
* @param id the field id for contain crop id info
* @param defVal the default value when id is not available
* @return 2-bit crop ID
*/
private String translateTo2BitCrid(Map cuData, String id, String defVal) {
String crid = getValueOr(cuData, id, "");
if (!crid.equals("")) {
return DssatCRIDHelper.get2BitCrid(crid);
} else {
return defVal;
}
}
/**
* Try to translate 3-bit CRID to 2-bit version stored in the map
*
* @param cuData the cultivar data record
*/
private void translateTo2BitCrid(Map cuData) {
String crid = getValueOr(cuData, "crid", "");
if (!crid.equals("")) {
cuData.put("crid", DssatCRIDHelper.get2BitCrid(crid));
}
}
/**
* Get soil/weather data from data holder
*
* @param expData The experiment data holder
* @param key The key name for soil/weather section
* @return the list of data holder
*/
private ArrayList readSWData(HashMap expData, String key) {
ArrayList ret;
Object soil = expData.get(key);
if (soil != null) {
if (soil instanceof ArrayList) {
ret = (ArrayList) soil;
} else {
ret = new ArrayList();
ret.add(soil);
}
} else {
ret = new ArrayList();
}
return ret;
}
private String replaceSMStr(String smStr, String val, int start) {
if (smStr.length() < start) {
smStr = String.format("%-" + start + "s", smStr);
}
smStr = smStr.substring(0, start)
+ val
+ smStr.substring(start + val.length());
return smStr;
}
private String getAppliedDomes(HashMap data, String domeType) {
if (getValueOr(data, domeType + "_dome_applied", "").equals("Y")) {
// Get dome ids
String domeKey = "";
if (domeType.equals("field")) {
domeKey = "field_overlay";
} else if (domeType.equals("seasonal")) {
domeKey = "seasonal_strategy";
}
String[] domeIds = getValueOr(data, domeKey, "").split("[|]");
String[] failedDomeIds = getValueOr(data, domeType + "_dome_failed", "").split("[|]");
HashSet<String> domes = new HashSet();
// Add all dome ids
for (String domeId : domeIds) {
if (!domeId.equals("")) {
domes.add(domeId);
}
}
// Remove failed dome id
for (String failedDomeId : failedDomeIds) {
if (!failedDomeId.equals("")) {
domes.remove(failedDomeId);
}
}
// Convert to string format, divide by "|"
StringBuilder ret = new StringBuilder();
String[] domeArr = domes.toArray(new String[0]);
if (domeArr.length > 0) {
ret.append(domeArr[0]);
}
for (int i = 1; i < domeArr.length; i++) {
ret.append("|").append(domeArr[i]);
}
return ret.toString();
} else {
return "";
}
}
}
|
src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java
|
package org.agmip.translators.dssat;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.agmip.translators.dssat.DssatCommonInput.copyItem;
import static org.agmip.util.MapUtil.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* DSSAT Experiment Data I/O API Class
*
* @author Meng Zhang
* @version 1.0
*/
public class DssatXFileOutput extends DssatCommonOutput {
private static final Logger LOG = LoggerFactory.getLogger(DssatXFileOutput.class);
// public static final DssatCRIDHelper crHelper = new DssatCRIDHelper();
/**
* DSSAT Experiment Data Output method
*
* @param arg0 file output path
* @param result data holder object
*/
@Override
public void writeFile(String arg0, Map result) {
// Initial variables
HashMap expData = (HashMap) result;
ArrayList<HashMap> soilArr = readSWData(expData, "soil");
ArrayList<HashMap> wthArr = readSWData(expData, "weather");
HashMap soilData;
HashMap wthData;
BufferedWriter bwX; // output object
StringBuilder sbGenData = new StringBuilder(); // construct the data info in the output
StringBuilder sbDomeData = new StringBuilder(); // construct the dome info in the output
StringBuilder sbNotesData = new StringBuilder(); // construct the data info in the output
StringBuilder sbData = new StringBuilder(); // construct the data info in the output
StringBuilder eventPart2 = new StringBuilder(); // output string for second part of event data
HashMap sqData;
ArrayList<HashMap> evtArr; // Arraylist for section data holder
ArrayList<HashMap> adjArr;
HashMap evtData;
// int trmnNum; // total numbers of treatment in the data holder
int cuNum; // total numbers of cultivars in the data holder
int flNum; // total numbers of fields in the data holder
int saNum; // total numbers of soil analysis in the data holder
int icNum; // total numbers of initial conditions in the data holder
int mpNum; // total numbers of plaintings in the data holder
int miNum; // total numbers of irrigations in the data holder
int mfNum; // total numbers of fertilizers in the data holder
int mrNum; // total numbers of residues in the data holder
int mcNum; // total numbers of chemical in the data holder
int mtNum; // total numbers of tillage in the data holder
int meNum; // total numbers of enveronment modification in the data holder
int mhNum; // total numbers of harvest in the data holder
int smNum; // total numbers of simulation controll record
ArrayList<HashMap> sqArr; // array for treatment record
ArrayList<HashMap> cuArr = new ArrayList(); // array for cultivars record
ArrayList<HashMap> flArr = new ArrayList(); // array for fields record
ArrayList<HashMap> saArr = new ArrayList(); // array for soil analysis record
ArrayList<HashMap> icArr = new ArrayList(); // array for initial conditions record
ArrayList<HashMap> mpArr = new ArrayList(); // array for plaintings record
ArrayList<ArrayList<HashMap>> miArr = new ArrayList(); // array for irrigations record
ArrayList<ArrayList<HashMap>> mfArr = new ArrayList(); // array for fertilizers record
ArrayList<ArrayList<HashMap>> mrArr = new ArrayList(); // array for residues record
ArrayList<ArrayList<HashMap>> mcArr = new ArrayList(); // array for chemical record
ArrayList<ArrayList<HashMap>> mtArr = new ArrayList(); // array for tillage record
ArrayList<ArrayList<HashMap>> meArr = new ArrayList(); // array for enveronment modification record
ArrayList<ArrayList<HashMap>> mhArr = new ArrayList(); // array for harvest record
ArrayList<HashMap> smArr = new ArrayList(); // array for simulation control record
// String exName;
boolean isFallow = false;
try {
// Set default value for missing data
if (expData == null || expData.isEmpty()) {
return;
}
// decompressData((HashMap) result);
setDefVal();
// Initial BufferedWriter
String fileName = getFileName(result, "X");
arg0 = revisePath(arg0);
outputFile = new File(arg0 + fileName);
bwX = new BufferedWriter(new FileWriter(outputFile));
// Output XFile
// EXP.DETAILS Section
sbError.append(String.format("*EXP.DETAILS: %1$-10s %2$s\r\n\r\n",
getFileName(result, "").replaceAll("\\.", ""),
getObjectOr(expData, "local_name", defValBlank)));
// GENERAL Section
sbGenData.append("*GENERAL\r\n");
// People
if (!getObjectOr(expData, "person_notes", "").equals("")) {
sbGenData.append(String.format("@PEOPLE\r\n %1$s\r\n", getObjectOr(expData, "person_notes", defValBlank)));
}
// Address
if (getObjectOr(expData, "institution", "").equals("")) {
// if (!getObjectOr(expData, "fl_loc_1", "").equals("")
// && getObjectOr(expData, "fl_loc_2", "").equals("")
// && getObjectOr(expData, "fl_loc_3", "").equals("")) {
// sbGenData.append(String.format("@ADDRESS\r\n %3$s, %2$s, %1$s\r\n",
// getObjectOr(expData, "fl_loc_1", defValBlank).toString(),
// getObjectOr(expData, "fl_loc_2", defValBlank).toString(),
// getObjectOr(expData, "fl_loc_3", defValBlank).toString()));
// }
} else {
sbGenData.append(String.format("@ADDRESS\r\n %1$s\r\n", getObjectOr(expData, "institution", defValBlank)));
}
// Site
if (!getObjectOr(expData, "site_name", "").equals("")) {
sbGenData.append(String.format("@SITE\r\n %1$s\r\n", getObjectOr(expData, "site_name", defValBlank)));
}
// Plot Info
if (isPlotInfoExist(expData)) {
sbGenData.append("@ PAREA PRNO PLEN PLDR PLSP PLAY HAREA HRNO HLEN HARM.........\r\n");
sbGenData.append(String.format(" %1$6s %2$5s %3$5s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$5s %10$-15s\r\n",
formatNumStr(6, expData, "plta", defValR),
formatNumStr(5, expData, "pltr#", defValI),
formatNumStr(5, expData, "pltln", defValR),
formatNumStr(5, expData, "pldr", defValI),
formatNumStr(5, expData, "pltsp", defValI),
getObjectOr(expData, "pllay", defValC),
formatNumStr(5, expData, "pltha", defValR),
formatNumStr(5, expData, "plth#", defValI),
formatNumStr(5, expData, "plthl", defValR),
getObjectOr(expData, "plthm", defValC)));
}
// Notes
if (!getObjectOr(expData, "tr_notes", "").equals("")) {
sbNotesData.append("@NOTES\r\n");
String notes = getObjectOr(expData, "tr_notes", defValC);
notes = notes.replaceAll("\\\\r\\\\n", "\r\n");
// If notes contain newline code, then write directly
if (notes.contains("\r\n")) {
// sbData.append(String.format(" %1$s\r\n", notes));
sbNotesData.append(notes);
} // Otherwise, add newline for every 75-bits charactors
else {
while (notes.length() > 75) {
sbNotesData.append(" ").append(notes.substring(0, 75)).append("\r\n");
notes = notes.substring(75);
}
sbNotesData.append(" ").append(notes).append("\r\n");
}
}
sbData.append("\r\n");
// TREATMENT Section
sqArr = getDataList(expData, "dssat_sequence", "data");
evtArr = getDataList(expData, "management", "events");
adjArr = getObjectOr(expData, "adjustments", new ArrayList());
ArrayList<HashMap> rootArr = getObjectOr(expData, "dssat_root", new ArrayList());
ArrayList<HashMap> meOrgArr = getDataList(expData, "dssat_environment_modification", "data");
ArrayList<HashMap> smOrgArr = getDataList(expData, "dssat_simulation_control", "data");
String seqId;
String em;
String sm;
boolean isAnyDomeApplied = false;
LinkedHashMap<String, String> appliedDomes = new LinkedHashMap<String, String>();
sbData.append("*TREATMENTS -------------FACTOR LEVELS------------\r\n");
sbData.append("@N R O C TNAME.................... CU FL SA IC MP MI MF MR MC MT ME MH SM\r\n");
// if there is no sequence info, create dummy data
if (sqArr.isEmpty()) {
sqArr.add(new HashMap());
}
// Set sequence related block info
for (int i = 0; i < sqArr.size(); i++) {
sqData = sqArr.get(i);
seqId = getValueOr(sqData, "seqid", defValBlank);
em = getValueOr(sqData, "em", defValBlank);
sm = getValueOr(sqData, "sm", defValBlank);
if (i < soilArr.size()) {
soilData = soilArr.get(i);
} else if (soilArr.isEmpty()) {
soilData = new HashMap();
} else {
soilData = soilArr.get(0);
}
if (soilData == null) {
soilData = new HashMap();
}
if (i < wthArr.size()) {
wthData = wthArr.get(i);
} else if (wthArr.isEmpty()) {
wthData = new HashMap();
} else {
wthData = wthArr.get(0);
}
if (wthData == null) {
wthData = new HashMap();
}
HashMap cuData = new HashMap();
HashMap flData = new HashMap();
HashMap mpData = new HashMap();
ArrayList<HashMap> miSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mfSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mrSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mcSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mtSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> meSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mhSubArr = new ArrayList<HashMap>();
HashMap smData = new HashMap();
HashMap rootData;
// Set exp root info
if (i < rootArr.size()) {
rootData = rootArr.get(i);
} else {
rootData = expData;
}
// Applied DOME Info
String trt_name = getValueOr(sqData, "trt_name", getValueOr(rootData, "trt_name", getValueOr(rootData, "exname", defValC)));
if (getValueOr(rootData, "dome_applied", "").equals("Y")) {
// If it comes with seasonal exname style
if (trt_name.matches(".+[^_]__\\d+$")) {
trt_name = trt_name.replaceAll("__\\d+$", "_*");
if (appliedDomes.get(trt_name + " Field ") == null) {
appliedDomes.put(trt_name + " Field ", getAppliedDomes(rootData, "field"));
}
if (appliedDomes.get(trt_name + " Seasonal ") == null) {
appliedDomes.put(trt_name + " Seasonal ", getAppliedDomes(rootData, "seasonal"));
}
} else {
appliedDomes.put(trt_name + " Field ", getAppliedDomes(rootData, "field"));
appliedDomes.put(trt_name + " Seasonal ", getAppliedDomes(rootData, "seasonal"));
}
isAnyDomeApplied = true;
} else {
appliedDomes.put(trt_name, "");
}
// Set field info
copyItem(flData, rootData, "id_field");
String dssat_wst_id = getValueOr(rootData, "dssat_wst_id", "");
// Weather data is missing plus dssat_wst_id is available
if (!dssat_wst_id.equals("") && wthData.isEmpty()) {
flData.put("wst_id", dssat_wst_id);
} else {
flData.put("wst_id", getWthFileName(rootData));
}
copyItem(flData, rootData, "flsl");
copyItem(flData, rootData, "flob");
copyItem(flData, rootData, "fl_drntype");
copyItem(flData, rootData, "fldrd");
copyItem(flData, rootData, "fldrs");
copyItem(flData, rootData, "flst");
if (soilData.get("sltx") != null) {
copyItem(flData, soilData, "sltx");
} else {
copyItem(flData, rootData, "sltx");
}
copyItem(flData, soilData, "sldp");
copyItem(flData, rootData, "soil_id");
copyItem(flData, rootData, "fl_name");
copyItem(flData, rootData, "fl_lat");
copyItem(flData, rootData, "fl_long");
copyItem(flData, rootData, "flele");
copyItem(flData, rootData, "farea");
copyItem(flData, rootData, "fllwr");
copyItem(flData, rootData, "flsla");
copyItem(flData, getObjectOr(rootData, "dssat_info", new HashMap()), "flhst");
copyItem(flData, getObjectOr(rootData, "dssat_info", new HashMap()), "fhdur");
// remove the "_trno" in the soil_id when soil analysis is available
String soilId = getValueOr(flData, "soil_id", "");
if (soilId.length() > 10 && soilId.matches("\\w+_\\d+") || soilId.length() < 8) {
flData.put("soil_id", getSoilID(flData));
}
flNum = setSecDataArr(flData, flArr);
// Set initial condition info
icNum = setSecDataArr(getObjectOr(rootData, "initial_conditions", new HashMap()), icArr);
// Set environment modification info
for (HashMap meOrgArr1 : meOrgArr) {
if (em.equals(meOrgArr1.get("em"))) {
HashMap tmp = new HashMap();
tmp.putAll(meOrgArr1);
tmp.remove("em");
meSubArr.add(tmp);
}
}
if (!adjArr.isEmpty()) {
ArrayList<HashMap<String, String>> startArr = new ArrayList();
ArrayList<HashMap<String, String>> endArr = new ArrayList();
String sdat = getValueOr(rootData, "sdat", "");
if (sdat.equals("")) {
sdat = getPdate(result);
}
final List<String> vars = Arrays.asList(new String[]{"tmax", "tmin", "srad", "wind", "rain", "co2y", "tdew"});
final List<String> emVars = Arrays.asList(new String[]{"emmax", "emmin", "emrad", "emwnd", "emrai", "emco2", "emdew"});
final List<String> emcVars = Arrays.asList(new String[]{"ecmax", "ecmin", "ecrad", "ecwnd", "ecrai", "ecco2", "ecdew"});
for (HashMap adjData : adjArr) {
if (getValueOr(adjData, "seqid", defValBlank).equals(seqId)) {
String var = getValueOr(adjData, "variable", "");
String ecVar;
String val = getValueOr(adjData, "value", "");
String method = getValueOr(adjData, "method", "");
String startDate = getValueOr(adjData, "startdate", sdat);
String endDate = getValueOr(adjData, "enddate", "");
int idx = vars.indexOf(var);
if (idx < 0) {
LOG.warn("Found unsupported adjusment variable [" + var + "], will be ignored.");
sbError.append("Found unsupported adjusment variable [").append(var).append("], will be ignored.");
continue;
} else {
var = emVars.get(idx);
ecVar = emcVars.get(idx);
}
if (method.equals("substitute")) {
method = "R";
} else if (method.equals("delta")) {
if (val.startsWith("-")) {
val = val.substring(1);
method = "S";
} else {
method = "A";
}
} else if (method.equals("multiply")) {
method = "M";
} else {
LOG.warn("Found unsupported adjusment method [" + method + "] for [" + var + "], will be ignored.");
sbError.append("Found unsupported adjusment method [").append(method).append("] for [").append(var).append("], will be ignored.");
continue;
}
HashMap tmp = DssatCommonInput.getSectionDataWithNocopy(startArr, "date", startDate);
if (tmp == null) {
tmp = new HashMap();
startArr.add(tmp);
}
tmp.put(var, val);
tmp.put(ecVar, method);
tmp.put("date", startDate);
if (!endDate.equals("")) {
tmp = DssatCommonInput.getSectionDataWithNocopy(endArr, "date", endDate);
if (tmp == null) {
tmp = new HashMap();
endArr.add(tmp);
}
tmp.put(var, "0");
tmp.put(ecVar, "A");
tmp.put("date", endDate);
}
}
}
meSubArr.addAll(startArr);
meSubArr.addAll(endArr);
}
// Set soil analysis info
// ArrayList<HashMap> icSubArr = getDataList(expData, "initial_condition", "soilLayer");
ArrayList<HashMap> soilLarys = getObjectOr(soilData, "soilLayer", new ArrayList());
// // If it is stored in the initial condition block
// if (isSoilAnalysisExist(icSubArr)) {
// HashMap saData = new HashMap();
// ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
// HashMap saSubData;
// for (int i = 0; i < icSubArr.size(); i++) {
// saSubData = new HashMap();
// copyItem(saSubData, icSubArr.get(i), "sabl", "icbl", false);
// copyItem(saSubData, icSubArr.get(i), "sasc", "slsc", false);
// saSubArr.add(saSubData);
// }
// copyItem(saData, soilData, "sadat");
// saData.put("soilLayer", saSubArr);
// saNum = setSecDataArr(saData, saArr);
// } else
// If it is stored in the soil block
if (isSoilAnalysisExist(soilLarys)) {
HashMap saData = new HashMap();
ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
HashMap saSubData;
for (HashMap soilLary : soilLarys) {
saSubData = new HashMap();
copyItem(saSubData, soilLary, "sabl", "sllb", false);
copyItem(saSubData, soilLary, "saoc", "sloc", false);
copyItem(saSubData, soilLary, "sasc", "slsc", false);
saSubArr.add(saSubData);
}
copyItem(saData, soilData, "sadat");
saData.put("soilLayer", saSubArr);
saNum = setSecDataArr(saData, saArr, true);
} else {
saNum = 0;
}
// Set simulation control info
for (HashMap smOrgArr1 : smOrgArr) {
if (sm.equals(smOrgArr1.get("sm"))) {
smData.putAll(smOrgArr1);
smData.remove("sm");
break;
}
}
// if (smData.isEmpty()) {
// smData.put("fertilizer", mfSubArr);
// smData.put("irrigation", miSubArr);
// smData.put("planting", mpData);
// }
copyItem(smData, rootData, "sdat");
copyItem(smData, rootData, "dssat_model");
copyItem(smData, getObjectOr(wthData, "weather", new HashMap()), "co2y");
// Loop all event data
for (HashMap evtArr1 : evtArr) {
evtData = new HashMap();
evtData.putAll(evtArr1);
// Check if it has same sequence number
if (getValueOr(evtData, "seqid", defValBlank).equals(seqId)) {
evtData.remove("seqid");
// Planting event
if (getValueOr(evtData, "event", defValBlank).equals("planting")) {
// Set cultivals info
copyItem(cuData, evtData, "cul_name");
copyItem(cuData, evtData, "crid");
copyItem(cuData, evtData, "cul_id");
copyItem(cuData, evtData, "dssat_cul_id");
copyItem(cuData, evtData, "rm");
copyItem(cuData, evtData, "cul_notes");
translateTo2BitCrid(cuData);
// Set planting info
// To make comparision only on the planting information (without crop data), use HashMap to rebuild pure planting map
copyItem(mpData, evtData, "date");
copyItem(mpData, evtData, "edate");
copyItem(mpData, evtData, "plpop");
copyItem(mpData, evtData, "plpoe");
copyItem(mpData, evtData, "plma");
copyItem(mpData, evtData, "plds");
copyItem(mpData, evtData, "plrs");
copyItem(mpData, evtData, "plrd");
copyItem(mpData, evtData, "pldp");
copyItem(mpData, evtData, "plmwt");
copyItem(mpData, evtData, "page");
copyItem(mpData, evtData, "plenv");
copyItem(mpData, evtData, "plph");
copyItem(mpData, evtData, "plspl");
copyItem(mpData, evtData, "pl_name");
} // irrigation event
else if (getValueOr(evtData, "event", "").equals("irrigation")) {
miSubArr.add(evtData);
} // fertilizer event
else if (getValueOr(evtData, "event", "").equals("fertilizer")) {
mfSubArr.add(evtData);
} // organic_matter event
else if (getValueOr(evtData, "event", "").equals("organic_matter")) { // P.S. change event name to organic-materials; Back to organic_matter again.
mrSubArr.add(evtData);
} // chemical event
else if (getValueOr(evtData, "event", "").equals("chemical")) {
mcSubArr.add(evtData);
} // tillage event
else if (getValueOr(evtData, "event", "").equals("tillage")) {
mtSubArr.add(evtData);
// } // environment_modification event
// else if (getValueOr(evtData, "event", "").equals("environment_modification")) {
// meSubArr.add(evtData);
} // harvest event
else if (getValueOr(evtData, "event", "").equals("harvest")) {
mhSubArr.add(evtData);
if (!getValueOr(evtData, "date", "").trim().equals("")) {
smData.put("hadat_valid", "Y");
}
// copyItem(smData, evtData, "hadat", "date", false);
} else {
}
} else {
}
}
// Cancel for assume default value handling
// // If alternative fields are avaiable for fertilizer data
// if (mfSubArr.isEmpty()) {
// if (!getObjectOr(result, "fen_tot", "").equals("")
// || !getObjectOr(result, "fep_tot", "").equals("")
// || !getObjectOr(result, "fek_tot", "").equals("")) {
// mfSubArr.add(new HashMap());
// }
// }
// Specila handling for fallow experiment
if (mpData.isEmpty()) {
isFallow = true;
cuData.put("crid", "FA");
cuData.put("dssat_cul_id", "IB0001");
cuData.put("cul_name", "Fallow");
if (mhSubArr.isEmpty()) {
HashMap mhData = new HashMap();
copyItem(mhData, rootData, "date", "endat", false);
// mhData.put("hastg", "GS000");
mhSubArr.add(mhData);
smData.put("hadat_valid", "Y");
}
}
cuNum = setSecDataArr(cuData, cuArr);
mpNum = setSecDataArr(mpData, mpArr, true);
miNum = setSecDataArr(miSubArr, miArr, true);
mfNum = setSecDataArr(mfSubArr, mfArr, true);
mrNum = setSecDataArr(mrSubArr, mrArr, true);
mcNum = setSecDataArr(mcSubArr, mcArr, true);
mtNum = setSecDataArr(mtSubArr, mtArr, true);
meNum = setSecDataArr(meSubArr, meArr); // Since old format of EM might exist, skip the check for EM
mhNum = setSecDataArr(mhSubArr, mhArr, true);
smNum = setSecDataArr(smData, smArr);
if (smNum == 0) {
smNum = 1;
}
StringBuilder sbBadEventRrrMsg = new StringBuilder();
boolean badEventFlg = false;
if (saNum < 0) {
saNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("SA ");
}
if (icNum < 0) {
icNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("IC ");
}
if (mpNum < 0) {
mpNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("MP ");
}
if (miNum < 0) {
miNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("MI ");
}
if (mfNum < 0) {
mfNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("MF ");
}
if (mrNum < 0) {
mrNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("MR ");
}
if (mcNum < 0) {
mcNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("MC ");
}
if (mtNum < 0) {
mtNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("MT ");
}
if (meNum < 0) {
meNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("ME ");
}
if (mhNum < 0) {
mhNum = 0;
badEventFlg = true;
sbBadEventRrrMsg.append("MH ");
}
if (badEventFlg) {
String tmp = sbBadEventRrrMsg.toString();
sbBadEventRrrMsg = new StringBuilder();
sbBadEventRrrMsg.append(" ! Bad Event detected for ").append(tmp);
}
sbData.append(String.format("%1$-3s%2$1s %3$1s %4$1s %5$-25s %6$2s %7$2s %8$2s %9$2s %10$2s %11$2s %12$2s %13$2s %14$2s %15$2s %16$2s %17$2s %18$2s%19$s\r\n",
String.format("%2s", getValueOr(sqData, "trno", "1")), // For 3-bit treatment number
getValueOr(sqData, "sq", "1"), // P.S. default value here is based on document DSSAT vol2.pdf
getValueOr(sqData, "op", "1"),
getValueOr(sqData, "co", "0"),
formatStr(25, sqData, "trt_name", getValueOr(rootData, "trt_name", getValueOr(rootData, "exname", defValC))),
cuNum, //getObjectOr(data, "ge", defValI).toString(),
flNum, //getObjectOr(data, "fl", defValI).toString(),
saNum, //getObjectOr(data, "sa", defValI).toString(),
icNum, //getObjectOr(data, "ic", defValI).toString(),
mpNum, //getObjectOr(data, "pl", defValI).toString(),
miNum, //getObjectOr(data, "ir", defValI).toString(),
mfNum, //getObjectOr(data, "fe", defValI).toString(),
mrNum, //getObjectOr(data, "om", defValI).toString(),
mcNum, //getObjectOr(data, "ch", defValI).toString(),
mtNum, //getObjectOr(data, "ti", defValI).toString(),
meNum, //getObjectOr(data, "em", defValI).toString(),
mhNum, //getObjectOr(data, "ha", defValI).toString(),
smNum, // 1
sbBadEventRrrMsg.toString()));
}
sbData.append("\r\n");
// CULTIVARS Section
if (!cuArr.isEmpty()) {
sbData.append("*CULTIVARS\r\n");
sbData.append("@C CR INGENO CNAME\r\n");
for (int idx = 0; idx < cuArr.size(); idx++) {
HashMap secData = cuArr.get(idx);
// String cul_id = defValC;
String crid = getValueOr(secData, "crid", "");
// Checl if necessary data is missing
if (crid.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [crid]\r\n");
// } else {
// // Set cultivar id a default value deponds on the crop id
// if (crid.equals("MZ")) {
// cul_id = "990002";
// } else {
// cul_id = "999999";
// }
// }
// if (getObjectOr(secData, "cul_id", "").equals("")) {
// sbError.append("! Warning: Incompleted record because missing data : [cul_id], and will use default value '").append(cul_id).append("'\r\n");
}
sbData.append(String.format("%1$2s %2$-2s %3$-6s %4$s\r\n",
idx + 1,
formatStr(2, secData, "crid", defValBlank), // P.S. if missing, default value use blank string
formatStr(6, secData, "dssat_cul_id", getValueOr(secData, "cul_id", defValC)), // P.S. Set default value which is deponds on crid(Cancelled)
getValueOr(secData, "cul_name", defValC)));
if (!getValueOr(secData, "rm", "").equals("") || !getValueOr(secData, "cul_notes", "").equals("")) {
if (sbNotesData.toString().equals("")) {
sbNotesData.append("@NOTES\r\n");
}
sbNotesData.append(" Cultivar Additional Info\r\n");
sbNotesData.append(" C RM CNAME CUL_NOTES\r\n");
sbNotesData.append(String.format("%1$2s %2$4s %3$s\r\n",
idx + 1,
getValueOr(secData, "rm", defValC),
getValueOr(secData, "cul_notes", defValC)));
}
}
sbData.append("\r\n");
} else if (!isFallow) {
sbError.append("! Warning: There is no cultivar data in the experiment.\r\n");
}
// FIELDS Section
if (!flArr.isEmpty()) {
sbData.append("*FIELDS\r\n");
sbData.append("@L ID_FIELD WSTA.... FLSA FLOB FLDT FLDD FLDS FLST SLTX SLDP ID_SOIL FLNAME\r\n");
eventPart2 = new StringBuilder();
eventPart2.append("@L ...........XCRD ...........YCRD .....ELEV .............AREA .SLEN .FLWR .SLAS FLHST FHDUR\r\n");
} else {
sbError.append("! Warning: There is no field data in the experiment.\r\n");
}
for (int idx = 0; idx < flArr.size(); idx++) {
HashMap secData = flArr.get(idx);
// Check if the necessary is missing
if (getObjectOr(secData, "wst_id", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [wst_id]\r\n");
}
String soil_id = getValueOr(secData, "soil_id", defValC);
if (soil_id.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [soil_id]\r\n");
} else if (soil_id.length() > 10) {
sbError.append("! Warning: Oversized data : [soil_id] ").append(soil_id).append("\r\n");
}
sbData.append(String.format("%1$2s %2$-8s %3$-8s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$-5s %10$-5s%11$5s %12$-10s %13$s\r\n", // P.S. change length definition to match current way
idx + 1,
formatStr(8, secData, "id_field", defValC),
formatStr(8, secData, "wst_id", defValC),
formatStr(4, secData, "flsl", defValC),
formatNumStr(5, secData, "flob", defValR),
formatStr(5, secData, "fl_drntype", defValC),
formatNumStr(5, secData, "fldrd", defValR),
formatNumStr(5, secData, "fldrs", defValR),
formatStr(5, secData, "flst", defValC),
formatStr(5, transSltx(getValueOr(secData, "sltx", defValC)), "sltx"),
formatNumStr(5, secData, "sldp", defValR),
soil_id,
getValueOr(secData, "fl_name", defValC)));
eventPart2.append(String.format("%1$2s %2$15s %3$15s %4$9s %5$17s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1,
formatNumStr(15, secData, "fl_long", defValR),
formatNumStr(15, secData, "fl_lat", defValR),
formatNumStr(9, secData, "flele", defValR),
formatNumStr(17, secData, "farea", defValR),
"-99", // P.S. SLEN keeps -99
formatNumStr(5, secData, "fllwr", defValR),
formatNumStr(5, secData, "flsla", defValR),
formatStr(5, secData, "flhst", defValC),
formatNumStr(5, secData, "fhdur", defValR)));
}
if (!flArr.isEmpty()) {
sbData.append(eventPart2.toString()).append("\r\n");
}
// SOIL ANALYSIS Section
if (!saArr.isEmpty()) {
sbData.append("*SOIL ANALYSIS\r\n");
for (int idx = 0; idx < saArr.size(); idx++) {
HashMap secData = (HashMap) saArr.get(idx);
String brokenMark = "";
if (getValueOr(secData, "sadat", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append("@A SADAT SMHB SMPX SMKE SANAME\r\n");
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "sadat", defValD)),
getValueOr(secData, "samhb", defValC),
getValueOr(secData, "sampx", defValC),
getValueOr(secData, "samke", defValC),
getValueOr(secData, "sa_name", defValC)));
ArrayList<HashMap> subDataArr = getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append(brokenMark).append("@A SABL SADM SAOC SANI SAPHW SAPHB SAPX SAKE SASC\r\n");
}
for (HashMap subData : subDataArr) {
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1,
formatNumStr(5, subData, "sabl", defValR),
formatNumStr(5, subData, "sabdm", defValR),
formatNumStr(5, subData, "saoc", defValR),
formatNumStr(5, subData, "sani", defValR),
formatNumStr(5, subData, "saphw", defValR),
formatNumStr(5, subData, "saphb", defValR),
formatNumStr(5, subData, "sapx", defValR),
formatNumStr(5, subData, "sake", defValR),
formatNumStr(5, subData, "sasc", defValR)));
}
}
sbData.append("\r\n");
}
// INITIAL CONDITIONS Section
if (!icArr.isEmpty()) {
sbData.append("*INITIAL CONDITIONS\r\n");
for (int idx = 0; idx < icArr.size(); idx++) {
HashMap secData = icArr.get(idx);
String brokenMark = "";
if (getValueOr(secData, "icdat", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append("@C PCR ICDAT ICRT ICND ICRN ICRE ICWD ICRES ICREN ICREP ICRIP ICRID ICNAME\r\n");
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$s\r\n",
idx + 1,
translateTo2BitCrid(secData, "icpcr", defValC),
formatDateStr(getValueOr(secData, "icdat", getPdate(result))),
formatNumStr(5, secData, "icrt", defValR),
formatNumStr(5, secData, "icnd", defValR),
formatNumStr(5, secData, "icrz#", defValR),
formatNumStr(5, secData, "icrze", defValR),
formatNumStr(5, secData, "icwt", defValR),
formatNumStr(5, secData, "icrag", defValR),
formatNumStr(5, secData, "icrn", defValR),
formatNumStr(5, secData, "icrp", defValR),
formatNumStr(5, secData, "icrip", defValR),
formatNumStr(5, secData, "icrdp", defValR),
getValueOr(secData, "ic_name", defValC)));
ArrayList<HashMap> subDataArr = getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append(brokenMark).append("@C ICBL SH2O SNH4 SNO3\r\n");
}
for (HashMap subData : subDataArr) {
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s\r\n",
idx + 1,
formatNumStr(5, subData, "icbl", defValR),
formatNumStr(5, subData, "ich2o", defValR),
formatNumStr(5, subData, "icnh4", defValR),
formatNumStr(5, subData, "icno3", defValR)));
}
}
sbData.append("\r\n");
}
// PLANTING DETAILS Section
if (!mpArr.isEmpty()) {
sbData.append("*PLANTING DETAILS\r\n");
sbData.append("@P PDATE EDATE PPOP PPOE PLME PLDS PLRS PLRD PLDP PLWT PAGE PENV PLPH SPRL PLNAME\r\n");
for (int idx = 0; idx < mpArr.size(); idx++) {
HashMap secData = mpArr.get(idx);
// Check if necessary data is missing
String pdate = getValueOr(secData, "date", "");
if (pdate.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [pdate]\r\n");
} else if (formatDateStr(pdate).equals(defValD)) {
sbError.append("! Warning: Incompleted record because variable [pdate] with invalid value [").append(pdate).append("]\r\n");
}
if (getValueOr(secData, "plpop", getValueOr(secData, "plpoe", "")).equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plpop] and [plpoe]\r\n");
}
if (getValueOr(secData, "plrs", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plrs]\r\n");
}
// if (getValueOr(secData, "plma", "").equals("")) {
// sbError.append("! Warning: missing data : [plma], and will automatically use default value 'S'\r\n");
// }
// if (getValueOr(secData, "plds", "").equals("")) {
// sbError.append("! Warning: missing data : [plds], and will automatically use default value 'R'\r\n");
// }
// if (getValueOr(secData, "pldp", "").equals("")) {
// sbError.append("! Warning: missing data : [pldp], and will automatically use default value '7'\r\n");
// }
// mm -> cm
String pldp = getValueOr(secData, "pldp", "");
if (!pldp.equals("")) {
try {
BigDecimal pldpBD = new BigDecimal(pldp);
pldpBD = pldpBD.divide(new BigDecimal("10"));
secData.put("pldp", pldpBD.toString());
} catch (NumberFormatException e) {
}
}
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "date", defValD)),
formatDateStr(getValueOr(secData, "edate", defValD)),
formatNumStr(5, secData, "plpop", getValueOr(secData, "plpoe", defValR)),
formatNumStr(5, secData, "plpoe", getValueOr(secData, "plpop", defValR)),
getValueOr(secData, "plma", defValC), // P.S. Set default value as "S"(Cancelled)
getValueOr(secData, "plds", defValC), // P.S. Set default value as "R"(Cancelled)
formatNumStr(5, secData, "plrs", defValR),
formatNumStr(5, secData, "plrd", defValR),
formatNumStr(5, secData, "pldp", defValR), // P.S. Set default value as "7"(Cancelled)
formatNumStr(5, secData, "plmwt", defValR),
formatNumStr(5, secData, "page", defValR),
formatNumStr(5, secData, "plenv", defValR),
formatNumStr(5, secData, "plph", defValR),
formatNumStr(5, secData, "plspl", defValR),
getValueOr(secData, "pl_name", defValC)));
}
sbData.append("\r\n");
} else if (!isFallow) {
sbError.append("! Warning: There is no plainting data in the experiment.\r\n");
}
// IRRIGATION AND WATER MANAGEMENT Section
if (!miArr.isEmpty()) {
sbData.append("*IRRIGATION AND WATER MANAGEMENT\r\n");
for (int idx = 0; idx < miArr.size(); idx++) {
// secData = (ArrayList) miArr.get(idx);
ArrayList<HashMap> subDataArr = miArr.get(idx);
HashMap subData;
if (!subDataArr.isEmpty()) {
subData = subDataArr.get(0);
} else {
subData = new HashMap();
}
sbData.append("@I EFIR IDEP ITHR IEPT IOFF IAME IAMT IRNAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$s\r\n",
idx + 1,
formatNumStr(5, subData, "ireff", defValR),
formatNumStr(5, subData, "irmdp", defValR),
formatNumStr(5, subData, "irthr", defValR),
formatNumStr(5, subData, "irept", defValR),
getValueOr(subData, "irstg", defValC),
getValueOr(subData, "iame", defValC),
formatNumStr(5, subData, "iamt", defValR),
getValueOr(subData, "ir_name", defValC)));
if (!subDataArr.isEmpty()) {
sbData.append("@I IDATE IROP IRVAL\r\n");
}
for (HashMap subDataArr1 : subDataArr) {
subData = subDataArr1;
String brokenMark = "";
if (getValueOr(subData, "date", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$-5s %4$5s\r\n",
idx + 1,
formatDateStr(getValueOr(subData, "date", defValD)), // P.S. idate -> date
getValueOr(subData, "irop", defValC),
formatNumStr(5, subData, "irval", defValR)));
}
}
sbData.append("\r\n");
}
// FERTILIZERS (INORGANIC) Section
if (!mfArr.isEmpty()) {
sbData.append("*FERTILIZERS (INORGANIC)\r\n");
sbData.append("@F FDATE FMCD FACD FDEP FAMN FAMP FAMK FAMC FAMO FOCD FERNAME\r\n");
// String fen_tot = getValueOr(result, "fen_tot", defValR);
// String fep_tot = getValueOr(result, "fep_tot", defValR);
// String fek_tot = getValueOr(result, "fek_tot", defValR);
// String pdate = getPdate(result);
// if (pdate.equals("")) {
// pdate = defValD;
// }
for (int idx = 0; idx < mfArr.size(); idx++) {
ArrayList<HashMap> secDataArr = mfArr.get(idx);
for (HashMap secData : secDataArr) {
// if (getValueOr(secData, "fdate", "").equals("")) {
// sbError.append("! Warning: missing data : [fdate], and will automatically use planting value '").append(pdate).append("'\r\n");
// }
// if (getValueOr(secData, "fecd", "").equals("")) {
// sbError.append("! Warning: missing data : [fecd], and will automatically use default value 'FE001'\r\n");
// }
// if (getValueOr(secData, "feacd", "").equals("")) {
// sbError.append("! Warning: missing data : [feacd], and will automatically use default value 'AP002'\r\n");
// }
// if (getValueOr(secData, "fedep", "").equals("")) {
// sbError.append("! Warning: missing data : [fedep], and will automatically use default value '10'\r\n");
// }
// if (getValueOr(secData, "feamn", "").equals("")) {
// sbError.append("! Warning: missing data : [feamn], and will automatically use the value of FEN_TOT, '").append(fen_tot).append("'\r\n");
// }
// if (getValueOr(secData, "feamp", "").equals("")) {
// sbError.append("! Warning: missing data : [feamp], and will automatically use the value of FEP_TOT, '").append(fep_tot).append("'\r\n");
// }
// if (getValueOr(secData, "feamk", "").equals("")) {
// sbError.append("! Warning: missing data : [feamk], and will automatically use the value of FEK_TOT, '").append(fek_tot).append("'\r\n");
// }
String brokenMark = "";
if (getValueOr(secData, "date", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "date", defValD)), // P.S. fdate -> date
getValueOr(secData, "fecd", defValC), // P.S. Set default value as "FE005"(Cancelled)
getValueOr(secData, "feacd", defValC), // P.S. Set default value as "AP002"(Cancelled)
formatNumStr(5, secData, "fedep", defValR), // P.S. Set default value as "10"(Cancelled)
formatNumStr(5, secData, "feamn", "0"), // P.S. Set default value to use 0 instead of -99
formatNumStr(5, secData, "feamp", defValR), // P.S. Set default value to use the value of FEP_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamk", defValR), // P.S. Set default value to use the value of FEK_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamc", defValR),
formatNumStr(5, secData, "feamo", defValR),
getValueOr(secData, "feocd", defValC),
getValueOr(secData, "fe_name", defValC)));
}
}
sbData.append("\r\n");
}
// RESIDUES AND ORGANIC FERTILIZER Section
if (!mrArr.isEmpty()) {
sbData.append("*RESIDUES AND ORGANIC FERTILIZER\r\n");
sbData.append("@R RDATE RCOD RAMT RESN RESP RESK RINP RDEP RMET RENAME\r\n");
for (int idx = 0; idx < mrArr.size(); idx++) {
ArrayList<HashMap> secDataArr = mrArr.get(idx);
for (HashMap secData : secDataArr) {
String brokenMark = "";
if (getValueOr(secData, "date", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$-5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "date", defValD)), // P.S. omdat -> date
getValueOr(secData, "omcd", defValC),
formatNumStr(5, secData, "omamt", defValR),
formatNumStr(5, secData, "omn%", defValR),
formatNumStr(5, secData, "omp%", defValR),
formatNumStr(5, secData, "omk%", defValR),
formatNumStr(5, secData, "ominp", defValR),
formatNumStr(5, secData, "omdep", defValR),
formatNumStr(5, secData, "omacd", defValR),
getValueOr(secData, "om_name", defValC)));
}
}
sbData.append("\r\n");
}
// CHEMICAL APPLICATIONS Section
if (!mcArr.isEmpty()) {
sbData.append("*CHEMICAL APPLICATIONS\r\n");
sbData.append("@C CDATE CHCOD CHAMT CHME CHDEP CHT..CHNAME\r\n");
for (int idx = 0; idx < mcArr.size(); idx++) {
ArrayList<HashMap> secDataArr = mcArr.get(idx);
for (HashMap secData : secDataArr) {
String brokenMark = "";
if (getValueOr(secData, "date", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "date", defValD)), // P.S. cdate -> date
getValueOr(secData, "chcd", defValC),
formatNumStr(5, secData, "chamt", defValR),
getValueOr(secData, "chacd", defValC),
getValueOr(secData, "chdep", defValC),
getValueOr(secData, "ch_targets", defValC),
getValueOr(secData, "ch_name", defValC)));
}
}
sbData.append("\r\n");
}
// TILLAGE Section
if (!mtArr.isEmpty()) {
sbData.append("*TILLAGE AND ROTATIONS\r\n");
sbData.append("@T TDATE TIMPL TDEP TNAME\r\n");
for (int idx = 0; idx < mtArr.size(); idx++) {
ArrayList<HashMap> secDataArr = mtArr.get(idx);
for (HashMap secData : secDataArr) {
String brokenMark = "";
if (getValueOr(secData, "date", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$5s %4$5s %5$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "date", defValD)), // P.S. tdate -> date
getValueOr(secData, "tiimp", defValC),
formatNumStr(5, secData, "tidep", defValR),
getValueOr(secData, "ti_name", defValC)));
}
}
sbData.append("\r\n");
}
// ENVIRONMENT MODIFICATIONS Section
if (!meArr.isEmpty()) {
sbData.append("*ENVIRONMENT MODIFICATIONS\r\n");
sbData.append("@E ODATE EDAY ERAD EMAX EMIN ERAIN ECO2 EDEW EWIND ENVNAME\r\n");
for (int idx = 0, cnt = 1; idx < meArr.size(); idx++) {
ArrayList<HashMap> secDataArr = meArr.get(idx);
for (HashMap secData : secDataArr) {
if (secData.containsKey("em_data")) {
sbData.append(String.format("%1$2s %2$s\r\n",
cnt,
getValueOr(secData, "em_data", "").trim()));
} else {
String brokenMark = "";
if (getValueOr(secData, "date", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$-1s%4$4s %5$-1s%6$4s %7$-1s%8$4s %9$-1s%10$4s %11$-1s%12$4s %13$-1s%14$4s %15$-1s%16$4s %17$-1s%18$4s %19$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "date", defValD)), // P.S. emday -> date
getValueOr(secData, "ecdyl", "A"),
formatNumStr(4, secData, "emdyl", "0"),
getValueOr(secData, "ecrad", "A"),
formatNumStr(4, secData, "emrad", "0"),
getValueOr(secData, "ecmax", "A"),
formatNumStr(4, secData, "emmax", "0"),
getValueOr(secData, "ecmin", "A"),
formatNumStr(4, secData, "emmin", "0"),
getValueOr(secData, "ecrai", "A"),
formatNumStr(4, secData, "emrai", "0"),
getValueOr(secData, "ecco2", "A"),
formatNumStr(4, secData, "emco2", "0"),
getValueOr(secData, "ecdew", "A"),
formatNumStr(4, secData, "emdew", "0"),
getValueOr(secData, "ecwnd", "A"),
formatNumStr(4, secData, "emwnd", "0"),
getValueOr(secData, "em_name", defValC)));
}
}
}
sbData.append("\r\n");
}
// HARVEST DETAILS Section
if (!mhArr.isEmpty()) {
sbData.append("*HARVEST DETAILS\r\n");
sbData.append("@H HDATE HSTG HCOM HSIZE HPC HBPC HNAME\r\n");
for (int idx = 0; idx < mhArr.size(); idx++) {
ArrayList<HashMap> secDataArr = mhArr.get(idx);
for (HashMap secData : secDataArr) {
String brokenMark = "";
if (getValueOr(secData, "date", defValD).equals(defValD)) {
brokenMark = "!";
}
sbData.append(brokenMark).append(String.format("%1$2s %2$5s %3$-5s %4$-5s %5$-5s %6$5s %7$5s %8$s\r\n",
idx + 1,
formatDateStr(getValueOr(secData, "date", defValD)), // P.S. hdate -> date
getValueOr(secData, "hastg", defValC),
getValueOr(secData, "hacom", defValC),
getValueOr(secData, "hasiz", defValC),
formatNumStr(5, secData, "hap%", defValR),
formatNumStr(5, secData, "hab%", defValR),
getValueOr(secData, "ha_name", defValC)));
}
}
sbData.append("\r\n");
}
// SIMULATION CONTROLS and AUTOMATIC MANAGEMENT Section
if (!smArr.isEmpty()) {
// Loop all the simulation control records
sbData.append("*SIMULATION CONTROLS\r\n");
for (int idx = 0; idx < smArr.size(); idx++) {
HashMap secData = smArr.get(idx);
sbData.append(createSMMAStr(idx + 1, secData));
}
} else {
sbData.append("*SIMULATION CONTROLS\r\n");
sbData.append(createSMMAStr(1, new HashMap()));
}
// DOME Info Section
if (isAnyDomeApplied) {
sbDomeData.append("! APPLIED DOME INFO\r\n");
for (String exname : appliedDomes.keySet()) {
if (!getValueOr(appliedDomes, exname, "").equals("")) {
sbDomeData.append("! ").append(exname).append("\t");
sbDomeData.append(appliedDomes.get(exname));
sbDomeData.append("\r\n");
}
}
sbDomeData.append("\r\n");
}
// Output finish
bwX.write(sbError.toString());
bwX.write(sbDomeData.toString());
bwX.write(sbGenData.toString());
bwX.write(sbNotesData.toString());
bwX.write(sbData.toString());
bwX.close();
} catch (IOException e) {
LOG.error(DssatCommonOutput.getStackTrace(e));
}
}
/**
* Create string of Simulation Control and Automatic Management Section
*
* @param smid simulation index number
* @param trData date holder for one treatment data
* @return date string with format of "yyddd"
*/
private String createSMMAStr(int smid, HashMap trData) {
StringBuilder sb = new StringBuilder();
String nitro = "Y";
String water = "Y";
String co2 = "M";
String harOpt = "M";
String sdate;
String sm = String.format("%2d", smid);
// ArrayList<HashMap> dataArr;
HashMap subData;
// // Check if the meta data of fertilizer is not "N" ("Y" or null)
// if (!getValueOr(expData, "fertilizer", "").equals("N")) {
//
// // Check if necessary data is missing in all the event records
// // P.S. rule changed since all the necessary data has a default value for it
// dataArr = getObjectOr(trData, "fertilizer", new ArrayList());
// if (dataArr.isEmpty()) {
// nitro = "N";
// }
//// for (int i = 0; i < dataArr.size(); i++) {
//// subData = dataArr.get(i);
//// if (getValueOr(subData, "date", "").equals("")
//// || getValueOr(subData, "fecd", "").equals("")
//// || getValueOr(subData, "feacd", "").equals("")
//// || getValueOr(subData, "feamn", "").equals("")) {
//// nitro = "N";
//// break;
//// }
//// }
// }
// // Check if the meta data of irrigation is not "N" ("Y" or null)
// if (!getValueOr(expData, "irrigation", "").equals("N")) {
//
// // Check if necessary data is missing in all the event records
// dataArr = getObjectOr(trData, "irrigation", new ArrayList());
// for (int i = 0; i < dataArr.size(); i++) {
// subData = dataArr.get(i);
// if (getValueOr(subData, "date", "").equals("")
// || getValueOr(subData, "irval", "").equals("")) {
// water = "N";
// break;
// }
// }
// }
// Check if CO2Y value is provided and the value is positive, then set CO2 switch to W
String co2y = getValueOr(trData, "co2y", "").trim();
if (!co2y.equals("") && !co2y.startsWith("-")) {
co2 = "W";
}
sdate = getValueOr(trData, "sdat", "");
if (sdate.equals("")) {
subData = getObjectOr(trData, "planting", new HashMap());
sdate = getValueOr(subData, "date", defValD);
}
sdate = formatDateStr(sdate);
sdate = String.format("%5s", sdate);
if (!getValueOr(trData, "hadat_valid", "").trim().equals("")) {
harOpt = "R";
}
String smStr;
HashMap smData;
// GENERAL
sb.append("@N GENERAL NYERS NREPS START SDATE RSEED SNAME.................... SMODEL\r\n");
if (!(smStr = getValueOr(trData, "sm_general", "")).equals("")) {
if (!sdate.trim().equals("-99") && !sdate.trim().equals("")) {
smStr = replaceSMStr(smStr, sdate, 30);
}
smStr = replaceSMStr(smStr, getValueOr(trData, "dssat_model", ""), 68);
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "general", new HashMap())).isEmpty()) {
if (sdate.trim().equals("-99") || sdate.trim().equals("")) {
sdate = String.format("%1$02d%2$03d", Integer.parseInt(formatNumStr(2, smData, "sdyer", "0").trim()), Integer.parseInt(formatNumStr(3, smData, "sdday", "0").trim()));
}
sb.append(String.format("%1$2s %2$-11s %3$5s %4$5s %5$-1s %6$5s %7$5s %8$-25s %9$s\r\n",
sm,
"GE",
getValueOr(smData, "nyers", "1"),
getValueOr(smData, "nreps", "1"),
getValueOr(smData, "start", "S"),
sdate,
getValueOr(smData, "rseed", "250"),
getValueOr(smData, "sname", defValC),
getValueOr(trData, "dssat_model", getValueOr(smData, "model", ""))));
} else {
sb.append(sm).append(" GE 1 1 S ").append(sdate).append(" 2150 DEFAULT SIMULATION CONTRL ").append(getValueOr(trData, "dssat_model", "")).append("\r\n");
}
// OPTIONS
sb.append("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n");
if (!(smStr = getValueOr(trData, "sm_options", "")).equals("")) {
// smStr = replaceSMStr(smStr, co2, 64);
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "options", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$-1s %4$-1s %5$-1s %6$-1s %7$-1s %8$-1s %9$-1s %10$-1s %11$-1s\r\n",
sm,
"OP",
getValueOr(smData, "water", water),
getValueOr(smData, "nitro", nitro),
getValueOr(smData, "symbi", "Y"),
getValueOr(smData, "phosp", "N"),
getValueOr(smData, "potas", "N"),
getValueOr(smData, "dises", "N"),
getValueOr(smData, "chem", "N"),
getValueOr(smData, "till", "Y"),
getValueOr(smData, "co2", co2)));
} else {
sb.append(sm).append(" OP ").append(water).append(" ").append(nitro).append(" Y N N N N Y ").append(co2).append("\r\n");
}
// METHODS
sb.append("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n");
if (!(smStr = getValueOr(trData, "sm_methods", "")).equals("")) {
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "methods", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$-1s %4$-1s %5$-1s %6$-1s %7$-1s %8$-1s %9$-1s %10$-1s %11$-1s %12$-1s %13$-1s\r\n",
sm,
"ME",
getValueOr(smData, "wther", "M"),
getValueOr(smData, "incon", "M"),
getValueOr(smData, "light", "E"),
getValueOr(smData, "evapo", "R"),
getValueOr(smData, "infil", "S"),
getValueOr(smData, "photo", "L"),
getValueOr(smData, "hydro", "R"),
getValueOr(smData, "nswit", "1"),
getValueOr(smData, "mesom", "P"),
getValueOr(smData, "mesev", "S"),
getValueOr(smData, "mesol", "2")));
} else {
sb.append(sm).append(" ME M M E R S L R 1 P S 2\r\n"); // P.S. 2012/09/02 MESOM "G" -> "P"
}
// MANAGEMENT
sb.append("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n");
if (!(smStr = getValueOr(trData, "sm_management", "")).equals("")) {
// smStr = smStr.replaceAll(" D", " R");
// smStr = replaceSMStr(smStr, harOpt, 40);
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "management", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$-1s %4$-1s %5$-1s %6$-1s %7$-1s\r\n",
sm,
"MA",
getValueOr(smData, "plant", "R"),
getValueOr(smData, "irrig", "R"),
getValueOr(smData, "ferti", "R"),
getValueOr(smData, "resid", "R"),
getValueOr(smData, "harvs", harOpt)));
} else {
sb.append(sm).append(" MA R R R R ").append(harOpt).append("\r\n");
}
// OUTPUTS
sb.append("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n");
if (!(smStr = getValueOr(trData, "sm_outputs", "")).equals("")) {
sb.append(sm).append(" ").append(smStr).append("\r\n\r\n");
} else if (!(smData = getObjectOr(trData, "outputs", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$-1s %4$-1s %5$-1s %6$5s %7$-1s %8$-1s %9$-1s %10$-1s %11$-1s %12$-1s %13$-1s %14$-1s %15$-1s\r\n\r\n",
sm,
"OU",
getValueOr(smData, "fname", "N"),
getValueOr(smData, "ovvew", "Y"),
getValueOr(smData, "sumry", "Y"),
getValueOr(smData, "fropt", "1"),
getValueOr(smData, "grout", "Y"),
getValueOr(smData, "caout", "Y"),
getValueOr(smData, "waout", "N"),
getValueOr(smData, "niout", "N"),
getValueOr(smData, "miout", "N"),
getValueOr(smData, "diout", "N"),
getValueOr(smData, "vbose", "N"),
getValueOr(smData, "chout", "N"),
getValueOr(smData, "opout", "N")));
} else {
sb.append(sm).append(" OU N Y Y 1 Y Y N N N N N N N\r\n\r\n");
}
// PLANTING
sb.append("@ AUTOMATIC MANAGEMENT\r\n");
sb.append("@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n");
if (!(smStr = getValueOr(trData, "sm_planting", "")).equals("")) {
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "planting", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$02d%4$03d %5$02d%6$03d %7$5s %8$5s %9$5s %10$5s %11$5s\r\n",
sm,
"PL",
Integer.parseInt(formatNumStr(2, smData, "pfyer", "82")),
Integer.parseInt(formatNumStr(3, smData, "pfday", "050")),
Integer.parseInt(formatNumStr(2, smData, "plyer", "82")),
Integer.parseInt(formatNumStr(3, smData, "plday", "064")),
getValueOr(smData, "ph2ol", "40"),
getValueOr(smData, "ph2ou", "100"),
getValueOr(smData, "ph2od", "30"),
getValueOr(smData, "pstmx", "40"),
getValueOr(smData, "pstmn", "10")));
} else {
sb.append(sm).append(" PL 82050 82064 40 100 30 40 10\r\n");
}
// IRRIGATION
sb.append("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n");
if (!(smStr = getValueOr(trData, "sm_irrigation", "")).equals("")) {
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "irrigation", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$5s %4$5s %5$5s %6$-5s %7$-5s %8$5s %9$5s\r\n",
sm,
"IR",
getValueOr(smData, "imdep", "30"),
getValueOr(smData, "ithrl", "50"),
getValueOr(smData, "ithru", "100"),
getValueOr(smData, "iroff", "GS000"),
getValueOr(smData, "imeth", "IR001"),
getValueOr(smData, "iramt", "10"),
getValueOr(smData, "ireff", "1.00")));
} else {
sb.append(sm).append(" IR 30 50 100 GS000 IR001 10 1.00\r\n");
}
// NITROGEN
sb.append("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n");
if (!(smStr = getValueOr(trData, "sm_nitrogen", "")).equals("")) {
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "nitrogen", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$5s %4$5s %5$5s %6$-5s %7$-5s\r\n",
sm,
"NI",
getValueOr(smData, "nmdep", "30"),
getValueOr(smData, "nmthr", "50"),
getValueOr(smData, "namnt", "25"),
getValueOr(smData, "ncode", "FE001"),
getValueOr(smData, "naoff", "GS000")));
} else {
sb.append(sm).append(" NI 30 50 25 FE001 GS000\r\n");
}
// RESIDUES
sb.append("@N RESIDUES RIPCN RTIME RIDEP\r\n");
if (!(smStr = getValueOr(trData, "sm_residues", "")).equals("")) {
sb.append(sm).append(" ").append(smStr).append("\r\n");
} else if (!(smData = getObjectOr(trData, "residues", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$5s %4$5s %5$5s\r\n",
sm,
"RE",
getValueOr(smData, "ripcn", "100"),
getValueOr(smData, "rtime", "1"),
getValueOr(smData, "ridep", "20")));
} else {
sb.append(sm).append(" RE 100 1 20\r\n");
}
// HARVEST
sb.append("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n");
if (!(smStr = getValueOr(trData, "sm_harvests", "")).equals("")) {
sb.append(sm).append(" ").append(smStr).append("\r\n\r\n");
} else if (!(smData = getObjectOr(trData, "harvests", new HashMap())).isEmpty()) {
sb.append(String.format("%1$2s %2$-11s %3$5s %4$02d%5$03d %6$5s %7$5s\r\n\r\n",
sm,
"HA",
getValueOr(smData, "hfrst", "0"),
Integer.parseInt(formatNumStr(2, smData, "hlyer", "83")),
Integer.parseInt(formatNumStr(3, smData, "hlday", "057")),
getValueOr(smData, "hpcnp", "100"),
getValueOr(smData, "hpcnr", "0")));
} else {
sb.append(sm).append(" HA 0 83057 100 0\r\n\r\n");
}
return sb.toString();
}
/**
* Get index value of the record and set new id value in the array.
* In addition, it will check if the event date is available. If not, then
* return 0.
*
* @param m sub data
* @param arr array of sub data
* @return current index value of the sub data
*/
private int setSecDataArr(HashMap m, ArrayList arr, boolean isEvent) {
int idx = setSecDataArr(m, arr);
if (idx != 0 && isEvent && getValueOr(m, "date", "").equals("")) {
return -1;
} else {
return idx;
}
}
/**
* Get index value of the record and set new id value in the array
*
* @param m sub data
* @param arr array of sub data
* @return current index value of the sub data
*/
private int setSecDataArr(HashMap m, ArrayList arr) {
if (!m.isEmpty()) {
for (int j = 0; j < arr.size(); j++) {
if (arr.get(j).equals(m)) {
return j + 1;
}
}
arr.add(m);
return arr.size();
} else {
return 0;
}
}
private int setSecDataArr(ArrayList inArr, ArrayList outArr, boolean isEvent) {
int idx = setSecDataArr(inArr, outArr);
if (idx != 0 && isEvent && !checkEventDate(inArr)) {
return -1;
} else {
return idx;
}
}
private boolean checkEventDate(ArrayList arr) {
for (Object o : arr) {
if (getValueOr((HashMap) o, "date", "").equals("")) {
return false;
}
}
return true;
}
/**
* Get index value of the record and set new id value in the array
*
* @param inArr sub array of data
* @param outArr array of sub data
* @return current index value of the sub data
*/
private int setSecDataArr(ArrayList inArr, ArrayList outArr) {
if (!inArr.isEmpty()) {
for (int j = 0; j < outArr.size(); j++) {
if (outArr.get(j).equals(inArr)) {
return j + 1;
}
}
outArr.add(inArr);
return outArr.size();
} else {
return 0;
}
}
/**
* To check if there is plot info data existed in the experiment
*
* @param expData experiment data holder
* @return the boolean value for if plot info exists
*/
private boolean isPlotInfoExist(Map expData) {
String[] plotIds = {"plta", "pltr#", "pltln", "pldr", "pltsp", "pllay", "pltha", "plth#", "plthl", "plthm"};
for (String plotId : plotIds) {
if (!getValueOr(expData, plotId, "").equals("")) {
return true;
}
}
return false;
}
/**
* To check if there is soil analysis info data existed in the experiment
*
* @param expData initial condition layer data array
* @return the boolean value for if soil analysis info exists
*/
private boolean isSoilAnalysisExist(ArrayList<HashMap> icSubArr) {
for (HashMap icSubData : icSubArr) {
if (!getValueOr(icSubData, "slsc", "").equals("")) {
return true;
}
}
return false;
}
/**
* Get sub data array from experiment data object
*
* @param expData experiment data holder
* @param blockName top level block name
* @param dataListName sub array name
* @return sub data array
*/
private ArrayList<HashMap> getDataList(Map expData, String blockName, String dataListName) {
HashMap dataBlock = getObjectOr(expData, blockName, new HashMap());
return getObjectOr(dataBlock, dataListName, new ArrayList<HashMap>());
}
/**
* Try to translate 3-bit CRID to 2-bit version stored in the map
*
* @param cuData the cultivar data record
* @param id the field id for contain crop id info
* @param defVal the default value when id is not available
* @return 2-bit crop ID
*/
private String translateTo2BitCrid(Map cuData, String id, String defVal) {
String crid = getValueOr(cuData, id, "");
if (!crid.equals("")) {
return DssatCRIDHelper.get2BitCrid(crid);
} else {
return defVal;
}
}
/**
* Try to translate 3-bit CRID to 2-bit version stored in the map
*
* @param cuData the cultivar data record
*/
private void translateTo2BitCrid(Map cuData) {
String crid = getValueOr(cuData, "crid", "");
if (!crid.equals("")) {
cuData.put("crid", DssatCRIDHelper.get2BitCrid(crid));
}
}
/**
* Get soil/weather data from data holder
*
* @param expData The experiment data holder
* @param key The key name for soil/weather section
* @return the list of data holder
*/
private ArrayList readSWData(HashMap expData, String key) {
ArrayList ret;
Object soil = expData.get(key);
if (soil != null) {
if (soil instanceof ArrayList) {
ret = (ArrayList) soil;
} else {
ret = new ArrayList();
ret.add(soil);
}
} else {
ret = new ArrayList();
}
return ret;
}
private String replaceSMStr(String smStr, String val, int start) {
if (smStr.length() < start) {
smStr = String.format("%-" + start + "s", smStr);
}
smStr = smStr.substring(0, start)
+ val
+ smStr.substring(start + val.length());
return smStr;
}
private String getAppliedDomes(HashMap data, String domeType) {
if (getValueOr(data, domeType + "_dome_applied", "").equals("Y")) {
// Get dome ids
String domeKey = "";
if (domeType.equals("field")) {
domeKey = "field_overlay";
} else if (domeType.equals("seasonal")) {
domeKey = "seasonal_strategy";
}
String[] domeIds = getValueOr(data, domeKey, "").split("[|]");
String[] failedDomeIds = getValueOr(data, domeType + "_dome_failed", "").split("[|]");
HashSet<String> domes = new HashSet();
// Add all dome ids
for (String domeId : domeIds) {
if (!domeId.equals("")) {
domes.add(domeId);
}
}
// Remove failed dome id
for (String failedDomeId : failedDomeIds) {
if (!failedDomeId.equals("")) {
domes.remove(failedDomeId);
}
}
// Convert to string format, divide by "|"
StringBuilder ret = new StringBuilder();
String[] domeArr = domes.toArray(new String[0]);
if (domeArr.length > 0) {
ret.append(domeArr[0]);
}
for (int i = 1; i < domeArr.length; i++) {
ret.append("|").append(domeArr[i]);
}
return ret.toString();
} else {
return "";
}
}
}
|
set simulation control VBOSE default value from N to 0
|
src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java
|
set simulation control VBOSE default value from N to 0
|
<ide><path>rc/main/java/org/agmip/translators/dssat/DssatXFileOutput.java
<ide> getValueOr(smData, "niout", "N"),
<ide> getValueOr(smData, "miout", "N"),
<ide> getValueOr(smData, "diout", "N"),
<del> getValueOr(smData, "vbose", "N"),
<add> getValueOr(smData, "vbose", "0"),
<ide> getValueOr(smData, "chout", "N"),
<ide> getValueOr(smData, "opout", "N")));
<ide> } else {
<del> sb.append(sm).append(" OU N Y Y 1 Y Y N N N N N N N\r\n\r\n");
<add> sb.append(sm).append(" OU N Y Y 1 Y Y N N N N 0 N N\r\n\r\n");
<ide> }
<ide> // PLANTING
<ide> sb.append("@ AUTOMATIC MANAGEMENT\r\n");
|
|
JavaScript
|
mit
|
1d38799ef0ff4e4b73b70a8e7f11e45bff7cc794
| 0 |
vlvical/vlv.ical,vlvical/vlv.ical
|
function updateSelectionBox() {
var itemBox = $('#itemBox')[0];
itemBox.innerHTML = '<br>';
try {
var items = load('selection');
for (var i = 0; i < items.length; i++) {
var item = load(items[i]);
var element = $('<button id="' +
item.id +
'" class="selectionBoxItem">' +
item.name +
'</button>');
var removeButton = $('<button name="'+ item.id +
'" class="cd-item-remove cd-img-replace">Entfernen</button>');
element.insertBefore($('#itemBox')[0].childNodes[i]);
/* Wrap element inside li to apply styles to row */
$(element).wrap('<li></li>');
(element).after(removeButton);
/* highlight element, if it was changed through edit dialog */
if (item.changed) {
$(element).parent().addClass('item-edited');
$(element).append('<br> <em class="small text-muted">- Das Element wurde bearbeitet</em>');
}
$(element).on('click', function() {
openEditDialog(this.id);
});
}
// Delete a chosen Object
var id = null;
$('#itemBox li .cd-item-remove').on('click', function() {
id = this.name;
var item = load(id);
removeFromCart(item);
});
} catch(e) {
console.log("Could not update selection.");
console.log(e);
}
}
function openBox() {
var open = $('#openSelectionBox')[0];
$(open).hide("slide");
var box = $('#selectionBox')[0];
$(box).show("slide");
}
function closeBox() {
var open = $('#openSelectionBox')[0];
$(open).show("slide");
var box = $('#selectionBox')[0];
$(box).hide("slide");
}
function clearSelectionBox() {
var selection = load('selection');
selection = [];
saveObjects('selection', selection);
updateSelection();
}
|
chrome_plugin/js/inject/selectionBox.js
|
function updateSelectionBox() {
var itemBox = $('#itemBox')[0];
itemBox.innerHTML = '<br>';
try {
var items = load('selection');
for (var i = 0; i < items.length; i++) {
var item = load(items[i]);
var element = $('<button id="' +
item.id +
'" class="selectionBoxItem">' +
item.name +
'</button>');
var removeButton = $('<button name="'+ item.id +
'" class="cd-item-remove cd-img-replace">Entfernen</button>');
element.insertBefore($('#itemBox')[0].childNodes[i]);
/* Wrap element inside li to apply styles to row */
$(element).wrap('<li></li>');
(element).after(removeButton);
/* highlight element, if it was changed through edit dialog */
if (item.changed) {
$(element).parent().addClass('item-edited');
$(element).append('<br> <em class="small text-muted">- Das Element wurde bearbeitet</em>');
}
$(element).on('click', function() {
openEditDialog(this.id);
});
}
// Delete a chosen Object
var id = null;
$('#itemBox li .cd-item-remove').on('click', function() {
id = this.name;
var item = load(id);
removeFromCart(item);
});
} catch(e) {
console.log("Could not update selection.");
console.log(e);
}
}
function openEditDialog(id) {
var data = load(id);
var date,
begin,
end,
type,
repeat,
index;
/*
* Inject Table into DOM
*/
var table = '<table id="editItemTable" class="table table-hover">' +
'<thead><tr><th>#</th><th>Typ</th><th>Datum</th><th>Uhrzeit</th><th>Wiederholung</th></tr></thead>' +
'<tbody id="editTableBody"></tbody></table> ';
$('#formArea').append(table);
/*
* Iterate over Objects of an Event
*/
for (var i = 0; i < data.objects.length; i++) {
/*
* Check if begin is an Array,
* If True, Event could have multiple dates
* If False, Event is unique
*/
if(Array.isArray(data.objects[i].begin)){
var length = data.objects[i].begin.length;
for (var j = 0; j < length; j++) {
date = data.objects[i].begin[j].slice(6, 8) + '.' + data.objects[i].begin[j].slice(4, 6) + '.' + data.objects[i].begin[j].slice(0, 4);
begin = data.objects[i].begin[j].slice(9, 11) + ':' + data.objects[i].begin[j].slice(11, 13);
end = data.objects[i].end[j].slice(9, 11) + ':' + data.objects[i].end[j].slice(11, 13);
type = data.objects[i].type;
repeat = data.objects[i].weekly;
var row = '<tr><th scope="row">' + (i + 1) + '</th>' +
'<td>' + type + '</td>' +
'<td>' + date + '</td>' +
'<td>' + begin + ' - ' + end + '</td>' +
'<td>' + repeat + ' Wöchentlich</td></tr>';
$('#editTableBody').append(row);
}
} else {
date = data.objects[i].begin.slice(6, 8) + '.' + data.objects[i].begin.slice(4, 6) + '.' + data.objects[i].begin.slice(0, 4);
begin = data.objects[i].begin.slice(9, 11) + ':' + data.objects[i].begin.slice(11, 13);
end = data.objects[i].end.slice(9, 11) + ':' + data.objects[i].end.slice(11, 13);
type = data.objects[i].type;
var row = '<tr><th scope="row">' + (i + 1) + '</th>' +
'<td>' + type + '</td>' +
'<td>' + date + '</td>' +
'<td>' + begin + ' - ' + end + '</td>' +
'<td>Einmalig</td></tr>';
$('#editTableBody').append(row);
}
};
/*
* Color the clicked Table Row
* Fetch the # Number of the corresponding Row
* Save it into {int} index
*/
$('#editTableBody tr').on('click', function(){
$('tr').each(function(){ // this might be bad, need to reconsider
$(this).removeClass('success');
});
$(this).addClass('success');
index = parseInt($(this).find('th').text()) - 1;
});
bootbox.dialog({
title: data.origName,
message: $('#editItemTable'),
buttons: {
success: {
label: "Bearbeiten",
className: "btn-success",
callback: function () {
try {
if (data.objects[index] !== undefined) {
var begin = data.objects[index].begin;
console.log(data);
if(Array.isArray(begin)) {
openEditDialogDetailMulti(id, index);
} else {
openEditDialogDetail(id, index);
}
} else {
toastr.info("Es wurde kein Termin ausgewählt.");
return false;
}
} catch(e) {
toastr.error(e, 'Fehler');
return false;
}
}
}
},
keyboard: false
}
);
}
function openEditDialogDetailMulti(id, index) {
var data = load(id);
var i = index;
var date = [],
begin = [],
end = [];
$('body').css('overflow', 'hidden'); // hide body
var length = data.objects[i].begin.length;
for (var j = 0; j < length; j++) {
date.push(data.objects[i].begin[j].slice(0, 4) + '-' + data.objects[i].begin[j].slice(4, 6) + '-' + data.objects[i].begin[j].slice(6, 8));
begin.push(data.objects[i].begin[j].slice(9, 11) + ':' + data.objects[i].begin[j].slice(11, 13));
end.push(data.objects[i].end[j].slice(9, 11) + ':' + data.objects[i].end[j].slice(11, 13));
}
// assign the values of the object
$('#editMultiId').val( id );
$('#multiName').val( data.objects[i].name );
$('#multiLocation').val( data.objects[i].location );
$('#multiComment').val( data.objects[i].comment );
// assign the values of the object
$('#editMultiId').val( id );
var theName = $('#multiName').val( data.objects[i].name );
var theLocation = $('#multiLocation').val( data.objects[i].location );
var theComment = $('#multiComment').val( data.objects[i].comment );
// get initial values for reseting
var oldName = theName.val();
var oldLocation = theLocation.val();
var oldComment = theComment.val();
var origForm = $('#editFormMulti'); // Copy of the Form before Edit
var clonedForm = null; // Holds the edited Form
for (var j = 0; j < length; j++) {
var addedInputs = '<div class="panel panel-default">' +
'<div class="panel-heading">Zeitraum '+ (j + 1) +'</div>' +
'<div class="panel-body">' +
'<div class="form-group">' +
'<label for="date'+ j +'">Startdatum für Zeitraum '+ (j + 1) +'</label>' +
'<input id="multiDate'+ j +'" name="date'+ j +'" type="date" class="form-control input-md">' +
'</div>' +
'<div class="form-group">' +
'<label for="begin'+ j +'">Beginn</label>' +
'<input id="multiBeginTime'+ j +'" name="begin'+ j +'" type="time" class="form-control input-md">' +
'</div>' +
'<div class="form-group">' +
'<label for="end'+ j +'">Ende</label>' +
'<input id="multiEndTime'+ j +'" name="end'+ j +'" type="time" class="form-control input-md">' +
'</div>' +
'</div>' +
'</div>';
$('.form-group #multiRepeat').parent().before(addedInputs);
$('#multiDate' + j).val( date[j] );
$('#multiBeginTime' + j).val( begin[j] );
$('#multiEndTime' + j).val( end[j] );
}
var theRepeat = $('#multiRepeat').val( data.objects[i].weekly );
var oldRepeat = theRepeat.val();
bootbox.dialog({
title: data.origName,
message: $('#editFormMulti'),
backdrop: true,
closeButton: false,
buttons: {
success: {
label: "Speichern",
className: "btn-success",
callback: function () {
var i = index;
try {
var id = $('#editMultiId')[0].value;
var data = load(id);
} catch (e) {
$('#formArea div:nth-child(2)').prepend(origForm);
toastr.error(e, 'Fehler');
}
try {
data.objects[i].name = isEmpty($('#multiName').val());
data.objects[i].location = isEmpty($('#multiLocation').val());
data.objects[i].comment = isEmpty($('#multiComment').val());
data.objects[i].weekly = isEmpty($('#multiRepeat').val());
var date = [],
beginTime = [],
endTime = [];
for (var j = 0; j < length; j++) {
date.push(isEmpty($('#multiDate' + j)[0].value));
date[j] = date[j].split("-").join('');
beginTime.push(isEmpty($('#multiBeginTime' + j)[0].value));
beginTime[j] = beginTime[j].slice(0, 2) + beginTime[j].slice(3, 5) + '00';
endTime.push(isEmpty($('#multiEndTime' + j)[0].value));
endTime[j] = endTime[j].slice(0, 2) + endTime[j].slice(3, 5) + '00';
data.objects[i].begin[j] = date[j] + 'T' + beginTime[j];
data.objects[i].end[j] = date[j] + 'T' + endTime[j];
}
clonedForm = $('#editFormMulti');
} catch(e) {
console.error(e.name+": "+e.message);
toastr.error(e, 'Fehler');
return false; // Prevent the Modal from closing
}
try {
for (var j = 0; j < length; j++) {
$('.panel-default').empty();
$('.panel-default').remove();
}
$('#formArea div:nth-child(2)').prepend(clonedForm);
if (JSON.stringify(load(id)).localeCompare(JSON.stringify(data)) != 0) {
data.changed = true;
}
save(id, data);
} catch(e) {
for (var j = 0; j < length; j++) {
$('.panel-default').empty();
$('.panel-default').remove();
}
$('#formArea div:nth-child(2)').prepend(origForm);
toastr.error(e, 'Fehler');
}
updateSelectionBox();
$('body').css('overflow', 'auto');
}
},
cancel: {
label: "Abbrechen",
className: "btn-danger",
callback: function(){
try {
for (var j = 0; j < length; j++) {
$('.panel-default').empty();
$('.panel-default').remove();
}
$('body').css('overflow', 'auto');
$('#formArea div:nth-child(2)').prepend(origForm);
} catch(e) {
console.log(e);
}
}
},
reset: {
label: "Zurücksetzen",
className: "btn-primary pull-left",
callback: function() {
try {
$('#editName').val( oldName );
$('#editLocation').val( oldLocation);
$('#editComment').val( oldComment);
$('#editDate').val( oldDate );
$('#editBeginTime').val( oldBegin );
$('#editEndTime').val( oldEnd );
$('#editRepeat').val( oldRepeat );
return false;
} catch (e) {
console.log(e);
}
}
},
reset: {
label: "Zurücksetzen",
className: "btn-primary pull-left",
callback: function() {
try {
$('#multiName').val( oldName );
$('#multiLocation').val( oldLocation);
$('#multiComment').val( oldComment);
for (var j = 0; j < length; j++) {
$('#multiDate' + j).val( date[j] );
$('#multiBeginTime' + j).val( begin[j] );
$('#multiEndTime' + j).val( end[j] );
}
$('#multiRepeat').val( oldRepeat );
return false;
} catch (e) {
console.log(e);
}
}
}
},
keyboard: false
}
);
}
function openEditDialogDetail(id, index) {
var data = load(id);
var i = index;
$('body').css('overflow', 'hidden');
var date = data.objects[i].begin.slice(0, 4) + '-' + data.objects[i].begin.slice(4, 6) + '-' + data.objects[i].begin.slice(6, 8);
var begin = data.objects[i].begin.slice(9, 11) + ':' + data.objects[i].begin.slice(11, 13);
var end = data.objects[i].end.slice(9, 11) + ':' + data.objects[i].end.slice(11, 13);
// assign the values of the object
$('#editId').val( id );
var theName = $('#editName').val( data.name );
var theLocation = $('#editLocation').val( data.objects[i].location );
var theComment = $('#editComment').val( data.objects[i].comment );
var theDate = $('#editDate').val( date );
var theBegin = $('#editBeginTime').val( begin );
var theEnd = $('#editEndTime').val( end );
var theRepeat = $('#editRepeat').val( data.objects[i].weekly );
// get initial values for reseting
var oldName = theName.val();
var oldLocation = theLocation.val();
var oldComment = theComment.val();
var oldDate = theDate.val();
var oldBegin = theBegin.val();
var oldEnd = theEnd.val();
var oldRepeat = theRepeat.val();
var clonedForm = null; // Holds the edited Form
var origForm = $('#editForm'); // Copy of the Form before Edit
bootbox.dialog({
title: data.origName,
message: $('#editForm'),
backdrop: true,
closeButton: false,
buttons: {
success: {
label: "Speichern",
className: "btn-success",
callback: function () {
try {
var id = $('#editId')[0].value;
var data = load(id);
} catch (e) {
$('#formArea div:nth-child(1)').prepend(origForm);
toastr.error(e, 'Fehler');
}
try {
data.name = isEmpty($('#editName')[0].value);
data.objects[i].location = isEmpty($('#editLocation')[0].value);
data.objects[i].comment = isEmpty($('#editComment')[0].value);
var date = isEmpty($('#editDate')[0].value);
date = date.split("-").join('');
var beginTime = isEmpty($('#editBeginTime')[0].value);
var endTime = isEmpty($('#editEndTime')[0].value);
beginTime = beginTime.slice(0, 2) + beginTime.slice(3, 5) + '00';
endTime = endTime.slice(0, 2) + endTime.slice(3, 5) + '00';
data.objects[i].begin = date + 'T' + beginTime;
data.objects[i].end = date + 'T' + endTime;
clonedForm = $('#editForm');
} catch(e) {
console.error(e.name+": "+e.message);
toastr.error(e, 'Fehler');
return false; // Prevent the Modal from closing
}
try {
$('#formArea div:nth-child(1)').prepend(clonedForm);
if (JSON.stringify(load(id)).localeCompare(JSON.stringify(data) != 0)) {
data.changed = true;
}
save(id, data);
} catch(e) {
$('#formArea div:nth-child(1)').prepend(origForm);
toastr.error(e, 'Fehler');
}
$('body').css('overflow', 'auto');
updateSelectionBox();
}
},
cancel: {
label: "Abbrechen",
className: "btn-danger",
callback: function(){
try {
$('body').css('overflow', 'auto');
$('#formArea div:nth-child(1)').prepend(origForm);
} catch(e) {
console.log(e);
}
}
}
},
keyboard: false
}
);
}
function injectDiv() {
var page = $('#page')[0];
var div = $('<div id="emptyBox"><br><br></div>');
div.insertBefore(document.body.childNodes[0]);
var open = $('<div id="openSelectionBox"><span class="cart-icon glyphicon glyphicon-shopping-cart" aria-hidden="true"></span> Öffnen</div>');
var help = $('<div id="help-section"><li class="dropdown active"> <a class="dropdown-toggle" data-toggle="dropdown" href="#" aria-expanded="false"><span class="cart-icon glyphicon glyphicon-question-sign" aria-hidden="true"></span> Hilfe <span class="caret"></span> </a> <ul class="dropdown-menu"> <li class=""><a href="#tourstarten" data-toggle="tab" aria-expanded="false">Führung starten</a></li> <li class="divider"></li> <li class=""><a href="http://vlvical.github.io/" data-toggle="tab" aria-expanded="true">FAQ & Webseite</a></li> </ul> </li> </div>');
var settings = $('<div id="settings-button"><span class="cart-icon glyphicon glyphicon-cog"></span> <span>Einstellungen</span> <span class="padded-divider">|</span> </div>');
var logo = $('<div id="pluginLogo"> <a href="http://vlvical.github.io/" target="_blank">VLV.ical</a> <span class="padded-divider">|</span> </div>');
$('#emptyBox').prepend(open);
$('#emptyBox').prepend(help);
$('#emptyBox').prepend(settings);
$('#emptyBox').prepend(logo);
$(settings).on('click', function() {
openSettingsDialog();
});
var box = $('<div id="selectionBox"><br></div>')
box.insertBefore(document.body.childNodes[0]);
open = $('#openSelectionBox')[0];
open.onclick = function () {
openBox();
};
var downloadArea = $('<div id="downloadArea"></div>');
downloadArea.insertBefore($('#selectionBox')[0].childNodes[0]);
var itemBox = $('<div id="itemBox"><br></div>');
itemBox.insertBefore($('#selectionBox')[0].childNodes[0]);
var backButton = $('<header class="cart-header"><div id="backButton"><p><span class="cart-icon glyphicon glyphicon-shopping-cart" aria-hidden="true"></span> Schließen</p></div></header>');
backButton.insertBefore($('#selectionBox')[0].childNodes[0]);
/*
* Insert Trash Button
*/
var deleteCart = $('<div id="deleteCart"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></div>');
$('.cart-header').prepend(deleteCart);
$(deleteCart).on('click', function () {
bootbox.dialog({
title: 'Warenkorb entleeren',
message: 'Willst du den Warenkorb entleeren?',
closeButton: false,
buttons: {
success: {
label: "Ja",
className: "btn-primary",
callback: function () {
try {
save('selection', []);
clearDataWithPrefix('nr');
updateSelection();
} catch(e) {
toastr.error(e, 'Fehler');
return false;
}
}
},
cancel: {
label: "Abbrechen",
className: "btn-default",
callback: function(){}
}
},
keyboard: false
});
});
/*
* Hover Effect for Trash Symbol
*/
$(deleteCart).on('mouseenter', function () {
$(this).find('span').fadeOut(500, function() { $(this).remove(); });
$(this).append('<p>Entleeren</p>');
});
$(deleteCart).on('mouseleave', function () {
$(this).find('p').fadeOut(500, function() { $(this).remove(); });
$(this).append('<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>');
});
backButton = $('#backButton')[0];
backButton.onclick = function () {
closeBox(this.parentNode);
page.style.width = "100%";
};
injectDownloadButtons();
}
function openBox() {
var open = $('#openSelectionBox')[0];
$(open).hide("slide");
var box = $('#selectionBox')[0];
$(box).show("slide");
}
function closeBox() {
var open = $('#openSelectionBox')[0];
$(open).show("slide");
var box = $('#selectionBox')[0];
$(box).hide("slide");
}
function clearSelectionBox() {
var selection = load('selection');
selection = [];
saveObjects('selection', selection);
updateSelection();
}
function openSettingsDialog() {
var settings = load('settings');
bootbox.dialog({
title: "Einstellungen",
message: getSettingsForm(),
backdrop: true,
closeButton: false,
buttons: {
success: {
label: "Speichern",
className: "btn-success",
callback: function () {
try {
clonedForm = $('#editForm');
settings.highlightUpdatesPeriod = parseInt($('#setUpdatePeriod')[0].value);
settings.addTypeToName = $("#addTypeToName").is(":checked");
settings.separateByType = $("#separateByType").is(":checked");
save('settings', settings);
$('#formArea div:nth-child(1)').prepend(clonedForm);
} catch(e) {
console.log("Saving settings failed!");
console.log(e);
}
}
},
cancel: {
label: "Abbrechen",
className: "btn-danger",
callback: function(){
try {
} catch(e) {
console.log(e);
}
}
}
},
keyboard: false
}
);
}
function getSettingsForm() {
var settings = load('settings');
var form = '<form id="settingsForm" class="form-horizontal">' +
'<div class="form-group"> <label for="setUpdatePeriod" class="col-sm-3 control-label">Zeitraum</label>' +
'<div class="col-sm-9"> <input type="number" class="form-control input-md" value="' + settings.highlightUpdatesPeriod + '" id="setUpdatePeriod" required>' +
'<p class="help-block">Größe des Zeitraums, in dem aktualisierte Veranstaltungen hervorgehoben werden (in Tagen)</p></div></div>' +
// end first form group
'<div class="form-group"> <label for="addTypeToName" class="col-sm-3 control-label">Dateiname</label>' +
'<div class="col-sm-9"> <input type="checkbox" class="form-control input-md" id="addTypeToName" data-on-text="EIN" data-off-text="AUS">' +
'<p class="help-block">Soll an den Veranstaltungsnamen der Typ angehangen werden? (Vorlesung, Übung, Seminar, etc.)</p></div></div>' +
// end second form group
'<div class="form-group"> <label for="separateByType" class="col-sm-3 control-label">Separate Dateien</label>' +
'<div class="col-sm-9"> <input type="checkbox" class="form-control input-md" id="separateByType" data-on-text="EIN" data-off-text="AUS">' +
'<p class="help-block">Sollen die Veranstaltungsarten separat heruntergeladen werden?</p></div></div>' +
'</form>';
$(document.body).prepend(form);
$('#addTypeToName').prop('checked', settings.addTypeToName);
$('#separateByType').prop('checked', settings.separateByType);
$("#addTypeToName").bootstrapSwitch('onColor', 'success');
$("#separateByType").bootstrapSwitch('onColor', 'success');
$("#setUpdatePeriod").TouchSpin({
min: 0,
max: 100,
step: 1,
boostat: 5,
maxboostedstep: 10,
postfix: 'Tage'
});
return $('#settingsForm');
}
|
additions to last commit
|
chrome_plugin/js/inject/selectionBox.js
|
additions to last commit
|
<ide><path>hrome_plugin/js/inject/selectionBox.js
<ide> }
<ide> }
<ide>
<del>function openEditDialog(id) {
<del> var data = load(id);
<del> var date,
<del> begin,
<del> end,
<del> type,
<del> repeat,
<del> index;
<del> /*
<del> * Inject Table into DOM
<del> */
<del> var table = '<table id="editItemTable" class="table table-hover">' +
<del> '<thead><tr><th>#</th><th>Typ</th><th>Datum</th><th>Uhrzeit</th><th>Wiederholung</th></tr></thead>' +
<del> '<tbody id="editTableBody"></tbody></table> ';
<del> $('#formArea').append(table);
<del>
<del> /*
<del> * Iterate over Objects of an Event
<del> */
<del> for (var i = 0; i < data.objects.length; i++) {
<del> /*
<del> * Check if begin is an Array,
<del> * If True, Event could have multiple dates
<del> * If False, Event is unique
<del> */
<del> if(Array.isArray(data.objects[i].begin)){
<del> var length = data.objects[i].begin.length;
<del> for (var j = 0; j < length; j++) {
<del> date = data.objects[i].begin[j].slice(6, 8) + '.' + data.objects[i].begin[j].slice(4, 6) + '.' + data.objects[i].begin[j].slice(0, 4);
<del> begin = data.objects[i].begin[j].slice(9, 11) + ':' + data.objects[i].begin[j].slice(11, 13);
<del> end = data.objects[i].end[j].slice(9, 11) + ':' + data.objects[i].end[j].slice(11, 13);
<del> type = data.objects[i].type;
<del> repeat = data.objects[i].weekly;
<del> var row = '<tr><th scope="row">' + (i + 1) + '</th>' +
<del> '<td>' + type + '</td>' +
<del> '<td>' + date + '</td>' +
<del> '<td>' + begin + ' - ' + end + '</td>' +
<del> '<td>' + repeat + ' Wöchentlich</td></tr>';
<del> $('#editTableBody').append(row);
<del> }
<del> } else {
<del> date = data.objects[i].begin.slice(6, 8) + '.' + data.objects[i].begin.slice(4, 6) + '.' + data.objects[i].begin.slice(0, 4);
<del> begin = data.objects[i].begin.slice(9, 11) + ':' + data.objects[i].begin.slice(11, 13);
<del> end = data.objects[i].end.slice(9, 11) + ':' + data.objects[i].end.slice(11, 13);
<del> type = data.objects[i].type;
<del> var row = '<tr><th scope="row">' + (i + 1) + '</th>' +
<del> '<td>' + type + '</td>' +
<del> '<td>' + date + '</td>' +
<del> '<td>' + begin + ' - ' + end + '</td>' +
<del> '<td>Einmalig</td></tr>';
<del> $('#editTableBody').append(row);
<del> }
<del>
<del> };
<del>
<del> /*
<del> * Color the clicked Table Row
<del> * Fetch the # Number of the corresponding Row
<del> * Save it into {int} index
<del> */
<del> $('#editTableBody tr').on('click', function(){
<del> $('tr').each(function(){ // this might be bad, need to reconsider
<del> $(this).removeClass('success');
<del> });
<del> $(this).addClass('success');
<del> index = parseInt($(this).find('th').text()) - 1;
<del> });
<del>
<del> bootbox.dialog({
<del> title: data.origName,
<del> message: $('#editItemTable'),
<del> buttons: {
<del> success: {
<del> label: "Bearbeiten",
<del> className: "btn-success",
<del> callback: function () {
<del> try {
<del> if (data.objects[index] !== undefined) {
<del> var begin = data.objects[index].begin;
<del> console.log(data);
<del>
<del> if(Array.isArray(begin)) {
<del> openEditDialogDetailMulti(id, index);
<del> } else {
<del> openEditDialogDetail(id, index);
<del> }
<del> } else {
<del> toastr.info("Es wurde kein Termin ausgewählt.");
<del> return false;
<del> }
<del> } catch(e) {
<del> toastr.error(e, 'Fehler');
<del> return false;
<del> }
<del> }
<del> }
<del> },
<del> keyboard: false
<del> }
<del> );
<del>}
<del>
<del>function openEditDialogDetailMulti(id, index) {
<del> var data = load(id);
<del> var i = index;
<del>
<del> var date = [],
<del> begin = [],
<del> end = [];
<del>
<del> $('body').css('overflow', 'hidden'); // hide body
<del>
<del> var length = data.objects[i].begin.length;
<del> for (var j = 0; j < length; j++) {
<del> date.push(data.objects[i].begin[j].slice(0, 4) + '-' + data.objects[i].begin[j].slice(4, 6) + '-' + data.objects[i].begin[j].slice(6, 8));
<del> begin.push(data.objects[i].begin[j].slice(9, 11) + ':' + data.objects[i].begin[j].slice(11, 13));
<del> end.push(data.objects[i].end[j].slice(9, 11) + ':' + data.objects[i].end[j].slice(11, 13));
<del> }
<del>
<del> // assign the values of the object
<del> $('#editMultiId').val( id );
<del> $('#multiName').val( data.objects[i].name );
<del> $('#multiLocation').val( data.objects[i].location );
<del> $('#multiComment').val( data.objects[i].comment );
<del>
<del> // assign the values of the object
<del> $('#editMultiId').val( id );
<del> var theName = $('#multiName').val( data.objects[i].name );
<del> var theLocation = $('#multiLocation').val( data.objects[i].location );
<del> var theComment = $('#multiComment').val( data.objects[i].comment );
<del>
<del>// get initial values for reseting
<del>
<del> var oldName = theName.val();
<del> var oldLocation = theLocation.val();
<del> var oldComment = theComment.val();
<del>
<del> var origForm = $('#editFormMulti'); // Copy of the Form before Edit
<del> var clonedForm = null; // Holds the edited Form
<del>
<del> for (var j = 0; j < length; j++) {
<del> var addedInputs = '<div class="panel panel-default">' +
<del> '<div class="panel-heading">Zeitraum '+ (j + 1) +'</div>' +
<del> '<div class="panel-body">' +
<del> '<div class="form-group">' +
<del> '<label for="date'+ j +'">Startdatum für Zeitraum '+ (j + 1) +'</label>' +
<del> '<input id="multiDate'+ j +'" name="date'+ j +'" type="date" class="form-control input-md">' +
<del> '</div>' +
<del> '<div class="form-group">' +
<del> '<label for="begin'+ j +'">Beginn</label>' +
<del> '<input id="multiBeginTime'+ j +'" name="begin'+ j +'" type="time" class="form-control input-md">' +
<del> '</div>' +
<del> '<div class="form-group">' +
<del> '<label for="end'+ j +'">Ende</label>' +
<del> '<input id="multiEndTime'+ j +'" name="end'+ j +'" type="time" class="form-control input-md">' +
<del> '</div>' +
<del> '</div>' +
<del> '</div>';
<del>
<del> $('.form-group #multiRepeat').parent().before(addedInputs);
<del>
<del> $('#multiDate' + j).val( date[j] );
<del> $('#multiBeginTime' + j).val( begin[j] );
<del> $('#multiEndTime' + j).val( end[j] );
<del> }
<del> var theRepeat = $('#multiRepeat').val( data.objects[i].weekly );
<del> var oldRepeat = theRepeat.val();
<del>
<del>
<del> bootbox.dialog({
<del> title: data.origName,
<del> message: $('#editFormMulti'),
<del> backdrop: true,
<del> closeButton: false,
<del> buttons: {
<del> success: {
<del> label: "Speichern",
<del> className: "btn-success",
<del> callback: function () {
<del> var i = index;
<del>
<del> try {
<del> var id = $('#editMultiId')[0].value;
<del> var data = load(id);
<del> } catch (e) {
<del> $('#formArea div:nth-child(2)').prepend(origForm);
<del> toastr.error(e, 'Fehler');
<del> }
<del>
<del> try {
<del> data.objects[i].name = isEmpty($('#multiName').val());
<del> data.objects[i].location = isEmpty($('#multiLocation').val());
<del> data.objects[i].comment = isEmpty($('#multiComment').val());
<del> data.objects[i].weekly = isEmpty($('#multiRepeat').val());
<del>
<del> var date = [],
<del> beginTime = [],
<del> endTime = [];
<del>
<del> for (var j = 0; j < length; j++) {
<del> date.push(isEmpty($('#multiDate' + j)[0].value));
<del> date[j] = date[j].split("-").join('');
<del>
<del> beginTime.push(isEmpty($('#multiBeginTime' + j)[0].value));
<del> beginTime[j] = beginTime[j].slice(0, 2) + beginTime[j].slice(3, 5) + '00';
<del>
<del> endTime.push(isEmpty($('#multiEndTime' + j)[0].value));
<del> endTime[j] = endTime[j].slice(0, 2) + endTime[j].slice(3, 5) + '00';
<del>
<del> data.objects[i].begin[j] = date[j] + 'T' + beginTime[j];
<del> data.objects[i].end[j] = date[j] + 'T' + endTime[j];
<del> }
<del>
<del> clonedForm = $('#editFormMulti');
<del> } catch(e) {
<del> console.error(e.name+": "+e.message);
<del> toastr.error(e, 'Fehler');
<del> return false; // Prevent the Modal from closing
<del> }
<del>
<del> try {
<del> for (var j = 0; j < length; j++) {
<del> $('.panel-default').empty();
<del> $('.panel-default').remove();
<del> }
<del> $('#formArea div:nth-child(2)').prepend(clonedForm);
<del>
<del> if (JSON.stringify(load(id)).localeCompare(JSON.stringify(data)) != 0) {
<del> data.changed = true;
<del> }
<del>
<del> save(id, data);
<del> } catch(e) {
<del> for (var j = 0; j < length; j++) {
<del> $('.panel-default').empty();
<del> $('.panel-default').remove();
<del> }
<del> $('#formArea div:nth-child(2)').prepend(origForm);
<del> toastr.error(e, 'Fehler');
<del> }
<del>
<del> updateSelectionBox();
<del> $('body').css('overflow', 'auto');
<del> }
<del> },
<del> cancel: {
<del> label: "Abbrechen",
<del> className: "btn-danger",
<del> callback: function(){
<del> try {
<del> for (var j = 0; j < length; j++) {
<del> $('.panel-default').empty();
<del> $('.panel-default').remove();
<del> }
<del> $('body').css('overflow', 'auto');
<del> $('#formArea div:nth-child(2)').prepend(origForm);
<del> } catch(e) {
<del> console.log(e);
<del> }
<del> }
<del> },
<del> reset: {
<del> label: "Zurücksetzen",
<del> className: "btn-primary pull-left",
<del> callback: function() {
<del> try {
<del>
<del> $('#editName').val( oldName );
<del> $('#editLocation').val( oldLocation);
<del> $('#editComment').val( oldComment);
<del> $('#editDate').val( oldDate );
<del> $('#editBeginTime').val( oldBegin );
<del> $('#editEndTime').val( oldEnd );
<del> $('#editRepeat').val( oldRepeat );
<del> return false;
<del> } catch (e) {
<del> console.log(e);
<del> }
<del> }
<del> },
<del> reset: {
<del> label: "Zurücksetzen",
<del> className: "btn-primary pull-left",
<del> callback: function() {
<del> try {
<del>
<del> $('#multiName').val( oldName );
<del> $('#multiLocation').val( oldLocation);
<del> $('#multiComment').val( oldComment);
<del> for (var j = 0; j < length; j++) {
<del> $('#multiDate' + j).val( date[j] );
<del> $('#multiBeginTime' + j).val( begin[j] );
<del> $('#multiEndTime' + j).val( end[j] );
<del> }
<del> $('#multiRepeat').val( oldRepeat );
<del> return false;
<del> } catch (e) {
<del> console.log(e);
<del> }
<del> }
<del> }
<del> },
<del> keyboard: false
<del> }
<del> );
<del>}
<del>
<del>function openEditDialogDetail(id, index) {
<del> var data = load(id);
<del> var i = index;
<del>
<del> $('body').css('overflow', 'hidden');
<del>
<del> var date = data.objects[i].begin.slice(0, 4) + '-' + data.objects[i].begin.slice(4, 6) + '-' + data.objects[i].begin.slice(6, 8);
<del> var begin = data.objects[i].begin.slice(9, 11) + ':' + data.objects[i].begin.slice(11, 13);
<del> var end = data.objects[i].end.slice(9, 11) + ':' + data.objects[i].end.slice(11, 13);
<del>
<del> // assign the values of the object
<del> $('#editId').val( id );
<del> var theName = $('#editName').val( data.name );
<del> var theLocation = $('#editLocation').val( data.objects[i].location );
<del> var theComment = $('#editComment').val( data.objects[i].comment );
<del> var theDate = $('#editDate').val( date );
<del> var theBegin = $('#editBeginTime').val( begin );
<del> var theEnd = $('#editEndTime').val( end );
<del> var theRepeat = $('#editRepeat').val( data.objects[i].weekly );
<del>
<del>// get initial values for reseting
<del>
<del> var oldName = theName.val();
<del> var oldLocation = theLocation.val();
<del> var oldComment = theComment.val();
<del> var oldDate = theDate.val();
<del> var oldBegin = theBegin.val();
<del> var oldEnd = theEnd.val();
<del> var oldRepeat = theRepeat.val();
<del>
<del> var clonedForm = null; // Holds the edited Form
<del> var origForm = $('#editForm'); // Copy of the Form before Edit
<del>
<del> bootbox.dialog({
<del> title: data.origName,
<del> message: $('#editForm'),
<del> backdrop: true,
<del> closeButton: false,
<del> buttons: {
<del> success: {
<del> label: "Speichern",
<del> className: "btn-success",
<del> callback: function () {
<del> try {
<del> var id = $('#editId')[0].value;
<del> var data = load(id);
<del> } catch (e) {
<del> $('#formArea div:nth-child(1)').prepend(origForm);
<del> toastr.error(e, 'Fehler');
<del> }
<del>
<del> try {
<del> data.name = isEmpty($('#editName')[0].value);
<del> data.objects[i].location = isEmpty($('#editLocation')[0].value);
<del> data.objects[i].comment = isEmpty($('#editComment')[0].value);
<del>
<del> var date = isEmpty($('#editDate')[0].value);
<del> date = date.split("-").join('');
<del>
<del> var beginTime = isEmpty($('#editBeginTime')[0].value);
<del> var endTime = isEmpty($('#editEndTime')[0].value);
<del>
<del> beginTime = beginTime.slice(0, 2) + beginTime.slice(3, 5) + '00';
<del> endTime = endTime.slice(0, 2) + endTime.slice(3, 5) + '00';
<del>
<del> data.objects[i].begin = date + 'T' + beginTime;
<del> data.objects[i].end = date + 'T' + endTime;
<del>
<del> clonedForm = $('#editForm');
<del> } catch(e) {
<del> console.error(e.name+": "+e.message);
<del> toastr.error(e, 'Fehler');
<del> return false; // Prevent the Modal from closing
<del> }
<del>
<del> try {
<del> $('#formArea div:nth-child(1)').prepend(clonedForm);
<del> if (JSON.stringify(load(id)).localeCompare(JSON.stringify(data) != 0)) {
<del> data.changed = true;
<del> }
<del> save(id, data);
<del> } catch(e) {
<del> $('#formArea div:nth-child(1)').prepend(origForm);
<del> toastr.error(e, 'Fehler');
<del> }
<del> $('body').css('overflow', 'auto');
<del> updateSelectionBox();
<del>
<del> }
<del> },
<del> cancel: {
<del> label: "Abbrechen",
<del> className: "btn-danger",
<del> callback: function(){
<del> try {
<del> $('body').css('overflow', 'auto');
<del> $('#formArea div:nth-child(1)').prepend(origForm);
<del> } catch(e) {
<del> console.log(e);
<del> }
<del> }
<del> }
<del> },
<del> keyboard: false
<del> }
<del> );
<del>}
<del>
<del>function injectDiv() {
<del> var page = $('#page')[0];
<del>
<del> var div = $('<div id="emptyBox"><br><br></div>');
<del> div.insertBefore(document.body.childNodes[0]);
<del>
<del> var open = $('<div id="openSelectionBox"><span class="cart-icon glyphicon glyphicon-shopping-cart" aria-hidden="true"></span> Öffnen</div>');
<del> var help = $('<div id="help-section"><li class="dropdown active"> <a class="dropdown-toggle" data-toggle="dropdown" href="#" aria-expanded="false"><span class="cart-icon glyphicon glyphicon-question-sign" aria-hidden="true"></span> Hilfe <span class="caret"></span> </a> <ul class="dropdown-menu"> <li class=""><a href="#tourstarten" data-toggle="tab" aria-expanded="false">Führung starten</a></li> <li class="divider"></li> <li class=""><a href="http://vlvical.github.io/" data-toggle="tab" aria-expanded="true">FAQ & Webseite</a></li> </ul> </li> </div>');
<del> var settings = $('<div id="settings-button"><span class="cart-icon glyphicon glyphicon-cog"></span> <span>Einstellungen</span> <span class="padded-divider">|</span> </div>');
<del> var logo = $('<div id="pluginLogo"> <a href="http://vlvical.github.io/" target="_blank">VLV.ical</a> <span class="padded-divider">|</span> </div>');
<del> $('#emptyBox').prepend(open);
<del> $('#emptyBox').prepend(help);
<del> $('#emptyBox').prepend(settings);
<del> $('#emptyBox').prepend(logo);
<del>
<del> $(settings).on('click', function() {
<del> openSettingsDialog();
<del> });
<del>
<del> var box = $('<div id="selectionBox"><br></div>')
<del> box.insertBefore(document.body.childNodes[0]);
<del>
<del> open = $('#openSelectionBox')[0];
<del> open.onclick = function () {
<del> openBox();
<del> };
<del>
<del> var downloadArea = $('<div id="downloadArea"></div>');
<del> downloadArea.insertBefore($('#selectionBox')[0].childNodes[0]);
<del>
<del> var itemBox = $('<div id="itemBox"><br></div>');
<del> itemBox.insertBefore($('#selectionBox')[0].childNodes[0]);
<del>
<del> var backButton = $('<header class="cart-header"><div id="backButton"><p><span class="cart-icon glyphicon glyphicon-shopping-cart" aria-hidden="true"></span> Schließen</p></div></header>');
<del> backButton.insertBefore($('#selectionBox')[0].childNodes[0]);
<del>
<del> /*
<del> * Insert Trash Button
<del> */
<del> var deleteCart = $('<div id="deleteCart"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></div>');
<del> $('.cart-header').prepend(deleteCart);
<del>
<del> $(deleteCart).on('click', function () {
<del> bootbox.dialog({
<del> title: 'Warenkorb entleeren',
<del> message: 'Willst du den Warenkorb entleeren?',
<del> closeButton: false,
<del> buttons: {
<del> success: {
<del> label: "Ja",
<del> className: "btn-primary",
<del> callback: function () {
<del> try {
<del> save('selection', []);
<del> clearDataWithPrefix('nr');
<del> updateSelection();
<del> } catch(e) {
<del> toastr.error(e, 'Fehler');
<del> return false;
<del> }
<del> }
<del> },
<del> cancel: {
<del> label: "Abbrechen",
<del> className: "btn-default",
<del> callback: function(){}
<del> }
<del> },
<del> keyboard: false
<del> });
<del> });
<del>
<del> /*
<del> * Hover Effect for Trash Symbol
<del> */
<del> $(deleteCart).on('mouseenter', function () {
<del> $(this).find('span').fadeOut(500, function() { $(this).remove(); });
<del> $(this).append('<p>Entleeren</p>');
<del> });
<del>
<del> $(deleteCart).on('mouseleave', function () {
<del> $(this).find('p').fadeOut(500, function() { $(this).remove(); });
<del> $(this).append('<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>');
<del> });
<del>
<del> backButton = $('#backButton')[0];
<del> backButton.onclick = function () {
<del> closeBox(this.parentNode);
<del> page.style.width = "100%";
<del> };
<del>
<del> injectDownloadButtons();
<del>}
<del>
<ide> function openBox() {
<ide>
<ide> var open = $('#openSelectionBox')[0];
<ide> saveObjects('selection', selection);
<ide> updateSelection();
<ide> }
<del>
<del>function openSettingsDialog() {
<del> var settings = load('settings');
<del> bootbox.dialog({
<del> title: "Einstellungen",
<del> message: getSettingsForm(),
<del> backdrop: true,
<del> closeButton: false,
<del> buttons: {
<del> success: {
<del> label: "Speichern",
<del> className: "btn-success",
<del> callback: function () {
<del> try {
<del> clonedForm = $('#editForm');
<del> settings.highlightUpdatesPeriod = parseInt($('#setUpdatePeriod')[0].value);
<del> settings.addTypeToName = $("#addTypeToName").is(":checked");
<del> settings.separateByType = $("#separateByType").is(":checked");
<del>
<del> save('settings', settings);
<del> $('#formArea div:nth-child(1)').prepend(clonedForm);
<del> } catch(e) {
<del>
<del> console.log("Saving settings failed!");
<del> console.log(e);
<del> }
<del> }
<del> },
<del> cancel: {
<del> label: "Abbrechen",
<del> className: "btn-danger",
<del> callback: function(){
<del> try {
<del>
<del> } catch(e) {
<del> console.log(e);
<del> }
<del> }
<del> }
<del> },
<del> keyboard: false
<del> }
<del> );
<del>}
<del>
<del>function getSettingsForm() {
<del> var settings = load('settings');
<del> var form = '<form id="settingsForm" class="form-horizontal">' +
<del> '<div class="form-group"> <label for="setUpdatePeriod" class="col-sm-3 control-label">Zeitraum</label>' +
<del> '<div class="col-sm-9"> <input type="number" class="form-control input-md" value="' + settings.highlightUpdatesPeriod + '" id="setUpdatePeriod" required>' +
<del> '<p class="help-block">Größe des Zeitraums, in dem aktualisierte Veranstaltungen hervorgehoben werden (in Tagen)</p></div></div>' +
<del> // end first form group
<del> '<div class="form-group"> <label for="addTypeToName" class="col-sm-3 control-label">Dateiname</label>' +
<del> '<div class="col-sm-9"> <input type="checkbox" class="form-control input-md" id="addTypeToName" data-on-text="EIN" data-off-text="AUS">' +
<del> '<p class="help-block">Soll an den Veranstaltungsnamen der Typ angehangen werden? (Vorlesung, Übung, Seminar, etc.)</p></div></div>' +
<del> // end second form group
<del> '<div class="form-group"> <label for="separateByType" class="col-sm-3 control-label">Separate Dateien</label>' +
<del> '<div class="col-sm-9"> <input type="checkbox" class="form-control input-md" id="separateByType" data-on-text="EIN" data-off-text="AUS">' +
<del> '<p class="help-block">Sollen die Veranstaltungsarten separat heruntergeladen werden?</p></div></div>' +
<del> '</form>';
<del> $(document.body).prepend(form);
<del> $('#addTypeToName').prop('checked', settings.addTypeToName);
<del> $('#separateByType').prop('checked', settings.separateByType);
<del>
<del> $("#addTypeToName").bootstrapSwitch('onColor', 'success');
<del> $("#separateByType").bootstrapSwitch('onColor', 'success');
<del> $("#setUpdatePeriod").TouchSpin({
<del> min: 0,
<del> max: 100,
<del> step: 1,
<del> boostat: 5,
<del> maxboostedstep: 10,
<del> postfix: 'Tage'
<del> });
<del> return $('#settingsForm');
<del>}
|
|
Java
|
apache-2.0
|
e290ab0872981043f875c1f5ad973de8fb5eccd2
| 0 |
marcorei/FirebaseUI-Android,lockerfish/FirebaseUI-Android,SUPERCILEX/FirebaseUI-Android,firebase/FirebaseUI-Android,JosefHruska/FirebaseUI-Android,SUPERCILEX/FirebaseUI-Android,marcorei/FirebaseUI-Android,ardock/FirebaseUI-Android,firebase/FirebaseUI-Android,samtstern/FirebaseUI-Android,MaciejCiemiega/FirebaseUI-Android,lockerfish/FirebaseUI-Android,blqthien/FirebaseUI-Android,samtstern/FirebaseUI-Android,firebase/FirebaseUI-Android,SUPERCILEX/FirebaseUI-Android,firebase/FirebaseUI-Android,SUPERCILEX/FirebaseUI-Android,ardock/FirebaseUI-Android,JosefHruska/FirebaseUI-Android,samtstern/FirebaseUI-Android,blqthien/FirebaseUI-Android
|
/*
* Firebase UI Bindings Android Library
*
* Copyright © 2015 Firebase - All Rights Reserved
* https://www.firebase.com
*
* 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 binaryform 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 FIREBASE 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 FIREBASE BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.firebase.ui;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.firebase.client.Firebase;
import com.firebase.client.Query;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* This class is a generic way of backing an RecyclerView with a Firebase location.
* It handles all of the child events at the given Firebase location. It marshals received data into the given
* class type.
*
* To use this class in your app, subclass it passing in all required parameters and implement the
* populateViewHolder method.
*
* <blockquote><pre>
* {@code
* private static class ChatMessageViewHolder extends RecyclerView.ViewHolder {
* TextView messageText;
* TextView nameText;
*
* public ChatMessageViewHolder(View itemView) {
* super(itemView);
* nameText = (TextView)itemView.findViewById(android.R.id.text1);
* messageText = (TextView) itemView.findViewById(android.R.id.text2);
* }
* }
*
* FirebaseRecyclerViewAdapter<ChatMessage, ChatMessageViewHolder> adapter;
* ref = new Firebase("https://<yourapp>.firebaseio.com");
*
* RecyclerView recycler = (RecyclerView) findViewById(R.id.messages_recycler);
* recycler.setHasFixedSize(true);
* recycler.setLayoutManager(new LinearLayoutManager(this));
*
* adapter = new FirebaseRecyclerViewAdapter<ChatMessage, ChatMessageViewHolder>(ChatMessage.class, android.R.layout.two_line_list_item, ChatMessageViewHolder.class, mRef) {
* public void populateViewHolder(ChatMessageViewHolder chatMessageViewHolder, ChatMessage chatMessage) {
* chatMessageViewHolder.nameText.setText(chatMessage.getName());
* chatMessageViewHolder.messageText.setText(chatMessage.getMessage());
* }
* };
* recycler.setAdapter(mAdapter);
* }
* </pre></blockquote>
*
* @param <T> The Java class that maps to the type of objects stored in the Firebase location.
* @param <VH> The ViewHolder class that contains the Views in the layout that is shown for each object.
*/
public abstract class FirebaseRecyclerViewAdapter<T, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
Class<T> mModelClass;
protected int mModelLayout;
Class<VH> mViewHolderClass;
FirebaseArray mSnapshots;
/**
* @param modelClass Firebase will marshall the data at a location into an instance of a class that you provide
* @param modelLayout This is the layout used to represent a single item in the list. You will be responsible for populating an
* instance of the corresponding view with the data from an instance of modelClass.
* @param viewHolderClass The class that hold references to all sub-views in an instance modelLayout.
* @param ref The Firebase location to watch for data changes. Can also be a slice of a location, using some
* combination of <code>limit()</code>, <code>startAt()</code>, and <code>endAt()</code>
*/
public FirebaseRecyclerViewAdapter(Class<T> modelClass, int modelLayout, Class<VH> viewHolderClass, Query ref) {
mModelClass = modelClass;
mModelLayout = modelLayout;
mViewHolderClass = viewHolderClass;
mSnapshots = new FirebaseArray(ref);
mSnapshots.setOnChangedListener(new FirebaseArray.OnChangedListener() {
@Override
public void onChanged(EventType type, int index, int oldIndex) {
switch (type) {
case Added:
notifyItemInserted(index);
break;
case Changed:
notifyItemChanged(index);
break;
case Removed:
notifyItemRemoved(index);
break;
case Moved:
notifyItemMoved(oldIndex, index);
break;
default:
throw new IllegalStateException("Incomplete case statement");
}
}
});
}
/**
* @param modelClass Firebase will marshall the data at a location into an instance of a class that you provide
* @param modelLayout This is the layout used to represent a single item in the list. You will be responsible for populating an
* instance of the corresponding view with the data from an instance of modelClass.
* @param viewHolderClass The class that hold references to all sub-views in an instance modelLayout.
* @param ref The Firebase location to watch for data changes. Can also be a slice of a location, using some
* combination of <code>limit()</code>, <code>startAt()</code>, and <code>endAt()</code>
*/
public FirebaseRecyclerViewAdapter(Class<T> modelClass, int modelLayout, Class<VH> viewHolderClass, Firebase ref) {
this(modelClass, modelLayout, viewHolderClass, (Query)ref);
}
public void cleanup() {
mSnapshots.cleanup();
}
@Override
public int getItemCount() {
return mSnapshots.getCount();
}
public T getItem(int position) {
return mSnapshots.getItem(position).getValue(mModelClass);
}
public Firebase getRef(int position) { return mSnapshots.getItem(position).getRef(); }
@Override
public long getItemId(int position) {
// http://stackoverflow.com/questions/5100071/whats-the-purpose-of-item-ids-in-android-listview-adapter
return mSnapshots.getItem(position).getKey().hashCode();
}
@Override
public VH onCreateViewHolder(ViewGroup parent, int viewType) {
ViewGroup view = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(mModelLayout, parent, false);
try {
Constructor<VH> constructor = mViewHolderClass.getConstructor(View.class);
return constructor.newInstance(view);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public void onBindViewHolder(VH viewHolder, int i) {
T model = getItem(i);
populateViewHolder(viewHolder, model);
}
abstract public void populateViewHolder(VH viewHolder, T model);
}
|
library/src/main/java/com/firebase/ui/FirebaseRecyclerViewAdapter.java
|
/*
* Firebase UI Bindings Android Library
*
* Copyright © 2015 Firebase - All Rights Reserved
* https://www.firebase.com
*
* 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 binaryform 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 FIREBASE 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 FIREBASE BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.firebase.ui;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.firebase.client.Firebase;
import com.firebase.client.Query;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* This class is a generic way of backing an RecyclerView with a Firebase location.
* It handles all of the child events at the given Firebase location. It marshals received data into the given
* class type.
*
* To use this class in your app, subclass it passing in all required parameters and implement the
* populateViewHolder method.
*
* <blockquote><pre>
* {@code
* private static class ChatMessageViewHolder extends RecyclerView.ViewHolder {
* TextView messageText;
* TextView nameText;
*
* public ChatMessageViewHolder(View itemView) {
* super(itemView);
* nameText = (TextView)itemView.findViewById(android.R.id.text1);
* messageText = (TextView) itemView.findViewById(android.R.id.text2);
* }
* }
*
* FirebaseRecyclerViewAdapter<ChatMessage, ChatMessageViewHolder> adapter;
* ref = new Firebase("https://<yourapp>.firebaseio.com");
*
* RecyclerView recycler = (RecyclerView) findViewById(R.id.messages_recycler);
* recycler.setHasFixedSize(true);
* recycler.setLayoutManager(new LinearLayoutManager(this));
*
* adapter = new FirebaseRecyclerViewAdapter<ChatMessage, ChatMessageViewHolder>(ChatMessage.class, android.R.layout.two_line_list_item, ChatMessageViewHolder.class, mRef) {
* public void populateViewHolder(ChatMessageViewHolder chatMessageViewHolder, ChatMessage chatMessage) {
* chatMessageViewHolder.nameText.setText(chatMessage.getName());
* chatMessageViewHolder.messageText.setText(chatMessage.getMessage());
* }
* };
* recycler.setAdapter(mAdapter);
*
*
* @param <T> The Java class that maps to the type of objects stored in the Firebase location.
* @param <VH> The ViewHolder class that contains the Views in the layout that is shown for each object.
*/
public abstract class FirebaseRecyclerViewAdapter<T, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
Class<T> mModelClass;
protected int mModelLayout;
Class<VH> mViewHolderClass;
FirebaseArray mSnapshots;
/**
* @param modelClass Firebase will marshall the data at a location into an instance of a class that you provide
* @param modelLayout This is the layout used to represent a single item in the list. You will be responsible for populating an
* instance of the corresponding view with the data from an instance of modelClass.
* @param viewHolderClass The class that hold references to all sub-views in an instance modelLayout.
* @param ref The Firebase location to watch for data changes. Can also be a slice of a location, using some
* combination of <code>limit()</code>, <code>startAt()</code>, and <code>endAt()</code>
*/
public FirebaseRecyclerViewAdapter(Class<T> modelClass, int modelLayout, Class<VH> viewHolderClass, Query ref) {
mModelClass = modelClass;
mModelLayout = modelLayout;
mViewHolderClass = viewHolderClass;
mSnapshots = new FirebaseArray(ref);
mSnapshots.setOnChangedListener(new FirebaseArray.OnChangedListener() {
@Override
public void onChanged(EventType type, int index, int oldIndex) {
switch (type) {
case Added:
notifyItemInserted(index);
break;
case Changed:
notifyItemChanged(index);
break;
case Removed:
notifyItemRemoved(index);
break;
case Moved:
notifyItemMoved(oldIndex, index);
break;
default:
throw new IllegalStateException("Incomplete case statement");
}
}
});
}
/**
* @param modelClass Firebase will marshall the data at a location into an instance of a class that you provide
* @param modelLayout This is the layout used to represent a single item in the list. You will be responsible for populating an
* instance of the corresponding view with the data from an instance of modelClass.
* @param viewHolderClass The class that hold references to all sub-views in an instance modelLayout.
* @param ref The Firebase location to watch for data changes. Can also be a slice of a location, using some
* combination of <code>limit()</code>, <code>startAt()</code>, and <code>endAt()</code>
*/
public FirebaseRecyclerViewAdapter(Class<T> modelClass, int modelLayout, Class<VH> viewHolderClass, Firebase ref) {
this(modelClass, modelLayout, viewHolderClass, (Query)ref);
}
public void cleanup() {
mSnapshots.cleanup();
}
@Override
public int getItemCount() {
return mSnapshots.getCount();
}
public T getItem(int position) {
return mSnapshots.getItem(position).getValue(mModelClass);
}
public Firebase getRef(int position) { return mSnapshots.getItem(position).getRef(); }
@Override
public long getItemId(int position) {
// http://stackoverflow.com/questions/5100071/whats-the-purpose-of-item-ids-in-android-listview-adapter
return mSnapshots.getItem(position).getKey().hashCode();
}
@Override
public VH onCreateViewHolder(ViewGroup parent, int viewType) {
ViewGroup view = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(mModelLayout, parent, false);
try {
Constructor<VH> constructor = mViewHolderClass.getConstructor(View.class);
return constructor.newInstance(view);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public void onBindViewHolder(VH viewHolder, int i) {
T model = getItem(i);
populateViewHolder(viewHolder, model);
}
abstract public void populateViewHolder(VH viewHolder, T model);
}
|
Fixed syntax error in Javadoc
|
library/src/main/java/com/firebase/ui/FirebaseRecyclerViewAdapter.java
|
Fixed syntax error in Javadoc
|
<ide><path>ibrary/src/main/java/com/firebase/ui/FirebaseRecyclerViewAdapter.java
<ide> *
<ide> * <blockquote><pre>
<ide> * {@code
<del> * private static class ChatMessageViewHolder extends RecyclerView.ViewHolder {
<del> * TextView messageText;
<del> * TextView nameText;
<add> * private static class ChatMessageViewHolder extends RecyclerView.ViewHolder {
<add> * TextView messageText;
<add> * TextView nameText;
<ide> *
<del> * public ChatMessageViewHolder(View itemView) {
<del> * super(itemView);
<del> * nameText = (TextView)itemView.findViewById(android.R.id.text1);
<del> * messageText = (TextView) itemView.findViewById(android.R.id.text2);
<add> * public ChatMessageViewHolder(View itemView) {
<add> * super(itemView);
<add> * nameText = (TextView)itemView.findViewById(android.R.id.text1);
<add> * messageText = (TextView) itemView.findViewById(android.R.id.text2);
<add> * }
<ide> * }
<add> *
<add> * FirebaseRecyclerViewAdapter<ChatMessage, ChatMessageViewHolder> adapter;
<add> * ref = new Firebase("https://<yourapp>.firebaseio.com");
<add> *
<add> * RecyclerView recycler = (RecyclerView) findViewById(R.id.messages_recycler);
<add> * recycler.setHasFixedSize(true);
<add> * recycler.setLayoutManager(new LinearLayoutManager(this));
<add> *
<add> * adapter = new FirebaseRecyclerViewAdapter<ChatMessage, ChatMessageViewHolder>(ChatMessage.class, android.R.layout.two_line_list_item, ChatMessageViewHolder.class, mRef) {
<add> * public void populateViewHolder(ChatMessageViewHolder chatMessageViewHolder, ChatMessage chatMessage) {
<add> * chatMessageViewHolder.nameText.setText(chatMessage.getName());
<add> * chatMessageViewHolder.messageText.setText(chatMessage.getMessage());
<add> * }
<add> * };
<add> * recycler.setAdapter(mAdapter);
<ide> * }
<del> *
<del> * FirebaseRecyclerViewAdapter<ChatMessage, ChatMessageViewHolder> adapter;
<del> * ref = new Firebase("https://<yourapp>.firebaseio.com");
<del> *
<del> * RecyclerView recycler = (RecyclerView) findViewById(R.id.messages_recycler);
<del> * recycler.setHasFixedSize(true);
<del> * recycler.setLayoutManager(new LinearLayoutManager(this));
<del> *
<del> * adapter = new FirebaseRecyclerViewAdapter<ChatMessage, ChatMessageViewHolder>(ChatMessage.class, android.R.layout.two_line_list_item, ChatMessageViewHolder.class, mRef) {
<del> * public void populateViewHolder(ChatMessageViewHolder chatMessageViewHolder, ChatMessage chatMessage) {
<del> * chatMessageViewHolder.nameText.setText(chatMessage.getName());
<del> * chatMessageViewHolder.messageText.setText(chatMessage.getMessage());
<del> * }
<del> * };
<del> * recycler.setAdapter(mAdapter);
<del> *
<add> * </pre></blockquote>
<ide> *
<ide> * @param <T> The Java class that maps to the type of objects stored in the Firebase location.
<ide> * @param <VH> The ViewHolder class that contains the Views in the layout that is shown for each object.
|
|
Java
|
apache-2.0
|
ab62d29112035ccb8fbfe8ce14ae6081c1f41066
| 0 |
camlow325/jvm-ssl-utils,steveax/jvm-ssl-utils,camlow325/jvm-ssl-utils,puppetlabs/jvm-ssl-utils,steveax/jvm-ssl-utils,puppetlabs/jvm-ssl-utils
|
package com.puppetlabs.certificate_authority;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.ASN1String;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERPrintableString;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.misc.MiscObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.Attribute;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import java.io.IOException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Utilities for working with X509 extensions.
*/
public class ExtensionsUtils {
/**
* Return true if the given OID is contained within the subtree of parent OID.
*
* @param parentOid The OID of the parent tree.
* @param oid The OID to compare.
* @return True if OID is a subtree
*/
public static boolean isSubtreeOf(String parentOid, String oid) {
if (parentOid.equals(oid)) {
return false;
} else {
return oid.startsWith(parentOid);
}
}
/**
* Given a Java X509Certificate object, return a list of maps representing
* all the X509 extensions embedded in the certificate. If no extensions
* exist on the certificate, the null is returned.
*
* @param cert The X509 certificate object.
* @return A list of maps describing each extensions in the provided
* certificate.
* @throws IOException
* @throws CertificateEncodingException
* @see #getExtensionList(Extensions)
*/
public static List<Map<String, Object>> getExtensionList(X509Certificate cert)
throws IOException, CertificateEncodingException
{
Extensions extensions = getExtensionsFromCert(cert);
if (extensions != null) {
return getExtensionList(extensions);
} else {
return null;
}
}
/**
* Given a Bouncy Castle CSR object, return a list of maps representing
* all the X509 extensions embedded in the CSR. If no extensions exist on
* the CSR, then null is returned.
*
* @param csr The Bouncy Castle CertificationRequest object
* @return A list of maps describing each extensions in the provided
* certificate.
* @throws IOException
* @see #getExtensionList(Extensions)
*/
public static List<Map<String, Object>> getExtensionList(PKCS10CertificationRequest csr)
throws IOException
{
Extensions extensions = getExtensionsFromCSR(csr);
if (extensions != null) {
return getExtensionList(extensions);
} else{
return null;
}
}
/**
* Given a Java certificate, get a map containing the value
* and criticality of the extensions described by the given OID. If the OID
* is not found in the certificate then null is returned.
*
* @param cert The Java X509 certificate object.
* @param oid The OID of the extension to be found.
* @return The map containing the extension value and critical flag.
*/
public static Map<String, Object> getExtension(X509Certificate cert, String oid)
throws IOException, CertificateEncodingException
{
Extensions extensions = getExtensionsFromCert(cert);
if (extensions != null) {
return makeExtensionMap(extensions, new ASN1ObjectIdentifier(oid));
} else {
return null;
}
}
/**
* Given a Bouncy Castle CSR, get a map describing an extension value and
* its criticality from its OID. If the extension is not found then null
* is returned.
*
* @param csr The Bouncy Castle CSR to extract an extension from.
* @param oid The OID of extension to find.
* @return A map describing the extension requested by its OID.
* @throws IOException
*/
public static Map<String, Object> getExtension(PKCS10CertificationRequest csr, String oid)
throws IOException
{
Extensions extensions = getExtensionsFromCSR(csr);
if (extensions != null) {
return makeExtensionMap(extensions, new ASN1ObjectIdentifier(oid));
} else {
return null;
}
}
/**
* Given a list of maps describing extensions, return a map containing
* the extensions described by the provided OID. Returns null if the OID
* doesn't exist in the provided list.
*
* @param extList A list of extensions returned by getExtensionList().
* @param oid The OID of the extension to find.
* @return The map describing the found extension, null if the oid doesn't exist.
* @see #getExtensionList(org.bouncycastle.asn1.x509.Extensions)
* @see #getExtensionList(java.security.cert.X509Certificate)
*/
public static Map<String, Object> getExtension(List<Map<String, Object>> extList,
String oid)
{
for (Map<String, Object> ext: extList) {
if (ext.get("oid").equals(oid)) {
return ext;
}
}
return null;
}
public static Object getExtensionValue(X509Certificate cert, String oid)
throws IOException, CertificateEncodingException
{
return getExtensionValue(getExtension(cert, oid));
}
public static Object getExtensionValue(PKCS10CertificationRequest csr,
String oid)
throws IOException
{
return getExtensionValue(getExtension(csr, oid));
}
public static Object getExtensionValue(List<Map<String, Object>> extList,
String oid)
{
return getExtensionValue(getExtension(extList, oid));
}
public static Object getExtensionValue(Map<String, Object> extMap) {
if (extMap != null) {
return extMap.get("value");
} else {
return null;
}
}
/**
* Given a Bouncy Castle Extensions container, return a list of maps
* representing all the X509 extensions embedded in the certificate.
*
* @param exts A Bouncy Castle Extensions container object.
* @return A list of maps describing each extensions in the provided
* certificate.
* @throws IOException
*/
private static List<Map<String, Object>> getExtensionList(Extensions exts)
throws IOException
{
List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
for (ASN1ObjectIdentifier oid : exts.getCriticalExtensionOIDs()) {
ret.add(makeExtensionMap(exts, oid, true));
}
for (ASN1ObjectIdentifier oid : exts.getNonCriticalExtensionOIDs()) {
ret.add(makeExtensionMap(exts, oid, false));
}
return ret;
}
/**
* Given an extensions container and an OID, extract the value and
* criticality flag and return the values in a map. If the extension is not
* found then null is returned.
*
* @param exts The Bouncy Castle extensions container.
* @param oid The OID of the extension to find.
* @return A map
* @throws IOException
*/
private static Map<String, Object> makeExtensionMap(Extensions exts,
ASN1ObjectIdentifier oid)
throws IOException
{
boolean critical = Arrays.asList(exts.getCriticalExtensionOIDs()).contains(oid);
return makeExtensionMap(exts, oid, critical);
}
/**
* Find the X509 Extensions from CSR object. If no extensions
* attribute is found then null is returned.
*
* @param csr The CSR object to extract the Extensions container from.
* @return An extensions container extracted form the CSR.
*/
static Extensions getExtensionsFromCSR(PKCS10CertificationRequest csr) {
Attribute[] attrs = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
for (Attribute attr : attrs) {
ASN1Set extsAsn1 = attr.getAttrValues();
if (extsAsn1 != null) {
return Extensions.getInstance(extsAsn1.getObjectAt(0));
}
}
return null;
}
/**
* Given a list of maps which represent Extensions, produce a Bouncy Castle
* Extensions object which contains each extension parsed into Bouncy Castle
* Extension objects.
*
* @return The results Extensions container.
* @see #parseExtensionObject(java.util.Map)
*/
static Extensions getExtensionsObjFromMap(List<Map<String,Object>> extMapsList)
throws IOException
{
if ((extMapsList != null) && (extMapsList.size() > 0)) {
List<Extension> ret = new ArrayList<Extension>();
for (Map<String, Object> extObj : extMapsList) {
ret.add(parseExtensionObject(extObj));
}
return new Extensions(ret.toArray(new Extension[ret.size()]));
} else {
return null;
}
}
/**
* Provided a map which describes an X509 extension, parse it into a
* Bouncy Castle Extension object.
*
* @param extMap Map describing an extension.
* @return A parsed Extension object.
* @throws IOException
*/
static Extension parseExtensionObject(Map<String, Object> extMap)
throws IOException
{
ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier((String)extMap.get("oid"));
ASN1Object ret;
if (oid.equals(Extension.subjectAlternativeName) ||
oid.equals(Extension.issuerAlternativeName))
{
@SuppressWarnings("unchecked")
Map<String, List<String>> val = (Map<String, List<String>>) extMap.get("value");
ret = mapToGeneralNames(val);
} else {
throw new IllegalArgumentException(
"Parsing an extension with an OID=" +
oid.getId() + " is not yet supported.");
}
return new Extension(oid, (Boolean)extMap.get("critical"), new DEROctetString(ret));
}
/**
* Get a Bouncy Castle Extensions container from a Java X509 certificate
* object. If no extensions are found then null is returned.
*
* @param cert The Java X509 certificate object.
* @return A Bouncy Castle Extensions container object extracted from the
* certificate.
* @throws CertificateEncodingException
* @throws IOException
*/
private static Extensions getExtensionsFromCert(X509Certificate cert)
throws CertificateEncodingException, IOException
{
return new X509CertificateHolder(cert.getEncoded()).getExtensions();
}
/**
* Given an Extensions container, an OID, and a critical flag, create a map
* of this extension's data with the following keys:
*
* - "oid" : The OID of the extensions
* - "value" : A String, or list of Strings of this OID's data
* - "critical" : A bool set to true if this extensions is critical,
* false if it isn't.
*
* If the given OID doesn't exist in the extensions container then null is
* returned.
*
* @param exts A Bouncy Castle Extensions container containing the provided OID
* @param oid The OID of the extension to create the map for.
* @param critical True if this extension is critical, false if it isn't.
* @return A map representing the extension with the given OID which exists
* in the provided Extensions container.
* @throws IOException
*/
private static Map<String, Object> makeExtensionMap(Extensions exts,
ASN1ObjectIdentifier oid,
boolean critical)
throws IOException
{
Extension ext = exts.getExtension(oid);
if (ext != null) {
byte[] extensionData = ext.getExtnValue().getOctets();
ASN1Object asn1Value = binaryToASN1Object(oid, extensionData);
HashMap<String, Object> ret = new HashMap<String, Object>();
ret.put("oid", oid.getId());
ret.put("critical", critical);
ret.put("value", asn1ObjToObj(asn1Value));
return ret;
} else {
return null;
}
}
/**
* Convert a chunk of binary data into the Bouncy Castle ASN1 data structure
* which represents the data it contains accord to its OID. I've searched
* all over the BouncyCastle API and I can't seem to find this mapping
* defined anywhere, so I've created it here.
*
* @param oid The extension OID.
* @param data The binary data value of the extension with the given OID.
* @return An ASN1Object which contains the data described by the
* provided OID.
* @throws IOException
*/
private static ASN1Object binaryToASN1Object(ASN1ObjectIdentifier oid,
byte[] data)
throws IOException
{
if (oid.equals(Extension.subjectAlternativeName) ||
oid.equals(Extension.issuerAlternativeName))
{
return GeneralNames.getInstance(data);
} else if (oid.equals(Extension.authorityKeyIdentifier)) {
return AuthorityKeyIdentifier.getInstance(data);
} else if (oid.equals(Extension.subjectKeyIdentifier)) {
return SubjectKeyIdentifier.getInstance(data);
} else if (oid.equals(Extension.basicConstraints)) {
return BasicConstraints.getInstance(data);
} else if (oid.equals(Extension.keyUsage)) {
DERBitString bs = new DERBitString(data);
return new KeyUsage(bs.getPadBits());
} else if (oid.equals(Extension.extendedKeyUsage)) {
return ExtendedKeyUsage.getInstance(data);
} else if (oid.equals(MiscObjectIdentifiers.netscapeCertComment)) {
return new DERPrintableString(new String(data, "UTF8"));
} else {
// Most extensions are a simple string value.
return new DERPrintableString(new String(data, "UTF8"));
}
}
/**
* Convert a Bouncy Castle ASN1Object into a Java data structure, which
* will generally be in the form of a string, map, list or combination thereof.
* If this method can't determine a method of converting the ASN1 object then
* the raw byte array is returned.
*
* @param asn1Prim The ASN1 object to
* @return A Java data structure which represents the provided ASN1Object.
* @throws IOException
*/
private static Object asn1ObjToObj(ASN1Encodable asn1Prim)
throws IOException
{
if (asn1Prim instanceof GeneralNames) {
return generalNamesToMap((GeneralNames) asn1Prim);
} else if (asn1Prim instanceof AuthorityKeyIdentifier) {
return authorityKeyIdToMap((AuthorityKeyIdentifier) asn1Prim);
} else if (asn1Prim instanceof BasicConstraints) {
return basicConstraintsToMap((BasicConstraints) asn1Prim);
} else if (asn1Prim instanceof SubjectKeyIdentifier) {
SubjectKeyIdentifier ski = (SubjectKeyIdentifier) asn1Prim;
return ski.getKeyIdentifier();
} else if (asn1Prim instanceof ExtendedKeyUsage) {
return extKeyUsageToList((ExtendedKeyUsage) asn1Prim);
} else if (asn1Prim instanceof KeyPurposeId) {
KeyPurposeId kpi = (KeyPurposeId) asn1Prim;
return kpi.getId();
} else if (asn1Prim instanceof KeyUsage) {
KeyUsage ku = (KeyUsage)asn1Prim;
return keyUsageToMap(ku);
} else if (asn1Prim instanceof DERBitString) {
DERBitString bitString = (DERBitString)asn1Prim;
return bitString.getString();
} else if (asn1Prim instanceof ASN1TaggedObject) {
ASN1TaggedObject taggedObj = (ASN1TaggedObject)asn1Prim;
return asn1ObjToObj(taggedObj.getObject());
} else if (asn1Prim instanceof ASN1Sequence) {
return asn1SeqToList((ASN1Sequence) asn1Prim);
} else if (asn1Prim instanceof ASN1String) {
ASN1String str = (ASN1String)asn1Prim;
return str.getString();
} else if (asn1Prim instanceof ASN1OctetString) {
ASN1OctetString str = (ASN1OctetString)asn1Prim;
return new String(str.getOctets(), "UTF-8");
} else {
// Return the raw data if there's no clear method of decoding
return asn1Prim.toASN1Primitive().getEncoded();
}
}
private static Map<String, Boolean> keyUsageToMap(KeyUsage ku) {
HashMap<String, Boolean> ret = new HashMap<String, Boolean>();
ret.put("digital_signature", ku.hasUsages(KeyUsage.digitalSignature));
ret.put("non_repudiation", ku.hasUsages(KeyUsage.nonRepudiation));
ret.put("key_encipherment", ku.hasUsages(KeyUsage.keyEncipherment));
ret.put("data_encipherment", ku.hasUsages(KeyUsage.dataEncipherment));
ret.put("key_agreement", ku.hasUsages(KeyUsage.keyAgreement));
ret.put("key_cert_sign", ku.hasUsages(KeyUsage.keyCertSign));
ret.put("crl_sign", ku.hasUsages(KeyUsage.cRLSign));
ret.put("encipher_only", ku.hasUsages(KeyUsage.encipherOnly));
ret.put("decipher_only", ku.hasUsages(KeyUsage.decipherOnly));
return ret;
}
private static List<Object> extKeyUsageToList(ExtendedKeyUsage eku)
throws IOException
{
List<Object> ret = new ArrayList<Object>();
for (KeyPurposeId kpid : eku.getUsages()) {
ret.add(asn1ObjToObj(kpid));
}
return ret;
}
private static Map<String, Object> basicConstraintsToMap(BasicConstraints bc) {
Map<String, Object> ret = new HashMap<String, Object>();
ret.put("is_ca", bc.isCA());
ret.put("path_len_constraint", bc.getPathLenConstraint());
return ret;
}
private static Map<String, Object> authorityKeyIdToMap(AuthorityKeyIdentifier akid)
throws IOException
{
Map<String, Object> ret = new HashMap<String, Object>();
ret.put("issuer", generalNamesToMap(akid.getAuthorityCertIssuer()));
ret.put("serial_number", akid.getAuthorityCertSerialNumber());
ret.put("key_identifier", akid.getKeyIdentifier());
return ret;
}
/**
* Convert an ASN1 Sequence to a Java list.
*
* @param seq The ASN1 sequence to be converted.
* @return A List of parsed ASN1 objects contained in the provided sequence.
* @throws IOException
*/
private static List<Object> asn1SeqToList(ASN1Sequence seq)
throws IOException
{
List<Object> ret = new ArrayList<Object>();
for (int i=0; i < seq.size(); i++) {
ret.add(asn1ObjToObj(seq.getObjectAt(i)));
}
return ret;
}
/** The key name each tag number represents in a GeneralNames data structure */
private static final Map<Integer, String> generalNameTags =
new HashMap<Integer, String>() {{
put(0, "other_name");
put(1, "rfc822_name");
put(2, "dns_name");
put(3, "x400_address");
put(4, "directory_name");
put(5, "edi_party_name");
put(6, "uri");
put(7, "ip");
put(8, "registered_id");
}};
/**
* Given type name, return the general name tag value.
*
* @param name The GeneralName tag name defined in generalNameTags
* @return The tag number of the name, or null if the name doesn't exist.
*/
private static Integer getGnTagFromName(String name) {
for (int i=0; i < generalNameTags.size(); i++) {
if (generalNameTags.get(i).equalsIgnoreCase(name)) {
return i;
}
}
return null;
}
/**
* Convert a Bouncy Castle GeneralNames object into a Java map where the key
* is the type of name defined, and the value is a list of names of that type.
*
* @param names The GeneralNames object to be parsed.
* @return A list of the names contained in each GeneralName in the
* GeneralNames data structure.
* @throws IOException
* @see org.bouncycastle.asn1.x509.GeneralName
*/
private static Map<String, List<String>> generalNamesToMap(GeneralNames names)
throws IOException
{
if (names != null) {
Map<String, List<String>> ret = new HashMap<String, List<String>>();
for (GeneralName generalName : names.getNames()) {
String type = generalNameTags.get(generalName.getTagNo());
if (ret.get(type) == null) {
ret.put(type, new ArrayList<String>());
}
String name = (String) asn1ObjToObj(generalName.getName().toASN1Primitive());
ret.get(type).add(name);
}
return ret;
} else {
return null;
}
}
/**
* Convert a list of general name maps into a GeneralNames object.
*
* @param gnMap A map containing name types and a list of names.
* @return A Bouncy Castle GeneralNames object.
* @see #generalNamesToMap(org.bouncycastle.asn1.x509.GeneralNames)
*/
private static GeneralNames mapToGeneralNames(Map<String, List<String>> gnMap) {
List<GeneralName> ret = new ArrayList<GeneralName>();
for (String type: gnMap.keySet()) {
Integer tag = getGnTagFromName(type);
if (tag == null) {
throw new IllegalArgumentException(
"Could not find a tag number for the type name '" +
type + '"');
}
for (String name: gnMap.get(type)) {
ret.add(new GeneralName(tag, name));
}
}
return new GeneralNames(ret.toArray(new GeneralName[ret.size()]));
}
}
|
src/java/com/puppetlabs/certificate_authority/ExtensionsUtils.java
|
package com.puppetlabs.certificate_authority;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.ASN1String;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERPrintableString;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.misc.MiscObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.Attribute;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import java.io.IOException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Utilities for working with X509 extensions.
*/
public class ExtensionsUtils {
/**
* Return true if the given OID is contained within the subtree of parent OID.
*
* @param parentOid The OID of the parent tree.
* @param oid The OID to compare.
* @return True if OID is a subtree
*/
public static boolean isSubtreeOf(String parentOid, String oid) {
if (parentOid.equals(oid)) {
return false;
} else {
return oid.startsWith(parentOid);
}
}
/**
* Given a Java X509Certificate object, return a list of maps representing
* all the X509 extensions embedded in the certificate. If no extensions
* exist on the certificate, the null is returned.
*
* @param cert The X509 certificate object.
* @return A list of maps describing each extensions in the provided
* certificate.
* @throws IOException
* @throws CertificateEncodingException
* @see #getExtensionList(Extensions)
*/
public static List<Map<String, Object>> getExtensionList(X509Certificate cert)
throws IOException, CertificateEncodingException
{
Extensions extensions = getExtensionsFromCert(cert);
if (extensions != null) {
return getExtensionList(extensions);
} else {
return null;
}
}
/**
* Given a Bouncy Castle CSR object, return a list of maps representing
* all the X509 extensions embedded in the CSR. If no extensions exist on
* the CSR, then null is returned.
*
* @param csr The Bouncy Castle CertificationRequest object
* @return A list of maps describing each extensions in the provided
* certificate.
* @throws IOException
* @see #getExtensionList(Extensions)
*/
public static List<Map<String, Object>> getExtensionList(PKCS10CertificationRequest csr)
throws IOException
{
Extensions extensions = getExtensionsFromCSR(csr);
if (extensions != null) {
return getExtensionList(extensions);
} else{
return null;
}
}
/**
* Given a Java certificate, get a map containing the value
* and criticality of the extensions described by the given OID. If the OID
* is not found in the certificate then null is returned.
*
* @param cert The Java X509 certificate object.
* @param oid The OID of the extension to be found.
* @return The map containing the extension value and critical flag.
*/
public static Map<String, Object> getExtension(X509Certificate cert, String oid)
throws IOException, CertificateEncodingException
{
Extensions extensions = getExtensionsFromCert(cert);
if (extensions != null) {
return makeExtensionMap(extensions, new ASN1ObjectIdentifier(oid));
} else {
return null;
}
}
/**
* Given a Bouncy Castle CSR, get a map describing an extension value and
* its criticality from its OID. If the extension is not found then null
* is returned.
*
* @param csr The Bouncy Castle CSR to extract an extension from.
* @param oid The OID of extension to find.
* @return A map describing the extension requested by its OID.
* @throws IOException
*/
public static Map<String, Object> getExtension(PKCS10CertificationRequest csr, String oid)
throws IOException
{
Extensions extensions = getExtensionsFromCSR(csr);
if (extensions != null) {
return makeExtensionMap(extensions, new ASN1ObjectIdentifier(oid));
} else {
return null;
}
}
/**
* Given a list of maps describing extensions, return a map containing
* the extensions described by the provided OID. Returns null if the OID
* doesn't exist in the provided list.
*
* @param extList A list of extensions returned by getExtensionList().
* @param oid The OID of the extension to find.
* @return The map describing the found extension, null if the oid doesn't exist.
* @see #getExtensionList(org.bouncycastle.asn1.x509.Extensions)
* @see #getExtensionList(java.security.cert.X509Certificate)
*/
public static Map<String, Object> getExtension(List<Map<String, Object>> extList,
String oid)
{
for (Map<String, Object> ext: extList) {
if (ext.get("oid").equals(oid)) {
return ext;
}
}
return null;
}
public static Object getExtensionValue(X509Certificate cert, String oid)
throws IOException, CertificateEncodingException
{
return getExtensionValue(getExtension(cert, oid));
}
public static Object getExtensionValue(PKCS10CertificationRequest csr,
String oid)
throws IOException
{
return getExtensionValue(getExtension(csr, oid));
}
public static Object getExtensionValue(List<Map<String, Object>> extList,
String oid)
{
return getExtensionValue(getExtension(extList, oid));
}
public static Object getExtensionValue(Map<String, Object> extMap) {
if (extMap != null) {
return extMap.get("value");
} else {
return null;
}
}
/**
* Given a Bouncy Castle Extensions container, return a list of maps
* representing all the X509 extensions embedded in the certificate.
*
* @param exts A Bouncy Castle Extensions container object.
* @return A list of maps describing each extensions in the provided
* certificate.
* @throws IOException
*/
private static List<Map<String, Object>> getExtensionList(Extensions exts)
throws IOException
{
List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
for (ASN1ObjectIdentifier oid : exts.getCriticalExtensionOIDs()) {
ret.add(makeExtensionMap(exts, oid, true));
}
for (ASN1ObjectIdentifier oid : exts.getNonCriticalExtensionOIDs()) {
ret.add(makeExtensionMap(exts, oid, false));
}
return ret;
}
/**
* Given an extensions container and an OID, extract the value and
* criticality flag and return the values in a map. If the extension is not
* found then null is returned.
*
* @param exts The Bouncy Castle extensions container.
* @param oid The OID of the extension to find.
* @return A map
* @throws IOException
*/
private static Map<String, Object> makeExtensionMap(Extensions exts,
ASN1ObjectIdentifier oid)
throws IOException
{
boolean critical = Arrays.asList(exts.getCriticalExtensionOIDs()).contains(oid);
return makeExtensionMap(exts, oid, critical);
}
/**
* Find the X509 Extensions from CSR object. If no extensions
* attribute is found then null is returned.
*
* @param csr The CSR object to extract the Extensions container from.
* @return An extensions container extracted form the CSR.
*/
static Extensions getExtensionsFromCSR(PKCS10CertificationRequest csr) {
for (Attribute attr : csr.getAttributes()) {
if (attr.getAttrType() == PKCSObjectIdentifiers.pkcs_9_at_extensionRequest) {
// TODO: All this casting shouldn't be needed.
ASN1Set extsAsn1 = attr.getAttrValues();
if (extsAsn1 != null) {
DERSet derSet = (DERSet) extsAsn1.getObjectAt(0);
if (derSet != null) {
return (Extensions) derSet.getObjectAt(0);
} else {
return null;
}
}
}
}
return null;
}
/**
* Given a list of maps which represent Extensions, produce a Bouncy Castle
* Extensions object which contains each extension parsed into Bouncy Castle
* Extension objects.
*
* @return The results Extensions container.
* @see #parseExtensionObject(java.util.Map)
*/
static Extensions getExtensionsObjFromMap(List<Map<String,Object>> extMapsList)
throws IOException
{
if ((extMapsList != null) && (extMapsList.size() > 0)) {
List<Extension> ret = new ArrayList<Extension>();
for (Map<String, Object> extObj : extMapsList) {
ret.add(parseExtensionObject(extObj));
}
return new Extensions(ret.toArray(new Extension[ret.size()]));
} else {
return null;
}
}
/**
* Provided a map which describes an X509 extension, parse it into a
* Bouncy Castle Extension object.
*
* @param extMap Map describing an extension.
* @return A parsed Extension object.
* @throws IOException
*/
static Extension parseExtensionObject(Map<String, Object> extMap)
throws IOException
{
ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier((String)extMap.get("oid"));
ASN1Object ret;
if (oid.equals(Extension.subjectAlternativeName) ||
oid.equals(Extension.issuerAlternativeName))
{
@SuppressWarnings("unchecked")
Map<String, List<String>> val = (Map<String, List<String>>) extMap.get("value");
ret = mapToGeneralNames(val);
} else {
throw new IllegalArgumentException(
"Parsing an extension with an OID=" +
oid.getId() + " is not yet supported.");
}
return new Extension(oid, (Boolean)extMap.get("critical"), new DEROctetString(ret));
}
/**
* Get a Bouncy Castle Extensions container from a Java X509 certificate
* object. If no extensions are found then null is returned.
*
* @param cert The Java X509 certificate object.
* @return A Bouncy Castle Extensions container object extracted from the
* certificate.
* @throws CertificateEncodingException
* @throws IOException
*/
private static Extensions getExtensionsFromCert(X509Certificate cert)
throws CertificateEncodingException, IOException
{
return new X509CertificateHolder(cert.getEncoded()).getExtensions();
}
/**
* Given an Extensions container, an OID, and a critical flag, create a map
* of this extension's data with the following keys:
*
* - "oid" : The OID of the extensions
* - "value" : A String, or list of Strings of this OID's data
* - "critical" : A bool set to true if this extensions is critical,
* false if it isn't.
*
* If the given OID doesn't exist in the extensions container then null is
* returned.
*
* @param exts A Bouncy Castle Extensions container containing the provided OID
* @param oid The OID of the extension to create the map for.
* @param critical True if this extension is critical, false if it isn't.
* @return A map representing the extension with the given OID which exists
* in the provided Extensions container.
* @throws IOException
*/
private static Map<String, Object> makeExtensionMap(Extensions exts,
ASN1ObjectIdentifier oid,
boolean critical)
throws IOException
{
Extension ext = exts.getExtension(oid);
if (ext != null) {
byte[] extensionData = ext.getExtnValue().getOctets();
ASN1Object asn1Value = binaryToASN1Object(oid, extensionData);
HashMap<String, Object> ret = new HashMap<String, Object>();
ret.put("oid", oid.getId());
ret.put("critical", critical);
ret.put("value", asn1ObjToObj(asn1Value));
return ret;
} else {
return null;
}
}
/**
* Convert a chunk of binary data into the Bouncy Castle ASN1 data structure
* which represents the data it contains accord to its OID. I've searched
* all over the BouncyCastle API and I can't seem to find this mapping
* defined anywhere, so I've created it here.
*
* @param oid The extension OID.
* @param data The binary data value of the extension with the given OID.
* @return An ASN1Object which contains the data described by the
* provided OID.
* @throws IOException
*/
private static ASN1Object binaryToASN1Object(ASN1ObjectIdentifier oid,
byte[] data)
throws IOException
{
if (oid.equals(Extension.subjectAlternativeName) ||
oid.equals(Extension.issuerAlternativeName))
{
return GeneralNames.getInstance(data);
} else if (oid.equals(Extension.authorityKeyIdentifier)) {
return AuthorityKeyIdentifier.getInstance(data);
} else if (oid.equals(Extension.subjectKeyIdentifier)) {
return SubjectKeyIdentifier.getInstance(data);
} else if (oid.equals(Extension.basicConstraints)) {
return BasicConstraints.getInstance(data);
} else if (oid.equals(Extension.keyUsage)) {
DERBitString bs = new DERBitString(data);
return new KeyUsage(bs.getPadBits());
} else if (oid.equals(Extension.extendedKeyUsage)) {
return ExtendedKeyUsage.getInstance(data);
} else if (oid.equals(MiscObjectIdentifiers.netscapeCertComment)) {
return new DERPrintableString(new String(data, "UTF8"));
} else {
// Most extensions are a simple string value.
return new DERPrintableString(new String(data, "UTF8"));
}
}
/**
* Convert a Bouncy Castle ASN1Object into a Java data structure, which
* will generally be in the form of a string, map, list or combination thereof.
* If this method can't determine a method of converting the ASN1 object then
* the raw byte array is returned.
*
* @param asn1Prim The ASN1 object to
* @return A Java data structure which represents the provided ASN1Object.
* @throws IOException
*/
private static Object asn1ObjToObj(ASN1Encodable asn1Prim)
throws IOException
{
if (asn1Prim instanceof GeneralNames) {
return generalNamesToMap((GeneralNames) asn1Prim);
} else if (asn1Prim instanceof AuthorityKeyIdentifier) {
return authorityKeyIdToMap((AuthorityKeyIdentifier) asn1Prim);
} else if (asn1Prim instanceof BasicConstraints) {
return basicConstraintsToMap((BasicConstraints) asn1Prim);
} else if (asn1Prim instanceof SubjectKeyIdentifier) {
SubjectKeyIdentifier ski = (SubjectKeyIdentifier) asn1Prim;
return ski.getKeyIdentifier();
} else if (asn1Prim instanceof ExtendedKeyUsage) {
return extKeyUsageToList((ExtendedKeyUsage) asn1Prim);
} else if (asn1Prim instanceof KeyPurposeId) {
KeyPurposeId kpi = (KeyPurposeId) asn1Prim;
return kpi.getId();
} else if (asn1Prim instanceof KeyUsage) {
KeyUsage ku = (KeyUsage)asn1Prim;
return keyUsageToMap(ku);
} else if (asn1Prim instanceof DERBitString) {
DERBitString bitString = (DERBitString)asn1Prim;
return bitString.getString();
} else if (asn1Prim instanceof ASN1TaggedObject) {
ASN1TaggedObject taggedObj = (ASN1TaggedObject)asn1Prim;
return asn1ObjToObj(taggedObj.getObject());
} else if (asn1Prim instanceof ASN1Sequence) {
return asn1SeqToList((ASN1Sequence) asn1Prim);
} else if (asn1Prim instanceof ASN1String) {
ASN1String str = (ASN1String)asn1Prim;
return str.getString();
} else if (asn1Prim instanceof ASN1OctetString) {
ASN1OctetString str = (ASN1OctetString)asn1Prim;
return new String(str.getOctets(), "UTF-8");
} else {
// Return the raw data if there's no clear method of decoding
return asn1Prim.toASN1Primitive().getEncoded();
}
}
private static Map<String, Boolean> keyUsageToMap(KeyUsage ku) {
HashMap<String, Boolean> ret = new HashMap<String, Boolean>();
ret.put("digital_signature", ku.hasUsages(KeyUsage.digitalSignature));
ret.put("non_repudiation", ku.hasUsages(KeyUsage.nonRepudiation));
ret.put("key_encipherment", ku.hasUsages(KeyUsage.keyEncipherment));
ret.put("data_encipherment", ku.hasUsages(KeyUsage.dataEncipherment));
ret.put("key_agreement", ku.hasUsages(KeyUsage.keyAgreement));
ret.put("key_cert_sign", ku.hasUsages(KeyUsage.keyCertSign));
ret.put("crl_sign", ku.hasUsages(KeyUsage.cRLSign));
ret.put("encipher_only", ku.hasUsages(KeyUsage.encipherOnly));
ret.put("decipher_only", ku.hasUsages(KeyUsage.decipherOnly));
return ret;
}
private static List<Object> extKeyUsageToList(ExtendedKeyUsage eku)
throws IOException
{
List<Object> ret = new ArrayList<Object>();
for (KeyPurposeId kpid : eku.getUsages()) {
ret.add(asn1ObjToObj(kpid));
}
return ret;
}
private static Map<String, Object> basicConstraintsToMap(BasicConstraints bc) {
Map<String, Object> ret = new HashMap<String, Object>();
ret.put("is_ca", bc.isCA());
ret.put("path_len_constraint", bc.getPathLenConstraint());
return ret;
}
private static Map<String, Object> authorityKeyIdToMap(AuthorityKeyIdentifier akid)
throws IOException
{
Map<String, Object> ret = new HashMap<String, Object>();
ret.put("issuer", generalNamesToMap(akid.getAuthorityCertIssuer()));
ret.put("serial_number", akid.getAuthorityCertSerialNumber());
ret.put("key_identifier", akid.getKeyIdentifier());
return ret;
}
/**
* Convert an ASN1 Sequence to a Java list.
*
* @param seq The ASN1 sequence to be converted.
* @return A List of parsed ASN1 objects contained in the provided sequence.
* @throws IOException
*/
private static List<Object> asn1SeqToList(ASN1Sequence seq)
throws IOException
{
List<Object> ret = new ArrayList<Object>();
for (int i=0; i < seq.size(); i++) {
ret.add(asn1ObjToObj(seq.getObjectAt(i)));
}
return ret;
}
/** The key name each tag number represents in a GeneralNames data structure */
private static final Map<Integer, String> generalNameTags =
new HashMap<Integer, String>() {{
put(0, "other_name");
put(1, "rfc822_name");
put(2, "dns_name");
put(3, "x400_address");
put(4, "directory_name");
put(5, "edi_party_name");
put(6, "uri");
put(7, "ip");
put(8, "registered_id");
}};
/**
* Given type name, return the general name tag value.
*
* @param name The GeneralName tag name defined in generalNameTags
* @return The tag number of the name, or null if the name doesn't exist.
*/
private static Integer getGnTagFromName(String name) {
for (int i=0; i < generalNameTags.size(); i++) {
if (generalNameTags.get(i).equalsIgnoreCase(name)) {
return i;
}
}
return null;
}
/**
* Convert a Bouncy Castle GeneralNames object into a Java map where the key
* is the type of name defined, and the value is a list of names of that type.
*
* @param names The GeneralNames object to be parsed.
* @return A list of the names contained in each GeneralName in the
* GeneralNames data structure.
* @throws IOException
* @see org.bouncycastle.asn1.x509.GeneralName
*/
private static Map<String, List<String>> generalNamesToMap(GeneralNames names)
throws IOException
{
if (names != null) {
Map<String, List<String>> ret = new HashMap<String, List<String>>();
for (GeneralName generalName : names.getNames()) {
String type = generalNameTags.get(generalName.getTagNo());
if (ret.get(type) == null) {
ret.put(type, new ArrayList<String>());
}
String name = (String) asn1ObjToObj(generalName.getName().toASN1Primitive());
ret.get(type).add(name);
}
return ret;
} else {
return null;
}
}
/**
* Convert a list of general name maps into a GeneralNames object.
*
* @param gnMap A map containing name types and a list of names.
* @return A Bouncy Castle GeneralNames object.
* @see #generalNamesToMap(org.bouncycastle.asn1.x509.GeneralNames)
*/
private static GeneralNames mapToGeneralNames(Map<String, List<String>> gnMap) {
List<GeneralName> ret = new ArrayList<GeneralName>();
for (String type: gnMap.keySet()) {
Integer tag = getGnTagFromName(type);
if (tag == null) {
throw new IllegalArgumentException(
"Could not find a tag number for the type name '" +
type + '"');
}
for (String name: gnMap.get(type)) {
ret.add(new GeneralName(tag, name));
}
}
return new GeneralNames(ret.toArray(new GeneralName[ret.size()]));
}
}
|
(PE-4373) Fixed retrieving extensions from CSR
|
src/java/com/puppetlabs/certificate_authority/ExtensionsUtils.java
|
(PE-4373) Fixed retrieving extensions from CSR
|
<ide><path>rc/java/com/puppetlabs/certificate_authority/ExtensionsUtils.java
<ide> * @return An extensions container extracted form the CSR.
<ide> */
<ide> static Extensions getExtensionsFromCSR(PKCS10CertificationRequest csr) {
<del> for (Attribute attr : csr.getAttributes()) {
<del> if (attr.getAttrType() == PKCSObjectIdentifiers.pkcs_9_at_extensionRequest) {
<del> // TODO: All this casting shouldn't be needed.
<del> ASN1Set extsAsn1 = attr.getAttrValues();
<del> if (extsAsn1 != null) {
<del> DERSet derSet = (DERSet) extsAsn1.getObjectAt(0);
<del> if (derSet != null) {
<del> return (Extensions) derSet.getObjectAt(0);
<del> } else {
<del> return null;
<del> }
<del> }
<add> Attribute[] attrs = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
<add> for (Attribute attr : attrs) {
<add> ASN1Set extsAsn1 = attr.getAttrValues();
<add> if (extsAsn1 != null) {
<add> return Extensions.getInstance(extsAsn1.getObjectAt(0));
<ide> }
<ide> }
<ide>
|
|
Java
|
mit
|
error: pathspec 'src/testProjects/KeyGeneration.java' did not match any file(s) known to git
|
11ccb38d655a78f92f7a98d1fa8777e5316814cb
| 1 |
jackpotsvr/Java-Conquer-Server
|
package testProjects;
public class KeyGeneration {
public static void main(String[]Args)
{
}
}
|
src/testProjects/KeyGeneration.java
|
Test projects created.
|
src/testProjects/KeyGeneration.java
|
Test projects created.
|
<ide><path>rc/testProjects/KeyGeneration.java
<add>package testProjects;
<add>
<add>public class KeyGeneration {
<add> public static void main(String[]Args)
<add> {
<add>
<add> }
<add>
<add>}
|
|
Java
|
mit
|
a0e8a0fc7722c177af0953def96bd569f4b9933f
| 0 |
JAGFin1/example-gradle-project
|
package com.github.example;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ExampleTest {
@Test
public void passingTest() {
assertTrue(true);
}
}
|
src/test/java/com/github/example/ExampleTest.java
|
package com.github.example;
import static org.junit.Assert.assert;
import org.junit.Test;
public class ExampleTest {
@Test
public void passingTest() {
assertTrue(true);
}
}
|
Update ExampleTest.java
|
src/test/java/com/github/example/ExampleTest.java
|
Update ExampleTest.java
|
<ide><path>rc/test/java/com/github/example/ExampleTest.java
<ide> package com.github.example;
<ide>
<del>import static org.junit.Assert.assert;
<add>import static org.junit.Assert.assertTrue;
<ide> import org.junit.Test;
<ide>
<ide> public class ExampleTest {
<ide>
<del> @Test
<del> public void passingTest() {
<del> assertTrue(true);
<del> }
<del>
<add> @Test
<add> public void passingTest() {
<add> assertTrue(true);
<add> }
<ide> }
|
|
Java
|
bsd-3-clause
|
73647001d0f575cbdcda7acdff9fc59633fdf577
| 0 |
NCIP/cagrid,NCIP/cagrid,NCIP/cagrid,NCIP/cagrid
|
package gov.nih.nci.cagrid.introduce.steps;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.introduce.TestCaseInfo;
import gov.nih.nci.cagrid.introduce.beans.ServiceDescription;
import gov.nih.nci.cagrid.introduce.beans.method.MethodType;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeExceptions;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeExceptionsException;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeInputs;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeInputsInput;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeOutput;
import gov.nih.nci.cagrid.introduce.beans.method.MethodsType;
import gov.nih.nci.cagrid.introduce.codegen.SyncTools;
import gov.nih.nci.cagrid.introduce.common.CommonTools;
import java.io.File;
import javax.xml.namespace.QName;
import com.atomicobject.haste.framework.Step;
public class AddComplexMethodWithFaultStep extends Step {
private TestCaseInfo tci;
private String methodName;
public AddComplexMethodWithFaultStep(TestCaseInfo tci, String methodName) {
this.tci = tci;
this.methodName = methodName;
}
public void runStep() throws Throwable {
System.out.println("Adding a complex method with fault.");
String pathtobasedir = System.getProperty("basedir");
System.out.println(pathtobasedir);
if (pathtobasedir == null) {
System.err.println("basedir system property not set");
throw new Exception("basedir system property not set");
}
// copy over the bookstore schema to be used with the test
Utils.copyFile(new File(pathtobasedir + File.separator + TestCaseInfo.GOLD_SCHEMA_DIR + File.separator
+ "bookstore.xsd"), new File(pathtobasedir + File.separator + tci.getDir() + File.separator + "schema"
+ File.separator + tci.getName() + File.separator + "bookstore.xsd"));
ServiceDescription introService = (ServiceDescription) Utils.deserializeDocument(pathtobasedir + File.separator
+ tci.getDir() + File.separator + "introduce.xml", ServiceDescription.class);
MethodsType methodsType = introService.getMethods();
MethodType method = new MethodType();
method.setName(methodName);
// set the output
MethodTypeOutput output = new MethodTypeOutput();
output.setLocation("./bookstore.xsd");
output.setType("Book");
output.setPackageName("bookstore");
output.setIsArray(new Boolean(false));
output.setNamespace("gme://projectmobius.org/1/BookStore");
// set some parameters
MethodTypeInputs inputs = new MethodTypeInputs();
MethodTypeInputsInput[] inputsArray = new MethodTypeInputsInput[1];
MethodTypeInputsInput input = new MethodTypeInputsInput();
input.setName("inputOne");
input.setType("Book");
input.setLocation("./bookstore.xsd");
input.setPackageName("bookstore");
input.setIsArray(new Boolean(true));
input.setNamespace("gme://projectmobius.org/1/BookStore");
inputsArray[0] = input;
inputs.setInput(inputsArray);
method.setInputs(inputs);
// set a fault
MethodTypeExceptionsException[] exceptionsArray = new MethodTypeExceptionsException[1];
MethodTypeExceptionsException exception = new MethodTypeExceptionsException();
exception.setName("testFault");
exceptionsArray[0] = exception;
MethodTypeExceptions exceptions = new MethodTypeExceptions();
exceptions.setException(exceptionsArray);
method.setExceptions(exceptions);
method.setOutput(output);
// add new method to array in bean
// this seems to be a wierd way be adding things....
MethodType[] newMethods;
int newLength = 0;
if (methodsType.getMethod() != null) {
newLength = methodsType.getMethod().length + 1;
newMethods = new MethodType[newLength];
System.arraycopy(methodsType.getMethod(), 0, newMethods, 0, methodsType.getMethod().length);
} else {
newLength = 1;
newMethods = new MethodType[newLength];
}
newMethods[newLength - 1] = method;
methodsType.setMethod(newMethods);
Utils.serializeDocument(pathtobasedir + File.separator + tci.getDir() + File.separator + "introduce.xml",
introService, new QName("gme://gov.nih.nci.cagrid/1/Introduce", "ServiceSkeleton"));
try {
SyncTools sync = new SyncTools(new File(pathtobasedir + File.separator + tci.getDir()));
sync.sync();
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
// look at the interface to make sure method exists.......
String serviceInterface = pathtobasedir + File.separator + tci.dir + File.separator + "src" + File.separator
+ tci.getPackageDir() + "/common/" + tci.getName() + "I.java";
assertTrue(StepTools.methodExists(serviceInterface, methodName));
String cmd = CommonTools.getAntAllCommand(pathtobasedir + File.separator + tci.getDir());
Process p = CommonTools.createAndOutputProcess(cmd);
p.waitFor();
assertEquals("Checking build status", 0, p.exitValue());
}
}
|
cagrid-1-0/caGrid/projects/introduce/test/src/java/Introduce/gov/nih/nci/cagrid/introduce/steps/AddComplexMethodWithFaultStep.java
|
package gov.nih.nci.cagrid.introduce.steps;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.introduce.TestCaseInfo;
import gov.nih.nci.cagrid.introduce.beans.ServiceDescription;
import gov.nih.nci.cagrid.introduce.beans.method.MethodType;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeExceptions;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeExceptionsException;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeInputs;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeInputsInput;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeOutput;
import gov.nih.nci.cagrid.introduce.beans.method.MethodsType;
import gov.nih.nci.cagrid.introduce.codegen.SyncTools;
import gov.nih.nci.cagrid.introduce.common.CommonTools;
import java.io.File;
import javax.xml.namespace.QName;
import com.atomicobject.haste.framework.Step;
public class AddComplexMethodWithFaultStep extends Step {
private TestCaseInfo tci;
private String methodName;
public AddComplexMethodWithFaultStep(TestCaseInfo tci, String methodName) {
this.tci = tci;
this.methodName = methodName;
}
public void runStep() throws Throwable {
System.out.println("Adding a complex method with fault.");
String pathtobasedir = System.getProperty("basedir");
System.out.println(pathtobasedir);
if (pathtobasedir == null) {
System.err.println("basedir system property not set");
throw new Exception("basedir system property not set");
}
// copy over the bookstore schema to be used with the test
Utils.copyFile(new File(pathtobasedir + File.separator + TestCaseInfo.GOLD_SCHEMA_DIR + File.separator
+ "bookstore.xsd"), new File(pathtobasedir + File.separator + tci.getDir() + File.separator + "schema"
+ File.separator + tci.getName() + File.separator + "bookstore.xsd"));
ServiceDescription introService = (ServiceDescription) Utils.deserializeDocument(pathtobasedir + File.separator
+ tci.getDir() + File.separator + "introduce.xml", ServiceDescription.class);
MethodsType methodsType = introService.getMethods();
MethodType method = new MethodType();
method.setName(methodName);
// set the output
MethodTypeOutput output = new MethodTypeOutput();
output.setLocation("./bookstore.xsd");
output.setType("Book");
output.setIsArray(new Boolean(false));
output.setNamespace("gme://projectmobius.org/1/BookStore");
// set some parameters
MethodTypeInputs inputs = new MethodTypeInputs();
MethodTypeInputsInput[] inputsArray = new MethodTypeInputsInput[1];
MethodTypeInputsInput input = new MethodTypeInputsInput();
input.setName("inputOne");
input.setType("Book");
input.setLocation("./bookstore.xsd");
input.setIsArray(new Boolean(true));
input.setNamespace("gme://projectmobius.org/1/BookStore");
inputsArray[0] = input;
inputs.setInput(inputsArray);
method.setInputs(inputs);
// set a fault
MethodTypeExceptionsException[] exceptionsArray = new MethodTypeExceptionsException[1];
MethodTypeExceptionsException exception = new MethodTypeExceptionsException();
exception.setName("testFault");
exceptionsArray[0] = exception;
MethodTypeExceptions exceptions = new MethodTypeExceptions();
exceptions.setException(exceptionsArray);
method.setExceptions(exceptions);
method.setOutput(output);
// add new method to array in bean
// this seems to be a wierd way be adding things....
MethodType[] newMethods;
int newLength = 0;
if (methodsType.getMethod() != null) {
newLength = methodsType.getMethod().length + 1;
newMethods = new MethodType[newLength];
System.arraycopy(methodsType.getMethod(), 0, newMethods, 0, methodsType.getMethod().length);
} else {
newLength = 1;
newMethods = new MethodType[newLength];
}
newMethods[newLength - 1] = method;
methodsType.setMethod(newMethods);
Utils.serializeDocument(pathtobasedir + File.separator + tci.getDir() + File.separator + "introduce.xml",
introService, new QName("gme://gov.nih.nci.cagrid/1/Introduce", "ServiceSkeleton"));
try {
SyncTools sync = new SyncTools(new File(pathtobasedir + File.separator + tci.getDir()));
sync.sync();
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
// look at the interface to make sure method exists.......
String serviceInterface = pathtobasedir + File.separator + tci.dir + File.separator + "src" + File.separator
+ tci.getPackageDir() + "/common/" + tci.getName() + "I.java";
assertTrue(StepTools.methodExists(serviceInterface, methodName));
String cmd = CommonTools.getAntAllCommand(pathtobasedir + File.separator + tci.getDir());
Process p = CommonTools.createAndOutputProcess(cmd);
p.waitFor();
assertEquals("Checking build status", 0, p.exitValue());
}
}
|
*** empty log message ***
|
cagrid-1-0/caGrid/projects/introduce/test/src/java/Introduce/gov/nih/nci/cagrid/introduce/steps/AddComplexMethodWithFaultStep.java
|
*** empty log message ***
|
<ide><path>agrid-1-0/caGrid/projects/introduce/test/src/java/Introduce/gov/nih/nci/cagrid/introduce/steps/AddComplexMethodWithFaultStep.java
<ide> MethodTypeOutput output = new MethodTypeOutput();
<ide> output.setLocation("./bookstore.xsd");
<ide> output.setType("Book");
<add> output.setPackageName("bookstore");
<ide> output.setIsArray(new Boolean(false));
<ide> output.setNamespace("gme://projectmobius.org/1/BookStore");
<ide>
<ide> input.setName("inputOne");
<ide> input.setType("Book");
<ide> input.setLocation("./bookstore.xsd");
<add> input.setPackageName("bookstore");
<ide> input.setIsArray(new Boolean(true));
<ide> input.setNamespace("gme://projectmobius.org/1/BookStore");
<ide> inputsArray[0] = input;
|
|
JavaScript
|
bsd-2-clause
|
6c458aed9eb146b2276e7cd15fadc7ae8f84f74f
| 0 |
seferov/yemeksepeti-extension,seferov/yemeksepeti-extension
|
// (c) 2015 Farhad Safarov <http://ferhad.in>
var jokerNotifier = {
_jokerUrl: 'https://www.yemeksepeti.com/basket/GetNewJokerOffer',
checkJoker: function() {
var _this = this,
ysRequest = {
'Culture': 'tr-TR',
'LanguageId': 'tr-TR'
};
chrome.cookies.getAll({}, function(data) {
$.each(data, function(index, cookie){
switch(cookie.name) {
case 'catalogName':
ysRequest['CatalogName'] = cookie.value;
break;
case 'loginToken':
ysRequest['Token'] = cookie.value;
break;
}
});
_this._fetchResult(ysRequest);
})
},
_fetchResult: function(ysRequest) {
var _this = this;
$.ajax({
url: this._jokerUrl,
type: 'post',
data: {
'ysRequest': ysRequest
},
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest'
},
dataType: 'json',
success: function (data) {
_this.displayResult(data);
}
});
},
displayResult: function(data) {
var resultArea = $('.result');
if (data.OfferItems && data.OfferItems.length) {
if (typeof(startTimer) === typeof(Function)) {
// Remaining duration
var duration = $('<div/>', {
'id': 'duration',
'class': 'strong'
});
resultArea.append(duration);
startTimer(data.RemainingDuration/1000, duration);
}
var table = $('<table/>');
$.each(data.OfferItems, function(index, offer) {
var row = $('<tr/>', {
'data-href': 'http://www.yemeksepeti.com' + offer.Restaurant.RestaurantUrl
});
row.append($('<td/>').html($('<img />', {
src: 'http:'+offer.Restaurant.JokerImageUrl,
alt: offer.Restaurant.DisplayName,
width: 60
})));
row.append($('<td/>').text(offer.Restaurant.DisplayName));
row.append($('<td/>', {'class': 'strong'}).html(offer.Restaurant.AveragePoint));
table.append(row);
});
resultArea.append(table);
chrome.browserAction.setBadgeText ( { text: data.OfferItems.length.toString() } );
}
else {
resultArea.html(data.IsValid ? 'Joker yok :(' : data.Message);
chrome.browserAction.setBadgeText ( { text: '' } );
}
}
};
|
js/joker_notifier.js
|
// (c) 2015 Farhad Safarov <http://ferhad.in>
var jokerNotifier = {
_jokerUrl: 'https://www.yemeksepeti.com/basket/GetNewJokerOffer',
checkJoker: function() {
var _this = this,
ysRequest = {
'Culture': 'tr-TR',
'LanguageId': 'tr-TR'
};
chrome.cookies.getAll({}, function(data) {
$.each(data, function(index, cookie){
switch(cookie.name) {
case 'catalogName':
ysRequest['CatalogName'] = cookie.value;
break;
case 'loginToken':
ysRequest['Token'] = cookie.value;
break;
}
});
_this._fetchResult(ysRequest);
})
},
_fetchResult: function(ysRequest) {
var _this = this;
$.ajax({
url: this._jokerUrl,
type: 'post',
data: {
'ysRequest': ysRequest
},
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest'
},
dataType: 'json',
success: function (data) {
_this.displayResult(data);
}
});
},
displayResult: function(data) {
var resultArea = $('.result');
if (data.OfferItems && data.OfferItems.length) {
if (typeof(startTimer) === typeof(Function)) {
// Remaining duration
var duration = $('<div/>', {
'id': 'duration',
'class': 'strong'
});
resultArea.append(duration);
startTimer(data.RemainingDuration/1000, duration);
}
var table = $('<table/>');
$.each(data.OfferItems, function(index, offer) {
var row = $('<tr/>', {
'data-href': 'http://www.yemeksepeti.com' + offer.Restaurant.RestaurantUrl
});
row.append($('<td/>').html($('<img />', {
src: 'http:'+offer.Restaurant.JokerImageUrl,
alt: offer.Restaurant.DisplayName,
width: 60
})));
row.append($('<td/>').text(offer.Restaurant.DisplayName));
row.append($('<td/>', {'class': 'strong'}).html(offer.Restaurant.AveragePoint));
table.append(row);
});
resultArea.append(table);
chrome.browserAction.setBadgeText ( { text: data.OfferItems.length.toString() } );
}
else {
resultArea.html(data.isValid ? 'Joker yok :(' : data.Message);
chrome.browserAction.setBadgeText ( { text: '' } );
}
}
};
|
typo fixed
|
js/joker_notifier.js
|
typo fixed
|
<ide><path>s/joker_notifier.js
<ide> chrome.browserAction.setBadgeText ( { text: data.OfferItems.length.toString() } );
<ide> }
<ide> else {
<del> resultArea.html(data.isValid ? 'Joker yok :(' : data.Message);
<add> resultArea.html(data.IsValid ? 'Joker yok :(' : data.Message);
<ide> chrome.browserAction.setBadgeText ( { text: '' } );
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
c1b074d56dd3430aad0be51a10015b618923e93c
| 0 |
au-research/ANDS-ResearchVocabularies-Toolkit,au-research/ANDS-ResearchVocabularies-Toolkit,au-research/ANDS-Vocabs-Toolkit,au-research/ANDS-ResearchVocabularies-Toolkit,au-research/ANDS-Vocabs-Toolkit,au-research/ANDS-Vocabs-Toolkit
|
/** See the file "LICENSE" for the full license governing this code. */
package au.org.ands.vocabs.toolkit.restlet;
import java.lang.invoke.MethodHandles;
import java.util.HashMap;
import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import au.org.ands.vocabs.toolkit.tasks.TaskInfo;
import au.org.ands.vocabs.toolkit.tasks.TaskRunner;
import au.org.ands.vocabs.toolkit.tasks.TaskStatus;
import au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils;
/** Restlets for running Toolkit supported tasks. */
@Path("runTask")
public class RunTask {
/** Logger for this class. */
private Logger logger = LoggerFactory.getLogger(
MethodHandles.lookup().lookupClass());
/** Injected servlet context. */
@Context
private ServletContext context;
/** Run a task.
* @param taskId The task id. The id of the task
* in the task database table.
* @return The result of running the task, either in JSON or XML format.
*/
@Path("{taskId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@GET
public final HashMap<String, String> runTask(
@PathParam("taskId") final int taskId) {
logger.debug("called runTask, taskid = " + taskId);
// Initialize these to null/empty values. On success of
// the try, taskInfo will be non-null, and throwableText
// will remain empty. On failure, taskInfo will remain null,
// and throwableText will be non-empty.
TaskInfo taskInfo = null;
String throwableText = "";
try {
taskInfo = ToolkitFileUtils.getTaskInfo(taskId);
} catch (Throwable e) {
throwableText = "; caught exception: " + e.getMessage();
logger.error("Caught an exception getting TaskInfo for task id: "
+ taskId, e);
}
if (taskInfo == null) {
// Either an exception getting the data from the database,
// or an error generated by the validity checks in getTaskInfo().
HashMap<String, String> response =
new HashMap<String, String>();
response.put("status", TaskStatus.ERROR);
response.put("runTask", "Unable to get all task details for"
+ " task with id " + taskId + throwableText);
return response;
} else {
TaskRunner runner = new TaskRunner(taskInfo);
runner.runTask();
return runner.getResults();
}
}
}
|
src/main/java/au/org/ands/vocabs/toolkit/restlet/RunTask.java
|
/** See the file "LICENSE" for the full license governing this code. */
package au.org.ands.vocabs.toolkit.restlet;
import java.lang.invoke.MethodHandles;
import java.util.HashMap;
import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import au.org.ands.vocabs.toolkit.tasks.TaskInfo;
import au.org.ands.vocabs.toolkit.tasks.TaskRunner;
import au.org.ands.vocabs.toolkit.tasks.TaskStatus;
import au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils;
/** Restlets for running a Toolkit supported tasks. */
@Path("runTask")
public class RunTask {
/** Logger for this class. */
private Logger logger = LoggerFactory.getLogger(
MethodHandles.lookup().lookupClass());
/** Injected servlet context. */
@Context
private ServletContext context;
/** Get the list of PoolParty projects.
* @param taskId The task id.
* @return The list of PoolParty projects, in JSON format,
* as returned by PoolParty. */
@Path("{taskId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@GET
public final HashMap<String, String> runTask(
@PathParam("taskId") final int taskId) {
logger.debug("called runTask, taskid = " + taskId);
// Initialize these to null/empty values. On success of
// the try, taskInfo will be non-null, and throwableText
// will remain empty. On failure, taskInfo will remain null,
// and throwableText will be non-empty.
TaskInfo taskInfo = null;
String throwableText = "";
try {
taskInfo = ToolkitFileUtils.getTaskInfo(taskId);
} catch (Throwable e) {
throwableText = "; caught exception: " + e.getMessage();
logger.error("Caught an exception getting TaskInfo for task id: "
+ taskId, e);
}
if (taskInfo == null) {
// Either an exception getting the data from the database,
// or an error generated by the validity checks in getTaskInfo().
HashMap<String, String> response =
new HashMap<String, String>();
response.put("status", TaskStatus.ERROR);
response.put("runTask", "Unable to get all task details for"
+ " task with id " + taskId + throwableText);
return response;
} else {
TaskRunner runner = new TaskRunner(taskInfo);
runner.runTask();
return runner.getResults();
}
}
}
|
Fix Javadoc comments for RunTask
The Javadoc comments for the runTask() restlet method
were copied/pasted from elsewhere, and not updated.
Make them reflect what the method actually does.
|
src/main/java/au/org/ands/vocabs/toolkit/restlet/RunTask.java
|
Fix Javadoc comments for RunTask
|
<ide><path>rc/main/java/au/org/ands/vocabs/toolkit/restlet/RunTask.java
<ide> import au.org.ands.vocabs.toolkit.tasks.TaskStatus;
<ide> import au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils;
<ide>
<del>/** Restlets for running a Toolkit supported tasks. */
<add>/** Restlets for running Toolkit supported tasks. */
<ide> @Path("runTask")
<ide> public class RunTask {
<ide>
<ide> @Context
<ide> private ServletContext context;
<ide>
<del> /** Get the list of PoolParty projects.
<del> * @param taskId The task id.
<del> * @return The list of PoolParty projects, in JSON format,
<del> * as returned by PoolParty. */
<add> /** Run a task.
<add> * @param taskId The task id. The id of the task
<add> * in the task database table.
<add> * @return The result of running the task, either in JSON or XML format.
<add> */
<ide> @Path("{taskId}")
<ide> @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
<ide> @GET
|
|
Java
|
bsd-3-clause
|
c51ceb3e10f940907eba434422cbc86d389d4091
| 0 |
ra4king/GameUtils
|
package com.ra4king.gameutils.gameworld;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Transparency;
import java.util.ArrayList;
import com.ra4king.gameutils.Art;
import com.ra4king.gameutils.Entity;
import com.ra4king.gameutils.Game;
import com.ra4king.gameutils.Screen;
import com.ra4king.gameutils.util.Bag;
/**
* A GameWorld is a container of Entities. It has a z-buffer that goes in back-to-front order, 0 being the back.
* @author Roi Atalla
*/
public class GameWorld implements Screen {
private Game parent;
private ArrayList<Bag<Entity>> entities;
private ArrayList<Temp> temp;
private Image bg;
private String bgImage;
private double xOffset, yOffset;
private boolean hasInited, hasShown;
private volatile boolean isLooping;
/**
* Initializes this object.
*/
public GameWorld() {
entities = new ArrayList<Bag<Entity>>();
entities.add(new Bag<Entity>());
temp = new ArrayList<Temp>();
setBackground(Color.lightGray);
}
public void init(Game game) {
parent = game;
//for(Entity e : getEntities())
preLoop();
try{
for(Bag<Entity> b : entities)
for(Entity e : b)
if(e != null)
e.init(this);
}
finally {
postLoop();
}
hasInited = true;
}
/**
* Calls each Entity's <code>show()</code> method in z-index order.
*/
public synchronized void show() {
hasShown = true;
//for(Entity e : getEntities())
preLoop();
try{
for(Bag<Entity> b : entities)
for(Entity e : b)
if(e != null)
e.show();
}
finally {
postLoop();
}
}
/**
* Calls each Entity's <code>hide()</code> method in z-index order.
*/
public synchronized void hide() {
hasShown = false;
//for(Entity e : getEntities())
preLoop();
try{
for(Bag<Entity> b : entities)
for(Entity e : b)
if(e != null)
e.hide();
}
finally {
postLoop();
}
}
public synchronized void paused() {
//for(Entity e : getEntities())
preLoop();
try{
for(Bag<Entity> b : entities)
for(Entity e : b)
if(e != null)
e.paused();
}
finally {
postLoop();
}
}
public synchronized void resumed() {
//for(Entity e : getEntities())
preLoop();
try{
for(Bag<Entity> b : entities)
for(Entity e : b)
if(e != null)
e.resumed();
}
finally {
postLoop();
}
}
public synchronized void resized(int width, int height) {}
/**
* Calls each Entity's <code>update(long)</code> method in z-index order.
* @param deltaTime The time passed since the last call to it.
*/
public synchronized void update(long deltaTime) {
//for(Entity e : getEntities())
preLoop();
try {
for(Bag<Entity> b : entities)
for(Entity e : b)
if(e != null)
try{
e.update(deltaTime);
}
catch(Exception exc) {
exc.printStackTrace();
}
}
finally {
postLoop();
}
}
/**
* Draws the background then all the Entities in z-index order.
* @param g The Graphics context to draw to the screen.
*/
public synchronized void draw(Graphics2D g) {
g = (Graphics2D)g.create();
Image bg = (this.bg == null ? parent.getArt().get(bgImage) : this.bg);
if(bg != null)
g.drawImage(bg,0,0,getWidth(),getHeight(),0,0,bg.getWidth(null),bg.getHeight(null),null);
//for(Entity e : getEntities())
preLoop();
g.translate(xOffset, yOffset);
try{
for(Bag<Entity> b : entities)
for(Entity e : b)
try{
if(e != null)
e.draw((Graphics2D)g.create());
}
catch(Exception exc) {
exc.printStackTrace();
}
}
finally {
postLoop();
}
}
/**
* @return The parent of this object.
*/
public Game getGame() {
return parent;
}
/**
* Adds the Entity with a z-index of 0.
* @param e The Entity to be added.
* @return The Entity that was added.
*/
public synchronized Entity add(Entity e) {
return add(0,e);
}
/**
* Adds the Entity with the specified z-index.
* @param e The Entity to be added.
* @param zindex The z-index of this Entity.
* @return The Entity that was added.
*/
public synchronized Entity add(int zindex, Entity e) {
if(isLooping) {
temp.add(new Temp(zindex,e));
}
else {
while(zindex >= entities.size())
entities.add(new Bag<Entity>());
entities.get(zindex).add(e);
if(hasInited)
e.init(this);
if(hasShown)
e.show();
}
return e;
}
/**
* Returns true if this GameWorld contains this Entity.
* @param e The Entity to search for.
* @return True if this GameWorld contains this Entity, false otherwise.
*/
public boolean contains(Entity e) {
if(isLooping && temp.contains(e))
return true;
return getEntities().contains(e);
}
public boolean replace(Entity old, Entity e) {
if(isLooping) {
int i = temp.indexOf(old);
if(i >= 0) {
temp.get(i).e = e;
return true;
}
}
int zindex = getZIndex(old);
if(zindex < 0)
return false;
boolean isNew = getZIndex(e) < 0;
remove(e);
Bag<Entity> bag = entities.get(zindex);
bag.set(bag.indexOf(old),e);
if(isNew) {
e.init(this);
e.show();
}
return true;
}
/**
* Removes the Entity from the world.
* @param e The Entity to remove.
* @return True if the Entity was found and removed, false if the Entity was not found.
*/
public synchronized boolean remove(Entity e) {
boolean removed = false;
for(Bag<Entity> bag : entities)
removed |= bag.remove(e);
if(removed)
e.hide();
return removed;
}
/**
* Clears this game world.
*/
public synchronized void clear() {
entities.clear();
temp.clear();
System.gc();
entities.add(new Bag<Entity>());
}
/**
* Changes the z-index of the specified Entity.
* @param e The Entity whose z-index is changed.
* @param newZIndex The new z-index
* @return True if the Entity was found and updated, false otherwise.
*/
public synchronized boolean changeZIndex(Entity e, int newZIndex) {
if(isLooping) {
int i = temp.indexOf(e);
if(i >= 0) {
temp.get(i).zIndex = newZIndex;
return true;
}
}
if(!remove(e))
return false;
add(newZIndex,e);
e.show();
return true;
}
/**
* Returns the z-index of the specified Entity.
* @param e The Entity who's index is returned.
* @return The z-index of the specified Entity, or -1 if the Entity was not found.
*/
public synchronized int getZIndex(Entity e) {
if(isLooping) {
int i = temp.indexOf(e);
if(i >= 0)
return temp.get(i).zIndex;
}
for(int a = 0; a < entities.size(); a++)
if(entities.get(a).indexOf(e) >= 0)
return a;
return -1;
}
/**
* Returns true if the specified z-index exists.
* @param zindex The z-index to check.
* @return True if the specified z-index exists, false otherwise.
*/
public synchronized boolean containsZIndex(int zindex) {
return zindex < entities.size();
}
/**
* A list of all Entities at the specified z-index.
* @param zindex The z-index.
* @return A list of all Entities at the specified z-index.
*/
public synchronized ArrayList<Entity> getEntitiesAt(int zindex) {
return entities.get(zindex);
}
/**
* A list of all Entities in this entire world.
* @return A list of all Entities in this world in z-index order.
*/
public synchronized ArrayList<Entity> getEntities() {
ArrayList<Entity> allEntities = new ArrayList<Entity>();
for(Bag<Entity> bag : entities)
allEntities.addAll(bag);
return allEntities;
}
/**
* Sets the background of this GameWorld with an image in Art.
* @param s The associated name of an image in Art. This image will be drawn before all other Entities.
*/
public synchronized void setBackground(String s) {
bg = null;
bgImage = s;
}
/**
* Sets the background of this GameWorld. A compatible image is created.
* @param bg The image to be drawn before all other Entities.
*/
public synchronized void setBackground(Image bg) {
bgImage = null;
this.bg = Art.createCompatibleImage(bg);
}
/**
* Sets the background to the specified color.
* This method creates a 1x1 image with the specified color
* and stretches it to the width and height of the parent.
* @param color The color to be used as the entire background. It will be drawn before all other Entities.
*/
public synchronized void setBackground(Color color) {
bgImage = null;
bg = Art.createCompatibleImage(1, 1, color.getAlpha() == 0 || color.getAlpha() == 255 ? (color.getAlpha() == 0 ? Transparency.BITMASK : Transparency.OPAQUE) : Transparency.TRANSLUCENT);
Graphics g = bg.getGraphics();
g.setColor(color);
g.fillRect(0,0,1,1);
g.dispose();
}
/**
* Returns the background image.
* @return The image used as the background.
*/
public Image getBackgroundImage() {
if(bg == null)
return parent.getArt().get(bgImage);
return bg;
}
/**
* @return The total number of Entities in this world.
*/
public synchronized int size() {
return getEntities().size();
}
/**
* This calls the parent's getWidth() method.
* @return The width of this world.
*/
public int getWidth() {
return parent.getWidth();
}
/**
* This calls the parent's getHeight() method.
* @return The height of this world.
*/
public int getHeight() {
return parent.getHeight();
}
public void setXOffset(double xOffset) {
this.xOffset = xOffset;
}
public double getXOffset() {
return xOffset;
}
public void setYOffset(double yOffset) {
this.yOffset = yOffset;
}
public double getYOffset() {
return yOffset;
}
public void preLoop() {
if(isLooping)
return;
temp.clear();
isLooping = true;
}
public void postLoop() {
if(!isLooping)
return;
isLooping = false;
for(Temp p : temp)
add(p.zIndex,p.e);
temp.clear();
for(Bag<Entity> bag : entities)
bag.remove(null);
}
private class Temp {
private Entity e;
private int zIndex;
Temp(int zIndex, Entity e) {
this.zIndex = zIndex;
this.e = e;
}
}
}
|
src/com/ra4king/gameutils/gameworld/GameWorld.java
|
package com.ra4king.gameutils.gameworld;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Transparency;
import java.util.ArrayList;
import com.ra4king.gameutils.Art;
import com.ra4king.gameutils.Entity;
import com.ra4king.gameutils.Game;
import com.ra4king.gameutils.Screen;
import com.ra4king.gameutils.util.Bag;
/**
* A GameWorld is a container of Entities. It has a z-buffer that goes in back-to-front order, 0 being the back.
* @author Roi Atalla
*/
public class GameWorld implements Screen {
private Game parent;
private ArrayList<Bag<Entity>> entities;
private ArrayList<Temp> temp;
private Image bg;
private String bgImage;
private double xOffset, yOffset;
private boolean hasInited, hasShown;
private volatile boolean isLooping;
/**
* Initializes this object.
*/
public GameWorld() {
entities = new ArrayList<Bag<Entity>>();
entities.add(new Bag<Entity>());
temp = new ArrayList<Temp>();
setBackground(Color.lightGray);
}
public void init(Game game) {
parent = game;
//for(Entity e : getEntities())
preLoop();
try{
for(Bag<Entity> b : entities)
for(Entity e : b)
if(e != null)
e.init(this);
}
finally {
postLoop();
}
hasInited = true;
}
/**
* Calls each Entity's <code>show()</code> method in z-index order.
*/
public synchronized void show() {
hasShown = true;
//for(Entity e : getEntities())
preLoop();
try{
for(Bag<Entity> b : entities)
for(Entity e : b)
if(e != null)
e.show();
}
finally {
postLoop();
}
}
/**
* Calls each Entity's <code>hide()</code> method in z-index order.
*/
public synchronized void hide() {
hasShown = false;
//for(Entity e : getEntities())
preLoop();
try{
for(Bag<Entity> b : entities)
for(Entity e : b)
if(e != null)
e.hide();
}
finally {
postLoop();
}
}
public synchronized void paused() {
//for(Entity e : getEntities())
preLoop();
try{
for(Bag<Entity> b : entities)
for(Entity e : b)
if(e != null)
e.paused();
}
finally {
postLoop();
}
}
public synchronized void resumed() {
//for(Entity e : getEntities())
preLoop();
try{
for(Bag<Entity> b : entities)
for(Entity e : b)
if(e != null)
e.resumed();
}
finally {
postLoop();
}
}
public synchronized void resized(int width, int height) {}
/**
* Calls each Entity's <code>update(long)</code> method in z-index order.
* @param deltaTime The time passed since the last call to it.
*/
public synchronized void update(long deltaTime) {
//for(Entity e : getEntities())
preLoop();
try {
for(Bag<Entity> b : entities)
for(Entity e : b)
if(e != null)
try{
e.update(deltaTime);
}
catch(Exception exc) {
exc.printStackTrace();
}
}
finally {
postLoop();
}
}
/**
* Draws the background then all the Entities in z-index order.
* @param g The Graphics context to draw to the screen.
*/
public synchronized void draw(Graphics2D g) {
Image bg = (this.bg == null ? parent.getArt().get(bgImage) : this.bg);
if(bg != null)
g.drawImage(bg,0,0,getWidth(),getHeight(),0,0,bg.getWidth(null),bg.getHeight(null),null);
//for(Entity e : getEntities())
preLoop();
g.translate(xOffset, yOffset);
try{
for(Bag<Entity> b : entities)
for(Entity e : b)
try{
if(e != null)
e.draw((Graphics2D)g.create());
}
catch(Exception exc) {
exc.printStackTrace();
}
}
finally {
postLoop();
}
}
/**
* @return The parent of this object.
*/
public Game getGame() {
return parent;
}
/**
* Adds the Entity with a z-index of 0.
* @param e The Entity to be added.
* @return The Entity that was added.
*/
public synchronized Entity add(Entity e) {
return add(0,e);
}
/**
* Adds the Entity with the specified z-index.
* @param e The Entity to be added.
* @param zindex The z-index of this Entity.
* @return The Entity that was added.
*/
public synchronized Entity add(int zindex, Entity e) {
if(isLooping) {
temp.add(new Temp(zindex,e));
}
else {
while(zindex >= entities.size())
entities.add(new Bag<Entity>());
entities.get(zindex).add(e);
if(hasInited)
e.init(this);
if(hasShown)
e.show();
}
return e;
}
/**
* Returns true if this GameWorld contains this Entity.
* @param e The Entity to search for.
* @return True if this GameWorld contains this Entity, false otherwise.
*/
public boolean contains(Entity e) {
if(isLooping && temp.contains(e))
return true;
return getEntities().contains(e);
}
public boolean replace(Entity old, Entity e) {
if(isLooping) {
int i = temp.indexOf(old);
if(i >= 0) {
temp.get(i).e = e;
return true;
}
}
int zindex = getZIndex(old);
if(zindex < 0)
return false;
boolean isNew = getZIndex(e) < 0;
remove(e);
Bag<Entity> bag = entities.get(zindex);
bag.set(bag.indexOf(old),e);
if(isNew) {
e.init(this);
e.show();
}
return true;
}
/**
* Removes the Entity from the world.
* @param e The Entity to remove.
* @return True if the Entity was found and removed, false if the Entity was not found.
*/
public synchronized boolean remove(Entity e) {
boolean removed = false;
for(Bag<Entity> bag : entities)
removed |= bag.remove(e);
if(removed)
e.hide();
return removed;
}
/**
* Clears this game world.
*/
public synchronized void clear() {
entities.clear();
temp.clear();
System.gc();
entities.add(new Bag<Entity>());
}
/**
* Changes the z-index of the specified Entity.
* @param e The Entity whose z-index is changed.
* @param newZIndex The new z-index
* @return True if the Entity was found and updated, false otherwise.
*/
public synchronized boolean changeZIndex(Entity e, int newZIndex) {
if(isLooping) {
int i = temp.indexOf(e);
if(i >= 0) {
temp.get(i).zIndex = newZIndex;
return true;
}
}
if(!remove(e))
return false;
add(newZIndex,e);
e.show();
return true;
}
/**
* Returns the z-index of the specified Entity.
* @param e The Entity who's index is returned.
* @return The z-index of the specified Entity, or -1 if the Entity was not found.
*/
public synchronized int getZIndex(Entity e) {
if(isLooping) {
int i = temp.indexOf(e);
if(i >= 0)
return temp.get(i).zIndex;
}
for(int a = 0; a < entities.size(); a++)
if(entities.get(a).indexOf(e) >= 0)
return a;
return -1;
}
/**
* Returns true if the specified z-index exists.
* @param zindex The z-index to check.
* @return True if the specified z-index exists, false otherwise.
*/
public synchronized boolean containsZIndex(int zindex) {
return zindex < entities.size();
}
/**
* A list of all Entities at the specified z-index.
* @param zindex The z-index.
* @return A list of all Entities at the specified z-index.
*/
public synchronized ArrayList<Entity> getEntitiesAt(int zindex) {
return entities.get(zindex);
}
/**
* A list of all Entities in this entire world.
* @return A list of all Entities in this world in z-index order.
*/
public synchronized ArrayList<Entity> getEntities() {
ArrayList<Entity> allEntities = new ArrayList<Entity>();
for(Bag<Entity> bag : entities)
allEntities.addAll(bag);
return allEntities;
}
/**
* Sets the background of this GameWorld with an image in Art.
* @param s The associated name of an image in Art. This image will be drawn before all other Entities.
*/
public synchronized void setBackground(String s) {
bg = null;
bgImage = s;
}
/**
* Sets the background of this GameWorld. A compatible image is created.
* @param bg The image to be drawn before all other Entities.
*/
public synchronized void setBackground(Image bg) {
bgImage = null;
this.bg = Art.createCompatibleImage(bg);
}
/**
* Sets the background to the specified color.
* This method creates a 1x1 image with the specified color
* and stretches it to the width and height of the parent.
* @param color The color to be used as the entire background. It will be drawn before all other Entities.
*/
public synchronized void setBackground(Color color) {
bgImage = null;
bg = Art.createCompatibleImage(1, 1, color.getAlpha() == 0 || color.getAlpha() == 255 ? (color.getAlpha() == 0 ? Transparency.BITMASK : Transparency.OPAQUE) : Transparency.TRANSLUCENT);
Graphics g = bg.getGraphics();
g.setColor(color);
g.fillRect(0,0,1,1);
g.dispose();
}
/**
* Returns the background image.
* @return The image used as the background.
*/
public Image getBackgroundImage() {
if(bg == null)
return parent.getArt().get(bgImage);
return bg;
}
/**
* @return The total number of Entities in this world.
*/
public synchronized int size() {
return getEntities().size();
}
/**
* This calls the parent's getWidth() method.
* @return The width of this world.
*/
public int getWidth() {
return parent.getWidth();
}
/**
* This calls the parent's getHeight() method.
* @return The height of this world.
*/
public int getHeight() {
return parent.getHeight();
}
public void setXOffset(double xOffset) {
this.xOffset = xOffset;
}
public double getXOffset() {
return xOffset;
}
public void setYOffset(double yOffset) {
this.yOffset = yOffset;
}
public double getYOffset() {
return yOffset;
}
public void preLoop() {
if(isLooping)
return;
temp.clear();
isLooping = true;
}
public void postLoop() {
if(!isLooping)
return;
isLooping = false;
for(Temp p : temp)
add(p.zIndex,p.e);
temp.clear();
for(Bag<Entity> bag : entities)
bag.remove(null);
}
private class Temp {
private Entity e;
private int zIndex;
Temp(int zIndex, Entity e) {
this.zIndex = zIndex;
this.e = e;
}
}
}
|
Setup draw() correctly with the X and Y offsets.
|
src/com/ra4king/gameutils/gameworld/GameWorld.java
|
Setup draw() correctly with the X and Y offsets.
|
<ide><path>rc/com/ra4king/gameutils/gameworld/GameWorld.java
<ide> * @param g The Graphics context to draw to the screen.
<ide> */
<ide> public synchronized void draw(Graphics2D g) {
<add> g = (Graphics2D)g.create();
<add>
<ide> Image bg = (this.bg == null ? parent.getArt().get(bgImage) : this.bg);
<ide>
<ide> if(bg != null)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.