Dataset Viewer
Auto-converted to Parquet
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
0c2e554e2735954ef3180dcc99ccaacb78aa5f0a
0
hs-jenkins-bot/Singularity,evertrue/Singularity,tejasmanohar/Singularity,calebTomlinson/Singularity,nvoron23/Singularity,hs-jenkins-bot/Singularity,calebTomlinson/Singularity,evertrue/Singularity,acbellini/Singularity,evertrue/Singularity,nvoron23/Singularity,nvoron23/Singularity,HubSpot/Singularity,HubSpot/Singularity,stevenschlansker/Singularity,grepsr/Singularity,andrhamm/Singularity,tejasmanohar/Singularity,evertrue/Singularity,grepsr/Singularity,acbellini/Singularity,calebTomlinson/Singularity,mjball/Singularity,nvoron23/Singularity,mjball/Singularity,tejasmanohar/Singularity,acbellini/Singularity,andrhamm/Singularity,hs-jenkins-bot/Singularity,evertrue/Singularity,grepsr/Singularity,HubSpot/Singularity,acbellini/Singularity,andrhamm/Singularity,grepsr/Singularity,grepsr/Singularity,nvoron23/Singularity,andrhamm/Singularity,mjball/Singularity,hs-jenkins-bot/Singularity,nvoron23/Singularity,acbellini/Singularity,grepsr/Singularity,acbellini/Singularity,evertrue/Singularity,stevenschlansker/Singularity,tejasmanohar/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,calebTomlinson/Singularity,calebTomlinson/Singularity,stevenschlansker/Singularity,HubSpot/Singularity,tejasmanohar/Singularity,calebTomlinson/Singularity,mjball/Singularity,mjball/Singularity,andrhamm/Singularity,stevenschlansker/Singularity,stevenschlansker/Singularity,stevenschlansker/Singularity,tejasmanohar/Singularity
package com.hubspot.singularity; import java.util.List; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import org.quartz.CronExpression; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.hubspot.mesos.Resources; public class SingularityRequest { @NotNull private final String command; @NotNull private final String name; private final String executor; private final Resources resources; private final String schedule; @Min(0) private final Integer instances; private final Boolean daemon; private static final Joiner JOINER = Joiner.on(" "); @JsonCreator public SingularityRequest(@JsonProperty("command") String command, @JsonProperty("name") String name, @JsonProperty("executor") String executor, @JsonProperty("resources") Resources resources, @JsonProperty("schedule") String schedule, @JsonProperty("instances") Integer instances, @JsonProperty("daemon") Boolean daemon) { schedule = adjustSchedule(schedule); Preconditions.checkState(schedule == null || ((instances == null || instances == 0) && (daemon == null || !daemon)), "Scheduled requests can not be ran on more than one instance, and must not be daemons"); Preconditions.checkState((daemon == null || daemon) || (instances == null || instances == 0), "Non-daemons can not be ran on more than one instance"); Preconditions.checkState(schedule == null || CronExpression.isValidExpression(schedule), "Cron Schedule %s was not parseable", schedule); this.command = command; this.name = name; this.resources = resources; this.executor = executor; this.schedule = schedule; this.daemon = daemon; this.instances = instances; } /** * * Transforms unix cron into fucking quartz cron; adding seconds if not passed in and switching either day of month or day of week to ? * * Field Name Allowed Values Allowed Special Characters * Seconds 0-59 , - * / * Minutes 0-59 , - * / * Hours 0-23 , - * / * Day-of-month 1-31 , - * ? / L W * Month 1-12 or JAN-DEC , - * / * Day-of-Week 1-7 or SUN-SAT , - * ? / L # * Year (Optional) empty, 1970-2199 , - * / */ private String adjustSchedule(String schedule) { if (schedule == null) { return null; } String[] split = schedule.split(" "); if (split.length < 4) { throw new IllegalStateException(String.format("Schedule %s is invalid", schedule)); } List<String> newSchedule = Lists.newArrayListWithCapacity(6); boolean hasSeconds = split.length > 5; if (!hasSeconds) { newSchedule.add("*"); } else { newSchedule.add(split[0]); } int indexMod = hasSeconds ? 1 : 0; newSchedule.add(split[indexMod + 0]); newSchedule.add(split[indexMod + 1]); String dayOfMonth = split[indexMod + 2]; String dayOfWeek = split[indexMod + 4]; if (dayOfWeek.equals("*")) { dayOfWeek = "?"; } else if (!dayOfWeek.equals("?")) { dayOfMonth = "?"; } newSchedule.add(dayOfMonth); newSchedule.add(split[indexMod + 3]); newSchedule.add(dayOfWeek); return JOINER.join(newSchedule); } public byte[] getRequestData(ObjectMapper objectMapper) throws Exception { return objectMapper.writeValueAsBytes(this); } public static SingularityRequest getRequestFromData(byte[] request, ObjectMapper objectMapper) throws Exception { return objectMapper.readValue(request, SingularityRequest.class); } public Integer getInstances() { return instances; } public Boolean getDaemon() { return daemon; } @JsonIgnore public boolean alwaysRunning() { return (daemon == null || daemon.booleanValue()) && !isScheduled(); } @JsonIgnore public boolean isScheduled() { return schedule != null; } public String getSchedule() { return schedule; } public String getName() { return name; } public String getExecutor() { return executor; } public Resources getResources() { return resources; } public String getCommand() { return command; } }
src/main/java/com/hubspot/singularity/SingularityRequest.java
package com.hubspot.singularity; import java.util.List; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import org.quartz.CronExpression; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.hubspot.mesos.Resources; public class SingularityRequest { @NotNull private final String command; @NotNull private final String name; private final String executor; private final Resources resources; private final String schedule; @Min(0) private final Integer instances; private final Boolean daemon; private static final Joiner JOINER = Joiner.on(" "); @JsonCreator public SingularityRequest(@JsonProperty("command") String command, @JsonProperty("name") String name, @JsonProperty("executor") String executor, @JsonProperty("resources") Resources resources, @JsonProperty("schedule") String schedule, @JsonProperty("instances") Integer instances, @JsonProperty("daemon") Boolean daemon) { schedule = adjustSchedule(schedule); Preconditions.checkState(schedule == null || ((instances == null || instances == 0) && (daemon == null || !daemon)), "Scheduled requests can not be ran on more than one instance, and must not be daemons"); Preconditions.checkState((daemon == null || daemon) || (instances == null || instances == 0), "Non-daemons can not be ran on more than one instance"); Preconditions.checkState(schedule == null || CronExpression.isValidExpression(schedule), "Cron Schedule %s was not parseable", schedule); this.command = command; this.name = name; this.resources = resources; this.executor = executor; this.schedule = schedule; this.daemon = daemon; this.instances = instances; } /** * * Transforms unix cron into fucking quartz cron; adding seconds if not passed in and switching either day of month or day of week to ? * * Field Name Allowed Values Allowed Special Characters * Seconds 0-59 , - * / * Minutes 0-59 , - * / * Hours 0-23 , - * / * Day-of-month 1-31 , - * ? / L W * Month 1-12 or JAN-DEC , - * / * Day-of-Week 1-7 or SUN-SAT , - * ? / L # * Year (Optional) empty, 1970-2199 , - * / */ private String adjustSchedule(String schedule) { if (schedule == null) { return null; } String[] split = schedule.split(" "); if (split.length < 4) { throw new IllegalStateException(String.format("Schedule %s is invalid", schedule)); } List<String> newSchedule = Lists.newArrayListWithCapacity(6); boolean hasSeconds = split.length > 5; if (!hasSeconds) { newSchedule.add("*"); } else { newSchedule.add(split[0]); } int indexMod = hasSeconds ? 1 : 0; newSchedule.add(split[indexMod + 0]); newSchedule.add(split[indexMod + 1]); String dayOfMonth = split[indexMod + 2]; String dayOfWeek = split[indexMod + 4]; if (dayOfWeek.equals("*")) { dayOfWeek = "?"; } else { dayOfMonth = "?"; } newSchedule.add(dayOfMonth); newSchedule.add(split[indexMod + 3]); newSchedule.add(dayOfWeek); return JOINER.join(newSchedule); } public byte[] getRequestData(ObjectMapper objectMapper) throws Exception { return objectMapper.writeValueAsBytes(this); } public static SingularityRequest getRequestFromData(byte[] request, ObjectMapper objectMapper) throws Exception { return objectMapper.readValue(request, SingularityRequest.class); } public Integer getInstances() { return instances; } public Boolean getDaemon() { return daemon; } @JsonIgnore public boolean alwaysRunning() { return (daemon == null || daemon.booleanValue()) && !isScheduled(); } @JsonIgnore public boolean isScheduled() { return schedule != null; } public String getSchedule() { return schedule; } public String getName() { return name; } public String getExecutor() { return executor; } public Resources getResources() { return resources; } public String getCommand() { return command; } }
fix this
src/main/java/com/hubspot/singularity/SingularityRequest.java
fix this
<ide><path>rc/main/java/com/hubspot/singularity/SingularityRequest.java <ide> <ide> if (dayOfWeek.equals("*")) { <ide> dayOfWeek = "?"; <del> } else { <add> } else if (!dayOfWeek.equals("?")) { <ide> dayOfMonth = "?"; <ide> } <ide>
Java
apache-2.0
621a9f25e9ae969566c0fdda5bfa0cc801a52176
0
andyshao/zxing,GeekHades/zxing,gank0326/zxing,qianchenglenger/zxing,praveen062/zxing,ikenneth/zxing,tanelihuuskonen/zxing,graug/zxing,layeka/zxing,juoni/zxing,zxing/zxing,GeorgeMe/zxing,angrilove/zxing,ptrnov/zxing,Solvoj/zxing,peterdocter/zxing,sitexa/zxing,0111001101111010/zxing,BraveAction/zxing,JasOXIII/zxing,ikenneth/zxing,1yvT0s/zxing,ouyangkongtong/zxing,iris-iriswang/zxing,lijian17/zxing,HiWong/zxing,peterdocter/zxing,kharohiy/zxing,cncomer/zxing,roudunyy/zxing,juoni/zxing,projectocolibri/zxing,Peter32/zxing,daverix/zxing,angrilove/zxing,wanjingyan001/zxing,SriramRamesh/zxing,wangdoubleyan/zxing,YongHuiLuo/zxing,qingsong-xu/zxing,TestSmirk/zxing,menglifei/zxing,peterdocter/zxing,kailIII/zxing,t123yh/zxing,wangdoubleyan/zxing,kyosho81/zxing,whycode/zxing,mig1098/zxing,eddyb/zxing,huangzl233/zxing,shwethamallya89/zxing,Kevinsu917/zxing,RatanPaul/zxing,reidwooten99/zxing,917386389/zxing,loaf/zxing,hiagodotme/zxing,graug/zxing,nickperez1285/zxing,YongHuiLuo/zxing,ren545457803/zxing,zhangyihao/zxing,manl1100/zxing,Matrix44/zxing,FloatingGuy/zxing,ssakitha/QR-Code-Reader,catalindavid/zxing,SriramRamesh/zxing,huangsongyan/zxing,ptrnov/zxing,sunil1989/zxing,huihui4045/zxing,Kabele/zxing,ctoliver/zxing,Akylas/zxing,bittorrent/zxing,roadrunner1987/zxing,tanelihuuskonen/zxing,mecury/zxing,geeklain/zxing,danielZhang0601/zxing,ChristingKim/zxing,BraveAction/zxing,krishnanMurali/zxing,menglifei/zxing,WB-ZZ-TEAM/zxing,ssakitha/sakisolutions,peterdocter/zxing,peterdocter/zxing,Kevinsu917/zxing,Matrix44/zxing,meixililu/zxing,liuchaoya/zxing,freakynit/zxing,peterdocter/zxing,ChristingKim/zxing,hgl888/zxing,OnecloudVideo/zxing,zzhui1988/zxing,ZhernakovMikhail/zxing,huopochuan/zxing,1shawn/zxing,mayfourth/zxing,fhchina/zxing,YLBFDEV/zxing,OnecloudVideo/zxing,huangsongyan/zxing,irfanah/zxing,jianwoo/zxing,daverix/zxing,lijian17/zxing,wanjingyan001/zxing,wangxd1213/zxing,ouyangkongtong/zxing,allenmo/zxing,micwallace/webscanner,peterdocter/zxing,finch0219/zxing,yuanhuihui/zxing,keqingyuan/zxing,qianchenglenger/zxing,zootsuitbrian/zxing,irfanah/zxing,huihui4045/zxing,bestwpw/zxing,Matrix44/zxing,ssakitha/QR-Code-Reader,Fedhaier/zxing,GeorgeMe/zxing,yuanhuihui/zxing,zilaiyedaren/zxing,irwinai/zxing,hiagodotme/zxing,1shawn/zxing,lvbaosong/zxing,YuYongzhi/zxing,HiWong/zxing,0111001101111010/zxing,cnbin/zxing,praveen062/zxing,wangjun/zxing,zjcscut/zxing,krishnanMurali/zxing,Luise-li/zxing,finch0219/zxing,sysujzh/zxing,micwallace/webscanner,zootsuitbrian/zxing,andyao/zxing,todotobe1/zxing,nickperez1285/zxing,liuchaoya/zxing,ForeverLucky/zxing,roudunyy/zxing,liboLiao/zxing,zootsuitbrian/zxing,saif-hmk/zxing,t123yh/zxing,ForeverLucky/zxing,DONIKAN/zxing,easycold/zxing,Akylas/zxing,0111001101111010/zxing,ChanJLee/zxing,meixililu/zxing,Peter32/zxing,ren545457803/zxing,easycold/zxing,DONIKAN/zxing,zonamovil/zxing,kyosho81/zxing,cncomer/zxing,ale13jo/zxing,rustemferreira/zxing-projectx,eight-pack-abdominals/ZXing,eddyb/zxing,DavidLDawes/zxing,andyshao/zxing,zzhui1988/zxing,micwallace/webscanner,zxing/zxing,Akylas/zxing,slayerlp/zxing,irwinai/zxing,zonamovil/zxing,hgl888/zxing,manl1100/zxing,YuYongzhi/zxing,FloatingGuy/zxing,GeekHades/zxing,freakynit/zxing,ctoliver/zxing,tks-dp/zxing,fhchina/zxing,sysujzh/zxing,daverix/zxing,Yi-Kun/zxing,JerryChin/zxing,qingsong-xu/zxing,keqingyuan/zxing,joni1408/zxing,cnbin/zxing,lvbaosong/zxing,erbear/zxing,wangxd1213/zxing,whycode/zxing,zootsuitbrian/zxing,liboLiao/zxing,shixingxing/zxing,ZhernakovMikhail/zxing,Akylas/zxing,eight-pack-abdominals/ZXing,daverix/zxing,geeklain/zxing,sitexa/zxing,kailIII/zxing,iris-iriswang/zxing,l-dobrev/zxing,0111001101111010/zxing,allenmo/zxing,huopochuan/zxing,zootsuitbrian/zxing,reidwooten99/zxing,Akylas/zxing,ale13jo/zxing,TestSmirk/zxing,917386389/zxing,befairyliu/zxing,wirthandrel/zxing,Akylas/zxing,Luise-li/zxing,10045125/zxing,layeka/zxing,roadrunner1987/zxing,todotobe1/zxing,loaf/zxing,shwethamallya89/zxing,rustemferreira/zxing-projectx,YLBFDEV/zxing,zilaiyedaren/zxing,1yvT0s/zxing,JerryChin/zxing,WB-ZZ-TEAM/zxing,Kabele/zxing,danielZhang0601/zxing,zjcscut/zxing,sunil1989/zxing,ChanJLee/zxing,catalindavid/zxing,zootsuitbrian/zxing,daverix/zxing,JasOXIII/zxing,tks-dp/zxing,ssakitha/sakisolutions,kharohiy/zxing,MonkeyZZZZ/Zxing,Akylas/zxing,Fedhaier/zxing,bestwpw/zxing,mayfourth/zxing,MonkeyZZZZ/Zxing,east119/zxing,bittorrent/zxing,l-dobrev/zxing,DavidLDawes/zxing,RatanPaul/zxing,east119/zxing,Yi-Kun/zxing,jianwoo/zxing,mecury/zxing,saif-hmk/zxing,erbear/zxing,andyao/zxing,zootsuitbrian/zxing,projectocolibri/zxing,huangzl233/zxing,Matrix44/zxing,shixingxing/zxing,mig1098/zxing,geeklain/zxing,befairyliu/zxing,wangjun/zxing,wirthandrel/zxing,joni1408/zxing,slayerlp/zxing,zhangyihao/zxing,peterdocter/zxing,Solvoj/zxing
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.qrcode.detector; import com.google.zxing.DecodeHintType; import com.google.zxing.MonochromeBitmapSource; import com.google.zxing.ReaderException; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitArray; import com.google.zxing.common.Collections; import com.google.zxing.common.Comparator; import java.util.Hashtable; import java.util.Vector; /** * <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square * markers at three corners of a QR Code.</p> * * <p>This class is not thread-safe and should not be reused.</p> * * @author [email protected] (Sean Owen) */ final class FinderPatternFinder { private static final int CENTER_QUORUM = 2; private static final int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center private static final int MAX_MODULES = 57; // support up to version 10 for mobile clients private static final int INTEGER_MATH_SHIFT = 8; private final MonochromeBitmapSource image; private final Vector possibleCenters; private boolean hasSkipped; /** * <p>Creates a finder that will search the image for three finder patterns.</p> * * @param image image to search */ FinderPatternFinder(MonochromeBitmapSource image) { this.image = image; this.possibleCenters = new Vector(); } FinderPatternInfo find(Hashtable hints) throws ReaderException { boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER); int maxI = image.getHeight(); int maxJ = image.getWidth(); // We are looking for black/white/black/white/black modules in // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the // image, and then account for the center being 3 modules in size. This gives the smallest // number of pixels the center could be, so skip this often. When trying harder, look for all // QR versions regardless of how dense they are. int iSkip = (int) (maxI / (MAX_MODULES * 4.0f) * 3); if (iSkip < MIN_SKIP || tryHarder) { iSkip = MIN_SKIP; } boolean done = false; int[] stateCount = new int[5]; for (int i = iSkip - 1; i < maxI && !done; i += iSkip) { // Get a row of black/white values BitArray blackRow = image.getBlackRow(i, null, 0, maxJ); stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; int currentState = 0; for (int j = 0; j < maxJ; j++) { if (blackRow.get(j)) { // Black pixel if ((currentState & 1) == 1) { // Counting white pixels currentState++; } stateCount[currentState]++; } else { // White pixel if ((currentState & 1) == 0) { // Counting black pixels if (currentState == 4) { // A winner? if (foundPatternCross(stateCount)) { // Yes boolean confirmed = handlePossibleCenter(stateCount, i, j); if (confirmed) { iSkip = 1; // Go back to examining each line if (hasSkipped) { done = haveMulitplyConfirmedCenters(); } else { int rowSkip = findRowSkip(); if (rowSkip > stateCount[2]) { // Skip rows between row of lower confirmed center // and top of presumed third confirmed center // but back up a bit to get a full chance of detecting // it, entire width of center of finder pattern // Skip by rowSkip, but back off by stateCount[2] (size of last center // of pattern we saw) to be conservative, and also back off by iSkip which // is about to be re-added i += rowSkip - stateCount[2] - iSkip; j = maxJ - 1; } } } else { // Advance to next black pixel do { j++; } while (j < maxJ && !blackRow.get(j)); j--; // back up to that last white pixel } // Clear state to start looking again currentState = 0; stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; } else { // No, shift counts back by two stateCount[0] = stateCount[2]; stateCount[1] = stateCount[3]; stateCount[2] = stateCount[4]; stateCount[3] = 1; stateCount[4] = 0; currentState = 3; } } else { stateCount[++currentState]++; } } else { // Counting white pixels stateCount[currentState]++; } } } if (foundPatternCross(stateCount)) { boolean confirmed = handlePossibleCenter(stateCount, i, maxJ); if (confirmed) { iSkip = stateCount[0]; if (hasSkipped) { // Found a third one done = haveMulitplyConfirmedCenters(); } } } } FinderPattern[] patternInfo = selectBestPatterns(); patternInfo = orderBestPatterns(patternInfo); return new FinderPatternInfo(patternInfo); } /** * Given a count of black/white/black/white/black pixels just seen and an end position, * figures the location of the center of this run. */ private static float centerFromEnd(int[] stateCount, int end) { return (float) (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f; } /** * @param stateCount count of black/white/black/white/black pixels just read * @return true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios * used by finder patterns to be considered a match */ private static boolean foundPatternCross(int[] stateCount) { int totalModuleSize = 0; for (int i = 0; i < 5; i++) { int count = stateCount[i]; if (count == 0) { return false; } totalModuleSize += count; } if (totalModuleSize < 7) { return false; } int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7; int maxVariance = moduleSize / 2; // Allow less than 50% variance from 1-1-3-1-1 proportions return Math.abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && Math.abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance; } /** * <p>After a horizontal scan finds a potential finder pattern, this method * "cross-checks" by scanning down vertically through the center of the possible * finder pattern to see if the same proportion is detected.</p> * * @param startI row where a finder pattern was detected * @param centerJ center of the section that appears to cross a finder pattern * @param maxCount maximum reasonable number of modules that should be * observed in any reading state, based on the results of the horizontal scan * @return vertical center of finder pattern, or {@link Float#NaN} if not found */ private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) { MonochromeBitmapSource image = this.image; int maxI = image.getHeight(); int[] stateCount = new int[5]; // Start counting up from center int i = startI; while (i >= 0 && image.isBlack(centerJ, i)) { stateCount[2]++; i--; } if (i < 0) { return Float.NaN; } while (i >= 0 && !image.isBlack(centerJ, i) && stateCount[1] <= maxCount) { stateCount[1]++; i--; } // If already too many modules in this state or ran off the edge: if (i < 0 || stateCount[1] > maxCount) { return Float.NaN; } while (i >= 0 && image.isBlack(centerJ, i) && stateCount[0] <= maxCount) { stateCount[0]++; i--; } if (stateCount[0] > maxCount) { return Float.NaN; } // Now also count down from center i = startI + 1; while (i < maxI && image.isBlack(centerJ, i)) { stateCount[2]++; i++; } if (i == maxI) { return Float.NaN; } while (i < maxI && !image.isBlack(centerJ, i) && stateCount[3] < maxCount) { stateCount[3]++; i++; } if (i == maxI || stateCount[3] >= maxCount) { return Float.NaN; } while (i < maxI && image.isBlack(centerJ, i) && stateCount[4] < maxCount) { stateCount[4]++; i++; } if (stateCount[4] >= maxCount) { return Float.NaN; } // If we found a finder-pattern-like section, but its size is more than 20% different than // the original, assume it's a false positive int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { return Float.NaN; } return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : Float.NaN; } /** * <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical, * except it reads horizontally instead of vertically. This is used to cross-cross * check a vertical cross check and locate the real center of the alignment pattern.</p> */ private float crossCheckHorizontal(int startJ, int centerI, int maxCount, int originalStateCountTotal) { MonochromeBitmapSource image = this.image; int maxJ = image.getWidth(); int[] stateCount = new int[5]; int j = startJ; while (j >= 0 && image.isBlack(j, centerI)) { stateCount[2]++; j--; } if (j < 0) { return Float.NaN; } while (j >= 0 && !image.isBlack(j, centerI) && stateCount[1] <= maxCount) { stateCount[1]++; j--; } if (j < 0 || stateCount[1] > maxCount) { return Float.NaN; } while (j >= 0 && image.isBlack(j, centerI) && stateCount[0] <= maxCount) { stateCount[0]++; j--; } if (stateCount[0] > maxCount) { return Float.NaN; } j = startJ + 1; while (j < maxJ && image.isBlack(j, centerI)) { stateCount[2]++; j++; } if (j == maxJ) { return Float.NaN; } while (j < maxJ && !image.isBlack(j, centerI) && stateCount[3] < maxCount) { stateCount[3]++; j++; } if (j == maxJ || stateCount[3] >= maxCount) { return Float.NaN; } while (j < maxJ && image.isBlack(j, centerI) && stateCount[4] < maxCount) { stateCount[4]++; j++; } if (stateCount[4] >= maxCount) { return Float.NaN; } // If we found a finder-pattern-like section, but its size is significantly different than // the original, assume it's a false positive int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { return Float.NaN; } return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : Float.NaN; } /** * <p>This is called when a horizontal scan finds a possible alignment pattern. It will * cross check with a vertical scan, and if successful, will, ah, cross-cross-check * with another horizontal scan. This is needed primarily to locate the real horizontal * center of the pattern in cases of extreme skew.</p> * * <p>If that succeeds the finder pattern location is added to a list that tracks * the number of times each location has been nearly-matched as a finder pattern. * Each additional find is more evidence that the location is in fact a finder * pattern center * * @param stateCount reading state module counts from horizontal scan * @param i row where finder pattern may be found * @param j end of possible finder pattern in row * @return true if a finder pattern candidate was found this time */ private boolean handlePossibleCenter(int[] stateCount, int i, int j) { int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; float centerJ = centerFromEnd(stateCount, j); float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2], stateCountTotal); if (!Float.isNaN(centerI)) { // Re-cross check centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2], stateCountTotal); if (!Float.isNaN(centerJ)) { float estimatedModuleSize = (float) stateCountTotal / 7.0f; boolean found = false; int max = possibleCenters.size(); for (int index = 0; index < max; index++) { FinderPattern center = (FinderPattern) possibleCenters.elementAt(index); // Look for about the same center and module size: if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) { center.incrementCount(); found = true; break; } } if (!found) { possibleCenters.addElement(new FinderPattern(centerJ, centerI, estimatedModuleSize)); } return true; } } return false; } /** * @return number of rows we could safely skip during scanning, based on the first * two finder patterns that have been located. In some cases their position will * allow us to infer that the third pattern must lie below a certain point farther * down in the image. */ private int findRowSkip() { int max = possibleCenters.size(); if (max <= 1) { return 0; } FinderPattern firstConfirmedCenter = null; for (int i = 0; i < max; i++) { FinderPattern center = (FinderPattern) possibleCenters.elementAt(i); if (center.getCount() >= CENTER_QUORUM) { if (firstConfirmedCenter == null) { firstConfirmedCenter = center; } else { // We have two confirmed centers // How far down can we skip before resuming looking for the next // pattern? In the worst case, only the difference between the // difference in the x / y coordinates of the two centers. // This is the case where you find top left first. Draw it out. hasSkipped = true; return (int) Math.abs(Math.abs(firstConfirmedCenter.getX() - center.getX()) - Math.abs(firstConfirmedCenter.getY() - center.getY())); } } } return 0; } /** * @return true iff we have found at least 3 finder patterns that have been detected * at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the * candidates is "pretty similar" */ private boolean haveMulitplyConfirmedCenters() { int confirmedCount = 0; float totalModuleSize = 0.0f; int max = possibleCenters.size(); for (int i = 0; i < max; i++) { FinderPattern pattern = (FinderPattern) possibleCenters.elementAt(i); if (pattern.getCount() >= CENTER_QUORUM) { confirmedCount++; totalModuleSize += pattern.getEstimatedModuleSize(); } } if (confirmedCount < 3) { return false; } // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" // and that we need to keep looking. We detect this by asking if the estimated module sizes // vary too much. We arbitrarily say that when the total deviation from average exceeds // 15% of the total module size estimates, it's too much. float average = totalModuleSize / max; float totalDeviation = 0.0f; for (int i = 0; i < max; i++) { FinderPattern pattern = (FinderPattern) possibleCenters.elementAt(i); totalDeviation += Math.abs(pattern.getEstimatedModuleSize() - average); } return totalDeviation <= 0.15f * totalModuleSize; } /** * @return the 3 best {@link FinderPattern}s from our list of candidates. The "best" are * those that have been detected at least {@link #CENTER_QUORUM} times, and whose module * size differs from the average among those patterns the least * @throws ReaderException if 3 such finder patterns do not exist */ private FinderPattern[] selectBestPatterns() throws ReaderException { Collections.insertionSort(possibleCenters, new CenterComparator()); int size = 0; int max = possibleCenters.size(); while (size < max) { if (((FinderPattern) possibleCenters.elementAt(size)).getCount() < CENTER_QUORUM) { break; } size++; } if (size < 3) { // Couldn't find enough finder patterns throw new ReaderException("Could not find three finder patterns"); } if (size == 3) { // Found just enough -- hope these are good! return new FinderPattern[]{ (FinderPattern) possibleCenters.elementAt(0), (FinderPattern) possibleCenters.elementAt(1), (FinderPattern) possibleCenters.elementAt(2) }; } possibleCenters.setSize(size); // Hmm, multiple found. We need to pick the best three. Find the most // popular ones whose module size is nearest the average float averageModuleSize = 0.0f; for (int i = 0; i < size; i++) { averageModuleSize += ((FinderPattern) possibleCenters.elementAt(i)).getEstimatedModuleSize(); } averageModuleSize /= (float) size; // We don't have java.util.Collections in J2ME Collections.insertionSort(possibleCenters, new ClosestToAverageComparator(averageModuleSize)); return new FinderPattern[]{ (FinderPattern) possibleCenters.elementAt(0), (FinderPattern) possibleCenters.elementAt(1), (FinderPattern) possibleCenters.elementAt(2) }; } /** * <p>Having found three "best" finder patterns we need to decide which is the top-left, top-right, * bottom-left. We assume that the one closest to the other two is the top-left one; this is not * strictly true (imagine extreme perspective distortion) but for the moment is a serviceable assumption. * Lastly we sort top-right from bottom-left by figuring out orientation from vector cross products.</p> * * @param patterns three best {@link FinderPattern}s * @return same {@link FinderPattern}s ordered bottom-left, top-left, top-right */ private static FinderPattern[] orderBestPatterns(FinderPattern[] patterns) { // Find distances between pattern centers float abDistance = distance(patterns[0], patterns[1]); float bcDistance = distance(patterns[1], patterns[2]); float acDistance = distance(patterns[0], patterns[2]); FinderPattern topLeft; FinderPattern topRight; FinderPattern bottomLeft; // Assume one closest to other two is top left; // topRight and bottomLeft will just be guesses below at first if (bcDistance >= abDistance && bcDistance >= acDistance) { topLeft = patterns[0]; topRight = patterns[1]; bottomLeft = patterns[2]; } else if (acDistance >= bcDistance && acDistance >= abDistance) { topLeft = patterns[1]; topRight = patterns[0]; bottomLeft = patterns[2]; } else { topLeft = patterns[2]; topRight = patterns[0]; bottomLeft = patterns[1]; } // Use cross product to figure out which of other1/2 is the bottom left // pattern. The vector "top-left -> bottom-left" x "top-left -> top-right" // should yield a vector with positive z component if ((bottomLeft.getY() - topLeft.getY()) * (topRight.getX() - topLeft.getX()) < (bottomLeft.getX() - topLeft.getX()) * (topRight.getY() - topLeft.getY())) { FinderPattern temp = topRight; topRight = bottomLeft; bottomLeft = temp; } return new FinderPattern[]{bottomLeft, topLeft, topRight}; } /** * @return distance between two points */ static float distance(ResultPoint pattern1, ResultPoint pattern2) { float xDiff = pattern1.getX() - pattern2.getX(); float yDiff = pattern1.getY() - pattern2.getY(); return (float) Math.sqrt((double) (xDiff * xDiff + yDiff * yDiff)); } /** * <p>Orders by {@link FinderPattern#getCount()}, descending.</p> */ private static class CenterComparator implements Comparator { public int compare(Object center1, Object center2) { return ((FinderPattern) center2).getCount() - ((FinderPattern) center1).getCount(); } } /** * <p>Orders by variance from average module size, ascending.</p> */ private static class ClosestToAverageComparator implements Comparator { private final float averageModuleSize; private ClosestToAverageComparator(float averageModuleSize) { this.averageModuleSize = averageModuleSize; } public int compare(Object center1, Object center2) { return Math.abs(((FinderPattern) center1).getEstimatedModuleSize() - averageModuleSize) < Math.abs(((FinderPattern) center2).getEstimatedModuleSize() - averageModuleSize) ? -1 : 1; } } }
core/src/com/google/zxing/qrcode/detector/FinderPatternFinder.java
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.qrcode.detector; import com.google.zxing.DecodeHintType; import com.google.zxing.MonochromeBitmapSource; import com.google.zxing.ReaderException; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitArray; import com.google.zxing.common.Collections; import com.google.zxing.common.Comparator; import java.util.Hashtable; import java.util.Vector; /** * <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square * markers at three corners of a QR Code.</p> * * <p>This class is not thread-safe and should not be reused.</p> * * @author [email protected] (Sean Owen) */ final class FinderPatternFinder { private static final int CENTER_QUORUM = 2; private static final int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center private static final int MAX_MODULES = 57; // support up to version 10 for mobile clients private final MonochromeBitmapSource image; private final Vector possibleCenters; private boolean hasSkipped; /** * <p>Creates a finder that will search the image for three finder patterns.</p> * * @param image image to search */ FinderPatternFinder(MonochromeBitmapSource image) { this.image = image; this.possibleCenters = new Vector(); } FinderPatternInfo find(Hashtable hints) throws ReaderException { boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER); int maxI = image.getHeight(); int maxJ = image.getWidth(); // We are looking for black/white/black/white/black modules in // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far int[] stateCount = new int[5]; boolean done = false; // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the // image, and then account for the center being 3 modules in size. This gives the smallest // number of pixels the center could be, so skip this often. When trying harder, look for all // QR versions regardless of how dense they are. int iSkip = (int) (maxI / (MAX_MODULES * 4.0f) * 3); if (iSkip < MIN_SKIP || tryHarder) { iSkip = MIN_SKIP; } for (int i = iSkip - 1; i < maxI && !done; i += iSkip) { // Get a row of black/white values BitArray blackRow = image.getBlackRow(i, null, 0, maxJ); stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; int currentState = 0; for (int j = 0; j < maxJ; j++) { if (blackRow.get(j)) { // Black pixel if ((currentState & 1) == 1) { // Counting white pixels currentState++; } stateCount[currentState]++; } else { // White pixel if ((currentState & 1) == 0) { // Counting black pixels if (currentState == 4) { // A winner? if (foundPatternCross(stateCount)) { // Yes boolean confirmed = handlePossibleCenter(stateCount, i, j); if (confirmed) { iSkip = 1; // Go back to examining each line if (hasSkipped) { done = haveMulitplyConfirmedCenters(); } else { int rowSkip = findRowSkip(); if (rowSkip > stateCount[2]) { // Skip rows between row of lower confirmed center // and top of presumed third confirmed center // but back up a bit to get a full chance of detecting // it, entire width of center of finder pattern // Skip by rowSkip, but back off by stateCount[2] (size of last center // of pattern we saw) to be conservative, and also back off by iSkip which // is about to be re-added i += rowSkip - stateCount[2] - iSkip; j = maxJ - 1; } } } else { // Advance to next black pixel do { j++; } while (j < maxJ && !blackRow.get(j)); j--; // back up to that last white pixel } // Clear state to start looking again currentState = 0; stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; } else { // No, shift counts back by two stateCount[0] = stateCount[2]; stateCount[1] = stateCount[3]; stateCount[2] = stateCount[4]; stateCount[3] = 1; stateCount[4] = 0; currentState = 3; } } else { stateCount[++currentState]++; } } else { // Counting white pixels stateCount[currentState]++; } } } if (foundPatternCross(stateCount)) { boolean confirmed = handlePossibleCenter(stateCount, i, maxJ); if (confirmed) { iSkip = stateCount[0]; if (hasSkipped) { // Found a third one done = haveMulitplyConfirmedCenters(); } } } } FinderPattern[] patternInfo = selectBestPatterns(); patternInfo = orderBestPatterns(patternInfo); return new FinderPatternInfo(patternInfo); } /** * Given a count of black/white/black/white/black pixels just seen and an end position, * figures the location of the center of this run. */ private static float centerFromEnd(int[] stateCount, int end) { return (float) (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f; } /** * @param stateCount count of black/white/black/white/black pixels just read * @return true iff the proportions of the counts is close enough to the 1/13/1/1 ratios * used by finder patterns to be considered a match */ private static boolean foundPatternCross(int[] stateCount) { int totalModuleSize = 0; for (int i = 0; i < 5; i++) { if (stateCount[i] == 0) { return false; } totalModuleSize += stateCount[i]; } if (totalModuleSize < 7) { return false; } float moduleSize = (float) totalModuleSize / 7.0f; float maxVariance = moduleSize / 2.0f; // Allow less than 50% variance from 1-1-3-1-1 proportions return Math.abs(moduleSize - stateCount[0]) < maxVariance && Math.abs(moduleSize - stateCount[1]) < maxVariance && Math.abs(3.0f * moduleSize - stateCount[2]) < 3.0f * maxVariance && Math.abs(moduleSize - stateCount[3]) < maxVariance && Math.abs(moduleSize - stateCount[4]) < maxVariance; } /** * <p>After a horizontal scan finds a potential finder pattern, this method * "cross-checks" by scanning down vertically through the center of the possible * finder pattern to see if the same proportion is detected.</p> * * @param startI row where a finder pattern was detected * @param centerJ center of the section that appears to cross a finder pattern * @param maxCount maximum reasonable number of modules that should be * observed in any reading state, based on the results of the horizontal scan * @return vertical center of finder pattern, or {@link Float#NaN} if not found */ private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) { MonochromeBitmapSource image = this.image; int maxI = image.getHeight(); int[] stateCount = new int[5]; // Start counting up from center int i = startI; while (i >= 0 && image.isBlack(centerJ, i)) { stateCount[2]++; i--; } if (i < 0) { return Float.NaN; } while (i >= 0 && !image.isBlack(centerJ, i) && stateCount[1] <= maxCount) { stateCount[1]++; i--; } // If already too many modules in this state or ran off the edge: if (i < 0 || stateCount[1] > maxCount) { return Float.NaN; } while (i >= 0 && image.isBlack(centerJ, i) && stateCount[0] <= maxCount) { stateCount[0]++; i--; } if (stateCount[0] > maxCount) { return Float.NaN; } // Now also count down from center i = startI + 1; while (i < maxI && image.isBlack(centerJ, i)) { stateCount[2]++; i++; } if (i == maxI) { return Float.NaN; } while (i < maxI && !image.isBlack(centerJ, i) && stateCount[3] < maxCount) { stateCount[3]++; i++; } if (i == maxI || stateCount[3] >= maxCount) { return Float.NaN; } while (i < maxI && image.isBlack(centerJ, i) && stateCount[4] < maxCount) { stateCount[4]++; i++; } if (stateCount[4] >= maxCount) { return Float.NaN; } // If we found a finder-pattern-like section, but its size is more than 20% different than // the original, assume it's a false positive int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { return Float.NaN; } return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : Float.NaN; } /** * <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical, * except it reads horizontally instead of vertically. This is used to cross-cross * check a vertical cross check and locate the real center of the alignment pattern.</p> */ private float crossCheckHorizontal(int startJ, int centerI, int maxCount, int originalStateCountTotal) { MonochromeBitmapSource image = this.image; int maxJ = image.getWidth(); int[] stateCount = new int[5]; int j = startJ; while (j >= 0 && image.isBlack(j, centerI)) { stateCount[2]++; j--; } if (j < 0) { return Float.NaN; } while (j >= 0 && !image.isBlack(j, centerI) && stateCount[1] <= maxCount) { stateCount[1]++; j--; } if (j < 0 || stateCount[1] > maxCount) { return Float.NaN; } while (j >= 0 && image.isBlack(j, centerI) && stateCount[0] <= maxCount) { stateCount[0]++; j--; } if (stateCount[0] > maxCount) { return Float.NaN; } j = startJ + 1; while (j < maxJ && image.isBlack(j, centerI)) { stateCount[2]++; j++; } if (j == maxJ) { return Float.NaN; } while (j < maxJ && !image.isBlack(j, centerI) && stateCount[3] < maxCount) { stateCount[3]++; j++; } if (j == maxJ || stateCount[3] >= maxCount) { return Float.NaN; } while (j < maxJ && image.isBlack(j, centerI) && stateCount[4] < maxCount) { stateCount[4]++; j++; } if (stateCount[4] >= maxCount) { return Float.NaN; } // If we found a finder-pattern-like section, but its size is significantly different than // the original, assume it's a false positive int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { return Float.NaN; } return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : Float.NaN; } /** * <p>This is called when a horizontal scan finds a possible alignment pattern. It will * cross check with a vertical scan, and if successful, will, ah, cross-cross-check * with another horizontal scan. This is needed primarily to locate the real horizontal * center of the pattern in cases of extreme skew.</p> * * <p>If that succeeds the finder pattern location is added to a list that tracks * the number of times each location has been nearly-matched as a finder pattern. * Each additional find is more evidence that the location is in fact a finder * pattern center * * @param stateCount reading state module counts from horizontal scan * @param i row where finder pattern may be found * @param j end of possible finder pattern in row * @return true if a finder pattern candidate was found this time */ private boolean handlePossibleCenter(int[] stateCount, int i, int j) { int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; float centerJ = centerFromEnd(stateCount, j); float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2], stateCountTotal); if (!Float.isNaN(centerI)) { // Re-cross check centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2], stateCountTotal); if (!Float.isNaN(centerJ)) { float estimatedModuleSize = (float) stateCountTotal / 7.0f; boolean found = false; int max = possibleCenters.size(); for (int index = 0; index < max; index++) { FinderPattern center = (FinderPattern) possibleCenters.elementAt(index); // Look for about the same center and module size: if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) { center.incrementCount(); found = true; break; } } if (!found) { possibleCenters.addElement(new FinderPattern(centerJ, centerI, estimatedModuleSize)); } return true; } } return false; } /** * @return number of rows we could safely skip during scanning, based on the first * two finder patterns that have been located. In some cases their position will * allow us to infer that the third pattern must lie below a certain point farther * down in the image. */ private int findRowSkip() { int max = possibleCenters.size(); if (max <= 1) { return 0; } FinderPattern firstConfirmedCenter = null; for (int i = 0; i < max; i++) { FinderPattern center = (FinderPattern) possibleCenters.elementAt(i); if (center.getCount() >= CENTER_QUORUM) { if (firstConfirmedCenter == null) { firstConfirmedCenter = center; } else { // We have two confirmed centers // How far down can we skip before resuming looking for the next // pattern? In the worst case, only the difference between the // difference in the x / y coordinates of the two centers. // This is the case where you find top left first. Draw it out. hasSkipped = true; return (int) Math.abs(Math.abs(firstConfirmedCenter.getX() - center.getX()) - Math.abs(firstConfirmedCenter.getY() - center.getY())); } } } return 0; } /** * @return true iff we have found at least 3 finder patterns that have been detected * at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the * candidates is "pretty similar" */ private boolean haveMulitplyConfirmedCenters() { int confirmedCount = 0; float totalModuleSize = 0.0f; int max = possibleCenters.size(); for (int i = 0; i < max; i++) { FinderPattern pattern = (FinderPattern) possibleCenters.elementAt(i); if (pattern.getCount() >= CENTER_QUORUM) { confirmedCount++; totalModuleSize += pattern.getEstimatedModuleSize(); } } if (confirmedCount < 3) { return false; } // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" // and that we need to keep looking. We detect this by asking if the estimated module sizes // vary too much. We arbitrarily say that when the total deviation from average exceeds // 15% of the total module size estimates, it's too much. float average = totalModuleSize / max; float totalDeviation = 0.0f; for (int i = 0; i < max; i++) { FinderPattern pattern = (FinderPattern) possibleCenters.elementAt(i); totalDeviation += Math.abs(pattern.getEstimatedModuleSize() - average); } return totalDeviation <= 0.15f * totalModuleSize; } /** * @return the 3 best {@link FinderPattern}s from our list of candidates. The "best" are * those that have been detected at least {@link #CENTER_QUORUM} times, and whose module * size differs from the average among those patterns the least * @throws ReaderException if 3 such finder patterns do not exist */ private FinderPattern[] selectBestPatterns() throws ReaderException { Collections.insertionSort(possibleCenters, new CenterComparator()); int size = 0; int max = possibleCenters.size(); while (size < max) { if (((FinderPattern) possibleCenters.elementAt(size)).getCount() < CENTER_QUORUM) { break; } size++; } if (size < 3) { // Couldn't find enough finder patterns throw new ReaderException("Could not find three finder patterns"); } if (size == 3) { // Found just enough -- hope these are good! return new FinderPattern[]{ (FinderPattern) possibleCenters.elementAt(0), (FinderPattern) possibleCenters.elementAt(1), (FinderPattern) possibleCenters.elementAt(2) }; } possibleCenters.setSize(size); // Hmm, multiple found. We need to pick the best three. Find the most // popular ones whose module size is nearest the average float averageModuleSize = 0.0f; for (int i = 0; i < size; i++) { averageModuleSize += ((FinderPattern) possibleCenters.elementAt(i)).getEstimatedModuleSize(); } averageModuleSize /= (float) size; // We don't have java.util.Collections in J2ME Collections.insertionSort(possibleCenters, new ClosestToAverageComparator(averageModuleSize)); return new FinderPattern[]{ (FinderPattern) possibleCenters.elementAt(0), (FinderPattern) possibleCenters.elementAt(1), (FinderPattern) possibleCenters.elementAt(2) }; } /** * <p>Having found three "best" finder patterns we need to decide which is the top-left, top-right, * bottom-left. We assume that the one closest to the other two is the top-left one; this is not * strictly true (imagine extreme perspective distortion) but for the moment is a serviceable assumption. * Lastly we sort top-right from bottom-left by figuring out orientation from vector cross products.</p> * * @param patterns three best {@link FinderPattern}s * @return same {@link FinderPattern}s ordered bottom-left, top-left, top-right */ private static FinderPattern[] orderBestPatterns(FinderPattern[] patterns) { // Find distances between pattern centers float abDistance = distance(patterns[0], patterns[1]); float bcDistance = distance(patterns[1], patterns[2]); float acDistance = distance(patterns[0], patterns[2]); FinderPattern topLeft; FinderPattern topRight; FinderPattern bottomLeft; // Assume one closest to other two is top left; // topRight and bottomLeft will just be guesses below at first if (bcDistance >= abDistance && bcDistance >= acDistance) { topLeft = patterns[0]; topRight = patterns[1]; bottomLeft = patterns[2]; } else if (acDistance >= bcDistance && acDistance >= abDistance) { topLeft = patterns[1]; topRight = patterns[0]; bottomLeft = patterns[2]; } else { topLeft = patterns[2]; topRight = patterns[0]; bottomLeft = patterns[1]; } // Use cross product to figure out which of other1/2 is the bottom left // pattern. The vector "top-left -> bottom-left" x "top-left -> top-right" // should yield a vector with positive z component if ((bottomLeft.getY() - topLeft.getY()) * (topRight.getX() - topLeft.getX()) < (bottomLeft.getX() - topLeft.getX()) * (topRight.getY() - topLeft.getY())) { FinderPattern temp = topRight; topRight = bottomLeft; bottomLeft = temp; } return new FinderPattern[]{bottomLeft, topLeft, topRight}; } /** * @return distance between two points */ static float distance(ResultPoint pattern1, ResultPoint pattern2) { float xDiff = pattern1.getX() - pattern2.getX(); float yDiff = pattern1.getY() - pattern2.getY(); return (float) Math.sqrt((double) (xDiff * xDiff + yDiff * yDiff)); } /** * <p>Orders by {@link FinderPattern#getCount()}, descending.</p> */ private static class CenterComparator implements Comparator { public int compare(Object center1, Object center2) { return ((FinderPattern) center2).getCount() - ((FinderPattern) center1).getCount(); } } /** * <p>Orders by variance from average module size, ascending.</p> */ private static class ClosestToAverageComparator implements Comparator { private final float averageModuleSize; private ClosestToAverageComparator(float averageModuleSize) { this.averageModuleSize = averageModuleSize; } public int compare(Object center1, Object center2) { return Math.abs(((FinderPattern) center1).getEstimatedModuleSize() - averageModuleSize) < Math.abs(((FinderPattern) center2).getEstimatedModuleSize() - averageModuleSize) ? -1 : 1; } } }
Switch to integer math in a critical QR Code detector method for speed and tweak a few things before I start investigating this method and the infamous "270 issue" git-svn-id: b10e9e05a96f28f96949e4aa4212c55f640c8f96@485 59b500cc-1b3d-0410-9834-0bbf25fbcc57
core/src/com/google/zxing/qrcode/detector/FinderPatternFinder.java
Switch to integer math in a critical QR Code detector method for speed and tweak a few things before I start investigating this method and the infamous "270 issue"
<ide><path>ore/src/com/google/zxing/qrcode/detector/FinderPatternFinder.java <ide> private static final int CENTER_QUORUM = 2; <ide> private static final int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center <ide> private static final int MAX_MODULES = 57; // support up to version 10 for mobile clients <add> private static final int INTEGER_MATH_SHIFT = 8; <ide> <ide> private final MonochromeBitmapSource image; <ide> private final Vector possibleCenters; <ide> int maxJ = image.getWidth(); <ide> // We are looking for black/white/black/white/black modules in <ide> // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far <del> int[] stateCount = new int[5]; <del> boolean done = false; <ide> <ide> // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the <ide> // image, and then account for the center being 3 modules in size. This gives the smallest <ide> iSkip = MIN_SKIP; <ide> } <ide> <add> boolean done = false; <add> int[] stateCount = new int[5]; <ide> for (int i = iSkip - 1; i < maxI && !done; i += iSkip) { <ide> // Get a row of black/white values <ide> BitArray blackRow = image.getBlackRow(i, null, 0, maxJ); <ide> <ide> /** <ide> * @param stateCount count of black/white/black/white/black pixels just read <del> * @return true iff the proportions of the counts is close enough to the 1/13/1/1 ratios <add> * @return true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios <ide> * used by finder patterns to be considered a match <ide> */ <ide> private static boolean foundPatternCross(int[] stateCount) { <ide> int totalModuleSize = 0; <ide> for (int i = 0; i < 5; i++) { <del> if (stateCount[i] == 0) { <add> int count = stateCount[i]; <add> if (count == 0) { <ide> return false; <ide> } <del> totalModuleSize += stateCount[i]; <add> totalModuleSize += count; <ide> } <ide> if (totalModuleSize < 7) { <ide> return false; <ide> } <del> float moduleSize = (float) totalModuleSize / 7.0f; <del> float maxVariance = moduleSize / 2.0f; <add> int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7; <add> int maxVariance = moduleSize / 2; <ide> // Allow less than 50% variance from 1-1-3-1-1 proportions <del> return Math.abs(moduleSize - stateCount[0]) < maxVariance && <del> Math.abs(moduleSize - stateCount[1]) < maxVariance && <del> Math.abs(3.0f * moduleSize - stateCount[2]) < 3.0f * maxVariance && <del> Math.abs(moduleSize - stateCount[3]) < maxVariance && <del> Math.abs(moduleSize - stateCount[4]) < maxVariance; <add> return Math.abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && <add> Math.abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && <add> Math.abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && <add> Math.abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && <add> Math.abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance; <ide> } <ide> <ide> /**
Java
apache-2.0
dc91cf9ef27fb16f05c0dfc001997b00ebadaac6
0
Hocdoc/lettuce,pulse00/lettuce,Hocdoc/lettuce,taer/lettuce,taer/lettuce,pulse00/lettuce,lettuce-io/lettuce-core,mp911de/lettuce,lettuce-io/lettuce-core,lettuce-io/lettuce-core,lettuce-io/lettuce-core,mp911de/lettuce
// Copyright (C) 2011 - Will Glozer. All rights reserved. package com.lambdaworks.redis.pubsub; import java.util.concurrent.BlockingQueue; import com.lambdaworks.redis.codec.RedisCodec; import com.lambdaworks.redis.protocol.CommandHandler; import com.lambdaworks.redis.protocol.CommandOutput; import com.lambdaworks.redis.protocol.RedisCommand; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; /** * A netty {@link ChannelHandler} responsible for writing redis pub/sub commands and reading the response stream from the * server. * * @param <K> Key type. * @param <V> Value type. * * @author Will Glozer */ public class PubSubCommandHandler<K, V> extends CommandHandler<K, V> { private RedisCodec<K, V> codec; private PubSubOutput<K, V> output; /** * Initialize a new instance. * * @param queue Command queue. * @param codec Codec. */ public PubSubCommandHandler(BlockingQueue<RedisCommand<K, V, ?>> queue, RedisCodec<K, V> codec) { super(queue); this.codec = codec; this.output = new PubSubOutput<K, V>(codec); } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf buffer) throws InterruptedException { while (output.type() == null && !queue.isEmpty()) { CommandOutput<K, V, ?> output = queue.peek().getOutput(); if (!rsm.decode(buffer, output)) { return; } queue.take().complete(); if (output instanceof PubSubOutput) { ctx.fireChannelRead(output); } } while (rsm.decode(buffer, output)) { ctx.fireChannelRead(output); output = new PubSubOutput<K, V>(codec); buffer.discardReadBytes(); } } }
src/main/java/com/lambdaworks/redis/pubsub/PubSubCommandHandler.java
// Copyright (C) 2011 - Will Glozer. All rights reserved. package com.lambdaworks.redis.pubsub; import java.util.concurrent.BlockingQueue; import com.lambdaworks.redis.codec.RedisCodec; import com.lambdaworks.redis.protocol.CommandHandler; import com.lambdaworks.redis.protocol.CommandOutput; import com.lambdaworks.redis.protocol.RedisCommand; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; /** * A netty {@link ChannelHandler} responsible for writing redis pub/sub commands and reading the response stream from the * server. * * @param <K> Key type. * @param <V> Value type. * * @author Will Glozer */ public class PubSubCommandHandler<K, V> extends CommandHandler<K, V> { private RedisCodec<K, V> codec; private PubSubOutput<K, V> output; /** * Initialize a new instance. * * @param queue Command queue. * @param codec Codec. */ public PubSubCommandHandler(BlockingQueue<RedisCommand<K, V, ?>> queue, RedisCodec<K, V> codec) { super(queue); this.codec = codec; this.output = new PubSubOutput<K, V>(codec); } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf buffer) throws InterruptedException { while (output.type() == null && !queue.isEmpty()) { CommandOutput<K, V, ?> output = queue.peek().getOutput(); if (!rsm.decode(buffer, output)) { return; } queue.take().complete(); if (output instanceof PubSubOutput) { ctx.fireChannelRead(output); } } while (rsm.decode(buffer, output)) { ctx.fireChannelRead(output); output = new PubSubOutput<K, V>(codec); } buffer.discardReadBytes(); } }
only discard bytes once they have been fully used
src/main/java/com/lambdaworks/redis/pubsub/PubSubCommandHandler.java
only discard bytes once they have been fully used
<ide><path>rc/main/java/com/lambdaworks/redis/pubsub/PubSubCommandHandler.java <ide> while (rsm.decode(buffer, output)) { <ide> ctx.fireChannelRead(output); <ide> output = new PubSubOutput<K, V>(codec); <add> buffer.discardReadBytes(); <ide> } <del> <del> buffer.discardReadBytes(); <ide> } <ide> <ide> }
Java
apache-2.0
218d1a7694824cca4096a521492cd2fc58b26cec
0
edlectrico/android-dynamic-ui,edlectrico/android-dynamic-ui
package es.deusto.deustotech.dynamicui.modules; import java.util.HashMap; import android.content.Context; import android.util.Log; import com.hp.hpl.jena.ontology.Individual; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.rdf.model.InfModel; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.reasoner.Reasoner; import com.hp.hpl.jena.reasoner.rulesys.GenericRuleReasoner; import com.hp.hpl.jena.reasoner.rulesys.Rule; import es.deusto.deustotech.dynamicui.components.FinalUIConfiguration; import es.deusto.deustotech.dynamicui.components.UIConfiguration; import es.deusto.deustotech.dynamicui.model.ICapability; public class UIReasoner { private ICapability user, device, context; private FinalUIConfiguration finalConfiguration; private HashMap<String, UIConfiguration> currentUI; private HistoryManager historyManager; private Context appContext; public static final String NS = "http://www.deustotech.es/prueba.owl#"; public OntModel ontModel = null; public OntClass ontUserClass = null; public OntClass ontDeviceClass = null; public OntClass ontContextClass = null; public OntClass ontFinalConfClass = null; public Reasoner reasoner; public InfModel infModel; // private static final float MAX_BRIGHTNESS = 1.0F; public UIReasoner(){ super(); } public UIReasoner(ICapability user, ICapability device, ICapability context, HashMap<String, UIConfiguration> currentUI, Context appContext) { super(); this.user = user; this.device = device; this.context = context; this.historyManager = new HistoryManager(this.appContext); this.currentUI = currentUI; this.appContext = appContext; generateModel(); reasoner = new GenericRuleReasoner(Rule.parseRules(loadRules())); executeRules(generateModel()); finalConfiguration = parseConfiguration(); Log.d(UIReasoner.class.getSimpleName(), "Rules ended"); } private Model generateModel() { this.ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); this.ontModel.setNsPrefix("prueba", NS); this.ontUserClass = ontModel.createClass(NS + "User"); this.ontDeviceClass = ontModel.createClass(NS + "Device"); this.ontContextClass = ontModel.createClass(NS + "Context"); this.ontFinalConfClass = ontModel.createClass(NS + "FinalUIConfiguration"); addInstancesWithJena("user", "device", "context", "final_conf"); this.ontModel.write(System.out); return this.ontModel; } /** * This method adds the corresponding classes to the model * * @param userId * @param deviceId * @param contextId * @param finalUIConf */ private void addInstancesWithJena(final String userId, final String deviceId, final String contextId, final String finalUIConf){ addUserInstance(userId); addDeviceInstance(deviceId); addContextInstance(contextId); } private Individual addUserInstance(String id) { Individual individual = this.ontUserClass.createIndividual(NS + id); Property viewSize = this.ontModel.getProperty(NS + "VIEW_SIZE"); Literal literal = this.ontModel.createTypedLiteral("DEFAULT"); individual.setPropertyValue(viewSize, literal); Property input = this.ontModel.getProperty(NS + "INPUT"); literal = this.ontModel.createTypedLiteral(this.user.getCapabilityValue(ICapability.CAPABILITY.INPUT)); individual.setPropertyValue(input, literal); Property brightness = this.ontModel.getProperty(NS + "BRIGHTNESS"); literal = this.ontModel.createTypedLiteral(this.user.getCapabilityValue(ICapability.CAPABILITY.BRIGHTNESS)); individual.setPropertyValue(brightness, literal); return individual; } private Individual addDeviceInstance(String id) { Individual individual = this.ontDeviceClass.createIndividual(NS + id); Property viewSize = this.ontModel.getProperty(NS + "VIEW_SIZE"); Literal literal = this.ontModel.createTypedLiteral(this.device.getCapabilityValue(ICapability.CAPABILITY.VIEW_SIZE)); individual.setPropertyValue(viewSize, literal); Property input = this.ontModel.getProperty(NS + "INPUT"); literal = this.ontModel.createTypedLiteral(this.device.getCapabilityValue(ICapability.CAPABILITY.INPUT)); individual.setPropertyValue(input, literal); Property brightness = this.ontModel.getProperty(NS + "BRIGHTNESS"); literal = this.ontModel.createTypedLiteral(this.device.getCapabilityValue(ICapability.CAPABILITY.BRIGHTNESS)); individual.setPropertyValue(brightness, literal); Property orientation = this.ontModel.getProperty(NS + "ORIENTATION"); literal = this.ontModel.createTypedLiteral(this.device.getCapabilityValue(ICapability.CAPABILITY.ORIENTATION)); individual.setPropertyValue(orientation, literal); Property acceleration = this.ontModel.getProperty(NS + "ACCELERATION"); literal = this.ontModel.createTypedLiteral(this.device.getCapabilityValue(ICapability.CAPABILITY.ORIENTATION)); individual.setPropertyValue(acceleration, literal); return individual; } private Individual addContextInstance(String id) { Individual individual = this.ontContextClass.createIndividual(NS + id); Property viewSize = this.ontModel.getProperty(NS + "TEMPERATURE"); Literal literal = this.ontModel.createTypedLiteral(this.context.getCapabilityValue(ICapability.CAPABILITY.TEMPERATURE)); individual.setPropertyValue(viewSize, literal); Property input = this.ontModel.getProperty(NS + "ILLUMINANCE"); literal = this.ontModel.createTypedLiteral(this.context.getCapabilityValue(ICapability.CAPABILITY.ILLUMINANCE)); individual.setPropertyValue(input, literal); return individual; } /** * This method loads any rule to be executed by the reasoner * @return A String containing every rule */ private String loadRules() { String rules = ""; String adaptViewSize_1 = "[adaptViewSize1: " + "(?u http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.deustotech.es/prueba.owl#User) " + "(?u http://www.deustotech.es/prueba.owl#VIEW_SIZE ?vs) " + "equal(?vs, \"DEFAULT\") " + " -> " + "print(\"ADAPTING CONFIGURATION\") " + "(http://www.deustotech.es/prueba.owl#FinalUIConfigurationInstance http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.deustotech.es/prueba.owl#FinalUIConfiguration) " + "(http://www.deustotech.es/prueba.owl#FinalUIConfigurationInstance http://www.deustotech.es/prueba.owl#VIEW_SIZE \"VERY_BIG\") ]"; String adaptViewSize_2 = "[adaptViewSize2: " + "(?u http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.deustotech.es/prueba.owl#User) " + "(?u http://www.deustotech.es/prueba.owl#VIEW_SIZE ?vs) " + "equal(?vs, \"BIG\") " + " -> " + "(?u http://user.ontology.es#fakeproperty \"RULE_EXECUTED_BIG\")] "; rules = adaptViewSize_1 + adaptViewSize_2 + ""; return rules; } private void executeRules(Model dataModel) { infModel = ModelFactory.createInfModel(reasoner, dataModel); infModel.prepare(); for (Statement st : infModel.listStatements().toList()){ Log.d("InfModel", st.toString()); } } /** * This method extracts the FinalUIConfiguration from the model * to create the corresponding Java Object * * @return The Java Object corresponding to the same FinalUIConfiguration semantic model */ private FinalUIConfiguration parseConfiguration(){ finalConfiguration = new FinalUIConfiguration(); final Resource resource = infModel.getResource("http://www.deustotech.es/prueba.owl#FinalUIConfigurationInstance"); final Statement statement = resource.getProperty(this.ontModel.getProperty(NS + "VIEW_SIZE")); finalConfiguration.setViewSize(statement.getObject().toString()); return finalConfiguration; } /** * This method takes the updated user, the current device's capabilities * and the current configuration and returns the best suitable UI * for this situation. * * @return a new UI configuration (FinalUIConfiguration) to be displayed in the device */ // public FinalUIConfiguration getAdaptedConfiguration() { // //TODO: // //1. Check if there is a previous configuration for this situation // if (checkAdaptationHistory()){ // return historyManager.getAdaptedConfiguration(); // } else { // //2. Else, generate a new one // //2.1 First, from a standard one // StandardUIManager standardUIManager = new StandardUIManager(); // FinalUIConfiguration standardConfiguration = standardUIManager.getStandardConfiguration(user); // // if (StandardUIManager.isSufficient(standardConfiguration)){ // return standardConfiguration; // } else { // //2.2 If it is not sufficient, a new one // //TODO: How do we determine if an adaptation is sufficient enough? // return adaptConfiguration(this.user.getAllCapabilities(), this.device.getAllCapabilities(), this.context.getAllCapabilities()); // } // } // } // // private boolean checkAdaptationHistory() { // return historyManager.checkConfiguration(this.user, this.currentUI); // } // // private FinalUIConfiguration adaptConfiguration( // HashMap<CAPABILITY, Object> userCapabilities, // HashMap<CAPABILITY, Object> deviceCapabilities, // HashMap<CAPABILITY, Object> contextCapabilities) { // // //TODO: This is a mock configuration. The logic of this method // //should return the corresponding UIConfiguration object so // //the AdaptationModule could adapt the UI to its characteristics // // /** // * 1. Get user capabilities // * 2. Get current UI configuration // * 3. If it is not enough, generate a new configuration taking into account the // * defined taxonomy of how each component from context, user and device affects // * to the final UI result component // */ // // FinalUIConfiguration finalUIConfiguration = new FinalUIConfiguration(); // // // //TODO: This class should obtain the corresponding output // //via certain rules in order to obtain the corresponding // //component adaptation // // /** // * VIEW_SIZE // * // * Affected by: // * -Context: luminosity, temperature // * -User; output, view_size, brightness // * -Device: brightness, output, acceleration, view_size, orientation // * // * Priorities order: // * -user_output, device_output, user_view_size, device_view_size, context_luminosity, device_brightness. // * context_temperature, device_orientation, device_acceleration // * // * */ // // if (userCapabilities.get(CAPABILITY.OUTPUT).equals(ICapability.OUTPUT.DEFAULT)){ //User can read text and hear audio // if (deviceCapabilities.get(CAPABILITY.OUTPUT).equals(ICapability.OUTPUT.DEFAULT)){ //device can use text and audio outputs // if (userCapabilities.get(CAPABILITY.VIEW_SIZE).equals(deviceCapabilities.get(CAPABILITY.VIEW_SIZE))){ //the ui is updated to user preference // if (brightnessComparison((ICapability.BRIGHTNESS) deviceCapabilities.get(CAPABILITY.BRIGHTNESS), (ICapability.ILLUMINANCE) contextCapabilities.get(CAPABILITY.ILLUMINANCE)) == 1){ // //TODO: increase brightness // } else if (brightnessComparison((ICapability.BRIGHTNESS)deviceCapabilities.get(CAPABILITY.BRIGHTNESS), (ICapability.ILLUMINANCE)contextCapabilities.get(CAPABILITY.ILLUMINANCE)) == -1){ // //TODO: decrease brightness // } // } else if (viewSizeComparison((ICapability.VIEW_SIZE)userCapabilities.get(CAPABILITY.VIEW_SIZE), (ICapability.VIEW_SIZE)deviceCapabilities.get(CAPABILITY.VIEW_SIZE)) == 1){ //the ui is NOT updated to user preference // //TODO: increase view size // } else if (viewSizeComparison((ICapability.VIEW_SIZE)userCapabilities.get(CAPABILITY.VIEW_SIZE), (ICapability.VIEW_SIZE)deviceCapabilities.get(CAPABILITY.VIEW_SIZE)) == -1){ // //TODO: decrease view size // } // } // } else if (userCapabilities.get(CAPABILITY.OUTPUT).equals(ICapability.OUTPUT.ONLY_TEXT)){ // // } else if (userCapabilities.get(CAPABILITY.OUTPUT).equals(ICapability.OUTPUT.ONLY_AUDIO)){ // // } // // // // // if (userCapabilities.get(CAPABILITY.VIEW_SIZE).equals(ICapability.VIEW_SIZE.BIG)){ //// if (currentUI.get(WidgetName.BUTTON).getHeight() == -2){ //wrap_content // finalUIConfiguration.setHeight(500); //// } else finalUIConfiguration.setHeight(200); // //// if (currentUI.get(WidgetName.BUTTON).getWidth() == -2){ //wrap_content // finalUIConfiguration.setWidth(500); //// } else finalUIConfiguration.setWidth(200); // // } else { // finalUIConfiguration.setHeight(100); // finalUIConfiguration.setWidth(100); // } // // /** // * TEXT_SIZE // * // * Affected by: // * -Context: luminosity // * -User; output, text_size // * -Device: acceleration, text_size // * // * */ // // // if (userCapabilities.get(CAPABILITY.USER_TEXT_SIZE).equals(ICapability.TEXT_SIZE.BIG)){ //// if ((!currentUI.get(CAPABILITY.DEVICE_TEXT_SIZE).equals(ICapability.TEXT_SIZE.BIG)) && //// (!currentUI.get(CAPABILITY.DEVICE_TEXT_SIZE).equals(ICapability.TEXT_SIZE.VERY_BIG))) { //// //TODO: BIG //// } //// } // // // /** // * BRIGHTNESS // * // * Affected by: // * -Context: luminosity // * -User; output, brightness // * -Device: brightness, battery // * // * */ // // //http://stackoverflow.com/questions/7704961/screen-brightness-value-in-android // //http://stackoverflow.com/questions/3737579/changing-screen-brightness-programmatically-in-android // // // /* // if (userCapabilities.get(CAPABILITY.USER_BRIGHTNESS).equals(ICapability.BRIGHTNESS.VERY_HIGH)){ // if (!currentUI.get(CAPABILITY.DEVICE_BRIGHTNESS).equals(ICapability.BRIGHTNESS.VERY_HIGH)){ // //TODO: Higher brightness value // } // } // */ // // finalUIConfiguration.setBrightness(ICapability.BRIGHTNESS.VERY_HIGH); // // // //TODO: Can it be changed? // /** // * CONTRAST // * // * Affected by: // * -Context: luminosity // * -User; output, contrast // * -Device: contrast // * // * */ // // /** // * VIEW_COLOR // * // * Affected by: // * -Context: luminosity // * -User; output, input? text_color, view_color // * -Device: brightness, text_color, view_color, output? input? // * // * rule_1.1: if user_input && user_output is HAPTIC (views available) // * rule_1.2: if device_input && device_output is HAPTIC // * //the last adaptation value will be made by context // * rule_1.3: if user_view_color != device_text_color (if not different, can't see the text) // * rule_1.4: if context_luminosity < value_x // * if context_luminosity > value_y // * // * RULE_1_RESULT // * // * */ // // finalUIConfiguration.setViewColor(Color.GREEN); // // /** // * TEXT_COLOR (almost same VIEW_COLOR rules) // * // * Affected by: // * -Context: luminosity // * -User; output, text_color, view_color // * -Device: brightness, text_color, view_color, // * // * Text is not just for HAPTIC interfaces, non-haptic // * ones also use text. // * Text color must be always different from the "button" // * or the control one. // * // * */ // // finalUIConfiguration.setTextColor(Color.BLUE); // // // /** // * VOLUME // * // * Affected by: // * -Context: noise // * -User; output, volume // * -Device: output, battery, volume // * // * rule_3.1: if device_output is VOLUME // * rule_3.2: if context_noise > device_volume // * rule_3.3: if user_volume < context_noise // * rule_3.4: if device_battery is OK // * // * RULE_3_RESULT // * */ // // //http://stackoverflow.com/questions/2539264/volume-control-in-android-application // // // /* // if (userCapabilities.get(CAPABILITY.USER_BRIGHTNESS).equals(ICapability.BRIGHTNESS.VERY_HIGH)){ // if (this.currentUI.get(WidgetName.BUTTON).getHeight() == -2){ //wrap_content // //TODO: Bigger // return new UIConfiguration(Color.RED, Color.GREEN, 500, 700, "VERY BIG"); // } // } // // return new UIConfiguration(Color.RED, Color.GREEN, 500, 500, "TEST"); // */ // //// finalUIConfiguration.setTextColor(Color.GREEN); //// finalUIConfiguration.setViewColor(Color.WHITE ); // finalUIConfiguration.setText("TESTING"); // // return finalUIConfiguration; // } /** * This method compares current device brightness status with the context brightness levels * * @param deviceBrightness * @param contextBrightness * @return a number indicting if * -1: device brightness level is higher than the context one, * 0: if both are the same (adaptation is ok) or * 1: if context brightness is higher than the device configuration screen brightness */ private int brightnessComparison(ICapability.BRIGHTNESS deviceBrightness, ICapability.ILLUMINANCE contextBrightness){ if (deviceBrightness.equals(ICapability.BRIGHTNESS.LOW) || deviceBrightness.equals(ICapability.BRIGHTNESS.DEFAULT) || deviceBrightness.equals(ICapability.BRIGHTNESS.HIGH)){ if (contextBrightness.equals(ICapability.ILLUMINANCE.SUNLIGHT)){ return 1; //context value higher than device current brightness level } else return -1; } else if (((deviceBrightness.equals(ICapability.BRIGHTNESS.VERY_HIGH)) && contextBrightness.equals(ICapability.ILLUMINANCE.SUNLIGHT)) || (((deviceBrightness.equals(ICapability.BRIGHTNESS.DEFAULT)) || deviceBrightness.equals(ICapability.BRIGHTNESS.LOW) && contextBrightness.equals(ICapability.ILLUMINANCE.MOONLESS_OVERCAST_NIGHT)))){ return 0; } else return -1; } /** *This method compares current device view size status with the user's * @param userViewSize * @param deviceViewSize * @return a number indicting if * -1: user view size is higher than the device's, * 0: if both are the same (adaptation is ok) or * 1: if device view size is higher than the user's */ private int viewSizeComparison(ICapability.VIEW_SIZE userViewSize, ICapability.VIEW_SIZE deviceViewSize){ if (userViewSize.equals(deviceViewSize)){ return 0; } else if (userViewSize.compareTo(deviceViewSize) == -1){ return -1; } else return 1; //TODO: compare enum cardinal order, if User > Device -> return -1; else return 1; } public ICapability getUser() { return user; } public ICapability getDevice() { return device; } public HashMap<String, UIConfiguration> getUiConfiguration() { return currentUI; } }
src/es/deusto/deustotech/dynamicui/modules/UIReasoner.java
package es.deusto.deustotech.dynamicui.modules; import java.util.HashMap; import android.content.Context; import android.util.Log; import com.hp.hpl.jena.ontology.Individual; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.rdf.model.InfModel; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.reasoner.Reasoner; import com.hp.hpl.jena.reasoner.rulesys.GenericRuleReasoner; import com.hp.hpl.jena.reasoner.rulesys.Rule; import es.deusto.deustotech.dynamicui.components.FinalUIConfiguration; import es.deusto.deustotech.dynamicui.components.UIConfiguration; import es.deusto.deustotech.dynamicui.model.ICapability; public class UIReasoner { private ICapability user, device, context; private FinalUIConfiguration finalConfiguration; private HashMap<String, UIConfiguration> currentUI; private HistoryManager historyManager; private Context appContext; public static final String NS = "http://www.deustotech.es/prueba.owl#"; public OntModel ontModel = null; public OntClass ontUserClass = null; public OntClass ontDeviceClass = null; public OntClass ontContextClass = null; public OntClass ontFinalConfClass = null; public Reasoner reasoner; public InfModel infModel; // private static final float MAX_BRIGHTNESS = 1.0F; public UIReasoner(){ super(); } public UIReasoner(ICapability user, ICapability device, ICapability context, HashMap<String, UIConfiguration> currentUI, Context appContext) { super(); this.user = user; this.device = device; this.context = context; this.historyManager = new HistoryManager(this.appContext); this.currentUI = currentUI; this.appContext = appContext; generateModel(); reasoner = new GenericRuleReasoner(Rule.parseRules(loadRules())); executeRules(generateModel()); finalConfiguration = parseConfiguration(); Log.d(UIReasoner.class.getSimpleName(), "Rules ended"); } private Model generateModel() { this.ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); this.ontModel.setNsPrefix("prueba", NS); this.ontUserClass = ontModel.createClass(NS + "User"); this.ontDeviceClass = ontModel.createClass(NS + "Device"); this.ontContextClass = ontModel.createClass(NS + "Context"); this.ontFinalConfClass = ontModel.createClass(NS + "FinalUIConfiguration"); addInstancesWithJena("user", "device", "context", "final_conf"); this.ontModel.write(System.out); return this.ontModel; } /** * This method adds the corresponding classes to the model * * @param userId * @param deviceId * @param contextId * @param finalUIConf */ private void addInstancesWithJena(final String userId, final String deviceId, final String contextId, final String finalUIConf){ addUserInstance(userId); addDeviceInstance(deviceId); addContextInstance(contextId); } private Individual addUserInstance(String id) { Individual individual = this.ontUserClass.createIndividual(NS + id); Property viewSize = this.ontModel.getProperty(NS + "VIEW_SIZE"); Literal literal = this.ontModel.createTypedLiteral("DEFAULT"); individual.setPropertyValue(viewSize, literal); Property input = this.ontModel.getProperty(NS + "INPUT"); literal = this.ontModel.createTypedLiteral(this.user.getCapabilityValue(ICapability.CAPABILITY.INPUT)); individual.setPropertyValue(input, literal); Property brightness = this.ontModel.getProperty(NS + "BRIGHTNESS"); literal = this.ontModel.createTypedLiteral(this.user.getCapabilityValue(ICapability.CAPABILITY.BRIGHTNESS)); individual.setPropertyValue(brightness, literal); return individual; } private Individual addDeviceInstance(String id) { Individual individual = this.ontDeviceClass.createIndividual(NS + id); Property viewSize = this.ontModel.getProperty(NS + "VIEW_SIZE"); Literal literal = this.ontModel.createTypedLiteral(this.device.getCapabilityValue(ICapability.CAPABILITY.VIEW_SIZE)); individual.setPropertyValue(viewSize, literal); Property input = this.ontModel.getProperty(NS + "INPUT"); literal = this.ontModel.createTypedLiteral(this.device.getCapabilityValue(ICapability.CAPABILITY.INPUT)); individual.setPropertyValue(input, literal); Property brightness = this.ontModel.getProperty(NS + "BRIGHTNESS"); literal = this.ontModel.createTypedLiteral(this.device.getCapabilityValue(ICapability.CAPABILITY.BRIGHTNESS)); individual.setPropertyValue(brightness, literal); Property orientation = this.ontModel.getProperty(NS + "ORIENTATION"); literal = this.ontModel.createTypedLiteral(this.device.getCapabilityValue(ICapability.CAPABILITY.ORIENTATION)); individual.setPropertyValue(orientation, literal); Property acceleration = this.ontModel.getProperty(NS + "ACCELERATION"); literal = this.ontModel.createTypedLiteral(this.device.getCapabilityValue(ICapability.CAPABILITY.ORIENTATION)); individual.setPropertyValue(acceleration, literal); return individual; } private Individual addContextInstance(String id) { Individual individual = this.ontContextClass.createIndividual(NS + id); Property viewSize = this.ontModel.getProperty(NS + "TEMPERATURE"); Literal literal = this.ontModel.createTypedLiteral(this.context.getCapabilityValue(ICapability.CAPABILITY.TEMPERATURE)); individual.setPropertyValue(viewSize, literal); Property input = this.ontModel.getProperty(NS + "ILLUMINANCE"); literal = this.ontModel.createTypedLiteral(this.context.getCapabilityValue(ICapability.CAPABILITY.ILLUMINANCE)); individual.setPropertyValue(input, literal); return individual; } /** * This method loads any rule to be executed by the reasoner * @return A String containing every rule */ private String loadRules() { String rules = ""; String adaptViewSize_1 = "[adaptViewSize1: " + "(?u http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.deustotech.es/prueba.owl#User) " + "(?u http://www.deustotech.es/prueba.owl#VIEW_SIZE ?vs) " + "equal(?vs, \"DEFAULT\") " + " -> " + "print(\"ADAPTING CONFIGURATION\") " + "(http://www.deustotech.es/prueba.owl#FinalUIConfigurationInstance http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.deustotech.es/prueba.owl#FinalUIConfiguration) " + "(http://www.deustotech.es/prueba.owl#FinalUIConfigurationInstance http://www.deustotech.es/prueba.owl#VIEW_SIZE \"VERY_BIG\") ]"; String adaptViewSize_2 = "[adaptViewSize2: " + "(?u http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.deustotech.es/prueba.owl#User) " + "(?u http://www.deustotech.es/prueba.owl#VIEW_SIZE ?vs) " + "equal(?vs, \"BIG\") " + " -> " + "(?u http://user.ontology.es#fakeproperty \"RULE_EXECUTED_BIG\")] "; rules = adaptViewSize_1 + adaptViewSize_2 + ""; return rules; } private void executeRules(Model dataModel) { infModel = ModelFactory.createInfModel(reasoner, dataModel); infModel.prepare(); for (Statement st : infModel.listStatements().toList()){ Log.d("InfModel", st.toString()); } } /** * This method extracts the FinalUIConfiguration from the model * to create the corresponding Java Object * * @return The Java Object corresponding to the same FinalUIConfiguration semantic model */ private FinalUIConfiguration parseConfiguration(){ finalConfiguration = new FinalUIConfiguration(); final Resource resource = infModel.getResource("http://www.deustotech.es/prueba.owl#FinalUIConfigurationInstance"); final Statement statement = resource.getProperty(this.ontModel.getProperty(NS + "VIEW_SIZE")); finalConfiguration.setViewSize(statement.getObject().toString()); return finalConfiguration; } /** * This method takes the updated user, the current device's capabilities * and the current configuration and returns the best suitable UI * for this situation. * * @return a new UI configuration (FinalUIConfiguration) to be displayed in the device */ // public FinalUIConfiguration getAdaptedConfiguration() { // //TODO: // //1. Check if there is a previous configuration for this situation // if (checkAdaptationHistory()){ // return historyManager.getAdaptedConfiguration(); // } else { // //2. Else, generate a new one // //2.1 First, from a standard one // StandardUIManager standardUIManager = new StandardUIManager(); // FinalUIConfiguration standardConfiguration = standardUIManager.getStandardConfiguration(user); // // if (StandardUIManager.isSufficient(standardConfiguration)){ // return standardConfiguration; // } else { // //2.2 If it is not sufficient, a new one // //TODO: How do we determine if an adaptation is sufficient enough? // return adaptConfiguration(this.user.getAllCapabilities(), this.device.getAllCapabilities(), this.context.getAllCapabilities()); // } // } // } // // private boolean checkAdaptationHistory() { // return historyManager.checkConfiguration(this.user, this.currentUI); // } // // private FinalUIConfiguration adaptConfiguration( // HashMap<CAPABILITY, Object> userCapabilities, // HashMap<CAPABILITY, Object> deviceCapabilities, // HashMap<CAPABILITY, Object> contextCapabilities) { // // //TODO: This is a mock configuration. The logic of this method // //should return the corresponding UIConfiguration object so // //the AdaptationModule could adapt the UI to its characteristics // // /** // * 1. Get user capabilities // * 2. Get current UI configuration // * 3. If it is not enough, generate a new configuration taking into account the // * defined taxonomy of how each component from context, user and device affects // * to the final UI result component // */ // // FinalUIConfiguration finalUIConfiguration = new FinalUIConfiguration(); // // // //TODO: This class should obtain the corresponding output // //via certain rules in order to obtain the corresponding // //component adaptation // // /** // * VIEW_SIZE // * // * Affected by: // * -Context: luminosity, temperature // * -User; output, view_size, brightness // * -Device: brightness, output, acceleration, view_size, orientation // * // * Priorities order: // * -user_output, device_output, user_view_size, device_view_size, context_luminosity, device_brightness. // * context_temperature, device_orientation, device_acceleration // * // * */ // // if (userCapabilities.get(CAPABILITY.OUTPUT).equals(ICapability.OUTPUT.DEFAULT)){ //User can read text and hear audio // if (deviceCapabilities.get(CAPABILITY.OUTPUT).equals(ICapability.OUTPUT.DEFAULT)){ //device can use text and audio outputs // if (userCapabilities.get(CAPABILITY.VIEW_SIZE).equals(deviceCapabilities.get(CAPABILITY.VIEW_SIZE))){ //the ui is updated to user preference // if (brightnessComparison((ICapability.BRIGHTNESS) deviceCapabilities.get(CAPABILITY.BRIGHTNESS), (ICapability.ILLUMINANCE) contextCapabilities.get(CAPABILITY.ILLUMINANCE)) == 1){ // //TODO: increase brightness // } else if (brightnessComparison((ICapability.BRIGHTNESS)deviceCapabilities.get(CAPABILITY.BRIGHTNESS), (ICapability.ILLUMINANCE)contextCapabilities.get(CAPABILITY.ILLUMINANCE)) == -1){ // //TODO: decrease brightness // } // } else if (viewSizeComparison((ICapability.VIEW_SIZE)userCapabilities.get(CAPABILITY.VIEW_SIZE), (ICapability.VIEW_SIZE)deviceCapabilities.get(CAPABILITY.VIEW_SIZE)) == 1){ //the ui is NOT updated to user preference // //TODO: increase view size // } else if (viewSizeComparison((ICapability.VIEW_SIZE)userCapabilities.get(CAPABILITY.VIEW_SIZE), (ICapability.VIEW_SIZE)deviceCapabilities.get(CAPABILITY.VIEW_SIZE)) == -1){ // //TODO: decrease view size // } // } // } else if (userCapabilities.get(CAPABILITY.OUTPUT).equals(ICapability.OUTPUT.ONLY_TEXT)){ // // } else if (userCapabilities.get(CAPABILITY.OUTPUT).equals(ICapability.OUTPUT.ONLY_AUDIO)){ // // } // // // // // if (userCapabilities.get(CAPABILITY.VIEW_SIZE).equals(ICapability.VIEW_SIZE.BIG)){ //// if (currentUI.get(WidgetName.BUTTON).getHeight() == -2){ //wrap_content // finalUIConfiguration.setHeight(500); //// } else finalUIConfiguration.setHeight(200); // //// if (currentUI.get(WidgetName.BUTTON).getWidth() == -2){ //wrap_content // finalUIConfiguration.setWidth(500); //// } else finalUIConfiguration.setWidth(200); // // } else { // finalUIConfiguration.setHeight(100); // finalUIConfiguration.setWidth(100); // } // // /** // * TEXT_SIZE // * // * Affected by: // * -Context: luminosity // * -User; output, text_size // * -Device: acceleration, text_size // * // * */ // // // if (userCapabilities.get(CAPABILITY.USER_TEXT_SIZE).equals(ICapability.TEXT_SIZE.BIG)){ //// if ((!currentUI.get(CAPABILITY.DEVICE_TEXT_SIZE).equals(ICapability.TEXT_SIZE.BIG)) && //// (!currentUI.get(CAPABILITY.DEVICE_TEXT_SIZE).equals(ICapability.TEXT_SIZE.VERY_BIG))) { //// //TODO: BIG //// } //// } // // // /** // * BRIGHTNESS // * // * Affected by: // * -Context: luminosity // * -User; output, brightness // * -Device: brightness, battery // * // * */ // // //http://stackoverflow.com/questions/7704961/screen-brightness-value-in-android // //http://stackoverflow.com/questions/3737579/changing-screen-brightness-programmatically-in-android // // // /* // if (userCapabilities.get(CAPABILITY.USER_BRIGHTNESS).equals(ICapability.BRIGHTNESS.VERY_HIGH)){ // if (!currentUI.get(CAPABILITY.DEVICE_BRIGHTNESS).equals(ICapability.BRIGHTNESS.VERY_HIGH)){ // //TODO: Higher brightness value // } // } // */ // // finalUIConfiguration.setBrightness(ICapability.BRIGHTNESS.VERY_HIGH); // // // //TODO: Can it be changed? // /** // * CONTRAST // * // * Affected by: // * -Context: luminosity // * -User; output, contrast // * -Device: contrast // * // * */ // // /** // * VIEW_COLOR // * // * Affected by: // * -Context: luminosity // * -User; output, input? text_color, view_color // * -Device: brightness, text_color, view_color, output? input? // * // * rule_1.1: if user_input && user_output is HAPTIC (views available) // * rule_1.2: if device_input && device_output is HAPTIC // * //the last adaptation value will be made by context // * rule_1.3: if user_view_color != device_text_color (if not different, can't see the text) // * rule_1.4: if context_luminosity < value_x // * if context_luminosity > value_y // * // * RULE_1_RESULT // * // * */ // // finalUIConfiguration.setViewColor(Color.GREEN); // // /** // * TEXT_COLOR (almost same VIEW_COLOR rules) // * // * Affected by: // * -Context: luminosity // * -User; output, text_color, view_color // * -Device: brightness, text_color, view_color, // * // * Text is not just for HAPTIC interfaces, non-haptic // * ones also use text. // * Text color must be always different from the "button" // * or the control one. // * // * */ // // finalUIConfiguration.setTextColor(Color.BLUE); // // // /** // * VOLUME // * // * Affected by: // * -Context: noise // * -User; output, volume // * -Device: output, battery, volume // * // * rule_3.1: if device_output is VOLUME // * rule_3.2: if context_noise > device_volume // * rule_3.3: if user_volume < context_noise // * rule_3.4: if device_battery is OK // * // * RULE_3_RESULT // * */ // // //http://stackoverflow.com/questions/2539264/volume-control-in-android-application // // // /* // if (userCapabilities.get(CAPABILITY.USER_BRIGHTNESS).equals(ICapability.BRIGHTNESS.VERY_HIGH)){ // if (this.currentUI.get(WidgetName.BUTTON).getHeight() == -2){ //wrap_content // //TODO: Bigger // return new UIConfiguration(Color.RED, Color.GREEN, 500, 700, "VERY BIG"); // } // } // // return new UIConfiguration(Color.RED, Color.GREEN, 500, 500, "TEST"); // */ // //// finalUIConfiguration.setTextColor(Color.GREEN); //// finalUIConfiguration.setViewColor(Color.WHITE ); // finalUIConfiguration.setText("TESTING"); // // return finalUIConfiguration; // } /** * This method compares current device brightness status with the context brightness levels * * @param deviceBrightness * @param contextBrightness * @return a number indicting if * -1: device brightness level is higher than the context one, * 0: if both are the same (adaptation is ok) or * 1: if context brightness is higher than the device configuration screen brightness */ private int brightnessComparison(ICapability.BRIGHTNESS deviceBrightness, ICapability.ILLUMINANCE contextBrightness){ if (deviceBrightness.equals(ICapability.BRIGHTNESS.LOW) || deviceBrightness.equals(ICapability.BRIGHTNESS.DEFAULT) || deviceBrightness.equals(ICapability.BRIGHTNESS.HIGH)){ if (contextBrightness.equals(ICapability.ILLUMINANCE.SUNLIGHT)){ return 1; //context value higher than device current brightness level } else return -1; } else if (((deviceBrightness.equals(ICapability.BRIGHTNESS.VERY_HIGH)) && contextBrightness.equals(ICapability.ILLUMINANCE.SUNLIGHT)) || (((deviceBrightness.equals(ICapability.BRIGHTNESS.DEFAULT)) || deviceBrightness.equals(ICapability.BRIGHTNESS.LOW) && contextBrightness.equals(ICapability.ILLUMINANCE.MOONLESS_OVERCAST_NIGHT)))){ return 0; } else return -1; } /** *This method compares current device view size status with the user's * @param userViewSize * @param deviceViewSize * @return a number indicting if * -1: user view size is higher than the device's, * 0: if both are the same (adaptation is ok) or * 1: if device view size is higher than the user's */ private int viewSizeComparison(ICapability.VIEW_SIZE userViewSize, ICapability.VIEW_SIZE deviceViewSize){ if (userViewSize.equals(deviceViewSize)){ return 0; } else if (userViewSize.compareTo(deviceViewSize) == -1){ return -1; } else return 1; //TODO: compare enum cardinal order, if User > Device -> return -1; else return 1; } public ICapability getUser() { return user; } public ICapability getDevice() { return device; } public HashMap<String, UIConfiguration> getUiConfiguration() { return currentUI; } }
Few changes
src/es/deusto/deustotech/dynamicui/modules/UIReasoner.java
Few changes
<ide><path>rc/es/deusto/deustotech/dynamicui/modules/UIReasoner.java <ide> * This method loads any rule to be executed by the reasoner <ide> * @return A String containing every rule <ide> */ <del> private String loadRules() { <del> String rules = ""; <del> <del> String adaptViewSize_1 = "[adaptViewSize1: " + <del> "(?u http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.deustotech.es/prueba.owl#User) " + <del> "(?u http://www.deustotech.es/prueba.owl#VIEW_SIZE ?vs) " + <del> "equal(?vs, \"DEFAULT\") " + <del> <del> " -> " + <del> <del> "print(\"ADAPTING CONFIGURATION\") " + <del> "(http://www.deustotech.es/prueba.owl#FinalUIConfigurationInstance http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.deustotech.es/prueba.owl#FinalUIConfiguration) " + <del> "(http://www.deustotech.es/prueba.owl#FinalUIConfigurationInstance http://www.deustotech.es/prueba.owl#VIEW_SIZE \"VERY_BIG\") ]"; <del> <del> <del> String adaptViewSize_2 = "[adaptViewSize2: " + <del> "(?u http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.deustotech.es/prueba.owl#User) " + <del> "(?u http://www.deustotech.es/prueba.owl#VIEW_SIZE ?vs) " + <del> "equal(?vs, \"BIG\") " + <del> <del> " -> " + <del> <del> "(?u http://user.ontology.es#fakeproperty \"RULE_EXECUTED_BIG\")] "; <del> <del> rules = adaptViewSize_1 + adaptViewSize_2 + ""; <del> <del> return rules; <del> } <add> private String loadRules() { <add> String rules = ""; <add> <add> String adaptViewSize_1 = "[adaptViewSize1: " <add> + "(?u http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.deustotech.es/prueba.owl#User) " <add> + "(?u http://www.deustotech.es/prueba.owl#VIEW_SIZE ?vs) " <add> + "equal(?vs, \"DEFAULT\") " <add> + <add> <add> " -> " <add> + <add> <add> "print(\"ADAPTING CONFIGURATION\") " <add> + "(http://www.deustotech.es/prueba.owl#FinalUIConfigurationInstance http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.deustotech.es/prueba.owl#FinalUIConfiguration) " <add> + "(http://www.deustotech.es/prueba.owl#FinalUIConfigurationInstance http://www.deustotech.es/prueba.owl#VIEW_SIZE \"VERY_BIG\") ]"; <add> <add> String adaptViewSize_2 = "[adaptViewSize2: " <add> + "(?u http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.deustotech.es/prueba.owl#User) " <add> + "(?u http://www.deustotech.es/prueba.owl#VIEW_SIZE ?vs) " <add> + "equal(?vs, \"BIG\") " + <add> <add> " -> " + <add> <add> "(?u http://user.ontology.es#fakeproperty \"RULE_EXECUTED_BIG\")] "; <add> <add> rules = adaptViewSize_1 + adaptViewSize_2 + ""; <add> <add> return rules; <add> } <ide> <ide> private void executeRules(Model dataModel) { <ide> infModel = ModelFactory.createInfModel(reasoner, dataModel);
Java
apache-2.0
aa56c3cc08190a8b864d61026a9dce95b6d76bc3
0
paulmadore/woodcoinj,lavajumper/bitcoinj-scrypt,funkshelper/bitcoinj,lavajumper/bitcoinj-scrypt,lavajumper/bitcoinj-scrypt
package com.google.bitcoin.tools; import com.google.bitcoin.core.*; import org.litecoin.LitecoinParams; import com.google.bitcoin.store.BlockStore; import com.google.bitcoin.store.MemoryBlockStore; import com.google.bitcoin.utils.BriefLogFormatter; import com.google.bitcoin.utils.Threading; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.net.InetAddress; import java.nio.ByteBuffer; import java.security.DigestOutputStream; import java.security.MessageDigest; import java.util.Date; import java.util.TreeMap; import static com.google.common.base.Preconditions.checkState; /** * Downloads and verifies a full chain from your local peer, emitting checkpoints at each difficulty transition period * to a file which is then signed with your key. */ public class BuildCheckpoints { public static void main(String[] args) throws Exception { BriefLogFormatter.init(); final NetworkParameters params = LitecoinParams.get(); // Sorted map of UNIX time of block to StoredBlock object. final TreeMap<Integer, StoredBlock> checkpoints = new TreeMap<Integer, StoredBlock>(); // Configure bitcoinj to fetch only headers, not save them to disk, connect to a local fully synced/validated // node and to save block headers that are on interval boundaries, as long as they are <1 month old. final BlockStore store = new MemoryBlockStore(params); final BlockChain chain = new BlockChain(params, store); final PeerGroup peerGroup = new PeerGroup(params, chain); peerGroup.addAddress(InetAddress.getLocalHost()); long now = new Date().getTime() / 1000; peerGroup.setFastCatchupTimeSecs(now); final long oneMonthAgo = now - (86400 * 30); chain.addListener(new AbstractBlockChainListener() { @Override public void notifyNewBestBlock(StoredBlock block) throws VerificationException { int height = block.getHeight(); if (height % params.getInterval() == 0 && block.getHeader().getTimeSeconds() <= oneMonthAgo) { System.out.println(String.format("Checkpointing block %s at height %d", block.getHeader().getHash(), block.getHeight())); checkpoints.put(height, block); } } }, Threading.SAME_THREAD); peerGroup.startAndWait(); peerGroup.downloadBlockChain(); checkState(checkpoints.size() > 0); // Write checkpoint data out. final FileOutputStream fileOutputStream = new FileOutputStream("checkpointslitecoin", false); MessageDigest digest = MessageDigest.getInstance("SHA-256"); final DigestOutputStream digestOutputStream = new DigestOutputStream(fileOutputStream, digest); digestOutputStream.on(false); final DataOutputStream dataOutputStream = new DataOutputStream(digestOutputStream); dataOutputStream.writeBytes("CHECKPOINTS 1"); dataOutputStream.writeInt(0); // Number of signatures to read. Do this later. digestOutputStream.on(true); dataOutputStream.writeInt(checkpoints.size()); ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE); for (StoredBlock block : checkpoints.values()) { block.serializeCompact(buffer); dataOutputStream.write(buffer.array()); buffer.position(0); } dataOutputStream.close(); Sha256Hash checkpointsHash = new Sha256Hash(digest.digest()); System.out.println("Hash of checkpoints data is " + checkpointsHash); digestOutputStream.close(); fileOutputStream.close(); peerGroup.stopAndWait(); store.close(); // Sanity check the created file. CheckpointManager manager = new CheckpointManager(params, new FileInputStream("checkpoints")); checkState(manager.numCheckpoints() == checkpoints.size()); StoredBlock test = manager.getCheckpointBefore(1346335719); // Just after block 200,000 checkState(test.getHeight() == 199584); checkState(test.getHeader().getHashAsString().equals("49b13ca1eb4a55ced4e99e38469db12b74428c19fd2fb9fa0c262e5839eccf6a")); } }
tools/src/main/java/com/google/bitcoin/tools/BuildCheckpoints.java
package com.google.bitcoin.tools; import com.google.bitcoin.core.*; import com.google.bitcoin.params.MainNetParams; import com.google.bitcoin.store.BlockStore; import com.google.bitcoin.store.MemoryBlockStore; import com.google.bitcoin.utils.BriefLogFormatter; import com.google.bitcoin.utils.Threading; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.net.InetAddress; import java.nio.ByteBuffer; import java.security.DigestOutputStream; import java.security.MessageDigest; import java.util.Date; import java.util.TreeMap; import static com.google.common.base.Preconditions.checkState; /** * Downloads and verifies a full chain from your local peer, emitting checkpoints at each difficulty transition period * to a file which is then signed with your key. */ public class BuildCheckpoints { public static void main(String[] args) throws Exception { BriefLogFormatter.init(); final NetworkParameters params = MainNetParams.get(); // Sorted map of UNIX time of block to StoredBlock object. final TreeMap<Integer, StoredBlock> checkpoints = new TreeMap<Integer, StoredBlock>(); // Configure bitcoinj to fetch only headers, not save them to disk, connect to a local fully synced/validated // node and to save block headers that are on interval boundaries, as long as they are <1 month old. final BlockStore store = new MemoryBlockStore(params); final BlockChain chain = new BlockChain(params, store); final PeerGroup peerGroup = new PeerGroup(params, chain); peerGroup.addAddress(InetAddress.getLocalHost()); long now = new Date().getTime() / 1000; peerGroup.setFastCatchupTimeSecs(now); final long oneMonthAgo = now - (86400 * 30); chain.addListener(new AbstractBlockChainListener() { @Override public void notifyNewBestBlock(StoredBlock block) throws VerificationException { int height = block.getHeight(); if (height % params.getInterval() == 0 && block.getHeader().getTimeSeconds() <= oneMonthAgo) { System.out.println(String.format("Checkpointing block %s at height %d", block.getHeader().getHash(), block.getHeight())); checkpoints.put(height, block); } } }, Threading.SAME_THREAD); peerGroup.startAndWait(); peerGroup.downloadBlockChain(); checkState(checkpoints.size() > 0); // Write checkpoint data out. final FileOutputStream fileOutputStream = new FileOutputStream("checkpoints", false); MessageDigest digest = MessageDigest.getInstance("SHA-256"); final DigestOutputStream digestOutputStream = new DigestOutputStream(fileOutputStream, digest); digestOutputStream.on(false); final DataOutputStream dataOutputStream = new DataOutputStream(digestOutputStream); dataOutputStream.writeBytes("CHECKPOINTS 1"); dataOutputStream.writeInt(0); // Number of signatures to read. Do this later. digestOutputStream.on(true); dataOutputStream.writeInt(checkpoints.size()); ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE); for (StoredBlock block : checkpoints.values()) { block.serializeCompact(buffer); dataOutputStream.write(buffer.array()); buffer.position(0); } dataOutputStream.close(); Sha256Hash checkpointsHash = new Sha256Hash(digest.digest()); System.out.println("Hash of checkpoints data is " + checkpointsHash); digestOutputStream.close(); fileOutputStream.close(); peerGroup.stopAndWait(); store.close(); // Sanity check the created file. CheckpointManager manager = new CheckpointManager(params, new FileInputStream("checkpoints")); checkState(manager.numCheckpoints() == checkpoints.size()); StoredBlock test = manager.getCheckpointBefore(1348310800); // Just after block 200,000 checkState(test.getHeight() == 199584); checkState(test.getHeader().getHashAsString().equals("000000000000002e00a243fe9aa49c78f573091d17372c2ae0ae5e0f24f55b52")); } }
Litecoin: generate checkpointslitecoin
tools/src/main/java/com/google/bitcoin/tools/BuildCheckpoints.java
Litecoin: generate checkpointslitecoin
<ide><path>ools/src/main/java/com/google/bitcoin/tools/BuildCheckpoints.java <ide> package com.google.bitcoin.tools; <ide> <ide> import com.google.bitcoin.core.*; <del>import com.google.bitcoin.params.MainNetParams; <add>import org.litecoin.LitecoinParams; <ide> import com.google.bitcoin.store.BlockStore; <ide> import com.google.bitcoin.store.MemoryBlockStore; <ide> import com.google.bitcoin.utils.BriefLogFormatter; <ide> public class BuildCheckpoints { <ide> public static void main(String[] args) throws Exception { <ide> BriefLogFormatter.init(); <del> final NetworkParameters params = MainNetParams.get(); <add> final NetworkParameters params = LitecoinParams.get(); <ide> <ide> // Sorted map of UNIX time of block to StoredBlock object. <ide> final TreeMap<Integer, StoredBlock> checkpoints = new TreeMap<Integer, StoredBlock>(); <ide> checkState(checkpoints.size() > 0); <ide> <ide> // Write checkpoint data out. <del> final FileOutputStream fileOutputStream = new FileOutputStream("checkpoints", false); <add> final FileOutputStream fileOutputStream = new FileOutputStream("checkpointslitecoin", false); <ide> MessageDigest digest = MessageDigest.getInstance("SHA-256"); <ide> final DigestOutputStream digestOutputStream = new DigestOutputStream(fileOutputStream, digest); <ide> digestOutputStream.on(false); <ide> // Sanity check the created file. <ide> CheckpointManager manager = new CheckpointManager(params, new FileInputStream("checkpoints")); <ide> checkState(manager.numCheckpoints() == checkpoints.size()); <del> StoredBlock test = manager.getCheckpointBefore(1348310800); // Just after block 200,000 <add> StoredBlock test = manager.getCheckpointBefore(1346335719); // Just after block 200,000 <ide> checkState(test.getHeight() == 199584); <del> checkState(test.getHeader().getHashAsString().equals("000000000000002e00a243fe9aa49c78f573091d17372c2ae0ae5e0f24f55b52")); <add> checkState(test.getHeader().getHashAsString().equals("49b13ca1eb4a55ced4e99e38469db12b74428c19fd2fb9fa0c262e5839eccf6a")); <ide> } <ide> }
Java
apache-2.0
a3eb32dce8dee5788ace4c34aba2a623f05c5fa3
0
coekie/gentyref,leangen/geantyref
package com.googlecode.gentyref; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.RandomAccess; import junit.framework.TestCase; public abstract class AbstractGenericsReflectorTest extends TestCase { /** * A constant that's false, to use in an if() block for code that's only there to show that it compiles. * This code "proves" that the test is an actual valid test case, by showing the compiler agrees. * But some of the code should not actually be executed, because it might throw exceptions * (because we're too lazy to initialize everything). */ private static final boolean COMPILE_CHECK = false; private static final TypeToken<ArrayList<String>> ARRAYLIST_OF_STRING = new TypeToken<ArrayList<String>>(){}; private static final TypeToken<List<String>> LIST_OF_STRING = new TypeToken<List<String>>(){}; private static final TypeToken<Collection<String>> COLLECTION_OF_STRING = new TypeToken<Collection<String>>(){}; private static final TypeToken<ArrayList<List<String>>> ARRAYLIST_OF_LIST_OF_STRING = new TypeToken<ArrayList<List<String>>>(){}; private static final TypeToken<List<List<String>>> LIST_OF_LIST_OF_STRING = new TypeToken<List<List<String>>>(){}; private static final TypeToken<Collection<List<String>>> COLLECTION_OF_LIST_OF_STRING = new TypeToken<Collection<List<String>>>(){}; private static final TypeToken<ArrayList<? extends String>> ARRAYLIST_OF_EXT_STRING = new TypeToken<ArrayList<? extends String>>(){}; private static final TypeToken<Collection<? extends String>> COLLECTION_OF_EXT_STRING = new TypeToken<Collection<? extends String>>(){}; private static final TypeToken<Collection<? super String>> COLLECTION_OF_SUPER_STRING = new TypeToken<Collection<? super String>>(){}; private static final TypeToken<ArrayList<List<? extends String>>> ARRAYLIST_OF_LIST_OF_EXT_STRING = new TypeToken<ArrayList<List<? extends String>>>(){}; private static final TypeToken<List<List<? extends String>>> LIST_OF_LIST_OF_EXT_STRING = new TypeToken<List<List<? extends String>>>(){}; private static final TypeToken<Collection<List<? extends String>>> COLLECTION_OF_LIST_OF_EXT_STRING = new TypeToken<Collection<List<? extends String>>>(){}; private final ReflectionStrategy strategy; class Box<T> implements WithF<T>, WithFToken<TypeToken<T>> { public T f; } public AbstractGenericsReflectorTest(ReflectionStrategy strategy) { this.strategy = strategy; } private boolean isSupertype(TypeToken<?> supertype, TypeToken<?> subtype) { return strategy.isSupertype(supertype.getType(), subtype.getType()); } /** * Test if superType is seen as a real (not equal) supertype of subType. */ private void testRealSupertype(TypeToken<?> superType, TypeToken<?> subType) { // test if it's really seen as a supertype assertTrue(isSupertype(superType, subType)); // check if they're not seen as supertypes the other way around assertFalse(isSupertype(subType, superType)); } private <T> void checkedTestInexactSupertype(TypeToken<T> expectedSuperclass, TypeToken<? extends T> type) { testInexactSupertype(expectedSuperclass, type); } /** * Checks if the supertype is seen as a supertype of subType. * But, if superType is a Class or ParameterizedType, with different type parameters. */ private void testInexactSupertype(TypeToken<?> superType, TypeToken<?> subType) { testRealSupertype(superType, subType); strategy.testInexactSupertype(superType.getType(), subType.getType()); } /** * Like testExactSuperclass, but the types of the arguments are checked so only valid test cases can be applied */ private <T> void checkedTestExactSuperclass(TypeToken<T> expectedSuperclass, TypeToken<? extends T> type) { testExactSuperclass(expectedSuperclass, type); } /** * Like testExactSuperclass, but the types of the arguments are checked so only valid test cases can be applied */ private <T> void assertCheckedTypeEquals(TypeToken<T> expected, TypeToken<T> type) { assertEquals(expected, type); } /** * Checks if the supertype is seen as a supertype of subType. * SuperType must be a Class or ParameterizedType, with the right type parameters. */ private void testExactSuperclass(TypeToken<?> expectedSuperclass, TypeToken<?> type) { testRealSupertype(expectedSuperclass, type); strategy.testExactSuperclass(expectedSuperclass.getType(), type.getType()); } protected static Class<?> getClassType(Type type) { if (type instanceof Class) { return (Class<?>)type; } else if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; return (Class<?>)pType.getRawType(); } else if (type instanceof GenericArrayType) { GenericArrayType aType = (GenericArrayType) type; Class<?> componentType = getClassType(aType.getGenericComponentType()); return Array.newInstance(componentType, 0).getClass(); } else { throw new IllegalArgumentException("Only supports Class, ParameterizedType and GenericArrayType. Not " + type.getClass()); } } private TypeToken<?> getFieldType(TypeToken<?> forType, String fieldName) { return getFieldType(forType.getType(), fieldName); } /** * Marker interface to mark the type of the field f. * Note: we could use a method instead of a field, so the method could be in the interface, * enforcing correct usage, but that would influence the actual test too much. */ interface WithF<T> {} /** * Variant on WithF, where the type parameter is a TypeToken. * TODO do we really need this? */ interface WithFToken<T extends TypeToken<?>> {} /** * Uses the reflector being tested to get the type of the field named "f" in the given type. * The returned value is cased into a TypeToken assuming the WithF interface is used correctly, * and the reflector returned the correct result. */ @SuppressWarnings("unchecked") // assuming the WithT interface is used correctly private <T> TypeToken<? extends T> getF(TypeToken<? extends WithF<? extends T>> type) { return (TypeToken<? extends T>) getFieldType(type, "f"); } /** * Variant of {@link #getF(TypeToken)} that's stricter in arguments and return type, for checked equals tests. * @see #getF(TypeToken) */ @SuppressWarnings("unchecked") // assuming the WithT interface is used correctly private <T> TypeToken<T> getStrictF(TypeToken<? extends WithF<T>> type) { return (TypeToken<T>) getFieldType(type, "f"); } @SuppressWarnings("unchecked") private <T extends TypeToken<?>> T getFToken(TypeToken<? extends WithFToken<T>> type) { return (T) getFieldType(type, "f"); } private TypeToken<?> getFieldType(Type forType, String fieldName) { try { Class<?> clazz = getClassType(forType); return getFieldType(forType, clazz.getField(fieldName)); } catch (NoSuchFieldException e) { throw new RuntimeException("Error in test: can't find field " + fieldName, e); } } private TypeToken<?> getFieldType(Type forType, Field field) { return TypeToken.get(strategy.getFieldType(forType, field)); } // private Type getReturnType(String methodName, Type forType) { // try { // Class<?> clazz = getClass(forType); // return strategy.getExactReturnType(clazz.getMethod(methodName), forType); // } catch (NoSuchMethodException e) { // throw new RuntimeException("Error in test: can't find method " + methodName, e); // } // } private <T, U extends T> void checkedTestExactSuperclassChain(TypeToken<T> type1, TypeToken<U> type2, TypeToken<? extends U> type3) { testExactSuperclassChain(type1, type2, type3); } private void testExactSuperclassChain(TypeToken<?> ... types) { for (int i = 0; i < types.length; i++) { assertTrue(isSupertype(types[i], types[i])); for (int j = i + 1; j < types.length; j++) { testExactSuperclass(types[i], types[j]); } } } private <T, U extends T> void checkedTestInexactSupertypeChain(TypeToken<T> type1, TypeToken<U> type2, TypeToken<? extends U> type3) { testInexactSupertypeChain(type1, type2, type3); } private void testInexactSupertypeChain(TypeToken<?> ...types) { for (int i = 0; i < types.length; i++) { assertTrue(isSupertype(types[i], types[i])); for (int j = i + 1; j < types.length; j++) { testInexactSupertype(types[i], types[j]); } } } /** * Test that type1 is not a supertype of type2 (and, while we're at it, not vice-versa either). */ private void testNotSupertypes(TypeToken<?>... types) { for (int i = 0; i < types.length; i++) { for (int j = i + 1; j < types.length; j++) { assertFalse(isSupertype(types[i], types[j])); assertFalse(isSupertype(types[j], types[i])); } } } private <T> TypeToken<T> tt(Class<T> t) { return TypeToken.get(t); } public void testBasic() { checkedTestExactSuperclassChain(tt(Object.class), tt(Number.class), tt(Integer.class)); testNotSupertypes(tt(Integer.class), tt(Double.class)); } public void testSimpleTypeParam() { checkedTestExactSuperclassChain(COLLECTION_OF_STRING, LIST_OF_STRING, ARRAYLIST_OF_STRING); testNotSupertypes(COLLECTION_OF_STRING, new TypeToken<ArrayList<Integer>>(){}); } public interface StringList extends List<String> { } public void testStringList() { checkedTestExactSuperclassChain(COLLECTION_OF_STRING, LIST_OF_STRING, tt(StringList.class)); } public void testTextendsStringList() { class C<T extends StringList> implements WithF<T>{ public T f; } // raw if (COMPILE_CHECK) { @SuppressWarnings("unchecked") C c = null; List<String> listOfString = c.f; } testExactSuperclass(LIST_OF_STRING, getFieldType(C.class, "f")); // wildcard TypeToken<? extends StringList> ft = getF(new TypeToken<C<?>>(){}); checkedTestExactSuperclassChain(LIST_OF_STRING, tt(StringList.class), ft); } public void testExtendViaOtherTypeParam() { class C<T extends StringList, U extends T> implements WithF<U> { @SuppressWarnings("unused") public U f; } // raw testExactSuperclass(LIST_OF_STRING, getFieldType(C.class, "f")); // wildcard TypeToken<? extends StringList> ft = getF(new TypeToken<C<?,?>>(){}); checkedTestExactSuperclassChain(LIST_OF_STRING, tt(StringList.class), ft); } @SuppressWarnings("unchecked") public void testMultiBoundParametrizedStringList() { class C<T extends Object & StringList> implements WithF<T>{ @SuppressWarnings("unused") public T f; } // raw new C().f = new Object(); // compile check assertEquals(tt(Object.class), getFieldType(C.class, "f")); // wildcard TypeToken<? extends StringList> ft = getF(new TypeToken<C<?>>(){}); checkedTestExactSuperclassChain(LIST_OF_STRING, tt(StringList.class), ft); } public void testFListOfT_String() { class C<T> implements WithF<List<T>> { @SuppressWarnings("unused") public List<T> f; } TypeToken<List<String>> ft = getStrictF(new TypeToken<C<String>>(){}); assertCheckedTypeEquals(LIST_OF_STRING, ft); } public void testOfListOfString() { checkedTestExactSuperclassChain(COLLECTION_OF_LIST_OF_STRING, LIST_OF_LIST_OF_STRING, ARRAYLIST_OF_LIST_OF_STRING); testNotSupertypes(COLLECTION_OF_LIST_OF_STRING, new TypeToken<ArrayList<List<Integer>>>(){}); } public void testFListOfListOfT_String() { class C<T> implements WithF<List<List<T>>> { @SuppressWarnings("unused") public List<List<T>> f; } TypeToken<List<List<String>>> ft = getStrictF(new TypeToken<C<String>>(){}); assertCheckedTypeEquals(LIST_OF_LIST_OF_STRING, ft); } public interface ListOfListOfT<T> extends List<List<T>> {} public void testListOfListOfT_String() { checkedTestExactSuperclassChain(COLLECTION_OF_LIST_OF_STRING, LIST_OF_LIST_OF_STRING, new TypeToken<ListOfListOfT<String>>(){}); } public interface ListOfListOfT_String extends ListOfListOfT<String> {} public void testListOfListOfT_StringInterface() { checkedTestExactSuperclassChain(COLLECTION_OF_LIST_OF_STRING, LIST_OF_LIST_OF_STRING, tt(ListOfListOfT_String.class)); } public interface ListOfListOfString extends List<List<String>> {} public void testListOfListOfStringInterface() { checkedTestExactSuperclassChain(COLLECTION_OF_LIST_OF_STRING, LIST_OF_LIST_OF_STRING, tt(ListOfListOfString.class)); } public void testWildcardTExtendsListOfListOfString() { class C<T extends List<List<String>>> implements WithF<T> { @SuppressWarnings("unused") public T f; } TypeToken<? extends List<List<String>>> ft = getF(new TypeToken<C<?>>(){}); checkedTestExactSuperclass(COLLECTION_OF_LIST_OF_STRING, ft); } public void testExtWildcard() { checkedTestExactSuperclass(COLLECTION_OF_EXT_STRING, ARRAYLIST_OF_EXT_STRING); checkedTestExactSuperclass(COLLECTION_OF_LIST_OF_EXT_STRING, ARRAYLIST_OF_LIST_OF_EXT_STRING); testNotSupertypes(COLLECTION_OF_EXT_STRING, new TypeToken<ArrayList<Integer>>(){}); testNotSupertypes(COLLECTION_OF_EXT_STRING, new TypeToken<ArrayList<Object>>(){}); } public interface ListOfListOfExtT<T> extends List<List<? extends T>> {} public void testListOfListOfExtT_String() { checkedTestExactSuperclass(COLLECTION_OF_LIST_OF_EXT_STRING, new TypeToken<ListOfListOfExtT<String>>(){}); } public void testUExtendsListOfExtT() { class C<T, U extends List<? extends T>> implements WithF<U> { @SuppressWarnings("unused") public U f; } // this doesn't compile in eclipse, so we hold the compilers hand by adding a step in between // TODO check if this compiles with sun compiler // TypeToken<? extends List<? extends String>> ft = getF(new TypeToken<C<? extends String, ?>>(){}); TypeToken<? extends C<? extends String, ?>> tt = new TypeToken<C<? extends String, ?>>(){}; TypeToken<? extends List<? extends String>> ft = getF(tt); checkedTestInexactSupertype(COLLECTION_OF_EXT_STRING, ft); } public void testListOfExtT() { class C<T> implements WithF<List<? extends T>> { @SuppressWarnings("unused") public List<? extends T> f; } TypeToken<? extends List<? extends String>> ft = getF(new TypeToken<C<String>>(){}); checkedTestExactSuperclass(COLLECTION_OF_EXT_STRING, ft); } public void testListOfSuperT() { class C<T> implements WithF<List<? super T>> { @SuppressWarnings("unused") public List<? super T> f; } TypeToken<? extends List<? super String>> ft = getF(new TypeToken<C<String>>(){}); checkedTestExactSuperclass(COLLECTION_OF_SUPER_STRING, ft); } public void testInnerFieldWithTypeOfOuter() { class Outer<T> { @SuppressWarnings("unused") class Inner implements WithF<T> { public T f; } class Inner2 implements WithF<List<List<? extends T>>> { @SuppressWarnings("unused") public List<List<? extends T>> f; } } TypeToken<String> ft = getStrictF(new TypeToken<Outer<String>.Inner>(){}); assertCheckedTypeEquals(tt(String.class), ft); TypeToken<List<List<? extends String>>> ft2 = getStrictF(new TypeToken<Outer<String>.Inner2>(){}); assertCheckedTypeEquals(LIST_OF_LIST_OF_EXT_STRING, ft2); } public void testInnerExtendsWithTypeOfOuter() { class Outer<T> { class Inner extends ArrayList<T> { } } checkedTestExactSuperclass(COLLECTION_OF_STRING, new TypeToken<Outer<String>.Inner>(){}); } public void testInnerDifferentParams() { class Outer<T> { class Inner<S> { } } // inner param different testNotSupertypes(new TypeToken<Outer<String>.Inner<Integer>>(){}, new TypeToken<Outer<String>.Inner<String>>(){}); // outer param different testNotSupertypes(new TypeToken<Outer<Integer>.Inner<String>>(){}, new TypeToken<Outer<String>.Inner<String>>(){}); } /** * Supertype of a raw type is erased */ @SuppressWarnings("unchecked") public void testSubclassRaw() { class Superclass<T extends Number> { public T t; } class Subclass<U> extends Superclass<Integer>{} assertEquals(tt(Number.class), getFieldType(Subclass.class, "t")); Number n = new Subclass().t; // compile check new Subclass().t = n; // compile check } /** * Supertype of a raw type is erased. * (And there's no such thing as a ParameterizedType with some type parameters raw and others not) */ @SuppressWarnings("unchecked") public void testSubclassRawMix() { class Superclass<T, U extends Number> { // public T t; public U u; } class Subclass<T> extends Superclass<T, Integer> {} assertEquals(tt(Number.class), getFieldType(Subclass.class, "u")); Number n = new Subclass().u; // compile check new Subclass().u = n; // compile check } /** * If a type has no parameters, it doesn't matter that it got erased. * So even though Middleclass was erased, its supertype is not. */ public void testSubclassRawViaUnparameterized() { class Superclass<T extends Number> implements WithF<T> { @SuppressWarnings("unused") public T f; } class Middleclass extends Superclass<Integer> {} class Subclass<U> extends Middleclass {} TypeToken<Integer> ft = getStrictF(tt(Subclass.class)); assertCheckedTypeEquals(tt(Integer.class), ft); } /** * Similar for inner types: the outer type of a raw inner type is also erased */ @SuppressWarnings("unchecked") public void testInnerRaw() { class Outer<T extends Number> { public Inner rawInner; class Inner<U extends T> { public T t; public U u; } } assertEquals(tt(Outer.Inner.class), getFieldType(Outer.class, "rawInner")); assertEquals(tt(Number.class), getFieldType(Outer.Inner.class, "t")); assertEquals(tt(Number.class), getFieldType(Outer.Inner.class, "u")); if (COMPILE_CHECK) { Number n = new Outer<Integer>().rawInner.t; // compile check new Outer<Integer>().rawInner.t = n; // compile check n = new Outer<Integer>().rawInner.u; // compile check new Outer<Integer>().rawInner.u = n; // compile check } } public void testSuperWildcard() { Box<? super Integer> b = new Box<Integer>(); // compile check b.f = new Integer(0); // compile check testInexactSupertype(getFieldType(new TypeToken<Box<? super Integer>>(){}, "f"), tt(Integer.class)); TypeToken<? super Integer> ft = getFToken(new TypeToken<Box<? super Integer>>(){}); checkedTestInexactSupertype(ft, tt(Integer.class)); } public void testContainment() { checkedTestInexactSupertypeChain(new TypeToken<List<?>>(){}, new TypeToken<List<? extends Number>>(){}, new TypeToken<List<Integer>>(){}); checkedTestInexactSupertypeChain(new TypeToken<List<?>>(){}, new TypeToken<List<? super Integer>>(){}, new TypeToken<List<Object>>(){}); } public void testArrays() { checkedTestExactSuperclassChain(tt(Object[].class), tt(Number[].class), tt(Integer[].class)); testNotSupertypes(new TypeToken<Integer[]>(){}, new TypeToken<String[]>(){}); checkedTestExactSuperclassChain(tt(Object.class), tt(Object[].class), tt(Object[][].class)); checkedTestExactSuperclass(tt(Serializable.class), tt(Integer[].class)); checkedTestExactSuperclass(tt(Cloneable[].class), tt(Object[][].class)); } public void testGenericArrays() { checkedTestExactSuperclass(new TypeToken<Collection<String>[]>(){}, new TypeToken<ArrayList<String>[]>(){}); checkedTestInexactSupertype(new TypeToken<Collection<? extends Number>[]>(){}, new TypeToken<ArrayList<Integer>[]>(){}); checkedTestExactSuperclass(tt(RandomAccess[].class), new TypeToken<ArrayList<Integer>[]>(){}); assertTrue(isSupertype(tt(ArrayList[].class), new TypeToken<ArrayList<Integer>[]>(){})); // not checked* because we're avoiding the inverse test } public void testArrayOfT() { class C<T> implements WithF<T[]> { @SuppressWarnings("unused") public T[] f; } TypeToken<String[]> ft = getStrictF(new TypeToken<C<String>>(){}); assertCheckedTypeEquals(tt(String[].class), ft); } public void testArrayOfListOfT() { class C<T> implements WithF<List<T>[]> { @SuppressWarnings("unused") public List<T>[] f; } TypeToken<List<String>[]> ft = getStrictF(new TypeToken<C<String>>(){}); assertCheckedTypeEquals(new TypeToken<List<String>[]>(){}, ft); } @SuppressWarnings("unchecked") public void testArrayRaw() { class C<T> { @SuppressWarnings("unused") public List<String> f; } new C().f = new ArrayList<Integer>(); // compile check assertEquals(tt(List.class), getFieldType(new TypeToken<C>(){}, "f")); } public void testPrimitiveArray() { testNotSupertypes(tt(double[].class), tt(float[].class)); testNotSupertypes(tt(int[].class), tt(Integer[].class)); } public void testCapture() { TypeToken<Box<?>> bw = new TypeToken<Box<?>>(){}; TypeToken<?> capture1 = getF(bw); TypeToken<?> capture2 = getF(bw); assertFalse(capture1.equals(capture2)); // if these were equal, this would be valid: // Box<?> b1 = new Box<Integer>(); // Box<?> b2 = new Box<String>(); // b1.f = b2.f; // but the capture is still equal to itself assertTrue(capture1.equals(capture1)); } class Node<N extends Node<N,E>, E extends Edge<N, E>> implements WithF<List<E>> { public List<E> f; public E e; } class Edge<N extends Node<N,E>, E extends Edge<N, E>> implements WithF<List<N>> { public List<N> f; public N n; } public void testGraphWildcard() { TypeToken<? extends List<? extends Edge<? extends Node<?,?>,?>>> ft = getF(new TypeToken<Node<?, ?>>(){}); testInexactSupertype(new TypeToken<List<? extends Edge<? extends Node<?,?>,?>>>(){}, ft); } public void testGraphCapture() throws NoSuchFieldException { Field e = Node.class.getField("e"); Field n = Edge.class.getField("n"); TypeToken<?> node = new TypeToken<Node<?, ?>>(){}; TypeToken<?> edgeOfNode = getFieldType(node.getType(), e); TypeToken<?> nodeOfEdgeOfNode = getFieldType(edgeOfNode.getType(), n); TypeToken<?> edgeOfNodeOfEdgeOfNode = getFieldType(nodeOfEdgeOfNode.getType(), e); assertEquals(edgeOfNode, edgeOfNodeOfEdgeOfNode); assertFalse(node.equals(nodeOfEdgeOfNode)); // node is not captured, nodeOfEdgeOfNode is } }
src/test/java/com/googlecode/gentyref/AbstractGenericsReflectorTest.java
package com.googlecode.gentyref; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.RandomAccess; import junit.framework.TestCase; public abstract class AbstractGenericsReflectorTest extends TestCase { /** * A constant that's false, to use in an if() block for code that's only there to show that it compiles. * This code "proves" that the test is an actual valid test case, by showing the compiler agrees. * But some of the code should not actually be executed, because it might throw exceptions * (because we're too lazy to initialize everything). */ private static final boolean COMPILE_CHECK = false; private static final TypeToken<ArrayList<String>> ARRAYLIST_OF_STRING = new TypeToken<ArrayList<String>>(){}; private static final TypeToken<List<String>> LIST_OF_STRING = new TypeToken<List<String>>(){}; private static final TypeToken<Collection<String>> COLLECTION_OF_STRING = new TypeToken<Collection<String>>(){}; private static final TypeToken<ArrayList<List<String>>> ARRAYLIST_OF_LIST_OF_STRING = new TypeToken<ArrayList<List<String>>>(){}; private static final TypeToken<List<List<String>>> LIST_OF_LIST_OF_STRING = new TypeToken<List<List<String>>>(){}; private static final TypeToken<Collection<List<String>>> COLLECTION_OF_LIST_OF_STRING = new TypeToken<Collection<List<String>>>(){}; private static final TypeToken<ArrayList<? extends String>> ARRAYLIST_OF_EXT_STRING = new TypeToken<ArrayList<? extends String>>(){}; private static final TypeToken<Collection<? extends String>> COLLECTION_OF_EXT_STRING = new TypeToken<Collection<? extends String>>(){}; private static final TypeToken<Collection<? super String>> COLLECTION_OF_SUPER_STRING = new TypeToken<Collection<? super String>>(){}; private static final TypeToken<ArrayList<List<? extends String>>> ARRAYLIST_OF_LIST_OF_EXT_STRING = new TypeToken<ArrayList<List<? extends String>>>(){}; private static final TypeToken<List<List<? extends String>>> LIST_OF_LIST_OF_EXT_STRING = new TypeToken<List<List<? extends String>>>(){}; private static final TypeToken<Collection<List<? extends String>>> COLLECTION_OF_LIST_OF_EXT_STRING = new TypeToken<Collection<List<? extends String>>>(){}; private final ReflectionStrategy strategy; class Box<T> implements WithF<T>, WithFToken<TypeToken<T>> { public T f; } public AbstractGenericsReflectorTest(ReflectionStrategy strategy) { this.strategy = strategy; } private boolean isSupertype(TypeToken<?> supertype, TypeToken<?> subtype) { return strategy.isSupertype(supertype.getType(), subtype.getType()); } /** * Test if superType is seen as a real (not equal) supertype of subType. */ private void testRealSupertype(TypeToken<?> superType, TypeToken<?> subType) { // test if it's really seen as a supertype assertTrue(isSupertype(superType, subType)); // check if they're not seen as supertypes the other way around assertFalse(isSupertype(subType, superType)); } private <T> void checkedTestInexactSupertype(TypeToken<T> expectedSuperclass, TypeToken<? extends T> type) { testInexactSupertype(expectedSuperclass, type); } /** * Checks if the supertype is seen as a supertype of subType. * But, if superType is a Class or ParameterizedType, with different type parameters. */ private void testInexactSupertype(TypeToken<?> superType, TypeToken<?> subType) { testRealSupertype(superType, subType); strategy.testInexactSupertype(superType.getType(), subType.getType()); } /** * Like testExactSuperclass, but the types of the arguments are checked so only valid test cases can be applied */ private <T> void checkedTestExactSuperclass(TypeToken<T> expectedSuperclass, TypeToken<? extends T> type) { testExactSuperclass(expectedSuperclass, type); } /** * Like testExactSuperclass, but the types of the arguments are checked so only valid test cases can be applied */ private <T> void assertCheckedTypeEquals(TypeToken<T> expected, TypeToken<T> type) { assertEquals(expected, type); } /** * Checks if the supertype is seen as a supertype of subType. * SuperType must be a Class or ParameterizedType, with the right type parameters. */ private void testExactSuperclass(TypeToken<?> expectedSuperclass, TypeToken<?> type) { testRealSupertype(expectedSuperclass, type); strategy.testExactSuperclass(expectedSuperclass.getType(), type.getType()); } protected static Class<?> getClassType(Type type) { if (type instanceof Class) { return (Class<?>)type; } else if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; return (Class<?>)pType.getRawType(); } else if (type instanceof GenericArrayType) { GenericArrayType aType = (GenericArrayType) type; Class<?> componentType = getClassType(aType.getGenericComponentType()); return Array.newInstance(componentType, 0).getClass(); } else { throw new IllegalArgumentException("Only supports Class, ParameterizedType and GenericArrayType. Not " + type.getClass()); } } private TypeToken<?> getFieldType(TypeToken<?> forType, String fieldName) { return getFieldType(forType.getType(), fieldName); } /** * Marker interface to mark the type of the field f. * Note: we could use a method instead of a field, so the method could be in the interface, * enforcing correct usage, but that would influence the actual test too much. */ interface WithF<T> {} /** * Variant on WithF, where the type parameter is a TypeToken. * TODO do we really need this? */ interface WithFToken<T extends TypeToken<?>> {} /** * Uses the reflector being tested to get the type of the field named "f" in the given type. * The returned value is cased into a TypeToken assuming the WithF interface is used correctly, * and the reflector returned the correct result. */ @SuppressWarnings("unchecked") // assuming the WithT interface is used correctly private <T> TypeToken<? extends T> getF(TypeToken<? extends WithF<? extends T>> type) { return (TypeToken<? extends T>) getFieldType(type, "f"); } /** * Variant of {@link #getF(TypeToken)} that's stricter in arguments and return type, for checked equals tests. * @see #getF(TypeToken) */ @SuppressWarnings("unchecked") // assuming the WithT interface is used correctly private <T> TypeToken<T> getStrictF(TypeToken<? extends WithF<T>> type) { return (TypeToken<T>) getFieldType(type, "f"); } @SuppressWarnings("unchecked") private <T extends TypeToken<?>> T getFToken(TypeToken<? extends WithFToken<T>> type) { return (T) getFieldType(type, "f"); } private TypeToken<?> getFieldType(Type forType, String fieldName) { try { Class<?> clazz = getClassType(forType); return TypeToken.get(strategy.getFieldType(forType, clazz.getField(fieldName))); } catch (NoSuchFieldException e) { throw new RuntimeException("Error in test: can't find field " + fieldName, e); } } // private Type getReturnType(String methodName, Type forType) { // try { // Class<?> clazz = getClass(forType); // return strategy.getExactReturnType(clazz.getMethod(methodName), forType); // } catch (NoSuchMethodException e) { // throw new RuntimeException("Error in test: can't find method " + methodName, e); // } // } private <T, U extends T> void checkedTestExactSuperclassChain(TypeToken<T> type1, TypeToken<U> type2, TypeToken<? extends U> type3) { testExactSuperclassChain(type1, type2, type3); } private void testExactSuperclassChain(TypeToken<?> ... types) { for (int i = 0; i < types.length; i++) { assertTrue(isSupertype(types[i], types[i])); for (int j = i + 1; j < types.length; j++) { testExactSuperclass(types[i], types[j]); } } } private <T, U extends T> void checkedTestInexactSupertypeChain(TypeToken<T> type1, TypeToken<U> type2, TypeToken<? extends U> type3) { testInexactSupertypeChain(type1, type2, type3); } private void testInexactSupertypeChain(TypeToken<?> ...types) { for (int i = 0; i < types.length; i++) { assertTrue(isSupertype(types[i], types[i])); for (int j = i + 1; j < types.length; j++) { testInexactSupertype(types[i], types[j]); } } } /** * Test that type1 is not a supertype of type2 (and, while we're at it, not vice-versa either). */ private void testNotSupertypes(TypeToken<?>... types) { for (int i = 0; i < types.length; i++) { for (int j = i + 1; j < types.length; j++) { assertFalse(isSupertype(types[i], types[j])); assertFalse(isSupertype(types[j], types[i])); } } } private <T> TypeToken<T> tt(Class<T> t) { return TypeToken.get(t); } public void testBasic() { checkedTestExactSuperclassChain(tt(Object.class), tt(Number.class), tt(Integer.class)); testNotSupertypes(tt(Integer.class), tt(Double.class)); } public void testSimpleTypeParam() { checkedTestExactSuperclassChain(COLLECTION_OF_STRING, LIST_OF_STRING, ARRAYLIST_OF_STRING); testNotSupertypes(COLLECTION_OF_STRING, new TypeToken<ArrayList<Integer>>(){}); } public interface StringList extends List<String> { } public void testStringList() { checkedTestExactSuperclassChain(COLLECTION_OF_STRING, LIST_OF_STRING, tt(StringList.class)); } public void testTextendsStringList() { class C<T extends StringList> implements WithF<T>{ public T f; } // raw if (COMPILE_CHECK) { @SuppressWarnings("unchecked") C c = null; List<String> listOfString = c.f; } testExactSuperclass(LIST_OF_STRING, getFieldType(C.class, "f")); // wildcard TypeToken<? extends StringList> ft = getF(new TypeToken<C<?>>(){}); checkedTestExactSuperclassChain(LIST_OF_STRING, tt(StringList.class), ft); } public void testExtendViaOtherTypeParam() { class C<T extends StringList, U extends T> implements WithF<U> { @SuppressWarnings("unused") public U f; } // raw testExactSuperclass(LIST_OF_STRING, getFieldType(C.class, "f")); // wildcard TypeToken<? extends StringList> ft = getF(new TypeToken<C<?,?>>(){}); checkedTestExactSuperclassChain(LIST_OF_STRING, tt(StringList.class), ft); } @SuppressWarnings("unchecked") public void testMultiBoundParametrizedStringList() { class C<T extends Object & StringList> implements WithF<T>{ @SuppressWarnings("unused") public T f; } // raw new C().f = new Object(); // compile check assertEquals(tt(Object.class), getFieldType(C.class, "f")); // wildcard TypeToken<? extends StringList> ft = getF(new TypeToken<C<?>>(){}); checkedTestExactSuperclassChain(LIST_OF_STRING, tt(StringList.class), ft); } public void testFListOfT_String() { class C<T> implements WithF<List<T>> { @SuppressWarnings("unused") public List<T> f; } TypeToken<List<String>> ft = getStrictF(new TypeToken<C<String>>(){}); assertCheckedTypeEquals(LIST_OF_STRING, ft); } public void testOfListOfString() { checkedTestExactSuperclassChain(COLLECTION_OF_LIST_OF_STRING, LIST_OF_LIST_OF_STRING, ARRAYLIST_OF_LIST_OF_STRING); testNotSupertypes(COLLECTION_OF_LIST_OF_STRING, new TypeToken<ArrayList<List<Integer>>>(){}); } public void testFListOfListOfT_String() { class C<T> implements WithF<List<List<T>>> { @SuppressWarnings("unused") public List<List<T>> f; } TypeToken<List<List<String>>> ft = getStrictF(new TypeToken<C<String>>(){}); assertCheckedTypeEquals(LIST_OF_LIST_OF_STRING, ft); } public interface ListOfListOfT<T> extends List<List<T>> {} public void testListOfListOfT_String() { checkedTestExactSuperclassChain(COLLECTION_OF_LIST_OF_STRING, LIST_OF_LIST_OF_STRING, new TypeToken<ListOfListOfT<String>>(){}); } public interface ListOfListOfT_String extends ListOfListOfT<String> {} public void testListOfListOfT_StringInterface() { checkedTestExactSuperclassChain(COLLECTION_OF_LIST_OF_STRING, LIST_OF_LIST_OF_STRING, tt(ListOfListOfT_String.class)); } public interface ListOfListOfString extends List<List<String>> {} public void testListOfListOfStringInterface() { checkedTestExactSuperclassChain(COLLECTION_OF_LIST_OF_STRING, LIST_OF_LIST_OF_STRING, tt(ListOfListOfString.class)); } public void testWildcardTExtendsListOfListOfString() { class C<T extends List<List<String>>> implements WithF<T> { @SuppressWarnings("unused") public T f; } TypeToken<? extends List<List<String>>> ft = getF(new TypeToken<C<?>>(){}); checkedTestExactSuperclass(COLLECTION_OF_LIST_OF_STRING, ft); } public void testExtWildcard() { checkedTestExactSuperclass(COLLECTION_OF_EXT_STRING, ARRAYLIST_OF_EXT_STRING); checkedTestExactSuperclass(COLLECTION_OF_LIST_OF_EXT_STRING, ARRAYLIST_OF_LIST_OF_EXT_STRING); testNotSupertypes(COLLECTION_OF_EXT_STRING, new TypeToken<ArrayList<Integer>>(){}); testNotSupertypes(COLLECTION_OF_EXT_STRING, new TypeToken<ArrayList<Object>>(){}); } public interface ListOfListOfExtT<T> extends List<List<? extends T>> {} public void testListOfListOfExtT_String() { checkedTestExactSuperclass(COLLECTION_OF_LIST_OF_EXT_STRING, new TypeToken<ListOfListOfExtT<String>>(){}); } public void testUExtendsListOfExtT() { class C<T, U extends List<? extends T>> implements WithF<U> { @SuppressWarnings("unused") public U f; } // this doesn't compile in eclipse, so we hold the compilers hand by adding a step in between // TODO check if this compiles with sun compiler // TypeToken<? extends List<? extends String>> ft = getF(new TypeToken<C<? extends String, ?>>(){}); TypeToken<? extends C<? extends String, ?>> tt = new TypeToken<C<? extends String, ?>>(){}; TypeToken<? extends List<? extends String>> ft = getF(tt); checkedTestInexactSupertype(COLLECTION_OF_EXT_STRING, ft); } public void testListOfExtT() { class C<T> implements WithF<List<? extends T>> { @SuppressWarnings("unused") public List<? extends T> f; } TypeToken<? extends List<? extends String>> ft = getF(new TypeToken<C<String>>(){}); checkedTestExactSuperclass(COLLECTION_OF_EXT_STRING, ft); } public void testListOfSuperT() { class C<T> implements WithF<List<? super T>> { @SuppressWarnings("unused") public List<? super T> f; } TypeToken<? extends List<? super String>> ft = getF(new TypeToken<C<String>>(){}); checkedTestExactSuperclass(COLLECTION_OF_SUPER_STRING, ft); } public void testInnerFieldWithTypeOfOuter() { class Outer<T> { @SuppressWarnings("unused") class Inner implements WithF<T> { public T f; } class Inner2 implements WithF<List<List<? extends T>>> { @SuppressWarnings("unused") public List<List<? extends T>> f; } } TypeToken<String> ft = getStrictF(new TypeToken<Outer<String>.Inner>(){}); assertCheckedTypeEquals(tt(String.class), ft); TypeToken<List<List<? extends String>>> ft2 = getStrictF(new TypeToken<Outer<String>.Inner2>(){}); assertCheckedTypeEquals(LIST_OF_LIST_OF_EXT_STRING, ft2); } public void testInnerExtendsWithTypeOfOuter() { class Outer<T> { class Inner extends ArrayList<T> { } } checkedTestExactSuperclass(COLLECTION_OF_STRING, new TypeToken<Outer<String>.Inner>(){}); } public void testInnerDifferentParams() { class Outer<T> { class Inner<S> { } } // inner param different testNotSupertypes(new TypeToken<Outer<String>.Inner<Integer>>(){}, new TypeToken<Outer<String>.Inner<String>>(){}); // outer param different testNotSupertypes(new TypeToken<Outer<Integer>.Inner<String>>(){}, new TypeToken<Outer<String>.Inner<String>>(){}); } /** * Supertype of a raw type is erased */ @SuppressWarnings("unchecked") public void testSubclassRaw() { class Superclass<T extends Number> { public T t; } class Subclass<U> extends Superclass<Integer>{} assertEquals(tt(Number.class), getFieldType(Subclass.class, "t")); Number n = new Subclass().t; // compile check new Subclass().t = n; // compile check } /** * Supertype of a raw type is erased. * (And there's no such thing as a ParameterizedType with some type parameters raw and others not) */ @SuppressWarnings("unchecked") public void testSubclassRawMix() { class Superclass<T, U extends Number> { // public T t; public U u; } class Subclass<T> extends Superclass<T, Integer> {} assertEquals(tt(Number.class), getFieldType(Subclass.class, "u")); Number n = new Subclass().u; // compile check new Subclass().u = n; // compile check } /** * If a type has no parameters, it doesn't matter that it got erased. * So even though Middleclass was erased, its supertype is not. */ public void testSubclassRawViaUnparameterized() { class Superclass<T extends Number> implements WithF<T> { @SuppressWarnings("unused") public T f; } class Middleclass extends Superclass<Integer> {} class Subclass<U> extends Middleclass {} TypeToken<Integer> ft = getStrictF(tt(Subclass.class)); assertCheckedTypeEquals(tt(Integer.class), ft); } /** * Similar for inner types: the outer type of a raw inner type is also erased */ @SuppressWarnings("unchecked") public void testInnerRaw() { class Outer<T extends Number> { public Inner rawInner; class Inner<U extends T> { public T t; public U u; } } assertEquals(tt(Outer.Inner.class), getFieldType(Outer.class, "rawInner")); assertEquals(tt(Number.class), getFieldType(Outer.Inner.class, "t")); assertEquals(tt(Number.class), getFieldType(Outer.Inner.class, "u")); if (COMPILE_CHECK) { Number n = new Outer<Integer>().rawInner.t; // compile check new Outer<Integer>().rawInner.t = n; // compile check n = new Outer<Integer>().rawInner.u; // compile check new Outer<Integer>().rawInner.u = n; // compile check } } public void testSuperWildcard() { Box<? super Integer> b = new Box<Integer>(); // compile check b.f = new Integer(0); // compile check testInexactSupertype(getFieldType(new TypeToken<Box<? super Integer>>(){}, "f"), tt(Integer.class)); TypeToken<? super Integer> ft = getFToken(new TypeToken<Box<? super Integer>>(){}); checkedTestInexactSupertype(ft, tt(Integer.class)); } public void testContainment() { checkedTestInexactSupertypeChain(new TypeToken<List<?>>(){}, new TypeToken<List<? extends Number>>(){}, new TypeToken<List<Integer>>(){}); checkedTestInexactSupertypeChain(new TypeToken<List<?>>(){}, new TypeToken<List<? super Integer>>(){}, new TypeToken<List<Object>>(){}); } public void testArrays() { checkedTestExactSuperclassChain(tt(Object[].class), tt(Number[].class), tt(Integer[].class)); testNotSupertypes(new TypeToken<Integer[]>(){}, new TypeToken<String[]>(){}); checkedTestExactSuperclassChain(tt(Object.class), tt(Object[].class), tt(Object[][].class)); checkedTestExactSuperclass(tt(Serializable.class), tt(Integer[].class)); checkedTestExactSuperclass(tt(Cloneable[].class), tt(Object[][].class)); } public void testGenericArrays() { checkedTestExactSuperclass(new TypeToken<Collection<String>[]>(){}, new TypeToken<ArrayList<String>[]>(){}); checkedTestInexactSupertype(new TypeToken<Collection<? extends Number>[]>(){}, new TypeToken<ArrayList<Integer>[]>(){}); checkedTestExactSuperclass(tt(RandomAccess[].class), new TypeToken<ArrayList<Integer>[]>(){}); assertTrue(isSupertype(tt(ArrayList[].class), new TypeToken<ArrayList<Integer>[]>(){})); // not checked* because we're avoiding the inverse test } public void testArrayOfT() { class C<T> implements WithF<T[]> { @SuppressWarnings("unused") public T[] f; } TypeToken<String[]> ft = getStrictF(new TypeToken<C<String>>(){}); assertCheckedTypeEquals(tt(String[].class), ft); } public void testArrayOfListOfT() { class C<T> implements WithF<List<T>[]> { @SuppressWarnings("unused") public List<T>[] f; } TypeToken<List<String>[]> ft = getStrictF(new TypeToken<C<String>>(){}); assertCheckedTypeEquals(new TypeToken<List<String>[]>(){}, ft); } @SuppressWarnings("unchecked") public void testArrayRaw() { class C<T> { @SuppressWarnings("unused") public List<String> f; } new C().f = new ArrayList<Integer>(); // compile check assertEquals(tt(List.class), getFieldType(new TypeToken<C>(){}, "f")); } public void testPrimitiveArray() { testNotSupertypes(tt(double[].class), tt(float[].class)); testNotSupertypes(tt(int[].class), tt(Integer[].class)); } // TODO graph tests for recursively referring bounds // interface Graph<N extends Node<N, E>, E extends Edge<N, E>> {} // interface Node<N extends Node<N,E>, E extends Edge<N, E>> {} // interface Edge<N extends Node<N,E>, E extends Edge<N, E>> {} }
add tests related to capture conversion git-svn-id: 326906f25eac0196cf968068262a06313b1d5d7a@18 9a24f7ba-d458-11dd-86d7-074df07e0730
src/test/java/com/googlecode/gentyref/AbstractGenericsReflectorTest.java
add tests related to capture conversion
<ide><path>rc/test/java/com/googlecode/gentyref/AbstractGenericsReflectorTest.java <ide> package com.googlecode.gentyref; <ide> import java.io.Serializable; <ide> import java.lang.reflect.Array; <add>import java.lang.reflect.Field; <ide> import java.lang.reflect.GenericArrayType; <ide> import java.lang.reflect.ParameterizedType; <ide> import java.lang.reflect.Type; <ide> private TypeToken<?> getFieldType(Type forType, String fieldName) { <ide> try { <ide> Class<?> clazz = getClassType(forType); <del> return TypeToken.get(strategy.getFieldType(forType, clazz.getField(fieldName))); <add> return getFieldType(forType, clazz.getField(fieldName)); <ide> } catch (NoSuchFieldException e) { <ide> throw new RuntimeException("Error in test: can't find field " + fieldName, e); <ide> } <add> } <add> <add> private TypeToken<?> getFieldType(Type forType, Field field) { <add> return TypeToken.get(strategy.getFieldType(forType, field)); <ide> } <ide> <ide> // private Type getReturnType(String methodName, Type forType) { <ide> testNotSupertypes(tt(int[].class), tt(Integer[].class)); <ide> } <ide> <del> // TODO graph tests for recursively referring bounds <del>// interface Graph<N extends Node<N, E>, E extends Edge<N, E>> {} <del>// interface Node<N extends Node<N,E>, E extends Edge<N, E>> {} <del>// interface Edge<N extends Node<N,E>, E extends Edge<N, E>> {} <del> <add> public void testCapture() { <add> TypeToken<Box<?>> bw = new TypeToken<Box<?>>(){}; <add> TypeToken<?> capture1 = getF(bw); <add> TypeToken<?> capture2 = getF(bw); <add> assertFalse(capture1.equals(capture2)); <add> // if these were equal, this would be valid: <add>// Box<?> b1 = new Box<Integer>(); <add>// Box<?> b2 = new Box<String>(); <add>// b1.f = b2.f; <add> // but the capture is still equal to itself <add> assertTrue(capture1.equals(capture1)); <add> } <add> <add> class Node<N extends Node<N,E>, E extends Edge<N, E>> implements WithF<List<E>> { <add> public List<E> f; <add> public E e; <add> } <add> class Edge<N extends Node<N,E>, E extends Edge<N, E>> implements WithF<List<N>> { <add> public List<N> f; <add> public N n; <add> } <add> <add> public void testGraphWildcard() { <add> TypeToken<? extends List<? extends Edge<? extends Node<?,?>,?>>> ft = getF(new TypeToken<Node<?, ?>>(){}); <add> testInexactSupertype(new TypeToken<List<? extends Edge<? extends Node<?,?>,?>>>(){}, ft); <add> } <add> <add> public void testGraphCapture() throws NoSuchFieldException { <add> Field e = Node.class.getField("e"); <add> Field n = Edge.class.getField("n"); <add> TypeToken<?> node = new TypeToken<Node<?, ?>>(){}; <add> TypeToken<?> edgeOfNode = getFieldType(node.getType(), e); <add> TypeToken<?> nodeOfEdgeOfNode = getFieldType(edgeOfNode.getType(), n); <add> TypeToken<?> edgeOfNodeOfEdgeOfNode = getFieldType(nodeOfEdgeOfNode.getType(), e); <add> assertEquals(edgeOfNode, edgeOfNodeOfEdgeOfNode); <add> assertFalse(node.equals(nodeOfEdgeOfNode)); // node is not captured, nodeOfEdgeOfNode is <add> } <ide> }
Java
apache-2.0
4f902f30d6d770003ebb8ab6fd420d1c00dc520d
0
"etnetera/jmeter,d0k1/jmeter,ThiagoGarciaAlves/jmeter,etnetera/jmeter,irfanah/jmeter,hemikak/jmeter,(...TRUNCATED)
"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license a(...TRUNCATED)
src/jorphan/org/apache/jorphan/logging/LoggingManager.java
"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license a(...TRUNCATED)
"Allow more room for thread name (20 chars)\n\ngit-svn-id: 7c053b8fbd1fb5868f764c6f9536fc6a9bbe7da9@(...TRUNCATED)
src/jorphan/org/apache/jorphan/logging/LoggingManager.java
Allow more room for thread name (20 chars)
"<ide><path>rc/jorphan/org/apache/jorphan/logging/LoggingManager.java\n<ide> \t\t\t+ \"%{category}: (...TRUNCATED)
Java
apache-2.0
368030cf0bd22f8e6020befa6dfed6de0a3ed136
0
1and1/cosmo,1and1/cosmo,1and1/cosmo,astrolox/cosmo,astrolox/cosmo,astrolox/cosmo
"/*\n * Copyright 2006 Open Source Applications Foundation\n * \n * Licensed under the Apache Licens(...TRUNCATED)
cosmo-core/src/main/java/org/unitedinternet/cosmo/dao/ContentDao.java
"/*\n * Copyright 2006 Open Source Applications Foundation\n * \n * Licensed under the Apache Licens(...TRUNCATED)
Marked update/remove content methods as @ExternalizableContent
cosmo-core/src/main/java/org/unitedinternet/cosmo/dao/ContentDao.java
Marked update/remove content methods as @ExternalizableContent
"<ide><path>osmo-core/src/main/java/org/unitedinternet/cosmo/dao/ContentDao.java\n<ide> * (...TRUNCATED)
Java
epl-1.0
9a8ca2930d934d7053e6e3f0b4d1e152ca104b20
0
"debrief/debrief,debrief/debrief,theanuradha/debrief,theanuradha/debrief,theanuradha/debrief,debrief(...TRUNCATED)
"package Debrief.ReaderWriter.NMEA;\r\n\r\nimport java.awt.Color;\r\nimport java.io.BufferedReader;\(...TRUNCATED)
org.mwc.debrief.legacy/src/Debrief/ReaderWriter/NMEA/ImportNMEA.java
"package Debrief.ReaderWriter.NMEA;\r\n\r\nimport java.awt.Color;\r\nimport java.io.BufferedReader;\(...TRUNCATED)
"change processing so we can optionally choose to generate DR track from organic sensors rather than(...TRUNCATED)
org.mwc.debrief.legacy/src/Debrief/ReaderWriter/NMEA/ImportNMEA.java
"change processing so we can optionally choose to generate DR track from organic sensors rather than(...TRUNCATED)
"<ide><path>rg.mwc.debrief.legacy/src/Debrief/ReaderWriter/NMEA/ImportNMEA.java\n<ide> private enu(...TRUNCATED)
Java
bsd-3-clause
a4c876f87ead8fd84668c8f76189c0775c48a4a6
0
"jamie-dryad/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,jimallman/dry(...TRUNCATED)
"/*\n * DSQuery.java\n *\n * Version: $Revision$\n *\n * Date: $Date$\n *\n * Copyright (c) 2002, He(...TRUNCATED)
dspace/src/org/dspace/search/DSQuery.java
"/*\n * DSQuery.java\n *\n * Version: $Revision$\n *\n * Date: $Date$\n *\n * Copyright (c) 2002, He(...TRUNCATED)
"Added hack to allow boolean searching. Basically, I transform 'AND' into '&&',\n'OR' into '||' and (...TRUNCATED)
dspace/src/org/dspace/search/DSQuery.java
"Added hack to allow boolean searching. Basically, I transform 'AND' into '&&', 'OR' into '||' and '(...TRUNCATED)
"<ide><path>space/src/org/dspace/search/DSQuery.java\n<ide> \n<ide> import org.apache.log4j.Logger;\(...TRUNCATED)
README.md exists but content is empty.
Downloads last month
94