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,thomsonreuters/jmeter,hizhangqi/jmeter-1,irfanah/jmeter,ra0077/jmeter,fj11/jmeter,tuanhq/jmeter,ubikfsabbe/jmeter,ThiagoGarciaAlves/jmeter,etnetera/jmeter,ubikloadpack/jmeter,ubikfsabbe/jmeter,ubikfsabbe/jmeter,fj11/jmeter,ubikloadpack/jmeter,thomsonreuters/jmeter,DoctorQ/jmeter,d0k1/jmeter,kyroskoh/jmeter,liwangbest/jmeter,kschroeder/jmeter,fj11/jmeter,hizhangqi/jmeter-1,etnetera/jmeter,tuanhq/jmeter,ThiagoGarciaAlves/jmeter,d0k1/jmeter,DoctorQ/jmeter,hemikak/jmeter,ubikloadpack/jmeter,DoctorQ/jmeter,max3163/jmeter,vherilier/jmeter,etnetera/jmeter,max3163/jmeter,ra0077/jmeter,max3163/jmeter,max3163/jmeter,hemikak/jmeter,hizhangqi/jmeter-1,vherilier/jmeter,ra0077/jmeter,kschroeder/jmeter,ra0077/jmeter,kyroskoh/jmeter,irfanah/jmeter,kyroskoh/jmeter,ubikfsabbe/jmeter,liwangbest/jmeter,vherilier/jmeter,vherilier/jmeter,ubikloadpack/jmeter,liwangbest/jmeter,tuanhq/jmeter,kschroeder/jmeter,thomsonreuters/jmeter,hemikak/jmeter,d0k1/jmeter | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jorphan.logging;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import org.apache.avalon.excalibur.logger.LogKitLoggerManager;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.DefaultContext;
import org.apache.jorphan.util.ClassContext;
import org.apache.log.Hierarchy;
import org.apache.log.LogTarget;
import org.apache.log.Logger;
import org.apache.log.Priority;
import org.apache.log.format.PatternFormatter;
import org.apache.log.output.NullOutputLogTarget;
import org.apache.log.output.io.WriterTarget;
import org.xml.sax.SAXException;
/**
* Manages JMeter logging
*/
public final class LoggingManager {
// N.B time pattern is passed to java.text.SimpleDateFormat
/*
* Predefined format patterns, selected by the property log_format_type (see
* jmeter.properties) The new-line is added later
*/
private static final String DEFAULT_PATTERN = "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} - " //$NON_NLS-1$
+ "%{category}: %{message} %{throwable}"; //$NON_NLS-1$
private static final String PATTERN_THREAD_PREFIX = "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} " //$NON_NLS-1$
+ "%20{thread} %{category}: %{message} %{throwable}"; //$NON_NLS-1$
private static final String PATTERN_THREAD_SUFFIX = "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} " //$NON_NLS-1$
+ "%{category}[%{thread}]: %{message} %{throwable}"; //$NON_NLS-1$
private static PatternFormatter format = null;
/** Used to hold the default logging target. */
//@GuardedBy("this")
private static LogTarget target = new NullOutputLogTarget();
// Hack to detect when System.out has been set as the target, to avoid closing it
private static volatile boolean isTargetSystemOut = false;// Is the target System.out?
private static volatile boolean isWriterSystemOut = false;// Is the Writer System.out?
public static final String LOG_FILE = "log_file"; //$NON_NLS-1$
public static final String LOG_PRIORITY = "log_level"; //$NON_NLS-1$
//@GuardedBy("this")
private static LoggingManager logManager = null;
private LoggingManager() {
}
public static synchronized LoggingManager getLogManager() {
return logManager;
}
/**
* Initialise the logging system from the Jmeter properties. Logkit loggers
* inherit from their parents.
*
* Normally the jmeter properties file defines a single log file, so set
* this as the default from "log_file", default "jmeter.log" The default
* priority is set from "log_level", with a default of INFO
*
*/
public static void initializeLogging(Properties properties) {
synchronized(LoggingManager.class){
if (logManager == null) {
logManager = new LoggingManager();
}
}
setFormat(properties);
// Set the top-level defaults
setTarget(makeWriter(properties.getProperty(LOG_FILE, "jmeter.log"), LOG_FILE)); //$NON_NLS-1$
setPriority(properties.getProperty(LOG_PRIORITY, "INFO"));
setLoggingLevels(properties);
// now set the individual categories (if any)
setConfig(properties);// Further configuration
}
private static void setFormat(Properties properties) {
String pattern = DEFAULT_PATTERN;
String type = properties.getProperty("log_format_type", ""); //$NON_NLS-1$
if (type.length() == 0) {
pattern = properties.getProperty("log_format", DEFAULT_PATTERN); //$NON_NLS-1$
} else {
if (type.equalsIgnoreCase("thread_suffix")) { //$NON_NLS-1$
pattern = PATTERN_THREAD_SUFFIX;
} else if (type.equalsIgnoreCase("thread_prefix")) { //$NON_NLS-1$
pattern = PATTERN_THREAD_PREFIX;
} else {
pattern = DEFAULT_PATTERN;
}
}
format = new PatternFormatter(pattern + "\n"); //$NON_NLS-1$
}
private static void setConfig(Properties p) {
String cfg = p.getProperty("log_config"); //$NON_NLS-1$
if (cfg == null) {
return;
}
// Make sure same hierarchy is used
Hierarchy hier = Hierarchy.getDefaultHierarchy();
LogKitLoggerManager manager = new LogKitLoggerManager(null, hier, null, null);
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
try {
Configuration c = builder.buildFromFile(cfg);
Context ctx = new DefaultContext();
manager.contextualize(ctx);
manager.configure(c);
} catch (IllegalArgumentException e) {
// This happens if the default log-target id-ref specifies a non-existent target
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (NullPointerException e) {
// This can happen if a log-target id-ref specifies a non-existent target
System.out.println("Error processing logging config " + cfg);
System.out.println("Perhaps a log target is missing?");
} catch (ConfigurationException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (SAXException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (IOException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (ContextException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
}
}
/*
* Helper method to ensure that format is initialised if initializeLogging()
* has not yet been called.
*/
private static PatternFormatter getFormat() {
if (format == null) {
format = new PatternFormatter(DEFAULT_PATTERN + "\n"); //$NON_NLS-1$
}
return format;
}
/*
* Helper method to handle log target creation. If there is an error
* creating the file, then it uses System.out.
*/
private static Writer makeWriter(String logFile, String propName) {
// If the name contains at least one set of paired single-quotes, reformat using DateFormat
final int length = logFile.split("'",-1).length;
if (length > 1 && length %2 == 1){
try {
SimpleDateFormat df = new SimpleDateFormat(logFile);
logFile = df.format(new Date());
} catch (Exception ignored) {
}
}
Writer wt;
isWriterSystemOut = false;
try {
wt = new FileWriter(logFile);
} catch (Exception e) {
System.out.println(propName + "=" + logFile + " " + e.toString());
System.out.println("[" + propName + "-> System.out]");
isWriterSystemOut = true;
wt = new PrintWriter(System.out);
}
return wt;
}
/**
* Handle LOG_PRIORITY.category=priority and LOG_FILE.category=file_name
* properties. If the prefix is detected, then remove it to get the
* category.
*/
public static void setLoggingLevels(Properties appProperties) {
Iterator props = appProperties.keySet().iterator();
while (props.hasNext()) {
String prop = (String) props.next();
if (prop.startsWith(LOG_PRIORITY + ".")) //$NON_NLS-1$
// don't match the empty category
{
String category = prop.substring(LOG_PRIORITY.length() + 1);
setPriority(appProperties.getProperty(prop), category);
}
if (prop.startsWith(LOG_FILE + ".")) { //$NON_NLS-1$
String category = prop.substring(LOG_FILE.length() + 1);
String file = appProperties.getProperty(prop);
setTarget(new WriterTarget(makeWriter(file, prop), getFormat()), category);
}
}
}
private static final String PACKAGE_PREFIX = "org.apache."; //$NON_NLS-1$
/*
* Stack contains the follow when the context is obtained:
* 0 - getCallerClassNameAt()
* 1 - this method
* 2 - getLoggerForClass()
*
*/
private static String getCallerClassName() {
String name = ClassContext.getCallerClassNameAt(3);
return name;
}
public static String removePrefix(String name){
if (name.startsWith(PACKAGE_PREFIX)) { // remove the package prefix
name = name.substring(PACKAGE_PREFIX.length());
}
return name;
}
/**
* Get the Logger for a class - no argument needed because the calling class
* name is derived automatically from the call stack.
*
* @return Logger
*/
public static Logger getLoggerForClass() {
String className = getCallerClassName();
return Hierarchy.getDefaultHierarchy().getLoggerFor(removePrefix(className));
}
public static Logger getLoggerFor(String category) {
return Hierarchy.getDefaultHierarchy().getLoggerFor(category);
}
public static Logger getLoggerForShortName(String category) {
return Hierarchy.getDefaultHierarchy().getLoggerFor(removePrefix(category));
}
public static void setPriority(String p, String category) {
setPriority(Priority.getPriorityForName(p), category);
}
/**
*
* @param p - priority, e.g. DEBUG, INFO
* @param fullName - e.g. org.apache.jmeter.etc
*/
public static void setPriorityFullName(String p, String fullName) {
setPriority(Priority.getPriorityForName(p), removePrefix(fullName));
}
public static void setPriority(Priority p, String category) {
Hierarchy.getDefaultHierarchy().getLoggerFor(category).setPriority(p);
}
public static void setPriority(String p) {
setPriority(Priority.getPriorityForName(p));
}
public static void setPriority(Priority p) {
Hierarchy.getDefaultHierarchy().setDefaultPriority(p);
}
public static void setTarget(LogTarget target, String category) {
Logger logger = Hierarchy.getDefaultHierarchy().getLoggerFor(category);
logger.setLogTargets(new LogTarget[] { target });
}
/**
* Sets the default log target from the parameter. The existing target is
* first closed if necessary.
*
* @param targetFile
* (Writer)
*/
public static synchronized void setTarget(Writer targetFile) {
if (target == null) {
target = getTarget(targetFile, getFormat());
isTargetSystemOut = isWriterSystemOut;
} else {
if (!isTargetSystemOut && target instanceof WriterTarget) {
((WriterTarget) target).close();
}
target = getTarget(targetFile, getFormat());
isTargetSystemOut = isWriterSystemOut;
}
Hierarchy.getDefaultHierarchy().setDefaultLogTarget(target);
}
private static LogTarget getTarget(Writer targetFile, PatternFormatter fmt) {
return new WriterTarget(targetFile, fmt);
}
}
| src/jorphan/org/apache/jorphan/logging/LoggingManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jorphan.logging;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import org.apache.avalon.excalibur.logger.LogKitLoggerManager;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.DefaultContext;
import org.apache.jorphan.util.ClassContext;
import org.apache.log.Hierarchy;
import org.apache.log.LogTarget;
import org.apache.log.Logger;
import org.apache.log.Priority;
import org.apache.log.format.PatternFormatter;
import org.apache.log.output.NullOutputLogTarget;
import org.apache.log.output.io.WriterTarget;
import org.xml.sax.SAXException;
/**
* Manages JMeter logging
*/
public final class LoggingManager {
// N.B time pattern is passed to java.text.SimpleDateFormat
/*
* Predefined format patterns, selected by the property log_format_type (see
* jmeter.properties) The new-line is added later
*/
private static final String DEFAULT_PATTERN = "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} - " //$NON_NLS-1$
+ "%{category}: %{message} %{throwable}"; //$NON_NLS-1$
private static final String PATTERN_THREAD_PREFIX = "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} " //$NON_NLS-1$
+ "%12{thread} %{category}: %{message} %{throwable}"; //$NON_NLS-1$
private static final String PATTERN_THREAD_SUFFIX = "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} " //$NON_NLS-1$
+ "%{category}[%{thread}]: %{message} %{throwable}"; //$NON_NLS-1$
private static PatternFormatter format = null;
/** Used to hold the default logging target. */
//@GuardedBy("this")
private static LogTarget target = new NullOutputLogTarget();
// Hack to detect when System.out has been set as the target, to avoid closing it
private static volatile boolean isTargetSystemOut = false;// Is the target System.out?
private static volatile boolean isWriterSystemOut = false;// Is the Writer System.out?
public static final String LOG_FILE = "log_file"; //$NON_NLS-1$
public static final String LOG_PRIORITY = "log_level"; //$NON_NLS-1$
//@GuardedBy("this")
private static LoggingManager logManager = null;
private LoggingManager() {
}
public static synchronized LoggingManager getLogManager() {
return logManager;
}
/**
* Initialise the logging system from the Jmeter properties. Logkit loggers
* inherit from their parents.
*
* Normally the jmeter properties file defines a single log file, so set
* this as the default from "log_file", default "jmeter.log" The default
* priority is set from "log_level", with a default of INFO
*
*/
public static void initializeLogging(Properties properties) {
synchronized(LoggingManager.class){
if (logManager == null) {
logManager = new LoggingManager();
}
}
setFormat(properties);
// Set the top-level defaults
setTarget(makeWriter(properties.getProperty(LOG_FILE, "jmeter.log"), LOG_FILE)); //$NON_NLS-1$
setPriority(properties.getProperty(LOG_PRIORITY, "INFO"));
setLoggingLevels(properties);
// now set the individual categories (if any)
setConfig(properties);// Further configuration
}
private static void setFormat(Properties properties) {
String pattern = DEFAULT_PATTERN;
String type = properties.getProperty("log_format_type", ""); //$NON_NLS-1$
if (type.length() == 0) {
pattern = properties.getProperty("log_format", DEFAULT_PATTERN); //$NON_NLS-1$
} else {
if (type.equalsIgnoreCase("thread_suffix")) { //$NON_NLS-1$
pattern = PATTERN_THREAD_SUFFIX;
} else if (type.equalsIgnoreCase("thread_prefix")) { //$NON_NLS-1$
pattern = PATTERN_THREAD_PREFIX;
} else {
pattern = DEFAULT_PATTERN;
}
}
format = new PatternFormatter(pattern + "\n"); //$NON_NLS-1$
}
private static void setConfig(Properties p) {
String cfg = p.getProperty("log_config"); //$NON_NLS-1$
if (cfg == null) {
return;
}
// Make sure same hierarchy is used
Hierarchy hier = Hierarchy.getDefaultHierarchy();
LogKitLoggerManager manager = new LogKitLoggerManager(null, hier, null, null);
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
try {
Configuration c = builder.buildFromFile(cfg);
Context ctx = new DefaultContext();
manager.contextualize(ctx);
manager.configure(c);
} catch (IllegalArgumentException e) {
// This happens if the default log-target id-ref specifies a non-existent target
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (NullPointerException e) {
// This can happen if a log-target id-ref specifies a non-existent target
System.out.println("Error processing logging config " + cfg);
System.out.println("Perhaps a log target is missing?");
} catch (ConfigurationException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (SAXException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (IOException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (ContextException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
}
}
/*
* Helper method to ensure that format is initialised if initializeLogging()
* has not yet been called.
*/
private static PatternFormatter getFormat() {
if (format == null) {
format = new PatternFormatter(DEFAULT_PATTERN + "\n"); //$NON_NLS-1$
}
return format;
}
/*
* Helper method to handle log target creation. If there is an error
* creating the file, then it uses System.out.
*/
private static Writer makeWriter(String logFile, String propName) {
// If the name contains at least one set of paired single-quotes, reformat using DateFormat
final int length = logFile.split("'",-1).length;
if (length > 1 && length %2 == 1){
try {
SimpleDateFormat df = new SimpleDateFormat(logFile);
logFile = df.format(new Date());
} catch (Exception ignored) {
}
}
Writer wt;
isWriterSystemOut = false;
try {
wt = new FileWriter(logFile);
} catch (Exception e) {
System.out.println(propName + "=" + logFile + " " + e.toString());
System.out.println("[" + propName + "-> System.out]");
isWriterSystemOut = true;
wt = new PrintWriter(System.out);
}
return wt;
}
/**
* Handle LOG_PRIORITY.category=priority and LOG_FILE.category=file_name
* properties. If the prefix is detected, then remove it to get the
* category.
*/
public static void setLoggingLevels(Properties appProperties) {
Iterator props = appProperties.keySet().iterator();
while (props.hasNext()) {
String prop = (String) props.next();
if (prop.startsWith(LOG_PRIORITY + ".")) //$NON_NLS-1$
// don't match the empty category
{
String category = prop.substring(LOG_PRIORITY.length() + 1);
setPriority(appProperties.getProperty(prop), category);
}
if (prop.startsWith(LOG_FILE + ".")) { //$NON_NLS-1$
String category = prop.substring(LOG_FILE.length() + 1);
String file = appProperties.getProperty(prop);
setTarget(new WriterTarget(makeWriter(file, prop), getFormat()), category);
}
}
}
private static final String PACKAGE_PREFIX = "org.apache."; //$NON_NLS-1$
/*
* Stack contains the follow when the context is obtained:
* 0 - getCallerClassNameAt()
* 1 - this method
* 2 - getLoggerForClass()
*
*/
private static String getCallerClassName() {
String name = ClassContext.getCallerClassNameAt(3);
return name;
}
public static String removePrefix(String name){
if (name.startsWith(PACKAGE_PREFIX)) { // remove the package prefix
name = name.substring(PACKAGE_PREFIX.length());
}
return name;
}
/**
* Get the Logger for a class - no argument needed because the calling class
* name is derived automatically from the call stack.
*
* @return Logger
*/
public static Logger getLoggerForClass() {
String className = getCallerClassName();
return Hierarchy.getDefaultHierarchy().getLoggerFor(removePrefix(className));
}
public static Logger getLoggerFor(String category) {
return Hierarchy.getDefaultHierarchy().getLoggerFor(category);
}
public static Logger getLoggerForShortName(String category) {
return Hierarchy.getDefaultHierarchy().getLoggerFor(removePrefix(category));
}
public static void setPriority(String p, String category) {
setPriority(Priority.getPriorityForName(p), category);
}
/**
*
* @param p - priority, e.g. DEBUG, INFO
* @param fullName - e.g. org.apache.jmeter.etc
*/
public static void setPriorityFullName(String p, String fullName) {
setPriority(Priority.getPriorityForName(p), removePrefix(fullName));
}
public static void setPriority(Priority p, String category) {
Hierarchy.getDefaultHierarchy().getLoggerFor(category).setPriority(p);
}
public static void setPriority(String p) {
setPriority(Priority.getPriorityForName(p));
}
public static void setPriority(Priority p) {
Hierarchy.getDefaultHierarchy().setDefaultPriority(p);
}
public static void setTarget(LogTarget target, String category) {
Logger logger = Hierarchy.getDefaultHierarchy().getLoggerFor(category);
logger.setLogTargets(new LogTarget[] { target });
}
/**
* Sets the default log target from the parameter. The existing target is
* first closed if necessary.
*
* @param targetFile
* (Writer)
*/
public static synchronized void setTarget(Writer targetFile) {
if (target == null) {
target = getTarget(targetFile, getFormat());
isTargetSystemOut = isWriterSystemOut;
} else {
if (!isTargetSystemOut && target instanceof WriterTarget) {
((WriterTarget) target).close();
}
target = getTarget(targetFile, getFormat());
isTargetSystemOut = isWriterSystemOut;
}
Hierarchy.getDefaultHierarchy().setDefaultLogTarget(target);
}
private static LogTarget getTarget(Writer targetFile, PatternFormatter fmt) {
return new WriterTarget(targetFile, fmt);
}
}
| Allow more room for thread name (20 chars)
git-svn-id: 7c053b8fbd1fb5868f764c6f9536fc6a9bbe7da9@654760 13f79535-47bb-0310-9956-ffa450edef68
| 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
<ide> + "%{category}: %{message} %{throwable}"; //$NON_NLS-1$
<ide>
<ide> private static final String PATTERN_THREAD_PREFIX = "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} " //$NON_NLS-1$
<del> + "%12{thread} %{category}: %{message} %{throwable}"; //$NON_NLS-1$
<add> + "%20{thread} %{category}: %{message} %{throwable}"; //$NON_NLS-1$
<ide>
<ide> private static final String PATTERN_THREAD_SUFFIX = "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} " //$NON_NLS-1$
<ide> + "%{category}[%{thread}]: %{message} %{throwable}"; //$NON_NLS-1$ |
|
Java | apache-2.0 | 368030cf0bd22f8e6020befa6dfed6de0a3ed136 | 0 | 1and1/cosmo,1and1/cosmo,1and1/cosmo,astrolox/cosmo,astrolox/cosmo,astrolox/cosmo | /*
* Copyright 2006 Open Source Applications Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.unitedinternet.cosmo.dao;
import java.util.Date;
import java.util.Set;
import org.unitedinternet.cosmo.dao.external.ExternalizableContent;
import org.unitedinternet.cosmo.model.CollectionItem;
import org.unitedinternet.cosmo.model.ContentItem;
import org.unitedinternet.cosmo.model.User;
/**
* Interface for DAO that provides base operations for content items.
*
* A content item is either a piece of content (or file) or a collection
* containing content items or other collection items.
*
*/
public interface ContentDao extends ItemDao {
/**
* Create a new collection.
*
* @param parent
* parent of collection.
* @param collection
* collection to create
* @return newly created collection
*/
public CollectionItem createCollection(CollectionItem parent,
CollectionItem collection);
/**
* Update collection and children. The set of children can contain
* new items, existing items, and item removals. An item removal
* is recognized by Item.isActive==false.
* @param collection collection to update
* @param children children to updated
* @return updated collection
*/
public CollectionItem updateCollection(CollectionItem collection,
Set<ContentItem> children);
/**
* Update an existing collection.
*
* @param collection
* collection to update
* @return updated collection
*/
public CollectionItem updateCollection(CollectionItem collection);
/**
* Create new content item. A content item represents a piece of content or
* file.
*
* @param parent
* parent collection of content. If null, content is assumed to
* live in the top-level user collection
* @param content
* content to create
* @return newly created content
*/
@ExternalizableContent
public ContentItem createContent(CollectionItem parent, ContentItem content);
/**
* creates a set of content items, used during events import from other calendar
*
* @param parent
* parent collection of content. If null, content is assumed to
* live in the top-level user collection
*
* @param contents
* the set of contents to create
*/
public void createBatchContent(CollectionItem parent, Set<ContentItem> contents);
/**
*
* @param contents Set<ContentItem>
*/
public void updateBatchContent(Set<ContentItem> contents);
/**
*
* @param parent CollectionItem
* @param contents Set<ContentItem>
*/
public void removeBatchContent(CollectionItem parent, Set<ContentItem> contents);
/**
* Create new content item and associate with multiple parent collections.
*
* @param parents
* parent collections of content.
* @param content
* content to create
* @return newly created content
*/
public ContentItem createContent(Set<CollectionItem> parents, ContentItem content);
/**
* Update an existing content item.
*
* @param content
* content item to update
* @return updated content item
*/
@ExternalizableContent
public ContentItem updateContent(ContentItem content);
/**
* Remove content item
*
* @param content
* content item to remove
*/
@ExternalizableContent
public void removeContent(ContentItem content);
/**
* Remove all content owned by a user
*
* @param user
* user to remove content for
*/
public void removeUserContent(User user);
/**
* Remove collection item
*
* @param collection
* collection item to remove
*/
public void removeCollection(CollectionItem collection);
/**
* Update timestamp on collection.
* @param collection collection to update
* @return updated collection
*/
public CollectionItem updateCollectionTimestamp(CollectionItem collection);
/**
* Load all children for collection that have been updated since a
* given timestamp. If no timestamp is specified, then return all
* children.
* @param collection collection
* @param timestamp timestamp
* @return children of collection that have been updated since
* timestamp, or all children if timestamp is null
*/
public Set<ContentItem> loadChildren(CollectionItem collection, Date timestamp);
/**
* Removes all items from a given collection.
* @param collection The collection which contains all items which will be deleted.
*/
public void removeItemsFromCollection(CollectionItem collection);
}
| cosmo-core/src/main/java/org/unitedinternet/cosmo/dao/ContentDao.java | /*
* Copyright 2006 Open Source Applications Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.unitedinternet.cosmo.dao;
import java.util.Date;
import java.util.Set;
import org.unitedinternet.cosmo.dao.external.ExternalizableContent;
import org.unitedinternet.cosmo.model.CollectionItem;
import org.unitedinternet.cosmo.model.ContentItem;
import org.unitedinternet.cosmo.model.User;
/**
* Interface for DAO that provides base operations for content items.
*
* A content item is either a piece of content (or file) or a collection
* containing content items or other collection items.
*
*/
public interface ContentDao extends ItemDao {
/**
* Create a new collection.
*
* @param parent
* parent of collection.
* @param collection
* collection to create
* @return newly created collection
*/
public CollectionItem createCollection(CollectionItem parent,
CollectionItem collection);
/**
* Update collection and children. The set of children can contain
* new items, existing items, and item removals. An item removal
* is recognized by Item.isActive==false.
* @param collection collection to update
* @param children children to updated
* @return updated collection
*/
public CollectionItem updateCollection(CollectionItem collection,
Set<ContentItem> children);
/**
* Update an existing collection.
*
* @param collection
* collection to update
* @return updated collection
*/
public CollectionItem updateCollection(CollectionItem collection);
/**
* Create new content item. A content item represents a piece of content or
* file.
*
* @param parent
* parent collection of content. If null, content is assumed to
* live in the top-level user collection
* @param content
* content to create
* @return newly created content
*/
@ExternalizableContent
public ContentItem createContent(CollectionItem parent, ContentItem content);
/**
* creates a set of content items, used during events import from other calendar
*
* @param parent
* parent collection of content. If null, content is assumed to
* live in the top-level user collection
*
* @param contents
* the set of contents to create
*/
public void createBatchContent(CollectionItem parent, Set<ContentItem> contents);
/**
*
* @param contents Set<ContentItem>
*/
public void updateBatchContent(Set<ContentItem> contents);
/**
*
* @param parent CollectionItem
* @param contents Set<ContentItem>
*/
public void removeBatchContent(CollectionItem parent, Set<ContentItem> contents);
/**
* Create new content item and associate with multiple parent collections.
*
* @param parents
* parent collections of content.
* @param content
* content to create
* @return newly created content
*/
public ContentItem createContent(Set<CollectionItem> parents, ContentItem content);
/**
* Update an existing content item.
*
* @param content
* content item to update
* @return updated content item
*/
public ContentItem updateContent(ContentItem content);
/**
* Remove content item
*
* @param content
* content item to remove
*/
public void removeContent(ContentItem content);
/**
* Remove all content owned by a user
*
* @param user
* user to remove content for
*/
public void removeUserContent(User user);
/**
* Remove collection item
*
* @param collection
* collection item to remove
*/
public void removeCollection(CollectionItem collection);
/**
* Update timestamp on collection.
* @param collection collection to update
* @return updated collection
*/
public CollectionItem updateCollectionTimestamp(CollectionItem collection);
/**
* Load all children for collection that have been updated since a
* given timestamp. If no timestamp is specified, then return all
* children.
* @param collection collection
* @param timestamp timestamp
* @return children of collection that have been updated since
* timestamp, or all children if timestamp is null
*/
public Set<ContentItem> loadChildren(CollectionItem collection, Date timestamp);
/**
* Removes all items from a given collection.
* @param collection The collection which contains all items which will be deleted.
*/
public void removeItemsFromCollection(CollectionItem collection);
}
| 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
<ide> * content item to update
<ide> * @return updated content item
<ide> */
<add> @ExternalizableContent
<ide> public ContentItem updateContent(ContentItem content);
<ide>
<ide>
<ide> * @param content
<ide> * content item to remove
<ide> */
<add> @ExternalizableContent
<ide> public void removeContent(ContentItem content);
<ide>
<ide> /** |
|
Java | epl-1.0 | 9a8ca2930d934d7053e6e3f0b4d1e152ca104b20 | 0 | debrief/debrief,debrief/debrief,theanuradha/debrief,theanuradha/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief | package Debrief.ReaderWriter.NMEA;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import junit.framework.TestCase;
import Debrief.GUI.Frames.Application;
import Debrief.Wrappers.FixWrapper;
import Debrief.Wrappers.TrackWrapper;
import MWC.GUI.Layers;
import MWC.GUI.ToolParent;
import MWC.GUI.Properties.DebriefColors;
import MWC.GenericData.HiResDate;
import MWC.GenericData.WorldDistance;
import MWC.GenericData.WorldLocation;
import MWC.GenericData.WorldSpeed;
import MWC.GenericData.WorldVector;
import MWC.TacticalData.Fix;
public class ImportNMEA
{
/** prefix we use for ownship track that's extractd
* from NMEA data
*/
public static final String WECDIS_OWNSHIP_PREFIX = "WECDIS_OWNSHIP";
private enum MsgType
{
VESSEL_NAME, OS_POS, CONTACT, TIMESTAMP, UNKNOWN, AIS, OS_DEPTH,
OS_COURSE_SPEED, OS_COURSE, OS_SPEED;
}
private static class State
{
static SimpleDateFormat sdf;
private static Date dateFor(final String dateStr, final String timeStr)
{
if (sdf == null)
{
sdf = new SimpleDateFormat("yyyyMMdd,HHmmss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
}
Date res = null;
try
{
res = sdf.parse(dateStr + "," + timeStr);
}
catch (final ParseException e)
{
Application.logError2(ToolParent.ERROR, "AIS importer failed to parse:"
+ dateStr + ", " + timeStr, e);
}
return res;
}
public final Date date;
public final String name;
public final WorldLocation location;
public State(final String name, final String dateStr, final String timeStr,
final String tLat, final String tLong)
{
if (dateStr != null && timeStr != null)
{
date = dateFor(dateStr, timeStr);
}
else
{
date = null;
}
this.name = name;
location = locationFor(tLat, tLong);
}
private WorldLocation locationFor(final String tLat, final String tLong)
{
final double dLat = degsFor(tLat);
final double dLong = degsFor(tLong);
final WorldLocation loc = new WorldLocation(dLat, dLong, 0);
return loc;
}
}
public static class TestImportAIS extends TestCase
{
@SuppressWarnings("deprecation")
public void testDate()
{
final String dateStr = "20160720";
final String timeStr = "082807.345";
final Date date = State.dateFor(dateStr, timeStr);
assertNotNull("got date");
assertEquals("got right date/time", "20 Jul 2016 08:28:07 GMT", date
.toGMTString());
}
public void testDegs()
{
assertEquals("got it", 34.159, degsFor("3409.5794,N"), 0.001);
assertEquals("got it", -15.621, degsFor("01537.3128,W"), 0.001);
assertEquals("got it", -34.159, degsFor("3409.5794,S"), 0.001);
assertEquals("got it", 15.621, degsFor("01537.3128,E"), 0.001);
assertEquals("got it", -34.5, degsFor("3430.0,S"), 0.001);
assertEquals("got it", 15.25, degsFor("01515.0,E"), 0.001);
assertEquals("got it", 15.25, degsFor("01515.0,E"), 0.001);
assertEquals("got it", 2.693, degsFor("00241.5907,E"), 0.001);
assertEquals("got it", 36.2395, degsFor("3614.3708,N"), 0.001);
}
public void testFullImport() throws Exception
{
testImport("../org.mwc.cmap.combined.feature/root_installs/sample_data/other_formats/20160720.log");
}
public void testImport(final String testFile) throws Exception
{
final File testI = new File(testFile);
// only run the test if we have the log-file available
if (testI.exists())
{
assertTrue(testI.exists());
final InputStream is = new FileInputStream(testI);
final Layers tLayers = new Layers();
final ImportNMEA importer = new ImportNMEA(tLayers);
importer.importThis(testFile, is, 0l, 0l);
assertEquals("got tracks", 416, tLayers.size());
}
// TODO: also test that we use correct sample frequency - though that's prob best done on a
// smaller file.
}
@SuppressWarnings(
{"deprecation"})
public void testKnownImport()
{
final String test1 =
"$POSL,CONTACT,OC,DR,CHARLIE NAME,CHARLIE NAME,13.0,254.6,T,20160720,082807.345,FS,SFSP------^2a^2a^2a^2a^2a,0.0,M,3409.5794,N,01537.3128,W,0,,,*5D";
final String test2 = "$POSL,VNM,HMS NONSUCH*03";
final String test3 =
"$POSL,POS,GPS,1122.2222,N,00712.6666,W,0.00,,Center of Rotation,N,,,,,*41";
final String test4 = "$POSL,DZA,20160720,000000.859,0007328229*42";
final String test5 =
"$POSL,CONTACT,OC,DELETE,AIS 5,AIS 5,1.0,125.3,T,20160720,010059.897,FS,SFSP------^2a^2a^2a^2a^2a,0.0,M,1212.1234,N,12312.1234,W,0,,,*6E";
final String test6 =
"$POSL,POS2,GPS,4422.1122,N,00812.1111,W,0.00,,GPS Antenna,N,,,,,*5C";
final String test7 =
"$POSL,AIS,564166000,3606.3667,N,00522.3698,W,0,7.8,327.9,0,330.0,AIS1,0,0*06";
final String test8 = "$POSL,PDS,9.2,M*03";
final String test9 = "$POSL,VEL,GPS,276.3,4.6,,,*35";
final String test10_drSpd = "$POSL,VEL,SPL,,,4.1,0.0,4.0*12";
final String test11_drCrse = "$POSL,HDG,111.2,-04.1*7F";
assertEquals("Tgt POS", MsgType.CONTACT, parseType(test1));
assertEquals("Vessel name", MsgType.VESSEL_NAME, parseType(test2));
assertEquals("OS POS", MsgType.OS_POS, parseType(test3));
assertEquals("Timestamp", MsgType.TIMESTAMP, parseType(test4));
// ok, let's try the ownship name
assertEquals("got name", "HMS NONSUCH", parseMyName(test2));
// and the AIS track fields
final State aisState1 = parseContact(test1);
assertNotNull("found state", aisState1);
assertEquals("got name", "CHARLIE NAME", aisState1.name);
assertNotNull("found date", aisState1.date);
assertEquals("got date", "20 Jul 2016 08:28:07 GMT", aisState1.date
.toGMTString());
assertNotNull("found location", aisState1.location);
assertEquals("got lat", 34.1596, aisState1.location.getLat(), 0.001);
assertEquals("got long", -15.622, aisState1.location.getLong(), 0.001);
// and the AIS track fields
final State aisState = parseContact(test5);
assertNotNull("found state", aisState);
assertEquals("got name", "AIS 5", aisState.name);
// and the ownship track fields
final State oState1 = parseOwnship(test3, "test_name");
assertNotNull("found state", oState1);
assertEquals("got name", "test_name_POS_GPS", oState1.name);
assertNull("found date", oState1.date);
assertNotNull("found location", oState1.location);
assertEquals("got lat", 11.370, oState1.location.getLat(), 0.001);
assertEquals("got long", -7.211, oState1.location.getLong(), 0.001);
// and the ownship track fields
final State oState2 = parseOwnship(test6, "test_name2");
assertNotNull("found state", oState2);
assertEquals("got name", "test_name2_POS2_GPS", oState2.name);
assertNull("found date", oState2.date);
assertNotNull("found location", oState2.location);
assertEquals("got lat", 44.368, oState2.location.getLat(), 0.001);
assertEquals("got long", -8.201, oState2.location.getLong(), 0.001);
// and the ownship track fields
final State oState3 = parseAIS(test7);
assertNotNull("found state", oState3);
assertEquals("got name", "564166000", oState3.name);
assertNull("found date", oState3.date);
assertNotNull("found location", oState3.location);
// ok, let's try the ownship name
assertEquals("got time", "20 Jul 2016 00:00:00 GMT", parseMyDate(test4)
.toGMTString());
assertEquals("got depth", 9.2d, parseMyDepth(test8), 0.001);
assertEquals("got course", 276.3d, parseMyCourse(coursePatternGPS, test9), 0.001);
assertEquals("got speed", 4.6d, parseMySpeed(speedPatternGPS, test9), 0.001);
// and the DR equivalents
assertEquals("got speed", 4.1d, parseMySpeed(speedPatternLOG, test10_drSpd), 0.001);
assertEquals("got course", 111.2d, parseMyCourse(coursePatternHDG, test11_drCrse), 0.001);
}
}
/**
* $POSL,AIS,564166000,1212.1234,N,12312.1234,W,0,7.8,327.9,0,330.0,AIS1,0,0*06
*/
final private static Pattern aisPattern =
Pattern
.compile("\\$POSL,AIS,(?<MMSI>\\d+?),"
+ "(?<LAT>\\d{4}.\\d{4},(N|S)),(?<LONG>\\d{5}.\\d{4},(E|W)),.*,AIS1,.*");
/**
* $POSL,CONTACT,OC,DELETE,AIS 5,AIS
* 5,1.0,125.3,T,20160720,010059.897,FS,SFSP------^2a^2a^2a^2a^2a
* ,0.0,M,1212.1313,N,12312.1234,W,0,,,*6E"
*/
final private static Pattern contactPattern = Pattern
.compile("\\$POSL,CONTACT,OC,\\w*,(?<NAME>.*?),.*"
+ ",(?<DATE>\\d{8}),(?<TIME>\\d{6}.\\d{3}),.*,"
+ "(?<LAT>\\d{4}.\\d{4},(N|S)),(?<LONG>\\d{5}.\\d{4},(E|W)),.*");
/**
* $POSL,VEL,GPS,276.3,4.6,,,*35
*/
final private static Pattern coursePatternGPS = Pattern
.compile("\\$POSL,VEL,GPS,(?<COURSE>\\d+.\\d+),.*");
/**
* $POSL,HDG,111.0,-04.1*7F
*/
final private static Pattern coursePatternHDG = Pattern
.compile("\\$POSL,HDG,(?<COURSE>\\d+.\\d+),.*");
/**
* $POSL,DZA,20160720,000000.859,0007328229*42
*/
final private static Pattern datePattern = Pattern
.compile("\\$POSL,DZA,(?<DATE>\\d{8}),(?<TIME>\\d{6}.\\d{3}),.*");
/**
* $POSL,PDS,9.2,M*0
*/
final private static Pattern depthPattern = Pattern
.compile("\\$POSL,PDS,(?<DEPTH>\\d+.\\d+),.*");
/**
* "$POSL,VNM,HMS NONSUCH*03";
*/
final private static Pattern namePattern = Pattern
.compile("\\$POSL,VNM,(?<NAME>.*)\\*\\d\\d");
/**
* $POSL,VEL,GPS,276.3,4.6,,,*35
*/
final private static Pattern speedPatternGPS = Pattern
.compile("\\$POSL,VEL,GPS,.*,(?<SPEED>\\d+.\\d+),.*");
/**
* $POSL,VEL,SPL,,,4.0,0.0,4.0*12
*/
final private static Pattern speedPatternLOG = Pattern
.compile("\\$POSL,VEL,SPL,,,(?<SPEED>\\d+.\\d+),.*");
/**
* "$POSL,POS,GPS,1122.2222,N,12312.1234,W,0.00,,Center of Rotation,N,,,,,*41";
*/
final private static Pattern osPattern =
Pattern
.compile("\\$POSL,(?<SOURCE>\\w?POS\\d?,.*),(?<LAT>\\d{4}.\\d{4},(N|S)),(?<LONG>\\d{5}.\\d{4},(E|W)),.*");
final private static Pattern typePattern = Pattern
.compile("\\$POSL,(?<TYPE1>\\w*),(?<TYPE2>\\w*),*.*");
private static double degsFor(final String text)
{
final int dec = text.indexOf(".");
final String degs = text.substring(0, dec - 2);
final String mins = text.substring(dec - 2, text.length() - 2);
final String hemi = text.substring(text.length() - 1);
double res = Double.valueOf(degs) + Double.valueOf(mins) / 60d;
if (hemi.equals("S") | hemi.equals("W"))
{
// switch the direction
res = -res;
}
return res;
}
private static FixWrapper fixFor(final Date date, final State state,
final FixWrapper lastFix, final Double myDepth)
{
// set the depth, if we have it
if (myDepth != null)
{
state.location.setDepth(myDepth);
}
final Fix theF = new Fix(new HiResDate(date), state.location, 0d, 0d);
final FixWrapper fw = new FixWrapper(theF);
if (lastFix != null)
{
// have a go at the course & speed
final WorldVector diff = state.location.subtract(lastFix.getLocation());
// first the course
fw.getFix().setCourse(diff.getBearing());
final double m_travelled =
new WorldDistance(diff.getRange(), WorldDistance.DEGS)
.getValueIn(WorldDistance.METRES);
final double timeDiffMillis =
(date.getTime() - lastFix.getDTG().getDate().getTime());
final double speed_m_s = m_travelled / (timeDiffMillis / 1000d);
final WorldSpeed theSpeed = new WorldSpeed(speed_m_s, WorldSpeed.M_sec);
// and the speed
final double speed_yps = theSpeed.getValueIn(WorldSpeed.ft_sec) / 3d;
fw.getFix().setSpeed(speed_yps);
}
return fw;
}
static private State parseAIS(final String nmea_sentence)
{
final Matcher m = aisPattern.matcher(nmea_sentence);
final State res;
if (m.matches())
{
final String name = m.group("MMSI");
final String tLat = m.group("LAT");
final String tLong = m.group("LONG");
res = new State(name, null, null, tLat, tLong);
}
else
{
res = null;
}
return res;
}
static private State parseContact(final String nmea_sentence)
{
final Matcher m = contactPattern.matcher(nmea_sentence);
final State res;
if (m.matches())
{
final String name = m.group("NAME");
final String dateStr = m.group("DATE");
final String timeStr = m.group("TIME");
final String tLat = m.group("LAT");
final String tLong = m.group("LONG");
res = new State(name, dateStr, timeStr, tLat, tLong);
}
else
{
res = null;
}
return res;
}
static private double parseMyCourse(final Pattern pattern,
final String nmea_sentence)
{
final Matcher m = pattern.matcher(nmea_sentence);
final double res;
if (m.matches())
{
res = Double.parseDouble(m.group("COURSE"));
}
else
{
res = 0d;
}
return res;
}
private static Date parseMyDate(final String nmea_sentence)
{
final Matcher m = datePattern.matcher(nmea_sentence);
final Date res;
if (m.matches())
{
final String dateStr = m.group("DATE");
final String timeStr = m.group("TIME");
res = State.dateFor(dateStr, timeStr);
}
else
{
res = null;
}
return res;
}
static private double parseMyDepth(final String nmea_sentence)
{
final Matcher m = depthPattern.matcher(nmea_sentence);
final double res;
if (m.matches())
{
res = Double.parseDouble(m.group("DEPTH"));
}
else
{
res = 0d;
}
return res;
}
static private String parseMyName(final String nmea_sentence)
{
final Matcher m = namePattern.matcher(nmea_sentence);
final String res;
if (m.matches())
{
res = m.group("NAME");
}
else
{
res = null;
}
return res;
}
static private double parseMySpeed(final Pattern pattern,
final String nmea_sentence)
{
final Matcher m = pattern.matcher(nmea_sentence);
final double res;
if (m.matches())
{
res = Double.parseDouble(m.group("SPEED"));
}
else
{
res = 0d;
}
return res;
}
static private State parseOwnship(final String nmea_sentence,
final String myName)
{
final Matcher m = osPattern.matcher(nmea_sentence);
final State res;
if (m.matches())
{
final String tLat = m.group("LAT");
final String tLong = m.group("LONG");
final String source = m.group("SOURCE").replace(",", "_");
res = new State(myName + "_" + source, null, null, tLat, tLong);
}
else
{
res = null;
}
return res;
}
static private MsgType parseType(final String nmea_sentence)
{
final Matcher m = typePattern.matcher(nmea_sentence);
final MsgType res;
if (m.matches())
{
final String str = m.group("TYPE1");
final String str2 = m.group("TYPE2");
if (str.equals("VNM"))
res = MsgType.VESSEL_NAME;
else if (str.equals("POS") && str2.equals("GPS"))
res = MsgType.OS_POS;
else if (str.contains("VEL") && str2.equals("GPS"))
res = MsgType.OS_COURSE_SPEED;
else if (str.contains("VEL") && str2.equals("SPL"))
res = MsgType.OS_SPEED;
else if (str.contains("HDG"))
res = MsgType.OS_COURSE;
else if (str.equals("CONTACT"))
res = MsgType.CONTACT;
else if (str.equals("AIS"))
res = MsgType.AIS;
else if (str.equals("DZA"))
res = MsgType.TIMESTAMP;
else if (str.equals("PDS"))
res = MsgType.OS_DEPTH;
else
res = MsgType.UNKNOWN;
}
else
{
res = MsgType.UNKNOWN;
}
return res;
}
/**
* where we write our data
*
*/
private final Layers _layers;
/**
* the set of tracks we build up, to reduce screen updates
*
*/
HashMap<String, ArrayList<FixWrapper>> tracks =
new HashMap<String, ArrayList<FixWrapper>>();
/**
* the set of tracks we build up, to reduce screen updates
*
*/
HashMap<String, Color> colors = new HashMap<String, Color>();
public ImportNMEA(final Layers target)
{
super();
_layers = target;
}
public void importThis(final String fName, final InputStream is,
final long osFreq, final long aisFreq) throws Exception
{
String myName = null;
double myDepth = 0d;
Date date = null;
final boolean importOS = !(osFreq == Long.MAX_VALUE);
final boolean importAIS = !(aisFreq == Long.MAX_VALUE);
final boolean importContacts = false;
// reset our list of tracks
tracks.clear();
colors.clear();
// remember the first ownship location, for the DR track
WorldLocation origin = null;
// ok, loop through the lines
final BufferedReader br = new BufferedReader(new InputStreamReader(is));
String nmea_sentence;
// flag for if we wish to obtain DR data from GPS message, or from organic sensors
final boolean DRfromGPS = false;
// remember the last DR course read in, since we capture course and speed
// from different messages
Double drCourse = null;
int ctr = 0;
// loop through the lines
while ((nmea_sentence = br.readLine()) != null)
{
final MsgType msg = parseType(nmea_sentence);
ctr++;
if (ctr % 10000 == 0)
{
System.out.print(".");
}
if (ctr % 50000 == 0)
{
System.out.println("");
System.out.print(ctr);
}
switch (msg)
{
case TIMESTAMP:
// ok, extract the rest of the body
date = parseMyDate(nmea_sentence);
// and remember the name
break;
case VESSEL_NAME:
// ok, extract the rest of the body
myName = parseMyName(nmea_sentence);
break;
case OS_DEPTH:
if (importOS)
{
// ok, extract the rest of the body
myDepth = parseMyDepth(nmea_sentence);
}
break;
case OS_COURSE:
if (importOS)
{
// ok, extract the rest of the body
drCourse = parseMyCourse(coursePatternHDG, nmea_sentence);
}
break;
case OS_SPEED:
if (importOS)
{
// ok, extract the rest of the body
double drSpeedDegs = parseMySpeed(speedPatternLOG, nmea_sentence);
// are we taking DR from GPS?
if(DRfromGPS)
{
// ok, skip creating the DR - do it in the other message
}
else
{
// do we know our origin?
if (origin != null)
{
// ok, grow the DR track
storeDRFix(origin, drCourse, drSpeedDegs, date, myName, myDepth,
DebriefColors.BLUE);
}
}
}
break;
case OS_COURSE_SPEED:
if (importOS)
{
// ok, extract the rest of the body
final double myCourseDegs = parseMyCourse(coursePatternGPS, nmea_sentence);
final double mySpeedKts = parseMySpeed(speedPatternGPS, nmea_sentence);
// are we taking DR from GPS?
if (DRfromGPS)
{
// do we know our origin?
if (origin != null)
{
// ok, grow the DR track
storeDRFix(origin, myCourseDegs, mySpeedKts, date, myName,
myDepth, DebriefColors.BLUE);
}
}
else
{
// ok, skip creating the DR using GPS deltas - do it from the organic sensors
}
}
break;
case OS_POS:
if (importOS)
{
// note: if we don't know ownship name yet,
// let's make one up
if (myName == null)
{
myName = WECDIS_OWNSHIP_PREFIX;
}
// extract the location
final State state = parseOwnship(nmea_sentence, myName);
// do we need an origin?
if (origin == null)
{
origin = new WorldLocation(state.location);
}
// do we know our name yet?
if (state != null && date != null)
{
// now store the ownship location
storeLocation(date, state, osFreq, DebriefColors.PURPLE, myDepth);
}
}
break;
case CONTACT:
if (importContacts)
{
// extract the location
final State hisState = parseContact(nmea_sentence);
if (hisState == null)
{
System.out.println("INVALID CONTACT");
}
else
{
// now store the ownship location
storeLocation(hisState.date, hisState, aisFreq,
DebriefColors.GREEN, null);
}
}
break;
case AIS:
if (importAIS)
{
// extract the location
final State hisState = parseAIS(nmea_sentence);
if (hisState == null)
{
// ok, it was prob the "other" AIS receiver
}
else
{
if (date != null)
{
// now store the ownship location
storeLocation(date, hisState, aisFreq, DebriefColors.YELLOW, null);
}
}
}
break;
case UNKNOWN:
break;
}
}
for (final String trackName : tracks.keySet())
{
final ArrayList<FixWrapper> track = tracks.get(trackName);
// ok, build the track
final TrackWrapper tr = new TrackWrapper();
tr.setName(trackName);
tr.setColor(colors.get(trackName));
System.out.println("storing " + track.size() + " for " + trackName);
// SPECIAL HANDLING - we filter DR tracks at this stage
Long lastTime = null;
final boolean resample = trackName.endsWith("-DR");
for (final FixWrapper fix : track)
{
// ok, also do the label
fix.resetName();
final long thisTime = fix.getDateTimeGroup().getDate().getTime();
long delta = Long.MAX_VALUE;
if (resample && lastTime != null)
{
delta = thisTime - lastTime;
}
if ((!resample) || lastTime == null || delta >= osFreq)
{
tr.add(fix);
lastTime = thisTime;
}
}
_layers.addThisLayer(tr);
}
}
private void storeDRFix(final WorldLocation origin,
final double myCourseDegs, final double mySpeedKts, final Date date,
final String myName, final double myDepth, final Color color)
{
final String trackName = myName + "-DR";
// find the track
ArrayList<FixWrapper> track = tracks.get(trackName);
final FixWrapper newFix;
// do we have any?
if (track == null)
{
track = new ArrayList<FixWrapper>();
tracks.put(trackName, track);
colors.put(trackName, color);
// nope, create the origin
final Fix fix =
new Fix(new HiResDate(date.getTime()), origin, Math
.toRadians(myCourseDegs), MWC.Algorithms.Conversions
.Kts2Yps(mySpeedKts));
newFix = new FixWrapper(fix);
}
else
{
// ok, get the last point
final FixWrapper lastFix = track.get(track.size() - 1);
// now calculate the new point
final long timeDelta =
date.getTime() - lastFix.getDateTimeGroup().getDate().getTime();
// calculate the distance travelled
final double m_s =
new WorldSpeed(mySpeedKts, WorldSpeed.Kts)
.getValueIn(WorldSpeed.M_sec);
final double distanceM = m_s * timeDelta / 1000d;
final double distanceDegs =
new WorldDistance(distanceM, WorldDistance.METRES)
.getValueIn(WorldDistance.DEGS);
final WorldVector offset =
new WorldVector(Math.toRadians(myCourseDegs), distanceDegs, 0);
final WorldLocation newLoc = lastFix.getLocation().add(offset);
// store the depth
newLoc.setDepth(myDepth);
final Fix fix =
new Fix(new HiResDate(date.getTime()), newLoc, Math
.toRadians(myCourseDegs), MWC.Algorithms.Conversions
.Kts2Yps(mySpeedKts));
newFix = new FixWrapper(fix);
// no, don't set the color, we want the fix to take
// the color of the parent track
// newFix.setColor(color);
}
track.add(newFix);
}
private void storeLocation(final Date date, final State state,
final long freq, final Color color, final Double myDepth)
{
final String myName = state.name;
ArrayList<FixWrapper> track = tracks.get(myName);
final boolean addIt;
final FixWrapper lastFix;
if (track == null)
{
track = new ArrayList<FixWrapper>();
tracks.put(myName, track);
colors.put(myName, color);
// ok. we're certainly adding this one
addIt = true;
lastFix = null;
}
else
{
// find the time of the last fix stored
lastFix = track.get(track.size() - 1);
final long lastTime = lastFix.getDateTimeGroup().getDate().getTime();
// have we passed the indicated frequency?
if (date.getTime() >= lastTime + freq)
{
addIt = true;
}
else
{
addIt = false;
}
}
if (addIt)
{
// create a fix from the state
final FixWrapper theF = fixFor(date, state, lastFix, myDepth);
// and store it
track.add(theF);
}
}
}
| org.mwc.debrief.legacy/src/Debrief/ReaderWriter/NMEA/ImportNMEA.java | package Debrief.ReaderWriter.NMEA;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import junit.framework.TestCase;
import Debrief.GUI.Frames.Application;
import Debrief.Wrappers.FixWrapper;
import Debrief.Wrappers.TrackWrapper;
import MWC.GUI.Layers;
import MWC.GUI.ToolParent;
import MWC.GUI.Properties.DebriefColors;
import MWC.GenericData.HiResDate;
import MWC.GenericData.WorldDistance;
import MWC.GenericData.WorldLocation;
import MWC.GenericData.WorldSpeed;
import MWC.GenericData.WorldVector;
import MWC.TacticalData.Fix;
public class ImportNMEA
{
/** prefix we use for ownship track that's extractd
* from NMEA data
*/
public static final String WECDIS_OWNSHIP_PREFIX = "WECDIS_OWNSHIP";
private enum MsgType
{
VESSEL_NAME, OS_POS, CONTACT, TIMESTAMP, UNKNOWN, AIS, OS_DEPTH,
OS_COURSE_SPEED;
}
private static class State
{
static SimpleDateFormat sdf;
private static Date dateFor(final String dateStr, final String timeStr)
{
if (sdf == null)
{
sdf = new SimpleDateFormat("yyyyMMdd,HHmmss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
}
Date res = null;
try
{
res = sdf.parse(dateStr + "," + timeStr);
}
catch (final ParseException e)
{
Application.logError2(ToolParent.ERROR, "AIS importer failed to parse:"
+ dateStr + ", " + timeStr, e);
}
return res;
}
public final Date date;
public final String name;
public final WorldLocation location;
public State(final String name, final String dateStr, final String timeStr,
final String tLat, final String tLong)
{
if (dateStr != null && timeStr != null)
{
date = dateFor(dateStr, timeStr);
}
else
{
date = null;
}
this.name = name;
location = locationFor(tLat, tLong);
}
private WorldLocation locationFor(final String tLat, final String tLong)
{
final double dLat = degsFor(tLat);
final double dLong = degsFor(tLong);
final WorldLocation loc = new WorldLocation(dLat, dLong, 0);
return loc;
}
}
public static class TestImportAIS extends TestCase
{
@SuppressWarnings("deprecation")
public void testDate()
{
final String dateStr = "20160720";
final String timeStr = "082807.345";
final Date date = State.dateFor(dateStr, timeStr);
assertNotNull("got date");
assertEquals("got right date/time", "20 Jul 2016 08:28:07 GMT", date
.toGMTString());
}
public void testDegs()
{
assertEquals("got it", 34.159, degsFor("3409.5794,N"), 0.001);
assertEquals("got it", -15.621, degsFor("01537.3128,W"), 0.001);
assertEquals("got it", -34.159, degsFor("3409.5794,S"), 0.001);
assertEquals("got it", 15.621, degsFor("01537.3128,E"), 0.001);
assertEquals("got it", -34.5, degsFor("3430.0,S"), 0.001);
assertEquals("got it", 15.25, degsFor("01515.0,E"), 0.001);
assertEquals("got it", 15.25, degsFor("01515.0,E"), 0.001);
assertEquals("got it", 2.693, degsFor("00241.5907,E"), 0.001);
assertEquals("got it", 36.2395, degsFor("3614.3708,N"), 0.001);
}
public void testFullImport() throws Exception
{
testImport("../org.mwc.cmap.combined.feature/root_installs/sample_data/other_formats/20160720.log");
}
public void testImport(final String testFile) throws Exception
{
final File testI = new File(testFile);
// only run the test if we have the log-file available
if (testI.exists())
{
assertTrue(testI.exists());
final InputStream is = new FileInputStream(testI);
final Layers tLayers = new Layers();
final ImportNMEA importer = new ImportNMEA(tLayers);
importer.importThis(testFile, is, 0l, 0l);
assertEquals("got tracks", 416, tLayers.size());
}
// TODO: also test that we use correct sample frequency - though that's prob best done on a
// smaller file.
}
@SuppressWarnings(
{"deprecation"})
public void testKnownImport()
{
final String test1 =
"$POSL,CONTACT,OC,DR,CHARLIE NAME,CHARLIE NAME,13.0,254.6,T,20160720,082807.345,FS,SFSP------^2a^2a^2a^2a^2a,0.0,M,3409.5794,N,01537.3128,W,0,,,*5D";
final String test2 = "$POSL,VNM,HMS NONSUCH*03";
final String test3 =
"$POSL,POS,GPS,1122.2222,N,00712.6666,W,0.00,,Center of Rotation,N,,,,,*41";
final String test4 = "$POSL,DZA,20160720,000000.859,0007328229*42";
final String test5 =
"$POSL,CONTACT,OC,DELETE,AIS 5,AIS 5,1.0,125.3,T,20160720,010059.897,FS,SFSP------^2a^2a^2a^2a^2a,0.0,M,1212.1234,N,12312.1234,W,0,,,*6E";
final String test6 =
"$POSL,POS2,GPS,4422.1122,N,00812.1111,W,0.00,,GPS Antenna,N,,,,,*5C";
final String test7 =
"$POSL,AIS,564166000,3606.3667,N,00522.3698,W,0,7.8,327.9,0,330.0,AIS1,0,0*06";
final String test8 = "$POSL,PDS,9.2,M*03";
final String test9 = "$POSL,VEL,GPS,276.3,4.6,,,*35";
assertEquals("Tgt POS", MsgType.CONTACT, parseType(test1));
assertEquals("Vessel name", MsgType.VESSEL_NAME, parseType(test2));
assertEquals("OS POS", MsgType.OS_POS, parseType(test3));
assertEquals("Timestamp", MsgType.TIMESTAMP, parseType(test4));
// ok, let's try the ownship name
assertEquals("got name", "HMS NONSUCH", parseMyName(test2));
// and the AIS track fields
final State aisState1 = parseContact(test1);
assertNotNull("found state", aisState1);
assertEquals("got name", "CHARLIE NAME", aisState1.name);
assertNotNull("found date", aisState1.date);
assertEquals("got date", "20 Jul 2016 08:28:07 GMT", aisState1.date
.toGMTString());
assertNotNull("found location", aisState1.location);
assertEquals("got lat", 34.1596, aisState1.location.getLat(), 0.001);
assertEquals("got long", -15.622, aisState1.location.getLong(), 0.001);
// and the AIS track fields
final State aisState = parseContact(test5);
assertNotNull("found state", aisState);
assertEquals("got name", "AIS 5", aisState.name);
// and the ownship track fields
final State oState1 = parseOwnship(test3, "test_name");
assertNotNull("found state", oState1);
assertEquals("got name", "test_name_POS_GPS", oState1.name);
assertNull("found date", oState1.date);
assertNotNull("found location", oState1.location);
assertEquals("got lat", 11.370, oState1.location.getLat(), 0.001);
assertEquals("got long", -7.211, oState1.location.getLong(), 0.001);
// and the ownship track fields
final State oState2 = parseOwnship(test6, "test_name2");
assertNotNull("found state", oState2);
assertEquals("got name", "test_name2_POS2_GPS", oState2.name);
assertNull("found date", oState2.date);
assertNotNull("found location", oState2.location);
assertEquals("got lat", 44.368, oState2.location.getLat(), 0.001);
assertEquals("got long", -8.201, oState2.location.getLong(), 0.001);
// and the ownship track fields
final State oState3 = parseAIS(test7);
assertNotNull("found state", oState3);
assertEquals("got name", "564166000", oState3.name);
assertNull("found date", oState3.date);
assertNotNull("found location", oState3.location);
// ok, let's try the ownship name
assertEquals("got time", "20 Jul 2016 00:00:00 GMT", parseMyDate(test4)
.toGMTString());
assertEquals("got depth", 9.2d, parseMyDepth(test8), 0.001);
assertEquals("got course", 276.3d, parseMyCourse(test9), 0.001);
assertEquals("got speed", 4.6d, parseMySpeed(test9), 0.001);
}
}
/**
* $POSL,AIS,564166000,1212.1234,N,12312.1234,W,0,7.8,327.9,0,330.0,AIS1,0,0*06
*/
final private static Pattern aisPattern =
Pattern
.compile("\\$POSL,AIS,(?<MMSI>\\d+?),"
+ "(?<LAT>\\d{4}.\\d{4},(N|S)),(?<LONG>\\d{5}.\\d{4},(E|W)),.*,AIS1,.*");
/**
* $POSL,CONTACT,OC,DELETE,AIS 5,AIS
* 5,1.0,125.3,T,20160720,010059.897,FS,SFSP------^2a^2a^2a^2a^2a
* ,0.0,M,1212.1313,N,12312.1234,W,0,,,*6E"
*/
final private static Pattern contactPattern = Pattern
.compile("\\$POSL,CONTACT,OC,\\w*,(?<NAME>.*?),.*"
+ ",(?<DATE>\\d{8}),(?<TIME>\\d{6}.\\d{3}),.*,"
+ "(?<LAT>\\d{4}.\\d{4},(N|S)),(?<LONG>\\d{5}.\\d{4},(E|W)),.*");
/**
* $POSL,VEL,GPS,276.3,4.6,,,*35
*/
final private static Pattern coursePattern = Pattern
.compile("\\$POSL,VEL,GPS,(?<COURSE>\\d+.\\d+),.*");
/**
* $POSL,DZA,20160720,000000.859,0007328229*42
*/
final private static Pattern datePattern = Pattern
.compile("\\$POSL,DZA,(?<DATE>\\d{8}),(?<TIME>\\d{6}.\\d{3}),.*");
/**
* $POSL,PDS,9.2,M*0
*/
final private static Pattern depthPattern = Pattern
.compile("\\$POSL,PDS,(?<DEPTH>\\d+.\\d+),.*");
/**
* "$POSL,VNM,HMS NONSUCH*03";
*/
final private static Pattern namePattern = Pattern
.compile("\\$POSL,VNM,(?<NAME>.*)\\*\\d\\d");
/**
* $POSL,VEL,GPS,276.3,4.6,,,*35
*/
final private static Pattern speedPattern = Pattern
.compile("\\$POSL,VEL,GPS,.*,(?<SPEED>\\d+.\\d+),.*");
/**
* "$POSL,POS,GPS,1122.2222,N,12312.1234,W,0.00,,Center of Rotation,N,,,,,*41";
*/
final private static Pattern osPattern =
Pattern
.compile("\\$POSL,(?<SOURCE>\\w?POS\\d?,.*),(?<LAT>\\d{4}.\\d{4},(N|S)),(?<LONG>\\d{5}.\\d{4},(E|W)),.*");
final private static Pattern typePattern = Pattern
.compile("\\$POSL,(?<TYPE1>\\w*),(?<TYPE2>\\w*),*.*");
private static double degsFor(final String text)
{
final int dec = text.indexOf(".");
final String degs = text.substring(0, dec - 2);
final String mins = text.substring(dec - 2, text.length() - 2);
final String hemi = text.substring(text.length() - 1);
double res = Double.valueOf(degs) + Double.valueOf(mins) / 60d;
if (hemi.equals("S") | hemi.equals("W"))
{
// switch the direction
res = -res;
}
return res;
}
private static FixWrapper fixFor(final Date date, final State state,
final FixWrapper lastFix, final Double myDepth)
{
// set the depth, if we have it
if (myDepth != null)
{
state.location.setDepth(myDepth);
}
final Fix theF = new Fix(new HiResDate(date), state.location, 0d, 0d);
final FixWrapper fw = new FixWrapper(theF);
if (lastFix != null)
{
// have a go at the course & speed
final WorldVector diff = state.location.subtract(lastFix.getLocation());
// first the course
fw.getFix().setCourse(diff.getBearing());
final double m_travelled =
new WorldDistance(diff.getRange(), WorldDistance.DEGS)
.getValueIn(WorldDistance.METRES);
final double timeDiffMillis =
(date.getTime() - lastFix.getDTG().getDate().getTime());
final double speed_m_s = m_travelled / (timeDiffMillis / 1000d);
final WorldSpeed theSpeed = new WorldSpeed(speed_m_s, WorldSpeed.M_sec);
// and the speed
final double speed_yps = theSpeed.getValueIn(WorldSpeed.ft_sec) / 3d;
fw.getFix().setSpeed(speed_yps);
}
return fw;
}
static private State parseAIS(final String nmea_sentence)
{
final Matcher m = aisPattern.matcher(nmea_sentence);
final State res;
if (m.matches())
{
final String name = m.group("MMSI");
final String tLat = m.group("LAT");
final String tLong = m.group("LONG");
res = new State(name, null, null, tLat, tLong);
}
else
{
res = null;
}
return res;
}
static private State parseContact(final String nmea_sentence)
{
final Matcher m = contactPattern.matcher(nmea_sentence);
final State res;
if (m.matches())
{
final String name = m.group("NAME");
final String dateStr = m.group("DATE");
final String timeStr = m.group("TIME");
final String tLat = m.group("LAT");
final String tLong = m.group("LONG");
res = new State(name, dateStr, timeStr, tLat, tLong);
}
else
{
res = null;
}
return res;
}
static private double parseMyCourse(final String nmea_sentence)
{
final Matcher m = coursePattern.matcher(nmea_sentence);
final double res;
if (m.matches())
{
res = Double.parseDouble(m.group("COURSE"));
}
else
{
res = 0d;
}
return res;
}
private static Date parseMyDate(final String nmea_sentence)
{
final Matcher m = datePattern.matcher(nmea_sentence);
final Date res;
if (m.matches())
{
final String dateStr = m.group("DATE");
final String timeStr = m.group("TIME");
res = State.dateFor(dateStr, timeStr);
}
else
{
res = null;
}
return res;
}
static private double parseMyDepth(final String nmea_sentence)
{
final Matcher m = depthPattern.matcher(nmea_sentence);
final double res;
if (m.matches())
{
res = Double.parseDouble(m.group("DEPTH"));
}
else
{
res = 0d;
}
return res;
}
static private String parseMyName(final String nmea_sentence)
{
final Matcher m = namePattern.matcher(nmea_sentence);
final String res;
if (m.matches())
{
res = m.group("NAME");
}
else
{
res = null;
}
return res;
}
static private double parseMySpeed(final String nmea_sentence)
{
final Matcher m = speedPattern.matcher(nmea_sentence);
final double res;
if (m.matches())
{
res = Double.parseDouble(m.group("SPEED"));
}
else
{
res = 0d;
}
return res;
}
static private State parseOwnship(final String nmea_sentence,
final String myName)
{
final Matcher m = osPattern.matcher(nmea_sentence);
final State res;
if (m.matches())
{
final String tLat = m.group("LAT");
final String tLong = m.group("LONG");
final String source = m.group("SOURCE").replace(",", "_");
res = new State(myName + "_" + source, null, null, tLat, tLong);
}
else
{
res = null;
}
return res;
}
static private MsgType parseType(final String nmea_sentence)
{
final Matcher m = typePattern.matcher(nmea_sentence);
final MsgType res;
if (m.matches())
{
final String str = m.group("TYPE1");
final String str2 = m.group("TYPE2");
if (str.equals("VNM"))
res = MsgType.VESSEL_NAME;
else if (str.equals("POS") && str2.equals("GPS"))
res = MsgType.OS_POS;
else if (str.contains("VEL") && str2.equals("GPS"))
res = MsgType.OS_COURSE_SPEED;
else if (str.equals("CONTACT"))
res = MsgType.CONTACT;
else if (str.equals("AIS"))
res = MsgType.AIS;
else if (str.equals("DZA"))
res = MsgType.TIMESTAMP;
else if (str.equals("PDS"))
res = MsgType.OS_DEPTH;
else
res = MsgType.UNKNOWN;
}
else
{
res = MsgType.UNKNOWN;
}
return res;
}
/**
* where we write our data
*
*/
private final Layers _layers;
/**
* the set of tracks we build up, to reduce screen updates
*
*/
HashMap<String, ArrayList<FixWrapper>> tracks =
new HashMap<String, ArrayList<FixWrapper>>();
/**
* the set of tracks we build up, to reduce screen updates
*
*/
HashMap<String, Color> colors = new HashMap<String, Color>();
public ImportNMEA(final Layers target)
{
super();
_layers = target;
}
public void importThis(final String fName, final InputStream is,
final long osFreq, final long aisFreq) throws Exception
{
String myName = null;
double myDepth = 0d;
Date date = null;
final boolean importOS = !(osFreq == Long.MAX_VALUE);
final boolean importAIS = !(aisFreq == Long.MAX_VALUE);
final boolean importContacts = false;
// reset our list of tracks
tracks.clear();
colors.clear();
// remember the first ownship location, for the DR track
WorldLocation origin = null;
// ok, loop through the lines
final BufferedReader br = new BufferedReader(new InputStreamReader(is));
String nmea_sentence;
int ctr = 0;
// loop through the lines
while ((nmea_sentence = br.readLine()) != null)
{
final MsgType msg = parseType(nmea_sentence);
ctr++;
if (ctr % 10000 == 0)
{
System.out.print(".");
}
if (ctr % 50000 == 0)
{
System.out.println("");
System.out.print(ctr);
}
switch (msg)
{
case TIMESTAMP:
// ok, extract the rest of the body
date = parseMyDate(nmea_sentence);
// and remember the name
break;
case VESSEL_NAME:
// ok, extract the rest of the body
myName = parseMyName(nmea_sentence);
break;
case OS_DEPTH:
if (importOS)
{
// ok, extract the rest of the body
myDepth = parseMyDepth(nmea_sentence);
}
break;
case OS_COURSE_SPEED:
if (importOS)
{
// ok, extract the rest of the body
final double myCourseDegs = parseMyCourse(nmea_sentence);
final double mySpeedKts = parseMySpeed(nmea_sentence);
// do we know our origin?
if (origin != null)
{
// ok, grow the DR track
storeDRFix(origin, myCourseDegs, mySpeedKts, date, myName, myDepth,
DebriefColors.BLUE);
}
}
break;
case OS_POS:
if (importOS)
{
// note: if we don't know ownship name yet,
// let's make one up
if (myName == null)
{
myName = WECDIS_OWNSHIP_PREFIX;
}
// extract the location
final State state = parseOwnship(nmea_sentence, myName);
// do we need an origin?
if (origin == null)
{
origin = new WorldLocation(state.location);
}
// do we know our name yet?
if (state != null && date != null)
{
// now store the ownship location
storeLocation(date, state, osFreq, DebriefColors.PURPLE, myDepth);
}
}
break;
case CONTACT:
if (importContacts)
{
// extract the location
final State hisState = parseContact(nmea_sentence);
if (hisState == null)
{
System.out.println("INVALID CONTACT");
}
else
{
// now store the ownship location
storeLocation(hisState.date, hisState, aisFreq,
DebriefColors.GREEN, null);
}
}
break;
case AIS:
if (importAIS)
{
// extract the location
final State hisState = parseAIS(nmea_sentence);
if (hisState == null)
{
// ok, it was prob the "other" AIS receiver
}
else
{
if (date != null)
{
// now store the ownship location
storeLocation(date, hisState, aisFreq, DebriefColors.YELLOW, null);
}
}
}
break;
case UNKNOWN:
break;
}
}
for (final String trackName : tracks.keySet())
{
final ArrayList<FixWrapper> track = tracks.get(trackName);
// ok, build the track
final TrackWrapper tr = new TrackWrapper();
tr.setName(trackName);
tr.setColor(colors.get(trackName));
System.out.println("storing " + track.size() + " for " + trackName);
// SPECIAL HANDLING - we filter DR tracks at this stage
Long lastTime = null;
final boolean resample = trackName.endsWith("-DR");
for (final FixWrapper fix : track)
{
// ok, also do the label
fix.resetName();
final long thisTime = fix.getDateTimeGroup().getDate().getTime();
long delta = Long.MAX_VALUE;
if (resample && lastTime != null)
{
delta = thisTime - lastTime;
}
if ((!resample) || lastTime == null || delta >= osFreq)
{
tr.add(fix);
lastTime = thisTime;
}
}
_layers.addThisLayer(tr);
}
}
private void storeDRFix(final WorldLocation origin,
final double myCourseDegs, final double mySpeedKts, final Date date,
final String myName, final double myDepth, final Color color)
{
final String trackName = myName + "-DR";
// find the track
ArrayList<FixWrapper> track = tracks.get(trackName);
final FixWrapper newFix;
// do we have any?
if (track == null)
{
track = new ArrayList<FixWrapper>();
tracks.put(trackName, track);
colors.put(trackName, color);
// nope, create the origin
final Fix fix =
new Fix(new HiResDate(date.getTime()), origin, Math
.toRadians(myCourseDegs), MWC.Algorithms.Conversions
.Kts2Yps(mySpeedKts));
newFix = new FixWrapper(fix);
}
else
{
// ok, get the last point
final FixWrapper lastFix = track.get(track.size() - 1);
// now calculate the new point
final long timeDelta =
date.getTime() - lastFix.getDateTimeGroup().getDate().getTime();
// calculate the distance travelled
final double m_s =
new WorldSpeed(mySpeedKts, WorldSpeed.Kts)
.getValueIn(WorldSpeed.M_sec);
final double distanceM = m_s * timeDelta / 1000d;
final double distanceDegs =
new WorldDistance(distanceM, WorldDistance.METRES)
.getValueIn(WorldDistance.DEGS);
final WorldVector offset =
new WorldVector(Math.toRadians(myCourseDegs), distanceDegs, 0);
final WorldLocation newLoc = lastFix.getLocation().add(offset);
// store the depth
newLoc.setDepth(myDepth);
final Fix fix =
new Fix(new HiResDate(date.getTime()), newLoc, Math
.toRadians(myCourseDegs), MWC.Algorithms.Conversions
.Kts2Yps(mySpeedKts));
newFix = new FixWrapper(fix);
// no, don't set the color, we want the fix to take
// the color of the parent track
// newFix.setColor(color);
}
track.add(newFix);
}
private void storeLocation(final Date date, final State state,
final long freq, final Color color, final Double myDepth)
{
final String myName = state.name;
ArrayList<FixWrapper> track = tracks.get(myName);
final boolean addIt;
final FixWrapper lastFix;
if (track == null)
{
track = new ArrayList<FixWrapper>();
tracks.put(myName, track);
colors.put(myName, color);
// ok. we're certainly adding this one
addIt = true;
lastFix = null;
}
else
{
// find the time of the last fix stored
lastFix = track.get(track.size() - 1);
final long lastTime = lastFix.getDateTimeGroup().getDate().getTime();
// have we passed the indicated frequency?
if (date.getTime() >= lastTime + freq)
{
addIt = true;
}
else
{
addIt = false;
}
}
if (addIt)
{
// create a fix from the state
final FixWrapper theF = fixFor(date, state, lastFix, myDepth);
// and store it
track.add(theF);
}
}
}
| change processing so we can optionally choose to generate DR track from organic sensors rather than using GPS locations
| 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 using GPS locations | <ide><path>rg.mwc.debrief.legacy/src/Debrief/ReaderWriter/NMEA/ImportNMEA.java
<ide> private enum MsgType
<ide> {
<ide> VESSEL_NAME, OS_POS, CONTACT, TIMESTAMP, UNKNOWN, AIS, OS_DEPTH,
<del> OS_COURSE_SPEED;
<add> OS_COURSE_SPEED, OS_COURSE, OS_SPEED;
<ide> }
<ide>
<ide> private static class State
<ide> "$POSL,AIS,564166000,3606.3667,N,00522.3698,W,0,7.8,327.9,0,330.0,AIS1,0,0*06";
<ide> final String test8 = "$POSL,PDS,9.2,M*03";
<ide> final String test9 = "$POSL,VEL,GPS,276.3,4.6,,,*35";
<add> final String test10_drSpd = "$POSL,VEL,SPL,,,4.1,0.0,4.0*12";
<add> final String test11_drCrse = "$POSL,HDG,111.2,-04.1*7F";
<ide>
<ide> assertEquals("Tgt POS", MsgType.CONTACT, parseType(test1));
<ide> assertEquals("Vessel name", MsgType.VESSEL_NAME, parseType(test2));
<ide>
<ide> assertEquals("got depth", 9.2d, parseMyDepth(test8), 0.001);
<ide>
<del> assertEquals("got course", 276.3d, parseMyCourse(test9), 0.001);
<del> assertEquals("got speed", 4.6d, parseMySpeed(test9), 0.001);
<add> assertEquals("got course", 276.3d, parseMyCourse(coursePatternGPS, test9), 0.001);
<add> assertEquals("got speed", 4.6d, parseMySpeed(speedPatternGPS, test9), 0.001);
<add>
<add> // and the DR equivalents
<add> assertEquals("got speed", 4.1d, parseMySpeed(speedPatternLOG, test10_drSpd), 0.001);
<add> assertEquals("got course", 111.2d, parseMyCourse(coursePatternHDG, test11_drCrse), 0.001);
<add>
<add>
<ide> }
<ide> }
<ide>
<ide> /**
<ide> * $POSL,VEL,GPS,276.3,4.6,,,*35
<ide> */
<del> final private static Pattern coursePattern = Pattern
<add> final private static Pattern coursePatternGPS = Pattern
<ide> .compile("\\$POSL,VEL,GPS,(?<COURSE>\\d+.\\d+),.*");
<add>
<add> /**
<add> * $POSL,HDG,111.0,-04.1*7F
<add> */
<add> final private static Pattern coursePatternHDG = Pattern
<add> .compile("\\$POSL,HDG,(?<COURSE>\\d+.\\d+),.*");
<ide>
<ide> /**
<ide> * $POSL,DZA,20160720,000000.859,0007328229*42
<ide> /**
<ide> * $POSL,VEL,GPS,276.3,4.6,,,*35
<ide> */
<del> final private static Pattern speedPattern = Pattern
<add> final private static Pattern speedPatternGPS = Pattern
<ide> .compile("\\$POSL,VEL,GPS,.*,(?<SPEED>\\d+.\\d+),.*");
<del>
<add> /**
<add> * $POSL,VEL,SPL,,,4.0,0.0,4.0*12
<add> */
<add> final private static Pattern speedPatternLOG = Pattern
<add> .compile("\\$POSL,VEL,SPL,,,(?<SPEED>\\d+.\\d+),.*");
<ide> /**
<ide> * "$POSL,POS,GPS,1122.2222,N,12312.1234,W,0.00,,Center of Rotation,N,,,,,*41";
<ide> */
<ide> return res;
<ide> }
<ide>
<del> static private double parseMyCourse(final String nmea_sentence)
<del> {
<del> final Matcher m = coursePattern.matcher(nmea_sentence);
<add> static private double parseMyCourse(final Pattern pattern,
<add> final String nmea_sentence)
<add> {
<add> final Matcher m = pattern.matcher(nmea_sentence);
<ide> final double res;
<ide> if (m.matches())
<ide> {
<ide> return res;
<ide> }
<ide>
<del> static private double parseMySpeed(final String nmea_sentence)
<del> {
<del> final Matcher m = speedPattern.matcher(nmea_sentence);
<add> static private double parseMySpeed(final Pattern pattern,
<add> final String nmea_sentence)
<add> {
<add> final Matcher m = pattern.matcher(nmea_sentence);
<ide> final double res;
<ide> if (m.matches())
<ide> {
<ide> res = MsgType.OS_POS;
<ide> else if (str.contains("VEL") && str2.equals("GPS"))
<ide> res = MsgType.OS_COURSE_SPEED;
<add> else if (str.contains("VEL") && str2.equals("SPL"))
<add> res = MsgType.OS_SPEED;
<add> else if (str.contains("HDG"))
<add> res = MsgType.OS_COURSE;
<ide> else if (str.equals("CONTACT"))
<ide> res = MsgType.CONTACT;
<ide> else if (str.equals("AIS"))
<ide> final BufferedReader br = new BufferedReader(new InputStreamReader(is));
<ide>
<ide> String nmea_sentence;
<add>
<add> // flag for if we wish to obtain DR data from GPS message, or from organic sensors
<add> final boolean DRfromGPS = false;
<add>
<add> // remember the last DR course read in, since we capture course and speed
<add> // from different messages
<add> Double drCourse = null;
<ide>
<ide> int ctr = 0;
<ide>
<ide> myDepth = parseMyDepth(nmea_sentence);
<ide> }
<ide> break;
<add> case OS_COURSE:
<add> if (importOS)
<add> {
<add> // ok, extract the rest of the body
<add> drCourse = parseMyCourse(coursePatternHDG, nmea_sentence);
<add> }
<add> break;
<add> case OS_SPEED:
<add> if (importOS)
<add> {
<add> // ok, extract the rest of the body
<add> double drSpeedDegs = parseMySpeed(speedPatternLOG, nmea_sentence);
<add>
<add> // are we taking DR from GPS?
<add> if(DRfromGPS)
<add> {
<add> // ok, skip creating the DR - do it in the other message
<add> }
<add> else
<add> {
<add> // do we know our origin?
<add> if (origin != null)
<add> {
<add> // ok, grow the DR track
<add> storeDRFix(origin, drCourse, drSpeedDegs, date, myName, myDepth,
<add> DebriefColors.BLUE);
<add> }
<add> }
<add> }
<add> break;
<ide> case OS_COURSE_SPEED:
<ide> if (importOS)
<ide> {
<ide> // ok, extract the rest of the body
<del> final double myCourseDegs = parseMyCourse(nmea_sentence);
<del> final double mySpeedKts = parseMySpeed(nmea_sentence);
<del>
<del> // do we know our origin?
<del> if (origin != null)
<del> {
<del> // ok, grow the DR track
<del> storeDRFix(origin, myCourseDegs, mySpeedKts, date, myName, myDepth,
<del> DebriefColors.BLUE);
<del> }
<add> final double myCourseDegs = parseMyCourse(coursePatternGPS, nmea_sentence);
<add> final double mySpeedKts = parseMySpeed(speedPatternGPS, nmea_sentence);
<add>
<add> // are we taking DR from GPS?
<add> if (DRfromGPS)
<add> {
<add> // do we know our origin?
<add> if (origin != null)
<add> {
<add> // ok, grow the DR track
<add> storeDRFix(origin, myCourseDegs, mySpeedKts, date, myName,
<add> myDepth, DebriefColors.BLUE);
<add> }
<add> }
<add> else
<add> {
<add> // ok, skip creating the DR using GPS deltas - do it from the organic sensors
<add> }
<ide> }
<ide> break;
<ide> case OS_POS: |
|
Java | bsd-3-clause | a4c876f87ead8fd84668c8f76189c0775c48a4a6 | 0 | jamie-dryad/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,jamie-dryad/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,mdiggory/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,mdiggory/dryad-repo,mdiggory/dryad-repo,rnathanday/dryad-repo,mdiggory/dryad-repo,rnathanday/dryad-repo,mdiggory/dryad-repo | /*
* DSQuery.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.search;
// java classes
import java.io.*;
import java.util.*;
import java.sql.*;
// lucene search engine classes
import org.apache.lucene.index.*;
import org.apache.lucene.document.*;
import org.apache.lucene.queryParser.*;
import org.apache.lucene.search.*;
import org.apache.lucene.analysis.*;
import org.apache.log4j.Logger;
//Jakarta-ORO classes (regular expressions)
import org.apache.oro.text.perl.Perl5Util;
// dspace classes
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
// issues
// need to filter query string for security
// cmd line query needs to process args correctly (seems to split them up)
public class DSQuery
{
// Result types
static final String ALL = "999";
static final String ITEM = "" + Constants.ITEM;
static final String COLLECTION = "" + Constants.COLLECTION;
static final String COMMUNITY = "" + Constants.COMMUNITY;
/** log4j logger */
private static Logger log = Logger.getLogger(DSQuery.class);
/** Do a query, returning a List of DSpace Handles to objects matching the query.
* @param query string in Lucene query syntax
*
* @return HashMap with lists for items, communities, and collections
* (keys are strings from Constants.ITEM, Constants.COLLECTION, etc.
*/
public static synchronized HashMap doQuery(Context c, String querystring)
throws IOException
{
querystring = checkEmptyQuery( querystring );
// play with regular expressions to work around lucene bug
Perl5Util util = new Perl5Util();
querystring = util.substitute("s/ AND / && /g", querystring);
querystring = util.substitute("s/ OR / || /g", querystring);
querystring = util.substitute("s/ NOT / ! /g", querystring);
querystring = querystring.toLowerCase();
ArrayList resultlist= new ArrayList();
ArrayList itemlist = new ArrayList();
ArrayList commlist = new ArrayList();
ArrayList colllist = new ArrayList();
HashMap metahash = new HashMap();
// initial results are empty
metahash.put(ALL, resultlist);
metahash.put(ITEM, itemlist );
metahash.put(COLLECTION,colllist );
metahash.put(COMMUNITY, commlist );
try
{
IndexSearcher searcher = new IndexSearcher(
ConfigurationManager.getProperty("search.dir"));
QueryParser qp = new QueryParser("default", new DSAnalyzer());
Query myquery = qp.parse(querystring);
Hits hits = searcher.search(myquery);
for (int i = 0; i < hits.length(); i++)
{
Document d = hits.doc(i);
String handletext = d.get("handle");
String handletype = d.get("type");
resultlist.add(handletext);
if (handletype.equals(ITEM))
{
itemlist.add(handletext);
}
else if (handletype.equals(COLLECTION))
{
colllist.add(handletext);
}
else if (handletype.equals(COMMUNITY))
{
commlist.add(handletext); break;
}
}
// close the IndexSearcher - and all its filehandles
searcher.close();
// store all of the different types of hits in the hash
metahash.put(ALL, resultlist);
metahash.put(ITEM, itemlist );
metahash.put(COLLECTION,colllist );
metahash.put(COMMUNITY, commlist );
}
catch (NumberFormatException e)
{
// a bad parse means that there are no results
// doing nothing with the exception gets you
// throw new SQLException( "Error parsing search results: " + e );
// ?? quit?
}
catch (ParseException e)
{
// a parse exception - log and return null results
log.warn(LogManager.getHeader(c,
"Lucene Parse Exception",
"" + e));
}
return metahash;
}
static String checkEmptyQuery( String myquery )
{
if( myquery.equals("") )
{
myquery = "empty_query_string";
}
return myquery;
}
/** Do a query, restricted to a collection
* @param query
* @param collection
*
* @return HashMap same results as doQuery, restricted to a collection
*/
public static HashMap doQuery(Context c, String querystring, Collection coll)
throws IOException, ParseException
{
querystring = checkEmptyQuery( querystring );
String location = "l" + (coll.getID());
String newquery = new String("+(" + querystring + ") +location:\"" + location + "\"");
return doQuery(c, newquery);
}
/** Do a query, restricted to a community
* @param querystring
* @param community
*
* @return HashMap results, same as full doQuery, only hits in a Community
*/
public static HashMap doQuery(Context c, String querystring, Community comm)
throws IOException, ParseException
{
querystring = checkEmptyQuery( querystring );
String location = "m" + (comm.getID());
String newquery = new String("+(" + querystring + ") +location:\"" + location + "\"");
return doQuery(c, newquery);
}
/** return everything from a query
* @param results hashmap from doQuery
*
* @return List of all objects returned by search
*/
public static List getResults(HashMap results)
{
return ((List)results.get(ALL));
}
/** return just the items from a query
* @param results hashmap from doQuery
*
* @return List of items found by query
*/
public static List getItemResults(HashMap results)
{
return ((List)results.get(ITEM));
}
/** return just the collections from a query
* @param results hashmap from doQuery
*
* @return List of collections found by query
*/
public static List getCollectionResults(HashMap results)
{
return ((List)results.get(COLLECTION));
}
/** return just the communities from a query
* @param results hashmap from doQuery
*
* @return list of Communities found by query
*/
public static List getCommunityResults(HashMap results)
{
return ((List)results.get(COMMUNITY));
}
/** returns true if anything found
* @param results hashmap from doQuery
*
* @return true if anything found, false if nothing
*/
public static boolean resultsFound(HashMap results)
{
List thislist = getResults(results);
return (!thislist.isEmpty());
}
/** returns true if items found
* @param results hashmap from doQuery
*
* @return true if items found, false if none found
*/
public static boolean itemsFound(HashMap results)
{
List thislist = getItemResults(results);
return (!thislist.isEmpty());
}
/** returns true if collections found
* @param results hashmap from doQuery
*
* @return true if collections found, false if none
*/
public static boolean collectionsFound(HashMap results)
{
List thislist = getCollectionResults(results);
return (!thislist.isEmpty());
}
/** returns true if communities found
* @param results hashmap from doQuery
*
* @return true if communities found, false if none
*/
public static boolean communitiesFound(HashMap results)
{
List thislist = getCommunityResults(results);
return (!thislist.isEmpty());
}
/** Do a query, printing results to stdout
* largely for testing, but it is useful
*/
public static void doCMDLineQuery(String query)
{
System.out.println("Command line query: " + query);
try
{
Context c = new Context();
HashMap results = doQuery(c, query);
List itemlist = getItemResults(results);
List colllist = getCollectionResults(results);
List commlist = getCommunityResults(results);
if (communitiesFound(results))
{
System.out.println("\n" + "Communities: ");
Iterator i = commlist.iterator();
while (i.hasNext())
{
Object thishandle = i.next();
System.out.println("\t" + thishandle.toString());
}
}
if (collectionsFound(results))
{
System.out.println("\n" + "Collections: ");
Iterator j = colllist.iterator();
while (j.hasNext())
{
Object thishandle = j.next();
System.out.println("\t" + thishandle.toString());
}
}
System.out.println("\n" + "Items: ");
Iterator k = itemlist.iterator();
while (k.hasNext())
{
Object thishandle = k.next();
System.out.println("\t" + thishandle.toString());
}
if (!itemsFound(results))
{
System.out.println ("\tNo items found!");
}
}
catch (Exception e)
{
System.out.println("Exception caught: " + e);
}
}
public static void main(String[] args)
{
DSQuery q = new DSQuery();
if (args.length > 0)
{
q.doCMDLineQuery(args[0]);
}
}
}
| dspace/src/org/dspace/search/DSQuery.java | /*
* DSQuery.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.search;
// java classes
import java.io.*;
import java.util.*;
import java.sql.*;
// lucene search engine classes
import org.apache.lucene.index.*;
import org.apache.lucene.document.*;
import org.apache.lucene.queryParser.*;
import org.apache.lucene.search.*;
import org.apache.lucene.analysis.*;
import org.apache.log4j.Logger;
// dspace classes
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
// issues
// need to filter query string for security
// cmd line query needs to process args correctly (seems to split them up)
public class DSQuery
{
// Result types
static final String ALL = "999";
static final String ITEM = "" + Constants.ITEM;
static final String COLLECTION = "" + Constants.COLLECTION;
static final String COMMUNITY = "" + Constants.COMMUNITY;
/** log4j logger */
private static Logger log = Logger.getLogger(DSQuery.class);
/** Do a query, returning a List of DSpace Handles to objects matching the query.
* @param query string in Lucene query syntax
*
* @return HashMap with lists for items, communities, and collections
* (keys are strings from Constants.ITEM, Constants.COLLECTION, etc.
*/
public static synchronized HashMap doQuery(Context c, String querystring)
throws IOException
{
querystring = checkEmptyQuery( querystring );
querystring = querystring.toLowerCase();
ArrayList resultlist= new ArrayList();
ArrayList itemlist = new ArrayList();
ArrayList commlist = new ArrayList();
ArrayList colllist = new ArrayList();
HashMap metahash = new HashMap();
// initial results are empty
metahash.put(ALL, resultlist);
metahash.put(ITEM, itemlist );
metahash.put(COLLECTION,colllist );
metahash.put(COMMUNITY, commlist );
try
{
IndexSearcher searcher = new IndexSearcher(
ConfigurationManager.getProperty("search.dir"));
QueryParser qp = new QueryParser("default", new DSAnalyzer());
Query myquery = qp.parse(querystring);
Hits hits = searcher.search(myquery);
for (int i = 0; i < hits.length(); i++)
{
Document d = hits.doc(i);
String handletext = d.get("handle");
String handletype = d.get("type");
resultlist.add(handletext);
if (handletype.equals(ITEM))
{
itemlist.add(handletext);
}
else if (handletype.equals(COLLECTION))
{
colllist.add(handletext);
}
else if (handletype.equals(COMMUNITY))
{
commlist.add(handletext); break;
}
}
// close the IndexSearcher - and all its filehandles
searcher.close();
// store all of the different types of hits in the hash
metahash.put(ALL, resultlist);
metahash.put(ITEM, itemlist );
metahash.put(COLLECTION,colllist );
metahash.put(COMMUNITY, commlist );
}
catch (NumberFormatException e)
{
// a bad parse means that there are no results
// doing nothing with the exception gets you
// throw new SQLException( "Error parsing search results: " + e );
// ?? quit?
}
catch (ParseException e)
{
// a parse exception - log and return null results
log.warn(LogManager.getHeader(c,
"Lucene Parse Exception",
"" + e));
}
return metahash;
}
static String checkEmptyQuery( String myquery )
{
if( myquery.equals("") )
{
myquery = "empty_query_string";
}
return myquery;
}
/** Do a query, restricted to a collection
* @param query
* @param collection
*
* @return HashMap same results as doQuery, restricted to a collection
*/
public static HashMap doQuery(Context c, String querystring, Collection coll)
throws IOException, ParseException
{
querystring = checkEmptyQuery( querystring );
String location = "l" + (coll.getID());
String newquery = new String("+(" + querystring + ") +location:\"" + location + "\"");
return doQuery(c, newquery);
}
/** Do a query, restricted to a community
* @param querystring
* @param community
*
* @return HashMap results, same as full doQuery, only hits in a Community
*/
public static HashMap doQuery(Context c, String querystring, Community comm)
throws IOException, ParseException
{
querystring = checkEmptyQuery( querystring );
String location = "m" + (comm.getID());
String newquery = new String("+(" + querystring + ") +location:\"" + location + "\"");
return doQuery(c, newquery);
}
/** return everything from a query
* @param results hashmap from doQuery
*
* @return List of all objects returned by search
*/
public static List getResults(HashMap results)
{
return ((List)results.get(ALL));
}
/** return just the items from a query
* @param results hashmap from doQuery
*
* @return List of items found by query
*/
public static List getItemResults(HashMap results)
{
return ((List)results.get(ITEM));
}
/** return just the collections from a query
* @param results hashmap from doQuery
*
* @return List of collections found by query
*/
public static List getCollectionResults(HashMap results)
{
return ((List)results.get(COLLECTION));
}
/** return just the communities from a query
* @param results hashmap from doQuery
*
* @return list of Communities found by query
*/
public static List getCommunityResults(HashMap results)
{
return ((List)results.get(COMMUNITY));
}
/** returns true if anything found
* @param results hashmap from doQuery
*
* @return true if anything found, false if nothing
*/
public static boolean resultsFound(HashMap results)
{
List thislist = getResults(results);
return (!thislist.isEmpty());
}
/** returns true if items found
* @param results hashmap from doQuery
*
* @return true if items found, false if none found
*/
public static boolean itemsFound(HashMap results)
{
List thislist = getItemResults(results);
return (!thislist.isEmpty());
}
/** returns true if collections found
* @param results hashmap from doQuery
*
* @return true if collections found, false if none
*/
public static boolean collectionsFound(HashMap results)
{
List thislist = getCollectionResults(results);
return (!thislist.isEmpty());
}
/** returns true if communities found
* @param results hashmap from doQuery
*
* @return true if communities found, false if none
*/
public static boolean communitiesFound(HashMap results)
{
List thislist = getCommunityResults(results);
return (!thislist.isEmpty());
}
/** Do a query, printing results to stdout
* largely for testing, but it is useful
*/
public static void doCMDLineQuery(String query)
{
System.out.println("Command line query: " + query);
try
{
Context c = new Context();
HashMap results = doQuery(c, query);
List itemlist = getItemResults(results);
List colllist = getCollectionResults(results);
List commlist = getCommunityResults(results);
if (communitiesFound(results))
{
System.out.println("\n" + "Communities: ");
Iterator i = commlist.iterator();
while (i.hasNext())
{
Object thishandle = i.next();
System.out.println("\t" + thishandle.toString());
}
}
if (collectionsFound(results))
{
System.out.println("\n" + "Collections: ");
Iterator j = colllist.iterator();
while (j.hasNext())
{
Object thishandle = j.next();
System.out.println("\t" + thishandle.toString());
}
}
System.out.println("\n" + "Items: ");
Iterator k = itemlist.iterator();
while (k.hasNext())
{
Object thishandle = k.next();
System.out.println("\t" + thishandle.toString());
}
if (!itemsFound(results))
{
System.out.println ("\tNo items found!");
}
}
catch (Exception e)
{
System.out.println("Exception caught: " + e);
}
}
public static void main(String[] args)
{
DSQuery q = new DSQuery();
if (args.length > 0)
{
q.doCMDLineQuery(args[0]);
}
}
}
| Added hack to allow boolean searching. Basically, I transform 'AND' into '&&',
'OR' into '||' and 'NOT' into '!' brefore I make the query string lowercase.
git-svn-id: 39c64a9546defcc59b5f71fe8fe20b2d01c24c1f@564 9c30dcfa-912a-0410-8fc2-9e0234be79fd
| dspace/src/org/dspace/search/DSQuery.java | Added hack to allow boolean searching. Basically, I transform 'AND' into '&&', 'OR' into '||' and 'NOT' into '!' brefore I make the query string lowercase. | <ide><path>space/src/org/dspace/search/DSQuery.java
<ide>
<ide> import org.apache.log4j.Logger;
<ide>
<add>//Jakarta-ORO classes (regular expressions)
<add>import org.apache.oro.text.perl.Perl5Util;
<add>
<ide> // dspace classes
<ide> import org.dspace.content.Collection;
<ide> import org.dspace.content.Community;
<ide> throws IOException
<ide> {
<ide> querystring = checkEmptyQuery( querystring );
<add>
<add> // play with regular expressions to work around lucene bug
<add> Perl5Util util = new Perl5Util();
<add>
<add> querystring = util.substitute("s/ AND / && /g", querystring);
<add> querystring = util.substitute("s/ OR / || /g", querystring);
<add> querystring = util.substitute("s/ NOT / ! /g", querystring);
<add>
<ide> querystring = querystring.toLowerCase();
<ide>
<ide> ArrayList resultlist= new ArrayList(); |
|
JavaScript | bsd-3-clause | 339f12d1b02774aee1065f92376be797c1fc5ef0 | 0 | rlugojr/VivaGraphJS,rshipp/VivaGraphJS,hochshi/VivaGraphJS,aigeano/recommendation-visualizer,aigeano/recommendation-visualizer,dikshay/VivaGraphJS,dikshay/VivaGraphJS,rlugojr/VivaGraphJS,rshipp/VivaGraphJS,hochshi/VivaGraphJS | /**
* @author Andrei Kashcha (aka anvaka) / http://anvaka.blogspot.com
*/
/*global Viva, window*/
/*jslint sloppy: true, vars: true, plusplus: true, bitwise: true, nomen: true */
Viva.Graph.Utils = Viva.Graph.Utils || {};
// TODO: Add support for touch events: http://www.sitepen.com/blog/2008/07/10/touching-and-gesturing-on-the-iphone/
// TODO: Move to input namespace
Viva.Graph.Utils.dragndrop = function (element) {
var start,
drag,
end,
scroll,
prevSelectStart,
prevDragStart,
documentEvents = Viva.Graph.Utils.events(window.document),
elementEvents = Viva.Graph.Utils.events(element),
findElementPosition = Viva.Graph.Utils.findElementPosition,
startX = 0,
startY = 0,
dragObject,
getMousePos = function (e) {
var posx = 0,
posy = 0;
e = e || window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
} else if (e.clientX || e.clientY) {
posx = e.clientX + window.document.body.scrollLeft + window.document.documentElement.scrollLeft;
posy = e.clientY + window.document.body.scrollTop + window.document.documentElement.scrollTop;
}
return [posx, posy];
},
stopPropagation = function (e) {
if (e.stopPropagation) { e.stopPropagation(); } else { e.cancelBubble = true; }
},
handleDisabledEvent = function (e) {
stopPropagation(e);
return false;
},
handleMouseMove = function (e) {
e = e || window.event;
if (drag) {
drag(e, {x : e.clientX - startX, y : e.clientY - startY });
}
startX = e.clientX;
startY = e.clientY;
},
handleMouseDown = function (e) {
e = e || window.event;
// for IE, left click == 1
// for Firefox, left click == 0
var isLeftButton = ((e.button === 1 && window.event !== null) || e.button === 0);
if (isLeftButton) {
startX = e.clientX;
startY = e.clientY;
// TODO: bump zIndex?
dragObject = e.target || e.srcElement;
if (start) { start(e, {x: startX, y : startY}); }
documentEvents.on('mousemove', handleMouseMove);
documentEvents.on('mouseup', handleMouseUp);
stopPropagation(e);
// TODO: This is suggested here: http://luke.breuer.com/tutorial/javascript-drag-and-drop-tutorial.aspx
// do we need it? What if event already there?
// Not bullet proof:
prevSelectStart = window.document.onselectstart;
prevDragStart = window.document.ondragstart;
window.document.onselectstart = handleDisabledEvent;
dragObject.ondragstart = handleDisabledEvent;
// prevent text selection (except IE)
return false;
}
},
handleMouseUp = function (e) {
e = e || window.event;
documentEvents.stop('mousemove', handleMouseMove);
documentEvents.stop('mouseup', handleMouseUp);
window.document.onselectstart = prevSelectStart;
dragObject.ondragstart = prevDragStart;
dragObject = null;
if (end) { end(e); }
},
handleMouseWheel = function (e) {
if (typeof scroll !== 'function') {
return;
}
e = e || window.event;
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
var delta,
mousePos = getMousePos(e),
elementOffset = findElementPosition(element),
relMousePos = {
x: mousePos[0] - elementOffset[0],
y: mousePos[1] - elementOffset[1]
};
if (e.wheelDelta) {
delta = e.wheelDelta / 360; // Chrome/Safari
} else {
delta = e.detail / -9; // Mozilla
}
scroll(e, delta, relMousePos);
},
updateScrollEvents = function (scrollCallback) {
if (!scroll && scrollCallback) {
// client is interested in scrolling. Start listening to events:
if (Viva.BrowserInfo.browser === 'webkit') {
element.addEventListener('mousewheel', handleMouseWheel, false); // Chrome/Safari
} else {
element.addEventListener('DOMMouseScroll', handleMouseWheel, false); // Others
}
} else if (scroll && !scrollCallback) {
if (Viva.BrowserInfo.browser === 'webkit') {
element.removeEventListener('mousewheel', handleMouseWheel, false); // Chrome/Safari
} else {
element.removeEventListener('DOMMouseScroll', handleMouseWheel, false); // Others
}
}
scroll = scrollCallback;
};
elementEvents.on('mousedown', handleMouseDown);
return {
onStart : function (callback) {
start = callback;
return this;
},
onDrag : function (callback) {
drag = callback;
return this;
},
onStop : function (callback) {
end = callback;
return this;
},
/**
* Occurs when mouse wheel event happens. callback = function(e, scrollDelta, scrollPoint);
*/
onScroll : function (callback) {
updateScrollEvents(callback);
return this;
},
release : function () {
// TODO: could be unsafe. We might wanna release dragObject, etc.
documentEvents.stop('mousemove', handleMouseMove);
documentEvents.stop('mousedown', handleMouseDown);
documentEvents.stop('mouseup', handleMouseUp);
updateScrollEvents(null);
}
};
};
| src/Input/dragndrop.js | /**
* @author Andrei Kashcha (aka anvaka) / http://anvaka.blogspot.com
*/
/*global Viva, window*/
/*jslint sloppy: true, vars: true, plusplus: true, bitwise: true, nomen: true */
Viva.Graph.Utils = Viva.Graph.Utils || {};
// TODO: Add support for touch events: http://www.sitepen.com/blog/2008/07/10/touching-and-gesturing-on-the-iphone/
// TODO: Move to input namespace
Viva.Graph.Utils.dragndrop = function (element) {
var start,
drag,
end,
scroll,
prevSelectStart,
prevDragStart,
documentEvents = Viva.Graph.Utils.events(window.document),
elementEvents = Viva.Graph.Utils.events(element),
findElementPosition = Viva.Graph.Utils.findElementPosition,
startX = 0,
startY = 0,
dragObject,
getMousePos = function (e) {
var posx = 0,
posy = 0;
e = e || window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
} else if (e.clientX || e.clientY) {
posx = e.clientX + window.document.body.scrollLeft + window.document.documentElement.scrollLeft;
posy = e.clientY + window.document.body.scrollTop + window.document.documentElement.scrollTop;
}
return [posx, posy];
},
stopPropagation = function (e) {
if (e.stopPropagation) { e.stopPropagation(); } else { e.cancelBubble = true; }
},
handleDisabledEvent = function (e) {
stopPropagation(e);
return false;
},
handleMouseMove = function (e) {
e = e || window.event;
if (drag) {
drag(e, {x : e.clientX - startX, y : e.clientY - startY });
}
startX = e.clientX;
startY = e.clientY;
},
handleMouseDown = function (e) {
e = e || window.event;
// for IE, left click == 1
// for Firefox, left click == 0
var isLeftButton = ((e.button === 1 && window.event !== null) || e.button === 0);
if (isLeftButton) {
startX = e.clientX;
startY = e.clientY;
// TODO: bump zIndex?
dragObject = e.target || e.srcElement;
if (start) { start(e, {x: startX, y : startY}); }
documentEvents.on('mousemove', handleMouseMove);
documentEvents.on('mouseup', handleMouseUp);
stopPropagation(e);
// TODO: This is suggested here: http://luke.breuer.com/tutorial/javascript-drag-and-drop-tutorial.aspx
// do we need it? What if event already there?
// Not bullet proof:
prevSelectStart = window.document.onselectstart;
prevDragStart = window.document.ondragstart;
window.document.onselectstart = handleDisabledEvent;
dragObject.ondragstart = handleDisabledEvent;
// prevent text selection (except IE)
return false;
}
},
handleMouseUp = function (e) {
e = e || window.event;
documentEvents.stop('mousemove', handleMouseMove);
documentEvents.stop('mouseup', handleMouseUp);
window.document.onselectstart = prevSelectStart;
dragObject.ondragstart = prevDragStart;
dragObject = null;
if (end) { end(); }
},
handleMouseWheel = function (e) {
if (typeof scroll !== 'function') {
return;
}
e = e || window.event;
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
var delta,
mousePos = getMousePos(e),
elementOffset = findElementPosition(element),
relMousePos = {
x: mousePos[0] - elementOffset[0],
y: mousePos[1] - elementOffset[1]
};
if (e.wheelDelta) {
delta = e.wheelDelta / 360; // Chrome/Safari
} else {
delta = e.detail / -9; // Mozilla
}
scroll(e, delta, relMousePos);
},
updateScrollEvents = function (scrollCallback) {
if (!scroll && scrollCallback) {
// client is interested in scrolling. Start listening to events:
if (Viva.BrowserInfo.browser === 'webkit') {
element.addEventListener('mousewheel', handleMouseWheel, false); // Chrome/Safari
} else {
element.addEventListener('DOMMouseScroll', handleMouseWheel, false); // Others
}
} else if (scroll && !scrollCallback) {
if (Viva.BrowserInfo.browser === 'webkit') {
element.removeEventListener('mousewheel', handleMouseWheel, false); // Chrome/Safari
} else {
element.removeEventListener('DOMMouseScroll', handleMouseWheel, false); // Others
}
}
scroll = scrollCallback;
};
elementEvents.on('mousedown', handleMouseDown);
return {
onStart : function (callback) {
start = callback;
return this;
},
onDrag : function (callback) {
drag = callback;
return this;
},
onStop : function (callback) {
end = callback;
return this;
},
/**
* Occurs when mouse wheel event happens. callback = function(e, scrollDelta, scrollPoint);
*/
onScroll : function (callback) {
updateScrollEvents(callback);
return this;
},
release : function () {
// TODO: could be unsafe. We might wanna release dragObject, etc.
documentEvents.stop('mousemove', handleMouseMove);
documentEvents.stop('mousedown', handleMouseDown);
documentEvents.stop('mouseup', handleMouseUp);
updateScrollEvents(null);
}
};
};
| Fixed drag'n'drop onStop argument | src/Input/dragndrop.js | Fixed drag'n'drop onStop argument | <ide><path>rc/Input/dragndrop.js
<ide> window.document.onselectstart = prevSelectStart;
<ide> dragObject.ondragstart = prevDragStart;
<ide> dragObject = null;
<del> if (end) { end(); }
<add> if (end) { end(e); }
<ide> },
<ide>
<ide> handleMouseWheel = function (e) { |
|
JavaScript | mit | f29594354ef88e1ec7856927c5a919844fd75c9e | 0 | alfl/plur | describe("The plurivalent logic test suite", function() {
var plur = require('../src/plur.js');
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
it("can validate the value True", function() {
var True = plur.True();
expect(True).not.toBe(undefined);
expect(True).not.toBe(null);
expect(True.value.size).toBe(1);
expect(True.value.has(true)).toBe(true);
});
it("can validate the value False", function() {
var False = plur.False();
expect(False).not.toBe(undefined);
expect(False).not.toBe(null);
expect(False.value.size).toBe(1);
expect(False.value.has(false)).toBe(true);
});
it("can validate the value Paradox", function() {
var Paradox = plur.Paradox();
expect(Paradox).not.toBe(undefined);
expect(Paradox).not.toBe(null);
expect(Paradox.value.size).toBe(2);
expect(Paradox.value.has(true)).toBe(true);
expect(Paradox.value.has(false)).toBe(true);
});
it("can validate the value Empty", function() {
var Empty = plur.Empty();
expect(Empty).not.toBe(undefined);
expect(Empty).not.toBe(null);
expect(Empty.value.size).toBe(0);
});
it("can validate the value Cipher", function() {
var Cipher = plur.Cipher();
expect(Cipher).not.toBe(undefined);
expect(Cipher).not.toBe(null);
expect(Cipher.value.size).toBe(1);
expect(Cipher.value.has(0)).toBe(true);
});
it("can validate the value Ineffable", function() {
var Ineffable = plur.Ineffable();
expect(Ineffable).not.toBe(undefined);
expect(Ineffable).not.toBe(null);
expect(Ineffable.value.size).toBe(1);
// This is also a test of how the underlying implementation
// handles NaN tests. Traditionally NaN != NaN.
expect(Ineffable.value.has(NaN)).toBe(true);
});
it("can validate AND operations against TRUE", function() {
var True = plur.True();
var False = plur.False();
var Paradox = plur.Paradox();
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(True.and(True).value.size).toBe(1);
expect(True.and(True).value.has(true)).toBe(true);
expect(True.and(False).value.size).toBe(1);
expect(True.and(False).value.has(false)).toBe(true);
expect(False.and(True).value.size).toBe(1);
expect(False.and(True).value.has(false)).toBe(true);
expect(True.and(Paradox).value.size).toBe(2);
expect(True.and(Paradox).value.has(true)).toBe(true);
expect(True.and(Paradox).value.has(false)).toBe(true);
expect(Paradox.and(True).value.size).toBe(2);
expect(Paradox.and(True).value.has(true)).toBe(true);
expect(Paradox.and(True).value.has(false)).toBe(true);
expect(True.and(Empty).value.size).toBe(0);
expect(Empty.and(True).value.size).toBe(0);
expect(True.and(Cipher).value.size).toBe(1);
expect(True.and(Cipher).value.has(false)).toBe(true);
expect(Cipher.and(True).value.size).toBe(1);
expect(Cipher.and(True).value.has(false)).toBe(true);
expect(True.and(Ineffable).value.size).toBe(1);
expect(True.and(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.and(True).value.size).toBe(1);
expect(Ineffable.and(True).value.has(NaN)).toBe(true);
});
it("can validate OR operations against TRUE", function() {
var True = plur.True();
var False = plur.False();
var Paradox = plur.Paradox();
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(True.or(True).value.size).toBe(1);
expect(True.or(True).value.has(true)).toBe(true);
expect(True.or(False).value.size).toBe(1);
expect(True.or(False).value.has(true)).toBe(true);
expect(False.or(True).value.size).toBe(1);
expect(False.or(True).value.has(true)).toBe(true);
expect(True.or(Paradox).value.size).toBe(1);
expect(True.or(Paradox).value.has(true)).toBe(true);
expect(Paradox.or(True).value.size).toBe(1);
expect(Paradox.or(True).value.has(true)).toBe(true);
expect(True.or(Empty).value.size).toBe(1);
expect(True.or(Empty).value.has(true)).toBe(true);
expect(Empty.or(True).value.size).toBe(1);
expect(Empty.or(True).value.has(true)).toBe(true);
expect(True.or(Cipher).value.size).toBe(1);
expect(True.or(Cipher).value.has(true)).toBe(true);
expect(Cipher.or(True).value.size).toBe(1);
expect(Cipher.or(True).value.has(true)).toBe(true);
expect(True.or(Ineffable).value.size).toBe(1);
expect(True.or(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.or(True).value.size).toBe(1);
expect(Ineffable.or(True).value.has(NaN)).toBe(true);
});
it("can validate AND operations against FALSE", function() {
var False = plur.False();
var Paradox = plur.Paradox();
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(False.and(False).value.size).toBe(1);
expect(False.and(False).value.has(false)).toBe(true);
expect(False.and(Paradox).value.size).toBe(1);
expect(False.and(Paradox).value.has(false)).toBe(true);
expect(Paradox.and(False).value.size).toBe(1);
expect(Paradox.and(False).value.has(false)).toBe(true);
expect(False.and(Empty).value.size).toBe(0);
expect(Empty.and(False).value.size).toBe(0);
expect(False.and(Cipher).value.size).toBe(1);
expect(False.and(Cipher).value.has(false)).toBe(true);
expect(Cipher.and(False).value.size).toBe(1);
expect(Cipher.and(False).value.has(false)).toBe(true);
expect(False.and(Ineffable).value.size).toBe(1);
expect(False.and(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.and(False).value.size).toBe(1);
expect(Ineffable.and(False).value.has(NaN)).toBe(true);
});
it("can validate OR operations against FALSE", function() {
var False = plur.False();
var Paradox = plur.Paradox();
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(False.or(False).value.size).toBe(1);
expect(False.or(False).value.has(false)).toBe(true);
expect(False.or(Paradox).value.size).toBe(2);
expect(False.or(Paradox).value.has(true)).toBe(true);
expect(False.or(Paradox).value.has(false)).toBe(true);
expect(Paradox.or(False).value.size).toBe(2);
expect(Paradox.or(False).value.has(true)).toBe(true);
expect(Paradox.or(False).value.has(false)).toBe(true);
expect(False.or(Empty).value.size).toBe(1);
expect(False.or(Empty).value.has(false)).toBe(true);
expect(Empty.or(False).value.size).toBe(1);
expect(Empty.or(False).value.has(false)).toBe(true);
expect(False.or(Cipher).value.size).toBe(1);
expect(False.or(Cipher).value.has(false)).toBe(true);
expect(Cipher.or(False).value.size).toBe(1);
expect(Cipher.or(False).value.has(false)).toBe(true);
expect(False.or(Ineffable).value.size).toBe(1);
expect(False.or(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.or(False).value.size).toBe(1);
expect(Ineffable.or(False).value.has(NaN)).toBe(true);
});
it("can validate AND operations against PARADOX", function() {
var Paradox = plur.Paradox();
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(Paradox.and(Paradox).value.size).toBe(2);
expect(Paradox.and(Paradox).value.has(true)).toBe(true);
expect(Paradox.and(Paradox).value.has(false)).toBe(true);
expect(Paradox.and(Empty).value.size).toBe(0);
expect(Empty.and(Paradox).value.size).toBe(0);
expect(Paradox.and(Cipher).value.size).toBe(1);
expect(Paradox.and(Cipher).value.has(false)).toBe(true);
expect(Cipher.and(Paradox).value.size).toBe(1);
expect(Cipher.and(Paradox).value.has(false)).toBe(true);
expect(Paradox.and(Ineffable).value.size).toBe(1);
expect(Paradox.and(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.and(Paradox).value.size).toBe(1);
expect(Ineffable.and(Paradox).value.has(NaN)).toBe(true);
});
it("can validate OR operations against PARADOX", function() {
var Paradox = plur.Paradox();
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(Paradox.or(Paradox).value.size).toBe(2);
expect(Paradox.or(Paradox).value.has(true)).toBe(true);
expect(Paradox.or(Paradox).value.has(false)).toBe(true);
expect(Paradox.or(Empty).value.size).toBe(2);
expect(Paradox.or(Empty).value.has(true)).toBe(true);
expect(Paradox.or(Empty).value.has(false)).toBe(true);
expect(Empty.or(Paradox).value.size).toBe(2);
expect(Empty.or(Paradox).value.has(true)).toBe(true);
expect(Empty.or(Paradox).value.has(false)).toBe(true);
expect(Paradox.or(Cipher).value.size).toBe(2);
expect(Paradox.or(Cipher).value.has(true)).toBe(true);
expect(Paradox.or(Cipher).value.has(false)).toBe(true);
expect(Cipher.or(Paradox).value.size).toBe(2);
expect(Cipher.or(Paradox).value.has(true)).toBe(true);
expect(Cipher.or(Paradox).value.has(false)).toBe(true);
expect(Paradox.or(Ineffable).value.size).toBe(1);
expect(Paradox.or(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.or(Paradox).value.size).toBe(1);
expect(Ineffable.or(Paradox).value.has(NaN)).toBe(true);
});
it("can validate AND operations against EMPTY", function() {
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(Empty.and(Empty).value.size).toBe(0);
expect(Empty.and(Cipher).value.size).toBe(0);
expect(Cipher.and(Empty).value.size).toBe(0);
expect(Empty.and(Ineffable).value.size).toBe(1);
expect(Empty.and(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.and(Empty).value.size).toBe(1);
expect(Ineffable.and(Empty).value.has(NaN)).toBe(true);
});
it("can validate OR operations against EMPTY", function() {
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(Empty.or(Empty).value.size).toBe(0);
expect(Empty.or(Cipher).value.size).toBe(1);
expect(Empty.or(Cipher).value.has(0)).toBe(true);
expect(Cipher.or(Empty).value.size).toBe(1);
expect(Cipher.or(Empty).value.has(0)).toBe(true);
expect(Empty.or(Ineffable).value.size).toBe(1);
expect(Empty.or(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.or(Empty).value.size).toBe(1);
expect(Ineffable.or(Empty).value.has(NaN)).toBe(true);
});
it("can validate AND operations against CIPHER", function() {
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(Cipher.and(Cipher).value.size).toBe(1);
expect(Cipher.and(Cipher).value.has(0)).toBe(true);
expect(Cipher.and(Ineffable).value.size).toBe(1);
expect(Cipher.and(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.and(Cipher).value.size).toBe(1);
expect(Ineffable.and(Cipher).value.has(NaN)).toBe(true);
});
it("can validate OR operations against CIPHER", function() {
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(Cipher.or(Cipher).value.size).toBe(1);
expect(Cipher.or(Cipher).value.has(0)).toBe(true);
expect(Cipher.or(Cipher).value.size).toBe(1);
expect(Cipher.or(Cipher).value.has(0)).toBe(true);
expect(Cipher.or(Ineffable).value.size).toBe(1);
expect(Cipher.or(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.or(Cipher).value.size).toBe(1);
expect(Ineffable.or(Cipher).value.has(NaN)).toBe(true);
});
it("can validate AND operations against INEFFABLE", function() {
var Ineffable = plur.Ineffable();
expect(Ineffable.and(Ineffable).value.size).toBe(1);
expect(Ineffable.and(Ineffable).value.has(NaN)).toBe(true);
});
it("can validate OR operations against INEFFABLE", function() {
var Ineffable = plur.Ineffable();
expect(Ineffable.or(Ineffable).value.size).toBe(1);
expect(Ineffable.or(Ineffable).value.has(NaN)).toBe(true);
});
it("can validate NOT operations", function() {
var True = plur.True();
var False = plur.False();
var Paradox = plur.Paradox();
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(True.not().value.size).toBe(1);
expect(True.not().value.has(false)).toBe(true);
expect(False.not().value.size).toBe(1);
expect(False.not().value.has(true)).toBe(true);
// TODO: Check if !Paradox == Empty.
expect(Paradox.not().value.size).toBe(0);
// TODO: Check if !Empty == Paradox.
expect(Empty.not().value.size).toBe(2);
expect(Empty.not().value.has(true)).toBe(true);
expect(Empty.not().value.has(false)).toBe(true);
expect(Cipher.not().value.size).toBe(1);
expect(Cipher.not().value.has(true)).toBe(true);
expect(Ineffable.not().value.size).toBe(1);
expect(Ineffable.not().value.has(NaN)).toBe(true);
});
it("can validate IS operations", function() {
var True = plur.True();
var False = plur.False();
var Paradox = plur.Paradox();
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(True.is(True)).toBe(true);
expect(True.not().is(True)).toBe(false);
expect(False.is(False)).toBe(true);
expect(False.not().is(False)).toBe(false);
expect(Paradox.is(Paradox)).toBe(true);
expect(Paradox.not().is(Paradox)).toBe(false);
expect(Empty.is(Empty)).toBe(true);
expect(Empty.not().is(Empty)).toBe(false);
expect(Cipher.is(Cipher)).toBe(true);
expect(Cipher.not().is(Cipher)).toBe(false);
// The Ineffable is not Ineffable.
expect(Ineffable.is(Ineffable)).toBe(true);
expect(Ineffable.not().is(Ineffable)).toBe(true);
});
});
| spec/plurSpec.js | describe("The plurivalent logic test suite", function() {
var plur = require('../src/plur.js');
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
it("can validate the value True", function() {
var True = plur.True();
expect(True).not.toBe(undefined);
expect(True).not.toBe(null);
expect(True.value.size).toBe(1);
expect(True.value.has(true)).toBe(true);
});
it("can validate the value False", function() {
var False = plur.False();
expect(False).not.toBe(undefined);
expect(False).not.toBe(null);
expect(False.value.size).toBe(1);
expect(False.value.has(false)).toBe(true);
});
it("can validate the value Paradox", function() {
var Paradox = plur.Paradox();
expect(Paradox).not.toBe(undefined);
expect(Paradox).not.toBe(null);
expect(Paradox.value.size).toBe(2);
expect(Paradox.value.has(true)).toBe(true);
expect(Paradox.value.has(false)).toBe(true);
});
it("can validate the value Empty", function() {
var Empty = plur.Empty();
expect(Empty).not.toBe(undefined);
expect(Empty).not.toBe(null);
expect(Empty.value.size).toBe(0);
});
it("can validate the value Cipher", function() {
var Cipher = plur.Cipher();
expect(Cipher).not.toBe(undefined);
expect(Cipher).not.toBe(null);
expect(Cipher.value.size).toBe(1);
expect(Cipher.value.has(0)).toBe(true);
});
it("can validate the value Ineffable", function() {
var Ineffable = plur.Ineffable();
expect(Ineffable).not.toBe(undefined);
expect(Ineffable).not.toBe(null);
expect(Ineffable.value.size).toBe(1);
// This is also a test of how the underlying implementation
// handles NaN tests. Traditionally NaN != NaN.
expect(Ineffable.value.has(NaN)).toBe(true);
});
it("can validate AND operations against TRUE", function() {
var True = plur.True();
var False = plur.False();
var Paradox = plur.Paradox();
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(True.and(True).value.size).toBe(1);
expect(True.and(True).value.has(true)).toBe(true);
expect(True.and(False).value.size).toBe(1);
expect(True.and(False).value.has(false)).toBe(true);
expect(False.and(True).value.size).toBe(1);
expect(False.and(True).value.has(false)).toBe(true);
expect(True.and(Paradox).value.size).toBe(2);
expect(True.and(Paradox).value.has(true)).toBe(true);
expect(True.and(Paradox).value.has(false)).toBe(true);
expect(Paradox.and(True).value.size).toBe(2);
expect(Paradox.and(True).value.has(true)).toBe(true);
expect(Paradox.and(True).value.has(false)).toBe(true);
expect(True.and(Empty).value.size).toBe(0);
expect(Empty.and(True).value.size).toBe(0);
expect(True.and(Cipher).value.size).toBe(1);
expect(True.and(Cipher).value.has(false)).toBe(true);
expect(Cipher.and(True).value.size).toBe(1);
expect(Cipher.and(True).value.has(false)).toBe(true);
expect(True.and(Ineffable).value.size).toBe(1);
expect(True.and(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.and(True).value.size).toBe(1);
expect(Ineffable.and(True).value.has(NaN)).toBe(true);
});
it("can validate OR operations against TRUE", function() {
var True = plur.True();
var False = plur.False();
var Paradox = plur.Paradox();
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(True.or(True).value.size).toBe(1);
expect(True.or(True).value.has(true)).toBe(true);
expect(True.or(False).value.size).toBe(1);
expect(True.or(False).value.has(true)).toBe(true);
expect(False.or(True).value.size).toBe(1);
expect(False.or(True).value.has(true)).toBe(true);
expect(True.or(Paradox).value.size).toBe(1);
expect(True.or(Paradox).value.has(true)).toBe(true);
expect(Paradox.or(True).value.size).toBe(1);
expect(Paradox.or(True).value.has(true)).toBe(true);
expect(True.or(Empty).value.size).toBe(1);
expect(True.or(Empty).value.has(true)).toBe(true);
expect(Empty.or(True).value.size).toBe(1);
expect(Empty.or(True).value.has(true)).toBe(true);
expect(True.or(Cipher).value.size).toBe(1);
expect(True.or(Cipher).value.has(true)).toBe(true);
expect(Cipher.or(True).value.size).toBe(1);
expect(Cipher.or(True).value.has(true)).toBe(true);
expect(True.or(Ineffable).value.size).toBe(1);
expect(True.or(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.or(True).value.size).toBe(1);
expect(Ineffable.or(True).value.has(NaN)).toBe(true);
});
it("can validate AND operations against FALSE", function() {
var False = plur.False();
var Paradox = plur.Paradox();
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(False.and(False).value.size).toBe(1);
expect(False.and(False).value.has(false)).toBe(true);
expect(False.and(Paradox).value.size).toBe(1);
expect(False.and(Paradox).value.has(false)).toBe(true);
expect(Paradox.and(False).value.size).toBe(1);
expect(Paradox.and(False).value.has(false)).toBe(true);
expect(False.and(Empty).value.size).toBe(0);
expect(Empty.and(False).value.size).toBe(0);
expect(False.and(Cipher).value.size).toBe(1);
expect(False.and(Cipher).value.has(false)).toBe(true);
expect(Cipher.and(False).value.size).toBe(1);
expect(Cipher.and(False).value.has(false)).toBe(true);
expect(False.and(Ineffable).value.size).toBe(1);
expect(False.and(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.and(False).value.size).toBe(1);
expect(Ineffable.and(False).value.has(NaN)).toBe(true);
});
it("can validate OR operations against FALSE", function() {
var False = plur.False();
var Paradox = plur.Paradox();
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(False.or(False).value.size).toBe(1);
expect(False.or(False).value.has(false)).toBe(true);
expect(False.or(Paradox).value.size).toBe(2);
expect(False.or(Paradox).value.has(true)).toBe(true);
expect(False.or(Paradox).value.has(false)).toBe(true);
expect(Paradox.or(False).value.size).toBe(2);
expect(Paradox.or(False).value.has(true)).toBe(true);
expect(Paradox.or(False).value.has(false)).toBe(true);
expect(False.or(Empty).value.size).toBe(1);
expect(False.or(Empty).value.has(false)).toBe(true);
expect(Empty.or(False).value.size).toBe(1);
expect(Empty.or(False).value.has(false)).toBe(true);
expect(False.or(Cipher).value.size).toBe(1);
expect(False.or(Cipher).value.has(false)).toBe(true);
expect(Cipher.or(False).value.size).toBe(1);
expect(Cipher.or(False).value.has(false)).toBe(true);
expect(False.or(Ineffable).value.size).toBe(1);
expect(False.or(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.or(False).value.size).toBe(1);
expect(Ineffable.or(False).value.has(NaN)).toBe(true);
});
it("can validate AND operations against PARADOX", function() {
var Paradox = plur.Paradox();
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(Paradox.and(Paradox).value.size).toBe(2);
expect(Paradox.and(Paradox).value.has(true)).toBe(true);
expect(Paradox.and(Paradox).value.has(false)).toBe(true);
expect(Paradox.and(Empty).value.size).toBe(0);
expect(Empty.and(Paradox).value.size).toBe(0);
expect(Paradox.and(Cipher).value.size).toBe(1);
expect(Paradox.and(Cipher).value.has(false)).toBe(true);
expect(Cipher.and(Paradox).value.size).toBe(1);
expect(Cipher.and(Paradox).value.has(false)).toBe(true);
expect(Paradox.and(Ineffable).value.size).toBe(1);
expect(Paradox.and(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.and(Paradox).value.size).toBe(1);
expect(Ineffable.and(Paradox).value.has(NaN)).toBe(true);
});
it("can validate OR operations against PARADOX", function() {
var Paradox = plur.Paradox();
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(Paradox.or(Paradox).value.size).toBe(2);
expect(Paradox.or(Paradox).value.has(true)).toBe(true);
expect(Paradox.or(Paradox).value.has(false)).toBe(true);
expect(Paradox.or(Empty).value.size).toBe(2);
expect(Paradox.or(Empty).value.has(true)).toBe(true);
expect(Paradox.or(Empty).value.has(false)).toBe(true);
expect(Empty.or(Paradox).value.size).toBe(2);
expect(Empty.or(Paradox).value.has(true)).toBe(true);
expect(Empty.or(Paradox).value.has(false)).toBe(true);
expect(Paradox.or(Cipher).value.size).toBe(2);
expect(Paradox.or(Cipher).value.has(true)).toBe(true);
expect(Paradox.or(Cipher).value.has(false)).toBe(true);
expect(Cipher.or(Paradox).value.size).toBe(2);
expect(Cipher.or(Paradox).value.has(true)).toBe(true);
expect(Cipher.or(Paradox).value.has(false)).toBe(true);
expect(Paradox.or(Ineffable).value.size).toBe(1);
expect(Paradox.or(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.or(Paradox).value.size).toBe(1);
expect(Ineffable.or(Paradox).value.has(NaN)).toBe(true);
});
it("can validate AND operations against EMPTY", function() {
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(Empty.and(Empty).value.size).toBe(0);
expect(Empty.and(Cipher).value.size).toBe(0);
expect(Cipher.and(Empty).value.size).toBe(0);
expect(Empty.and(Ineffable).value.size).toBe(1);
expect(Empty.and(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.and(Empty).value.size).toBe(1);
expect(Ineffable.and(Empty).value.has(NaN)).toBe(true);
});
it("can validate OR operations against EMPTY", function() {
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(Empty.or(Empty).value.size).toBe(0);
expect(Empty.or(Cipher).value.size).toBe(1);
expect(Empty.or(Cipher).value.has(0)).toBe(true);
expect(Cipher.or(Empty).value.size).toBe(1);
expect(Cipher.or(Empty).value.has(0)).toBe(true);
expect(Empty.or(Ineffable).value.size).toBe(1);
expect(Empty.or(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.or(Empty).value.size).toBe(1);
expect(Ineffable.or(Empty).value.has(NaN)).toBe(true);
});
it("can validate AND operations against CIPHER", function() {
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(Cipher.and(Cipher).value.size).toBe(1);
expect(Cipher.and(Cipher).value.has(0)).toBe(true);
expect(Cipher.and(Ineffable).value.size).toBe(1);
expect(Cipher.and(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.and(Cipher).value.size).toBe(1);
expect(Ineffable.and(Cipher).value.has(NaN)).toBe(true);
});
it("can validate OR operations against CIPHER", function() {
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(Cipher.or(Cipher).value.size).toBe(1);
expect(Cipher.or(Cipher).value.has(0)).toBe(true);
expect(Cipher.or(Cipher).value.size).toBe(1);
expect(Cipher.or(Cipher).value.has(0)).toBe(true);
expect(Cipher.or(Ineffable).value.size).toBe(1);
expect(Cipher.or(Ineffable).value.has(NaN)).toBe(true);
expect(Ineffable.or(Cipher).value.size).toBe(1);
expect(Ineffable.or(Cipher).value.has(NaN)).toBe(true);
});
it("can validate AND operations against INEFFABLE", function() {
var Ineffable = plur.Ineffable();
expect(Ineffable.and(Ineffable).value.size).toBe(1);
expect(Ineffable.and(Ineffable).value.has(NaN)).toBe(true);
});
it("can validate OR operations against INEFFABLE", function() {
var Ineffable = plur.Ineffable();
expect(Ineffable.or(Ineffable).value.size).toBe(1);
expect(Ineffable.or(Ineffable).value.has(NaN)).toBe(true);
});
it("can validate NOT operations", function() {
var True = plur.True();
var False = plur.False();
var Paradox = plur.Paradox();
var Empty = plur.Empty();
var Cipher = plur.Cipher();
var Ineffable = plur.Ineffable();
expect(True.not().value.size).toBe(1);
expect(True.not().value.has(false)).toBe(true);
expect(False.not().value.size).toBe(1);
expect(False.not().value.has(true)).toBe(true);
// TODO: Check if !Paradox == Empty.
expect(Paradox.not().value.size).toBe(0);
// TODO: Check if !Empty == Paradox.
expect(Empty.not().value.size).toBe(2);
expect(Empty.not().value.has(true)).toBe(true);
expect(Empty.not().value.has(false)).toBe(true);
expect(Cipher.not().value.size).toBe(1);
expect(Cipher.not().value.has(true)).toBe(true);
expect(Ineffable.not().value.size).toBe(1);
expect(Ineffable.not().value.has(NaN)).toBe(true);
});
});
| Added test spec. TDD FTW.
| spec/plurSpec.js | Added test spec. TDD FTW. | <ide><path>pec/plurSpec.js
<ide> expect(Ineffable.not().value.size).toBe(1);
<ide> expect(Ineffable.not().value.has(NaN)).toBe(true);
<ide> });
<add>
<add> it("can validate IS operations", function() {
<add> var True = plur.True();
<add> var False = plur.False();
<add> var Paradox = plur.Paradox();
<add> var Empty = plur.Empty();
<add> var Cipher = plur.Cipher();
<add> var Ineffable = plur.Ineffable();
<add>
<add> expect(True.is(True)).toBe(true);
<add> expect(True.not().is(True)).toBe(false);
<add>
<add> expect(False.is(False)).toBe(true);
<add> expect(False.not().is(False)).toBe(false);
<add>
<add> expect(Paradox.is(Paradox)).toBe(true);
<add> expect(Paradox.not().is(Paradox)).toBe(false);
<add>
<add> expect(Empty.is(Empty)).toBe(true);
<add> expect(Empty.not().is(Empty)).toBe(false);
<add>
<add> expect(Cipher.is(Cipher)).toBe(true);
<add> expect(Cipher.not().is(Cipher)).toBe(false);
<add>
<add> // The Ineffable is not Ineffable.
<add> expect(Ineffable.is(Ineffable)).toBe(true);
<add> expect(Ineffable.not().is(Ineffable)).toBe(true);
<add> });
<ide> });
<ide> |
|
Java | agpl-3.0 | 01bb415be92703ef9ee2b07c9ae6cc780a3c5c8a | 0 | geomajas/geomajas-project-client-gwt2,geomajas/geomajas-project-client-gwt2,geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-server,geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-server,geomajas/geomajas-project-server,geomajas/geomajas-project-client-gwt | /*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2013 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contributors License Agreement. For full licensing
* details, see LICENSE.txt in the project root.
*/
package org.geomajas.plugin.wmsclient.client.layer;
import java.util.ArrayList;
import java.util.List;
import org.geomajas.geometry.Bbox;
import org.geomajas.layer.tile.RasterTile;
import org.geomajas.layer.tile.TileCode;
import org.geomajas.plugin.wmsclient.client.render.WmsScalesRenderer;
import org.geomajas.plugin.wmsclient.client.render.WmsScalesRendererFactory;
import org.geomajas.plugin.wmsclient.client.service.WmsService;
import org.geomajas.plugin.wmsclient.client.service.WmsTileService;
import org.geomajas.puregwt.client.gfx.HtmlContainer;
import org.geomajas.puregwt.client.map.ViewPort;
import org.geomajas.puregwt.client.map.layer.AbstractLayer;
import org.geomajas.puregwt.client.map.layer.LayerStylePresenter;
import org.geomajas.puregwt.client.map.render.LayerScalesRenderer;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
/**
* Default implementation of a {@link WmsLayer}.
*
* @author Pieter De Graef
*/
public class WmsLayerImpl extends AbstractLayer implements WmsLayer {
protected final WmsLayerConfiguration wmsConfig;
protected final WmsTileConfiguration tileConfig;
@Inject
protected WmsService wmsService;
@Inject
protected WmsTileService tileService;
@Inject
private WmsScalesRendererFactory rendererFactory;
protected WmsScalesRenderer renderer;
@Inject
protected WmsLayerImpl(@Assisted String title, @Assisted WmsLayerConfiguration wmsConfig,
@Assisted WmsTileConfiguration tileConfig) {
super(wmsConfig.getLayers());
this.wmsConfig = wmsConfig;
this.tileConfig = tileConfig;
this.title = title;
}
@Override
public List<LayerStylePresenter> getStylePresenters() {
List<LayerStylePresenter> presenters = new ArrayList<LayerStylePresenter>();
presenters.add(new WmsLayerStylePresenter(wmsService.getLegendGraphicUrl(wmsConfig)));
return presenters;
}
// ------------------------------------------------------------------------
// Public methods:
// ------------------------------------------------------------------------
@Override
public WmsLayerConfiguration getConfig() {
return wmsConfig;
}
@Override
public WmsTileConfiguration getTileConfig() {
return tileConfig;
}
/**
* Returns the view port CRS. This layer should always have the same CRS as the map!
*
* @return The layer CRS (=map CRS).
*/
public String getCrs() {
return viewPort.getCrs();
}
@Override
public ViewPort getViewPort() {
return viewPort;
}
// ------------------------------------------------------------------------
// OpacitySupported implementation:
// ------------------------------------------------------------------------
@Override
public void setOpacity(double opacity) {
renderer.getHtmlContainer().setOpacity(opacity);
}
@Override
public double getOpacity() {
return renderer.getHtmlContainer().getOpacity();
}
// ------------------------------------------------------------------------
// HasMapScalesRenderer implementation:
// ------------------------------------------------------------------------
/**
* Get the specific renderer for this type of layer. This will return a scale-based renderer that used a
* {@link org.geomajas.plugin.wmsclient.client.render.WmsTiledScaleRendererImpl} for each resolution.
*/
public LayerScalesRenderer getRenderer(HtmlContainer container) {
if (renderer == null) {
renderer = rendererFactory.create(this, container);
}
return renderer;
}
@Override
public List<RasterTile> getTiles(double scale, Bbox worldBounds) {
List<TileCode> codes = tileService.getTileCodesForBounds(getViewPort(), tileConfig, worldBounds, scale);
List<RasterTile> tiles = new ArrayList<RasterTile>();
if (!codes.isEmpty()) {
double actualScale = viewPort.getZoomStrategy().getZoomStepScale(codes.get(0).getTileLevel());
for (TileCode code : codes) {
Bbox bounds = tileService.getWorldBoundsForTile(getViewPort(), tileConfig, code);
RasterTile tile = new RasterTile(getScreenBounds(actualScale, bounds), code.toString());
tile.setCode(code);
tile.setUrl(wmsService.getMapUrl(getConfig(), getCrs(), bounds, tileConfig.getTileWidth(),
tileConfig.getTileHeight()));
tiles.add(tile);
}
}
return tiles;
}
private Bbox getScreenBounds(double scale, Bbox worldBounds) {
return new Bbox(Math.round(scale * worldBounds.getX()), -Math.round(scale * worldBounds.getMaxY()),
Math.round(scale * worldBounds.getMaxX()) - Math.round(scale * worldBounds.getX()), Math.round(scale
* worldBounds.getMaxY())
- Math.round(scale * worldBounds.getY()));
}
} | plugin/geomajas-plugin-wmsclient/wmsclient/src/main/java/org/geomajas/plugin/wmsclient/client/layer/WmsLayerImpl.java | /*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2013 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contributors License Agreement. For full licensing
* details, see LICENSE.txt in the project root.
*/
package org.geomajas.plugin.wmsclient.client.layer;
import java.util.ArrayList;
import java.util.List;
import org.geomajas.geometry.Bbox;
import org.geomajas.layer.tile.RasterTile;
import org.geomajas.layer.tile.TileCode;
import org.geomajas.plugin.wmsclient.client.render.WmsScalesRenderer;
import org.geomajas.plugin.wmsclient.client.render.WmsScalesRendererFactory;
import org.geomajas.plugin.wmsclient.client.service.WmsService;
import org.geomajas.plugin.wmsclient.client.service.WmsTileService;
import org.geomajas.puregwt.client.gfx.HtmlContainer;
import org.geomajas.puregwt.client.map.ViewPort;
import org.geomajas.puregwt.client.map.layer.AbstractLayer;
import org.geomajas.puregwt.client.map.layer.LayerStylePresenter;
import org.geomajas.puregwt.client.map.render.LayerScalesRenderer;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
/**
* Default implementation of a {@link WmsLayer}.
*
* @author Pieter De Graef
*/
public class WmsLayerImpl extends AbstractLayer implements WmsLayer {
protected final WmsLayerConfiguration wmsConfig;
protected final WmsTileConfiguration tileConfig;
@Inject
protected WmsService wmsService;
@Inject
protected WmsTileService tileService;
@Inject
private WmsScalesRendererFactory rendererFactory;
protected WmsScalesRenderer renderer;
@Inject
protected WmsLayerImpl(@Assisted String title, @Assisted WmsLayerConfiguration wmsConfig,
@Assisted WmsTileConfiguration tileConfig) {
super(wmsConfig.getLayers());
this.wmsConfig = wmsConfig;
this.tileConfig = tileConfig;
this.title = title;
}
@Override
public List<LayerStylePresenter> getStylePresenters() {
List<LayerStylePresenter> presenters = new ArrayList<LayerStylePresenter>();
presenters.add(new WmsLayerStylePresenter(wmsService.getLegendGraphicUrl(wmsConfig)));
return presenters;
}
// ------------------------------------------------------------------------
// Public methods:
// ------------------------------------------------------------------------
@Override
public WmsLayerConfiguration getConfig() {
return wmsConfig;
}
@Override
public WmsTileConfiguration getTileConfig() {
return tileConfig;
}
/**
* Returns the view port CRS. This layer should always have the same CRS as the map!
*
* @return The layer CRS (=map CRS).
*/
public String getCrs() {
return viewPort.getCrs();
}
@Override
public ViewPort getViewPort() {
return viewPort;
}
// ------------------------------------------------------------------------
// OpacitySupported implementation:
// ------------------------------------------------------------------------
@Override
public void setOpacity(double opacity) {
renderer.getHtmlContainer().setOpacity(opacity);
}
@Override
public double getOpacity() {
return renderer.getHtmlContainer().getOpacity();
}
// ------------------------------------------------------------------------
// HasMapScalesRenderer implementation:
// ------------------------------------------------------------------------
/**
* Get the specific renderer for this type of layer. This will return a scale-based renderer that used a
* {@link org.geomajas.plugin.wmsclient.client.render.WmsTiledScaleRendererImpl} for each resolution.
*/
public LayerScalesRenderer getRenderer(HtmlContainer container) {
if (renderer == null) {
renderer = rendererFactory.create(this, container);
}
return renderer;
}
@Override
@Override
public List<RasterTile> getTiles(double scale, Bbox worldBounds) {
List<TileCode> codes = tileService.getTileCodesForBounds(getViewPort(), tileConfig, worldBounds, scale);
List<RasterTile> tiles = new ArrayList<RasterTile>();
if (!codes.isEmpty()) {
double actualScale = viewPort.getZoomStrategy().getZoomStepScale(codes.get(0).getTileLevel());
for (TileCode code : codes) {
Bbox bounds = tileService.getWorldBoundsForTile(getViewPort(), tileConfig, code);
RasterTile tile = new RasterTile(getScreenBounds(actualScale, bounds), code.toString());
tile.setCode(code);
tile.setUrl(wmsService.getMapUrl(getConfig(), getCrs(), bounds, tileConfig.getTileWidth(),
tileConfig.getTileHeight()));
tiles.add(tile);
}
}
return tiles;
}
private Bbox getScreenBounds(double scale, Bbox worldBounds) {
return new Bbox(Math.round(scale * worldBounds.getX()), -Math.round(scale * worldBounds.getMaxY()),
Math.round(scale * worldBounds.getMaxX()) - Math.round(scale * worldBounds.getX()), Math.round(scale
* worldBounds.getMaxY())
- Math.round(scale * worldBounds.getY()));
}
} | Removed some double @Override annotations (because of {@inheritDoc} ?)
| plugin/geomajas-plugin-wmsclient/wmsclient/src/main/java/org/geomajas/plugin/wmsclient/client/layer/WmsLayerImpl.java | Removed some double @Override annotations (because of {@inheritDoc} ?) | <ide><path>lugin/geomajas-plugin-wmsclient/wmsclient/src/main/java/org/geomajas/plugin/wmsclient/client/layer/WmsLayerImpl.java
<ide> }
<ide>
<ide> @Override
<del> @Override
<ide> public List<RasterTile> getTiles(double scale, Bbox worldBounds) {
<ide> List<TileCode> codes = tileService.getTileCodesForBounds(getViewPort(), tileConfig, worldBounds, scale);
<ide> List<RasterTile> tiles = new ArrayList<RasterTile>(); |
|
JavaScript | apache-2.0 | 3c287e3c01da9371a3ff8da9c41a0ec7bdd05158 | 0 | tiobe/closure-compiler,monetate/closure-compiler,ChadKillingsworth/closure-compiler,ChadKillingsworth/closure-compiler,Yannic/closure-compiler,vobruba-martin/closure-compiler,vobruba-martin/closure-compiler,vobruba-martin/closure-compiler,ChadKillingsworth/closure-compiler,ChadKillingsworth/closure-compiler,google/closure-compiler,nawawi/closure-compiler,shantanusharma/closure-compiler,mprobst/closure-compiler,mprobst/closure-compiler,google/closure-compiler,google/closure-compiler,mprobst/closure-compiler,tiobe/closure-compiler,tiobe/closure-compiler,mprobst/closure-compiler,google/closure-compiler,Yannic/closure-compiler,monetate/closure-compiler,monetate/closure-compiler,nawawi/closure-compiler,shantanusharma/closure-compiler,nawawi/closure-compiler,nawawi/closure-compiler,Yannic/closure-compiler,tiobe/closure-compiler,monetate/closure-compiler,vobruba-martin/closure-compiler,shantanusharma/closure-compiler,shantanusharma/closure-compiler,Yannic/closure-compiler | /*
* Copyright 2011 The Closure Compiler 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.
*/
/**
* @fileoverview Externs for YouTube Player API for <iframe> Embeds.
* @see http://code.google.com/apis/youtube/iframe_api_reference.html
* @externs
*/
/** @return {undefined} */
var onYouTubePlayerAPIReady = function() {};
/** @return {undefined} */
window.onYouTubePlayerAPIReady = function() {};
/** @const */
var YT = {};
/**
* @constructor
* @param {(string|Element)} container
* @param {Object.<string, *>} opts
*/
YT.Player = function(container, opts) {};
/** @typedef {!{
* videoId: string,
* startSeconds: (number|undefined),
* endSeconds: (number|undefined),
* suggestedQuality: (string|undefined),
* }} */
YT.Player.VideoIdParams;
/**
* Loads the specified video's thumbnail and prepares the player to play the
* video.
* @param {!YT.Player.VideoIdParams|string} videoIdOrObject YouTube Video ID or
* parameters object.
* @param {number=} opt_startSeconds Float/integer that specifies the time
* from which the video should start playing.
* @param {string=} opt_suggestedQuality The suggested playback quality for
* the video.
*/
YT.Player.prototype.cueVideoById = function(
videoIdOrObject, opt_startSeconds, opt_suggestedQuality) {};
/**
* Loads and plays the specified video.
* @param {!YT.Player.VideoIdParams|string} videoIdOrObject YouTube Video ID or
* parameters object.
* @param {number=} opt_startSeconds Float/integer that specifies the time
* from which the video should start playing.
* @param {string=} opt_suggestedQuality The suggested playback quality for
* the video.
*/
YT.Player.prototype.loadVideoById = function(
videoIdOrObject, opt_startSeconds, opt_suggestedQuality) {};
/** @typedef {!{
* mediaContentUrl: string,
* startSeconds: (number|undefined),
* endSeconds: (number|undefined),
* suggestedQuality: (string|undefined),
* }} */
YT.Player.MediaContentUrlParams;
/**
* Loads the specified video's thumbnail and prepares the player to play the
* video.
* @param {!YT.Player.MediaContentUrlParams|string} mediaContentUrlOrObject
* YouTube player URL in the format http://www.youtube.com/v/VIDEO_ID or
* parameters object.
* @param {number=} opt_startSeconds Float/integer that specifies the time
* from which the video should start playing.
* @param {string=} opt_suggestedQuality The suggested playback quality for
* the video.
*/
YT.Player.prototype.cueVideoByUrl = function(
mediaContentUrlOrObject, opt_startSeconds, opt_suggestedQuality) {};
/**
* Loads and plays the specified video.
* @param {!YT.Player.MediaContentUrlParams|string} mediaContentUrlOrObject
* YouTube player URL in the format http://www.youtube.com/v/VIDEO_ID or
* parameters object.
* @param {number=} opt_startSeconds Float/integer that specifies the time
* from which the video should start playing.
* @param {string=} opt_suggestedQuality The suggested playback quality for
* the video.
*/
YT.Player.prototype.loadVideoByUrl = function(
mediaContentUrlOrObject, opt_startSeconds, opt_suggestedQuality) {};
/**
* Loads and cues a specified video in a playlist.
*
* @param {string|!Array<string>|!Object} playlistOrObject An object containing
* the parameters. N.B. a String object will be treated as an object
* instead of as a string. Otherwise, a string literal that is a playlist
* id (without the PL list prefix) or an array of video ids.
* @param {number=} opt_index The index to begin playback at.
* @param {number=} opt_startSeconds Float/integer that specifies the time
* from which the video should start playing.
* @param {string=} opt_suggestedQuality The suggested playback quality for
* the video.
*/
YT.Player.prototype.cuePlaylist = function(
playlistOrObject, opt_index, opt_startSeconds, opt_suggestedQuality) {};
/**
* @param {string|!Array<string>|!Object} playlistOrObject An object
* containing the parameters. N.B. a String object will be treated as an
* object instead of as a string. Otherwise, a string literal that is a
* playlist id (without the PL list prefix) or an array of video ids.
* @param {number=} opt_index The index to begin playback at.
* @param {number=} opt_startSeconds Float/integer that specifies the time
* from which the video should start playing.
* @param {string=} opt_suggestedQuality The suggested playback quality for
* the video.
*/
YT.Player.prototype.loadPlaylist = function(
playlistOrObject, opt_index, opt_startSeconds, opt_suggestedQuality) {};
/** @return {undefined} */
YT.Player.prototype.playVideo = function() {};
/** @return {undefined} */
YT.Player.prototype.pauseVideo = function() {};
/** @return {undefined} */
YT.Player.prototype.stopVideo = function() {};
/**
* @param {number} seconds
* @param {boolean} allowSeekAhead
*/
YT.Player.prototype.seekTo = function(seconds, allowSeekAhead) {};
/** @return {undefined} */
YT.Player.prototype.clearVideo = function() {};
/** @return {undefined} */
YT.Player.prototype.nextVideo = function() {};
/** @return {undefined} */
YT.Player.prototype.previousVideo = function() {};
/** @param {number} index */
YT.Player.prototype.playVideoAt = function(index) {};
/** @return {undefined} */
YT.Player.prototype.mute = function() {};
/** @return {undefined} */
YT.Player.prototype.unMute = function() {};
/** @return {boolean} */
YT.Player.prototype.isMuted = function() {};
/** @param {number} volume */
YT.Player.prototype.setVolume = function(volume) {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getVolume = function() {};
/** @param {boolean} loopPlaylists */
YT.Player.prototype.setLoop = function(loopPlaylists) {};
/** @param {boolean} shufflePlaylist */
YT.Player.prototype.setShuffle = function(shufflePlaylist) {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getVideoBytesLoaded = function() {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getVideoBytesTotal = function() {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getVideoLoadedFraction = function() {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getVideoStartBytes = function() {};
/**
* @return {YT.PlayerState|number}
* @nosideeffects
*/
YT.Player.prototype.getPlayerState = function() {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getCurrentTime = function() {};
/**
* @return {(undefined|string)}
* @nosideeffects
*/
YT.Player.prototype.getPlaybackQuality = function() {};
/** @param {string} suggestedQuality */
YT.Player.prototype.setPlaybackQuality = function(suggestedQuality) {};
/**
* @return {Array.<string>}
* @nosideeffects
*/
YT.Player.prototype.getAvailableQualityLevels = function() {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getDuration = function() {};
/**
* @return {string}
* @nosideeffects
*/
YT.Player.prototype.getVideoUrl = function() {};
/**
* @return {string}
* @nosideeffects
*/
YT.Player.prototype.getVideoEmbedCode = function() {};
/**
* @return {Array.<string>}
* @nosideeffects
*/
YT.Player.prototype.getPlaylist = function() {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getPlaylistIndex = function() {};
/**
* @param {string} eventName
* @param {string} listenerName
*/
YT.Player.prototype.addEventListener = function(eventName, listenerName) {};
/** Destroys the player reference. */
YT.Player.prototype.destroy = function() {};
/**
* @return {HTMLIFrameElement} The DOM node for the embedded iframe.
* @nosideeffects
*/
YT.Player.prototype.getIframe = function() {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getPlaybackRate = function() {};
/** @param {number} suggestedRate */
YT.Player.prototype.setPlaybackRate = function(suggestedRate) {};
/**
* @return {!Array.<number>}
* @nosideeffects
*/
YT.Player.prototype.getAvailablePlaybackRates = function() {};
/**
* Gets the spherical video config object, with information about the viewport
* headings and zoom level.
*
* @return {{yaw: (undefined|number), pitch: (undefined|number),
* roll: (undefined|number), fov: (undefined|number)}}
*/
YT.Player.prototype.getSphericalProperties = function() {};
/**
* Sets the spherical video config object. The call will be No-Op for non-360
* videos, and will change the view port according to the input for 360 videos.
*
* @param {?{yaw: (undefined|number), pitch: (undefined|number),
* roll: (undefined|number), fov: (undefined|number),
* enableOrientationSensor: (undefined|boolean)}} option
*/
YT.Player.prototype.setSphericalProperties = function(option) {};
/** @enum */
YT.PlayerState = {
UNSTARTED: -1,
ENDED: 0,
PLAYING: 1,
PAUSED: 2,
BUFFERING: 3,
CUED: 4
};
/**
* @constructor
* @private
*/
YT.Event = function() {};
/** @type {string|number|undefined} */
YT.Event.prototype.data;
/** @type {YT.Player} */
YT.Event.prototype.target = null;
| contrib/externs/google_youtube_iframe.js | /*
* Copyright 2011 The Closure Compiler 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.
*/
/**
* @fileoverview Externs for YouTube Player API for <iframe> Embeds.
* @see http://code.google.com/apis/youtube/iframe_api_reference.html
* @externs
*/
/** @return {undefined} */
var onYouTubePlayerAPIReady = function() {};
/** @return {undefined} */
window.onYouTubePlayerAPIReady = function() {};
/** @const */
var YT = {};
/**
* @constructor
* @param {(string|Element)} container
* @param {Object.<string, *>} opts
*/
YT.Player = function(container, opts) {};
/** @typedef {!{
* videoId: string,
* startSeconds: (number|undefined),
* endSeconds: (number|undefined),
* suggestedQuality: (string|undefined),
* }} */
YT.Player.VideoIdParams;
/**
* Loads the specified video's thumbnail and prepares the player to play the
* video.
* @param {!YT.Player.VideoIdParams|string} videoIdOrObject YouTube Video ID or
* parameters object.
* @param {number=} opt_startSeconds Float/integer that specifies the time
* from which the video should start playing.
* @param {string=} opt_suggestedQuality The suggested playback quality for
* the video.
*/
YT.Player.prototype.cueVideoById = function(
videoIdOrObject, opt_startSeconds, opt_suggestedQuality) {};
/**
* Loads and plays the specified video.
* @param {!YT.Player.VideoIdParams|string} videoIdOrObject YouTube Video ID or
* parameters object.
* @param {number=} opt_startSeconds Float/integer that specifies the time
* from which the video should start playing.
* @param {string=} opt_suggestedQuality The suggested playback quality for
* the video.
*/
YT.Player.prototype.loadVideoById = function(
videoIdOrObject, opt_startSeconds, opt_suggestedQuality) {};
/** @typedef {!{
* mediaContentUrl: string,
* startSeconds: (number|undefined),
* endSeconds: (number|undefined),
* suggestedQuality: (string|undefined),
* }} */
YT.Player.MediaContentUrlParams;
/**
* Loads the specified video's thumbnail and prepares the player to play the
* video.
* @param {!YT.Player.MediaContentUrlParams|string} mediaContentUrlOrObject
* YouTube player URL in the format http://www.youtube.com/v/VIDEO_ID or
* parameters object.
* @param {number=} opt_startSeconds Float/integer that specifies the time
* from which the video should start playing.
* @param {string=} opt_suggestedQuality The suggested playback quality for
* the video.
*/
YT.Player.prototype.cueVideoByUrl = function(
mediaContentUrlOrObject, opt_startSeconds, opt_suggestedQuality) {};
/**
* Loads and plays the specified video.
* @param {!YT.Player.MediaContentUrlParams|string} mediaContentUrlOrObject
* YouTube player URL in the format http://www.youtube.com/v/VIDEO_ID or
* parameters object.
* @param {number=} opt_startSeconds Float/integer that specifies the time
* from which the video should start playing.
* @param {string=} opt_suggestedQuality The suggested playback quality for
* the video.
*/
YT.Player.prototype.loadVideoByUrl = function(
mediaContentUrlOrObject, opt_startSeconds, opt_suggestedQuality) {};
/**
* Loads and cues a specified video in a playlist.
*
* @param {string|!Array<string>|!Object} playlistOrObject An object containing
* the parameters. N.B. a String object will be treated as an object
* instead of as a string. Otherwise, a string literal that is a playlist
* id (without the PL list prefix) or an array of video ids.
* @param {number=} opt_index The index to begin playback at.
* @param {number=} opt_startSeconds Float/integer that specifies the time
* from which the video should start playing.
* @param {string=} opt_suggestedQuality The suggested playback quality for
* the video.
*/
YT.Player.prototype.cuePlaylist = function(
playlistOrObject, opt_index, opt_startSeconds, opt_suggestedQuality) {};
/**
* @param {string|!Array<string>|!Object} playlistOrObject An object
* containing the parameters. N.B. a String object will be treated as an
* object instead of as a string. Otherwise, a string literal that is a
* playlist id (without the PL list prefix) or an array of video ids.
* @param {number=} opt_index The index to begin playback at.
* @param {number=} opt_startSeconds Float/integer that specifies the time
* from which the video should start playing.
* @param {string=} opt_suggestedQuality The suggested playback quality for
* the video.
*/
YT.Player.prototype.loadPlaylist = function(
playlistOrObject, opt_index, opt_startSeconds, opt_suggestedQuality) {};
/** @return {undefined} */
YT.Player.prototype.playVideo = function() {};
/** @return {undefined} */
YT.Player.prototype.pauseVideo = function() {};
/** @return {undefined} */
YT.Player.prototype.stopVideo = function() {};
/**
* @param {number} seconds
* @param {boolean} allowSeekAhead
*/
YT.Player.prototype.seekTo = function(seconds, allowSeekAhead) {};
/** @return {undefined} */
YT.Player.prototype.clearVideo = function() {};
/** @return {undefined} */
YT.Player.prototype.nextVideo = function() {};
/** @return {undefined} */
YT.Player.prototype.previousVideo = function() {};
/** @param {number} index */
YT.Player.prototype.playVideoAt = function(index) {};
/** @return {undefined} */
YT.Player.prototype.mute = function() {};
/** @return {undefined} */
YT.Player.prototype.unMute = function() {};
/** @return {boolean} */
YT.Player.prototype.isMuted = function() {};
/** @param {number} volume */
YT.Player.prototype.setVolume = function(volume) {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getVolume = function() {};
/** @param {boolean} loopPlaylists */
YT.Player.prototype.setLoop = function(loopPlaylists) {};
/** @param {boolean} shufflePlaylist */
YT.Player.prototype.setShuffle = function(shufflePlaylist) {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getVideoBytesLoaded = function() {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getVideoBytesTotal = function() {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getVideoLoadedFraction = function() {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getVideoStartBytes = function() {};
/**
* @return {YT.PlayerState|number}
* @nosideeffects
*/
YT.Player.prototype.getPlayerState = function() {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getCurrentTime = function() {};
/**
* @return {(undefined|string)}
* @nosideeffects
*/
YT.Player.prototype.getPlaybackQuality = function() {};
/** @param {string} suggestedQuality */
YT.Player.prototype.setPlaybackQuality = function(suggestedQuality) {};
/**
* @return {Array.<string>}
* @nosideeffects
*/
YT.Player.prototype.getAvailableQualityLevels = function() {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getDuration = function() {};
/**
* @return {string}
* @nosideeffects
*/
YT.Player.prototype.getVideoUrl = function() {};
/**
* @return {string}
* @nosideeffects
*/
YT.Player.prototype.getVideoEmbedCode = function() {};
/**
* @return {Array.<string>}
* @nosideeffects
*/
YT.Player.prototype.getPlaylist = function() {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getPlaylistIndex = function() {};
/**
* @param {string} eventName
* @param {string} listenerName
*/
YT.Player.prototype.addEventListener = function(eventName, listenerName) {};
/** Destroys the player reference. */
YT.Player.prototype.destroy = function() {};
/**
* @return {HTMLIFrameElement} The DOM node for the embedded iframe.
* @nosideeffects
*/
YT.Player.prototype.getIframe = function() {};
/**
* @return {number}
* @nosideeffects
*/
YT.Player.prototype.getPlaybackRate = function() {};
/** @param {number} suggestedRate */
YT.Player.prototype.setPlaybackRate = function(suggestedRate) {};
/**
* @return {!Array.<number>}
* @nosideeffects
*/
YT.Player.prototype.getAvailablePlaybackRates = function() {};
/** @enum */
YT.PlayerState = {
UNSTARTED: -1,
ENDED: 0,
PLAYING: 1,
PAUSED: 2,
BUFFERING: 3,
CUED: 4
};
/**
* @constructor
* @private
*/
YT.Event = function() {};
/** @type {string|number|undefined} */
YT.Event.prototype.data;
/** @type {YT.Player} */
YT.Event.prototype.target = null;
| Adding the YouTube 360 video iframe API to google_youtube_iframe.js.
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=200310123
| contrib/externs/google_youtube_iframe.js | Adding the YouTube 360 video iframe API to google_youtube_iframe.js. | <ide><path>ontrib/externs/google_youtube_iframe.js
<ide> * @nosideeffects
<ide> */
<ide> YT.Player.prototype.getAvailablePlaybackRates = function() {};
<add>
<add>
<add>/**
<add> * Gets the spherical video config object, with information about the viewport
<add> * headings and zoom level.
<add> *
<add> * @return {{yaw: (undefined|number), pitch: (undefined|number),
<add> * roll: (undefined|number), fov: (undefined|number)}}
<add> */
<add>YT.Player.prototype.getSphericalProperties = function() {};
<add>
<add>
<add>/**
<add> * Sets the spherical video config object. The call will be No-Op for non-360
<add> * videos, and will change the view port according to the input for 360 videos.
<add> *
<add> * @param {?{yaw: (undefined|number), pitch: (undefined|number),
<add> * roll: (undefined|number), fov: (undefined|number),
<add> * enableOrientationSensor: (undefined|boolean)}} option
<add> */
<add>YT.Player.prototype.setSphericalProperties = function(option) {};
<ide>
<ide>
<ide> /** @enum */ |
|
Java | apache-2.0 | 60c6fed4d93d2346aecee5d072ef1ba41049985f | 0 | gioma68/mondrian-dsp | /*
*
* Custom Schema processor which helps to implement dynamic security roles
*
* This software is subject to the terms of the Eclipse Public License v1.0
* Agreement, available at the following URL: http://www.eclipse.org/legal/epl-v10.html.
* You must accept the terms of that agreement to use this software.
*
* @author gmartano
* @since Jan 2016
* @version 1.0.0
*
*/
package com.mysample.mondrian.dsp;
import mondrian.olap.Util;
import mondrian.spi.*;
import mondrian.i18n.*;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.engine.core.system.PentahoSessionHolder;
import org.apache.log4j.Logger;
import java.io.InputStream;
import java.util.regex.PatternSyntaxException;
/* used to log to console for debugging purpose */
import static java.lang.System.out;
public class DynamicSchemaProcessor extends LocalizingDynamicSchemaProcessor {
private static final Logger LOG = Logger.getLogger(DynamicSchemaProcessor.class);
/** Creates a new instance of class */
public DynamicSchemaProcessor() {
}
@Override
public String filter(String schemaUrl, Util.PropertyList connectInfo, InputStream stream)
throws Exception {
String schema = super.filter(schemaUrl, connectInfo, stream);
System.out.println("[CUSTOM.DSP] *********** Started DSP Custom ***********");
IPentahoSession session = PentahoSessionHolder.getSession();
String usercode = (String) session.getAttribute("USERNAME");
try {
System.out.println("[CUSTOM.DSP] Trying to replace '%USER_NAME%' with session value: "+usercode);
LOG.info("Trying to replace '%USER_NAME%' with session value: "+usercode);
schema = schema.replaceAll("%USER_NAME%", usercode);
}
catch (PatternSyntaxException pse) {
System.out.println("[CUSTOM.DSP] Some error during custom schema processing: "+usercode);
LOG.error("Some error during custom schema processing. " , pse);
pse.printStackTrace();
}
LOG.info("DSP Ended correctly for "+usercode);
System.out.println("[CUSTOM.DSP] *********** DSP Ended correctly for "+usercode+" ***********");
return schema;
}
}
| src/com/mysample/mondrian/dsp/DynamicSchemaProcessor.java | /*
*
* Custom Schema processor which helps to implement dynamic security roles
*
* This software is subject to the terms of the Eclipse Public License v1.0
* Agreement, available at the following URL: http://www.eclipse.org/legal/epl-v10.html.
* You must accept the terms of that agreement to use this software.
*
* @author gmartano
* @since Jan 2016
* @version 1.0.0
*
*/
package com.mysample.mondrian.dsp;
import mondrian.olap.Util;
import mondrian.spi.*;
import mondrian.i18n.*;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.engine.core.system.PentahoSessionHolder;
import org.apache.log4j.Logger;
import java.io.InputStream;
import java.util.regex.PatternSyntaxException;
/* used to log to console for first debug purpose */
import static java.lang.System.out;
public class DynamicSchemaProcessor extends LocalizingDynamicSchemaProcessor {
private static final Logger LOG = Logger.getLogger(DynamicSchemaProcessor.class);
/** Creates a new instance of class */
public DynamicSchemaProcessor() {
}
@Override
public String filter(String schemaUrl, Util.PropertyList connectInfo, InputStream stream)
throws Exception {
String schema = super.filter(schemaUrl, connectInfo, stream);
System.out.println("[CUSTOM.DSP] *********** Started DSP Custom ***********");
IPentahoSession session = PentahoSessionHolder.getSession();
String usercode = (String) session.getAttribute("USERNAME");
try {
System.out.println("[CUSTOM.DSP] Trying to replace '%USER_NAME%' with session value: "+usercode);
LOG.info("Trying to replace '%USER_NAME%' with session value: "+usercode);
schema = schema.replaceAll("%USER_NAME%", usercode);
}
catch (PatternSyntaxException pse) {
System.out.println("[CUSTOM.DSP] Some error during custom schema processing: "+usercode);
LOG.error("Some error during custom schema processing. " , pse);
pse.printStackTrace();
}
LOG.info("DSP Ended correctly for "+usercode);
System.out.println("[CUSTOM.DSP] *********** DSP Ended correctly for "+usercode+" ***********");
return schema;
}
}
| Update DynamicSchemaProcessor.java | src/com/mysample/mondrian/dsp/DynamicSchemaProcessor.java | Update DynamicSchemaProcessor.java | <ide><path>rc/com/mysample/mondrian/dsp/DynamicSchemaProcessor.java
<ide> import org.apache.log4j.Logger;
<ide> import java.io.InputStream;
<ide> import java.util.regex.PatternSyntaxException;
<del>/* used to log to console for first debug purpose */
<add>/* used to log to console for debugging purpose */
<ide> import static java.lang.System.out;
<ide>
<ide> public class DynamicSchemaProcessor extends LocalizingDynamicSchemaProcessor { |
|
Java | mit | 936aeb29ae695fd9178028114dc3d074347ba8de | 0 | srarcbrsent/tc,srarcbrsent/tc,srarcbrsent/tc,srarcbrsent/tc | package com.ysu.zyw.tc.components.cache.codis.ops;
import com.ysu.zyw.tc.components.cache.TcAbstractOpsForGroupedValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.serializer.RedisSerializer;
import javax.annotation.Nonnull;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
@Slf4j
public class TcCodisOpsForGroupedValue extends TcAbstractOpsForGroupedValue implements ApplicationContextAware {
// this is only for lazy init tc codis server delegate, only the first call of keys or delete
// will lead to init tc codis server delegate, or sometimes this two api is useless, then
// the codis server delegate will never be init.
private ApplicationContext applicationContext;
@SuppressWarnings("unchecked")
@Override
public Set<String> keys(@Nonnull String group) {
checkNotNull(group, "empty group is not allowed");
// try merge all the master codis-server keys.
RedisSerializer<String> keySerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
TcCodisServerDelegate tcCodisServerDelegate = applicationContext.getBean(TcCodisServerDelegate.class);
Set<String> keys = new HashSet<>();
tcCodisServerDelegate.doInEveryCodisServer(connectionFactory -> {
byte[] sKey = keySerializer.serialize(GROUP_FIELD_PREFIX + group + GROUP_NAME_KEY_SPLIT + "*");
RedisConnection connection = connectionFactory.getConnection();
Set<byte[]> sValue = connection.keys(sKey);
int bSize = keys.size();
keys.addAll(sValue.stream().map(keySerializer::deserialize).collect(Collectors.toSet()));
log.info("from codis server [{}:{}] all load [{}] keys, current keys [{}]",
connectionFactory.getHostName(), connectionFactory.getPort(), keys.size() - bSize, keys.size());
});
return keys;
}
@SuppressWarnings("unchecked")
@Override
public void delete(@Nonnull String group) {
checkArgument(StringUtils.isNotBlank(group), "empty group is not allowed");
// try delete all the master codis-server keys.
RedisSerializer<String> keySerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
TcCodisServerDelegate tcCodisServerDelegate = applicationContext.getBean(TcCodisServerDelegate.class);
tcCodisServerDelegate.doInEveryCodisServer(connectionFactory -> {
byte[] sKey = keySerializer.serialize(GROUP_FIELD_PREFIX + group + GROUP_NAME_KEY_SPLIT + "*");
RedisConnection connection = connectionFactory.getConnection();
Set<byte[]> sValue = connection.keys(sKey);
Long delC = connection.del(sValue.toArray(new byte[sValue.size()][]));
log.info("from codis server [{}:{}] all del [{}] keys",
connectionFactory.getHostName(), connectionFactory.getPort(), delC);
});
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
| tc-components/src/main/java/com/ysu/zyw/tc/components/cache/codis/ops/TcCodisOpsForGroupedValue.java | package com.ysu.zyw.tc.components.cache.codis.ops;
import com.ysu.zyw.tc.components.cache.TcAbstractOpsForGroupedValue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.serializer.RedisSerializer;
import javax.annotation.Nonnull;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
@Slf4j
public class TcCodisOpsForGroupedValue extends TcAbstractOpsForGroupedValue implements ApplicationContextAware {
// this is only for lazy init tc codis server delegate, only the first call of keys or delete
// will lead to init tc codis server delegate, or sometimes this two api is useless, then
// the codis server delegate will never be init.
private ApplicationContext applicationContext;
@SuppressWarnings("unchecked")
@Override
public Set<String> keys(@Nonnull String group) {
checkNotNull(group, "empty group is not allowed");
// try merge all the master codis-server keys.
RedisSerializer<String> keySerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
TcCodisServerDelegate tcCodisServerDelegate = applicationContext.getBean(TcCodisServerDelegate.class);
Set<String> keys = new HashSet<>();
tcCodisServerDelegate.doInEveryCodisServer(connectionFactory -> {
byte[] sKey = keySerializer.serialize(GROUP_FIELD_PREFIX + group + GROUP_NAME_KEY_SPLIT + "*");
RedisConnection connection = connectionFactory.getConnection();
Set<byte[]> sValue = connection.keys(sKey);
int bSize = keys.size();
keys.addAll(sValue.stream().map(keySerializer::deserialize).collect(Collectors.toSet()));
log.info("from codis server [{}:{}] all load [{}] keys, current keys [{}]",
connectionFactory.getHostName(), connectionFactory.getPort(), keys.size() - bSize, keys.size());
});
return keys;
}
@SuppressWarnings("unchecked")
@Override
public void delete(@Nonnull String group) {
checkNotNull(group, "empty group is not allowed");
// try delete all the master codis-server keys.
RedisSerializer<String> keySerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
TcCodisServerDelegate tcCodisServerDelegate = applicationContext.getBean(TcCodisServerDelegate.class);
tcCodisServerDelegate.doInEveryCodisServer(connectionFactory -> {
byte[] sKey = keySerializer.serialize(GROUP_FIELD_PREFIX + group + GROUP_NAME_KEY_SPLIT + "*");
RedisConnection connection = connectionFactory.getConnection();
Set<byte[]> sValue = connection.keys(sKey);
Long delC = connection.del(sValue.toArray(new byte[sValue.size()][]));
log.info("from codis server [{}:{}] all del [{}] keys",
connectionFactory.getHostName(), connectionFactory.getPort(), delC);
});
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
| project optimize (58)
| tc-components/src/main/java/com/ysu/zyw/tc/components/cache/codis/ops/TcCodisOpsForGroupedValue.java | project optimize (58) | <ide><path>c-components/src/main/java/com/ysu/zyw/tc/components/cache/codis/ops/TcCodisOpsForGroupedValue.java
<ide>
<ide> import com.ysu.zyw.tc.components.cache.TcAbstractOpsForGroupedValue;
<ide> import lombok.extern.slf4j.Slf4j;
<add>import org.apache.commons.lang3.StringUtils;
<ide> import org.springframework.beans.BeansException;
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.context.ApplicationContextAware;
<ide> import java.util.Set;
<ide> import java.util.stream.Collectors;
<ide>
<add>import static com.google.common.base.Preconditions.checkArgument;
<ide> import static com.google.common.base.Preconditions.checkNotNull;
<ide>
<ide> @Slf4j
<ide> @SuppressWarnings("unchecked")
<ide> @Override
<ide> public void delete(@Nonnull String group) {
<del> checkNotNull(group, "empty group is not allowed");
<add> checkArgument(StringUtils.isNotBlank(group), "empty group is not allowed");
<ide> // try delete all the master codis-server keys.
<ide> RedisSerializer<String> keySerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
<ide> TcCodisServerDelegate tcCodisServerDelegate = applicationContext.getBean(TcCodisServerDelegate.class); |
|
Java | agpl-3.0 | abdfa8a9b326312371f701fed69a8722f247b49b | 0 | DeanWay/phenotips,veronikaslc/phenotips,DeanWay/phenotips,teyden/phenotips,JKereliuk/phenotips,danielpgross/phenotips,itaiGershtansky/phenotips,teyden/phenotips,teyden/phenotips,mjshepherd/phenotips,mjshepherd/phenotips,phenotips/phenotips,phenotips/phenotips,JKereliuk/phenotips,phenotips/phenotips,tmarathe/phenotips,danielpgross/phenotips,teyden/phenotips,mjshepherd/phenotips,phenotips/phenotips,danielpgross/phenotips,alexhenrie/phenotips,teyden/phenotips,alexhenrie/phenotips,phenotips/phenotips,itaiGershtansky/phenotips,veronikaslc/phenotips,DeanWay/phenotips,itaiGershtansky/phenotips,veronikaslc/phenotips,alexhenrie/phenotips,tmarathe/phenotips,tmarathe/phenotips,JKereliuk/phenotips | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.phenotips.data.internal;
import org.phenotips.Constants;
import org.phenotips.components.ComponentManagerRegistry;
import org.phenotips.data.Disorder;
import org.phenotips.data.Feature;
import org.phenotips.data.Patient;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.extension.distribution.internal.DistributionManager;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.DBStringListProperty;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* Implementation of patient data based on the XWiki data model, where patient data is represented by properties in
* objects of type {@code PhenoTips.PatientClass}.
*
* @version $Id$
* @since 1.0M8
*/
public class PhenoTipsPatient implements Patient
{
/** The default template for creating a new patient. */
public static final EntityReference TEMPLATE_REFERENCE = new EntityReference("PatientTemplate",
EntityType.DOCUMENT, Constants.CODE_SPACE_REFERENCE);
/** The default space where patient data is stored. */
public static final EntityReference DEFAULT_DATA_SPACE = new EntityReference("data", EntityType.SPACE);
/** Known phenotype properties. */
private static final String[] PHENOTYPE_PROPERTIES = new String[] {"phenotype", "negative_phenotype"};
/** Logging helper object. */
private Logger logger = LoggerFactory.getLogger(PhenoTipsPatient.class);
/** @see #getDocument() */
private DocumentReference document;
/** @see #getReporter() */
private DocumentReference reporter;
/** @see #getFeatures() */
private Set<Feature> features = new TreeSet<Feature>();
/** @see #getDisorders() */
private Set<Disorder> disorders = new TreeSet<Disorder>();
/** Holds the list of all ontology versions. */
private Map<String, String> versions = new HashMap<String, String>();
/**
* Constructor that copies the data from an XDocument.
*
* @param doc the XDocument representing this patient in XWiki
*/
public PhenoTipsPatient(XWikiDocument doc)
{
this.document = doc.getDocumentReference();
this.reporter = doc.getCreatorReference();
BaseObject data = doc.getXObject(CLASS_REFERENCE);
if (data == null) {
return;
}
try {
for (String property : PHENOTYPE_PROPERTIES) {
DBStringListProperty values = (DBStringListProperty) data.get(property);
if (values == null) {
continue;
}
for (String value : values.getList()) {
if (StringUtils.isNotBlank(value)) {
this.features.add(new PhenoTipsFeature(doc, values, value));
}
}
}
DBStringListProperty values = (DBStringListProperty) data.get("omim_id");
if (values != null) {
for (String value : values.getList()) {
if (StringUtils.isNotBlank(value)) {
this.disorders.add(new PhenoTipsDisorder(values, value));
}
}
}
} catch (XWikiException ex) {
this.logger.warn("Failed to access patient data for [{}]: {}", doc.getDocumentReference(), ex.getMessage(),
ex);
}
// Readonly from now on
this.features = Collections.unmodifiableSet(this.features);
this.disorders = Collections.unmodifiableSet(this.disorders);
this.setOntologiesVersions(doc);
}
private void setOntologiesVersions(XWikiDocument doc)
{
List<BaseObject> ontologyVersionObjects = doc.getXObjects(VERSION_REFERENCE);
if (ontologyVersionObjects == null) {
return;
}
for (BaseObject versionObject : ontologyVersionObjects) {
String versionType = versionObject.getStringValue("name");
String versionString = versionObject.getStringValue("version");
if (StringUtils.isNotEmpty(versionType) && StringUtils.isNotEmpty(versionString)) {
this.versions.put(versionType, versionString);
}
}
}
@Override
public DocumentReference getDocument()
{
return this.document;
}
@Override
public DocumentReference getReporter()
{
return this.reporter;
}
@Override
public Set<Feature> getFeatures()
{
return this.features;
}
@Override
public Set<Disorder> getDisorders()
{
return this.disorders;
}
@Override
public String toString()
{
return toJSON().toString(2);
}
@Override
public JSONObject toJSON()
{
JSONObject result = new JSONObject();
result.element("id", getDocument().getName());
if (getReporter() != null) {
result.element("reporter", getReporter().getName());
}
if (!this.features.isEmpty()) {
JSONArray featuresJSON = new JSONArray();
for (Feature phenotype : this.features) {
featuresJSON.add(phenotype.toJSON());
}
result.element("features", featuresJSON);
}
if (!this.disorders.isEmpty()) {
JSONArray diseasesJSON = new JSONArray();
for (Disorder disease : this.disorders) {
diseasesJSON.add(disease.toJSON());
}
result.element("disorders", diseasesJSON);
}
try {
DistributionManager distribution =
ComponentManagerRegistry.getContextComponentManager().getInstance(DistributionManager.class);
JSONObject versionsJSON = new JSONObject();
this.versions.put("phenotips_version",
distribution.getDistributionExtension().getId().getVersion().toString());
for (Map.Entry<String, String> version : this.versions.entrySet()) {
versionsJSON.element(version.getKey() + "_version", version.getValue());
}
result.element("versioning", versionsJSON);
} catch (ComponentLookupException ex) {
// Shouldn't happen, no worries.
this.logger.debug("Failed to access the DistributionManager component: {}", ex.getMessage(), ex);
}
return result;
}
}
| components/patient-data/api/src/main/java/org/phenotips/data/internal/PhenoTipsPatient.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.phenotips.data.internal;
import org.phenotips.Constants;
import org.phenotips.components.ComponentManagerRegistry;
import org.phenotips.data.Disorder;
import org.phenotips.data.Feature;
import org.phenotips.data.Patient;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.extension.distribution.internal.DistributionManager;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.DBStringListProperty;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* Implementation of patient data based on the XWiki data model, where patient data is represented by properties in
* objects of type {@code PhenoTips.PatientClass}.
*
* @version $Id$
* @since 1.0M8
*/
public class PhenoTipsPatient implements Patient
{
/** The default template for creating a new patient. */
public static final EntityReference TEMPLATE_REFERENCE = new EntityReference("PatientTemplate",
EntityType.DOCUMENT, Constants.CODE_SPACE_REFERENCE);
/** The default space where patient data is stored. */
public static final EntityReference DEFAULT_DATA_SPACE = new EntityReference("data", EntityType.SPACE);
/** Known phenotype properties. */
private static final String[] PHENOTYPE_PROPERTIES = new String[] {"phenotype", "negative_phenotype"};
/** Logging helper object. */
private Logger logger = LoggerFactory.getLogger(PhenoTipsPatient.class);
/** @see #getDocument() */
private DocumentReference document;
/** @see #getReporter() */
private DocumentReference reporter;
/** @see #getFeatures() */
private Set<Feature> features = new TreeSet<Feature>();
/** @see #getDisorders() */
private Set<Disorder> disorders = new TreeSet<Disorder>();
/** Holds the list of all ontology versions. */
private Map<String, String> versions = new HashMap<String, String>();
/**
* Constructor that copies the data from an XDocument.
*
* @param doc the XDocument representing this patient in XWiki
*/
public PhenoTipsPatient(XWikiDocument doc)
{
this.document = doc.getDocumentReference();
this.reporter = doc.getCreatorReference();
BaseObject data = doc.getXObject(CLASS_REFERENCE);
if (data == null) {
return;
}
try {
for (String property : PHENOTYPE_PROPERTIES) {
DBStringListProperty values = (DBStringListProperty) data.get(property);
if (values == null) {
continue;
}
for (String value : values.getList()) {
if (StringUtils.isNotBlank(value)) {
this.features.add(new PhenoTipsFeature(doc, values, value));
}
}
}
DBStringListProperty values = (DBStringListProperty) data.get("omim_id");
if (values != null) {
for (String value : values.getList()) {
if (StringUtils.isNotBlank(value)) {
this.disorders.add(new PhenoTipsDisorder(values, value));
}
}
}
} catch (XWikiException ex) {
this.logger.warn("Failed to access patient data for [{}]: {}", doc.getDocumentReference(), ex.getMessage(),
ex);
}
// Readonly from now on
this.features = Collections.unmodifiableSet(this.features);
this.disorders = Collections.unmodifiableSet(this.disorders);
this.setOntologiesVersions(doc);
}
private void setOntologiesVersions(XWikiDocument doc)
{
List<BaseObject> ontologyVersionObjects = doc.getXObjects(VERSION_REFERENCE);
if (ontologyVersionObjects == null) {
return;
}
for (BaseObject versionObject : ontologyVersionObjects) {
String versionType = versionObject.getStringValue("name");
String versionString = versionObject.getStringValue("version");
if (StringUtils.isNotEmpty(versionString)) {
this.versions.put(versionType, versionString);
}
}
}
@Override
public DocumentReference getDocument()
{
return this.document;
}
@Override
public DocumentReference getReporter()
{
return this.reporter;
}
@Override
public Set<Feature> getFeatures()
{
return this.features;
}
@Override
public Set<Disorder> getDisorders()
{
return this.disorders;
}
@Override
public String toString()
{
return toJSON().toString(2);
}
@Override
public JSONObject toJSON()
{
JSONObject result = new JSONObject();
result.element("id", getDocument().getName());
if (getReporter() != null) {
result.element("reporter", getReporter().getName());
}
if (!this.features.isEmpty()) {
JSONArray featuresJSON = new JSONArray();
for (Feature phenotype : this.features) {
featuresJSON.add(phenotype.toJSON());
}
result.element("features", featuresJSON);
}
if (!this.disorders.isEmpty()) {
JSONArray diseasesJSON = new JSONArray();
for (Disorder disease : this.disorders) {
diseasesJSON.add(disease.toJSON());
}
result.element("disorders", diseasesJSON);
}
try {
DistributionManager distribution =
ComponentManagerRegistry.getContextComponentManager().getInstance(DistributionManager.class);
JSONObject versionsJSON = new JSONObject();
this.versions.put("phenotips_version",
distribution.getDistributionExtension().getId().getVersion().toString());
for (Map.Entry<String, String> version : this.versions.entrySet()) {
versionsJSON.element(version.getKey(), version.getValue());
}
result.element("versioning", versionsJSON);
} catch (ComponentLookupException ex) {
// Shouldn't happen, no worries.
}
return result;
}
}
| Issue #693: Export the version of HPO used when recording the patient data in the patient's JSON export
Bulletproofing, changed the name of ontology versions to include a "_version" suffix, improved error handling
| components/patient-data/api/src/main/java/org/phenotips/data/internal/PhenoTipsPatient.java | Issue #693: Export the version of HPO used when recording the patient data in the patient's JSON export Bulletproofing, changed the name of ontology versions to include a "_version" suffix, improved error handling | <ide><path>omponents/patient-data/api/src/main/java/org/phenotips/data/internal/PhenoTipsPatient.java
<ide> for (BaseObject versionObject : ontologyVersionObjects) {
<ide> String versionType = versionObject.getStringValue("name");
<ide> String versionString = versionObject.getStringValue("version");
<del> if (StringUtils.isNotEmpty(versionString)) {
<add> if (StringUtils.isNotEmpty(versionType) && StringUtils.isNotEmpty(versionString)) {
<ide> this.versions.put(versionType, versionString);
<ide> }
<ide> }
<ide> this.versions.put("phenotips_version",
<ide> distribution.getDistributionExtension().getId().getVersion().toString());
<ide> for (Map.Entry<String, String> version : this.versions.entrySet()) {
<del> versionsJSON.element(version.getKey(), version.getValue());
<add> versionsJSON.element(version.getKey() + "_version", version.getValue());
<ide> }
<ide> result.element("versioning", versionsJSON);
<ide> } catch (ComponentLookupException ex) {
<ide> // Shouldn't happen, no worries.
<add> this.logger.debug("Failed to access the DistributionManager component: {}", ex.getMessage(), ex);
<ide> }
<ide> return result;
<ide> } |
|
JavaScript | bsd-3-clause | dfaa7238a6a86bbe90cfebb5d02e5f17e4605914 | 0 | openAgile/CommitStream.Web,JogoShugh/CommitStream.Web,JogoShugh/CommitStream.Web,openAgile/CommitStream.Web,openAgile/CommitStream.Web,JogoShugh/CommitStream.Web,openAgile/CommitStream.Web,JogoShugh/CommitStream.Web | (function(){
'use strict';
function CommitStreamAdminBoot(el) {
var persistentOptions = {
headers: { Bearer: '' }
};
var app = angular.module('commitStreamAdmin', ['commitStreamAdmin.config',
'angular-hal', 'ngRoute', 'ui.bootstrap','cgPrompt']);
app.config(['$sceProvider', '$sceDelegateProvider', function($sceProvider, $sceDelegateProvider) {
// $sceProvider.enabled(false);
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'https://v1commitstream.cloudapp.net/**'
]);
}]);
app.factory('CommitStreamApi', ['serviceUrl', 'halClient', function(serviceUrl, halClient) {
return {
'load' : function() {
return halClient.$get(serviceUrl + '/api/public', persistentOptions);
},
};
}]);
app.config(['serviceUrlProvider', '$routeProvider', function(serviceUrlProvider, $routeProvider) {
var serviceUrl = serviceUrlProvider.$get();
$routeProvider.when('/', {templateUrl: serviceUrl + '/partials/instances.html', controller: 'InstancesController'});
$routeProvider.when('/inboxes', {templateUrl: serviceUrl + '/partials/inboxes.html', controller: 'InboxesController'});
$routeProvider.otherwise({redirectTo: serviceUrl + '/'});
}]);
app.directive('resizableOverlay', function($window) {
return function($scope) {
return angular.element($window).bind('resize', function() {
$scope.adjustOverlay();
return $scope.$apply();
});
};
});
app.directive('toggleCheckbox', function($timeout) {
/**
* Directive
*/
return {
restrict: 'A',
transclude: true,
replace: false,
require: 'ngModel',
link: function ($scope, $element, $attr, ngModel) {
// update model from Element
var updateModelFromElement = function() {
// If modified
var checked = $element.prop('checked');
if (checked != ngModel.$viewValue) {
// Update ngModel
ngModel.$setViewValue(checked);
$scope.$apply();
}
};
// Update input from Model
var updateElementFromModel = function(newValue) {
$element.trigger('change');
};
// Observe: Element changes affect Model
$element.on('change', function() {
updateModelFromElement();
});
$scope.$watch(function() {
return ngModel.$viewValue;
}, function(newValue) {
updateElementFromModel(newValue);
}, true);
// Initialise BootstrapToggle
$element.bootstrapToggle();
}
};
});
app.controller('InstancesController',
['$rootScope', '$scope', '$http', '$location', 'CommitStreamApi', 'serviceUrl', 'configGetUrl', 'configSaveUrl',
function($rootScope, $scope, $http, $location, CommitStreamApi, serviceUrl, configGetUrl, configSaveUrl) {
var config;
$scope.loaderUrl = serviceUrl + '/ajax-loader.gif';
var loading = true;
$scope.loading = function() {
return loading;
};
var errorHandler = function(error) {
loading = false;
if (error.data && error.data.errors && error.data.errors.length) {
$scope.error.value = error.data.errors[0];
} else {
$scope.error.value = 'There was an unexpected error when processing your request.';
}
};
$scope.error = { value: ''};
$scope.errorActive = function() {
return $scope.error.value !== '';
};
CommitStreamApi
.load()
.then(function(resources) {
$rootScope.resources = resources;
if (!configGetUrl) return {
data: {
serviceUrl: serviceUrl,
instanceId: '',
apiKey: '',
globalDigestId: '',
configured: false,
enabled: false
}
}
return $http.get(configGetUrl);
})
.then(function(configRes) {
// TODO handle null case?
config = configRes.data;
$rootScope.config = config;
if (config.configured) {
persistentOptions.headers.Bearer = config.apiKey;
return $rootScope.resources.$get('instance', {instanceId: config.instanceId});
} else {
// return $rootScope.resources.$post('instances');
return false;
}
})
.then(function(instance) {
if (instance) {
persistentOptions.headers.Bearer = instance.apiKey; // Ensure apiKey for NEW instance
$rootScope.instance = instance;
if (config.configured) {
return $rootScope.resources.$get('digest', {
instanceId: config.instanceId,
digestId: config.globalDigestId
});
} else {
return instance.$post('digest-create', {}, {
description: 'Global Repositories List'
});
}
} else {
return false;
}
})
.then(function(digest) {
if (digest) {
$rootScope.digest = digest;
}
$location.path('/inboxes');
})
.catch(errorHandler);
}]
);
app.controller('InboxesController', ['$rootScope', '$scope', '$timeout', 'serviceUrl',
'configSaveUrl', '$http', '$q', 'prompt', '$location',
function($rootScope, $scope, $timeout, serviceUrl,
configSaveUrl, $http, $q, prompt, $location) {
$scope.inboxesVisible = function() {
// Only display when we actually have the config in $scope!
return $rootScope.config;
};
if (!$rootScope.config) {
$location.path('/');
return;
}
$scope.newInbox = {
url: '',
name: '',
family: 'GitHub' // Until we support other systems, hard-code this.
};
$scope.serviceUrl = serviceUrl;
$scope.inboxes = [];
$scope.enabledState = {
enabled: $rootScope.config.enabled,
applying: false,
onText: 'Enabled',
offText: 'Disabled'
};
$scope.message = { value: ''};
$scope.messageActive = function() {
return $scope.message.value !== '';
};
$scope.error = { value: ''};
$scope.errorActive = function() {
return $scope.error.value !== '';
};
// NOTE: this is a bit of a hack to remove errors upon network request to clear
// out the UI prompts
persistentOptions.transformUrl = function(url) {
$scope.error.value = '';
return url;
};
$scope.urlPattern = /^https?\:\/\/.{1,}\/.{1,}$/;
$scope.inboxName = function() {
if (!$scope.newInbox.url || $scope.newInbox.url.length < 1) return '...';
var index = $scope.newInbox.url.lastIndexOf('/');
if (index < 0) return '...';
if (index === $scope.newInbox.url.length - 1) return '...';
return $scope.newInbox.url.substr(index + 1);
};
var errorHandler = function(error) {
if (error.data && error.data.errors && error.data.errors.length) {
$scope.error.value = error.data.errors[0];
} else {
$scope.error.value = 'There was an unexpected error when processing your request.';
}
};
var configSave = function(enabled) {
$rootScope.config.enabled = enabled;
if (!$rootScope.config.configured) {
return $rootScope.resources.$post('instances')
.then(function(instance) {
persistentOptions.headers.Bearer = instance.apiKey; // Ensure apiKey for NEW instance
$rootScope.instance = instance;
return instance.$post('digest-create', {}, {
description: 'Global Repositories List'
});
})
.then(function(digest) {
$rootScope.digest = digest;
$rootScope.config.instanceId = $rootScope.instance.instanceId;
$rootScope.config.globalDigestId = digest.digestId;
$rootScope.config.apiKey = $rootScope.instance.apiKey;
$rootScope.config.configured = true;
if (configSaveUrl) return $http.post(configSaveUrl, $rootScope.config);
return $q.when(true);
});
} else {
if (configSaveUrl) return $http.post(configSaveUrl, $rootScope.config);
return $q.when(true);
}
};
var inboxConfigure = function(inbox) {
var links = inbox.$links();
inbox.addCommit = links['add-commit'].href + '?apiKey=' + persistentOptions.headers.Bearer;
inbox.removeHref = links['self'].href + '?apiKey=' + persistentOptions.headers.Bearer;
};
var inboxesGet = function() {
if ($rootScope.digest) {
$rootScope.digest.$get('inboxes')
.then(function(inboxesRes) {
return inboxesRes.$get('inboxes');
}).then(function(inboxes) {
$scope.inboxes.length = 0;
inboxes.forEach(function(inbox) {
inboxConfigure(inbox);
$scope.inboxes.unshift(inbox);
});
})
.catch(errorHandler);
}
};
var inboxesUpdate = function(enabled) {
if (enabled) {
$('.inbox-url').select().focus();
}
inboxesGet();
}
inboxesUpdate($rootScope.config.enabled);
$scope.enabledChanged = function() {
$scope.newInbox.url = '';
var toggle = $('.commitstream-admin .enabled');
var enabled = toggle.prop('checked');
$scope.enabledState.applying = true;
toggle.bootstrapToggle('disable');
configSave(enabled).then(function(configSaveResult) {
// TODO need to handle configSaveResult?
inboxesUpdate(enabled);
})
.catch(errorHandler)
.finally(function() {
$scope.enabledState.applying = false;
toggle.bootstrapToggle('enable');
});
};
$scope.applying = function() {
return $scope.enabledState.applying;
};
$scope.overlayVisible = function() {
return $scope.enabledState.applying ||!$rootScope.config.enabled;
};
$scope.adjustOverlay = function() {
var repolistWidth = $('.repos-list').width();
var repolistHeight = $('.repos-list').height();
$('.repos-section .overlay').height(repolistHeight);
$('.repos-section .overlay').width(repolistWidth);
};
// A jQuery based way of handling resizing of the window to adjust the overlay
// when CS is disabled.
// $(window).resize(function(){
// $scope.adjustOverlay();
// });
$scope.inboxCreate = function() {
var index = $scope.newInbox.url.lastIndexOf('/');
$scope.newInbox.name = $scope.newInbox.url.substr(index + 1);
$rootScope.digest.$post('inbox-create', {}, $scope.newInbox)
.then(function(inbox) {
inboxConfigure(inbox);
$scope.inboxes.unshift(inbox);
$scope.newInbox.url = '';
$scope.inboxHighlightTop(inbox.removeHref);
})
.catch(errorHandler);
};
$scope.inboxRemove = function(inbox) {
prompt({
title: 'Remove Repository?',
message: 'Are you sure you want to remove the repository ' + inbox.name + '?',
buttons: [
{ label:'Remove',
primary: true,
class: 'action-remove'
},
{
label:'Cancel',
cancel: true,
class: 'action-cancel'
}
]
}).then(function() {
inbox.$del('self').then(function(result) {
$scope.message.value = 'Successfully removed repository';
var index = $scope.inboxes.indexOf(inbox);
$scope.inboxes.splice(index, 1);
$timeout(function() {
$('.commitstream-admin .message').fadeOut('slow', function() {
$scope.message.value = '';
});
}, 4000);
})
.catch(errorHandler);
});
};
var inboxHighlight = function(el) {
if ($rootScope.config.enabled) {
el.focus();
el.select();
}
};
$scope.inboxHighlight = function(evt) {
inboxHighlight(evt.currentTarget);
};
$scope.inboxHighlightTop = function() {
$timeout(function() {
var el = $($('.commitstream-admin .inbox')[0]);
inboxHighlight(el);
}, 0);
};
}]);
angular.bootstrap(el, ['commitStreamAdmin']);
};
window.CommitStreamAdminBoot = CommitStreamAdminBoot;
}()); | src/app/client/js/admin.js | (function(){
'use strict';
function CommitStreamAdminBoot(el) {
var persistentOptions = {
headers: { Bearer: '' }
};
var app = angular.module('commitStreamAdmin', ['commitStreamAdmin.config',
'angular-hal', 'ngRoute', 'ui.bootstrap','cgPrompt']);
app.config(['$sceProvider', '$sceDelegateProvider', function($sceProvider, $sceDelegateProvider) {
$sceProvider.enabled(false);
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'https://v1commitstream.cloudapp.net/**'
]);
}]);
app.factory('CommitStreamApi', ['serviceUrl', 'halClient', function(serviceUrl, halClient) {
return {
'load' : function() {
return halClient.$get(serviceUrl + '/api/public', persistentOptions);
},
};
}]);
app.config(['serviceUrlProvider', '$routeProvider', function(serviceUrlProvider, $routeProvider) {
var serviceUrl = serviceUrlProvider.$get();
$routeProvider.when('/', {templateUrl: serviceUrl + '/partials/instances.html', controller: 'InstancesController'});
$routeProvider.when('/inboxes', {templateUrl: serviceUrl + '/partials/inboxes.html', controller: 'InboxesController'});
$routeProvider.otherwise({redirectTo: serviceUrl + '/'});
}]);
app.directive('resizableOverlay', function($window) {
return function($scope) {
return angular.element($window).bind('resize', function() {
$scope.adjustOverlay();
return $scope.$apply();
});
};
});
app.directive('toggleCheckbox', function($timeout) {
/**
* Directive
*/
return {
restrict: 'A',
transclude: true,
replace: false,
require: 'ngModel',
link: function ($scope, $element, $attr, ngModel) {
// update model from Element
var updateModelFromElement = function() {
// If modified
var checked = $element.prop('checked');
if (checked != ngModel.$viewValue) {
// Update ngModel
ngModel.$setViewValue(checked);
$scope.$apply();
}
};
// Update input from Model
var updateElementFromModel = function(newValue) {
$element.trigger('change');
};
// Observe: Element changes affect Model
$element.on('change', function() {
updateModelFromElement();
});
$scope.$watch(function() {
return ngModel.$viewValue;
}, function(newValue) {
updateElementFromModel(newValue);
}, true);
// Initialise BootstrapToggle
$element.bootstrapToggle();
}
};
});
app.controller('InstancesController',
['$rootScope', '$scope', '$http', '$location', 'CommitStreamApi', 'serviceUrl', 'configGetUrl', 'configSaveUrl',
function($rootScope, $scope, $http, $location, CommitStreamApi, serviceUrl, configGetUrl, configSaveUrl) {
var config;
$scope.loaderUrl = serviceUrl + '/ajax-loader.gif';
var loading = true;
$scope.loading = function() {
return loading;
};
var errorHandler = function(error) {
loading = false;
if (error.data && error.data.errors && error.data.errors.length) {
$scope.error.value = error.data.errors[0];
} else {
$scope.error.value = 'There was an unexpected error when processing your request.';
}
};
$scope.error = { value: ''};
$scope.errorActive = function() {
return $scope.error.value !== '';
};
CommitStreamApi
.load()
.then(function(resources) {
$rootScope.resources = resources;
if (!configGetUrl) return {
data: {
serviceUrl: serviceUrl,
instanceId: '',
apiKey: '',
globalDigestId: '',
configured: false,
enabled: false
}
}
return $http.get(configGetUrl);
})
.then(function(configRes) {
// TODO handle null case?
config = configRes.data;
$rootScope.config = config;
if (config.configured) {
persistentOptions.headers.Bearer = config.apiKey;
return $rootScope.resources.$get('instance', {instanceId: config.instanceId});
} else {
// return $rootScope.resources.$post('instances');
return false;
}
})
.then(function(instance) {
if (instance) {
persistentOptions.headers.Bearer = instance.apiKey; // Ensure apiKey for NEW instance
$rootScope.instance = instance;
if (config.configured) {
return $rootScope.resources.$get('digest', {
instanceId: config.instanceId,
digestId: config.globalDigestId
});
} else {
return instance.$post('digest-create', {}, {
description: 'Global Repositories List'
});
}
} else {
return false;
}
})
.then(function(digest) {
if (digest) {
$rootScope.digest = digest;
}
$location.path('/inboxes');
})
.catch(errorHandler);
}]
);
app.controller('InboxesController', ['$rootScope', '$scope', '$timeout', 'serviceUrl',
'configSaveUrl', '$http', '$q', 'prompt', '$location',
function($rootScope, $scope, $timeout, serviceUrl,
configSaveUrl, $http, $q, prompt, $location) {
$scope.inboxesVisible = function() {
// Only display when we actually have the config in $scope!
return $rootScope.config;
};
if (!$rootScope.config) {
$location.path('/');
return;
}
$scope.newInbox = {
url: '',
name: '',
family: 'GitHub' // Until we support other systems, hard-code this.
};
$scope.serviceUrl = serviceUrl;
$scope.inboxes = [];
$scope.enabledState = {
enabled: $rootScope.config.enabled,
applying: false,
onText: 'Enabled',
offText: 'Disabled'
};
$scope.message = { value: ''};
$scope.messageActive = function() {
return $scope.message.value !== '';
};
$scope.error = { value: ''};
$scope.errorActive = function() {
return $scope.error.value !== '';
};
// NOTE: this is a bit of a hack to remove errors upon network request to clear
// out the UI prompts
persistentOptions.transformUrl = function(url) {
$scope.error.value = '';
return url;
};
$scope.urlPattern = /^https?\:\/\/.{1,}\/.{1,}$/;
$scope.inboxName = function() {
if (!$scope.newInbox.url || $scope.newInbox.url.length < 1) return '...';
var index = $scope.newInbox.url.lastIndexOf('/');
if (index < 0) return '...';
if (index === $scope.newInbox.url.length - 1) return '...';
return $scope.newInbox.url.substr(index + 1);
};
var errorHandler = function(error) {
if (error.data && error.data.errors && error.data.errors.length) {
$scope.error.value = error.data.errors[0];
} else {
$scope.error.value = 'There was an unexpected error when processing your request.';
}
};
var configSave = function(enabled) {
$rootScope.config.enabled = enabled;
if (!$rootScope.config.configured) {
return $rootScope.resources.$post('instances')
.then(function(instance) {
persistentOptions.headers.Bearer = instance.apiKey; // Ensure apiKey for NEW instance
$rootScope.instance = instance;
return instance.$post('digest-create', {}, {
description: 'Global Repositories List'
});
})
.then(function(digest) {
$rootScope.digest = digest;
$rootScope.config.instanceId = $rootScope.instance.instanceId;
$rootScope.config.globalDigestId = digest.digestId;
$rootScope.config.apiKey = $rootScope.instance.apiKey;
$rootScope.config.configured = true;
if (configSaveUrl) return $http.post(configSaveUrl, $rootScope.config);
return $q.when(true);
});
} else {
if (configSaveUrl) return $http.post(configSaveUrl, $rootScope.config);
return $q.when(true);
}
};
var inboxConfigure = function(inbox) {
var links = inbox.$links();
inbox.addCommit = links['add-commit'].href + '?apiKey=' + persistentOptions.headers.Bearer;
inbox.removeHref = links['self'].href + '?apiKey=' + persistentOptions.headers.Bearer;
};
var inboxesGet = function() {
if ($rootScope.digest) {
$rootScope.digest.$get('inboxes')
.then(function(inboxesRes) {
return inboxesRes.$get('inboxes');
}).then(function(inboxes) {
$scope.inboxes.length = 0;
inboxes.forEach(function(inbox) {
inboxConfigure(inbox);
$scope.inboxes.unshift(inbox);
});
})
.catch(errorHandler);
}
};
var inboxesUpdate = function(enabled) {
if (enabled) {
$('.inbox-url').select().focus();
}
inboxesGet();
}
inboxesUpdate($rootScope.config.enabled);
$scope.enabledChanged = function() {
$scope.newInbox.url = '';
var toggle = $('.commitstream-admin .enabled');
var enabled = toggle.prop('checked');
$scope.enabledState.applying = true;
toggle.bootstrapToggle('disable');
configSave(enabled).then(function(configSaveResult) {
// TODO need to handle configSaveResult?
inboxesUpdate(enabled);
})
.catch(errorHandler)
.finally(function() {
$scope.enabledState.applying = false;
toggle.bootstrapToggle('enable');
});
};
$scope.applying = function() {
return $scope.enabledState.applying;
};
$scope.overlayVisible = function() {
return $scope.enabledState.applying ||!$rootScope.config.enabled;
};
$scope.adjustOverlay = function() {
var repolistWidth = $('.repos-list').width();
var repolistHeight = $('.repos-list').height();
$('.repos-section .overlay').height(repolistHeight);
$('.repos-section .overlay').width(repolistWidth);
};
// A jQuery based way of handling resizing of the window to adjust the overlay
// when CS is disabled.
// $(window).resize(function(){
// $scope.adjustOverlay();
// });
$scope.inboxCreate = function() {
var index = $scope.newInbox.url.lastIndexOf('/');
$scope.newInbox.name = $scope.newInbox.url.substr(index + 1);
$rootScope.digest.$post('inbox-create', {}, $scope.newInbox)
.then(function(inbox) {
inboxConfigure(inbox);
$scope.inboxes.unshift(inbox);
$scope.newInbox.url = '';
$scope.inboxHighlightTop(inbox.removeHref);
})
.catch(errorHandler);
};
$scope.inboxRemove = function(inbox) {
prompt({
title: 'Remove Repository?',
message: 'Are you sure you want to remove the repository ' + inbox.name + '?',
buttons: [
{ label:'Remove',
primary: true,
class: 'action-remove'
},
{
label:'Cancel',
cancel: true,
class: 'action-cancel'
}
]
}).then(function() {
inbox.$del('self').then(function(result) {
$scope.message.value = 'Successfully removed repository';
var index = $scope.inboxes.indexOf(inbox);
$scope.inboxes.splice(index, 1);
$timeout(function() {
$('.commitstream-admin .message').fadeOut('slow', function() {
$scope.message.value = '';
});
}, 4000);
})
.catch(errorHandler);
});
};
var inboxHighlight = function(el) {
if ($rootScope.config.enabled) {
el.focus();
el.select();
}
};
$scope.inboxHighlight = function(evt) {
inboxHighlight(evt.currentTarget);
};
$scope.inboxHighlightTop = function() {
$timeout(function() {
var el = $($('.commitstream-admin .inbox')[0]);
inboxHighlight(el);
}, 0);
};
}]);
angular.bootstrap(el, ['commitStreamAdmin']);
};
window.CommitStreamAdminBoot = CommitStreamAdminBoot;
}()); | S-52318: ditto
| src/app/client/js/admin.js | S-52318: ditto | <ide><path>rc/app/client/js/admin.js
<ide> var app = angular.module('commitStreamAdmin', ['commitStreamAdmin.config',
<ide> 'angular-hal', 'ngRoute', 'ui.bootstrap','cgPrompt']);
<ide> app.config(['$sceProvider', '$sceDelegateProvider', function($sceProvider, $sceDelegateProvider) {
<del> $sceProvider.enabled(false);
<add> // $sceProvider.enabled(false);
<ide> $sceDelegateProvider.resourceUrlWhitelist([
<ide> 'self',
<ide> 'https://v1commitstream.cloudapp.net/**' |
|
Java | apache-2.0 | c8d04e5df3f52c567d9992a364115478d4489072 | 0 | isururanawaka/disruptor,epickrram/disruptor,AllenRay/disruptor,epickrram/disruptor,biddyweb/disruptor,isururanawaka/disruptor,Spikhalskiy/disruptor,isururanawaka/disruptor,hejunbinlan/disruptor,iacdingping/disruptor,fengshao0907/disruptor,LMAX-Exchange/disruptor,killbug2004/disruptor,azureplus/disruptor,eclipseek/disruptor,HappyYang/disruptor,cherrydocker/disruptor,pengzj/disruptor,sgulinski/disruptor,sgulinski/disruptor,jasonchaffee/disruptor,adamweixuan/disruptor,DerekYangYC/disruptor,chanakaudaya/disruptor,eliocapelati/disruptor,vvertigo/disruptor,qiaochao911/disruptor,brennangaunce/disruptor,simmeryson/MyDisruptor,pengzj/disruptor,newsky/disruptor,xiexingguang/disruptor,midnight0532/read-disruptor,epickrram/disruptor,vvertigo/disruptor,tharanga-abeyseela/disruptor,tharanga-abeyseela/disruptor,sgulinski/disruptor,fengshao0907/disruptor,eclipseek/disruptor,DerekYangYC/disruptor,cherrydocker/disruptor,AllenRay/disruptor,brennangaunce/disruptor,hejunbinlan/disruptor,LMAX-Exchange/disruptor,adamweixuan/disruptor,jasonchaffee/disruptor,vvertigo/disruptor,eliocapelati/disruptor,xiexingguang/disruptor,killbug2004/disruptor,qiaochao911/disruptor,eliocapelati/disruptor,newsky/disruptor,killbug2004/disruptor,Spikhalskiy/disruptor,biddyweb/disruptor,chanakaudaya/disruptor,midnight0532/read-disruptor,DerekYangYC/disruptor,biddyweb/disruptor,adamweixuan/disruptor,chanakaudaya/disruptor,azureplus/disruptor,hejunbinlan/disruptor,HappyYang/disruptor,tharanga-abeyseela/disruptor,brennangaunce/disruptor,jasonchaffee/disruptor,AllenRay/disruptor,HappyYang/disruptor,eclipseek/disruptor,Spikhalskiy/disruptor,cherrydocker/disruptor,fengshao0907/disruptor,midnight0532/read-disruptor,iacdingping/disruptor,iacdingping/disruptor,newsky/disruptor,xiexingguang/disruptor,pengzj/disruptor,qiaochao911/disruptor,azureplus/disruptor,simmeryson/MyDisruptor | /*
* Copyright 2011 LMAX Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lmax.disruptor;
import static com.lmax.disruptor.Util.getMinimumSequence;
/**
* Strategies employed for claiming the sequence of events in the {@link RingBuffer} by publishers.
*/
public interface ClaimStrategy
{
/**
* Claim the next sequence index in the {@link RingBuffer} and increment.
*
* @return the event index to be used for the publisher.
*/
long incrementAndGet();
/**
* Increment by a delta and get the result.
*
* @param delta to increment by.
* @return the result after incrementing.
*/
long incrementAndGet(final int delta);
/**
* Set the current sequence value for claiming an event in the {@link RingBuffer}
*
* @param sequence to be set as the current value.
*/
void setSequence(final long sequence);
/**
* Ensure dependent processors are in range without over taking them for the buffer size.
*
* @param sequence to check is in range
* @param dependentSequences to be checked for range.
*/
void ensureProcessorsAreInRange(final long sequence, final Sequence[] dependentSequences);
/**
* Serialise publishing in sequence.
*
* @param cursor to serialise against.
* @param sequence sequence to be applied
* @param batchSize of the sequence.
*/
void serialisePublishing(final Sequence cursor, final long sequence, final long batchSize);
/**
* Indicates the threading policy to be applied for claiming events by publisher to the {@link RingBuffer}
*/
enum Option
{
/** Makes the {@link RingBuffer} thread safe for claiming events by multiple producing threads. */
MULTI_THREADED
{
@Override
public ClaimStrategy newInstance(final int bufferSize)
{
return new MultiThreadedStrategy(bufferSize);
}
},
/** Optimised {@link RingBuffer} for use by single thread claiming events as a publisher. */
SINGLE_THREADED
{
@Override
public ClaimStrategy newInstance(final int bufferSize)
{
return new SingleThreadedStrategy(bufferSize);
}
};
/**
* Used by the {@link RingBuffer} as a polymorphic constructor.
*
* @param bufferSize of the {@link RingBuffer} for events.
* @return a new instance of the ClaimStrategy
*/
abstract ClaimStrategy newInstance(final int bufferSize);
}
/**
* Strategy to be used when there are multiple publisher threads claiming events.
*/
static final class MultiThreadedStrategy
implements ClaimStrategy
{
private final int bufferSize;
private final PaddedAtomicLong sequence = new PaddedAtomicLong();
private final PaddedAtomicLong minProcessorSequence = new PaddedAtomicLong();
public MultiThreadedStrategy(final int bufferSize)
{
this.bufferSize = bufferSize;
sequence.lazySet(RingBuffer.INITIAL_CURSOR_VALUE);
minProcessorSequence.lazySet(RingBuffer.INITIAL_CURSOR_VALUE);
}
@Override
public long incrementAndGet()
{
return sequence.incrementAndGet();
}
@Override
public long incrementAndGet(final int delta)
{
return sequence.addAndGet(delta);
}
@Override
public void setSequence(final long sequence)
{
this.sequence.lazySet(sequence);
}
@Override
public void ensureProcessorsAreInRange(final long sequence, final Sequence[] dependentSequences)
{
final long wrapPoint = sequence - bufferSize;
if (wrapPoint > minProcessorSequence.get())
{
long minSequence;
while (wrapPoint > (minSequence = getMinimumSequence(dependentSequences)))
{
Thread.yield();
}
minProcessorSequence.lazySet(minSequence);
}
}
@Override
public void serialisePublishing(final Sequence cursor, final long sequence, final long batchSize)
{
final long expectedSequence = sequence - batchSize;
int counter = 1000;
while (expectedSequence != cursor.get())
{
if (0 == --counter)
{
counter = 1000;
Thread.yield();
}
}
}
}
/**
* Optimised strategy can be used when there is a single publisher thread claiming events.
*/
static final class SingleThreadedStrategy
implements ClaimStrategy
{
private final int SEQ_INDEX = 7;
private final int bufferSize;
private final long[] sequence = new long[15]; // cache line padded
private final long[] minProcessorSequence = new long[15]; // cache line padded
public SingleThreadedStrategy(final int bufferSize)
{
this.bufferSize = bufferSize;
sequence[SEQ_INDEX] = RingBuffer.INITIAL_CURSOR_VALUE;
minProcessorSequence[SEQ_INDEX] = RingBuffer.INITIAL_CURSOR_VALUE;
}
@Override
public long incrementAndGet()
{
long value = sequence[SEQ_INDEX] + 1L;
sequence[SEQ_INDEX] = value;
return value;
}
@Override
public long incrementAndGet(final int delta)
{
long value = sequence[SEQ_INDEX] + delta;
sequence[SEQ_INDEX] = value;
return value;
}
@Override
public void setSequence(final long sequence)
{
this.sequence[SEQ_INDEX] = sequence;
}
@Override
public void ensureProcessorsAreInRange(final long sequence, final Sequence[] dependentSequences)
{
final long wrapPoint = sequence - bufferSize;
if (wrapPoint > minProcessorSequence[SEQ_INDEX])
{
long minSequence;
while (wrapPoint > (minSequence = getMinimumSequence(dependentSequences)))
{
Thread.yield();
}
minProcessorSequence[SEQ_INDEX] = minSequence;
}
}
@Override
public void serialisePublishing(final Sequence cursor, final long sequence, final long batchSize)
{
}
}
}
| code/src/main/com/lmax/disruptor/ClaimStrategy.java | /*
* Copyright 2011 LMAX Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lmax.disruptor;
import static com.lmax.disruptor.Util.getMinimumSequence;
/**
* Strategies employed for claiming the sequence of events in the {@link RingBuffer} by publishers.
*/
public interface ClaimStrategy
{
/**
* Claim the next sequence index in the {@link RingBuffer} and increment.
*
* @return the event index to be used for the publisher.
*/
long incrementAndGet();
/**
* Increment by a delta and get the result.
*
* @param delta to increment by.
* @return the result after incrementing.
*/
long incrementAndGet(final int delta);
/**
* Set the current sequence value for claiming an event in the {@link RingBuffer}
*
* @param sequence to be set as the current value.
*/
void setSequence(final long sequence);
/**
* Ensure dependent processors are in range without over taking them for the buffer size.
*
* @param sequence to check is in range
* @param dependentSequences to be checked for range.
*/
void ensureProcessorsAreInRange(final long sequence, final Sequence[] dependentSequences);
/**
* Serialise publishing in sequence.
*
* @param cursor to serialise against.
* @param sequence sequence to be applied
* @param batchSize of the sequence.
*/
void serialisePublishing(final Sequence cursor, final long sequence, final long batchSize);
/**
* Indicates the threading policy to be applied for claiming events by publisher to the {@link RingBuffer}
*/
enum Option
{
/** Makes the {@link RingBuffer} thread safe for claiming events by multiple producing threads. */
MULTI_THREADED
{
@Override
public ClaimStrategy newInstance(final int bufferSize)
{
return new MultiThreadedStrategy(bufferSize);
}
},
/** Optimised {@link RingBuffer} for use by single thread claiming events as a publisher. */
SINGLE_THREADED
{
@Override
public ClaimStrategy newInstance(final int bufferSize)
{
return new SingleThreadedStrategy(bufferSize);
}
};
/**
* Used by the {@link RingBuffer} as a polymorphic constructor.
*
* @param bufferSize of the {@link RingBuffer} for events.
* @return a new instance of the ClaimStrategy
*/
abstract ClaimStrategy newInstance(final int bufferSize);
}
/**
* Strategy to be used when there are multiple publisher threads claiming events.
*/
static final class MultiThreadedStrategy
implements ClaimStrategy
{
private final int bufferSize;
private final PaddedAtomicLong sequence = new PaddedAtomicLong();
private final PaddedAtomicLong minProcessorSequence = new PaddedAtomicLong();
public MultiThreadedStrategy(final int bufferSize)
{
this.bufferSize = bufferSize;
sequence.lazySet(RingBuffer.INITIAL_CURSOR_VALUE);
minProcessorSequence.lazySet(RingBuffer.INITIAL_CURSOR_VALUE);
}
@Override
public long incrementAndGet()
{
return sequence.incrementAndGet();
}
@Override
public long incrementAndGet(final int delta)
{
return sequence.addAndGet(delta);
}
@Override
public void setSequence(final long sequence)
{
this.sequence.lazySet(sequence);
}
@Override
public void ensureProcessorsAreInRange(final long sequence, final Sequence[] dependentSequences)
{
final long wrapPoint = sequence - bufferSize;
if (wrapPoint > minProcessorSequence.get())
{
long minSequence;
while (wrapPoint > (minSequence = getMinimumSequence(dependentSequences)))
{
Thread.yield();
}
minProcessorSequence.lazySet(minSequence);
}
}
@Override
public void serialisePublishing(final Sequence cursor, final long sequence, final long batchSize)
{
final long expectedSequence = sequence - batchSize;
int counter = 1000;
while (expectedSequence != cursor.get())
{
if (0 == --counter)
{
counter = 1000;
Thread.yield();
}
}
}
}
/**
* Optimised strategy can be used when there is a single publisher thread claiming events.
*/
static final class SingleThreadedStrategy
implements ClaimStrategy
{
private final int SEQ_INDEX = 7;
private final int bufferSize;
private final long[] sequence = new long[15]; // cache line padded
private long minProcessorSequence = RingBuffer.INITIAL_CURSOR_VALUE;
public SingleThreadedStrategy(final int bufferSize)
{
this.bufferSize = bufferSize;
sequence[SEQ_INDEX] = RingBuffer.INITIAL_CURSOR_VALUE;
}
@Override
public long incrementAndGet()
{
long value = sequence[SEQ_INDEX] + 1L;
sequence[SEQ_INDEX] = value;
return value;
}
@Override
public long incrementAndGet(final int delta)
{
long value = sequence[SEQ_INDEX] + delta;
sequence[SEQ_INDEX] = value;
return value;
}
@Override
public void setSequence(final long sequence)
{
this.sequence[SEQ_INDEX] = sequence;
}
@Override
public void ensureProcessorsAreInRange(final long sequence, final Sequence[] dependentSequences)
{
final long wrapPoint = sequence - bufferSize;
if (wrapPoint > minProcessorSequence)
{
long minSequence;
while (wrapPoint > (minSequence = getMinimumSequence(dependentSequences)))
{
Thread.yield();
}
minProcessorSequence = minSequence;
}
}
@Override
public void serialisePublishing(final Sequence cursor, final long sequence, final long batchSize)
{
}
}
}
| Add padding to prevent false sharing on minProcessorSequence field. Unicast can now do 50m+ events per second :-)
| code/src/main/com/lmax/disruptor/ClaimStrategy.java | Add padding to prevent false sharing on minProcessorSequence field. Unicast can now do 50m+ events per second :-) | <ide><path>ode/src/main/com/lmax/disruptor/ClaimStrategy.java
<ide> private final int SEQ_INDEX = 7;
<ide> private final int bufferSize;
<ide> private final long[] sequence = new long[15]; // cache line padded
<del> private long minProcessorSequence = RingBuffer.INITIAL_CURSOR_VALUE;
<add> private final long[] minProcessorSequence = new long[15]; // cache line padded
<ide>
<ide> public SingleThreadedStrategy(final int bufferSize)
<ide> {
<ide> this.bufferSize = bufferSize;
<ide> sequence[SEQ_INDEX] = RingBuffer.INITIAL_CURSOR_VALUE;
<add> minProcessorSequence[SEQ_INDEX] = RingBuffer.INITIAL_CURSOR_VALUE;
<ide> }
<ide>
<ide> @Override
<ide> public void ensureProcessorsAreInRange(final long sequence, final Sequence[] dependentSequences)
<ide> {
<ide> final long wrapPoint = sequence - bufferSize;
<del> if (wrapPoint > minProcessorSequence)
<add> if (wrapPoint > minProcessorSequence[SEQ_INDEX])
<ide> {
<ide> long minSequence;
<ide> while (wrapPoint > (minSequence = getMinimumSequence(dependentSequences)))
<ide> Thread.yield();
<ide> }
<ide>
<del> minProcessorSequence = minSequence;
<add> minProcessorSequence[SEQ_INDEX] = minSequence;
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 16e922c64a88d25aba733ca3329f8cd118aa92fb | 0 | genedelisa/rockymusic | package com.rockhoppertech.music;
/*
* #%L
* Rocky Music Core
* %%
* Copyright (C) 1996 - 2013 Rockhopper Technologies
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.Serializable;
import java.util.Comparator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* A representation of musical frequency (Pitch).
* <p>
* <p>
* Internally represented by a midi number. The frequency is calculated based on
* the MIDI number.
* </p>
*
* See http://en.wikipedia.org/wiki/Scientific_pitch_notation
*
* For MusicXML, Common Lisp Music and others the octave is "off" by 1. In MIDI
* middle c is C5, for them it is C4.
*
* <p>
* For equal temperament you should use the PitchFactory to obtain instances a
* la the GoF Flyweight design pattern. (Most likely you will have zillions of
* instances of Pitch in your program. The Flyweight helps this problem).
* </p>
*
*
* @author <a href="http://genedelisa.com/">Gene De Lisa</a>
* @version 1.0 Mon Aug 10, 1998
* @see com.rockhoppertech.music.PitchFactory
* @see com.rockhoppertech.music.PitchFormat
*/
public class Pitch implements Serializable, Comparable<Pitch> {
/**
*
*/
private static final long serialVersionUID = -4983186242989608159L;
private static final Logger logger = LoggerFactory
.getLogger(Pitch.class);
/**
* The main datum.
*/
private int midiNumber;
private String preferredSpelling;
private short cents;
/**
* Equal temperament frequency for the midiNumber
*/
private double frequency;
/**
* 0 if not microtonal
*/
private short pitchBend;
/**
* middle c or 261.6255653005986 hz Used to calculate the frequency.
*/
public static final double REF_PITCH = 220d * Math.pow(2d,
(3d / 12d));
/**
* <p>
* Use the PitchFactory to get an instance instead. Use this only in special
* circumstances
* </p>
* <p>
* Midi number will be 0.
* </p>
*/
public Pitch() {
this(0);
}
/**
* <p>
* Use the PitchFactory to get an instance instead. Use this only in special
* circumstances
* </p>
* <p>
* Can use a constant.
* <p>
*
* {@code
* new Pitch(Pitch.C5);
* }
*
* @param n
* the midi number to use. 60 is middle c.
*/
public Pitch(int n) {
if (n < 0 || n > 127) {
throw new IllegalArgumentException("MIDI number out of range " + n);
}
midiNumber = n;
// this.frequency = Pitch.midiFq(this.midiNumber);
frequency = PitchFactory.EQUAL_TEMPERAMENT.get(midiNumber);
this.preferredSpelling = PitchFormat.getInstance().format(n);
logger.debug("spelling '{}'", this.preferredSpelling);
}
/**
* <p>
* Use the PitchFactory to get an instance instead. Use this only in special
* circumstances
* </p>
* <p>
* Parses a string representation of the pitch using PitchFormat. Also sets
* the frequency.
* </p>
*
* {@link com.rockhoppertech.music.PitchFormat}
*
* @param s
* String the pitch string like c#5
*/
public Pitch(String s) {
midiNumber = PitchFormat.stringToMidiNumber(s);
frequency = PitchFactory.EQUAL_TEMPERAMENT.get(midiNumber);
this.preferredSpelling = s;
}
/**
* @return the internal midi number
*/
public int getMidiNumber() {
return midiNumber;
}
/**
* Sets the midi number and frequency.
*
* @param n
* the midi number
*/
public void setMidiNumber(int n) {
midiNumber = n;
frequency = PitchFactory.EQUAL_TEMPERAMENT.get(midiNumber);
}
/**
* Describe <code>getFrequency</code> method here.
*
* @return a <code>double</code> value
*/
public double getFrequency() {
return frequency;
}
/**
* <p>
* <code>transpose</code> pitch up or down by the specified number of minor
* seconds (half steps). Can use constants.
* </p>
* <p>
* This uses the PitchFactory to return the appropriate instance. The object
* that is the receiver of this message is not affected in any way.
* </p>
* {@code
* p.transpose(Pitch.TRITONE);
* p.transpose(Pitch.MAJOR_SEVENTH);
* }
*
* @param minorSeconds
* The value added with the receiver's midinumber. Can be
* negative to transpose down.
* @return the transposed Pitch
*/
public Pitch transpose(int minorSeconds) {
int n = midiNumber + minorSeconds;
Pitch p = PitchFactory.getPitch(n);
logger.debug(String.format("transposed to %d", n));
return p;
}
/*
* <p>If you want to use a JSpinner list model and you don't want to write a
* spinner editor, just return the pitch name here.
*
* </p>
*
* @see toProlixString() for a longer version
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return PitchFormat.getInstance().format(this);
}
public String toProlixString() {
StringBuilder sb = new StringBuilder();
sb.append("Pitch[");
sb.append("midiNumber=").append(midiNumber);
sb.append(" frequency=").append(frequency);
sb.append(" cents=").append(cents);
sb.append(" pitchBend=").append(pitchBend);
sb.append("]");
return sb.toString();
}
/**
* Check to see if the pitch is diatonic or not.
*
* @param num
* The midi number
* @return whether it is an accidental
*/
public static boolean isAccidental(int num) {
boolean r = false;
switch (num % 12) {
case 1:
case 3:
case 6:
case 8:
case 10:
r = true;
break;
default:
r = false;
break;
}
return r;
}
public final static int REGEX_FLAGS = Pattern.CASE_INSENSITIVE
| Pattern.UNICODE_CASE | Pattern.CANON_EQ;
public static boolean isSharp(String pitchName) {
String sharpNoteNameRegexp = "([A-G])(#|s|x)";
Pattern pattern = Pattern.compile(sharpNoteNameRegexp,
REGEX_FLAGS);
Matcher match = pattern.matcher(pitchName);
if (match.matches()) {
logger.debug("{} matches", pitchName);
return true;
}
return false;
}
public static boolean isFlat(String pitchName) {
String flatNoteNameRegexp = "([A-G])(-|b|f)";
Pattern pattern = Pattern.compile(flatNoteNameRegexp,
REGEX_FLAGS);
Matcher match = pattern.matcher(pitchName);
if (match.matches()) {
logger.debug("{} matches", pitchName);
return true;
}
return false;
}
/**
* <p>
* Calculate frequency of a pitch class/octave pair.
* </p>
*
* @param pitch
* the pitch class
* @param oct
* the octave. 6.0 is middle C's octave
* @return the frequency
*/
public static double midiFq(double pitch, double oct) {
return (REF_PITCH * Math.pow(2d,
(oct - 5d)) * Math.pow(2d,
(pitch / 12d)));
}
/**
* Calculate equal tempered frequency of a midi note. The PitchFactory
* contains a cached table of Equal Temp. pitches. so use that instead of
* this method.
*
* Called by {@code PitchFactory} when calculating {@code EQUAL_TEMPERAMENT}
* .
*
* <pre>
* {@code
* frequency = PitchFactory.EQUAL_TEMPERAMENT.get(this.midiNumber);
* }
* </pre>
*
* @param midiNoteNumber
* an <code>int</code> value
* @return the frequency
*/
public static double midiFq(int midiNoteNumber) {
int pitch = midiNoteNumber / 12;
int oct = midiNoteNumber % 12;
double dp = pitch - 5d;
double doct = oct / 12d;
return (REF_PITCH * Math.pow(2d,
dp) * Math.pow(2d,
doct));
}
/*
* <p>Uses the MIDI number for natural ordering. </p>
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(Pitch other) {
int val = 0;
if (getMidiNumber() == other.getMidiNumber()) {
val = 0;
} else if (getMidiNumber() < other.getMidiNumber()) {
val = -1;
} else {
val = 1;
}
return val;
}
public enum P {
C0(0),
CS0(1),
DF0(1),
D0(2),
DS0(3),
EF0(3),
E0(4),
F0(5),
FS0(6),
GF0(6),
G0(7),
GS0(8),
AF0(8),
A0(9),
AS0(10),
BF0(10),
B0(11),
C1(12),
CS1(13),
DF1(13),
D1(14),
DS1(15),
EF1(15),
E1(16),
F1(17),
FS1(18),
GF1(18),
G1(19),
GS1(20),
AF1(20),
A1(21),
AS1(22),
BF1(22),
B1(23),
C2(24),
CS2(25),
DF2(25),
D2(26),
DS2(27),
EF2(27),
E2(28),
F2(29),
FS2(30),
GF2(30),
G2(31),
GS2(32),
AF2(32),
A2(33),
AS2(34),
BF2(34),
B2(35),
C3(36),
CS3(37),
DF3(37),
D3(38),
DS3(39),
EF3(39),
E3(40),
F3(41),
FS3(42),
GF3(42),
G3(43),
GS3(44),
AF3(44),
A3(45),
AS3(46),
BF3(46),
B3(47),
C4(48),
CS4(49),
DF4(49),
D4(50),
DS4(51),
EF4(51),
E4(52),
F4(53),
FS4(54),
GF4(54),
G4(55),
GS4(56),
AF4(56),
A4(57),
AS4(58),
BF4(58),
B4(59),
C5(60),
MIDDLE_C(60),
CS5(61),
DF5(61),
D5(62),
DS5(63),
EF5(63),
E5(64),
F5(65),
FS5(66),
GF5(66),
G5(67),
GS5(68),
AF5(68),
A5(69),
AS5(70),
BF5(70),
B5(71),
C6(72),
CS6(73),
DF6(73),
D6(74),
DS6(75),
EF6(75),
E6(76),
F6(77),
FS6(78),
GF6(78),
G6(79),
GS6(80),
AF6(80),
A6(81),
AS6(82),
BF6(82),
B6(83),
C7(84),
CS7(85),
DF7(85),
D7(86),
DS7(87),
EF7(87),
E7(88),
F7(89),
FS7(90),
GF7(90),
G7(91),
GS7(92),
AF7(92),
A7(93),
AS7(94),
BF7(94),
B7(95),
C8(96),
CS8(97),
DF8(97),
D8(98),
DS8(99),
EF8(99),
E8(100),
F8(101),
FS8(102),
GF8(102),
G8(103),
GS8(104),
AF8(104),
A8(105),
AS8(106),
BF8(106),
B8(107),
C9(108),
CS9(109),
DF9(109),
D9(110),
DS9(111),
EF9(111),
E9(112),
F9(113),
FS9(114),
GF9(114),
G9(115),
GS9(116),
AF9(116),
A9(117),
AS9(118),
BF9(118),
B9(119),
C10(120),
CS10(121),
DF10(121),
D10(122),
DS10(123),
EF10(123),
E10(124),
F10(125),
FS10(126),
GF10(126),
G10(127);
private int value;
private P(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
// all this nonsense just to change middle C from C5 to something else
// like C4
// TODO would be better if the Pitch class itself were an enum instad of
// class?
private void plus(int amt) {
value += amt;
}
public void add12() {
P[] a = Pitch.P.class.getEnumConstants();
for (P p : a) {
p.plus(12);
}
}
private void minus(int amt) {
value -= amt;
}
public void sub12() {
P[] a = Pitch.P.class.getEnumConstants();
for (P p : a) {
p.minus(12);
}
}
}
public static final int C0 = 0;
public static final int CS0 = 1;
public static final int DF0 = 1;
public static final int D0 = 2;
public static final int DS0 = 3;
public static final int EF0 = 3;
public static final int E0 = 4;
public static final int F0 = 5;
public static final int FS0 = 6;
public static final int GF0 = 6;
public static final int G0 = 7;
public static final int GS0 = 8;
public static final int AF0 = 8;
public static final int A0 = 9;
public static final int AS0 = 10;
public static final int BF0 = 10;
public static final int B0 = 11;
public static final int C1 = 12;
public static final int CS1 = 13;
public static final int DF1 = 13;
public static final int D1 = 14;
public static final int DS1 = 15;
public static final int EF1 = 15;
public static final int E1 = 16;
public static final int F1 = 17;
public static final int FS1 = 18;
public static final int GF1 = 18;
public static final int G1 = 19;
public static final int GS1 = 20;
public static final int AF1 = 20;
public static final int A1 = 21;
public static final int AS1 = 22;
public static final int BF1 = 22;
public static final int B1 = 23;
public static final int C2 = 24;
public static final int CS2 = 25;
public static final int DF2 = 25;
public static final int D2 = 26;
public static final int DS2 = 27;
public static final int EF2 = 27;
public static final int E2 = 28;
public static final int F2 = 29;
public static final int FS2 = 30;
public static final int GF2 = 30;
public static final int G2 = 31;
public static final int GS2 = 32;
public static final int AF2 = 32;
public static final int A2 = 33;
public static final int AS2 = 34;
public static final int BF2 = 34;
public static final int B2 = 35;
public static final int C3 = 36;
public static final int CS3 = 37;
public static final int DF3 = 37;
public static final int D3 = 38;
public static final int DS3 = 39;
public static final int EF3 = 39;
public static final int E3 = 40;
public static final int F3 = 41;
public static final int FS3 = 42;
public static final int GF3 = 42;
public static final int G3 = 43;
public static final int GS3 = 44;
public static final int AF3 = 44;
public static final int A3 = 45;
public static final int AS3 = 46;
public static final int BF3 = 46;
public static final int B3 = 47;
public static final int C4 = 48;
public static final int CS4 = 49;
public static final int DF4 = 49;
public static final int D4 = 50;
public static final int DS4 = 51;
public static final int EF4 = 51;
public static final int E4 = 52;
public static final int F4 = 53;
public static final int FS4 = 54;
public static final int GF4 = 54;
public static final int G4 = 55;
public static final int GS4 = 56;
public static final int AF4 = 56;
public static final int A4 = 57;
public static final int AS4 = 58;
public static final int BF4 = 58;
public static final int B4 = 59;
public static final int C5 = 60;
public static final int MIDDLE_C = 60;
public static final int CS5 = 61;
public static final int DF5 = 61;
public static final int D5 = 62;
public static final int DS5 = 63;
public static final int EF5 = 63;
public static final int E5 = 64;
public static final int F5 = 65;
public static final int FS5 = 66;
public static final int GF5 = 66;
public static final int G5 = 67;
public static final int GS5 = 68;
public static final int AF5 = 68;
public static final int A5 = 69;
public static final int AS5 = 70;
public static final int BF5 = 70;
public static final int B5 = 71;
public static final int C6 = 72;
public static final int CS6 = 73;
public static final int DF6 = 73;
public static final int D6 = 74;
public static final int DS6 = 75;
public static final int EF6 = 75;
public static final int E6 = 76;
public static final int F6 = 77;
public static final int FS6 = 78;
public static final int GF6 = 78;
public static final int G6 = 79;
public static final int GS6 = 80;
public static final int AF6 = 80;
public static final int A6 = 81;
public static final int AS6 = 82;
public static final int BF6 = 82;
public static final int B6 = 83;
public static final int C7 = 84;
public static final int CS7 = 85;
public static final int DF7 = 85;
public static final int D7 = 86;
public static final int DS7 = 87;
public static final int EF7 = 87;
public static final int E7 = 88;
public static final int F7 = 89;
public static final int FS7 = 90;
public static final int GF7 = 90;
public static final int G7 = 91;
public static final int GS7 = 92;
public static final int AF7 = 92;
public static final int A7 = 93;
public static final int AS7 = 94;
public static final int BF7 = 94;
public static final int B7 = 95;
public static final int C8 = 96;
public static final int CS8 = 97;
public static final int DF8 = 97;
public static final int D8 = 98;
public static final int DS8 = 99;
public static final int EF8 = 99;
public static final int E8 = 100;
public static final int F8 = 101;
public static final int FS8 = 102;
public static final int GF8 = 102;
public static final int G8 = 103;
public static final int GS8 = 104;
public static final int AF8 = 104;
public static final int A8 = 105;
public static final int AS8 = 106;
public static final int BF8 = 106;
public static final int B8 = 107;
public static final int C9 = 108;
public static final int CS9 = 109;
public static final int DF9 = 109;
public static final int D9 = 110;
public static final int DS9 = 111;
public static final int EF9 = 111;
public static final int E9 = 112;
public static final int F9 = 113;
public static final int FS9 = 114;
public static final int GF9 = 114;
public static final int G9 = 115;
public static final int GS9 = 116;
public static final int AF9 = 116;
public static final int A9 = 117;
public static final int AS9 = 118;
public static final int BF9 = 118;
public static final int B9 = 119;
public static final int C10 = 120;
public static final int CS10 = 121;
public static final int DF10 = 121;
public static final int D10 = 122;
public static final int DS10 = 123;
public static final int EF10 = 123;
public static final int E10 = 124;
public static final int F10 = 125;
public static final int FS10 = 126;
public static final int GF10 = 126;
public static final int G10 = 127;
public static final int MIN = C0;
public static final int MAX = G10;
public static final int MINOR_SECOND = 1;
public static final int MAJOR_SECOND = 2;
public static final int MINOR_THIRD = 3;
public static final int MAJOR_THIRD = 4;
public static final int PERFECT_FOURTH = 5;
public static final int TRITONE = 6;
public static final int PERFECT_FIFTH = 7;
public static final int MINOR_SIXTH = 8;
public static final int MAJOR_SIXTH = 9;
public static final int MINOR_SEVENTH = 10;
public static final int MAJOR_SEVENTH = 11;
public static final int OCTAVE = 12;
/*
* <p>See Effective Java. </p>
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + midiNumber;
return result;
}
/*
* <p>Compares just MIDI number. </p>
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Pitch other = (Pitch) obj;
if (midiNumber != other.midiNumber) {
return false;
}
return true;
}
/**
* @return the cents
*/
public short getCents() {
return cents;
}
/**
* @param cents
* the cents to set
*/
public void setCents(short cents) {
this.cents = cents;
}
/**
* @param frequency
* the frequency to set
*/
public void setFrequency(double frequency) {
this.frequency = frequency;
}
public short getPitchBend() {
return pitchBend;
}
public void setPitchBend(short pitchBend) {
this.pitchBend = pitchBend;
}
public int getPitchClass() {
return midiNumber % 12;
}
public Set<String> getSynonyms() {
return Pitch.getSynonyms(midiNumber);
}
/**
*
* Here is a JUnit example. <code>
* assertThat(somePitch.getSynonymsForPitchClass(), hasItem("Db"));
* </code>
*
* @return a {@code Set} of synonyms
*/
public Set<String> getSynonymsForPitchClass() {
return Pitch.getSynonyms(midiNumber % 12);
}
public static Set<String> getSynonyms(int midiNumber) {
Set<String> syn = new TreeSet<String>();
for (Map.Entry<String, Integer> entry : nameMap.entrySet()) {
if (entry.getValue() == midiNumber) {
// don't really feel like writing custom JUnit matchers
String key = entry.getKey();
syn.add(key);
syn.add(key.toLowerCase(Locale.ENGLISH));
syn.add(key.toUpperCase(Locale.ENGLISH));
syn.add(StringUtils.capitalize(key.toLowerCase(Locale.ENGLISH)));
}
}
return syn;
}
// this is the fastest and easiest. a pain to set up but now its set up.
public static final Map<String, Integer> nameMap = new TreeMap<String, Integer>();
static {
nameMap.put("C",
0);
nameMap.put("CS",
1);
nameMap.put("Cs",
1);
nameMap.put("C#",
1);
nameMap.put("DF",
1);
nameMap.put("Df",
1);
nameMap.put("DB",
1);
nameMap.put("D",
2);
nameMap.put("DS",
3);
nameMap.put("Ds",
3);
nameMap.put("D#",
3);
nameMap.put("EF",
3);
nameMap.put("Ef",
3);
nameMap.put("EB",
3);
nameMap.put("E",
4);
nameMap.put("F",
5);
nameMap.put("FS",
6);
nameMap.put("Fs",
6);
nameMap.put("F#",
6);
nameMap.put("GF",
6);
nameMap.put("Gf",
6);
nameMap.put("GB",
6);
nameMap.put("G",
7);
nameMap.put("GS",
8);
nameMap.put("Gs",
8);
nameMap.put("G#",
8);
nameMap.put("AF",
8);
nameMap.put("Af",
8);
nameMap.put("AB",
8);
nameMap.put("A",
9);
nameMap.put("AS",
10);
nameMap.put("As",
10);
nameMap.put("A#",
10);
nameMap.put("BF",
10);
nameMap.put("Bf",
10);
nameMap.put("BB",
10);
nameMap.put("B",
11);
nameMap.put("CB",
11);
nameMap.put("CF",
11);
nameMap.put("Cf",
11);
nameMap.put("C0",
0);
nameMap.put("CS0",
1);
nameMap.put("C#0",
1);
nameMap.put("DF0",
1);
nameMap.put("Df0",
1);
nameMap.put("DB0",
1);
nameMap.put("D0",
2);
nameMap.put("DS0",
3);
nameMap.put("D#0",
3);
nameMap.put("EF0",
3);
nameMap.put("Ef0",
3);
nameMap.put("EB0",
3);
nameMap.put("E0",
4);
nameMap.put("F0",
5);
nameMap.put("FS0",
6);
nameMap.put("F#0",
6);
nameMap.put("GF0",
6);
nameMap.put("Gf0",
6);
nameMap.put("GB0",
6);
nameMap.put("G0",
7);
nameMap.put("GS0",
8);
nameMap.put("G#0",
8);
nameMap.put("AF0",
8);
nameMap.put("Af0",
8);
nameMap.put("AB0",
8);
nameMap.put("A0",
9);
nameMap.put("AS0",
10);
nameMap.put("A#0",
10);
nameMap.put("BF0",
10);
nameMap.put("Bf0",
10);
nameMap.put("BB0",
10);
nameMap.put("B0",
11);
nameMap.put("CF1",
11);
nameMap.put("Cf1",
11);
nameMap.put("CB1",
11);
nameMap.put("C1",
12);
nameMap.put("CS1",
13);
nameMap.put("C#1",
13);
nameMap.put("DF1",
13);
nameMap.put("DB1",
13);
nameMap.put("D1",
14);
nameMap.put("DS1",
15);
nameMap.put("D#1",
15);
nameMap.put("EF1",
15);
nameMap.put("EB1",
15);
nameMap.put("E1",
16);
nameMap.put("F1",
17);
nameMap.put("FS1",
18);
nameMap.put("F#1",
18);
nameMap.put("GF1",
18);
nameMap.put("GB1",
18);
nameMap.put("G1",
19);
nameMap.put("GS1",
20);
nameMap.put("G#1",
20);
nameMap.put("AF1",
20);
nameMap.put("AB1",
20);
nameMap.put("A1",
21);
nameMap.put("AS1",
22);
nameMap.put("A#1",
22);
nameMap.put("BF1",
22);
nameMap.put("BB1",
22);
nameMap.put("B1",
23);
nameMap.put("CF2",
23);
nameMap.put("Cf2",
23);
nameMap.put("CB2",
23);
nameMap.put("C2",
24);
nameMap.put("CS2",
25);
nameMap.put("C#2",
25);
nameMap.put("DF2",
25);
nameMap.put("DB2",
25);
nameMap.put("D2",
26);
nameMap.put("DS2",
27);
nameMap.put("D#2",
27);
nameMap.put("EF2",
27);
nameMap.put("EB2",
27);
nameMap.put("E2",
28);
nameMap.put("F2",
29);
nameMap.put("FS2",
30);
nameMap.put("F#2",
30);
nameMap.put("GF2",
30);
nameMap.put("GB2",
30);
nameMap.put("G2",
31);
nameMap.put("GS2",
32);
nameMap.put("G#2",
32);
nameMap.put("AF2",
32);
nameMap.put("AB2",
32);
nameMap.put("A2",
33);
nameMap.put("AS2",
34);
nameMap.put("A#2",
34);
nameMap.put("BF2",
34);
nameMap.put("BB2",
34);
nameMap.put("B2",
35);
nameMap.put("CF3",
35);
nameMap.put("Cf3",
35);
nameMap.put("CB3",
35);
nameMap.put("C3",
36);
nameMap.put("CS3",
37);
nameMap.put("C#3",
37);
nameMap.put("DF3",
37);
nameMap.put("DB3",
37);
nameMap.put("D3",
38);
nameMap.put("DS3",
39);
nameMap.put("D#3",
39);
nameMap.put("EF3",
39);
nameMap.put("EB3",
39);
nameMap.put("E3",
40);
nameMap.put("F3",
41);
nameMap.put("FS3",
42);
nameMap.put("F#3",
42);
nameMap.put("GF3",
42);
nameMap.put("GB3",
42);
nameMap.put("G3",
43);
nameMap.put("GS3",
44);
nameMap.put("G#3",
44);
nameMap.put("AF3",
44);
nameMap.put("AB3",
44);
nameMap.put("A3",
45);
nameMap.put("AS3",
46);
nameMap.put("A#3",
46);
nameMap.put("BF3",
46);
nameMap.put("BB3",
46);
nameMap.put("B3",
47);
nameMap.put("CF4",
47);
nameMap.put("Cf4",
47);
nameMap.put("CB4",
47);
nameMap.put("C4",
48);
nameMap.put("CS4",
49);
nameMap.put("C#4",
49);
nameMap.put("DF4",
49);
nameMap.put("Df4",
49);
nameMap.put("DB4",
49);
nameMap.put("D4",
50);
nameMap.put("DS4",
51);
nameMap.put("D#4",
51);
nameMap.put("EF4",
51);
nameMap.put("Ef4",
51);
nameMap.put("EB4",
51);
nameMap.put("E4",
52);
nameMap.put("F4",
53);
nameMap.put("FS4",
54);
nameMap.put("F#4",
54);
nameMap.put("GF4",
54);
nameMap.put("Gf4",
54);
nameMap.put("GB4",
54);
nameMap.put("G4",
55);
nameMap.put("GS4",
56);
nameMap.put("G#4",
56);
nameMap.put("AF4",
56);
nameMap.put("Af4",
56);
nameMap.put("AB4",
56);
nameMap.put("A4",
57);
nameMap.put("AS4",
58);
nameMap.put("A#4",
58);
nameMap.put("BF4",
58);
nameMap.put("Bf4",
58);
nameMap.put("BB4",
58);
nameMap.put("B4",
59);
// changed PitchFactory.getPitchByName to lookup in uppercase
// so the lc versions are not needed
nameMap.put("CF5",
B4);
nameMap.put("Cf5",
B4);
nameMap.put("CB5",
B4);
nameMap.put("C5",
C5);
nameMap.put("C#5",
CS5);
nameMap.put("CS5",
CS5);
nameMap.put("DF5",
CS5);
nameMap.put("Df5",
CS5);
nameMap.put("DB5",
CS5);
nameMap.put("D5",
D5);
nameMap.put("DS5",
63);
nameMap.put("D#5",
63);
nameMap.put("EF5",
63);
nameMap.put("Ef5",
63);
nameMap.put("EB5",
63);
nameMap.put("E5",
64);
nameMap.put("F5",
65);
nameMap.put("FS5",
66);
nameMap.put("F#5",
66);
nameMap.put("GF5",
66);
nameMap.put("Gf5",
66);
nameMap.put("GB5",
66);
nameMap.put("G5",
67);
nameMap.put("GS5",
68);
nameMap.put("G#5",
68);
nameMap.put("AF5",
68);
nameMap.put("Af5",
68);
nameMap.put("AB5",
68);
nameMap.put("A5",
69);
nameMap.put("AS5",
70);
nameMap.put("A#5",
70);
nameMap.put("BF5",
70);
nameMap.put("Bf5",
70);
nameMap.put("BB5",
70);
nameMap.put("B5",
71);
nameMap.put("CF6",
71);
nameMap.put("Cf6",
71);
nameMap.put("CB6",
71);
nameMap.put("C6",
72);
nameMap.put("CS6",
73);
nameMap.put("C#6",
73);
nameMap.put("DF6",
73);
nameMap.put("Df6",
73);
nameMap.put("DB6",
73);
nameMap.put("D6",
74);
nameMap.put("DS6",
75);
nameMap.put("D#6",
75);
nameMap.put("EF6",
75);
nameMap.put("Ef6",
75);
nameMap.put("EB6",
75);
nameMap.put("E6",
76);
nameMap.put("F6",
77);
nameMap.put("FS6",
78);
nameMap.put("F#6",
78);
nameMap.put("GF6",
78);
nameMap.put("Gf6",
78);
nameMap.put("GB6",
78);
nameMap.put("G6",
79);
nameMap.put("GS6",
80);
nameMap.put("G#6",
80);
nameMap.put("AF6",
80);
nameMap.put("Af6",
80);
nameMap.put("AB6",
80);
nameMap.put("A6",
81);
nameMap.put("AS6",
82);
nameMap.put("A#6",
82);
nameMap.put("BF6",
82);
nameMap.put("Bf6",
82);
nameMap.put("BB6",
82);
nameMap.put("B6",
83);
nameMap.put("CF7",
83);
nameMap.put("Cf7",
83);
nameMap.put("CB7",
83);
nameMap.put("C7",
84);
nameMap.put("CS7",
85);
nameMap.put("C#7",
85);
nameMap.put("DF7",
85);
nameMap.put("Df7",
85);
nameMap.put("DB7",
85);
nameMap.put("D7",
86);
nameMap.put("DS7",
87);
nameMap.put("D#7",
87);
nameMap.put("EF7",
87);
nameMap.put("Ef7",
87);
nameMap.put("EB7",
87);
nameMap.put("E7",
88);
nameMap.put("F7",
89);
nameMap.put("FS7",
90);
nameMap.put("F#7",
90);
nameMap.put("GF7",
90);
nameMap.put("Gf7",
90);
nameMap.put("GB7",
90);
nameMap.put("G7",
91);
nameMap.put("GS7",
92);
nameMap.put("G#7",
92);
nameMap.put("AF7",
92);
nameMap.put("Af7",
92);
nameMap.put("AB7",
92);
nameMap.put("A7",
93);
nameMap.put("AS7",
94);
nameMap.put("A#7",
94);
nameMap.put("BF7",
94);
nameMap.put("Bf7",
94);
nameMap.put("BB7",
94);
nameMap.put("B7",
95);
nameMap.put("CF8",
95);
nameMap.put("Cf8",
95);
nameMap.put("CB8",
95);
nameMap.put("C8",
96);
nameMap.put("CS8",
97);
nameMap.put("C#8",
97);
nameMap.put("DF8",
97);
nameMap.put("Df8",
97);
nameMap.put("DB8",
97);
nameMap.put("D8",
98);
nameMap.put("DS8",
99);
nameMap.put("D#8",
99);
nameMap.put("EF8",
99);
nameMap.put("Ef8",
99);
nameMap.put("EB8",
99);
nameMap.put("E8",
100);
nameMap.put("F8",
101);
nameMap.put("FS8",
102);
nameMap.put("F#8",
102);
nameMap.put("GF8",
102);
nameMap.put("Gf8",
102);
nameMap.put("GB8",
102);
nameMap.put("G8",
103);
nameMap.put("GS8",
104);
nameMap.put("G#8",
104);
nameMap.put("AF8",
104);
nameMap.put("Af8",
104);
nameMap.put("AB8",
104);
nameMap.put("A8",
105);
nameMap.put("AS8",
106);
nameMap.put("A#8",
106);
nameMap.put("BF8",
106);
nameMap.put("Bf8",
106);
nameMap.put("BB8",
106);
nameMap.put("B8",
107);
nameMap.put("CF9",
107);
nameMap.put("Cf9",
107);
nameMap.put("CB9",
107);
nameMap.put("C9",
108);
nameMap.put("CS9",
109);
nameMap.put("C#9",
109);
nameMap.put("DF9",
109);
nameMap.put("Df9",
109);
nameMap.put("DB9",
109);
nameMap.put("D9",
110);
nameMap.put("DS9",
111);
nameMap.put("D#9",
111);
nameMap.put("EF9",
111);
nameMap.put("Ef9",
111);
nameMap.put("EB9",
111);
nameMap.put("E9",
112);
nameMap.put("F9",
113);
nameMap.put("FS9",
114);
nameMap.put("F#9",
114);
nameMap.put("GF9",
114);
nameMap.put("GB9",
114);
nameMap.put("G9",
115);
nameMap.put("GS9",
116);
nameMap.put("G#9",
116);
nameMap.put("AF9",
116);
nameMap.put("Af9",
116);
nameMap.put("AB9",
116);
nameMap.put("A9",
117);
nameMap.put("AS9",
118);
nameMap.put("A#9",
118);
nameMap.put("BF9",
118);
nameMap.put("Bf9",
118);
nameMap.put("BB9",
118);
nameMap.put("B9",
119);
nameMap.put("CF10",
119);
nameMap.put("Cf10",
119);
nameMap.put("CB10",
119);
nameMap.put("C10",
120);
nameMap.put("CS10",
121);
nameMap.put("C#10",
121);
nameMap.put("DF10",
121);
nameMap.put("Df10",
121);
nameMap.put("DB10",
121);
nameMap.put("D10",
122);
nameMap.put("DS10",
123);
nameMap.put("D#10",
123);
nameMap.put("EF10",
123);
nameMap.put("Ef10",
123);
nameMap.put("EB10",
123);
nameMap.put("E10",
124);
nameMap.put("F10",
125);
nameMap.put("FS10",
126);
nameMap.put("F#10",
126);
nameMap.put("GF10",
126);
nameMap.put("Gf10",
126);
nameMap.put("GB10",
126);
nameMap.put("G10",
127);
}
public static final PitchClassComparator pitchClassComparator = new PitchClassComparator();
public static final class PitchClassComparator implements
Comparator<Pitch>, Serializable {
/**
*
*/
private static final long serialVersionUID = 4929792298044867022L;
@Override
public int compare(Pitch o1, Pitch o2) {
int val = 0;
if (o1.getPitchClass() == o2.getPitchClass()) {
val = 0;
} else if (o1.getPitchClass() < o2.getPitchClass()) {
val = -1;
} else {
val = 1;
}
return val;
}
}
/**
* @return the preferredSpelling
*/
public String getPreferredSpelling() {
if (preferredSpelling == null || preferredSpelling.equals("") || preferredSpelling.equals("null")) {
logger.debug(
"preferred spelling empty for pitch {}",
this.midiNumber);
preferredSpelling = PitchFormat.getInstance().format(
this.midiNumber);
}
return preferredSpelling;
}
/**
* @param preferredSpelling
* the preferredSpelling to set
*/
public void setPreferredSpelling(String preferredSpelling) {
this.preferredSpelling = preferredSpelling;
};
}
/*
* History:
*
* $Log$
*
* This version: $Revision$ Last modified: $Date$ Last modified by: $Author$
*/
| rockymusic-core/src/main/java/com/rockhoppertech/music/Pitch.java | package com.rockhoppertech.music;
/*
* #%L
* Rocky Music Core
* %%
* Copyright (C) 1996 - 2013 Rockhopper Technologies
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.Serializable;
import java.util.Comparator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* A representation of musical frequency (Pitch).
* <p>
* <p>
* Internally represented by a midi number. The frequency is calculated based on
* the MIDI number.
* </p>
*
* See http://en.wikipedia.org/wiki/Scientific_pitch_notation
*
* For MusicXML, Common Lisp Music and others the octave is "off" by 1. In MIDI
* middle c is C5, for them it is C4.
*
* <p>
* For equal temperament you should use the PitchFactory to obtain instances a
* la the GoF Flyweight design pattern. (Most likely you will have zillions of
* instances of Pitch in your program. The Flyweight helps this problem).
* </p>
*
*
* @author <a href="http://genedelisa.com/">Gene De Lisa</a>
* @version 1.0 Mon Aug 10, 1998
* @see com.rockhoppertech.music.PitchFactory
* @see com.rockhoppertech.music.PitchFormat
*/
public class Pitch implements Serializable, Comparable<Pitch> {
/**
*
*/
private static final long serialVersionUID = -4983186242989608159L;
private static final Logger logger = LoggerFactory
.getLogger(Pitch.class);
/**
* The main datum.
*/
private int midiNumber;
private String preferredSpelling;
private short cents;
/**
* Equal temperament frequency for the midiNumber
*/
private double frequency;
/**
* 0 if not microtonal
*/
private short pitchBend;
/**
* middle c or 261.6255653005986 hz Used to calculate the frequency.
*/
public static final double REF_PITCH = 220d * Math.pow(2d,
(3d / 12d));
/**
* <p>
* Use the PitchFactory to get an instance instead. Use this only in special
* circumstances
* </p>
* <p>
* Midi number will be 0.
* </p>
*/
public Pitch() {
this(0);
}
/**
* <p>
* Use the PitchFactory to get an instance instead. Use this only in special
* circumstances
* </p>
* <p>
* Can use a constant.
* <p>
*
* {@code
* new Pitch(Pitch.C5);
* }
*
* @param n
* the midi number to use. 60 is middle c.
*/
public Pitch(int n) {
if (n < 0 || n > 127) {
throw new IllegalArgumentException("MIDI number out of range " + n);
}
midiNumber = n;
// this.frequency = Pitch.midiFq(this.midiNumber);
frequency = PitchFactory.EQUAL_TEMPERAMENT.get(midiNumber);
this.preferredSpelling = PitchFormat.getInstance().format(n);
}
/**
* <p>
* Use the PitchFactory to get an instance instead. Use this only in special
* circumstances
* </p>
* <p>
* Parses a string representation of the pitch using PitchFormat. Also sets
* the frequency.
* </p>
*
* {@link com.rockhoppertech.music.PitchFormat}
*
* @param s
* String the pitch string like c#5
*/
public Pitch(String s) {
midiNumber = PitchFormat.stringToMidiNumber(s);
frequency = PitchFactory.EQUAL_TEMPERAMENT.get(midiNumber);
this.preferredSpelling = s;
}
/**
* @return the internal midi number
*/
public int getMidiNumber() {
return midiNumber;
}
/**
* Sets the midi number and frequency.
*
* @param n
* the midi number
*/
public void setMidiNumber(int n) {
midiNumber = n;
frequency = PitchFactory.EQUAL_TEMPERAMENT.get(midiNumber);
}
/**
* Describe <code>getFrequency</code> method here.
*
* @return a <code>double</code> value
*/
public double getFrequency() {
return frequency;
}
/**
* <p>
* <code>transpose</code> pitch up or down by the specified number of minor
* seconds (half steps). Can use constants.
* </p>
* <p>
* This uses the PitchFactory to return the appropriate instance. The object
* that is the receiver of this message is not affected in any way.
* </p>
* {@code
* p.transpose(Pitch.TRITONE);
* p.transpose(Pitch.MAJOR_SEVENTH);
* }
*
* @param minorSeconds
* The value added with the receiver's midinumber. Can be
* negative to transpose down.
* @return the transposed Pitch
*/
public Pitch transpose(int minorSeconds) {
int n = midiNumber + minorSeconds;
Pitch p = PitchFactory.getPitch(n);
logger.debug(String.format("transposed to %d", n));
return p;
}
/*
* <p>If you want to use a JSpinner list model and you don't want to write a
* spinner editor, just return the pitch name here.
*
* </p>
*
* @see toProlixString() for a longer version
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return PitchFormat.getInstance().format(this);
}
public String toProlixString() {
StringBuilder sb = new StringBuilder();
sb.append("Pitch[");
sb.append("midiNumber=").append(midiNumber);
sb.append(" frequency=").append(frequency);
sb.append(" cents=").append(cents);
sb.append(" pitchBend=").append(pitchBend);
sb.append("]");
return sb.toString();
}
/**
* Check to see if the pitch is diatonic or not.
*
* @param num
* The midi number
* @return whether it is an accidental
*/
public static boolean isAccidental(int num) {
boolean r = false;
switch (num % 12) {
case 1:
case 3:
case 6:
case 8:
case 10:
r = true;
break;
default:
r = false;
break;
}
return r;
}
public final static int REGEX_FLAGS = Pattern.CASE_INSENSITIVE
| Pattern.UNICODE_CASE | Pattern.CANON_EQ;
public static boolean isSharp(String pitchName) {
String sharpNoteNameRegexp = "([A-G])(#|s|x)";
Pattern pattern = Pattern.compile(sharpNoteNameRegexp,
REGEX_FLAGS);
Matcher match = pattern.matcher(pitchName);
if (match.matches()) {
logger.debug("{} matches", pitchName);
return true;
}
return false;
}
public static boolean isFlat(String pitchName) {
String flatNoteNameRegexp = "([A-G])(-|b|f)";
Pattern pattern = Pattern.compile(flatNoteNameRegexp,
REGEX_FLAGS);
Matcher match = pattern.matcher(pitchName);
if (match.matches()) {
logger.debug("{} matches", pitchName);
return true;
}
return false;
}
/**
* <p>
* Calculate frequency of a pitch class/octave pair.
* </p>
*
* @param pitch
* the pitch class
* @param oct
* the octave. 6.0 is middle C's octave
* @return the frequency
*/
public static double midiFq(double pitch, double oct) {
return (REF_PITCH * Math.pow(2d,
(oct - 5d)) * Math.pow(2d,
(pitch / 12d)));
}
/**
* Calculate equal tempered frequency of a midi note. The PitchFactory
* contains a cached table of Equal Temp. pitches. so use that instead of
* this method.
*
* Called by {@code PitchFactory} when calculating {@code EQUAL_TEMPERAMENT}
* .
*
* <pre>
* {@code
* frequency = PitchFactory.EQUAL_TEMPERAMENT.get(this.midiNumber);
* }
* </pre>
*
* @param midiNoteNumber
* an <code>int</code> value
* @return the frequency
*/
public static double midiFq(int midiNoteNumber) {
int pitch = midiNoteNumber / 12;
int oct = midiNoteNumber % 12;
double dp = pitch - 5d;
double doct = oct / 12d;
return (REF_PITCH * Math.pow(2d,
dp) * Math.pow(2d,
doct));
}
/*
* <p>Uses the MIDI number for natural ordering. </p>
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(Pitch other) {
int val = 0;
if (getMidiNumber() == other.getMidiNumber()) {
val = 0;
} else if (getMidiNumber() < other.getMidiNumber()) {
val = -1;
} else {
val = 1;
}
return val;
}
public enum P {
C0(0),
CS0(1),
DF0(1),
D0(2),
DS0(3),
EF0(3),
E0(4),
F0(5),
FS0(6),
GF0(6),
G0(7),
GS0(8),
AF0(8),
A0(9),
AS0(10),
BF0(10),
B0(11),
C1(12),
CS1(13),
DF1(13),
D1(14),
DS1(15),
EF1(15),
E1(16),
F1(17),
FS1(18),
GF1(18),
G1(19),
GS1(20),
AF1(20),
A1(21),
AS1(22),
BF1(22),
B1(23),
C2(24),
CS2(25),
DF2(25),
D2(26),
DS2(27),
EF2(27),
E2(28),
F2(29),
FS2(30),
GF2(30),
G2(31),
GS2(32),
AF2(32),
A2(33),
AS2(34),
BF2(34),
B2(35),
C3(36),
CS3(37),
DF3(37),
D3(38),
DS3(39),
EF3(39),
E3(40),
F3(41),
FS3(42),
GF3(42),
G3(43),
GS3(44),
AF3(44),
A3(45),
AS3(46),
BF3(46),
B3(47),
C4(48),
CS4(49),
DF4(49),
D4(50),
DS4(51),
EF4(51),
E4(52),
F4(53),
FS4(54),
GF4(54),
G4(55),
GS4(56),
AF4(56),
A4(57),
AS4(58),
BF4(58),
B4(59),
C5(60),
MIDDLE_C(60),
CS5(61),
DF5(61),
D5(62),
DS5(63),
EF5(63),
E5(64),
F5(65),
FS5(66),
GF5(66),
G5(67),
GS5(68),
AF5(68),
A5(69),
AS5(70),
BF5(70),
B5(71),
C6(72),
CS6(73),
DF6(73),
D6(74),
DS6(75),
EF6(75),
E6(76),
F6(77),
FS6(78),
GF6(78),
G6(79),
GS6(80),
AF6(80),
A6(81),
AS6(82),
BF6(82),
B6(83),
C7(84),
CS7(85),
DF7(85),
D7(86),
DS7(87),
EF7(87),
E7(88),
F7(89),
FS7(90),
GF7(90),
G7(91),
GS7(92),
AF7(92),
A7(93),
AS7(94),
BF7(94),
B7(95),
C8(96),
CS8(97),
DF8(97),
D8(98),
DS8(99),
EF8(99),
E8(100),
F8(101),
FS8(102),
GF8(102),
G8(103),
GS8(104),
AF8(104),
A8(105),
AS8(106),
BF8(106),
B8(107),
C9(108),
CS9(109),
DF9(109),
D9(110),
DS9(111),
EF9(111),
E9(112),
F9(113),
FS9(114),
GF9(114),
G9(115),
GS9(116),
AF9(116),
A9(117),
AS9(118),
BF9(118),
B9(119),
C10(120),
CS10(121),
DF10(121),
D10(122),
DS10(123),
EF10(123),
E10(124),
F10(125),
FS10(126),
GF10(126),
G10(127);
private int value;
private P(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
// all this nonsense just to change middle C from C5 to something else
// like C4
// TODO would be better if the Pitch class itself were an enum instad of
// class?
private void plus(int amt) {
value += amt;
}
public void add12() {
P[] a = Pitch.P.class.getEnumConstants();
for (P p : a) {
p.plus(12);
}
}
private void minus(int amt) {
value -= amt;
}
public void sub12() {
P[] a = Pitch.P.class.getEnumConstants();
for (P p : a) {
p.minus(12);
}
}
}
public static final int C0 = 0;
public static final int CS0 = 1;
public static final int DF0 = 1;
public static final int D0 = 2;
public static final int DS0 = 3;
public static final int EF0 = 3;
public static final int E0 = 4;
public static final int F0 = 5;
public static final int FS0 = 6;
public static final int GF0 = 6;
public static final int G0 = 7;
public static final int GS0 = 8;
public static final int AF0 = 8;
public static final int A0 = 9;
public static final int AS0 = 10;
public static final int BF0 = 10;
public static final int B0 = 11;
public static final int C1 = 12;
public static final int CS1 = 13;
public static final int DF1 = 13;
public static final int D1 = 14;
public static final int DS1 = 15;
public static final int EF1 = 15;
public static final int E1 = 16;
public static final int F1 = 17;
public static final int FS1 = 18;
public static final int GF1 = 18;
public static final int G1 = 19;
public static final int GS1 = 20;
public static final int AF1 = 20;
public static final int A1 = 21;
public static final int AS1 = 22;
public static final int BF1 = 22;
public static final int B1 = 23;
public static final int C2 = 24;
public static final int CS2 = 25;
public static final int DF2 = 25;
public static final int D2 = 26;
public static final int DS2 = 27;
public static final int EF2 = 27;
public static final int E2 = 28;
public static final int F2 = 29;
public static final int FS2 = 30;
public static final int GF2 = 30;
public static final int G2 = 31;
public static final int GS2 = 32;
public static final int AF2 = 32;
public static final int A2 = 33;
public static final int AS2 = 34;
public static final int BF2 = 34;
public static final int B2 = 35;
public static final int C3 = 36;
public static final int CS3 = 37;
public static final int DF3 = 37;
public static final int D3 = 38;
public static final int DS3 = 39;
public static final int EF3 = 39;
public static final int E3 = 40;
public static final int F3 = 41;
public static final int FS3 = 42;
public static final int GF3 = 42;
public static final int G3 = 43;
public static final int GS3 = 44;
public static final int AF3 = 44;
public static final int A3 = 45;
public static final int AS3 = 46;
public static final int BF3 = 46;
public static final int B3 = 47;
public static final int C4 = 48;
public static final int CS4 = 49;
public static final int DF4 = 49;
public static final int D4 = 50;
public static final int DS4 = 51;
public static final int EF4 = 51;
public static final int E4 = 52;
public static final int F4 = 53;
public static final int FS4 = 54;
public static final int GF4 = 54;
public static final int G4 = 55;
public static final int GS4 = 56;
public static final int AF4 = 56;
public static final int A4 = 57;
public static final int AS4 = 58;
public static final int BF4 = 58;
public static final int B4 = 59;
public static final int C5 = 60;
public static final int MIDDLE_C = 60;
public static final int CS5 = 61;
public static final int DF5 = 61;
public static final int D5 = 62;
public static final int DS5 = 63;
public static final int EF5 = 63;
public static final int E5 = 64;
public static final int F5 = 65;
public static final int FS5 = 66;
public static final int GF5 = 66;
public static final int G5 = 67;
public static final int GS5 = 68;
public static final int AF5 = 68;
public static final int A5 = 69;
public static final int AS5 = 70;
public static final int BF5 = 70;
public static final int B5 = 71;
public static final int C6 = 72;
public static final int CS6 = 73;
public static final int DF6 = 73;
public static final int D6 = 74;
public static final int DS6 = 75;
public static final int EF6 = 75;
public static final int E6 = 76;
public static final int F6 = 77;
public static final int FS6 = 78;
public static final int GF6 = 78;
public static final int G6 = 79;
public static final int GS6 = 80;
public static final int AF6 = 80;
public static final int A6 = 81;
public static final int AS6 = 82;
public static final int BF6 = 82;
public static final int B6 = 83;
public static final int C7 = 84;
public static final int CS7 = 85;
public static final int DF7 = 85;
public static final int D7 = 86;
public static final int DS7 = 87;
public static final int EF7 = 87;
public static final int E7 = 88;
public static final int F7 = 89;
public static final int FS7 = 90;
public static final int GF7 = 90;
public static final int G7 = 91;
public static final int GS7 = 92;
public static final int AF7 = 92;
public static final int A7 = 93;
public static final int AS7 = 94;
public static final int BF7 = 94;
public static final int B7 = 95;
public static final int C8 = 96;
public static final int CS8 = 97;
public static final int DF8 = 97;
public static final int D8 = 98;
public static final int DS8 = 99;
public static final int EF8 = 99;
public static final int E8 = 100;
public static final int F8 = 101;
public static final int FS8 = 102;
public static final int GF8 = 102;
public static final int G8 = 103;
public static final int GS8 = 104;
public static final int AF8 = 104;
public static final int A8 = 105;
public static final int AS8 = 106;
public static final int BF8 = 106;
public static final int B8 = 107;
public static final int C9 = 108;
public static final int CS9 = 109;
public static final int DF9 = 109;
public static final int D9 = 110;
public static final int DS9 = 111;
public static final int EF9 = 111;
public static final int E9 = 112;
public static final int F9 = 113;
public static final int FS9 = 114;
public static final int GF9 = 114;
public static final int G9 = 115;
public static final int GS9 = 116;
public static final int AF9 = 116;
public static final int A9 = 117;
public static final int AS9 = 118;
public static final int BF9 = 118;
public static final int B9 = 119;
public static final int C10 = 120;
public static final int CS10 = 121;
public static final int DF10 = 121;
public static final int D10 = 122;
public static final int DS10 = 123;
public static final int EF10 = 123;
public static final int E10 = 124;
public static final int F10 = 125;
public static final int FS10 = 126;
public static final int GF10 = 126;
public static final int G10 = 127;
public static final int MIN = C0;
public static final int MAX = G10;
public static final int MINOR_SECOND = 1;
public static final int MAJOR_SECOND = 2;
public static final int MINOR_THIRD = 3;
public static final int MAJOR_THIRD = 4;
public static final int PERFECT_FOURTH = 5;
public static final int TRITONE = 6;
public static final int PERFECT_FIFTH = 7;
public static final int MINOR_SIXTH = 8;
public static final int MAJOR_SIXTH = 9;
public static final int MINOR_SEVENTH = 10;
public static final int MAJOR_SEVENTH = 11;
public static final int OCTAVE = 12;
/*
* <p>See Effective Java. </p>
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + midiNumber;
return result;
}
/*
* <p>Compares just MIDI number. </p>
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Pitch other = (Pitch) obj;
if (midiNumber != other.midiNumber) {
return false;
}
return true;
}
/**
* @return the cents
*/
public short getCents() {
return cents;
}
/**
* @param cents
* the cents to set
*/
public void setCents(short cents) {
this.cents = cents;
}
/**
* @param frequency
* the frequency to set
*/
public void setFrequency(double frequency) {
this.frequency = frequency;
}
public short getPitchBend() {
return pitchBend;
}
public void setPitchBend(short pitchBend) {
this.pitchBend = pitchBend;
}
public int getPitchClass() {
return midiNumber % 12;
}
public Set<String> getSynonyms() {
return Pitch.getSynonyms(midiNumber);
}
/**
*
* Here is a JUnit example. <code>
* assertThat(somePitch.getSynonymsForPitchClass(), hasItem("Db"));
* </code>
*
* @return a {@code Set} of synonyms
*/
public Set<String> getSynonymsForPitchClass() {
return Pitch.getSynonyms(midiNumber % 12);
}
public static Set<String> getSynonyms(int midiNumber) {
Set<String> syn = new TreeSet<String>();
for (Map.Entry<String, Integer> entry : nameMap.entrySet()) {
if (entry.getValue() == midiNumber) {
// don't really feel like writing custom JUnit matchers
String key = entry.getKey();
syn.add(key);
syn.add(key.toLowerCase(Locale.ENGLISH));
syn.add(key.toUpperCase(Locale.ENGLISH));
syn.add(StringUtils.capitalize(key.toLowerCase(Locale.ENGLISH)));
}
}
return syn;
}
// this is the fastest and easiest. a pain to set up but now its set up.
public static final Map<String, Integer> nameMap = new TreeMap<String, Integer>();
static {
nameMap.put("C",
0);
nameMap.put("CS",
1);
nameMap.put("Cs",
1);
nameMap.put("C#",
1);
nameMap.put("DF",
1);
nameMap.put("Df",
1);
nameMap.put("DB",
1);
nameMap.put("D",
2);
nameMap.put("DS",
3);
nameMap.put("Ds",
3);
nameMap.put("D#",
3);
nameMap.put("EF",
3);
nameMap.put("Ef",
3);
nameMap.put("EB",
3);
nameMap.put("E",
4);
nameMap.put("F",
5);
nameMap.put("FS",
6);
nameMap.put("Fs",
6);
nameMap.put("F#",
6);
nameMap.put("GF",
6);
nameMap.put("Gf",
6);
nameMap.put("GB",
6);
nameMap.put("G",
7);
nameMap.put("GS",
8);
nameMap.put("Gs",
8);
nameMap.put("G#",
8);
nameMap.put("AF",
8);
nameMap.put("Af",
8);
nameMap.put("AB",
8);
nameMap.put("A",
9);
nameMap.put("AS",
10);
nameMap.put("As",
10);
nameMap.put("A#",
10);
nameMap.put("BF",
10);
nameMap.put("Bf",
10);
nameMap.put("BB",
10);
nameMap.put("B",
11);
nameMap.put("CB",
11);
nameMap.put("CF",
11);
nameMap.put("Cf",
11);
nameMap.put("C0",
0);
nameMap.put("CS0",
1);
nameMap.put("C#0",
1);
nameMap.put("DF0",
1);
nameMap.put("Df0",
1);
nameMap.put("DB0",
1);
nameMap.put("D0",
2);
nameMap.put("DS0",
3);
nameMap.put("D#0",
3);
nameMap.put("EF0",
3);
nameMap.put("Ef0",
3);
nameMap.put("EB0",
3);
nameMap.put("E0",
4);
nameMap.put("F0",
5);
nameMap.put("FS0",
6);
nameMap.put("F#0",
6);
nameMap.put("GF0",
6);
nameMap.put("Gf0",
6);
nameMap.put("GB0",
6);
nameMap.put("G0",
7);
nameMap.put("GS0",
8);
nameMap.put("G#0",
8);
nameMap.put("AF0",
8);
nameMap.put("Af0",
8);
nameMap.put("AB0",
8);
nameMap.put("A0",
9);
nameMap.put("AS0",
10);
nameMap.put("A#0",
10);
nameMap.put("BF0",
10);
nameMap.put("Bf0",
10);
nameMap.put("BB0",
10);
nameMap.put("B0",
11);
nameMap.put("CF1",
11);
nameMap.put("Cf1",
11);
nameMap.put("CB1",
11);
nameMap.put("C1",
12);
nameMap.put("CS1",
13);
nameMap.put("C#1",
13);
nameMap.put("DF1",
13);
nameMap.put("DB1",
13);
nameMap.put("D1",
14);
nameMap.put("DS1",
15);
nameMap.put("D#1",
15);
nameMap.put("EF1",
15);
nameMap.put("EB1",
15);
nameMap.put("E1",
16);
nameMap.put("F1",
17);
nameMap.put("FS1",
18);
nameMap.put("F#1",
18);
nameMap.put("GF1",
18);
nameMap.put("GB1",
18);
nameMap.put("G1",
19);
nameMap.put("GS1",
20);
nameMap.put("G#1",
20);
nameMap.put("AF1",
20);
nameMap.put("AB1",
20);
nameMap.put("A1",
21);
nameMap.put("AS1",
22);
nameMap.put("A#1",
22);
nameMap.put("BF1",
22);
nameMap.put("BB1",
22);
nameMap.put("B1",
23);
nameMap.put("CF2",
23);
nameMap.put("Cf2",
23);
nameMap.put("CB2",
23);
nameMap.put("C2",
24);
nameMap.put("CS2",
25);
nameMap.put("C#2",
25);
nameMap.put("DF2",
25);
nameMap.put("DB2",
25);
nameMap.put("D2",
26);
nameMap.put("DS2",
27);
nameMap.put("D#2",
27);
nameMap.put("EF2",
27);
nameMap.put("EB2",
27);
nameMap.put("E2",
28);
nameMap.put("F2",
29);
nameMap.put("FS2",
30);
nameMap.put("F#2",
30);
nameMap.put("GF2",
30);
nameMap.put("GB2",
30);
nameMap.put("G2",
31);
nameMap.put("GS2",
32);
nameMap.put("G#2",
32);
nameMap.put("AF2",
32);
nameMap.put("AB2",
32);
nameMap.put("A2",
33);
nameMap.put("AS2",
34);
nameMap.put("A#2",
34);
nameMap.put("BF2",
34);
nameMap.put("BB2",
34);
nameMap.put("B2",
35);
nameMap.put("CF3",
35);
nameMap.put("Cf3",
35);
nameMap.put("CB3",
35);
nameMap.put("C3",
36);
nameMap.put("CS3",
37);
nameMap.put("C#3",
37);
nameMap.put("DF3",
37);
nameMap.put("DB3",
37);
nameMap.put("D3",
38);
nameMap.put("DS3",
39);
nameMap.put("D#3",
39);
nameMap.put("EF3",
39);
nameMap.put("EB3",
39);
nameMap.put("E3",
40);
nameMap.put("F3",
41);
nameMap.put("FS3",
42);
nameMap.put("F#3",
42);
nameMap.put("GF3",
42);
nameMap.put("GB3",
42);
nameMap.put("G3",
43);
nameMap.put("GS3",
44);
nameMap.put("G#3",
44);
nameMap.put("AF3",
44);
nameMap.put("AB3",
44);
nameMap.put("A3",
45);
nameMap.put("AS3",
46);
nameMap.put("A#3",
46);
nameMap.put("BF3",
46);
nameMap.put("BB3",
46);
nameMap.put("B3",
47);
nameMap.put("CF4",
47);
nameMap.put("Cf4",
47);
nameMap.put("CB4",
47);
nameMap.put("C4",
48);
nameMap.put("CS4",
49);
nameMap.put("C#4",
49);
nameMap.put("DF4",
49);
nameMap.put("Df4",
49);
nameMap.put("DB4",
49);
nameMap.put("D4",
50);
nameMap.put("DS4",
51);
nameMap.put("D#4",
51);
nameMap.put("EF4",
51);
nameMap.put("Ef4",
51);
nameMap.put("EB4",
51);
nameMap.put("E4",
52);
nameMap.put("F4",
53);
nameMap.put("FS4",
54);
nameMap.put("F#4",
54);
nameMap.put("GF4",
54);
nameMap.put("Gf4",
54);
nameMap.put("GB4",
54);
nameMap.put("G4",
55);
nameMap.put("GS4",
56);
nameMap.put("G#4",
56);
nameMap.put("AF4",
56);
nameMap.put("Af4",
56);
nameMap.put("AB4",
56);
nameMap.put("A4",
57);
nameMap.put("AS4",
58);
nameMap.put("A#4",
58);
nameMap.put("BF4",
58);
nameMap.put("Bf4",
58);
nameMap.put("BB4",
58);
nameMap.put("B4",
59);
// changed PitchFactory.getPitchByName to lookup in uppercase
// so the lc versions are not needed
nameMap.put("CF5",
B4);
nameMap.put("Cf5",
B4);
nameMap.put("CB5",
B4);
nameMap.put("C5",
C5);
nameMap.put("C#5",
CS5);
nameMap.put("CS5",
CS5);
nameMap.put("DF5",
CS5);
nameMap.put("Df5",
CS5);
nameMap.put("DB5",
CS5);
nameMap.put("D5",
D5);
nameMap.put("DS5",
63);
nameMap.put("D#5",
63);
nameMap.put("EF5",
63);
nameMap.put("Ef5",
63);
nameMap.put("EB5",
63);
nameMap.put("E5",
64);
nameMap.put("F5",
65);
nameMap.put("FS5",
66);
nameMap.put("F#5",
66);
nameMap.put("GF5",
66);
nameMap.put("Gf5",
66);
nameMap.put("GB5",
66);
nameMap.put("G5",
67);
nameMap.put("GS5",
68);
nameMap.put("G#5",
68);
nameMap.put("AF5",
68);
nameMap.put("Af5",
68);
nameMap.put("AB5",
68);
nameMap.put("A5",
69);
nameMap.put("AS5",
70);
nameMap.put("A#5",
70);
nameMap.put("BF5",
70);
nameMap.put("Bf5",
70);
nameMap.put("BB5",
70);
nameMap.put("B5",
71);
nameMap.put("CF6",
71);
nameMap.put("Cf6",
71);
nameMap.put("CB6",
71);
nameMap.put("C6",
72);
nameMap.put("CS6",
73);
nameMap.put("C#6",
73);
nameMap.put("DF6",
73);
nameMap.put("Df6",
73);
nameMap.put("DB6",
73);
nameMap.put("D6",
74);
nameMap.put("DS6",
75);
nameMap.put("D#6",
75);
nameMap.put("EF6",
75);
nameMap.put("Ef6",
75);
nameMap.put("EB6",
75);
nameMap.put("E6",
76);
nameMap.put("F6",
77);
nameMap.put("FS6",
78);
nameMap.put("F#6",
78);
nameMap.put("GF6",
78);
nameMap.put("Gf6",
78);
nameMap.put("GB6",
78);
nameMap.put("G6",
79);
nameMap.put("GS6",
80);
nameMap.put("G#6",
80);
nameMap.put("AF6",
80);
nameMap.put("Af6",
80);
nameMap.put("AB6",
80);
nameMap.put("A6",
81);
nameMap.put("AS6",
82);
nameMap.put("A#6",
82);
nameMap.put("BF6",
82);
nameMap.put("Bf6",
82);
nameMap.put("BB6",
82);
nameMap.put("B6",
83);
nameMap.put("CF7",
83);
nameMap.put("Cf7",
83);
nameMap.put("CB7",
83);
nameMap.put("C7",
84);
nameMap.put("CS7",
85);
nameMap.put("C#7",
85);
nameMap.put("DF7",
85);
nameMap.put("Df7",
85);
nameMap.put("DB7",
85);
nameMap.put("D7",
86);
nameMap.put("DS7",
87);
nameMap.put("D#7",
87);
nameMap.put("EF7",
87);
nameMap.put("Ef7",
87);
nameMap.put("EB7",
87);
nameMap.put("E7",
88);
nameMap.put("F7",
89);
nameMap.put("FS7",
90);
nameMap.put("F#7",
90);
nameMap.put("GF7",
90);
nameMap.put("Gf7",
90);
nameMap.put("GB7",
90);
nameMap.put("G7",
91);
nameMap.put("GS7",
92);
nameMap.put("G#7",
92);
nameMap.put("AF7",
92);
nameMap.put("Af7",
92);
nameMap.put("AB7",
92);
nameMap.put("A7",
93);
nameMap.put("AS7",
94);
nameMap.put("A#7",
94);
nameMap.put("BF7",
94);
nameMap.put("Bf7",
94);
nameMap.put("BB7",
94);
nameMap.put("B7",
95);
nameMap.put("CF8",
95);
nameMap.put("Cf8",
95);
nameMap.put("CB8",
95);
nameMap.put("C8",
96);
nameMap.put("CS8",
97);
nameMap.put("C#8",
97);
nameMap.put("DF8",
97);
nameMap.put("Df8",
97);
nameMap.put("DB8",
97);
nameMap.put("D8",
98);
nameMap.put("DS8",
99);
nameMap.put("D#8",
99);
nameMap.put("EF8",
99);
nameMap.put("Ef8",
99);
nameMap.put("EB8",
99);
nameMap.put("E8",
100);
nameMap.put("F8",
101);
nameMap.put("FS8",
102);
nameMap.put("F#8",
102);
nameMap.put("GF8",
102);
nameMap.put("Gf8",
102);
nameMap.put("GB8",
102);
nameMap.put("G8",
103);
nameMap.put("GS8",
104);
nameMap.put("G#8",
104);
nameMap.put("AF8",
104);
nameMap.put("Af8",
104);
nameMap.put("AB8",
104);
nameMap.put("A8",
105);
nameMap.put("AS8",
106);
nameMap.put("A#8",
106);
nameMap.put("BF8",
106);
nameMap.put("Bf8",
106);
nameMap.put("BB8",
106);
nameMap.put("B8",
107);
nameMap.put("CF9",
107);
nameMap.put("Cf9",
107);
nameMap.put("CB9",
107);
nameMap.put("C9",
108);
nameMap.put("CS9",
109);
nameMap.put("C#9",
109);
nameMap.put("DF9",
109);
nameMap.put("Df9",
109);
nameMap.put("DB9",
109);
nameMap.put("D9",
110);
nameMap.put("DS9",
111);
nameMap.put("D#9",
111);
nameMap.put("EF9",
111);
nameMap.put("Ef9",
111);
nameMap.put("EB9",
111);
nameMap.put("E9",
112);
nameMap.put("F9",
113);
nameMap.put("FS9",
114);
nameMap.put("F#9",
114);
nameMap.put("GF9",
114);
nameMap.put("GB9",
114);
nameMap.put("G9",
115);
nameMap.put("GS9",
116);
nameMap.put("G#9",
116);
nameMap.put("AF9",
116);
nameMap.put("Af9",
116);
nameMap.put("AB9",
116);
nameMap.put("A9",
117);
nameMap.put("AS9",
118);
nameMap.put("A#9",
118);
nameMap.put("BF9",
118);
nameMap.put("Bf9",
118);
nameMap.put("BB9",
118);
nameMap.put("B9",
119);
nameMap.put("CF10",
119);
nameMap.put("Cf10",
119);
nameMap.put("CB10",
119);
nameMap.put("C10",
120);
nameMap.put("CS10",
121);
nameMap.put("C#10",
121);
nameMap.put("DF10",
121);
nameMap.put("Df10",
121);
nameMap.put("DB10",
121);
nameMap.put("D10",
122);
nameMap.put("DS10",
123);
nameMap.put("D#10",
123);
nameMap.put("EF10",
123);
nameMap.put("Ef10",
123);
nameMap.put("EB10",
123);
nameMap.put("E10",
124);
nameMap.put("F10",
125);
nameMap.put("FS10",
126);
nameMap.put("F#10",
126);
nameMap.put("GF10",
126);
nameMap.put("Gf10",
126);
nameMap.put("GB10",
126);
nameMap.put("G10",
127);
}
public static final PitchClassComparator pitchClassComparator = new PitchClassComparator();
public static final class PitchClassComparator implements
Comparator<Pitch>, Serializable {
/**
*
*/
private static final long serialVersionUID = 4929792298044867022L;
@Override
public int compare(Pitch o1, Pitch o2) {
int val = 0;
if (o1.getPitchClass() == o2.getPitchClass()) {
val = 0;
} else if (o1.getPitchClass() < o2.getPitchClass()) {
val = -1;
} else {
val = 1;
}
return val;
}
}
/**
* @return the preferredSpelling
*/
public String getPreferredSpelling() {
if (preferredSpelling == null || preferredSpelling.equals("") || preferredSpelling.equals("null")) {
logger.debug(
"preferred spelling empty for pitch {}",
this.midiNumber);
preferredSpelling = PitchFormat.getInstance().format(
this.midiNumber);
}
return preferredSpelling;
}
/**
* @param preferredSpelling
* the preferredSpelling to set
*/
public void setPreferredSpelling(String preferredSpelling) {
this.preferredSpelling = preferredSpelling;
};
}
/*
* History:
*
* $Log$
*
* This version: $Revision$ Last modified: $Date$ Last modified by: $Author$
*/
| spelling fix | rockymusic-core/src/main/java/com/rockhoppertech/music/Pitch.java | spelling fix | <ide><path>ockymusic-core/src/main/java/com/rockhoppertech/music/Pitch.java
<ide> // this.frequency = Pitch.midiFq(this.midiNumber);
<ide> frequency = PitchFactory.EQUAL_TEMPERAMENT.get(midiNumber);
<ide> this.preferredSpelling = PitchFormat.getInstance().format(n);
<add> logger.debug("spelling '{}'", this.preferredSpelling);
<ide> }
<ide>
<ide> /** |
|
JavaScript | mit | 150403fa800fd93ce22c8df28a3c1dd596bfcfe8 | 0 | tamiadev/grunt-tamia-sprite | /**
* Sprite generator for Tâmia
*
* @requires GraphicsMagick or Cairo
* @author Artem Sapegin (http://sapegin.me)
*/
/*jshint node:true */
module.exports = function(grunt) {
'use strict';
var fs = require('fs');
var path = require('path');
var spritesmith = require('spritesmith');
var _ = grunt.util._;
var async = grunt.util.async;
grunt.registerMultiTask('sprite', 'Sprite generator for Tâmia', function() {
this.requiresConfig([ this.name, this.target, 'src' ].join('.'));
this.requiresConfig([ this.name, this.target, 'dest' ].join('.'));
var allDone = this.async();
var params = _.defaults(this.data, {
engine: 'auto',
algorithm: 'top-down',
destStyl: this.data.dest.replace(/\.png$/, '.styl')
});
var files = this.filesSrc;
if (!files.length) {
grunt.warn('Source files not found.');
allDone();
}
// Separate retina files
var filesRetina = _.filter(files, isRetina);
files = _.filter(files, isNotRetina);
if (filesRetina.length && filesRetina.length !== files.length) {
grunt.warn('Number of normal and Retina images should be equal.');
allDone();
}
async.parallel([
function(done) {
generate(_.extend({}, params, {
src: files
}), done);
},
function(done) {
generate(_.extend({}, params, {
src: filesRetina,
dest: params.dest.replace(/\.png$/, '@2x.png'),
skipStyl: true
}), done);
}
], allDone);
});
function generate(options, done) {
if (!options.src.length) return done();
spritesmith({
src: options.src,
engine: options.engine,
algorithm: options.algorithm,
exportOpts: {
format: 'png'
}
}, function (err, result) {
if (err) {
grunt.fatal(err);
return done();
}
// Save sprite image
grunt.file.mkdir(path.dirname(options.dest));
fs.writeFileSync(options.dest, result.image, 'binary');
grunt.log.writeln('File "' + options.dest + '" created.');
if (!options.skipStyl) {
// Generate Stylus variables
var maxFingerprint = 0;
var lines = _.map(result.coordinates, function(coords, filename) {
var fingerprint = fs.statSync(filename).mtime.getTime();
if (fingerprint > maxFingerprint) {
maxFingerprint = fingerprint;
}
var name = path.basename(filename, '.png');
return ['sprite_' + name, '=', -coords.x + 'px', -coords.y + 'px', coords.width + 'px', coords.height + 'px'].join(' ');
});
// Fingerprint: timestamp of the newest file
lines.unshift('sprite-image = "../build/_sprite.png?' + maxFingerprint + '"');
// Save variables
grunt.file.write(options.destStyl, lines.join('\n'));
grunt.log.writeln('File "' + options.destStyl + '" created.');
}
done();
});
}
function isRetina(name) {
return name.indexOf('@2x') !== -1;
}
function isNotRetina(name) {
return !isRetina(name);
}
};
| tasks/sprite.js | /**
* Sprite generator for Tâmia
*
* @requires GraphicsMagick or Cairo
* @author Artem Sapegin (http://sapegin.me)
*/
/*jshint node:true */
module.exports = function(grunt) {
'use strict';
var fs = require('fs');
var path = require('path');
var spritesmith = require('spritesmith');
var _ = grunt.util._;
var async = grunt.util.async;
grunt.registerMultiTask('sprite', 'Sprite generator for Tâmia', function() {
this.requiresConfig([ this.name, this.target, 'src' ].join('.'));
this.requiresConfig([ this.name, this.target, 'dest' ].join('.'));
var allDone = this.async();
var params = _.defaults(this.data, {
engine: 'auto',
algorithm: 'top-down',
destStyl: this.data.dest.replace(/\.png$/, '.styl')
});
var files = this.filesSrc;
if (!files.length) {
grunt.warn('Source files not found.');
allDone();
}
// Separate retina files
var filesRetina = _.filter(files, isRetina);
files = _.filter(files, isNotRetina);
if (filesRetina.length && filesRetina.length !== files.length) {
grunt.warn('Number of normal and Retina images should be equal.');
allDone();
}
async.parallel([
function(done) {
generate(_.extend({}, params, {
src: files
}), done);
},
function(done) {
generate(_.extend({}, params, {
src: filesRetina,
dest: params.dest.replace(/\.png$/, '@2x.png'),
skipStyl: true
}), done);
}
], allDone);
});
function generate(options, done) {
if (!options.src.length) return done();
spritesmith({
src: options.src,
engine: options.engine,
algorithm: options.algorithm,
exportOpts: {
format: 'png'
}
}, function (err, result) {
if (err) {
grunt.fatal(err);
return done();
}
// Save sprite image
grunt.file.mkdir(path.dirname(options.dest));
fs.writeFileSync(options.dest, result.image, 'binary');
grunt.log.writeln('File "' + options.dest + '" created.');
if (!options.skipStyl) {
// Generate Stylus variables
var lines = _.map(result.coordinates, function(coords, filename) {
var name = path.basename(filename, '.png');
return ['sprite_' + name, '=', -coords.x + 'px', -coords.y + 'px', coords.width + 'px', coords.height + 'px'].join(' ');
});
// Save variables
grunt.file.write(options.destStyl, lines.join('\n'));
grunt.log.writeln('File "' + options.destStyl + '" created.');
}
done();
});
}
function isRetina(name) {
return name.indexOf('@2x') !== -1;
}
function isNotRetina(name) {
return !isRetina(name);
}
};
| Fingerprint.
| tasks/sprite.js | Fingerprint. | <ide><path>asks/sprite.js
<ide>
<ide> if (!options.skipStyl) {
<ide> // Generate Stylus variables
<add> var maxFingerprint = 0;
<ide> var lines = _.map(result.coordinates, function(coords, filename) {
<add> var fingerprint = fs.statSync(filename).mtime.getTime();
<add> if (fingerprint > maxFingerprint) {
<add> maxFingerprint = fingerprint;
<add> }
<ide> var name = path.basename(filename, '.png');
<ide> return ['sprite_' + name, '=', -coords.x + 'px', -coords.y + 'px', coords.width + 'px', coords.height + 'px'].join(' ');
<ide> });
<add>
<add> // Fingerprint: timestamp of the newest file
<add> lines.unshift('sprite-image = "../build/_sprite.png?' + maxFingerprint + '"');
<ide>
<ide> // Save variables
<ide> grunt.file.write(options.destStyl, lines.join('\n')); |
|
Java | bsd-2-clause | d7f0d6e914477e41d8c68484906a818b564f24a3 | 0 | alopatindev/smsnenado,alopatindev/smsnenado | package com.sbar.smsnenado;
import android.app.ActivityManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import com.sbar.smsnenado.BootService;
import com.sbar.smsnenado.SmsItem;
public class Common {
public static String LOG_TAG = "SmsNoMore";
public static void LOGI(final String text) { Log.i(LOG_TAG, text); }
public static void LOGE(final String text) { Log.e(LOG_TAG, text); }
public static void LOGW(final String text) { Log.w(LOG_TAG, text); }
public static final String DATETIME_FORMAT = "EE, d MMM yyyy";
public static String getConvertedDateTime(Date date) {
return new SimpleDateFormat(DATETIME_FORMAT).format(date);
}
public static String getPhoneNumber(Context context) {
TelephonyManager tm = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
String result = tm.getLine1Number();
if (result == null)
result = "";
return result;
}
public static String getAppVersion(Context context) {
try {
PackageInfo packageInfo = context
.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
LOGE("Package name not found: " + e.getMessage());
}
return "(uknown version)";
}
public static int getSmsCount(Context context) {
try {
Cursor c = context.getContentResolver().query(
Uri.parse("content://sms/inbox"),
new String[] {
"count(_id)",
},
null,
null,
null
);
c.moveToFirst();
int result = c.getInt(0);
c.close();
return result;
} catch (Throwable t) {
LOGE("getSmsCount: " + t.getMessage());
t.printStackTrace();
}
return 0;
}
static ArrayList<SmsItem> getSmsInternalQueue(Context context) {
ArrayList<SmsItem> list = new ArrayList<SmsItem>();
DatabaseConnector dc = DatabaseConnector.getInstance(context);
try {
Cursor c = dc.selectInternalMessageQueue();
if (!c.moveToFirst()) {
Common.LOGI("there are no messages with such status");
c.close();
return list;
}
do {
SmsItem item = new SmsItem();
item.mId = c.getString(
c.getColumnIndex("msg_id"));
item.mAddress = c.getString(
c.getColumnIndex("address"));
item.mText = c.getString(c.getColumnIndex("text"));
item.mUserPhoneNumber = c.getString(
c.getColumnIndex("user_phone_number"));
item.mDate = new Date(c.getLong(
c.getColumnIndex("date")));
item.mStatus = c.getInt(c.getColumnIndex("status"));
//item.mRead = c.getString(c.getColumnIndex("read")).equals("1");
item.mRead = true;
item.mSubscriptionAgreed =
c.getString(c.getColumnIndex("subscription_agreed"))
.equals("1");
Common.LOGI(" getSmsInternalQueue : " + item);
list.add(item);
} while (c.moveToNext());
c.close();
} catch (Throwable t) {
Common.LOGE("getSmsListByStatus failed: " + t.getMessage());
t.printStackTrace();
}
return list;
}
private static ArrayList<SmsItem> trimToSizeList(ArrayList<SmsItem> list,
int size) {
while (list.size() > size) {
list.remove(list.size() - 1);
}
return list;
}
public static ArrayList<String> s_idCache = new ArrayList<String>();
static ArrayList<SmsItem> getSmsList(Context context, int from, int limit) {
ArrayList<SmsItem> list = new ArrayList<SmsItem>();
SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(context);
boolean markSpamAsRead = false;
boolean markConfirmationsAsRead = false;
/*boolean markSpamAsRead = sharedPref.getBoolean(
SettingsActivity.KEY_BOOL_MARK_AS_READ_NEW_SPAM,
true);
boolean markConfirmationsAsRead = sharedPref.getBoolean(
SettingsActivity.KEY_BOOL_MARK_AS_READ_CONFIRMATIONS,
true);*/
boolean hideConfirmations = sharedPref.getBoolean(
SettingsActivity.KEY_BOOL_HIDE_CONFIRMATIONS,
true);
DatabaseConnector dc = DatabaseConnector.getInstance(context);
boolean networkAvailable = isNetworkAvailable(context);
int smsNumber = Common.getSmsCount(context);
int num = 0;
int skipped = 0;
do {
try {
Cursor c = context.getContentResolver().query(
Uri.parse("content://sms/inbox"),
new String[] {
"_id",
"address",
"date",
"body",
"read",
},
null,
null,
"date desc limit " + (from + skipped) +
"," + limit
);
if (!c.moveToFirst() || c.getCount() == 0) {
Common.LOGI("there are no more messages");
c.close();
return trimToSizeList(list, limit);
}
do {
SmsItem item = new SmsItem();
item.mId = c.getString(c.getColumnIndex("_id"));
boolean addToList = true;
for (String id : s_idCache) {
if (id.equals(item.mId)) {
addToList = false;
break;
}
}
if (!addToList) {
skipped++;
continue;
}
s_idCache.add(item.mId);
item.mAddress = c.getString(c.getColumnIndex("address"));
item.mText = c.getString(c.getColumnIndex("body"));
item.mDate = new Date(c.getLong(c.getColumnIndex("date")));
item.mRead = c.getString(c.getColumnIndex("read"))
.equals("1");
item.mOrderId = dc.getOrderId(item.mId);
BootService service = BootService.getInstance();
int messageStatus = dc.getMessageStatus(item.mId);
boolean knownMessage = messageStatus !=
SmsItem.STATUS_UNKNOWN;
boolean blackListed = dc.isBlackListed(item.mAddress);
if (!knownMessage) {
if (item.mAddress.equals(
SmsnenadoAPI.SMS_CONFIRM_ADDRESS)) {
if (!item.mRead && markConfirmationsAsRead) {
Common.setSmsAsRead(context, item.mId);
if (service != null)
service.onReceiveConfirmation(item.mText);
Common.LOGI("marked confirmation as read");
}
} else if (blackListed) {
Common.LOGI("this message is marked as spam");
messageStatus = SmsItem.STATUS_SPAM;
if (!item.mRead && markSpamAsRead) {
Common.setSmsAsRead(context, item.mId);
Common.LOGI("...and as read");
}
}
Common.LOGI("got new message: status=" + item.mStatus);
dc.addMessage(item.mId, item.mStatus, item.mDate,
item.mAddress);
} else {
if (messageStatus == SmsItem.STATUS_NONE &&
blackListed) {
Common.LOGI("this message is marked as spam");
messageStatus = SmsItem.STATUS_SPAM;
if (!item.mRead && markSpamAsRead) {
Common.setSmsAsRead(context, item.mId);
Common.LOGI("...and as read");
}
} else if (blackListed && (
messageStatus == SmsItem.STATUS_IN_QUEUE ||
(messageStatus != SmsItem.STATUS_UNSUBSCRIBED &&
messageStatus != SmsItem.STATUS_NONE &&
messageStatus != SmsItem.STATUS_SPAM &&
messageStatus !=
SmsItem.STATUS_IN_INTERNAL_QUEUE &&
messageStatus != SmsItem.STATUS_UNKNOWN))) {
if (!item.mOrderId.isEmpty()) {
if (networkAvailable && service != null)
service.getAPI().statusRequest(item.mOrderId,
item.mId);
} else {
Common.LOGI("won't send status request, orderId=''");
}
}
}
item.mStatus = messageStatus;
if (item.mAddress.equals(SmsnenadoAPI.SMS_CONFIRM_ADDRESS)) {
if (!item.mRead && markConfirmationsAsRead) {
Common.setSmsAsRead(context, item.mId);
Common.LOGI("marked confirmation as read");
}
if (hideConfirmations) {
addToList = false;
}
}
if (addToList) {
list.add(item);
} else {
++skipped;
}
++num;
} while (c.moveToNext());
c.close();
} catch (Throwable t) {
LOGE("getSmsList: " + t.getMessage());
t.printStackTrace();
}
LOGI("skipped=" + skipped + " num=" + num +
" smsNumber="+smsNumber);
} while (list.size() < limit/* && num < smsNumber - skipped - 1*/);
LOGI("smsList.size=" + list.size());
return trimToSizeList(list, limit);
}
public static void setSmsAsRead(Context context, String id) {
/*try {
ContentValues c = new ContentValues();
c.put("read", true);
context.getContentResolver().update(
Uri.parse("content://sms/"),
c,
"_id = ?",
new String[] { id });
} catch (Throwable t) {
LOGE("setSmsAsRead: " + t.getMessage());
t.printStackTrace();
}*/
}
public static String getDataDirectory(Context context) {
String dirname = String.format(
"/data/data/%s/",
context.getApplicationContext().getPackageName());
return dirname;
}
public static boolean isFirstRun(Context context) {
String dirname = getDataDirectory(context) + "shared_prefs";
File dir = new File(dirname);
return !(dir.exists() && dir.isDirectory());
}
public static boolean isServiceRunning(Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE
);
for (ActivityManager.RunningServiceInfo service :
manager.getRunningServices(Integer.MAX_VALUE)) {
if (BootService.class.getName().equals(
service.service.getClassName())) {
return true;
}
}
return false;
}
private static Handler sMainHandler = new Handler(Looper.getMainLooper());
public static void runOnMainThread(Runnable runnable) {
sMainHandler.post(runnable);
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm =
(ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo == null) {
LOGE("netInfo == null");
return false;
}
SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(context);
boolean onlyViaWifi = sharedPref.getBoolean(
SettingsActivity.KEY_BOOL_ONLY_VIA_WIFI,
false);
if (onlyViaWifi) {
int type = netInfo.getType();
if (type != ConnectivityManager.TYPE_WIFI &&
type != ConnectivityManager.TYPE_WIMAX) {
LOGI("connected but not via WiFi. it's disallowed.");
return false;
}
}
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
LOGI("connected/connecting");
return true;
}
LOGI("not connected");
return false;
}
public static boolean isValidEmail(String email) {
try {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
} catch (Throwable t) {
LOGE("isValidEmail failed: " + t.getMessage());
t.printStackTrace();
return false;
}
}
}
| src/com/sbar/smsnenado/Common.java | package com.sbar.smsnenado;
import android.app.ActivityManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import com.sbar.smsnenado.BootService;
import com.sbar.smsnenado.SmsItem;
public class Common {
public static String LOG_TAG = "SmsNoMore";
public static void LOGI(final String text) { Log.i(LOG_TAG, text); }
public static void LOGE(final String text) { Log.e(LOG_TAG, text); }
public static void LOGW(final String text) { Log.w(LOG_TAG, text); }
public static final String DATETIME_FORMAT = "EE, d MMM yyyy";
public static String getConvertedDateTime(Date date) {
return new SimpleDateFormat(DATETIME_FORMAT).format(date);
}
public static String getPhoneNumber(Context context) {
TelephonyManager tm = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getLine1Number();
}
public static String getAppVersion(Context context) {
try {
PackageInfo packageInfo = context
.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
LOGE("Package name not found: " + e.getMessage());
}
return "(uknown version)";
}
public static int getSmsCount(Context context) {
try {
Cursor c = context.getContentResolver().query(
Uri.parse("content://sms/inbox"),
new String[] {
"count(_id)",
},
null,
null,
null
);
c.moveToFirst();
int result = c.getInt(0);
c.close();
return result;
} catch (Throwable t) {
LOGE("getSmsCount: " + t.getMessage());
t.printStackTrace();
}
return 0;
}
static ArrayList<SmsItem> getSmsInternalQueue(Context context) {
ArrayList<SmsItem> list = new ArrayList<SmsItem>();
DatabaseConnector dc = DatabaseConnector.getInstance(context);
try {
Cursor c = dc.selectInternalMessageQueue();
if (!c.moveToFirst()) {
Common.LOGI("there are no messages with such status");
c.close();
return list;
}
do {
SmsItem item = new SmsItem();
item.mId = c.getString(
c.getColumnIndex("msg_id"));
item.mAddress = c.getString(
c.getColumnIndex("address"));
item.mText = c.getString(c.getColumnIndex("text"));
item.mUserPhoneNumber = c.getString(
c.getColumnIndex("user_phone_number"));
item.mDate = new Date(c.getLong(
c.getColumnIndex("date")));
item.mStatus = c.getInt(c.getColumnIndex("status"));
//item.mRead = c.getString(c.getColumnIndex("read")).equals("1");
item.mRead = true;
item.mSubscriptionAgreed =
c.getString(c.getColumnIndex("subscription_agreed"))
.equals("1");
Common.LOGI(" getSmsInternalQueue : " + item);
list.add(item);
} while (c.moveToNext());
c.close();
} catch (Throwable t) {
Common.LOGE("getSmsListByStatus failed: " + t.getMessage());
t.printStackTrace();
}
return list;
}
private static ArrayList<SmsItem> trimToSizeList(ArrayList<SmsItem> list,
int size) {
while (list.size() > size) {
list.remove(list.size() - 1);
}
return list;
}
public static ArrayList<String> s_idCache = new ArrayList<String>();
static ArrayList<SmsItem> getSmsList(Context context, int from, int limit) {
ArrayList<SmsItem> list = new ArrayList<SmsItem>();
SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(context);
boolean markSpamAsRead = false;
boolean markConfirmationsAsRead = false;
/*boolean markSpamAsRead = sharedPref.getBoolean(
SettingsActivity.KEY_BOOL_MARK_AS_READ_NEW_SPAM,
true);
boolean markConfirmationsAsRead = sharedPref.getBoolean(
SettingsActivity.KEY_BOOL_MARK_AS_READ_CONFIRMATIONS,
true);*/
boolean hideConfirmations = sharedPref.getBoolean(
SettingsActivity.KEY_BOOL_HIDE_CONFIRMATIONS,
true);
DatabaseConnector dc = DatabaseConnector.getInstance(context);
boolean networkAvailable = isNetworkAvailable(context);
int smsNumber = Common.getSmsCount(context);
int num = 0;
int skipped = 0;
do {
try {
Cursor c = context.getContentResolver().query(
Uri.parse("content://sms/inbox"),
new String[] {
"_id",
"address",
"date",
"body",
"read",
},
null,
null,
"date desc limit " + (from + skipped) +
"," + limit
);
if (!c.moveToFirst() || c.getCount() == 0) {
Common.LOGI("there are no more messages");
c.close();
return trimToSizeList(list, limit);
}
do {
SmsItem item = new SmsItem();
item.mId = c.getString(c.getColumnIndex("_id"));
boolean addToList = true;
for (String id : s_idCache) {
if (id.equals(item.mId)) {
addToList = false;
break;
}
}
if (!addToList) {
skipped++;
continue;
}
s_idCache.add(item.mId);
item.mAddress = c.getString(c.getColumnIndex("address"));
item.mText = c.getString(c.getColumnIndex("body"));
item.mDate = new Date(c.getLong(c.getColumnIndex("date")));
item.mRead = c.getString(c.getColumnIndex("read"))
.equals("1");
item.mOrderId = dc.getOrderId(item.mId);
BootService service = BootService.getInstance();
int messageStatus = dc.getMessageStatus(item.mId);
boolean knownMessage = messageStatus !=
SmsItem.STATUS_UNKNOWN;
boolean blackListed = dc.isBlackListed(item.mAddress);
if (!knownMessage) {
if (item.mAddress.equals(
SmsnenadoAPI.SMS_CONFIRM_ADDRESS)) {
if (!item.mRead && markConfirmationsAsRead) {
Common.setSmsAsRead(context, item.mId);
if (service != null)
service.onReceiveConfirmation(item.mText);
Common.LOGI("marked confirmation as read");
}
} else if (blackListed) {
Common.LOGI("this message is marked as spam");
messageStatus = SmsItem.STATUS_SPAM;
if (!item.mRead && markSpamAsRead) {
Common.setSmsAsRead(context, item.mId);
Common.LOGI("...and as read");
}
}
Common.LOGI("got new message: status=" + item.mStatus);
dc.addMessage(item.mId, item.mStatus, item.mDate,
item.mAddress);
} else {
if (messageStatus == SmsItem.STATUS_NONE &&
blackListed) {
Common.LOGI("this message is marked as spam");
messageStatus = SmsItem.STATUS_SPAM;
if (!item.mRead && markSpamAsRead) {
Common.setSmsAsRead(context, item.mId);
Common.LOGI("...and as read");
}
} else if (blackListed && (
messageStatus == SmsItem.STATUS_IN_QUEUE ||
(messageStatus != SmsItem.STATUS_UNSUBSCRIBED &&
messageStatus != SmsItem.STATUS_NONE &&
messageStatus != SmsItem.STATUS_SPAM &&
messageStatus !=
SmsItem.STATUS_IN_INTERNAL_QUEUE &&
messageStatus != SmsItem.STATUS_UNKNOWN))) {
if (!item.mOrderId.isEmpty()) {
if (networkAvailable && service != null)
service.getAPI().statusRequest(item.mOrderId,
item.mId);
} else {
Common.LOGI("won't send status request, orderId=''");
}
}
}
item.mStatus = messageStatus;
if (item.mAddress.equals(SmsnenadoAPI.SMS_CONFIRM_ADDRESS)) {
if (!item.mRead && markConfirmationsAsRead) {
Common.setSmsAsRead(context, item.mId);
Common.LOGI("marked confirmation as read");
}
if (hideConfirmations) {
addToList = false;
}
}
if (addToList) {
list.add(item);
} else {
++skipped;
}
++num;
} while (c.moveToNext());
c.close();
} catch (Throwable t) {
LOGE("getSmsList: " + t.getMessage());
t.printStackTrace();
}
LOGI("skipped=" + skipped + " num=" + num +
" smsNumber="+smsNumber);
} while (list.size() < limit/* && num < smsNumber - skipped - 1*/);
LOGI("smsList.size=" + list.size());
return trimToSizeList(list, limit);
}
public static void setSmsAsRead(Context context, String id) {
/*try {
ContentValues c = new ContentValues();
c.put("read", true);
context.getContentResolver().update(
Uri.parse("content://sms/"),
c,
"_id = ?",
new String[] { id });
} catch (Throwable t) {
LOGE("setSmsAsRead: " + t.getMessage());
t.printStackTrace();
}*/
}
public static String getDataDirectory(Context context) {
String dirname = String.format(
"/data/data/%s/",
context.getApplicationContext().getPackageName());
return dirname;
}
public static boolean isFirstRun(Context context) {
String dirname = getDataDirectory(context) + "shared_prefs";
File dir = new File(dirname);
return !(dir.exists() && dir.isDirectory());
}
public static boolean isServiceRunning(Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE
);
for (ActivityManager.RunningServiceInfo service :
manager.getRunningServices(Integer.MAX_VALUE)) {
if (BootService.class.getName().equals(
service.service.getClassName())) {
return true;
}
}
return false;
}
private static Handler sMainHandler = new Handler(Looper.getMainLooper());
public static void runOnMainThread(Runnable runnable) {
sMainHandler.post(runnable);
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm =
(ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo == null) {
LOGE("netInfo == null");
return false;
}
SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(context);
boolean onlyViaWifi = sharedPref.getBoolean(
SettingsActivity.KEY_BOOL_ONLY_VIA_WIFI,
false);
if (onlyViaWifi) {
int type = netInfo.getType();
if (type != ConnectivityManager.TYPE_WIFI &&
type != ConnectivityManager.TYPE_WIMAX) {
LOGI("connected but not via WiFi. it's disallowed.");
return false;
}
}
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
LOGI("connected/connecting");
return true;
}
LOGI("not connected");
return false;
}
public static boolean isValidEmail(String email) {
try {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
} catch (Throwable t) {
LOGE("isValidEmail failed: " + t.getMessage());
t.printStackTrace();
return false;
}
}
}
| crash fix
| src/com/sbar/smsnenado/Common.java | crash fix | <ide><path>rc/com/sbar/smsnenado/Common.java
<ide> public static String getPhoneNumber(Context context) {
<ide> TelephonyManager tm = (TelephonyManager)
<ide> context.getSystemService(Context.TELEPHONY_SERVICE);
<del> return tm.getLine1Number();
<add> String result = tm.getLine1Number();
<add> if (result == null)
<add> result = "";
<add> return result;
<ide> }
<ide>
<ide> public static String getAppVersion(Context context) { |
|
Java | mit | 92b0c5a4090ba24f313f5db0f766dd7799b33a43 | 0 | CS2103JAN2017-W14-B2/main,CS2103JAN2017-W14-B2/main | package seedu.taskboss.logic.parser;
import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.taskboss.logic.parser.CliSyntax.PREFIX_CATEGORY;
import static seedu.taskboss.logic.parser.CliSyntax.PREFIX_END_DATE;
import static seedu.taskboss.logic.parser.CliSyntax.PREFIX_INFORMATION;
import static seedu.taskboss.logic.parser.CliSyntax.PREFIX_PRIORITY;
import static seedu.taskboss.logic.parser.CliSyntax.PREFIX_RECURRENCE;
import static seedu.taskboss.logic.parser.CliSyntax.PREFIX_START_DATE;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import seedu.taskboss.commons.exceptions.IllegalValueException;
import seedu.taskboss.logic.commands.Command;
import seedu.taskboss.logic.commands.EditCommand;
import seedu.taskboss.logic.commands.EditCommand.EditTaskDescriptor;
import seedu.taskboss.logic.commands.IncorrectCommand;
import seedu.taskboss.model.category.UniqueCategoryList;
import seedu.taskboss.model.task.DateTime;
import seedu.taskboss.model.task.Recurrence;
import seedu.taskboss.model.task.Recurrence.Frequency;
/**
* Parses input arguments and creates a new EditCommand object
*/
public class EditCommandParser {
private static final String EMPTY_STRING = "";
//@@author A0143157J
/**
* Parses the given {@code String} of arguments in the context of the EditCommand
* and returns an EditCommand object for execution.
*/
public Command parse(String args) {
assert args != null;
ArgumentTokenizer argsTokenizer =
new ArgumentTokenizer(PREFIX_PRIORITY, PREFIX_INFORMATION, PREFIX_RECURRENCE,
PREFIX_START_DATE, PREFIX_END_DATE, PREFIX_CATEGORY);
argsTokenizer.tokenize(args);
List<Optional<String>> preambleFields = ParserUtil.
splitPreamble(argsTokenizer.getPreamble().orElse(EMPTY_STRING), 2);
Optional<Integer> index = preambleFields.get(0).flatMap(ParserUtil::parseIndex);
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
EditTaskDescriptor editTaskDescriptor = new EditTaskDescriptor();
try {
editTaskDescriptor.setName(ParserUtil.parseName(preambleFields.get(1)));
editTaskDescriptor.setPriorityLevel(ParserUtil.
parsePriorityLevel(argsTokenizer.getValue(PREFIX_PRIORITY)));
Optional<DateTime> startDateTimeOp = ParserUtil.
parseDateTime(argsTokenizer.getValue(PREFIX_START_DATE));
processStartDateTime(args, editTaskDescriptor, startDateTimeOp);
Optional<DateTime> endDateTimeOp = ParserUtil.
parseDateTime(argsTokenizer.getValue(PREFIX_END_DATE));
processEndDateTime(args, editTaskDescriptor, endDateTimeOp);
editTaskDescriptor.setInformation(ParserUtil.parseInformation
(argsTokenizer.getValue(PREFIX_INFORMATION)));
processRecurrence(args, argsTokenizer, editTaskDescriptor);
editTaskDescriptor.setCategories(parseCategoriesForEdit
(ParserUtil.toSet(argsTokenizer.getAllValues(PREFIX_CATEGORY))));
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
} catch (IllegalArgumentException iae) {
return new IncorrectCommand(Recurrence.MESSAGE_RECURRENCE_CONSTRAINTS);
}
if (!editTaskDescriptor.isAnyFieldEdited()) {
return new IncorrectCommand(EditCommand.MESSAGE_NOT_EDITED);
}
return new EditCommand(index.get(), editTaskDescriptor);
}
/**
* Sets recurrence as NONE if user input is "edit INDEX r/",
* @throws IllegalValueException
*/
private void processRecurrence(String args, ArgumentTokenizer argsTokenizer, EditTaskDescriptor editTaskDescriptor)
throws IllegalValueException {
if (args.contains(PREFIX_RECURRENCE.getPrefix()) &&
argsTokenizer.getValue(PREFIX_RECURRENCE).get().equals(EMPTY_STRING)) {
editTaskDescriptor.setRecurrence(Optional.of(new Recurrence(Frequency.NONE)));
} else {
editTaskDescriptor.setRecurrence(ParserUtil.parseRecurrence
(argsTokenizer.getValue(PREFIX_RECURRENCE)));
}
}
/**
* Removes the current endDateTime if user input is "edit INDEX ed/",
* @throws IllegalValueException
*/
private void processEndDateTime(String args, EditTaskDescriptor editTaskDescriptor,
Optional<DateTime> endDateTimeOp) throws IllegalValueException {
if (!endDateTimeOp.isPresent() && args.contains(PREFIX_END_DATE.getPrefix())) {
editTaskDescriptor.setEndDateTime(Optional.of(new DateTime(EMPTY_STRING)));
} else {
editTaskDescriptor.setEndDateTime(endDateTimeOp);
}
}
/**
* Removes the current startDateTime if user input is "edit INDEX sd/",
* @throws IllegalValueException
*/
private void processStartDateTime(String args, EditTaskDescriptor editTaskDescriptor,
Optional<DateTime> startDateTimeOp) throws IllegalValueException {
if (!startDateTimeOp.isPresent() && args.contains(PREFIX_START_DATE.getPrefix())) {
editTaskDescriptor.setStartDateTime(Optional.of(new DateTime(EMPTY_STRING)));
} else {
editTaskDescriptor.setStartDateTime(startDateTimeOp);
}
}
//@@author
/**
* Parses {@code Collection<String> categories} into
* an {@code Optional<UniqueCategoryList>} if {@code categories} is non-empty.
* If {@code categories} contain only one element which is an empty string, it will be parsed into a
* {@code Optional<UniqueCategoryList>} containing zero categories.
*/
private Optional<UniqueCategoryList> parseCategoriesForEdit(Collection<String> categories)
throws IllegalValueException {
assert categories != null;
if (categories.isEmpty()) {
return Optional.empty();
}
Collection<String> categorySet = categories.size() == 1 && categories.contains(EMPTY_STRING)
? Collections.emptySet() : categories;
return Optional.of(ParserUtil.parseCategories(categorySet));
}
}
| src/main/java/seedu/taskboss/logic/parser/EditCommandParser.java | package seedu.taskboss.logic.parser;
import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.taskboss.logic.parser.CliSyntax.PREFIX_CATEGORY;
import static seedu.taskboss.logic.parser.CliSyntax.PREFIX_END_DATE;
import static seedu.taskboss.logic.parser.CliSyntax.PREFIX_INFORMATION;
import static seedu.taskboss.logic.parser.CliSyntax.PREFIX_PRIORITY;
import static seedu.taskboss.logic.parser.CliSyntax.PREFIX_RECURRENCE;
import static seedu.taskboss.logic.parser.CliSyntax.PREFIX_START_DATE;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import seedu.taskboss.commons.exceptions.IllegalValueException;
import seedu.taskboss.logic.commands.Command;
import seedu.taskboss.logic.commands.EditCommand;
import seedu.taskboss.logic.commands.EditCommand.EditTaskDescriptor;
import seedu.taskboss.logic.commands.IncorrectCommand;
import seedu.taskboss.model.category.UniqueCategoryList;
import seedu.taskboss.model.task.DateTime;
import seedu.taskboss.model.task.Recurrence;
import seedu.taskboss.model.task.Recurrence.Frequency;
/**
* Parses input arguments and creates a new EditCommand object
*/
public class EditCommandParser {
private static final String EMPTY_STRING = "";
//@@author A0143157J
/**
* Parses the given {@code String} of arguments in the context of the EditCommand
* and returns an EditCommand object for execution.
*/
public Command parse(String args) {
assert args != null;
ArgumentTokenizer argsTokenizer =
new ArgumentTokenizer(PREFIX_PRIORITY, PREFIX_INFORMATION, PREFIX_RECURRENCE,
PREFIX_START_DATE, PREFIX_END_DATE, PREFIX_CATEGORY);
argsTokenizer.tokenize(args);
List<Optional<String>> preambleFields = ParserUtil.
splitPreamble(argsTokenizer.getPreamble().orElse(EMPTY_STRING), 2);
Optional<Integer> index = preambleFields.get(0).flatMap(ParserUtil::parseIndex);
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
EditTaskDescriptor editTaskDescriptor = new EditTaskDescriptor();
try {
editTaskDescriptor.setName(ParserUtil.parseName(preambleFields.get(1)));
editTaskDescriptor.setPriorityLevel(ParserUtil.
parsePriorityLevel(argsTokenizer.getValue(PREFIX_PRIORITY)));
Optional<DateTime> startDateTimeOp = ParserUtil.
parseDateTime(argsTokenizer.getValue(PREFIX_START_DATE));
// if user input is "edit INDEX sd/", remove the current startDateTime
if (!startDateTimeOp.isPresent() && args.contains(PREFIX_START_DATE.getPrefix())) {
editTaskDescriptor.setStartDateTime(Optional.of(new DateTime(EMPTY_STRING)));
} else {
editTaskDescriptor.setStartDateTime(startDateTimeOp);
}
Optional<DateTime> endDateTimeOp = ParserUtil.
parseDateTime(argsTokenizer.getValue(PREFIX_END_DATE));
// if user input is "edit INDEX ed/", remove the current endDateTime
if (!endDateTimeOp.isPresent() && args.contains(PREFIX_END_DATE.getPrefix())) {
editTaskDescriptor.setEndDateTime(Optional.of(new DateTime(EMPTY_STRING)));
} else {
editTaskDescriptor.setEndDateTime(endDateTimeOp);
}
editTaskDescriptor.setInformation(ParserUtil.parseInformation
(argsTokenizer.getValue(PREFIX_INFORMATION)));
// if user in put is "edit INDEX r/", set recurrence as NONE
if (args.contains(PREFIX_RECURRENCE.getPrefix()) &&
argsTokenizer.getValue(PREFIX_RECURRENCE).get().equals(EMPTY_STRING)) {
editTaskDescriptor.setRecurrence(Optional.of(new Recurrence(Frequency.NONE)));
} else {
editTaskDescriptor.setRecurrence(ParserUtil.parseRecurrence
(argsTokenizer.getValue(PREFIX_RECURRENCE)));
}
editTaskDescriptor.setCategories(parseCategoriesForEdit
(ParserUtil.toSet(argsTokenizer.getAllValues(PREFIX_CATEGORY))));
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
} catch (IllegalArgumentException iae) {
return new IncorrectCommand(Recurrence.MESSAGE_RECURRENCE_CONSTRAINTS);
}
if (!editTaskDescriptor.isAnyFieldEdited()) {
return new IncorrectCommand(EditCommand.MESSAGE_NOT_EDITED);
}
return new EditCommand(index.get(), editTaskDescriptor);
}
//@@author
/**
* Parses {@code Collection<String> categories} into
* an {@code Optional<UniqueCategoryList>} if {@code categories} is non-empty.
* If {@code categories} contain only one element which is an empty string, it will be parsed into a
* {@code Optional<UniqueCategoryList>} containing zero categories.
*/
private Optional<UniqueCategoryList> parseCategoriesForEdit(Collection<String> categories)
throws IllegalValueException {
assert categories != null;
if (categories.isEmpty()) {
return Optional.empty();
}
Collection<String> categorySet = categories.size() == 1 && categories.contains(EMPTY_STRING)
? Collections.emptySet() : categories;
return Optional.of(ParserUtil.parseCategories(categorySet));
}
}
| Increase SLAP::EditCommandParser
| src/main/java/seedu/taskboss/logic/parser/EditCommandParser.java | Increase SLAP::EditCommandParser | <ide><path>rc/main/java/seedu/taskboss/logic/parser/EditCommandParser.java
<ide>
<ide> Optional<DateTime> startDateTimeOp = ParserUtil.
<ide> parseDateTime(argsTokenizer.getValue(PREFIX_START_DATE));
<del> // if user input is "edit INDEX sd/", remove the current startDateTime
<del> if (!startDateTimeOp.isPresent() && args.contains(PREFIX_START_DATE.getPrefix())) {
<del> editTaskDescriptor.setStartDateTime(Optional.of(new DateTime(EMPTY_STRING)));
<del> } else {
<del> editTaskDescriptor.setStartDateTime(startDateTimeOp);
<del> }
<add> processStartDateTime(args, editTaskDescriptor, startDateTimeOp);
<ide>
<ide> Optional<DateTime> endDateTimeOp = ParserUtil.
<ide> parseDateTime(argsTokenizer.getValue(PREFIX_END_DATE));
<del> // if user input is "edit INDEX ed/", remove the current endDateTime
<del> if (!endDateTimeOp.isPresent() && args.contains(PREFIX_END_DATE.getPrefix())) {
<del> editTaskDescriptor.setEndDateTime(Optional.of(new DateTime(EMPTY_STRING)));
<del> } else {
<del> editTaskDescriptor.setEndDateTime(endDateTimeOp);
<del> }
<add> processEndDateTime(args, editTaskDescriptor, endDateTimeOp);
<ide>
<ide> editTaskDescriptor.setInformation(ParserUtil.parseInformation
<ide> (argsTokenizer.getValue(PREFIX_INFORMATION)));
<del>
<del> // if user in put is "edit INDEX r/", set recurrence as NONE
<del> if (args.contains(PREFIX_RECURRENCE.getPrefix()) &&
<del> argsTokenizer.getValue(PREFIX_RECURRENCE).get().equals(EMPTY_STRING)) {
<del> editTaskDescriptor.setRecurrence(Optional.of(new Recurrence(Frequency.NONE)));
<del> } else {
<del> editTaskDescriptor.setRecurrence(ParserUtil.parseRecurrence
<del> (argsTokenizer.getValue(PREFIX_RECURRENCE)));
<del> }
<del>
<add> processRecurrence(args, argsTokenizer, editTaskDescriptor);
<ide> editTaskDescriptor.setCategories(parseCategoriesForEdit
<ide> (ParserUtil.toSet(argsTokenizer.getAllValues(PREFIX_CATEGORY))));
<ide> } catch (IllegalValueException ive) {
<ide> }
<ide>
<ide> return new EditCommand(index.get(), editTaskDescriptor);
<add> }
<add>
<add> /**
<add> * Sets recurrence as NONE if user input is "edit INDEX r/",
<add> * @throws IllegalValueException
<add> */
<add> private void processRecurrence(String args, ArgumentTokenizer argsTokenizer, EditTaskDescriptor editTaskDescriptor)
<add> throws IllegalValueException {
<add> if (args.contains(PREFIX_RECURRENCE.getPrefix()) &&
<add> argsTokenizer.getValue(PREFIX_RECURRENCE).get().equals(EMPTY_STRING)) {
<add> editTaskDescriptor.setRecurrence(Optional.of(new Recurrence(Frequency.NONE)));
<add> } else {
<add> editTaskDescriptor.setRecurrence(ParserUtil.parseRecurrence
<add> (argsTokenizer.getValue(PREFIX_RECURRENCE)));
<add> }
<add> }
<add>
<add> /**
<add> * Removes the current endDateTime if user input is "edit INDEX ed/",
<add> * @throws IllegalValueException
<add> */
<add> private void processEndDateTime(String args, EditTaskDescriptor editTaskDescriptor,
<add> Optional<DateTime> endDateTimeOp) throws IllegalValueException {
<add> if (!endDateTimeOp.isPresent() && args.contains(PREFIX_END_DATE.getPrefix())) {
<add> editTaskDescriptor.setEndDateTime(Optional.of(new DateTime(EMPTY_STRING)));
<add> } else {
<add> editTaskDescriptor.setEndDateTime(endDateTimeOp);
<add> }
<add> }
<add>
<add> /**
<add> * Removes the current startDateTime if user input is "edit INDEX sd/",
<add> * @throws IllegalValueException
<add> */
<add> private void processStartDateTime(String args, EditTaskDescriptor editTaskDescriptor,
<add> Optional<DateTime> startDateTimeOp) throws IllegalValueException {
<add> if (!startDateTimeOp.isPresent() && args.contains(PREFIX_START_DATE.getPrefix())) {
<add> editTaskDescriptor.setStartDateTime(Optional.of(new DateTime(EMPTY_STRING)));
<add> } else {
<add> editTaskDescriptor.setStartDateTime(startDateTimeOp);
<add> }
<ide> }
<ide>
<ide> //@@author |
|
JavaScript | mit | 3761a449c1c713d4d6102ef5d10c3d9487c62195 | 0 | tjcsl/director,tjcsl/director,tjcsl/director,tjcsl/director | $(document).ready(function() {
$("#console").click(function() {
$("#input").focus();
});
$.ajaxSetup({
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", csrf_token);
}
});
var history = [];
var history_point = 0;
$(document).keydown(function(e) {
if (e.which == 38) {
history_point += 1;
if (history_point < history.length) {
$("#input").val(history[history_point]);
}
else {
history_point = history.length - 1;
}
e.preventDefault();
}
if (e.which == 40) {
history_point -= 1;
if (history_point >= 0 && history.length > 0) {
$("#input").val(history[history_point]);
}
else {
$("#input").val("");
history_point = -1;
}
e.preventDefault();
}
});
$.post(sql_endpoint, {"version": true}, function(data) {
$("#output").append(data + "\n");
});
$("#input").keypress(function(e) {
if (e.which == 13) {
var val = $(this).val();
if (val) {
if (val == "exit" || val == "\\q" || val == ".q") {
window.location.href = back_endpoint;
return;
}
if ($.trim(val.toLowerCase()) == "\\! clear") {
$("#output").text("");
$(this).val("");
return;
}
$("#output").append($("#ps").text() + val + "\n");
$("#console table").hide();
$.post(sql_endpoint, {"sql": val}, function(data) {
$("#output").append(data);
}).always(function() {
$("#console table").show();
$("#input").focus();
$("#console").scrollTop($("#console")[0].scrollHeight);
});
history.unshift(val);
history_point = -1;
$(this).val("");
}
else {
$("#output").append($("#ps").text() + "\n");
}
$("#console").scrollTop($("#console")[0].scrollHeight);
}
});
});
| web3/static/js/sql_console.js | $(document).ready(function() {
$("#console").click(function() {
$("#input").focus();
});
$.ajaxSetup({
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", csrf_token);
}
});
var history = [];
var history_point = 0;
$(document).keydown(function(e) {
if (e.which == 38) {
history_point += 1;
if (history_point < history.length) {
$("#input").val(history[history_point]);
}
else {
history_point = history.length - 1;
}
e.preventDefault();
}
if (e.which == 40) {
history_point -= 1;
if (history_point >= 0 && history.length > 0) {
$("#input").val(history[history_point]);
}
else {
$("#input").val("");
history_point = -1;
}
e.preventDefault();
}
});
$.post(sql_endpoint, {"version": true}, function(data) {
$("#output").append(data + "\n");
});
$("#input").keypress(function(e) {
if (e.which == 13) {
var val = $(this).val();
if (val) {
$(this).val("");
if (val == "exit" || val == "\\q" || val == ".q") {
window.location.href = back_endpoint;
return;
}
if ($.trim(val.toLowerCase()) == "\\! clear") {
$("#output").text("");
return;
}
$("#output").append($("#ps").text() + val + "\n");
$("#console table").hide();
$.post(sql_endpoint, {"sql": val}, function(data) {
$("#output").append(data);
}).always(function() {
$("#console table").show();
$("#input").focus();
$("#console").scrollTop($("#console")[0].scrollHeight);
});
history.unshift(val);
history_point = -1;
}
else {
$("#output").append($("#ps").text() + "\n");
}
$("#console").scrollTop($("#console")[0].scrollHeight);
}
});
});
| prevent flicker
| web3/static/js/sql_console.js | prevent flicker | <ide><path>eb3/static/js/sql_console.js
<ide> if (e.which == 13) {
<ide> var val = $(this).val();
<ide> if (val) {
<del> $(this).val("");
<ide> if (val == "exit" || val == "\\q" || val == ".q") {
<ide> window.location.href = back_endpoint;
<ide> return;
<ide> }
<ide> if ($.trim(val.toLowerCase()) == "\\! clear") {
<ide> $("#output").text("");
<add> $(this).val("");
<ide> return;
<ide> }
<ide> $("#output").append($("#ps").text() + val + "\n");
<ide> });
<ide> history.unshift(val);
<ide> history_point = -1;
<add> $(this).val("");
<ide> }
<ide> else {
<ide> $("#output").append($("#ps").text() + "\n"); |
|
Java | apache-2.0 | 6a774ee31c8ca7aeda23b8e24fda299aace5dc18 | 0 | maboelhassan/alluxio,maboelhassan/alluxio,wwjiang007/alluxio,bf8086/alluxio,maobaolong/alluxio,Reidddddd/mo-alluxio,jsimsa/alluxio,maobaolong/alluxio,apc999/alluxio,maobaolong/alluxio,EvilMcJerkface/alluxio,madanadit/alluxio,EvilMcJerkface/alluxio,maboelhassan/alluxio,jswudi/alluxio,Reidddddd/alluxio,jswudi/alluxio,wwjiang007/alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,madanadit/alluxio,jsimsa/alluxio,ShailShah/alluxio,wwjiang007/alluxio,calvinjia/tachyon,Alluxio/alluxio,bf8086/alluxio,Reidddddd/alluxio,maboelhassan/alluxio,calvinjia/tachyon,PasaLab/tachyon,wwjiang007/alluxio,calvinjia/tachyon,Alluxio/alluxio,wwjiang007/alluxio,aaudiber/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,jsimsa/alluxio,jswudi/alluxio,apc999/alluxio,PasaLab/tachyon,bf8086/alluxio,madanadit/alluxio,Reidddddd/mo-alluxio,maboelhassan/alluxio,Reidddddd/alluxio,Reidddddd/alluxio,Reidddddd/mo-alluxio,madanadit/alluxio,ChangerYoung/alluxio,aaudiber/alluxio,aaudiber/alluxio,WilliamZapata/alluxio,wwjiang007/alluxio,bf8086/alluxio,yuluo-ding/alluxio,EvilMcJerkface/alluxio,apc999/alluxio,jswudi/alluxio,maboelhassan/alluxio,Reidddddd/mo-alluxio,riversand963/alluxio,ChangerYoung/alluxio,madanadit/alluxio,jsimsa/alluxio,WilliamZapata/alluxio,WilliamZapata/alluxio,WilliamZapata/alluxio,madanadit/alluxio,uronce-cc/alluxio,maobaolong/alluxio,Alluxio/alluxio,Reidddddd/alluxio,Alluxio/alluxio,yuluo-ding/alluxio,maobaolong/alluxio,Alluxio/alluxio,wwjiang007/alluxio,jsimsa/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,ShailShah/alluxio,aaudiber/alluxio,Reidddddd/mo-alluxio,maobaolong/alluxio,Reidddddd/alluxio,calvinjia/tachyon,calvinjia/tachyon,ChangerYoung/alluxio,Alluxio/alluxio,riversand963/alluxio,jsimsa/alluxio,yuluo-ding/alluxio,Reidddddd/alluxio,jswudi/alluxio,EvilMcJerkface/alluxio,PasaLab/tachyon,apc999/alluxio,ChangerYoung/alluxio,apc999/alluxio,calvinjia/tachyon,bf8086/alluxio,calvinjia/tachyon,yuluo-ding/alluxio,bf8086/alluxio,ShailShah/alluxio,riversand963/alluxio,maobaolong/alluxio,bf8086/alluxio,WilliamZapata/alluxio,ShailShah/alluxio,uronce-cc/alluxio,apc999/alluxio,ChangerYoung/alluxio,apc999/alluxio,bf8086/alluxio,yuluo-ding/alluxio,uronce-cc/alluxio,madanadit/alluxio,Alluxio/alluxio,madanadit/alluxio,yuluo-ding/alluxio,wwjiang007/alluxio,PasaLab/tachyon,EvilMcJerkface/alluxio,jswudi/alluxio,wwjiang007/alluxio,ChangerYoung/alluxio,aaudiber/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,ShailShah/alluxio,calvinjia/tachyon,riversand963/alluxio,aaudiber/alluxio,maobaolong/alluxio,ShailShah/alluxio,uronce-cc/alluxio,PasaLab/tachyon,maobaolong/alluxio,wwjiang007/alluxio,PasaLab/tachyon,maboelhassan/alluxio,EvilMcJerkface/alluxio,aaudiber/alluxio,riversand963/alluxio,uronce-cc/alluxio,PasaLab/tachyon,uronce-cc/alluxio,maobaolong/alluxio | /*
* Licensed to the University of California, Berkeley under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package tachyon.worker.block;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import tachyon.Constants;
import tachyon.Pair;
import tachyon.conf.TachyonConf;
import tachyon.worker.BlockStoreLocation;
import tachyon.worker.block.allocator.Allocator;
import tachyon.worker.block.allocator.NaiveAllocator;
import tachyon.worker.block.evictor.EvictionPlan;
import tachyon.worker.block.evictor.Evictor;
import tachyon.worker.block.evictor.NaiveEvictor;
import tachyon.worker.block.io.BlockReader;
import tachyon.worker.block.io.BlockWriter;
import tachyon.worker.block.io.LocalFileBlockReader;
import tachyon.worker.block.io.LocalFileBlockWriter;
import tachyon.worker.block.meta.BlockMeta;
import tachyon.worker.block.meta.TempBlockMeta;
/**
* This class represents an object store that manages all the blocks in the local tiered storage.
* This store exposes simple public APIs to operate blocks. Inside this store, it creates an
* Allocator to decide where to put a new block, an Evictor to decide where to evict a stale block,
* a BlockMetadataManager to maintain the status of the tiered storage, and a LockManager to
* coordinate read/write on the same block.
* <p>
* This class is thread-safe.
*/
public class TieredBlockStore implements BlockStore {
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
private final TachyonConf mTachyonConf;
private final BlockMetadataManager mMetaManager;
private final BlockLockManager mLockManager;
private final Allocator mAllocator;
private final Evictor mEvictor;
private List<BlockAccessEventListener> mAccessEventListeners = new
ArrayList<BlockAccessEventListener>();
private List<BlockMetaEventListener> mMetaEventListeners = new
ArrayList<BlockMetaEventListener>();
/** A readwrite lock for meta data **/
private final ReentrantReadWriteLock mEvictionLock = new ReentrantReadWriteLock();
public TieredBlockStore(TachyonConf tachyonConf) {
mTachyonConf = Preconditions.checkNotNull(tachyonConf);
mMetaManager = new BlockMetadataManager(mTachyonConf);
mLockManager = new BlockLockManager(mMetaManager);
// TODO: create Allocator according to tachyonConf.
mAllocator = new NaiveAllocator(mMetaManager);
// TODO: create Evictor according to tachyonConf
mEvictor = new NaiveEvictor(mMetaManager);
}
@Override
public Optional<Long> lockBlock(long userId, long blockId) {
return mLockManager.lockBlock(userId, blockId, BlockLockType.READ);
}
@Override
public boolean unlockBlock(long lockId) {
return mLockManager.unlockBlock(lockId);
}
@Override
public boolean unlockBlock(long userId, long blockId) {
return mLockManager.unlockBlock(userId, blockId);
}
@Override
public Optional<BlockWriter> getBlockWriter(long userId, long blockId) throws IOException {
Optional<TempBlockMeta> optBlock = mMetaManager.getTempBlockMeta(blockId);
if (!optBlock.isPresent()) {
return Optional.absent();
}
BlockWriter writer = new LocalFileBlockWriter(optBlock.get());
return Optional.of(writer);
}
@Override
public Optional<BlockReader> getBlockReader(long userId, long blockId, long lockId)
throws IOException {
Preconditions.checkState(mLockManager.validateLockId(userId, blockId, lockId));
Optional<BlockMeta> optBlock = mMetaManager.getBlockMeta(blockId);
if (!optBlock.isPresent()) {
return Optional.absent();
}
BlockReader reader = new LocalFileBlockReader(optBlock.get());
return Optional.of(reader);
}
@Override
public Optional<TempBlockMeta> createBlockMeta(long userId, long blockId,
BlockStoreLocation location, long initialBlockSize) throws IOException {
mEvictionLock.readLock().lock();
Optional<TempBlockMeta> optTempBlock =
createBlockMetaNoLock(userId, blockId, location, initialBlockSize);
mEvictionLock.readLock().unlock();
return optTempBlock;
}
@Override
public Optional<BlockMeta> getBlockMeta(long userId, long blockId, long lockId) {
Preconditions.checkState(mLockManager.validateLockId(userId, blockId, lockId));
return mMetaManager.getBlockMeta(blockId);
}
@Override
public boolean commitBlock(long userId, long blockId) {
mEvictionLock.readLock().lock();
boolean result = commitBlockNoLock(userId, blockId);
mEvictionLock.readLock().unlock();
return result;
}
@Override
public boolean abortBlock(long userId, long blockId) {
mEvictionLock.readLock().lock();
boolean result = abortBlockNoLock(userId, blockId);
mEvictionLock.readLock().unlock();
return result;
}
@Override
public boolean requestSpace(long userId, long blockId, long moreBytes) throws IOException {
// TODO: Change the lock to read lock and only upgrade to write lock if necessary
mEvictionLock.writeLock().lock();
boolean result = requestSpaceNoLock(userId, blockId, moreBytes);
mEvictionLock.writeLock().unlock();
return result;
}
@Override
public boolean moveBlock(long userId, long blockId, BlockStoreLocation newLocation)
throws IOException {
mEvictionLock.readLock().lock();
// TODO: Handle absent
long lockId = mLockManager.lockBlock(userId, blockId, BlockLockType.WRITE).get();
boolean result = moveBlockNoLock(userId, blockId, newLocation);
mLockManager.unlockBlock(lockId);
mEvictionLock.readLock().unlock();
return result;
}
@Override
public boolean removeBlock(long userId, long blockId) throws IOException {
mEvictionLock.readLock().lock();
// TODO: Handle absent
long lockId = mLockManager.lockBlock(userId, blockId, BlockLockType.WRITE).get();
boolean result = removeBlockNoLock(userId, blockId);
mLockManager.unlockBlock(lockId);
mEvictionLock.readLock().unlock();
return result;
}
@Override
public void accessBlock(long userId, long blockId) {
for (BlockAccessEventListener listener: mAccessEventListeners) {
listener.onAccessBlock(userId, blockId);
}
}
@Override
public boolean freeSpace(long userId, long availableBytes, BlockStoreLocation location)
throws IOException {
mEvictionLock.writeLock().lock();
boolean result = freeSpaceNoEvictionLock(userId, availableBytes, location);
mEvictionLock.writeLock().unlock();
return result;
}
@Override
public boolean cleanupUser(long userId) {
mEvictionLock.readLock().lock();
mMetaManager.cleanupUser(userId);
mLockManager.cleanupUser(userId);
mEvictionLock.readLock().unlock();
return true;
}
@Override
public BlockStoreMeta getBlockStoreMeta() {
return mMetaManager.getBlockStoreMeta();
}
@Override
public void registerMetaListener(BlockMetaEventListener listener) {
mMetaEventListeners.add(listener);
}
@Override
public void registerAccessListener(BlockAccessEventListener listener) {
mAccessEventListeners.add(listener);
}
private Optional<TempBlockMeta> createBlockMetaNoLock(long userId, long blockId,
BlockStoreLocation location, long initialBlockSize) throws IOException {
Optional<TempBlockMeta> optTempBlock =
mAllocator.allocateBlock(userId, blockId, initialBlockSize, location);
if (!optTempBlock.isPresent()) {
// Failed to allocate a temp block, let Evictor kick in to ensure sufficient space available.
// Upgrade to write lock to guard evictor.
mEvictionLock.readLock().unlock();
mEvictionLock.writeLock().lock();
boolean result = freeSpaceNoEvictionLock(userId, initialBlockSize, location);
// Downgrade to read lock again after eviction
mEvictionLock.readLock().lock();
mEvictionLock.writeLock().unlock();
// Not enough space in this block store, let's try to free some space.
if (!result) {
LOG.error("Cannot free {} bytes space in {}", initialBlockSize, location);
return Optional.absent();
}
optTempBlock = mAllocator.allocateBlock(userId, blockId, initialBlockSize, location);
Preconditions.checkState(optTempBlock.isPresent(), "Cannot allocate block {}:", blockId);
}
// Add allocated temp block to metadata manager
mMetaManager.addTempBlockMeta(optTempBlock.get());
return optTempBlock;
}
private boolean commitBlockNoLock(long userId, long blockId) {
Optional<TempBlockMeta> optTempBlock = mMetaManager.getTempBlockMeta(blockId);
if (!optTempBlock.isPresent()) {
return false;
}
TempBlockMeta tempBlock = optTempBlock.get();
for (BlockMetaEventListener listener: mMetaEventListeners) {
listener.preCommitBlock(userId, blockId, tempBlock.getBlockLocation());
}
// Check the userId is the owner of this temp block
if (tempBlock.getUserId() != userId) {
return false;
}
String sourcePath = tempBlock.getPath();
String destPath = tempBlock.getCommitPath();
boolean renamed = new File(sourcePath).renameTo(new File(destPath));
if (!renamed) {
return false;
}
if (!mMetaManager.commitTempBlockMeta(tempBlock)) {
return false;
}
for (BlockMetaEventListener listener : mMetaEventListeners) {
listener.postCommitBlock(userId, blockId, tempBlock.getBlockLocation());
}
return true;
}
private boolean abortBlockNoLock(long userId, long blockId) {
Optional<TempBlockMeta> optTempBlock = mMetaManager.getTempBlockMeta(blockId);
if (!optTempBlock.isPresent()) {
return false;
}
TempBlockMeta tempBlock = optTempBlock.get();
// Check the userId is the owner of this temp block
if (tempBlock.getUserId() != userId) {
return false;
}
String path = tempBlock.getPath();
boolean deleted = new File(path).delete();
if (!deleted) {
return false;
}
return mMetaManager.abortTempBlockMeta(tempBlock);
}
private boolean requestSpaceNoLock(long userId, long blockId, long moreBytes) throws IOException {
Optional<TempBlockMeta> optTempBlock = mMetaManager.getTempBlockMeta(blockId);
if (!optTempBlock.isPresent()) {
return false;
}
TempBlockMeta tempBlock = optTempBlock.get();
BlockStoreLocation location = tempBlock.getBlockLocation();
if (!freeSpaceNoEvictionLock(userId, moreBytes, location)) {
return false;
}
// Increase the size of this temp block
mMetaManager.resizeTempBlockMeta(tempBlock, tempBlock.getBlockSize() + moreBytes);
return true;
}
private boolean moveBlockNoLock(long userId, long blockId, BlockStoreLocation newLocation)
throws IOException {
for (BlockMetaEventListener listener: mMetaEventListeners) {
listener.preMoveBlock(userId, blockId, newLocation);
}
Optional<BlockMeta> optSrcBlock = mMetaManager.getBlockMeta(blockId);
if (!optSrcBlock.isPresent()) {
return false;
}
String srcPath = optSrcBlock.get().getPath();
Optional<BlockMeta> optDestBlock = mMetaManager.moveBlockMeta(userId, blockId, newLocation);
if (!optDestBlock.isPresent()) {
return false;
}
String destPath = optDestBlock.get().getPath();
if(!new File(srcPath).renameTo(new File(destPath))) {
return false;
}
for (BlockMetaEventListener listener: mMetaEventListeners) {
listener.postMoveBlock(userId, blockId, newLocation);
}
return true;
}
private boolean removeBlockNoLock(long userId, long blockId) throws IOException {
for (BlockMetaEventListener listener: mMetaEventListeners) {
listener.preRemoveBlock(userId, blockId);
}
Optional<BlockMeta> optBlock = mMetaManager.getBlockMeta(blockId);
if (!optBlock.isPresent()) {
LOG.error("Block is not present");
return false;
}
BlockMeta block = optBlock.get();
// Delete metadata of the block
if (!mMetaManager.removeBlockMeta(block)) {
LOG.error("Unable to remove metadata");
return false;
}
// Delete the data file of the block
if (!new File(block.getPath()).delete()) {
return false;
}
for (BlockMetaEventListener listener: mMetaEventListeners) {
listener.postRemoveBlock(userId, blockId);
}
return true;
}
private boolean freeSpaceNoEvictionLock(long userId, long availableBytes,
BlockStoreLocation location) throws IOException {
Optional<EvictionPlan> optPlan = mEvictor.freeSpace(availableBytes, location);
// Absent plan means failed to evict enough space.
if (!optPlan.isPresent()) {
LOG.error("Failed to free space: no eviction plan by evictor");
return false;
}
EvictionPlan plan = optPlan.get();
// Step1: remove blocks to make room.
for (long blockId : plan.toEvict()) {
// TODO: Handle absent
long lockId = mLockManager.lockBlock(userId, blockId, BlockLockType.WRITE).get();
boolean result = removeBlockNoLock(userId, blockId);
mLockManager.unlockBlock(lockId);
if (!result) {
LOG.error("Failed to free space: cannot evict block {}", blockId);
return false;
}
}
// Step2: transfer blocks among tiers.
for (Pair<Long, BlockStoreLocation> entry : plan.toMove()) {
long blockId = entry.getFirst();
BlockStoreLocation newLocation = entry.getSecond();
// TODO: Handle absent
long lockId = mLockManager.lockBlock(userId, blockId, BlockLockType.WRITE).get();
boolean result = moveBlockNoLock(userId, blockId, newLocation);
mLockManager.unlockBlock(lockId);
if (!result) {
LOG.error("Failed to free space: cannot move block {} to {}", blockId, newLocation);
return false;
}
}
return true;
}
}
| servers/src/main/java/tachyon/worker/block/TieredBlockStore.java | /*
* Licensed to the University of California, Berkeley under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package tachyon.worker.block;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import tachyon.Constants;
import tachyon.Pair;
import tachyon.conf.TachyonConf;
import tachyon.worker.BlockStoreLocation;
import tachyon.worker.block.allocator.Allocator;
import tachyon.worker.block.allocator.NaiveAllocator;
import tachyon.worker.block.evictor.EvictionPlan;
import tachyon.worker.block.evictor.Evictor;
import tachyon.worker.block.evictor.NaiveEvictor;
import tachyon.worker.block.io.BlockReader;
import tachyon.worker.block.io.BlockWriter;
import tachyon.worker.block.io.LocalFileBlockReader;
import tachyon.worker.block.io.LocalFileBlockWriter;
import tachyon.worker.block.meta.BlockMeta;
import tachyon.worker.block.meta.TempBlockMeta;
/**
* This class represents an object store that manages all the blocks in the local tiered storage.
* This store exposes simple public APIs to operate blocks. Inside this store, it creates an
* Allocator to decide where to put a new block, an Evictor to decide where to evict a stale block,
* a BlockMetadataManager to maintain the status of the tiered storage, and a LockManager to
* coordinate read/write on the same block.
* <p>
* This class is thread-safe.
*/
public class TieredBlockStore implements BlockStore {
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
private final TachyonConf mTachyonConf;
private final BlockMetadataManager mMetaManager;
private final BlockLockManager mLockManager;
private final Allocator mAllocator;
private final Evictor mEvictor;
private List<BlockAccessEventListener> mAccessEventListeners = new
ArrayList<BlockAccessEventListener>();
private List<BlockMetaEventListener> mMetaEventListeners = new
ArrayList<BlockMetaEventListener>();
/** A readwrite lock for meta data **/
private final ReentrantReadWriteLock mEvictionLock = new ReentrantReadWriteLock();
public TieredBlockStore(TachyonConf tachyonConf) {
mTachyonConf = Preconditions.checkNotNull(tachyonConf);
mMetaManager = new BlockMetadataManager(mTachyonConf);
mLockManager = new BlockLockManager(mMetaManager);
// TODO: create Allocator according to tachyonConf.
mAllocator = new NaiveAllocator(mMetaManager);
// TODO: create Evictor according to tachyonConf
mEvictor = new NaiveEvictor(mMetaManager);
}
@Override
public Optional<Long> lockBlock(long userId, long blockId) {
return mLockManager.lockBlock(userId, blockId, BlockLockType.READ);
}
@Override
public boolean unlockBlock(long lockId) {
return mLockManager.unlockBlock(lockId);
}
@Override
public boolean unlockBlock(long userId, long blockId) {
return mLockManager.unlockBlock(userId, blockId);
}
@Override
public Optional<BlockWriter> getBlockWriter(long userId, long blockId) throws IOException {
Optional<TempBlockMeta> optBlock = mMetaManager.getTempBlockMeta(blockId);
if (!optBlock.isPresent()) {
return Optional.absent();
}
BlockWriter writer = new LocalFileBlockWriter(optBlock.get());
return Optional.of(writer);
}
@Override
public Optional<BlockReader> getBlockReader(long userId, long blockId, long lockId)
throws IOException {
Preconditions.checkState(mLockManager.validateLockId(userId, blockId, lockId));
Optional<BlockMeta> optBlock = mMetaManager.getBlockMeta(blockId);
if (!optBlock.isPresent()) {
return Optional.absent();
}
BlockReader reader = new LocalFileBlockReader(optBlock.get());
return Optional.of(reader);
}
@Override
public Optional<TempBlockMeta> createBlockMeta(long userId, long blockId,
BlockStoreLocation location, long initialBlockSize) throws IOException {
mEvictionLock.readLock().lock();
Optional<TempBlockMeta> optTempBlock =
createBlockMetaNoLock(userId, blockId, location, initialBlockSize);
mEvictionLock.readLock().unlock();
return optTempBlock;
}
@Override
public Optional<BlockMeta> getBlockMeta(long userId, long blockId, long lockId) {
Preconditions.checkState(mLockManager.validateLockId(userId, blockId, lockId));
return mMetaManager.getBlockMeta(blockId);
}
@Override
public boolean commitBlock(long userId, long blockId) {
TempBlockMeta tempBlock = mMetaManager.getTempBlockMeta(blockId).orNull();
for (BlockMetaEventListener listener: mMetaEventListeners) {
listener.preCommitBlock(userId, blockId, tempBlock.getBlockLocation());
}
mEvictionLock.readLock().lock();
boolean result = commitBlockNoLock(userId, blockId);
mEvictionLock.readLock().unlock();
if (result) {
for (BlockMetaEventListener listener : mMetaEventListeners) {
listener.postCommitBlock(userId, blockId, tempBlock.getBlockLocation());
}
}
return true;
}
@Override
public boolean abortBlock(long userId, long blockId) {
mEvictionLock.readLock().lock();
boolean result = abortBlockNoLock(userId, blockId);
mEvictionLock.readLock().unlock();
return result;
}
@Override
public boolean requestSpace(long userId, long blockId, long moreBytes) throws IOException {
// TODO: Change the lock to read lock and only upgrade to write lock if necessary
mEvictionLock.writeLock().lock();
boolean result = requestSpaceNoLock(userId, blockId, moreBytes);
mEvictionLock.writeLock().unlock();
return result;
}
@Override
public boolean moveBlock(long userId, long blockId, BlockStoreLocation newLocation)
throws IOException {
for (BlockMetaEventListener listener: mMetaEventListeners) {
listener.preMoveBlock(userId, blockId, newLocation);
}
mEvictionLock.readLock().lock();
// TODO: Handle absent
long lockId = mLockManager.lockBlock(userId, blockId, BlockLockType.WRITE).get();
boolean result = moveBlockNoLock(userId, blockId, newLocation);
mLockManager.unlockBlock(lockId);
mEvictionLock.readLock().unlock();
if (result) {
for (BlockMetaEventListener listener: mMetaEventListeners) {
listener.postMoveBlock(userId, blockId, newLocation);
}
}
return result;
}
@Override
public boolean removeBlock(long userId, long blockId) throws IOException {
for (BlockMetaEventListener listener: mMetaEventListeners) {
listener.preRemoveBlock(userId, blockId);
}
mEvictionLock.readLock().lock();
// TODO: Handle absent
long lockId = mLockManager.lockBlock(userId, blockId, BlockLockType.WRITE).get();
boolean result = removeBlockNoLock(userId, blockId);
mLockManager.unlockBlock(lockId);
mEvictionLock.readLock().unlock();
if (result) {
for (BlockMetaEventListener listener: mMetaEventListeners) {
listener.postRemoveBlock(userId, blockId);
}
}
return result;
}
@Override
public void accessBlock(long userId, long blockId) {
for (BlockAccessEventListener listener: mAccessEventListeners) {
listener.onAccessBlock(userId, blockId);
}
}
@Override
public boolean freeSpace(long userId, long availableBytes, BlockStoreLocation location)
throws IOException {
mEvictionLock.writeLock().lock();
boolean result = freeSpaceNoEvictionLock(userId, availableBytes, location);
mEvictionLock.writeLock().unlock();
return result;
}
@Override
public boolean cleanupUser(long userId) {
mEvictionLock.readLock().lock();
mMetaManager.cleanupUser(userId);
mLockManager.cleanupUser(userId);
mEvictionLock.readLock().unlock();
return true;
}
@Override
public BlockStoreMeta getBlockStoreMeta() {
return mMetaManager.getBlockStoreMeta();
}
@Override
public void registerMetaListener(BlockMetaEventListener listener) {
mMetaEventListeners.add(listener);
}
@Override
public void registerAccessListener(BlockAccessEventListener listener) {
mAccessEventListeners.add(listener);
}
private Optional<TempBlockMeta> createBlockMetaNoLock(long userId, long blockId,
BlockStoreLocation location, long initialBlockSize) throws IOException {
Optional<TempBlockMeta> optTempBlock =
mAllocator.allocateBlock(userId, blockId, initialBlockSize, location);
if (!optTempBlock.isPresent()) {
// Failed to allocate a temp block, let Evictor kick in to ensure sufficient space available.
// Upgrade to write lock to guard evictor.
mEvictionLock.readLock().unlock();
mEvictionLock.writeLock().lock();
boolean result = freeSpaceNoEvictionLock(userId, initialBlockSize, location);
// Downgrade to read lock again after eviction
mEvictionLock.readLock().lock();
mEvictionLock.writeLock().unlock();
// Not enough space in this block store, let's try to free some space.
if (!result) {
LOG.error("Cannot free {} bytes space in {}", initialBlockSize, location);
return Optional.absent();
}
optTempBlock = mAllocator.allocateBlock(userId, blockId, initialBlockSize, location);
Preconditions.checkState(optTempBlock.isPresent(), "Cannot allocate block {}:", blockId);
}
// Add allocated temp block to metadata manager
mMetaManager.addTempBlockMeta(optTempBlock.get());
return optTempBlock;
}
private boolean commitBlockNoLock(long userId, long blockId) {
Optional<TempBlockMeta> optTempBlock = mMetaManager.getTempBlockMeta(blockId);
if (!optTempBlock.isPresent()) {
return false;
}
TempBlockMeta tempBlock = optTempBlock.get();
// Check the userId is the owner of this temp block
if (tempBlock.getUserId() != userId) {
return false;
}
String sourcePath = tempBlock.getPath();
String destPath = tempBlock.getCommitPath();
boolean renamed = new File(sourcePath).renameTo(new File(destPath));
if (!renamed) {
return false;
}
return mMetaManager.commitTempBlockMeta(tempBlock);
}
private boolean abortBlockNoLock(long userId, long blockId) {
Optional<TempBlockMeta> optTempBlock = mMetaManager.getTempBlockMeta(blockId);
if (!optTempBlock.isPresent()) {
return false;
}
TempBlockMeta tempBlock = optTempBlock.get();
// Check the userId is the owner of this temp block
if (tempBlock.getUserId() != userId) {
return false;
}
String path = tempBlock.getPath();
boolean deleted = new File(path).delete();
if (!deleted) {
return false;
}
return mMetaManager.abortTempBlockMeta(tempBlock);
}
private boolean requestSpaceNoLock(long userId, long blockId, long moreBytes) throws IOException {
Optional<TempBlockMeta> optTempBlock = mMetaManager.getTempBlockMeta(blockId);
if (!optTempBlock.isPresent()) {
return false;
}
TempBlockMeta tempBlock = optTempBlock.get();
BlockStoreLocation location = tempBlock.getBlockLocation();
if (!freeSpaceNoEvictionLock(userId, moreBytes, location)) {
return false;
}
// Increase the size of this temp block
mMetaManager.resizeTempBlockMeta(tempBlock, tempBlock.getBlockSize() + moreBytes);
return true;
}
private boolean moveBlockNoLock(long userId, long blockId, BlockStoreLocation newLocation)
throws IOException {
Optional<BlockMeta> optSrcBlock = mMetaManager.getBlockMeta(blockId);
if (!optSrcBlock.isPresent()) {
return false;
}
String srcPath = optSrcBlock.get().getPath();
Optional<BlockMeta> optDestBlock = mMetaManager.moveBlockMeta(userId, blockId, newLocation);
if (!optDestBlock.isPresent()) {
return false;
}
String destPath = optDestBlock.get().getPath();
return new File(srcPath).renameTo(new File(destPath));
}
private boolean removeBlockNoLock(long userId, long blockId) throws IOException {
Optional<BlockMeta> optBlock = mMetaManager.getBlockMeta(blockId);
if (!optBlock.isPresent()) {
LOG.error("Block is not present");
return false;
}
BlockMeta block = optBlock.get();
// Delete metadata of the block
if (!mMetaManager.removeBlockMeta(block)) {
LOG.error("Unable to remove metadata");
return false;
}
// Delete the data file of the block
return new File(block.getPath()).delete();
}
private boolean freeSpaceNoEvictionLock(long userId, long availableBytes,
BlockStoreLocation location) throws IOException {
Optional<EvictionPlan> optPlan = mEvictor.freeSpace(availableBytes, location);
// Absent plan means failed to evict enough space.
if (!optPlan.isPresent()) {
LOG.error("Failed to free space: no eviction plan by evictor");
return false;
}
EvictionPlan plan = optPlan.get();
// Step1: remove blocks to make room.
for (long blockId : plan.toEvict()) {
// TODO: Handle absent
long lockId = mLockManager.lockBlock(userId, blockId, BlockLockType.WRITE).get();
boolean result = removeBlockNoLock(userId, blockId);
mLockManager.unlockBlock(lockId);
if (!result) {
LOG.error("Failed to free space: cannot evict block {}", blockId);
return false;
}
}
// Step2: transfer blocks among tiers.
for (Pair<Long, BlockStoreLocation> entry : plan.toMove()) {
long blockId = entry.getFirst();
BlockStoreLocation newLocation = entry.getSecond();
// TODO: Handle absent
long lockId = mLockManager.lockBlock(userId, blockId, BlockLockType.WRITE).get();
boolean result = moveBlockNoLock(userId, blockId, newLocation);
mLockManager.unlockBlock(lockId);
if (!result) {
LOG.error("Failed to free space: cannot move block {} to {}", blockId, newLocation);
return false;
}
}
return true;
}
}
| move BlockMetaEventListener hooks so they are triggered also by eviction
| servers/src/main/java/tachyon/worker/block/TieredBlockStore.java | move BlockMetaEventListener hooks so they are triggered also by eviction | <ide><path>ervers/src/main/java/tachyon/worker/block/TieredBlockStore.java
<ide>
<ide> @Override
<ide> public boolean commitBlock(long userId, long blockId) {
<del> TempBlockMeta tempBlock = mMetaManager.getTempBlockMeta(blockId).orNull();
<del> for (BlockMetaEventListener listener: mMetaEventListeners) {
<del> listener.preCommitBlock(userId, blockId, tempBlock.getBlockLocation());
<del> }
<del>
<ide> mEvictionLock.readLock().lock();
<ide> boolean result = commitBlockNoLock(userId, blockId);
<ide> mEvictionLock.readLock().unlock();
<del>
<del> if (result) {
<del> for (BlockMetaEventListener listener : mMetaEventListeners) {
<del> listener.postCommitBlock(userId, blockId, tempBlock.getBlockLocation());
<del> }
<del> }
<del> return true;
<add> return result;
<ide> }
<ide>
<ide> @Override
<ide> @Override
<ide> public boolean moveBlock(long userId, long blockId, BlockStoreLocation newLocation)
<ide> throws IOException {
<del> for (BlockMetaEventListener listener: mMetaEventListeners) {
<del> listener.preMoveBlock(userId, blockId, newLocation);
<del> }
<del>
<ide> mEvictionLock.readLock().lock();
<ide> // TODO: Handle absent
<ide> long lockId = mLockManager.lockBlock(userId, blockId, BlockLockType.WRITE).get();
<ide> boolean result = moveBlockNoLock(userId, blockId, newLocation);
<ide> mLockManager.unlockBlock(lockId);
<ide> mEvictionLock.readLock().unlock();
<del>
<del> if (result) {
<del> for (BlockMetaEventListener listener: mMetaEventListeners) {
<del> listener.postMoveBlock(userId, blockId, newLocation);
<del> }
<del> }
<ide> return result;
<ide> }
<ide>
<ide> @Override
<ide> public boolean removeBlock(long userId, long blockId) throws IOException {
<del> for (BlockMetaEventListener listener: mMetaEventListeners) {
<del> listener.preRemoveBlock(userId, blockId);
<del> }
<del>
<ide> mEvictionLock.readLock().lock();
<ide> // TODO: Handle absent
<ide> long lockId = mLockManager.lockBlock(userId, blockId, BlockLockType.WRITE).get();
<ide> boolean result = removeBlockNoLock(userId, blockId);
<ide> mLockManager.unlockBlock(lockId);
<ide> mEvictionLock.readLock().unlock();
<del>
<del> if (result) {
<del> for (BlockMetaEventListener listener: mMetaEventListeners) {
<del> listener.postRemoveBlock(userId, blockId);
<del> }
<del> }
<ide> return result;
<ide> }
<ide>
<ide> return false;
<ide> }
<ide> TempBlockMeta tempBlock = optTempBlock.get();
<add>
<add> for (BlockMetaEventListener listener: mMetaEventListeners) {
<add> listener.preCommitBlock(userId, blockId, tempBlock.getBlockLocation());
<add> }
<ide> // Check the userId is the owner of this temp block
<ide> if (tempBlock.getUserId() != userId) {
<ide> return false;
<ide> if (!renamed) {
<ide> return false;
<ide> }
<del> return mMetaManager.commitTempBlockMeta(tempBlock);
<add> if (!mMetaManager.commitTempBlockMeta(tempBlock)) {
<add> return false;
<add> }
<add>
<add> for (BlockMetaEventListener listener : mMetaEventListeners) {
<add> listener.postCommitBlock(userId, blockId, tempBlock.getBlockLocation());
<add> }
<add> return true;
<ide> }
<ide>
<ide> private boolean abortBlockNoLock(long userId, long blockId) {
<ide>
<ide> private boolean moveBlockNoLock(long userId, long blockId, BlockStoreLocation newLocation)
<ide> throws IOException {
<add> for (BlockMetaEventListener listener: mMetaEventListeners) {
<add> listener.preMoveBlock(userId, blockId, newLocation);
<add> }
<ide> Optional<BlockMeta> optSrcBlock = mMetaManager.getBlockMeta(blockId);
<ide> if (!optSrcBlock.isPresent()) {
<ide> return false;
<ide> }
<ide> String destPath = optDestBlock.get().getPath();
<ide>
<del> return new File(srcPath).renameTo(new File(destPath));
<add> if(!new File(srcPath).renameTo(new File(destPath))) {
<add> return false;
<add> }
<add>
<add> for (BlockMetaEventListener listener: mMetaEventListeners) {
<add> listener.postMoveBlock(userId, blockId, newLocation);
<add> }
<add> return true;
<ide> }
<ide>
<ide> private boolean removeBlockNoLock(long userId, long blockId) throws IOException {
<add> for (BlockMetaEventListener listener: mMetaEventListeners) {
<add> listener.preRemoveBlock(userId, blockId);
<add> }
<add>
<ide> Optional<BlockMeta> optBlock = mMetaManager.getBlockMeta(blockId);
<ide> if (!optBlock.isPresent()) {
<ide> LOG.error("Block is not present");
<ide> return false;
<ide> }
<ide> // Delete the data file of the block
<del> return new File(block.getPath()).delete();
<add> if (!new File(block.getPath()).delete()) {
<add> return false;
<add> }
<add>
<add> for (BlockMetaEventListener listener: mMetaEventListeners) {
<add> listener.postRemoveBlock(userId, blockId);
<add> }
<add> return true;
<ide> }
<ide>
<ide> private boolean freeSpaceNoEvictionLock(long userId, long availableBytes, |
|
Java | mit | ad1f139320fa475a4128d55bde24764da648a8e5 | 0 | conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5 | package org.opentripplanner.analyst.cluster;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.conveyal.geojson.GeoJsonModule;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.opentripplanner.analyst.PointSet;
import org.opentripplanner.analyst.ResultSet;
import org.opentripplanner.analyst.SampleSet;
import org.opentripplanner.api.model.AgencyAndIdSerializer;
import org.opentripplanner.api.model.JodaLocalDateSerializer;
import org.opentripplanner.api.model.QualifiedModeSetSerializer;
import org.opentripplanner.api.model.TraverseModeSetSerializer;
import org.opentripplanner.common.MavenVersion;
import org.opentripplanner.profile.RaptorWorkerData;
import org.opentripplanner.profile.RepeatedRaptorProfileRouter;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.graph.Graph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream;
/**
*
*/
public class AnalystWorker implements Runnable {
/**
* worker ID - just a random ID so we can differentiate machines used for computation.
* Useful to isolate the logs from a particular machine, as well as to evaluate any
* variation in performance coming from variation in the performance of the underlying
* VMs.
*
* This needs to be static so the logger can access it; see the static member class
* WorkerIdDefiner. A side effect is that only one worker can run in a given JVM. It also
* needs to be defined before the logger is defined, so that it is initialized before the
* logger is.
*/
public static final String machineId = UUID.randomUUID().toString().replaceAll("-", "");
private static final Logger LOG = LoggerFactory.getLogger(AnalystWorker.class);
public static final String WORKER_ID_HEADER = "X-Worker-Id";
public static final int POLL_TIMEOUT = 10 * 1000;
/**
* If this value is non-negative, the worker will not actually do any work. It will just report all tasks
* as completed immediately, but will fail to do so on the given percentage of tasks. This is used in testing task
* re-delivery and overall broker sanity.
*/
public int dryRunFailureRate = -1;
/** How long (minimum, in milliseconds) should this worker stay alive after receiving a single point request? */
public static final int SINGLE_POINT_KEEPALIVE = 15 * 60 * 1000;
/** should this worker shut down automatically */
public final boolean autoShutdown;
public static final Random random = new Random();
private TaskStatisticsStore statsStore;
/** is there currently a channel open to the broker to receive single point jobs? */
private volatile boolean sideChannelOpen = false;
ObjectMapper objectMapper;
String BROKER_BASE_URL = "http://localhost:9001";
static final HttpClient httpClient;
/** Cache RAPTOR data by Job ID */
private Cache<String, RaptorWorkerData> workerDataCache = CacheBuilder.newBuilder()
.maximumSize(200)
.build();
static {
PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager();
mgr.setDefaultMaxPerRoute(20);
int timeout = 10 * 1000;
SocketConfig cfg = SocketConfig.custom()
.setSoTimeout(timeout)
.build();
mgr.setDefaultSocketConfig(cfg);
httpClient = HttpClients.custom()
.setConnectionManager(mgr)
.build();
}
// Of course this will eventually need to be shared between multiple AnalystWorker threads.
ClusterGraphBuilder clusterGraphBuilder;
// Of course this will eventually need to be shared between multiple AnalystWorker threads.
PointSetDatastore pointSetDatastore;
// Clients for communicating with Amazon web services
AmazonS3 s3;
String graphId = null;
long startupTime, nextShutdownCheckTime;
// Region awsRegion = Region.getRegion(Regions.EU_CENTRAL_1);
Region awsRegion = Region.getRegion(Regions.US_EAST_1);
/** aws instance type, or null if not running on AWS */
private String instanceType;
long lastHighPriorityRequestProcessed = 0;
/**
* Queue for high-priority tasks. Should be plenty long enough to hold all that have come in -
* we don't need to block on polling the manager.
*/
private ThreadPoolExecutor highPriorityExecutor, batchExecutor;
public AnalystWorker(Properties config) {
// parse the configuration
// set up the stats store
String statsQueue = config.getProperty("statistics-queue");
if (statsQueue != null)
this.statsStore = new SQSTaskStatisticsStore(statsQueue);
else
// a stats store that does nothing.
this.statsStore = s -> {};
String addr = config.getProperty("broker-address");
String port = config.getProperty("broker-port");
if (addr != null) {
if (port != null)
this.BROKER_BASE_URL = String.format("http://%s:%s", addr, port);
else
this.BROKER_BASE_URL = String.format("http://%s", addr);
}
// set the initial graph affinity of this worker (if it is not in the config file it will be
// set to null, i.e. no graph affinity)
// we don't actually build the graph now; this is just a hint to the broker as to what
// graph this machine was intended to analyze.
this.graphId = config.getProperty("initial-graph-id");
this.pointSetDatastore = new PointSetDatastore(10, null, false, config.getProperty("pointsets-bucket"));
this.clusterGraphBuilder = new ClusterGraphBuilder(config.getProperty("graphs-bucket"));
Boolean autoShutdown = Boolean.parseBoolean(config.getProperty("auto-shutdown"));
this.autoShutdown = autoShutdown == null ? false : autoShutdown;
// Consider shutting this worker down once per hour, starting 55 minutes after it started up.
startupTime = System.currentTimeMillis();
nextShutdownCheckTime = startupTime + 55 * 60 * 1000;
// When creating the S3 and SQS clients use the default credentials chain.
// This will check environment variables and ~/.aws/credentials first, then fall back on
// the auto-assigned IAM role if this code is running on an EC2 instance.
// http://docs.aws.amazon.com/AWSSdkDocsJava/latest/DeveloperGuide/java-dg-roles.html
s3 = new AmazonS3Client();
s3.setRegion(awsRegion);
/* The ObjectMapper (de)serializes JSON. */
objectMapper = new ObjectMapper();
objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // ignore JSON fields that don't match target type
/* Tell Jackson how to (de)serialize AgencyAndIds, which appear as map keys in routing requests. */
objectMapper.registerModule(AgencyAndIdSerializer.makeModule());
/* serialize/deserialize qualified mode sets */
objectMapper.registerModule(QualifiedModeSetSerializer.makeModule());
/* serialize/deserialize Joda dates */
objectMapper.registerModule(JodaLocalDateSerializer.makeModule());
/* serialize/deserialize traversemodesets */
objectMapper.registerModule(TraverseModeSetSerializer.makeModule());
objectMapper.registerModule(new GeoJsonModule());
instanceType = getInstanceType();
}
@Override
public void run() {
// create executors with up to one thread per processor
int nP = Runtime.getRuntime().availableProcessors();
highPriorityExecutor = new ThreadPoolExecutor(1, nP, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(255));
highPriorityExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
batchExecutor = new ThreadPoolExecutor(1, nP, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(nP * 2));
batchExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
// build the graph, iff we know what graph to build
if (graphId != null) {
LOG.info("Prebuilding graph {}", graphId);
Graph graph = clusterGraphBuilder.getGraph(graphId);
// also prebuild the stop tree cache
graph.index.getStopTreeCache();
LOG.info("Done prebuilding graph {}", graphId);
}
// Start filling the work queues.
boolean idle = false;
while (true) {
long now = System.currentTimeMillis();
// Consider shutting down if enough time has passed
if (now > nextShutdownCheckTime && autoShutdown) {
if (idle && now > lastHighPriorityRequestProcessed + SINGLE_POINT_KEEPALIVE) {
LOG.warn("Machine is idle, shutting down.");
try {
Process process = new ProcessBuilder("sudo", "/sbin/shutdown", "-h", "now")
.start();
process.waitFor();
} catch (Exception ex) {
LOG.error("Unable to terminate worker", ex);
} finally {
System.exit(0);
}
}
nextShutdownCheckTime += 60 * 60 * 1000;
}
LOG.info("Long-polling for work ({} second timeout).", POLL_TIMEOUT / 1000.0);
// Long-poll (wait a few seconds for messages to become available)
List<AnalystClusterRequest> tasks = getSomeWork(WorkType.BATCH);
if (tasks == null) {
LOG.info("Didn't get any work. Retrying.");
idle = true;
continue;
}
// run through high-priority tasks first to ensure they are enqueued even if the batch
// queue blocks.
tasks.stream().filter(t -> t.outputLocation == null)
.forEach(t -> highPriorityExecutor.execute(() -> {
LOG.warn(
"Handling single point request via normal channel, side channel should open shortly.");
this.handleOneRequest(t);
}));
logQueueStatus();
// enqueue low-priority tasks; note that this may block anywhere in the process
tasks.stream().filter(t -> t.outputLocation != null)
.forEach(t -> {
// attempt to enqueue, waiting if the queue is full
while (true) {
try {
batchExecutor.execute(() -> this.handleOneRequest(t));
break;
} catch (RejectedExecutionException e) {
// queue is full, wait 200ms and try again
try {
Thread.sleep(200);
} catch (InterruptedException e1) { /* nothing */}
}
}
});
logQueueStatus();
idle = false;
}
}
private void handleOneRequest(AnalystClusterRequest clusterRequest) {
if (dryRunFailureRate >= 0) {
// This worker is running in test mode.
// It should report all work as completed without actually doing anything,
// but will fail a certain percentage of the time.
if (random.nextInt(100) >= dryRunFailureRate) {
// Pretend to succeed.
deleteRequest(clusterRequest);
} else {
LOG.info("Intentionally failing on task {}", clusterRequest.taskId);
}
return;
}
try {
long startTime = System.currentTimeMillis();
LOG.info("Handling message {}", clusterRequest.toString());
if (clusterRequest.outputLocation == null) {
// high priority
lastHighPriorityRequestProcessed = startTime;
if (!sideChannelOpen)
openSideChannel();
}
TaskStatistics ts = new TaskStatistics();
ts.pointsetId = clusterRequest.destinationPointsetId;
ts.graphId = clusterRequest.graphId;
ts.awsInstanceType = instanceType;
ts.jobId = clusterRequest.jobId;
ts.workerId = machineId;
ts.single = clusterRequest.outputLocation == null;
long graphStartTime = System.currentTimeMillis();
// Get the graph object for the ID given in the request, fetching inputs and building as needed.
// All requests handled together are for the same graph, and this call is synchronized so the graph will
// only be built once.
Graph graph = clusterGraphBuilder.getGraph(clusterRequest.graphId);
graphId = clusterRequest.graphId; // Record graphId so we "stick" to this same graph on subsequent polls
ts.graphBuild = (int) (System.currentTimeMillis() - graphStartTime);
ts.graphTripCount = graph.index.patternForTrip.size();
ts.graphStopCount = graph.index.stopForId.size();
// This result envelope will hold the result of the profile or single-time one-to-many search.
ResultEnvelope envelope = new ResultEnvelope();
if (clusterRequest.profileRequest != null) {
ts.lon = clusterRequest.profileRequest.fromLon;
ts.lat = clusterRequest.profileRequest.fromLat;
RepeatedRaptorProfileRouter router;
boolean isochrone = clusterRequest.destinationPointsetId == null;
ts.isochrone = isochrone;
if (!isochrone) {
// A pointset was specified, calculate travel times to the points in the pointset.
// Fetch the set of points we will use as destinations for this one-to-many search
PointSet pointSet = pointSetDatastore.get(clusterRequest.destinationPointsetId);
// TODO this breaks if graph has been rebuilt
SampleSet sampleSet = pointSet.getOrCreateSampleSet(graph);
router =
new RepeatedRaptorProfileRouter(graph, clusterRequest.profileRequest, sampleSet);
// no reason to cache single-point RaptorWorkerData
if (clusterRequest.outputLocation != null) {
router.raptorWorkerData = workerDataCache.get(clusterRequest.jobId, () -> {
return RepeatedRaptorProfileRouter
.getRaptorWorkerData(clusterRequest.profileRequest, graph,
sampleSet, ts);
});
}
} else {
router = new RepeatedRaptorProfileRouter(graph, clusterRequest.profileRequest);
if (clusterRequest.outputLocation == null) {
router.raptorWorkerData = workerDataCache.get(clusterRequest.jobId,
() -> RepeatedRaptorProfileRouter
.getRaptorWorkerData(clusterRequest.profileRequest, graph, null,
ts));
}
}
try {
router.route(ts);
long resultSetStart = System.currentTimeMillis();
if (isochrone) {
envelope.worstCase = new ResultSet(router.timeSurfaceRangeSet.max);
envelope.bestCase = new ResultSet(router.timeSurfaceRangeSet.min);
envelope.avgCase = new ResultSet(router.timeSurfaceRangeSet.avg);
} else {
ResultSet.RangeSet results = router
.makeResults(clusterRequest.includeTimes, !isochrone, isochrone);
// put in constructor?
envelope.bestCase = results.min;
envelope.avgCase = results.avg;
envelope.worstCase = results.max;
}
envelope.id = clusterRequest.id;
envelope.destinationPointsetId = clusterRequest.destinationPointsetId;
ts.resultSets = (int) (System.currentTimeMillis() - resultSetStart);
ts.success = true;
} catch (Exception ex) {
// Leave the envelope empty TODO include error information
ts.success = false;
}
} else {
// No profile request, this must be a plain one to many routing request.
RoutingRequest routingRequest = clusterRequest.routingRequest;
// TODO finish the non-profile case
}
if (clusterRequest.outputLocation != null) {
// Convert the result envelope and its contents to JSON and gzip it in this thread.
// Transfer the results to Amazon S3 in another thread, piping between the two.
String s3key = String.join("/", clusterRequest.jobId, clusterRequest.id + ".json.gz");
PipedInputStream inPipe = new PipedInputStream();
PipedOutputStream outPipe = new PipedOutputStream(inPipe);
new Thread(() -> {
s3.putObject(clusterRequest.outputLocation, s3key, inPipe, null);
}).start();
OutputStream gzipOutputStream = new GZIPOutputStream(outPipe);
// We could do the writeValue() in a thread instead, in which case both the DELETE and S3 options
// could consume it in the same way.
objectMapper.writeValue(gzipOutputStream, envelope);
gzipOutputStream.close();
// DELETE the task from the broker, confirming it has been handled and should not be re-delivered.
deleteRequest(clusterRequest);
} else {
// No output location on S3 specified, return the result via the broker and mark the task completed.
finishPriorityTask(clusterRequest, envelope);
}
ts.total = (int) (System.currentTimeMillis() - startTime);
statsStore.store(ts);
} catch (Exception ex) {
LOG.error("An error occurred while routing", ex);
}
}
/** Open a single point channel to the broker to receive high-priority requests immediately */
private synchronized void openSideChannel () {
if (sideChannelOpen)
return;
LOG.info("Opening side channel for single point requests.");
new Thread(() -> {
sideChannelOpen = true;
// don't keep single point connections alive forever
while (System.currentTimeMillis() < lastHighPriorityRequestProcessed + SINGLE_POINT_KEEPALIVE) {
LOG.info("Awaiting high-priority work");
try {
List<AnalystClusterRequest> tasks = getSomeWork(WorkType.HIGH_PRIORITY);
if (tasks != null)
tasks.stream().forEach(t -> highPriorityExecutor.execute(
() -> this.handleOneRequest(t)));
logQueueStatus();
} catch (Exception e) {
LOG.error("Unexpected exception getting single point work", e);
}
}
sideChannelOpen = false;
}).start();
}
public List<AnalystClusterRequest> getSomeWork(WorkType type) {
// Run a POST request (long-polling for work) indicating which graph this worker prefers to work on
String url;
if (type == WorkType.HIGH_PRIORITY)
// this is a side-channel request for single point work
url = BROKER_BASE_URL + "/single/" + graphId;
else
url = BROKER_BASE_URL + "/dequeue/" + graphId;
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(new BasicHeader(WORKER_ID_HEADER, machineId));
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
if (response.getStatusLine().getStatusCode() != 200) {
EntityUtils.consumeQuietly(entity);
return null;
}
return objectMapper.readValue(entity.getContent(), new TypeReference<List<AnalystClusterRequest>>() {
});
} catch (JsonProcessingException e) {
LOG.error("JSON processing exception while getting work", e);
} catch (SocketTimeoutException stex) {
LOG.error("Socket timeout while waiting to receive work.");
} catch (HttpHostConnectException ce) {
LOG.error("Broker refused connection. Sleeping before retry.");
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
}
} catch (IOException e) {
LOG.error("IO exception while getting work", e);
}
return null;
}
/**
* Signal the broker that the given high-priority task is completed, providing a result.
*/
public void finishPriorityTask(AnalystClusterRequest clusterRequest, Object result) {
String url = BROKER_BASE_URL + String.format("/complete/priority/%s", clusterRequest.taskId);
HttpPost httpPost = new HttpPost(url);
try {
// TODO reveal any errors etc. that occurred on the worker.
// Really this should probably be done with an InputStreamEntity and a JSON writer thread.
byte[] serializedResult = objectMapper.writeValueAsBytes(result);
httpPost.setEntity(new ByteArrayEntity(serializedResult));
HttpResponse response = httpClient.execute(httpPost);
// Signal the http client library that we're done with this response object, allowing connection reuse.
EntityUtils.consumeQuietly(response.getEntity());
if (response.getStatusLine().getStatusCode() == 200) {
LOG.info("Successfully marked task {} as completed.", clusterRequest.taskId);
} else if (response.getStatusLine().getStatusCode() == 404) {
LOG.info("Task {} was not marked as completed because it doesn't exist.", clusterRequest.taskId);
} else {
LOG.info("Failed to mark task {} as completed, ({}).", clusterRequest.taskId,
response.getStatusLine());
}
} catch (Exception e) {
LOG.warn("Failed to mark task {} as completed.", clusterRequest.taskId, e);
}
}
/**
* DELETE the given message from the broker, indicating that it has been processed by a worker.
*/
public void deleteRequest(AnalystClusterRequest clusterRequest) {
String url = BROKER_BASE_URL + String.format("/tasks/%s", clusterRequest.taskId);
HttpDelete httpDelete = new HttpDelete(url);
try {
HttpResponse response = httpClient.execute(httpDelete);
// Signal the http client library that we're done with this response object, allowing connection reuse.
EntityUtils.consumeQuietly(response.getEntity());
if (response.getStatusLine().getStatusCode() == 200) {
LOG.info("Successfully deleted task {}.", clusterRequest.taskId);
} else {
LOG.info("Failed to delete task {} ({}).", clusterRequest.taskId, response.getStatusLine());
}
} catch (Exception e) {
LOG.warn("Failed to delete task {}", clusterRequest.taskId, e);
}
}
/** Get the AWS instance type if applicable */
public String getInstanceType () {
try {
HttpGet get = new HttpGet();
// see http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
// This seems very much not EC2-like to hardwire an IP address for getting instance metadata,
// but that's how it's done.
get.setURI(new URI("http://169.254.169.254/latest/meta-data/instance-type"));
get.setConfig(RequestConfig.custom()
.setConnectTimeout(2000)
.setSocketTimeout(2000)
.build()
);
HttpResponse res = httpClient.execute(get);
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String type = reader.readLine().trim();
reader.close();
return type;
} catch (Exception e) {
LOG.info("could not retrieve EC2 instance type, you may be running outside of EC2.");
return null;
}
}
/** log queue status */
private void logQueueStatus() {
LOG.info("Wating tasks: high priority: {}, batch: {}", highPriorityExecutor.getQueue().size(), batchExecutor.getQueue().size());
}
/**
* Requires a worker configuration, which is a Java Properties file with the following
* attributes.
*
* broker-address address of the broker, without protocol or port
* broker port port broker is running on, default 80.
* graphs-bucket S3 bucket in which graphs are stored.
* pointsets-bucket S3 bucket in which pointsets are stored
* auto-shutdown Should this worker shut down its machine if it is idle (e.g. on throwaway cloud instances)
* statistics-queue SQS queue to which to send statistics (optional)
* initial-graph-id The graph ID for this worker to start on
*/
public static void main(String[] args) {
LOG.info("Starting analyst worker");
LOG.info("OTP commit is {}", MavenVersion.VERSION.commit);
Properties config = new Properties();
try {
File cfg;
if (args.length > 0)
cfg = new File(args[0]);
else
cfg = new File("worker.conf");
InputStream cfgis = new FileInputStream(cfg);
config.load(cfgis);
cfgis.close();
} catch (Exception e) {
LOG.info("Error loading worker configuration", e);
return;
}
new AnalystWorker(config).run();
}
public static enum WorkType {
HIGH_PRIORITY, BATCH;
}
} | src/main/java/org/opentripplanner/analyst/cluster/AnalystWorker.java | package org.opentripplanner.analyst.cluster;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.conveyal.geojson.GeoJsonModule;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.opentripplanner.analyst.PointSet;
import org.opentripplanner.analyst.ResultSet;
import org.opentripplanner.analyst.SampleSet;
import org.opentripplanner.api.model.AgencyAndIdSerializer;
import org.opentripplanner.api.model.JodaLocalDateSerializer;
import org.opentripplanner.api.model.QualifiedModeSetSerializer;
import org.opentripplanner.api.model.TraverseModeSetSerializer;
import org.opentripplanner.common.MavenVersion;
import org.opentripplanner.profile.RaptorWorkerData;
import org.opentripplanner.profile.RepeatedRaptorProfileRouter;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.graph.Graph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream;
/**
*
*/
public class AnalystWorker implements Runnable {
/**
* worker ID - just a random ID so we can differentiate machines used for computation.
* Useful to isolate the logs from a particular machine, as well as to evaluate any
* variation in performance coming from variation in the performance of the underlying
* VMs.
*
* This needs to be static so the logger can access it; see the static member class
* WorkerIdDefiner. A side effect is that only one worker can run in a given JVM. It also
* needs to be defined before the logger is defined, so that it is initialized before the
* logger is.
*/
public static final String machineId = UUID.randomUUID().toString().replaceAll("-", "");
private static final Logger LOG = LoggerFactory.getLogger(AnalystWorker.class);
public static final String WORKER_ID_HEADER = "X-Worker-Id";
public static final int POLL_TIMEOUT = 10 * 1000;
/**
* If this value is non-negative, the worker will not actually do any work. It will just report all tasks
* as completed immediately, but will fail to do so on the given percentage of tasks. This is used in testing task
* re-delivery and overall broker sanity.
*/
public int dryRunFailureRate = -1;
/** How long (minimum, in milliseconds) should this worker stay alive after receiving a single point request? */
public static final int SINGLE_POINT_KEEPALIVE = 15 * 60 * 1000;
/** should this worker shut down automatically */
public final boolean autoShutdown;
public static final Random random = new Random();
private TaskStatisticsStore statsStore;
/** is there currently a channel open to the broker to receive single point jobs? */
private volatile boolean sideChannelOpen = false;
ObjectMapper objectMapper;
String BROKER_BASE_URL = "http://localhost:9001";
static final HttpClient httpClient;
/** Cache RAPTOR data by Job ID */
private Cache<String, RaptorWorkerData> workerDataCache = CacheBuilder.newBuilder()
.maximumSize(200)
.build();
static {
PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager();
mgr.setDefaultMaxPerRoute(20);
int timeout = 10 * 1000;
SocketConfig cfg = SocketConfig.custom()
.setSoTimeout(timeout)
.build();
mgr.setDefaultSocketConfig(cfg);
httpClient = HttpClients.custom()
.setConnectionManager(mgr)
.build();
}
// Of course this will eventually need to be shared between multiple AnalystWorker threads.
ClusterGraphBuilder clusterGraphBuilder;
// Of course this will eventually need to be shared between multiple AnalystWorker threads.
PointSetDatastore pointSetDatastore;
// Clients for communicating with Amazon web services
AmazonS3 s3;
String graphId = null;
long startupTime, nextShutdownCheckTime;
// Region awsRegion = Region.getRegion(Regions.EU_CENTRAL_1);
Region awsRegion = Region.getRegion(Regions.US_EAST_1);
/** aws instance type, or null if not running on AWS */
private String instanceType;
long lastHighPriorityRequestProcessed = 0;
/**
* Queue for high-priority tasks. Should be plenty long enough to hold all that have come in -
* we don't need to block on polling the manager.
*/
private ThreadPoolExecutor highPriorityExecutor, batchExecutor;
public AnalystWorker(Properties config) {
// parse the configuration
// set up the stats store
String statsQueue = config.getProperty("statistics-queue");
if (statsQueue != null)
this.statsStore = new SQSTaskStatisticsStore(statsQueue);
else
// a stats store that does nothing.
this.statsStore = s -> {};
String addr = config.getProperty("broker-address");
String port = config.getProperty("broker-port");
if (addr != null) {
if (port != null)
this.BROKER_BASE_URL = String.format("http://%s:%s", addr, port);
else
this.BROKER_BASE_URL = String.format("http://%s", addr);
}
// set the initial graph affinity of this worker (if it is not in the config file it will be
// set to null, i.e. no graph affinity)
// we don't actually build the graph now; this is just a hint to the broker as to what
// graph this machine was intended to analyze.
this.graphId = config.getProperty("initial-graph-id");
this.pointSetDatastore = new PointSetDatastore(10, null, false, config.getProperty("pointsets-bucket"));
this.clusterGraphBuilder = new ClusterGraphBuilder(config.getProperty("graphs-bucket"));
Boolean autoShutdown = Boolean.parseBoolean(config.getProperty("auto-shutdown"));
this.autoShutdown = autoShutdown == null ? false : autoShutdown;
// Consider shutting this worker down once per hour, starting 55 minutes after it started up.
startupTime = System.currentTimeMillis();
nextShutdownCheckTime = startupTime + 55 * 60 * 1000;
// When creating the S3 and SQS clients use the default credentials chain.
// This will check environment variables and ~/.aws/credentials first, then fall back on
// the auto-assigned IAM role if this code is running on an EC2 instance.
// http://docs.aws.amazon.com/AWSSdkDocsJava/latest/DeveloperGuide/java-dg-roles.html
s3 = new AmazonS3Client();
s3.setRegion(awsRegion);
/* The ObjectMapper (de)serializes JSON. */
objectMapper = new ObjectMapper();
objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // ignore JSON fields that don't match target type
/* Tell Jackson how to (de)serialize AgencyAndIds, which appear as map keys in routing requests. */
objectMapper.registerModule(AgencyAndIdSerializer.makeModule());
/* serialize/deserialize qualified mode sets */
objectMapper.registerModule(QualifiedModeSetSerializer.makeModule());
/* serialize/deserialize Joda dates */
objectMapper.registerModule(JodaLocalDateSerializer.makeModule());
/* serialize/deserialize traversemodesets */
objectMapper.registerModule(TraverseModeSetSerializer.makeModule());
objectMapper.registerModule(new GeoJsonModule());
instanceType = getInstanceType();
}
@Override
public void run() {
// create executors with up to one thread per processor
int nP = Runtime.getRuntime().availableProcessors();
highPriorityExecutor = new ThreadPoolExecutor(1, nP, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(255));
highPriorityExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
batchExecutor = new ThreadPoolExecutor(1, nP, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(nP * 2));
batchExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
// build the graph, iff we know what graph to build
if (graphId != null) {
LOG.info("Prebuilding graph {}", graphId);
clusterGraphBuilder.getGraph(graphId);
}
// Start filling the work queues.
boolean idle = false;
while (true) {
long now = System.currentTimeMillis();
// Consider shutting down if enough time has passed
if (now > nextShutdownCheckTime && autoShutdown) {
if (idle && now > lastHighPriorityRequestProcessed + SINGLE_POINT_KEEPALIVE) {
LOG.warn("Machine is idle, shutting down.");
try {
Process process = new ProcessBuilder("sudo", "/sbin/shutdown", "-h", "now")
.start();
process.waitFor();
} catch (Exception ex) {
LOG.error("Unable to terminate worker", ex);
} finally {
System.exit(0);
}
}
nextShutdownCheckTime += 60 * 60 * 1000;
}
LOG.info("Long-polling for work ({} second timeout).", POLL_TIMEOUT / 1000.0);
// Long-poll (wait a few seconds for messages to become available)
List<AnalystClusterRequest> tasks = getSomeWork(WorkType.BATCH);
if (tasks == null) {
LOG.info("Didn't get any work. Retrying.");
idle = true;
continue;
}
// run through high-priority tasks first to ensure they are enqueued even if the batch
// queue blocks.
tasks.stream().filter(t -> t.outputLocation == null)
.forEach(t -> highPriorityExecutor.execute(() -> {
LOG.warn(
"Handling single point request via normal channel, side channel should open shortly.");
this.handleOneRequest(t);
}));
logQueueStatus();
// enqueue low-priority tasks; note that this may block anywhere in the process
tasks.stream().filter(t -> t.outputLocation != null)
.forEach(t -> {
// attempt to enqueue, waiting if the queue is full
while (true) {
try {
batchExecutor.execute(() -> this.handleOneRequest(t));
break;
} catch (RejectedExecutionException e) {
// queue is full, wait 200ms and try again
try {
Thread.sleep(200);
} catch (InterruptedException e1) { /* nothing */}
}
}
});
logQueueStatus();
idle = false;
}
}
private void handleOneRequest(AnalystClusterRequest clusterRequest) {
if (dryRunFailureRate >= 0) {
// This worker is running in test mode.
// It should report all work as completed without actually doing anything,
// but will fail a certain percentage of the time.
if (random.nextInt(100) >= dryRunFailureRate) {
// Pretend to succeed.
deleteRequest(clusterRequest);
} else {
LOG.info("Intentionally failing on task {}", clusterRequest.taskId);
}
return;
}
try {
long startTime = System.currentTimeMillis();
LOG.info("Handling message {}", clusterRequest.toString());
if (clusterRequest.outputLocation == null) {
// high priority
lastHighPriorityRequestProcessed = startTime;
if (!sideChannelOpen)
openSideChannel();
}
TaskStatistics ts = new TaskStatistics();
ts.pointsetId = clusterRequest.destinationPointsetId;
ts.graphId = clusterRequest.graphId;
ts.awsInstanceType = instanceType;
ts.jobId = clusterRequest.jobId;
ts.workerId = machineId;
ts.single = clusterRequest.outputLocation == null;
long graphStartTime = System.currentTimeMillis();
// Get the graph object for the ID given in the request, fetching inputs and building as needed.
// All requests handled together are for the same graph, and this call is synchronized so the graph will
// only be built once.
Graph graph = clusterGraphBuilder.getGraph(clusterRequest.graphId);
graphId = clusterRequest.graphId; // Record graphId so we "stick" to this same graph on subsequent polls
ts.graphBuild = (int) (System.currentTimeMillis() - graphStartTime);
ts.graphTripCount = graph.index.patternForTrip.size();
ts.graphStopCount = graph.index.stopForId.size();
// This result envelope will hold the result of the profile or single-time one-to-many search.
ResultEnvelope envelope = new ResultEnvelope();
if (clusterRequest.profileRequest != null) {
ts.lon = clusterRequest.profileRequest.fromLon;
ts.lat = clusterRequest.profileRequest.fromLat;
RepeatedRaptorProfileRouter router;
boolean isochrone = clusterRequest.destinationPointsetId == null;
ts.isochrone = isochrone;
if (!isochrone) {
// A pointset was specified, calculate travel times to the points in the pointset.
// Fetch the set of points we will use as destinations for this one-to-many search
PointSet pointSet = pointSetDatastore.get(clusterRequest.destinationPointsetId);
// TODO this breaks if graph has been rebuilt
SampleSet sampleSet = pointSet.getOrCreateSampleSet(graph);
router =
new RepeatedRaptorProfileRouter(graph, clusterRequest.profileRequest, sampleSet);
// no reason to cache single-point RaptorWorkerData
if (clusterRequest.outputLocation != null) {
router.raptorWorkerData = workerDataCache.get(clusterRequest.jobId, () -> {
return RepeatedRaptorProfileRouter
.getRaptorWorkerData(clusterRequest.profileRequest, graph,
sampleSet, ts);
});
}
} else {
router = new RepeatedRaptorProfileRouter(graph, clusterRequest.profileRequest);
if (clusterRequest.outputLocation == null) {
router.raptorWorkerData = workerDataCache.get(clusterRequest.jobId,
() -> RepeatedRaptorProfileRouter
.getRaptorWorkerData(clusterRequest.profileRequest, graph, null,
ts));
}
}
try {
router.route(ts);
long resultSetStart = System.currentTimeMillis();
if (isochrone) {
envelope.worstCase = new ResultSet(router.timeSurfaceRangeSet.max);
envelope.bestCase = new ResultSet(router.timeSurfaceRangeSet.min);
envelope.avgCase = new ResultSet(router.timeSurfaceRangeSet.avg);
} else {
ResultSet.RangeSet results = router
.makeResults(clusterRequest.includeTimes, !isochrone, isochrone);
// put in constructor?
envelope.bestCase = results.min;
envelope.avgCase = results.avg;
envelope.worstCase = results.max;
}
envelope.id = clusterRequest.id;
envelope.destinationPointsetId = clusterRequest.destinationPointsetId;
ts.resultSets = (int) (System.currentTimeMillis() - resultSetStart);
ts.success = true;
} catch (Exception ex) {
// Leave the envelope empty TODO include error information
ts.success = false;
}
} else {
// No profile request, this must be a plain one to many routing request.
RoutingRequest routingRequest = clusterRequest.routingRequest;
// TODO finish the non-profile case
}
if (clusterRequest.outputLocation != null) {
// Convert the result envelope and its contents to JSON and gzip it in this thread.
// Transfer the results to Amazon S3 in another thread, piping between the two.
String s3key = String.join("/", clusterRequest.jobId, clusterRequest.id + ".json.gz");
PipedInputStream inPipe = new PipedInputStream();
PipedOutputStream outPipe = new PipedOutputStream(inPipe);
new Thread(() -> {
s3.putObject(clusterRequest.outputLocation, s3key, inPipe, null);
}).start();
OutputStream gzipOutputStream = new GZIPOutputStream(outPipe);
// We could do the writeValue() in a thread instead, in which case both the DELETE and S3 options
// could consume it in the same way.
objectMapper.writeValue(gzipOutputStream, envelope);
gzipOutputStream.close();
// DELETE the task from the broker, confirming it has been handled and should not be re-delivered.
deleteRequest(clusterRequest);
} else {
// No output location on S3 specified, return the result via the broker and mark the task completed.
finishPriorityTask(clusterRequest, envelope);
}
ts.total = (int) (System.currentTimeMillis() - startTime);
statsStore.store(ts);
} catch (Exception ex) {
LOG.error("An error occurred while routing", ex);
}
}
/** Open a single point channel to the broker to receive high-priority requests immediately */
private synchronized void openSideChannel () {
if (sideChannelOpen)
return;
LOG.info("Opening side channel for single point requests.");
new Thread(() -> {
sideChannelOpen = true;
// don't keep single point connections alive forever
while (System.currentTimeMillis() < lastHighPriorityRequestProcessed + SINGLE_POINT_KEEPALIVE) {
LOG.info("Awaiting high-priority work");
try {
List<AnalystClusterRequest> tasks = getSomeWork(WorkType.HIGH_PRIORITY);
if (tasks != null)
tasks.stream().forEach(t -> highPriorityExecutor.execute(
() -> this.handleOneRequest(t)));
logQueueStatus();
} catch (Exception e) {
LOG.error("Unexpected exception getting single point work", e);
}
}
sideChannelOpen = false;
}).start();
}
public List<AnalystClusterRequest> getSomeWork(WorkType type) {
// Run a POST request (long-polling for work) indicating which graph this worker prefers to work on
String url;
if (type == WorkType.HIGH_PRIORITY)
// this is a side-channel request for single point work
url = BROKER_BASE_URL + "/single/" + graphId;
else
url = BROKER_BASE_URL + "/dequeue/" + graphId;
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(new BasicHeader(WORKER_ID_HEADER, machineId));
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
if (response.getStatusLine().getStatusCode() != 200) {
EntityUtils.consumeQuietly(entity);
return null;
}
return objectMapper.readValue(entity.getContent(), new TypeReference<List<AnalystClusterRequest>>() {
});
} catch (JsonProcessingException e) {
LOG.error("JSON processing exception while getting work", e);
} catch (SocketTimeoutException stex) {
LOG.error("Socket timeout while waiting to receive work.");
} catch (HttpHostConnectException ce) {
LOG.error("Broker refused connection. Sleeping before retry.");
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
}
} catch (IOException e) {
LOG.error("IO exception while getting work", e);
}
return null;
}
/**
* Signal the broker that the given high-priority task is completed, providing a result.
*/
public void finishPriorityTask(AnalystClusterRequest clusterRequest, Object result) {
String url = BROKER_BASE_URL + String.format("/complete/priority/%s", clusterRequest.taskId);
HttpPost httpPost = new HttpPost(url);
try {
// TODO reveal any errors etc. that occurred on the worker.
// Really this should probably be done with an InputStreamEntity and a JSON writer thread.
byte[] serializedResult = objectMapper.writeValueAsBytes(result);
httpPost.setEntity(new ByteArrayEntity(serializedResult));
HttpResponse response = httpClient.execute(httpPost);
// Signal the http client library that we're done with this response object, allowing connection reuse.
EntityUtils.consumeQuietly(response.getEntity());
if (response.getStatusLine().getStatusCode() == 200) {
LOG.info("Successfully marked task {} as completed.", clusterRequest.taskId);
} else if (response.getStatusLine().getStatusCode() == 404) {
LOG.info("Task {} was not marked as completed because it doesn't exist.", clusterRequest.taskId);
} else {
LOG.info("Failed to mark task {} as completed, ({}).", clusterRequest.taskId,
response.getStatusLine());
}
} catch (Exception e) {
LOG.warn("Failed to mark task {} as completed.", clusterRequest.taskId, e);
}
}
/**
* DELETE the given message from the broker, indicating that it has been processed by a worker.
*/
public void deleteRequest(AnalystClusterRequest clusterRequest) {
String url = BROKER_BASE_URL + String.format("/tasks/%s", clusterRequest.taskId);
HttpDelete httpDelete = new HttpDelete(url);
try {
HttpResponse response = httpClient.execute(httpDelete);
// Signal the http client library that we're done with this response object, allowing connection reuse.
EntityUtils.consumeQuietly(response.getEntity());
if (response.getStatusLine().getStatusCode() == 200) {
LOG.info("Successfully deleted task {}.", clusterRequest.taskId);
} else {
LOG.info("Failed to delete task {} ({}).", clusterRequest.taskId, response.getStatusLine());
}
} catch (Exception e) {
LOG.warn("Failed to delete task {}", clusterRequest.taskId, e);
}
}
/** Get the AWS instance type if applicable */
public String getInstanceType () {
try {
HttpGet get = new HttpGet();
// see http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
// This seems very much not EC2-like to hardwire an IP address for getting instance metadata,
// but that's how it's done.
get.setURI(new URI("http://169.254.169.254/latest/meta-data/instance-type"));
get.setConfig(RequestConfig.custom()
.setConnectTimeout(2000)
.setSocketTimeout(2000)
.build()
);
HttpResponse res = httpClient.execute(get);
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String type = reader.readLine().trim();
reader.close();
return type;
} catch (Exception e) {
LOG.info("could not retrieve EC2 instance type, you may be running outside of EC2.");
return null;
}
}
/** log queue status */
private void logQueueStatus() {
LOG.info("Wating tasks: high priority: {}, batch: {}", highPriorityExecutor.getQueue().size(), batchExecutor.getQueue().size());
}
/**
* Requires a worker configuration, which is a Java Properties file with the following
* attributes.
*
* broker-address address of the broker, without protocol or port
* broker port port broker is running on, default 80.
* graphs-bucket S3 bucket in which graphs are stored.
* pointsets-bucket S3 bucket in which pointsets are stored
* auto-shutdown Should this worker shut down its machine if it is idle (e.g. on throwaway cloud instances)
* statistics-queue SQS queue to which to send statistics (optional)
* initial-graph-id The graph ID for this worker to start on
*/
public static void main(String[] args) {
LOG.info("Starting analyst worker");
LOG.info("OTP commit is {}", MavenVersion.VERSION.commit);
Properties config = new Properties();
try {
File cfg;
if (args.length > 0)
cfg = new File(args[0]);
else
cfg = new File("worker.conf");
InputStream cfgis = new FileInputStream(cfg);
config.load(cfgis);
cfgis.close();
} catch (Exception e) {
LOG.info("Error loading worker configuration", e);
return;
}
new AnalystWorker(config).run();
}
public static enum WorkType {
HIGH_PRIORITY, BATCH;
}
} | prebuild stop tree cache as well as graph, fixes #2051.
Former-commit-id: e839021758dec795d132eaf2ec6a823fb4ea82f0
| src/main/java/org/opentripplanner/analyst/cluster/AnalystWorker.java | prebuild stop tree cache as well as graph, fixes #2051. | <ide><path>rc/main/java/org/opentripplanner/analyst/cluster/AnalystWorker.java
<ide> // build the graph, iff we know what graph to build
<ide> if (graphId != null) {
<ide> LOG.info("Prebuilding graph {}", graphId);
<del> clusterGraphBuilder.getGraph(graphId);
<add> Graph graph = clusterGraphBuilder.getGraph(graphId);
<add> // also prebuild the stop tree cache
<add> graph.index.getStopTreeCache();
<add> LOG.info("Done prebuilding graph {}", graphId);
<ide> }
<ide>
<ide> // Start filling the work queues. |
|
JavaScript | apache-2.0 | f3315fe5e4183a9db3edffe309113238effe5949 | 0 | mongoh/tuid | /* Copyright 2014 Rishi Sharma
*
* 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.
*/
// Counter to simulate a "new" request
var counter = 0;
if (!window['getXMLHttpRequest']) {
// Copied from MochiKit/Async.js
function getXMLHttpRequest() {
var self = arguments.callee;
if (!self.XMLHttpRequest) {
var tryThese = [
function () { return new XMLHttpRequest(); },
function () { return new ActiveXObject('Msxml2.XMLHTTP'); },
function () { return new ActiveXObject('Microsoft.XMLHTTP'); },
function () { return new ActiveXObject('Msxml2.XMLHTTP.4.0'); },
function () { return null; }
];
for (var i = 0; i < tryThese.length; i++) {
var func = tryThese[i];
try {
self.XMLHttpRequest = func;
return func();
} catch (e) {
// pass
}
}
}
return self.XMLHttpRequest();
}
}
function tuid(cb){
var tuid;
var client = getXMLHttpRequest();
counter >= 1000 ? counter = 0 : counter++;
client.open("PUT", "https://tuid.s3.amazonaws.com/lock/file");
client.setRequestHeader("x-amz-storage-class", "REDUCED_REDUNDANCY");
client.setRequestHeader("x-amz-counter", counter.toString())
client.onreadystatechange = function(){
if ( client.readyState === 4 && client.status === 200 ) {
var versionId = client.getResponseHeader("x-amz-version-id");
if ( versionId ) {
tuid = versionId + new Date().getTime();
}
cb(tuid);
}
};
client.send(null);
return client;
}; | tuid.js | /* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Counter to simulate a "new" request
var counter = 0;
if (!window['getXMLHttpRequest']) {
// Copied from MochiKit/Async.js
function getXMLHttpRequest() {
var self = arguments.callee;
if (!self.XMLHttpRequest) {
var tryThese = [
function () { return new XMLHttpRequest(); },
function () { return new ActiveXObject('Msxml2.XMLHTTP'); },
function () { return new ActiveXObject('Microsoft.XMLHTTP'); },
function () { return new ActiveXObject('Msxml2.XMLHTTP.4.0'); },
function () { return null; }
];
for (var i = 0; i < tryThese.length; i++) {
var func = tryThese[i];
try {
self.XMLHttpRequest = func;
return func();
} catch (e) {
// pass
}
}
}
return self.XMLHttpRequest();
}
}
function tuid(cb){
var tuid;
var client = getXMLHttpRequest();
counter >= 1000 ? counter = 0 : counter++;
client.open("PUT", "https://tuid.s3.amazonaws.com/lock/file");
client.setRequestHeader("x-amz-storage-class", "REDUCED_REDUNDANCY");
client.setRequestHeader("x-amz-counter", counter.toString())
client.onreadystatechange = function(){
if ( client.readyState === 4 && client.status === 200 ) {
var versionId = client.getResponseHeader("x-amz-version-id");
if ( versionId ) {
tuid = versionId + new Date().getTime();
}
cb(tuid);
}
};
client.send(null);
return client;
}; | Updated copyright.
| tuid.js | Updated copyright. | <ide><path>uid.js
<del>/* Copyright 2012 Mozilla Foundation
<add>/* Copyright 2014 Rishi Sharma
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License. |
|
Java | apache-2.0 | f658fb0a6aececaab949eea9410faadd91d606e2 | 0 | TheAks999/libgdx,davebaol/libgdx,Deftwun/libgdx,ztv/libgdx,ryoenji/libgdx,katiepino/libgdx,jasonwee/libgdx,sarkanyi/libgdx,zhimaijoy/libgdx,bsmr-java/libgdx,czyzby/libgdx,alireza-hosseini/libgdx,antag99/libgdx,tommycli/libgdx,BlueRiverInteractive/libgdx,kotcrab/libgdx,josephknight/libgdx,fwolff/libgdx,Xhanim/libgdx,firefly2442/libgdx,Gliby/libgdx,djom20/libgdx,saqsun/libgdx,SidneyXu/libgdx,kzganesan/libgdx,basherone/libgdxcn,JDReutt/libgdx,junkdog/libgdx,yangweigbh/libgdx,MikkelTAndersen/libgdx,sinistersnare/libgdx,stickyd/libgdx,kagehak/libgdx,jsjolund/libgdx,Zonglin-Li6565/libgdx,tommyettinger/libgdx,KrisLee/libgdx,alireza-hosseini/libgdx,tommyettinger/libgdx,curtiszimmerman/libgdx,snovak/libgdx,del-sol/libgdx,nooone/libgdx,hyvas/libgdx,ttencate/libgdx,ricardorigodon/libgdx,Zomby2D/libgdx,JFixby/libgdx,xranby/libgdx,noelsison2/libgdx,sarkanyi/libgdx,MathieuDuponchelle/gdx,xpenatan/libgdx-LWJGL3,BlueRiverInteractive/libgdx,ya7lelkom/libgdx,Thotep/libgdx,thepullman/libgdx,alireza-hosseini/libgdx,309746069/libgdx,SidneyXu/libgdx,nave966/libgdx,MovingBlocks/libgdx,haedri/libgdx-1,czyzby/libgdx,gdos/libgdx,shiweihappy/libgdx,kagehak/libgdx,Thotep/libgdx,del-sol/libgdx,Gliby/libgdx,ryoenji/libgdx,1yvT0s/libgdx,gouessej/libgdx,revo09/libgdx,basherone/libgdxcn,antag99/libgdx,srwonka/libGdx,SidneyXu/libgdx,antag99/libgdx,designcrumble/libgdx,fwolff/libgdx,NathanSweet/libgdx,ya7lelkom/libgdx,1yvT0s/libgdx,shiweihappy/libgdx,JFixby/libgdx,realitix/libgdx,junkdog/libgdx,collinsmith/libgdx,toa5/libgdx,TheAks999/libgdx,NathanSweet/libgdx,stickyd/libgdx,jberberick/libgdx,Xhanim/libgdx,GreenLightning/libgdx,alireza-hosseini/libgdx,collinsmith/libgdx,Thotep/libgdx,stickyd/libgdx,Heart2009/libgdx,jsjolund/libgdx,titovmaxim/libgdx,bladecoder/libgdx,alex-dorokhov/libgdx,del-sol/libgdx,xpenatan/libgdx-LWJGL3,czyzby/libgdx,saltares/libgdx,Deftwun/libgdx,collinsmith/libgdx,ThiagoGarciaAlves/libgdx,FyiurAmron/libgdx,fiesensee/libgdx,junkdog/libgdx,djom20/libgdx,tommycli/libgdx,MadcowD/libgdx,ninoalma/libgdx,flaiker/libgdx,shiweihappy/libgdx,thepullman/libgdx,gf11speed/libgdx,SidneyXu/libgdx,fwolff/libgdx,yangweigbh/libgdx,zhimaijoy/libgdx,BlueRiverInteractive/libgdx,BlueRiverInteractive/libgdx,309746069/libgdx,EsikAntony/libgdx,saltares/libgdx,tommyettinger/libgdx,toa5/libgdx,copystudy/libgdx,FredGithub/libgdx,MetSystem/libgdx,Xhanim/libgdx,tell10glu/libgdx,PedroRomanoBarbosa/libgdx,bgroenks96/libgdx,codepoke/libgdx,titovmaxim/libgdx,xpenatan/libgdx-LWJGL3,PedroRomanoBarbosa/libgdx,bladecoder/libgdx,bladecoder/libgdx,nooone/libgdx,MathieuDuponchelle/gdx,zommuter/libgdx,collinsmith/libgdx,Badazdz/libgdx,309746069/libgdx,TheAks999/libgdx,mumer92/libgdx,lordjone/libgdx,jsjolund/libgdx,alex-dorokhov/libgdx,ztv/libgdx,FyiurAmron/libgdx,toloudis/libgdx,Gliby/libgdx,kagehak/libgdx,ryoenji/libgdx,NathanSweet/libgdx,billgame/libgdx,gf11speed/libgdx,davebaol/libgdx,bsmr-java/libgdx,curtiszimmerman/libgdx,copystudy/libgdx,firefly2442/libgdx,Gliby/libgdx,sarkanyi/libgdx,BlueRiverInteractive/libgdx,saqsun/libgdx,ttencate/libgdx,zommuter/libgdx,yangweigbh/libgdx,Zomby2D/libgdx,haedri/libgdx-1,nrallakis/libgdx,jberberick/libgdx,nave966/libgdx,nudelchef/libgdx,junkdog/libgdx,kotcrab/libgdx,xoppa/libgdx,anserran/libgdx,toa5/libgdx,del-sol/libgdx,Dzamir/libgdx,bsmr-java/libgdx,thepullman/libgdx,xpenatan/libgdx-LWJGL3,Arcnor/libgdx,lordjone/libgdx,kzganesan/libgdx,JDReutt/libgdx,zhimaijoy/libgdx,nooone/libgdx,tommycli/libgdx,snovak/libgdx,Thotep/libgdx,azakhary/libgdx,Dzamir/libgdx,TheAks999/libgdx,collinsmith/libgdx,Heart2009/libgdx,Dzamir/libgdx,gdos/libgdx,Wisienkas/libgdx,titovmaxim/libgdx,UnluckyNinja/libgdx,toloudis/libgdx,yangweigbh/libgdx,collinsmith/libgdx,Arcnor/libgdx,alex-dorokhov/libgdx,davebaol/libgdx,sinistersnare/libgdx,Zomby2D/libgdx,youprofit/libgdx,Wisienkas/libgdx,toa5/libgdx,curtiszimmerman/libgdx,zommuter/libgdx,tell10glu/libgdx,1yvT0s/libgdx,ttencate/libgdx,azakhary/libgdx,revo09/libgdx,jasonwee/libgdx,Thotep/libgdx,kagehak/libgdx,Arcnor/libgdx,FyiurAmron/libgdx,gf11speed/libgdx,mumer92/libgdx,katiepino/libgdx,Heart2009/libgdx,azakhary/libgdx,JFixby/libgdx,xranby/libgdx,zommuter/libgdx,ttencate/libgdx,ztv/libgdx,czyzby/libgdx,stickyd/libgdx,EsikAntony/libgdx,firefly2442/libgdx,zommuter/libgdx,Badazdz/libgdx,JFixby/libgdx,Xhanim/libgdx,sinistersnare/libgdx,jsjolund/libgdx,SidneyXu/libgdx,ryoenji/libgdx,gdos/libgdx,Senth/libgdx,BlueRiverInteractive/libgdx,youprofit/libgdx,MadcowD/libgdx,PedroRomanoBarbosa/libgdx,hyvas/libgdx,fiesensee/libgdx,UnluckyNinja/libgdx,anserran/libgdx,srwonka/libGdx,bgroenks96/libgdx,josephknight/libgdx,sjosegarcia/libgdx,js78/libgdx,Deftwun/libgdx,alireza-hosseini/libgdx,anserran/libgdx,Badazdz/libgdx,kagehak/libgdx,anserran/libgdx,ryoenji/libgdx,FredGithub/libgdx,Dzamir/libgdx,davebaol/libgdx,noelsison2/libgdx,jasonwee/libgdx,GreenLightning/libgdx,samskivert/libgdx,gf11speed/libgdx,ThiagoGarciaAlves/libgdx,flaiker/libgdx,Xhanim/libgdx,andyvand/libgdx,ricardorigodon/libgdx,gouessej/libgdx,MovingBlocks/libgdx,ThiagoGarciaAlves/libgdx,mumer92/libgdx,sarkanyi/libgdx,andyvand/libgdx,KrisLee/libgdx,tell10glu/libgdx,mumer92/libgdx,sinistersnare/libgdx,nooone/libgdx,gdos/libgdx,del-sol/libgdx,stickyd/libgdx,josephknight/libgdx,1yvT0s/libgdx,shiweihappy/libgdx,sjosegarcia/libgdx,xoppa/libgdx,stinsonga/libgdx,cypherdare/libgdx,junkdog/libgdx,hyvas/libgdx,haedri/libgdx-1,noelsison2/libgdx,Deftwun/libgdx,gdos/libgdx,ya7lelkom/libgdx,yangweigbh/libgdx,revo09/libgdx,Arcnor/libgdx,haedri/libgdx-1,nudelchef/libgdx,bgroenks96/libgdx,yangweigbh/libgdx,anserran/libgdx,Xhanim/libgdx,kotcrab/libgdx,nave966/libgdx,KrisLee/libgdx,tommycli/libgdx,samskivert/libgdx,ztv/libgdx,bladecoder/libgdx,srwonka/libGdx,FyiurAmron/libgdx,luischavez/libgdx,copystudy/libgdx,EsikAntony/libgdx,Wisienkas/libgdx,luischavez/libgdx,KrisLee/libgdx,jberberick/libgdx,snovak/libgdx,kzganesan/libgdx,TheAks999/libgdx,noelsison2/libgdx,ricardorigodon/libgdx,FredGithub/libgdx,czyzby/libgdx,gf11speed/libgdx,SidneyXu/libgdx,gouessej/libgdx,firefly2442/libgdx,ricardorigodon/libgdx,Deftwun/libgdx,saltares/libgdx,stickyd/libgdx,zommuter/libgdx,saqsun/libgdx,titovmaxim/libgdx,josephknight/libgdx,MetSystem/libgdx,nudelchef/libgdx,BlueRiverInteractive/libgdx,MetSystem/libgdx,samskivert/libgdx,MathieuDuponchelle/gdx,xoppa/libgdx,thepullman/libgdx,tell10glu/libgdx,ztv/libgdx,jasonwee/libgdx,jsjolund/libgdx,andyvand/libgdx,djom20/libgdx,bsmr-java/libgdx,noelsison2/libgdx,Senth/libgdx,xoppa/libgdx,del-sol/libgdx,309746069/libgdx,libgdx/libgdx,Wisienkas/libgdx,MikkelTAndersen/libgdx,firefly2442/libgdx,luischavez/libgdx,youprofit/libgdx,1yvT0s/libgdx,EsikAntony/libgdx,Deftwun/libgdx,hyvas/libgdx,djom20/libgdx,FyiurAmron/libgdx,zhimaijoy/libgdx,snovak/libgdx,andyvand/libgdx,youprofit/libgdx,ryoenji/libgdx,fiesensee/libgdx,gdos/libgdx,sinistersnare/libgdx,toloudis/libgdx,bgroenks96/libgdx,djom20/libgdx,flaiker/libgdx,BlueRiverInteractive/libgdx,JDReutt/libgdx,titovmaxim/libgdx,JDReutt/libgdx,azakhary/libgdx,sarkanyi/libgdx,JFixby/libgdx,nrallakis/libgdx,curtiszimmerman/libgdx,kotcrab/libgdx,stickyd/libgdx,junkdog/libgdx,kotcrab/libgdx,kzganesan/libgdx,xoppa/libgdx,EsikAntony/libgdx,josephknight/libgdx,UnluckyNinja/libgdx,MathieuDuponchelle/gdx,curtiszimmerman/libgdx,designcrumble/libgdx,Gliby/libgdx,MadcowD/libgdx,xranby/libgdx,basherone/libgdxcn,hyvas/libgdx,nudelchef/libgdx,billgame/libgdx,katiepino/libgdx,shiweihappy/libgdx,UnluckyNinja/libgdx,jsjolund/libgdx,andyvand/libgdx,srwonka/libGdx,tell10glu/libgdx,copystudy/libgdx,JDReutt/libgdx,libgdx/libgdx,srwonka/libGdx,andyvand/libgdx,Dzamir/libgdx,titovmaxim/libgdx,MovingBlocks/libgdx,JDReutt/libgdx,fiesensee/libgdx,titovmaxim/libgdx,zommuter/libgdx,hyvas/libgdx,gf11speed/libgdx,mumer92/libgdx,copystudy/libgdx,collinsmith/libgdx,alex-dorokhov/libgdx,noelsison2/libgdx,FyiurAmron/libgdx,Badazdz/libgdx,saltares/libgdx,mumer92/libgdx,KrisLee/libgdx,309746069/libgdx,saqsun/libgdx,davebaol/libgdx,MikkelTAndersen/libgdx,fwolff/libgdx,tommycli/libgdx,nave966/libgdx,MadcowD/libgdx,antag99/libgdx,jberberick/libgdx,srwonka/libGdx,Gliby/libgdx,alex-dorokhov/libgdx,luischavez/libgdx,Dzamir/libgdx,TheAks999/libgdx,saqsun/libgdx,haedri/libgdx-1,MovingBlocks/libgdx,designcrumble/libgdx,gouessej/libgdx,Badazdz/libgdx,Arcnor/libgdx,ya7lelkom/libgdx,realitix/libgdx,xoppa/libgdx,davebaol/libgdx,saltares/libgdx,ninoalma/libgdx,czyzby/libgdx,curtiszimmerman/libgdx,GreenLightning/libgdx,ztv/libgdx,toloudis/libgdx,MetSystem/libgdx,ya7lelkom/libgdx,sjosegarcia/libgdx,jasonwee/libgdx,saltares/libgdx,yangweigbh/libgdx,toa5/libgdx,curtiszimmerman/libgdx,jberberick/libgdx,cypherdare/libgdx,nave966/libgdx,bsmr-java/libgdx,Wisienkas/libgdx,jasonwee/libgdx,luischavez/libgdx,nrallakis/libgdx,nelsonsilva/libgdx,bsmr-java/libgdx,MikkelTAndersen/libgdx,js78/libgdx,kzganesan/libgdx,toloudis/libgdx,petugez/libgdx,snovak/libgdx,nrallakis/libgdx,gf11speed/libgdx,Senth/libgdx,ricardorigodon/libgdx,luischavez/libgdx,Wisienkas/libgdx,MathieuDuponchelle/gdx,stinsonga/libgdx,Arcnor/libgdx,andyvand/libgdx,stinsonga/libgdx,flaiker/libgdx,JDReutt/libgdx,MikkelTAndersen/libgdx,kotcrab/libgdx,js78/libgdx,haedri/libgdx-1,jberberick/libgdx,Zomby2D/libgdx,JFixby/libgdx,samskivert/libgdx,cypherdare/libgdx,Gliby/libgdx,sinistersnare/libgdx,Dzamir/libgdx,Xhanim/libgdx,FyiurAmron/libgdx,yangweigbh/libgdx,tell10glu/libgdx,xranby/libgdx,Senth/libgdx,lordjone/libgdx,czyzby/libgdx,basherone/libgdxcn,realitix/libgdx,TheAks999/libgdx,Badazdz/libgdx,haedri/libgdx-1,MovingBlocks/libgdx,sjosegarcia/libgdx,Deftwun/libgdx,junkdog/libgdx,nudelchef/libgdx,nrallakis/libgdx,josephknight/libgdx,xpenatan/libgdx-LWJGL3,sjosegarcia/libgdx,Heart2009/libgdx,UnluckyNinja/libgdx,sjosegarcia/libgdx,nudelchef/libgdx,codepoke/libgdx,Badazdz/libgdx,nudelchef/libgdx,KrisLee/libgdx,Heart2009/libgdx,samskivert/libgdx,PedroRomanoBarbosa/libgdx,billgame/libgdx,ryoenji/libgdx,MadcowD/libgdx,Zomby2D/libgdx,1yvT0s/libgdx,kzganesan/libgdx,MikkelTAndersen/libgdx,andyvand/libgdx,josephknight/libgdx,nave966/libgdx,kotcrab/libgdx,FredGithub/libgdx,PedroRomanoBarbosa/libgdx,Zonglin-Li6565/libgdx,ninoalma/libgdx,katiepino/libgdx,anserran/libgdx,toa5/libgdx,hyvas/libgdx,djom20/libgdx,jsjolund/libgdx,ya7lelkom/libgdx,azakhary/libgdx,jasonwee/libgdx,JFixby/libgdx,nrallakis/libgdx,Senth/libgdx,anserran/libgdx,ttencate/libgdx,Dzamir/libgdx,ninoalma/libgdx,xranby/libgdx,gdos/libgdx,designcrumble/libgdx,designcrumble/libgdx,lordjone/libgdx,srwonka/libGdx,katiepino/libgdx,gdos/libgdx,cypherdare/libgdx,codepoke/libgdx,gouessej/libgdx,toa5/libgdx,fwolff/libgdx,realitix/libgdx,toa5/libgdx,designcrumble/libgdx,thepullman/libgdx,js78/libgdx,shiweihappy/libgdx,designcrumble/libgdx,GreenLightning/libgdx,libgdx/libgdx,realitix/libgdx,zhimaijoy/libgdx,ztv/libgdx,shiweihappy/libgdx,billgame/libgdx,noelsison2/libgdx,mumer92/libgdx,katiepino/libgdx,billgame/libgdx,kzganesan/libgdx,petugez/libgdx,tell10glu/libgdx,ricardorigodon/libgdx,saltares/libgdx,del-sol/libgdx,NathanSweet/libgdx,ThiagoGarciaAlves/libgdx,samskivert/libgdx,Thotep/libgdx,copystudy/libgdx,revo09/libgdx,309746069/libgdx,MovingBlocks/libgdx,nrallakis/libgdx,realitix/libgdx,antag99/libgdx,MetSystem/libgdx,stinsonga/libgdx,MikkelTAndersen/libgdx,petugez/libgdx,EsikAntony/libgdx,petugez/libgdx,codepoke/libgdx,gouessej/libgdx,Thotep/libgdx,petugez/libgdx,kagehak/libgdx,realitix/libgdx,saqsun/libgdx,flaiker/libgdx,UnluckyNinja/libgdx,libgdx/libgdx,realitix/libgdx,kagehak/libgdx,Zonglin-Li6565/libgdx,1yvT0s/libgdx,copystudy/libgdx,titovmaxim/libgdx,czyzby/libgdx,bsmr-java/libgdx,MetSystem/libgdx,js78/libgdx,snovak/libgdx,luischavez/libgdx,xranby/libgdx,sarkanyi/libgdx,gf11speed/libgdx,billgame/libgdx,firefly2442/libgdx,Thotep/libgdx,ttencate/libgdx,xpenatan/libgdx-LWJGL3,nrallakis/libgdx,saqsun/libgdx,basherone/libgdxcn,youprofit/libgdx,haedri/libgdx-1,nelsonsilva/libgdx,fiesensee/libgdx,xoppa/libgdx,xranby/libgdx,youprofit/libgdx,noelsison2/libgdx,nelsonsilva/libgdx,ThiagoGarciaAlves/libgdx,MetSystem/libgdx,bgroenks96/libgdx,tommyettinger/libgdx,bgroenks96/libgdx,flaiker/libgdx,lordjone/libgdx,nelsonsilva/libgdx,bladecoder/libgdx,xpenatan/libgdx-LWJGL3,PedroRomanoBarbosa/libgdx,djom20/libgdx,tommycli/libgdx,Zonglin-Li6565/libgdx,GreenLightning/libgdx,MetSystem/libgdx,fwolff/libgdx,gouessej/libgdx,zhimaijoy/libgdx,js78/libgdx,Senth/libgdx,Zonglin-Li6565/libgdx,alex-dorokhov/libgdx,fiesensee/libgdx,MadcowD/libgdx,gouessej/libgdx,flaiker/libgdx,libgdx/libgdx,MovingBlocks/libgdx,ThiagoGarciaAlves/libgdx,nelsonsilva/libgdx,js78/libgdx,toloudis/libgdx,FyiurAmron/libgdx,Zonglin-Li6565/libgdx,snovak/libgdx,sarkanyi/libgdx,kagehak/libgdx,fwolff/libgdx,MikkelTAndersen/libgdx,PedroRomanoBarbosa/libgdx,copystudy/libgdx,codepoke/libgdx,nooone/libgdx,designcrumble/libgdx,KrisLee/libgdx,toloudis/libgdx,jasonwee/libgdx,Deftwun/libgdx,bgroenks96/libgdx,MadcowD/libgdx,zommuter/libgdx,Xhanim/libgdx,alireza-hosseini/libgdx,thepullman/libgdx,GreenLightning/libgdx,Heart2009/libgdx,srwonka/libGdx,azakhary/libgdx,mumer92/libgdx,codepoke/libgdx,petugez/libgdx,FredGithub/libgdx,ThiagoGarciaAlves/libgdx,Wisienkas/libgdx,EsikAntony/libgdx,Zonglin-Li6565/libgdx,FredGithub/libgdx,MathieuDuponchelle/gdx,Wisienkas/libgdx,sjosegarcia/libgdx,katiepino/libgdx,samskivert/libgdx,xranby/libgdx,fwolff/libgdx,jberberick/libgdx,luischavez/libgdx,ninoalma/libgdx,youprofit/libgdx,NathanSweet/libgdx,antag99/libgdx,billgame/libgdx,josephknight/libgdx,jberberick/libgdx,Senth/libgdx,Heart2009/libgdx,TheAks999/libgdx,Senth/libgdx,ninoalma/libgdx,firefly2442/libgdx,nave966/libgdx,FredGithub/libgdx,revo09/libgdx,EsikAntony/libgdx,jsjolund/libgdx,bsmr-java/libgdx,tommycli/libgdx,ttencate/libgdx,ricardorigodon/libgdx,SidneyXu/libgdx,alex-dorokhov/libgdx,ninoalma/libgdx,toloudis/libgdx,Heart2009/libgdx,petugez/libgdx,alex-dorokhov/libgdx,PedroRomanoBarbosa/libgdx,saltares/libgdx,alireza-hosseini/libgdx,tommycli/libgdx,ninoalma/libgdx,tell10glu/libgdx,codepoke/libgdx,stinsonga/libgdx,1yvT0s/libgdx,kotcrab/libgdx,GreenLightning/libgdx,sarkanyi/libgdx,hyvas/libgdx,nelsonsilva/libgdx,xpenatan/libgdx-LWJGL3,anserran/libgdx,alireza-hosseini/libgdx,curtiszimmerman/libgdx,nave966/libgdx,flaiker/libgdx,lordjone/libgdx,tommyettinger/libgdx,youprofit/libgdx,zhimaijoy/libgdx,ricardorigodon/libgdx,lordjone/libgdx,stickyd/libgdx,sjosegarcia/libgdx,fiesensee/libgdx,cypherdare/libgdx,ThiagoGarciaAlves/libgdx,collinsmith/libgdx,MathieuDuponchelle/gdx,junkdog/libgdx,nooone/libgdx,djom20/libgdx,MovingBlocks/libgdx,JFixby/libgdx,ya7lelkom/libgdx,xoppa/libgdx,shiweihappy/libgdx,JDReutt/libgdx,fiesensee/libgdx,nudelchef/libgdx,zhimaijoy/libgdx,codepoke/libgdx,snovak/libgdx,UnluckyNinja/libgdx,MathieuDuponchelle/gdx,GreenLightning/libgdx,FredGithub/libgdx,antag99/libgdx,thepullman/libgdx,lordjone/libgdx,thepullman/libgdx,Zonglin-Li6565/libgdx,revo09/libgdx,UnluckyNinja/libgdx,samskivert/libgdx,basherone/libgdxcn,Badazdz/libgdx,MathieuDuponchelle/gdx,billgame/libgdx,petugez/libgdx,MadcowD/libgdx,SidneyXu/libgdx,KrisLee/libgdx,antag99/libgdx,ya7lelkom/libgdx,bgroenks96/libgdx,del-sol/libgdx,Gliby/libgdx,ttencate/libgdx,ztv/libgdx,309746069/libgdx,katiepino/libgdx,309746069/libgdx,firefly2442/libgdx,saqsun/libgdx,js78/libgdx,revo09/libgdx,revo09/libgdx | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.backends.android;
import java.lang.reflect.Method;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.backends.android.surfaceview.FillResolutionStrategy;
import com.badlogic.gdx.backends.android.surfaceview.GLSurfaceViewCupcake;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GL11;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Clipboard;
import com.badlogic.gdx.utils.GdxNativesLoader;
/** An implementation of the {@link Application} interface for Android. Create an {@link Activity} that derives from this class. In
* the {@link Activity#onCreate(Bundle)} method call the {@link #initialize(ApplicationListener, boolean)} method specifying the
* configuration for the GLSurfaceView.
*
* @author mzechner */
public class AndroidApplication extends Activity implements Application {
static {
GdxNativesLoader.load();
}
protected AndroidGraphics graphics;
protected AndroidInput input;
protected AndroidAudio audio;
protected AndroidFiles files;
protected AndroidNet net;
protected ApplicationListener listener;
protected Handler handler;
protected boolean firstResume = true;
protected final Array<Runnable> runnables = new Array<Runnable>();
protected final Array<Runnable> executedRunnables = new Array<Runnable>();
protected WakeLock wakeLock = null;
protected int logLevel = LOG_INFO;
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. If useGL20IfAvailable is set the AndroidApplication will try to create an OpenGL ES 2.0
* context which can then be used via {@link Graphics#getGL20()}. The {@link GL10} and {@link GL11} interfaces should not be
* used when OpenGL ES 2.0 is enabled. To query whether enabling OpenGL ES 2.0 was successful use the
* {@link Graphics#isGL20Available()} method. Uses a default {@link AndroidApplicationConfiguration}.
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @param useGL2IfAvailable whether to use OpenGL ES 2.0 if its available. */
public void initialize (ApplicationListener listener, boolean useGL2IfAvailable) {
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
config.useGL20 = useGL2IfAvailable;
initialize(listener, config);
}
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. If config.useGL20 is set the AndroidApplication will try to create an OpenGL ES 2.0
* context which can then be used via {@link Graphics#getGL20()}. The {@link GL10} and {@link GL11} interfaces should not be
* used when OpenGL ES 2.0 is enabled. To query whether enabling OpenGL ES 2.0 was successful use the
* {@link Graphics#isGL20Available()} method. You can configure other aspects of the application with the rest of the fields in
* the {@link AndroidApplicationConfiguration} instance.
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer,
* etc.). */
public void initialize (ApplicationListener listener, AndroidApplicationConfiguration config) {
graphics = new AndroidGraphics(this, config, config.resolutionStrategy == null ? new FillResolutionStrategy()
: config.resolutionStrategy);
input = new AndroidInput(this, graphics.view, config);
audio = new AndroidAudio(this, config);
files = new AndroidFiles(this.getAssets(), this.getFilesDir().getAbsolutePath());
net = new AndroidNet(this);
this.listener = listener;
this.handler = new Handler();
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
try {
requestWindowFeature(Window.FEATURE_NO_TITLE);
} catch (Exception ex) {
log("AndroidApplication", "Content already displayed, cannot request FEATURE_NO_TITLE", ex);
}
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
setContentView(graphics.getView(), createLayoutParams());
createWakeLock(config);
hideStatusBar(config);
}
protected FrameLayout.LayoutParams createLayoutParams () {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,
android.view.ViewGroup.LayoutParams.FILL_PARENT);
layoutParams.gravity = Gravity.CENTER;
return layoutParams;
}
protected void createWakeLock (AndroidApplicationConfiguration config) {
if (config.useWakelock) {
PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "libgdx wakelock");
}
}
protected void hideStatusBar (AndroidApplicationConfiguration config) {
if (!config.hideStatusBar || getVersion() < 11)
return;
View rootView = getWindow().getDecorView();
try {
Method m = View.class.getMethod("setSystemUiVisibility", int.class);
m.invoke(rootView, 0x0);
m.invoke(rootView, 0x1);
} catch (Exception e) {
log("AndroidApplication", "Can't hide status bar", e);
}
}
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. If useGL20IfAvailable is set the AndroidApplication will try to create an OpenGL ES 2.0
* context which can then be used via {@link Graphics#getGL20()}. The {@link GL10} and {@link GL11} interfaces should not be
* used when OpenGL ES 2.0 is enabled. To query whether enabling OpenGL ES 2.0 was successful use the
* {@link Graphics#isGL20Available()} method. Uses a default {@link AndroidApplicationConfiguration}.
* <p/>
* Note: you have to add the returned view to your layout!
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @param useGL2IfAvailable whether to use OpenGL ES 2.0 if its available.
* @return the GLSurfaceView of the application */
public View initializeForView (ApplicationListener listener, boolean useGL2IfAvailable) {
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
config.useGL20 = useGL2IfAvailable;
return initializeForView(listener, config);
}
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. If config.useGL20 is set the AndroidApplication will try to create an OpenGL ES 2.0
* context which can then be used via {@link Graphics#getGL20()}. The {@link GL10} and {@link GL11} interfaces should not be
* used when OpenGL ES 2.0 is enabled. To query whether enabling OpenGL ES 2.0 was successful use the
* {@link Graphics#isGL20Available()} method. You can configure other aspects of the application with the rest of the fields in
* the {@link AndroidApplicationConfiguration} instance.
* <p/>
* Note: you have to add the returned view to your layout!
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer,
* etc.).
* @return the GLSurfaceView of the application */
public View initializeForView (ApplicationListener listener, AndroidApplicationConfiguration config) {
graphics = new AndroidGraphics(this, config, config.resolutionStrategy == null ? new FillResolutionStrategy()
: config.resolutionStrategy);
input = new AndroidInput(this, graphics.view, config);
audio = new AndroidAudio(this, config);
files = new AndroidFiles(this.getAssets(), this.getFilesDir().getAbsolutePath());
net = new AndroidNet(this);
this.listener = listener;
this.handler = new Handler();
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
createWakeLock(config);
hideStatusBar(config);
return graphics.getView();
}
@Override
protected void onPause () {
if (wakeLock != null) wakeLock.release();
boolean isContinuous = graphics.isContinuousRendering();
graphics.setContinuousRendering(true);
graphics.pause();
input.unregisterSensorListeners();
// erase pointer ids. this sucks donkeyballs...
int[] realId = input.realId;
for (int i = 0; i < realId.length; i++)
realId[i] = -1;
if (isFinishing()) {
graphics.clearManagedCaches();
graphics.destroy();
}
graphics.setContinuousRendering(isContinuous);
if (graphics != null && graphics.view != null) {
if (graphics.view instanceof GLSurfaceViewCupcake) ((GLSurfaceViewCupcake)graphics.view).onPause();
if (graphics.view instanceof android.opengl.GLSurfaceView) ((android.opengl.GLSurfaceView)graphics.view).onPause();
}
super.onPause();
}
@Override
protected void onResume () {
if (wakeLock != null) wakeLock.acquire();
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
((AndroidInput)getInput()).registerSensorListeners();
if (graphics != null && graphics.view != null) {
if (graphics.view instanceof GLSurfaceViewCupcake) ((GLSurfaceViewCupcake)graphics.view).onResume();
if (graphics.view instanceof android.opengl.GLSurfaceView) ((android.opengl.GLSurfaceView)graphics.view).onResume();
}
if (!firstResume) {
graphics.resume();
} else
firstResume = false;
super.onResume();
}
@Override
protected void onDestroy () {
super.onDestroy();
}
/** {@inheritDoc} */
@Override
public Audio getAudio () {
return audio;
}
/** {@inheritDoc} */
@Override
public Files getFiles () {
return files;
}
/** {@inheritDoc} */
@Override
public Graphics getGraphics () {
return graphics;
}
/** {@inheritDoc} */
@Override
public Input getInput () {
return input;
}
@Override
public Net getNet () {
return net;
}
/** {@inheritDoc} */
@Override
public ApplicationType getType () {
return ApplicationType.Android;
}
/** {@inheritDoc} */
@Override
public int getVersion () {
return Integer.parseInt(android.os.Build.VERSION.SDK);
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return Debug.getNativeHeapAllocatedSize();
}
@Override
public Preferences getPreferences (String name) {
return new AndroidPreferences(getSharedPreferences(name, Context.MODE_PRIVATE));
}
AndroidClipboard clipboard;
@Override
public Clipboard getClipboard() {
if (clipboard == null) {
clipboard = new AndroidClipboard(this);
}
return clipboard;
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
Gdx.graphics.requestRendering();
}
}
@Override
public void onConfigurationChanged (Configuration config) {
super.onConfigurationChanged(config);
boolean keyboardAvailable = false;
if (config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) keyboardAvailable = true;
input.keyboardAvailable = keyboardAvailable;
}
@Override
public void exit () {
handler.post(new Runnable() {
@Override
public void run () {
AndroidApplication.this.finish();
}
});
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) {
Log.d(tag, message);
}
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) {
Log.d(tag, message, exception);
}
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) Log.i(tag, message);
}
@Override
public void log (String tag, String message, Exception exception) {
if (logLevel >= LOG_INFO) Log.i(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) Log.e(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) Log.e(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
}
| backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidApplication.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.backends.android;
import java.lang.reflect.Method;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.backends.android.surfaceview.FillResolutionStrategy;
import com.badlogic.gdx.backends.android.surfaceview.GLSurfaceViewCupcake;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GL11;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Clipboard;
import com.badlogic.gdx.utils.GdxNativesLoader;
/** An implementation of the {@link Application} interface for Android. Create an {@link Activity} that derives from this class. In
* the {@link Activity#onCreate(Bundle)} method call the {@link #initialize(ApplicationListener, boolean)} method specifying the
* configuration for the GLSurfaceView.
*
* @author mzechner */
public class AndroidApplication extends Activity implements Application {
static {
GdxNativesLoader.load();
}
protected AndroidGraphics graphics;
protected AndroidInput input;
protected AndroidAudio audio;
protected AndroidFiles files;
protected AndroidNet net;
protected ApplicationListener listener;
protected Handler handler;
protected boolean firstResume = true;
protected final Array<Runnable> runnables = new Array<Runnable>();
protected final Array<Runnable> executedRunnables = new Array<Runnable>();
protected WakeLock wakeLock = null;
protected int logLevel = LOG_INFO;
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. If useGL20IfAvailable is set the AndroidApplication will try to create an OpenGL ES 2.0
* context which can then be used via {@link Graphics#getGL20()}. The {@link GL10} and {@link GL11} interfaces should not be
* used when OpenGL ES 2.0 is enabled. To query whether enabling OpenGL ES 2.0 was successful use the
* {@link Graphics#isGL20Available()} method. Uses a default {@link AndroidApplicationConfiguration}.
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @param useGL2IfAvailable whether to use OpenGL ES 2.0 if its available. */
public void initialize (ApplicationListener listener, boolean useGL2IfAvailable) {
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
config.useGL20 = useGL2IfAvailable;
initialize(listener, config);
}
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. If config.useGL20 is set the AndroidApplication will try to create an OpenGL ES 2.0
* context which can then be used via {@link Graphics#getGL20()}. The {@link GL10} and {@link GL11} interfaces should not be
* used when OpenGL ES 2.0 is enabled. To query whether enabling OpenGL ES 2.0 was successful use the
* {@link Graphics#isGL20Available()} method. You can configure other aspects of the application with the rest of the fields in
* the {@link AndroidApplicationConfiguration} instance.
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer,
* etc.). */
public void initialize (ApplicationListener listener, AndroidApplicationConfiguration config) {
graphics = new AndroidGraphics(this, config, config.resolutionStrategy == null ? new FillResolutionStrategy()
: config.resolutionStrategy);
input = new AndroidInput(this, graphics.view, config);
audio = new AndroidAudio(this, config);
files = new AndroidFiles(this.getAssets(), this.getFilesDir().getAbsolutePath());
net = new AndroidNet(this);
this.listener = listener;
this.handler = new Handler();
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
try {
requestWindowFeature(Window.FEATURE_NO_TITLE);
} catch (Exception ex) {
log("AndroidApplication", "Content already displayed, cannot request FEATURE_NO_TITLE", ex);
}
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
setContentView(graphics.getView(), createLayoutParams());
createWakeLock(config);
hideStatusBar(config);
}
protected FrameLayout.LayoutParams createLayoutParams () {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,
android.view.ViewGroup.LayoutParams.FILL_PARENT);
layoutParams.gravity = Gravity.CENTER;
return layoutParams;
}
protected void createWakeLock (AndroidApplicationConfiguration config) {
if (config.useWakelock) {
PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "libgdx wakelock");
}
}
protected void hideStatusBar (AndroidApplicationConfiguration config) {
if (!config.hideStatusBar || getVersion() < 11)
return;
View rootView = getWindow().getDecorView();
try {
Method m = View.class.getMethod("setSystemUiVisibility", int.class);
m.invoke(rootView, 0x0);
m.invoke(rootView, 0x1);
} catch (Exception e) {
}
}
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. If useGL20IfAvailable is set the AndroidApplication will try to create an OpenGL ES 2.0
* context which can then be used via {@link Graphics#getGL20()}. The {@link GL10} and {@link GL11} interfaces should not be
* used when OpenGL ES 2.0 is enabled. To query whether enabling OpenGL ES 2.0 was successful use the
* {@link Graphics#isGL20Available()} method. Uses a default {@link AndroidApplicationConfiguration}.
* <p/>
* Note: you have to add the returned view to your layout!
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @param useGL2IfAvailable whether to use OpenGL ES 2.0 if its available.
* @return the GLSurfaceView of the application */
public View initializeForView (ApplicationListener listener, boolean useGL2IfAvailable) {
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
config.useGL20 = useGL2IfAvailable;
return initializeForView(listener, config);
}
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. If config.useGL20 is set the AndroidApplication will try to create an OpenGL ES 2.0
* context which can then be used via {@link Graphics#getGL20()}. The {@link GL10} and {@link GL11} interfaces should not be
* used when OpenGL ES 2.0 is enabled. To query whether enabling OpenGL ES 2.0 was successful use the
* {@link Graphics#isGL20Available()} method. You can configure other aspects of the application with the rest of the fields in
* the {@link AndroidApplicationConfiguration} instance.
* <p/>
* Note: you have to add the returned view to your layout!
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer,
* etc.).
* @return the GLSurfaceView of the application */
public View initializeForView (ApplicationListener listener, AndroidApplicationConfiguration config) {
graphics = new AndroidGraphics(this, config, config.resolutionStrategy == null ? new FillResolutionStrategy()
: config.resolutionStrategy);
input = new AndroidInput(this, graphics.view, config);
audio = new AndroidAudio(this, config);
files = new AndroidFiles(this.getAssets(), this.getFilesDir().getAbsolutePath());
net = new AndroidNet(this);
this.listener = listener;
this.handler = new Handler();
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
createWakeLock(config);
hideStatusBar(config);
return graphics.getView();
}
@Override
protected void onPause () {
if (wakeLock != null) wakeLock.release();
boolean isContinuous = graphics.isContinuousRendering();
graphics.setContinuousRendering(true);
graphics.pause();
input.unregisterSensorListeners();
// erase pointer ids. this sucks donkeyballs...
int[] realId = input.realId;
for (int i = 0; i < realId.length; i++)
realId[i] = -1;
if (isFinishing()) {
graphics.clearManagedCaches();
graphics.destroy();
}
graphics.setContinuousRendering(isContinuous);
if (graphics != null && graphics.view != null) {
if (graphics.view instanceof GLSurfaceViewCupcake) ((GLSurfaceViewCupcake)graphics.view).onPause();
if (graphics.view instanceof android.opengl.GLSurfaceView) ((android.opengl.GLSurfaceView)graphics.view).onPause();
}
super.onPause();
}
@Override
protected void onResume () {
if (wakeLock != null) wakeLock.acquire();
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
((AndroidInput)getInput()).registerSensorListeners();
if (graphics != null && graphics.view != null) {
if (graphics.view instanceof GLSurfaceViewCupcake) ((GLSurfaceViewCupcake)graphics.view).onResume();
if (graphics.view instanceof android.opengl.GLSurfaceView) ((android.opengl.GLSurfaceView)graphics.view).onResume();
}
if (!firstResume) {
graphics.resume();
} else
firstResume = false;
super.onResume();
}
@Override
protected void onDestroy () {
super.onDestroy();
}
/** {@inheritDoc} */
@Override
public Audio getAudio () {
return audio;
}
/** {@inheritDoc} */
@Override
public Files getFiles () {
return files;
}
/** {@inheritDoc} */
@Override
public Graphics getGraphics () {
return graphics;
}
/** {@inheritDoc} */
@Override
public Input getInput () {
return input;
}
@Override
public Net getNet () {
return net;
}
/** {@inheritDoc} */
@Override
public ApplicationType getType () {
return ApplicationType.Android;
}
/** {@inheritDoc} */
@Override
public int getVersion () {
return Integer.parseInt(android.os.Build.VERSION.SDK);
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return Debug.getNativeHeapAllocatedSize();
}
@Override
public Preferences getPreferences (String name) {
return new AndroidPreferences(getSharedPreferences(name, Context.MODE_PRIVATE));
}
AndroidClipboard clipboard;
@Override
public Clipboard getClipboard() {
if (clipboard == null) {
clipboard = new AndroidClipboard(this);
}
return clipboard;
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
Gdx.graphics.requestRendering();
}
}
@Override
public void onConfigurationChanged (Configuration config) {
super.onConfigurationChanged(config);
boolean keyboardAvailable = false;
if (config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) keyboardAvailable = true;
input.keyboardAvailable = keyboardAvailable;
}
@Override
public void exit () {
handler.post(new Runnable() {
@Override
public void run () {
AndroidApplication.this.finish();
}
});
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) {
Log.d(tag, message);
}
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) {
Log.d(tag, message, exception);
}
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) Log.i(tag, message);
}
@Override
public void log (String tag, String message, Exception exception) {
if (logLevel >= LOG_INFO) Log.i(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) Log.e(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) Log.e(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
}
| Add logging for hideStatusBar exception | backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidApplication.java | Add logging for hideStatusBar exception | <ide><path>ackends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidApplication.java
<ide> m.invoke(rootView, 0x0);
<ide> m.invoke(rootView, 0x1);
<ide> } catch (Exception e) {
<add> log("AndroidApplication", "Can't hide status bar", e);
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 2d33976948498d9d952e3d896e3cf0ebfb93859e | 0 | SynBioDex/SBOLDesigner,SynBioDex/SBOLDesigner | /*
* Copyright (c) 2012 - 2015, Clark & Parsia, LLC. <http://www.clarkparsia.com>
*
* 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 edu.utah.ece.async.sboldesigner.sbol.editor.dialog;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.PatternSyntaxException;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import org.sbolstandard.core2.ComponentDefinition;
import org.sbolstandard.core2.SBOLDocument;
import org.sbolstandard.core2.SBOLReader;
import org.sbolstandard.core2.SBOLValidationException;
import org.sbolstandard.core2.SequenceOntology;
import org.synbiohub.frontend.IdentifiedMetadata;
import org.synbiohub.frontend.SynBioHubException;
import org.synbiohub.frontend.SynBioHubFrontend;
import org.synbiohub.frontend.WebOfRegistriesData;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import edu.utah.ece.async.sboldesigner.sbol.CharSequenceUtil;
import edu.utah.ece.async.sboldesigner.sbol.SBOLUtils;
import edu.utah.ece.async.sboldesigner.sbol.SBOLUtils.Types;
import edu.utah.ece.async.sboldesigner.sbol.editor.Part;
import edu.utah.ece.async.sboldesigner.sbol.editor.Parts;
import edu.utah.ece.async.sboldesigner.sbol.editor.Registries;
import edu.utah.ece.async.sboldesigner.sbol.editor.Registry;
import edu.utah.ece.async.sboldesigner.sbol.editor.SBOLEditorPreferences;
import edu.utah.ece.async.sboldesigner.sbol.editor.SynBioHubFrontends;
import edu.utah.ece.async.sboldesigner.swing.ComboBoxRenderer;
import edu.utah.ece.async.sboldesigner.swing.FormBuilder;
/**
*
* @author Evren Sirin
*/
public class RegistryInputDialog extends InputDialog<SBOLDocument> {
private final ComboBoxRenderer<Registry> registryRenderer = new ComboBoxRenderer<Registry>() {
@Override
protected String getLabel(Registry registry) {
StringBuilder sb = new StringBuilder();
if (registry != null) {
sb.append(registry.getName());
if (!registry.getLocation().equals("N/A")) {
sb.append(" (");
sb.append(CharSequenceUtil.shorten(registry.getLocation(), 30));
sb.append(")");
}
}
return sb.toString();
}
@Override
protected String getToolTip(Registry registry) {
return registry == null ? "" : registry.getDescription();
}
};
private final ComboBoxRenderer<IdentifiedMetadata> collectionsRenderer = new ComboBoxRenderer<IdentifiedMetadata>() {
@Override
protected String getLabel(IdentifiedMetadata collection) {
if (collection != null) {
return collection.getDisplayId();
} else {
return "Unknown";
}
}
@Override
protected String getToolTip(IdentifiedMetadata collection) {
return collection == null ? "" : collection.getDescription();
}
};
private static final String TITLE = "Select a part from registry";
public static final Part ALL_PARTS = new Part("All parts", "All");
// represents what part we should display in role selection
private Part part;
// represents the role of the template CD, could be used in roleRefinement
private URI refinementRole;
private JComboBox<Part> roleSelection;
private JComboBox<String> roleRefinement;
private ActionListener roleRefinementListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
updateTable();
}
};
private Types type;
private SBOLDocument workingDoc;
private JComboBox<Types> typeSelection;
private JComboBox<IdentifiedMetadata> collectionSelection;
private boolean updateCollection = true;
private ActionListener collectionSelectionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
// only update collectionSelection when we aren't programmatically
// modifying it in collectionSelectionListener
if (updateCollection) {
updateCollectionSelection(false, null);
updateTable();
}
}
};
private static HashMap<Registry, ArrayList<IdentifiedMetadata>> collectionPaths = new HashMap<>();
private JTable table;
private JLabel tableLabel;
private JScrollPane scroller;
final JTextField filterSelection = new JTextField();
/*
* Determines whether the table should be refreshed when a user types in
* filter text. This is true when the results from SynBioHubQuery exceeds
* the QUERY_LIMIT.
*/
private boolean refreshSearch = false;
/*
* Stores the filter text that caused the current ArrayList<TableMetadata>.
*/
private String cacheKey = "";
private ComponentDefinitionBox root;
private static SynBioHubFrontend synBioHub;
private boolean allowCollectionSelection = false;
private String objectType = "ComponentDefinition";
/**
* Allows a collection to be selected.
*/
public void allowCollectionSelection() {
allowCollectionSelection = true;
}
public void setObjectType(String objectType) {
this.objectType = objectType;
}
/**
* For when the working document is known and the root is not needed.
*/
public RegistryInputDialog(final Component parent, final Part part, Types type, URI refinementRole,
SBOLDocument workingDoc) {
super(parent, TITLE);
this.workingDoc = workingDoc;
setup(null, part, type, refinementRole);
}
/**
* For when the working document is unknown and the root is not needed.
*/
public RegistryInputDialog(final Component parent, final Part part, Types type, URI refinementRole) {
super(parent, TITLE);
this.workingDoc = null;
setup(null, part, type, refinementRole);
}
/**
* For when the working document is known and preferences node shouldn't be
* used
*/
public RegistryInputDialog(final Component parent, ComponentDefinitionBox root, final Part part, Types type,
URI refinementRole, SBOLDocument workingDoc) {
super(parent, TITLE);
this.workingDoc = workingDoc;
setup(root, part, type, refinementRole);
}
/**
* For when the working document is unknown and preferences node should be
* used
*/
public RegistryInputDialog(final Component parent, ComponentDefinitionBox root, final Part part, Types type,
URI refinementRole) {
super(parent, TITLE);
this.workingDoc = null;
setup(root, part, type, refinementRole);
}
/**
* root, if not null, will reference the root CD that was selected.
*/
private void setup(ComponentDefinitionBox root, final Part part, Types type, URI refinementRole) {
this.root = root;
this.part = part;
this.refinementRole = refinementRole;
this.type = type;
Registries registries = Registries.get();
int selectedRegistry = registries.getVersionRegistryIndex();
registrySelection = new JComboBox<Registry>(Iterables.toArray(registries, Registry.class));
if (registries.size() > 0) {
registrySelection.setSelectedIndex(selectedRegistry);
}
registrySelection.addActionListener(actionListener);
registrySelection.setRenderer(registryRenderer);
builder.add("Registry", registrySelection);
if (registries.size() == 0) {
JOptionPane.showMessageDialog(this,
"No parts registries are defined.\nPlease click 'Options' and add a parts registry.");
location = null;
uriPrefix = null;
} else {
location = registries.get(selectedRegistry).getLocation();
uriPrefix = registries.get(selectedRegistry).getUriPrefix();
}
}
@Override
public void initFormPanel(FormBuilder builder) {
// set up type selection
typeSelection = new JComboBox<Types>(Types.values());
typeSelection.setSelectedItem(type);
typeSelection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateTable();
updateContext();
}
});
if (objectType == "ComponentDefinition") {
builder.add("Part type", typeSelection);
}
// set up collection selection
collectionSelection = new JComboBox<IdentifiedMetadata>();
collectionSelection.setRenderer(collectionsRenderer);
updateCollectionSelection(true, null);
collectionSelection.addActionListener(collectionSelectionListener);
builder.add("Collection", collectionSelection);
// set up role selection
List<Part> parts = Lists.newArrayList(Parts.sorted());
parts.add(0, ALL_PARTS);
roleSelection = new JComboBox<Part>(parts.toArray(new Part[0]));
roleSelection.setRenderer(new PartCellRenderer());
roleSelection.setSelectedItem(part);
roleSelection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
part = (Part) roleSelection.getSelectedItem();
updateRoleRefinement();
updateTable();
}
});
if (objectType == "ComponentDefinition") {
builder.add("Part role", roleSelection);
}
// set up the JComboBox for role refinement
roleRefinement = new JComboBox<String>();
updateRoleRefinement();
roleRefinement.removeActionListener(roleRefinementListener);
if (refinementRole != null && refinementRole != part.getRole()) {
String roleName = new SequenceOntology().getName(refinementRole);
if (!comboBoxContains(roleRefinement, roleName)) {
roleRefinement.addItem(roleName);
}
roleRefinement.setSelectedItem(roleName);
}
roleRefinement.addActionListener(roleRefinementListener);
if (objectType == "ComponentDefinition") {
builder.add("Role refinement", roleRefinement);
}
updateContext();
// set up the filter
filterSelection.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent paramDocumentEvent) {
searchOrFilterTable();
}
@Override
public void insertUpdate(DocumentEvent paramDocumentEvent) {
searchOrFilterTable();
}
@Override
public void changedUpdate(DocumentEvent paramDocumentEvent) {
searchOrFilterTable();
}
private void searchOrFilterTable() {
/*
* System.out.println();
* System.out.println("searchOrFilterTable");
* System.out.println("refreshSearch: " + refreshSearch);
* System.out.println("cacheKey: " + cacheKey);
* System.out.println("filter: " + filterSelection.getText());
*/
if ((refreshSearch || filterSelection.getText().equals("")
|| !filterSelection.getText().contains(cacheKey)) && isMetadata()) {
searchParts(part, synBioHub, filterSelection.getText());
} else {
updateFilter(filterSelection.getText());
}
}
});
builder.add("Filter parts", filterSelection);
}
/**
* Returns whether box contains s
*/
private boolean comboBoxContains(JComboBox<String> box, String s) {
for (int i = 0; i < box.getItemCount(); i++) {
if (s != null && s.equals(roleRefinement.getItemAt(i))) {
return true;
}
}
return false;
}
@Override
protected JPanel initMainPanel() {
JPanel panel;
Part part = null;
if (roleSelection.isEnabled() && roleRefinement.isEnabled()) {
String roleName = (String) roleRefinement.getSelectedItem();
if (roleName == null || roleName.equals("None")) {
part = (Part) roleSelection.getSelectedItem();
} else {
SequenceOntology so = new SequenceOntology();
URI role = so.getURIbyName(roleName);
part = new Part(role, null, null);
}
} else {
part = ALL_PARTS;
}
if (isMetadata()) {
searchParts(part, synBioHub, filterSelection.getText());
TableMetadataTableModel tableModel = new TableMetadataTableModel(new ArrayList<TableMetadata>());
panel = createTablePanel(tableModel, "Matching parts (" + tableModel.getRowCount() + ")");
} else {
List<ComponentDefinition> components = searchParts(part);
ComponentDefinitionTableModel tableModel = new ComponentDefinitionTableModel(components);
panel = createTablePanel(tableModel, "Matching parts (" + tableModel.getRowCount() + ")");
}
table = (JTable) panel.getClientProperty("table");
tableLabel = (JLabel) panel.getClientProperty("label");
scroller = (JScrollPane) panel.getClientProperty("scroller");
return panel;
}
/**
* Checks to see if the registry we are working on is represented by
* IdentifiedMetadata.
*/
private boolean isMetadata() {
return location.startsWith("http://") || location.startsWith("https://");
}
/**
* Gets the SBOLDocument from the path (file on disk) and returns all its
* CDs.
*/
private List<ComponentDefinition> searchParts(Part part) {
try {
if (isMetadata()) {
throw new Exception("Incorrect state. url isn't a path");
}
if (part.equals(ALL_PARTS)) {
part = null;
}
SBOLReader.setURIPrefix(SBOLEditorPreferences.INSTANCE.getUserInfo().getURI().toString());
SBOLReader.setCompliant(true);
SBOLDocument doc;
Registry registry = (Registry) registrySelection.getSelectedItem();
if (registry.equals(Registry.BUILT_IN)) {
// read from BuiltInParts.xml
doc = SBOLReader.read(Registry.class.getResourceAsStream("/BuiltInParts.xml"));
} else if (registry.equals(Registry.WORKING_DOCUMENT)) {
if (workingDoc != null) {
// workingDoc is specified, so use that
doc = workingDoc;
} else {
// read from SBOLUtils.setupFile();
File file = SBOLUtils.setupFile();
if (file.exists()) {
doc = SBOLReader.read(file);
} else {
// JOptionPane.showMessageDialog(null, "The working
// document could not be found on disk. Try opening the
// file again.");
return new ArrayList<ComponentDefinition>();
}
}
} else {
// read from the location (path)
doc = SBOLReader.read(location);
}
doc.setDefaultURIprefix(SBOLEditorPreferences.INSTANCE.getUserInfo().getURI().toString());
return SBOLUtils.getCDOfRole(doc, part);
} catch (Exception e) {
e.printStackTrace();
MessageDialog.showMessage(null, "Getting the SBOLDocument from path failed: ", e.getMessage());
Registries registries = Registries.get();
registries.setVersionRegistryIndex(0);
registries.save();
return null;
}
}
/**
* Queries SynBioHub for CDs matching the role(s), type(s), and
* collection(s) of the part. Also filters by the filterText.
*/
private void searchParts(Part part, SynBioHubFrontend synbiohub, String filterText) {
try {
if (!isMetadata()) {
throw new Exception("Incorrect state. url is a path");
}
if (synbiohub == null) {
synbiohub = createSynBioHubFrontend(location, uriPrefix);
}
if (part != null) {
// create the query
IdentifiedMetadata selectedCollection = (IdentifiedMetadata) collectionSelection.getSelectedItem();
if (selectedCollection == null) {
return;
}
Set<URI> setCollections = new HashSet<URI>(Arrays.asList(URI.create(selectedCollection.getUri())));
Set<URI> setRoles = new HashSet<URI>(part.getRoles());
Set<URI> setTypes = SBOLUtils.convertTypesToSet((Types) typeSelection.getSelectedItem());
SynBioHubQuery query = new SynBioHubQuery(synbiohub, setRoles, setTypes, setCollections, filterText,
objectType, new TableUpdater(), this);
// non-blocking: will update using the TableUpdater
query.execute();
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Querying this repository failed: " + e.getMessage() + "\n"
+ " Internet connection is required for importing from SynBioHub. Setting default registry to built-in parts, which doesn't require an internet connection.");
Registries registries = Registries.get();
registries.setVersionRegistryIndex(0);
registries.save();
}
}
@Override
protected SBOLDocument getSelection() {
try {
SBOLDocument document = null;
ComponentDefinition comp = null;
int row = table.convertRowIndexToModel(table.getSelectedRow());
if (isMetadata()) {
TableMetadata compMeta = ((TableMetadataTableModel) table.getModel()).getElement(row);
if (synBioHub == null) {
System.out.print(uriPrefix);
synBioHub = createSynBioHubFrontend(location, uriPrefix);
}
if (compMeta.isCollection && !allowCollectionSelection) {
JOptionPane.showMessageDialog(getParent(), "Selecting collections is not allowed");
return new SBOLDocument();
}
// TODO: if uri below starts with uriPrefix then get from synbiohub as below
// otherwise, create a new synbiohubFrontend which has location/uriPrefix which matches uri below
document = synBioHub.getSBOL(URI.create(compMeta.identified.getUri()));
comp = document.getComponentDefinition(URI.create(compMeta.identified.getUri()));
if (comp == null) {
// if cannot find it then return root component definition
// from document
for (ComponentDefinition cd : document.getRootComponentDefinitions()) {
comp = cd;
}
}
} else {
document = new SBOLDocument();
comp = ((ComponentDefinitionTableModel) table.getModel()).getElement(row);
document = document.createRecursiveCopy(comp);
}
if (root != null) {
root.cd = document.getComponentDefinition(comp.getIdentity());
}
return document;
} catch (SBOLValidationException | SynBioHubException e) {
e.printStackTrace();
MessageDialog.showMessage(null, "Getting this selection failed: ", e.getMessage());
return null;
}
}
@Override
protected void registryChanged() {
if (isMetadata()) {
synBioHub = createSynBioHubFrontend(location, uriPrefix);
}
loginButton.setEnabled(isMetadata());
updateCollectionSelection(true, null);
updateTable();
}
private void updateCollectionSelection(boolean registryChanged, IdentifiedMetadata newCollection) {
collectionSelection.setEnabled(isMetadata());
if (!isMetadata()) {
return;
}
if (synBioHub == null) {
synBioHub = createSynBioHubFrontend(location, uriPrefix);
}
Registry registry = (Registry) registrySelection.getSelectedItem();
updateCollection = false;
if (registryChanged) {
// display only "rootCollections"
IdentifiedMetadata allCollections = new IdentifiedMetadata();
allCollections.setName("All Collections");
allCollections.setDisplayId("All Collections");
allCollections.setUri("http://AllCollections");
IdentifiedMetadata rootCollections = new IdentifiedMetadata();
rootCollections.setName("Root Collections");
rootCollections.setDisplayId("Root Collections");
rootCollections.setUri("http://RootCollections");
collectionSelection.removeAllItems();
collectionSelection.addItem(rootCollections);
collectionSelection.addItem(allCollections);
collectionSelection.setSelectedItem(rootCollections);
// restore/create cached collection path
if (collectionPaths.containsKey(registry)) {
for (IdentifiedMetadata collection : collectionPaths.get(registry)) {
collectionSelection.addItem(collection);
collectionSelection.setSelectedItem(collection);
}
} else {
collectionPaths.put(registry, new ArrayList<>());
}
} else {
// clicked on different collection
if (newCollection != null) {
collectionSelection.addItem(newCollection);
collectionSelection.setSelectedItem(newCollection);
collectionPaths.get(registry).add(newCollection);
} else {
while (collectionSelection.getSelectedIndex() + 1 < collectionSelection.getItemCount()) {
collectionSelection.removeItemAt(collectionSelection.getSelectedIndex() + 1);
collectionPaths.get(registry).remove(collectionSelection.getSelectedIndex());
}
}
}
updateCollection = true;
}
private void updateRoleRefinement() {
roleRefinement.removeActionListener(roleRefinementListener);
roleRefinement.removeAllItems();
for (String s : SBOLUtils.createRefinements((Part) roleSelection.getSelectedItem())) {
roleRefinement.addItem(s);
}
roleRefinement.addActionListener(roleRefinementListener);
}
private void updateContext() {
boolean enableRoles = typeSelection.getSelectedItem() == Types.DNA
|| typeSelection.getSelectedItem() == Types.RNA;
roleSelection.setEnabled(enableRoles);
roleRefinement.setEnabled(enableRoles);
}
public void updateTable() {
// create the part criteria
Part part = null;
if (roleSelection.isEnabled() && roleRefinement.isEnabled()) {
String roleName = (String) roleRefinement.getSelectedItem();
if (roleName == null || roleName.equals("None")) {
part = (Part) roleSelection.getSelectedItem();
} else {
SequenceOntology so = new SequenceOntology();
URI role = so.getURIbyName(roleName);
part = new Part(role, null, null);
}
} else {
part = ALL_PARTS;
}
if (isMetadata()) {
searchParts(part, synBioHub, filterSelection.getText());
} else {
List<ComponentDefinition> components = searchParts(part);
components = SBOLUtils.getCDOfType(components, (Types) typeSelection.getSelectedItem());
ComponentDefinitionTableModel tableModel = new ComponentDefinitionTableModel(components);
table = new JTable(tableModel);
tableLabel.setText("Matching parts (" + components.size() + ")");
refreshSearch = false;
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tableModel);
table.setRowSorter(sorter);
setWidthAsPercentages(table, tableModel.getWidths());
}
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent event) {
setSelectAllowed(table.getSelectedRow() >= 0);
}
});
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2 && table.getSelectedRow() >= 0) {
handleTableSelection(false);
}
}
});
scroller.setViewportView(table);
}
@Override
protected void handleTableSelection(boolean select) {
// handle collection selected
if (isMetadata()) {
int row = table.convertRowIndexToModel(table.getSelectedRow());
TableMetadata meta = ((TableMetadataTableModel) table.getModel()).getElement(row);
if (meta.isCollection && (!select || !allowCollectionSelection)) {
updateCollectionSelection(false, meta.identified);
updateTable();
return;
}
}
// otherwise a part was selected
canceled = false;
setVisible(false);
}
private void updateFilter(String filterText) {
filterText = "(?i)" + filterText;
if (isMetadata()) {
TableRowSorter<TableMetadataTableModel> sorter = (TableRowSorter) table.getRowSorter();
if (filterText.length() == 0) {
sorter.setRowFilter(null);
} else {
try {
RowFilter<TableMetadataTableModel, Object> rf = RowFilter.regexFilter(filterText, 0, 1, 2, 4);
sorter.setRowFilter(rf);
} catch (PatternSyntaxException e) {
sorter.setRowFilter(null);
}
}
tableLabel.setText("Matching parts (" + sorter.getViewRowCount() + ")");
} else {
TableRowSorter<ComponentDefinitionTableModel> sorter = (TableRowSorter) table.getRowSorter();
if (filterText.length() == 0) {
sorter.setRowFilter(null);
} else {
try {
RowFilter<ComponentDefinitionTableModel, Object> rf = RowFilter.regexFilter(filterText, 0, 1, 2, 4);
sorter.setRowFilter(rf);
} catch (PatternSyntaxException e) {
sorter.setRowFilter(null);
}
}
tableLabel.setText("Matching parts (" + sorter.getViewRowCount() + ")");
}
}
/**
* Updates the table using the provided components. This lets the
* SBOLStackQuery thread update the table.
*/
public class TableUpdater {
public void updateTable(ArrayList<TableMetadata> identified, String filterText) {
if (!filterSelection.getText().equals(filterText)) {
// don't update if the filterSelection text has changed.
return;
}
TableMetadataTableModel tableModel = new TableMetadataTableModel(identified);
table = new JTable(tableModel);
tableLabel.setText("Matching parts (" + identified.size() + ")");
refreshSearch = identified.size() >= SynBioHubQuery.QUERY_LIMIT;
if (filterText != null && !refreshSearch) {
cacheKey = filterText;
}
/*
* System.out.println(); System.out.println("TableUpdater");
* System.out.println("refreshSearch: " + refreshSearch);
* System.out.println("cacheKey: " + cacheKey); System.out.println(
* "filter: " + filterSelection.getText());
*/
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tableModel);
table.setRowSorter(sorter);
setWidthAsPercentages(table, tableModel.getWidths());
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent event) {
setSelectAllowed(table.getSelectedRow() >= 0);
}
});
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2 && table.getSelectedRow() >= 0) {
handleTableSelection(false);
}
}
});
scroller.setViewportView(table);
}
}
/**
* Wraps SynBioHubFrontend creation so legacy locations can be used.
*/
private SynBioHubFrontend createSynBioHubFrontend(String location, String uriPrefix) {
// update location and SynBioHub location if not using https
if (location == "http://synbiohub.org") {
location = "https://synbiohub.org";
// This isn't elegant, but should work
ArrayList<Registry> oldRegistries = new ArrayList<Registry>();
for (int i = 3; i < Registries.get().size(); i++) {
oldRegistries.add(Registries.get().get(i));
}
Registries.get().restoreDefaults();
for (Registry r : oldRegistries) {
Registries.get().add(r);
}
Registries.get().save();
}
// get logged in SynBioHubFrontend if possible
SynBioHubFrontends frontends = new SynBioHubFrontends();
if (frontends.hasFrontend(location)) {
return frontends.getFrontend(location);
}
return new SynBioHubFrontend(location, uriPrefix);
}
}
| src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/RegistryInputDialog.java | /*
* Copyright (c) 2012 - 2015, Clark & Parsia, LLC. <http://www.clarkparsia.com>
*
* 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 edu.utah.ece.async.sboldesigner.sbol.editor.dialog;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.PatternSyntaxException;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import org.sbolstandard.core2.ComponentDefinition;
import org.sbolstandard.core2.SBOLDocument;
import org.sbolstandard.core2.SBOLReader;
import org.sbolstandard.core2.SBOLValidationException;
import org.sbolstandard.core2.SequenceOntology;
import org.synbiohub.frontend.IdentifiedMetadata;
import org.synbiohub.frontend.SynBioHubException;
import org.synbiohub.frontend.SynBioHubFrontend;
import org.synbiohub.frontend.WebOfRegistriesData;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import edu.utah.ece.async.sboldesigner.sbol.CharSequenceUtil;
import edu.utah.ece.async.sboldesigner.sbol.SBOLUtils;
import edu.utah.ece.async.sboldesigner.sbol.SBOLUtils.Types;
import edu.utah.ece.async.sboldesigner.sbol.editor.Part;
import edu.utah.ece.async.sboldesigner.sbol.editor.Parts;
import edu.utah.ece.async.sboldesigner.sbol.editor.Registries;
import edu.utah.ece.async.sboldesigner.sbol.editor.Registry;
import edu.utah.ece.async.sboldesigner.sbol.editor.SBOLEditorPreferences;
import edu.utah.ece.async.sboldesigner.sbol.editor.SynBioHubFrontends;
import edu.utah.ece.async.sboldesigner.swing.ComboBoxRenderer;
import edu.utah.ece.async.sboldesigner.swing.FormBuilder;
/**
*
* @author Evren Sirin
*/
public class RegistryInputDialog extends InputDialog<SBOLDocument> {
private final ComboBoxRenderer<Registry> registryRenderer = new ComboBoxRenderer<Registry>() {
@Override
protected String getLabel(Registry registry) {
StringBuilder sb = new StringBuilder();
if (registry != null) {
sb.append(registry.getName());
if (!registry.getLocation().equals("N/A")) {
sb.append(" (");
sb.append(CharSequenceUtil.shorten(registry.getLocation(), 30));
sb.append(")");
}
}
return sb.toString();
}
@Override
protected String getToolTip(Registry registry) {
return registry == null ? "" : registry.getDescription();
}
};
private final ComboBoxRenderer<IdentifiedMetadata> collectionsRenderer = new ComboBoxRenderer<IdentifiedMetadata>() {
@Override
protected String getLabel(IdentifiedMetadata collection) {
if (collection != null) {
return collection.getDisplayId();
} else {
return "Unknown";
}
}
@Override
protected String getToolTip(IdentifiedMetadata collection) {
return collection == null ? "" : collection.getDescription();
}
};
private static final String TITLE = "Select a part from registry";
public static final Part ALL_PARTS = new Part("All parts", "All");
// represents what part we should display in role selection
private Part part;
// represents the role of the template CD, could be used in roleRefinement
private URI refinementRole;
private JComboBox<Part> roleSelection;
private JComboBox<String> roleRefinement;
private ActionListener roleRefinementListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
updateTable();
}
};
private Types type;
private SBOLDocument workingDoc;
private JComboBox<Types> typeSelection;
private JComboBox<IdentifiedMetadata> collectionSelection;
private boolean updateCollection = true;
private ActionListener collectionSelectionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
// only update collectionSelection when we aren't programmatically
// modifying it in collectionSelectionListener
if (updateCollection) {
updateCollectionSelection(false, null);
updateTable();
}
}
};
private static HashMap<Registry, ArrayList<IdentifiedMetadata>> collectionPaths = new HashMap<>();
private JTable table;
private JLabel tableLabel;
private JScrollPane scroller;
final JTextField filterSelection = new JTextField();
/*
* Determines whether the table should be refreshed when a user types in
* filter text. This is true when the results from SynBioHubQuery exceeds
* the QUERY_LIMIT.
*/
private boolean refreshSearch = false;
/*
* Stores the filter text that caused the current ArrayList<TableMetadata>.
*/
private String cacheKey = "";
private ComponentDefinitionBox root;
private static SynBioHubFrontend synBioHub;
private boolean allowCollectionSelection = false;
private String objectType = "ComponentDefinition";
/**
* Allows a collection to be selected.
*/
public void allowCollectionSelection() {
allowCollectionSelection = true;
}
public void setObjectType(String objectType) {
this.objectType = objectType;
}
/**
* For when the working document is known and the root is not needed.
*/
public RegistryInputDialog(final Component parent, final Part part, Types type, URI refinementRole,
SBOLDocument workingDoc) {
super(parent, TITLE);
this.workingDoc = workingDoc;
setup(null, part, type, refinementRole);
}
/**
* For when the working document is unknown and the root is not needed.
*/
public RegistryInputDialog(final Component parent, final Part part, Types type, URI refinementRole) {
super(parent, TITLE);
this.workingDoc = null;
setup(null, part, type, refinementRole);
}
/**
* For when the working document is known and preferences node shouldn't be
* used
*/
public RegistryInputDialog(final Component parent, ComponentDefinitionBox root, final Part part, Types type,
URI refinementRole, SBOLDocument workingDoc) {
super(parent, TITLE);
this.workingDoc = workingDoc;
setup(root, part, type, refinementRole);
}
/**
* For when the working document is unknown and preferences node should be
* used
*/
public RegistryInputDialog(final Component parent, ComponentDefinitionBox root, final Part part, Types type,
URI refinementRole) {
super(parent, TITLE);
this.workingDoc = null;
setup(root, part, type, refinementRole);
}
/**
* root, if not null, will reference the root CD that was selected.
*/
private void setup(ComponentDefinitionBox root, final Part part, Types type, URI refinementRole) {
this.root = root;
this.part = part;
this.refinementRole = refinementRole;
this.type = type;
Registries registries = Registries.get();
int selectedRegistry = registries.getVersionRegistryIndex();
registrySelection = new JComboBox<Registry>(Iterables.toArray(registries, Registry.class));
if (registries.size() > 0) {
registrySelection.setSelectedIndex(selectedRegistry);
}
registrySelection.addActionListener(actionListener);
registrySelection.setRenderer(registryRenderer);
builder.add("Registry", registrySelection);
if (registries.size() == 0) {
JOptionPane.showMessageDialog(this,
"No parts registries are defined.\nPlease click 'Options' and add a parts registry.");
location = null;
uriPrefix = null;
} else {
location = registries.get(selectedRegistry).getLocation();
uriPrefix = registries.get(selectedRegistry).getUriPrefix();
}
}
@Override
public void initFormPanel(FormBuilder builder) {
// set up type selection
typeSelection = new JComboBox<Types>(Types.values());
typeSelection.setSelectedItem(type);
typeSelection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateTable();
updateContext();
}
});
if (objectType == "ComponentDefinition") {
builder.add("Part type", typeSelection);
}
// set up collection selection
collectionSelection = new JComboBox<IdentifiedMetadata>();
collectionSelection.setRenderer(collectionsRenderer);
updateCollectionSelection(true, null);
collectionSelection.addActionListener(collectionSelectionListener);
builder.add("Collection", collectionSelection);
// set up role selection
List<Part> parts = Lists.newArrayList(Parts.sorted());
parts.add(0, ALL_PARTS);
roleSelection = new JComboBox<Part>(parts.toArray(new Part[0]));
roleSelection.setRenderer(new PartCellRenderer());
roleSelection.setSelectedItem(part);
roleSelection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
part = (Part) roleSelection.getSelectedItem();
updateRoleRefinement();
updateTable();
}
});
if (objectType == "ComponentDefinition") {
builder.add("Part role", roleSelection);
}
// set up the JComboBox for role refinement
roleRefinement = new JComboBox<String>();
updateRoleRefinement();
roleRefinement.removeActionListener(roleRefinementListener);
if (refinementRole != null && refinementRole != part.getRole()) {
String roleName = new SequenceOntology().getName(refinementRole);
if (!comboBoxContains(roleRefinement, roleName)) {
roleRefinement.addItem(roleName);
}
roleRefinement.setSelectedItem(roleName);
}
roleRefinement.addActionListener(roleRefinementListener);
if (objectType == "ComponentDefinition") {
builder.add("Role refinement", roleRefinement);
}
updateContext();
// set up the filter
filterSelection.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent paramDocumentEvent) {
searchOrFilterTable();
}
@Override
public void insertUpdate(DocumentEvent paramDocumentEvent) {
searchOrFilterTable();
}
@Override
public void changedUpdate(DocumentEvent paramDocumentEvent) {
searchOrFilterTable();
}
private void searchOrFilterTable() {
/*
* System.out.println();
* System.out.println("searchOrFilterTable");
* System.out.println("refreshSearch: " + refreshSearch);
* System.out.println("cacheKey: " + cacheKey);
* System.out.println("filter: " + filterSelection.getText());
*/
if ((refreshSearch || filterSelection.getText().equals("")
|| !filterSelection.getText().contains(cacheKey)) && isMetadata()) {
searchParts(part, synBioHub, filterSelection.getText());
} else {
updateFilter(filterSelection.getText());
}
}
});
builder.add("Filter parts", filterSelection);
}
/**
* Returns whether box contains s
*/
private boolean comboBoxContains(JComboBox<String> box, String s) {
for (int i = 0; i < box.getItemCount(); i++) {
if (s != null && s.equals(roleRefinement.getItemAt(i))) {
return true;
}
}
return false;
}
@Override
protected JPanel initMainPanel() {
JPanel panel;
Part part = null;
if (roleSelection.isEnabled() && roleRefinement.isEnabled()) {
String roleName = (String) roleRefinement.getSelectedItem();
if (roleName == null || roleName.equals("None")) {
part = (Part) roleSelection.getSelectedItem();
} else {
SequenceOntology so = new SequenceOntology();
URI role = so.getURIbyName(roleName);
part = new Part(role, null, null);
}
} else {
part = ALL_PARTS;
}
if (isMetadata()) {
searchParts(part, synBioHub, filterSelection.getText());
TableMetadataTableModel tableModel = new TableMetadataTableModel(new ArrayList<TableMetadata>());
panel = createTablePanel(tableModel, "Matching parts (" + tableModel.getRowCount() + ")");
} else {
List<ComponentDefinition> components = searchParts(part);
ComponentDefinitionTableModel tableModel = new ComponentDefinitionTableModel(components);
panel = createTablePanel(tableModel, "Matching parts (" + tableModel.getRowCount() + ")");
}
table = (JTable) panel.getClientProperty("table");
tableLabel = (JLabel) panel.getClientProperty("label");
scroller = (JScrollPane) panel.getClientProperty("scroller");
return panel;
}
/**
* Checks to see if the registry we are working on is represented by
* IdentifiedMetadata.
*/
private boolean isMetadata() {
return location.startsWith("http://") || location.startsWith("https://");
}
/**
* Gets the SBOLDocument from the path (file on disk) and returns all its
* CDs.
*/
private List<ComponentDefinition> searchParts(Part part) {
try {
if (isMetadata()) {
throw new Exception("Incorrect state. url isn't a path");
}
if (part.equals(ALL_PARTS)) {
part = null;
}
SBOLReader.setURIPrefix(SBOLEditorPreferences.INSTANCE.getUserInfo().getURI().toString());
SBOLReader.setCompliant(true);
SBOLDocument doc;
Registry registry = (Registry) registrySelection.getSelectedItem();
if (registry.equals(Registry.BUILT_IN)) {
// read from BuiltInParts.xml
doc = SBOLReader.read(Registry.class.getResourceAsStream("/BuiltInParts.xml"));
} else if (registry.equals(Registry.WORKING_DOCUMENT)) {
if (workingDoc != null) {
// workingDoc is specified, so use that
doc = workingDoc;
} else {
// read from SBOLUtils.setupFile();
File file = SBOLUtils.setupFile();
if (file.exists()) {
doc = SBOLReader.read(file);
} else {
// JOptionPane.showMessageDialog(null, "The working
// document could not be found on disk. Try opening the
// file again.");
return new ArrayList<ComponentDefinition>();
}
}
} else {
// read from the location (path)
doc = SBOLReader.read(location);
}
doc.setDefaultURIprefix(SBOLEditorPreferences.INSTANCE.getUserInfo().getURI().toString());
return SBOLUtils.getCDOfRole(doc, part);
} catch (Exception e) {
e.printStackTrace();
MessageDialog.showMessage(null, "Getting the SBOLDocument from path failed: ", e.getMessage());
Registries registries = Registries.get();
registries.setVersionRegistryIndex(0);
registries.save();
return null;
}
}
/**
* Queries SynBioHub for CDs matching the role(s), type(s), and
* collection(s) of the part. Also filters by the filterText.
*/
private void searchParts(Part part, SynBioHubFrontend synbiohub, String filterText) {
try {
if (!isMetadata()) {
throw new Exception("Incorrect state. url is a path");
}
if (synbiohub == null) {
synbiohub = createSynBioHubFrontend(location, uriPrefix);
}
if (part != null) {
// create the query
IdentifiedMetadata selectedCollection = (IdentifiedMetadata) collectionSelection.getSelectedItem();
if (selectedCollection == null) {
return;
}
Set<URI> setCollections = new HashSet<URI>(Arrays.asList(URI.create(selectedCollection.getUri())));
Set<URI> setRoles = new HashSet<URI>(part.getRoles());
Set<URI> setTypes = SBOLUtils.convertTypesToSet((Types) typeSelection.getSelectedItem());
SynBioHubQuery query = new SynBioHubQuery(synbiohub, setRoles, setTypes, setCollections, filterText,
objectType, new TableUpdater(), this);
// non-blocking: will update using the TableUpdater
query.execute();
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Querying this repository failed: " + e.getMessage() + "\n"
+ " Internet connection is required for importing from SynBioHub. Setting default registry to built-in parts, which doesn't require an internet connection.");
Registries registries = Registries.get();
registries.setVersionRegistryIndex(0);
registries.save();
}
}
@Override
protected SBOLDocument getSelection() {
try {
SBOLDocument document = null;
ComponentDefinition comp = null;
int row = table.convertRowIndexToModel(table.getSelectedRow());
if (isMetadata()) {
TableMetadata compMeta = ((TableMetadataTableModel) table.getModel()).getElement(row);
if (synBioHub == null) {
System.out.print(uriPrefix);
synBioHub = createSynBioHubFrontend(location, uriPrefix);
}
if (compMeta.isCollection && !allowCollectionSelection) {
JOptionPane.showMessageDialog(getParent(), "Selecting collections is not allowed");
return new SBOLDocument();
}
// TODO: if uri below starts with uriPrefix then get from synbiohub as below
// otherwise, create a new synbiohubFrontend which has location/uriPrefix which matches uri below
document = synBioHub.getSBOL(URI.create(compMeta.identified.getUri()));
comp = document.getComponentDefinition(URI.create(compMeta.identified.getUri()));
if (comp == null) {
// if cannot find it then return root component definition
// from document
for (ComponentDefinition cd : document.getRootComponentDefinitions()) {
comp = cd;
}
}
} else {
document = new SBOLDocument();
comp = ((ComponentDefinitionTableModel) table.getModel()).getElement(row);
document = document.createRecursiveCopy(comp);
}
if (root != null) {
root.cd = document.getComponentDefinition(comp.getIdentity());
}
return document;
} catch (SBOLValidationException | SynBioHubException e) {
e.printStackTrace();
MessageDialog.showMessage(null, "Getting this selection failed: ", e.getMessage());
return null;
}
}
@Override
protected void registryChanged() {
if (isMetadata()) {
synBioHub = createSynBioHubFrontend(location, uriPrefix);
}
loginButton.setEnabled(isMetadata());
updateCollectionSelection(true, null);
updateTable();
}
private void updateCollectionSelection(boolean registryChanged, IdentifiedMetadata newCollection) {
collectionSelection.setEnabled(isMetadata());
if (!isMetadata()) {
return;
}
if (synBioHub == null) {
synBioHub = createSynBioHubFrontend(location, uriPrefix);
}
Registry registry = (Registry) registrySelection.getSelectedItem();
updateCollection = false;
if (registryChanged) {
// display only "rootCollections"
IdentifiedMetadata rootCollections = new IdentifiedMetadata();
rootCollections.setName("Root Collections");
rootCollections.setDisplayId("Root Collections");
rootCollections.setUri("http://RootCollections");
IdentifiedMetadata allCollections = new IdentifiedMetadata();
allCollections.setName("All Collections");
allCollections.setDisplayId("All Collections");
allCollections.setUri("http://AllCollections");
collectionSelection.removeAllItems();
collectionSelection.addItem(rootCollections);
collectionSelection.addItem(allCollections);
collectionSelection.setSelectedItem(rootCollections);
// restore/create cached collection path
if (collectionPaths.containsKey(registry)) {
for (IdentifiedMetadata collection : collectionPaths.get(registry)) {
collectionSelection.addItem(collection);
collectionSelection.setSelectedItem(collection);
}
} else {
collectionPaths.put(registry, new ArrayList<>());
}
} else {
// clicked on different collection
if (newCollection != null) {
collectionSelection.addItem(newCollection);
collectionSelection.setSelectedItem(newCollection);
collectionPaths.get(registry).add(newCollection);
} else {
while (collectionSelection.getSelectedIndex() + 1 < collectionSelection.getItemCount()) {
collectionSelection.removeItemAt(collectionSelection.getSelectedIndex() + 1);
collectionPaths.get(registry).remove(collectionSelection.getSelectedIndex());
}
}
}
updateCollection = true;
}
private void updateRoleRefinement() {
roleRefinement.removeActionListener(roleRefinementListener);
roleRefinement.removeAllItems();
for (String s : SBOLUtils.createRefinements((Part) roleSelection.getSelectedItem())) {
roleRefinement.addItem(s);
}
roleRefinement.addActionListener(roleRefinementListener);
}
private void updateContext() {
boolean enableRoles = typeSelection.getSelectedItem() == Types.DNA
|| typeSelection.getSelectedItem() == Types.RNA;
roleSelection.setEnabled(enableRoles);
roleRefinement.setEnabled(enableRoles);
}
public void updateTable() {
// create the part criteria
Part part = null;
if (roleSelection.isEnabled() && roleRefinement.isEnabled()) {
String roleName = (String) roleRefinement.getSelectedItem();
if (roleName == null || roleName.equals("None")) {
part = (Part) roleSelection.getSelectedItem();
} else {
SequenceOntology so = new SequenceOntology();
URI role = so.getURIbyName(roleName);
part = new Part(role, null, null);
}
} else {
part = ALL_PARTS;
}
if (isMetadata()) {
searchParts(part, synBioHub, filterSelection.getText());
} else {
List<ComponentDefinition> components = searchParts(part);
components = SBOLUtils.getCDOfType(components, (Types) typeSelection.getSelectedItem());
ComponentDefinitionTableModel tableModel = new ComponentDefinitionTableModel(components);
table = new JTable(tableModel);
tableLabel.setText("Matching parts (" + components.size() + ")");
refreshSearch = false;
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tableModel);
table.setRowSorter(sorter);
setWidthAsPercentages(table, tableModel.getWidths());
}
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent event) {
setSelectAllowed(table.getSelectedRow() >= 0);
}
});
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2 && table.getSelectedRow() >= 0) {
handleTableSelection(false);
}
}
});
scroller.setViewportView(table);
}
@Override
protected void handleTableSelection(boolean select) {
// handle collection selected
if (isMetadata()) {
int row = table.convertRowIndexToModel(table.getSelectedRow());
TableMetadata meta = ((TableMetadataTableModel) table.getModel()).getElement(row);
if (meta.isCollection && (!select || !allowCollectionSelection)) {
updateCollectionSelection(false, meta.identified);
updateTable();
return;
}
}
// otherwise a part was selected
canceled = false;
setVisible(false);
}
private void updateFilter(String filterText) {
filterText = "(?i)" + filterText;
if (isMetadata()) {
TableRowSorter<TableMetadataTableModel> sorter = (TableRowSorter) table.getRowSorter();
if (filterText.length() == 0) {
sorter.setRowFilter(null);
} else {
try {
RowFilter<TableMetadataTableModel, Object> rf = RowFilter.regexFilter(filterText, 0, 1, 2, 4);
sorter.setRowFilter(rf);
} catch (PatternSyntaxException e) {
sorter.setRowFilter(null);
}
}
tableLabel.setText("Matching parts (" + sorter.getViewRowCount() + ")");
} else {
TableRowSorter<ComponentDefinitionTableModel> sorter = (TableRowSorter) table.getRowSorter();
if (filterText.length() == 0) {
sorter.setRowFilter(null);
} else {
try {
RowFilter<ComponentDefinitionTableModel, Object> rf = RowFilter.regexFilter(filterText, 0, 1, 2, 4);
sorter.setRowFilter(rf);
} catch (PatternSyntaxException e) {
sorter.setRowFilter(null);
}
}
tableLabel.setText("Matching parts (" + sorter.getViewRowCount() + ")");
}
}
/**
* Updates the table using the provided components. This lets the
* SBOLStackQuery thread update the table.
*/
public class TableUpdater {
public void updateTable(ArrayList<TableMetadata> identified, String filterText) {
if (!filterSelection.getText().equals(filterText)) {
// don't update if the filterSelection text has changed.
return;
}
TableMetadataTableModel tableModel = new TableMetadataTableModel(identified);
table = new JTable(tableModel);
tableLabel.setText("Matching parts (" + identified.size() + ")");
refreshSearch = identified.size() >= SynBioHubQuery.QUERY_LIMIT;
if (filterText != null && !refreshSearch) {
cacheKey = filterText;
}
/*
* System.out.println(); System.out.println("TableUpdater");
* System.out.println("refreshSearch: " + refreshSearch);
* System.out.println("cacheKey: " + cacheKey); System.out.println(
* "filter: " + filterSelection.getText());
*/
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tableModel);
table.setRowSorter(sorter);
setWidthAsPercentages(table, tableModel.getWidths());
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent event) {
setSelectAllowed(table.getSelectedRow() >= 0);
}
});
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2 && table.getSelectedRow() >= 0) {
handleTableSelection(false);
}
}
});
scroller.setViewportView(table);
}
}
/**
* Wraps SynBioHubFrontend creation so legacy locations can be used.
*/
private SynBioHubFrontend createSynBioHubFrontend(String location, String uriPrefix) {
// update location and SynBioHub location if not using https
if (location == "http://synbiohub.org") {
location = "https://synbiohub.org";
// This isn't elegant, but should work
ArrayList<Registry> oldRegistries = new ArrayList<Registry>();
for (int i = 3; i < Registries.get().size(); i++) {
oldRegistries.add(Registries.get().get(i));
}
Registries.get().restoreDefaults();
for (Registry r : oldRegistries) {
Registries.get().add(r);
}
Registries.get().save();
}
// get logged in SynBioHubFrontend if possible
SynBioHubFrontends frontends = new SynBioHubFrontends();
if (frontends.hasFrontend(location)) {
return frontends.getFrontend(location);
}
return new SynBioHubFrontend(location, uriPrefix);
}
}
| Flipped AllCollections and root.
| src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/RegistryInputDialog.java | Flipped AllCollections and root. | <ide><path>rc/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/RegistryInputDialog.java
<ide> updateCollection = false;
<ide> if (registryChanged) {
<ide> // display only "rootCollections"
<add> IdentifiedMetadata allCollections = new IdentifiedMetadata();
<add> allCollections.setName("All Collections");
<add> allCollections.setDisplayId("All Collections");
<add> allCollections.setUri("http://AllCollections");
<ide> IdentifiedMetadata rootCollections = new IdentifiedMetadata();
<ide> rootCollections.setName("Root Collections");
<ide> rootCollections.setDisplayId("Root Collections");
<ide> rootCollections.setUri("http://RootCollections");
<del> IdentifiedMetadata allCollections = new IdentifiedMetadata();
<del> allCollections.setName("All Collections");
<del> allCollections.setDisplayId("All Collections");
<del> allCollections.setUri("http://AllCollections");
<ide> collectionSelection.removeAllItems();
<ide> collectionSelection.addItem(rootCollections);
<ide> collectionSelection.addItem(allCollections); |
|
Java | bsd-3-clause | 32a6d7f83744f75dc1765bcfd62151f16ae348f0 | 0 | lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon | /*
* $Id: IpAccessControl.java,v 1.5 2003-07-14 06:45:07 tlipkis Exp $
*/
/*
Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.servlet;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;
import java.net.*;
import java.text.*;
import org.mortbay.html.*;
import org.mortbay.tools.*;
import org.lockss.util.*;
import org.lockss.daemon.*;
import org.lockss.daemon.status.*;
/** Display and update IP access control lists.
*/
public class IpAccessControl extends LockssServlet {
static final String AC_PREFIX = ServletManager.IP_ACCESS_PREFIX;
public static final String PARAM_IP_INCLUDE = AC_PREFIX + "include";
public static final String PARAM_IP_EXCLUDE = AC_PREFIX + "exclude";
private static final String footIP =
"List individual IP addresses (<code>172.16.31.14</code>), " +
"class A, B or C subnets (<code>10.*.*.*</code> ,  " +
"<code>172.16.31.*</code>) or CIDR notation " +
"subnets (<code>172.16.31.0/24</code>). " +
"<br>Enter each address or subnet mask on a separate line. " +
"<br>Deny addresses supersede Allow addresses." +
"<br>If the Allow list is empty, no remote access will be allowed.";
static Logger log = Logger.getLogger("IpAcc");
private ConfigManager configMgr;
public void init(ServletConfig config) throws ServletException {
super.init(config);
configMgr = getLockssDaemon().getConfigManager();
}
public void lockssHandleRequest() throws IOException {
String action = req.getParameter("action");
boolean isError = false;
if ("Update".equals(action)){
Vector incl = ipStrToVector(req.getParameter("inc_ips"));
Vector excl = ipStrToVector(req.getParameter("exc_ips"));
Vector inclErrs = findInvalidIps(incl);
Vector exclErrs = findInvalidIps(excl);
if (inclErrs.size() > 0 || exclErrs.size() > 0) {
displayPage(incl, excl, inclErrs, exclErrs);
} else {
try {
saveIPChanges(incl, excl);
} catch (Exception e) {
log.error("Error saving changes", e);
// set to null so will display unedited values.
// xxx should display error here
incl = null;
excl = null;
}
displayPage(incl, excl, null, null);
}
} else {
displayPage();
}
}
/**
* Display the page, given no new ip addresses and no errors
*/
private void displayPage()
throws IOException {
Vector incl = getListFromParam(PARAM_IP_INCLUDE);
Vector excl = getListFromParam(PARAM_IP_EXCLUDE);
// hack to remove possibly duplicated first element from platform subnet
if (incl.size() >= 2 && incl.get(0).equals(incl.get(1))) {
incl.remove(0);
}
displayPage(incl, excl, null, null);
}
private Vector getListFromParam(String param) {
Configuration config = Configuration.getCurrentConfig();
return StringUtil.breakAt(config.get(param), ';');
}
/**
* Display the UpdateIps page.
* @param incl vector of included ip addresses
* @param excl vector of excluded ip addresses
* @param inclErrs vector of malformed include ip addresses.
* @param exclErrs vector of malformed include ip addresses.
*/
private void displayPage(Vector incl, Vector excl,
Vector inclErrs, Vector exclErrs)
throws IOException {
Page page = newPage();
page.add(getIncludeExcludeElement(incl, excl,
inclErrs, exclErrs));
page.add(getFooter());
page.write(resp.getWriter());
}
/**
* Generate the block of the page that has the included/excluded
* ip address table.
* @param incl vector of included ip addresses
* @param excl vector of excluded ip addresses
* @param inclErrs vector of malformed include ip addresses.
* @param exclErrs vector of malformed include ip addresses.
* @return an html element representing the include/exclude ip address form
*/
private Element getIncludeExcludeElement(Vector incl, Vector excl,
Vector inclErrs,
Vector exclErrs) {
boolean isError = false;
String incString = null;
String excString = null;
Composite comp = new Composite();
Block centeredBlock = new Block(Block.Center);
Form frm = new Form(srvURL(myServletDescr(), null));
frm.method("POST");
Table table = new Table(1, "BORDER=1 CELLPADDING=0");
//table.center();
table.newRow("bgcolor=\"#CCCCCC\"");
table.newCell("align=center");
table.add("<font size=+1>Allow Access" + addFootnote(footIP) +
" </font>");
table.newCell("align=center");
table.add("<font size=+1>Deny Access" + addFootnote(footIP) +
" </font>");
if ((inclErrs != null && inclErrs.size() > 0) ||
(exclErrs != null && exclErrs.size() > 0)) {
String errorStr = null;
table.newRow();
table.newCell();
if (inclErrs != null && inclErrs.size() > 0) {
errorStr = getIPString(inclErrs);
table.add("Please correct the following error: <p><b><font color=\"#FF0000\">Error: Invalid IP Address "+errorStr+"</font></b>");
} else {
table.add(" ");
}
table.newCell();
if (exclErrs != null && exclErrs.size() > 0) {
errorStr = getIPString(exclErrs);
table.add("Please correct the following error: <p><b><font color=\"#FF0000\">Error: Invalid IP Address "+errorStr+"</font></b>");
} else {
table.add(" ");
}
}
incString = getIPString(incl);
excString = getIPString(excl);
TextArea incArea = new TextArea("inc_ips");
incArea.setSize(30, 20);
incArea.add(incString);
TextArea excArea = new TextArea("exc_ips");
excArea.setSize(30, 20);
excArea.add(excString);
table.newRow();
table.newCell("align=center");
table.add(incArea);
table.newCell("align=center");
table.add(excArea);
centeredBlock.add(table);
frm.add(centeredBlock);
Input submit = new Input(Input.Submit, "action", "Update");
frm.add("<center>"+submit+"</center>");
comp.add(frm);
return comp;
}
/**
* Checks the validity of a vector of IP addresses
* @param ipList vector containing strings representing the ip addresses
* @return vector of the malformed ip addresses
*/
public Vector findInvalidIps(Vector ipList) {
Vector errorIPs = new Vector();
if (ipList != null) {
for (Iterator iter = ipList.iterator(); iter.hasNext();) {
String ipStr = (String)iter.next();
IpFilter.Mask ip;
try {
ip = new IpFilter.Mask(ipStr, true);
} catch (IpFilter.MalformedException e) {
errorIPs.addElement(ipStr);
}
}
}
return errorIPs;
}
/**
* Convert a string of newline separated IP addresses to a vector of strings,
* removing duplicates
*
* @param ipStr string to convert into a vector
* @return vector of strings representing ip addresses
*/
private Vector ipStrToVector(String ipStr) {
return StringUtil.breakAt(ipStr, '\n', 0, true, true);
}
/**
* Convert a vector of strings representing ip addresses
* to a single string with the addresses seperated by a newline
*/
private String getIPString(Vector ipList) {
return StringUtil.terminatedSeparatedString(ipList, "\n", "\n");
}
/**
* Save the ip addresses to the cluster.txt property file
* @param incIPsList vector of ip addresses to include
* @param excIPsList vector of ip addresses to exclude
* @param realpath path to the cluster.txt file
* @return whether the save was successful
*/
public void saveIPChanges(Vector incIPsList, Vector excIPsList)
throws IOException {
String incStr = StringUtil.separatedString(incIPsList, ";");
String excStr = StringUtil.separatedString(excIPsList, ";");
Properties acProps = new Properties();
acProps.put(PARAM_IP_INCLUDE, incStr);
acProps.put(PARAM_IP_EXCLUDE, excStr);
configMgr.writeCacheConfigFile(acProps,
ConfigManager.CONFIG_FILE_UI_IP_ACCESS,
"UI IP Access Control");
}
/**
* Read the prop file, change ip access list props and rewrite file
* @param filename name of the cluster property file
* @param incStr string of included ip addresses
* @param excStr string of excluded ip addresses
* @return whether the save was successful
*/
// public boolean replacePropertyInFile(File file, String incStr,
// String excStr) {
// PropertyTree t = new PropertyTree();
// String filename = file.getPath();
// try {
// if (file.exists()) {
// // get property tree
// InputStream istr = new FileInputStream(filename);
// t.load(istr);
// istr.close();
// }
// // replace ip properties
// t.put(LcapProperties.IP_INCLUDE_PROP_KEY, incStr);
// t.put(LcapProperties.IP_EXCLUDE_PROP_KEY, excStr);
// // write properties to file
// saveTree(t, filename, "LOCKSS Cluster Property file");
// } catch (Exception e) {
// LcapLog.error("UpdateIps: Error writing prop file", filename + ": " + e);
// return false;
// }
// return true;
// }
}
| src/org/lockss/servlet/IpAccessControl.java | /*
* $Id: IpAccessControl.java,v 1.4 2003-06-26 23:53:31 eaalto Exp $
*/
/*
Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.servlet;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;
import java.net.*;
import java.text.*;
import org.mortbay.html.*;
import org.mortbay.tools.*;
import org.lockss.util.*;
import org.lockss.daemon.*;
import org.lockss.daemon.status.*;
/** Display and update IP access control lists.
*/
public class IpAccessControl extends LockssServlet {
static final String AC_PREFIX = ServletManager.IP_ACCESS_PREFIX;
public static final String PARAM_IP_INCLUDE = AC_PREFIX + "include";
public static final String PARAM_IP_EXCLUDE = AC_PREFIX + "exclude";
private static final String footIP =
"List individual IP addresses (<code>172.16.31.14</code>), " +
"class A, B or C subnets (<code>10.*.*.*</code> ,  " +
"<code>172.16.31.*</code>) or CIDR notation " +
"subnets (<code>172.16.31.0/24</code>). " +
"<br>Enter each address or subnet mask on a separate line. " +
"<br>Deny addresses supersede Allow addresses." +
"<br>If the Allow list is empty, no remote access will be allowed.";
static Logger log = Logger.getLogger("IpAcc");
// public void init(ServletConfig config) throws ServletException {
// super.init(config);
// }
public void lockssHandleRequest() throws IOException {
String action = req.getParameter("action");
boolean isError = false;
if ("Update".equals(action)){
Vector incl = ipStrToVector(req.getParameter("inc_ips"));
Vector excl = ipStrToVector(req.getParameter("exc_ips"));
Vector inclErrs = findInvalidIps(incl);
Vector exclErrs = findInvalidIps(excl);
if (inclErrs.size() > 0 || exclErrs.size() > 0) {
displayPage(incl, excl, inclErrs, exclErrs);
} else {
try {
saveIPChanges(incl, excl);
} catch (Exception e) {
log.error("Error saving changes", e);
// set to null so will display unedited values.
// xxx should display error here
incl = null;
excl = null;
}
displayPage(incl, excl, null, null);
}
} else {
displayPage();
}
}
/**
* Display the page, given no new ip addresses and no errors
*/
private void displayPage()
throws IOException {
Vector incl = getListFromParam(PARAM_IP_INCLUDE);
Vector excl = getListFromParam(PARAM_IP_EXCLUDE);
// hack to remove possibly duplicated first element from platform subnet
if (incl.size() >= 2 && incl.get(0).equals(incl.get(1))) {
incl.remove(0);
}
displayPage(incl, excl, null, null);
}
private Vector getListFromParam(String param) {
Configuration config = Configuration.getCurrentConfig();
return StringUtil.breakAt(config.get(param), ';');
}
/**
* Display the UpdateIps page.
* @param incl vector of included ip addresses
* @param excl vector of excluded ip addresses
* @param inclErrs vector of malformed include ip addresses.
* @param exclErrs vector of malformed include ip addresses.
*/
private void displayPage(Vector incl, Vector excl,
Vector inclErrs, Vector exclErrs)
throws IOException {
Page page = newPage();
page.add(getIncludeExcludeElement(incl, excl,
inclErrs, exclErrs));
page.add(getFooter());
page.write(resp.getWriter());
}
/**
* Generate the block of the page that has the included/excluded
* ip address table.
* @param incl vector of included ip addresses
* @param excl vector of excluded ip addresses
* @param inclErrs vector of malformed include ip addresses.
* @param exclErrs vector of malformed include ip addresses.
* @return an html element representing the include/exclude ip address form
*/
private Element getIncludeExcludeElement(Vector incl, Vector excl,
Vector inclErrs,
Vector exclErrs) {
boolean isError = false;
String incString = null;
String excString = null;
Composite comp = new Composite();
Block centeredBlock = new Block(Block.Center);
Form frm = new Form(srvURL(myServletDescr(), null));
frm.method("POST");
Table table = new Table(1, "BORDER=1 CELLPADDING=0");
//table.center();
table.newRow("bgcolor=\"#CCCCCC\"");
table.newCell("align=center");
table.add("<font size=+1>Allow Access" + addFootnote(footIP) +
" </font>");
table.newCell("align=center");
table.add("<font size=+1>Deny Access" + addFootnote(footIP) +
" </font>");
if ((inclErrs != null && inclErrs.size() > 0) ||
(exclErrs != null && exclErrs.size() > 0)) {
String errorStr = null;
table.newRow();
table.newCell();
if (inclErrs != null && inclErrs.size() > 0) {
errorStr = getIPString(inclErrs);
table.add("Please correct the following error: <p><b><font color=\"#FF0000\">Error: Invalid IP Address "+errorStr+"</font></b>");
} else {
table.add(" ");
}
table.newCell();
if (exclErrs != null && exclErrs.size() > 0) {
errorStr = getIPString(exclErrs);
table.add("Please correct the following error: <p><b><font color=\"#FF0000\">Error: Invalid IP Address "+errorStr+"</font></b>");
} else {
table.add(" ");
}
}
incString = getIPString(incl);
excString = getIPString(excl);
TextArea incArea = new TextArea("inc_ips");
incArea.setSize(30, 20);
incArea.add(incString);
TextArea excArea = new TextArea("exc_ips");
excArea.setSize(30, 20);
excArea.add(excString);
table.newRow();
table.newCell("align=center");
table.add(incArea);
table.newCell("align=center");
table.add(excArea);
centeredBlock.add(table);
frm.add(centeredBlock);
Input submit = new Input(Input.Submit, "action", "Update");
frm.add("<center>"+submit+"</center>");
comp.add(frm);
return comp;
}
/**
* Checks the validity of a vector of IP addresses
* @param ipList vector containing strings representing the ip addresses
* @return vector of the malformed ip addresses
*/
public Vector findInvalidIps(Vector ipList) {
Vector errorIPs = new Vector();
if (ipList != null) {
for (Iterator iter = ipList.iterator(); iter.hasNext();) {
String ipStr = (String)iter.next();
IpFilter.Mask ip;
try {
ip = new IpFilter.Mask(ipStr, true);
} catch (IpFilter.MalformedException e) {
errorIPs.addElement(ipStr);
}
}
}
return errorIPs;
}
/**
* Convert a string of newline separated IP addresses to a vector of strings,
* removing duplicates
*
* @param ipStr string to convert into a vector
* @return vector of strings representing ip addresses
*/
private Vector ipStrToVector(String ipStr) {
return StringUtil.breakAt(ipStr, '\n', 0, true, true);
}
/**
* Convert a vector of strings representing ip addresses
* to a single string with the addresses seperated by a newline
*/
private String getIPString(Vector ipList) {
return StringUtil.terminatedSeparatedString(ipList, "\n", "\n");
}
/**
* Save the ip addresses to the cluster.txt property file
* @param incIPsList vector of ip addresses to include
* @param excIPsList vector of ip addresses to exclude
* @param realpath path to the cluster.txt file
* @return whether the save was successful
*/
public void saveIPChanges(Vector incIPsList, Vector excIPsList)
throws IOException {
String incStr = StringUtil.separatedString(incIPsList, ";");
String excStr = StringUtil.separatedString(excIPsList, ";");
Properties acProps = new Properties();
acProps.put(PARAM_IP_INCLUDE, incStr);
acProps.put(PARAM_IP_EXCLUDE, excStr);
Configuration.writeCacheConfigFile(acProps,
Configuration.CONFIG_FILE_UI_IP_ACCESS,
"UI IP Access Control");
}
/**
* Read the prop file, change ip access list props and rewrite file
* @param filename name of the cluster property file
* @param incStr string of included ip addresses
* @param excStr string of excluded ip addresses
* @return whether the save was successful
*/
// public boolean replacePropertyInFile(File file, String incStr,
// String excStr) {
// PropertyTree t = new PropertyTree();
// String filename = file.getPath();
// try {
// if (file.exists()) {
// // get property tree
// InputStream istr = new FileInputStream(filename);
// t.load(istr);
// istr.close();
// }
// // replace ip properties
// t.put(LcapProperties.IP_INCLUDE_PROP_KEY, incStr);
// t.put(LcapProperties.IP_EXCLUDE_PROP_KEY, excStr);
// // write properties to file
// saveTree(t, filename, "LOCKSS Cluster Property file");
// } catch (Exception e) {
// LcapLog.error("UpdateIps: Error writing prop file", filename + ": " + e);
// return false;
// }
// return true;
// }
}
| Use ConfigManager instance for writing config file.
git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@1697 4f837ed2-42f5-46e7-a7a5-fa17313484d4
| src/org/lockss/servlet/IpAccessControl.java | Use ConfigManager instance for writing config file. | <ide><path>rc/org/lockss/servlet/IpAccessControl.java
<ide> /*
<del> * $Id: IpAccessControl.java,v 1.4 2003-06-26 23:53:31 eaalto Exp $
<add> * $Id: IpAccessControl.java,v 1.5 2003-07-14 06:45:07 tlipkis Exp $
<ide> */
<ide>
<ide> /*
<ide>
<ide> static Logger log = Logger.getLogger("IpAcc");
<ide>
<del>// public void init(ServletConfig config) throws ServletException {
<del>// super.init(config);
<del>// }
<add> private ConfigManager configMgr;
<add>
<add> public void init(ServletConfig config) throws ServletException {
<add> super.init(config);
<add> configMgr = getLockssDaemon().getConfigManager();
<add> }
<ide>
<ide> public void lockssHandleRequest() throws IOException {
<ide> String action = req.getParameter("action");
<ide> Properties acProps = new Properties();
<ide> acProps.put(PARAM_IP_INCLUDE, incStr);
<ide> acProps.put(PARAM_IP_EXCLUDE, excStr);
<del> Configuration.writeCacheConfigFile(acProps,
<del> Configuration.CONFIG_FILE_UI_IP_ACCESS,
<del> "UI IP Access Control");
<add> configMgr.writeCacheConfigFile(acProps,
<add> ConfigManager.CONFIG_FILE_UI_IP_ACCESS,
<add> "UI IP Access Control");
<ide> }
<ide>
<ide> /** |
|
Java | epl-1.0 | b1b77a7bc79b061ee1116b29b3a8d4e123343d23 | 0 | Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1 | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.internal.ui.views;
import java.util.Timer;
import java.util.TimerTask;
import org.eclipse.birt.report.designer.internal.ui.views.actions.EditAction;
import org.eclipse.birt.report.designer.internal.ui.views.actions.RenameAction;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
/**
* The listeners for rename action
*/
public class RenameListener extends KeyAdapter implements
MouseListener,
SelectionListener,
IDoubleClickListener
{
private TreeViewer sourceViewer;
/**
* selection cached
*/
private TreeItem selectedItem = null;
private Timer timer;
private boolean readyToRename;
public RenameListener( TreeViewer sourceViewer )
{
this.sourceViewer = sourceViewer;
}
public void apply( )
{
sourceViewer.getTree( ).addSelectionListener( this );
sourceViewer.getTree( ).addKeyListener( this );
//sourceViewer.getTree( ).addMouseListener( this );
sourceViewer.addDoubleClickListener( this );
}
public void remove( )
{
sourceViewer.getTree( ).removeSelectionListener( this );
sourceViewer.getTree( ).removeKeyListener( this );
//sourceViewer.getTree( ).removeMouseListener( this );
sourceViewer.removeDoubleClickListener( this );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDoubleClick( MouseEvent e )
{
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDown( MouseEvent e )
{//prevent from conflicts
cancelTimer( );
if ( e.button != 1 )
{
cancelRenaming( );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
*/
public void mouseUp( MouseEvent e )
{
if ( !readyToRename )
{
return;
}
readyToRename = false;
//selection doesn't change
timer = new Timer( );
final RenameAction renameAction = new RenameAction( sourceViewer );
timer.schedule( new TimerTask( ) {
public void run( )
{//Do rename
sourceViewer.getTree( )
.getDisplay( )
.asyncExec( new Runnable( ) {
public void run( )
{
renameAction.run( );
}
} );
}
//wait for double time to check if it is a double click
}, Display.getCurrent( ).getDoubleClickTime( ) + 100 );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
*/
public void keyReleased( KeyEvent e )
{
cancelTimer( );
if ( e.keyCode == SWT.F2 && e.stateMask == 0 )
{
if ( selectedItem != null )
{
RenameAction action = new RenameAction( sourceViewer );
if ( action.isEnabled( ) && action.isHandled( ) )
action.run( );
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetSelected( SelectionEvent e )
{
cancelTimer( );
TreeItem lastSelect = selectedItem;
TreeItem[] selectedItems = ( (Tree) e.getSource( ) ).getSelection( );
if ( selectedItems.length != 1 )
{//No selection or multiple selection
readyToRename = false;
}
else
{
selectedItem = selectedItems[0];
readyToRename = ( selectedItem == lastSelect );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetDefaultSelected( SelectionEvent e )
{//Do nothing
}
/**
* Cancels the timer
*/
private void cancelTimer( )
{
if ( timer != null )
{
timer.cancel( );
timer = null;
}
}
/**
* Cancels the inline rename action
*/
private void cancelRenaming( )
{
RenameInlineTool.cancelActiveInstance( );
cancelTimer( );
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent)
*/
public void doubleClick( DoubleClickEvent event )
{
//perform edit
cancelTimer( );
if ( selectedItem != null && !selectedItem.isDisposed( ) )
{//ignore multiple selection or invalid
// selection
new EditAction( selectedItem.getData( ) ).run( );
}
}
} | UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/RenameListener.java | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.internal.ui.views;
import java.util.Timer;
import java.util.TimerTask;
import org.eclipse.birt.report.designer.internal.ui.views.actions.EditAction;
import org.eclipse.birt.report.designer.internal.ui.views.actions.RenameAction;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
/**
* The listeners for rename action
*/
public class RenameListener extends KeyAdapter implements
MouseListener,
SelectionListener, IDoubleClickListener
{
private TreeViewer sourceViewer;
/**
* selection cached
*/
private TreeItem selectedItem = null;
private Timer timer;
private boolean readyToRename;
public RenameListener( TreeViewer sourceViewer )
{
this.sourceViewer = sourceViewer;
}
public void apply( )
{
sourceViewer.getTree( ).addSelectionListener( this );
sourceViewer.getTree( ).addKeyListener( this );
//sourceViewer.getTree( ).addMouseListener( this );
sourceViewer.addDoubleClickListener(this);
}
public void remove( )
{
sourceViewer.getTree( ).removeSelectionListener( this );
sourceViewer.getTree( ).removeKeyListener( this );
//sourceViewer.getTree( ).removeMouseListener( this );
sourceViewer.removeDoubleClickListener(this);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDoubleClick( MouseEvent e )
{
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDown( MouseEvent e )
{//prevent from conflicts
cancelTimer( );
if ( e.button != 1 )
{
cancelRenaming( );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
*/
public void mouseUp( MouseEvent e )
{
if ( !readyToRename )
{
return;
}
readyToRename = false;
//selection doesn't change
timer = new Timer( );
final RenameAction renameAction = new RenameAction( sourceViewer );
timer.schedule( new TimerTask( ) {
public void run( )
{//Do rename
sourceViewer.getTree( )
.getDisplay( )
.asyncExec( new Runnable( ) {
public void run( )
{
renameAction.run( );
}
} );
}
//wait for double time to check if it is a double click
}, Display.getCurrent( ).getDoubleClickTime( ) + 100 );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
*/
public void keyReleased( KeyEvent e )
{
cancelTimer( );
if ( e.keyCode == SWT.F2 && e.stateMask == 0 )
{
if ( selectedItem != null )
{
new RenameAction( sourceViewer ).run( );
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetSelected( SelectionEvent e )
{
cancelTimer( );
TreeItem lastSelect = selectedItem;
TreeItem[] selectedItems = ( (Tree) e.getSource( ) ).getSelection( );
if ( selectedItems.length != 1 )
{//No selection or multiple selection
readyToRename = false;
}
else
{
selectedItem = selectedItems[0];
readyToRename = ( selectedItem == lastSelect );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetDefaultSelected( SelectionEvent e )
{//Do nothing
}
/**
* Cancels the timer
*/
private void cancelTimer( )
{
if ( timer != null )
{
timer.cancel( );
timer = null;
}
}
/**
* Cancels the inline rename action
*/
private void cancelRenaming( )
{
RenameInlineTool.cancelActiveInstance( );
cancelTimer( );
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent)
*/
public void doubleClick(DoubleClickEvent event)
{
//perform edit
cancelTimer( );
if ( selectedItem != null && !selectedItem.isDisposed( ) )
{//ignore multiple selection or invalid
// selection
new EditAction( selectedItem.getData( ) ).run( );
}
}
} | - Summary: fix Bugzilla Bug 172817
NPE is thrown when press F2 in outline
- Bugzilla Bug (s) Resolved:172817
- Description:
Resolved NPE is thrown when press F2 on item which is not a ReportItem.
- Tests Description :
Manual test
- Files Edited:
- Files Added:
- Files Deleted:
- Notes to Build Team:
- Notes to Developers:
- Notes to QA:
- Notes to Documentation:
| UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/RenameListener.java | - Summary: fix Bugzilla Bug 172817 NPE is thrown when press F2 in outline | <ide><path>I/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/RenameListener.java
<ide>
<ide> public class RenameListener extends KeyAdapter implements
<ide> MouseListener,
<del> SelectionListener, IDoubleClickListener
<add> SelectionListener,
<add> IDoubleClickListener
<ide> {
<ide>
<ide> private TreeViewer sourceViewer;
<ide> sourceViewer.getTree( ).addSelectionListener( this );
<ide> sourceViewer.getTree( ).addKeyListener( this );
<ide> //sourceViewer.getTree( ).addMouseListener( this );
<del> sourceViewer.addDoubleClickListener(this);
<add> sourceViewer.addDoubleClickListener( this );
<ide> }
<ide>
<ide> public void remove( )
<ide> sourceViewer.getTree( ).removeSelectionListener( this );
<ide> sourceViewer.getTree( ).removeKeyListener( this );
<ide> //sourceViewer.getTree( ).removeMouseListener( this );
<del> sourceViewer.removeDoubleClickListener(this);
<add> sourceViewer.removeDoubleClickListener( this );
<ide> }
<ide>
<ide> /*
<ide> } );
<ide> }
<ide> //wait for double time to check if it is a double click
<del> }, Display.getCurrent( ).getDoubleClickTime( ) + 100 );
<add> }, Display.getCurrent( ).getDoubleClickTime( ) + 100 );
<ide>
<ide> }
<ide>
<ide> {
<ide> if ( selectedItem != null )
<ide> {
<del> new RenameAction( sourceViewer ).run( );
<add> RenameAction action = new RenameAction( sourceViewer );
<add> if ( action.isEnabled( ) && action.isHandled( ) )
<add> action.run( );
<ide> }
<ide> }
<ide> }
<ide> cancelTimer( );
<ide> }
<ide>
<del> /* (non-Javadoc)
<del> * @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent)
<del> */
<del> public void doubleClick(DoubleClickEvent event)
<del> {
<del> //perform edit
<del> cancelTimer( );
<del> if ( selectedItem != null && !selectedItem.isDisposed( ) )
<del> {//ignore multiple selection or invalid
<del> // selection
<del> new EditAction( selectedItem.getData( ) ).run( );
<del> }
<del> }
<add> /* (non-Javadoc)
<add> * @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent)
<add> */
<add> public void doubleClick( DoubleClickEvent event )
<add> {
<add> //perform edit
<add> cancelTimer( );
<add> if ( selectedItem != null && !selectedItem.isDisposed( ) )
<add> {//ignore multiple selection or invalid
<add> // selection
<add> new EditAction( selectedItem.getData( ) ).run( );
<add> }
<add> }
<ide> } |
|
Java | mpl-2.0 | 2739adae9c167d02a4e8839a0a6fe3ae9fe63d0b | 0 | msteinhoff/hello-world | 846b5a6b-cb8e-11e5-beec-00264a111016 | src/main/java/HelloWorld.java | 845fa382-cb8e-11e5-af6f-00264a111016 | updated some files | src/main/java/HelloWorld.java | updated some files | <ide><path>rc/main/java/HelloWorld.java
<del>845fa382-cb8e-11e5-af6f-00264a111016
<add>846b5a6b-cb8e-11e5-beec-00264a111016 |
|
JavaScript | mit | 1a3820f810c75c089b744c0b0d0253a6a78376a2 | 0 | jaden/HotPocket,jaden/HotPocket | 'use strict';
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
var minify_css = require('gulp-minify-css');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var replace = require('gulp-replace');
var rename = require('gulp-rename');
var del = require('del');
gulp.task('clean', function(callback) {
del([
'public/css/bundle-*.min.css',
'public/js/bundle-*.min.js',
], callback);
});
gulp.task('browserify', ['clean'], function() {
// set up the browserify instance on a task basis
var b = browserify({
entries: './resources/js/app.js',
debug: false
});
return b.bundle()
.pipe(source('bundle.min.js')) // this is a fake filename that doesn't exist (yet)
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(uglify())
.on('error', gutil.log)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./public/js/'));
});
gulp.task('styles', ['clean'], function() {
return gulp.src([
'public/css/bootstrap/bootstrap.min.css',
'node_modules/nprogress/nprogress.css'],
{ base: '.'})
.pipe(minify_css())
.pipe(concat('bundle.min.css'))
.pipe(gulp.dest('public/css'));
});
// Only runs after js and styles have been generated
gulp.task('cache-bust', ['browserify', 'styles'], function() {
var timestamp = new Date().getTime();
gulp.src("./public/css/bundle.min.css")
.pipe(rename("./public/css/bundle-" + timestamp + ".min.css"))
.pipe(gulp.dest("."));
gulp.src("./public/js/bundle.min.js")
.pipe(rename("./public/js/bundle-" + timestamp + ".min.js"))
.pipe(gulp.dest("."));
return gulp.src('resources/views/index.php',
{ base: '.' }) // To overwrite the src file http://stackoverflow.com/questions/22418799/can-gulp-overwrite-all-src-files
.pipe(replace(/href="\/css\/bundle-[0-9]+\.min\.css"/,
'href="/css/bundle-' + timestamp + '.min.css"'))
.pipe(replace(/src="\/js\/bundle-[0-9]+\.min\.js"/,
'src="/js/bundle-' + timestamp + '.min.js"'))
.pipe(gulp.dest('.')); // Replace the source file
});
gulp.task('default', ['cache-bust']);
gulp.task('lint', function() {
return gulp.src('./resources/js/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('watch', ['browserify'], function() {
gulp.watch('./resources/js/**/*.js', ['browserify']);
}); | gulpfile.js | 'use strict';
// TODO Run jshint on build
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
gulp.task('browserify', function() {
// set up the browserify instance on a task basis
var b = browserify({
entries: './resources/js/app.js',
debug: false
});
return b.bundle()
.pipe(source('bundle.min.js')) // this is a "pretend" filename that doesn't exist yet
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
// Add transformation tasks to the pipeline here.
.pipe(uglify())
.on('error', gutil.log)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./public/js/'));
});
gulp.task('default', ['browserify']);
gulp.task('watch', function() {
gulp.watch('./resources/js/**/*.js', ['browserify']);
}); | Add cache busting for CSS and JS files
Clean up old files, generate new files with the timestamp suffix and
update the index.php file with the new timestamp path.
| gulpfile.js | Add cache busting for CSS and JS files | <ide><path>ulpfile.js
<ide> 'use strict';
<ide>
<del>// TODO Run jshint on build
<add>var browserify = require('browserify');
<add>var gulp = require('gulp');
<add>var source = require('vinyl-source-stream');
<add>var buffer = require('vinyl-buffer');
<add>var uglify = require('gulp-uglify');
<add>var sourcemaps = require('gulp-sourcemaps');
<add>var gutil = require('gulp-util');
<add>var minify_css = require('gulp-minify-css');
<add>var concat = require('gulp-concat');
<add>var jshint = require('gulp-jshint');
<add>var replace = require('gulp-replace');
<add>var rename = require('gulp-rename');
<add>var del = require('del');
<ide>
<del>var browserify = require('browserify');
<del>var gulp = require('gulp');
<del>var source = require('vinyl-source-stream');
<del>var buffer = require('vinyl-buffer');
<del>var uglify = require('gulp-uglify');
<del>var sourcemaps = require('gulp-sourcemaps');
<del>var gutil = require('gulp-util');
<add>gulp.task('clean', function(callback) {
<add> del([
<add> 'public/css/bundle-*.min.css',
<add> 'public/js/bundle-*.min.js',
<add> ], callback);
<add>});
<ide>
<del>gulp.task('browserify', function() {
<add>gulp.task('browserify', ['clean'], function() {
<ide> // set up the browserify instance on a task basis
<ide> var b = browserify({
<ide> entries: './resources/js/app.js',
<ide> });
<ide>
<ide> return b.bundle()
<del> .pipe(source('bundle.min.js')) // this is a "pretend" filename that doesn't exist yet
<add> .pipe(source('bundle.min.js')) // this is a fake filename that doesn't exist (yet)
<ide> .pipe(buffer())
<ide> .pipe(sourcemaps.init({loadMaps: true}))
<del> // Add transformation tasks to the pipeline here.
<ide> .pipe(uglify())
<ide> .on('error', gutil.log)
<ide> .pipe(sourcemaps.write('./'))
<ide> .pipe(gulp.dest('./public/js/'));
<ide> });
<ide>
<del>gulp.task('default', ['browserify']);
<add>gulp.task('styles', ['clean'], function() {
<add> return gulp.src([
<add> 'public/css/bootstrap/bootstrap.min.css',
<add> 'node_modules/nprogress/nprogress.css'],
<add> { base: '.'})
<ide>
<del>gulp.task('watch', function() {
<add> .pipe(minify_css())
<add> .pipe(concat('bundle.min.css'))
<add> .pipe(gulp.dest('public/css'));
<add>});
<add>
<add>// Only runs after js and styles have been generated
<add>gulp.task('cache-bust', ['browserify', 'styles'], function() {
<add> var timestamp = new Date().getTime();
<add>
<add> gulp.src("./public/css/bundle.min.css")
<add> .pipe(rename("./public/css/bundle-" + timestamp + ".min.css"))
<add> .pipe(gulp.dest("."));
<add>
<add> gulp.src("./public/js/bundle.min.js")
<add> .pipe(rename("./public/js/bundle-" + timestamp + ".min.js"))
<add> .pipe(gulp.dest("."));
<add>
<add> return gulp.src('resources/views/index.php',
<add> { base: '.' }) // To overwrite the src file http://stackoverflow.com/questions/22418799/can-gulp-overwrite-all-src-files
<add>
<add> .pipe(replace(/href="\/css\/bundle-[0-9]+\.min\.css"/,
<add> 'href="/css/bundle-' + timestamp + '.min.css"'))
<add>
<add> .pipe(replace(/src="\/js\/bundle-[0-9]+\.min\.js"/,
<add> 'src="/js/bundle-' + timestamp + '.min.js"'))
<add>
<add> .pipe(gulp.dest('.')); // Replace the source file
<add>});
<add>
<add>gulp.task('default', ['cache-bust']);
<add>
<add>gulp.task('lint', function() {
<add> return gulp.src('./resources/js/*.js')
<add> .pipe(jshint())
<add> .pipe(jshint.reporter('default'));
<add>});
<add>
<add>gulp.task('watch', ['browserify'], function() {
<ide> gulp.watch('./resources/js/**/*.js', ['browserify']);
<ide> }); |
|
Java | mit | 410e430a1e7b8d32c62d21ecb55f4530a761fae7 | 0 | gabelew/SimCity201 | package city.animationPanels;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Timer;
import city.gui.Gui;
import city.gui.SimCityGui;
public class ApartmentAnimationPanel extends InsideAnimationPanel implements ActionListener{
private static final long serialVersionUID = 1L;
private SimCityGui simCityGui;
private static BufferedImage kitchen = null;
private static BufferedImage grill = null;
private static BufferedImage fridge = null;
private static BufferedImage table = null;
private static BufferedImage bed = null;
static final int WALL_LENGTH = 875;
static final int WALL_WIDTH = 10;
//variables for kitchen
static final int xCOOK_POSITION = 20;
static final int yCOOK_POSITION = 30;
static final int yKITCHEN_COUNTER_OFFSET = 30;
static final int yGRILL_RIGHT_OFFSET = 30;
static final int xGRILL_RIGHT_OFFSET = 52;
static final int yFIDGE_OFFSET = 15;
static final int xFIDGE_OFFSET = 100;
public ApartmentAnimationPanel(SimCityGui simCityGui){
this.simCityGui = simCityGui;
setSize(WINDOWX, WINDOWY);
setVisible(true);
simCityGui.animationPanel.timer.addActionListener(this);
try {
StringBuilder path = new StringBuilder("imgs/");
kitchen = ImageIO.read(new File(path.toString() + "kitchen.png"));
fridge = ImageIO.read(new File(path.toString() + "fidge.png"));
table = ImageIO.read(new File(path.toString() + "table.png"));
bed = ImageIO.read(new File(path.toString() + "bed.png"));
grill = ImageIO.read(new File(path.toString() + "grill2.png"));
} catch (IOException e){
}
}
@Override
public void actionPerformed(ActionEvent arg0) {
for(Gui gui : getGuis()) {
if (gui.isPresent()) {
gui.updatePosition();
}
}
if(insideBuildingPanel != null && insideBuildingPanel.isVisible)
repaint(); //Will have paintComponent called
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
//Clear the screen by painting a rectangle the size of the frame
g2.setColor(getBackground());
g2.fillRect(0, 0, WINDOWX, WINDOWY);
//make a hallway
g2.setColor(Color.BLACK);
g2.fillRect(0, 150, WALL_LENGTH, WALL_WIDTH);
g2.fillRect(0, 300, WALL_LENGTH, WALL_WIDTH);
g2.setColor(Color.GRAY);
g2.fillRect(0, 160, WALL_LENGTH, 140);
g2.setColor(Color.RED);
g2.fillRect(0, 200, WALL_LENGTH, 60);
//create rooms for each person. Total of 8 rooms in an apartment
for(int i = 0; i < 5; i++){
g2.setColor(Color.BLACK);
g2.fillRect(217*i, 0, WALL_WIDTH, 150);
g2.fillRect(217*i, 300, WALL_WIDTH, 150);
}
//creates a kitchen, fridge, table, and bed for each tenant
for(int i = 0; i < 5; i++){
//top 4
g2.drawImage(kitchen, xCOOK_POSITION+(i*217), yCOOK_POSITION-yKITCHEN_COUNTER_OFFSET, null);
g2.drawImage(grill, xCOOK_POSITION+xGRILL_RIGHT_OFFSET+(i*217), yCOOK_POSITION-yGRILL_RIGHT_OFFSET, null);
g2.drawImage(fridge, xCOOK_POSITION+xFIDGE_OFFSET+(i*217), yCOOK_POSITION+yFIDGE_OFFSET, null);
g2.drawImage(table, 57+(i*217), 70, null);
g2.drawImage(bed, 150+(i*217), 100, null);
//bottom 4
g2.drawImage(kitchen, xCOOK_POSITION+(i*217),310+ yCOOK_POSITION-yKITCHEN_COUNTER_OFFSET, null);
g2.drawImage(grill, xCOOK_POSITION+xGRILL_RIGHT_OFFSET+(i*217), 310+yCOOK_POSITION-yGRILL_RIGHT_OFFSET, null);
g2.drawImage(fridge, xCOOK_POSITION+xFIDGE_OFFSET+(i*217),310+ yCOOK_POSITION+yFIDGE_OFFSET, null);
//g2.drawImage(grill, (i*217) ,320,null);
//g2.drawImage(kitchen, 15+(i*217), 320, null);
//g2.drawImage(fridge, 100+(i*217), 310, null);
g2.drawImage(table, 57+(i*217), 370, null);
g2.drawImage(bed, 150+(i*217), 420, null);
}
}
}
| src/city/animationPanels/ApartmentAnimationPanel.java | package city.animationPanels;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Timer;
import city.gui.Gui;
import city.gui.SimCityGui;
public class ApartmentAnimationPanel extends InsideAnimationPanel implements ActionListener{
private static final long serialVersionUID = 1L;
private SimCityGui simCityGui;
private static BufferedImage kitchen = null;
private static BufferedImage fridge = null;
private static BufferedImage table = null;
private static BufferedImage bed = null;
static final int WALL_LENGTH = 875;
static final int WALL_WIDTH = 10;
public ApartmentAnimationPanel(SimCityGui simCityGui){
this.simCityGui = simCityGui;
setSize(WINDOWX, WINDOWY);
setVisible(true);
simCityGui.animationPanel.timer.addActionListener(this);
try {
StringBuilder path = new StringBuilder("imgs/");
kitchen = ImageIO.read(new File(path.toString() + "kitchen.png"));
fridge = ImageIO.read(new File(path.toString() + "fidge.png"));
table = ImageIO.read(new File(path.toString() + "table.png"));
bed = ImageIO.read(new File(path.toString() + "bed.png"));
} catch (IOException e){
}
}
@Override
public void actionPerformed(ActionEvent arg0) {
for(Gui gui : getGuis()) {
if (gui.isPresent()) {
gui.updatePosition();
}
}
if(insideBuildingPanel != null && insideBuildingPanel.isVisible)
repaint(); //Will have paintComponent called
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
//Clear the screen by painting a rectangle the size of the frame
g2.setColor(getBackground());
g2.fillRect(0, 0, WINDOWX, WINDOWY);
//make a hallway
g2.setColor(Color.BLACK);
g2.fillRect(0, 150, WALL_LENGTH, WALL_WIDTH);
g2.fillRect(0, 300, WALL_LENGTH, WALL_WIDTH);
g2.setColor(Color.GRAY);
g2.fillRect(0, 160, WALL_LENGTH, 140);
g2.setColor(Color.RED);
g2.fillRect(0, 200, WALL_LENGTH, 60);
//create rooms for each person. Total of 8 rooms in an apartment
for(int i = 0; i < 5; i++){
g2.setColor(Color.BLACK);
g2.fillRect(217*i, 0, WALL_WIDTH, 150);
g2.fillRect(217*i, 300, WALL_WIDTH, 150);
}
//creates a kitchen, fridge, table, and bed for each tenant
for(int i = 0; i < 5; i++){
//top 4
g2.drawImage(kitchen, 15+(i*217), 20, null);
g2.drawImage(fridge, 100+(i*217), 10, null);
g2.drawImage(table, 57+(i*217), 50, null);
g2.drawImage(bed, 150+(i*217), 70, null);
//bottom 4
g2.drawImage(kitchen, 15+(i*217), 320, null);
g2.drawImage(fridge, 100+(i*217), 310, null);
g2.drawImage(table, 57+(i*217), 350, null);
g2.drawImage(bed, 150+(i*217), 370, null);
}
}
}
| Updated Apartment GUI, added grill to animation
| src/city/animationPanels/ApartmentAnimationPanel.java | Updated Apartment GUI, added grill to animation | <ide><path>rc/city/animationPanels/ApartmentAnimationPanel.java
<ide> private SimCityGui simCityGui;
<ide>
<ide> private static BufferedImage kitchen = null;
<add> private static BufferedImage grill = null;
<ide> private static BufferedImage fridge = null;
<ide> private static BufferedImage table = null;
<ide> private static BufferedImage bed = null;
<ide> static final int WALL_LENGTH = 875;
<ide> static final int WALL_WIDTH = 10;
<del>
<add> //variables for kitchen
<add> static final int xCOOK_POSITION = 20;
<add> static final int yCOOK_POSITION = 30;
<add> static final int yKITCHEN_COUNTER_OFFSET = 30;
<add> static final int yGRILL_RIGHT_OFFSET = 30;
<add> static final int xGRILL_RIGHT_OFFSET = 52;
<add> static final int yFIDGE_OFFSET = 15;
<add> static final int xFIDGE_OFFSET = 100;
<add>
<ide> public ApartmentAnimationPanel(SimCityGui simCityGui){
<ide> this.simCityGui = simCityGui;
<ide>
<ide> fridge = ImageIO.read(new File(path.toString() + "fidge.png"));
<ide> table = ImageIO.read(new File(path.toString() + "table.png"));
<ide> bed = ImageIO.read(new File(path.toString() + "bed.png"));
<add> grill = ImageIO.read(new File(path.toString() + "grill2.png"));
<ide>
<ide> } catch (IOException e){
<ide>
<ide> //creates a kitchen, fridge, table, and bed for each tenant
<ide> for(int i = 0; i < 5; i++){
<ide> //top 4
<del> g2.drawImage(kitchen, 15+(i*217), 20, null);
<del> g2.drawImage(fridge, 100+(i*217), 10, null);
<del> g2.drawImage(table, 57+(i*217), 50, null);
<del> g2.drawImage(bed, 150+(i*217), 70, null);
<add> g2.drawImage(kitchen, xCOOK_POSITION+(i*217), yCOOK_POSITION-yKITCHEN_COUNTER_OFFSET, null);
<add> g2.drawImage(grill, xCOOK_POSITION+xGRILL_RIGHT_OFFSET+(i*217), yCOOK_POSITION-yGRILL_RIGHT_OFFSET, null);
<add> g2.drawImage(fridge, xCOOK_POSITION+xFIDGE_OFFSET+(i*217), yCOOK_POSITION+yFIDGE_OFFSET, null);
<add> g2.drawImage(table, 57+(i*217), 70, null);
<add> g2.drawImage(bed, 150+(i*217), 100, null);
<ide>
<ide> //bottom 4
<del> g2.drawImage(kitchen, 15+(i*217), 320, null);
<del> g2.drawImage(fridge, 100+(i*217), 310, null);
<del> g2.drawImage(table, 57+(i*217), 350, null);
<del> g2.drawImage(bed, 150+(i*217), 370, null);
<add> g2.drawImage(kitchen, xCOOK_POSITION+(i*217),310+ yCOOK_POSITION-yKITCHEN_COUNTER_OFFSET, null);
<add> g2.drawImage(grill, xCOOK_POSITION+xGRILL_RIGHT_OFFSET+(i*217), 310+yCOOK_POSITION-yGRILL_RIGHT_OFFSET, null);
<add> g2.drawImage(fridge, xCOOK_POSITION+xFIDGE_OFFSET+(i*217),310+ yCOOK_POSITION+yFIDGE_OFFSET, null);
<add> //g2.drawImage(grill, (i*217) ,320,null);
<add> //g2.drawImage(kitchen, 15+(i*217), 320, null);
<add> //g2.drawImage(fridge, 100+(i*217), 310, null);
<add> g2.drawImage(table, 57+(i*217), 370, null);
<add> g2.drawImage(bed, 150+(i*217), 420, null);
<ide>
<ide> }
<ide> |
|
Java | lgpl-2.1 | 3eb361b456b67f0b5ccdb7bdaccc964fda68a5ae | 0 | levants/lightmare | package org.lightmare.jpa;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.log4j.Logger;
import org.lightmare.ejb.meta.ConnectionSemaphore;
import org.lightmare.jndi.NamingUtils;
/**
* Creates and caches {@link EntityManagerFactory} for each ejb bean
* {@link Class}'s appropriate field (annotated by @PersistenceContext)
*
* @author Levan
*
*/
public class JPAManager {
// Keeps unique EntityManagerFactories builded by unit names
private static final ConcurrentMap<String, ConnectionSemaphore> CONNECTIONS = new ConcurrentHashMap<String, ConnectionSemaphore>();
private List<String> classes;
private String path;
private URL url;
private Map<?, ?> properties;
private boolean swapDataSource;
boolean scanArchives;
private static final Logger LOG = Logger.getLogger(JPAManager.class);
private JPAManager() {
}
public static boolean checkForEmf(String unitName) {
boolean check = unitName != null && !unitName.isEmpty();
if (check) {
check = CONNECTIONS.containsKey(unitName);
}
return check;
}
public static ConnectionSemaphore getSemaphore(String unitName) {
return CONNECTIONS.get(unitName);
}
private static ConnectionSemaphore createSemaphore(String unitName) {
ConnectionSemaphore semaphore = CONNECTIONS.get(unitName);
ConnectionSemaphore current = null;
if (semaphore == null) {
semaphore = new ConnectionSemaphore();
semaphore.setUnitName(unitName);
semaphore.setInProgress(true);
semaphore.setCached(true);
current = CONNECTIONS.putIfAbsent(unitName, semaphore);
}
if (current == null) {
current = semaphore;
}
current.incrementUser();
return current;
}
public static ConnectionSemaphore setSemaphore(String unitName,
String jndiName) {
ConnectionSemaphore semaphore = null;
if (unitName != null && !unitName.isEmpty()) {
semaphore = createSemaphore(unitName);
if (jndiName != null && !jndiName.isEmpty()) {
ConnectionSemaphore existent = CONNECTIONS.putIfAbsent(
jndiName, semaphore);
if (existent == null) {
semaphore.setJndiName(jndiName);
}
}
}
return semaphore;
}
private static void awaitConnection(ConnectionSemaphore semaphore) {
synchronized (semaphore) {
boolean inProgress = semaphore.isInProgress()
&& !semaphore.isBound();
while (inProgress) {
try {
semaphore.wait();
inProgress = semaphore.isInProgress()
&& !semaphore.isBound();
} catch (InterruptedException ex) {
inProgress = false;
LOG.error(ex.getMessage(), ex);
}
}
}
}
public static boolean isInProgress(String jndiName) {
ConnectionSemaphore semaphore = CONNECTIONS.get(jndiName);
boolean inProgress = semaphore != null;
if (inProgress) {
inProgress = semaphore.isInProgress() && !semaphore.isBound();
if (inProgress) {
awaitConnection(semaphore);
}
}
return inProgress;
}
/**
* Creates {@link EntityManagerFactory} by hibernate or by extended builder
* {@link Ejb3ConfigurationImpl} if entity classes or persistence.xml file
* path are provided
*
* @see Ejb3ConfigurationImpl#configure(String, Map) and
* Ejb3ConfigurationImpl#createEntityManagerFactory()
*
* @param unitName
* @return {@link EntityManagerFactory}
*/
@SuppressWarnings("deprecation")
private EntityManagerFactory buildEntityManagerFactory(String unitName)
throws IOException {
EntityManagerFactory emf;
Ejb3ConfigurationImpl cfg;
boolean checkForPath = checkForPath();
boolean checkForURL = checkForURL();
boolean checkForClasses = checkForClasses();
if (checkForPath || checkForURL) {
Enumeration<URL> xmls;
ConfigLoader configLoader = new ConfigLoader();
if (checkForPath) {
xmls = configLoader.readFile(path);
} else {
xmls = configLoader.readURL(url);
}
if (checkForClasses) {
cfg = new Ejb3ConfigurationImpl(classes, xmls);
} else {
cfg = new Ejb3ConfigurationImpl(xmls);
}
cfg.setShortPath(configLoader.getShortPath());
} else {
cfg = new Ejb3ConfigurationImpl(classes);
}
cfg.setSwapDataSource(swapDataSource);
cfg.setScanArchives(scanArchives);
Ejb3ConfigurationImpl configured = cfg.configure(unitName, properties);
emf = configured != null ? configured.buildEntityManagerFactory()
: null;
return emf;
}
/**
* Checks if entity classes are provided
*
* @return boolean
*/
private boolean checkForClasses() {
return classes != null && !classes.isEmpty();
}
/**
* Checks if entity persistence.xml path is provided
*
* @return boolean
*/
private boolean checkForPath() {
return path != null && !path.isEmpty();
}
/**
* Checks if entity persistence.xml {@link URL} is provided
*
* @return boolean
*/
private boolean checkForURL() {
return url != null && !url.toString().isEmpty();
}
/**
* Checks if entity classes or persistence.xml path are provided
*
* @param classes
* @return boolean
*/
private boolean checkForBuild() {
return checkForClasses() || checkForPath() || checkForURL();
}
/**
* Checks if entity classes or persistence.xml file path are provided to
* create {@link EntityManagerFactory}
*
* @see #buildEntityManagerFactory(String, String, Map, List)
*
* @param unitName
* @param properties
* @param path
* @param classes
* @return {@link EntityManagerFactory}
* @throws IOException
*/
private EntityManagerFactory createEntityManagerFactory(String unitName)
throws IOException {
EntityManagerFactory emf;
if (checkForBuild()) {
emf = buildEntityManagerFactory(unitName);
} else if (properties == null) {
emf = Persistence.createEntityManagerFactory(unitName);
} else {
emf = Persistence.createEntityManagerFactory(unitName, properties);
}
return emf;
}
/**
* Binds {@link EntityManagerFactory} to {@link javax.naming.InitialContext}
*
* @param jndiName
* @param unitName
* @param emf
* @throws IOException
*/
private void bindJndiName(ConnectionSemaphore semaphore) throws IOException {
boolean bound = semaphore.isBound();
if (!bound) {
String jndiName = semaphore.getJndiName();
if (jndiName != null && !jndiName.isEmpty()) {
NamingUtils namingUtils = new NamingUtils();
try {
Context context = namingUtils.getContext();
if (context.lookup(jndiName) == null) {
namingUtils.getContext().bind(jndiName,
semaphore.getEmf());
}
semaphore.setBound(true);
} catch (NamingException ex) {
throw new IOException(String.format(
"could not bind connection %s",
semaphore.getUnitName()), ex);
}
} else {
semaphore.setBound(true);
}
}
}
public void setConnection(String unitName) throws IOException {
ConnectionSemaphore semaphore = CONNECTIONS.get(unitName);
if (semaphore.isInProgress()) {
EntityManagerFactory emf = createEntityManagerFactory(unitName);
semaphore.setEmf(emf);
semaphore.setInProgress(false);
bindJndiName(semaphore);
} else if (semaphore.getEmf() == null) {
throw new IOException(String.format(
"Connection %s was not in progress", unitName));
} else {
bindJndiName(semaphore);
}
}
/**
* Gets {@link ConnectionSemaphore} from cache, awaits if connection
* instantiation is in progress
*
* @param unitName
* @return {@link ConnectionSemaphore}
* @throws IOException
*/
public static ConnectionSemaphore getConnection(String unitName)
throws IOException {
ConnectionSemaphore semaphore = CONNECTIONS.get(unitName);
if (semaphore != null) {
awaitConnection(semaphore);
}
return semaphore;
}
/**
* Gets {@link EntityManagerFactory} from {@link ConnectionSemaphore},
* awaits if connection
*
* @param unitName
* @return {@link EntityManagerFactory}
* @throws IOException
*/
public static EntityManagerFactory getEntityManagerFactory(String unitName)
throws IOException {
EntityManagerFactory emf = null;
ConnectionSemaphore semaphore = CONNECTIONS.get(unitName);
if (semaphore != null) {
awaitConnection(semaphore);
emf = semaphore.getEmf();
}
return emf;
}
/**
* Unbinds connection from {@link javax.naming.Context}
*
* @param semaphore
*/
private static void unbindConnection(ConnectionSemaphore semaphore) {
String jndiName = semaphore.getJndiName();
if (jndiName != null && semaphore.isBound()) {
NamingUtils namingUtils = new NamingUtils();
try {
Context context = namingUtils.getContext();
if (context.lookup(jndiName) != null) {
context.unbind(jndiName);
}
} catch (NamingException ex) {
LOG.error(ex.getMessage(), ex);
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
}
}
}
/**
* Closes connection ({@link EntityManagerFactory}) in passed
* {@link ConnectionSemaphore}
*
* @param semaphore
*/
private static void closeConnection(ConnectionSemaphore semaphore) {
int users = semaphore.decrementUser();
if (users <= 0) {
EntityManagerFactory emf = semaphore.getEmf();
closeEntityManagerFactory(emf);
unbindConnection(semaphore);
CONNECTIONS.remove(semaphore.getUnitName());
}
}
/**
* Removes {@link ConnectionSemaphore} from cache and unbinds name from
* {@link javax.naming.Context}
*
* @param unitName
*/
public static void removeConnection(String unitName) {
ConnectionSemaphore semaphore = CONNECTIONS.get(unitName);
if (semaphore != null) {
awaitConnection(semaphore);
closeConnection(semaphore);
NamingUtils namingUtils = new NamingUtils();
try {
String jndiName = NamingUtils.createJndiName(unitName);
namingUtils.unbind(jndiName);
} catch (IOException ex) {
LOG.error(String.format(
"Could not unbind jndi name %s cause %s", unitName,
ex.getMessage()), ex);
}
}
}
/**
* Closes passed {@link EntityManagerFactory}
*
* @param emf
*/
private static void closeEntityManagerFactory(EntityManagerFactory emf) {
if (emf != null && emf.isOpen()) {
emf.close();
}
}
/**
* Closes all existing {@link EntityManagerFactory} instances kept in cache
*/
public static void closeEntityManagerFactories() {
Collection<ConnectionSemaphore> semaphores = CONNECTIONS.values();
EntityManagerFactory emf;
for (ConnectionSemaphore semaphore : semaphores) {
emf = semaphore.getEmf();
closeEntityManagerFactory(emf);
}
CONNECTIONS.clear();
}
/**
* Builder class to create {@link JPAManager} class object
*
* @author Levan
*
*/
public static class Builder {
private JPAManager manager;
public Builder() {
manager = new JPAManager();
manager.scanArchives = true;
}
public Builder setClasses(List<String> classes) {
manager.classes = classes;
return this;
}
public Builder setURL(URL url) {
manager.url = url;
return this;
}
public Builder setPath(String path) {
manager.path = path;
return this;
}
public Builder setProperties(Map<?, ?> properties) {
manager.properties = properties;
return this;
}
public Builder setSwapDataSource(boolean swapDataSource) {
manager.swapDataSource = swapDataSource;
return this;
}
public Builder setScanArchives(boolean scanArchives) {
manager.scanArchives = scanArchives;
return this;
}
public JPAManager build() {
return manager;
}
}
}
| src/main/java/org/lightmare/jpa/JPAManager.java | package org.lightmare.jpa;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceException;
import org.apache.log4j.Logger;
import org.lightmare.ejb.meta.ConnectionSemaphore;
import org.lightmare.jndi.NamingUtils;
/**
* Creates and caches {@link EntityManagerFactory} for each ejb bean
* {@link Class}'s appropriate field (annotated by @PersistenceContext)
*
* @author Levan
*
*/
public class JPAManager {
// Keeps unique EntityManagerFactories builded by unit names
private static final ConcurrentMap<String, ConnectionSemaphore> CONNECTIONS = new ConcurrentHashMap<String, ConnectionSemaphore>();
private List<String> classes;
private String path;
private URL url;
private Map<?, ?> properties;
private boolean swapDataSource;
boolean scanArchives;
private static final Logger LOG = Logger.getLogger(JPAManager.class);
private JPAManager() {
}
public static boolean checkForEmf(String unitName) {
boolean check = unitName != null && !unitName.isEmpty();
if (check) {
check = CONNECTIONS.containsKey(unitName);
}
return check;
}
public static ConnectionSemaphore getSemaphore(String unitName) {
return CONNECTIONS.get(unitName);
}
private static ConnectionSemaphore createSemaphore(String unitName) {
ConnectionSemaphore semaphore = CONNECTIONS.get(unitName);
ConnectionSemaphore current = null;
if (semaphore == null) {
semaphore = new ConnectionSemaphore();
semaphore.setUnitName(unitName);
semaphore.setInProgress(true);
semaphore.setCached(true);
current = CONNECTIONS.putIfAbsent(unitName, semaphore);
}
if (current == null) {
current = semaphore;
}
current.incrementUser();
return current;
}
public static ConnectionSemaphore setSemaphore(String unitName,
String jndiName) {
ConnectionSemaphore semaphore = null;
if (unitName != null && !unitName.isEmpty()) {
semaphore = createSemaphore(unitName);
if (jndiName != null && !jndiName.isEmpty()) {
ConnectionSemaphore existent = CONNECTIONS.putIfAbsent(
jndiName, semaphore);
if (existent == null) {
semaphore.setJndiName(jndiName);
}
}
}
return semaphore;
}
private static void awaitConnection(ConnectionSemaphore semaphore) {
synchronized (semaphore) {
boolean inProgress = semaphore.isInProgress()
&& !semaphore.isBound();
while (inProgress) {
try {
semaphore.wait();
inProgress = semaphore.isInProgress()
&& !semaphore.isBound();
} catch (InterruptedException ex) {
inProgress = false;
LOG.error(ex.getMessage(), ex);
}
}
}
}
public static boolean isInProgress(String jndiName) {
ConnectionSemaphore semaphore = CONNECTIONS.get(jndiName);
boolean inProgress = semaphore != null;
if (inProgress) {
inProgress = semaphore.isInProgress() && !semaphore.isBound();
if (inProgress) {
awaitConnection(semaphore);
}
}
return inProgress;
}
/**
* Creates {@link EntityManagerFactory} by hibernate or by extended builder
* {@link Ejb3ConfigurationImpl} if entity classes or persistence.xml file
* path are provided
*
* @see Ejb3ConfigurationImpl#configure(String, Map) and
* Ejb3ConfigurationImpl#createEntityManagerFactory()
*
* @param unitName
* @return {@link EntityManagerFactory}
*/
@SuppressWarnings("deprecation")
private EntityManagerFactory buildEntityManagerFactory(String unitName)
throws IOException {
EntityManagerFactory emf;
Ejb3ConfigurationImpl cfg;
boolean checkForPath = checkForPath();
boolean checkForURL = checkForURL();
boolean checkForClasses = checkForClasses();
if (checkForPath || checkForURL) {
Enumeration<URL> xmls;
ConfigLoader configLoader = new ConfigLoader();
if (checkForPath) {
xmls = configLoader.readFile(path);
} else {
xmls = configLoader.readURL(url);
}
if (checkForClasses) {
cfg = new Ejb3ConfigurationImpl(classes, xmls);
} else {
cfg = new Ejb3ConfigurationImpl(xmls);
}
cfg.setShortPath(configLoader.getShortPath());
} else {
cfg = new Ejb3ConfigurationImpl(classes);
}
cfg.setSwapDataSource(swapDataSource);
cfg.setScanArchives(scanArchives);
Ejb3ConfigurationImpl configured = cfg.configure(unitName, properties);
emf = configured != null ? configured.buildEntityManagerFactory()
: null;
return emf;
}
/**
* Checks if entity classes are provided
*
* @return boolean
*/
private boolean checkForClasses() {
return classes != null && !classes.isEmpty();
}
/**
* Checks if entity persistence.xml path is provided
*
* @return boolean
*/
private boolean checkForPath() {
return path != null && !path.isEmpty();
}
/**
* Checks if entity persistence.xml {@link URL} is provided
*
* @return boolean
*/
private boolean checkForURL() {
return url != null && !url.toString().isEmpty();
}
/**
* Checks if entity classes or persistence.xml path are provided
*
* @param classes
* @return boolean
*/
private boolean checkForBuild() {
return checkForClasses() || checkForPath() || checkForURL();
}
/**
* Checks if entity classes or persistence.xml file path are provided to
* create {@link EntityManagerFactory}
*
* @see #buildEntityManagerFactory(String, String, Map, List)
*
* @param unitName
* @param properties
* @param path
* @param classes
* @return {@link EntityManagerFactory}
* @throws IOException
*/
private EntityManagerFactory createEntityManagerFactory(String unitName)
throws IOException {
EntityManagerFactory emf;
if (checkForBuild()) {
emf = buildEntityManagerFactory(unitName);
} else if (properties == null) {
emf = Persistence.createEntityManagerFactory(unitName);
} else {
emf = Persistence.createEntityManagerFactory(unitName, properties);
}
return emf;
}
/**
* Binds {@link EntityManagerFactory} to {@link javax.naming.InitialContext}
*
* @param jndiName
* @param unitName
* @param emf
* @throws IOException
*/
private void bindJndiName(ConnectionSemaphore semaphore) throws IOException {
boolean bound = semaphore.isBound();
if (!bound) {
String jndiName = semaphore.getJndiName();
if (jndiName != null && !jndiName.isEmpty()) {
NamingUtils namingUtils = new NamingUtils();
try {
Context context = namingUtils.getContext();
if (context.lookup(jndiName) == null) {
namingUtils.getContext().bind(jndiName,
semaphore.getEmf());
}
semaphore.setBound(true);
} catch (NamingException ex) {
throw new IOException(String.format(
"could not bind connection %s",
semaphore.getUnitName()), ex);
}
} else {
semaphore.setBound(true);
}
}
}
public void setConnection(String unitName) throws IOException {
ConnectionSemaphore semaphore = CONNECTIONS.get(unitName);
if (semaphore.isInProgress()) {
EntityManagerFactory emf = createEntityManagerFactory(unitName);
semaphore.setEmf(emf);
semaphore.setInProgress(false);
bindJndiName(semaphore);
} else if (semaphore.getEmf() == null) {
throw new IOException(String.format(
"Connection %s was not in progress", unitName));
} else {
bindJndiName(semaphore);
}
}
/**
* Gets {@link ConnectionSemaphore} from cache, awaits if connection
* instantiation is in progress
*
* @param unitName
* @return {@link ConnectionSemaphore}
* @throws IOException
*/
public static ConnectionSemaphore getConnection(String unitName)
throws IOException {
ConnectionSemaphore semaphore = CONNECTIONS.get(unitName);
if (semaphore != null) {
awaitConnection(semaphore);
}
return semaphore;
}
/**
* Gets {@link EntityManagerFactory} from {@link ConnectionSemaphore},
* awaits if connection
*
* @param unitName
* @return {@link EntityManagerFactory}
* @throws IOException
*/
public static EntityManagerFactory getEntityManagerFactory(String unitName)
throws IOException {
EntityManagerFactory emf = null;
ConnectionSemaphore semaphore = CONNECTIONS.get(unitName);
if (semaphore != null) {
awaitConnection(semaphore);
emf = semaphore.getEmf();
}
return emf;
}
/**
* Unbinds connection from {@link javax.naming.Context}
*
* @param semaphore
*/
private static void unbindConnection(ConnectionSemaphore semaphore) {
String jndiName = semaphore.getJndiName();
if (jndiName != null && semaphore.isBound()) {
NamingUtils namingUtils = new NamingUtils();
try {
Context context = namingUtils.getContext();
if (context.lookup(jndiName) != null) {
context.unbind(jndiName);
}
} catch (NamingException ex) {
LOG.error(ex.getMessage(), ex);
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
}
}
}
/**
* Closes connection ({@link EntityManagerFactory}) in passed
* {@link ConnectionSemaphore}
*
* @param semaphore
*/
private static void closeConnection(ConnectionSemaphore semaphore) {
int users = semaphore.decrementUser();
if (users <= 0) {
EntityManagerFactory emf = semaphore.getEmf();
closeEntityManagerFactory(emf);
unbindConnection(semaphore);
CONNECTIONS.remove(semaphore.getUnitName());
}
}
/**
* Removes {@link ConnectionSemaphore} from cache and unbinds name from
* {@link javax.naming.Context}
*
* @param unitName
*/
public static void removeConnection(String unitName) {
ConnectionSemaphore semaphore = CONNECTIONS.get(unitName);
if (semaphore != null) {
awaitConnection(semaphore);
closeConnection(semaphore);
NamingUtils namingUtils = new NamingUtils();
try {
String jndiName = NamingUtils.createJndiName(unitName);
namingUtils.unbind(jndiName);
} catch (IOException ex) {
LOG.error(String.format(
"Could not unbind jndi name %s cause %s", unitName,
ex.getMessage()), ex);
}
}
}
/**
* Closes passed {@link EntityManagerFactory}
*
* @param emf
*/
private static void closeEntityManagerFactory(EntityManagerFactory emf) {
if (emf != null && emf.isOpen()) {
emf.close();
}
}
/**
* Closes all existing {@link EntityManagerFactory} instances kept in cache
*/
public static void closeEntityManagerFactories() {
Collection<ConnectionSemaphore> semaphores = CONNECTIONS.values();
EntityManagerFactory emf;
for (ConnectionSemaphore semaphore : semaphores) {
emf = semaphore.getEmf();
closeEntityManagerFactory(emf);
}
CONNECTIONS.clear();
}
/**
* Builder class to create {@link JPAManager} class object
*
* @author Levan
*
*/
public static class Builder {
private JPAManager manager;
public Builder() {
manager = new JPAManager();
manager.scanArchives = true;
}
public Builder setClasses(List<String> classes) {
manager.classes = classes;
return this;
}
public Builder setURL(URL url) {
manager.url = url;
return this;
}
public Builder setPath(String path) {
manager.path = path;
return this;
}
public Builder setProperties(Map<?, ?> properties) {
manager.properties = properties;
return this;
}
public Builder setSwapDataSource(boolean swapDataSource) {
manager.swapDataSource = swapDataSource;
return this;
}
public Builder setScanArchives(boolean scanArchives) {
manager.scanArchives = scanArchives;
return this;
}
public JPAManager build() {
return manager;
}
}
}
| organized imports in JPAManager class | src/main/java/org/lightmare/jpa/JPAManager.java | organized imports in JPAManager class | <ide><path>rc/main/java/org/lightmare/jpa/JPAManager.java
<ide> import javax.naming.NamingException;
<ide> import javax.persistence.EntityManagerFactory;
<ide> import javax.persistence.Persistence;
<del>import javax.persistence.PersistenceException;
<ide>
<ide> import org.apache.log4j.Logger;
<ide> import org.lightmare.ejb.meta.ConnectionSemaphore; |
|
Java | mit | 0b652e73728997263ad1e56b5b97a01803e7876f | 0 | chuangxian/lib-edge | package myzd.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Created by Chen Baichuan on 18/07/2017.
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class HttpRequestDomain {
private String requestId;
private String remoteAddr;
private String requestUrl;
private String requestUri;
private String requestMethod;
private String requestTime;
private String parameter;
private String responseTime;
private String responseBody;
private long timestamp;
private String sessionId;
// public String getRequestId() {
// return requestId;
// }
//
// public void setRequestId(String requestId) {
// this.requestId = requestId;
// }
//
// public String getRemoteAddr() {
// return remoteAddr;
// }
//
// public void setRemoteAddr(String remoteAddr) {
// this.remoteAddr = remoteAddr;
// }
//
// public String getRequestMethod() {
// return requestMethod;
// }
//
// public String getRequestUrl() {
// return requestUrl;
// }
//
// public void setRequestUrl(String requestUrl) {
// this.requestUrl = requestUrl;
// }
//
// public String getRequestUri() {
// return requestUri;
// }
//
// public void setRequestUri(String requestUri) {
// this.requestUri = requestUri;
// }
//
// public void setRequestMethod(String requestMethod) {
// this.requestMethod = requestMethod;
// }
//
// public String getRequestTime() {
// return requestTime;
// }
//
// public void setRequestTime(String requestTime) {
// this.requestTime = requestTime;
// }
//
// public String getResponseTime() {
// return responseTime;
// }
//
// public void setResponseTime(String responseTime) {
// this.responseTime = responseTime;
// }
//
// public String getParameter() {
// return parameter;
// }
//
// public void setParameter(String parameter) {
// this.parameter = parameter;
// }
//
// public String getResponseBody() {
// return responseBody;
// }
//
// public void setResponseBody(String responseBody) {
// this.responseBody = responseBody;
// }
//
// public String getSessionId() {
// return sessionId;
// }
//
// public void setSessionId(String sessionId) {
// this.sessionId = sessionId;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(long timestamp) {
// this.timestamp = timestamp;
// }
}
| src/main/java/myzd/domain/HttpRequestDomain.java | package myzd.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Created by Chen Baichuan on 18/07/2017.
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class HttpRequestDomain {
private String requestId;
private String remoteAddr;
private String requestUrl;
private String requestUri;
private String requestMethod;
private String requestTime;
private String parameter;
private String responseTime;
private String responseBody;
private long timestamp;
private String sessionId;
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getRemoteAddr() {
return remoteAddr;
}
public void setRemoteAddr(String remoteAddr) {
this.remoteAddr = remoteAddr;
}
public String getRequestMethod() {
return requestMethod;
}
public String getRequestUrl() {
return requestUrl;
}
public void setRequestUrl(String requestUrl) {
this.requestUrl = requestUrl;
}
public String getRequestUri() {
return requestUri;
}
public void setRequestUri(String requestUri) {
this.requestUri = requestUri;
}
public void setRequestMethod(String requestMethod) {
this.requestMethod = requestMethod;
}
public String getRequestTime() {
return requestTime;
}
public void setRequestTime(String requestTime) {
this.requestTime = requestTime;
}
public String getResponseTime() {
return responseTime;
}
public void setResponseTime(String responseTime) {
this.responseTime = responseTime;
}
public String getParameter() {
return parameter;
}
public void setParameter(String parameter) {
this.parameter = parameter;
}
public String getResponseBody() {
return responseBody;
}
public void setResponseBody(String responseBody) {
this.responseBody = responseBody;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
}
| 修改httpRequestDomain的get,set方法
| src/main/java/myzd/domain/HttpRequestDomain.java | 修改httpRequestDomain的get,set方法 | <ide><path>rc/main/java/myzd/domain/HttpRequestDomain.java
<ide> private long timestamp;
<ide> private String sessionId;
<ide>
<del> public String getRequestId() {
<del> return requestId;
<del> }
<del>
<del> public void setRequestId(String requestId) {
<del> this.requestId = requestId;
<del> }
<del>
<del> public String getRemoteAddr() {
<del> return remoteAddr;
<del> }
<del>
<del> public void setRemoteAddr(String remoteAddr) {
<del> this.remoteAddr = remoteAddr;
<del> }
<del>
<del> public String getRequestMethod() {
<del> return requestMethod;
<del> }
<del>
<del> public String getRequestUrl() {
<del> return requestUrl;
<del> }
<del>
<del> public void setRequestUrl(String requestUrl) {
<del> this.requestUrl = requestUrl;
<del> }
<del>
<del> public String getRequestUri() {
<del> return requestUri;
<del> }
<del>
<del> public void setRequestUri(String requestUri) {
<del> this.requestUri = requestUri;
<del> }
<del>
<del> public void setRequestMethod(String requestMethod) {
<del> this.requestMethod = requestMethod;
<del> }
<del>
<del> public String getRequestTime() {
<del> return requestTime;
<del> }
<del>
<del> public void setRequestTime(String requestTime) {
<del> this.requestTime = requestTime;
<del> }
<del>
<del> public String getResponseTime() {
<del> return responseTime;
<del> }
<del>
<del> public void setResponseTime(String responseTime) {
<del> this.responseTime = responseTime;
<del> }
<del>
<del> public String getParameter() {
<del> return parameter;
<del> }
<del>
<del> public void setParameter(String parameter) {
<del> this.parameter = parameter;
<del> }
<del>
<del> public String getResponseBody() {
<del> return responseBody;
<del> }
<del>
<del> public void setResponseBody(String responseBody) {
<del> this.responseBody = responseBody;
<del> }
<del>
<del> public String getSessionId() {
<del> return sessionId;
<del> }
<del>
<del> public void setSessionId(String sessionId) {
<del> this.sessionId = sessionId;
<del> }
<del>
<del> public long getTimestamp() {
<del> return timestamp;
<del> }
<del>
<del> public void setTimestamp(long timestamp) {
<del> this.timestamp = timestamp;
<del> }
<add>// public String getRequestId() {
<add>// return requestId;
<add>// }
<add>//
<add>// public void setRequestId(String requestId) {
<add>// this.requestId = requestId;
<add>// }
<add>//
<add>// public String getRemoteAddr() {
<add>// return remoteAddr;
<add>// }
<add>//
<add>// public void setRemoteAddr(String remoteAddr) {
<add>// this.remoteAddr = remoteAddr;
<add>// }
<add>//
<add>// public String getRequestMethod() {
<add>// return requestMethod;
<add>// }
<add>//
<add>// public String getRequestUrl() {
<add>// return requestUrl;
<add>// }
<add>//
<add>// public void setRequestUrl(String requestUrl) {
<add>// this.requestUrl = requestUrl;
<add>// }
<add>//
<add>// public String getRequestUri() {
<add>// return requestUri;
<add>// }
<add>//
<add>// public void setRequestUri(String requestUri) {
<add>// this.requestUri = requestUri;
<add>// }
<add>//
<add>// public void setRequestMethod(String requestMethod) {
<add>// this.requestMethod = requestMethod;
<add>// }
<add>//
<add>// public String getRequestTime() {
<add>// return requestTime;
<add>// }
<add>//
<add>// public void setRequestTime(String requestTime) {
<add>// this.requestTime = requestTime;
<add>// }
<add>//
<add>// public String getResponseTime() {
<add>// return responseTime;
<add>// }
<add>//
<add>// public void setResponseTime(String responseTime) {
<add>// this.responseTime = responseTime;
<add>// }
<add>//
<add>// public String getParameter() {
<add>// return parameter;
<add>// }
<add>//
<add>// public void setParameter(String parameter) {
<add>// this.parameter = parameter;
<add>// }
<add>//
<add>// public String getResponseBody() {
<add>// return responseBody;
<add>// }
<add>//
<add>// public void setResponseBody(String responseBody) {
<add>// this.responseBody = responseBody;
<add>// }
<add>//
<add>// public String getSessionId() {
<add>// return sessionId;
<add>// }
<add>//
<add>// public void setSessionId(String sessionId) {
<add>// this.sessionId = sessionId;
<add>// }
<add>//
<add>// public long getTimestamp() {
<add>// return timestamp;
<add>// }
<add>//
<add>// public void setTimestamp(long timestamp) {
<add>// this.timestamp = timestamp;
<add>// }
<ide> } |
|
Java | apache-2.0 | 3d30b7371fe99e3432d300a843f366fc32fae704 | 0 | jpechane/debezium,debezium/debezium,debezium/debezium,jpechane/debezium,debezium/debezium,debezium/debezium,jpechane/debezium,jpechane/debezium | /*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.connector.oracle;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.debezium.annotation.ThreadSafe;
import io.debezium.annotation.VisibleForTesting;
import io.debezium.connector.base.ChangeEventQueueMetrics;
import io.debezium.connector.common.CdcSourceTaskContext;
import io.debezium.pipeline.metrics.StreamingChangeEventSourceMetrics;
import io.debezium.pipeline.source.spi.EventMetadataProvider;
/**
* The metrics implementation for Oracle connector streaming phase.
*/
@ThreadSafe
public class OracleStreamingChangeEventSourceMetrics extends StreamingChangeEventSourceMetrics implements OracleStreamingChangeEventSourceMetricsMXBean {
private static final Logger LOGGER = LoggerFactory.getLogger(OracleStreamingChangeEventSourceMetrics.class);
private static final long MILLIS_PER_SECOND = 1000L;
private final AtomicReference<Scn> currentScn = new AtomicReference<>();
private final AtomicInteger logMinerQueryCount = new AtomicInteger();
private final AtomicInteger totalCapturedDmlCount = new AtomicInteger();
private final AtomicReference<Duration> totalDurationOfFetchingQuery = new AtomicReference<>();
private final AtomicInteger lastCapturedDmlCount = new AtomicInteger();
private final AtomicReference<Duration> lastDurationOfFetchingQuery = new AtomicReference<>();
private final AtomicLong maxCapturedDmlCount = new AtomicLong();
private final AtomicLong totalProcessedRows = new AtomicLong();
private final AtomicReference<Duration> maxDurationOfFetchingQuery = new AtomicReference<>();
private final AtomicReference<Duration> totalBatchProcessingDuration = new AtomicReference<>();
private final AtomicReference<Duration> lastBatchProcessingDuration = new AtomicReference<>();
private final AtomicReference<Duration> maxBatchProcessingDuration = new AtomicReference<>();
private final AtomicReference<Duration> totalParseTime = new AtomicReference<>();
private final AtomicReference<Duration> totalStartLogMiningSessionDuration = new AtomicReference<>();
private final AtomicReference<Duration> lastStartLogMiningSessionDuration = new AtomicReference<>();
private final AtomicReference<Duration> maxStartingLogMiningSessionDuration = new AtomicReference<>();
private final AtomicReference<Duration> totalProcessingTime = new AtomicReference<>();
private final AtomicReference<Duration> minBatchProcessingTime = new AtomicReference<>();
private final AtomicReference<Duration> maxBatchProcessingTime = new AtomicReference<>();
private final AtomicReference<Duration> totalResultSetNextTime = new AtomicReference<>();
private final AtomicLong maxBatchProcessingThroughput = new AtomicLong();
private final AtomicReference<String[]> currentLogFileName;
private final AtomicReference<String[]> redoLogStatus;
private final AtomicLong minimumLogsMined = new AtomicLong();
private final AtomicLong maximumLogsMined = new AtomicLong();
private final AtomicInteger switchCounter = new AtomicInteger();
private final AtomicInteger batchSize = new AtomicInteger();
private final AtomicLong millisecondToSleepBetweenMiningQuery = new AtomicLong();
private final AtomicBoolean recordMiningHistory = new AtomicBoolean();
private final AtomicInteger hoursToKeepTransaction = new AtomicInteger();
private final AtomicLong networkConnectionProblemsCounter = new AtomicLong();
private final AtomicReference<Duration> lagFromTheSourceDuration = new AtomicReference<>();
private final AtomicReference<Duration> minLagFromTheSourceDuration = new AtomicReference<>();
private final AtomicReference<Duration> maxLagFromTheSourceDuration = new AtomicReference<>();
private final AtomicReference<Duration> lastCommitDuration = new AtomicReference<>();
private final AtomicReference<Duration> maxCommitDuration = new AtomicReference<>();
private final AtomicLong activeTransactions = new AtomicLong();
private final AtomicLong rolledBackTransactions = new AtomicLong();
private final AtomicLong committedTransactions = new AtomicLong();
private final AtomicReference<Set<String>> abandonedTransactionIds = new AtomicReference<>();
private final AtomicReference<Set<String>> rolledBackTransactionIds = new AtomicReference<>();
private final AtomicLong registeredDmlCount = new AtomicLong();
private final AtomicLong committedDmlCount = new AtomicLong();
private final AtomicInteger errorCount = new AtomicInteger();
private final AtomicInteger warningCount = new AtomicInteger();
private final AtomicInteger scnFreezeCount = new AtomicInteger();
private final AtomicLong timeDifference = new AtomicLong();
private final AtomicInteger offsetSeconds = new AtomicInteger();
private final AtomicReference<Scn> oldestScn = new AtomicReference<>();
private final AtomicReference<Scn> committedScn = new AtomicReference<>();
private final AtomicReference<Scn> offsetScn = new AtomicReference<>();
private final AtomicInteger unparsableDdlCount = new AtomicInteger();
// Constants for sliding window algorithm
private final int batchSizeMin;
private final int batchSizeMax;
private final int batchSizeDefault;
// constants for sleeping algorithm
private final long sleepTimeMin;
private final long sleepTimeMax;
private final long sleepTimeDefault;
private final long sleepTimeIncrement;
private final Instant startTime;
private final Clock clock;
public OracleStreamingChangeEventSourceMetrics(CdcSourceTaskContext taskContext, ChangeEventQueueMetrics changeEventQueueMetrics,
EventMetadataProvider metadataProvider,
OracleConnectorConfig connectorConfig) {
this(taskContext, changeEventQueueMetrics, metadataProvider, connectorConfig, Clock.systemUTC());
}
/**
* Constructor that allows providing a clock to be used for Tests.
*/
@VisibleForTesting
OracleStreamingChangeEventSourceMetrics(CdcSourceTaskContext taskContext, ChangeEventQueueMetrics changeEventQueueMetrics,
EventMetadataProvider metadataProvider,
OracleConnectorConfig connectorConfig,
Clock clock) {
super(taskContext, changeEventQueueMetrics, metadataProvider);
this.clock = clock;
startTime = clock.instant();
timeDifference.set(0L);
offsetSeconds.set(0);
currentScn.set(Scn.NULL);
oldestScn.set(Scn.NULL);
offsetScn.set(Scn.NULL);
committedScn.set(Scn.NULL);
currentLogFileName = new AtomicReference<>();
minimumLogsMined.set(0L);
maximumLogsMined.set(0L);
redoLogStatus = new AtomicReference<>();
switchCounter.set(0);
recordMiningHistory.set(connectorConfig.isLogMiningHistoryRecorded());
batchSizeDefault = connectorConfig.getLogMiningBatchSizeDefault();
batchSizeMin = connectorConfig.getLogMiningBatchSizeMin();
batchSizeMax = connectorConfig.getLogMiningBatchSizeMax();
sleepTimeDefault = connectorConfig.getLogMiningSleepTimeDefault().toMillis();
sleepTimeMin = connectorConfig.getLogMiningSleepTimeMin().toMillis();
sleepTimeMax = connectorConfig.getLogMiningSleepTimeMax().toMillis();
sleepTimeIncrement = connectorConfig.getLogMiningSleepTimeIncrement().toMillis();
hoursToKeepTransaction.set(Long.valueOf(connectorConfig.getLogMiningTransactionRetention().toHours()).intValue());
reset();
}
@Override
public void reset() {
batchSize.set(batchSizeDefault);
millisecondToSleepBetweenMiningQuery.set(sleepTimeDefault);
totalCapturedDmlCount.set(0);
totalProcessedRows.set(0);
maxDurationOfFetchingQuery.set(Duration.ZERO);
lastDurationOfFetchingQuery.set(Duration.ZERO);
logMinerQueryCount.set(0);
maxBatchProcessingDuration.set(Duration.ZERO);
totalDurationOfFetchingQuery.set(Duration.ZERO);
lastCapturedDmlCount.set(0);
maxCapturedDmlCount.set(0);
totalBatchProcessingDuration.set(Duration.ZERO);
maxBatchProcessingThroughput.set(0);
lastBatchProcessingDuration.set(Duration.ZERO);
networkConnectionProblemsCounter.set(0);
totalParseTime.set(Duration.ZERO);
totalStartLogMiningSessionDuration.set(Duration.ZERO);
lastStartLogMiningSessionDuration.set(Duration.ZERO);
maxStartingLogMiningSessionDuration.set(Duration.ZERO);
totalProcessingTime.set(Duration.ZERO);
minBatchProcessingTime.set(Duration.ZERO);
maxBatchProcessingTime.set(Duration.ZERO);
totalResultSetNextTime.set(Duration.ZERO);
// transactional buffer metrics
lagFromTheSourceDuration.set(Duration.ZERO);
maxLagFromTheSourceDuration.set(Duration.ZERO);
minLagFromTheSourceDuration.set(Duration.ZERO);
lastCommitDuration.set(Duration.ZERO);
maxCommitDuration.set(Duration.ZERO);
activeTransactions.set(0);
rolledBackTransactions.set(0);
committedTransactions.set(0);
registeredDmlCount.set(0);
committedDmlCount.set(0);
abandonedTransactionIds.set(new HashSet<>());
rolledBackTransactionIds.set(new HashSet<>());
errorCount.set(0);
warningCount.set(0);
scnFreezeCount.set(0);
}
public void setCurrentScn(Scn scn) {
currentScn.set(scn);
}
public void setCurrentLogFileName(Set<String> names) {
currentLogFileName.set(names.stream().toArray(String[]::new));
if (names.size() < minimumLogsMined.get()) {
minimumLogsMined.set(names.size());
}
if (names.size() > maximumLogsMined.get()) {
maximumLogsMined.set(names.size());
}
}
@Override
public long getMinimumMinedLogCount() {
return minimumLogsMined.get();
}
@Override
public long getMaximumMinedLogCount() {
return maximumLogsMined.get();
}
public void setRedoLogStatus(Map<String, String> status) {
String[] statusArray = status.entrySet().stream().map(e -> e.getKey() + " | " + e.getValue()).toArray(String[]::new);
redoLogStatus.set(statusArray);
}
public void setSwitchCount(int counter) {
switchCounter.set(counter);
}
public void setLastCapturedDmlCount(int dmlCount) {
lastCapturedDmlCount.set(dmlCount);
if (dmlCount > maxCapturedDmlCount.get()) {
maxCapturedDmlCount.set(dmlCount);
}
totalCapturedDmlCount.getAndAdd(dmlCount);
}
public void setLastDurationOfBatchCapturing(Duration lastDuration) {
lastDurationOfFetchingQuery.set(lastDuration);
totalDurationOfFetchingQuery.accumulateAndGet(lastDurationOfFetchingQuery.get(), Duration::plus);
if (maxDurationOfFetchingQuery.get().toMillis() < lastDurationOfFetchingQuery.get().toMillis()) {
maxDurationOfFetchingQuery.set(lastDuration);
}
logMinerQueryCount.incrementAndGet();
}
public void setLastDurationOfBatchProcessing(Duration lastDuration) {
lastBatchProcessingDuration.set(lastDuration);
totalBatchProcessingDuration.accumulateAndGet(lastDuration, Duration::plus);
if (maxBatchProcessingDuration.get().toMillis() < lastDuration.toMillis()) {
maxBatchProcessingDuration.set(lastDuration);
}
if (getLastBatchProcessingThroughput() > maxBatchProcessingThroughput.get()) {
maxBatchProcessingThroughput.set(getLastBatchProcessingThroughput());
}
}
public void incrementNetworkConnectionProblemsCounter() {
networkConnectionProblemsCounter.incrementAndGet();
}
@Override
public String getCurrentScn() {
return currentScn.get().toString();
}
@Override
public long getTotalCapturedDmlCount() {
return totalCapturedDmlCount.get();
}
@Override
public String[] getCurrentRedoLogFileName() {
return currentLogFileName.get();
}
@Override
public String[] getRedoLogStatus() {
return redoLogStatus.get();
}
@Override
public int getSwitchCounter() {
return switchCounter.get();
}
@Override
public Long getLastDurationOfFetchQueryInMilliseconds() {
return lastDurationOfFetchingQuery.get() == null ? 0 : lastDurationOfFetchingQuery.get().toMillis();
}
@Override
public long getLastBatchProcessingTimeInMilliseconds() {
return lastBatchProcessingDuration.get().toMillis();
}
@Override
public Long getMaxDurationOfFetchQueryInMilliseconds() {
return maxDurationOfFetchingQuery.get() == null ? 0 : maxDurationOfFetchingQuery.get().toMillis();
}
@Override
public Long getMaxCapturedDmlInBatch() {
return maxCapturedDmlCount.get();
}
@Override
public int getLastCapturedDmlCount() {
return lastCapturedDmlCount.get();
}
@Override
public long getTotalProcessedRows() {
return totalProcessedRows.get();
}
@Override
public long getTotalResultSetNextTimeInMilliseconds() {
return totalResultSetNextTime.get().toMillis();
}
@Override
public long getAverageBatchProcessingThroughput() {
if (totalBatchProcessingDuration.get().isZero()) {
return 0L;
}
return Math.round((totalCapturedDmlCount.floatValue() / totalBatchProcessingDuration.get().toMillis()) * 1000);
}
@Override
public long getLastBatchProcessingThroughput() {
if (lastBatchProcessingDuration.get().isZero()) {
return 0L;
}
return Math.round((lastCapturedDmlCount.floatValue() / lastBatchProcessingDuration.get().toMillis()) * 1000);
}
@Override
public long getFetchingQueryCount() {
return logMinerQueryCount.get();
}
@Override
public int getBatchSize() {
return batchSize.get();
}
@Override
public long getMillisecondToSleepBetweenMiningQuery() {
return millisecondToSleepBetweenMiningQuery.get();
}
@Override
public boolean getRecordMiningHistory() {
return recordMiningHistory.get();
}
@Override
public int getHoursToKeepTransactionInBuffer() {
return hoursToKeepTransaction.get();
}
@Override
public long getMaxBatchProcessingThroughput() {
return maxBatchProcessingThroughput.get();
}
@Override
public long getNetworkConnectionProblemsCounter() {
return networkConnectionProblemsCounter.get();
}
@Override
public long getTotalParseTimeInMilliseconds() {
return totalParseTime.get().toMillis();
}
public void addCurrentParseTime(Duration currentParseTime) {
totalParseTime.accumulateAndGet(currentParseTime, Duration::plus);
}
@Override
public long getTotalMiningSessionStartTimeInMilliseconds() {
return totalStartLogMiningSessionDuration.get().toMillis();
}
public void addCurrentMiningSessionStart(Duration currentStartLogMiningSession) {
lastStartLogMiningSessionDuration.set(currentStartLogMiningSession);
if (currentStartLogMiningSession.compareTo(maxStartingLogMiningSessionDuration.get()) > 0) {
maxStartingLogMiningSessionDuration.set(currentStartLogMiningSession);
}
totalStartLogMiningSessionDuration.accumulateAndGet(currentStartLogMiningSession, Duration::plus);
}
@Override
public long getLastMiningSessionStartTimeInMilliseconds() {
return lastStartLogMiningSessionDuration.get().toMillis();
}
@Override
public long getMaxMiningSessionStartTimeInMilliseconds() {
return maxStartingLogMiningSessionDuration.get().toMillis();
}
@Override
public long getTotalProcessingTimeInMilliseconds() {
return totalProcessingTime.get().toMillis();
}
@Override
public long getMinBatchProcessingTimeInMilliseconds() {
return minBatchProcessingTime.get().toMillis();
}
@Override
public long getMaxBatchProcessingTimeInMilliseconds() {
return maxBatchProcessingTime.get().toMillis();
}
public void setCurrentBatchProcessingTime(Duration currentBatchProcessingTime) {
totalProcessingTime.accumulateAndGet(currentBatchProcessingTime, Duration::plus);
}
public void addCurrentResultSetNext(Duration currentNextTime) {
totalResultSetNextTime.accumulateAndGet(currentNextTime, Duration::plus);
}
public void addProcessedRows(Long rows) {
totalProcessedRows.getAndAdd(rows);
}
@Override
public void setBatchSize(int size) {
if (size >= batchSizeMin && size <= batchSizeMax) {
batchSize.set(size);
}
}
@Override
public void setMillisecondToSleepBetweenMiningQuery(long milliseconds) {
if (milliseconds >= sleepTimeMin && milliseconds < sleepTimeMax) {
millisecondToSleepBetweenMiningQuery.set(milliseconds);
}
}
@Override
public void changeSleepingTime(boolean increment) {
long sleepTime = millisecondToSleepBetweenMiningQuery.get();
if (increment && sleepTime < sleepTimeMax) {
sleepTime = millisecondToSleepBetweenMiningQuery.addAndGet(sleepTimeIncrement);
}
else if (sleepTime > sleepTimeMin) {
sleepTime = millisecondToSleepBetweenMiningQuery.addAndGet(-sleepTimeIncrement);
}
LOGGER.debug("Updating sleep time window. Sleep time {}. Min sleep time {}. Max sleep time {}.", sleepTime, sleepTimeMin, sleepTimeMax);
}
@Override
public void changeBatchSize(boolean increment, boolean lobEnabled) {
int currentBatchSize = batchSize.get();
if (increment && currentBatchSize < batchSizeMax) {
currentBatchSize = batchSize.addAndGet(batchSizeMin);
}
else if (currentBatchSize > batchSizeMin) {
currentBatchSize = batchSize.addAndGet(-batchSizeMin);
}
if (currentBatchSize == batchSizeMax) {
if (!lobEnabled) {
LOGGER.info("The connector is now using the maximum batch size {} when querying the LogMiner view. This could be indicative of large SCN gaps", currentBatchSize);
}
else {
LOGGER.debug("The connector is now using the maximum batch size {} when querying the LogMiner view.", currentBatchSize);
}
}
else {
LOGGER.debug("Updating batch size window. Batch size {}. Min batch size {}. Max batch size {}.", currentBatchSize, batchSizeMin, batchSizeMax);
}
}
// transactional buffer metrics
@Override
public long getNumberOfActiveTransactions() {
return activeTransactions.get();
}
@Override
public long getNumberOfRolledBackTransactions() {
return rolledBackTransactions.get();
}
@Override
public long getNumberOfCommittedTransactions() {
return committedTransactions.get();
}
@Override
public long getCommitThroughput() {
long timeSpent = Duration.between(startTime, clock.instant()).toMillis();
return committedTransactions.get() * MILLIS_PER_SECOND / (timeSpent != 0 ? timeSpent : 1);
}
@Override
public long getRegisteredDmlCount() {
return registeredDmlCount.get();
}
@Override
public String getOldestScn() {
return oldestScn.get().toString();
}
@Override
public String getCommittedScn() {
return committedScn.get().toString();
}
@Override
public String getOffsetScn() {
return offsetScn.get().toString();
}
@Override
public long getLagFromSourceInMilliseconds() {
return lagFromTheSourceDuration.get().toMillis();
}
@Override
public long getMaxLagFromSourceInMilliseconds() {
return maxLagFromTheSourceDuration.get().toMillis();
}
@Override
public long getMinLagFromSourceInMilliseconds() {
return minLagFromTheSourceDuration.get().toMillis();
}
@Override
public Set<String> getAbandonedTransactionIds() {
return abandonedTransactionIds.get();
}
@Override
public Set<String> getRolledBackTransactionIds() {
return rolledBackTransactionIds.get();
}
@Override
public long getLastCommitDurationInMilliseconds() {
return lastCommitDuration.get().toMillis();
}
@Override
public long getMaxCommitDurationInMilliseconds() {
return maxCommitDuration.get().toMillis();
}
@Override
public int getErrorCount() {
return errorCount.get();
}
@Override
public int getWarningCount() {
return warningCount.get();
}
@Override
public int getScnFreezeCount() {
return scnFreezeCount.get();
}
@Override
public int getUnparsableDdlCount() {
return unparsableDdlCount.get();
}
public void setOldestScn(Scn scn) {
oldestScn.set(scn);
}
public void setCommittedScn(Scn scn) {
committedScn.set(scn);
}
public void setOffsetScn(Scn scn) {
offsetScn.set(scn);
}
public void setActiveTransactions(long activeTransactionCount) {
activeTransactions.set(activeTransactionCount);
}
public void incrementRolledBackTransactions() {
rolledBackTransactions.incrementAndGet();
}
public void incrementCommittedTransactions() {
committedTransactions.incrementAndGet();
}
public void incrementRegisteredDmlCount() {
registeredDmlCount.incrementAndGet();
}
public void incrementCommittedDmlCount(long counter) {
committedDmlCount.getAndAdd(counter);
}
public void incrementErrorCount() {
errorCount.incrementAndGet();
}
public void incrementWarningCount() {
warningCount.incrementAndGet();
}
public void incrementScnFreezeCount() {
scnFreezeCount.incrementAndGet();
}
public void addAbandonedTransactionId(String transactionId) {
if (transactionId != null) {
abandonedTransactionIds.get().add(transactionId);
}
}
public void addRolledBackTransactionId(String transactionId) {
if (transactionId != null) {
rolledBackTransactionIds.get().add(transactionId);
}
}
public void setLastCommitDuration(Duration lastDuration) {
lastCommitDuration.set(lastDuration);
if (lastDuration.toMillis() > maxCommitDuration.get().toMillis()) {
maxCommitDuration.set(lastDuration);
}
}
/**
* Calculates the time difference between the database server and the connector.
* Along with the time difference also the offset of the database server time to UTC is stored.
* Both values are required to calculate lag metrics.
*
* @param databaseSystemTime the system time (<code>SYSTIMESTAMP</code>) of the database
*/
public void calculateTimeDifference(OffsetDateTime databaseSystemTime) {
int offsetSeconds = databaseSystemTime.getOffset().getTotalSeconds();
this.offsetSeconds.set(offsetSeconds);
LOGGER.trace("Timezone offset of database system time is {} seconds", offsetSeconds);
Instant now = clock.instant();
long timeDiffMillis = Duration.between(databaseSystemTime.toInstant(), now).toMillis();
this.timeDifference.set(timeDiffMillis);
LOGGER.trace("Current time {} ms, database difference {} ms", now.toEpochMilli(), timeDiffMillis);
}
public void calculateLagMetrics(Instant changeTime) {
if (changeTime != null) {
final Instant correctedChangeTime = changeTime.plusMillis(timeDifference.longValue()).minusSeconds(offsetSeconds.longValue());
final Duration lag = Duration.between(correctedChangeTime, clock.instant()).abs();
lagFromTheSourceDuration.set(lag);
if (maxLagFromTheSourceDuration.get().toMillis() < lag.toMillis()) {
maxLagFromTheSourceDuration.set(lag);
}
if (minLagFromTheSourceDuration.get().toMillis() > lag.toMillis()) {
minLagFromTheSourceDuration.set(lag);
}
}
}
public void incrementUnparsableDdlCount() {
unparsableDdlCount.incrementAndGet();
}
@Override
public String toString() {
return "OracleStreamingChangeEventSourceMetrics{" +
"currentScn=" + currentScn +
", oldestScn=" + oldestScn.get() +
", committedScn=" + committedScn.get() +
", offsetScn=" + offsetScn.get() +
", logMinerQueryCount=" + logMinerQueryCount +
", totalProcessedRows=" + totalProcessedRows +
", totalCapturedDmlCount=" + totalCapturedDmlCount +
", totalDurationOfFetchingQuery=" + totalDurationOfFetchingQuery +
", lastCapturedDmlCount=" + lastCapturedDmlCount +
", lastDurationOfFetchingQuery=" + lastDurationOfFetchingQuery +
", maxCapturedDmlCount=" + maxCapturedDmlCount +
", maxDurationOfFetchingQuery=" + maxDurationOfFetchingQuery +
", totalBatchProcessingDuration=" + totalBatchProcessingDuration +
", lastBatchProcessingDuration=" + lastBatchProcessingDuration +
", maxBatchProcessingDuration=" + maxBatchProcessingDuration +
", maxBatchProcessingThroughput=" + maxBatchProcessingThroughput +
", currentLogFileName=" + currentLogFileName +
", minLogFilesMined=" + minimumLogsMined +
", maxLogFilesMined=" + maximumLogsMined +
", redoLogStatus=" + redoLogStatus +
", switchCounter=" + switchCounter +
", batchSize=" + batchSize +
", millisecondToSleepBetweenMiningQuery=" + millisecondToSleepBetweenMiningQuery +
", recordMiningHistory=" + recordMiningHistory +
", hoursToKeepTransaction=" + hoursToKeepTransaction +
", networkConnectionProblemsCounter" + networkConnectionProblemsCounter +
", batchSizeDefault=" + batchSizeDefault +
", batchSizeMin=" + batchSizeMin +
", batchSizeMax=" + batchSizeMax +
", sleepTimeDefault=" + sleepTimeDefault +
", sleepTimeMin=" + sleepTimeMin +
", sleepTimeMax=" + sleepTimeMax +
", sleepTimeIncrement=" + sleepTimeIncrement +
", totalParseTime=" + totalParseTime +
", totalStartLogMiningSessionDuration=" + totalStartLogMiningSessionDuration +
", lastStartLogMiningSessionDuration=" + lastStartLogMiningSessionDuration +
", maxStartLogMiningSessionDuration=" + maxStartingLogMiningSessionDuration +
", totalProcessTime=" + totalProcessingTime +
", minBatchProcessTime=" + minBatchProcessingTime +
", maxBatchProcessTime=" + maxBatchProcessingTime +
", totalResultSetNextTime=" + totalResultSetNextTime +
", lagFromTheSource=Duration" + lagFromTheSourceDuration.get() +
", maxLagFromTheSourceDuration=" + maxLagFromTheSourceDuration.get() +
", minLagFromTheSourceDuration=" + minLagFromTheSourceDuration.get() +
", lastCommitDuration=" + lastCommitDuration +
", maxCommitDuration=" + maxCommitDuration +
", activeTransactions=" + activeTransactions.get() +
", rolledBackTransactions=" + rolledBackTransactions.get() +
", committedTransactions=" + committedTransactions.get() +
", abandonedTransactionIds=" + abandonedTransactionIds.get() +
", rolledbackTransactionIds=" + rolledBackTransactionIds.get() +
", registeredDmlCount=" + registeredDmlCount.get() +
", committedDmlCount=" + committedDmlCount.get() +
", errorCount=" + errorCount.get() +
", warningCount=" + warningCount.get() +
", scnFreezeCount=" + scnFreezeCount.get() +
", unparsableDdlCount=" + unparsableDdlCount.get() +
'}';
}
}
| debezium-connector-oracle/src/main/java/io/debezium/connector/oracle/OracleStreamingChangeEventSourceMetrics.java | /*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.connector.oracle;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.debezium.annotation.ThreadSafe;
import io.debezium.annotation.VisibleForTesting;
import io.debezium.connector.base.ChangeEventQueueMetrics;
import io.debezium.connector.common.CdcSourceTaskContext;
import io.debezium.pipeline.metrics.StreamingChangeEventSourceMetrics;
import io.debezium.pipeline.source.spi.EventMetadataProvider;
/**
* The metrics implementation for Oracle connector streaming phase.
*/
@ThreadSafe
public class OracleStreamingChangeEventSourceMetrics extends StreamingChangeEventSourceMetrics implements OracleStreamingChangeEventSourceMetricsMXBean {
private static final Logger LOGGER = LoggerFactory.getLogger(OracleStreamingChangeEventSourceMetrics.class);
private static final long MILLIS_PER_SECOND = 1000L;
private final AtomicReference<Scn> currentScn = new AtomicReference<>();
private final AtomicInteger logMinerQueryCount = new AtomicInteger();
private final AtomicInteger totalCapturedDmlCount = new AtomicInteger();
private final AtomicReference<Duration> totalDurationOfFetchingQuery = new AtomicReference<>();
private final AtomicInteger lastCapturedDmlCount = new AtomicInteger();
private final AtomicReference<Duration> lastDurationOfFetchingQuery = new AtomicReference<>();
private final AtomicLong maxCapturedDmlCount = new AtomicLong();
private final AtomicLong totalProcessedRows = new AtomicLong();
private final AtomicReference<Duration> maxDurationOfFetchingQuery = new AtomicReference<>();
private final AtomicReference<Duration> totalBatchProcessingDuration = new AtomicReference<>();
private final AtomicReference<Duration> lastBatchProcessingDuration = new AtomicReference<>();
private final AtomicReference<Duration> maxBatchProcessingDuration = new AtomicReference<>();
private final AtomicReference<Duration> totalParseTime = new AtomicReference<>();
private final AtomicReference<Duration> totalStartLogMiningSessionDuration = new AtomicReference<>();
private final AtomicReference<Duration> lastStartLogMiningSessionDuration = new AtomicReference<>();
private final AtomicReference<Duration> maxStartingLogMiningSessionDuration = new AtomicReference<>();
private final AtomicReference<Duration> totalProcessingTime = new AtomicReference<>();
private final AtomicReference<Duration> minBatchProcessingTime = new AtomicReference<>();
private final AtomicReference<Duration> maxBatchProcessingTime = new AtomicReference<>();
private final AtomicReference<Duration> totalResultSetNextTime = new AtomicReference<>();
private final AtomicLong maxBatchProcessingThroughput = new AtomicLong();
private final AtomicReference<String[]> currentLogFileName;
private final AtomicReference<String[]> redoLogStatus;
private final AtomicLong minimumLogsMined = new AtomicLong();
private final AtomicLong maximumLogsMined = new AtomicLong();
private final AtomicInteger switchCounter = new AtomicInteger();
private final AtomicInteger batchSize = new AtomicInteger();
private final AtomicLong millisecondToSleepBetweenMiningQuery = new AtomicLong();
private final AtomicBoolean recordMiningHistory = new AtomicBoolean();
private final AtomicInteger hoursToKeepTransaction = new AtomicInteger();
private final AtomicLong networkConnectionProblemsCounter = new AtomicLong();
private final AtomicReference<Duration> lagFromTheSourceDuration = new AtomicReference<>();
private final AtomicReference<Duration> minLagFromTheSourceDuration = new AtomicReference<>();
private final AtomicReference<Duration> maxLagFromTheSourceDuration = new AtomicReference<>();
private final AtomicReference<Duration> lastCommitDuration = new AtomicReference<>();
private final AtomicReference<Duration> maxCommitDuration = new AtomicReference<>();
private final AtomicLong activeTransactions = new AtomicLong();
private final AtomicLong rolledBackTransactions = new AtomicLong();
private final AtomicLong committedTransactions = new AtomicLong();
private final AtomicReference<Set<String>> abandonedTransactionIds = new AtomicReference<>();
private final AtomicReference<Set<String>> rolledBackTransactionIds = new AtomicReference<>();
private final AtomicLong registeredDmlCount = new AtomicLong();
private final AtomicLong committedDmlCount = new AtomicLong();
private final AtomicInteger errorCount = new AtomicInteger();
private final AtomicInteger warningCount = new AtomicInteger();
private final AtomicInteger scnFreezeCount = new AtomicInteger();
private final AtomicLong timeDifference = new AtomicLong();
private final AtomicInteger offsetSeconds = new AtomicInteger();
private final AtomicReference<Scn> oldestScn = new AtomicReference<>();
private final AtomicReference<Scn> committedScn = new AtomicReference<>();
private final AtomicReference<Scn> offsetScn = new AtomicReference<>();
private final AtomicInteger unparsableDdlCount = new AtomicInteger();
// Constants for sliding window algorithm
private final int batchSizeMin;
private final int batchSizeMax;
private final int batchSizeDefault;
// constants for sleeping algorithm
private final long sleepTimeMin;
private final long sleepTimeMax;
private final long sleepTimeDefault;
private final long sleepTimeIncrement;
private final Instant startTime;
private final Clock clock;
public OracleStreamingChangeEventSourceMetrics(CdcSourceTaskContext taskContext, ChangeEventQueueMetrics changeEventQueueMetrics,
EventMetadataProvider metadataProvider,
OracleConnectorConfig connectorConfig) {
this(taskContext, changeEventQueueMetrics, metadataProvider, connectorConfig, Clock.systemUTC());
}
/**
* Constructor that allows providing a clock to be used for Tests.
*/
@VisibleForTesting
OracleStreamingChangeEventSourceMetrics(CdcSourceTaskContext taskContext, ChangeEventQueueMetrics changeEventQueueMetrics,
EventMetadataProvider metadataProvider,
OracleConnectorConfig connectorConfig,
Clock clock) {
super(taskContext, changeEventQueueMetrics, metadataProvider);
this.clock = clock;
startTime = clock.instant();
timeDifference.set(0L);
offsetSeconds.set(0);
currentScn.set(Scn.NULL);
oldestScn.set(Scn.NULL);
offsetScn.set(Scn.NULL);
committedScn.set(Scn.NULL);
currentLogFileName = new AtomicReference<>();
minimumLogsMined.set(0L);
maximumLogsMined.set(0L);
redoLogStatus = new AtomicReference<>();
switchCounter.set(0);
recordMiningHistory.set(connectorConfig.isLogMiningHistoryRecorded());
batchSizeDefault = connectorConfig.getLogMiningBatchSizeDefault();
batchSizeMin = connectorConfig.getLogMiningBatchSizeMin();
batchSizeMax = connectorConfig.getLogMiningBatchSizeMax();
sleepTimeDefault = connectorConfig.getLogMiningSleepTimeDefault().toMillis();
sleepTimeMin = connectorConfig.getLogMiningSleepTimeMin().toMillis();
sleepTimeMax = connectorConfig.getLogMiningSleepTimeMax().toMillis();
sleepTimeIncrement = connectorConfig.getLogMiningSleepTimeIncrement().toMillis();
hoursToKeepTransaction.set(Long.valueOf(connectorConfig.getLogMiningTransactionRetention().toHours()).intValue());
reset();
}
@Override
public void reset() {
batchSize.set(batchSizeDefault);
millisecondToSleepBetweenMiningQuery.set(sleepTimeDefault);
totalCapturedDmlCount.set(0);
totalProcessedRows.set(0);
maxDurationOfFetchingQuery.set(Duration.ZERO);
lastDurationOfFetchingQuery.set(Duration.ZERO);
logMinerQueryCount.set(0);
maxBatchProcessingDuration.set(Duration.ZERO);
totalDurationOfFetchingQuery.set(Duration.ZERO);
lastCapturedDmlCount.set(0);
maxCapturedDmlCount.set(0);
totalBatchProcessingDuration.set(Duration.ZERO);
maxBatchProcessingThroughput.set(0);
lastBatchProcessingDuration.set(Duration.ZERO);
networkConnectionProblemsCounter.set(0);
totalParseTime.set(Duration.ZERO);
totalStartLogMiningSessionDuration.set(Duration.ZERO);
lastStartLogMiningSessionDuration.set(Duration.ZERO);
maxStartingLogMiningSessionDuration.set(Duration.ZERO);
totalProcessingTime.set(Duration.ZERO);
minBatchProcessingTime.set(Duration.ZERO);
maxBatchProcessingTime.set(Duration.ZERO);
totalResultSetNextTime.set(Duration.ZERO);
// transactional buffer metrics
lagFromTheSourceDuration.set(Duration.ZERO);
maxLagFromTheSourceDuration.set(Duration.ZERO);
minLagFromTheSourceDuration.set(Duration.ZERO);
lastCommitDuration.set(Duration.ZERO);
maxCommitDuration.set(Duration.ZERO);
activeTransactions.set(0);
rolledBackTransactions.set(0);
committedTransactions.set(0);
registeredDmlCount.set(0);
committedDmlCount.set(0);
abandonedTransactionIds.set(new HashSet<>());
rolledBackTransactionIds.set(new HashSet<>());
errorCount.set(0);
warningCount.set(0);
scnFreezeCount.set(0);
}
public void setCurrentScn(Scn scn) {
currentScn.set(scn);
}
public void setCurrentLogFileName(Set<String> names) {
currentLogFileName.set(names.stream().toArray(String[]::new));
if (names.size() < minimumLogsMined.get()) {
minimumLogsMined.set(names.size());
}
if (names.size() > maximumLogsMined.get()) {
maximumLogsMined.set(names.size());
}
}
@Override
public long getMinimumMinedLogCount() {
return minimumLogsMined.get();
}
@Override
public long getMaximumMinedLogCount() {
return maximumLogsMined.get();
}
public void setRedoLogStatus(Map<String, String> status) {
String[] statusArray = status.entrySet().stream().map(e -> e.getKey() + " | " + e.getValue()).toArray(String[]::new);
redoLogStatus.set(statusArray);
}
public void setSwitchCount(int counter) {
switchCounter.set(counter);
}
public void setLastCapturedDmlCount(int dmlCount) {
lastCapturedDmlCount.set(dmlCount);
if (dmlCount > maxCapturedDmlCount.get()) {
maxCapturedDmlCount.set(dmlCount);
}
totalCapturedDmlCount.getAndAdd(dmlCount);
}
public void setLastDurationOfBatchCapturing(Duration lastDuration) {
lastDurationOfFetchingQuery.set(lastDuration);
totalDurationOfFetchingQuery.accumulateAndGet(lastDurationOfFetchingQuery.get(), Duration::plus);
if (maxDurationOfFetchingQuery.get().toMillis() < lastDurationOfFetchingQuery.get().toMillis()) {
maxDurationOfFetchingQuery.set(lastDuration);
}
logMinerQueryCount.incrementAndGet();
}
public void setLastDurationOfBatchProcessing(Duration lastDuration) {
lastBatchProcessingDuration.set(lastDuration);
totalBatchProcessingDuration.accumulateAndGet(lastDuration, Duration::plus);
if (maxBatchProcessingDuration.get().toMillis() < lastDuration.toMillis()) {
maxBatchProcessingDuration.set(lastDuration);
}
if (getLastBatchProcessingThroughput() > maxBatchProcessingThroughput.get()) {
maxBatchProcessingThroughput.set(getLastBatchProcessingThroughput());
}
}
public void incrementNetworkConnectionProblemsCounter() {
networkConnectionProblemsCounter.incrementAndGet();
}
@Override
public String getCurrentScn() {
return currentScn.get().toString();
}
@Override
public long getTotalCapturedDmlCount() {
return totalCapturedDmlCount.get();
}
@Override
public String[] getCurrentRedoLogFileName() {
return currentLogFileName.get();
}
@Override
public String[] getRedoLogStatus() {
return redoLogStatus.get();
}
@Override
public int getSwitchCounter() {
return switchCounter.get();
}
@Override
public Long getLastDurationOfFetchQueryInMilliseconds() {
return lastDurationOfFetchingQuery.get() == null ? 0 : lastDurationOfFetchingQuery.get().toMillis();
}
@Override
public long getLastBatchProcessingTimeInMilliseconds() {
return lastBatchProcessingDuration.get().toMillis();
}
@Override
public Long getMaxDurationOfFetchQueryInMilliseconds() {
return maxDurationOfFetchingQuery.get() == null ? 0 : maxDurationOfFetchingQuery.get().toMillis();
}
@Override
public Long getMaxCapturedDmlInBatch() {
return maxCapturedDmlCount.get();
}
@Override
public int getLastCapturedDmlCount() {
return lastCapturedDmlCount.get();
}
@Override
public long getTotalProcessedRows() {
return totalProcessedRows.get();
}
@Override
public long getTotalResultSetNextTimeInMilliseconds() {
return totalResultSetNextTime.get().toMillis();
}
@Override
public long getAverageBatchProcessingThroughput() {
if (totalBatchProcessingDuration.get().isZero()) {
return 0L;
}
return Math.round((totalCapturedDmlCount.floatValue() / totalBatchProcessingDuration.get().toMillis()) * 1000);
}
@Override
public long getLastBatchProcessingThroughput() {
if (lastBatchProcessingDuration.get().isZero()) {
return 0L;
}
return Math.round((lastCapturedDmlCount.floatValue() / lastBatchProcessingDuration.get().toMillis()) * 1000);
}
@Override
public long getFetchingQueryCount() {
return logMinerQueryCount.get();
}
@Override
public int getBatchSize() {
return batchSize.get();
}
@Override
public long getMillisecondToSleepBetweenMiningQuery() {
return millisecondToSleepBetweenMiningQuery.get();
}
@Override
public boolean getRecordMiningHistory() {
return recordMiningHistory.get();
}
@Override
public int getHoursToKeepTransactionInBuffer() {
return hoursToKeepTransaction.get();
}
@Override
public long getMaxBatchProcessingThroughput() {
return maxBatchProcessingThroughput.get();
}
@Override
public long getNetworkConnectionProblemsCounter() {
return networkConnectionProblemsCounter.get();
}
@Override
public long getTotalParseTimeInMilliseconds() {
return totalParseTime.get().toMillis();
}
public void addCurrentParseTime(Duration currentParseTime) {
totalParseTime.accumulateAndGet(currentParseTime, Duration::plus);
}
@Override
public long getTotalMiningSessionStartTimeInMilliseconds() {
return totalStartLogMiningSessionDuration.get().toMillis();
}
public void addCurrentMiningSessionStart(Duration currentStartLogMiningSession) {
lastStartLogMiningSessionDuration.set(currentStartLogMiningSession);
if (currentStartLogMiningSession.compareTo(maxStartingLogMiningSessionDuration.get()) > 0) {
maxStartingLogMiningSessionDuration.set(currentStartLogMiningSession);
}
totalStartLogMiningSessionDuration.accumulateAndGet(currentStartLogMiningSession, Duration::plus);
}
@Override
public long getLastMiningSessionStartTimeInMilliseconds() {
return lastStartLogMiningSessionDuration.get().toMillis();
}
@Override
public long getMaxMiningSessionStartTimeInMilliseconds() {
return maxStartingLogMiningSessionDuration.get().toMillis();
}
@Override
public long getTotalProcessingTimeInMilliseconds() {
return totalProcessingTime.get().toMillis();
}
@Override
public long getMinBatchProcessingTimeInMilliseconds() {
return minBatchProcessingTime.get().toMillis();
}
@Override
public long getMaxBatchProcessingTimeInMilliseconds() {
return maxBatchProcessingTime.get().toMillis();
}
public void setCurrentBatchProcessingTime(Duration currentBatchProcessingTime) {
totalProcessingTime.accumulateAndGet(currentBatchProcessingTime, Duration::plus);
}
public void addCurrentResultSetNext(Duration currentNextTime) {
totalResultSetNextTime.accumulateAndGet(currentNextTime, Duration::plus);
}
public void addProcessedRows(Long rows) {
totalProcessedRows.getAndAdd(rows);
}
@Override
public void setBatchSize(int size) {
if (size >= batchSizeMin && size <= batchSizeMax) {
batchSize.set(size);
}
}
@Override
public void setMillisecondToSleepBetweenMiningQuery(long milliseconds) {
if (milliseconds >= sleepTimeMin && milliseconds < sleepTimeMax) {
millisecondToSleepBetweenMiningQuery.set(milliseconds);
}
}
@Override
public void changeSleepingTime(boolean increment) {
long sleepTime = millisecondToSleepBetweenMiningQuery.get();
if (increment && sleepTime < sleepTimeMax) {
sleepTime = millisecondToSleepBetweenMiningQuery.addAndGet(sleepTimeIncrement);
}
else if (sleepTime > sleepTimeMin) {
sleepTime = millisecondToSleepBetweenMiningQuery.addAndGet(-sleepTimeIncrement);
}
LOGGER.debug("Updating sleep time window. Sleep time {}. Min sleep time {}. Max sleep time {}.", sleepTime, sleepTimeMin, sleepTimeMax);
}
@Override
public void changeBatchSize(boolean increment, boolean lobEnabled) {
int currentBatchSize = batchSize.get();
if (increment && currentBatchSize < batchSizeMax) {
currentBatchSize = batchSize.addAndGet(batchSizeMin);
}
else if (currentBatchSize > batchSizeMin) {
currentBatchSize = batchSize.addAndGet(-batchSizeMin);
}
if (currentBatchSize == batchSizeMax) {
if (!lobEnabled) {
LOGGER.info("LogMiner is now using the maximum batch size {}. This could be indicative of large SCN gaps", currentBatchSize);
}
else {
LOGGER.debug("LogMiner is now using the maximum batch size {}.", currentBatchSize);
}
}
else {
LOGGER.debug("Updating batch size window. Batch size {}. Min batch size {}. Max batch size {}.", currentBatchSize, batchSizeMin, batchSizeMax);
}
}
// transactional buffer metrics
@Override
public long getNumberOfActiveTransactions() {
return activeTransactions.get();
}
@Override
public long getNumberOfRolledBackTransactions() {
return rolledBackTransactions.get();
}
@Override
public long getNumberOfCommittedTransactions() {
return committedTransactions.get();
}
@Override
public long getCommitThroughput() {
long timeSpent = Duration.between(startTime, clock.instant()).toMillis();
return committedTransactions.get() * MILLIS_PER_SECOND / (timeSpent != 0 ? timeSpent : 1);
}
@Override
public long getRegisteredDmlCount() {
return registeredDmlCount.get();
}
@Override
public String getOldestScn() {
return oldestScn.get().toString();
}
@Override
public String getCommittedScn() {
return committedScn.get().toString();
}
@Override
public String getOffsetScn() {
return offsetScn.get().toString();
}
@Override
public long getLagFromSourceInMilliseconds() {
return lagFromTheSourceDuration.get().toMillis();
}
@Override
public long getMaxLagFromSourceInMilliseconds() {
return maxLagFromTheSourceDuration.get().toMillis();
}
@Override
public long getMinLagFromSourceInMilliseconds() {
return minLagFromTheSourceDuration.get().toMillis();
}
@Override
public Set<String> getAbandonedTransactionIds() {
return abandonedTransactionIds.get();
}
@Override
public Set<String> getRolledBackTransactionIds() {
return rolledBackTransactionIds.get();
}
@Override
public long getLastCommitDurationInMilliseconds() {
return lastCommitDuration.get().toMillis();
}
@Override
public long getMaxCommitDurationInMilliseconds() {
return maxCommitDuration.get().toMillis();
}
@Override
public int getErrorCount() {
return errorCount.get();
}
@Override
public int getWarningCount() {
return warningCount.get();
}
@Override
public int getScnFreezeCount() {
return scnFreezeCount.get();
}
@Override
public int getUnparsableDdlCount() {
return unparsableDdlCount.get();
}
public void setOldestScn(Scn scn) {
oldestScn.set(scn);
}
public void setCommittedScn(Scn scn) {
committedScn.set(scn);
}
public void setOffsetScn(Scn scn) {
offsetScn.set(scn);
}
public void setActiveTransactions(long activeTransactionCount) {
activeTransactions.set(activeTransactionCount);
}
public void incrementRolledBackTransactions() {
rolledBackTransactions.incrementAndGet();
}
public void incrementCommittedTransactions() {
committedTransactions.incrementAndGet();
}
public void incrementRegisteredDmlCount() {
registeredDmlCount.incrementAndGet();
}
public void incrementCommittedDmlCount(long counter) {
committedDmlCount.getAndAdd(counter);
}
public void incrementErrorCount() {
errorCount.incrementAndGet();
}
public void incrementWarningCount() {
warningCount.incrementAndGet();
}
public void incrementScnFreezeCount() {
scnFreezeCount.incrementAndGet();
}
public void addAbandonedTransactionId(String transactionId) {
if (transactionId != null) {
abandonedTransactionIds.get().add(transactionId);
}
}
public void addRolledBackTransactionId(String transactionId) {
if (transactionId != null) {
rolledBackTransactionIds.get().add(transactionId);
}
}
public void setLastCommitDuration(Duration lastDuration) {
lastCommitDuration.set(lastDuration);
if (lastDuration.toMillis() > maxCommitDuration.get().toMillis()) {
maxCommitDuration.set(lastDuration);
}
}
/**
* Calculates the time difference between the database server and the connector.
* Along with the time difference also the offset of the database server time to UTC is stored.
* Both values are required to calculate lag metrics.
*
* @param databaseSystemTime the system time (<code>SYSTIMESTAMP</code>) of the database
*/
public void calculateTimeDifference(OffsetDateTime databaseSystemTime) {
int offsetSeconds = databaseSystemTime.getOffset().getTotalSeconds();
this.offsetSeconds.set(offsetSeconds);
LOGGER.trace("Timezone offset of database system time is {} seconds", offsetSeconds);
Instant now = clock.instant();
long timeDiffMillis = Duration.between(databaseSystemTime.toInstant(), now).toMillis();
this.timeDifference.set(timeDiffMillis);
LOGGER.trace("Current time {} ms, database difference {} ms", now.toEpochMilli(), timeDiffMillis);
}
public void calculateLagMetrics(Instant changeTime) {
if (changeTime != null) {
final Instant correctedChangeTime = changeTime.plusMillis(timeDifference.longValue()).minusSeconds(offsetSeconds.longValue());
final Duration lag = Duration.between(correctedChangeTime, clock.instant()).abs();
lagFromTheSourceDuration.set(lag);
if (maxLagFromTheSourceDuration.get().toMillis() < lag.toMillis()) {
maxLagFromTheSourceDuration.set(lag);
}
if (minLagFromTheSourceDuration.get().toMillis() > lag.toMillis()) {
minLagFromTheSourceDuration.set(lag);
}
}
}
public void incrementUnparsableDdlCount() {
unparsableDdlCount.incrementAndGet();
}
@Override
public String toString() {
return "OracleStreamingChangeEventSourceMetrics{" +
"currentScn=" + currentScn +
", oldestScn=" + oldestScn.get() +
", committedScn=" + committedScn.get() +
", offsetScn=" + offsetScn.get() +
", logMinerQueryCount=" + logMinerQueryCount +
", totalProcessedRows=" + totalProcessedRows +
", totalCapturedDmlCount=" + totalCapturedDmlCount +
", totalDurationOfFetchingQuery=" + totalDurationOfFetchingQuery +
", lastCapturedDmlCount=" + lastCapturedDmlCount +
", lastDurationOfFetchingQuery=" + lastDurationOfFetchingQuery +
", maxCapturedDmlCount=" + maxCapturedDmlCount +
", maxDurationOfFetchingQuery=" + maxDurationOfFetchingQuery +
", totalBatchProcessingDuration=" + totalBatchProcessingDuration +
", lastBatchProcessingDuration=" + lastBatchProcessingDuration +
", maxBatchProcessingDuration=" + maxBatchProcessingDuration +
", maxBatchProcessingThroughput=" + maxBatchProcessingThroughput +
", currentLogFileName=" + currentLogFileName +
", minLogFilesMined=" + minimumLogsMined +
", maxLogFilesMined=" + maximumLogsMined +
", redoLogStatus=" + redoLogStatus +
", switchCounter=" + switchCounter +
", batchSize=" + batchSize +
", millisecondToSleepBetweenMiningQuery=" + millisecondToSleepBetweenMiningQuery +
", recordMiningHistory=" + recordMiningHistory +
", hoursToKeepTransaction=" + hoursToKeepTransaction +
", networkConnectionProblemsCounter" + networkConnectionProblemsCounter +
", batchSizeDefault=" + batchSizeDefault +
", batchSizeMin=" + batchSizeMin +
", batchSizeMax=" + batchSizeMax +
", sleepTimeDefault=" + sleepTimeDefault +
", sleepTimeMin=" + sleepTimeMin +
", sleepTimeMax=" + sleepTimeMax +
", sleepTimeIncrement=" + sleepTimeIncrement +
", totalParseTime=" + totalParseTime +
", totalStartLogMiningSessionDuration=" + totalStartLogMiningSessionDuration +
", lastStartLogMiningSessionDuration=" + lastStartLogMiningSessionDuration +
", maxStartLogMiningSessionDuration=" + maxStartingLogMiningSessionDuration +
", totalProcessTime=" + totalProcessingTime +
", minBatchProcessTime=" + minBatchProcessingTime +
", maxBatchProcessTime=" + maxBatchProcessingTime +
", totalResultSetNextTime=" + totalResultSetNextTime +
", lagFromTheSource=Duration" + lagFromTheSourceDuration.get() +
", maxLagFromTheSourceDuration=" + maxLagFromTheSourceDuration.get() +
", minLagFromTheSourceDuration=" + minLagFromTheSourceDuration.get() +
", lastCommitDuration=" + lastCommitDuration +
", maxCommitDuration=" + maxCommitDuration +
", activeTransactions=" + activeTransactions.get() +
", rolledBackTransactions=" + rolledBackTransactions.get() +
", committedTransactions=" + committedTransactions.get() +
", abandonedTransactionIds=" + abandonedTransactionIds.get() +
", rolledbackTransactionIds=" + rolledBackTransactionIds.get() +
", registeredDmlCount=" + registeredDmlCount.get() +
", committedDmlCount=" + committedDmlCount.get() +
", errorCount=" + errorCount.get() +
", warningCount=" + warningCount.get() +
", scnFreezeCount=" + scnFreezeCount.get() +
", unparsableDdlCount=" + unparsableDdlCount.get() +
'}';
}
}
| DBZ-3664 Wording fix | debezium-connector-oracle/src/main/java/io/debezium/connector/oracle/OracleStreamingChangeEventSourceMetrics.java | DBZ-3664 Wording fix | <ide><path>ebezium-connector-oracle/src/main/java/io/debezium/connector/oracle/OracleStreamingChangeEventSourceMetrics.java
<ide>
<ide> if (currentBatchSize == batchSizeMax) {
<ide> if (!lobEnabled) {
<del> LOGGER.info("LogMiner is now using the maximum batch size {}. This could be indicative of large SCN gaps", currentBatchSize);
<add> LOGGER.info("The connector is now using the maximum batch size {} when querying the LogMiner view. This could be indicative of large SCN gaps", currentBatchSize);
<ide> }
<ide> else {
<del> LOGGER.debug("LogMiner is now using the maximum batch size {}.", currentBatchSize);
<add> LOGGER.debug("The connector is now using the maximum batch size {} when querying the LogMiner view.", currentBatchSize);
<ide> }
<ide> }
<ide> else { |
|
Java | mit | 0c17cac11ca3078a9c930f82537ec1dd60596d5e | 0 | tdd-pingis/tdd-pingpong,tdd-pingis/tdd-pingpong,Heliozoa/tdd-pingpong,Heliozoa/tdd-pingpong,tdd-pingis/tdd-pingpong,tdd-pingis/tdd-pingpong,Heliozoa/tdd-pingpong,Heliozoa/tdd-pingpong | package pingis.controllers;
import static org.hamcrest.CoreMatchers.containsString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;
import pingis.config.OAuthProperties;
import pingis.config.SecurityConfig;
import pingis.entities.Challenge;
import pingis.entities.ChallengeType;
import pingis.entities.Task;
import pingis.entities.TaskInstance;
import pingis.entities.TaskType;
import pingis.entities.User;
import pingis.entities.sandbox.Submission;
import pingis.services.ChallengeService;
import pingis.services.EditorService;
import pingis.services.TaskInstanceService;
import pingis.services.TaskService;
import pingis.services.UserService;
import pingis.services.sandbox.SandboxService;
import pingis.utils.EditorTabData;
@RunWith(SpringRunner.class)
@WebMvcTest(TaskController.class)
@ContextConfiguration(classes = {TaskController.class, SecurityConfig.class, OAuthProperties.class})
@WebAppConfiguration
public class TaskControllerTest {
@Autowired
WebApplicationContext context;
private MockMvc mvc;
@MockBean
private SandboxService sandboxServiceMock;
@MockBean
private ChallengeService challengeServiceMock;
@MockBean
private TaskInstanceService taskInstanceServiceMock;
@MockBean
private TaskService taskServiceMock;
@MockBean
private EditorService editorServiceMock;
@MockBean
private UserService userServiceMock;
@Captor
private ArgumentCaptor<Map<String, byte[]>> packagingArgCaptor;
private Challenge challenge;
private Task testTask;
private Task implementationTask;
private TaskInstance testTaskInstance;
private TaskInstance implTaskInstance;
private User testUser;
private Submission submission;
@Before
public void setUp() {
testUser = new User(1, "TESTUSER", 1);
challenge = new Challenge("Calculator", testUser,
"Simple calculator");
testTask = new Task(1,
TaskType.TEST, testUser, "CalculatorAddition",
"Implement addition", "return 1+1;", 1, 1);
implementationTask = new Task(2,
TaskType.IMPLEMENTATION, testUser, "implement addition",
"implement addition", "public test", 1, 1);
testTaskInstance
= new TaskInstance(testUser, "", testTask);
implTaskInstance = new TaskInstance(testUser, "",
implementationTask);
testTask.setChallenge(challenge);
challenge.addTask(implementationTask);
implementationTask.setChallenge(challenge);
submission = new Submission();
submission.setId(UUID.randomUUID());
MockitoAnnotations.initMocks(this);
this.mvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
}
@Test
public void givenTaskWhenGetTestTask() throws Exception {
when(taskInstanceServiceMock.findOne(testTaskInstance.getId()))
.thenReturn(testTaskInstance);
Map<String, EditorTabData> tabData = this
.generateTabData(implTaskInstance, testTaskInstance);
when(editorServiceMock.generateEditorContents(testTaskInstance)).thenReturn(tabData);
String uri = "/task/" + testTaskInstance.getId();
performSimpleGetRequestAndFindContent(uri, "task", testTask.getCodeStub());
verify(taskInstanceServiceMock, times(1)).findOne(testTaskInstance.getId());
verify(editorServiceMock, times(1))
.generateEditorContents(testTaskInstance);
verifyNoMoreInteractions(taskInstanceServiceMock);
verifyNoMoreInteractions(editorServiceMock);
}
@Test
public void givenTaskWhenGetImplementationTask() throws Exception {
User testUser = new User(1, "TESTUSER", 1);
when(taskInstanceServiceMock.findOne(implTaskInstance.getId()))
.thenReturn(implTaskInstance);
Map<String, EditorTabData> tabData = generateTabData(implTaskInstance, testTaskInstance);
when(editorServiceMock.generateEditorContents(implTaskInstance)).thenReturn(tabData);
String uri = "/task/" + implTaskInstance.getId();
performSimpleGetRequestAndFindContent(uri, "task", implementationTask.getCodeStub());
verify(taskInstanceServiceMock, times(1)).findOne(implTaskInstance.getId());
verify(editorServiceMock, times(1))
.generateEditorContents(implTaskInstance);
verifyNoMoreInteractions(taskInstanceServiceMock);
verifyNoMoreInteractions(editorServiceMock);
}
private Map<String, EditorTabData> generateTabData(TaskInstance implTaskInstance,
TaskInstance testTaskInstance) {
Map<String, EditorTabData> tabData = new LinkedHashMap<String, EditorTabData>();
EditorTabData tab1 = new EditorTabData("Implement code here",
implTaskInstance.getTask().getCodeStub());
EditorTabData tab2 = new EditorTabData("Test to fulfill",
testTaskInstance.getTask().getCodeStub());
tabData.put("editor1", tab1);
tabData.put("editor2", tab2);
return tabData;
}
@Test
public void submitTestTask() throws Exception {
String submissionCode = "/* this is a test */";
when(taskInstanceServiceMock.findOne(testTaskInstance.getId())).thenReturn(testTaskInstance);
when(challengeServiceMock.findOne(challenge.getId())).thenReturn(challenge);
when(taskServiceMock.findTaskInChallenge(challenge.getId(), implementationTask.getIndex()))
.thenReturn(implementationTask);
when(taskServiceMock.getCorrespondingTask(testTask)).thenReturn(implementationTask);
when(sandboxServiceMock.submit(Mockito.any(), Mockito.any())).thenReturn(submission);
mvc.perform(post("/task")
.param("submissionCode", submissionCode)
.param("taskInstanceId", Long.toString(implTaskInstance.getId())))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrlPattern("/feedback*"));
verify(taskInstanceServiceMock, times(1)).findOne(testTaskInstance.getId());
verify(taskInstanceServiceMock).updateTaskInstanceCode(testTaskInstance.getId(),
submissionCode);
verify(taskServiceMock).getCorrespondingTask(testTask);
verifyNoMoreInteractions(taskInstanceServiceMock);
verifyNoMoreInteractions(challengeServiceMock);
verifyNoMoreInteractions(taskServiceMock);
}
@Test
public void submitImplementationTask() throws Exception {
String submissionCode = "/* this is an implementation */";
when(taskInstanceServiceMock.findOne(implTaskInstance.getId())).thenReturn(implTaskInstance);
when(challengeServiceMock.findOne(challenge.getId())).thenReturn(challenge);
when(taskServiceMock.findTaskInChallenge(challenge.getId(), testTask.getIndex()))
.thenReturn(testTask);
when(taskServiceMock.getCorrespondingTask(implementationTask)).thenReturn(testTask);
when(sandboxServiceMock.submit(Mockito.any(), Mockito.any())).thenReturn(submission);
mvc.perform(post("/task")
.param("submissionCode", submissionCode)
.param("taskInstanceId", Long.toString(implTaskInstance.getId())))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrlPattern("/feedback*"));
verify(taskInstanceServiceMock, times(1)).findOne(implTaskInstance.getId());
verify(taskInstanceServiceMock).updateTaskInstanceCode(implTaskInstance.getId(),
submissionCode);
verify(taskServiceMock).getCorrespondingTask(implementationTask);
verifyNoMoreInteractions(taskInstanceServiceMock);
verifyNoMoreInteractions(challengeServiceMock);
verifyNoMoreInteractions(taskServiceMock);
}
@Test
public void givenErrorWhenGetNonExistentTask() throws Exception {
when(taskInstanceServiceMock.findOne(123))
.thenReturn(null);
mvc.perform(get("/task/123"))
.andExpect(status().isOk())
.andExpect(view().name("error"));
verify(taskInstanceServiceMock, times(1)).findOne(123);
verifyNoMoreInteractions(taskInstanceServiceMock);
verifyNoMoreInteractions(editorServiceMock);
}
private void performSimpleGetRequestAndFindContent(String uri,
String viewName,
String expectedContent) throws Exception {
mvc.perform(get(uri))
.andExpect(status().isOk())
.andExpect(view().name(viewName))
.andExpect(content().string(containsString(expectedContent)));
}
@Test
public void nextTaskReturnsNextTaskView() throws Exception {
Long challengeId = 678L;
List<Task> testTasks = new ArrayList<Task>();
MultiValueMap<Task, TaskInstance> implementationTaskInstances = new LinkedMultiValueMap<>();
when(challengeServiceMock.findOne(any())).thenReturn(mock(Challenge.class));
when(taskServiceMock.filterTasksByUser(any(), any())).thenReturn(testTasks);
when(taskServiceMock.getAvailableTestTaskInstances(any(), any()))
.thenReturn(implementationTaskInstances);
mvc.perform(get("/nextTask/" + challengeId))
.andExpect(status().isOk())
.andExpect(view().name("nexttask"))
.andExpect(model().attributeExists("challenge"))
.andExpect(model().attributeExists("testTasks"))
.andExpect(model().attributeExists("implementationTaskInstances"));
verify(challengeServiceMock).findOne(678L);
}
@Test
public void newImplementationTaskInstanceRedirectsToTask() throws Exception {
Long taskId = 123L;
Long testTaskInstanceId = 555L;
Long newTaskInstanceId = 743L;
Task task = mock(Task.class);
when(task.getType()).thenReturn(TaskType.IMPLEMENTATION);
when(taskServiceMock.findOne(any())).thenReturn(task);
TaskInstance newTaskInstance = mock(TaskInstance.class);
when(newTaskInstance.getId()).thenReturn(newTaskInstanceId);
when(taskInstanceServiceMock.createEmpty(any(), any())).thenReturn(newTaskInstance);
TaskInstance testTaskInstance = mock(TaskInstance.class);
when(taskInstanceServiceMock.findOne(anyLong())).thenReturn(testTaskInstance);
when(newTaskInstance.getChallenge()).thenReturn(mock(Challenge.class));
mvc.perform(get("/newTaskInstance")
.param("taskId", taskId.toString())
.param("testTaskInstanceId", testTaskInstanceId.toString()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/task/" + newTaskInstanceId))
.andExpect(model().attribute("taskInstanceId", newTaskInstanceId.toString()));
verify(taskServiceMock).findOne(taskId);
verify(taskInstanceServiceMock).findOne(testTaskInstanceId);
verify(taskInstanceServiceMock).save(newTaskInstance);
verify(taskInstanceServiceMock).save(testTaskInstance);
}
@Test
public void newTestTaskInstanceRedirectsToTask() throws Exception {
Long taskId = 123L;
Long testTaskInstanceId = 234L;
Long newTaskInstanceId = 345L;
Task task = mock(Task.class);
when(task.getType()).thenReturn(TaskType.TEST);
when(taskServiceMock.findOne(any())).thenReturn(task);
TaskInstance newTaskInstance = mock(TaskInstance.class);
when(newTaskInstance.getId()).thenReturn(newTaskInstanceId);
when(taskInstanceServiceMock.createEmpty(any(), any())).thenReturn(newTaskInstance);
when(newTaskInstance.getChallenge()).thenReturn(mock(Challenge.class));
mvc.perform(get("/newTaskInstance")
.param("taskId", taskId.toString())
.param("testTaskInstanceId", testTaskInstanceId.toString()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/task/" + newTaskInstanceId))
.andExpect(model().attribute("taskInstanceId", newTaskInstanceId.toString()));
verify(taskServiceMock).findOne(taskId);
verify(taskInstanceServiceMock, never()).save(any());
}
@Test
public void newArcadeTaskInstanceRedirectsToTask() throws Exception {
Long taskId = 123L;
Long testTaskInstanceId = 234L;
Long newTaskInstanceId = 345L;
Task task = mock(Task.class);
when(task.getType()).thenReturn(TaskType.TEST);
when(taskServiceMock.findOne(any())).thenReturn(task);
TaskInstance newTaskInstance = mock(TaskInstance.class);
when(newTaskInstance.getId()).thenReturn(newTaskInstanceId);
when(taskInstanceServiceMock.createEmpty(any(), any())).thenReturn(newTaskInstance);
Challenge challenge = mock(Challenge.class);
when(challenge.getType()).thenReturn(ChallengeType.ARCADE);
when(newTaskInstance.getChallenge()).thenReturn(challenge);
when(userServiceMock.getCurrentUser()).thenReturn(mock(User.class));
mvc.perform(get("/newTaskInstance")
.param("taskId", taskId.toString())
.param("testTaskInstanceId", testTaskInstanceId.toString()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/task/" + newTaskInstanceId))
.andExpect(model().attribute("taskInstanceId", newTaskInstanceId.toString()));
verify(taskServiceMock).findOne(taskId);
verify(taskInstanceServiceMock, never()).save(any());
verify(userServiceMock).save(any());
}
@Test
public void randomTaskRedirectsToRandomTask() throws Exception {
Long challengeId = 333L;
Challenge challenge = mock(Challenge.class);
when(challenge.getId()).thenReturn(challengeId);
when(challengeServiceMock.getRandomChallenge()).thenReturn(challenge);
mvc.perform(get("/randomTask"))
.andExpect(status().is3xxRedirection())
.andExpect(model().attribute("challengeId", challengeId.toString()))
.andExpect(redirectedUrlPattern("/randomTask/?*"));
}
@Test
public void randomTaskWithoutAvailableTaskRedirectsToUser() throws Exception {
when(taskServiceMock.noNextTaskAvailable(any(), any())).thenReturn(true);
mvc.perform(get("/randomTask/0"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/user"));
}
@Test
public void randomTaskWithTestTaskRedirectsToNewTaskInstance() throws Exception {
Long challengeId = 999L;
Long taskId = 237L;
Task task = mock(Task.class);
when(task.getId()).thenReturn(taskId);
when(challengeServiceMock.findOne(any())).thenReturn(mock(Challenge.class));
when(userServiceMock.getCurrentUser()).thenReturn(mock(User.class));
when(taskServiceMock.noNextTaskAvailable(any(), any())).thenReturn(false);
when(taskServiceMock.getRandomTaskType()).thenReturn(TaskType.TEST);
when(taskServiceMock.hasNextTestTaskAvailable(any(), any())).thenReturn(true);
when(taskServiceMock.getRandomTestTask(any(), any())).thenReturn(task);
mvc.perform(get("/randomTask/0")
.param("challengeId", challengeId.toString()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrlPattern("/newTaskInstance?*"))
.andExpect(model().attribute("taskId", taskId.toString()))
.andExpect(model().attribute("testTaskInstanceId", "0"));
verify(taskServiceMock).getRandomTestTask(any(), any());
}
@Test
public void randomTaskWithImplementationTaskRedirectsToNewTaskInstance() throws Exception {
Long challengeId = 998L;
Long taskId = 337L;
Long taskInstanceId = 222L;
Task task = mock(Task.class);
when(task.getId()).thenReturn(taskId);
TaskInstance taskInstance = mock(TaskInstance.class);
when(taskInstance.getId()).thenReturn(taskInstanceId);
when(challengeServiceMock.findOne(any())).thenReturn(mock(Challenge.class));
when(userServiceMock.getCurrentUser()).thenReturn(mock(User.class));
when(taskServiceMock.noNextTaskAvailable(any(), any())).thenReturn(false);
when(taskServiceMock.hasNextImplTaskAvailable(any(), any())).thenReturn(true);
when(taskServiceMock.getRandomTaskType()).thenReturn(TaskType.IMPLEMENTATION);
when(taskServiceMock.getRandomImplTask(any(), any())).thenReturn(task);
when(taskServiceMock.getRandomTaskInstance(any(), any(), any())).thenReturn(taskInstance);
mvc.perform(get("/randomTask/0")
.param("challengeId", challengeId.toString()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrlPattern("/newTaskInstance?*"))
.andExpect(model().attribute("taskId", taskId.toString()))
.andExpect(model().attribute("testTaskInstanceId", taskInstanceId.toString()));
verify(taskServiceMock).getRandomImplTask(any(), any());
}
}
| src/test/java/pingis/controllers/TaskControllerTest.java | package pingis.controllers;
import static org.hamcrest.CoreMatchers.containsString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;
import pingis.config.OAuthProperties;
import pingis.config.SecurityConfig;
import pingis.entities.Challenge;
import pingis.entities.Task;
import pingis.entities.TaskInstance;
import pingis.entities.TaskType;
import pingis.entities.User;
import pingis.entities.sandbox.Submission;
import pingis.services.ChallengeService;
import pingis.services.EditorService;
import pingis.services.TaskInstanceService;
import pingis.services.TaskService;
import pingis.services.UserService;
import pingis.services.sandbox.SandboxService;
import pingis.utils.EditorTabData;
@RunWith(SpringRunner.class)
@WebMvcTest(TaskController.class)
@ContextConfiguration(classes = {TaskController.class, SecurityConfig.class, OAuthProperties.class})
@WebAppConfiguration
public class TaskControllerTest {
@Autowired
WebApplicationContext context;
private MockMvc mvc;
@MockBean
private SandboxService sandboxServiceMock;
@MockBean
private ChallengeService challengeServiceMock;
@MockBean
private TaskInstanceService taskInstanceServiceMock;
@MockBean
private TaskService taskServiceMock;
@MockBean
private EditorService editorServiceMock;
@MockBean
private UserService userServiceMock;
@Captor
private ArgumentCaptor<Map<String, byte[]>> packagingArgCaptor;
private Challenge challenge;
private Task testTask;
private Task implementationTask;
private TaskInstance testTaskInstance;
private TaskInstance implTaskInstance;
private User testUser;
private Submission submission;
@Before
public void setUp() {
testUser = new User(1, "TESTUSER", 1);
challenge = new Challenge("Calculator", testUser,
"Simple calculator");
testTask = new Task(1,
TaskType.TEST, testUser, "CalculatorAddition",
"Implement addition", "return 1+1;", 1, 1);
implementationTask = new Task(2,
TaskType.IMPLEMENTATION, testUser, "implement addition",
"implement addition", "public test", 1, 1);
testTaskInstance
= new TaskInstance(testUser, "", testTask);
implTaskInstance = new TaskInstance(testUser, "",
implementationTask);
testTask.setChallenge(challenge);
challenge.addTask(implementationTask);
implementationTask.setChallenge(challenge);
submission = new Submission();
submission.setId(UUID.randomUUID());
MockitoAnnotations.initMocks(this);
this.mvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
}
@Test
public void givenTaskWhenGetTestTask() throws Exception {
when(taskInstanceServiceMock.findOne(testTaskInstance.getId()))
.thenReturn(testTaskInstance);
Map<String, EditorTabData> tabData = this
.generateTabData(implTaskInstance, testTaskInstance);
when(editorServiceMock.generateEditorContents(testTaskInstance)).thenReturn(tabData);
String uri = "/task/" + testTaskInstance.getId();
performSimpleGetRequestAndFindContent(uri, "task", testTask.getCodeStub());
verify(taskInstanceServiceMock, times(1)).findOne(testTaskInstance.getId());
verify(editorServiceMock, times(1))
.generateEditorContents(testTaskInstance);
verifyNoMoreInteractions(taskInstanceServiceMock);
verifyNoMoreInteractions(editorServiceMock);
}
@Test
public void givenTaskWhenGetImplementationTask() throws Exception {
User testUser = new User(1, "TESTUSER", 1);
when(taskInstanceServiceMock.findOne(implTaskInstance.getId()))
.thenReturn(implTaskInstance);
Map<String, EditorTabData> tabData = generateTabData(implTaskInstance, testTaskInstance);
when(editorServiceMock.generateEditorContents(implTaskInstance)).thenReturn(tabData);
String uri = "/task/" + implTaskInstance.getId();
performSimpleGetRequestAndFindContent(uri, "task", implementationTask.getCodeStub());
verify(taskInstanceServiceMock, times(1)).findOne(implTaskInstance.getId());
verify(editorServiceMock, times(1))
.generateEditorContents(implTaskInstance);
verifyNoMoreInteractions(taskInstanceServiceMock);
verifyNoMoreInteractions(editorServiceMock);
}
private Map<String, EditorTabData> generateTabData(TaskInstance implTaskInstance,
TaskInstance testTaskInstance) {
Map<String, EditorTabData> tabData = new LinkedHashMap<String, EditorTabData>();
EditorTabData tab1 = new EditorTabData("Implement code here",
implTaskInstance.getTask().getCodeStub());
EditorTabData tab2 = new EditorTabData("Test to fulfill",
testTaskInstance.getTask().getCodeStub());
tabData.put("editor1", tab1);
tabData.put("editor2", tab2);
return tabData;
}
@Test
public void submitTestTask() throws Exception {
String submissionCode = "/* this is a test */";
when(taskInstanceServiceMock.findOne(testTaskInstance.getId())).thenReturn(testTaskInstance);
when(challengeServiceMock.findOne(challenge.getId())).thenReturn(challenge);
when(taskServiceMock.findTaskInChallenge(challenge.getId(), implementationTask.getIndex()))
.thenReturn(implementationTask);
when(taskServiceMock.getCorrespondingTask(testTask)).thenReturn(implementationTask);
when(sandboxServiceMock.submit(Mockito.any(), Mockito.any())).thenReturn(submission);
mvc.perform(post("/task")
.param("submissionCode", submissionCode)
.param("taskInstanceId", Long.toString(implTaskInstance.getId())))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrlPattern("/feedback*"));
verify(taskInstanceServiceMock, times(1)).findOne(testTaskInstance.getId());
verify(taskInstanceServiceMock).updateTaskInstanceCode(testTaskInstance.getId(),
submissionCode);
verify(taskServiceMock).getCorrespondingTask(testTask);
verifyNoMoreInteractions(taskInstanceServiceMock);
verifyNoMoreInteractions(challengeServiceMock);
verifyNoMoreInteractions(taskServiceMock);
}
@Test
public void submitImplementationTask() throws Exception {
String submissionCode = "/* this is an implementation */";
when(taskInstanceServiceMock.findOne(implTaskInstance.getId())).thenReturn(implTaskInstance);
when(challengeServiceMock.findOne(challenge.getId())).thenReturn(challenge);
when(taskServiceMock.findTaskInChallenge(challenge.getId(), testTask.getIndex()))
.thenReturn(testTask);
when(taskServiceMock.getCorrespondingTask(implementationTask)).thenReturn(testTask);
when(sandboxServiceMock.submit(Mockito.any(), Mockito.any())).thenReturn(submission);
mvc.perform(post("/task")
.param("submissionCode", submissionCode)
.param("taskInstanceId", Long.toString(implTaskInstance.getId())))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrlPattern("/feedback*"));
verify(taskInstanceServiceMock, times(1)).findOne(implTaskInstance.getId());
verify(taskInstanceServiceMock).updateTaskInstanceCode(implTaskInstance.getId(),
submissionCode);
verify(taskServiceMock).getCorrespondingTask(implementationTask);
verifyNoMoreInteractions(taskInstanceServiceMock);
verifyNoMoreInteractions(challengeServiceMock);
verifyNoMoreInteractions(taskServiceMock);
}
@Test
public void givenErrorWhenGetNonExistentTask() throws Exception {
when(taskInstanceServiceMock.findOne(123))
.thenReturn(null);
mvc.perform(get("/task/123"))
.andExpect(status().isOk())
.andExpect(view().name("error"));
verify(taskInstanceServiceMock, times(1)).findOne(123);
verifyNoMoreInteractions(taskInstanceServiceMock);
verifyNoMoreInteractions(editorServiceMock);
}
private void performSimpleGetRequestAndFindContent(String uri,
String viewName,
String expectedContent) throws Exception {
mvc.perform(get(uri))
.andExpect(status().isOk())
.andExpect(view().name(viewName))
.andExpect(content().string(containsString(expectedContent)));
}
@Test
public void nextTaskReturnsNextTaskView() throws Exception {
Long challengeId = 678L;
Challenge challenge = mock(Challenge.class);
Iterator itr = mock(Iterator.class);
when(itr.hasNext()).thenReturn(false);
List testTasks = mock(List.class);
when(testTasks.iterator()).thenReturn(itr);
Set set = mock(Set.class);
when(set.iterator()).thenReturn(itr);
MultiValueMap implementationTaskInstances = mock(MultiValueMap.class);
when(implementationTaskInstances.keySet()).thenReturn(set);
when(challengeServiceMock.findOne(any())).thenReturn(mock(Challenge.class));
when(taskServiceMock.filterTasksByUser(any(), any())).thenReturn(testTasks);
when(taskServiceMock.getAvailableTestTaskInstances(any(), any()))
.thenReturn(implementationTaskInstances);
mvc.perform(get("/nextTask/" + challengeId))
.andExpect(status().isOk())
.andExpect(view().name("nexttask"))
.andExpect(model().attributeExists("challenge"))
.andExpect(model().attributeExists("testTasks"))
.andExpect(model().attributeExists("implementationTaskInstances"));
verify(challengeServiceMock).findOne(678L);
}
@Test
public void newImplementationTaskInstanceRedirectsToTask() throws Exception {
Long taskId = 123L;
Long testTaskInstanceId = 555L;
Long newTaskInstanceId = 743L;
Task task = mock(Task.class);
when(task.getType()).thenReturn(TaskType.IMPLEMENTATION);
when(taskServiceMock.findOne(any())).thenReturn(task);
TaskInstance newTaskInstance = mock(TaskInstance.class);
when(newTaskInstance.getId()).thenReturn(newTaskInstanceId);
when(taskInstanceServiceMock.createEmpty(any(), any())).thenReturn(newTaskInstance);
TaskInstance testTaskInstance = mock(TaskInstance.class);
when(taskInstanceServiceMock.findOne(anyLong())).thenReturn(testTaskInstance);
mvc.perform(get("/newTaskInstance")
.param("taskId", taskId.toString())
.param("testTaskInstanceId", testTaskInstanceId.toString()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/task/" + newTaskInstanceId))
.andExpect(model().attribute("taskInstanceId", newTaskInstanceId.toString()));
verify(taskServiceMock).findOne(taskId);
verify(taskInstanceServiceMock).findOne(testTaskInstanceId);
verify(taskInstanceServiceMock).save(newTaskInstance);
verify(taskInstanceServiceMock).save(testTaskInstance);
}
@Test
public void newTestTaskInstanceRedirectsToTask() throws Exception {
Long taskId = 123L;
Long testTaskInstanceId = 234L;
Long newTaskInstanceId = 345L;
Task task = mock(Task.class);
when(task.getType()).thenReturn(TaskType.TEST);
when(taskServiceMock.findOne(any())).thenReturn(task);
TaskInstance newTaskInstance = mock(TaskInstance.class);
when(newTaskInstance.getId()).thenReturn(newTaskInstanceId);
when(taskInstanceServiceMock.createEmpty(any(), any())).thenReturn(newTaskInstance);
mvc.perform(get("/newTaskInstance")
.param("taskId", taskId.toString())
.param("testTaskInstanceId", testTaskInstanceId.toString()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/task/" + newTaskInstanceId))
.andExpect(model().attribute("taskInstanceId", newTaskInstanceId.toString()));
verify(taskServiceMock).findOne(taskId);
verify(taskInstanceServiceMock, never()).save(any());
}
@Test
public void randomTaskRedirectsToRandomTask() throws Exception {
Long challengeId = 333L;
Challenge challenge = mock(Challenge.class);
when(challenge.getId()).thenReturn(challengeId);
when(challengeServiceMock.getRandomChallenge()).thenReturn(challenge);
mvc.perform(get("/randomTask"))
.andExpect(status().is3xxRedirection())
.andExpect(model().attribute("challengeId", challengeId.toString()))
.andExpect(redirectedUrlPattern("/randomTask/?*"));
}
@Test
public void randomTaskWithoutAvailableTaskRedirectsToUser() throws Exception {
when(taskServiceMock.noNextTaskAvailable(any(), any())).thenReturn(true);
mvc.perform(get("/randomTask/0"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/user"));
}
@Test
public void randomTaskWithTestTaskRedirectsToNewTaskInstance() throws Exception {
Long challengeId = 999L;
Long taskId = 237L;
Task task = mock(Task.class);
when(task.getId()).thenReturn(taskId);
when(challengeServiceMock.findOne(any())).thenReturn(mock(Challenge.class));
when(userServiceMock.getCurrentUser()).thenReturn(mock(User.class));
when(taskServiceMock.noNextTaskAvailable(any(), any())).thenReturn(false);
when(taskServiceMock.getRandomTaskType()).thenReturn(TaskType.TEST);
when(taskServiceMock.hasNextTestTaskAvailable(any(), any())).thenReturn(true);
when(taskServiceMock.getRandomTestTask(any(), any())).thenReturn(task);
mvc.perform(get("/randomTask/0")
.param("challengeId", challengeId.toString()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrlPattern("/newTaskInstance?*"))
.andExpect(model().attribute("taskId", taskId.toString()))
.andExpect(model().attribute("testTaskInstanceId", "0"));
verify(taskServiceMock).getRandomTestTask(any(), any());
}
@Test
public void randomTaskWithImplementationTaskRedirectsToNewTaskInstance() throws Exception {
Long challengeId = 998L;
Long taskId = 337L;
Long taskInstanceId = 222L;
Task task = mock(Task.class);
when(task.getId()).thenReturn(taskId);
TaskInstance taskInstance = mock(TaskInstance.class);
when(taskInstance.getId()).thenReturn(taskInstanceId);
when(challengeServiceMock.findOne(any())).thenReturn(mock(Challenge.class));
when(userServiceMock.getCurrentUser()).thenReturn(mock(User.class));
when(taskServiceMock.noNextTaskAvailable(any(), any())).thenReturn(false);
when(taskServiceMock.hasNextImplTaskAvailable(any(), any())).thenReturn(true);
when(taskServiceMock.getRandomTaskType()).thenReturn(TaskType.IMPLEMENTATION);
when(taskServiceMock.getRandomImplTask(any(), any())).thenReturn(task);
when(taskServiceMock.getRandomTaskInstance(any(), any(), any())).thenReturn(taskInstance);
mvc.perform(get("/randomTask/0")
.param("challengeId", challengeId.toString()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrlPattern("/newTaskInstance?*"))
.andExpect(model().attribute("taskId", taskId.toString()))
.andExpect(model().attribute("testTaskInstanceId", taskInstanceId.toString()));
verify(taskServiceMock).getRandomImplTask(any(), any());
}
}
| Fixed tests for unchecked operations and added a new test
| src/test/java/pingis/controllers/TaskControllerTest.java | Fixed tests for unchecked operations and added a new test | <ide><path>rc/test/java/pingis/controllers/TaskControllerTest.java
<ide> import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
<ide> import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
<ide>
<del>import java.util.Iterator;
<add>import java.util.ArrayList;
<ide> import java.util.LinkedHashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<del>import java.util.Set;
<ide> import java.util.UUID;
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide> import org.springframework.test.context.web.WebAppConfiguration;
<ide> import org.springframework.test.web.servlet.MockMvc;
<ide> import org.springframework.test.web.servlet.setup.MockMvcBuilders;
<add>import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<ide> import org.springframework.web.context.WebApplicationContext;
<ide> import pingis.config.OAuthProperties;
<ide> import pingis.config.SecurityConfig;
<ide> import pingis.entities.Challenge;
<add>import pingis.entities.ChallengeType;
<ide> import pingis.entities.Task;
<ide> import pingis.entities.TaskInstance;
<ide> import pingis.entities.TaskType;
<ide> public void nextTaskReturnsNextTaskView() throws Exception {
<ide> Long challengeId = 678L;
<ide>
<del> Challenge challenge = mock(Challenge.class);
<del>
<del> Iterator itr = mock(Iterator.class);
<del> when(itr.hasNext()).thenReturn(false);
<del>
<del> List testTasks = mock(List.class);
<del> when(testTasks.iterator()).thenReturn(itr);
<del>
<del> Set set = mock(Set.class);
<del> when(set.iterator()).thenReturn(itr);
<del>
<del> MultiValueMap implementationTaskInstances = mock(MultiValueMap.class);
<del> when(implementationTaskInstances.keySet()).thenReturn(set);
<add> List<Task> testTasks = new ArrayList<Task>();
<add>
<add> MultiValueMap<Task, TaskInstance> implementationTaskInstances = new LinkedMultiValueMap<>();
<ide>
<ide> when(challengeServiceMock.findOne(any())).thenReturn(mock(Challenge.class));
<ide> when(taskServiceMock.filterTasksByUser(any(), any())).thenReturn(testTasks);
<ide> TaskInstance testTaskInstance = mock(TaskInstance.class);
<ide> when(taskInstanceServiceMock.findOne(anyLong())).thenReturn(testTaskInstance);
<ide>
<add> when(newTaskInstance.getChallenge()).thenReturn(mock(Challenge.class));
<add>
<ide> mvc.perform(get("/newTaskInstance")
<ide> .param("taskId", taskId.toString())
<ide> .param("testTaskInstanceId", testTaskInstanceId.toString()))
<ide> when(newTaskInstance.getId()).thenReturn(newTaskInstanceId);
<ide> when(taskInstanceServiceMock.createEmpty(any(), any())).thenReturn(newTaskInstance);
<ide>
<add> when(newTaskInstance.getChallenge()).thenReturn(mock(Challenge.class));
<add>
<ide> mvc.perform(get("/newTaskInstance")
<ide> .param("taskId", taskId.toString())
<ide> .param("testTaskInstanceId", testTaskInstanceId.toString()))
<ide> verify(taskServiceMock).findOne(taskId);
<ide> verify(taskInstanceServiceMock, never()).save(any());
<ide> }
<add>
<add>
<add> @Test
<add> public void newArcadeTaskInstanceRedirectsToTask() throws Exception {
<add> Long taskId = 123L;
<add> Long testTaskInstanceId = 234L;
<add> Long newTaskInstanceId = 345L;
<add>
<add> Task task = mock(Task.class);
<add> when(task.getType()).thenReturn(TaskType.TEST);
<add> when(taskServiceMock.findOne(any())).thenReturn(task);
<add>
<add> TaskInstance newTaskInstance = mock(TaskInstance.class);
<add> when(newTaskInstance.getId()).thenReturn(newTaskInstanceId);
<add> when(taskInstanceServiceMock.createEmpty(any(), any())).thenReturn(newTaskInstance);
<add>
<add> Challenge challenge = mock(Challenge.class);
<add> when(challenge.getType()).thenReturn(ChallengeType.ARCADE);
<add> when(newTaskInstance.getChallenge()).thenReturn(challenge);
<add>
<add> when(userServiceMock.getCurrentUser()).thenReturn(mock(User.class));
<add>
<add> mvc.perform(get("/newTaskInstance")
<add> .param("taskId", taskId.toString())
<add> .param("testTaskInstanceId", testTaskInstanceId.toString()))
<add> .andExpect(status().is3xxRedirection())
<add> .andExpect(redirectedUrl("/task/" + newTaskInstanceId))
<add> .andExpect(model().attribute("taskInstanceId", newTaskInstanceId.toString()));
<add>
<add> verify(taskServiceMock).findOne(taskId);
<add> verify(taskInstanceServiceMock, never()).save(any());
<add> verify(userServiceMock).save(any());
<add> }
<add>
<ide>
<ide> @Test
<ide> public void randomTaskRedirectsToRandomTask() throws Exception { |
|
Java | apache-2.0 | 8bf5c23c97487e35ac2f1a5e8c88dc6a539a2d37 | 0 | bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud | package com.planet_ink.coffee_mud.Abilities.Skills;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2016-2018 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Skill_TailSwipe extends StdSkill
{
@Override
public String ID()
{
return "Skill_TailSwipe";
}
private final static String localizedName = CMLib.lang().L("Tail Swipe");
@Override
public String name()
{
return localizedName;
}
private static final String[] triggerStrings = I(new String[] { "TAILSWIPE" });
@Override
public int abstractQuality()
{
return Ability.QUALITY_MALICIOUS;
}
@Override
public String[] triggerStrings()
{
return triggerStrings;
}
@Override
protected int canAffectCode()
{
return 0;
}
@Override
protected int canTargetCode()
{
return Ability.CAN_MOBS;
}
@Override
public int classificationCode()
{
return Ability.ACODE_SKILL | Ability.DOMAIN_MARTIALLORE;
}
@Override
public int usageType()
{
return USAGE_MOVEMENT;
}
@Override
public long flags()
{
return Ability.FLAG_MOVING;
}
protected int enhancement = 0;
protected boolean doneTicking = false;
@Override
public int abilityCode()
{
return enhancement;
}
@Override
public void setAbilityCode(int newCode)
{
enhancement = newCode;
}
@Override
public void affectPhyStats(Physical affected, PhyStats affectableStats)
{
super.affectPhyStats(affected,affectableStats);
if(!doneTicking)
affectableStats.setDisposition(affectableStats.disposition()|PhyStats.IS_SITTING);
}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!(affected instanceof MOB))
return true;
final MOB mob=(MOB)affected;
if((doneTicking)&&(msg.amISource(mob)))
unInvoke();
else
if(msg.amISource(mob)&&(msg.sourceMinor()==CMMsg.TYP_STAND))
return false;
return true;
}
@Override
public void unInvoke()
{
if(!(affected instanceof MOB))
return;
final MOB mob=(MOB)affected;
if(canBeUninvoked())
doneTicking=true;
super.unInvoke();
if(canBeUninvoked() && (mob!=null))
{
final Room R=mob.location();
if((R!=null)&&(!mob.amDead()))
{
final CMMsg msg=CMClass.getMsg(mob,null,CMMsg.MSG_NOISYMOVEMENT,L("<S-NAME> regain(s) <S-HIS-HER> feet."));
if(R.okMessage(mob,msg)&&(!mob.amDead()))
{
R.send(mob,msg);
CMLib.commands().postStand(mob,true);
}
}
else
mob.tell(L("You regain your feet."));
}
}
@Override
public int castingQuality(MOB mob, Physical target)
{
if((mob!=null)&&(target!=null))
{
if(mob.isInCombat()&&(mob.rangeToTarget()>0))
return Ability.QUALITY_INDIFFERENT;
if(mob.charStats().getBodyPart(Race.BODY_TAIL)<=0)
return Ability.QUALITY_INDIFFERENT;
}
return super.castingQuality(mob,target);
}
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
if(mob.isInCombat()&&(mob.rangeToTarget()>1)&&(!auto))
{
mob.tell(L("You are too far away to tail swipe!"));
return false;
}
if(mob.charStats().getBodyPart(Race.BODY_TAIL)<=0)
{
mob.tell(L("You need a tail to do this."));
return false;
}
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
// now see if it worked
final int chance=(mob.charStats().getStat(CharStats.STAT_STRENGTH)-target.charStats().getStat(CharStats.STAT_DEXTERITY))*2;
final boolean success=proficiencyCheck(mob,chance,auto);
if(success)
{
invoker=mob;
final int topDamage=(adjustedLevel(mob,asLevel)/4)+1;
int damage=CMLib.dice().roll(1,topDamage,0);
final Room R=mob.location();
final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_JUSTICE|(auto?CMMsg.MASK_ALWAYS:0),null);
if((R!=null)&&(R.okMessage(mob,msg)))
{
R.send(mob,msg);
if(msg.value()>0)
damage = (int)Math.round(CMath.div(damage,2.0));
CMLib.combat().postDamage(mob,target,this,damage,
CMMsg.MASK_ALWAYS|CMMsg.MASK_SOUND|CMMsg.MASK_MOVE|CMMsg.TYP_JUSTICE,Weapon.TYPE_BASHING,
L("^F^<FIGHT^><S-NAME> <DAMAGE> <T-NAME> with a tail swipe!^</FIGHT^>^?@x1",CMLib.protocol().msp("bashed1.wav",30)));
int tripChance = (chance > 0) ? chance/2 : chance*2;
if((msg.value()<=0)
&&(CMLib.flags().isStanding(target))
&&(proficiencyCheck(mob,tripChance,auto)))
{
if(maliciousAffect(mob,target,asLevel,2,CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_JUSTICE|(auto?CMMsg.MASK_ALWAYS:0)) != null)
R.show(mob,target,CMMsg.MSG_OK_ACTION,L("<T-NAME> hit(s) the floor!"));
}
}
}
else
return maliciousFizzle(mob,target,L("<S-NAME> fail(s) to tail swipe <T-NAMESELF>."));
// return whether it worked
return success;
}
}
| com/planet_ink/coffee_mud/Abilities/Skills/Skill_TailSwipe.java | package com.planet_ink.coffee_mud.Abilities.Skills;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2016-2018 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Skill_TailSwipe extends StdSkill
{
@Override
public String ID()
{
return "Skill_TailSwipe";
}
private final static String localizedName = CMLib.lang().L("Tail Swipe");
@Override
public String name()
{
return localizedName;
}
private static final String[] triggerStrings = I(new String[] { "TAILSWIPE" });
@Override
public int abstractQuality()
{
return Ability.QUALITY_MALICIOUS;
}
@Override
public String[] triggerStrings()
{
return triggerStrings;
}
@Override
protected int canAffectCode()
{
return 0;
}
@Override
protected int canTargetCode()
{
return Ability.CAN_MOBS;
}
@Override
public int classificationCode()
{
return Ability.ACODE_SKILL | Ability.DOMAIN_MARTIALLORE;
}
@Override
public int usageType()
{
return USAGE_MOVEMENT;
}
@Override
public long flags()
{
return Ability.FLAG_MOVING;
}
protected int enhancement = 0;
protected boolean doneTicking = false;
@Override
public int abilityCode()
{
return enhancement;
}
@Override
public void setAbilityCode(int newCode)
{
enhancement = newCode;
}
@Override
public void affectPhyStats(Physical affected, PhyStats affectableStats)
{
super.affectPhyStats(affected,affectableStats);
if(!doneTicking)
affectableStats.setDisposition(affectableStats.disposition()|PhyStats.IS_SITTING);
}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!(affected instanceof MOB))
return true;
final MOB mob=(MOB)affected;
if((doneTicking)&&(msg.amISource(mob)))
unInvoke();
else
if(msg.amISource(mob)&&(msg.sourceMinor()==CMMsg.TYP_STAND))
return false;
return true;
}
@Override
public void unInvoke()
{
if(!(affected instanceof MOB))
return;
final MOB mob=(MOB)affected;
if(canBeUninvoked())
doneTicking=true;
super.unInvoke();
if(canBeUninvoked() && (mob!=null))
{
final Room R=mob.location();
if((R!=null)&&(!mob.amDead()))
{
final CMMsg msg=CMClass.getMsg(mob,null,CMMsg.MSG_NOISYMOVEMENT,L("<S-NAME> regain(s) <S-HIS-HER> feet."));
if(R.okMessage(mob,msg)&&(!mob.amDead()))
{
R.send(mob,msg);
CMLib.commands().postStand(mob,true);
}
}
else
mob.tell(L("You regain your feet."));
}
}
@Override
public int castingQuality(MOB mob, Physical target)
{
if((mob!=null)&&(target!=null))
{
if(mob.isInCombat()&&(mob.rangeToTarget()>0))
return Ability.QUALITY_INDIFFERENT;
if(mob.charStats().getBodyPart(Race.BODY_TAIL)<=0)
return Ability.QUALITY_INDIFFERENT;
}
return super.castingQuality(mob,target);
}
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
if(mob.isInCombat()&&(mob.rangeToTarget()>1)&&(!auto))
{
mob.tell(L("You are too far away to tail swipe!"));
return false;
}
if(mob.charStats().getBodyPart(Race.BODY_TAIL)<=0)
{
mob.tell(L("You need a tail to do this."));
return false;
}
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
// now see if it worked
final int chance=(mob.charStats().getStat(CharStats.STAT_STRENGTH)-target.charStats().getStat(CharStats.STAT_DEXTERITY))*2;
final boolean success=proficiencyCheck(mob,chance,auto);
if(success)
{
invoker=mob;
final int topDamage=(adjustedLevel(mob,asLevel)/4)+1;
int damage=CMLib.dice().roll(1,topDamage,0);
final Room R=mob.location();
final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_JUSTICE|(auto?CMMsg.MASK_ALWAYS:0),null);
if((R!=null)&&(R.okMessage(mob,msg)))
{
R.send(mob,msg);
if(msg.value()>0)
damage = (int)Math.round(CMath.div(damage,2.0));
CMLib.combat().postDamage(mob,target,this,damage,
CMMsg.MASK_ALWAYS|CMMsg.MASK_SOUND|CMMsg.MASK_MOVE|CMMsg.TYP_JUSTICE,Weapon.TYPE_BASHING,
L("^F^<FIGHT^><S-NAME> <DAMAGE> <T-NAME> with a tail swipe!^</FIGHT^>^?@x1",CMLib.protocol().msp("bashed1.wav",30)));
int tripChance = (chance > 0) ? chance/2 : chance*2;
if((msg.value()<=0)
&&(CMLib.flags().isStanding(target))
&&(proficiencyCheck(mob,tripChance,auto)))
{
if(maliciousAffect(mob,target,asLevel,2,CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_JUSTICE|(auto?CMMsg.MASK_ALWAYS:0)) != null)
R.show(mob,target,CMMsg.MSG_OK_ACTION,L("<S-NAME> hit(s) the floor!"));
}
}
}
else
return maliciousFizzle(mob,target,L("<S-NAME> fail(s) to tail swipe <T-NAMESELF>."));
// return whether it worked
return success;
}
}
| typo in tail swipe target
git-svn-id: 0cdf8356e41b2d8ccbb41bb76c82068fe80b2514@16337 0d6f1817-ed0e-0410-87c9-987e46238f29
| com/planet_ink/coffee_mud/Abilities/Skills/Skill_TailSwipe.java | typo in tail swipe target | <ide><path>om/planet_ink/coffee_mud/Abilities/Skills/Skill_TailSwipe.java
<ide> &&(proficiencyCheck(mob,tripChance,auto)))
<ide> {
<ide> if(maliciousAffect(mob,target,asLevel,2,CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_JUSTICE|(auto?CMMsg.MASK_ALWAYS:0)) != null)
<del> R.show(mob,target,CMMsg.MSG_OK_ACTION,L("<S-NAME> hit(s) the floor!"));
<add> R.show(mob,target,CMMsg.MSG_OK_ACTION,L("<T-NAME> hit(s) the floor!"));
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | 75094c0fac9886eeb5a9bfc127f867f761ed7ef4 | 0 | motlin/gs-collections,xingguang2013/gs-collections,goldmansachs/gs-collections,Pelumi/gs-collections,gabby2212/gs-collections,mix-juice001/gs-collections | /*
* Copyright 2014 Goldman Sachs.
*
* 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.gs.collections.impl.utility;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;
import com.gs.collections.api.RichIterable;
import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.function.Function0;
import com.gs.collections.api.block.function.Function2;
import com.gs.collections.api.block.function.Function3;
import com.gs.collections.api.block.procedure.Procedure2;
import com.gs.collections.api.collection.primitive.MutableBooleanCollection;
import com.gs.collections.api.collection.primitive.MutableByteCollection;
import com.gs.collections.api.collection.primitive.MutableCharCollection;
import com.gs.collections.api.collection.primitive.MutableDoubleCollection;
import com.gs.collections.api.collection.primitive.MutableFloatCollection;
import com.gs.collections.api.collection.primitive.MutableIntCollection;
import com.gs.collections.api.collection.primitive.MutableLongCollection;
import com.gs.collections.api.collection.primitive.MutableShortCollection;
import com.gs.collections.api.list.ImmutableList;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.map.MapIterable;
import com.gs.collections.api.map.MutableMap;
import com.gs.collections.api.multimap.Multimap;
import com.gs.collections.api.multimap.MutableMultimap;
import com.gs.collections.api.partition.PartitionIterable;
import com.gs.collections.api.set.MutableSet;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.api.tuple.Twin;
import com.gs.collections.impl.bag.mutable.HashBag;
import com.gs.collections.impl.block.factory.Comparators;
import com.gs.collections.impl.block.factory.Functions;
import com.gs.collections.impl.block.factory.Functions0;
import com.gs.collections.impl.block.factory.IntegerPredicates;
import com.gs.collections.impl.block.factory.ObjectIntProcedures;
import com.gs.collections.impl.block.factory.Predicates;
import com.gs.collections.impl.block.factory.Predicates2;
import com.gs.collections.impl.block.factory.PrimitiveFunctions;
import com.gs.collections.impl.block.factory.Procedures;
import com.gs.collections.impl.block.factory.StringFunctions;
import com.gs.collections.impl.block.function.AddFunction;
import com.gs.collections.impl.block.function.MaxSizeFunction;
import com.gs.collections.impl.block.function.MinSizeFunction;
import com.gs.collections.impl.block.predicate.PairPredicate;
import com.gs.collections.impl.block.procedure.CollectionAddProcedure;
import com.gs.collections.impl.factory.Lists;
import com.gs.collections.impl.factory.Maps;
import com.gs.collections.impl.factory.Sets;
import com.gs.collections.impl.list.Interval;
import com.gs.collections.impl.list.mutable.FastList;
import com.gs.collections.impl.list.mutable.primitive.BooleanArrayList;
import com.gs.collections.impl.list.mutable.primitive.ByteArrayList;
import com.gs.collections.impl.list.mutable.primitive.CharArrayList;
import com.gs.collections.impl.list.mutable.primitive.DoubleArrayList;
import com.gs.collections.impl.list.mutable.primitive.FloatArrayList;
import com.gs.collections.impl.list.mutable.primitive.IntArrayList;
import com.gs.collections.impl.list.mutable.primitive.LongArrayList;
import com.gs.collections.impl.list.mutable.primitive.ShortArrayList;
import com.gs.collections.impl.map.mutable.UnifiedMap;
import com.gs.collections.impl.math.IntegerSum;
import com.gs.collections.impl.math.Sum;
import com.gs.collections.impl.multimap.list.FastListMultimap;
import com.gs.collections.impl.set.mutable.UnifiedSet;
import com.gs.collections.impl.test.Verify;
import com.gs.collections.impl.tuple.Tuples;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static com.gs.collections.impl.factory.Iterables.*;
import static org.junit.Assert.*;
public class IterateTest
{
private MutableList<Iterable<Integer>> iterables;
@Before
public void setUp()
{
this.iterables = Lists.mutable.of();
this.iterables.add(Interval.oneTo(5).toList());
this.iterables.add(Interval.oneTo(5).toSet());
this.iterables.add(Interval.oneTo(5).toBag());
this.iterables.add(Interval.oneTo(5).toSortedSet());
this.iterables.add(Interval.oneTo(5).toSortedMap(i -> i, i -> i));
this.iterables.add(Interval.oneTo(5).toMap(i -> i, i -> i));
this.iterables.add(Interval.oneTo(5).addAllTo(new ArrayList<Integer>(5)));
this.iterables.add(Collections.unmodifiableList(new ArrayList<Integer>(Interval.oneTo(5))));
this.iterables.add(Collections.unmodifiableCollection(new ArrayList<Integer>(Interval.oneTo(5))));
this.iterables.add(Interval.oneTo(5));
this.iterables.add(Interval.oneTo(5).asLazy());
this.iterables.add(new IterableAdapter<Integer>(Interval.oneTo(5)));
}
@Test
public void addAllTo()
{
Verify.assertContainsAll(Iterate.addAllTo(FastList.newListWith(1, 2, 3), FastList.newList()), 1, 2, 3);
}
@Test
public void sizeOf()
{
Assert.assertEquals(5, Iterate.sizeOf(Interval.oneTo(5)));
Assert.assertEquals(5, Iterate.sizeOf(Interval.oneTo(5).toList()));
Assert.assertEquals(5, Iterate.sizeOf(Interval.oneTo(5).asLazy()));
Assert.assertEquals(3, Iterate.sizeOf(UnifiedMap.newWithKeysValues(1, 1, 2, 2, 3, 3)));
Assert.assertEquals(5, Iterate.sizeOf(new IterableAdapter<Integer>(Interval.oneTo(5))));
}
@Test
public void toArray()
{
Object[] expected = {1, 2, 3, 4, 5};
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5)));
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5).toList()));
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5).asLazy()));
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5).toSortedMap(a -> a, a -> a)));
Assert.assertArrayEquals(expected, Iterate.toArray(new IterableAdapter<Integer>(Interval.oneTo(5))));
}
@Test(expected = NullPointerException.class)
public void toArray_NullParameter()
{
Iterate.toArray(null);
}
@Test
public void toArray_with_array()
{
Object[] expected = {1, 2, 3, 4, 5};
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5), new Object[5]));
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5).toList(), new Object[5]));
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5).asLazy(), new Object[5]));
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5).toSortedMap(a -> a, a -> a), new Object[5]));
Assert.assertArrayEquals(expected, Iterate.toArray(new IterableAdapter<Integer>(Interval.oneTo(5)), new Object[5]));
Assert.assertArrayEquals(new Integer[]{1, 2, 3, 4, 5, 6, 7}, Iterate.toArray(new IterableAdapter<Integer>(Interval.oneTo(7)), new Object[5]));
}
@Test
public void fromToDoit()
{
MutableList<Integer> list = Lists.mutable.of();
Interval.fromTo(6, 10).forEach(Procedures.cast(list::add));
Verify.assertContainsAll(list, 6, 10);
}
@Test
public void injectInto()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertEquals(Integer.valueOf(15), Iterate.injectInto(0, each, AddFunction.INTEGER))));
}
@Test
public void injectIntoInt()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertEquals(15, Iterate.injectInto(0, each, AddFunction.INTEGER_TO_INT))));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.injectInto(0, null, AddFunction.INTEGER_TO_INT);
});
}
@Test
public void injectIntoLong()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertEquals(15L, Iterate.injectInto(0L, each, AddFunction.INTEGER_TO_LONG))));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.injectInto(0L, null, AddFunction.INTEGER_TO_LONG);
});
}
@Test
public void injectIntoDouble()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertEquals(15.0d, Iterate.injectInto(0.0d, each, AddFunction.INTEGER_TO_DOUBLE), 0.001)));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.injectInto(0.0d, null, AddFunction.INTEGER_TO_DOUBLE);
});
}
@Test
public void injectIntoFloat()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertEquals(15.0d, Iterate.injectInto(0.0f, each, AddFunction.INTEGER_TO_FLOAT), 0.001)));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.injectInto(0.0f, null, AddFunction.INTEGER_TO_FLOAT);
});
}
@Test
public void injectInto2()
{
Assert.assertEquals(new Double(7), Iterate.injectInto(1.0, iList(1.0, 2.0, 3.0), AddFunction.DOUBLE));
}
@Test
public void injectIntoString()
{
Assert.assertEquals("0123", Iterate.injectInto("0", iList("1", "2", "3"), AddFunction.STRING));
}
@Test
public void injectIntoMaxString()
{
Assert.assertEquals(Integer.valueOf(3), Iterate.injectInto(Integer.MIN_VALUE, iList("1", "12", "123"), MaxSizeFunction.STRING));
}
@Test
public void injectIntoMinString()
{
Assert.assertEquals(Integer.valueOf(1), Iterate.injectInto(Integer.MAX_VALUE, iList("1", "12", "123"), MinSizeFunction.STRING));
}
@Test
public void flatCollectFromAttributes()
{
MutableList<ListContainer<String>> list = mList(
new ListContainer<String>(Lists.mutable.of("One", "Two")),
new ListContainer<String>(Lists.mutable.of("Two-and-a-half", "Three", "Four")),
new ListContainer<String>(Lists.mutable.<String>of()),
new ListContainer<String>(Lists.mutable.of("Five")));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(list, ListContainer.<String>getListFunction()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(Collections.synchronizedList(list), ListContainer.getListFunction()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(Collections.synchronizedCollection(list), ListContainer.getListFunction()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(LazyIterate.adapt(list), ListContainer.<String>getListFunction()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(new ArrayList<ListContainer<String>>(list), ListContainer.getListFunction()));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.flatCollect(null, null);});
}
@Test
public void flatCollectFromAttributesWithTarget()
{
MutableList<ListContainer<String>> list = Lists.fixedSize.of(
new ListContainer<String>(Lists.mutable.of("One", "Two")),
new ListContainer<String>(Lists.mutable.of("Two-and-a-half", "Three", "Four")),
new ListContainer<String>(Lists.mutable.<String>of()),
new ListContainer<String>(Lists.mutable.of("Five")));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(list, ListContainer.<String>getListFunction(), FastList.newList()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(Collections.synchronizedList(list), ListContainer.<String>getListFunction(), FastList.newList()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(Collections.synchronizedCollection(list), ListContainer.<String>getListFunction(), FastList.newList()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(LazyIterate.adapt(list), ListContainer.<String>getListFunction(), FastList.newList()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(new ArrayList<ListContainer<String>>(list), ListContainer.<String>getListFunction(), FastList.newList()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(new IterableAdapter<ListContainer<String>>(new ArrayList<ListContainer<String>>(list)), ListContainer.getListFunction(), FastList.newList()));
}
@Test(expected = IllegalArgumentException.class)
public void flatCollectFromAttributesWithTarget_NullParameter()
{
Iterate.flatCollect(null, null, UnifiedSet.newSet());
}
@Test
public void flatCollectFromAttributesUsingStringFunction()
{
MutableList<ListContainer<String>> list = Lists.mutable.of(
new ListContainer<String>(Lists.mutable.of("One", "Two")),
new ListContainer<String>(Lists.mutable.of("Two-and-a-half", "Three", "Four")),
new ListContainer<String>(Lists.mutable.<String>of()),
new ListContainer<String>(Lists.mutable.of("Five")));
Function<ListContainer<String>, List<String>> function = ListContainer::getList;
Collection<String> result = Iterate.flatCollect(list, function);
FastList<String> result2 = Iterate.flatCollect(list, function, FastList.<String>newList());
Assert.assertEquals(iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"), result);
Assert.assertEquals(iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"), result2);
}
@Test
public void flatCollectOneLevel()
{
MutableList<MutableList<String>> list = Lists.mutable.of(
Lists.mutable.of("One", "Two"),
Lists.mutable.of("Two-and-a-half", "Three", "Four"),
Lists.mutable.<String>of(),
Lists.mutable.of("Five"));
Collection<String> result = Iterate.flatten(list);
Assert.assertEquals(iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"), result);
}
@Test
public void flatCollectOneLevel_target()
{
MutableList<MutableList<String>> list = Lists.mutable.of(
Lists.mutable.of("One", "Two"),
Lists.mutable.of("Two-and-a-half", "Three", "Four"),
Lists.mutable.<String>of(),
Lists.mutable.of("Five"));
MutableList<String> target = Lists.mutable.of();
Collection<String> result = Iterate.flatten(list, target);
Assert.assertSame(result, target);
Assert.assertEquals(iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"), result);
}
@Test
public void groupBy()
{
FastList<String> source = FastList.newListWith("Ted", "Sally", "Mary", "Bob", "Sara");
Multimap<Character, String> result1 = Iterate.groupBy(source, StringFunctions.firstLetter());
Multimap<Character, String> result2 = Iterate.groupBy(Collections.synchronizedList(source), StringFunctions.firstLetter());
Multimap<Character, String> result3 = Iterate.groupBy(Collections.synchronizedCollection(source), StringFunctions.firstLetter());
Multimap<Character, String> result4 = Iterate.groupBy(LazyIterate.adapt(source), StringFunctions.firstLetter());
Multimap<Character, String> result5 = Iterate.groupBy(new ArrayList<String>(source), StringFunctions.firstLetter());
MutableMultimap<Character, String> expected = FastListMultimap.newMultimap();
expected.put('T', "Ted");
expected.put('S', "Sally");
expected.put('M', "Mary");
expected.put('B', "Bob");
expected.put('S', "Sara");
Assert.assertEquals(expected, result1);
Assert.assertEquals(expected, result2);
Assert.assertEquals(expected, result3);
Assert.assertEquals(expected, result4);
Assert.assertEquals(expected, result5);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.groupBy(null, null);});
}
@Test
public void groupByEach()
{
MutableList<String> source = FastList.newListWith("Ted", "Sally", "Sally", "Mary", "Bob", "Sara");
Function<String, Set<Character>> uppercaseSetFunction = new WordToItsLetters();
Multimap<Character, String> result1 = Iterate.groupByEach(source, uppercaseSetFunction);
Multimap<Character, String> result2 = Iterate.groupByEach(Collections.synchronizedList(source), uppercaseSetFunction);
Multimap<Character, String> result3 = Iterate.groupByEach(Collections.synchronizedCollection(source), uppercaseSetFunction);
Multimap<Character, String> result4 = Iterate.groupByEach(LazyIterate.adapt(source), uppercaseSetFunction);
Multimap<Character, String> result5 = Iterate.groupByEach(new ArrayList<String>(source), uppercaseSetFunction);
MutableMultimap<Character, String> expected = FastListMultimap.newMultimap();
expected.put('T', "Ted");
expected.putAll('E', FastList.newListWith("Ted"));
expected.put('D', "Ted");
expected.putAll('S', FastList.newListWith("Sally", "Sally", "Sara"));
expected.putAll('A', FastList.newListWith("Sally", "Sally", "Mary", "Sara"));
expected.putAll('L', FastList.newListWith("Sally", "Sally"));
expected.putAll('Y', FastList.newListWith("Sally", "Sally", "Mary"));
expected.put('M', "Mary");
expected.putAll('R', FastList.newListWith("Mary", "Sara"));
expected.put('B', "Bob");
expected.put('O', "Bob");
Assert.assertEquals(expected, result1);
Assert.assertEquals(expected, result2);
Assert.assertEquals(expected, result3);
Assert.assertEquals(expected, result4);
Assert.assertEquals(expected, result5);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.groupByEach(null, null);});
}
@Test
public void groupByWithTarget()
{
FastList<String> source = FastList.newListWith("Ted", "Sally", "Mary", "Bob", "Sara");
Multimap<Character, String> result1 = Iterate.groupBy(source, StringFunctions.firstLetter(), FastListMultimap.newMultimap());
Multimap<Character, String> result2 = Iterate.groupBy(Collections.synchronizedList(source), StringFunctions.firstLetter(), FastListMultimap.newMultimap());
Multimap<Character, String> result3 = Iterate.groupBy(Collections.synchronizedCollection(source), StringFunctions.firstLetter(), FastListMultimap.newMultimap());
Multimap<Character, String> result4 = Iterate.groupBy(LazyIterate.adapt(source), StringFunctions.firstLetter(), FastListMultimap.newMultimap());
Multimap<Character, String> result5 = Iterate.groupBy(new ArrayList<String>(source), StringFunctions.firstLetter(), FastListMultimap.newMultimap());
MutableMultimap<Character, String> expected = FastListMultimap.newMultimap();
expected.put('T', "Ted");
expected.put('S', "Sally");
expected.put('M', "Mary");
expected.put('B', "Bob");
expected.put('S', "Sara");
Assert.assertEquals(expected, result1);
Assert.assertEquals(expected, result2);
Assert.assertEquals(expected, result3);
Assert.assertEquals(expected, result4);
Assert.assertEquals(expected, result5);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.groupBy(null, null, null);});
}
@Test
public void groupByEachWithTarget()
{
MutableList<String> source = FastList.newListWith("Ted", "Sally", "Sally", "Mary", "Bob", "Sara");
Function<String, Set<Character>> uppercaseSetFunction = StringIterate::asUppercaseSet;
Multimap<Character, String> result1 = Iterate.groupByEach(source, uppercaseSetFunction, FastListMultimap.<Character, String>newMultimap());
Multimap<Character, String> result2 = Iterate.groupByEach(Collections.synchronizedList(source), uppercaseSetFunction, FastListMultimap.<Character, String>newMultimap());
Multimap<Character, String> result3 = Iterate.groupByEach(Collections.synchronizedCollection(source), uppercaseSetFunction, FastListMultimap.<Character, String>newMultimap());
Multimap<Character, String> result4 = Iterate.groupByEach(LazyIterate.adapt(source), uppercaseSetFunction, FastListMultimap.<Character, String>newMultimap());
Multimap<Character, String> result5 = Iterate.groupByEach(new ArrayList<String>(source), uppercaseSetFunction, FastListMultimap.<Character, String>newMultimap());
MutableMultimap<Character, String> expected = FastListMultimap.newMultimap();
expected.put('T', "Ted");
expected.putAll('E', FastList.newListWith("Ted"));
expected.put('D', "Ted");
expected.putAll('S', FastList.newListWith("Sally", "Sally", "Sara"));
expected.putAll('A', FastList.newListWith("Sally", "Sally", "Mary", "Sara"));
expected.putAll('L', FastList.newListWith("Sally", "Sally"));
expected.putAll('Y', FastList.newListWith("Sally", "Sally"));
expected.put('M', "Mary");
expected.putAll('R', FastList.newListWith("Mary", "Sara"));
expected.put('Y', "Mary");
expected.put('B', "Bob");
expected.put('O', "Bob");
Assert.assertEquals(expected, result1);
Assert.assertEquals(expected, result2);
Assert.assertEquals(expected, result3);
Assert.assertEquals(expected, result4);
Assert.assertEquals(expected, result5);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.groupByEach(null, null, null);});
}
@Test
public void toList()
{
Assert.assertEquals(FastList.newListWith(1, 2, 3), FastList.newList(Interval.oneTo(3)));
}
@Test
public void contains()
{
Assert.assertTrue(Iterate.contains(FastList.newListWith(1, 2, 3), 1));
Assert.assertFalse(Iterate.contains(FastList.newListWith(1, 2, 3), 4));
Assert.assertTrue(Iterate.contains(FastList.newListWith(1, 2, 3).asLazy(), 1));
Assert.assertTrue(Iterate.contains(UnifiedMap.newWithKeysValues(1, 1, 2, 2, 3, 3), 1));
Assert.assertFalse(Iterate.contains(UnifiedMap.newWithKeysValues(1, 1, 2, 2, 3, 3), 4));
Assert.assertTrue(Iterate.contains(Interval.oneTo(3), 1));
Assert.assertFalse(Iterate.contains(Interval.oneTo(3), 4));
}
public static final class ListContainer<T>
{
private final List<T> list;
private ListContainer(List<T> list)
{
this.list = list;
}
private static <V> Function<ListContainer<V>, List<V>> getListFunction()
{
return anObject -> anObject.list;
}
public List<T> getList()
{
return this.list;
}
}
@Test
public void getFirstAndLast()
{
MutableList<Boolean> list = mList(Boolean.TRUE, null, Boolean.FALSE);
Assert.assertEquals(Boolean.TRUE, Iterate.getFirst(list));
Assert.assertEquals(Boolean.FALSE, Iterate.getLast(list));
Assert.assertEquals(Boolean.TRUE, Iterate.getFirst(Collections.unmodifiableList(list)));
Assert.assertEquals(Boolean.FALSE, Iterate.getLast(Collections.unmodifiableList(list)));
Assert.assertEquals(Boolean.TRUE, Iterate.getFirst(new IterableAdapter<Boolean>(list)));
Assert.assertEquals(Boolean.FALSE, Iterate.getLast(new IterableAdapter<Boolean>(list)));
}
@Test(expected = IllegalArgumentException.class)
public void getFirst_null_throws()
{
Iterate.getFirst(null);
}
@Test(expected = IllegalArgumentException.class)
public void getList_null_throws()
{
Iterate.getLast(null);
}
@Test
public void getFirstAndLastInterval()
{
Assert.assertEquals(Integer.valueOf(1), Iterate.getFirst(Interval.oneTo(5)));
Assert.assertEquals(Integer.valueOf(5), Iterate.getLast(Interval.oneTo(5)));
}
@Test
public void getFirstAndLastLinkedList()
{
List<Boolean> list = new LinkedList<Boolean>(mList(Boolean.TRUE, null, Boolean.FALSE));
Assert.assertEquals(Boolean.TRUE, Iterate.getFirst(list));
Assert.assertEquals(Boolean.FALSE, Iterate.getLast(list));
}
@Test
public void getFirstAndLastTreeSet()
{
Set<String> set = new TreeSet<String>(mList("1", "2"));
Assert.assertEquals("1", Iterate.getFirst(set));
Assert.assertEquals("2", Iterate.getLast(set));
}
@Test
public void getFirstAndLastCollection()
{
Collection<Boolean> list = mList(Boolean.TRUE, null, Boolean.FALSE).asSynchronized();
Assert.assertEquals(Boolean.TRUE, Iterate.getFirst(list));
Assert.assertEquals(Boolean.FALSE, Iterate.getLast(list));
}
@Test
public void getFirstAndLastOnEmpty()
{
Assert.assertNull(Iterate.getFirst(mList()));
Assert.assertNull(Iterate.getLast(mList()));
}
@Test
public void getFirstAndLastForSet()
{
Set<Integer> orderedSet = new TreeSet<Integer>();
orderedSet.add(1);
orderedSet.add(2);
orderedSet.add(3);
Assert.assertEquals(Integer.valueOf(1), Iterate.getFirst(orderedSet));
Assert.assertEquals(Integer.valueOf(3), Iterate.getLast(orderedSet));
}
@Test
public void getFirstAndLastOnEmptyForSet()
{
MutableSet<Object> set = UnifiedSet.newSet();
Assert.assertNull(Iterate.getFirst(set));
Assert.assertNull(Iterate.getLast(set));
}
private MutableSet<Integer> getIntegerSet()
{
return Interval.toSet(1, 5);
}
@Test
public void selectDifferentTargetCollection()
{
MutableSet<Integer> set = this.getIntegerSet();
List<Integer> list = Iterate.select(set, Predicates.instanceOf(Integer.class), new ArrayList<Integer>());
Assert.assertEquals(FastList.newListWith(1, 2, 3, 4, 5), list);
}
@Test
public void rejectWithDifferentTargetCollection()
{
MutableSet<Integer> set = this.getIntegerSet();
Collection<Integer> result = Iterate.reject(set, Predicates.instanceOf(Integer.class), FastList.newList());
Verify.assertEmpty(result);
}
@Test
public void count_empty()
{
Assert.assertEquals(0, Iterate.count(iList(), a -> true));
}
@Test(expected = IllegalArgumentException.class)
public void count_null_throws()
{
Iterate.count(null, a -> true);
}
@Test
public void toMap()
{
MutableSet<Integer> set = UnifiedSet.newSet(this.getIntegerSet());
MutableMap<String, Integer> map = Iterate.toMap(set, String::valueOf);
Verify.assertSize(5, map);
Object expectedValue = 1;
Object expectedKey = "1";
Verify.assertContainsKeyValue(expectedKey, expectedValue, map);
Verify.assertContainsKeyValue("2", 2, map);
Verify.assertContainsKeyValue("3", 3, map);
Verify.assertContainsKeyValue("4", 4, map);
Verify.assertContainsKeyValue("5", 5, map);
}
@Test
public void addToMap()
{
MutableSet<Integer> set = Interval.toSet(1, 5);
MutableMap<String, Integer> map = UnifiedMap.newMap();
map.put("the answer", 42);
Iterate.addToMap(set, String::valueOf, map);
Verify.assertSize(6, map);
Verify.assertContainsAllKeyValues(
map,
"the answer", 42,
"1", 1,
"2", 2,
"3", 3,
"4", 4,
"5", 5);
}
@Test
public void toMapSelectingKeyAndValue()
{
MutableSet<Integer> set = UnifiedSet.newSet(this.getIntegerSet());
MutableMap<String, Integer> map = Iterate.toMap(set, String::valueOf, object -> 10 * object);
Verify.assertSize(5, map);
Verify.assertContainsKeyValue("1", 10, map);
Verify.assertContainsKeyValue("2", 20, map);
Verify.assertContainsKeyValue("3", 30, map);
Verify.assertContainsKeyValue("4", 40, map);
Verify.assertContainsKeyValue("5", 50, map);
}
@Test
public void forEachWithIndex()
{
this.iterables.forEach(Procedures.cast(each -> {
UnifiedSet<Integer> set = UnifiedSet.newSet();
Iterate.forEachWithIndex(each, ObjectIntProcedures.fromProcedure(CollectionAddProcedure.on(set)));
Assert.assertEquals(UnifiedSet.newSetWith(1, 2, 3, 4, 5), set);
}));
}
@Test
public void selectPairs()
{
ImmutableList<Twin<String>> twins = iList(
Tuples.twin("1", "2"),
Tuples.twin("2", "1"),
Tuples.twin("3", "3"));
Collection<Twin<String>> results = Iterate.select(twins, new PairPredicate<String, String>()
{
public boolean accept(String argument1, String argument2)
{
return "1".equals(argument1) || "1".equals(argument2);
}
});
Verify.assertSize(2, results);
}
@Test
public void detect()
{
this.iterables.forEach(Procedures.cast(each -> {
Integer result = Iterate.detect(each, Predicates.instanceOf(Integer.class));
Assert.assertTrue(UnifiedSet.newSet(each).contains(result));
}));
}
@Test
public void detectIndex()
{
MutableList<Integer> list = Interval.toReverseList(1, 5);
Assert.assertEquals(4, Iterate.detectIndex(list, Predicates.equal(1)));
Assert.assertEquals(0, Iterate.detectIndex(list, Predicates.equal(5)));
Assert.assertEquals(-1, Iterate.detectIndex(Lists.immutable.of(), Predicates.equal(1)));
Assert.assertEquals(-1, Iterate.detectIndex(Sets.immutable.of(), Predicates.equal(1)));
}
@Test
public void detectIndexWithTreeSet()
{
Set<Integer> treeSet = new TreeSet<Integer>(Interval.toReverseList(1, 5));
Assert.assertEquals(0, Iterate.detectIndex(treeSet, Predicates.equal(1)));
Assert.assertEquals(4, Iterate.detectIndex(treeSet, Predicates.equal(5)));
}
@Test
public void detectIndexWith()
{
MutableList<Integer> list = Interval.toReverseList(1, 5);
Assert.assertEquals(4, Iterate.detectIndexWith(list, Predicates2.equal(), 1));
Assert.assertEquals(0, Iterate.detectIndexWith(list, Predicates2.equal(), 5));
Assert.assertEquals(-1, Iterate.detectIndexWith(iList(), Predicates2.equal(), 5));
Assert.assertEquals(-1, Iterate.detectIndexWith(iSet(), Predicates2.equal(), 5));
}
@Test
public void detectIndexWithWithTreeSet()
{
Set<Integer> treeSet = new TreeSet<Integer>(Interval.toReverseList(1, 5));
Assert.assertEquals(0, Iterate.detectIndexWith(treeSet, Predicates2.equal(), 1));
Assert.assertEquals(4, Iterate.detectIndexWith(treeSet, Predicates2.equal(), 5));
}
@Test
public void detectWithIfNone()
{
this.iterables.forEach(Procedures.cast(each -> {
Integer result = Iterate.detectWithIfNone(each, Predicates2.instanceOf(), Integer.class, 5);
Verify.assertContains(result, UnifiedSet.newSet(each));
}));
}
@Test
public void selectWith()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.selectWith(each, Predicates2.greaterThan(), 3);
Assert.assertTrue(result.containsAll(FastList.newListWith(4, 5)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.selectWith(null, null, null);});
}
@Test
public void selectWithWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.selectWith(each, Predicates2.greaterThan(), 3, FastList.<Integer>newList());
Assert.assertTrue(result.containsAll(FastList.newListWith(4, 5)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.selectWith(null, null, null, null);});
}
@Test
public void rejectWith()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.rejectWith(each, Predicates2.greaterThan(), 3);
Assert.assertTrue(result.containsAll(FastList.newListWith(1, 2, 3)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.rejectWith(null, null, null);});
}
@Test
public void rejectWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.rejectWith(each, Predicates2.greaterThan(), 3, FastList.<Integer>newList());
Assert.assertTrue(result.containsAll(FastList.newListWith(1, 2, 3)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.rejectWith(null, null, null, null);});
}
@Test
public void selectAndRejectWith()
{
this.iterables.forEach(Procedures.cast(each -> {
Twin<MutableList<Integer>> result = Iterate.selectAndRejectWith(each, Predicates2.greaterThan(), 3);
Assert.assertEquals(iBag(4, 5), result.getOne().toBag());
Assert.assertEquals(iBag(1, 2, 3), result.getTwo().toBag());
}));
}
@Test
public void partition()
{
this.iterables.forEach(Procedures.cast(each -> {
PartitionIterable<Integer> result = Iterate.partition(each, Predicates.greaterThan(3));
Assert.assertEquals(iBag(4, 5), result.getSelected().toBag());
Assert.assertEquals(iBag(1, 2, 3), result.getRejected().toBag());
}));
}
@Test
public void rejectTargetCollection()
{
MutableList<Integer> list = Interval.toReverseList(1, 5);
MutableList<Integer> results = Iterate.reject(list, Predicates.instanceOf(Integer.class), FastList.newList());
Verify.assertEmpty(results);
}
@Test
public void rejectOnRandomAccessTargetCollection()
{
List<Integer> list = Collections.synchronizedList(Interval.toReverseList(1, 5));
MutableList<Integer> results =
Iterate.reject(list, Predicates.instanceOf(Integer.class), FastList.<Integer>newList());
Verify.assertEmpty(results);
}
@Test
public void rejectWithTargetCollection()
{
MutableList<Integer> list = Interval.toReverseList(1, 5);
MutableList<Integer> results = Iterate.rejectWith(list, Predicates2.instanceOf(), Integer.class, FastList.newList());
Verify.assertEmpty(results);
}
@Test
public void rejectWithOnRandomAccessTargetCollection()
{
List<Integer> list = Collections.synchronizedList(Interval.toReverseList(1, 5));
MutableList<Integer> results = Iterate.rejectWith(list, Predicates2.instanceOf(), Integer.class, FastList.newList());
Verify.assertEmpty(results);
}
@Test
public void anySatisfy()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertTrue(Iterate.anySatisfy(each, Predicates.instanceOf(Integer.class)))));
}
@Test
public void anySatisfyWith()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertTrue(Iterate.anySatisfyWith(each, Predicates2.instanceOf(), Integer.class))));
}
@Test
public void allSatisfy()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertTrue(Iterate.allSatisfy(each, Predicates.instanceOf(Integer.class)))));
}
@Test
public void allSatisfyWith()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertTrue(Iterate.allSatisfyWith(each, Predicates2.instanceOf(), Integer.class))));
}
@Test
public void noneSatisfy()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertTrue(Iterate.noneSatisfy(each, Predicates.instanceOf(String.class)))));
}
@Test
public void noneSatisfyWith()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertTrue(Iterate.noneSatisfyWith(each, Predicates2.instanceOf(), String.class))));
}
@Test
public void selectWithSet()
{
Verify.assertSize(1, Iterate.selectWith(this.getIntegerSet(), Predicates2.equal(), 1));
Verify.assertSize(1, Iterate.selectWith(this.getIntegerSet(), Predicates2.equal(), 1, FastList.<Integer>newList()));
}
@Test
public void rejectWithSet()
{
Verify.assertSize(4, Iterate.rejectWith(this.getIntegerSet(), Predicates2.equal(), 1));
Verify.assertSize(4, Iterate.rejectWith(this.getIntegerSet(), Predicates2.equal(), 1, FastList.<Integer>newList()));
}
@Test
public void detectWithSet()
{
Assert.assertEquals(Integer.valueOf(1), Iterate.detectWith(this.getIntegerSet(), Predicates2.equal(), 1));
}
@Test
public void detectWithRandomAccess()
{
List<Integer> list = Collections.synchronizedList(Interval.oneTo(5));
Assert.assertEquals(Integer.valueOf(1), Iterate.detectWith(list, Predicates2.equal(), 1));
}
@Test
public void anySatisfyWithSet()
{
Assert.assertTrue(Iterate.anySatisfyWith(this.getIntegerSet(), Predicates2.equal(), 1));
}
@Test
public void allSatisfyWithSet()
{
Assert.assertFalse(Iterate.allSatisfyWith(this.getIntegerSet(), Predicates2.equal(), 1));
Assert.assertTrue(Iterate.allSatisfyWith(this.getIntegerSet(), Predicates2.instanceOf(), Integer.class));
}
@Test
public void noneSatisfyWithSet()
{
Assert.assertTrue(Iterate.noneSatisfyWith(this.getIntegerSet(), Predicates2.equal(), 100));
Assert.assertFalse(Iterate.noneSatisfyWith(this.getIntegerSet(), Predicates2.instanceOf(), Integer.class));
}
@Test
public void selectAndRejectWithSet()
{
Twin<MutableList<Integer>> result = Iterate.selectAndRejectWith(this.getIntegerSet(), Predicates2.in(), iList(1));
Verify.assertSize(1, result.getOne());
Verify.assertSize(4, result.getTwo());
}
@Test
public void forEach()
{
this.iterables.forEach(Procedures.cast(each -> {
UnifiedSet<Integer> set = UnifiedSet.newSet();
Iterate.forEach(each, Procedures.cast(set::add));
Assert.assertEquals(UnifiedSet.newSetWith(1, 2, 3, 4, 5), set);
}));
}
@Test
public void collectIf()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<String> result = Iterate.collectIf(each, Predicates.greaterThan(3), String::valueOf);
Assert.assertTrue(result.containsAll(FastList.newListWith("4", "5")));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.collectIf(null, null, null);});
}
@Test
public void collectIfTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<String> result = Iterate.collectIf(each, Predicates.greaterThan(3), String::valueOf, FastList.newList());
Assert.assertTrue(result.containsAll(FastList.newListWith("4", "5")));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.collectIf(null, null, null, null);});
}
@Test
public void collect()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<String> result = Iterate.collect(each, String::valueOf);
Assert.assertTrue(result.containsAll(FastList.newListWith("1", "2", "3", "4", "5")));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.collect(null, a -> a);});
}
@Test
public void collectBoolean()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableBooleanCollection result = Iterate.collectBoolean(each, PrimitiveFunctions.integerIsPositive());
Assert.assertTrue(result.containsAll(true, true, true, true, true));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectBoolean(null, PrimitiveFunctions.integerIsPositive());
});
}
@Test
public void collectBooleanWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableBooleanCollection expected = new BooleanArrayList();
MutableBooleanCollection actual = Iterate.collectBoolean(each, PrimitiveFunctions.integerIsPositive(), expected);
Assert.assertTrue(expected.containsAll(true, true, true, true, true));
Assert.assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectBoolean(null, PrimitiveFunctions.integerIsPositive(), new BooleanArrayList());
});
}
@Test
public void collectByte()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableByteCollection result = Iterate.collectByte(each, PrimitiveFunctions.unboxIntegerToByte());
Assert.assertTrue(result.containsAll((byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectByte(null, PrimitiveFunctions.unboxIntegerToByte());
});
}
@Test
public void collectByteWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableByteCollection expected = new ByteArrayList();
MutableByteCollection actual = Iterate.collectByte(each, PrimitiveFunctions.unboxIntegerToByte(), expected);
Assert.assertTrue(actual.containsAll((byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5));
Assert.assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectByte(null, PrimitiveFunctions.unboxIntegerToByte(), new ByteArrayList());
});
}
@Test
public void collectChar()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableCharCollection result = Iterate.collectChar(each, PrimitiveFunctions.unboxIntegerToChar());
Assert.assertTrue(result.containsAll((char) 1, (char) 2, (char) 3, (char) 4, (char) 5));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectChar(null, PrimitiveFunctions.unboxIntegerToChar());
});
}
@Test
public void collectCharWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableCharCollection expected = new CharArrayList();
MutableCharCollection actual = Iterate.collectChar(each, PrimitiveFunctions.unboxIntegerToChar(), expected);
Assert.assertTrue(actual.containsAll((char) 1, (char) 2, (char) 3, (char) 4, (char) 5));
Assert.assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectChar(null, PrimitiveFunctions.unboxIntegerToChar(), new CharArrayList());
});
}
@Test
public void collectDouble()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableDoubleCollection result = Iterate.collectDouble(each, PrimitiveFunctions.unboxIntegerToDouble());
Assert.assertTrue(result.containsAll(1.0d, 2.0d, 3.0d, 4.0d, 5.0d));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectDouble(null, PrimitiveFunctions.unboxIntegerToDouble());
});
}
@Test
public void collectDoubleWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableDoubleCollection expected = new DoubleArrayList();
MutableDoubleCollection actual = Iterate.collectDouble(each, PrimitiveFunctions.unboxIntegerToDouble(), expected);
Assert.assertTrue(actual.containsAll(1.0d, 2.0d, 3.0d, 4.0d, 5.0d));
Assert.assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectDouble(null, PrimitiveFunctions.unboxIntegerToDouble(), new DoubleArrayList());
});
}
@Test
public void collectFloat()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableFloatCollection result = Iterate.collectFloat(each, PrimitiveFunctions.unboxIntegerToFloat());
Assert.assertTrue(result.containsAll(1.0f, 2.0f, 3.0f, 4.0f, 5.0f));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectFloat(null, PrimitiveFunctions.unboxIntegerToFloat());
});
}
@Test
public void collectFloatWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableFloatCollection expected = new FloatArrayList();
MutableFloatCollection actual = Iterate.collectFloat(each, PrimitiveFunctions.unboxIntegerToFloat(), expected);
Assert.assertTrue(actual.containsAll(1.0f, 2.0f, 3.0f, 4.0f, 5.0f));
Assert.assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectFloat(null, PrimitiveFunctions.unboxIntegerToFloat(), new FloatArrayList());
});
}
@Test
public void collectInt()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableIntCollection result = Iterate.collectInt(each, PrimitiveFunctions.unboxIntegerToInt());
Assert.assertTrue(result.containsAll(1, 2, 3, 4, 5));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectInt(null, PrimitiveFunctions.unboxIntegerToInt());
});
}
@Test
public void collectIntWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableIntCollection expected = new IntArrayList();
MutableIntCollection actual = Iterate.collectInt(each, PrimitiveFunctions.unboxIntegerToInt(), expected);
Assert.assertTrue(actual.containsAll(1, 2, 3, 4, 5));
assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectInt(null, PrimitiveFunctions.unboxIntegerToInt(), new IntArrayList());
});
}
@Test
public void collectLong()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableLongCollection result = Iterate.collectLong(each, PrimitiveFunctions.unboxIntegerToLong());
Assert.assertTrue(result.containsAll(1L, 2L, 3L, 4L, 5L));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectLong(null, PrimitiveFunctions.unboxIntegerToLong());
});
}
@Test
public void collectLongWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableLongCollection expected = new LongArrayList();
MutableLongCollection actual = Iterate.collectLong(each, PrimitiveFunctions.unboxIntegerToLong(), expected);
Assert.assertTrue(actual.containsAll(1L, 2L, 3L, 4L, 5L));
Assert.assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectLong(null, PrimitiveFunctions.unboxIntegerToLong(), new LongArrayList());
});
}
@Test
public void collectShort()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableShortCollection result = Iterate.collectShort(each, PrimitiveFunctions.unboxIntegerToShort());
Assert.assertTrue(result.containsAll((short) 1, (short) 2, (short) 3, (short) 4, (short) 5));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectShort(null, PrimitiveFunctions.unboxIntegerToShort());
});
}
@Test
public void collectShortWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableShortCollection expected = new ShortArrayList();
MutableShortCollection actual = Iterate.collectShort(each, PrimitiveFunctions.unboxIntegerToShort(), expected);
Assert.assertTrue(actual.containsAll((short) 1, (short) 2, (short) 3, (short) 4, (short) 5));
Assert.assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectShort(null, PrimitiveFunctions.unboxIntegerToShort(), new ShortArrayList());
});
}
@Test
public void collect_sortedSetSource()
{
class Foo implements Comparable<Foo>
{
private final int value;
Foo(int value)
{
this.value = value;
}
public int getValue()
{
return this.value;
}
@Override
public int compareTo(Foo that)
{
return Comparators.naturalOrder().compare(this.value, that.value);
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || this.getClass() != o.getClass())
{
return false;
}
Foo foo = (Foo) o;
return this.value == foo.value;
}
@Override
public int hashCode()
{
return this.value;
}
}
class Bar
{
private final int value;
Bar(int value)
{
this.value = value;
}
public int getValue()
{
return this.value;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || this.getClass() != o.getClass())
{
return false;
}
Bar bar = (Bar) o;
return this.value == bar.value;
}
@Override
public int hashCode()
{
return this.value;
}
}
Set<Foo> foos = new TreeSet<Foo>();
foos.add(new Foo(1));
foos.add(new Foo(2));
Collection<Bar> bars = Iterate.collect(foos, foo -> new Bar(foo.getValue()));
Assert.assertEquals(FastList.newListWith(new Bar(1), new Bar(2)), bars);
}
@Test
public void collectTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<String> result = Iterate.collect(each, String::valueOf, UnifiedSet.<String>newSet());
Assert.assertTrue(result.containsAll(FastList.newListWith("1", "2", "3", "4", "5")));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.collect(null, a -> a, null);});
}
@Test
public void collectWith()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<String> result = Iterate.collectWith(each, (each1, parm) -> each1.toString() + parm, " ");
Assert.assertTrue(result.containsAll(FastList.newListWith("1 ", "2 ", "3 ", "4 ", "5 ")));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.collectWith(null, null, null);});
}
@Test
public void collectWithWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<String> result = Iterate.collectWith(each, (each1, parm) -> each1.toString() + parm, " ", UnifiedSet.newSet());
Assert.assertTrue(result.containsAll(FastList.newListWith("1 ", "2 ", "3 ", "4 ", "5 ")));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.collectWith(null, null, null, null);});
}
@Test
public void removeIf()
{
MutableList<Integer> integers = Interval.oneTo(5).toList();
this.assertRemoveIfFromList(integers);
this.assertRemoveIfFromList(Collections.synchronizedList(integers));
this.assertRemoveIfFromList(FastList.newList(integers));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.removeIf(null, null);});
}
private void assertRemoveIfFromList(List<Integer> newIntegers)
{
Collection<Integer> result = Iterate.removeIf(newIntegers, IntegerPredicates.isEven());
Assert.assertSame(newIntegers, result);
Verify.assertContainsAll(newIntegers, 1, 3, 5);
Verify.assertSize(3, newIntegers);
}
@Test
public void removeIfLinkedList()
{
List<Integer> integers = new LinkedList<Integer>(Interval.oneTo(5).toList());
this.assertRemoveIfFromList(integers);
}
@Test
public void removeIfAll()
{
MutableList<Integer> integers = Interval.oneTo(5).toList();
Collection<Integer> result = Iterate.removeIf(integers, a -> true);
Assert.assertSame(integers, result);
Verify.assertSize(0, integers);
}
@Test
public void removeIfNone()
{
MutableList<Integer> integers = Interval.oneTo(5).toList();
Collection<Integer> result = Iterate.removeIf(integers, a -> false);
Assert.assertSame(integers, result);
Verify.assertSize(5, integers);
}
@Test
public void removeIfFromSet()
{
MutableSet<Integer> integers = Interval.toSet(1, 5);
Collection<Integer> result = Iterate.removeIf(integers, IntegerPredicates.isEven());
Assert.assertSame(integers, result);
Verify.assertContainsAll(integers, 1, 3, 5);
Verify.assertSize(3, integers);
}
@Test
public void injectIntoIfProcedure()
{
Integer newItemToIndex = 99;
MutableMap<String, Integer> index1 = createPretendIndex(1);
MutableMap<String, Integer> index2 = createPretendIndex(2);
MutableMap<String, Integer> index3 = createPretendIndex(3);
MutableMap<String, Integer> index4 = createPretendIndex(4);
MutableMap<String, Integer> index5 = createPretendIndex(5);
MutableMap<String, MutableMap<String, Integer>> allIndexes = UnifiedMap.newMapWith(
Tuples.pair("pretend index 1", index1),
Tuples.pair("pretend index 2", index2),
Tuples.pair("pretend index 3", index3),
Tuples.pair("pretend index 4", index4),
Tuples.pair("pretend index 5", index5));
MutableSet<MutableMap<String, Integer>> systemIndexes = Sets.fixedSize.of(index3, index5);
MapIterate.injectIntoIf(newItemToIndex, allIndexes, Predicates.notIn(systemIndexes), (itemToAdd, index) -> {
index.put(itemToAdd.toString(), itemToAdd);
return itemToAdd;
});
Verify.assertSize(5, allIndexes);
Verify.assertContainsKey("pretend index 2", allIndexes);
Verify.assertContainsKey("pretend index 3", allIndexes);
Verify.assertContainsKeyValue("99", newItemToIndex, index1);
Verify.assertContainsKeyValue("99", newItemToIndex, index2);
Verify.assertNotContainsKey("99", index3);
Verify.assertContainsKeyValue("99", newItemToIndex, index4);
Verify.assertNotContainsKey("99", index5);
}
public static MutableMap<String, Integer> createPretendIndex(int initialEntry)
{
return UnifiedMap.newWithKeysValues(String.valueOf(initialEntry), initialEntry);
}
@Test
public void isEmpty()
{
Assert.assertTrue(Iterate.isEmpty(null));
Assert.assertTrue(Iterate.isEmpty(Lists.fixedSize.of()));
Assert.assertFalse(Iterate.isEmpty(Lists.fixedSize.of("1")));
Assert.assertTrue(Iterate.isEmpty(Maps.fixedSize.of()));
Assert.assertFalse(Iterate.isEmpty(Maps.fixedSize.of("1", "1")));
Assert.assertTrue(Iterate.isEmpty(new IterableAdapter<Object>(Lists.fixedSize.of())));
Assert.assertFalse(Iterate.isEmpty(new IterableAdapter<String>(Lists.fixedSize.of("1"))));
Assert.assertTrue(Iterate.isEmpty(Lists.fixedSize.of().asLazy()));
Assert.assertFalse(Iterate.isEmpty(Lists.fixedSize.of("1").asLazy()));
}
@Test
public void notEmpty()
{
Assert.assertFalse(Iterate.notEmpty(null));
Assert.assertFalse(Iterate.notEmpty(Lists.fixedSize.of()));
Assert.assertTrue(Iterate.notEmpty(Lists.fixedSize.of("1")));
Assert.assertFalse(Iterate.notEmpty(Maps.fixedSize.of()));
Assert.assertTrue(Iterate.notEmpty(Maps.fixedSize.of("1", "1")));
Assert.assertFalse(Iterate.notEmpty(new IterableAdapter<Object>(Lists.fixedSize.of())));
Assert.assertTrue(Iterate.notEmpty(new IterableAdapter<String>(Lists.fixedSize.of("1"))));
Assert.assertFalse(Iterate.notEmpty(Lists.fixedSize.of().asLazy()));
Assert.assertTrue(Iterate.notEmpty(Lists.fixedSize.of("1").asLazy()));
}
@Test
public void toSortedList()
{
MutableList<Integer> list = Interval.toReverseList(1, 5);
MutableList<Integer> sorted = Iterate.toSortedList(list);
Verify.assertStartsWith(sorted, 1, 2, 3, 4, 5);
}
@Test
public void toSortedListWithComparator()
{
MutableList<Integer> list = Interval.oneTo(5).toList();
MutableList<Integer> sorted = Iterate.toSortedList(list, Collections.reverseOrder());
Verify.assertStartsWith(sorted, 5, 4, 3, 2, 1);
}
@Test
public void select()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.select(each, Predicates.greaterThan(3));
Assert.assertTrue(result.containsAll(FastList.newListWith(4, 5)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.select(null, null);});
}
@Test
public void selectTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.select(each, Predicates.greaterThan(3), FastList.newList());
Assert.assertTrue(result.containsAll(FastList.newListWith(4, 5)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.select(null, null, null);});
}
@Test
public void reject()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.reject(each, Predicates.greaterThan(3));
Assert.assertTrue(result.containsAll(FastList.newListWith(1, 2, 3)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.reject(null, null);});
}
@Test
public void rejectTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.reject(each, Predicates.greaterThan(3), FastList.newList());
Assert.assertTrue(result.containsAll(FastList.newListWith(1, 2, 3)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.reject(null, null, null);});
}
@Test
public void selectInstancesOf()
{
Iterable<Number> numbers1 = Collections.unmodifiableList(new ArrayList<Number>(FastList.newListWith(1, 2.0, 3, 4.0, 5)));
Iterable<Number> numbers2 = Collections.unmodifiableCollection(new ArrayList<Number>(FastList.newListWith(1, 2.0, 3, 4.0, 5)));
Verify.assertContainsAll(Iterate.selectInstancesOf(numbers1, Integer.class), 1, 3, 5);
Verify.assertContainsAll(Iterate.selectInstancesOf(numbers2, Integer.class), 1, 3, 5);
}
@Test
public void count()
{
this.iterables.forEach(Procedures.cast(each -> {
int result = Iterate.count(each, Predicates.greaterThan(3));
Assert.assertEquals(2, result);
}));
}
@Test(expected = IllegalArgumentException.class)
public void count_null_null_throws()
{
Iterate.count(null, null);
}
@Test
public void countWith()
{
this.iterables.forEach(Procedures.cast(each -> {
int result = Iterate.countWith(each, Predicates2.greaterThan(), 3);
Assert.assertEquals(2, result);
}));
}
@Test(expected = IllegalArgumentException.class)
public void countWith_null_throws()
{
Iterate.countWith(null, null, null);
}
@Test
public void injectIntoWith()
{
Sum result = new IntegerSum(0);
Integer parameter = 2;
MutableList<Integer> integers = Interval.oneTo(5).toList();
this.basicTestDoubleSum(result, integers, parameter);
}
@Test
public void injectIntoWithRandomAccess()
{
Sum result = new IntegerSum(0);
Integer parameter = 2;
MutableList<Integer> integers = Interval.oneTo(5).toList().asSynchronized();
this.basicTestDoubleSum(result, integers, parameter);
}
private void basicTestDoubleSum(Sum newResult, Collection<Integer> newIntegers, Integer newParameter)
{
Function3<Sum, Integer, Integer, Sum> function = (sum, element, withValue) -> sum.add(element.intValue() * withValue.intValue());
Sum sumOfDoubledValues = Iterate.injectIntoWith(newResult, newIntegers, function, newParameter);
Assert.assertEquals(30, sumOfDoubledValues.getValue().intValue());
}
@Test
public void injectIntoWithHashSet()
{
Sum result = new IntegerSum(0);
Integer parameter = 2;
MutableSet<Integer> integers = Interval.toSet(1, 5);
this.basicTestDoubleSum(result, integers, parameter);
}
@Test
public void forEachWith()
{
this.iterables.forEach(Procedures.cast(each -> {
Sum result = new IntegerSum(0);
Iterate.forEachWith(each, (integer, parm) -> {result.add(integer.intValue() * parm.intValue());}, 2);
Assert.assertEquals(30, result.getValue().intValue());
}));
}
@Test
public void forEachWithSets()
{
Sum result = new IntegerSum(0);
MutableSet<Integer> integers = Interval.toSet(1, 5);
Iterate.forEachWith(integers, (each, parm) -> {result.add(each.intValue() * parm.intValue());}, 2);
Assert.assertEquals(30, result.getValue().intValue());
}
@Test
public void removeIfWith()
{
MutableList<Integer> objects = FastList.newList(Lists.fixedSize.of(1, 2, 3, null));
Iterate.removeIfWith(objects, Predicates2.isNull(), null);
Verify.assertSize(3, objects);
Verify.assertContainsAll(objects, 1, 2, 3);
MutableList<Integer> objects1 = FastList.newList(Lists.fixedSize.of(null, 1, 2, 3));
Iterate.removeIfWith(objects1, Predicates2.isNull(), null);
Verify.assertSize(3, objects1);
Verify.assertContainsAll(objects1, 1, 2, 3);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.removeIfWith(null, null, null);});
}
@Test
public void removeIfWithFastList()
{
MutableList<Integer> objects = FastList.newListWith(1, 2, 3, null);
Iterate.removeIfWith(objects, Predicates2.isNull(), null);
Verify.assertSize(3, objects);
Verify.assertContainsAll(objects, 1, 2, 3);
MutableList<Integer> objects1 = FastList.newListWith(null, 1, 2, 3);
Iterate.removeIfWith(objects1, Predicates2.isNull(), null);
Verify.assertSize(3, objects1);
Verify.assertContainsAll(objects1, 1, 2, 3);
}
@Test
public void removeIfWithRandomAccess()
{
List<Integer> objects = Collections.synchronizedList(new ArrayList<Integer>(Lists.fixedSize.of(1, 2, 3, null)));
Iterate.removeIfWith(objects, Predicates2.isNull(), null);
Verify.assertSize(3, objects);
Verify.assertContainsAll(objects, 1, 2, 3);
List<Integer> objects1 =
Collections.synchronizedList(new ArrayList<Integer>(Lists.fixedSize.of(null, 1, 2, 3)));
Iterate.removeIfWith(objects1, Predicates2.isNull(), null);
Verify.assertSize(3, objects1);
Verify.assertContainsAll(objects1, 1, 2, 3);
}
@Test
public void removeIfWithLinkedList()
{
List<Integer> objects = new LinkedList<Integer>(Lists.fixedSize.of(1, 2, 3, null));
Iterate.removeIfWith(objects, Predicates2.isNull(), null);
Verify.assertSize(3, objects);
Verify.assertContainsAll(objects, 1, 2, 3);
List<Integer> objects1 = new LinkedList<Integer>(Lists.fixedSize.of(null, 1, 2, 3));
Iterate.removeIfWith(objects1, Predicates2.isNull(), null);
Verify.assertSize(3, objects1);
Verify.assertContainsAll(objects1, 1, 2, 3);
}
@Test
public void sortThis()
{
MutableList<Integer> list = Interval.oneTo(5).toList();
Collections.shuffle(list);
Verify.assertStartsWith(Iterate.sortThis(list), 1, 2, 3, 4, 5);
List<Integer> list3 = Interval.oneTo(5).addAllTo(new LinkedList<Integer>());
Collections.shuffle(list3);
Verify.assertStartsWith(Iterate.sortThis(list3), 1, 2, 3, 4, 5);
List<Integer> listOfSizeOne = new LinkedList<Integer>();
listOfSizeOne.add(1);
Iterate.sortThis(listOfSizeOne);
Assert.assertEquals(FastList.newListWith(1), listOfSizeOne);
}
@Test
public void sortThisWithPredicate()
{
MutableList<Integer> list = Interval.oneTo(5).toList();
Interval.oneTo(5).addAllTo(list);
Collections.shuffle(list);
Verify.assertStartsWith(Iterate.sortThis(list, Predicates2.<Integer>lessThan()), 1, 1, 2, 2, 3, 3, 4, 4, 5, 5);
MutableList<Integer> list2 = Interval.oneTo(5).toList();
Interval.oneTo(5).addAllTo(list2);
Collections.shuffle(list2);
Verify.assertStartsWith(Iterate.sortThis(list2, Predicates2.<Integer>greaterThan()), 5, 5, 4, 4, 3, 3, 2, 2, 1, 1);
List<Integer> list3 = Interval.oneTo(5).addAllTo(new LinkedList<Integer>());
Interval.oneTo(5).addAllTo(list3);
Collections.shuffle(list3);
Verify.assertStartsWith(Iterate.sortThis(list3, Predicates2.<Integer>lessThan()), 1, 1, 2, 2, 3, 3, 4, 4, 5, 5);
}
@Test
public void sortThisBy()
{
MutableList<Integer> list = Interval.oneTo(5).toList();
Interval.oneTo(5).addAllTo(list);
Collections.shuffle(list);
Verify.assertStartsWith(Iterate.sortThisBy(list, String::valueOf), 1, 1, 2, 2, 3, 3, 4, 4, 5, 5);
}
@Test
public void sortThisWithComparator()
{
MutableList<Integer> list = Interval.oneTo(5).toList();
Verify.assertStartsWith(Iterate.sortThis(list, Collections.reverseOrder()), 5, 4, 3, 2, 1);
List<Integer> list3 = Interval.oneTo(5).addAllTo(new LinkedList<Integer>());
Verify.assertStartsWith(Iterate.sortThis(list3, Collections.reverseOrder()), 5, 4, 3, 2, 1);
}
@Test
public void take()
{
MutableSet<Integer> set = this.getIntegerSet();
Verify.assertSize(2, Iterate.take(set, 2));
Verify.assertEmpty(Iterate.take(set, 0));
Verify.assertSize(5, Iterate.take(set, 5));
Verify.assertSize(5, Iterate.take(set, 10));
MutableSet<Integer> set2 = UnifiedSet.newSet();
Verify.assertEmpty(Iterate.take(set2, 2));
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.take(each, 2);
Verify.assertSize(2, result);
}));
}
@Test(expected = IllegalArgumentException.class)
public void take_null_throws()
{
Iterate.take(null, 1);
}
@Test(expected = IllegalArgumentException.class)
public void take_negative_throws()
{
Iterate.take(this.getIntegerSet(), -1);
}
@Test
public void drop()
{
MutableSet<Integer> set = this.getIntegerSet();
Verify.assertSize(3, Iterate.drop(set, 2));
Verify.assertEmpty(Iterate.drop(set, 5));
Verify.assertEmpty(Iterate.drop(set, 6));
Verify.assertSize(5, Iterate.drop(set, 0));
MutableSet<Integer> set2 = UnifiedSet.newSet();
Verify.assertEmpty(Iterate.drop(set2, 2));
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.drop(each, 2);
Verify.assertSize(3, result);
}));
}
@Test(expected = IllegalArgumentException.class)
public void drop_null_throws()
{
Iterate.drop(null, 1);
}
@Test(expected = IllegalArgumentException.class)
public void drop_negative_throws()
{
Iterate.drop(this.getIntegerSet(), -1);
}
@Test
public void getOnlySingleton()
{
Object value = new Object();
Assert.assertSame(value, Iterate.getOnly(Lists.fixedSize.of(value)));
}
@Test(expected = IllegalArgumentException.class)
public void getOnlyEmpty()
{
Iterate.getOnly(Lists.fixedSize.<String>of());
}
@Test(expected = IllegalArgumentException.class)
public void getOnlyMultiple()
{
Iterate.getOnly(Lists.fixedSize.of(new Object(), new Object()));
}
private static final class IterableAdapter<E>
implements Iterable<E>
{
private final Iterable<E> iterable;
private IterableAdapter(Iterable<E> newIterable)
{
this.iterable = newIterable;
}
@Override
public Iterator<E> iterator()
{
return this.iterable.iterator();
}
}
@Test
public void zip()
{
this.zip(FastList.newListWith("1", "2", "3", "4", "5", "6", "7"));
this.zip(Arrays.asList("1", "2", "3", "4", "5", "6", "7"));
this.zip(new HashSet<String>(FastList.newListWith("1", "2", "3", "4", "5", "6", "7")));
this.zip(FastList.newListWith("1", "2", "3", "4", "5", "6", "7").asLazy());
this.zip(new ArrayList<String>(Interval.oneTo(101).collect(String::valueOf).toList()));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.zip(null, null);});
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.zip(null, null, null);});
}
private void zip(Iterable<String> iterable)
{
List<Object> nulls = Collections.nCopies(Iterate.sizeOf(iterable), null);
Collection<Pair<String, Object>> pairs = Iterate.zip(iterable, nulls);
Assert.assertEquals(
UnifiedSet.newSet(iterable),
Iterate.collect(pairs, Functions.<String>firstOfPair(), UnifiedSet.<String>newSet()));
Assert.assertEquals(
nulls,
Iterate.collect(pairs, Functions.secondOfPair(), Lists.mutable.of()));
}
@Test
public void zipWithIndex()
{
this.zipWithIndex(FastList.newListWith("1", "2", "3", "4", "5", "6", "7"));
this.zipWithIndex(Arrays.asList("1", "2", "3", "4", "5", "6", "7"));
this.zipWithIndex(new HashSet<String>(FastList.newListWith("1", "2", "3", "4", "5", "6", "7")));
this.zipWithIndex(FastList.newListWith("1", "2", "3", "4", "5", "6", "7").asLazy());
this.zipWithIndex(Lists.immutable.of("1", "2", "3", "4", "5", "6", "7"));
this.zipWithIndex(new ArrayList<String>(Interval.oneTo(101).collect(String::valueOf).toList()));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.zipWithIndex(null);});
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.zipWithIndex(null, null);});
}
private void zipWithIndex(Iterable<String> iterable)
{
Collection<Pair<String, Integer>> pairs = Iterate.zipWithIndex(iterable);
Assert.assertEquals(
UnifiedSet.newSet(iterable),
Iterate.collect(pairs, Functions.<String>firstOfPair(), UnifiedSet.<String>newSet()));
Assert.assertEquals(
Interval.zeroTo(Iterate.sizeOf(iterable) - 1).toSet(),
Iterate.collect(pairs, Functions.<Integer>secondOfPair(), UnifiedSet.<Integer>newSet()));
}
@Test
public void chunk()
{
FastList<String> fastList = FastList.newListWith("1", "2", "3", "4", "5", "6", "7");
RichIterable<RichIterable<String>> groups1 = Iterate.chunk(fastList, 2);
RichIterable<Integer> sizes1 = groups1.collect(Functions.getSizeOf());
Assert.assertEquals(FastList.newListWith(2, 2, 2, 1), sizes1);
ArrayList<String> arrayList = new ArrayList<String>(fastList);
RichIterable<RichIterable<String>> groups2 = Iterate.chunk(arrayList, 2);
RichIterable<Integer> sizes2 = groups1.collect(Functions.getSizeOf());
Assert.assertEquals(FastList.newListWith(2, 2, 2, 1), sizes2);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.chunk(null, 1);});
}
@Test
public void getOnly()
{
Assert.assertEquals("first", Iterate.getOnly(FastList.newListWith("first")));
Assert.assertEquals("first", Iterate.getOnly(FastList.newListWith("first").asLazy()));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.getOnly(FastList.newListWith("first", "second"));
});
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.getOnly(null);});
}
private static class WordToItsLetters implements Function<String, Set<Character>>
{
private static final long serialVersionUID = 1L;
public Set<Character> valueOf(String name)
{
return StringIterate.asUppercaseSet(name);
}
}
@Test
public void makeString()
{
this.iterables.forEach(Procedures.cast(each -> {
String result = Iterate.makeString(each);
Assert.assertEquals("1, 2, 3, 4, 5", result);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.makeString(null);});
}
@Test
public void appendString()
{
this.iterables.forEach(Procedures.cast(each -> {
StringBuilder stringBuilder = new StringBuilder();
Iterate.appendString(each, stringBuilder);
String result = stringBuilder.toString();
Assert.assertEquals("1, 2, 3, 4, 5", result);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.appendString(null, new StringBuilder());});
}
@Test
public void aggregateByMutating()
{
this.aggregateByMutableResult(FastList.newListWith(1, 1, 1, 2, 2, 3));
this.aggregateByMutableResult(UnifiedSet.newSetWith(1, 1, 1, 2, 2, 3));
this.aggregateByMutableResult(HashBag.newBagWith(1, 1, 1, 2, 2, 3));
this.aggregateByMutableResult(new HashSet<Integer>(UnifiedSet.newSetWith(1, 1, 1, 2, 2, 3)));
this.aggregateByMutableResult(new LinkedList<Integer>(FastList.newListWith(1, 1, 1, 2, 2, 3)));
this.aggregateByMutableResult(new ArrayList<Integer>(FastList.newListWith(1, 1, 1, 2, 2, 3)));
this.aggregateByMutableResult(Arrays.asList(1, 1, 1, 2, 2, 3));
Verify.assertThrows(IllegalArgumentException.class, () -> {IterateTest.this.aggregateByMutableResult(null);});
}
private void aggregateByMutableResult(Iterable<Integer> iterable)
{
Function0<AtomicInteger> valueCreator = Functions0.zeroAtomicInteger();
Procedure2<AtomicInteger, Integer> sumAggregator = AtomicInteger::addAndGet;
MapIterable<String, AtomicInteger> aggregation = Iterate.aggregateInPlaceBy(iterable, String::valueOf, valueCreator, sumAggregator);
if (iterable instanceof Set)
{
Assert.assertEquals(1, aggregation.get("1").intValue());
Assert.assertEquals(2, aggregation.get("2").intValue());
Assert.assertEquals(3, aggregation.get("3").intValue());
}
else
{
Assert.assertEquals(3, aggregation.get("1").intValue());
Assert.assertEquals(4, aggregation.get("2").intValue());
Assert.assertEquals(3, aggregation.get("3").intValue());
}
}
@Test
public void aggregateByImmutableResult()
{
this.aggregateByImmutableResult(FastList.newListWith(1, 1, 1, 2, 2, 3));
this.aggregateByImmutableResult(UnifiedSet.newSetWith(1, 1, 1, 2, 2, 3));
this.aggregateByImmutableResult(HashBag.newBagWith(1, 1, 1, 2, 2, 3));
this.aggregateByImmutableResult(new HashSet<Integer>(UnifiedSet.newSetWith(1, 1, 1, 2, 2, 3)));
this.aggregateByImmutableResult(new LinkedList<Integer>(FastList.newListWith(1, 1, 1, 2, 2, 3)));
this.aggregateByImmutableResult(new ArrayList<Integer>(FastList.newListWith(1, 1, 1, 2, 2, 3)));
this.aggregateByImmutableResult(Arrays.asList(1, 1, 1, 2, 2, 3));
Verify.assertThrows(IllegalArgumentException.class, () -> {this.aggregateByImmutableResult(null);});
}
private void aggregateByImmutableResult(Iterable<Integer> iterable)
{
Function0<Integer> valueCreator = Functions0.value(0);
Function2<Integer, Integer, Integer> sumAggregator = (aggregate, value) -> aggregate + value;
MapIterable<String, Integer> aggregation = Iterate.aggregateBy(iterable, String::valueOf, valueCreator, sumAggregator);
if (iterable instanceof Set)
{
Assert.assertEquals(1, aggregation.get("1").intValue());
Assert.assertEquals(2, aggregation.get("2").intValue());
Assert.assertEquals(3, aggregation.get("3").intValue());
}
else
{
Assert.assertEquals(3, aggregation.get("1").intValue());
Assert.assertEquals(4, aggregation.get("2").intValue());
Assert.assertEquals(3, aggregation.get("3").intValue());
}
}
@Test
public void sumOfInt()
{
Assert.assertEquals(6, Iterate.sumOfInt(FastList.newListWith(1, 2, 3), value -> value));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.sumOfInt(null, null);});
}
@Test
public void sumOfLong()
{
Assert.assertEquals(6L, Iterate.sumOfLong(FastList.newListWith(Long.valueOf(1), Long.valueOf(2), Long.valueOf(3)), value -> value));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.sumOfLong(null, null);});
}
@Test
public void sumOfFloat()
{
Assert.assertEquals(6.0d, Iterate.sumOfFloat(FastList.newListWith(Float.valueOf(1), Float.valueOf(2), Float.valueOf(3)), value -> value), 0.0d);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.sumOfFloat(null, null);});
}
@Test
public void sumOfDouble()
{
Assert.assertEquals(6.0d, Iterate.sumOfDouble(FastList.newListWith(Double.valueOf(1), Double.valueOf(2), Double.valueOf(3)), value -> value), 0.0d);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.sumOfDouble(null, null);});
}
@Test
public void minBy()
{
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(FastList.newListWith(1, 2, 3), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(FastList.newListWith(3, 2, 1), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(FastList.newListWith(1, 2, 3).asSynchronized(), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(FastList.newListWith(3, 2, 1).asSynchronized(), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(Arrays.asList(1, 2, 3), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(Arrays.asList(3, 2, 1), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(new LinkedList<Integer>(Arrays.asList(1, 2, 3)), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(new LinkedList<Integer>(Arrays.asList(3, 2, 1)), Functions.getIntegerPassThru()));
}
@Test
public void minByThrowsOnEmpty()
{
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.minBy(FastList.<Integer>newList(), Functions.getIntegerPassThru());
});
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.minBy(FastList.<Integer>newList().asSynchronized(), Functions.getIntegerPassThru());
});
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.minBy(Arrays.<Integer>asList(), Functions.getIntegerPassThru());
});
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.minBy(new LinkedList<Integer>(), Functions.getIntegerPassThru());
});
}
@Test(expected = IllegalArgumentException.class)
public void minByThrowsOnNull()
{
Iterate.minBy(null, null);
}
@Test
public void maxBy()
{
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(FastList.newListWith(1, 2, 3), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(FastList.newListWith(3, 2, 1), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(FastList.newListWith(1, 2, 3).asSynchronized(), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(FastList.newListWith(3, 2, 1).asSynchronized(), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(Arrays.asList(1, 2, 3), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(Arrays.asList(3, 2, 1), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(new LinkedList<Integer>(Arrays.asList(1, 2, 3)), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(new LinkedList<Integer>(Arrays.asList(3, 2, 1)), Functions.getIntegerPassThru()));
}
@Test
public void maxByThrowsOnEmpty()
{
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.maxBy(FastList.<Integer>newList(), Functions.getIntegerPassThru());
});
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.maxBy(FastList.<Integer>newList().asSynchronized(), Functions.getIntegerPassThru());
});
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.maxBy(Arrays.<Integer>asList(), Functions.getIntegerPassThru());
});
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.maxBy(new LinkedList<Integer>(), Functions.getIntegerPassThru());
});
}
@Test(expected = IllegalArgumentException.class)
public void maxByThrowsOnNull()
{
Iterate.maxBy(null, null);
}
@Test
public void classIsNonInstantiable()
{
Verify.assertClassNonInstantiable(Iterate.class);
}
}
| unit-tests/src/test/java/com/gs/collections/impl/utility/IterateTest.java | /*
* Copyright 2014 Goldman Sachs.
*
* 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.gs.collections.impl.utility;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;
import com.gs.collections.api.RichIterable;
import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.function.Function0;
import com.gs.collections.api.block.function.Function2;
import com.gs.collections.api.block.function.Function3;
import com.gs.collections.api.block.procedure.Procedure2;
import com.gs.collections.api.collection.primitive.MutableBooleanCollection;
import com.gs.collections.api.collection.primitive.MutableByteCollection;
import com.gs.collections.api.collection.primitive.MutableCharCollection;
import com.gs.collections.api.collection.primitive.MutableDoubleCollection;
import com.gs.collections.api.collection.primitive.MutableFloatCollection;
import com.gs.collections.api.collection.primitive.MutableIntCollection;
import com.gs.collections.api.collection.primitive.MutableLongCollection;
import com.gs.collections.api.collection.primitive.MutableShortCollection;
import com.gs.collections.api.list.ImmutableList;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.map.MapIterable;
import com.gs.collections.api.map.MutableMap;
import com.gs.collections.api.multimap.Multimap;
import com.gs.collections.api.multimap.MutableMultimap;
import com.gs.collections.api.partition.PartitionIterable;
import com.gs.collections.api.set.MutableSet;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.api.tuple.Twin;
import com.gs.collections.impl.bag.mutable.HashBag;
import com.gs.collections.impl.block.factory.Comparators;
import com.gs.collections.impl.block.factory.Functions;
import com.gs.collections.impl.block.factory.Functions0;
import com.gs.collections.impl.block.factory.IntegerPredicates;
import com.gs.collections.impl.block.factory.ObjectIntProcedures;
import com.gs.collections.impl.block.factory.Predicates;
import com.gs.collections.impl.block.factory.Predicates2;
import com.gs.collections.impl.block.factory.PrimitiveFunctions;
import com.gs.collections.impl.block.factory.Procedures;
import com.gs.collections.impl.block.factory.StringFunctions;
import com.gs.collections.impl.block.function.AddFunction;
import com.gs.collections.impl.block.function.MaxSizeFunction;
import com.gs.collections.impl.block.function.MinSizeFunction;
import com.gs.collections.impl.block.predicate.PairPredicate;
import com.gs.collections.impl.block.procedure.CollectionAddProcedure;
import com.gs.collections.impl.factory.Lists;
import com.gs.collections.impl.factory.Maps;
import com.gs.collections.impl.factory.Sets;
import com.gs.collections.impl.list.Interval;
import com.gs.collections.impl.list.mutable.FastList;
import com.gs.collections.impl.list.mutable.primitive.BooleanArrayList;
import com.gs.collections.impl.list.mutable.primitive.ByteArrayList;
import com.gs.collections.impl.list.mutable.primitive.CharArrayList;
import com.gs.collections.impl.list.mutable.primitive.DoubleArrayList;
import com.gs.collections.impl.list.mutable.primitive.FloatArrayList;
import com.gs.collections.impl.list.mutable.primitive.IntArrayList;
import com.gs.collections.impl.list.mutable.primitive.LongArrayList;
import com.gs.collections.impl.list.mutable.primitive.ShortArrayList;
import com.gs.collections.impl.map.mutable.UnifiedMap;
import com.gs.collections.impl.math.IntegerSum;
import com.gs.collections.impl.math.Sum;
import com.gs.collections.impl.multimap.list.FastListMultimap;
import com.gs.collections.impl.set.mutable.UnifiedSet;
import com.gs.collections.impl.test.Verify;
import com.gs.collections.impl.tuple.Tuples;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static com.gs.collections.impl.factory.Iterables.*;
import static org.junit.Assert.*;
public class IterateTest
{
private MutableList<Iterable<Integer>> iterables;
@Before
public void setUp()
{
this.iterables = Lists.mutable.of();
this.iterables.add(Interval.oneTo(5).toList());
this.iterables.add(Interval.oneTo(5).toSet());
this.iterables.add(Interval.oneTo(5).addAllTo(new ArrayList<Integer>(5)));
this.iterables.add(Collections.unmodifiableList(new ArrayList<Integer>(Interval.oneTo(5))));
this.iterables.add(Collections.unmodifiableCollection(new ArrayList<Integer>(Interval.oneTo(5))));
this.iterables.add(Interval.oneTo(5));
this.iterables.add(Interval.oneTo(5).asLazy());
this.iterables.add(new IterableAdapter<Integer>(Interval.oneTo(5)));
}
@Test
public void addAllTo()
{
Verify.assertContainsAll(Iterate.addAllTo(FastList.newListWith(1, 2, 3), FastList.newList()), 1, 2, 3);
}
@Test
public void sizeOf()
{
Assert.assertEquals(5, Iterate.sizeOf(Interval.oneTo(5)));
Assert.assertEquals(5, Iterate.sizeOf(Interval.oneTo(5).toList()));
Assert.assertEquals(5, Iterate.sizeOf(Interval.oneTo(5).asLazy()));
Assert.assertEquals(3, Iterate.sizeOf(UnifiedMap.newWithKeysValues(1, 1, 2, 2, 3, 3)));
Assert.assertEquals(5, Iterate.sizeOf(new IterableAdapter<Integer>(Interval.oneTo(5))));
}
@Test
public void toArray()
{
Object[] expected = {1, 2, 3, 4, 5};
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5)));
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5).toList()));
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5).asLazy()));
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5).toSortedMap(a -> a, a -> a)));
Assert.assertArrayEquals(expected, Iterate.toArray(new IterableAdapter<Integer>(Interval.oneTo(5))));
}
@Test(expected = NullPointerException.class)
public void toArray_NullParameter()
{
Iterate.toArray(null);
}
@Test
public void toArray_with_array()
{
Object[] expected = {1, 2, 3, 4, 5};
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5), new Object[5]));
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5).toList(), new Object[5]));
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5).asLazy(), new Object[5]));
Assert.assertArrayEquals(expected, Iterate.toArray(Interval.oneTo(5).toSortedMap(a -> a, a -> a), new Object[5]));
Assert.assertArrayEquals(expected, Iterate.toArray(new IterableAdapter<Integer>(Interval.oneTo(5)), new Object[5]));
Assert.assertArrayEquals(new Integer[]{1, 2, 3, 4, 5, 6, 7}, Iterate.toArray(new IterableAdapter<Integer>(Interval.oneTo(7)), new Object[5]));
}
@Test
public void fromToDoit()
{
MutableList<Integer> list = Lists.mutable.of();
Interval.fromTo(6, 10).forEach(Procedures.cast(list::add));
Verify.assertContainsAll(list, 6, 10);
}
@Test
public void injectInto()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertEquals(Integer.valueOf(15), Iterate.injectInto(0, each, AddFunction.INTEGER))));
}
@Test
public void injectIntoInt()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertEquals(15, Iterate.injectInto(0, each, AddFunction.INTEGER_TO_INT))));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.injectInto(0, null, AddFunction.INTEGER_TO_INT);
});
}
@Test
public void injectIntoLong()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertEquals(15L, Iterate.injectInto(0L, each, AddFunction.INTEGER_TO_LONG))));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.injectInto(0L, null, AddFunction.INTEGER_TO_LONG);
});
}
@Test
public void injectIntoDouble()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertEquals(15.0d, Iterate.injectInto(0.0d, each, AddFunction.INTEGER_TO_DOUBLE), 0.001)));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.injectInto(0.0d, null, AddFunction.INTEGER_TO_DOUBLE);
});
}
@Test
public void injectIntoFloat()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertEquals(15.0d, Iterate.injectInto(0.0f, each, AddFunction.INTEGER_TO_FLOAT), 0.001)));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.injectInto(0.0f, null, AddFunction.INTEGER_TO_FLOAT);
});
}
@Test
public void injectInto2()
{
Assert.assertEquals(new Double(7), Iterate.injectInto(1.0, iList(1.0, 2.0, 3.0), AddFunction.DOUBLE));
}
@Test
public void injectIntoString()
{
Assert.assertEquals("0123", Iterate.injectInto("0", iList("1", "2", "3"), AddFunction.STRING));
}
@Test
public void injectIntoMaxString()
{
Assert.assertEquals(Integer.valueOf(3), Iterate.injectInto(Integer.MIN_VALUE, iList("1", "12", "123"), MaxSizeFunction.STRING));
}
@Test
public void injectIntoMinString()
{
Assert.assertEquals(Integer.valueOf(1), Iterate.injectInto(Integer.MAX_VALUE, iList("1", "12", "123"), MinSizeFunction.STRING));
}
@Test
public void flatCollectFromAttributes()
{
MutableList<ListContainer<String>> list = mList(
new ListContainer<String>(Lists.mutable.of("One", "Two")),
new ListContainer<String>(Lists.mutable.of("Two-and-a-half", "Three", "Four")),
new ListContainer<String>(Lists.mutable.<String>of()),
new ListContainer<String>(Lists.mutable.of("Five")));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(list, ListContainer.<String>getListFunction()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(Collections.synchronizedList(list), ListContainer.getListFunction()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(Collections.synchronizedCollection(list), ListContainer.getListFunction()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(LazyIterate.adapt(list), ListContainer.<String>getListFunction()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(new ArrayList<ListContainer<String>>(list), ListContainer.getListFunction()));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.flatCollect(null, null);});
}
@Test
public void flatCollectFromAttributesWithTarget()
{
MutableList<ListContainer<String>> list = Lists.fixedSize.of(
new ListContainer<String>(Lists.mutable.of("One", "Two")),
new ListContainer<String>(Lists.mutable.of("Two-and-a-half", "Three", "Four")),
new ListContainer<String>(Lists.mutable.<String>of()),
new ListContainer<String>(Lists.mutable.of("Five")));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(list, ListContainer.<String>getListFunction(), FastList.newList()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(Collections.synchronizedList(list), ListContainer.<String>getListFunction(), FastList.newList()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(Collections.synchronizedCollection(list), ListContainer.<String>getListFunction(), FastList.newList()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(LazyIterate.adapt(list), ListContainer.<String>getListFunction(), FastList.newList()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(new ArrayList<ListContainer<String>>(list), ListContainer.<String>getListFunction(), FastList.newList()));
Assert.assertEquals(
iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"),
Iterate.flatCollect(new IterableAdapter<ListContainer<String>>(new ArrayList<ListContainer<String>>(list)), ListContainer.getListFunction(), FastList.newList()));
}
@Test(expected = IllegalArgumentException.class)
public void flatCollectFromAttributesWithTarget_NullParameter()
{
Iterate.flatCollect(null, null, UnifiedSet.newSet());
}
@Test
public void flatCollectFromAttributesUsingStringFunction()
{
MutableList<ListContainer<String>> list = Lists.mutable.of(
new ListContainer<String>(Lists.mutable.of("One", "Two")),
new ListContainer<String>(Lists.mutable.of("Two-and-a-half", "Three", "Four")),
new ListContainer<String>(Lists.mutable.<String>of()),
new ListContainer<String>(Lists.mutable.of("Five")));
Function<ListContainer<String>, List<String>> function = ListContainer::getList;
Collection<String> result = Iterate.flatCollect(list, function);
FastList<String> result2 = Iterate.flatCollect(list, function, FastList.<String>newList());
Assert.assertEquals(iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"), result);
Assert.assertEquals(iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"), result2);
}
@Test
public void flatCollectOneLevel()
{
MutableList<MutableList<String>> list = Lists.mutable.of(
Lists.mutable.of("One", "Two"),
Lists.mutable.of("Two-and-a-half", "Three", "Four"),
Lists.mutable.<String>of(),
Lists.mutable.of("Five"));
Collection<String> result = Iterate.flatten(list);
Assert.assertEquals(iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"), result);
}
@Test
public void flatCollectOneLevel_target()
{
MutableList<MutableList<String>> list = Lists.mutable.of(
Lists.mutable.of("One", "Two"),
Lists.mutable.of("Two-and-a-half", "Three", "Four"),
Lists.mutable.<String>of(),
Lists.mutable.of("Five"));
MutableList<String> target = Lists.mutable.of();
Collection<String> result = Iterate.flatten(list, target);
Assert.assertSame(result, target);
Assert.assertEquals(iList("One", "Two", "Two-and-a-half", "Three", "Four", "Five"), result);
}
@Test
public void groupBy()
{
FastList<String> source = FastList.newListWith("Ted", "Sally", "Mary", "Bob", "Sara");
Multimap<Character, String> result1 = Iterate.groupBy(source, StringFunctions.firstLetter());
Multimap<Character, String> result2 = Iterate.groupBy(Collections.synchronizedList(source), StringFunctions.firstLetter());
Multimap<Character, String> result3 = Iterate.groupBy(Collections.synchronizedCollection(source), StringFunctions.firstLetter());
Multimap<Character, String> result4 = Iterate.groupBy(LazyIterate.adapt(source), StringFunctions.firstLetter());
Multimap<Character, String> result5 = Iterate.groupBy(new ArrayList<String>(source), StringFunctions.firstLetter());
MutableMultimap<Character, String> expected = FastListMultimap.newMultimap();
expected.put('T', "Ted");
expected.put('S', "Sally");
expected.put('M', "Mary");
expected.put('B', "Bob");
expected.put('S', "Sara");
Assert.assertEquals(expected, result1);
Assert.assertEquals(expected, result2);
Assert.assertEquals(expected, result3);
Assert.assertEquals(expected, result4);
Assert.assertEquals(expected, result5);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.groupBy(null, null);});
}
@Test
public void groupByEach()
{
MutableList<String> source = FastList.newListWith("Ted", "Sally", "Sally", "Mary", "Bob", "Sara");
Function<String, Set<Character>> uppercaseSetFunction = new WordToItsLetters();
Multimap<Character, String> result1 = Iterate.groupByEach(source, uppercaseSetFunction);
Multimap<Character, String> result2 = Iterate.groupByEach(Collections.synchronizedList(source), uppercaseSetFunction);
Multimap<Character, String> result3 = Iterate.groupByEach(Collections.synchronizedCollection(source), uppercaseSetFunction);
Multimap<Character, String> result4 = Iterate.groupByEach(LazyIterate.adapt(source), uppercaseSetFunction);
Multimap<Character, String> result5 = Iterate.groupByEach(new ArrayList<String>(source), uppercaseSetFunction);
MutableMultimap<Character, String> expected = FastListMultimap.newMultimap();
expected.put('T', "Ted");
expected.putAll('E', FastList.newListWith("Ted"));
expected.put('D', "Ted");
expected.putAll('S', FastList.newListWith("Sally", "Sally", "Sara"));
expected.putAll('A', FastList.newListWith("Sally", "Sally", "Mary", "Sara"));
expected.putAll('L', FastList.newListWith("Sally", "Sally"));
expected.putAll('Y', FastList.newListWith("Sally", "Sally", "Mary"));
expected.put('M', "Mary");
expected.putAll('R', FastList.newListWith("Mary", "Sara"));
expected.put('B', "Bob");
expected.put('O', "Bob");
Assert.assertEquals(expected, result1);
Assert.assertEquals(expected, result2);
Assert.assertEquals(expected, result3);
Assert.assertEquals(expected, result4);
Assert.assertEquals(expected, result5);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.groupByEach(null, null);});
}
@Test
public void groupByWithTarget()
{
FastList<String> source = FastList.newListWith("Ted", "Sally", "Mary", "Bob", "Sara");
Multimap<Character, String> result1 = Iterate.groupBy(source, StringFunctions.firstLetter(), FastListMultimap.newMultimap());
Multimap<Character, String> result2 = Iterate.groupBy(Collections.synchronizedList(source), StringFunctions.firstLetter(), FastListMultimap.newMultimap());
Multimap<Character, String> result3 = Iterate.groupBy(Collections.synchronizedCollection(source), StringFunctions.firstLetter(), FastListMultimap.newMultimap());
Multimap<Character, String> result4 = Iterate.groupBy(LazyIterate.adapt(source), StringFunctions.firstLetter(), FastListMultimap.newMultimap());
Multimap<Character, String> result5 = Iterate.groupBy(new ArrayList<String>(source), StringFunctions.firstLetter(), FastListMultimap.newMultimap());
MutableMultimap<Character, String> expected = FastListMultimap.newMultimap();
expected.put('T', "Ted");
expected.put('S', "Sally");
expected.put('M', "Mary");
expected.put('B', "Bob");
expected.put('S', "Sara");
Assert.assertEquals(expected, result1);
Assert.assertEquals(expected, result2);
Assert.assertEquals(expected, result3);
Assert.assertEquals(expected, result4);
Assert.assertEquals(expected, result5);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.groupBy(null, null, null);});
}
@Test
public void groupByEachWithTarget()
{
MutableList<String> source = FastList.newListWith("Ted", "Sally", "Sally", "Mary", "Bob", "Sara");
Function<String, Set<Character>> uppercaseSetFunction = StringIterate::asUppercaseSet;
Multimap<Character, String> result1 = Iterate.groupByEach(source, uppercaseSetFunction, FastListMultimap.<Character, String>newMultimap());
Multimap<Character, String> result2 = Iterate.groupByEach(Collections.synchronizedList(source), uppercaseSetFunction, FastListMultimap.<Character, String>newMultimap());
Multimap<Character, String> result3 = Iterate.groupByEach(Collections.synchronizedCollection(source), uppercaseSetFunction, FastListMultimap.<Character, String>newMultimap());
Multimap<Character, String> result4 = Iterate.groupByEach(LazyIterate.adapt(source), uppercaseSetFunction, FastListMultimap.<Character, String>newMultimap());
Multimap<Character, String> result5 = Iterate.groupByEach(new ArrayList<String>(source), uppercaseSetFunction, FastListMultimap.<Character, String>newMultimap());
MutableMultimap<Character, String> expected = FastListMultimap.newMultimap();
expected.put('T', "Ted");
expected.putAll('E', FastList.newListWith("Ted"));
expected.put('D', "Ted");
expected.putAll('S', FastList.newListWith("Sally", "Sally", "Sara"));
expected.putAll('A', FastList.newListWith("Sally", "Sally", "Mary", "Sara"));
expected.putAll('L', FastList.newListWith("Sally", "Sally"));
expected.putAll('Y', FastList.newListWith("Sally", "Sally"));
expected.put('M', "Mary");
expected.putAll('R', FastList.newListWith("Mary", "Sara"));
expected.put('Y', "Mary");
expected.put('B', "Bob");
expected.put('O', "Bob");
Assert.assertEquals(expected, result1);
Assert.assertEquals(expected, result2);
Assert.assertEquals(expected, result3);
Assert.assertEquals(expected, result4);
Assert.assertEquals(expected, result5);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.groupByEach(null, null, null);});
}
@Test
public void toList()
{
Assert.assertEquals(FastList.newListWith(1, 2, 3), FastList.newList(Interval.oneTo(3)));
}
@Test
public void contains()
{
Assert.assertTrue(Iterate.contains(FastList.newListWith(1, 2, 3), 1));
Assert.assertFalse(Iterate.contains(FastList.newListWith(1, 2, 3), 4));
Assert.assertTrue(Iterate.contains(FastList.newListWith(1, 2, 3).asLazy(), 1));
Assert.assertTrue(Iterate.contains(UnifiedMap.newWithKeysValues(1, 1, 2, 2, 3, 3), 1));
Assert.assertFalse(Iterate.contains(UnifiedMap.newWithKeysValues(1, 1, 2, 2, 3, 3), 4));
Assert.assertTrue(Iterate.contains(Interval.oneTo(3), 1));
Assert.assertFalse(Iterate.contains(Interval.oneTo(3), 4));
}
public static final class ListContainer<T>
{
private final List<T> list;
private ListContainer(List<T> list)
{
this.list = list;
}
private static <V> Function<ListContainer<V>, List<V>> getListFunction()
{
return anObject -> anObject.list;
}
public List<T> getList()
{
return this.list;
}
}
@Test
public void getFirstAndLast()
{
MutableList<Boolean> list = mList(Boolean.TRUE, null, Boolean.FALSE);
Assert.assertEquals(Boolean.TRUE, Iterate.getFirst(list));
Assert.assertEquals(Boolean.FALSE, Iterate.getLast(list));
Assert.assertEquals(Boolean.TRUE, Iterate.getFirst(Collections.unmodifiableList(list)));
Assert.assertEquals(Boolean.FALSE, Iterate.getLast(Collections.unmodifiableList(list)));
Assert.assertEquals(Boolean.TRUE, Iterate.getFirst(new IterableAdapter<Boolean>(list)));
Assert.assertEquals(Boolean.FALSE, Iterate.getLast(new IterableAdapter<Boolean>(list)));
}
@Test(expected = IllegalArgumentException.class)
public void getFirst_null_throws()
{
Iterate.getFirst(null);
}
@Test(expected = IllegalArgumentException.class)
public void getList_null_throws()
{
Iterate.getLast(null);
}
@Test
public void getFirstAndLastInterval()
{
Assert.assertEquals(Integer.valueOf(1), Iterate.getFirst(Interval.oneTo(5)));
Assert.assertEquals(Integer.valueOf(5), Iterate.getLast(Interval.oneTo(5)));
}
@Test
public void getFirstAndLastLinkedList()
{
List<Boolean> list = new LinkedList<Boolean>(mList(Boolean.TRUE, null, Boolean.FALSE));
Assert.assertEquals(Boolean.TRUE, Iterate.getFirst(list));
Assert.assertEquals(Boolean.FALSE, Iterate.getLast(list));
}
@Test
public void getFirstAndLastTreeSet()
{
Set<String> set = new TreeSet<String>(mList("1", "2"));
Assert.assertEquals("1", Iterate.getFirst(set));
Assert.assertEquals("2", Iterate.getLast(set));
}
@Test
public void getFirstAndLastCollection()
{
Collection<Boolean> list = mList(Boolean.TRUE, null, Boolean.FALSE).asSynchronized();
Assert.assertEquals(Boolean.TRUE, Iterate.getFirst(list));
Assert.assertEquals(Boolean.FALSE, Iterate.getLast(list));
}
@Test
public void getFirstAndLastOnEmpty()
{
Assert.assertNull(Iterate.getFirst(mList()));
Assert.assertNull(Iterate.getLast(mList()));
}
@Test
public void getFirstAndLastForSet()
{
Set<Integer> orderedSet = new TreeSet<Integer>();
orderedSet.add(1);
orderedSet.add(2);
orderedSet.add(3);
Assert.assertEquals(Integer.valueOf(1), Iterate.getFirst(orderedSet));
Assert.assertEquals(Integer.valueOf(3), Iterate.getLast(orderedSet));
}
@Test
public void getFirstAndLastOnEmptyForSet()
{
MutableSet<Object> set = UnifiedSet.newSet();
Assert.assertNull(Iterate.getFirst(set));
Assert.assertNull(Iterate.getLast(set));
}
private MutableSet<Integer> getIntegerSet()
{
return Interval.toSet(1, 5);
}
@Test
public void selectDifferentTargetCollection()
{
MutableSet<Integer> set = this.getIntegerSet();
List<Integer> list = Iterate.select(set, Predicates.instanceOf(Integer.class), new ArrayList<Integer>());
Assert.assertEquals(FastList.newListWith(1, 2, 3, 4, 5), list);
}
@Test
public void rejectWithDifferentTargetCollection()
{
MutableSet<Integer> set = this.getIntegerSet();
Collection<Integer> result = Iterate.reject(set, Predicates.instanceOf(Integer.class), FastList.newList());
Verify.assertEmpty(result);
}
@Test
public void count_empty()
{
Assert.assertEquals(0, Iterate.count(iList(), a -> true));
}
@Test(expected = IllegalArgumentException.class)
public void count_null_throws()
{
Iterate.count(null, a -> true);
}
@Test
public void toMap()
{
MutableSet<Integer> set = UnifiedSet.newSet(this.getIntegerSet());
MutableMap<String, Integer> map = Iterate.toMap(set, String::valueOf);
Verify.assertSize(5, map);
Object expectedValue = 1;
Object expectedKey = "1";
Verify.assertContainsKeyValue(expectedKey, expectedValue, map);
Verify.assertContainsKeyValue("2", 2, map);
Verify.assertContainsKeyValue("3", 3, map);
Verify.assertContainsKeyValue("4", 4, map);
Verify.assertContainsKeyValue("5", 5, map);
}
@Test
public void addToMap()
{
MutableSet<Integer> set = Interval.toSet(1, 5);
MutableMap<String, Integer> map = UnifiedMap.newMap();
map.put("the answer", 42);
Iterate.addToMap(set, String::valueOf, map);
Verify.assertSize(6, map);
Verify.assertContainsAllKeyValues(
map,
"the answer", 42,
"1", 1,
"2", 2,
"3", 3,
"4", 4,
"5", 5);
}
@Test
public void toMapSelectingKeyAndValue()
{
MutableSet<Integer> set = UnifiedSet.newSet(this.getIntegerSet());
MutableMap<String, Integer> map = Iterate.toMap(set, String::valueOf, object -> 10 * object);
Verify.assertSize(5, map);
Verify.assertContainsKeyValue("1", 10, map);
Verify.assertContainsKeyValue("2", 20, map);
Verify.assertContainsKeyValue("3", 30, map);
Verify.assertContainsKeyValue("4", 40, map);
Verify.assertContainsKeyValue("5", 50, map);
}
@Test
public void forEachWithIndex()
{
this.iterables.forEach(Procedures.cast(each -> {
UnifiedSet<Integer> set = UnifiedSet.newSet();
Iterate.forEachWithIndex(each, ObjectIntProcedures.fromProcedure(CollectionAddProcedure.on(set)));
Assert.assertEquals(UnifiedSet.newSetWith(1, 2, 3, 4, 5), set);
}));
}
@Test
public void selectPairs()
{
ImmutableList<Twin<String>> twins = iList(
Tuples.twin("1", "2"),
Tuples.twin("2", "1"),
Tuples.twin("3", "3"));
Collection<Twin<String>> results = Iterate.select(twins, new PairPredicate<String, String>()
{
public boolean accept(String argument1, String argument2)
{
return "1".equals(argument1) || "1".equals(argument2);
}
});
Verify.assertSize(2, results);
}
@Test
public void detect()
{
this.iterables.forEach(Procedures.cast(each -> {
Integer result = Iterate.detect(each, Predicates.instanceOf(Integer.class));
Assert.assertTrue(UnifiedSet.newSet(each).contains(result));
}));
}
@Test
public void detectIndex()
{
MutableList<Integer> list = Interval.toReverseList(1, 5);
Assert.assertEquals(4, Iterate.detectIndex(list, Predicates.equal(1)));
Assert.assertEquals(0, Iterate.detectIndex(list, Predicates.equal(5)));
Assert.assertEquals(-1, Iterate.detectIndex(Lists.immutable.of(), Predicates.equal(1)));
Assert.assertEquals(-1, Iterate.detectIndex(Sets.immutable.of(), Predicates.equal(1)));
}
@Test
public void detectIndexWithTreeSet()
{
Set<Integer> treeSet = new TreeSet<Integer>(Interval.toReverseList(1, 5));
Assert.assertEquals(0, Iterate.detectIndex(treeSet, Predicates.equal(1)));
Assert.assertEquals(4, Iterate.detectIndex(treeSet, Predicates.equal(5)));
}
@Test
public void detectIndexWith()
{
MutableList<Integer> list = Interval.toReverseList(1, 5);
Assert.assertEquals(4, Iterate.detectIndexWith(list, Predicates2.equal(), 1));
Assert.assertEquals(0, Iterate.detectIndexWith(list, Predicates2.equal(), 5));
Assert.assertEquals(-1, Iterate.detectIndexWith(iList(), Predicates2.equal(), 5));
Assert.assertEquals(-1, Iterate.detectIndexWith(iSet(), Predicates2.equal(), 5));
}
@Test
public void detectIndexWithWithTreeSet()
{
Set<Integer> treeSet = new TreeSet<Integer>(Interval.toReverseList(1, 5));
Assert.assertEquals(0, Iterate.detectIndexWith(treeSet, Predicates2.equal(), 1));
Assert.assertEquals(4, Iterate.detectIndexWith(treeSet, Predicates2.equal(), 5));
}
@Test
public void detectWithIfNone()
{
this.iterables.forEach(Procedures.cast(each -> {
Integer result = Iterate.detectWithIfNone(each, Predicates2.instanceOf(), Integer.class, 5);
Verify.assertContains(result, UnifiedSet.newSet(each));
}));
}
@Test
public void selectWith()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.selectWith(each, Predicates2.greaterThan(), 3);
Assert.assertTrue(result.containsAll(FastList.newListWith(4, 5)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.selectWith(null, null, null);});
}
@Test
public void selectWithWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.selectWith(each, Predicates2.greaterThan(), 3, FastList.<Integer>newList());
Assert.assertTrue(result.containsAll(FastList.newListWith(4, 5)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.selectWith(null, null, null, null);});
}
@Test
public void rejectWith()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.rejectWith(each, Predicates2.greaterThan(), 3);
Assert.assertTrue(result.containsAll(FastList.newListWith(1, 2, 3)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.rejectWith(null, null, null);});
}
@Test
public void rejectWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.rejectWith(each, Predicates2.greaterThan(), 3, FastList.<Integer>newList());
Assert.assertTrue(result.containsAll(FastList.newListWith(1, 2, 3)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.rejectWith(null, null, null, null);});
}
@Test
public void selectAndRejectWith()
{
this.iterables.forEach(Procedures.cast(each -> {
Twin<MutableList<Integer>> result = Iterate.selectAndRejectWith(each, Predicates2.greaterThan(), 3);
Assert.assertEquals(iBag(4, 5), result.getOne().toBag());
Assert.assertEquals(iBag(1, 2, 3), result.getTwo().toBag());
}));
}
@Test
public void partition()
{
this.iterables.forEach(Procedures.cast(each -> {
PartitionIterable<Integer> result = Iterate.partition(each, Predicates.greaterThan(3));
Assert.assertEquals(iBag(4, 5), result.getSelected().toBag());
Assert.assertEquals(iBag(1, 2, 3), result.getRejected().toBag());
}));
}
@Test
public void rejectTargetCollection()
{
MutableList<Integer> list = Interval.toReverseList(1, 5);
MutableList<Integer> results = Iterate.reject(list, Predicates.instanceOf(Integer.class), FastList.newList());
Verify.assertEmpty(results);
}
@Test
public void rejectOnRandomAccessTargetCollection()
{
List<Integer> list = Collections.synchronizedList(Interval.toReverseList(1, 5));
MutableList<Integer> results =
Iterate.reject(list, Predicates.instanceOf(Integer.class), FastList.<Integer>newList());
Verify.assertEmpty(results);
}
@Test
public void rejectWithTargetCollection()
{
MutableList<Integer> list = Interval.toReverseList(1, 5);
MutableList<Integer> results = Iterate.rejectWith(list, Predicates2.instanceOf(), Integer.class, FastList.newList());
Verify.assertEmpty(results);
}
@Test
public void rejectWithOnRandomAccessTargetCollection()
{
List<Integer> list = Collections.synchronizedList(Interval.toReverseList(1, 5));
MutableList<Integer> results = Iterate.rejectWith(list, Predicates2.instanceOf(), Integer.class, FastList.newList());
Verify.assertEmpty(results);
}
@Test
public void anySatisfy()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertTrue(Iterate.anySatisfy(each, Predicates.instanceOf(Integer.class)))));
}
@Test
public void anySatisfyWith()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertTrue(Iterate.anySatisfyWith(each, Predicates2.instanceOf(), Integer.class))));
}
@Test
public void allSatisfy()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertTrue(Iterate.allSatisfy(each, Predicates.instanceOf(Integer.class)))));
}
@Test
public void allSatisfyWith()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertTrue(Iterate.allSatisfyWith(each, Predicates2.instanceOf(), Integer.class))));
}
@Test
public void noneSatisfy()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertTrue(Iterate.noneSatisfy(each, Predicates.instanceOf(String.class)))));
}
@Test
public void noneSatisfyWith()
{
this.iterables.forEach(Procedures.cast(each -> Assert.assertTrue(Iterate.noneSatisfyWith(each, Predicates2.instanceOf(), String.class))));
}
@Test
public void selectWithSet()
{
Verify.assertSize(1, Iterate.selectWith(this.getIntegerSet(), Predicates2.equal(), 1));
Verify.assertSize(1, Iterate.selectWith(this.getIntegerSet(), Predicates2.equal(), 1, FastList.<Integer>newList()));
}
@Test
public void rejectWithSet()
{
Verify.assertSize(4, Iterate.rejectWith(this.getIntegerSet(), Predicates2.equal(), 1));
Verify.assertSize(4, Iterate.rejectWith(this.getIntegerSet(), Predicates2.equal(), 1, FastList.<Integer>newList()));
}
@Test
public void detectWithSet()
{
Assert.assertEquals(Integer.valueOf(1), Iterate.detectWith(this.getIntegerSet(), Predicates2.equal(), 1));
}
@Test
public void detectWithRandomAccess()
{
List<Integer> list = Collections.synchronizedList(Interval.oneTo(5));
Assert.assertEquals(Integer.valueOf(1), Iterate.detectWith(list, Predicates2.equal(), 1));
}
@Test
public void anySatisfyWithSet()
{
Assert.assertTrue(Iterate.anySatisfyWith(this.getIntegerSet(), Predicates2.equal(), 1));
}
@Test
public void allSatisfyWithSet()
{
Assert.assertFalse(Iterate.allSatisfyWith(this.getIntegerSet(), Predicates2.equal(), 1));
Assert.assertTrue(Iterate.allSatisfyWith(this.getIntegerSet(), Predicates2.instanceOf(), Integer.class));
}
@Test
public void noneSatisfyWithSet()
{
Assert.assertTrue(Iterate.noneSatisfyWith(this.getIntegerSet(), Predicates2.equal(), 100));
Assert.assertFalse(Iterate.noneSatisfyWith(this.getIntegerSet(), Predicates2.instanceOf(), Integer.class));
}
@Test
public void selectAndRejectWithSet()
{
Twin<MutableList<Integer>> result = Iterate.selectAndRejectWith(this.getIntegerSet(), Predicates2.in(), iList(1));
Verify.assertSize(1, result.getOne());
Verify.assertSize(4, result.getTwo());
}
@Test
public void forEach()
{
this.iterables.forEach(Procedures.cast(each -> {
UnifiedSet<Integer> set = UnifiedSet.newSet();
Iterate.forEach(each, Procedures.cast(set::add));
Assert.assertEquals(UnifiedSet.newSetWith(1, 2, 3, 4, 5), set);
}));
}
@Test
public void collectIf()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<String> result = Iterate.collectIf(each, Predicates.greaterThan(3), String::valueOf);
Assert.assertTrue(result.containsAll(FastList.newListWith("4", "5")));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.collectIf(null, null, null);});
}
@Test
public void collectIfTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<String> result = Iterate.collectIf(each, Predicates.greaterThan(3), String::valueOf, FastList.newList());
Assert.assertTrue(result.containsAll(FastList.newListWith("4", "5")));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.collectIf(null, null, null, null);});
}
@Test
public void collect()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<String> result = Iterate.collect(each, String::valueOf);
Assert.assertTrue(result.containsAll(FastList.newListWith("1", "2", "3", "4", "5")));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.collect(null, a -> a);});
}
@Test
public void collectBoolean()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableBooleanCollection result = Iterate.collectBoolean(each, PrimitiveFunctions.integerIsPositive());
Assert.assertTrue(result.containsAll(true, true, true, true, true));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectBoolean(null, PrimitiveFunctions.integerIsPositive());
});
}
@Test
public void collectBooleanWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableBooleanCollection expected = new BooleanArrayList();
MutableBooleanCollection actual = Iterate.collectBoolean(each, PrimitiveFunctions.integerIsPositive(), expected);
Assert.assertTrue(expected.containsAll(true, true, true, true, true));
Assert.assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectBoolean(null, PrimitiveFunctions.integerIsPositive(), new BooleanArrayList());
});
}
@Test
public void collectByte()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableByteCollection result = Iterate.collectByte(each, PrimitiveFunctions.unboxIntegerToByte());
Assert.assertTrue(result.containsAll((byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectByte(null, PrimitiveFunctions.unboxIntegerToByte());
});
}
@Test
public void collectByteWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableByteCollection expected = new ByteArrayList();
MutableByteCollection actual = Iterate.collectByte(each, PrimitiveFunctions.unboxIntegerToByte(), expected);
Assert.assertTrue(actual.containsAll((byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5));
Assert.assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectByte(null, PrimitiveFunctions.unboxIntegerToByte(), new ByteArrayList());
});
}
@Test
public void collectChar()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableCharCollection result = Iterate.collectChar(each, PrimitiveFunctions.unboxIntegerToChar());
Assert.assertTrue(result.containsAll((char) 1, (char) 2, (char) 3, (char) 4, (char) 5));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectChar(null, PrimitiveFunctions.unboxIntegerToChar());
});
}
@Test
public void collectCharWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableCharCollection expected = new CharArrayList();
MutableCharCollection actual = Iterate.collectChar(each, PrimitiveFunctions.unboxIntegerToChar(), expected);
Assert.assertTrue(actual.containsAll((char) 1, (char) 2, (char) 3, (char) 4, (char) 5));
Assert.assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectChar(null, PrimitiveFunctions.unboxIntegerToChar(), new CharArrayList());
});
}
@Test
public void collectDouble()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableDoubleCollection result = Iterate.collectDouble(each, PrimitiveFunctions.unboxIntegerToDouble());
Assert.assertTrue(result.containsAll(1.0d, 2.0d, 3.0d, 4.0d, 5.0d));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectDouble(null, PrimitiveFunctions.unboxIntegerToDouble());
});
}
@Test
public void collectDoubleWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableDoubleCollection expected = new DoubleArrayList();
MutableDoubleCollection actual = Iterate.collectDouble(each, PrimitiveFunctions.unboxIntegerToDouble(), expected);
Assert.assertTrue(actual.containsAll(1.0d, 2.0d, 3.0d, 4.0d, 5.0d));
Assert.assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectDouble(null, PrimitiveFunctions.unboxIntegerToDouble(), new DoubleArrayList());
});
}
@Test
public void collectFloat()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableFloatCollection result = Iterate.collectFloat(each, PrimitiveFunctions.unboxIntegerToFloat());
Assert.assertTrue(result.containsAll(1.0f, 2.0f, 3.0f, 4.0f, 5.0f));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectFloat(null, PrimitiveFunctions.unboxIntegerToFloat());
});
}
@Test
public void collectFloatWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableFloatCollection expected = new FloatArrayList();
MutableFloatCollection actual = Iterate.collectFloat(each, PrimitiveFunctions.unboxIntegerToFloat(), expected);
Assert.assertTrue(actual.containsAll(1.0f, 2.0f, 3.0f, 4.0f, 5.0f));
Assert.assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectFloat(null, PrimitiveFunctions.unboxIntegerToFloat(), new FloatArrayList());
});
}
@Test
public void collectInt()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableIntCollection result = Iterate.collectInt(each, PrimitiveFunctions.unboxIntegerToInt());
Assert.assertTrue(result.containsAll(1, 2, 3, 4, 5));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectInt(null, PrimitiveFunctions.unboxIntegerToInt());
});
}
@Test
public void collectIntWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableIntCollection expected = new IntArrayList();
MutableIntCollection actual = Iterate.collectInt(each, PrimitiveFunctions.unboxIntegerToInt(), expected);
Assert.assertTrue(actual.containsAll(1, 2, 3, 4, 5));
assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectInt(null, PrimitiveFunctions.unboxIntegerToInt(), new IntArrayList());
});
}
@Test
public void collectLong()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableLongCollection result = Iterate.collectLong(each, PrimitiveFunctions.unboxIntegerToLong());
Assert.assertTrue(result.containsAll(1L, 2L, 3L, 4L, 5L));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectLong(null, PrimitiveFunctions.unboxIntegerToLong());
});
}
@Test
public void collectLongWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableLongCollection expected = new LongArrayList();
MutableLongCollection actual = Iterate.collectLong(each, PrimitiveFunctions.unboxIntegerToLong(), expected);
Assert.assertTrue(actual.containsAll(1L, 2L, 3L, 4L, 5L));
Assert.assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectLong(null, PrimitiveFunctions.unboxIntegerToLong(), new LongArrayList());
});
}
@Test
public void collectShort()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableShortCollection result = Iterate.collectShort(each, PrimitiveFunctions.unboxIntegerToShort());
Assert.assertTrue(result.containsAll((short) 1, (short) 2, (short) 3, (short) 4, (short) 5));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectShort(null, PrimitiveFunctions.unboxIntegerToShort());
});
}
@Test
public void collectShortWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
MutableShortCollection expected = new ShortArrayList();
MutableShortCollection actual = Iterate.collectShort(each, PrimitiveFunctions.unboxIntegerToShort(), expected);
Assert.assertTrue(actual.containsAll((short) 1, (short) 2, (short) 3, (short) 4, (short) 5));
Assert.assertSame("Target list sent as parameter not returned", expected, actual);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.collectShort(null, PrimitiveFunctions.unboxIntegerToShort(), new ShortArrayList());
});
}
@Test
public void collect_sortedSetSource()
{
class Foo implements Comparable<Foo>
{
private final int value;
Foo(int value)
{
this.value = value;
}
public int getValue()
{
return this.value;
}
@Override
public int compareTo(Foo that)
{
return Comparators.naturalOrder().compare(this.value, that.value);
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || this.getClass() != o.getClass())
{
return false;
}
Foo foo = (Foo) o;
return this.value == foo.value;
}
@Override
public int hashCode()
{
return this.value;
}
}
class Bar
{
private final int value;
Bar(int value)
{
this.value = value;
}
public int getValue()
{
return this.value;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || this.getClass() != o.getClass())
{
return false;
}
Bar bar = (Bar) o;
return this.value == bar.value;
}
@Override
public int hashCode()
{
return this.value;
}
}
Set<Foo> foos = new TreeSet<Foo>();
foos.add(new Foo(1));
foos.add(new Foo(2));
Collection<Bar> bars = Iterate.collect(foos, foo -> new Bar(foo.getValue()));
Assert.assertEquals(FastList.newListWith(new Bar(1), new Bar(2)), bars);
}
@Test
public void collectTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<String> result = Iterate.collect(each, String::valueOf, UnifiedSet.<String>newSet());
Assert.assertTrue(result.containsAll(FastList.newListWith("1", "2", "3", "4", "5")));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.collect(null, a -> a, null);});
}
@Test
public void collectWith()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<String> result = Iterate.collectWith(each, (each1, parm) -> each1.toString() + parm, " ");
Assert.assertTrue(result.containsAll(FastList.newListWith("1 ", "2 ", "3 ", "4 ", "5 ")));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.collectWith(null, null, null);});
}
@Test
public void collectWithWithTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<String> result = Iterate.collectWith(each, (each1, parm) -> each1.toString() + parm, " ", UnifiedSet.newSet());
Assert.assertTrue(result.containsAll(FastList.newListWith("1 ", "2 ", "3 ", "4 ", "5 ")));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.collectWith(null, null, null, null);});
}
@Test
public void removeIf()
{
MutableList<Integer> integers = Interval.oneTo(5).toList();
this.assertRemoveIfFromList(integers);
this.assertRemoveIfFromList(Collections.synchronizedList(integers));
this.assertRemoveIfFromList(FastList.newList(integers));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.removeIf(null, null);});
}
private void assertRemoveIfFromList(List<Integer> newIntegers)
{
Collection<Integer> result = Iterate.removeIf(newIntegers, IntegerPredicates.isEven());
Assert.assertSame(newIntegers, result);
Verify.assertContainsAll(newIntegers, 1, 3, 5);
Verify.assertSize(3, newIntegers);
}
@Test
public void removeIfLinkedList()
{
List<Integer> integers = new LinkedList<Integer>(Interval.oneTo(5).toList());
this.assertRemoveIfFromList(integers);
}
@Test
public void removeIfAll()
{
MutableList<Integer> integers = Interval.oneTo(5).toList();
Collection<Integer> result = Iterate.removeIf(integers, a -> true);
Assert.assertSame(integers, result);
Verify.assertSize(0, integers);
}
@Test
public void removeIfNone()
{
MutableList<Integer> integers = Interval.oneTo(5).toList();
Collection<Integer> result = Iterate.removeIf(integers, a -> false);
Assert.assertSame(integers, result);
Verify.assertSize(5, integers);
}
@Test
public void removeIfFromSet()
{
MutableSet<Integer> integers = Interval.toSet(1, 5);
Collection<Integer> result = Iterate.removeIf(integers, IntegerPredicates.isEven());
Assert.assertSame(integers, result);
Verify.assertContainsAll(integers, 1, 3, 5);
Verify.assertSize(3, integers);
}
@Test
public void injectIntoIfProcedure()
{
Integer newItemToIndex = 99;
MutableMap<String, Integer> index1 = createPretendIndex(1);
MutableMap<String, Integer> index2 = createPretendIndex(2);
MutableMap<String, Integer> index3 = createPretendIndex(3);
MutableMap<String, Integer> index4 = createPretendIndex(4);
MutableMap<String, Integer> index5 = createPretendIndex(5);
MutableMap<String, MutableMap<String, Integer>> allIndexes = UnifiedMap.newMapWith(
Tuples.pair("pretend index 1", index1),
Tuples.pair("pretend index 2", index2),
Tuples.pair("pretend index 3", index3),
Tuples.pair("pretend index 4", index4),
Tuples.pair("pretend index 5", index5));
MutableSet<MutableMap<String, Integer>> systemIndexes = Sets.fixedSize.of(index3, index5);
MapIterate.injectIntoIf(newItemToIndex, allIndexes, Predicates.notIn(systemIndexes), (itemToAdd, index) -> {
index.put(itemToAdd.toString(), itemToAdd);
return itemToAdd;
});
Verify.assertSize(5, allIndexes);
Verify.assertContainsKey("pretend index 2", allIndexes);
Verify.assertContainsKey("pretend index 3", allIndexes);
Verify.assertContainsKeyValue("99", newItemToIndex, index1);
Verify.assertContainsKeyValue("99", newItemToIndex, index2);
Verify.assertNotContainsKey("99", index3);
Verify.assertContainsKeyValue("99", newItemToIndex, index4);
Verify.assertNotContainsKey("99", index5);
}
public static MutableMap<String, Integer> createPretendIndex(int initialEntry)
{
return UnifiedMap.newWithKeysValues(String.valueOf(initialEntry), initialEntry);
}
@Test
public void isEmpty()
{
Assert.assertTrue(Iterate.isEmpty(null));
Assert.assertTrue(Iterate.isEmpty(Lists.fixedSize.of()));
Assert.assertFalse(Iterate.isEmpty(Lists.fixedSize.of("1")));
Assert.assertTrue(Iterate.isEmpty(Maps.fixedSize.of()));
Assert.assertFalse(Iterate.isEmpty(Maps.fixedSize.of("1", "1")));
Assert.assertTrue(Iterate.isEmpty(new IterableAdapter<Object>(Lists.fixedSize.of())));
Assert.assertFalse(Iterate.isEmpty(new IterableAdapter<String>(Lists.fixedSize.of("1"))));
Assert.assertTrue(Iterate.isEmpty(Lists.fixedSize.of().asLazy()));
Assert.assertFalse(Iterate.isEmpty(Lists.fixedSize.of("1").asLazy()));
}
@Test
public void notEmpty()
{
Assert.assertFalse(Iterate.notEmpty(null));
Assert.assertFalse(Iterate.notEmpty(Lists.fixedSize.of()));
Assert.assertTrue(Iterate.notEmpty(Lists.fixedSize.of("1")));
Assert.assertFalse(Iterate.notEmpty(Maps.fixedSize.of()));
Assert.assertTrue(Iterate.notEmpty(Maps.fixedSize.of("1", "1")));
Assert.assertFalse(Iterate.notEmpty(new IterableAdapter<Object>(Lists.fixedSize.of())));
Assert.assertTrue(Iterate.notEmpty(new IterableAdapter<String>(Lists.fixedSize.of("1"))));
Assert.assertFalse(Iterate.notEmpty(Lists.fixedSize.of().asLazy()));
Assert.assertTrue(Iterate.notEmpty(Lists.fixedSize.of("1").asLazy()));
}
@Test
public void toSortedList()
{
MutableList<Integer> list = Interval.toReverseList(1, 5);
MutableList<Integer> sorted = Iterate.toSortedList(list);
Verify.assertStartsWith(sorted, 1, 2, 3, 4, 5);
}
@Test
public void toSortedListWithComparator()
{
MutableList<Integer> list = Interval.oneTo(5).toList();
MutableList<Integer> sorted = Iterate.toSortedList(list, Collections.reverseOrder());
Verify.assertStartsWith(sorted, 5, 4, 3, 2, 1);
}
@Test
public void select()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.select(each, Predicates.greaterThan(3));
Assert.assertTrue(result.containsAll(FastList.newListWith(4, 5)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.select(null, null);});
}
@Test
public void selectTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.select(each, Predicates.greaterThan(3), FastList.newList());
Assert.assertTrue(result.containsAll(FastList.newListWith(4, 5)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.select(null, null, null);});
}
@Test
public void reject()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.reject(each, Predicates.greaterThan(3));
Assert.assertTrue(result.containsAll(FastList.newListWith(1, 2, 3)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.reject(null, null);});
}
@Test
public void rejectTarget()
{
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.reject(each, Predicates.greaterThan(3), FastList.newList());
Assert.assertTrue(result.containsAll(FastList.newListWith(1, 2, 3)));
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.reject(null, null, null);});
}
@Test
public void selectInstancesOf()
{
Iterable<Number> numbers1 = Collections.unmodifiableList(new ArrayList<Number>(FastList.newListWith(1, 2.0, 3, 4.0, 5)));
Iterable<Number> numbers2 = Collections.unmodifiableCollection(new ArrayList<Number>(FastList.newListWith(1, 2.0, 3, 4.0, 5)));
Verify.assertContainsAll(Iterate.selectInstancesOf(numbers1, Integer.class), 1, 3, 5);
Verify.assertContainsAll(Iterate.selectInstancesOf(numbers2, Integer.class), 1, 3, 5);
}
@Test
public void count()
{
this.iterables.forEach(Procedures.cast(each -> {
int result = Iterate.count(each, Predicates.greaterThan(3));
Assert.assertEquals(2, result);
}));
}
@Test(expected = IllegalArgumentException.class)
public void count_null_null_throws()
{
Iterate.count(null, null);
}
@Test
public void countWith()
{
this.iterables.forEach(Procedures.cast(each -> {
int result = Iterate.countWith(each, Predicates2.greaterThan(), 3);
Assert.assertEquals(2, result);
}));
}
@Test(expected = IllegalArgumentException.class)
public void countWith_null_throws()
{
Iterate.countWith(null, null, null);
}
@Test
public void injectIntoWith()
{
Sum result = new IntegerSum(0);
Integer parameter = 2;
MutableList<Integer> integers = Interval.oneTo(5).toList();
this.basicTestDoubleSum(result, integers, parameter);
}
@Test
public void injectIntoWithRandomAccess()
{
Sum result = new IntegerSum(0);
Integer parameter = 2;
MutableList<Integer> integers = Interval.oneTo(5).toList().asSynchronized();
this.basicTestDoubleSum(result, integers, parameter);
}
private void basicTestDoubleSum(Sum newResult, Collection<Integer> newIntegers, Integer newParameter)
{
Function3<Sum, Integer, Integer, Sum> function = (sum, element, withValue) -> sum.add(element.intValue() * withValue.intValue());
Sum sumOfDoubledValues = Iterate.injectIntoWith(newResult, newIntegers, function, newParameter);
Assert.assertEquals(30, sumOfDoubledValues.getValue().intValue());
}
@Test
public void injectIntoWithHashSet()
{
Sum result = new IntegerSum(0);
Integer parameter = 2;
MutableSet<Integer> integers = Interval.toSet(1, 5);
this.basicTestDoubleSum(result, integers, parameter);
}
@Test
public void forEachWith()
{
this.iterables.forEach(Procedures.cast(each -> {
Sum result = new IntegerSum(0);
Iterate.forEachWith(each, (integer, parm) -> {result.add(integer.intValue() * parm.intValue());}, 2);
Assert.assertEquals(30, result.getValue().intValue());
}));
}
@Test
public void forEachWithSets()
{
Sum result = new IntegerSum(0);
MutableSet<Integer> integers = Interval.toSet(1, 5);
Iterate.forEachWith(integers, (each, parm) -> {result.add(each.intValue() * parm.intValue());}, 2);
Assert.assertEquals(30, result.getValue().intValue());
}
@Test
public void removeIfWith()
{
MutableList<Integer> objects = FastList.newList(Lists.fixedSize.of(1, 2, 3, null));
Iterate.removeIfWith(objects, Predicates2.isNull(), null);
Verify.assertSize(3, objects);
Verify.assertContainsAll(objects, 1, 2, 3);
MutableList<Integer> objects1 = FastList.newList(Lists.fixedSize.of(null, 1, 2, 3));
Iterate.removeIfWith(objects1, Predicates2.isNull(), null);
Verify.assertSize(3, objects1);
Verify.assertContainsAll(objects1, 1, 2, 3);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.removeIfWith(null, null, null);});
}
@Test
public void removeIfWithFastList()
{
MutableList<Integer> objects = FastList.newListWith(1, 2, 3, null);
Iterate.removeIfWith(objects, Predicates2.isNull(), null);
Verify.assertSize(3, objects);
Verify.assertContainsAll(objects, 1, 2, 3);
MutableList<Integer> objects1 = FastList.newListWith(null, 1, 2, 3);
Iterate.removeIfWith(objects1, Predicates2.isNull(), null);
Verify.assertSize(3, objects1);
Verify.assertContainsAll(objects1, 1, 2, 3);
}
@Test
public void removeIfWithRandomAccess()
{
List<Integer> objects = Collections.synchronizedList(new ArrayList<Integer>(Lists.fixedSize.of(1, 2, 3, null)));
Iterate.removeIfWith(objects, Predicates2.isNull(), null);
Verify.assertSize(3, objects);
Verify.assertContainsAll(objects, 1, 2, 3);
List<Integer> objects1 =
Collections.synchronizedList(new ArrayList<Integer>(Lists.fixedSize.of(null, 1, 2, 3)));
Iterate.removeIfWith(objects1, Predicates2.isNull(), null);
Verify.assertSize(3, objects1);
Verify.assertContainsAll(objects1, 1, 2, 3);
}
@Test
public void removeIfWithLinkedList()
{
List<Integer> objects = new LinkedList<Integer>(Lists.fixedSize.of(1, 2, 3, null));
Iterate.removeIfWith(objects, Predicates2.isNull(), null);
Verify.assertSize(3, objects);
Verify.assertContainsAll(objects, 1, 2, 3);
List<Integer> objects1 = new LinkedList<Integer>(Lists.fixedSize.of(null, 1, 2, 3));
Iterate.removeIfWith(objects1, Predicates2.isNull(), null);
Verify.assertSize(3, objects1);
Verify.assertContainsAll(objects1, 1, 2, 3);
}
@Test
public void sortThis()
{
MutableList<Integer> list = Interval.oneTo(5).toList();
Collections.shuffle(list);
Verify.assertStartsWith(Iterate.sortThis(list), 1, 2, 3, 4, 5);
List<Integer> list3 = Interval.oneTo(5).addAllTo(new LinkedList<Integer>());
Collections.shuffle(list3);
Verify.assertStartsWith(Iterate.sortThis(list3), 1, 2, 3, 4, 5);
List<Integer> listOfSizeOne = new LinkedList<Integer>();
listOfSizeOne.add(1);
Iterate.sortThis(listOfSizeOne);
Assert.assertEquals(FastList.newListWith(1), listOfSizeOne);
}
@Test
public void sortThisWithPredicate()
{
MutableList<Integer> list = Interval.oneTo(5).toList();
Interval.oneTo(5).addAllTo(list);
Collections.shuffle(list);
Verify.assertStartsWith(Iterate.sortThis(list, Predicates2.<Integer>lessThan()), 1, 1, 2, 2, 3, 3, 4, 4, 5, 5);
MutableList<Integer> list2 = Interval.oneTo(5).toList();
Interval.oneTo(5).addAllTo(list2);
Collections.shuffle(list2);
Verify.assertStartsWith(Iterate.sortThis(list2, Predicates2.<Integer>greaterThan()), 5, 5, 4, 4, 3, 3, 2, 2, 1, 1);
List<Integer> list3 = Interval.oneTo(5).addAllTo(new LinkedList<Integer>());
Interval.oneTo(5).addAllTo(list3);
Collections.shuffle(list3);
Verify.assertStartsWith(Iterate.sortThis(list3, Predicates2.<Integer>lessThan()), 1, 1, 2, 2, 3, 3, 4, 4, 5, 5);
}
@Test
public void sortThisBy()
{
MutableList<Integer> list = Interval.oneTo(5).toList();
Interval.oneTo(5).addAllTo(list);
Collections.shuffle(list);
Verify.assertStartsWith(Iterate.sortThisBy(list, String::valueOf), 1, 1, 2, 2, 3, 3, 4, 4, 5, 5);
}
@Test
public void sortThisWithComparator()
{
MutableList<Integer> list = Interval.oneTo(5).toList();
Verify.assertStartsWith(Iterate.sortThis(list, Collections.reverseOrder()), 5, 4, 3, 2, 1);
List<Integer> list3 = Interval.oneTo(5).addAllTo(new LinkedList<Integer>());
Verify.assertStartsWith(Iterate.sortThis(list3, Collections.reverseOrder()), 5, 4, 3, 2, 1);
}
@Test
public void take()
{
MutableSet<Integer> set = this.getIntegerSet();
Verify.assertSize(2, Iterate.take(set, 2));
Verify.assertEmpty(Iterate.take(set, 0));
Verify.assertSize(5, Iterate.take(set, 5));
Verify.assertSize(5, Iterate.take(set, 10));
MutableSet<Integer> set2 = UnifiedSet.newSet();
Verify.assertEmpty(Iterate.take(set2, 2));
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.take(each, 2);
Verify.assertSize(2, result);
}));
}
@Test(expected = IllegalArgumentException.class)
public void take_null_throws()
{
Iterate.take(null, 1);
}
@Test(expected = IllegalArgumentException.class)
public void take_negative_throws()
{
Iterate.take(this.getIntegerSet(), -1);
}
@Test
public void drop()
{
MutableSet<Integer> set = this.getIntegerSet();
Verify.assertSize(3, Iterate.drop(set, 2));
Verify.assertEmpty(Iterate.drop(set, 5));
Verify.assertEmpty(Iterate.drop(set, 6));
Verify.assertSize(5, Iterate.drop(set, 0));
MutableSet<Integer> set2 = UnifiedSet.newSet();
Verify.assertEmpty(Iterate.drop(set2, 2));
this.iterables.forEach(Procedures.cast(each -> {
Collection<Integer> result = Iterate.drop(each, 2);
Verify.assertSize(3, result);
}));
}
@Test(expected = IllegalArgumentException.class)
public void drop_null_throws()
{
Iterate.drop(null, 1);
}
@Test(expected = IllegalArgumentException.class)
public void drop_negative_throws()
{
Iterate.drop(this.getIntegerSet(), -1);
}
@Test
public void getOnlySingleton()
{
Object value = new Object();
Assert.assertSame(value, Iterate.getOnly(Lists.fixedSize.of(value)));
}
@Test(expected = IllegalArgumentException.class)
public void getOnlyEmpty()
{
Iterate.getOnly(Lists.fixedSize.<String>of());
}
@Test(expected = IllegalArgumentException.class)
public void getOnlyMultiple()
{
Iterate.getOnly(Lists.fixedSize.of(new Object(), new Object()));
}
private static final class IterableAdapter<E>
implements Iterable<E>
{
private final Iterable<E> iterable;
private IterableAdapter(Iterable<E> newIterable)
{
this.iterable = newIterable;
}
@Override
public Iterator<E> iterator()
{
return this.iterable.iterator();
}
}
@Test
public void zip()
{
this.zip(FastList.newListWith("1", "2", "3", "4", "5", "6", "7"));
this.zip(Arrays.asList("1", "2", "3", "4", "5", "6", "7"));
this.zip(new HashSet<String>(FastList.newListWith("1", "2", "3", "4", "5", "6", "7")));
this.zip(FastList.newListWith("1", "2", "3", "4", "5", "6", "7").asLazy());
this.zip(new ArrayList<String>(Interval.oneTo(101).collect(String::valueOf).toList()));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.zip(null, null);});
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.zip(null, null, null);});
}
private void zip(Iterable<String> iterable)
{
List<Object> nulls = Collections.nCopies(Iterate.sizeOf(iterable), null);
Collection<Pair<String, Object>> pairs = Iterate.zip(iterable, nulls);
Assert.assertEquals(
UnifiedSet.newSet(iterable),
Iterate.collect(pairs, Functions.<String>firstOfPair(), UnifiedSet.<String>newSet()));
Assert.assertEquals(
nulls,
Iterate.collect(pairs, Functions.secondOfPair(), Lists.mutable.of()));
}
@Test
public void zipWithIndex()
{
this.zipWithIndex(FastList.newListWith("1", "2", "3", "4", "5", "6", "7"));
this.zipWithIndex(Arrays.asList("1", "2", "3", "4", "5", "6", "7"));
this.zipWithIndex(new HashSet<String>(FastList.newListWith("1", "2", "3", "4", "5", "6", "7")));
this.zipWithIndex(FastList.newListWith("1", "2", "3", "4", "5", "6", "7").asLazy());
this.zipWithIndex(Lists.immutable.of("1", "2", "3", "4", "5", "6", "7"));
this.zipWithIndex(new ArrayList<String>(Interval.oneTo(101).collect(String::valueOf).toList()));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.zipWithIndex(null);});
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.zipWithIndex(null, null);});
}
private void zipWithIndex(Iterable<String> iterable)
{
Collection<Pair<String, Integer>> pairs = Iterate.zipWithIndex(iterable);
Assert.assertEquals(
UnifiedSet.newSet(iterable),
Iterate.collect(pairs, Functions.<String>firstOfPair(), UnifiedSet.<String>newSet()));
Assert.assertEquals(
Interval.zeroTo(Iterate.sizeOf(iterable) - 1).toSet(),
Iterate.collect(pairs, Functions.<Integer>secondOfPair(), UnifiedSet.<Integer>newSet()));
}
@Test
public void chunk()
{
FastList<String> fastList = FastList.newListWith("1", "2", "3", "4", "5", "6", "7");
RichIterable<RichIterable<String>> groups1 = Iterate.chunk(fastList, 2);
RichIterable<Integer> sizes1 = groups1.collect(Functions.getSizeOf());
Assert.assertEquals(FastList.newListWith(2, 2, 2, 1), sizes1);
ArrayList<String> arrayList = new ArrayList<String>(fastList);
RichIterable<RichIterable<String>> groups2 = Iterate.chunk(arrayList, 2);
RichIterable<Integer> sizes2 = groups1.collect(Functions.getSizeOf());
Assert.assertEquals(FastList.newListWith(2, 2, 2, 1), sizes2);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.chunk(null, 1);});
}
@Test
public void getOnly()
{
Assert.assertEquals("first", Iterate.getOnly(FastList.newListWith("first")));
Assert.assertEquals("first", Iterate.getOnly(FastList.newListWith("first").asLazy()));
Verify.assertThrows(IllegalArgumentException.class, () -> {
Iterate.getOnly(FastList.newListWith("first", "second"));
});
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.getOnly(null);});
}
private static class WordToItsLetters implements Function<String, Set<Character>>
{
private static final long serialVersionUID = 1L;
public Set<Character> valueOf(String name)
{
return StringIterate.asUppercaseSet(name);
}
}
@Test
public void makeString()
{
this.iterables.forEach(Procedures.cast(each -> {
String result = Iterate.makeString(each);
Assert.assertEquals("1, 2, 3, 4, 5", result);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.makeString(null);});
}
@Test
public void appendString()
{
this.iterables.forEach(Procedures.cast(each -> {
StringBuilder stringBuilder = new StringBuilder();
Iterate.appendString(each, stringBuilder);
String result = stringBuilder.toString();
Assert.assertEquals("1, 2, 3, 4, 5", result);
}));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.appendString(null, new StringBuilder());});
}
@Test
public void aggregateByMutating()
{
this.aggregateByMutableResult(FastList.newListWith(1, 1, 1, 2, 2, 3));
this.aggregateByMutableResult(UnifiedSet.newSetWith(1, 1, 1, 2, 2, 3));
this.aggregateByMutableResult(HashBag.newBagWith(1, 1, 1, 2, 2, 3));
this.aggregateByMutableResult(new HashSet<Integer>(UnifiedSet.newSetWith(1, 1, 1, 2, 2, 3)));
this.aggregateByMutableResult(new LinkedList<Integer>(FastList.newListWith(1, 1, 1, 2, 2, 3)));
this.aggregateByMutableResult(new ArrayList<Integer>(FastList.newListWith(1, 1, 1, 2, 2, 3)));
this.aggregateByMutableResult(Arrays.asList(1, 1, 1, 2, 2, 3));
Verify.assertThrows(IllegalArgumentException.class, () -> {IterateTest.this.aggregateByMutableResult(null);});
}
private void aggregateByMutableResult(Iterable<Integer> iterable)
{
Function0<AtomicInteger> valueCreator = Functions0.zeroAtomicInteger();
Procedure2<AtomicInteger, Integer> sumAggregator = AtomicInteger::addAndGet;
MapIterable<String, AtomicInteger> aggregation = Iterate.aggregateInPlaceBy(iterable, String::valueOf, valueCreator, sumAggregator);
if (iterable instanceof Set)
{
Assert.assertEquals(1, aggregation.get("1").intValue());
Assert.assertEquals(2, aggregation.get("2").intValue());
Assert.assertEquals(3, aggregation.get("3").intValue());
}
else
{
Assert.assertEquals(3, aggregation.get("1").intValue());
Assert.assertEquals(4, aggregation.get("2").intValue());
Assert.assertEquals(3, aggregation.get("3").intValue());
}
}
@Test
public void aggregateByImmutableResult()
{
this.aggregateByImmutableResult(FastList.newListWith(1, 1, 1, 2, 2, 3));
this.aggregateByImmutableResult(UnifiedSet.newSetWith(1, 1, 1, 2, 2, 3));
this.aggregateByImmutableResult(HashBag.newBagWith(1, 1, 1, 2, 2, 3));
this.aggregateByImmutableResult(new HashSet<Integer>(UnifiedSet.newSetWith(1, 1, 1, 2, 2, 3)));
this.aggregateByImmutableResult(new LinkedList<Integer>(FastList.newListWith(1, 1, 1, 2, 2, 3)));
this.aggregateByImmutableResult(new ArrayList<Integer>(FastList.newListWith(1, 1, 1, 2, 2, 3)));
this.aggregateByImmutableResult(Arrays.asList(1, 1, 1, 2, 2, 3));
Verify.assertThrows(IllegalArgumentException.class, () -> {this.aggregateByImmutableResult(null);});
}
private void aggregateByImmutableResult(Iterable<Integer> iterable)
{
Function0<Integer> valueCreator = Functions0.value(0);
Function2<Integer, Integer, Integer> sumAggregator = (aggregate, value) -> aggregate + value;
MapIterable<String, Integer> aggregation = Iterate.aggregateBy(iterable, String::valueOf, valueCreator, sumAggregator);
if (iterable instanceof Set)
{
Assert.assertEquals(1, aggregation.get("1").intValue());
Assert.assertEquals(2, aggregation.get("2").intValue());
Assert.assertEquals(3, aggregation.get("3").intValue());
}
else
{
Assert.assertEquals(3, aggregation.get("1").intValue());
Assert.assertEquals(4, aggregation.get("2").intValue());
Assert.assertEquals(3, aggregation.get("3").intValue());
}
}
@Test
public void sumOfInt()
{
Assert.assertEquals(6, Iterate.sumOfInt(FastList.newListWith(1, 2, 3), value -> value));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.sumOfInt(null, null);});
}
@Test
public void sumOfLong()
{
Assert.assertEquals(6L, Iterate.sumOfLong(FastList.newListWith(Long.valueOf(1), Long.valueOf(2), Long.valueOf(3)), value -> value));
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.sumOfLong(null, null);});
}
@Test
public void sumOfFloat()
{
Assert.assertEquals(6.0d, Iterate.sumOfFloat(FastList.newListWith(Float.valueOf(1), Float.valueOf(2), Float.valueOf(3)), value -> value), 0.0d);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.sumOfFloat(null, null);});
}
@Test
public void sumOfDouble()
{
Assert.assertEquals(6.0d, Iterate.sumOfDouble(FastList.newListWith(Double.valueOf(1), Double.valueOf(2), Double.valueOf(3)), value -> value), 0.0d);
Verify.assertThrows(IllegalArgumentException.class, () -> {Iterate.sumOfDouble(null, null);});
}
@Test
public void minBy()
{
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(FastList.newListWith(1, 2, 3), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(FastList.newListWith(3, 2, 1), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(FastList.newListWith(1, 2, 3).asSynchronized(), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(FastList.newListWith(3, 2, 1).asSynchronized(), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(Arrays.asList(1, 2, 3), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(Arrays.asList(3, 2, 1), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(new LinkedList<Integer>(Arrays.asList(1, 2, 3)), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(1), Iterate.minBy(new LinkedList<Integer>(Arrays.asList(3, 2, 1)), Functions.getIntegerPassThru()));
}
@Test
public void minByThrowsOnEmpty()
{
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.minBy(FastList.<Integer>newList(), Functions.getIntegerPassThru());
});
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.minBy(FastList.<Integer>newList().asSynchronized(), Functions.getIntegerPassThru());
});
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.minBy(Arrays.<Integer>asList(), Functions.getIntegerPassThru());
});
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.minBy(new LinkedList<Integer>(), Functions.getIntegerPassThru());
});
}
@Test(expected = IllegalArgumentException.class)
public void minByThrowsOnNull()
{
Iterate.minBy(null, null);
}
@Test
public void maxBy()
{
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(FastList.newListWith(1, 2, 3), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(FastList.newListWith(3, 2, 1), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(FastList.newListWith(1, 2, 3).asSynchronized(), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(FastList.newListWith(3, 2, 1).asSynchronized(), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(Arrays.asList(1, 2, 3), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(Arrays.asList(3, 2, 1), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(new LinkedList<Integer>(Arrays.asList(1, 2, 3)), Functions.getIntegerPassThru()));
Assert.assertEquals(Integer.valueOf(3), Iterate.maxBy(new LinkedList<Integer>(Arrays.asList(3, 2, 1)), Functions.getIntegerPassThru()));
}
@Test
public void maxByThrowsOnEmpty()
{
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.maxBy(FastList.<Integer>newList(), Functions.getIntegerPassThru());
});
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.maxBy(FastList.<Integer>newList().asSynchronized(), Functions.getIntegerPassThru());
});
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.maxBy(Arrays.<Integer>asList(), Functions.getIntegerPassThru());
});
Verify.assertThrows(NoSuchElementException.class, () -> {
Iterate.maxBy(new LinkedList<Integer>(), Functions.getIntegerPassThru());
});
}
@Test(expected = IllegalArgumentException.class)
public void maxByThrowsOnNull()
{
Iterate.maxBy(null, null);
}
@Test
public void classIsNonInstantiable()
{
Verify.assertClassNonInstantiable(Iterate.class);
}
}
| [GSCOLLECT-1360] Replace anonymous inner classes with lambdas and method references in IterateTest and generated code.
git-svn-id: c173b60cd131fd691c78c4467fb70aa9fb29b506@597 d5c9223b-1aff-41ac-aadd-f810b4a99ac4
| unit-tests/src/test/java/com/gs/collections/impl/utility/IterateTest.java | [GSCOLLECT-1360] Replace anonymous inner classes with lambdas and method references in IterateTest and generated code. | <ide><path>nit-tests/src/test/java/com/gs/collections/impl/utility/IterateTest.java
<ide> this.iterables = Lists.mutable.of();
<ide> this.iterables.add(Interval.oneTo(5).toList());
<ide> this.iterables.add(Interval.oneTo(5).toSet());
<add> this.iterables.add(Interval.oneTo(5).toBag());
<add> this.iterables.add(Interval.oneTo(5).toSortedSet());
<add> this.iterables.add(Interval.oneTo(5).toSortedMap(i -> i, i -> i));
<add> this.iterables.add(Interval.oneTo(5).toMap(i -> i, i -> i));
<ide> this.iterables.add(Interval.oneTo(5).addAllTo(new ArrayList<Integer>(5)));
<ide> this.iterables.add(Collections.unmodifiableList(new ArrayList<Integer>(Interval.oneTo(5))));
<ide> this.iterables.add(Collections.unmodifiableCollection(new ArrayList<Integer>(Interval.oneTo(5)))); |
|
Java | lgpl-2.1 | fcf4e768b865ef6e5b646dc902f471f443e97b5c | 0 | tadamski/wildfly,tomazzupan/wildfly,wildfly/wildfly,iweiss/wildfly,pferraro/wildfly,jstourac/wildfly,rhusar/wildfly,tomazzupan/wildfly,tadamski/wildfly,jstourac/wildfly,wildfly/wildfly,wildfly/wildfly,jstourac/wildfly,golovnin/wildfly,golovnin/wildfly,xasx/wildfly,wildfly/wildfly,rhusar/wildfly,rhusar/wildfly,jstourac/wildfly,99sono/wildfly,99sono/wildfly,xasx/wildfly,iweiss/wildfly,golovnin/wildfly,pferraro/wildfly,iweiss/wildfly,iweiss/wildfly,tomazzupan/wildfly,xasx/wildfly,99sono/wildfly,pferraro/wildfly,rhusar/wildfly,tadamski/wildfly,pferraro/wildfly | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.domain.http.server;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.domain.http.server.Constants.ACCEPT;
import static org.jboss.as.domain.http.server.Constants.ACCESS_CONTROL_ALLOW_ORIGIN;
import static org.jboss.as.domain.http.server.Constants.APPLICATION_DMR_ENCODED;
import static org.jboss.as.domain.http.server.Constants.APPLICATION_JSON;
import static org.jboss.as.domain.http.server.Constants.CONTENT_DISPOSITION;
import static org.jboss.as.domain.http.server.Constants.CONTENT_TYPE;
import static org.jboss.as.domain.http.server.Constants.GET;
import static org.jboss.as.domain.http.server.Constants.INTERNAL_SERVER_ERROR;
import static org.jboss.as.domain.http.server.Constants.METHOD_NOT_ALLOWED;
import static org.jboss.as.domain.http.server.Constants.OK;
import static org.jboss.as.domain.http.server.Constants.POST;
import static org.jboss.as.domain.http.server.Constants.TEXT_HTML;
import static org.jboss.as.domain.http.server.Constants.US_ASCII;
import static org.jboss.as.domain.http.server.Constants.UTF_8;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.OperationBuilder;
import org.jboss.as.domain.http.server.multipart.BoundaryDelimitedInputStream;
import org.jboss.as.domain.http.server.multipart.MimeHeaderParser;
import org.jboss.as.domain.http.server.security.BasicAuthenticator;
import org.jboss.as.domain.http.server.security.DigestAuthenticator;
import org.jboss.as.domain.management.SecurityRealm;
import org.jboss.as.domain.management.security.DomainCallbackHandler;
import org.jboss.com.sun.net.httpserver.Headers;
import org.jboss.com.sun.net.httpserver.HttpContext;
import org.jboss.com.sun.net.httpserver.HttpExchange;
import org.jboss.com.sun.net.httpserver.HttpServer;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
/**
* An embedded web server that provides a JSON over HTTP API to the domain management model.
*
* @author Jason T. Greene
*/
class DomainApiHandler implements ManagementHttpHandler {
private static final String DOMAIN_API_CONTEXT = "/management";
private static final String UPLOAD_REQUEST = DOMAIN_API_CONTEXT + "/add-content";
private static Pattern MULTIPART_FD_BOUNDARY = Pattern.compile("^multipart/form-data.*;\\s*boundary=(.*)$");
private static Pattern DISPOSITION_FILE = Pattern.compile("^form-data.*filename=\"?([^\"]*)?\"?.*$");
private static final Logger log = Logger.getLogger("org.jboss.as.domain.http.api");
/**
* Represents all possible management operations that can be executed using HTTP GET
*/
enum GetOperation {
RESOURCE("read-resource"),
ATTRIBUTE("read-attribute"),
RESOURCE_DESCRIPTION("read-resource-description"),
SNAPSHOTS("list-snapshots"),
OPERATION_DESCRIPTION(
"read-operation-description"),
OPERATION_NAMES("read-operation-names");
private String realOperation;
GetOperation(String realOperation) {
this.realOperation = realOperation;
}
public String realOperation() {
return realOperation;
}
}
private ModelControllerClient modelController;
DomainApiHandler(ModelControllerClient modelController) {
this.modelController = modelController;
}
public void handle(HttpExchange http) throws IOException {
final URI request = http.getRequestURI();
final String requestMethod = http.getRequestMethod();
/*
* Detect the file upload request. If it is not present, submit the incoming request to the normal handler.
*/
if (POST.equals(requestMethod) && UPLOAD_REQUEST.equals(request.getPath())) {
processUploadRequest(http);
} else {
processRequest(http);
}
}
/**
* Handle a form POST deployment upload request.
*
* @param http The HttpExchange object that allows access to the request and response.
* @throws IOException if an error occurs while attempting to extract the deployment from the multipart/form data.
*/
private void processUploadRequest(final HttpExchange http) throws IOException {
File tempUploadFile = null;
ModelNode response = null;
try {
SeekResult result = seekToDeployment(http);
final ModelNode dmr = new ModelNode();
dmr.get("operation").set("upload-deployment-stream");
dmr.get("address").setEmptyList();
dmr.get("input-stream-index").set(0);
OperationBuilder operation = new OperationBuilder(dmr);
operation.addInputStream(result.stream);
response = modelController.execute(operation.build());
drain(http.getRequestBody());
} catch (Throwable t) {
// TODO Consider draining input stream
log.error("Unexpected error executing deployment upload request", t);
http.sendResponseHeaders(INTERNAL_SERVER_ERROR, -1);
return;
}
// TODO Determine what format the response should be in for a deployment upload request.
writeResponse(http, false, false, response, OK, false, TEXT_HTML);
}
/**
* Handles a operation request via HTTP.
*
* @param http The HttpExchange object that allows access to the request and response.
* @throws IOException if an error occurs while attempting to process the request.
*/
private void processRequest(final HttpExchange http) throws IOException {
final URI request = http.getRequestURI();
final String requestMethod = http.getRequestMethod();
boolean isGet = GET.equals(requestMethod);
if (!isGet && !POST.equals(requestMethod)) {
http.sendResponseHeaders(METHOD_NOT_ALLOWED, -1);
return;
}
ModelNode dmr = null;
ModelNode response;
int status = OK;
Headers requestHeaders = http.getRequestHeaders();
boolean encode = APPLICATION_DMR_ENCODED.equals(requestHeaders.getFirst(ACCEPT))
|| APPLICATION_DMR_ENCODED.equals(requestHeaders.getFirst(CONTENT_TYPE));
try {
dmr = isGet ? convertGetRequest(request) : convertPostRequest(http.getRequestBody(), encode);
response = modelController.execute(new OperationBuilder(dmr).build());
} catch (Throwable t) {
log.error("Unexpected error executing model request", t);
http.sendResponseHeaders(INTERNAL_SERVER_ERROR, -1);
return;
}
if (response.hasDefined(OUTCOME) && FAILED.equals(response.get(OUTCOME).asString())) {
status = INTERNAL_SERVER_ERROR;
}
boolean pretty = dmr.hasDefined("json.pretty") && dmr.get("json.pretty").asBoolean();
writeResponse(http, isGet, pretty, response, status, encode);
}
private void writeResponse(final HttpExchange http, boolean isGet, boolean pretty, ModelNode response, int status,
boolean encode) throws IOException {
String contentType = encode ? APPLICATION_DMR_ENCODED : APPLICATION_JSON;
writeResponse(http, isGet, pretty, response, status, encode, contentType);
}
/**
* Writes the HTTP response to the output stream.
*
* @param http The HttpExchange object that allows access to the request and response.
* @param isGet Flag indicating whether or not the request was a GET request or POST request.
* @param pretty Flag indicating whether or not the output, if JSON, should be pretty printed or not.
* @param response The DMR response from the operation.
* @param status The HTTP status code to be included in the response.
* @param encode Flag indicating whether or not to Base64 encode the response payload.
* @throws IOException if an error occurs while attempting to generate the HTTP response.
*/
private void writeResponse(final HttpExchange http, boolean isGet, boolean pretty, ModelNode response, int status,
boolean encode, String contentType) throws IOException {
final Headers responseHeaders = http.getResponseHeaders();
responseHeaders.add(CONTENT_TYPE, contentType);
responseHeaders.add(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
http.sendResponseHeaders(status, 0);
final OutputStream out = http.getResponseBody();
final PrintWriter print = new PrintWriter(out);
// GET (read) operations will never have a compensating update, and the status is already
// available via the http response status code, so unwrap them.
if (isGet && status == OK)
response = response.get("result");
try {
if (encode) {
response.writeBase64(out);
} else {
response.writeJSONString(print, !pretty);
}
} finally {
print.flush();
out.flush();
safeClose(print);
safeClose(out);
}
}
private static final class SeekResult {
BoundaryDelimitedInputStream stream;
String fileName;
}
/**
* Extracts the body content contained in a POST request.
*
* @param http The <code>HttpExchange</code> object containing POST request data.
* @return a result containing the stream and the file name reported by the client
* @throws IOException if an error occurs while attempting to extract the POST request data.
*/
private SeekResult seekToDeployment(final HttpExchange http) throws IOException {
final String type = http.getRequestHeaders().getFirst(CONTENT_TYPE);
if (type == null)
throw new IllegalArgumentException("No content type provided");
Matcher matcher = MULTIPART_FD_BOUNDARY.matcher(type);
if (!matcher.matches())
throw new IllegalArgumentException("Invalid content type provided: " + type);
final String boundary = "--" + matcher.group(1);
final BoundaryDelimitedInputStream stream = new BoundaryDelimitedInputStream(http.getRequestBody(), boundary.getBytes("US-ASCII"));
// Eat preamble
byte[] ignore = new byte[1024];
while (stream.read(ignore) != -1) {}
// From here on out a boundary is prefixed with a CRLF that should be skipped
stream.setBoundary(("\r\n" + boundary).getBytes(US_ASCII));
while (!stream.isOuterStreamClosed()) {
// purposefully send the trailing CRLF to headers so that a headerless body can be detected
MimeHeaderParser.ParseResult result = MimeHeaderParser.parseHeaders(stream);
if (result.eof()) continue; // Skip content-less part
Headers partHeaders = result.headers();
String disposition = partHeaders.getFirst(CONTENT_DISPOSITION);
if (disposition != null) {
matcher = DISPOSITION_FILE.matcher(disposition);
if (matcher.matches()) {
SeekResult seek = new SeekResult();
seek.fileName = matcher.group(1);
seek.stream = stream;
return seek;
}
}
while (stream.read(ignore) != -1) {}
}
throw new IllegalArgumentException("Request did not contain a deployment");
}
private void drain(InputStream stream) {
try {
byte[] ignore = new byte[1024];
while (stream.read(ignore) != -1) {}
} catch (Throwable eat) {
}
}
private void safeClose(Closeable close) {
try {
close.close();
} catch (Throwable eat) {
}
}
private ModelNode convertPostRequest(InputStream stream, boolean encode) throws IOException {
return encode ? ModelNode.fromBase64(stream) : ModelNode.fromJSONStream(stream);
}
private ModelNode convertGetRequest(URI request) {
ArrayList<String> pathSegments = decodePath(request.getRawPath());
Map<String, String> queryParameters = decodeQuery(request.getRawQuery());
GetOperation operation = null;
ModelNode dmr = new ModelNode();
for (Entry<String, String> entry : queryParameters.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if ("operation".equals(key)) {
try {
operation = GetOperation.valueOf(value.toUpperCase().replace('-', '_'));
value = operation.realOperation();
} catch (Exception e) {
// Unknown
continue;
}
}
dmr.get(entry.getKey()).set(value);
}
if (operation == null) {
operation = GetOperation.RESOURCE;
dmr.get("operation").set(operation.realOperation);
}
if (operation == GetOperation.RESOURCE && !dmr.has("recursive"))
dmr.get("recursive").set(false);
ModelNode list = dmr.get("address").setEmptyList();
for (int i = 1; i < pathSegments.size() - 1; i += 2) {
list.add(pathSegments.get(i), pathSegments.get(i + 1));
}
return dmr;
}
private ArrayList<String> decodePath(String path) {
if (path == null)
throw new IllegalArgumentException();
int i = path.charAt(0) == '/' ? 1 : 0;
ArrayList<String> segments = new ArrayList<String>();
do {
int j = path.indexOf('/', i);
if (j == -1)
j = path.length();
segments.add(unescape(path.substring(i, j)));
i = j + 1;
} while (i < path.length());
return segments;
}
private String unescape(String string) {
try {
// URLDecoder could be way more efficient, replace it one day
return URLDecoder.decode(string, UTF_8);
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
}
private Map<String, String> decodeQuery(String query) {
if (query == null || query.isEmpty())
return Collections.emptyMap();
int i = 0;
Map<String, String> parameters = new HashMap<String, String>();
do {
int j = query.indexOf('&', i);
if (j == -1)
j = query.length();
String pair = query.substring(i, j);
int k = pair.indexOf('=');
String key;
String value;
if (k == -1) {
key = unescape(pair);
value = "true";
} else {
key = unescape(pair.substring(0, k));
value = unescape(pair.substring(k + 1, pair.length()));
}
parameters.put(key, value);
i = j + 1;
} while (i < query.length());
return parameters;
}
public void start(HttpServer httpServer, SecurityRealm securityRealm) {
HttpContext context = httpServer.createContext(DOMAIN_API_CONTEXT, this);
if (securityRealm != null) {
DomainCallbackHandler callbackHandler = securityRealm.getCallbackHandler();
Class[] supportedCallbacks = callbackHandler.getSupportedCallbacks();
if (DigestAuthenticator.requiredCallbacksSupported(supportedCallbacks)) {
context.setAuthenticator(new DigestAuthenticator(callbackHandler, securityRealm.getName()));
} else if (BasicAuthenticator.requiredCallbacksSupported(supportedCallbacks)) {
context.setAuthenticator(new BasicAuthenticator(callbackHandler, securityRealm.getName()));
}
}
}
public void stop(HttpServer httpServer) {
httpServer.removeContext(DOMAIN_API_CONTEXT);
modelController = null;
}
}
| domain-http-api/src/main/java/org/jboss/as/domain/http/server/DomainApiHandler.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.domain.http.server;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.domain.http.server.Constants.ACCEPT;
import static org.jboss.as.domain.http.server.Constants.ACCESS_CONTROL_ALLOW_ORIGIN;
import static org.jboss.as.domain.http.server.Constants.APPLICATION_DMR_ENCODED;
import static org.jboss.as.domain.http.server.Constants.APPLICATION_JSON;
import static org.jboss.as.domain.http.server.Constants.CONTENT_DISPOSITION;
import static org.jboss.as.domain.http.server.Constants.CONTENT_TYPE;
import static org.jboss.as.domain.http.server.Constants.GET;
import static org.jboss.as.domain.http.server.Constants.INTERNAL_SERVER_ERROR;
import static org.jboss.as.domain.http.server.Constants.METHOD_NOT_ALLOWED;
import static org.jboss.as.domain.http.server.Constants.OK;
import static org.jboss.as.domain.http.server.Constants.POST;
import static org.jboss.as.domain.http.server.Constants.TEXT_HTML;
import static org.jboss.as.domain.http.server.Constants.US_ASCII;
import static org.jboss.as.domain.http.server.Constants.UTF_8;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.OperationBuilder;
import org.jboss.as.domain.http.server.multipart.BoundaryDelimitedInputStream;
import org.jboss.as.domain.http.server.multipart.MimeHeaderParser;
import org.jboss.as.domain.http.server.security.BasicAuthenticator;
import org.jboss.as.domain.http.server.security.DigestAuthenticator;
import org.jboss.as.domain.management.SecurityRealm;
import org.jboss.as.domain.management.security.DomainCallbackHandler;
import org.jboss.com.sun.net.httpserver.Headers;
import org.jboss.com.sun.net.httpserver.HttpContext;
import org.jboss.com.sun.net.httpserver.HttpExchange;
import org.jboss.com.sun.net.httpserver.HttpServer;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
/**
* An embedded web server that provides a JSON over HTTP API to the domain management model.
*
* @author Jason T. Greene
*/
class DomainApiHandler implements ManagementHttpHandler {
private static final String DOMAIN_API_CONTEXT = "/management";
private static final String UPLOAD_REQUEST = DOMAIN_API_CONTEXT + "/add-content";
private static Pattern MULTIPART_FD_BOUNDARY = Pattern.compile("^multipart/form-data.*;\\s*boundary=(.*)$");
private static Pattern DISPOSITION_FILE = Pattern.compile("^form-data.*filename=\"?([^\"]*)?\"?.*$");
private static final Logger log = Logger.getLogger("org.jboss.as.domain.http.api");
/**
* Represents all possible management operations that can be executed using HTTP GET
*/
enum GetOperation {
RESOURCE("read-resource"), ATTRIBUTE("read-attribute"), RESOURCE_DESCRIPTION("read-resource-description"), OPERATION_DESCRIPTION(
"read-operation-description"), OPERATION_NAMES("read-operation-names");
private String realOperation;
GetOperation(String realOperation) {
this.realOperation = realOperation;
}
public String realOperation() {
return realOperation;
}
}
private ModelControllerClient modelController;
DomainApiHandler(ModelControllerClient modelController) {
this.modelController = modelController;
}
public void handle(HttpExchange http) throws IOException {
final URI request = http.getRequestURI();
final String requestMethod = http.getRequestMethod();
/*
* Detect the file upload request. If it is not present, submit the incoming request to the normal handler.
*/
if (POST.equals(requestMethod) && UPLOAD_REQUEST.equals(request.getPath())) {
processUploadRequest(http);
} else {
processRequest(http);
}
}
/**
* Handle a form POST deployment upload request.
*
* @param http The HttpExchange object that allows access to the request and response.
* @throws IOException if an error occurs while attempting to extract the deployment from the multipart/form data.
*/
private void processUploadRequest(final HttpExchange http) throws IOException {
File tempUploadFile = null;
ModelNode response = null;
try {
SeekResult result = seekToDeployment(http);
final ModelNode dmr = new ModelNode();
dmr.get("operation").set("upload-deployment-stream");
dmr.get("address").setEmptyList();
dmr.get("input-stream-index").set(0);
OperationBuilder operation = new OperationBuilder(dmr);
operation.addInputStream(result.stream);
response = modelController.execute(operation.build());
drain(http.getRequestBody());
} catch (Throwable t) {
// TODO Consider draining input stream
log.error("Unexpected error executing deployment upload request", t);
http.sendResponseHeaders(INTERNAL_SERVER_ERROR, -1);
return;
}
// TODO Determine what format the response should be in for a deployment upload request.
writeResponse(http, false, false, response, OK, false, TEXT_HTML);
}
/**
* Handles a operation request via HTTP.
*
* @param http The HttpExchange object that allows access to the request and response.
* @throws IOException if an error occurs while attempting to process the request.
*/
private void processRequest(final HttpExchange http) throws IOException {
final URI request = http.getRequestURI();
final String requestMethod = http.getRequestMethod();
boolean isGet = GET.equals(requestMethod);
if (!isGet && !POST.equals(requestMethod)) {
http.sendResponseHeaders(METHOD_NOT_ALLOWED, -1);
return;
}
ModelNode dmr = null;
ModelNode response;
int status = OK;
Headers requestHeaders = http.getRequestHeaders();
boolean encode = APPLICATION_DMR_ENCODED.equals(requestHeaders.getFirst(ACCEPT))
|| APPLICATION_DMR_ENCODED.equals(requestHeaders.getFirst(CONTENT_TYPE));
try {
dmr = isGet ? convertGetRequest(request) : convertPostRequest(http.getRequestBody(), encode);
response = modelController.execute(new OperationBuilder(dmr).build());
} catch (Throwable t) {
log.error("Unexpected error executing model request", t);
http.sendResponseHeaders(INTERNAL_SERVER_ERROR, -1);
return;
}
if (response.hasDefined(OUTCOME) && FAILED.equals(response.get(OUTCOME).asString())) {
status = INTERNAL_SERVER_ERROR;
}
boolean pretty = dmr.hasDefined("json.pretty") && dmr.get("json.pretty").asBoolean();
writeResponse(http, isGet, pretty, response, status, encode);
}
private void writeResponse(final HttpExchange http, boolean isGet, boolean pretty, ModelNode response, int status,
boolean encode) throws IOException {
String contentType = encode ? APPLICATION_DMR_ENCODED : APPLICATION_JSON;
writeResponse(http, isGet, pretty, response, status, encode, contentType);
}
/**
* Writes the HTTP response to the output stream.
*
* @param http The HttpExchange object that allows access to the request and response.
* @param isGet Flag indicating whether or not the request was a GET request or POST request.
* @param pretty Flag indicating whether or not the output, if JSON, should be pretty printed or not.
* @param response The DMR response from the operation.
* @param status The HTTP status code to be included in the response.
* @param encode Flag indicating whether or not to Base64 encode the response payload.
* @throws IOException if an error occurs while attempting to generate the HTTP response.
*/
private void writeResponse(final HttpExchange http, boolean isGet, boolean pretty, ModelNode response, int status,
boolean encode, String contentType) throws IOException {
final Headers responseHeaders = http.getResponseHeaders();
responseHeaders.add(CONTENT_TYPE, contentType);
responseHeaders.add(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
http.sendResponseHeaders(status, 0);
final OutputStream out = http.getResponseBody();
final PrintWriter print = new PrintWriter(out);
// GET (read) operations will never have a compensating update, and the status is already
// available via the http response status code, so unwrap them.
if (isGet && status == OK)
response = response.get("result");
try {
if (encode) {
response.writeBase64(out);
} else {
response.writeJSONString(print, !pretty);
}
} finally {
print.flush();
out.flush();
safeClose(print);
safeClose(out);
}
}
private static final class SeekResult {
BoundaryDelimitedInputStream stream;
String fileName;
}
/**
* Extracts the body content contained in a POST request.
*
* @param http The <code>HttpExchange</code> object containing POST request data.
* @return a result containing the stream and the file name reported by the client
* @throws IOException if an error occurs while attempting to extract the POST request data.
*/
private SeekResult seekToDeployment(final HttpExchange http) throws IOException {
final String type = http.getRequestHeaders().getFirst(CONTENT_TYPE);
if (type == null)
throw new IllegalArgumentException("No content type provided");
Matcher matcher = MULTIPART_FD_BOUNDARY.matcher(type);
if (!matcher.matches())
throw new IllegalArgumentException("Invalid content type provided: " + type);
final String boundary = "--" + matcher.group(1);
final BoundaryDelimitedInputStream stream = new BoundaryDelimitedInputStream(http.getRequestBody(), boundary.getBytes("US-ASCII"));
// Eat preamble
byte[] ignore = new byte[1024];
while (stream.read(ignore) != -1) {}
// From here on out a boundary is prefixed with a CRLF that should be skipped
stream.setBoundary(("\r\n" + boundary).getBytes(US_ASCII));
while (!stream.isOuterStreamClosed()) {
// purposefully send the trailing CRLF to headers so that a headerless body can be detected
MimeHeaderParser.ParseResult result = MimeHeaderParser.parseHeaders(stream);
if (result.eof()) continue; // Skip content-less part
Headers partHeaders = result.headers();
String disposition = partHeaders.getFirst(CONTENT_DISPOSITION);
if (disposition != null) {
matcher = DISPOSITION_FILE.matcher(disposition);
if (matcher.matches()) {
SeekResult seek = new SeekResult();
seek.fileName = matcher.group(1);
seek.stream = stream;
return seek;
}
}
while (stream.read(ignore) != -1) {}
}
throw new IllegalArgumentException("Request did not contain a deployment");
}
private void drain(InputStream stream) {
try {
byte[] ignore = new byte[1024];
while (stream.read(ignore) != -1) {}
} catch (Throwable eat) {
}
}
private void safeClose(Closeable close) {
try {
close.close();
} catch (Throwable eat) {
}
}
private ModelNode convertPostRequest(InputStream stream, boolean encode) throws IOException {
return encode ? ModelNode.fromBase64(stream) : ModelNode.fromJSONStream(stream);
}
private ModelNode convertGetRequest(URI request) {
ArrayList<String> pathSegments = decodePath(request.getRawPath());
Map<String, String> queryParameters = decodeQuery(request.getRawQuery());
GetOperation operation = null;
ModelNode dmr = new ModelNode();
for (Entry<String, String> entry : queryParameters.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if ("operation".equals(key)) {
try {
operation = GetOperation.valueOf(value.toUpperCase().replace('-', '_'));
value = operation.realOperation();
} catch (Exception e) {
// Unknown
continue;
}
}
dmr.get(entry.getKey()).set(value);
}
if (operation == null) {
operation = GetOperation.RESOURCE;
dmr.get("operation").set(operation.realOperation);
}
if (operation == GetOperation.RESOURCE && !dmr.has("recursive"))
dmr.get("recursive").set(false);
ModelNode list = dmr.get("address").setEmptyList();
for (int i = 1; i < pathSegments.size() - 1; i += 2) {
list.add(pathSegments.get(i), pathSegments.get(i + 1));
}
return dmr;
}
private ArrayList<String> decodePath(String path) {
if (path == null)
throw new IllegalArgumentException();
int i = path.charAt(0) == '/' ? 1 : 0;
ArrayList<String> segments = new ArrayList<String>();
do {
int j = path.indexOf('/', i);
if (j == -1)
j = path.length();
segments.add(unescape(path.substring(i, j)));
i = j + 1;
} while (i < path.length());
return segments;
}
private String unescape(String string) {
try {
// URLDecoder could be way more efficient, replace it one day
return URLDecoder.decode(string, UTF_8);
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
}
private Map<String, String> decodeQuery(String query) {
if (query == null || query.isEmpty())
return Collections.emptyMap();
int i = 0;
Map<String, String> parameters = new HashMap<String, String>();
do {
int j = query.indexOf('&', i);
if (j == -1)
j = query.length();
String pair = query.substring(i, j);
int k = pair.indexOf('=');
String key;
String value;
if (k == -1) {
key = unescape(pair);
value = "true";
} else {
key = unescape(pair.substring(0, k));
value = unescape(pair.substring(k + 1, pair.length()));
}
parameters.put(key, value);
i = j + 1;
} while (i < query.length());
return parameters;
}
public void start(HttpServer httpServer, SecurityRealm securityRealm) {
HttpContext context = httpServer.createContext(DOMAIN_API_CONTEXT, this);
if (securityRealm != null) {
DomainCallbackHandler callbackHandler = securityRealm.getCallbackHandler();
Class[] supportedCallbacks = callbackHandler.getSupportedCallbacks();
if (DigestAuthenticator.requiredCallbacksSupported(supportedCallbacks)) {
context.setAuthenticator(new DigestAuthenticator(callbackHandler, securityRealm.getName()));
} else if (BasicAuthenticator.requiredCallbacksSupported(supportedCallbacks)) {
context.setAuthenticator(new BasicAuthenticator(callbackHandler, securityRealm.getName()));
}
}
}
public void stop(HttpServer httpServer) {
httpServer.removeContext(DOMAIN_API_CONTEXT);
modelController = null;
}
}
| [AS7-1966] Add ?operation=snapshots support to HTTP interface to allow snapshots to be listed.
| domain-http-api/src/main/java/org/jboss/as/domain/http/server/DomainApiHandler.java | [AS7-1966] Add ?operation=snapshots support to HTTP interface to allow snapshots to be listed. | <ide><path>omain-http-api/src/main/java/org/jboss/as/domain/http/server/DomainApiHandler.java
<ide> * Represents all possible management operations that can be executed using HTTP GET
<ide> */
<ide> enum GetOperation {
<del> RESOURCE("read-resource"), ATTRIBUTE("read-attribute"), RESOURCE_DESCRIPTION("read-resource-description"), OPERATION_DESCRIPTION(
<del> "read-operation-description"), OPERATION_NAMES("read-operation-names");
<add> RESOURCE("read-resource"),
<add> ATTRIBUTE("read-attribute"),
<add> RESOURCE_DESCRIPTION("read-resource-description"),
<add> SNAPSHOTS("list-snapshots"),
<add> OPERATION_DESCRIPTION(
<add> "read-operation-description"),
<add> OPERATION_NAMES("read-operation-names");
<ide>
<ide> private String realOperation;
<ide> |
|
Java | mit | 2d9270eaa0043702e9648497285e56bbfbfadf9e | 0 | Spiddekauga/android-utils | package com.spiddekauga.android.util;
import java.util.ArrayList;
import java.util.List;
/**
* Base class for object events. Used for add, edit, and remove actions.
*/
public abstract class ObjectEvent<ObjectType> {
private final Actions mAction;
private final List<ObjectType> mObjects = new ArrayList<>();
protected ObjectEvent(ObjectType object, Actions action) {
mAction = action;
mObjects.add(object);
}
protected ObjectEvent(List<ObjectType> objects, Actions action) {
if (objects.isEmpty()) {
throw new IllegalArgumentException("objects is empty");
}
mAction = action;
mObjects.addAll(objects);
}
/**
* @return all objects in this event
*/
public List<ObjectType> getObjects() {
return mObjects;
}
/**
* @return the first object in this event
*/
public ObjectType getFirstObject() {
return mObjects.get(0);
}
/**
* Get the action to take on the object event
* @return the action to take on the object event
*/
public Actions getAction() {
return mAction;
}
/**
* The different actions
*/
public enum Actions {
ADD,
EDIT,
REMOVE,
/** Called after {@link #ADD}, i.e., after an object has been added to the DB */
ADDED,
/** Called after {@link #EDIT}, i.e., after an object has been edited in the DB */
EDITED,
/** Called after {@link #REMOVED}, i.e., after an objects has been removed from the DB */
REMOVED,
}
}
| app-utils/src/main/java/com/spiddekauga/android/util/ObjectEvent.java | package com.spiddekauga.android.util;
/**
* Base class for object events. Used for add, edit, and remove actions.
*/
public abstract class ObjectEvent {
private final Actions mAction;
protected ObjectEvent(Actions action) {
mAction = action;
}
/**
* Get the action to take on the object event
* @return the action to take on the object event
*/
public Actions getAction() {
return mAction;
}
/**
* The different actions
*/
public enum Actions {
ADD,
EDIT,
REMOVE,
}
}
| Add ability to store items in the Object
| app-utils/src/main/java/com/spiddekauga/android/util/ObjectEvent.java | Add ability to store items in the Object | <ide><path>pp-utils/src/main/java/com/spiddekauga/android/util/ObjectEvent.java
<ide> package com.spiddekauga.android.util;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<ide>
<ide> /**
<ide> * Base class for object events. Used for add, edit, and remove actions.
<ide> */
<del>public abstract class ObjectEvent {
<add>public abstract class ObjectEvent<ObjectType> {
<ide> private final Actions mAction;
<add>private final List<ObjectType> mObjects = new ArrayList<>();
<ide>
<del>protected ObjectEvent(Actions action) {
<add>protected ObjectEvent(ObjectType object, Actions action) {
<ide> mAction = action;
<add> mObjects.add(object);
<add>}
<add>
<add>protected ObjectEvent(List<ObjectType> objects, Actions action) {
<add> if (objects.isEmpty()) {
<add> throw new IllegalArgumentException("objects is empty");
<add> }
<add>
<add> mAction = action;
<add> mObjects.addAll(objects);
<add>}
<add>
<add>/**
<add> * @return all objects in this event
<add> */
<add>public List<ObjectType> getObjects() {
<add> return mObjects;
<add>}
<add>
<add>/**
<add> * @return the first object in this event
<add> */
<add>public ObjectType getFirstObject() {
<add> return mObjects.get(0);
<ide> }
<ide>
<ide> /**
<ide> ADD,
<ide> EDIT,
<ide> REMOVE,
<add> /** Called after {@link #ADD}, i.e., after an object has been added to the DB */
<add> ADDED,
<add> /** Called after {@link #EDIT}, i.e., after an object has been edited in the DB */
<add> EDITED,
<add> /** Called after {@link #REMOVED}, i.e., after an objects has been removed from the DB */
<add> REMOVED,
<ide> }
<ide> } |
|
Java | agpl-3.0 | 66015b80450f153efd3d66e6a1d36f440c0e3dcc | 0 | Silverpeas/Silverpeas-Core,mmoqui/Silverpeas-Core,ebonnet/Silverpeas-Core,SilverTeamWork/Silverpeas-Core,SilverDav/Silverpeas-Core,mmoqui/Silverpeas-Core,ebonnet/Silverpeas-Core,ebonnet/Silverpeas-Core,SilverDav/Silverpeas-Core,SilverDav/Silverpeas-Core,SilverTeamWork/Silverpeas-Core,SilverYoCha/Silverpeas-Core,auroreallibe/Silverpeas-Core,auroreallibe/Silverpeas-Core,SilverTeamWork/Silverpeas-Core,ebonnet/Silverpeas-Core,SilverYoCha/Silverpeas-Core,SilverYoCha/Silverpeas-Core,Silverpeas/Silverpeas-Core,mmoqui/Silverpeas-Core,Silverpeas/Silverpeas-Core,auroreallibe/Silverpeas-Core,ebonnet/Silverpeas-Core,ebonnet/Silverpeas-Core | /**
* Copyright (C) 2000 - 2013 Silverpeas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of the GPL, you may
* redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS")
* applications as described in Silverpeas's FLOSS exception. You should have received a copy of the
* text describing the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.form.displayers;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.silverpeas.util.Charsets;
import com.silverpeas.form.FieldTemplate;
import com.silverpeas.form.PagesContext;
import com.silverpeas.form.fieldType.JdbcField;
import com.silverpeas.jcrutil.RandomGenerator;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
/**
*
* @author ehugonnet
*/
public class JdbcFieldDisplayerTest {
String lineSeparator = System.getProperty("line.separator");
String unixLineSeparator = "\n";
public JdbcFieldDisplayerTest() {
}
/**
* Test of getManagedTypes method, of class JdbcFieldDisplayer.
*/
@Test
public void testGetManagedTypes() {
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
String[] result = instance.getManagedTypes();
assertThat(result, is(notNullValue()));
assertThat(result, org.hamcrest.collection.IsArrayWithSize.arrayWithSize(1));
assertThat(result, org.hamcrest.collection.IsArrayContaining.hasItemInArray(JdbcField.TYPE));
}
/**
* Test of displayScripts method, of class JdbcFieldDisplayer.
*/
@Test
public void testDisplayScripts() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
PrintWriter printer = new PrintWriter(new OutputStreamWriter(out, Charsets.UTF_8), true);
FieldTemplate template = mock(FieldTemplate.class);
when(template.getTypeName()).thenReturn(JdbcField.TYPE);
when(template.isMandatory()).thenReturn(true);
when(template.getLabel("fr")).thenReturn("Mon champs JDBC");
when(template.getFieldName()).thenReturn("monChamps");
PagesContext pagesContext = new PagesContext();
pagesContext.setUseMandatory(true);
pagesContext.setCurrentFieldIndex("10");
pagesContext.setLastFieldIndex(20);
pagesContext.setLanguage("fr");
pagesContext.setEncoding("UTF-8");
pagesContext.setUserId("0");
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
instance.displayScripts(printer, template, pagesContext);
assertThat(new String(out.toByteArray(), Charsets.UTF_8).trim(), is(
"if (isWhitespace(stripInitialWhitespace(field.value))) {" + lineSeparator
+ "\t\terrorMsg+=\" - 'Mon champs JDBC' doit être renseigné\\n\";" + lineSeparator
+ "\t\terrorNb++;" + lineSeparator + "\t}" + lineSeparator + " try { " + lineSeparator
+ "if (typeof(checkmonChamps) == 'function')" + lineSeparator + " checkmonChamps('fr');"
+ lineSeparator + " } catch (e) { " + lineSeparator + " //catch all exceptions"
+ lineSeparator + " }"));
}
/**
* Test of display method, of class JdbcFieldDisplayer.
*/
@Test
public void testDisplay() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
PrintWriter printer = new PrintWriter(new OutputStreamWriter(out, Charsets.UTF_8), true);
FieldTemplate template = mock(FieldTemplate.class);
when(template.getTypeName()).thenReturn(JdbcField.TYPE);
when(template.isMandatory()).thenReturn(true);
when(template.getLabel("fr")).thenReturn("Mon champs JDBC");
when(template.getFieldName()).thenReturn("monChamps");
PagesContext pagesContext = new PagesContext();
pagesContext.setUseMandatory(true);
pagesContext.setCurrentFieldIndex("10");
pagesContext.setLastFieldIndex(20);
pagesContext.setLanguage("fr");
pagesContext.setEncoding("UTF-8");
pagesContext.setUserId("0");
JdbcField field = mock(JdbcField.class);
when(field.getTypeName()).thenReturn(JdbcField.TYPE);
int size = 5;
List<String> resList = new ArrayList<String>(size);
for (int i = 0; i < size; i++) {
resList.add(String.valueOf(i));
}
when(field.selectSql(null, null, "0")).thenReturn(resList);
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
instance.display(printer, field, template, pagesContext);
String display = new String(out.toByteArray(), Charsets.UTF_8).trim();
assertThat(display, is(notNullValue()));
assertThat(display.length(), is(1381));
}
/**
* Test of display method, of class JdbcFieldDisplayer.
*/
@Test
public void testDisplayListBox() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
PrintWriter printer = new PrintWriter(new OutputStreamWriter(out, Charsets.UTF_8), true);
FieldTemplate template = mock(FieldTemplate.class);
when(template.getTypeName()).thenReturn(JdbcField.TYPE);
when(template.isMandatory()).thenReturn(true);
when(template.getLabel("fr")).thenReturn("Mon champs JDBC");
when(template.getFieldName()).thenReturn("monChamps");
Map<String, String> parameters = new HashMap<String, String>(0);
parameters.put("displayer", "listbox");
when(template.getParameters("fr")).thenReturn(parameters);
PagesContext pagesContext = new PagesContext();
pagesContext.setUseMandatory(true);
pagesContext.setCurrentFieldIndex("10");
pagesContext.setLastFieldIndex(20);
pagesContext.setLanguage("fr");
pagesContext.setEncoding("UTF-8");
pagesContext.setUserId("0");
JdbcField field = mock(JdbcField.class);
when(field.getTypeName()).thenReturn(JdbcField.TYPE);
int size = 5;
List<String> resList = new ArrayList<String>(size);
for (int i = 0; i < size; i++) {
resList.add(String.valueOf(i));
}
when(field.selectSql(null, null, "0")).thenReturn(resList);
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
instance.display(printer, field, template, pagesContext);
String display = new String(out.toByteArray(), Charsets.UTF_8).trim();
assertThat(display, is(notNullValue()));
assertThat(display.length(), is(299));
assertThat(display, is(
"<select name=\"monChamps\" >" + unixLineSeparator
+ "<option></option><option value=\"0\">0</option>" + unixLineSeparator
+ "<option value=\"1\">1</option>" + unixLineSeparator + "<option value=\"2\">2</option>"
+ unixLineSeparator + "<option value=\"3\">3</option>" + unixLineSeparator
+ "<option value=\"4\">4</option>" + unixLineSeparator
+ "</select>" + unixLineSeparator
+ " <img src=\"/silverpeas//util/icons/mandatoryField.gif\" "
+ "width=\"5\" height=\"5\" alt=\"Obligatoire\"/>"));
}
/**
* Test of update method, of class JdbcFieldDisplayer.
*/
@Test
public void testUpdate() throws Exception {
String newValue = "newValue";
PagesContext pagesContext = new PagesContext();
pagesContext.setUseMandatory(true);
pagesContext.setCurrentFieldIndex("10");
pagesContext.setLastFieldIndex(20);
pagesContext.setLanguage("fr");
pagesContext.setEncoding("UTF-8");
pagesContext.setUserId("0");
JdbcField field = mock(JdbcField.class);
when(field.getTypeName()).thenReturn(JdbcField.TYPE);
when(field.isReadOnly()).thenReturn(false);
when(field.acceptValue("newValue", "fr")).thenReturn(true);
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
instance.update(newValue, field, null, pagesContext);
verify(field).setValue("newValue", "fr");
}
@Test(expected = com.silverpeas.form.FormException.class)
public void testUpdateIncorrectField() throws Exception {
String newValue = "";
JdbcField field = mock(JdbcField.class);
when(field.getTypeName()).thenReturn(RandomGenerator.getRandomString());
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
instance.update(newValue, field, null, null);
}
@Test(expected = com.silverpeas.form.FormException.class)
public void testUpdateIncorrectValue() throws Exception {
String newValue = "";
PagesContext pagesContext = new PagesContext();
pagesContext.setUseMandatory(true);
pagesContext.setCurrentFieldIndex("10");
pagesContext.setLastFieldIndex(20);
pagesContext.setLanguage("fr");
pagesContext.setEncoding("UTF-8");
pagesContext.setUserId("0");
JdbcField field = mock(JdbcField.class);
when(field.getTypeName()).thenReturn(JdbcField.TYPE);
when(field.isReadOnly()).thenReturn(true);
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
instance.update(newValue, field, null, pagesContext);
}
/**
* Test of isDisplayedMandatory method, of class JdbcFieldDisplayer.
*/
@Test
public void testIsDisplayedMandatory() {
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
assertThat(instance.isDisplayedMandatory(), is(true));
}
/**
* Test of getNbHtmlObjectsDisplayed method, of class JdbcFieldDisplayer.
*/
@Test
public void testGetNbHtmlObjectsDisplayed() {
FieldTemplate template = null;
PagesContext pagesContext = null;
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
int expResult = 1;
int result = instance.getNbHtmlObjectsDisplayed(template, pagesContext);
assertThat(result, is(expResult));
}
}
| lib-core/src/test-awaiting/java/com/silverpeas/form/displayers/JdbcFieldDisplayerTest.java | /**
* Copyright (C) 2000 - 2013 Silverpeas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of the GPL, you may
* redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS")
* applications as described in Silverpeas's FLOSS exception. You should have received a copy of the
* text describing the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.form.displayers;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.silverpeas.util.Charsets;
import com.silverpeas.form.FieldTemplate;
import com.silverpeas.form.PagesContext;
import com.silverpeas.form.fieldType.JdbcField;
import com.silverpeas.jcrutil.RandomGenerator;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
/**
*
* @author ehugonnet
*/
public class JdbcFieldDisplayerTest {
String lineSeparator = System.getProperty("line.separator");
String unixLineSeparator = "\n";
public JdbcFieldDisplayerTest() {
}
/**
* Test of getManagedTypes method, of class JdbcFieldDisplayer.
*/
@Test
public void testGetManagedTypes() {
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
String[] result = instance.getManagedTypes();
assertThat(result, is(notNullValue()));
assertThat(result, org.hamcrest.collection.IsArrayWithSize.arrayWithSize(1));
assertThat(result, org.hamcrest.collection.IsArrayContaining.hasItemInArray(JdbcField.TYPE));
}
/**
* Test of displayScripts method, of class JdbcFieldDisplayer.
*/
@Test
public void testDisplayScripts() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
PrintWriter printer = new PrintWriter(new OutputStreamWriter(out, Charsets.UTF_8), true);
FieldTemplate template = mock(FieldTemplate.class);
when(template.getTypeName()).thenReturn(JdbcField.TYPE);
when(template.isMandatory()).thenReturn(true);
when(template.getLabel("fr")).thenReturn("Mon champs JDBC");
when(template.getFieldName()).thenReturn("monChamps");
PagesContext pagesContext = new PagesContext();
pagesContext.setUseMandatory(true);
pagesContext.setCurrentFieldIndex("10");
pagesContext.setLastFieldIndex(20);
pagesContext.setLanguage("fr");
pagesContext.setEncoding("UTF-8");
pagesContext.setUserId("0");
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
instance.displayScripts(printer, template, pagesContext);
assertThat(new String(out.toByteArray(), Charsets.UTF_8).trim(), is(
"if (isWhitespace(stripInitialWhitespace(field.value))) {" + lineSeparator
+ "\t\terrorMsg+=\" - 'Mon champs JDBC' doit être renseigné\\n \";" + lineSeparator
+ "\t\terrorNb++;" + lineSeparator + "\t}" + lineSeparator + " try { " + lineSeparator
+ "if (typeof(checkmonChamps) == 'function')" + lineSeparator + " checkmonChamps('fr');"
+ lineSeparator + " } catch (e) { " + lineSeparator + " //catch all exceptions"
+ lineSeparator + " }"));
}
/**
* Test of display method, of class JdbcFieldDisplayer.
*/
@Test
public void testDisplay() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
PrintWriter printer = new PrintWriter(new OutputStreamWriter(out, Charsets.UTF_8), true);
FieldTemplate template = mock(FieldTemplate.class);
when(template.getTypeName()).thenReturn(JdbcField.TYPE);
when(template.isMandatory()).thenReturn(true);
when(template.getLabel("fr")).thenReturn("Mon champs JDBC");
when(template.getFieldName()).thenReturn("monChamps");
PagesContext pagesContext = new PagesContext();
pagesContext.setUseMandatory(true);
pagesContext.setCurrentFieldIndex("10");
pagesContext.setLastFieldIndex(20);
pagesContext.setLanguage("fr");
pagesContext.setEncoding("UTF-8");
pagesContext.setUserId("0");
JdbcField field = mock(JdbcField.class);
when(field.getTypeName()).thenReturn(JdbcField.TYPE);
int size = 5;
List<String> resList = new ArrayList<String>(size);
for (int i = 0; i < size; i++) {
resList.add(String.valueOf(i));
}
when(field.selectSql(null, null, "0")).thenReturn(resList);
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
instance.display(printer, field, template, pagesContext);
String display = new String(out.toByteArray(), Charsets.UTF_8).trim();
assertThat(display, is(notNullValue()));
assertThat(display.length(), is(1381));
}
/**
* Test of display method, of class JdbcFieldDisplayer.
*/
@Test
public void testDisplayListBox() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
PrintWriter printer = new PrintWriter(new OutputStreamWriter(out, Charsets.UTF_8), true);
FieldTemplate template = mock(FieldTemplate.class);
when(template.getTypeName()).thenReturn(JdbcField.TYPE);
when(template.isMandatory()).thenReturn(true);
when(template.getLabel("fr")).thenReturn("Mon champs JDBC");
when(template.getFieldName()).thenReturn("monChamps");
Map<String, String> parameters = new HashMap<String, String>(0);
parameters.put("displayer", "listbox");
when(template.getParameters("fr")).thenReturn(parameters);
PagesContext pagesContext = new PagesContext();
pagesContext.setUseMandatory(true);
pagesContext.setCurrentFieldIndex("10");
pagesContext.setLastFieldIndex(20);
pagesContext.setLanguage("fr");
pagesContext.setEncoding("UTF-8");
pagesContext.setUserId("0");
JdbcField field = mock(JdbcField.class);
when(field.getTypeName()).thenReturn(JdbcField.TYPE);
int size = 5;
List<String> resList = new ArrayList<String>(size);
for (int i = 0; i < size; i++) {
resList.add(String.valueOf(i));
}
when(field.selectSql(null, null, "0")).thenReturn(resList);
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
instance.display(printer, field, template, pagesContext);
String display = new String(out.toByteArray(), Charsets.UTF_8).trim();
assertThat(display, is(notNullValue()));
assertThat(display.length(), is(299));
assertThat(display, is(
"<select name=\"monChamps\" >" + unixLineSeparator
+ "<option></option><option value=\"0\">0</option>" + unixLineSeparator
+ "<option value=\"1\">1</option>" + unixLineSeparator + "<option value=\"2\">2</option>"
+ unixLineSeparator + "<option value=\"3\">3</option>" + unixLineSeparator
+ "<option value=\"4\">4</option>" + unixLineSeparator
+ "</select>" + unixLineSeparator
+ " <img src=\"/silverpeas//util/icons/mandatoryField.gif\" "
+ "width=\"5\" height=\"5\" alt=\"Obligatoire\"/>"));
}
/**
* Test of update method, of class JdbcFieldDisplayer.
*/
@Test
public void testUpdate() throws Exception {
String newValue = "newValue";
PagesContext pagesContext = new PagesContext();
pagesContext.setUseMandatory(true);
pagesContext.setCurrentFieldIndex("10");
pagesContext.setLastFieldIndex(20);
pagesContext.setLanguage("fr");
pagesContext.setEncoding("UTF-8");
pagesContext.setUserId("0");
JdbcField field = mock(JdbcField.class);
when(field.getTypeName()).thenReturn(JdbcField.TYPE);
when(field.isReadOnly()).thenReturn(false);
when(field.acceptValue("newValue", "fr")).thenReturn(true);
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
instance.update(newValue, field, null, pagesContext);
verify(field).setValue("newValue", "fr");
}
@Test(expected = com.silverpeas.form.FormException.class)
public void testUpdateIncorrectField() throws Exception {
String newValue = "";
JdbcField field = mock(JdbcField.class);
when(field.getTypeName()).thenReturn(RandomGenerator.getRandomString());
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
instance.update(newValue, field, null, null);
}
@Test(expected = com.silverpeas.form.FormException.class)
public void testUpdateIncorrectValue() throws Exception {
String newValue = "";
PagesContext pagesContext = new PagesContext();
pagesContext.setUseMandatory(true);
pagesContext.setCurrentFieldIndex("10");
pagesContext.setLastFieldIndex(20);
pagesContext.setLanguage("fr");
pagesContext.setEncoding("UTF-8");
pagesContext.setUserId("0");
JdbcField field = mock(JdbcField.class);
when(field.getTypeName()).thenReturn(JdbcField.TYPE);
when(field.isReadOnly()).thenReturn(true);
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
instance.update(newValue, field, null, pagesContext);
}
/**
* Test of isDisplayedMandatory method, of class JdbcFieldDisplayer.
*/
@Test
public void testIsDisplayedMandatory() {
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
assertThat(instance.isDisplayedMandatory(), is(true));
}
/**
* Test of getNbHtmlObjectsDisplayed method, of class JdbcFieldDisplayer.
*/
@Test
public void testGetNbHtmlObjectsDisplayed() {
FieldTemplate template = null;
PagesContext pagesContext = null;
JdbcFieldDisplayer instance = new JdbcFieldDisplayer();
int expResult = 1;
int result = instance.getNbHtmlObjectsDisplayed(template, pagesContext);
assertThat(result, is(expResult));
}
}
| Fix the failure of the test JdbcFieldDisplayerTest#testDisplayScripts
| lib-core/src/test-awaiting/java/com/silverpeas/form/displayers/JdbcFieldDisplayerTest.java | Fix the failure of the test JdbcFieldDisplayerTest#testDisplayScripts | <ide><path>ib-core/src/test-awaiting/java/com/silverpeas/form/displayers/JdbcFieldDisplayerTest.java
<ide> instance.displayScripts(printer, template, pagesContext);
<ide> assertThat(new String(out.toByteArray(), Charsets.UTF_8).trim(), is(
<ide> "if (isWhitespace(stripInitialWhitespace(field.value))) {" + lineSeparator
<del> + "\t\terrorMsg+=\" - 'Mon champs JDBC' doit être renseigné\\n \";" + lineSeparator
<add> + "\t\terrorMsg+=\" - 'Mon champs JDBC' doit être renseigné\\n\";" + lineSeparator
<ide> + "\t\terrorNb++;" + lineSeparator + "\t}" + lineSeparator + " try { " + lineSeparator
<ide> + "if (typeof(checkmonChamps) == 'function')" + lineSeparator + " checkmonChamps('fr');"
<ide> + lineSeparator + " } catch (e) { " + lineSeparator + " //catch all exceptions" |
|
Java | mit | 0bc7ff11e59c0244e6e805872ced024fe271d220 | 0 | dozd/XChange,npomfret/XChange,andre77/XChange,Panchen/XChange,gaborkolozsy/XChange,ww3456/XChange,LeonidShamis/XChange,stachon/XChange,douggie/XChange,jheusser/XChange,stevenuray/XChange,evdubs/XChange,anwfr/XChange,chrisrico/XChange,nopy/XChange,timmolter/XChange,TSavo/XChange | package org.knowm.xchange.dto.meta;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
/**
* Describe a call rate limit as a number of calls per some time span.
*/
public class RateLimit {
@JsonProperty("calls")
public int calls = 1;
@JsonProperty("time_span")
public int timeSpan = 1;
@JsonProperty("time_unit")
@JsonDeserialize(using = TimeUnitDeserializer.class)
public TimeUnit timeUnit = TimeUnit.SECONDS;
/**
* Constructor
*/
public RateLimit() {
}
/**
* Constructor
*
* @param calls
* @param timeSpan
* @param timeUnit
*/
public RateLimit(
@JsonProperty("calls") int calls,
@JsonProperty("time_span") int timeSpan,
@JsonProperty("time_unit") @JsonDeserialize(using = TimeUnitDeserializer.class) TimeUnit timeUnit
) {
this.calls = calls;
this.timeUnit = timeUnit;
this.timeSpan = timeSpan;
}
/**
* @return this rate limit as a number of milliseconds required between any two remote calls, assuming the client makes consecutive calls without
* any bursts or breaks for an infinite period of time.
*/
@JsonIgnore
public long getPollDelayMillis() {
return timeUnit.toMillis(timeSpan) / calls;
}
public static class TimeUnitDeserializer extends JsonDeserializer<TimeUnit> {
@Override
public TimeUnit deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
return TimeUnit.valueOf(jp.getValueAsString().toUpperCase());
}
}
}
| xchange-core/src/main/java/org/knowm/xchange/dto/meta/RateLimit.java | package org.knowm.xchange.dto.meta;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
/**
* Describe a call rate limit as a number of calls per some time span.
*/
public class RateLimit {
@JsonProperty("calls")
public int calls = 1;
@JsonProperty("time_span")
public int timeSpan = 1;
@JsonProperty("time_unit")
@JsonDeserialize(using = TimeUnitDeserializer.class)
public TimeUnit timeUnit = TimeUnit.SECONDS;
/**
* Constructor
*/
public RateLimit() {
}
/**
* Constructor
*
* @param calls
* @param timeSpan
* @param timeUnit
*/
public RateLimit(@JsonProperty("calls") int calls, @JsonProperty("time_span") int timeSpan, @JsonProperty("time_unit") TimeUnit timeUnit) {
this.calls = calls;
this.timeUnit = timeUnit;
this.timeSpan = timeSpan;
}
/**
* @return this rate limit as a number of milliseconds required between any two remote calls, assuming the client makes consecutive calls without
* any bursts or breaks for an infinite period of time.
*/
@JsonIgnore
public long getPollDelayMillis() {
return timeUnit.toMillis(timeSpan) / calls;
}
public static class TimeUnitDeserializer extends JsonDeserializer<TimeUnit> {
@Override
public TimeUnit deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
return TimeUnit.valueOf(jp.getValueAsString().toUpperCase());
}
}
}
| Add missing deserializer (was present on property, missing on constructor parameter). For some reason, this broke the Poloniex impl when using Jackson 2.8.2.
| xchange-core/src/main/java/org/knowm/xchange/dto/meta/RateLimit.java | Add missing deserializer (was present on property, missing on constructor parameter). For some reason, this broke the Poloniex impl when using Jackson 2.8.2. | <ide><path>change-core/src/main/java/org/knowm/xchange/dto/meta/RateLimit.java
<ide> * @param timeSpan
<ide> * @param timeUnit
<ide> */
<del> public RateLimit(@JsonProperty("calls") int calls, @JsonProperty("time_span") int timeSpan, @JsonProperty("time_unit") TimeUnit timeUnit) {
<add> public RateLimit(
<add> @JsonProperty("calls") int calls,
<add> @JsonProperty("time_span") int timeSpan,
<add> @JsonProperty("time_unit") @JsonDeserialize(using = TimeUnitDeserializer.class) TimeUnit timeUnit
<add> ) {
<ide>
<ide> this.calls = calls;
<ide> this.timeUnit = timeUnit;
<ide>
<ide> /**
<ide> * @return this rate limit as a number of milliseconds required between any two remote calls, assuming the client makes consecutive calls without
<del> * any bursts or breaks for an infinite period of time.
<add> * any bursts or breaks for an infinite period of time.
<ide> */
<ide> @JsonIgnore
<ide> public long getPollDelayMillis() { |
|
Java | apache-2.0 | error: pathspec 'chapter_002/src/test/java/ru/job4j/iterator/MatrixIteratorTest.java' did not match any file(s) known to git
| d6961e45163584839aec68dabd9ff364f5588ef8 | 1 | ogneyar79/Sirotkin_M | package ru.job4j.iterator;
import org.junit.Before;
import org.junit.Test;
import java.util.NoSuchElementException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class MatrixIteratorTest {
private ConcreteArray itSecond;
IIterator el;
@Before
public void setUp() {
itSecond = new ConcreteArray(new int[][]{{1, 2, 3}, {4, 5, 6}});
el = itSecond.getIterator();
}
@Test
public void hasNextNextSequentialInvocation() {
assertThat(el.hasNext(), is(true));
assertThat(el.next(), is(1));
assertThat(el.hasNext(), is(true));
assertThat(el.next(), is(2));
assertThat(el.hasNext(), is(true));
assertThat(el.next(), is(3));
assertThat(el.hasNext(), is(true));
assertThat(el.next(), is(4));
assertThat(el.hasNext(), is(true));
assertThat(el.next(), is(5));
assertThat(el.hasNext(), is(true));
assertThat(el.next(), is(6));
assertThat(el.hasNext(), is(false));
}
@Test
public void testsThatNextMethodDoesntDependsOnPriorHasNextInvocation() {
assertThat(el.next(), is(1));
assertThat(el.next(), is(2));
assertThat(el.next(), is(3));
assertThat(el.next(), is(4));
assertThat(el.next(), is(5));
assertThat(el.next(), is(6));
}
@Test
public void sequentialHasNextInvocationDoesntAffectRetrievalOrder() {
assertThat(el.hasNext(), is(true));
assertThat(el.hasNext(), is(true));
assertThat(el.next(), is(1));
assertThat(el.next(), is(2));
assertThat(el.next(), is(3));
assertThat(el.next(), is(4));
assertThat(el.next(), is(5));
assertThat(el.next(), is(6));
}
@Test(expected = NoSuchElementException.class)
public void shoulThrowNoSuchElementException() {
itSecond = new ConcreteArray(new int[][]{});
el = itSecond.getIterator();
el.next();
}
} | chapter_002/src/test/java/ru/job4j/iterator/MatrixIteratorTest.java | MatrixIteratorTestCan'tDoException
| chapter_002/src/test/java/ru/job4j/iterator/MatrixIteratorTest.java | MatrixIteratorTestCan'tDoException | <ide><path>hapter_002/src/test/java/ru/job4j/iterator/MatrixIteratorTest.java
<add>package ru.job4j.iterator;
<add>
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>
<add>import java.util.NoSuchElementException;
<add>
<add>import static org.hamcrest.MatcherAssert.assertThat;
<add>import static org.hamcrest.Matchers.is;
<add>
<add>public class MatrixIteratorTest {
<add>
<add> private ConcreteArray itSecond;
<add> IIterator el;
<add>
<add> @Before
<add> public void setUp() {
<add> itSecond = new ConcreteArray(new int[][]{{1, 2, 3}, {4, 5, 6}});
<add> el = itSecond.getIterator();
<add> }
<add>
<add> @Test
<add> public void hasNextNextSequentialInvocation() {
<add> assertThat(el.hasNext(), is(true));
<add> assertThat(el.next(), is(1));
<add> assertThat(el.hasNext(), is(true));
<add> assertThat(el.next(), is(2));
<add> assertThat(el.hasNext(), is(true));
<add> assertThat(el.next(), is(3));
<add> assertThat(el.hasNext(), is(true));
<add> assertThat(el.next(), is(4));
<add> assertThat(el.hasNext(), is(true));
<add> assertThat(el.next(), is(5));
<add> assertThat(el.hasNext(), is(true));
<add> assertThat(el.next(), is(6));
<add> assertThat(el.hasNext(), is(false));
<add> }
<add>
<add> @Test
<add> public void testsThatNextMethodDoesntDependsOnPriorHasNextInvocation() {
<add> assertThat(el.next(), is(1));
<add> assertThat(el.next(), is(2));
<add> assertThat(el.next(), is(3));
<add> assertThat(el.next(), is(4));
<add> assertThat(el.next(), is(5));
<add> assertThat(el.next(), is(6));
<add> }
<add>
<add> @Test
<add> public void sequentialHasNextInvocationDoesntAffectRetrievalOrder() {
<add> assertThat(el.hasNext(), is(true));
<add> assertThat(el.hasNext(), is(true));
<add> assertThat(el.next(), is(1));
<add> assertThat(el.next(), is(2));
<add> assertThat(el.next(), is(3));
<add> assertThat(el.next(), is(4));
<add> assertThat(el.next(), is(5));
<add> assertThat(el.next(), is(6));
<add> }
<add>
<add> @Test(expected = NoSuchElementException.class)
<add> public void shoulThrowNoSuchElementException() {
<add> itSecond = new ConcreteArray(new int[][]{});
<add> el = itSecond.getIterator();
<add> el.next();
<add> }
<add>} |
|
Java | apache-2.0 | ac78f1e105928d73c2dfe0b120e35e8c45e0d3ff | 0 | opencb/cellbase,dapregi/cellbase,opencb/cellbase,dapregi/cellbase,dapregi/cellbase,dapregi/cellbase,opencb/cellbase,opencb/cellbase,opencb/cellbase,dapregi/cellbase,dapregi/cellbase,opencb/cellbase,dapregi/cellbase,opencb/cellbase | /*
* Copyright 2015 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencb.cellbase.core.variant.annotation;
import org.opencb.biodata.models.core.Gene;
import org.opencb.biodata.models.core.Region;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.biodata.models.variant.VariantNormalizer;
import org.opencb.biodata.models.variant.annotation.ConsequenceTypeMappings;
import org.opencb.biodata.models.variant.avro.*;
import org.opencb.cellbase.core.api.*;
import org.opencb.biodata.models.core.RegulatoryFeature;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.commons.datastore.core.QueryResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//import org.opencb.cellbase.core.db.api.core.ConservedRegionDBAdaptor;
//import org.opencb.cellbase.core.db.api.core.GeneDBAdaptor;
//import org.opencb.cellbase.core.db.api.core.GenomeDBAdaptor;
//import org.opencb.cellbase.core.db.api.core.ProteinDBAdaptor;
//import org.opencb.cellbase.core.db.api.regulatory.RegulatoryRegionDBAdaptor;
//import org.opencb.cellbase.core.db.api.variation.ClinicalDBAdaptor;
//import org.opencb.cellbase.core.db.api.variation.VariantFunctionalScoreDBAdaptor;
//import org.opencb.cellbase.core.db.api.variation.VariationDBAdaptor;
/**
* Created by imedina on 06/02/16.
*/
/**
* Created by imedina on 11/07/14.
*
* @author Javier Lopez [email protected];
*/
public class VariantAnnotationCalculator { //extends MongoDBAdaptor implements VariantAnnotationDBAdaptor<VariantAnnotation> {
private GenomeDBAdaptor genomeDBAdaptor;
private GeneDBAdaptor geneDBAdaptor;
private RegulationDBAdaptor regulationDBAdaptor;
private VariantDBAdaptor variantDBAdaptor;
private ClinicalDBAdaptor clinicalDBAdaptor;
private ProteinDBAdaptor proteinDBAdaptor;
private ConservationDBAdaptor conservationDBAdaptor;
private Set<String> annotatorSet;
private String includeGeneFields;
private DBAdaptorFactory dbAdaptorFactory;
// private ObjectMapper geneObjectMapper;
private final VariantNormalizer normalizer;
private boolean normalize = false;
private boolean useCache = true;
private Logger logger = LoggerFactory.getLogger(this.getClass());
// public VariantAnnotationCalculator(String species, String assembly, MongoDataStore mongoDataStore) {
//// super(species, assembly, mongoDataStore);
//
// normalizer = new VariantNormalizer(false);
// logger.debug("VariantAnnotationMongoDBAdaptor: in 'constructor'");
// }
public VariantAnnotationCalculator(String species, String assembly, DBAdaptorFactory dbAdaptorFactory) {
// this(species, assembly, dbAdaptorFactory, true);
// }
//
// public VariantAnnotationCalculator(String species, String assembly, DBAdaptorFactory dbAdaptorFactory,
// boolean normalize) {
this.normalizer = new VariantNormalizer(false, false, true);
// this.normalize = normalize;
this.dbAdaptorFactory = dbAdaptorFactory;
this.genomeDBAdaptor = dbAdaptorFactory.getGenomeDBAdaptor(species, assembly);
this.variantDBAdaptor = dbAdaptorFactory.getVariationDBAdaptor(species, assembly);
this.geneDBAdaptor = dbAdaptorFactory.getGeneDBAdaptor(species, assembly);
this.regulationDBAdaptor = dbAdaptorFactory.getRegulationDBAdaptor(species, assembly);
this.proteinDBAdaptor = dbAdaptorFactory.getProteinDBAdaptor(species, assembly);
this.conservationDBAdaptor = dbAdaptorFactory.getConservationDBAdaptor(species, assembly);
this.clinicalDBAdaptor = dbAdaptorFactory.getClinicalDBAdaptor(species, assembly);
logger.debug("VariantAnnotationMongoDBAdaptor: in 'constructor'");
}
@Deprecated
public QueryResult getAllConsequenceTypesByVariant(Variant variant, QueryOptions queryOptions) {
long dbTimeStart = System.currentTimeMillis();
// We process include and exclude query options to know which annotators to use.
// Include parameter has preference over exclude.
// Set<String> annotatorSet = getAnnotatorSet(queryOptions);
//
// // This field contains all the fields to be returned by overlapping genes
// String includeGeneFields = getIncludedGeneFields(annotatorSet);
parseQueryParam(queryOptions);
List<Gene> geneList = getAffectedGenes(variant, includeGeneFields);
// TODO the last 'true' parameter needs to be changed by annotatorSet.contains("regulatory") once is ready
List<ConsequenceType> consequenceTypeList = getConsequenceTypeList(variant, geneList, true);
QueryResult queryResult = new QueryResult();
queryResult.setId(variant.toString());
queryResult.setDbTime(Long.valueOf(System.currentTimeMillis() - dbTimeStart).intValue());
queryResult.setNumResults(consequenceTypeList.size());
queryResult.setNumTotalResults(consequenceTypeList.size());
queryResult.setResult(consequenceTypeList);
return queryResult;
}
public QueryResult getAnnotationByVariant(Variant variant, QueryOptions queryOptions)
throws InterruptedException, ExecutionException {
return getAnnotationByVariantList(Collections.singletonList(variant), queryOptions).get(0);
}
public List<QueryResult<VariantAnnotation>> getAnnotationByVariantList(List<Variant> variantList,
QueryOptions queryOptions)
throws InterruptedException, ExecutionException {
logger.debug("Annotating batch");
parseQueryParam(queryOptions);
if (variantList == null || variantList.isEmpty()) {
return new ArrayList<>();
}
List<Variant> normalizedVariantList;
if (normalize) {
normalizedVariantList = normalizer.apply(variantList);
} else {
normalizedVariantList = variantList;
}
// Object to be returned
List<QueryResult<VariantAnnotation>> variantAnnotationResultList;
if (useCache) {
variantAnnotationResultList = getCachedPreferredAnnotation(normalizedVariantList);
} else {
variantAnnotationResultList = runAnnotationProcess(normalizedVariantList);
}
return variantAnnotationResultList;
}
private List<QueryResult<VariantAnnotation>> getCachedPreferredAnnotation(List<Variant> variantList)
throws InterruptedException, ExecutionException {
// Expected to be very few within a batch, no capacity initialized for the array
List<Integer> mustRunAnnotationPositions = new ArrayList<>();
List<Variant> mustRunAnnotation = new ArrayList<>();
// Expected to be most of them, array capacity set to variantList size
List<Integer> mustSearchVariationPositions = new ArrayList<>(variantList.size());
List<Variant> mustSearchVariation = new ArrayList<>();
// Phased variants cannot be annotated using the variation collection
for (int i = 0; i < variantList.size(); i++) {
if (isPhased(variantList.get(i))) {
mustRunAnnotationPositions.add(i);
mustRunAnnotation.add(variantList.get(i));
} else {
mustSearchVariationPositions.add(i);
mustSearchVariation.add(variantList.get(i));
}
}
// Search unphased variants within variation collection
QueryOptions queryOptions = new QueryOptions("include", getCachedVariationIncludeFields());
List<QueryResult<Variant>> variationQueryResultList = variantDBAdaptor.getByVariant(mustSearchVariation,
queryOptions);
// Object to be returned
List<QueryResult<VariantAnnotation>> variantAnnotationResultList =
Arrays.asList(new QueryResult[variantList.size()]);
// mustSearchVariation and variationQueryResultList do have same size, same order
for (int i = 0; i < mustSearchVariation.size(); i++) {
// Variant not found in variation collection or the variant was found but not annotated with CellBase - I can
// distinguish CellBase from ENSEMBL annotation because when CellBase annotates, it includes chromosome, start,
// reference and alternate fields - TODO: change this.
// Must be annotated by running the whole process
if (variationQueryResultList.get(i).getNumResults() == 0) {
// || variationQueryResultList.get(i).getResult().get(0).getAnnotation() == null
// || variationQueryResultList.get(i).getResult().get(0).getAnnotation().getConsequenceTypes() == null
// || variationQueryResultList.get(i).getResult().get(0).getAnnotation().getConsequenceTypes().isEmpty()) {
mustRunAnnotationPositions.add(mustSearchVariationPositions.get(i));
mustRunAnnotation.add(mustSearchVariation.get(i));
} else if (variationQueryResultList.get(i).getResult().get(0).getAnnotation() != null
&& variationQueryResultList.get(i).getResult().get(0).getAnnotation().getChromosome() == null) {
mustSearchVariation.get(i).setId(variationQueryResultList.get(i).getResult().get(0).getId());
if (mustSearchVariation.get(i).getAnnotation() == null) {
mustSearchVariation.get(i).setAnnotation(new VariantAnnotation());
}
mustSearchVariation.get(i).getAnnotation()
.setPopulationFrequencies(variationQueryResultList.get(i).getResult().get(0).getAnnotation()
.getPopulationFrequencies());
mustRunAnnotationPositions.add(mustSearchVariationPositions.get(i));
mustRunAnnotation.add(mustSearchVariation.get(i));
} else {
// variantList is the passed by reference argument and reference to objects within variantList are
// copied within mustSearchVariation. Modifying reference objects within mustSearchVariation will
// modify user-provided Variant objects. If there's no annotation - just set it; if there's an annotation
// object already created, let's only overwrite those fields created by the annotator
VariantAnnotation variantAnnotation;
if (mustSearchVariation.get(i).getAnnotation() == null) {
variantAnnotation = variationQueryResultList.get(i).getResult().get(0).getAnnotation();
mustSearchVariation.get(i).setAnnotation(variantAnnotation);
} else {
variantAnnotation = mustSearchVariation.get(i).getAnnotation();
mergeAnnotation(variantAnnotation, variationQueryResultList.get(i).getResult().get(0).getAnnotation());
}
variantAnnotationResultList.set(mustSearchVariationPositions.get(i),
new QueryResult<>(mustSearchVariation.get(i).toString(),
variationQueryResultList.get(i).getDbTime(), variationQueryResultList.get(i).getNumResults(),
variationQueryResultList.get(i).getNumTotalResults(), null, null,
Collections.singletonList(variantAnnotation)));
}
}
List<QueryResult<VariantAnnotation>> uncachedAnnotations = runAnnotationProcess(mustRunAnnotation);
for (int i = 0; i < mustRunAnnotation.size(); i++) {
variantAnnotationResultList.set(mustRunAnnotationPositions.get(i), uncachedAnnotations.get(i));
}
logger.debug("{}/{} ({}%) variants required running the annotation process", mustRunAnnotation.size(),
variantList.size(), (mustRunAnnotation.size() * (100.0 / variantList.size())));
return variantAnnotationResultList;
}
private boolean isPhased(Variant variant) {
return (variant.getStudies() != null && !variant.getStudies().isEmpty())
&& variant.getStudies().get(0).getFormat().contains("PS");
}
private String getCachedVariationIncludeFields() {
StringBuilder stringBuilder = new StringBuilder("annotation.chromosome,annotation.start,annotation.reference");
stringBuilder.append(",annotation.alternate,annotation.id");
if (annotatorSet.contains("variation")) {
stringBuilder.append(",annotation.id,annotation.populationFrequencies");
}
if (annotatorSet.contains("clinical")) {
stringBuilder.append(",annotation.variantTraitAssociation");
}
if (annotatorSet.contains("conservation")) {
stringBuilder.append(",annotation.conservation");
}
if (annotatorSet.contains("functionalScore")) {
stringBuilder.append(",annotation.functionalScore");
}
if (annotatorSet.contains("consequenceType")) {
stringBuilder.append(",annotation.consequenceTypes,annotation.displayConsequenceType");
}
if (annotatorSet.contains("expression")) {
stringBuilder.append(",annotation.geneExpression");
}
if (annotatorSet.contains("geneDisease")) {
stringBuilder.append(",annotation.geneTraitAssociation");
}
if (annotatorSet.contains("drugInteraction")) {
stringBuilder.append(",annotation.geneDrugInteraction");
}
if (annotatorSet.contains("populationFrequencies")) {
stringBuilder.append(",annotation.populationFrequencies");
}
return stringBuilder.toString();
}
private List<QueryResult<VariantAnnotation>> runAnnotationProcess(List<Variant> normalizedVariantList)
throws InterruptedException, ExecutionException {
QueryOptions queryOptions;
long globalStartTime = System.currentTimeMillis();
long startTime;
queryOptions = new QueryOptions();
// Object to be returned
List<QueryResult<VariantAnnotation>> variantAnnotationResultList = new ArrayList<>(normalizedVariantList.size());
/*
* Next three async blocks calculate annotations using Futures, this will be calculated in a different thread.
* Once the main loop has finished then they will be stored. This provides a ~30% of performance improvement.
*/
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);
FutureVariationAnnotator futureVariationAnnotator = null;
Future<List<QueryResult<Variant>>> variationFuture = null;
if (!useCache && (annotatorSet.contains("variation") || annotatorSet.contains("populationFrequencies"))) {
futureVariationAnnotator = new FutureVariationAnnotator(normalizedVariantList, new QueryOptions("include",
"id,annotation.populationFrequencies"));
variationFuture = fixedThreadPool.submit(futureVariationAnnotator);
}
FutureConservationAnnotator futureConservationAnnotator = null;
Future<List<QueryResult>> conservationFuture = null;
if (annotatorSet.contains("conservation")) {
futureConservationAnnotator = new FutureConservationAnnotator(normalizedVariantList, queryOptions);
conservationFuture = fixedThreadPool.submit(futureConservationAnnotator);
}
FutureVariantFunctionalScoreAnnotator futureVariantFunctionalScoreAnnotator = null;
Future<List<QueryResult<Score>>> variantFunctionalScoreFuture = null;
if (annotatorSet.contains("functionalScore")) {
futureVariantFunctionalScoreAnnotator = new FutureVariantFunctionalScoreAnnotator(normalizedVariantList, queryOptions);
variantFunctionalScoreFuture = fixedThreadPool.submit(futureVariantFunctionalScoreAnnotator);
}
FutureClinicalAnnotator futureClinicalAnnotator = null;
Future<List<QueryResult>> clinicalFuture = null;
if (annotatorSet.contains("clinical")) {
futureClinicalAnnotator = new FutureClinicalAnnotator(normalizedVariantList, queryOptions);
clinicalFuture = fixedThreadPool.submit(futureClinicalAnnotator);
}
/*
* We iterate over all variants to get the rest of the annotations and to create the VariantAnnotation objects
*/
List<Gene> geneList;
Queue<Variant> variantBuffer = new LinkedList<>();
startTime = System.currentTimeMillis();
for (int i = 0; i < normalizedVariantList.size(); i++) {
// Fetch overlapping genes for this variant
geneList = getAffectedGenes(normalizedVariantList.get(i), includeGeneFields);
// normalizedVariantList is the passed by reference argument - modifying normalizedVariantList will
// modify user-provided Variant objects. If there's no annotation - just set it; if there's an annotation
// object already created, let's only overwrite those fields created by the annotator
VariantAnnotation variantAnnotation;
if (normalizedVariantList.get(i).getAnnotation() == null) {
variantAnnotation = new VariantAnnotation();
normalizedVariantList.get(i).setAnnotation(variantAnnotation);
} else {
variantAnnotation = normalizedVariantList.get(i).getAnnotation();
}
variantAnnotation.setChromosome(normalizedVariantList.get(i).getChromosome());
variantAnnotation.setStart(normalizedVariantList.get(i).getStart());
variantAnnotation.setReference(normalizedVariantList.get(i).getReference());
variantAnnotation.setAlternate(normalizedVariantList.get(i).getAlternate());
if (annotatorSet.contains("consequenceType")) {
try {
List<ConsequenceType> consequenceTypeList = getConsequenceTypeList(normalizedVariantList.get(i), geneList, true);
variantAnnotation.setConsequenceTypes(consequenceTypeList);
checkAndAdjustPhasedConsequenceTypes(normalizedVariantList.get(i), variantBuffer);
variantAnnotation
.setDisplayConsequenceType(getMostSevereConsequenceType(normalizedVariantList.get(i)
.getAnnotation().getConsequenceTypes()));
} catch (UnsupportedURLVariantFormat e) {
logger.error("Consequence type was not calculated for variant {}. Unrecognised variant format."
+ " Leaving an empty consequence type list.", normalizedVariantList.get(i).toString());
} catch (Exception e) {
logger.error("Unhandled error when calculating consequence type for variant {}. Leaving an empty"
+ " consequence type list.", normalizedVariantList.get(i).toString());
// throw e;
}
}
/*
* Gene Annotation
*/
if (annotatorSet.contains("expression")) {
variantAnnotation.setGeneExpression(new ArrayList<>());
for (Gene gene : geneList) {
if (gene.getAnnotation().getExpression() != null) {
variantAnnotation.getGeneExpression().addAll(gene.getAnnotation().getExpression());
}
}
}
if (annotatorSet.contains("geneDisease")) {
variantAnnotation.setGeneTraitAssociation(new ArrayList<>());
for (Gene gene : geneList) {
if (gene.getAnnotation().getDiseases() != null) {
variantAnnotation.getGeneTraitAssociation().addAll(gene.getAnnotation().getDiseases());
}
}
}
if (annotatorSet.contains("drugInteraction")) {
variantAnnotation.setGeneDrugInteraction(new ArrayList<>());
for (Gene gene : geneList) {
if (gene.getAnnotation().getDrugs() != null) {
variantAnnotation.getGeneDrugInteraction().addAll(gene.getAnnotation().getDrugs());
}
}
}
QueryResult queryResult = new QueryResult(normalizedVariantList.get(i).toString());
queryResult.setDbTime((int) (System.currentTimeMillis() - startTime));
queryResult.setNumResults(1);
queryResult.setNumTotalResults(1);
//noinspection unchecked
queryResult.setResult(Collections.singletonList(variantAnnotation));
variantAnnotationResultList.add(queryResult);
}
// Adjust phase of two last variants - if still anything remaining to adjust. This can happen if the two last
// variants in the batch are phased and the distance between them < 3nts
if (variantBuffer.size() > 1) {
adjustPhasedConsequenceTypes(variantBuffer.toArray());
}
logger.debug("Main loop iteration annotation performance is {}ms for {} variants", System.currentTimeMillis()
- startTime, normalizedVariantList.size());
/*
* Now, hopefully the other annotations have finished and we can store the results.
* Method 'processResults' has been implemented in the same class for sanity.
*/
if (futureVariationAnnotator != null) {
futureVariationAnnotator.processResults(variationFuture, variantAnnotationResultList, annotatorSet);
}
if (futureConservationAnnotator != null) {
futureConservationAnnotator.processResults(conservationFuture, variantAnnotationResultList);
}
if (futureVariantFunctionalScoreAnnotator != null) {
futureVariantFunctionalScoreAnnotator.processResults(variantFunctionalScoreFuture, variantAnnotationResultList);
}
if (futureClinicalAnnotator != null) {
futureClinicalAnnotator.processResults(clinicalFuture, variantAnnotationResultList);
}
fixedThreadPool.shutdown();
logger.debug("Total batch annotation performance is {}ms for {} variants", System.currentTimeMillis()
- globalStartTime, normalizedVariantList.size());
return variantAnnotationResultList;
}
private void parseQueryParam(QueryOptions queryOptions) {
// We process include and exclude query options to know which annotators to use.
// Include parameter has preference over exclude.
annotatorSet = getAnnotatorSet(queryOptions);
logger.debug("Annotators to use: {}", annotatorSet.toString());
// This field contains all the fields to be returned by overlapping genes
includeGeneFields = getIncludedGeneFields(annotatorSet);
// Default behaviour no normalization
normalize = (queryOptions.get("normalize") != null && queryOptions.get("normalize").equals("true"));
// Default behaviour use cache
useCache = (queryOptions.get("useCache") != null ? queryOptions.get("useCache").equals("true") : true);
}
private void mergeAnnotation(VariantAnnotation destination, VariantAnnotation origin) {
destination.setId(origin.getId());
destination.setChromosome(origin.getChromosome());
destination.setStart(origin.getStart());
destination.setReference(origin.getReference());
destination.setAlternate(origin.getAlternate());
destination.setDisplayConsequenceType(origin.getDisplayConsequenceType());
destination.setConsequenceTypes(origin.getConsequenceTypes());
destination.setConservation(origin.getConservation());
destination.setGeneExpression(origin.getGeneExpression());
destination.setGeneTraitAssociation(origin.getGeneTraitAssociation());
destination.setPopulationFrequencies(origin.getPopulationFrequencies());
destination.setGeneDrugInteraction(origin.getGeneDrugInteraction());
destination.setVariantTraitAssociation(origin.getVariantTraitAssociation());
destination.setFunctionalScore(origin.getFunctionalScore());
}
private void checkAndAdjustPhasedConsequenceTypes(Variant variant, Queue<Variant> variantBuffer) {
// Only SNVs are currently considered for phase adjustment
if (variant.getType().equals(VariantType.SNV)) {
// Check and manage variantBuffer for dealing with phased variants
switch (variantBuffer.size()) {
case 0:
variantBuffer.add(variant);
break;
case 1:
if (potentialCodingSNVOverlap(variantBuffer.peek(), variant)) {
variantBuffer.add(variant);
} else {
variantBuffer.poll();
variantBuffer.add(variant);
}
break;
case 2:
if (potentialCodingSNVOverlap(variantBuffer.peek(), variant)) {
variantBuffer.add(variant);
adjustPhasedConsequenceTypes(variantBuffer.toArray());
variantBuffer.poll();
} else {
// Adjust consequence types for the two previous variants
adjustPhasedConsequenceTypes(variantBuffer.toArray());
// Remove the two previous variants after adjustment
variantBuffer.poll();
variantBuffer.poll();
variantBuffer.add(variant);
}
default:
break;
}
}
}
// private void checkAndAdjustPhasedConsequenceTypes(Queue<Variant> variantBuffer) {
// Variant[] variantArray = (Variant[]) variantBuffer.toArray();
// // SSACGATATCTT -> where S represents the position of the SNV
// if (potentialCodingSNVOverlap(variantArray[0], variantArray[1])) {
// // SSSACGATATCTT -> where S represents the position of the SNV. The three SNVs may affect the same codon
// if (potentialCodingSNVOverlap(variantArray[1], variantArray[2])) {
// adjustPhasedConsequenceTypes(variantArray);
// // SSACGATATCVTT -> where S represents the position of the SNV and V represents the position of the third
// // variant. Only the two first SNVs may affect the same codon.
// } else {
// adjustPhasedConsequenceTypes(Arrays.copyOfRange(variantArray, 0,3));
// }
// }
// }
private void adjustPhasedConsequenceTypes(Object[] variantArray) {
Variant variant0 = (Variant) variantArray[0];
for (ConsequenceType consequenceType1 : variant0.getAnnotation().getConsequenceTypes()) {
ProteinVariantAnnotation newProteinVariantAnnotation = null;
// Check if this is a coding consequence type. Also this consequence type may have been already
// updated if there are 3 consecutive phased SNVs affecting the same codon.
if (isCoding(consequenceType1)
&& !transcriptAnnotationUpdated(variant0, consequenceType1.getEnsemblTranscriptId())) {
Variant variant1 = (Variant) variantArray[1];
ConsequenceType consequenceType2
= findCodingOverlappingConsequenceType(consequenceType1, variant1.getAnnotation().getConsequenceTypes());
// The two first variants affect the same codon
if (consequenceType2 != null) {
// WARNING: assumes variants are sorted according to their coordinates
int cdnaPosition = consequenceType1.getCdnaPosition();
int cdsPosition = consequenceType1.getCdsPosition();
String codon = null;
// String alternateAA = null;
List<SequenceOntologyTerm> soTerms = null;
ConsequenceType consequenceType3 = null;
Variant variant2 = null;
// Check if the third variant also affects the same codon
if (variantArray.length > 2) {
variant2 = (Variant) variantArray[2];
consequenceType3
= findCodingOverlappingConsequenceType(consequenceType2, variant2.getAnnotation().getConsequenceTypes());
}
// The three SNVs affect the same codon
if (consequenceType3 != null) {
String referenceCodon = consequenceType1.getCodon().split("/")[0].toUpperCase();
// WARNING: assumes variants are sorted according to their coordinates
String alternateCodon = variant0.getAlternate() + variant1.getAlternate()
+ variant2.getAlternate();
codon = referenceCodon + "/" + alternateCodon;
// alternateAA = VariantAnnotationUtils.CODON_TO_A.get(alternateCodon);
soTerms = updatePhasedSoTerms(consequenceType1.getSequenceOntologyTerms(),
String.valueOf(referenceCodon), String.valueOf(alternateCodon),
variant1.getChromosome().equals("MT"));
// Update consequenceType3
consequenceType3.setCdnaPosition(cdnaPosition);
consequenceType3.setCdsPosition(cdsPosition);
consequenceType3.setCodon(codon);
// consequenceType3.getProteinVariantAnnotation().setAlternate(alternateAA);
newProteinVariantAnnotation = getProteinAnnotation(consequenceType3);
consequenceType3.setProteinVariantAnnotation(newProteinVariantAnnotation);
consequenceType3.setSequenceOntologyTerms(soTerms);
// Flag these transcripts as already updated for this variant
flagTranscriptAnnotationUpdated(variant2, consequenceType1.getEnsemblTranscriptId());
// Only the two first SNVs affect the same codon
} else {
int codonIdx1 = getUpperCaseLetterPosition(consequenceType1.getCodon().split("/")[0]);
int codonIdx2 = getUpperCaseLetterPosition(consequenceType2.getCodon().split("/")[0]);
// Set referenceCodon and alternateCodon leaving only the nts that change in uppercase.
// Careful with upper/lower case letters
char[] referenceCodonArray = consequenceType1.getCodon().split("/")[0].toLowerCase().toCharArray();
referenceCodonArray[codonIdx1] = Character.toUpperCase(referenceCodonArray[codonIdx1]);
referenceCodonArray[codonIdx2] = Character.toUpperCase(referenceCodonArray[codonIdx2]);
char[] alternateCodonArray = referenceCodonArray.clone();
alternateCodonArray[codonIdx1] = variant0.getAlternate().toUpperCase().toCharArray()[0];
alternateCodonArray[codonIdx2] = variant1.getAlternate().toUpperCase().toCharArray()[0];
codon = String.valueOf(referenceCodonArray) + "/" + String.valueOf(alternateCodonArray);
// alternateAA = VariantAnnotationUtils.CODON_TO_A.get(String.valueOf(alternateCodonArray).toUpperCase());
soTerms = updatePhasedSoTerms(consequenceType1.getSequenceOntologyTerms(),
String.valueOf(referenceCodonArray).toUpperCase(),
String.valueOf(alternateCodonArray).toUpperCase(), variant1.getChromosome().equals("MT"));
}
// Update consequenceType1 & 2
consequenceType1.setCodon(codon);
// consequenceType1.getProteinVariantAnnotation().setAlternate(alternateAA);
consequenceType1.setProteinVariantAnnotation(newProteinVariantAnnotation == null
? getProteinAnnotation(consequenceType1) : newProteinVariantAnnotation);
consequenceType1.setSequenceOntologyTerms(soTerms);
consequenceType2.setCdnaPosition(cdnaPosition);
consequenceType2.setCdsPosition(cdsPosition);
consequenceType2.setCodon(codon);
// consequenceType2.getProteinVariantAnnotation().setAlternate(alternateAA);
consequenceType2.setProteinVariantAnnotation(consequenceType1.getProteinVariantAnnotation());
consequenceType2.setSequenceOntologyTerms(soTerms);
// Flag these transcripts as already updated for this variant
flagTranscriptAnnotationUpdated(variant0, consequenceType1.getEnsemblTranscriptId());
flagTranscriptAnnotationUpdated(variant1, consequenceType1.getEnsemblTranscriptId());
}
}
}
}
private void flagTranscriptAnnotationUpdated(Variant variant, String ensemblTranscriptId) {
Map<String, Object> additionalAttributesMap = variant.getAnnotation().getAdditionalAttributes();
if (additionalAttributesMap == null) {
additionalAttributesMap = new HashMap<>();
Map<String, String> transcriptsSet = new HashMap<>();
transcriptsSet.put(ensemblTranscriptId, null);
additionalAttributesMap.put("phasedTranscripts", transcriptsSet);
variant.getAnnotation().setAdditionalAttributes(additionalAttributesMap);
} else if (additionalAttributesMap.get("phasedTranscripts") == null) {
Map<String, String> transcriptsSet = new HashMap<>();
transcriptsSet.put(ensemblTranscriptId, null);
additionalAttributesMap.put("phasedTranscripts", transcriptsSet);
} else {
((Map) additionalAttributesMap.get("phasedTranscripts")).put(ensemblTranscriptId, null);
}
}
private boolean transcriptAnnotationUpdated(Variant variant, String ensemblTranscriptId) {
if (variant.getAnnotation().getAdditionalAttributes() != null
&& variant.getAnnotation().getAdditionalAttributes().get("phasedTranscripts") != null
&& ((Map<String, String>) variant.getAnnotation().getAdditionalAttributes().get("phasedTranscripts"))
.containsKey(ensemblTranscriptId)) {
return true;
}
return false;
}
private int getUpperCaseLetterPosition(String string) {
// Pattern pat = Pattern.compile("G");
Pattern pat = Pattern.compile("[A,C,G,T]");
Matcher match = pat.matcher(string);
if (match.find()) {
return match.start();
} else {
return -1;
}
}
private ConsequenceType findCodingOverlappingConsequenceType(ConsequenceType consequenceType,
List<ConsequenceType> consequenceTypeList) {
for (ConsequenceType consequenceType1 : consequenceTypeList) {
if (isCoding(consequenceType1)
&& consequenceType.getEnsemblTranscriptId().equals(consequenceType1.getEnsemblTranscriptId())
&& consequenceType.getProteinVariantAnnotation().getPosition()
.equals(consequenceType1.getProteinVariantAnnotation().getPosition())) {
return consequenceType1;
}
}
return null;
}
private boolean isCoding(ConsequenceType consequenceType) {
for (SequenceOntologyTerm sequenceOntologyTerm : consequenceType.getSequenceOntologyTerms()) {
if (VariantAnnotationUtils.CODING_SO_NAMES.contains(sequenceOntologyTerm.getName())) {
return true;
}
}
return false;
}
private List<SequenceOntologyTerm> updatePhasedSoTerms(List<SequenceOntologyTerm> sequenceOntologyTermList,
String referenceCodon, String alternateCodon,
Boolean useMitochondrialCode) {
// Removes all coding-associated SO terms
int i = 0;
do {
if (VariantAnnotationUtils.CODING_SO_NAMES.contains(sequenceOntologyTermList.get(i).getName())) {
sequenceOntologyTermList.remove(i);
} else {
i++;
}
} while(i < sequenceOntologyTermList.size());
// Add the new coding SO term as appropriate
String newSoName = null;
if (VariantAnnotationUtils.isSynonymousCodon(useMitochondrialCode, referenceCodon, alternateCodon)) {
if (VariantAnnotationUtils.isStopCodon(useMitochondrialCode, referenceCodon)) {
newSoName = VariantAnnotationUtils.STOP_RETAINED_VARIANT;
} else { // coding end may be not correctly annotated (incomplete_terminal_codon_variant),
// but if the length of the cds%3=0, annotation should be synonymous variant
newSoName = VariantAnnotationUtils.SYNONYMOUS_VARIANT;
}
} else if (VariantAnnotationUtils.isStopCodon(useMitochondrialCode, referenceCodon)) {
newSoName = VariantAnnotationUtils.STOP_LOST;
} else if (VariantAnnotationUtils.isStopCodon(useMitochondrialCode, alternateCodon)) {
newSoName = VariantAnnotationUtils.STOP_GAINED;
} else {
newSoName = VariantAnnotationUtils.MISSENSE_VARIANT;
}
sequenceOntologyTermList
.add(new SequenceOntologyTerm(ConsequenceTypeMappings.getSoAccessionString(newSoName), newSoName));
return sequenceOntologyTermList;
}
private boolean potentialCodingSNVOverlap(Variant variant1, Variant variant2) {
return Math.abs(variant1.getStart() - variant2.getStart()) < 3
&& variant1.getChromosome().equals(variant2.getChromosome())
&& variant1.getType().equals(VariantType.SNV) && variant2.getType().equals(VariantType.SNV)
&& samePhase(variant1, variant2);
}
private boolean samePhase(Variant variant1, Variant variant2) {
if (variant1.getStudies() != null && !variant1.getStudies().isEmpty()) {
if (variant2.getStudies() != null && !variant2.getStudies().isEmpty()) {
int psIdx1 = variant1.getStudies().get(0).getFormat().indexOf("PS");
if (psIdx1 != -1) {
int psIdx2 = variant2.getStudies().get(0).getFormat().indexOf("PS");
if (psIdx2 != -1 && // variant2 does have PS set
// same phase set value in both variants
variant2.getStudies().get(0).getSamplesData().get(0).get(psIdx2)
.equals(variant1.getStudies().get(0).getSamplesData().get(0).get(psIdx1))
// Same genotype call in both variants (e.g. 1|0=1|0).
// WARNING: assuming variant1 and variant2 do have Files.
&& variant1.getStudies().get(0).getFiles().get(0).getCall()
.equals(variant2.getStudies().get(0).getFiles().get(0).getCall())) {
return true;
}
}
}
}
return false;
}
private String getMostSevereConsequenceType(List<ConsequenceType> consequenceTypeList) {
int max = -1;
String mostSevereConsequencetype = null;
for (ConsequenceType consequenceType : consequenceTypeList) {
for (SequenceOntologyTerm sequenceOntologyTerm : consequenceType.getSequenceOntologyTerms()) {
int rank = VariantAnnotationUtils.SO_SEVERITY.get(sequenceOntologyTerm.getName());
if (rank > max) {
max = rank;
mostSevereConsequencetype = sequenceOntologyTerm.getName();
}
}
}
return mostSevereConsequencetype;
}
private Set<String> getAnnotatorSet(QueryOptions queryOptions) {
Set<String> annotatorSet;
List<String> includeList = queryOptions.getAsStringList("include");
if (includeList.size() > 0) {
annotatorSet = new HashSet<>(includeList);
} else {
annotatorSet = new HashSet<>(Arrays.asList("variation", "clinical", "conservation", "functionalScore",
"consequenceType", "expression", "geneDisease", "drugInteraction", "populationFrequencies"));
List<String> excludeList = queryOptions.getAsStringList("exclude");
excludeList.forEach(annotatorSet::remove);
}
return annotatorSet;
}
private String getIncludedGeneFields(Set<String> annotatorSet) {
String includeGeneFields = "name,id,start,end,transcripts.id,transcripts.start,transcripts.end,transcripts.strand,"
+ "transcripts.cdsLength,transcripts.annotationFlags,transcripts.biotype,transcripts.genomicCodingStart,"
+ "transcripts.genomicCodingEnd,transcripts.cdnaCodingStart,transcripts.cdnaCodingEnd,transcripts.exons.start,"
+ "transcripts.exons.end,transcripts.exons.sequence,transcripts.exons.phase,mirna.matures,mirna.sequence,"
+ "mirna.matures.cdnaStart,mirna.matures.cdnaEnd";
if (annotatorSet.contains("expression")) {
includeGeneFields += ",annotation.expression";
}
if (annotatorSet.contains("geneDisease")) {
includeGeneFields += ",annotation.diseases";
}
if (annotatorSet.contains("drugInteraction")) {
includeGeneFields += ",annotation.drugs";
}
return includeGeneFields;
}
private List<Gene> getAffectedGenes(Variant variant, String includeFields) {
// reference = "" if insertion, reference = null if CNV for example
int variantStart = variant.getReference() != null && variant.getReference().isEmpty()
? variant.getStart() - 1 : variant.getStart();
QueryOptions queryOptions = new QueryOptions("include", includeFields);
// QueryResult queryResult = geneDBAdaptor.getAllByRegion(new Region(variant.getChromosome(),
// variantStart - 5000, variant.getStart() + variant.getReference().length() - 1 + 5000), queryOptions);
return geneDBAdaptor
.getByRegion(new Region(variant.getChromosome(), Math.max(1, variantStart - 5000),
variant.getEnd() + 5000), queryOptions).getResult();
// variant.getStart() + variant.getReference().length() - 1 + 5000), queryOptions).getResult();
// return geneDBAdaptor.get(new Query("region", variant.getChromosome()+":"+(variantStart - 5000)+":"
// +(variant.getStart() + variant.getReference().length() - 1 + 5000)), queryOptions)
// .getResult();
// QueryResult queryResult = geneDBAdaptor.getAllByRegion(new Region(variant.getChromosome(),
// variantStart - 5000, variant.getStart() + variant.getReference().length() - 1 + 5000), queryOptions);
//
// List<Gene> geneList = new ArrayList<>(queryResult.getNumResults());
// for (Object object : queryResult.getResult()) {
// Gene gene = geneObjectMapper.convertValue(object, Gene.class);
// geneList.add(gene);
// }
// return geneList;
}
private boolean nonSynonymous(ConsequenceType consequenceType, boolean useMitochondrialCode) {
if (consequenceType.getCodon() == null) {
return false;
} else {
String[] parts = consequenceType.getCodon().split("/");
String ref = String.valueOf(parts[0]).toUpperCase();
String alt = String.valueOf(parts[1]).toUpperCase();
return !VariantAnnotationUtils.isSynonymousCodon(useMitochondrialCode, ref, alt)
&& !VariantAnnotationUtils.isStopCodon(useMitochondrialCode, ref);
}
}
private ProteinVariantAnnotation getProteinAnnotation(ConsequenceType consequenceType) {
if (consequenceType.getProteinVariantAnnotation() != null) {
QueryResult<ProteinVariantAnnotation> proteinVariantAnnotation = proteinDBAdaptor.getVariantAnnotation(
consequenceType.getEnsemblTranscriptId(),
consequenceType.getProteinVariantAnnotation().getPosition(),
consequenceType.getProteinVariantAnnotation().getReference(),
consequenceType.getProteinVariantAnnotation().getAlternate(), new QueryOptions());
if (proteinVariantAnnotation.getNumResults() > 0) {
return proteinVariantAnnotation.getResult().get(0);
}
}
return null;
}
private ConsequenceTypeCalculator getConsequenceTypeCalculator(Variant variant) throws UnsupportedURLVariantFormat {
switch (getVariantType(variant)) {
case INSERTION:
return new ConsequenceTypeInsertionCalculator(genomeDBAdaptor);
case DELETION:
return new ConsequenceTypeDeletionCalculator(genomeDBAdaptor);
case SNV:
return new ConsequenceTypeSNVCalculator();
case CNV:
return new ConsequenceTypeCNVCalculator();
default:
throw new UnsupportedURLVariantFormat();
}
}
private VariantType getVariantType(Variant variant) throws UnsupportedURLVariantFormat {
if (variant.getType() == null) {
variant.setType(Variant.inferType(variant.getReference(), variant.getAlternate(), variant.getLength()));
}
// FIXME: remove the if block below as soon as the Variant.inferType method is able to differentiate between
// FIXME: insertions and deletions
if (variant.getType().equals(VariantType.INDEL)) {
if (variant.getReference().isEmpty()) {
variant.setType(VariantType.INSERTION);
} else {
variant.setType(VariantType.DELETION);
}
}
return variant.getType();
// return getVariantType(variant.getReference(), variant.getAlternate());
}
// private VariantType getVariantType(String reference, String alternate) {
// if (reference.isEmpty()) {
// return VariantType.INSERTION;
// } else if (alternate.isEmpty()) {
// return VariantType.DELETION;
// } else if (reference.length() == 1 && alternate.length() == 1) {
// return VariantType.SNV;
// } else {
// throw new UnsupportedURLVariantFormat();
// }
// }
private List<RegulatoryFeature> getAffectedRegulatoryRegions(Variant variant) {
int variantStart = variant.getReference() != null && variant.getReference().isEmpty()
? variant.getStart() - 1 : variant.getStart();
QueryOptions queryOptions = new QueryOptions();
queryOptions.add("include", "chromosome,start,end");
// QueryResult queryResult = regulationDBAdaptor.nativeGet(new Query("region", variant.getChromosome()
// + ":" + variantStart + ":" + (variant.getStart() + variant.getReference().length() - 1)), queryOptions);
QueryResult<RegulatoryFeature> queryResult = regulationDBAdaptor.getByRegion(new Region(variant.getChromosome(),
variantStart, variant.getEnd()), queryOptions);
// variantStart, variant.getStart() + variant.getReference().length() - 1), queryOptions);
List<RegulatoryFeature> regionList = new ArrayList<>(queryResult.getNumResults());
for (RegulatoryFeature object : queryResult.getResult()) {
regionList.add(object);
}
// for (Object object : queryResult.getResult()) {
// Document dbObject = (Document) object;
// RegulatoryRegion regulatoryRegion = new RegulatoryRegion();
// regulatoryRegion.setChromosome((String) dbObject.get("chromosome"));
// regulatoryRegion.setStart((int) dbObject.get("start"));
// regulatoryRegion.setEnd((int) dbObject.get("end"));
// regulatoryRegion.setType((String) dbObject.get("featureType"));
// regionList.add(regulatoryRegion);
// }
return regionList;
}
private List<ConsequenceType> getConsequenceTypeList(Variant variant, List<Gene> geneList, boolean regulatoryAnnotation) {
List<RegulatoryFeature> regulatoryRegionList = null;
if (regulatoryAnnotation) {
regulatoryRegionList = getAffectedRegulatoryRegions(variant);
}
ConsequenceTypeCalculator consequenceTypeCalculator = getConsequenceTypeCalculator(variant);
List<ConsequenceType> consequenceTypeList = consequenceTypeCalculator.run(variant, geneList, regulatoryRegionList);
if (variant.getType() == VariantType.SNV
|| Variant.inferType(variant.getReference(), variant.getAlternate(), variant.getLength()) == VariantType.SNV) {
for (ConsequenceType consequenceType : consequenceTypeList) {
if (nonSynonymous(consequenceType, variant.getChromosome().equals("MT"))) {
consequenceType.setProteinVariantAnnotation(getProteinAnnotation(consequenceType));
}
}
}
return consequenceTypeList;
}
private List<Region> variantListToRegionList(List<Variant> variantList) {
List<Region> regionList = new ArrayList<>(variantList.size());
for (Variant variant : variantList) {
regionList.add(new Region(variant.getChromosome(), variant.getStart(), variant.getStart()));
}
return regionList;
}
/*
* Future classes for Async annotations
*/
class FutureVariationAnnotator implements Callable<List<QueryResult<Variant>>> {
private List<Variant> variantList;
private QueryOptions queryOptions;
public FutureVariationAnnotator(List<Variant> variantList, QueryOptions queryOptions) {
this.variantList = variantList;
this.queryOptions = queryOptions;
}
@Override
public List<QueryResult<Variant>> call() throws Exception {
long startTime = System.currentTimeMillis();
List<QueryResult<Variant>> variationQueryResultList = variantDBAdaptor.getByVariant(variantList, queryOptions);
logger.debug("Variation query performance is {}ms for {} variants", System.currentTimeMillis() - startTime, variantList.size());
return variationQueryResultList;
}
public void processResults(Future<List<QueryResult<Variant>>> conservationFuture,
List<QueryResult<VariantAnnotation>> variantAnnotationResultList,
Set<String> annotatorSet) throws InterruptedException, ExecutionException {
// try {
while (!conservationFuture.isDone()) {
Thread.sleep(1);
}
List<QueryResult<Variant>> variationQueryResults = conservationFuture.get();
if (variationQueryResults != null) {
for (int i = 0; i < variantAnnotationResultList.size(); i++) {
if (variationQueryResults.get(i).first() != null && variationQueryResults.get(i).first().getIds().size() > 0) {
variantAnnotationResultList.get(i).first().setId(variationQueryResults.get(i).first().getIds().get(0));
}
if (annotatorSet.contains("populationFrequencies") && variationQueryResults.get(i).first() != null) {
variantAnnotationResultList.get(i).first().setPopulationFrequencies(variationQueryResults.get(i)
.first().getAnnotation().getPopulationFrequencies());
}
// List<Document> variationDBList = (List<Document>) variationQueryResults.get(i).getResult();
// if (variationDBList != null && variationDBList.size() > 0) {
// BasicDBList idsDBList = (BasicDBList) variationDBList.get(0).get("ids");
// if (idsDBList != null) {
// variantAnnotationResultList.get(i).getResult().get(0).setId((String) idsDBList.get(0));
// }
// if (annotatorSet.contains("populationFrequencies")) {
// Document annotationDBObject = (Document) variationDBList.get(0).get("annotation");
// if (annotationDBObject != null) {
// BasicDBList freqsDBList = (BasicDBList) annotationDBObject.get("populationFrequencies");
// if (freqsDBList != null) {
// Document freqDBObject;
// variantAnnotationResultList.get(i).getResult().get(0).setPopulationFrequencies(new ArrayList<>());
// for (int j = 0; j < freqsDBList.size(); j++) {
// freqDBObject = ((Document) freqsDBList.get(j));
// if (freqDBObject != null && freqDBObject.get("refAllele") != null) {
// if (freqDBObject.containsKey("study")) {
// variantAnnotationResultList.get(i).getResult().get(0)
// .getPopulationFrequencies()
// .add(new PopulationFrequency(freqDBObject.get("study").toString(),
// freqDBObject.get("population").toString(),
// freqDBObject.get("refAllele").toString(),
// freqDBObject.get("altAllele").toString(),
// Float.valueOf(freqDBObject.get("refAlleleFreq").toString()),
// Float.valueOf(freqDBObject.get("altAlleleFreq").toString()),
// 0.0f, 0.0f, 0.0f));
// } else {
// variantAnnotationResultList.get(i).getResult().get(0)
// .getPopulationFrequencies().add(new PopulationFrequency("1000G_PHASE_3",
// freqDBObject.get("population").toString(),
// freqDBObject.get("refAllele").toString(),
// freqDBObject.get("altAllele").toString(),
// Float.valueOf(freqDBObject.get("refAlleleFreq").toString()),
// Float.valueOf(freqDBObject.get("altAlleleFreq").toString()),
// 0.0f, 0.0f, 0.0f));
// }
// }
// }
// }
// }
// }
// }
}
}
// } catch (ExecutionException e) {
// } catch (InterruptedException | ExecutionException e) {
// e.printStackTrace();
// }
}
}
class FutureConservationAnnotator implements Callable<List<QueryResult>> {
private List<Variant> variantList;
private QueryOptions queryOptions;
public FutureConservationAnnotator(List<Variant> variantList, QueryOptions queryOptions) {
this.variantList = variantList;
this.queryOptions = queryOptions;
}
@Override
public List<QueryResult> call() throws Exception {
long startTime = System.currentTimeMillis();
List<QueryResult> conservationQueryResultList = conservationDBAdaptor
.getAllScoresByRegionList(variantListToRegionList(variantList), queryOptions);
logger.debug("Conservation query performance is {}ms for {} variants", System.currentTimeMillis() - startTime,
variantList.size());
return conservationQueryResultList;
}
public void processResults(Future<List<QueryResult>> conservationFuture,
List<QueryResult<VariantAnnotation>> variantAnnotationResultList)
throws InterruptedException, ExecutionException {
// try {
while (!conservationFuture.isDone()) {
Thread.sleep(1);
}
List<QueryResult> conservationQueryResults = conservationFuture.get();
if (conservationQueryResults != null) {
for (int i = 0; i < variantAnnotationResultList.size(); i++) {
variantAnnotationResultList.get(i).getResult().get(0)
.setConservation((List<Score>) conservationQueryResults.get(i).getResult());
}
}
// } catch (ExecutionException e) {
// } catch (InterruptedException | ExecutionException e) {
// e.printStackTrace();
// }
}
}
class FutureVariantFunctionalScoreAnnotator implements Callable<List<QueryResult<Score>>> {
private List<Variant> variantList;
private QueryOptions queryOptions;
public FutureVariantFunctionalScoreAnnotator(List<Variant> variantList, QueryOptions queryOptions) {
this.variantList = variantList;
this.queryOptions = queryOptions;
}
@Override
public List<QueryResult<Score>> call() throws Exception {
long startTime = System.currentTimeMillis();
// List<QueryResult> variantFunctionalScoreQueryResultList =
// variantFunctionalScoreDBAdaptor.getAllByVariantList(variantList, queryOptions);
List<QueryResult<Score>> variantFunctionalScoreQueryResultList =
variantDBAdaptor.getFunctionalScoreVariant(variantList, queryOptions);
logger.debug("VariantFunctionalScore query performance is {}ms for {} variants",
System.currentTimeMillis() - startTime, variantList.size());
return variantFunctionalScoreQueryResultList;
}
public void processResults(Future<List<QueryResult<Score>>> variantFunctionalScoreFuture,
List<QueryResult<VariantAnnotation>> variantAnnotationResultList)
throws InterruptedException, ExecutionException {
// try {
while (!variantFunctionalScoreFuture.isDone()) {
Thread.sleep(1);
}
List<QueryResult<Score>> variantFunctionalScoreQueryResults = variantFunctionalScoreFuture.get();
if (variantFunctionalScoreQueryResults != null) {
for (int i = 0; i < variantAnnotationResultList.size(); i++) {
if (variantFunctionalScoreQueryResults.get(i).getNumResults() > 0) {
variantAnnotationResultList.get(i).getResult().get(0)
.setFunctionalScore((List<Score>) variantFunctionalScoreQueryResults.get(i).getResult());
}
}
}
// } catch (ExecutionException e) {
// } catch (InterruptedException | ExecutionException e) {
// e.printStackTrace();
}
// }
}
class FutureClinicalAnnotator implements Callable<List<QueryResult>> {
private List<Variant> variantList;
private QueryOptions queryOptions;
public FutureClinicalAnnotator(List<Variant> variantList, QueryOptions queryOptions) {
this.variantList = variantList;
this.queryOptions = queryOptions;
}
@Override
public List<QueryResult> call() throws Exception {
long startTime = System.currentTimeMillis();
List<QueryResult> clinicalQueryResultList = clinicalDBAdaptor.getAllByGenomicVariantList(variantList, queryOptions);
logger.debug("Clinical query performance is {}ms for {} variants", System.currentTimeMillis() - startTime, variantList.size());
return clinicalQueryResultList;
}
public void processResults(Future<List<QueryResult>> clinicalFuture,
List<QueryResult<VariantAnnotation>> variantAnnotationResults)
throws InterruptedException, ExecutionException {
// try {
while (!clinicalFuture.isDone()) {
Thread.sleep(1);
}
List<QueryResult> clinicalQueryResults = clinicalFuture.get();
if (clinicalQueryResults != null) {
for (int i = 0; i < variantAnnotationResults.size(); i++) {
QueryResult clinicalQueryResult = clinicalQueryResults.get(i);
if (clinicalQueryResult.getResult() != null && clinicalQueryResult.getResult().size() > 0) {
variantAnnotationResults.get(i).getResult().get(0)
.setVariantTraitAssociation((VariantTraitAssociation) clinicalQueryResult.getResult().get(0));
}
}
}
// } catch (ExecutionException e) {
//// } catch (InterruptedException | ExecutionException e) {
// e.printStackTrace();
// }
}
}
}
| cellbase-core/src/main/java/org/opencb/cellbase/core/variant/annotation/VariantAnnotationCalculator.java | /*
* Copyright 2015 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencb.cellbase.core.variant.annotation;
import org.opencb.biodata.models.core.Gene;
import org.opencb.biodata.models.core.Region;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.biodata.models.variant.VariantNormalizer;
import org.opencb.biodata.models.variant.annotation.ConsequenceTypeMappings;
import org.opencb.biodata.models.variant.avro.*;
import org.opencb.cellbase.core.api.*;
import org.opencb.biodata.models.core.RegulatoryFeature;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.commons.datastore.core.QueryResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//import org.opencb.cellbase.core.db.api.core.ConservedRegionDBAdaptor;
//import org.opencb.cellbase.core.db.api.core.GeneDBAdaptor;
//import org.opencb.cellbase.core.db.api.core.GenomeDBAdaptor;
//import org.opencb.cellbase.core.db.api.core.ProteinDBAdaptor;
//import org.opencb.cellbase.core.db.api.regulatory.RegulatoryRegionDBAdaptor;
//import org.opencb.cellbase.core.db.api.variation.ClinicalDBAdaptor;
//import org.opencb.cellbase.core.db.api.variation.VariantFunctionalScoreDBAdaptor;
//import org.opencb.cellbase.core.db.api.variation.VariationDBAdaptor;
/**
* Created by imedina on 06/02/16.
*/
/**
* Created by imedina on 11/07/14.
*
* @author Javier Lopez [email protected];
*/
public class VariantAnnotationCalculator { //extends MongoDBAdaptor implements VariantAnnotationDBAdaptor<VariantAnnotation> {
private GenomeDBAdaptor genomeDBAdaptor;
private GeneDBAdaptor geneDBAdaptor;
private RegulationDBAdaptor regulationDBAdaptor;
private VariantDBAdaptor variantDBAdaptor;
private ClinicalDBAdaptor clinicalDBAdaptor;
private ProteinDBAdaptor proteinDBAdaptor;
private ConservationDBAdaptor conservationDBAdaptor;
private Set<String> annotatorSet;
private String includeGeneFields;
private DBAdaptorFactory dbAdaptorFactory;
// private ObjectMapper geneObjectMapper;
private final VariantNormalizer normalizer;
private boolean normalize = false;
private boolean useCache = true;
private Logger logger = LoggerFactory.getLogger(this.getClass());
// public VariantAnnotationCalculator(String species, String assembly, MongoDataStore mongoDataStore) {
//// super(species, assembly, mongoDataStore);
//
// normalizer = new VariantNormalizer(false);
// logger.debug("VariantAnnotationMongoDBAdaptor: in 'constructor'");
// }
public VariantAnnotationCalculator(String species, String assembly, DBAdaptorFactory dbAdaptorFactory) {
// this(species, assembly, dbAdaptorFactory, true);
// }
//
// public VariantAnnotationCalculator(String species, String assembly, DBAdaptorFactory dbAdaptorFactory,
// boolean normalize) {
this.normalizer = new VariantNormalizer(false, false, true);
// this.normalize = normalize;
this.dbAdaptorFactory = dbAdaptorFactory;
this.genomeDBAdaptor = dbAdaptorFactory.getGenomeDBAdaptor(species, assembly);
this.variantDBAdaptor = dbAdaptorFactory.getVariationDBAdaptor(species, assembly);
this.geneDBAdaptor = dbAdaptorFactory.getGeneDBAdaptor(species, assembly);
this.regulationDBAdaptor = dbAdaptorFactory.getRegulationDBAdaptor(species, assembly);
this.proteinDBAdaptor = dbAdaptorFactory.getProteinDBAdaptor(species, assembly);
this.conservationDBAdaptor = dbAdaptorFactory.getConservationDBAdaptor(species, assembly);
this.clinicalDBAdaptor = dbAdaptorFactory.getClinicalDBAdaptor(species, assembly);
logger.debug("VariantAnnotationMongoDBAdaptor: in 'constructor'");
}
@Deprecated
public QueryResult getAllConsequenceTypesByVariant(Variant variant, QueryOptions queryOptions) {
long dbTimeStart = System.currentTimeMillis();
// We process include and exclude query options to know which annotators to use.
// Include parameter has preference over exclude.
// Set<String> annotatorSet = getAnnotatorSet(queryOptions);
//
// // This field contains all the fields to be returned by overlapping genes
// String includeGeneFields = getIncludedGeneFields(annotatorSet);
parseQueryParam(queryOptions);
List<Gene> geneList = getAffectedGenes(variant, includeGeneFields);
// TODO the last 'true' parameter needs to be changed by annotatorSet.contains("regulatory") once is ready
List<ConsequenceType> consequenceTypeList = getConsequenceTypeList(variant, geneList, true);
QueryResult queryResult = new QueryResult();
queryResult.setId(variant.toString());
queryResult.setDbTime(Long.valueOf(System.currentTimeMillis() - dbTimeStart).intValue());
queryResult.setNumResults(consequenceTypeList.size());
queryResult.setNumTotalResults(consequenceTypeList.size());
queryResult.setResult(consequenceTypeList);
return queryResult;
}
public QueryResult getAnnotationByVariant(Variant variant, QueryOptions queryOptions)
throws InterruptedException, ExecutionException {
return getAnnotationByVariantList(Collections.singletonList(variant), queryOptions).get(0);
}
public List<QueryResult<VariantAnnotation>> getAnnotationByVariantList(List<Variant> variantList,
QueryOptions queryOptions)
throws InterruptedException, ExecutionException {
logger.debug("Annotating batch");
parseQueryParam(queryOptions);
if (variantList == null || variantList.isEmpty()) {
return new ArrayList<>();
}
List<Variant> normalizedVariantList;
if (normalize) {
normalizedVariantList = normalizer.apply(variantList);
} else {
normalizedVariantList = variantList;
}
// Object to be returned
List<QueryResult<VariantAnnotation>> variantAnnotationResultList;
if (useCache) {
variantAnnotationResultList = getCachedPreferredAnnotation(normalizedVariantList);
} else {
variantAnnotationResultList = runAnnotationProcess(normalizedVariantList);
}
return variantAnnotationResultList;
}
private List<QueryResult<VariantAnnotation>> getCachedPreferredAnnotation(List<Variant> variantList)
throws InterruptedException, ExecutionException {
// Expected to be very few within a batch, no capacity initialized for the array
List<Integer> mustRunAnnotationPositions = new ArrayList<>();
List<Variant> mustRunAnnotation = new ArrayList<>();
// Expected to be most of them, array capacity set to variantList size
List<Integer> mustSearchVariationPositions = new ArrayList<>(variantList.size());
List<Variant> mustSearchVariation = new ArrayList<>();
// Phased variants cannot be annotated using the variation collection
for (int i = 0; i < variantList.size(); i++) {
if (isPhased(variantList.get(i))) {
mustRunAnnotationPositions.add(i);
mustRunAnnotation.add(variantList.get(i));
} else {
mustSearchVariationPositions.add(i);
mustSearchVariation.add(variantList.get(i));
}
}
// Search unphased variants within variation collection
QueryOptions queryOptions = new QueryOptions("include", getCachedVariationIncludeFields());
List<QueryResult<Variant>> variationQueryResultList = variantDBAdaptor.getByVariant(mustSearchVariation,
queryOptions);
// Object to be returned
List<QueryResult<VariantAnnotation>> variantAnnotationResultList =
Arrays.asList(new QueryResult[variantList.size()]);
// mustSearchVariation and variationQueryResultList do have same size, same order
for (int i = 0; i < mustSearchVariation.size(); i++) {
// Variant not found in variation collection or the variant was found but not annotated with CellBase - I can
// distinguish CellBase from ENSEMBL annotation because when CellBase annotates, it includes chromosome, start,
// reference and alternate fields - TODO: change this.
// Must be annotated by running the whole process
if (variationQueryResultList.get(i).getNumResults() == 0) {
// || variationQueryResultList.get(i).getResult().get(0).getAnnotation() == null
// || variationQueryResultList.get(i).getResult().get(0).getAnnotation().getConsequenceTypes() == null
// || variationQueryResultList.get(i).getResult().get(0).getAnnotation().getConsequenceTypes().isEmpty()) {
mustRunAnnotationPositions.add(mustSearchVariationPositions.get(i));
mustRunAnnotation.add(mustSearchVariation.get(i));
} else if (variationQueryResultList.get(i).getResult().get(0).getAnnotation() != null
&& variationQueryResultList.get(i).getResult().get(0).getAnnotation().getChromosome() == null) {
mustSearchVariation.get(i).setId(variationQueryResultList.get(i).getResult().get(0).getId());
mustSearchVariation.get(i).getAnnotation()
.setPopulationFrequencies(variationQueryResultList.get(i).getResult().get(0).getAnnotation()
.getPopulationFrequencies());
mustRunAnnotationPositions.add(mustSearchVariationPositions.get(i));
mustRunAnnotation.add(mustSearchVariation.get(i));
} else {
// variantList is the passed by reference argument and reference to objects within variantList are
// copied within mustSearchVariation. Modifying reference objects within mustSearchVariation will
// modify user-provided Variant objects. If there's no annotation - just set it; if there's an annotation
// object already created, let's only overwrite those fields created by the annotator
VariantAnnotation variantAnnotation;
if (mustSearchVariation.get(i).getAnnotation() == null) {
variantAnnotation = variationQueryResultList.get(i).getResult().get(0).getAnnotation();
mustSearchVariation.get(i).setAnnotation(variantAnnotation);
} else {
variantAnnotation = mustSearchVariation.get(i).getAnnotation();
mergeAnnotation(variantAnnotation, variationQueryResultList.get(i).getResult().get(0).getAnnotation());
}
variantAnnotationResultList.set(mustSearchVariationPositions.get(i),
new QueryResult<>(mustSearchVariation.get(i).toString(),
variationQueryResultList.get(i).getDbTime(), variationQueryResultList.get(i).getNumResults(),
variationQueryResultList.get(i).getNumTotalResults(), null, null,
Collections.singletonList(variantAnnotation)));
}
}
List<QueryResult<VariantAnnotation>> uncachedAnnotations = runAnnotationProcess(mustRunAnnotation);
for (int i = 0; i < mustRunAnnotation.size(); i++) {
variantAnnotationResultList.set(mustRunAnnotationPositions.get(i), uncachedAnnotations.get(i));
}
logger.debug("{}/{} ({}%) variants required running the annotation process", mustRunAnnotation.size(),
variantList.size(), (mustRunAnnotation.size() * (100.0 / variantList.size())));
return variantAnnotationResultList;
}
private boolean isPhased(Variant variant) {
return (variant.getStudies() != null && !variant.getStudies().isEmpty())
&& variant.getStudies().get(0).getFormat().contains("PS");
}
private String getCachedVariationIncludeFields() {
StringBuilder stringBuilder = new StringBuilder("annotation.chromosome,annotation.start,annotation.reference");
stringBuilder.append(",annotation.alternate,annotation.id");
if (annotatorSet.contains("variation")) {
stringBuilder.append(",annotation.id,annotation.populationFrequencies");
}
if (annotatorSet.contains("clinical")) {
stringBuilder.append(",annotation.variantTraitAssociation");
}
if (annotatorSet.contains("conservation")) {
stringBuilder.append(",annotation.conservation");
}
if (annotatorSet.contains("functionalScore")) {
stringBuilder.append(",annotation.functionalScore");
}
if (annotatorSet.contains("consequenceType")) {
stringBuilder.append(",annotation.consequenceTypes,annotation.displayConsequenceType");
}
if (annotatorSet.contains("expression")) {
stringBuilder.append(",annotation.geneExpression");
}
if (annotatorSet.contains("geneDisease")) {
stringBuilder.append(",annotation.geneTraitAssociation");
}
if (annotatorSet.contains("drugInteraction")) {
stringBuilder.append(",annotation.geneDrugInteraction");
}
if (annotatorSet.contains("populationFrequencies")) {
stringBuilder.append(",annotation.populationFrequencies");
}
return stringBuilder.toString();
}
private List<QueryResult<VariantAnnotation>> runAnnotationProcess(List<Variant> normalizedVariantList)
throws InterruptedException, ExecutionException {
QueryOptions queryOptions;
long globalStartTime = System.currentTimeMillis();
long startTime;
queryOptions = new QueryOptions();
// Object to be returned
List<QueryResult<VariantAnnotation>> variantAnnotationResultList = new ArrayList<>(normalizedVariantList.size());
/*
* Next three async blocks calculate annotations using Futures, this will be calculated in a different thread.
* Once the main loop has finished then they will be stored. This provides a ~30% of performance improvement.
*/
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);
FutureVariationAnnotator futureVariationAnnotator = null;
Future<List<QueryResult<Variant>>> variationFuture = null;
if (!useCache && (annotatorSet.contains("variation") || annotatorSet.contains("populationFrequencies"))) {
futureVariationAnnotator = new FutureVariationAnnotator(normalizedVariantList, new QueryOptions("include",
"id,annotation.populationFrequencies"));
variationFuture = fixedThreadPool.submit(futureVariationAnnotator);
}
FutureConservationAnnotator futureConservationAnnotator = null;
Future<List<QueryResult>> conservationFuture = null;
if (annotatorSet.contains("conservation")) {
futureConservationAnnotator = new FutureConservationAnnotator(normalizedVariantList, queryOptions);
conservationFuture = fixedThreadPool.submit(futureConservationAnnotator);
}
FutureVariantFunctionalScoreAnnotator futureVariantFunctionalScoreAnnotator = null;
Future<List<QueryResult<Score>>> variantFunctionalScoreFuture = null;
if (annotatorSet.contains("functionalScore")) {
futureVariantFunctionalScoreAnnotator = new FutureVariantFunctionalScoreAnnotator(normalizedVariantList, queryOptions);
variantFunctionalScoreFuture = fixedThreadPool.submit(futureVariantFunctionalScoreAnnotator);
}
FutureClinicalAnnotator futureClinicalAnnotator = null;
Future<List<QueryResult>> clinicalFuture = null;
if (annotatorSet.contains("clinical")) {
futureClinicalAnnotator = new FutureClinicalAnnotator(normalizedVariantList, queryOptions);
clinicalFuture = fixedThreadPool.submit(futureClinicalAnnotator);
}
/*
* We iterate over all variants to get the rest of the annotations and to create the VariantAnnotation objects
*/
List<Gene> geneList;
Queue<Variant> variantBuffer = new LinkedList<>();
startTime = System.currentTimeMillis();
for (int i = 0; i < normalizedVariantList.size(); i++) {
// Fetch overlapping genes for this variant
geneList = getAffectedGenes(normalizedVariantList.get(i), includeGeneFields);
// normalizedVariantList is the passed by reference argument - modifying normalizedVariantList will
// modify user-provided Variant objects. If there's no annotation - just set it; if there's an annotation
// object already created, let's only overwrite those fields created by the annotator
VariantAnnotation variantAnnotation;
if (normalizedVariantList.get(i).getAnnotation() == null) {
variantAnnotation = new VariantAnnotation();
normalizedVariantList.get(i).setAnnotation(variantAnnotation);
} else {
variantAnnotation = normalizedVariantList.get(i).getAnnotation();
}
variantAnnotation.setChromosome(normalizedVariantList.get(i).getChromosome());
variantAnnotation.setStart(normalizedVariantList.get(i).getStart());
variantAnnotation.setReference(normalizedVariantList.get(i).getReference());
variantAnnotation.setAlternate(normalizedVariantList.get(i).getAlternate());
if (annotatorSet.contains("consequenceType")) {
try {
List<ConsequenceType> consequenceTypeList = getConsequenceTypeList(normalizedVariantList.get(i), geneList, true);
variantAnnotation.setConsequenceTypes(consequenceTypeList);
checkAndAdjustPhasedConsequenceTypes(normalizedVariantList.get(i), variantBuffer);
variantAnnotation
.setDisplayConsequenceType(getMostSevereConsequenceType(normalizedVariantList.get(i)
.getAnnotation().getConsequenceTypes()));
} catch (UnsupportedURLVariantFormat e) {
logger.error("Consequence type was not calculated for variant {}. Unrecognised variant format."
+ " Leaving an empty consequence type list.", normalizedVariantList.get(i).toString());
} catch (Exception e) {
logger.error("Unhandled error when calculating consequence type for variant {}. Leaving an empty"
+ " consequence type list.", normalizedVariantList.get(i).toString());
// throw e;
}
}
/*
* Gene Annotation
*/
if (annotatorSet.contains("expression")) {
variantAnnotation.setGeneExpression(new ArrayList<>());
for (Gene gene : geneList) {
if (gene.getAnnotation().getExpression() != null) {
variantAnnotation.getGeneExpression().addAll(gene.getAnnotation().getExpression());
}
}
}
if (annotatorSet.contains("geneDisease")) {
variantAnnotation.setGeneTraitAssociation(new ArrayList<>());
for (Gene gene : geneList) {
if (gene.getAnnotation().getDiseases() != null) {
variantAnnotation.getGeneTraitAssociation().addAll(gene.getAnnotation().getDiseases());
}
}
}
if (annotatorSet.contains("drugInteraction")) {
variantAnnotation.setGeneDrugInteraction(new ArrayList<>());
for (Gene gene : geneList) {
if (gene.getAnnotation().getDrugs() != null) {
variantAnnotation.getGeneDrugInteraction().addAll(gene.getAnnotation().getDrugs());
}
}
}
QueryResult queryResult = new QueryResult(normalizedVariantList.get(i).toString());
queryResult.setDbTime((int) (System.currentTimeMillis() - startTime));
queryResult.setNumResults(1);
queryResult.setNumTotalResults(1);
//noinspection unchecked
queryResult.setResult(Collections.singletonList(variantAnnotation));
variantAnnotationResultList.add(queryResult);
}
// Adjust phase of two last variants - if still anything remaining to adjust. This can happen if the two last
// variants in the batch are phased and the distance between them < 3nts
if (variantBuffer.size() > 1) {
adjustPhasedConsequenceTypes(variantBuffer.toArray());
}
logger.debug("Main loop iteration annotation performance is {}ms for {} variants", System.currentTimeMillis()
- startTime, normalizedVariantList.size());
/*
* Now, hopefully the other annotations have finished and we can store the results.
* Method 'processResults' has been implemented in the same class for sanity.
*/
if (futureVariationAnnotator != null) {
futureVariationAnnotator.processResults(variationFuture, variantAnnotationResultList, annotatorSet);
}
if (futureConservationAnnotator != null) {
futureConservationAnnotator.processResults(conservationFuture, variantAnnotationResultList);
}
if (futureVariantFunctionalScoreAnnotator != null) {
futureVariantFunctionalScoreAnnotator.processResults(variantFunctionalScoreFuture, variantAnnotationResultList);
}
if (futureClinicalAnnotator != null) {
futureClinicalAnnotator.processResults(clinicalFuture, variantAnnotationResultList);
}
fixedThreadPool.shutdown();
logger.debug("Total batch annotation performance is {}ms for {} variants", System.currentTimeMillis()
- globalStartTime, normalizedVariantList.size());
return variantAnnotationResultList;
}
private void parseQueryParam(QueryOptions queryOptions) {
// We process include and exclude query options to know which annotators to use.
// Include parameter has preference over exclude.
annotatorSet = getAnnotatorSet(queryOptions);
logger.debug("Annotators to use: {}", annotatorSet.toString());
// This field contains all the fields to be returned by overlapping genes
includeGeneFields = getIncludedGeneFields(annotatorSet);
// Default behaviour no normalization
normalize = (queryOptions.get("normalize") != null && queryOptions.get("normalize").equals("true"));
// Default behaviour use cache
useCache = (queryOptions.get("useCache") != null ? queryOptions.get("useCache").equals("true") : true);
}
private void mergeAnnotation(VariantAnnotation destination, VariantAnnotation origin) {
destination.setId(origin.getId());
destination.setChromosome(origin.getChromosome());
destination.setStart(origin.getStart());
destination.setReference(origin.getReference());
destination.setAlternate(origin.getAlternate());
destination.setDisplayConsequenceType(origin.getDisplayConsequenceType());
destination.setConsequenceTypes(origin.getConsequenceTypes());
destination.setConservation(origin.getConservation());
destination.setGeneExpression(origin.getGeneExpression());
destination.setGeneTraitAssociation(origin.getGeneTraitAssociation());
destination.setPopulationFrequencies(origin.getPopulationFrequencies());
destination.setGeneDrugInteraction(origin.getGeneDrugInteraction());
destination.setVariantTraitAssociation(origin.getVariantTraitAssociation());
destination.setFunctionalScore(origin.getFunctionalScore());
}
private void checkAndAdjustPhasedConsequenceTypes(Variant variant, Queue<Variant> variantBuffer) {
// Only SNVs are currently considered for phase adjustment
if (variant.getType().equals(VariantType.SNV)) {
// Check and manage variantBuffer for dealing with phased variants
switch (variantBuffer.size()) {
case 0:
variantBuffer.add(variant);
break;
case 1:
if (potentialCodingSNVOverlap(variantBuffer.peek(), variant)) {
variantBuffer.add(variant);
} else {
variantBuffer.poll();
variantBuffer.add(variant);
}
break;
case 2:
if (potentialCodingSNVOverlap(variantBuffer.peek(), variant)) {
variantBuffer.add(variant);
adjustPhasedConsequenceTypes(variantBuffer.toArray());
variantBuffer.poll();
} else {
// Adjust consequence types for the two previous variants
adjustPhasedConsequenceTypes(variantBuffer.toArray());
// Remove the two previous variants after adjustment
variantBuffer.poll();
variantBuffer.poll();
variantBuffer.add(variant);
}
default:
break;
}
}
}
// private void checkAndAdjustPhasedConsequenceTypes(Queue<Variant> variantBuffer) {
// Variant[] variantArray = (Variant[]) variantBuffer.toArray();
// // SSACGATATCTT -> where S represents the position of the SNV
// if (potentialCodingSNVOverlap(variantArray[0], variantArray[1])) {
// // SSSACGATATCTT -> where S represents the position of the SNV. The three SNVs may affect the same codon
// if (potentialCodingSNVOverlap(variantArray[1], variantArray[2])) {
// adjustPhasedConsequenceTypes(variantArray);
// // SSACGATATCVTT -> where S represents the position of the SNV and V represents the position of the third
// // variant. Only the two first SNVs may affect the same codon.
// } else {
// adjustPhasedConsequenceTypes(Arrays.copyOfRange(variantArray, 0,3));
// }
// }
// }
private void adjustPhasedConsequenceTypes(Object[] variantArray) {
Variant variant0 = (Variant) variantArray[0];
for (ConsequenceType consequenceType1 : variant0.getAnnotation().getConsequenceTypes()) {
ProteinVariantAnnotation newProteinVariantAnnotation = null;
// Check if this is a coding consequence type. Also this consequence type may have been already
// updated if there are 3 consecutive phased SNVs affecting the same codon.
if (isCoding(consequenceType1)
&& !transcriptAnnotationUpdated(variant0, consequenceType1.getEnsemblTranscriptId())) {
Variant variant1 = (Variant) variantArray[1];
ConsequenceType consequenceType2
= findCodingOverlappingConsequenceType(consequenceType1, variant1.getAnnotation().getConsequenceTypes());
// The two first variants affect the same codon
if (consequenceType2 != null) {
// WARNING: assumes variants are sorted according to their coordinates
int cdnaPosition = consequenceType1.getCdnaPosition();
int cdsPosition = consequenceType1.getCdsPosition();
String codon = null;
// String alternateAA = null;
List<SequenceOntologyTerm> soTerms = null;
ConsequenceType consequenceType3 = null;
Variant variant2 = null;
// Check if the third variant also affects the same codon
if (variantArray.length > 2) {
variant2 = (Variant) variantArray[2];
consequenceType3
= findCodingOverlappingConsequenceType(consequenceType2, variant2.getAnnotation().getConsequenceTypes());
}
// The three SNVs affect the same codon
if (consequenceType3 != null) {
String referenceCodon = consequenceType1.getCodon().split("/")[0].toUpperCase();
// WARNING: assumes variants are sorted according to their coordinates
String alternateCodon = variant0.getAlternate() + variant1.getAlternate()
+ variant2.getAlternate();
codon = referenceCodon + "/" + alternateCodon;
// alternateAA = VariantAnnotationUtils.CODON_TO_A.get(alternateCodon);
soTerms = updatePhasedSoTerms(consequenceType1.getSequenceOntologyTerms(),
String.valueOf(referenceCodon), String.valueOf(alternateCodon),
variant1.getChromosome().equals("MT"));
// Update consequenceType3
consequenceType3.setCdnaPosition(cdnaPosition);
consequenceType3.setCdsPosition(cdsPosition);
consequenceType3.setCodon(codon);
// consequenceType3.getProteinVariantAnnotation().setAlternate(alternateAA);
newProteinVariantAnnotation = getProteinAnnotation(consequenceType3);
consequenceType3.setProteinVariantAnnotation(newProteinVariantAnnotation);
consequenceType3.setSequenceOntologyTerms(soTerms);
// Flag these transcripts as already updated for this variant
flagTranscriptAnnotationUpdated(variant2, consequenceType1.getEnsemblTranscriptId());
// Only the two first SNVs affect the same codon
} else {
int codonIdx1 = getUpperCaseLetterPosition(consequenceType1.getCodon().split("/")[0]);
int codonIdx2 = getUpperCaseLetterPosition(consequenceType2.getCodon().split("/")[0]);
// Set referenceCodon and alternateCodon leaving only the nts that change in uppercase.
// Careful with upper/lower case letters
char[] referenceCodonArray = consequenceType1.getCodon().split("/")[0].toLowerCase().toCharArray();
referenceCodonArray[codonIdx1] = Character.toUpperCase(referenceCodonArray[codonIdx1]);
referenceCodonArray[codonIdx2] = Character.toUpperCase(referenceCodonArray[codonIdx2]);
char[] alternateCodonArray = referenceCodonArray.clone();
alternateCodonArray[codonIdx1] = variant0.getAlternate().toUpperCase().toCharArray()[0];
alternateCodonArray[codonIdx2] = variant1.getAlternate().toUpperCase().toCharArray()[0];
codon = String.valueOf(referenceCodonArray) + "/" + String.valueOf(alternateCodonArray);
// alternateAA = VariantAnnotationUtils.CODON_TO_A.get(String.valueOf(alternateCodonArray).toUpperCase());
soTerms = updatePhasedSoTerms(consequenceType1.getSequenceOntologyTerms(),
String.valueOf(referenceCodonArray).toUpperCase(),
String.valueOf(alternateCodonArray).toUpperCase(), variant1.getChromosome().equals("MT"));
}
// Update consequenceType1 & 2
consequenceType1.setCodon(codon);
// consequenceType1.getProteinVariantAnnotation().setAlternate(alternateAA);
consequenceType1.setProteinVariantAnnotation(newProteinVariantAnnotation == null
? getProteinAnnotation(consequenceType1) : newProteinVariantAnnotation);
consequenceType1.setSequenceOntologyTerms(soTerms);
consequenceType2.setCdnaPosition(cdnaPosition);
consequenceType2.setCdsPosition(cdsPosition);
consequenceType2.setCodon(codon);
// consequenceType2.getProteinVariantAnnotation().setAlternate(alternateAA);
consequenceType2.setProteinVariantAnnotation(consequenceType1.getProteinVariantAnnotation());
consequenceType2.setSequenceOntologyTerms(soTerms);
// Flag these transcripts as already updated for this variant
flagTranscriptAnnotationUpdated(variant0, consequenceType1.getEnsemblTranscriptId());
flagTranscriptAnnotationUpdated(variant1, consequenceType1.getEnsemblTranscriptId());
}
}
}
}
private void flagTranscriptAnnotationUpdated(Variant variant, String ensemblTranscriptId) {
Map<String, Object> additionalAttributesMap = variant.getAnnotation().getAdditionalAttributes();
if (additionalAttributesMap == null) {
additionalAttributesMap = new HashMap<>();
Map<String, String> transcriptsSet = new HashMap<>();
transcriptsSet.put(ensemblTranscriptId, null);
additionalAttributesMap.put("phasedTranscripts", transcriptsSet);
variant.getAnnotation().setAdditionalAttributes(additionalAttributesMap);
} else if (additionalAttributesMap.get("phasedTranscripts") == null) {
Map<String, String> transcriptsSet = new HashMap<>();
transcriptsSet.put(ensemblTranscriptId, null);
additionalAttributesMap.put("phasedTranscripts", transcriptsSet);
} else {
((Map) additionalAttributesMap.get("phasedTranscripts")).put(ensemblTranscriptId, null);
}
}
private boolean transcriptAnnotationUpdated(Variant variant, String ensemblTranscriptId) {
if (variant.getAnnotation().getAdditionalAttributes() != null
&& variant.getAnnotation().getAdditionalAttributes().get("phasedTranscripts") != null
&& ((Map<String, String>) variant.getAnnotation().getAdditionalAttributes().get("phasedTranscripts"))
.containsKey(ensemblTranscriptId)) {
return true;
}
return false;
}
private int getUpperCaseLetterPosition(String string) {
// Pattern pat = Pattern.compile("G");
Pattern pat = Pattern.compile("[A,C,G,T]");
Matcher match = pat.matcher(string);
if (match.find()) {
return match.start();
} else {
return -1;
}
}
private ConsequenceType findCodingOverlappingConsequenceType(ConsequenceType consequenceType,
List<ConsequenceType> consequenceTypeList) {
for (ConsequenceType consequenceType1 : consequenceTypeList) {
if (isCoding(consequenceType1)
&& consequenceType.getEnsemblTranscriptId().equals(consequenceType1.getEnsemblTranscriptId())
&& consequenceType.getProteinVariantAnnotation().getPosition()
.equals(consequenceType1.getProteinVariantAnnotation().getPosition())) {
return consequenceType1;
}
}
return null;
}
private boolean isCoding(ConsequenceType consequenceType) {
for (SequenceOntologyTerm sequenceOntologyTerm : consequenceType.getSequenceOntologyTerms()) {
if (VariantAnnotationUtils.CODING_SO_NAMES.contains(sequenceOntologyTerm.getName())) {
return true;
}
}
return false;
}
private List<SequenceOntologyTerm> updatePhasedSoTerms(List<SequenceOntologyTerm> sequenceOntologyTermList,
String referenceCodon, String alternateCodon,
Boolean useMitochondrialCode) {
// Removes all coding-associated SO terms
int i = 0;
do {
if (VariantAnnotationUtils.CODING_SO_NAMES.contains(sequenceOntologyTermList.get(i).getName())) {
sequenceOntologyTermList.remove(i);
} else {
i++;
}
} while(i < sequenceOntologyTermList.size());
// Add the new coding SO term as appropriate
String newSoName = null;
if (VariantAnnotationUtils.isSynonymousCodon(useMitochondrialCode, referenceCodon, alternateCodon)) {
if (VariantAnnotationUtils.isStopCodon(useMitochondrialCode, referenceCodon)) {
newSoName = VariantAnnotationUtils.STOP_RETAINED_VARIANT;
} else { // coding end may be not correctly annotated (incomplete_terminal_codon_variant),
// but if the length of the cds%3=0, annotation should be synonymous variant
newSoName = VariantAnnotationUtils.SYNONYMOUS_VARIANT;
}
} else if (VariantAnnotationUtils.isStopCodon(useMitochondrialCode, referenceCodon)) {
newSoName = VariantAnnotationUtils.STOP_LOST;
} else if (VariantAnnotationUtils.isStopCodon(useMitochondrialCode, alternateCodon)) {
newSoName = VariantAnnotationUtils.STOP_GAINED;
} else {
newSoName = VariantAnnotationUtils.MISSENSE_VARIANT;
}
sequenceOntologyTermList
.add(new SequenceOntologyTerm(ConsequenceTypeMappings.getSoAccessionString(newSoName), newSoName));
return sequenceOntologyTermList;
}
private boolean potentialCodingSNVOverlap(Variant variant1, Variant variant2) {
return Math.abs(variant1.getStart() - variant2.getStart()) < 3
&& variant1.getChromosome().equals(variant2.getChromosome())
&& variant1.getType().equals(VariantType.SNV) && variant2.getType().equals(VariantType.SNV)
&& samePhase(variant1, variant2);
}
private boolean samePhase(Variant variant1, Variant variant2) {
if (variant1.getStudies() != null && !variant1.getStudies().isEmpty()) {
if (variant2.getStudies() != null && !variant2.getStudies().isEmpty()) {
int psIdx1 = variant1.getStudies().get(0).getFormat().indexOf("PS");
if (psIdx1 != -1) {
int psIdx2 = variant2.getStudies().get(0).getFormat().indexOf("PS");
if (psIdx2 != -1 && // variant2 does have PS set
// same phase set value in both variants
variant2.getStudies().get(0).getSamplesData().get(0).get(psIdx2)
.equals(variant1.getStudies().get(0).getSamplesData().get(0).get(psIdx1))
// Same genotype call in both variants (e.g. 1|0=1|0).
// WARNING: assuming variant1 and variant2 do have Files.
&& variant1.getStudies().get(0).getFiles().get(0).getCall()
.equals(variant2.getStudies().get(0).getFiles().get(0).getCall())) {
return true;
}
}
}
}
return false;
}
private String getMostSevereConsequenceType(List<ConsequenceType> consequenceTypeList) {
int max = -1;
String mostSevereConsequencetype = null;
for (ConsequenceType consequenceType : consequenceTypeList) {
for (SequenceOntologyTerm sequenceOntologyTerm : consequenceType.getSequenceOntologyTerms()) {
int rank = VariantAnnotationUtils.SO_SEVERITY.get(sequenceOntologyTerm.getName());
if (rank > max) {
max = rank;
mostSevereConsequencetype = sequenceOntologyTerm.getName();
}
}
}
return mostSevereConsequencetype;
}
private Set<String> getAnnotatorSet(QueryOptions queryOptions) {
Set<String> annotatorSet;
List<String> includeList = queryOptions.getAsStringList("include");
if (includeList.size() > 0) {
annotatorSet = new HashSet<>(includeList);
} else {
annotatorSet = new HashSet<>(Arrays.asList("variation", "clinical", "conservation", "functionalScore",
"consequenceType", "expression", "geneDisease", "drugInteraction", "populationFrequencies"));
List<String> excludeList = queryOptions.getAsStringList("exclude");
excludeList.forEach(annotatorSet::remove);
}
return annotatorSet;
}
private String getIncludedGeneFields(Set<String> annotatorSet) {
String includeGeneFields = "name,id,start,end,transcripts.id,transcripts.start,transcripts.end,transcripts.strand,"
+ "transcripts.cdsLength,transcripts.annotationFlags,transcripts.biotype,transcripts.genomicCodingStart,"
+ "transcripts.genomicCodingEnd,transcripts.cdnaCodingStart,transcripts.cdnaCodingEnd,transcripts.exons.start,"
+ "transcripts.exons.end,transcripts.exons.sequence,transcripts.exons.phase,mirna.matures,mirna.sequence,"
+ "mirna.matures.cdnaStart,mirna.matures.cdnaEnd";
if (annotatorSet.contains("expression")) {
includeGeneFields += ",annotation.expression";
}
if (annotatorSet.contains("geneDisease")) {
includeGeneFields += ",annotation.diseases";
}
if (annotatorSet.contains("drugInteraction")) {
includeGeneFields += ",annotation.drugs";
}
return includeGeneFields;
}
private List<Gene> getAffectedGenes(Variant variant, String includeFields) {
// reference = "" if insertion, reference = null if CNV for example
int variantStart = variant.getReference() != null && variant.getReference().isEmpty()
? variant.getStart() - 1 : variant.getStart();
QueryOptions queryOptions = new QueryOptions("include", includeFields);
// QueryResult queryResult = geneDBAdaptor.getAllByRegion(new Region(variant.getChromosome(),
// variantStart - 5000, variant.getStart() + variant.getReference().length() - 1 + 5000), queryOptions);
return geneDBAdaptor
.getByRegion(new Region(variant.getChromosome(), Math.max(1, variantStart - 5000),
variant.getEnd() + 5000), queryOptions).getResult();
// variant.getStart() + variant.getReference().length() - 1 + 5000), queryOptions).getResult();
// return geneDBAdaptor.get(new Query("region", variant.getChromosome()+":"+(variantStart - 5000)+":"
// +(variant.getStart() + variant.getReference().length() - 1 + 5000)), queryOptions)
// .getResult();
// QueryResult queryResult = geneDBAdaptor.getAllByRegion(new Region(variant.getChromosome(),
// variantStart - 5000, variant.getStart() + variant.getReference().length() - 1 + 5000), queryOptions);
//
// List<Gene> geneList = new ArrayList<>(queryResult.getNumResults());
// for (Object object : queryResult.getResult()) {
// Gene gene = geneObjectMapper.convertValue(object, Gene.class);
// geneList.add(gene);
// }
// return geneList;
}
private boolean nonSynonymous(ConsequenceType consequenceType, boolean useMitochondrialCode) {
if (consequenceType.getCodon() == null) {
return false;
} else {
String[] parts = consequenceType.getCodon().split("/");
String ref = String.valueOf(parts[0]).toUpperCase();
String alt = String.valueOf(parts[1]).toUpperCase();
return !VariantAnnotationUtils.isSynonymousCodon(useMitochondrialCode, ref, alt)
&& !VariantAnnotationUtils.isStopCodon(useMitochondrialCode, ref);
}
}
private ProteinVariantAnnotation getProteinAnnotation(ConsequenceType consequenceType) {
if (consequenceType.getProteinVariantAnnotation() != null) {
QueryResult<ProteinVariantAnnotation> proteinVariantAnnotation = proteinDBAdaptor.getVariantAnnotation(
consequenceType.getEnsemblTranscriptId(),
consequenceType.getProteinVariantAnnotation().getPosition(),
consequenceType.getProteinVariantAnnotation().getReference(),
consequenceType.getProteinVariantAnnotation().getAlternate(), new QueryOptions());
if (proteinVariantAnnotation.getNumResults() > 0) {
return proteinVariantAnnotation.getResult().get(0);
}
}
return null;
}
private ConsequenceTypeCalculator getConsequenceTypeCalculator(Variant variant) throws UnsupportedURLVariantFormat {
switch (getVariantType(variant)) {
case INSERTION:
return new ConsequenceTypeInsertionCalculator(genomeDBAdaptor);
case DELETION:
return new ConsequenceTypeDeletionCalculator(genomeDBAdaptor);
case SNV:
return new ConsequenceTypeSNVCalculator();
case CNV:
return new ConsequenceTypeCNVCalculator();
default:
throw new UnsupportedURLVariantFormat();
}
}
private VariantType getVariantType(Variant variant) throws UnsupportedURLVariantFormat {
if (variant.getType() == null) {
variant.setType(Variant.inferType(variant.getReference(), variant.getAlternate(), variant.getLength()));
}
// FIXME: remove the if block below as soon as the Variant.inferType method is able to differentiate between
// FIXME: insertions and deletions
if (variant.getType().equals(VariantType.INDEL)) {
if (variant.getReference().isEmpty()) {
variant.setType(VariantType.INSERTION);
} else {
variant.setType(VariantType.DELETION);
}
}
return variant.getType();
// return getVariantType(variant.getReference(), variant.getAlternate());
}
// private VariantType getVariantType(String reference, String alternate) {
// if (reference.isEmpty()) {
// return VariantType.INSERTION;
// } else if (alternate.isEmpty()) {
// return VariantType.DELETION;
// } else if (reference.length() == 1 && alternate.length() == 1) {
// return VariantType.SNV;
// } else {
// throw new UnsupportedURLVariantFormat();
// }
// }
private List<RegulatoryFeature> getAffectedRegulatoryRegions(Variant variant) {
int variantStart = variant.getReference() != null && variant.getReference().isEmpty()
? variant.getStart() - 1 : variant.getStart();
QueryOptions queryOptions = new QueryOptions();
queryOptions.add("include", "chromosome,start,end");
// QueryResult queryResult = regulationDBAdaptor.nativeGet(new Query("region", variant.getChromosome()
// + ":" + variantStart + ":" + (variant.getStart() + variant.getReference().length() - 1)), queryOptions);
QueryResult<RegulatoryFeature> queryResult = regulationDBAdaptor.getByRegion(new Region(variant.getChromosome(),
variantStart, variant.getEnd()), queryOptions);
// variantStart, variant.getStart() + variant.getReference().length() - 1), queryOptions);
List<RegulatoryFeature> regionList = new ArrayList<>(queryResult.getNumResults());
for (RegulatoryFeature object : queryResult.getResult()) {
regionList.add(object);
}
// for (Object object : queryResult.getResult()) {
// Document dbObject = (Document) object;
// RegulatoryRegion regulatoryRegion = new RegulatoryRegion();
// regulatoryRegion.setChromosome((String) dbObject.get("chromosome"));
// regulatoryRegion.setStart((int) dbObject.get("start"));
// regulatoryRegion.setEnd((int) dbObject.get("end"));
// regulatoryRegion.setType((String) dbObject.get("featureType"));
// regionList.add(regulatoryRegion);
// }
return regionList;
}
private List<ConsequenceType> getConsequenceTypeList(Variant variant, List<Gene> geneList, boolean regulatoryAnnotation) {
List<RegulatoryFeature> regulatoryRegionList = null;
if (regulatoryAnnotation) {
regulatoryRegionList = getAffectedRegulatoryRegions(variant);
}
ConsequenceTypeCalculator consequenceTypeCalculator = getConsequenceTypeCalculator(variant);
List<ConsequenceType> consequenceTypeList = consequenceTypeCalculator.run(variant, geneList, regulatoryRegionList);
if (variant.getType() == VariantType.SNV
|| Variant.inferType(variant.getReference(), variant.getAlternate(), variant.getLength()) == VariantType.SNV) {
for (ConsequenceType consequenceType : consequenceTypeList) {
if (nonSynonymous(consequenceType, variant.getChromosome().equals("MT"))) {
consequenceType.setProteinVariantAnnotation(getProteinAnnotation(consequenceType));
}
}
}
return consequenceTypeList;
}
private List<Region> variantListToRegionList(List<Variant> variantList) {
List<Region> regionList = new ArrayList<>(variantList.size());
for (Variant variant : variantList) {
regionList.add(new Region(variant.getChromosome(), variant.getStart(), variant.getStart()));
}
return regionList;
}
/*
* Future classes for Async annotations
*/
class FutureVariationAnnotator implements Callable<List<QueryResult<Variant>>> {
private List<Variant> variantList;
private QueryOptions queryOptions;
public FutureVariationAnnotator(List<Variant> variantList, QueryOptions queryOptions) {
this.variantList = variantList;
this.queryOptions = queryOptions;
}
@Override
public List<QueryResult<Variant>> call() throws Exception {
long startTime = System.currentTimeMillis();
List<QueryResult<Variant>> variationQueryResultList = variantDBAdaptor.getByVariant(variantList, queryOptions);
logger.debug("Variation query performance is {}ms for {} variants", System.currentTimeMillis() - startTime, variantList.size());
return variationQueryResultList;
}
public void processResults(Future<List<QueryResult<Variant>>> conservationFuture,
List<QueryResult<VariantAnnotation>> variantAnnotationResultList,
Set<String> annotatorSet) throws InterruptedException, ExecutionException {
// try {
while (!conservationFuture.isDone()) {
Thread.sleep(1);
}
List<QueryResult<Variant>> variationQueryResults = conservationFuture.get();
if (variationQueryResults != null) {
for (int i = 0; i < variantAnnotationResultList.size(); i++) {
if (variationQueryResults.get(i).first() != null && variationQueryResults.get(i).first().getIds().size() > 0) {
variantAnnotationResultList.get(i).first().setId(variationQueryResults.get(i).first().getIds().get(0));
}
if (annotatorSet.contains("populationFrequencies") && variationQueryResults.get(i).first() != null) {
variantAnnotationResultList.get(i).first().setPopulationFrequencies(variationQueryResults.get(i)
.first().getAnnotation().getPopulationFrequencies());
}
// List<Document> variationDBList = (List<Document>) variationQueryResults.get(i).getResult();
// if (variationDBList != null && variationDBList.size() > 0) {
// BasicDBList idsDBList = (BasicDBList) variationDBList.get(0).get("ids");
// if (idsDBList != null) {
// variantAnnotationResultList.get(i).getResult().get(0).setId((String) idsDBList.get(0));
// }
// if (annotatorSet.contains("populationFrequencies")) {
// Document annotationDBObject = (Document) variationDBList.get(0).get("annotation");
// if (annotationDBObject != null) {
// BasicDBList freqsDBList = (BasicDBList) annotationDBObject.get("populationFrequencies");
// if (freqsDBList != null) {
// Document freqDBObject;
// variantAnnotationResultList.get(i).getResult().get(0).setPopulationFrequencies(new ArrayList<>());
// for (int j = 0; j < freqsDBList.size(); j++) {
// freqDBObject = ((Document) freqsDBList.get(j));
// if (freqDBObject != null && freqDBObject.get("refAllele") != null) {
// if (freqDBObject.containsKey("study")) {
// variantAnnotationResultList.get(i).getResult().get(0)
// .getPopulationFrequencies()
// .add(new PopulationFrequency(freqDBObject.get("study").toString(),
// freqDBObject.get("population").toString(),
// freqDBObject.get("refAllele").toString(),
// freqDBObject.get("altAllele").toString(),
// Float.valueOf(freqDBObject.get("refAlleleFreq").toString()),
// Float.valueOf(freqDBObject.get("altAlleleFreq").toString()),
// 0.0f, 0.0f, 0.0f));
// } else {
// variantAnnotationResultList.get(i).getResult().get(0)
// .getPopulationFrequencies().add(new PopulationFrequency("1000G_PHASE_3",
// freqDBObject.get("population").toString(),
// freqDBObject.get("refAllele").toString(),
// freqDBObject.get("altAllele").toString(),
// Float.valueOf(freqDBObject.get("refAlleleFreq").toString()),
// Float.valueOf(freqDBObject.get("altAlleleFreq").toString()),
// 0.0f, 0.0f, 0.0f));
// }
// }
// }
// }
// }
// }
// }
}
}
// } catch (ExecutionException e) {
// } catch (InterruptedException | ExecutionException e) {
// e.printStackTrace();
// }
}
}
class FutureConservationAnnotator implements Callable<List<QueryResult>> {
private List<Variant> variantList;
private QueryOptions queryOptions;
public FutureConservationAnnotator(List<Variant> variantList, QueryOptions queryOptions) {
this.variantList = variantList;
this.queryOptions = queryOptions;
}
@Override
public List<QueryResult> call() throws Exception {
long startTime = System.currentTimeMillis();
List<QueryResult> conservationQueryResultList = conservationDBAdaptor
.getAllScoresByRegionList(variantListToRegionList(variantList), queryOptions);
logger.debug("Conservation query performance is {}ms for {} variants", System.currentTimeMillis() - startTime,
variantList.size());
return conservationQueryResultList;
}
public void processResults(Future<List<QueryResult>> conservationFuture,
List<QueryResult<VariantAnnotation>> variantAnnotationResultList)
throws InterruptedException, ExecutionException {
// try {
while (!conservationFuture.isDone()) {
Thread.sleep(1);
}
List<QueryResult> conservationQueryResults = conservationFuture.get();
if (conservationQueryResults != null) {
for (int i = 0; i < variantAnnotationResultList.size(); i++) {
variantAnnotationResultList.get(i).getResult().get(0)
.setConservation((List<Score>) conservationQueryResults.get(i).getResult());
}
}
// } catch (ExecutionException e) {
// } catch (InterruptedException | ExecutionException e) {
// e.printStackTrace();
// }
}
}
class FutureVariantFunctionalScoreAnnotator implements Callable<List<QueryResult<Score>>> {
private List<Variant> variantList;
private QueryOptions queryOptions;
public FutureVariantFunctionalScoreAnnotator(List<Variant> variantList, QueryOptions queryOptions) {
this.variantList = variantList;
this.queryOptions = queryOptions;
}
@Override
public List<QueryResult<Score>> call() throws Exception {
long startTime = System.currentTimeMillis();
// List<QueryResult> variantFunctionalScoreQueryResultList =
// variantFunctionalScoreDBAdaptor.getAllByVariantList(variantList, queryOptions);
List<QueryResult<Score>> variantFunctionalScoreQueryResultList =
variantDBAdaptor.getFunctionalScoreVariant(variantList, queryOptions);
logger.debug("VariantFunctionalScore query performance is {}ms for {} variants",
System.currentTimeMillis() - startTime, variantList.size());
return variantFunctionalScoreQueryResultList;
}
public void processResults(Future<List<QueryResult<Score>>> variantFunctionalScoreFuture,
List<QueryResult<VariantAnnotation>> variantAnnotationResultList)
throws InterruptedException, ExecutionException {
// try {
while (!variantFunctionalScoreFuture.isDone()) {
Thread.sleep(1);
}
List<QueryResult<Score>> variantFunctionalScoreQueryResults = variantFunctionalScoreFuture.get();
if (variantFunctionalScoreQueryResults != null) {
for (int i = 0; i < variantAnnotationResultList.size(); i++) {
if (variantFunctionalScoreQueryResults.get(i).getNumResults() > 0) {
variantAnnotationResultList.get(i).getResult().get(0)
.setFunctionalScore((List<Score>) variantFunctionalScoreQueryResults.get(i).getResult());
}
}
}
// } catch (ExecutionException e) {
// } catch (InterruptedException | ExecutionException e) {
// e.printStackTrace();
}
// }
}
class FutureClinicalAnnotator implements Callable<List<QueryResult>> {
private List<Variant> variantList;
private QueryOptions queryOptions;
public FutureClinicalAnnotator(List<Variant> variantList, QueryOptions queryOptions) {
this.variantList = variantList;
this.queryOptions = queryOptions;
}
@Override
public List<QueryResult> call() throws Exception {
long startTime = System.currentTimeMillis();
List<QueryResult> clinicalQueryResultList = clinicalDBAdaptor.getAllByGenomicVariantList(variantList, queryOptions);
logger.debug("Clinical query performance is {}ms for {} variants", System.currentTimeMillis() - startTime, variantList.size());
return clinicalQueryResultList;
}
public void processResults(Future<List<QueryResult>> clinicalFuture,
List<QueryResult<VariantAnnotation>> variantAnnotationResults)
throws InterruptedException, ExecutionException {
// try {
while (!clinicalFuture.isDone()) {
Thread.sleep(1);
}
List<QueryResult> clinicalQueryResults = clinicalFuture.get();
if (clinicalQueryResults != null) {
for (int i = 0; i < variantAnnotationResults.size(); i++) {
QueryResult clinicalQueryResult = clinicalQueryResults.get(i);
if (clinicalQueryResult.getResult() != null && clinicalQueryResult.getResult().size() > 0) {
variantAnnotationResults.get(i).getResult().get(0)
.setVariantTraitAssociation((VariantTraitAssociation) clinicalQueryResult.getResult().get(0));
}
}
}
// } catch (ExecutionException e) {
//// } catch (InterruptedException | ExecutionException e) {
// e.printStackTrace();
// }
}
}
}
| feature/vacache: bug fixed at VariantAnnotationCalculator
| cellbase-core/src/main/java/org/opencb/cellbase/core/variant/annotation/VariantAnnotationCalculator.java | feature/vacache: bug fixed at VariantAnnotationCalculator | <ide><path>ellbase-core/src/main/java/org/opencb/cellbase/core/variant/annotation/VariantAnnotationCalculator.java
<ide> } else if (variationQueryResultList.get(i).getResult().get(0).getAnnotation() != null
<ide> && variationQueryResultList.get(i).getResult().get(0).getAnnotation().getChromosome() == null) {
<ide> mustSearchVariation.get(i).setId(variationQueryResultList.get(i).getResult().get(0).getId());
<add> if (mustSearchVariation.get(i).getAnnotation() == null) {
<add> mustSearchVariation.get(i).setAnnotation(new VariantAnnotation());
<add> }
<ide> mustSearchVariation.get(i).getAnnotation()
<ide> .setPopulationFrequencies(variationQueryResultList.get(i).getResult().get(0).getAnnotation()
<ide> .getPopulationFrequencies()); |
|
Java | mit | 16209c65450239100031889a45c63cc91bec7cd5 | 0 | Doist/JobSchedulerCompat | package com.doist.jobschedulercompat.scheduler.alarm;
import com.doist.jobschedulercompat.JobParameters;
import com.doist.jobschedulercompat.JobScheduler;
import com.doist.jobschedulercompat.JobService;
import com.doist.jobschedulercompat.job.JobStatus;
import com.doist.jobschedulercompat.util.DeviceUtils;
import com.doist.jobschedulercompat.util.WakeLockUtils;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.annotation.RestrictTo;
import android.util.Log;
import android.util.SparseArray;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Job service for {@link AlarmScheduler}, the {@link AlarmManager}-based scheduler.
*
* This service runs whenever new jobs are scheduled or deleted, whenever constraints (eg. connectivity, charging)
* might have changed, and whenever a previous job finished, as these can schedule new jobs.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public class AlarmJobService extends Service implements JobService.Binder.Callback {
private static final String LOG_TAG = "AlarmJobService";
private static final String KEY_WAKE_LOCK_PROCESS = "process";
private static final String KEY_WAKE_LOCK_JOB = "job";
private static final long TIMEOUT_WAKE_LOCK_PROCESS = TimeUnit.MINUTES.toMillis(1);
private static final long TIMEOUT_WAKE_LOCK_JOB = TimeUnit.MINUTES.toMillis(3); // Same as JobScheduler's.
static void start(Context context) {
WakeLockUtils.acquireWakeLock(context, KEY_WAKE_LOCK_PROCESS, TIMEOUT_WAKE_LOCK_PROCESS);
context.startService(new Intent(context, AlarmJobService.class));
}
private JobScheduler jobScheduler;
private final SparseArray<Connection> connections = new SparseArray<>();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
jobScheduler = JobScheduler.get(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
// Stop jobs that have been cancelled.
for (int i = connections.size() - 1; i >= 0; i--) {
Connection connection = connections.valueAt(i);
if (jobScheduler.getJob(connection.params.getJobId()) == null) {
stopJob(connection, false);
}
}
// Start jobs that are ready, schedule jobs that are not.
List<JobStatus> jobStatuses = jobScheduler.getJobsByScheduler(AlarmScheduler.TAG);
updateConstraints(jobStatuses);
for (JobStatus jobStatus : jobStatuses) {
Connection connection = connections.get(jobStatus.getJobId());
if (jobStatus.isReady()) {
if (connection == null) {
// Job is ready and not already running, bind to the service and start the job.
startJob(jobStatus, startId);
}
} else if (connection != null) {
// Job is running but not ready, unbind from the service and stop the job.
boolean needsReschedule = connection.binder != null && connection.binder.stopJob(connection.params);
stopJob(connection, needsReschedule);
}
}
// Enable alarm receiver if there any alarm-based jobs left.
setComponentEnabled(this, AlarmReceiver.class, !jobStatuses.isEmpty());
} finally {
if (connections.size() == 0) {
stopSelf(startId);
}
// Each job holds its own wake lock while processing, release ours now.
WakeLockUtils.releaseWakeLock(KEY_WAKE_LOCK_PROCESS);
}
return START_NOT_STICKY;
}
/**
* Updates the state of each constraint in each {@link JobStatus}.
*
* When constraints are not met, receivers and/or alarms are scheduled for when it's appropriate to run again.
*/
private void updateConstraints(List<JobStatus> jobStatuses) {
// Update charging constraint.
boolean unsatisfiedChargingConstraint = false;
boolean charging = DeviceUtils.isCharging(this);
for (JobStatus jobStatus : jobStatuses) {
jobStatus.setConstraintSatisfied(JobStatus.CONSTRAINT_CHARGING, charging);
unsatisfiedChargingConstraint |= jobStatus.hasChargingConstraint() && !charging;
}
// Enable charging receiver if there are unmet constraints, or disable it if there aren't.
setComponentEnabled(this, AlarmReceiver.BatteryReceiver.class, unsatisfiedChargingConstraint);
// Update idle constraint.
boolean unsatisfiedIdleConstraint = false;
boolean idle = DeviceUtils.isIdle(this);
for (JobStatus jobStatus : jobStatuses) {
jobStatus.setConstraintSatisfied(JobStatus.CONSTRAINT_IDLE, idle);
unsatisfiedIdleConstraint |= jobStatus.hasIdleConstraint() && !idle;
}
// ACTION_SCREEN_OFF cannot be received through a receiver declared in AndroidManifest.
// AlarmReceiver will be scheduled to run by AlarmManager at most 30 minutes from now.
// Get connectivity constraints.
boolean unsatisfiedConnectivityConstraint = false;
boolean connected = DeviceUtils.isConnected(this);
boolean unmetered = connected && DeviceUtils.isUnmetered(this);
boolean notRoaming = connected && DeviceUtils.isNotRoaming(this);
for (JobStatus jobStatus : jobStatuses) {
jobStatus.setConstraintSatisfied(JobStatus.CONSTRAINT_CONNECTIVITY, connected);
unsatisfiedConnectivityConstraint |= jobStatus.hasConnectivityConstraint() && !connected;
jobStatus.setConstraintSatisfied(JobStatus.CONSTRAINT_UNMETERED, unmetered);
unsatisfiedConnectivityConstraint |= jobStatus.hasUnmeteredConstraint() && !unmetered;
jobStatus.setConstraintSatisfied(JobStatus.CONSTRAINT_NOT_ROAMING, notRoaming);
unsatisfiedConnectivityConstraint |= jobStatus.hasNotRoamingConstraint() && !notRoaming;
}
// Enable connectivity receiver if there are unmet constraints, or disable it if there aren't.
setComponentEnabled(this, AlarmReceiver.ConnectivityReceiver.class, unsatisfiedConnectivityConstraint);
// Get timing constraints.
long nextExpiryTime = Long.MAX_VALUE;
long nextDelayTime = Long.MAX_VALUE;
long nowElapsed = SystemClock.elapsedRealtime();
for (JobStatus jobStatus : jobStatuses) {
if (jobStatus.hasDeadlineConstraint()) {
long jobDeadline = jobStatus.getLatestRunTimeElapsed();
if (jobDeadline <= nowElapsed) {
jobStatus.setConstraintSatisfied(JobStatus.CONSTRAINT_DEADLINE, true);
continue; // Skip timing delay, job will run now.
} else if (nextExpiryTime > jobDeadline) {
nextExpiryTime = jobDeadline;
}
}
if (jobStatus.hasTimingDelayConstraint()) {
long jobDelayTime = jobStatus.getEarliestRunTimeElapsed();
if (jobDelayTime <= nowElapsed) {
jobStatus.setConstraintSatisfied(JobStatus.CONSTRAINT_TIMING_DELAY, true);
} else if (nextDelayTime > jobDelayTime) {
nextDelayTime = jobDelayTime;
}
}
}
// Schedule alarm to run at the earliest deadline, if any.
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, AlarmReceiver.class), 0);
long triggerAtMillis = Math.min(nextExpiryTime, nextDelayTime);
if (unsatisfiedIdleConstraint) {
triggerAtMillis = Math.min(triggerAtMillis, TimeUnit.MINUTES.toMillis(30));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
} else {
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
}
} else if (triggerAtMillis != Long.MAX_VALUE) {
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
}
}
@Override
public void jobFinished(JobParameters params, boolean needsReschedule) {
Connection connection = connections.get(params.getJobId());
if (connection != null) {
stopJob(connection, needsReschedule);
}
}
/**
* Starts the user's {@link JobService} by binding to it.
*/
private void startJob(JobStatus jobStatus, int startId) {
WakeLockUtils.acquireWakeLock(this, KEY_WAKE_LOCK_JOB, TIMEOUT_WAKE_LOCK_JOB);
int jobId = jobStatus.getJobId();
JobParameters params = new JobParameters(jobId, jobStatus.getExtras(), jobStatus.isDeadlineSatisfied());
Connection connection = new Connection(jobId, startId, params);
Intent jobIntent = new Intent();
jobIntent.setComponent(jobStatus.getService());
if (bindService(jobIntent, connection, BIND_AUTO_CREATE)) {
connections.put(jobId, connection);
}
}
/**
* Stops the user's {@link JobService} by unbinding from it.
*/
private void stopJob(Connection connection, boolean needsReschedule) {
connections.remove(connection.jobId);
try {
unbindService(connection);
} catch (IllegalArgumentException e) {
// Service not connected at this point. Drop it.
}
jobScheduler.onJobCompleted(connection.jobId, needsReschedule);
stopSelf(connection.startId);
WakeLockUtils.releaseWakeLock(KEY_WAKE_LOCK_JOB);
}
private static void setComponentEnabled(Context context, Class cls, boolean enabled) {
PackageManager pm = context.getPackageManager();
if (pm != null) {
pm.setComponentEnabledSetting(
new ComponentName(context, cls),
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
: PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
/**
* {@link ServiceConnection} to the user's {@link JobService} that starts jobs when connected.
*/
private class Connection implements ServiceConnection {
private final int jobId;
private final int startId;
private final JobParameters params;
private JobService.Binder binder;
private Connection(int jobId, int startId, JobParameters params) {
this.jobId = jobId;
this.startId = startId;
this.params = params;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (!(service instanceof JobService.Binder)) {
Log.w(LOG_TAG, "Unknown service connected: " + service);
stopJob(this, false);
return;
}
binder = (JobService.Binder) service;
if (!binder.startJob(params, AlarmJobService.this)) {
stopJob(this, false);
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
// Should never happen as it's the same process.
binder = null;
if (connections.get(jobId) == this) {
stopJob(this, false);
}
}
}
}
| library/src/main/java/com/doist/jobschedulercompat/scheduler/alarm/AlarmJobService.java | package com.doist.jobschedulercompat.scheduler.alarm;
import com.doist.jobschedulercompat.JobParameters;
import com.doist.jobschedulercompat.JobScheduler;
import com.doist.jobschedulercompat.JobService;
import com.doist.jobschedulercompat.job.JobStatus;
import com.doist.jobschedulercompat.util.DeviceUtils;
import com.doist.jobschedulercompat.util.WakeLockUtils;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.annotation.RestrictTo;
import android.util.Log;
import android.util.SparseArray;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Job service for {@link AlarmScheduler}, the {@link AlarmManager}-based scheduler.
*
* This service runs whenever new jobs are scheduled or deleted, whenever constraints (eg. connectivity, charging)
* might have changed, and whenever a previous job finished, as these can schedule new jobs.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public class AlarmJobService extends Service implements JobService.Binder.Callback {
private static final String LOG_TAG = "AlarmJobService";
private static final String KEY_WAKE_LOCK_PROCESS = "process";
private static final String KEY_WAKE_LOCK_JOB = "job";
private static final long TIMEOUT_WAKE_LOCK_PROCESS = TimeUnit.MINUTES.toMillis(1);
private static final long TIMEOUT_WAKE_LOCK_JOB = TimeUnit.MINUTES.toMillis(3); // Same as JobScheduler's.
static void start(Context context) {
WakeLockUtils.acquireWakeLock(context, KEY_WAKE_LOCK_PROCESS, TIMEOUT_WAKE_LOCK_PROCESS);
context.startService(new Intent(context, AlarmJobService.class));
}
private JobScheduler jobScheduler;
private final SparseArray<Connection> connections = new SparseArray<>();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
jobScheduler = JobScheduler.get(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
// Stop jobs that have been cancelled.
for (int i = connections.size() - 1; i >= 0; i--) {
Connection connection = connections.valueAt(i);
if (jobScheduler.getJob(connection.params.getJobId()) == null) {
stopJob(connection, false);
}
}
// Start jobs that are ready, schedule jobs that are not.
List<JobStatus> jobStatuses = jobScheduler.getJobsByScheduler(AlarmScheduler.TAG);
updateConstraints(jobStatuses);
for (JobStatus jobStatus : jobStatuses) {
Connection connection = connections.get(jobStatus.getJobId());
if (jobStatus.isReady()) {
if (connection == null) {
// Job is ready and not already running, bind to the service and start the job.
startJob(jobStatus, startId);
}
} else if (connection != null) {
// Job is running but not ready, unbind from the service and stop the job.
boolean needsReschedule = connection.binder != null && connection.binder.stopJob(connection.params);
stopJob(connection, needsReschedule);
}
}
// Enable alarm receiver if there any alarm-based jobs left.
setComponentEnabled(this, AlarmReceiver.class, !jobStatuses.isEmpty());
} finally {
if (connections.size() == 0) {
stopSelf(startId);
}
// Each job holds its own wake lock while processing, release ours now.
WakeLockUtils.releaseWakeLock(KEY_WAKE_LOCK_PROCESS);
}
return START_NOT_STICKY;
}
/**
* Updates the state of each constraint in each {@link JobStatus}.
*
* When constraints are not met, receivers and/or alarms are scheduled for when it's appropriate to run again.
*/
private void updateConstraints(List<JobStatus> jobStatuses) {
// Update charging constraint.
boolean unsatisfiedChargingConstraint = false;
boolean charging = DeviceUtils.isCharging(this);
for (JobStatus jobStatus : jobStatuses) {
jobStatus.setConstraintSatisfied(JobStatus.CONSTRAINT_CHARGING, charging);
unsatisfiedChargingConstraint |= jobStatus.hasChargingConstraint() && !charging;
}
// Enable charging receiver if there are unmet constraints, or disable it if there aren't.
setComponentEnabled(this, AlarmReceiver.BatteryReceiver.class, unsatisfiedChargingConstraint);
// Update idle constraint.
boolean unsatisfiedIdleConstraint = false;
boolean idle = DeviceUtils.isIdle(this);
for (JobStatus jobStatus : jobStatuses) {
jobStatus.setConstraintSatisfied(JobStatus.CONSTRAINT_IDLE, idle);
unsatisfiedIdleConstraint |= jobStatus.hasIdleConstraint() && !idle;
}
// ACTION_SCREEN_OFF cannot be received through a receiver declared in AndroidManifest.
// AlarmReceiver will be scheduled to run by AlarmManager at most 30 minutes from now.
// Get connectivity constraints.
boolean unsatisfiedConnectivityConstraint = false;
boolean connected = DeviceUtils.isConnected(this);
boolean unmetered = connected && DeviceUtils.isUnmetered(this);
boolean notRoaming = connected && DeviceUtils.isNotRoaming(this);
for (JobStatus jobStatus : jobStatuses) {
jobStatus.setConstraintSatisfied(JobStatus.CONSTRAINT_CONNECTIVITY, connected);
unsatisfiedConnectivityConstraint |= jobStatus.hasConnectivityConstraint() && !connected;
jobStatus.setConstraintSatisfied(JobStatus.CONSTRAINT_UNMETERED, unmetered);
unsatisfiedConnectivityConstraint |= jobStatus.hasUnmeteredConstraint() && !unmetered;
jobStatus.setConstraintSatisfied(JobStatus.CONSTRAINT_NOT_ROAMING, notRoaming);
unsatisfiedConnectivityConstraint |= jobStatus.hasNotRoamingConstraint() && !notRoaming;
}
// Enable connectivity receiver if there are unmet constraints, or disable it if there aren't.
setComponentEnabled(this, AlarmReceiver.ConnectivityReceiver.class, unsatisfiedConnectivityConstraint);
// Get timing constraints.
long nextExpiryTime = Long.MAX_VALUE;
long nextDelayTime = Long.MAX_VALUE;
long nowElapsed = SystemClock.elapsedRealtime();
for (JobStatus jobStatus : jobStatuses) {
if (jobStatus.hasDeadlineConstraint()) {
long jobDeadline = jobStatus.getLatestRunTimeElapsed();
if (jobDeadline <= nowElapsed) {
jobStatus.setConstraintSatisfied(JobStatus.CONSTRAINT_DEADLINE, true);
continue; // Skip timing delay, job will run now.
} else if (nextExpiryTime > jobDeadline) {
nextExpiryTime = jobDeadline;
}
}
if (jobStatus.hasTimingDelayConstraint()) {
long jobDelayTime = jobStatus.getEarliestRunTimeElapsed();
if (jobDelayTime <= nowElapsed) {
jobStatus.setConstraintSatisfied(JobStatus.CONSTRAINT_TIMING_DELAY, true);
} else if (nextDelayTime > jobDelayTime) {
nextDelayTime = jobDelayTime;
}
}
}
// Schedule alarm to run at the earliest deadline, if any.
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, AlarmReceiver.class), 0);
long triggerAtMillis = Math.min(nextExpiryTime, nextDelayTime);
if (unsatisfiedIdleConstraint) {
triggerAtMillis = Math.min(triggerAtMillis, TimeUnit.MINUTES.toMillis(30));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
} else {
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
}
} else if (triggerAtMillis != Long.MAX_VALUE) {
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
}
}
@Override
public void jobFinished(JobParameters params, boolean needsReschedule) {
Connection connection = connections.get(params.getJobId());
if (connection != null) {
stopJob(connection, needsReschedule);
}
}
/**
* Starts the user's {@link JobService} by binding to it.
*/
private void startJob(JobStatus jobStatus, int startId) {
WakeLockUtils.acquireWakeLock(this, KEY_WAKE_LOCK_JOB, TIMEOUT_WAKE_LOCK_JOB);
int jobId = jobStatus.getJobId();
JobParameters params = new JobParameters(jobId, jobStatus.getExtras(), jobStatus.isDeadlineSatisfied());
Connection connection = new Connection(jobId, startId, params);
Intent jobIntent = new Intent();
if (bindService(jobIntent, connection, BIND_AUTO_CREATE)) {
connections.put(jobId, connection);
}
}
/**
* Stops the user's {@link JobService} by unbinding from it.
*/
private void stopJob(Connection connection, boolean needsReschedule) {
connections.remove(connection.jobId);
try {
unbindService(connection);
} catch (IllegalArgumentException e) {
// Service not connected at this point. Drop it.
}
jobScheduler.onJobCompleted(connection.jobId, needsReschedule);
stopSelf(connection.startId);
WakeLockUtils.releaseWakeLock(KEY_WAKE_LOCK_JOB);
}
private static void setComponentEnabled(Context context, Class cls, boolean enabled) {
PackageManager pm = context.getPackageManager();
if (pm != null) {
pm.setComponentEnabledSetting(
new ComponentName(context, cls),
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
: PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
/**
* {@link ServiceConnection} to the user's {@link JobService} that starts jobs when connected.
*/
private class Connection implements ServiceConnection {
private final int jobId;
private final int startId;
private final JobParameters params;
private JobService.Binder binder;
private Connection(int jobId, int startId, JobParameters params) {
this.jobId = jobId;
this.startId = startId;
this.params = params;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (!(service instanceof JobService.Binder)) {
Log.w(LOG_TAG, "Unknown service connected: " + service);
stopJob(this, false);
return;
}
binder = (JobService.Binder) service;
if (!binder.startJob(params, AlarmJobService.this)) {
stopJob(this, false);
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
// Should never happen as it's the same process.
binder = null;
if (connections.get(jobId) == this) {
stopJob(this, false);
}
}
}
}
| Fix AlarmJobService not specifying the component to run
| library/src/main/java/com/doist/jobschedulercompat/scheduler/alarm/AlarmJobService.java | Fix AlarmJobService not specifying the component to run | <ide><path>ibrary/src/main/java/com/doist/jobschedulercompat/scheduler/alarm/AlarmJobService.java
<ide> JobParameters params = new JobParameters(jobId, jobStatus.getExtras(), jobStatus.isDeadlineSatisfied());
<ide> Connection connection = new Connection(jobId, startId, params);
<ide> Intent jobIntent = new Intent();
<add> jobIntent.setComponent(jobStatus.getService());
<ide> if (bindService(jobIntent, connection, BIND_AUTO_CREATE)) {
<ide> connections.put(jobId, connection);
<ide> } |
|
Java | apache-2.0 | a1e4c7f6eb9a045d6ea70c5bb37512d22ec6d545 | 0 | mlhartme/stool,mlhartme/stool,mlhartme/stool,mlhartme/stool,mlhartme/stool | /*
* Copyright 1&1 Internet AG, https://github.com/1and1/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.oneandone.stool.cli;
import net.oneandone.stool.stage.Reference;
import net.oneandone.stool.util.Server;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Start extends StageCommand {
private final boolean tail;
private final int http;
private final int https;
private final Map<String, String> environment;
private final Map<String, Integer> selection;
public Start(Server server, boolean tail, List<String> selection) {
this(server, tail, -1, -1, selection);
}
public Start(Server server, boolean tail, int http, int https, List<String> selection) {
super(server);
this.tail = tail;
this.http = http;
this.https = https;
this.environment = new HashMap<>();
eatEnvironment(selection, environment);
this.selection = selection(selection);
}
private static void eatEnvironment(List<String> selection, Map<String, String> dest) {
Iterator<String> iter;
String str;
int idx;
iter = selection.iterator();
while (iter.hasNext()) {
str = iter.next();
idx = str.indexOf('=');
if (idx == -1) {
break;
}
dest.put(str.substring(0, idx), str.substring(idx + 1));
iter.remove();
}
}
@Override
public void doMain(Reference reference) throws Exception {
server.start(reference, http, https, environment, selection);
}
@Override
public void doFinish(Reference reference) throws Exception {
server.awaitStartup(reference);
console.info.println("Applications available:");
for (String app : server.running(reference)) {
for (String url : server.namedUrls(reference, app)) {
console.info.println(" " + url);
}
}
if (tail) {
doTail(reference);
}
}
//--
private void doTail(Reference reference) throws IOException {
console.info.println("Tailing container output.");
console.info.println("Press Ctrl-C to abort.");
console.info.println();
// TODO: stage.tailF(console.info);
}
}
| main/src/main/java/net/oneandone/stool/cli/Start.java | /*
* Copyright 1&1 Internet AG, https://github.com/1and1/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.oneandone.stool.cli;
import net.oneandone.stool.stage.Reference;
import net.oneandone.stool.util.Server;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Start extends StageCommand {
private final boolean tail;
private final int http;
private final int https;
private final Map<String, String> environment;
private final Map<String, Integer> selection;
public Start(Server server, boolean tail, List<String> selection) {
this(server, tail, -1, -1, selection);
}
public Start(Server server, boolean tail, int http, int https, List<String> selection) {
super(server);
this.tail = tail;
this.http = http;
this.https = https;
this.environment = new HashMap<>();
eatEnvironment(selection, environment);
this.selection = selection(selection);
}
private static void eatEnvironment(List<String> selection, Map<String, String> dest) {
Iterator<String> iter;
String str;
int idx;
iter = selection.iterator();
while (iter.hasNext()) {
str = iter.next();
idx = str.indexOf('=');
if (idx == -1) {
break;
}
dest.put(str.substring(0, idx), str.substring(idx + 1));
iter.remove();
}
}
@Override
public void doMain(Reference reference) throws Exception {
server.start(reference, http, https, environment, selection);
}
@Override
public void doFinish(Reference reference) throws Exception {
server.awaitStartup(reference);
Thread.sleep(2000);
console.info.println("Applications available:");
for (String app : server.running(reference)) {
for (String url : server.namedUrls(reference, app)) {
console.info.println(" " + url);
}
}
if (tail) {
doTail(reference);
}
}
//--
private void doTail(Reference reference) throws IOException {
console.info.println("Tailing container output.");
console.info.println("Press Ctrl-C to abort.");
console.info.println();
// TODO: stage.tailF(console.info);
}
}
| no longer needed
| main/src/main/java/net/oneandone/stool/cli/Start.java | no longer needed | <ide><path>ain/src/main/java/net/oneandone/stool/cli/Start.java
<ide> @Override
<ide> public void doFinish(Reference reference) throws Exception {
<ide> server.awaitStartup(reference);
<del>
<del> Thread.sleep(2000);
<ide> console.info.println("Applications available:");
<ide> for (String app : server.running(reference)) {
<ide> for (String url : server.namedUrls(reference, app)) { |
|
JavaScript | mit | e13d068fb1df4efbb9c5a0bdc49fd585ec62c05e | 0 | toshok/echojs,toshok/echojs,toshok/echojs,toshok/echojs,toshok/echojs,toshok/echojs,toshok/echojs,toshok/echojs | /* -*- Mode: js2; tab-width: 4; indent-tabs-mode: nil; -*-
* vim: set ts=4 sw=4 et tw=99 ft=js:
*/
import * as llvm from '@llvm';
import * as path from '@node-compat/path'
import { Stack } from './stack-es6';
import { TreeVisitor } from './node-visitor';
import { generate as escodegenerate } from '../external-deps/escodegen/escodegen-es6';
import { convert as closure_convert } from './closure-conversion';
import { reportError } from './errors';
import * as optimizations from './optimizations';
import * as types from './types';
import * as consts from './consts';
import * as runtime from './runtime';
import * as debug from './debug';
import * as b from './ast-builder';
import { startGenerator, intrinsic, is_intrinsic, is_string_literal } from './echo-util';
import { ExitableScope, TryExitableScope, SwitchExitableScope, LoopExitableScope } from './exitable-scope';
import { ABI } from './abi';
import { SRetABI } from './sret-abi';
let ir = llvm.IRBuilder;
let hasOwn = Object.prototype.hasOwnProperty;
class LLVMIRVisitor extends TreeVisitor {
constructor (module, filename, options, abi, allModules, this_module_info, dibuilder, difile) {
super();
this.module = module;
this.filename = filename;
this.options = options;
this.abi = abi;
this.allModules = allModules;
this.this_module_info = this_module_info;
this.dibuilder = dibuilder;
this.difile = difile;
this.idgen = startGenerator();
if (this.options.record_types)
this.genRecordId = startGenerator();
// build up our runtime method table
this.ejs_intrinsics = Object.create(null, {
templateDefaultHandlerCall: { value: this.handleTemplateDefaultHandlerCall },
templateCallsite: { value: this.handleTemplateCallsite },
moduleGet: { value: this.handleModuleGet },
moduleGetSlot: { value: this.handleModuleGetSlot },
moduleSetSlot: { value: this.handleModuleSetSlot },
moduleGetExotic: { value: this.handleModuleGetExotic },
getArgumentsObject: { value: this.handleGetArgumentsObject },
getLocal: { value: this.handleGetLocal },
setLocal: { value: this.handleSetLocal },
getGlobal: { value: this.handleGetGlobal },
setGlobal: { value: this.handleSetGlobal },
getArg: { value: this.handleGetArg },
getNewTarget: { value: this.handleGetNewTarget },
slot: { value: this.handleGetSlot },
setSlot: { value: this.handleSetSlot },
invokeClosure: { value: this.handleInvokeClosure },
constructClosure: { value: this.handleConstructClosure },
constructSuper: { value: this.handleConstructSuper },
constructSuperApply: { value: this.handleConstructSuperApply },
setConstructorKindDerived: { value: this.handleSetConstructorKindDerived },
setConstructorKindBase: { value: this.handleSetConstructorKindBase },
makeClosure: { value: this.handleMakeClosure },
makeClosureNoEnv: { value: this.handleMakeClosureNoEnv },
makeAnonClosure: { value: this.handleMakeAnonClosure },
makeGenerator: { value: this.handleMakeGenerator },
generatorYield: { value: this.handleGeneratorYield },
createArgScratchArea: { value: this.handleCreateArgScratchArea },
makeClosureEnv: { value: this.handleMakeClosureEnv },
typeofIsObject: { value: this.handleTypeofIsObject },
typeofIsFunction: { value: this.handleTypeofIsFunction },
typeofIsString: { value: this.handleTypeofIsString },
typeofIsSymbol: { value: this.handleTypeofIsSymbol },
typeofIsNumber: { value: this.handleTypeofIsNumber },
typeofIsBoolean: { value: this.handleTypeofIsBoolean },
builtinUndefined: { value: this.handleBuiltinUndefined },
isNullOrUndefined: { value: this.handleIsNullOrUndefined },
isUndefined: { value: this.handleIsUndefined },
isNull: { value: this.handleIsNull },
setPrototypeOf: { value: this.handleSetPrototypeOf },
objectCreate: { value: this.handleObjectCreate },
arrayFromRest: { value: this.handleArrayFromRest },
arrayFromSpread: { value: this.handleArrayFromSpread },
argPresent: { value: this.handleArgPresent },
createIterResult: { value: this.handleCreateIterResult },
createIteratorWrapper: { value: this.handleCreateIteratorWrapper }
});
this.opencode_intrinsics = {
unaryNot : true,
templateDefaultHandlerCall: true,
moduleGet : true, // unused
moduleGetSlot : true,
moduleSetSlot : true,
moduleGetExotic : true,
getLocal : true, // unused
setLocal : true, // unused
getGlobal : true, // unused
setGlobal : true, // unused
slot : true,
setSlot : true,
invokeClosure : false,
constructClosure : false,
makeClosure : true,
makeAnonClosure : true,
createArgScratchArea : true,
makeClosureEnv : true,
setConstructorKindDerived: false,
setConstructorKindBase: false,
typeofIsObject : true,
typeofIsFunction : true,
typeofIsString : true,
typeofIsSymbol : true,
typeofIsNumber : true,
typeofIsBoolean : true,
builtinUndefined : true,
isNullOrUndefined : true, // unused
isUndefined : true,
isNull : true
};
this.llvm_intrinsics = {
gcroot: () => module.getOrInsertIntrinsic("@llvm.gcroot")
};
this.ejs_runtime = runtime.createInterface(module, this.abi);
this.ejs_binops = runtime.createBinopsInterface(module, this.abi);
this.ejs_atoms = runtime.createAtomsInterface(module);
this.ejs_globals = runtime.createGlobalsInterface(module);
this.ejs_symbols = runtime.createSymbolsInterface(module);
this.module_atoms = new Map();
let init_function_name = `_ejs_module_init_string_literals_${this.filename}`;
this.literalInitializationFunction = this.module.getOrInsertFunction(init_function_name, types.Void, []);
if (this.options.debug)
this.literalInitializationDebugInfo = this.dibuilder.createFunction(this.difile, init_function_name, init_function_name, this.difile, 0, false, true, 0, 0, true, this.literalInitializationFunction);
// this function is only ever called by this module's toplevel
this.literalInitializationFunction.setInternalLinkage();
// initialize the scope stack with the global (empty) scope
this.scope_stack = new Stack(new Map());
let entry_bb = new llvm.BasicBlock("entry", this.literalInitializationFunction);
let return_bb = new llvm.BasicBlock("return", this.literalInitializationFunction);
if (this.options.debug)
ir.setCurrentDebugLocation(llvm.DebugLoc.get(0, 0, this.literalInitializationDebugInfo));
this.doInsideBBlock(entry_bb, () => { ir.createBr(return_bb); });
this.doInsideBBlock(return_bb, () => {
//this.createCall this.ejs_runtime.log, [consts.string(ir, "done with literal initialization")], ""
ir.createRetVoid();
});
this.literalInitializationBB = entry_bb;
}
// lots of helper methods
emitModuleInfo () {
let this_module_type = types.getModuleSpecificType(this.this_module_info.module_name, this.this_module_info.slot_num);
this.this_module_global = new llvm.GlobalVariable(this.module, this_module_type, this.this_module_info.module_name, llvm.Constant.getAggregateZero(this_module_type), true);
this.import_module_globals = new Map();
for (let import_module_string of this.this_module_info.importList) {
let import_module_info = this.allModules.get(import_module_string);
if (!import_module_info.isNative())
this.import_module_globals.set(import_module_string, new llvm.GlobalVariable(this.module, types.EjsModule, import_module_info.module_name, null, true));
}
this.this_module_initted = new llvm.GlobalVariable(this.module, types.Bool, `${this.this_module_info.module_name}_initialized`, consts.False(), false);
}
emitModuleResolution (module_accessors) {
// this.loadUndefinedEjsValue depends on this
this.currentFunction = this.toplevel_function;
ir.setInsertPoint(this.resolve_modules_bb);
if (this.options.debug)
ir.setCurrentDebugLocation(llvm.DebugLoc.get(0, 0, this.currentFunction.debug_info));
let uninitialized_bb = new llvm.BasicBlock("module_uninitialized", this.toplevel_function);
let initialized_bb = new llvm.BasicBlock("module_initialized", this.toplevel_function);
let load_init_flag = ir.createLoad(this.this_module_initted, "load_init_flag");
let load_init_cmp = ir.createICmpEq(load_init_flag, consts.False(), "load_init_cmp");
ir.createCondBr(load_init_cmp, uninitialized_bb, initialized_bb);
ir.setInsertPoint(uninitialized_bb);
ir.createStore(consts.True(), this.this_module_initted);
ir.createCall(this.literalInitializationFunction, [], "");
// fill in the information we know about this module
// our name
let name_slot = ir.createInBoundsGetElementPointer(this.this_module_global, [consts.int64(0), consts.int32(1)], "name_slot");
ir.createStore(consts.string(ir, this.this_module_info.path), name_slot);
// num_exports
let num_exports_slot = ir.createInBoundsGetElementPointer(this.this_module_global, [consts.int64(0), consts.int32(2)], "num_exports_slot");
ir.createStore(consts.int32(this.this_module_info.slot_num), num_exports_slot);
// define our accessor properties
for (let accessor of module_accessors) {
let get_func = (accessor.getter && accessor.getter.ir_func) || consts.Null(types.EjsClosureFunc);
let set_func = (accessor.setter && accessor.setter.ir_func) || consts.Null(types.EjsClosureFunc);
let module_arg = ir.createPointerCast(this.this_module_global, types.EjsModule.pointerTo(), "");
ir.createCall(this.ejs_runtime.module_add_export_accessors, [module_arg, consts.string(ir, accessor.key), get_func, set_func], "");
};
for (let import_module_string of this.this_module_info.importList) {
let import_module = this.import_module_globals.get(import_module_string);
if (import_module) {
this.createCall(this.ejs_runtime.module_resolve, [import_module], "", !this.ejs_runtime.module_resolve.doesNotThrow);
}
}
ir.createBr(this.toplevel_body_bb);
ir.setInsertPoint(initialized_bb);
return this.createRet(this.loadUndefinedEjsValue());
}
// result should be the landingpad's value
beginCatch (result) { return this.createCall(this.ejs_runtime.begin_catch, [ir.createPointerCast(result, types.Int8Pointer, "")], "begincatch"); }
endCatch () { return this.createCall(this.ejs_runtime.end_catch, [], "endcatch"); }
doInsideExitableScope (scope, f) {
scope.enter();
f();
scope.leave();
}
doInsideBBlock (b, f) {
let saved = ir.getInsertBlock();
ir.setInsertPoint(b);
f();
ir.setInsertPoint(saved);
return b;
}
createLoad (value, name) {
let rv = ir.createLoad(value, name);
rv.setAlignment(8);
return rv;
}
loadCachedEjsValue (name, init) {
let alloca_name = `${name}_alloca`;
let load_name = `${name}_load`;
let alloca;
if (this.currentFunction[alloca_name]) {
alloca = this.currentFunction[alloca_name];
}
else {
alloca = this.createAlloca(this.currentFunction, types.EjsValue, alloca_name);
this.currentFunction[alloca_name] = alloca;
this.doInsideBBlock(this.currentFunction.entry_bb, () => init(alloca));
}
return ir.createLoad(alloca, load_name);
}
loadBoolEjsValue (n) {
let rv = this.loadCachedEjsValue(n, (alloca) => {
let alloca_as_int64 = ir.createBitCast(alloca, types.Int64.pointerTo(), "alloca_as_pointer");
if (this.options.target_pointer_size === 64)
ir.createStore(consts.int64_lowhi(0xfff98000, n ? 0x00000001 : 0x000000000), alloca_as_int64);
else
ir.createStore(consts.int64_lowhi(0xffffff83, n ? 0x00000001 : 0x000000000), alloca_as_int64);
});
rv._ejs_returns_ejsval_bool = true;
return rv;
}
loadDoubleEjsValue (n) { return this.loadCachedEjsValue(`num_${n}`, (alloca) => this.storeDouble(alloca, n)); }
loadNullEjsValue () { return this.loadCachedEjsValue("null", (alloca) => this.storeNull(alloca)); }
loadUndefinedEjsValue () { return this.loadCachedEjsValue("undef", (alloca) => this.storeUndefined(alloca)); }
storeUndefined (alloca, name) {
let alloca_as_int64 = ir.createBitCast(alloca, types.Int64.pointerTo(), "alloca_as_pointer");
if (this.options.target_pointer_size === 64)
return ir.createStore(consts.int64_lowhi(0xfff90000, 0x00000000), alloca_as_int64, name);
else // 32 bit
return ir.createStore(consts.int64_lowhi(0xffffff82, 0x00000000), alloca_as_int64, name);
}
storeNull (alloca, name) {
let alloca_as_int64 = ir.createBitCast(alloca, types.Int64.pointerTo(), "alloca_as_pointer");
if (this.options.target_pointer_size === 64)
return ir.createStore(consts.int64_lowhi(0xfffb8000, 0x00000000), alloca_as_int64, name);
else // 32 bit
return ir.createStore(consts.int64_lowhi(0xffffff87, 0x00000000), alloca_as_int64, name);
}
storeDouble (alloca, jsnum, name) {
let c = llvm.ConstantFP.getDouble(jsnum);
let alloca_as_double = ir.createBitCast(alloca, types.Double.pointerTo(), "alloca_as_pointer");
return ir.createStore(c, alloca_as_double, name);
}
storeBoolean (alloca, jsbool, name) {
let alloca_as_int64 = ir.createBitCast(alloca, types.Int64.pointerTo(), "alloca_as_pointer");
if (this.options.target_pointer_size === 64)
return ir.createStore(consts.int64_lowhi(0xfff98000, jsbool ? 0x00000001 : 0x000000000), alloca_as_int64, name);
else
return ir.createStore(consts.int64_lowhi(0xffffff83, jsbool ? 0x00000001 : 0x000000000), alloca_as_int64, name);
}
storeToDest (dest, arg, name = "") {
if (!arg)
arg = { type: b.Literal, value: null };
if (arg.type === b.Literal) {
if (arg.value === null)
return this.storeNull(dest, name);
if (arg.value === undefined)
return this.storeUndefined(dest, name);
if (typeof arg.value === "number")
return this.storeDouble(dest, arg.value, name);
if (typeof arg.value === "boolean")
return this.storeBoolean(dest, arg.value, name);
// if typeof arg is "string"
let val = this.visit(arg);
return ir.createStore(val, dest, name);
}
else {
let val = this.visit(arg);
return ir.createStore(val, dest, name);
}
}
storeGlobal (prop, value) {
let gname;
// we store obj.prop, prop is an id
if (prop.type === b.Identifier)
gname = prop.name;
else // prop.type is b.Literal
gname = prop.value;
let c = this.getAtom(gname);
debug.log( () => `createPropertyStore %global[${gname}]` );
return this.createCall(this.ejs_runtime.global_setprop, [c, value], `globalpropstore_${gname}`);
}
loadGlobal (prop) {
let gname = prop.name;
if (this.options.frozen_global)
return ir.createLoad(this.ejs_globals[prop.name], `load-${gname}`);
let pname = this.getAtom(gname);
return this.createCall(this.ejs_runtime.global_getprop, [pname], `globalloadprop_${gname}`);
}
visitWithScope (scope, children) {
this.scope_stack.push(scope);
for (let child of children)
this.visit(child);
this.scope_stack.pop();
}
findIdentifierInScope (ident) {
for (let scope of this.scope_stack.stack) {
if (scope.has(ident))
return scope.get(ident);
}
return null;
}
createAlloca (func, type, name) {
let saved_insert_point = ir.getInsertBlock();
ir.setInsertPointStartBB(func.entry_bb);
let alloca = ir.createAlloca(type, name);
// if EjsValue was a pointer value we would be able to use an the llvm gcroot intrinsic here. but with the nan boxing
// we kinda lose out as the llvm IR code doesn't permit non-reference types to be gc roots.
// if type is types.EjsValue
// // EjsValues are rooted
// this.createCall this.llvm_intrinsics.gcroot(), [(ir.createPointerCast alloca, types.Int8Pointer.pointerTo(), "rooted_alloca"), consts.Null types.Int8Pointer], ""
ir.setInsertPoint(saved_insert_point);
return alloca;
}
createAllocas (func, ids, scope) {
let allocas = [];
let new_allocas = [];
// the allocas are always allocated in the function entry_bb so the mem2reg opt pass can regenerate the ssa form for us
let saved_insert_point = ir.getInsertBlock();
ir.setInsertPointStartBB(func.entry_bb);
let j = 0;
for (let i = 0, e = ids.length; i < e; i ++) {
let name = ids[i].id.name;
if (!scope.has(name)) {
allocas[j] = ir.createAlloca(types.EjsValue, `local_${name}`);
allocas[j].setAlignment(8);
scope.set(name, allocas[j]);
new_allocas[j] = true;
}
else {
allocas[j] = scope.get(name);
new_allocas[j] = false;
}
j = j + 1;
}
// reinstate the IRBuilder to its previous insert point so we can insert the actual initializations
ir.setInsertPoint(saved_insert_point);
return { allocas: allocas, new_allocas: new_allocas };
}
createPropertyStore (obj,prop,rhs,computed) {
if (computed) {
// we store obj[prop], prop can be any value
return this.createCall(this.ejs_runtime.object_setprop, [obj, this.visit(prop), rhs], "propstore_computed");
}
else {
var pname;
// we store obj.prop, prop is an id
if (prop.type === b.Identifier)
pname = prop.name;
else // prop.type is b.Literal
pname = prop.value;
let c = this.getAtom(pname);
debug.log(() => `createPropertyStore ${obj}[${pname}]`);
return this.createCall(this.ejs_runtime.object_setprop, [obj, c, rhs], `propstore_${pname}`);
}
}
createPropertyLoad (obj,prop,computed,canThrow = true) {
if (computed) {
// we load obj[prop], prop can be any value
let loadprop = this.visit(prop);
if (this.options.record_types)
this.createCall(this.ejs_runtime.record_getprop, [consts.int32(this.genRecordId()), obj, loadprop], "");
return this.createCall(this.ejs_runtime.object_getprop, [obj, loadprop], "getprop_computed", canThrow);
}
else {
// we load obj.prop, prop is an id
let pname = this.getAtom(prop.name);
if (this.options.record_types)
this.createCall(this.ejs_runtime.record_getprop, [consts.int32(this.genRecordId()), obj, pname], "");
return this.createCall(this.ejs_runtime.object_getprop, [obj, pname], `getprop_${prop.name}`, canThrow);
}
}
setDebugLoc (ast_node) {
if (!this.options.debug) return;
if (!ast_node || !ast_node.loc) return;
if (!this.currentFunction) return;
if (!this.currentFunction.debug_info) return;
ir.setCurrentDebugLocation(llvm.DebugLoc.get(ast_node.loc.start.line, ast_node.loc.start.column, this.currentFunction.debug_info));
}
visit (n) {
this.setDebugLoc(n);
return super.visit(n);
}
visitOrNull (n) { return this.visit(n) || this.loadNullEjsValue(); }
visitOrUndefined (n) { return this.visit(n) || this.loadUndefinedEjsValue(); }
visitProgram (n) {
// by the time we make it here the program has been
// transformed so that there is nothing at the toplevel
// but function declarations.
for (let func of n.body)
this.visit(func);
}
visitBlock (n) {
let new_scope = new Map();
let iife_dest_bb = null;
let iife_rv = null;
if (n.fromIIFE) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
iife_dest_bb = new llvm.BasicBlock("iife_dest", insertFunc);
iife_rv = n.ejs_iife_rv;
}
this.iifeStack.push ({ iife_rv, iife_dest_bb });
this.visitWithScope(new_scope, n.body);
this.iifeStack.pop();
if (iife_dest_bb) {
ir.createBr(iife_dest_bb);
ir.setInsertPoint(iife_dest_bb);
let rv = this.createLoad(this.findIdentifierInScope(iife_rv.name), "%iife_rv_load");
return rv;
}
else {
return n;
}
}
visitSwitch (n) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
// find the default: case first
let defaultCase = null;
for (let _case of n.cases) {
if (!_case.test) {
defaultCase = _case;
break;
}
}
// for each case, create 2 basic blocks
for (let _case of n.cases) {
_case.bb = new llvm.BasicBlock("case_bb", insertFunc);
if (_case !== defaultCase)
_case.dest_check = new llvm.BasicBlock("case_dest_check_bb", insertFunc);
}
let merge_bb = new llvm.BasicBlock("switch_merge", insertFunc);
let discr = this.visit(n.discriminant);
let case_checks = [];
for (let _case of n.cases) {
if (defaultCase !== _case)
case_checks.push ({ test: _case.test, dest_check: _case.dest_check, body: _case.bb });
}
case_checks.push ({ dest_check: defaultCase ? defaultCase.bb : merge_bb });
this.doInsideExitableScope (new SwitchExitableScope(merge_bb), () => {
// insert all the code for the tests
ir.createBr(case_checks[0].dest_check);
ir.setInsertPoint(case_checks[0].dest_check);
for (let casenum = 0; casenum < case_checks.length -1; casenum ++) {
let test = this.visit(case_checks[casenum].test);
let eqop = this.ejs_binops["==="];
this.setDebugLoc(test);
let discTest = this.createCall(eqop, [discr, test], "test", !eqop.doesNotThrow);
let disc_cmp, disc_truthy;
if (discTest._ejs_returns_ejsval_bool) {
disc_cmp = this.createEjsvalICmpEq(discTest, consts.ejsval_false());
}
else {
disc_truthy = this.createCall(this.ejs_runtime.truthy, [discTest], "disc_truthy");
disc_cmp = ir.createICmpEq(disc_truthy, consts.False(), "disccmpresult");
}
ir.createCondBr(disc_cmp, case_checks[casenum+1].dest_check, case_checks[casenum].body);
ir.setInsertPoint(case_checks[casenum+1].dest_check);
}
let case_bodies = [];
// now insert all the code for the case consequents
for (let _case of n.cases)
case_bodies.push ({bb:_case.bb, consequent:_case.consequent});
case_bodies.push ({bb:merge_bb});
for (let casenum = 0; casenum < case_bodies.length-1; casenum ++) {
ir.setInsertPoint(case_bodies[casenum].bb);
case_bodies[casenum].consequent.forEach ((consequent, i) => {
this.visit(consequent);
});
ir.createBr(case_bodies[casenum+1].bb);
}
ir.setInsertPoint(merge_bb);
});
return merge_bb;
}
visitCase (n) {
throw new Error("we shouldn't get here, case statements are handled in visitSwitch");
}
visitLabeledStatement (n) {
n.body.label = n.label.name;
return this.visit(n.body);
}
visitBreak (n) {
return ExitableScope.scopeStack.exitAft(true, n.label && n.label.name);
}
visitContinue (n) {
if (n.label && n.label.name)
return LoopExitableScope.findLabeledOrFinally(n.label.name).exitFore();
else
return LoopExitableScope.findLoopOrFinally().exitFore();
}
generateCondBr (exp, then_bb, else_bb) {
let cmp, exp_value;
if (exp.type === b.Literal && typeof exp.value === "boolean") {
cmp = consts.int1(exp.value ? 0 : 1); // we check for false below, so the then/else branches get swapped
}
else {
exp_value = this.visit(exp);
if (exp_value._ejs_returns_ejsval_bool) {
cmp = this.createEjsvalICmpEq(exp_value, consts.ejsval_false(), "cmpresult");
}
else if (exp_value._ejs_returns_native_bool) {
cmp = ir.createSelect(exp_value, consts.int1(0), consts.int1(1), "invert_check");
}
else {
let cond_truthy = this.createCall(this.ejs_runtime.truthy, [exp_value], "cond_truthy");
cmp = ir.createICmpEq(cond_truthy, consts.False(), "cmpresult");
}
}
ir.createCondBr(cmp, else_bb, then_bb);
return exp_value;
}
visitFor (n) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let init_bb = new llvm.BasicBlock("for_init", insertFunc);
let test_bb = new llvm.BasicBlock("for_test", insertFunc);
let body_bb = new llvm.BasicBlock("for_body", insertFunc);
let update_bb = new llvm.BasicBlock("for_update", insertFunc);
let merge_bb = new llvm.BasicBlock("for_merge", insertFunc);
ir.createBr(init_bb);
this.doInsideBBlock(init_bb, () => {
this.visit(n.init);
ir.createBr(test_bb);
});
this.doInsideBBlock(test_bb, () => {
if (n.test)
this.generateCondBr(n.test, body_bb, merge_bb);
else
ir.createBr(body_bb);
});
this.doInsideExitableScope (new LoopExitableScope(n.label, update_bb, merge_bb), () => {
this.doInsideBBlock(body_bb, () => {
this.visit(n.body);
ir.createBr(update_bb);
});
this.doInsideBBlock(update_bb, () => {
this.visit(n.update);
ir.createBr(test_bb);
});
});
ir.setInsertPoint(merge_bb);
return merge_bb;
}
visitDo (n) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let body_bb = new llvm.BasicBlock("do_body", insertFunc);
let test_bb = new llvm.BasicBlock("do_test", insertFunc);
let merge_bb = new llvm.BasicBlock("do_merge", insertFunc);
ir.createBr(body_bb);
this.doInsideExitableScope (new LoopExitableScope(n.label, test_bb, merge_bb), () => {
this.doInsideBBlock(body_bb, () => {
this.visit(n.body);
ir.createBr(test_bb);
});
this.doInsideBBlock(test_bb, () => {
this.generateCondBr(n.test, body_bb, merge_bb);
});
});
ir.setInsertPoint(merge_bb);
return merge_bb;
}
visitWhile (n) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let while_bb = new llvm.BasicBlock("while_start", insertFunc);
let body_bb = new llvm.BasicBlock("while_body", insertFunc);
let merge_bb = new llvm.BasicBlock("while_merge", insertFunc);
ir.createBr(while_bb);
this.doInsideBBlock(while_bb, () => {
this.generateCondBr(n.test, body_bb, merge_bb);
});
this.doInsideExitableScope (new LoopExitableScope(n.label, while_bb, merge_bb), () => {
this.doInsideBBlock(body_bb, () => {
this.visit(n.body);
ir.createBr(while_bb);
});
});
ir.setInsertPoint(merge_bb);
return merge_bb;
}
visitForIn (n) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let iterator = this.createCall(this.ejs_runtime.prop_iterator_new, [this.visit(n.right)], "iterator");
let lhs;
// make sure we get an alloca if there's a "var"
if (n.left[0]) {
this.visit(n.left);
lhs = n.left[0].declarations[0].id;
}
else {
lhs = n.left;
}
let forin_bb = new llvm.BasicBlock ("forin_start", insertFunc);
let body_bb = new llvm.BasicBlock ("forin_body", insertFunc);
let merge_bb = new llvm.BasicBlock ("forin_merge", insertFunc);
ir.createBr(forin_bb);
this.doInsideExitableScope (new LoopExitableScope (n.label, forin_bb, merge_bb), () => {
// forin_bb:
// moreleft = prop_iterator_next (iterator, true)
// if moreleft === false
// goto merge_bb
// else
// goto body_bb
//
this.doInsideBBlock (forin_bb, () => {
let moreleft = this.createCall(this.ejs_runtime.prop_iterator_next, [iterator, consts.True()], "moreleft");
let cmp = ir.createICmpEq(moreleft, consts.False(), "cmpmoreleft");
ir.createCondBr(cmp, merge_bb, body_bb);
});
// body_bb:
// current = prop_iteratorcurrent (iterator)
// *lhs = current
// <body>
// goto forin_bb
this.doInsideBBlock (body_bb, () => {
let current = this.createCall(this.ejs_runtime.prop_iterator_current, [iterator], "iterator_current");
this.storeValueInDest(current, lhs);
this.visit(n.body);
ir.createBr(forin_bb);
});
});
// merge_bb:
//
ir.setInsertPoint(merge_bb);
return merge_bb;
}
visitForOf (n) {
throw new Error("internal compiler error. for..of statements should have been transformed away by this point.");
}
visitUpdateExpression (n) {
let result = this.createAlloca(this.currentFunction, types.EjsValue, "%update_result");
let argument = this.visit(n.argument);
let one = this.loadDoubleEjsValue(1);
if (!n.prefix) {
// postfix updates store the argument before the op
ir.createStore(argument, result);
}
// argument = argument $op 1
let update_op = this.ejs_binops[n.operator === '++' ? '+' : '-'];
let temp = this.createCall(update_op, [argument, one], "update_temp", !update_op.doesNotThrow);
this.storeValueInDest(temp, n.argument);
// return result
if (n.prefix) {
argument = this.visit(n.argument);
// prefix updates store the argument after the op
ir.createStore(argument, result);
}
return this.createLoad(result, "%update_result_load");
}
visitConditionalExpression (n) {
return this.visitIfOrCondExp(n, true);
}
visitIf (n) {
return this.visitIfOrCondExp(n, false);
}
visitIfOrCondExp (n, load_result) {
let cond_val;
if (load_result)
cond_val = this.createAlloca(this.currentFunction, types.EjsValue, "%cond_val");
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let then_bb = new llvm.BasicBlock ("then", insertFunc);
let else_bb;
if (n.alternate)
else_bb = new llvm.BasicBlock ("else", insertFunc);
let merge_bb = new llvm.BasicBlock ("merge", insertFunc);
this.generateCondBr(n.test, then_bb, else_bb ? else_bb : merge_bb);
this.doInsideBBlock(then_bb, () => {
let then_val = this.visit(n.consequent);
if (load_result) ir.createStore(then_val, cond_val);
ir.createBr(merge_bb);
});
if (n.alternate) {
this.doInsideBBlock(else_bb, () => {
let else_val = this.visit(n.alternate);
if (load_result) ir.createStore(else_val, cond_val);
ir.createBr(merge_bb);
});
}
ir.setInsertPoint(merge_bb);
if (load_result)
return this.createLoad(cond_val, "cond_val_load");
else
return merge_bb;
}
visitReturn (n) {
if (this.iifeStack.top.iife_rv) {
// if we're inside an IIFE, convert the return statement into a store to the iife_rv alloca + a branch to the iife's dest bb
if (n.argument)
ir.createStore(this.visit(n.argument), this.findIdentifierInScope(this.iifeStack.top.iife_rv.name));
ir.createBr(this.iifeStack.top.iife_dest_bb);
}
else {
// otherwise generate an llvm IR ret
let rv = this.visitOrUndefined(n.argument);
if (this.finallyStack.length > 0) {
if (!this.currentFunction.returnValueAlloca)
this.currentFunction.returnValueAlloca = this.createAlloca(this.currentFunction, types.EjsValue, "returnValue");
ir.createStore(rv, this.currentFunction.returnValueAlloca);
ir.createStore(consts.int32(ExitableScope.REASON_RETURN), this.currentFunction.cleanup_reason);
ir.createBr(this.finallyStack[0]);
}
else {
let return_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "return_alloca");
ir.createStore(rv, return_alloca);
this.createRet(this.createLoad(return_alloca, "return_load"));
}
}
}
visitVariableDeclaration (n) {
if (n.kind === "var") throw new Error("internal compiler error. 'var' declarations should have been transformed to 'let's by this point.");
let scope = this.scope_stack.top;
let { allocas, new_allocas } = this.createAllocas(this.currentFunction, n.declarations, scope);
for (let i = 0, e = n.declarations.length; i < e; i ++) {
if (!n.declarations[i].init) {
// there was not an initializer. we only store undefined
// if the alloca is newly allocated.
if (new_allocas[i]) {
let initializer = this.visitOrUndefined(n.declarations[i].init);
ir.createStore(initializer, allocas[i]);
}
}
else {
let initializer = this.visitOrUndefined(n.declarations[i].init);
ir.createStore(initializer, allocas[i]);
}
}
}
visitMemberExpression (n) {
return this.createPropertyLoad(this.visit(n.object), n.property, n.computed);
}
storeValueInDest (rhvalue, lhs) {
if (lhs.type === b.Identifier) {
let dest = this.findIdentifierInScope(lhs.name);
let result;
if (dest)
result = ir.createStore(rhvalue, dest);
else
result = this.storeGlobal(lhs, rhvalue);
return result;
}
else if (lhs.type === b.MemberExpression) {
return this.createPropertyStore(this.visit(lhs.object), lhs.property, rhvalue, lhs.computed);
}
else if (is_intrinsic(lhs, "%slot")) {
return ir.createStore(rhvalue, this.handleSlotRef(lhs));
}
else if (is_intrinsic(lhs, "%getLocal")) {
return ir.createStore(rhvalue, this.findIdentifierInScope(lhs.arguments[0].name));
}
else if (is_intrinsic(lhs, "%getGlobal")) {
let gname = lhs.arguments[0].name;
return this.createCall(this.ejs_runtime.global_setprop, [this.getAtom(gname), rhvalue], `globalpropstore_${lhs.arguments[0].name}`);
}
else {
throw new Error(`unhandled lhs ${escodegenerate(lhs)}`);
}
}
visitAssignmentExpression (n) {
let lhs = n.left;
let rhs = n.right;
let rhvalue = this.visit(rhs);
if (n.operator.length === 2)
throw new Error(`binary assignment operators '${n.operator}' should not exist at this point`);
if (this.options.record_types)
this.createCall(this.ejs_runtime.record_assignment, [consts.int32(this.genRecordId()), rhvalue], "");
this.storeValueInDest(rhvalue, lhs);
// we need to visit lhs after the store so that we load the value, but only if it's used
if (!n.result_not_used)
return rhvalue;
}
visitFunction (n) {
if (!n.toplevel)
debug.log (() => ` function ${n.ir_name} at ${this.filename}:${n.loc ? n.loc.start.line : '<unknown>'}`);
// save off the insert point so we can get back to it after generating this function
let insertBlock = ir.getInsertBlock();
for (let param of n.formal_params) {
if (param.type !== b.Identifier)
throw new Error("formal parameters should only be identifiers by this point");
}
// XXX this methods needs to be augmented so that we can pass actual types (or the builtin args need
// to be reflected in jsllvm.cpp too). maybe we can pass the names to this method and it can do it all
// there?
let ir_func = n.ir_func;
let ir_args = n.ir_func.args;
debug.log ("");
//debug.log -> `ir_func = ${ir_func}`
//debug.log -> `param ${param.llvm_type} ${param.name}` for param in n.formal_params
this.currentFunction = ir_func;
// we need to do this here as well, since otherwise the allocas and stores we create below for our parameters
// could be accidentally attributed to the previous @currentFunction (the last location we set).
this.setDebugLoc(n);
// Create a new basic block to start insertion into.
let entry_bb = new llvm.BasicBlock("entry", ir_func);
ir.setInsertPoint(entry_bb);
let new_scope = new Map();
// we save off the top scope and entry_bb of the function so that we can hoist vars there
ir_func.topScope = new_scope;
ir_func.entry_bb = entry_bb;
ir_func.literalAllocas = Object.create(null);
let allocas = [];
// create allocas for the builtin args
for (let param of n.params) {
let alloca = ir.createAlloca(param.llvm_type, `local_${param.name}`);
alloca.setAlignment(8);
new_scope.set(param.name, alloca);
allocas.push(alloca);
}
// now create allocas for the formal parameters
let first_formal_index = allocas.length;
for (let param of n.formal_params) {
let alloca = this.createAlloca(this.currentFunction, types.EjsValue, `local_${param.name}`);
new_scope.set(param.name, alloca);
allocas.push(alloca);
}
debug.log ( () => {
allocas.map( (alloca) => `alloca ${alloca}`).join('\n');
});
// now store the arguments onto the stack
for (let i = 0, e = n.params.length; i < e; i ++) {
var store = ir.createStore(ir_args[i], allocas[i]);
debug.log ( () => `store ${store} *builtin` );
}
let body_bb = new llvm.BasicBlock("body", ir_func);
ir.setInsertPoint(body_bb);
//this.createCall this.ejs_runtime.log, [consts.string(ir, `entering ${n.ir_name}`)], ""
let insertFunc = body_bb.parent;
this.iifeStack = new Stack();
this.finallyStack = [];
this.visitWithScope(new_scope, [n.body]);
// XXX more needed here - this lacks all sorts of control flow stuff.
// Finish off the function.
this.createRet(this.loadUndefinedEjsValue());
if (n.toplevel) {
this.resolve_modules_bb = new llvm.BasicBlock("resolve_modules", ir_func);
this.toplevel_body_bb = body_bb;
this.toplevel_function = ir_func;
// branch to the resolve_modules_bb from our entry_bb, but only in the toplevel function
ir.setInsertPoint(entry_bb);
ir.createBr(this.resolve_modules_bb);
}
else {
// branch to the body_bb from our entry_bb
ir.setInsertPoint(entry_bb);
ir.createBr(body_bb);
}
this.currentFunction = null;
ir.setInsertPoint(insertBlock);
return ir_func;
}
createRet (x) {
//this.createCall this.ejs_runtime.log, [consts.string(ir, `leaving ${this.currentFunction.name}`)], ""
return this.abi.createRet(this.currentFunction, x);
}
visitUnaryExpression (n) {
debug.log ( () => `operator = '${n.operator}'` );
let builtin = `unop${n.operator}`;
let callee = this.ejs_runtime[builtin];
if (n.operator === "delete") {
if (n.argument.type !== b.MemberExpression) throw "unhandled delete syntax";
let fake_literal = {
type: b.Literal,
value: n.argument.property.name,
raw: `'${n.argument.property.name}'`
};
return this.createCall(callee, [this.visitOrNull(n.argument.object), this.visit(fake_literal)], "result");
}
else if (n.operator === "!") {
let arg_value = this.visitOrNull(n.argument);
if (this.opencode_intrinsics.unaryNot && this.options.target_pointer_size === 64 && arg_value._ejs_returns_ejsval_bool) {
let cmp = this.createEjsvalICmpEq(arg_value, consts.ejsval_true(), "cmpresult");
return this.createEjsBoolSelect(cmp, true);
}
else {
return this.createCall(callee, [arg_value], "result");
}
}
else {
if (!callee) {
throw new Error(`Internal error: unary operator '${n.operator}' not implemented`);
}
return this.createCall(callee, [this.visitOrNull(n.argument)], "result");
}
}
visitSequenceExpression (n) {
let rv = null;
for (let exp of n.expressions)
rv = this.visit(exp);
return rv;
}
visitBinaryExpression (n) {
debug.log ( () => `operator = '${n.operator}'` );
let callee = this.ejs_binops[n.operator];
if (!callee)
throw new Error(`Internal error: unhandled binary operator '${n.operator}'`);
let left_visited = this.visit(n.left);
let right_visited = this.visit(n.right);
if (this.options.record_types)
this.createCall(this.ejs_runtime.record_binop, [consts.int32(this.genRecordId()), consts.string(ir, n.operator), left_visited, right_visited], "");
// call the actual runtime binaryop method
return this.createCall(callee, [left_visited, right_visited], `result_${n.operator}`, !callee.doesNotThrow);
}
visitLogicalExpression (n) {
debug.log ( () => `operator = '${n.operator}'` );
let result = this.createAlloca(this.currentFunction, types.EjsValue, `result_${n.operator}`);
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let left_bb = new llvm.BasicBlock ("cond_left", insertFunc);
let right_bb = new llvm.BasicBlock ("cond_right", insertFunc);
let merge_bb = new llvm.BasicBlock ("cond_merge", insertFunc);
// we invert the test here - check if the condition is false/0
let left_visited = this.generateCondBr(n.left, left_bb, right_bb);
this.doInsideBBlock(left_bb, () => {
// inside the else branch, left was truthy
if (n.operator === "||")
// for || we short circuit out here
ir.createStore(left_visited, result);
else if (n.operator === "&&")
// for && we evaluate the second and store it
ir.createStore(this.visit(n.right), result);
else
throw "Internal error 99.1";
ir.createBr(merge_bb);
});
this.doInsideBBlock(right_bb, () => {
// inside the then branch, left was falsy
if (n.operator === "||")
// for || we evaluate the second and store it
ir.createStore(this.visit(n.right), result);
else if (n.operator === "&&")
// for && we short circuit out here
ir.createStore(left_visited, result);
else
throw "Internal error 99.1";
ir.createBr(merge_bb);
});
ir.setInsertPoint(merge_bb);
return this.createLoad(result, `result_${n.operator}_load`);
}
visitArgsForCall (callee, pullThisFromArg0, args) {
args = args.slice();
let argv = [];
if (callee.takes_builtins) {
let thisArg, closure;
if (pullThisFromArg0 && args[0].type === b.MemberExpression) {
thisArg = this.visit(args[0].object);
closure = this.createPropertyLoad(thisArg, args[0].property, args[0].computed);
}
else {
thisArg = this.loadUndefinedEjsValue();
closure = this.visit(args[0]);
}
let this_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "this_alloca");
ir.createStore(thisArg, this_alloca, "this_alloca_store");
args.shift();
argv.push(closure); // %closure
argv.push(this_alloca); // %this
argv.push(consts.int32(args.length)); // %argc
let args_length = args.length;
if (args_length > 0) {
for (let i = 0; i < args_length; i ++) {
args[i] = this.visitOrNull(args[i]);
}
for (let i = 0; i < args_length; i ++) {
let gep = ir.createGetElementPointer(this.currentFunction.scratch_area, [consts.int32(0), consts.int64(i)], `arg_gep_${i}`);
ir.createStore(args[i], gep, `argv[${i}]-store`);
}
let argsCast = ir.createGetElementPointer(this.currentFunction.scratch_area, [consts.int32(0), consts.int64(0)], "call_args_load");
argv.push(argsCast);
}
else {
argv.push(consts.Null(types.EjsValue.pointerTo()));
}
argv.push(this.loadUndefinedEjsValue()); // %newTarget = undefined
}
else {
for (let a of args)
argv.push(this.visitOrNull(a));
}
return argv;
}
debugLog (str) {
if (this.options.debug_level > 0)
this.createCall(this.ejs_runtime.log, [consts.string(ir, str)], "");
}
visitArgsForConstruct (callee, args, this_loc, newTarget_loc) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
args = args.slice();
let argv = [];
// constructors are always .takes_builtins, so we can skip the other case
//
let ctor = this.visit(args[0]);
args.shift();
argv.push(ctor); // %closure
argv.push(this_loc); // %this
argv.push(consts.int32(args.length)); // %argc
if (args.length > 0) {
let visited = [];
for (let a of args)
visited.push(this.visitOrNull(a));
visited.forEach ((a,i) => {
let gep = ir.createGetElementPointer(this.currentFunction.scratch_area, [consts.int32(0), consts.int64(i)], `arg_gep_${i}`);
ir.createStore(a, gep, `argv[${i}]-store`);
});
let argsCast = ir.createGetElementPointer(this.currentFunction.scratch_area, [consts.int32(0), consts.int64(0)], "call_args_load");
argv.push(argsCast);
}
else {
argv.push(consts.Null(types.EjsValue.pointerTo()));
}
argv.push(newTarget_loc || ctor); // %newTarget = ctor
return argv;
}
visitCallExpression (n) {
debug.log ( () => `visitCall ${JSON.stringify(n)}` );
debug.log ( () => ` arguments length = ${n.arguments.length}`);
debug.log ( () => {
return n.arguments.map ( (a, i) => ` arguments[${i}] = ${JSON.stringify(a)}` ).join('');
});
let unescapedName = n.callee.name.slice(1);
let intrinsicHandler = this.ejs_intrinsics[unescapedName];
if (!intrinsicHandler)
throw new Error(`Internal error: callee should not be null in visitCallExpression (callee = '${n.callee.name}', arguments = ${n.arguments.length})`);
return intrinsicHandler.call(this, n, this.opencode_intrinsics[unescapedName]);
}
visitThisExpression (n) {
debug.log("visitThisExpression");
return this.createLoad(this.createLoad(this.findIdentifierInScope("%this"), "load_this_ptr"), "load_this");
}
visitSpreadElement (n) {
throw new Error("halp");
}
visitIdentifier (n) {
let rv;
debug.log ( () => `identifier ${n.name}` );
let val = n.name;
let source = this.findIdentifierInScope(val);
if (source) {
debug.log ( () => `found identifier in scope, at ${source}` );
rv = this.createLoad(source, `load_${val}`);
return rv;
}
// special handling of the arguments object here, so we
// only initialize/create it if the function is
// actually going to use it.
if (val === "arguments") {
let arguments_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "local_arguments_object");
let saved_insert_point = ir.getInsertBlock();
ir.setInsertPoint(this.currentFunction.entry_bb);
let load_argc = this.createLoad(this.currentFunction.topScope.get("%argc"), "argc_load");
let load_args = this.createLoad(this.currentFunction.topScope.get("%args"), "args_load");
let args_new = this.ejs_runtime.arguments_new;
let arguments_object = this.createCall(args_new, [load_argc, load_args], "argstmp", !args_new.doesNotThrow);
ir.createStore(arguments_object, arguments_alloca);
this.currentFunction.topScope.set("arguments", arguments_alloca);
ir.setInsertPoint(saved_insert_point);
return this.createLoad(arguments_alloca, "load_arguments");
}
rv = null;
debug.log ( () => `calling getFunction for ${val}` );
rv = this.module.getFunction(val);
if (!rv) {
debug.log ( () => `Symbol '${val}' not found in current scope` );
rv = this.loadGlobal(n);
}
debug.log ( () => `returning ${rv}` );
return rv;
}
visitObjectExpression (n) {
let obj_proto = ir.createLoad(this.ejs_globals.Object_prototype, "load_objproto");
let object_create = this.ejs_runtime.object_create;
let obj = this.createCall(object_create, [obj_proto], "objtmp", !object_create.doesNotThrow);
let accessor_map = new Map();
// gather all properties so we can emit get+set as a single call to define_accessor_prop.
for (let property of n.properties) {
if (property.kind === "get" || property.kind === "set") {
if (!accessor_map.has(property.key)) accessor_map.set(property.key, new Map);
if (accessor_map.get(property.key).has(property.kind))
throw new SyntaxError(`a '${property.kind}' method for '${escodegenerate(property.key)}' has already been defined.`);
if (accessor_map.get(property.key).has("init"))
throw new SyntaxError(`${property.key.loc.start.line}: property name ${escodegenerate(property.key)} appears once in object literal.`);
}
else if (property.kind === "init") {
if (accessor_map.get(property.key))
throw new SyntaxError(`${property.key.loc.start.line}: property name ${escodegenerate(property.key)} appears once in object literal.`);
accessor_map.set(property.key, new Map);
}
else {
throw new Error(`unrecognized property kind '${property.kind}'`);
}
if (property.computed) {
accessor_map.get(property.key).set("computed", true);
}
accessor_map.get(property.key).set(property.kind, property);
}
accessor_map.forEach ((prop_map, propkey) => {
// XXX we need something like this line below to handle computed properties, but those are broken at the moment
//key = if property.key.type is Identifier then this.getAtom property.key.name else this.visit property.key
if (prop_map.has("computed"))
propkey = this.visit(propkey);
else if (propkey.type == b.Literal)
propkey = this.getAtom(String(propkey.value));
else if (propkey.type === b.Identifier)
propkey = this.getAtom(propkey.name);
if (prop_map.has("init")) {
let val = this.visit(prop_map.get("init").value);
this.createCall(this.ejs_runtime.object_define_value_prop, [obj, propkey, val, consts.int32(0x77)], `define_value_prop_${propkey}`);
}
else {
let getter = prop_map.get("get");
let setter = prop_map.get("set");
let get_method = getter ? this.visit(getter.value) : this.loadUndefinedEjsValue();
let set_method = setter ? this.visit(setter.value) : this.loadUndefinedEjsValue();
this.createCall(this.ejs_runtime.object_define_accessor_prop, [obj, propkey, get_method, set_method, consts.int32(0x19)], `define_accessor_prop_${propkey}`);
}
});
return obj;
}
visitArrayExpression (n) {
let force_fill = false;
// if there are holes, we need to fill the array at allocation time.
// FIXME(toshok) we could just as easily have the compiler emit code to initialize the holes as well, right?
for (let el of n.elements) {
if (el == null) {
force_fill = true;
break;
}
}
let obj = this.createCall(this.ejs_runtime.array_new, [consts.int32(n.elements.length), consts.bool(force_fill)], "arrtmp", !this.ejs_runtime.array_new.doesNotThrow);
let i = 0;
for (let el of n.elements) {
// don't create property stores for array holes
if (el == null) continue;
let val = this.visit(el);
let index = { type: b.Literal, value: i };
this.createPropertyStore(obj, index, val, true);
i = i + 1;
}
return obj;
}
visitExpressionStatement (n) {
n.expression.result_not_used = true;
return this.visit(n.expression);
}
generateUCS2 (id, jsstr) {
let ucsArrayType = llvm.ArrayType.get(types.JSChar, jsstr.length+1);
let array_data = [];
for (let i = 0, e = jsstr.length; i < e; i ++)
array_data.push(consts.jschar(jsstr.charCodeAt(i)));
array_data.push(consts.jschar(0));
let array = llvm.ConstantArray.get(ucsArrayType, array_data);
let arrayglobal = new llvm.GlobalVariable(this.module, ucsArrayType, `ucs2-${id}`, array, false);
arrayglobal.setAlignment(8);
return arrayglobal;
}
generateEJSPrimString (id, len) {
let strglobal = new llvm.GlobalVariable(this.module, types.EjsPrimString, `primstring-${id}`, llvm.Constant.getAggregateZero(types.EjsPrimString), false);
strglobal.setAlignment(8);
return strglobal;
}
generateEJSValueForString (id) {
let name = `ejsval-${id}`;
let strglobal = new llvm.GlobalVariable(this.module, types.EjsValue, name, llvm.Constant.getAggregateZero(types.EjsValue), false);
strglobal.setAlignment(8);
let val = this.module.getOrInsertGlobal(name, types.EjsValue);
val.setAlignment(8);
return val;
}
addStringLiteralInitialization (name, ucs2, primstr, val, len) {
let saved_insert_point = ir.getInsertBlock();
ir.setInsertPointStartBB(this.literalInitializationBB);
let saved_debug_loc;
if (this.options.debug) {
saved_debug_loc = ir.getCurrentDebugLocation();
ir.setCurrentDebugLocation(llvm.DebugLoc.get(0, 0, this.literalInitializationDebugInfo));
}
let strname = consts.string(ir, name);
let arg0 = strname;
let arg1 = val;
let arg2 = primstr;
let arg3 = ir.createInBoundsGetElementPointer(ucs2, [consts.int32(0), consts.int32(0)], "ucs2");
ir.createCall(this.ejs_runtime.init_string_literal, [arg0, arg1, arg2, arg3, consts.int32(len)], "");
ir.setInsertPoint(saved_insert_point);
if (this.options.debug)
ir.setCurrentDebugLocation(saved_debug_loc);
}
getAtom (str) {
// check if it's an atom (a runtime library constant) first of all
if (hasOwn.call(this.ejs_atoms, str))
return this.createLoad(this.ejs_atoms[str], `${str}_atom_load`);
// if it's not, we create a constant and embed it in this module
if (!this.module_atoms.has(str)) {
let literalId = this.idgen();
let ucs2_data = this.generateUCS2(literalId, str);
let primstring = this.generateEJSPrimString(literalId, str.length);
let ejsval = this.generateEJSValueForString(str);
this.module_atoms.set(str, ejsval);
this.addStringLiteralInitialization(str, ucs2_data, primstring, ejsval, str.length);
}
return this.createLoad(this.module_atoms.get(str), "literal_load");
}
visitLiteral (n) {
// null literals, load _ejs_null
if (n.value === null) {
debug.log("literal: null");
return this.loadNullEjsValue();
}
// undefined literals, load _ejs_undefined
if (n.value === undefined) {
debug.log("literal: undefined");
return this.loadUndefinedEjsValue();
}
// string literals
if (typeof n.raw === "string" && (n.raw[0] === '"' || n.raw[0] === "'")) {
debug.log ( () => `literal string: ${n.value}` );
var strload = this.getAtom(n.value);
strload.literal = n;
debug.log ( () => `strload = ${strload}` );
return strload;
}
// regular expression literals
if (typeof n.raw === "string" && n.raw[0] === '/') {
debug.log ( () => `literal regexp: ${n.raw}` );
let source = consts.string(ir, n.value.source);
let flags = consts.string(ir, `${n.value.global ? 'g' : ''}${n.value.multiline ? 'm' : ''}${n.value.ignoreCase ? 'i' : ''}`);
let regexp_new_utf8 = this.ejs_runtime.regexp_new_utf8;
var regexpcall = this.createCall(regexp_new_utf8, [source, flags], "regexptmp", !regexp_new_utf8.doesNotThrow);
debug.log ( () => `regexpcall = ${regexpcall}` );
return regexpcall;
}
// number literals
if (typeof n.value === "number") {
debug.log ( () => `literal number: ${n.value}` );
return this.loadDoubleEjsValue(n.value);
}
// boolean literals
if (typeof n.value === "boolean") {
debug.log ( () => `literal boolean: ${n.value}` );
return this.loadBoolEjsValue(n.value);
}
throw `Internal error: unrecognized literal of type ${typeof n.value}`;
}
createCall (callee, argv, callname, canThrow=true) {
// if we're inside a try block we have to use createInvoke, and pass two basic blocks:
// the normal block, which is basically this IR instruction's continuation
// the unwind block, where we land if the call throws an exception.
//
// Although for builtins we know won't throw, we can still use createCall.
let calltmp;
if (TryExitableScope.unwindStack.depth === 0 || callee.doesNotThrow || !canThrow) {
//ir.createCall this.ejs_runtime.log, [consts.string(ir, `calling ${callee.name}`)], ""
calltmp = this.abi.createCall(this.currentFunction, callee, argv, callname);
}
else {
let normal_block = new llvm.BasicBlock ("normal", this.currentFunction);
//ir.createCall this.ejs_runtime.log, [consts.string(ir, `invoking ${callee.name}`)], ""
calltmp = this.abi.createInvoke(this.currentFunction, callee, argv, normal_block, TryExitableScope.unwindStack.top.getLandingPadBlock(), callname);
// after we've made our call we need to change the insertion point to our continuation
ir.setInsertPoint(normal_block);
}
return calltmp;
}
visitThrow (n) {
let arg = this.visit(n.argument);
this.createCall(this.ejs_runtime.throw, [arg], "", true);
return ir.createUnreachable();
}
visitTry (n) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let finally_block = null;
let catch_block = null;
// the alloca that stores the reason we ended up in the finally block
if (!this.currentFunction.cleanup_reason)
this.currentFunction.cleanup_reason = this.createAlloca(this.currentFunction, types.Int32, "cleanup_reason");
// if we have a finally clause, create finally_block
if (n.finalizer) {
finally_block = new llvm.BasicBlock ("finally_bb", insertFunc);
this.finallyStack.unshift (finally_block);
}
// the merge bb where everything branches to after falling off the end of a catch/finally block
let merge_block = new llvm.BasicBlock ("try_merge", insertFunc);
let branch_target = finally_block ? finally_block : merge_block;
let scope = new TryExitableScope(this.currentFunction.cleanup_reason, branch_target, (() => new llvm.BasicBlock("exception", insertFunc)), finally_block != null);
this.doInsideExitableScope (scope, () => {
scope.enterTry();
this.visit(n.block);
if (n.finalizer)
this.finallyStack.shift();
// at the end of the try block branch to our branch_target (either the finally block or the merge block after the try{}) with REASON_FALLOFF
scope.exitAft(false);
scope.leaveTry();
});
if (scope.landing_pad_block && n.handlers.length > 0)
catch_block = new llvm.BasicBlock ("catch_bb", insertFunc);
if (scope.landing_pad_block) {
// the scope's landingpad block is created if needed by this.createCall (using that function we pass in as the last argument to TryExitableScope's ctor.)
// if a try block includes no calls, there's no need for an landing pad block as nothing can throw, and we don't bother generating any code for the
// catch clause.
this.doInsideBBlock (scope.landing_pad_block, () => {
let landing_pad_type = llvm.StructType.create("", [types.Int8Pointer, types.Int32]);
// XXX is it an error to have multiple catch handlers, as JS doesn't allow you to filter by type?
let clause_count = n.handlers.length > 0 ? 1 : 0;
let casted_personality = ir.createPointerCast(this.ejs_runtime.personality, types.Int8Pointer, "personality");
let caught_result = ir.createLandingPad(landing_pad_type, casted_personality, clause_count, "caught_result");
caught_result.addClause(ir.createPointerCast(this.ejs_runtime.exception_typeinfo, types.Int8Pointer, ""));
caught_result.setCleanup(true);
let exception = ir.createExtractValue(caught_result, 0, "exception");
if (catch_block)
ir.createBr(catch_block);
else if (finally_block)
ir.createBr(finally_block);
else
throw "this shouldn't happen. a try{} without either a catch{} or finally{}";
// if we have a catch clause, create catch_bb
if (n.handlers.length > 0) {
this.doInsideBBlock (catch_block, () => {
// call _ejs_begin_catch to return the actual exception
let catchval = this.beginCatch(exception);
// create a new scope which maps the catch parameter name (the "e" in "try { } catch (e) { }") to catchval
let catch_scope = new Map;
if (n.handlers[0].param && n.handlers[0].param.name) {
let catch_name = n.handlers[0].param.name;
let alloca = this.createAlloca(this.currentFunction, types.EjsValue, `local_catch_${catch_name}`);
catch_scope.set(catch_name, alloca);
ir.createStore(catchval, alloca);
}
if (n.finalizer)
this.finallyStack.unshift(finally_block);
this.doInsideExitableScope(scope, () => {
this.visitWithScope(catch_scope, [n.handlers[0]]);
});
// unsure about this one - we should likely call end_catch if another exception is thrown from the catch block?
this.endCatch();
if (n.finalizer)
this.finallyStack.shift();
// at the end of the catch block branch to our branch_target (either the finally block or the merge block after the try{}) with REASON_FALLOFF
scope.exitAft(false);
});
}
});
}
// Finally Block
if (n.finalizer) {
this.doInsideBBlock (finally_block, () => {
this.visit(n.finalizer);
let cleanup_reason = this.createLoad(this.currentFunction.cleanup_reason, "cleanup_reason_load");
let return_tramp = null;
if (this.currentFunction.returnValueAlloca) {
return_tramp = new llvm.BasicBlock ("return_tramp", insertFunc);
this.doInsideBBlock (return_tramp, () => {
if (this.finallyStack.length > 0) {
ir.createStore(consts.int32(ExitableScope.REASON_RETURN), this.currentFunction.cleanup_reason);
ir.createBr(this.finallyStack[0]);
}
else {
this.createRet(this.createLoad(this.currentFunction.returnValueAlloca, "rv"));
}
});
}
let switch_stmt = ir.createSwitch(cleanup_reason, merge_block, scope.destinations.length + 1);
if (this.currentFunction.returnValueAlloca)
switch_stmt.addCase(consts.int32(ExitableScope.REASON_RETURN), return_tramp);
let falloff_tramp = new llvm.BasicBlock("falloff_tramp", insertFunc);
this.doInsideBBlock (falloff_tramp, () => {
ir.createBr(merge_block);
});
switch_stmt.addCase(consts.int32(TryExitableScope.REASON_FALLOFF_TRY), falloff_tramp);
for (let s = 0, e = scope.destinations.length; s < e; s ++) {
let dest_tramp = new llvm.BasicBlock("dest_tramp", insertFunc);
var dest = scope.destinations[s];
this.doInsideBBlock (dest_tramp, () => {
if (dest.reason == TryExitableScope.REASON_BREAK)
dest.scope.exitAft(true);
else if (dest.reason == TryExitableScope.REASON_CONTINUE)
dest.scope.exitFore();
});
switch_stmt.addCase(dest.id, dest_tramp);
}
});
}
ir.setInsertPoint(merge_block);
}
handleTemplateDefaultHandlerCall (exp, opencode) {
// we should probably only inline the construction of the string if substitutions.length < $some-number
let cooked_strings = exp.arguments[0].elements;
let substitutions = exp.arguments[1].elements;
let cooked_i = 0;
let sub_i = 0;
let strval = null;
let concat_string = (s) => {
if (!strval)
strval = s;
else
strval = this.createCall(this.ejs_runtime.string_concat, [strval, s], "strconcat");
};
while (cooked_i < cooked_strings.length) {
let c = cooked_strings[cooked_i];
cooked_i += 1;
if (c.length !== 0)
concat_string(this.getAtom(c.value));
if (sub_i < substitutions.length) {
let sub = this.visit(substitutions[sub_i]);
concat_string(this.createCall(this.ejs_runtime.ToString, [sub], "subToString"));
sub_i += 1;
}
}
return strval;
}
handleTemplateCallsite (exp, opencode) {
// we expect to be called with context something of the form:
//
// function generate_callsiteId0 () {
// %templateCallsite(%callsiteId_0,
// [], // raw
// [] // cooked
// });
// }
//
// and we need to generate something along the lines of:
//
// global const %callsiteId_0 = null; // an llvm IR construct
//
// function generate_callsiteId0 () {
// if (!%callsiteId_0) {
// _ejs_gc_add_root(&%callsiteId_0);
// %callsiteId_0 = []; // cooked
// %callsiteId_0.raw = [];
// %callsiteId_0.freeze();
// }
// return callsiteId_0;
// }
//
// our containing function already exists, so we just
// need to replace the intrinsic with the new contents.
//
// XXX there's no reason to dynamically create the
// callsite, other than it being easier for now. The
// callsite id's structure is known at compile time so
// everything could be allocated from the data segment
// and just used from there (much the same way we do
// with string literals.)
let callsite_id = exp.arguments[0].value;
let callsite_raw_literal = exp.arguments[1];
let callsite_cooked_literal = exp.arguments[2];
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let then_bb = new llvm.BasicBlock ("then", insertFunc);
let merge_bb = new llvm.BasicBlock ("merge", insertFunc);
let callsite_alloca = this.createAlloca(this.currentFunction, types.EjsValue, `local_${callsite_id}`);
let callsite_global = new llvm.GlobalVariable(this.module, types.EjsValue, callsite_id, llvm.Constant.getAggregateZero(types.EjsValue), false);
let global_callsite_load = this.createLoad(callsite_global, "load_global_callsite");
ir.createStore(global_callsite_load, callsite_alloca);
let callsite_load = ir.createLoad(callsite_alloca, "load_local_callsite");
let isnull = this.isNumber(callsite_load);
ir.createCondBr(isnull, then_bb, merge_bb);
this.doInsideBBlock (then_bb, () => {
this.createCall(this.ejs_runtime.gc_add_root, [callsite_global], "");
// XXX missing: register callsite_obj gc root
let callsite_cooked = this.visit(callsite_cooked_literal);
let callsite_raw = this.visit(callsite_raw_literal);
let frozen_raw = this.createCall(this.ejs_runtime.object_freeze, [callsite_raw], "frozen_raw");
this.createCall(this.ejs_runtime.object_setprop, [callsite_cooked, this.visit(b.literal("raw")), frozen_raw], "propstore_raw");
let frozen_cooked = this.createCall(this.ejs_runtime.object_freeze, [callsite_cooked], "frozen_cooked");
ir.createStore(frozen_cooked, callsite_global);
ir.createStore(frozen_cooked, callsite_alloca);
ir.createBr(merge_bb);
});
ir.setInsertPoint(merge_bb);
return this.createRet(ir.createLoad(callsite_alloca, "load_local_callsite"));
}
handleModuleGet (exp, opencode) {
let moduleString = this.visit(exp.arguments[0].value);
return this.createCall(this.ejs_runtime.module_get, [moduleString], "moduletmp");
}
handleModuleSlotRef (exp, opencode) {
let moduleString = exp.arguments[0].value;
let exportId = exp.arguments[1].value;
let module_global;
if (moduleString.endsWith(".js"))
moduleString = moduleString.substring(0, moduleString.length-3);
if (moduleString === this.this_module_info.path) {
module_global = this.this_module_global;
}
else {
module_global = this.import_module_globals.get(moduleString);
}
module_global = ir.createPointerCast(module_global, types.EjsModule.pointerTo(), "");
let slotnum = this.allModules.get(moduleString).exports.get(exportId).slot_num;
if (opencode && this.options.target_pointer_size === 64) {
return ir.createInBoundsGetElementPointer(module_global, [consts.int64(0), consts.int32(3), consts.int64(slotnum)], "slot_ref");
}
else {
return this.createCall(this.ejs_runtime.module_get_slot_ref, [module_global, consts.int32(slotnum)], "module_slot");
}
}
handleModuleGetSlot (exp, opencode) {
let slot_ref = this.handleModuleSlotRef(exp, opencode);
return ir.createLoad(slot_ref, "module_slot_load");
}
handleModuleSetSlot (exp, opencode) {
let arg = exp.arguments[2];
let slot_ref = this.handleModuleSlotRef(exp, opencode);
this.storeToDest(slot_ref, arg);
return ir.createLoad(slot_ref, "load_slot"); // do we need this? we don't need to keep assignment expression semantics for this
}
handleModuleGetExotic (exp, opencode) {
/*
let moduleString = exp.arguments[0].value;
if (moduleString === this.this_module_info.path) {
let module_global = this.this_module_global;
return this.emitEjsvalFromPtr(module_global, "exotic");
}
else if (this.import_module_globals.has(moduleString)) {
let module_global = this.import_module_globals.get(moduleString)
return this.emitEjsvalFromPtr(module_global, "exotic");
}
else {
*/
return this.createCall(this.ejs_runtime.module_get, [this.visit(exp.arguments[0])], "get_module_exotic");
/*
}
*/
}
handleGetArg (exp, opencode) {
let load_args = this.createLoad(this.currentFunction.topScope.get("%args"), "args_load");
let arg_i = exp.arguments[0].value;
let arg_ptr = ir.createGetElementPointer(load_args, [consts.int32(arg_i)], `arg${arg_i}_ptr`);
return this.createLoad(arg_ptr, `arg${arg_i}`);
}
handleGetNewTarget (exp, opencode) {
return this.createLoad(this.findIdentifierInScope("%newTarget"), "new_target_load");
}
handleGetArgumentsObject (exp, opencode) {
let arguments_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "local_arguments_object");
let saved_insert_point = ir.getInsertBlock();
ir.setInsertPoint(this.currentFunction.entry_bb);
let load_argc = this.createLoad(this.currentFunction.topScope.get("%argc"), "argc_load");
let load_args = this.createLoad(this.currentFunction.topScope.get("%args"), "args_load");
let args_new = this.ejs_runtime.arguments_new;
let arguments_object = this.createCall(args_new, [load_argc, load_args], "argstmp", !args_new.doesNotThrow);
ir.createStore(arguments_object, arguments_alloca);
this.currentFunction.topScope.set("arguments", arguments_alloca);
ir.setInsertPoint(saved_insert_point);
return this.createLoad(arguments_alloca, "load_arguments");
}
handleGetLocal (exp, opencode) { return this.createLoad(this.findIdentifierInScope(exp.arguments[0].name), `load_${exp.arguments[0].name}`); }
handleGetGlobal (exp, opencode) { return this.loadGlobal(exp.arguments[0]); }
handleSetLocal (exp, opencode) {
let dest = this.findIdentifierInScope(exp.arguments[0].name);
if (!dest)
throw new Error(`identifier not found: ${exp.arguments[0].name}`);
let arg = exp.arguments[1];
this.storeToDest(dest, arg);
return ir.createLoad(dest, "load_val");
}
handleSetGlobal (exp, opencode) {
let gname = exp.arguments[0].name;
if (this.options.frozen_global)
throw new SyntaxError(`cannot set global property '${exp.arguments[0].name}' when using --frozen-global`);
let gatom = this.getAtom(gname);
let value = this.visit(exp.arguments[1]);
return this.createCall(this.ejs_runtime.global_setprop, [gatom, value], `globalpropstore_${gname}`);
}
// this method assumes it's called in an opencoded context
emitEjsvalTo (val, type, prefix) {
if (this.options.target_pointer_size === 64) {
let payload = this.createEjsvalAnd(val, consts.int64_lowhi(0x7fff, 0xffffffff), `${prefix}_payload`);
return ir.createIntToPtr(payload, type, `${prefix}_load`);
}
else {
throw new Error("emitEjsvalTo not implemented for this case");
}
}
emitEjsvalFromPtr (ptr, prefix) {
if (this.options.target_pointer_size === 64) {
let fromptr_alloca = this.createAlloca(this.currentFunction, types.EjsValue, `${prefix}_ejsval`);
let intval = ir.createPtrToInt(ptr, types.Int64, `${prefix}_intval`);
let payload = ir.createOr(intval, consts.int64_lowhi(0xFFFC0000, 0x00000000), `${prefix}_payload`);
let alloca_as_int64 = ir.createBitCast(fromptr_alloca, types.Int64.pointerTo(), `${prefix}_alloca_asptr`);
ir.createStore(payload, alloca_as_int64, `${prefix}_store`);
ir.createLoad(fromptr_alloca, `${prefix}_load`);
}
else {
throw new Error("emitEjsvalTo not implemented for this case");
}
}
emitEjsvalToObjectPtr (val) {
return this.emitEjsvalTo(val, types.EjsObject.pointerTo(), "to_objectptr");
}
emitEjsvalToClosureEnvPtr (val) {
return this.emitEjsvalTo(val, types.EjsClosureEnv.pointerTo(), "to_ptr");
}
// this method assumes it's called in an opencoded context
emitLoadSpecops (obj) {
if (this.options.target_pointer_size === 64) {
// %1 = getelementptr inbounds %struct._EJSObject* %obj, i64 0, i32 1
// %specops_load = load %struct.EJSSpecOps** %1, align 8, !tbaa !0
let specops_slot = ir.createInBoundsGetElementPointer(obj, [consts.int64(0), consts.int32(1)], "specops_slot");
return ir.createLoad(specops_slot, "specops_load");
}
else {
throw new Error("emitLoadSpecops not implemented for this case");
}
}
emitThrowNativeError (errorCode, errorMessage) {
this.createCall(this.ejs_runtime.throw_nativeerror_utf8, [consts.int32(errorCode), consts.string(ir, errorMessage)], "", true);
return ir.createUnreachable();
}
// this method assumes it's called in an opencoded context
emitLoadEjsFunctionClosureFunc (closure) {
if (this.options.target_pointer_size === 64) {
let func_slot_gep = ir.createInBoundsGetElementPointer(closure, [consts.int64(1)], "func_slot_gep");
let func_slot = ir.createBitCast(func_slot_gep, this.abi.createFunctionType(types.EjsValue, [types.EjsValue, types.EjsValue, types.Int32, types.EjsValue.pointerTo()]).pointerTo().pointerTo(), "func_slot");
return ir.createLoad(func_slot, "func_load");
}
else {
throw new Error("emitLoadEjsFunctionClosureFunc not implemented for this case");
}
}
// this method assumes it's called in an opencoded context
emitLoadEjsFunctionClosureEnv (closure) {
if (this.options.target_pointer_size === 64) {
let env_slot_gep = ir.createInBoundsGetElementPointer(closure, [consts.int64(1), consts.int32(1)], "env_slot_gep");
let env_slot = ir.createBitCast(env_slot_gep, types.EjsValue.pointerTo(), "env_slot");
return ir.createLoad(env_slot, "env_load");
}
else {
throw new Error("emitLoadEjsFunctionClosureEnv not implemented for this case");
}
}
handleInvokeClosure (exp, opencode) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
if (!this.currentFunction.scratch_area) {
throw new Error(`Internal error: function has no scratch space and makes a [[Call]] call with ${exp.arguments.length} arguments`);
}
let argv = this.visitArgsForCall(this.ejs_runtime.invoke_closure, true, exp.arguments);
if (opencode && this.options.target_pointer_size === 64) {
//
// generate basically the following code:
//
// f = argv[0]
// if (EJSVAL_IS_FUNCTION(F)
// f->func(f->env, argv[1], argv[2], argv[3])
// else
// _ejs_invoke_closure(...argv)
//
let candidate_is_object_bb = new llvm.BasicBlock ("candidate_is_object_bb", insertFunc);
var direct_invoke_bb = new llvm.BasicBlock ("direct_invoke_bb", insertFunc);
var runtime_invoke_bb = new llvm.BasicBlock ("runtime_invoke_bb", insertFunc);
var invoke_merge_bb = new llvm.BasicBlock ("invoke_merge_bb", insertFunc);
let cmp = this.isObject(argv[0]);
ir.createCondBr(cmp, candidate_is_object_bb, runtime_invoke_bb);
var call_result_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "call_result");
this.doInsideBBlock (candidate_is_object_bb, () => {
let closure = this.emitEjsvalToObjectPtr(argv[0]);
let cmp = this.isObjectFunction(closure);
ir.createCondBr(cmp, direct_invoke_bb, runtime_invoke_bb);
// in the successful case we modify our argv with the responses and directly invoke the closure func
this.doInsideBBlock (direct_invoke_bb, () => {
let func_load = this.emitLoadEjsFunctionClosureFunc(closure);
let env_load = this.emitLoadEjsFunctionClosureEnv(closure);
let direct_call_result = this.createCall(func_load, [env_load, argv[1], argv[2], argv[3], argv[4], argv[5]], "callresult");
ir.createStore(direct_call_result, call_result_alloca);
ir.createBr(invoke_merge_bb);
});
this.doInsideBBlock (runtime_invoke_bb, () => {
let runtime_call_result = this.createCall(this.ejs_runtime.invoke_closure, argv, "callresult", true);
ir.createStore(runtime_call_result, call_result_alloca);
ir.createBr(invoke_merge_bb);
});
});
ir.setInsertPoint(invoke_merge_bb);
return ir.createLoad(call_result_alloca, "call_result_load");
}
else {
return this.createCall(this.ejs_runtime.invoke_closure, argv, "call", true);
}
}
handleConstructClosure (exp, opencode) {
let this_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "this_alloca");
this.storeUndefined(this_alloca, "store_undefined_this");
if (!this.currentFunction.scratch_area) {
throw new Error(`Internal error: function has no scratch space and makes a [[Construct]] call with ${exp.arguments.length} arguments`);
}
let argv = this.visitArgsForConstruct(this.ejs_runtime.construct_closure, exp.arguments, this_alloca);
return this.createCall(this.ejs_runtime.construct_closure, argv, "construct", true);
}
handleConstructSuper (exp, opencode) {
let this_ptr = this.createLoad(this.findIdentifierInScope("%this"), "this_ptr");
let newTarget = this.createLoad(this.findIdentifierInScope("%newTarget"), "load_newTarget");
let argv = this.visitArgsForConstruct(this.ejs_runtime.construct_closure, exp.arguments, this_ptr, newTarget);
return this.createCall(this.ejs_runtime.construct_closure, argv, "construct_super", true);
}
handleConstructSuperApply (exp, opencode) {
let this_ptr = this.createLoad(this.findIdentifierInScope("%this"), "this_ptr");
let newTarget = this.createLoad(this.findIdentifierInScope("%newTarget"), "load_newTarget");
let argv = this.visitArgsForConstruct(this.ejs_runtime.construct_closure_apply, exp.arguments, this_ptr, newTarget);
return this.createCall(this.ejs_runtime.construct_closure_apply, argv, "construct_super_apply", true);
}
handleSetConstructorKindDerived (exp, opencode) {
let ctor = this.visit(exp.arguments[0]);
return this.createCall(this.ejs_runtime.set_constructor_kind_derived, [ctor], "");
}
handleSetConstructorKindBase (exp, opencode) {
let ctor = this.visit(exp.arguments[0]);
return this.createCall(this.ejs_runtime.set_constructor_kind_base, [ctor], "");
}
handleMakeGenerator (exp, opencode) {
let argv = this.visitArgsForCall(this.ejs_runtime.make_generator, false, exp.arguments);
return this.createCall(this.ejs_runtime.make_generator, argv, "generator");
}
handleGeneratorYield (exp, opencode) {
let argv = this.visitArgsForCall(this.ejs_runtime.generator_yield, false, exp.arguments);
return this.createCall(this.ejs_runtime.generator_yield, argv, "yield");
}
handleMakeClosure (exp, opencode) {
let argv = this.visitArgsForCall(this.ejs_runtime.make_closure, false, exp.arguments);
return this.createCall(this.ejs_runtime.make_closure, argv, "closure_tmp");
}
handleMakeClosureNoEnv (exp, opencode) {
let argv = this.visitArgsForCall(this.ejs_runtime.make_closure_noenv, false, exp.arguments);
return this.createCall(this.ejs_runtime.make_closure_noenv, argv, "closure_tmp");
}
handleMakeAnonClosure (exp, opencode) {
let argv = this.visitArgsForCall(this.ejs_runtime.make_anon_closure, false, exp.arguments);
return this.createCall(this.ejs_runtime.make_anon_closure, argv, "closure_tmp");
}
handleCreateArgScratchArea (exp, opencode) {
let argsArrayType = llvm.ArrayType.get(types.EjsValue, exp.arguments[0].value);
this.currentFunction.scratch_length = exp.arguments[0].value;
this.currentFunction.scratch_area = this.createAlloca(this.currentFunction, argsArrayType, "args_scratch_area");
this.currentFunction.scratch_area.setAlignment(8);
return this.currentFunction.scratch_area;
}
handleMakeClosureEnv (exp, opencode) {
let size = exp.arguments[0].value;
return this.createCall(this.ejs_runtime.make_closure_env, [consts.int32(size)], "env_tmp");
}
handleGetSlot (exp, opencode) {
//
// %ref = handleSlotRef
// %ret = load %EjsValueType* %ref, align 8
//
let slot_ref = this.handleSlotRef(exp, opencode);
return ir.createLoad(slot_ref, "slot_ref_load");
}
handleSetSlot (exp, opencode) {
let new_slot_val;
if (exp.arguments.length === 4)
new_slot_val = exp.arguments[3];
else
new_slot_val = exp.arguments[2];
let slotref = this.handleSlotRef(exp, opencode);
this.storeToDest(slotref, new_slot_val);
return ir.createLoad(slotref, "load_slot");
}
handleSlotRef (exp, opencode) {
let env = this.visitOrNull(exp.arguments[0]);
let slotnum = exp.arguments[1].value;
if (opencode && this.options.target_pointer_size === 64) {
let envp = this.emitEjsvalToClosureEnvPtr(env);
return ir.createInBoundsGetElementPointer(envp, [consts.int64(0), consts.int32(2), consts.int64(slotnum)], "slot_ref");
}
else {
return this.createCall(this.ejs_runtime.get_env_slot_ref, [env, consts.int32(slotnum)], "slot_ref_tmp", false);
}
}
createEjsBoolSelect (val, falseval = false) {
let rv = ir.createSelect(val, this.loadBoolEjsValue(!falseval), this.loadBoolEjsValue(falseval), "sel");
rv._ejs_returns_ejsval_bool = true;
return rv;
}
getEjsvalBits (arg) {
let bits_alloca;
if (this.currentFunction.bits_alloca)
bits_alloca = this.currentFunction.bits_alloca;
else
bits_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "bits_alloca");
ir.createStore(arg, bits_alloca);
let bits_ptr = ir.createBitCast(bits_alloca, types.Int64.pointerTo(), "bits_ptr");
if (!this.currentFunction.bits_alloca)
this.currentFunction.bits_alloca = bits_alloca;
return ir.createLoad(bits_ptr, "bits_load");
}
createEjsvalICmpUGt (arg, i64_const, name) { return ir.createICmpUGt(this.getEjsvalBits(arg), i64_const, name); }
createEjsvalICmpULt (arg, i64_const, name) { return ir.createICmpULt(this.getEjsvalBits(arg), i64_const, name); }
createEjsvalICmpEq (arg, i64_const, name) { return ir.createICmpEq (this.getEjsvalBits(arg), i64_const, name); }
createEjsvalAnd (arg, i64_const, name) { return ir.createAnd (this.getEjsvalBits(arg), i64_const, name); }
isObject (val) {
if (this.options.target_pointer_size === 64) {
return this.createEjsvalICmpUGt(val, consts.int64_lowhi(0xfffbffff, 0xffffffff), "cmpresult");
}
else {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffffffff, 0x00000000), "mask.i");
return ir.createICmpEq(mask, consts.int64_lowhi(0xffffff88, 0x00000000), "cmpresult");
}
}
isObjectFunction (obj) {
return ir.createICmpEq(this.emitLoadSpecops(obj), this.ejs_runtime.function_specops, "function_specops_cmp");
}
isObjectSymbol (obj) {
return ir.createICmpEq(this.emitLoadSpecops(obj), this.ejs_runtime.symbol_specops, "symbol_specops_cmp");
}
isString (val) {
if (this.options.target_pointer_size === 64) {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffff8000, 0x00000000), "mask.i");
return ir.createICmpEq(mask, consts.int64_lowhi(0xfffa8000, 0x00000000), "cmpresult");
}
else {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffffffff, 0x00000000), "mask.i");
return ir.createICmpEq(mask, consts.int64_lowhi(0xffffff85, 0x00000000), "cmpresult");
}
}
isNumber (val) {
if (this.options.target_pointer_size === 64) {
return this.createEjsvalICmpULt(val, consts.int64_lowhi(0xfff80001, 0x00000000), "cmpresult");
}
else {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffffffff, 0x00000000), "mask.i");
return ir.createICmpUlt(mask, consts.int64_lowhi(0xffffff81, 0x00000000), "cmpresult");
}
}
isBoolean (val) {
if (this.options.target_pointer_size === 64) {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffff8000, 0x00000000), "mask.i");
return ir.createICmpEq(mask, consts.int64_lowhi(0xfff98000, 0x00000000), "cmpresult");
}
else {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffffffff, 0x00000000), "mask.i");
return ir.createICmpEq(mask, consts.int64_lowhi(0xffffff83, 0x00000000), "cmpresult");
}
}
// these two could/should be changed to check for the specific bitpattern of _ejs_true/_ejs_false
isTrue (val) { return ir.createICmpEq(val, consts.ejsval_true(), "cmpresult"); }
isFalse (val) { return ir.createICmpEq(val, consts.ejsval_false(), "cmpresult"); }
isUndefined (val) {
if (this.options.target_pointer_size === 64) {
return this.createEjsvalICmpEq(val, consts.int64_lowhi(0xfff90000, 0x00000000), "cmpresult");
}
else {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffffffff, 0x00000000), "mask.i");
return ir.createICmpEq(mask, consts.int64_lowhi(0xffffff82, 0x00000000), "cmpresult");
}
}
isNull (val) {
if (this.options.target_pointer_size === 64) {
return this.createEjsvalICmpEq(val, consts.int64_lowhi(0xfffb8000, 0x00000000), "cmpresult");
}
else {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffffffff, 0x00000000), "mask.i");
return ir.createICmpEq(mask, consts.int64_lowhi(0xffffff87, 0x00000000), "cmpresult");
}
}
handleTypeofIsObject (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
return this.createEjsBoolSelect(this.isObject(arg));
}
handleTypeofIsFunction (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
if (opencode && this.options.target_pointer_size === 64) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
var typeofIsFunction_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "typeof_is_function");
var failure_bb = new llvm.BasicBlock ("typeof_function_false", insertFunc);
let is_object_bb = new llvm.BasicBlock ("typeof_function_is_object", insertFunc);
var success_bb = new llvm.BasicBlock ("typeof_function_true", insertFunc);
var merge_bb = new llvm.BasicBlock ("typeof_function_merge", insertFunc);
let cmp = this.isObject(arg, true);
ir.createCondBr(cmp, is_object_bb, failure_bb);
this.doInsideBBlock (is_object_bb, () => {
let obj = this.emitEjsvalToObjectPtr(arg);
let cmp = this.isObjectFunction(obj);
ir.createCondBr(cmp, success_bb, failure_bb);
});
this.doInsideBBlock (success_bb, () => {
this.storeBoolean(typeofIsFunction_alloca, true, "store_typeof");
ir.createBr(merge_bb);
});
this.doInsideBBlock (failure_bb, () => {
this.storeBoolean(typeofIsFunction_alloca, false, "store_typeof");
ir.createBr(merge_bb);
});
ir.setInsertPoint(merge_bb);
let rv = ir.createLoad(typeofIsFunction_alloca, "typeof_is_function");
rv._ejs_returns_ejsval_bool = true;
return rv;
}
else {
return this.createCall(this.ejs_runtime.typeof_is_function, [arg], "is_function", false);
}
}
handleTypeofIsSymbol (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
if (opencode && this.options.target_pointer_size === 64) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
var typeofIsSymbol_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "typeof_is_symbol");
var failure_bb = new llvm.BasicBlock ("typeof_symbol_false", insertFunc);
let is_object_bb = new llvm.BasicBlock ("typeof_symbol_is_object", insertFunc);
var success_bb = new llvm.BasicBlock ("typeof_symbol_true", insertFunc);
var merge_bb = new llvm.BasicBlock ("typeof_symbol_merge", insertFunc);
let cmp = this.isObject(arg, true);
ir.createCondBr(cmp, is_object_bb, failure_bb);
this.doInsideBBlock (is_object_bb, () => {
let obj = this.emitEjsvalToObjectPtr(arg);
let cmp = this.isObjectSymbol(obj);
ir.createCondBr(cmp, success_bb, failure_bb);
});
this.doInsideBBlock (success_bb, () => {
this.storeBoolean(typeofIsSymbol_alloca, true, "store_typeof");
ir.createBr(merge_bb);
});
this.doInsideBBlock (failure_bb, () => {
this.storeBoolean(typeofIsSymbol_alloca, false, "store_typeof");
ir.createBr(merge_bb);
});
ir.setInsertPoint(merge_bb);
let rv = ir.createLoad(typeofIsSymbol_alloca, "typeof_is_symbol");
rv._ejs_returns_ejsval_bool = true;
return rv;
}
else {
return this.createCall(this.ejs_runtime.typeof_is_symbol, [arg], "is_symbol", false);
}
}
handleTypeofIsString (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
return this.createEjsBoolSelect(this.isString(arg));
}
handleTypeofIsNumber (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
return this.createEjsBoolSelect(this.isNumber(arg));
}
handleTypeofIsBoolean (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
return this.createEjsBoolSelect(this.isBoolean(arg));
}
handleIsUndefined (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
return this.createEjsBoolSelect(this.isUndefined(arg));
}
handleIsNull (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
return this.createEjsBoolSelect(this.isNull(arg));
}
handleIsNullOrUndefined (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
if (opencode)
return this.createEjsBoolSelect(ir.createOr(this.isNull(arg), this.isUndefined(arg), "or"));
else
return this.createCall(this.ejs_binops["=="], [this.loadNullEjsValue(), arg], "is_null_or_undefined", false);
}
handleBuiltinUndefined (exp) { return this.loadUndefinedEjsValue(); }
handleSetPrototypeOf (exp) {
let obj = this.visitOrNull (exp.arguments[0]);
let proto = this.visitOrNull (exp.arguments[1]);
return this.createCall(this.ejs_runtime.object_set_prototype_of, [obj, proto], "set_prototype_of", true);
// we should check the return value of set_prototype_of
}
handleObjectCreate (exp) {
let proto = this.visitOrNull(exp.arguments[0]);
return this.createCall(this.ejs_runtime.object_create, [proto], "object_create", true);
// we should check the return value of object_create
}
handleArrayFromRest (exp) {
let rest_name = exp.arguments[0].value;
let formal_params_length = exp.arguments[1].value;
let has_rest_bb = new llvm.BasicBlock ("has_rest_bb", this.currentFunction);
let no_rest_bb = new llvm.BasicBlock ("no_rest_bb", this.currentFunction);
let rest_merge_bb = new llvm.BasicBlock ("rest_merge", this.currentFunction);
let rest_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "local_rest_object");
let load_argc = this.createLoad(this.currentFunction.topScope.get("%argc"), "argc_load");
let cmp = ir.createICmpSGt(load_argc, consts.int32(formal_params_length), "argcmpresult");
ir.createCondBr(cmp, has_rest_bb, no_rest_bb);
ir.setInsertPoint(has_rest_bb);
// we have > args than are declared, shove the rest into the rest parameter
let load_args = this.createLoad(this.currentFunction.topScope.get("%args"), "args_load");
let gep = ir.createInBoundsGetElementPointer(load_args, [consts.int32(formal_params_length)], "rest_arg_gep");
load_argc = ir.createNswSub(load_argc, consts.int32(formal_params_length));
let rest_value = this.createCall(this.ejs_runtime.array_new_copy, [load_argc, gep], "argstmp", !this.ejs_runtime.array_new_copy.doesNotThrow);
ir.createStore(rest_value, rest_alloca);
ir.createBr(rest_merge_bb);
ir.setInsertPoint(no_rest_bb);
// we have <= args than are declared, so the rest parameter is just an empty array
rest_value = this.createCall(this.ejs_runtime.array_new, [consts.int32(0), consts.False()], "arrtmp", !this.ejs_runtime.array_new.doesNotThrow);
ir.createStore(rest_value, rest_alloca);
ir.createBr(rest_merge_bb);
ir.setInsertPoint(rest_merge_bb);
this.currentFunction.topScope.set(rest_name, rest_alloca);
this.currentFunction.restArgPresent = true;
return ir.createLoad(rest_alloca, "load_rest");
}
handleArrayFromSpread (exp) {
let arg_count = exp.arguments.length;
if (this.currentFunction.scratch_area && this.currentFunction.scratch_length < arg_count) {
let spreadArrayType = llvm.ArrayType.get(types.EjsValue, arg_count);
this.currentFunction.scratch_area = this.createAlloca(this.currentFunction, spreadArrayType, "args_scratch_area");
this.currentFunction.scratch_area.setAlignment(8);
}
// reuse the scratch area
let spread_alloca = this.currentFunction.scratch_area;
let visited = [];
for (let a of exp.arguments)
visited.push(this.visitOrNull(a));
visited.forEach ((a, i) => {
let gep = ir.createGetElementPointer(spread_alloca, [consts.int32(0), consts.int64(i)], `spread_gep_${i}`);
ir.createStore(visited[i], gep, `spread[${i}]-store`);
});
let argsCast = ir.createGetElementPointer(spread_alloca, [consts.int32(0), consts.int64(0)], "spread_call_args_load");
let argv = [consts.int32(arg_count), argsCast];
return this.createCall(this.ejs_runtime.array_from_iterables, argv, "spread_arr");
}
handleArgPresent (exp) {
let arg_num = exp.arguments[0].value;
let load_argc = this.createLoad(this.currentFunction.topScope.get("%argc"), "argc_n_load");
let cmp = ir.createICmpUGE(load_argc, consts.int32(arg_num), "argcmpresult");
if (exp.arguments[1].value) {
// we have a default value for this parameter, so we also need to tell if the value is undefined
let has_slot_bb = new llvm.BasicBlock("has_slot_bb", this.currentFunction);
let has_arg_bb = new llvm.BasicBlock("has_arg_bb", this.currentFunction);
let no_arg_bb = new llvm.BasicBlock("no_arg_bb", this.currentFunction);
let merge_bb = new llvm.BasicBlock("arg_merge_bb", this.currentFunction);
let arg_present_alloca = this.createAlloca(this.currentFunction, types.Int1, `arg_${arg_num}_present`);
ir.createCondBr(cmp, has_slot_bb, no_arg_bb);
this.doInsideBBlock(has_slot_bb, () => {
// we actually have an arg slot for this number, so check if it's undefined
let load_args = this.createLoad(this.currentFunction.topScope.get("%args"), "args_load");
let arg_ptr = ir.createGetElementPointer(load_args, [consts.int32(arg_num-1)], `arg${arg_num}_ptr`);
let arg_load = this.createLoad(arg_ptr, `arg${arg_num}`);
let arg_is_undefined = this.isUndefined(arg_load);
ir.createCondBr(arg_is_undefined, no_arg_bb, has_arg_bb);
ir.createBr(has_arg_bb);
});
this.doInsideBBlock(has_arg_bb, () => {
// we have a slot and arg, win
ir.createStore(consts.int1(1), arg_present_alloca, "store_arg_present");
ir.createBr(merge_bb);
});
this.doInsideBBlock(no_arg_bb, () => {
// either we didn't have the slot, or the arg was undefined
ir.createStore(consts.int1(0), arg_present_alloca, "store_no_arg_present");
ir.createBr(merge_bb);
});
ir.setInsertPoint(merge_bb);
let load = ir.createLoad(arg_present_alloca, "load_arg_present");
cmp = ir.createICmpEq(load, consts.int1(1), "arg_present");
}
cmp._ejs_returns_native_bool = true;
return this.createEjsBoolSelect(cmp);
}
handleCreateIterResult (exp) {
let value = this.visit(exp.arguments[0]);
let done = this.visit(exp.arguments[1]);
return this.createCall(this.ejs_runtime.create_iter_result, [value, done], "iter_result");
}
handleCreateIteratorWrapper (exp) {
let iter = this.visit(exp.arguments[0]);
return this.createCall(this.ejs_runtime.iterator_wrapper_new, [iter], "iter_wrapper");
}
}
class AddFunctionsVisitor extends TreeVisitor {
constructor (module, abi, dibuilder, difile) {
super();
this.module = module;
this.abi = abi;
this.dibuilder = dibuilder;
this.difile = difile;
}
visitFunction (n) {
if (n && n.id && n.id.name)
n.ir_name = n.id.name;
else
n.ir_name = "_ejs_anonymous";
// at this point point n.params includes %env as its first param, and is followed by all the formal parameters from the original
// script source. we remove the %env parameter and save off he rest of the formal parameter names, and replace the list with
// our runtime parameters.
// remove %env from the formal parameter list, but save its name first
let env_name = n.params[0].name;
n.params.splice(0, 1);
// and store the JS formal parameters someplace else
n.formal_params = n.params;
n.params = [];
for (let param of this.abi.ejs_params)
n.params.push ({ type: b.Identifier, name: param.name, llvm_type: param.llvm_type });
n.params[this.abi.env_param_index].name = env_name;
// create the llvm IR function using our platform calling convention
n.ir_func = types.takes_builtins(this.abi.createFunction(this.module, n.ir_name, this.abi.ejs_return_type, n.params.map ( (param) => param.llvm_type )));
if (!n.toplevel) n.ir_func.setInternalLinkage();
let lineno = 0;
let col = 0;
if (n.loc) {
lineno = n.loc.start.line;
col = n.loc.start.column;
}
if (this.dibuilder && this.difile)
n.ir_func.debug_info = this.dibuilder.createFunction(this.difile, n.ir_name, n.displayName || n.ir_name, this.difile, lineno, false, true, lineno, 0, true, n.ir_func);
let ir_args = n.ir_func.args;
n.params.forEach( (param, i) => {
ir_args[i].setName(param.name);
});
// we don't need to recurse here since we won't have nested functions at this point
return n;
}
}
function sanitize_with_regexp (filename) {
return filename.replace(/[.,-\/\\]/g, "_"); // this is insanely inadequate
}
function insert_toplevel_func (tree, moduleInfo) {
let toplevel = {
type: b.FunctionDeclaration,
id: b.identifier(moduleInfo.toplevel_function_name),
displayName: "toplevel",
params: [],
defaults: [],
body: {
type: b.BlockStatement,
body: tree.body,
loc: {
start: {
line: 0,
column: 0
}
}
},
toplevel: true,
loc: {
start: {
line: 0,
column: 0
}
}
};
tree.body = [toplevel];
return tree;
}
export function compile (tree, base_output_filename, source_filename, module_infos, options) {
let abi = (options.target_arch === "armv7" || options.target_arch === "armv7s" || options.target_arch === "x86") ? new SRetABI() : new ABI();
let module_filename = source_filename;
if (module_filename.endsWith(".js"))
module_filename = module_filename.substring(0, module_filename.length-3);
let this_module_info = module_infos.get(module_filename);
tree = insert_toplevel_func(tree, this_module_info);
debug.log ( () => escodegenerate(tree) );
let toplevel_name = tree.body[0].id.name;
//debug.log 1, "before closure conversion"
//debug.log 1, -> escodegenerate tree
tree = closure_convert(tree, source_filename, module_infos, options);
debug.log (1, "after closure conversion" );
debug.log (1, () => escodegenerate(tree) );
/*
tree = typeinfer.run tree
debug.log 1, "after type inference"
debug.log 1, -> escodegenerate tree
*/
tree = optimizations.run(tree);
debug.log (1, "after optimization" );
debug.log (1, () => escodegenerate(tree) );
let module = new llvm.Module(base_output_filename);
module.toplevel_name = toplevel_name;
let module_accessors = [];
this_module_info.exports.forEach ((export_info, key) => {
let module_prop = undefined;
let f = this_module_info.getExportGetter(key);
if (f) {
if (!module_prop) module_prop = { key };
module_prop.getter = f;
tree.body.push(f);
}
f = this_module_info.getExportSetter(key);
if (f) {
if (!module_prop) module_prop = { key };
module_prop.setter = f;
tree.body.push(f);
}
if (module_prop)
module_accessors.push(module_prop);
});
let dibuilder;
let difile;
if (options.debug) {
dibuilder = new llvm.DIBuilder(module);
difile = dibuilder.createFile(source_filename + ".js", process.cwd());
dibuilder.createCompileUnit(source_filename + ".js", process.cwd(), "ejs", true, "", 2);
}
let visitor = new AddFunctionsVisitor(module, abi, dibuilder, difile);
tree = visitor.visit(tree);
debug.log ( () => escodegenerate(tree) );
visitor = new LLVMIRVisitor(module, source_filename, options, abi, module_infos, this_module_info, dibuilder, difile);
if (options.debug)
dibuilder.finalize();
visitor.emitModuleInfo();
visitor.visit(tree);
visitor.emitModuleResolution(module_accessors);
return module;
}
| lib/compiler.js | /* -*- Mode: js2; tab-width: 4; indent-tabs-mode: nil; -*-
* vim: set ts=4 sw=4 et tw=99 ft=js:
*/
import * as llvm from '@llvm';
import * as path from '@node-compat/path'
import { Stack } from './stack-es6';
import { TreeVisitor } from './node-visitor';
import { generate as escodegenerate } from '../external-deps/escodegen/escodegen-es6';
import { convert as closure_convert } from './closure-conversion';
import { reportError } from './errors';
import * as optimizations from './optimizations';
import * as types from './types';
import * as consts from './consts';
import * as runtime from './runtime';
import * as debug from './debug';
import * as b from './ast-builder';
import { startGenerator, intrinsic, is_intrinsic, is_string_literal } from './echo-util';
import { ExitableScope, TryExitableScope, SwitchExitableScope, LoopExitableScope } from './exitable-scope';
import { ABI } from './abi';
import { SRetABI } from './sret-abi';
let ir = llvm.IRBuilder;
let hasOwn = Object.prototype.hasOwnProperty;
class LLVMIRVisitor extends TreeVisitor {
constructor (module, filename, options, abi, allModules, this_module_info, dibuilder, difile) {
super();
this.module = module;
this.filename = filename;
this.options = options;
this.abi = abi;
this.allModules = allModules;
this.this_module_info = this_module_info;
this.dibuilder = dibuilder;
this.difile = difile;
this.idgen = startGenerator();
if (this.options.record_types)
this.genRecordId = startGenerator();
// build up our runtime method table
this.ejs_intrinsics = Object.create(null, {
templateDefaultHandlerCall: { value: this.handleTemplateDefaultHandlerCall },
templateCallsite: { value: this.handleTemplateCallsite },
moduleGet: { value: this.handleModuleGet },
moduleGetSlot: { value: this.handleModuleGetSlot },
moduleSetSlot: { value: this.handleModuleSetSlot },
moduleGetExotic: { value: this.handleModuleGetExotic },
getArgumentsObject: { value: this.handleGetArgumentsObject },
getLocal: { value: this.handleGetLocal },
setLocal: { value: this.handleSetLocal },
getGlobal: { value: this.handleGetGlobal },
setGlobal: { value: this.handleSetGlobal },
getArg: { value: this.handleGetArg },
getNewTarget: { value: this.handleGetNewTarget },
slot: { value: this.handleGetSlot },
setSlot: { value: this.handleSetSlot },
invokeClosure: { value: this.handleInvokeClosure },
constructClosure: { value: this.handleConstructClosure },
constructSuper: { value: this.handleConstructSuper },
constructSuperApply: { value: this.handleConstructSuperApply },
setConstructorKindDerived: { value: this.handleSetConstructorKindDerived },
setConstructorKindBase: { value: this.handleSetConstructorKindBase },
makeClosure: { value: this.handleMakeClosure },
makeClosureNoEnv: { value: this.handleMakeClosureNoEnv },
makeAnonClosure: { value: this.handleMakeAnonClosure },
makeGenerator: { value: this.handleMakeGenerator },
generatorYield: { value: this.handleGeneratorYield },
createArgScratchArea: { value: this.handleCreateArgScratchArea },
makeClosureEnv: { value: this.handleMakeClosureEnv },
typeofIsObject: { value: this.handleTypeofIsObject },
typeofIsFunction: { value: this.handleTypeofIsFunction },
typeofIsString: { value: this.handleTypeofIsString },
typeofIsSymbol: { value: this.handleTypeofIsSymbol },
typeofIsNumber: { value: this.handleTypeofIsNumber },
typeofIsBoolean: { value: this.handleTypeofIsBoolean },
builtinUndefined: { value: this.handleBuiltinUndefined },
isNullOrUndefined: { value: this.handleIsNullOrUndefined },
isUndefined: { value: this.handleIsUndefined },
isNull: { value: this.handleIsNull },
setPrototypeOf: { value: this.handleSetPrototypeOf },
objectCreate: { value: this.handleObjectCreate },
arrayFromRest: { value: this.handleArrayFromRest },
arrayFromSpread: { value: this.handleArrayFromSpread },
argPresent: { value: this.handleArgPresent },
createIterResult: { value: this.handleCreateIterResult },
createIteratorWrapper: { value: this.handleCreateIteratorWrapper }
});
this.opencode_intrinsics = {
unaryNot : true,
templateDefaultHandlerCall: true,
moduleGet : true, // unused
moduleGetSlot : true,
moduleSetSlot : true,
moduleGetExotic : true,
getLocal : true, // unused
setLocal : true, // unused
getGlobal : true, // unused
setGlobal : true, // unused
slot : true,
setSlot : true,
invokeClosure : false,
constructClosure : false,
makeClosure : true,
makeAnonClosure : true,
createArgScratchArea : true,
makeClosureEnv : true,
setConstructorKindDerived: false,
setConstructorKindBase: false,
typeofIsObject : true,
typeofIsFunction : true,
typeofIsString : true,
typeofIsSymbol : true,
typeofIsNumber : true,
typeofIsBoolean : true,
builtinUndefined : true,
isNullOrUndefined : true, // unused
isUndefined : true,
isNull : true
};
this.llvm_intrinsics = {
gcroot: () => module.getOrInsertIntrinsic("@llvm.gcroot")
};
this.ejs_runtime = runtime.createInterface(module, this.abi);
this.ejs_binops = runtime.createBinopsInterface(module, this.abi);
this.ejs_atoms = runtime.createAtomsInterface(module);
this.ejs_globals = runtime.createGlobalsInterface(module);
this.ejs_symbols = runtime.createSymbolsInterface(module);
this.module_atoms = new Map();
let init_function_name = `_ejs_module_init_string_literals_${this.filename}`;
this.literalInitializationFunction = this.module.getOrInsertFunction(init_function_name, types.Void, []);
if (this.options.debug)
this.literalInitializationDebugInfo = this.dibuilder.createFunction(this.difile, init_function_name, init_function_name, this.difile, 0, false, true, 0, 0, true, this.literalInitializationFunction);
// this function is only ever called by this module's toplevel
this.literalInitializationFunction.setInternalLinkage();
// initialize the scope stack with the global (empty) scope
this.scope_stack = new Stack(new Map());
let entry_bb = new llvm.BasicBlock("entry", this.literalInitializationFunction);
let return_bb = new llvm.BasicBlock("return", this.literalInitializationFunction);
if (this.options.debug)
ir.setCurrentDebugLocation(llvm.DebugLoc.get(0, 0, this.literalInitializationDebugInfo));
this.doInsideBBlock(entry_bb, () => { ir.createBr(return_bb); });
this.doInsideBBlock(return_bb, () => {
//this.createCall this.ejs_runtime.log, [consts.string(ir, "done with literal initialization")], ""
ir.createRetVoid();
});
this.literalInitializationBB = entry_bb;
}
// lots of helper methods
emitModuleInfo () {
let this_module_type = types.getModuleSpecificType(this.this_module_info.module_name, this.this_module_info.slot_num);
this.this_module_global = new llvm.GlobalVariable(this.module, this_module_type, this.this_module_info.module_name, llvm.Constant.getAggregateZero(this_module_type), true);
this.import_module_globals = new Map();
for (let import_module_string of this.this_module_info.importList) {
let import_module_info = this.allModules.get(import_module_string);
if (!import_module_info.isNative())
this.import_module_globals.set(import_module_string, new llvm.GlobalVariable(this.module, types.EjsModule, import_module_info.module_name, null, true));
}
this.this_module_initted = new llvm.GlobalVariable(this.module, types.Bool, `${this.this_module_info.module_name}_initialized`, consts.False(), false);
}
emitModuleResolution (module_accessors) {
// this.loadUndefinedEjsValue depends on this
this.currentFunction = this.toplevel_function;
ir.setInsertPoint(this.resolve_modules_bb);
if (this.options.debug)
ir.setCurrentDebugLocation(llvm.DebugLoc.get(0, 0, this.currentFunction.debug_info));
let uninitialized_bb = new llvm.BasicBlock("module_uninitialized", this.toplevel_function);
let initialized_bb = new llvm.BasicBlock("module_initialized", this.toplevel_function);
let load_init_flag = ir.createLoad(this.this_module_initted, "load_init_flag");
let load_init_cmp = ir.createICmpEq(load_init_flag, consts.False(), "load_init_cmp");
ir.createCondBr(load_init_cmp, uninitialized_bb, initialized_bb);
ir.setInsertPoint(uninitialized_bb);
ir.createStore(consts.True(), this.this_module_initted);
ir.createCall(this.literalInitializationFunction, [], "");
// fill in the information we know about this module
// our name
let name_slot = ir.createInBoundsGetElementPointer(this.this_module_global, [consts.int64(0), consts.int32(1)], "name_slot");
ir.createStore(consts.string(ir, this.this_module_info.path), name_slot);
// num_exports
let num_exports_slot = ir.createInBoundsGetElementPointer(this.this_module_global, [consts.int64(0), consts.int32(2)], "num_exports_slot");
ir.createStore(consts.int32(this.this_module_info.slot_num), num_exports_slot);
// define our accessor properties
for (let accessor of module_accessors) {
let get_func = (accessor.getter && accessor.getter.ir_func) || consts.Null(types.EjsClosureFunc);
let set_func = (accessor.setter && accessor.setter.ir_func) || consts.Null(types.EjsClosureFunc);
let module_arg = ir.createPointerCast(this.this_module_global, types.EjsModule.pointerTo(), "");
ir.createCall(this.ejs_runtime.module_add_export_accessors, [module_arg, consts.string(ir, accessor.key), get_func, set_func], "");
};
for (let import_module_string of this.this_module_info.importList) {
let import_module = this.import_module_globals.get(import_module_string);
if (import_module) {
this.createCall(this.ejs_runtime.module_resolve, [import_module], "", !this.ejs_runtime.module_resolve.doesNotThrow);
}
}
ir.createBr(this.toplevel_body_bb);
ir.setInsertPoint(initialized_bb);
return ir.createRet(this.loadUndefinedEjsValue());
}
// result should be the landingpad's value
beginCatch (result) { return this.createCall(this.ejs_runtime.begin_catch, [ir.createPointerCast(result, types.Int8Pointer, "")], "begincatch"); }
endCatch () { return this.createCall(this.ejs_runtime.end_catch, [], "endcatch"); }
doInsideExitableScope (scope, f) {
scope.enter();
f();
scope.leave();
}
doInsideBBlock (b, f) {
let saved = ir.getInsertBlock();
ir.setInsertPoint(b);
f();
ir.setInsertPoint(saved);
return b;
}
createLoad (value, name) {
let rv = ir.createLoad(value, name);
rv.setAlignment(8);
return rv;
}
loadCachedEjsValue (name, init) {
let alloca_name = `${name}_alloca`;
let load_name = `${name}_load`;
let alloca;
if (this.currentFunction[alloca_name]) {
alloca = this.currentFunction[alloca_name];
}
else {
alloca = this.createAlloca(this.currentFunction, types.EjsValue, alloca_name);
this.currentFunction[alloca_name] = alloca;
this.doInsideBBlock(this.currentFunction.entry_bb, () => init(alloca));
}
return ir.createLoad(alloca, load_name);
}
loadBoolEjsValue (n) {
let rv = this.loadCachedEjsValue(n, (alloca) => {
let alloca_as_int64 = ir.createBitCast(alloca, types.Int64.pointerTo(), "alloca_as_pointer");
if (this.options.target_pointer_size === 64)
ir.createStore(consts.int64_lowhi(0xfff98000, n ? 0x00000001 : 0x000000000), alloca_as_int64);
else
ir.createStore(consts.int64_lowhi(0xffffff83, n ? 0x00000001 : 0x000000000), alloca_as_int64);
});
rv._ejs_returns_ejsval_bool = true;
return rv;
}
loadDoubleEjsValue (n) { return this.loadCachedEjsValue(`num_${n}`, (alloca) => this.storeDouble(alloca, n)); }
loadNullEjsValue () { return this.loadCachedEjsValue("null", (alloca) => this.storeNull(alloca)); }
loadUndefinedEjsValue () { return this.loadCachedEjsValue("undef", (alloca) => this.storeUndefined(alloca)); }
storeUndefined (alloca, name) {
let alloca_as_int64 = ir.createBitCast(alloca, types.Int64.pointerTo(), "alloca_as_pointer");
if (this.options.target_pointer_size === 64)
return ir.createStore(consts.int64_lowhi(0xfff90000, 0x00000000), alloca_as_int64, name);
else // 32 bit
return ir.createStore(consts.int64_lowhi(0xffffff82, 0x00000000), alloca_as_int64, name);
}
storeNull (alloca, name) {
let alloca_as_int64 = ir.createBitCast(alloca, types.Int64.pointerTo(), "alloca_as_pointer");
if (this.options.target_pointer_size === 64)
return ir.createStore(consts.int64_lowhi(0xfffb8000, 0x00000000), alloca_as_int64, name);
else // 32 bit
return ir.createStore(consts.int64_lowhi(0xffffff87, 0x00000000), alloca_as_int64, name);
}
storeDouble (alloca, jsnum, name) {
let c = llvm.ConstantFP.getDouble(jsnum);
let alloca_as_double = ir.createBitCast(alloca, types.Double.pointerTo(), "alloca_as_pointer");
return ir.createStore(c, alloca_as_double, name);
}
storeBoolean (alloca, jsbool, name) {
let alloca_as_int64 = ir.createBitCast(alloca, types.Int64.pointerTo(), "alloca_as_pointer");
if (this.options.target_pointer_size === 64)
return ir.createStore(consts.int64_lowhi(0xfff98000, jsbool ? 0x00000001 : 0x000000000), alloca_as_int64, name);
else
return ir.createStore(consts.int64_lowhi(0xffffff83, jsbool ? 0x00000001 : 0x000000000), alloca_as_int64, name);
}
storeToDest (dest, arg, name = "") {
if (!arg)
arg = { type: b.Literal, value: null };
if (arg.type === b.Literal) {
if (arg.value === null)
return this.storeNull(dest, name);
if (arg.value === undefined)
return this.storeUndefined(dest, name);
if (typeof arg.value === "number")
return this.storeDouble(dest, arg.value, name);
if (typeof arg.value === "boolean")
return this.storeBoolean(dest, arg.value, name);
// if typeof arg is "string"
let val = this.visit(arg);
return ir.createStore(val, dest, name);
}
else {
let val = this.visit(arg);
return ir.createStore(val, dest, name);
}
}
storeGlobal (prop, value) {
let gname;
// we store obj.prop, prop is an id
if (prop.type === b.Identifier)
gname = prop.name;
else // prop.type is b.Literal
gname = prop.value;
let c = this.getAtom(gname);
debug.log( () => `createPropertyStore %global[${gname}]` );
return this.createCall(this.ejs_runtime.global_setprop, [c, value], `globalpropstore_${gname}`);
}
loadGlobal (prop) {
let gname = prop.name;
if (this.options.frozen_global)
return ir.createLoad(this.ejs_globals[prop.name], `load-${gname}`);
let pname = this.getAtom(gname);
return this.createCall(this.ejs_runtime.global_getprop, [pname], `globalloadprop_${gname}`);
}
visitWithScope (scope, children) {
this.scope_stack.push(scope);
for (let child of children)
this.visit(child);
this.scope_stack.pop();
}
findIdentifierInScope (ident) {
for (let scope of this.scope_stack.stack) {
if (scope.has(ident))
return scope.get(ident);
}
return null;
}
createAlloca (func, type, name) {
let saved_insert_point = ir.getInsertBlock();
ir.setInsertPointStartBB(func.entry_bb);
let alloca = ir.createAlloca(type, name);
// if EjsValue was a pointer value we would be able to use an the llvm gcroot intrinsic here. but with the nan boxing
// we kinda lose out as the llvm IR code doesn't permit non-reference types to be gc roots.
// if type is types.EjsValue
// // EjsValues are rooted
// this.createCall this.llvm_intrinsics.gcroot(), [(ir.createPointerCast alloca, types.Int8Pointer.pointerTo(), "rooted_alloca"), consts.Null types.Int8Pointer], ""
ir.setInsertPoint(saved_insert_point);
return alloca;
}
createAllocas (func, ids, scope) {
let allocas = [];
let new_allocas = [];
// the allocas are always allocated in the function entry_bb so the mem2reg opt pass can regenerate the ssa form for us
let saved_insert_point = ir.getInsertBlock();
ir.setInsertPointStartBB(func.entry_bb);
let j = 0;
for (let i = 0, e = ids.length; i < e; i ++) {
let name = ids[i].id.name;
if (!scope.has(name)) {
allocas[j] = ir.createAlloca(types.EjsValue, `local_${name}`);
allocas[j].setAlignment(8);
scope.set(name, allocas[j]);
new_allocas[j] = true;
}
else {
allocas[j] = scope.get(name);
new_allocas[j] = false;
}
j = j + 1;
}
// reinstate the IRBuilder to its previous insert point so we can insert the actual initializations
ir.setInsertPoint(saved_insert_point);
return { allocas: allocas, new_allocas: new_allocas };
}
createPropertyStore (obj,prop,rhs,computed) {
if (computed) {
// we store obj[prop], prop can be any value
return this.createCall(this.ejs_runtime.object_setprop, [obj, this.visit(prop), rhs], "propstore_computed");
}
else {
var pname;
// we store obj.prop, prop is an id
if (prop.type === b.Identifier)
pname = prop.name;
else // prop.type is b.Literal
pname = prop.value;
let c = this.getAtom(pname);
debug.log(() => `createPropertyStore ${obj}[${pname}]`);
return this.createCall(this.ejs_runtime.object_setprop, [obj, c, rhs], `propstore_${pname}`);
}
}
createPropertyLoad (obj,prop,computed,canThrow = true) {
if (computed) {
// we load obj[prop], prop can be any value
let loadprop = this.visit(prop);
if (this.options.record_types)
this.createCall(this.ejs_runtime.record_getprop, [consts.int32(this.genRecordId()), obj, loadprop], "");
return this.createCall(this.ejs_runtime.object_getprop, [obj, loadprop], "getprop_computed", canThrow);
}
else {
// we load obj.prop, prop is an id
let pname = this.getAtom(prop.name);
if (this.options.record_types)
this.createCall(this.ejs_runtime.record_getprop, [consts.int32(this.genRecordId()), obj, pname], "");
return this.createCall(this.ejs_runtime.object_getprop, [obj, pname], `getprop_${prop.name}`, canThrow);
}
}
setDebugLoc (ast_node) {
if (!this.options.debug) return;
if (!ast_node || !ast_node.loc) return;
if (!this.currentFunction) return;
if (!this.currentFunction.debug_info) return;
ir.setCurrentDebugLocation(llvm.DebugLoc.get(ast_node.loc.start.line, ast_node.loc.start.column, this.currentFunction.debug_info));
}
visit (n) {
this.setDebugLoc(n);
return super.visit(n);
}
visitOrNull (n) { return this.visit(n) || this.loadNullEjsValue(); }
visitOrUndefined (n) { return this.visit(n) || this.loadUndefinedEjsValue(); }
visitProgram (n) {
// by the time we make it here the program has been
// transformed so that there is nothing at the toplevel
// but function declarations.
for (let func of n.body)
this.visit(func);
}
visitBlock (n) {
let new_scope = new Map();
let iife_dest_bb = null;
let iife_rv = null;
if (n.fromIIFE) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
iife_dest_bb = new llvm.BasicBlock("iife_dest", insertFunc);
iife_rv = n.ejs_iife_rv;
}
this.iifeStack.push ({ iife_rv, iife_dest_bb });
this.visitWithScope(new_scope, n.body);
this.iifeStack.pop();
if (iife_dest_bb) {
ir.createBr(iife_dest_bb);
ir.setInsertPoint(iife_dest_bb);
let rv = this.createLoad(this.findIdentifierInScope(iife_rv.name), "%iife_rv_load");
return rv;
}
else {
return n;
}
}
visitSwitch (n) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
// find the default: case first
let defaultCase = null;
for (let _case of n.cases) {
if (!_case.test) {
defaultCase = _case;
break;
}
}
// for each case, create 2 basic blocks
for (let _case of n.cases) {
_case.bb = new llvm.BasicBlock("case_bb", insertFunc);
if (_case !== defaultCase)
_case.dest_check = new llvm.BasicBlock("case_dest_check_bb", insertFunc);
}
let merge_bb = new llvm.BasicBlock("switch_merge", insertFunc);
let discr = this.visit(n.discriminant);
let case_checks = [];
for (let _case of n.cases) {
if (defaultCase !== _case)
case_checks.push ({ test: _case.test, dest_check: _case.dest_check, body: _case.bb });
}
case_checks.push ({ dest_check: defaultCase ? defaultCase.bb : merge_bb });
this.doInsideExitableScope (new SwitchExitableScope(merge_bb), () => {
// insert all the code for the tests
ir.createBr(case_checks[0].dest_check);
ir.setInsertPoint(case_checks[0].dest_check);
for (let casenum = 0; casenum < case_checks.length -1; casenum ++) {
let test = this.visit(case_checks[casenum].test);
let eqop = this.ejs_binops["==="];
this.setDebugLoc(test);
let discTest = this.createCall(eqop, [discr, test], "test", !eqop.doesNotThrow);
let disc_cmp, disc_truthy;
if (discTest._ejs_returns_ejsval_bool) {
disc_cmp = this.createEjsvalICmpEq(discTest, consts.ejsval_false());
}
else {
disc_truthy = this.createCall(this.ejs_runtime.truthy, [discTest], "disc_truthy");
disc_cmp = ir.createICmpEq(disc_truthy, consts.False(), "disccmpresult");
}
ir.createCondBr(disc_cmp, case_checks[casenum+1].dest_check, case_checks[casenum].body);
ir.setInsertPoint(case_checks[casenum+1].dest_check);
}
let case_bodies = [];
// now insert all the code for the case consequents
for (let _case of n.cases)
case_bodies.push ({bb:_case.bb, consequent:_case.consequent});
case_bodies.push ({bb:merge_bb});
for (let casenum = 0; casenum < case_bodies.length-1; casenum ++) {
ir.setInsertPoint(case_bodies[casenum].bb);
case_bodies[casenum].consequent.forEach ((consequent, i) => {
this.visit(consequent);
});
ir.createBr(case_bodies[casenum+1].bb);
}
ir.setInsertPoint(merge_bb);
});
return merge_bb;
}
visitCase (n) {
throw new Error("we shouldn't get here, case statements are handled in visitSwitch");
}
visitLabeledStatement (n) {
n.body.label = n.label.name;
return this.visit(n.body);
}
visitBreak (n) {
return ExitableScope.scopeStack.exitAft(true, n.label && n.label.name);
}
visitContinue (n) {
if (n.label && n.label.name)
return LoopExitableScope.findLabeledOrFinally(n.label.name).exitFore();
else
return LoopExitableScope.findLoopOrFinally().exitFore();
}
generateCondBr (exp, then_bb, else_bb) {
let cmp, exp_value;
if (exp.type === b.Literal && typeof exp.value === "boolean") {
cmp = consts.int1(exp.value ? 0 : 1); // we check for false below, so the then/else branches get swapped
}
else {
exp_value = this.visit(exp);
if (exp_value._ejs_returns_ejsval_bool) {
cmp = this.createEjsvalICmpEq(exp_value, consts.ejsval_false(), "cmpresult");
}
else if (exp_value._ejs_returns_native_bool) {
cmp = ir.createSelect(exp_value, consts.int1(0), consts.int1(1), "invert_check");
}
else {
let cond_truthy = this.createCall(this.ejs_runtime.truthy, [exp_value], "cond_truthy");
cmp = ir.createICmpEq(cond_truthy, consts.False(), "cmpresult");
}
}
ir.createCondBr(cmp, else_bb, then_bb);
return exp_value;
}
visitFor (n) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let init_bb = new llvm.BasicBlock("for_init", insertFunc);
let test_bb = new llvm.BasicBlock("for_test", insertFunc);
let body_bb = new llvm.BasicBlock("for_body", insertFunc);
let update_bb = new llvm.BasicBlock("for_update", insertFunc);
let merge_bb = new llvm.BasicBlock("for_merge", insertFunc);
ir.createBr(init_bb);
this.doInsideBBlock(init_bb, () => {
this.visit(n.init);
ir.createBr(test_bb);
});
this.doInsideBBlock(test_bb, () => {
if (n.test)
this.generateCondBr(n.test, body_bb, merge_bb);
else
ir.createBr(body_bb);
});
this.doInsideExitableScope (new LoopExitableScope(n.label, update_bb, merge_bb), () => {
this.doInsideBBlock(body_bb, () => {
this.visit(n.body);
ir.createBr(update_bb);
});
this.doInsideBBlock(update_bb, () => {
this.visit(n.update);
ir.createBr(test_bb);
});
});
ir.setInsertPoint(merge_bb);
return merge_bb;
}
visitDo (n) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let body_bb = new llvm.BasicBlock("do_body", insertFunc);
let test_bb = new llvm.BasicBlock("do_test", insertFunc);
let merge_bb = new llvm.BasicBlock("do_merge", insertFunc);
ir.createBr(body_bb);
this.doInsideExitableScope (new LoopExitableScope(n.label, test_bb, merge_bb), () => {
this.doInsideBBlock(body_bb, () => {
this.visit(n.body);
ir.createBr(test_bb);
});
this.doInsideBBlock(test_bb, () => {
this.generateCondBr(n.test, body_bb, merge_bb);
});
});
ir.setInsertPoint(merge_bb);
return merge_bb;
}
visitWhile (n) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let while_bb = new llvm.BasicBlock("while_start", insertFunc);
let body_bb = new llvm.BasicBlock("while_body", insertFunc);
let merge_bb = new llvm.BasicBlock("while_merge", insertFunc);
ir.createBr(while_bb);
this.doInsideBBlock(while_bb, () => {
this.generateCondBr(n.test, body_bb, merge_bb);
});
this.doInsideExitableScope (new LoopExitableScope(n.label, while_bb, merge_bb), () => {
this.doInsideBBlock(body_bb, () => {
this.visit(n.body);
ir.createBr(while_bb);
});
});
ir.setInsertPoint(merge_bb);
return merge_bb;
}
visitForIn (n) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let iterator = this.createCall(this.ejs_runtime.prop_iterator_new, [this.visit(n.right)], "iterator");
let lhs;
// make sure we get an alloca if there's a "var"
if (n.left[0]) {
this.visit(n.left);
lhs = n.left[0].declarations[0].id;
}
else {
lhs = n.left;
}
let forin_bb = new llvm.BasicBlock ("forin_start", insertFunc);
let body_bb = new llvm.BasicBlock ("forin_body", insertFunc);
let merge_bb = new llvm.BasicBlock ("forin_merge", insertFunc);
ir.createBr(forin_bb);
this.doInsideExitableScope (new LoopExitableScope (n.label, forin_bb, merge_bb), () => {
// forin_bb:
// moreleft = prop_iterator_next (iterator, true)
// if moreleft === false
// goto merge_bb
// else
// goto body_bb
//
this.doInsideBBlock (forin_bb, () => {
let moreleft = this.createCall(this.ejs_runtime.prop_iterator_next, [iterator, consts.True()], "moreleft");
let cmp = ir.createICmpEq(moreleft, consts.False(), "cmpmoreleft");
ir.createCondBr(cmp, merge_bb, body_bb);
});
// body_bb:
// current = prop_iteratorcurrent (iterator)
// *lhs = current
// <body>
// goto forin_bb
this.doInsideBBlock (body_bb, () => {
let current = this.createCall(this.ejs_runtime.prop_iterator_current, [iterator], "iterator_current");
this.storeValueInDest(current, lhs);
this.visit(n.body);
ir.createBr(forin_bb);
});
});
// merge_bb:
//
ir.setInsertPoint(merge_bb);
return merge_bb;
}
visitForOf (n) {
throw new Error("internal compiler error. for..of statements should have been transformed away by this point.");
}
visitUpdateExpression (n) {
let result = this.createAlloca(this.currentFunction, types.EjsValue, "%update_result");
let argument = this.visit(n.argument);
let one = this.loadDoubleEjsValue(1);
if (!n.prefix) {
// postfix updates store the argument before the op
ir.createStore(argument, result);
}
// argument = argument $op 1
let update_op = this.ejs_binops[n.operator === '++' ? '+' : '-'];
let temp = this.createCall(update_op, [argument, one], "update_temp", !update_op.doesNotThrow);
this.storeValueInDest(temp, n.argument);
// return result
if (n.prefix) {
argument = this.visit(n.argument);
// prefix updates store the argument after the op
ir.createStore(argument, result);
}
return this.createLoad(result, "%update_result_load");
}
visitConditionalExpression (n) {
return this.visitIfOrCondExp(n, true);
}
visitIf (n) {
return this.visitIfOrCondExp(n, false);
}
visitIfOrCondExp (n, load_result) {
let cond_val;
if (load_result)
cond_val = this.createAlloca(this.currentFunction, types.EjsValue, "%cond_val");
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let then_bb = new llvm.BasicBlock ("then", insertFunc);
let else_bb;
if (n.alternate)
else_bb = new llvm.BasicBlock ("else", insertFunc);
let merge_bb = new llvm.BasicBlock ("merge", insertFunc);
this.generateCondBr(n.test, then_bb, else_bb ? else_bb : merge_bb);
this.doInsideBBlock(then_bb, () => {
let then_val = this.visit(n.consequent);
if (load_result) ir.createStore(then_val, cond_val);
ir.createBr(merge_bb);
});
if (n.alternate) {
this.doInsideBBlock(else_bb, () => {
let else_val = this.visit(n.alternate);
if (load_result) ir.createStore(else_val, cond_val);
ir.createBr(merge_bb);
});
}
ir.setInsertPoint(merge_bb);
if (load_result)
return this.createLoad(cond_val, "cond_val_load");
else
return merge_bb;
}
visitReturn (n) {
if (this.iifeStack.top.iife_rv) {
// if we're inside an IIFE, convert the return statement into a store to the iife_rv alloca + a branch to the iife's dest bb
if (n.argument)
ir.createStore(this.visit(n.argument), this.findIdentifierInScope(this.iifeStack.top.iife_rv.name));
ir.createBr(this.iifeStack.top.iife_dest_bb);
}
else {
// otherwise generate an llvm IR ret
let rv = this.visitOrUndefined(n.argument);
if (this.finallyStack.length > 0) {
if (!this.currentFunction.returnValueAlloca)
this.currentFunction.returnValueAlloca = this.createAlloca(this.currentFunction, types.EjsValue, "returnValue");
ir.createStore(rv, this.currentFunction.returnValueAlloca);
ir.createStore(consts.int32(ExitableScope.REASON_RETURN), this.currentFunction.cleanup_reason);
ir.createBr(this.finallyStack[0]);
}
else {
let return_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "return_alloca");
ir.createStore(rv, return_alloca);
this.createRet(this.createLoad(return_alloca, "return_load"));
}
}
}
visitVariableDeclaration (n) {
if (n.kind === "var") throw new Error("internal compiler error. 'var' declarations should have been transformed to 'let's by this point.");
let scope = this.scope_stack.top;
let { allocas, new_allocas } = this.createAllocas(this.currentFunction, n.declarations, scope);
for (let i = 0, e = n.declarations.length; i < e; i ++) {
if (!n.declarations[i].init) {
// there was not an initializer. we only store undefined
// if the alloca is newly allocated.
if (new_allocas[i]) {
let initializer = this.visitOrUndefined(n.declarations[i].init);
ir.createStore(initializer, allocas[i]);
}
}
else {
let initializer = this.visitOrUndefined(n.declarations[i].init);
ir.createStore(initializer, allocas[i]);
}
}
}
visitMemberExpression (n) {
return this.createPropertyLoad(this.visit(n.object), n.property, n.computed);
}
storeValueInDest (rhvalue, lhs) {
if (lhs.type === b.Identifier) {
let dest = this.findIdentifierInScope(lhs.name);
let result;
if (dest)
result = ir.createStore(rhvalue, dest);
else
result = this.storeGlobal(lhs, rhvalue);
return result;
}
else if (lhs.type === b.MemberExpression) {
return this.createPropertyStore(this.visit(lhs.object), lhs.property, rhvalue, lhs.computed);
}
else if (is_intrinsic(lhs, "%slot")) {
return ir.createStore(rhvalue, this.handleSlotRef(lhs));
}
else if (is_intrinsic(lhs, "%getLocal")) {
return ir.createStore(rhvalue, this.findIdentifierInScope(lhs.arguments[0].name));
}
else if (is_intrinsic(lhs, "%getGlobal")) {
let gname = lhs.arguments[0].name;
return this.createCall(this.ejs_runtime.global_setprop, [this.getAtom(gname), rhvalue], `globalpropstore_${lhs.arguments[0].name}`);
}
else {
throw new Error(`unhandled lhs ${escodegenerate(lhs)}`);
}
}
visitAssignmentExpression (n) {
let lhs = n.left;
let rhs = n.right;
let rhvalue = this.visit(rhs);
if (n.operator.length === 2)
throw new Error(`binary assignment operators '${n.operator}' should not exist at this point`);
if (this.options.record_types)
this.createCall(this.ejs_runtime.record_assignment, [consts.int32(this.genRecordId()), rhvalue], "");
this.storeValueInDest(rhvalue, lhs);
// we need to visit lhs after the store so that we load the value, but only if it's used
if (!n.result_not_used)
return rhvalue;
}
visitFunction (n) {
if (!n.toplevel)
debug.log (() => ` function ${n.ir_name} at ${this.filename}:${n.loc ? n.loc.start.line : '<unknown>'}`);
// save off the insert point so we can get back to it after generating this function
let insertBlock = ir.getInsertBlock();
for (let param of n.formal_params) {
if (param.type !== b.Identifier)
throw new Error("formal parameters should only be identifiers by this point");
}
// XXX this methods needs to be augmented so that we can pass actual types (or the builtin args need
// to be reflected in jsllvm.cpp too). maybe we can pass the names to this method and it can do it all
// there?
let ir_func = n.ir_func;
let ir_args = n.ir_func.args;
debug.log ("");
//debug.log -> `ir_func = ${ir_func}`
//debug.log -> `param ${param.llvm_type} ${param.name}` for param in n.formal_params
this.currentFunction = ir_func;
// we need to do this here as well, since otherwise the allocas and stores we create below for our parameters
// could be accidentally attributed to the previous @currentFunction (the last location we set).
this.setDebugLoc(n);
// Create a new basic block to start insertion into.
let entry_bb = new llvm.BasicBlock("entry", ir_func);
ir.setInsertPoint(entry_bb);
let new_scope = new Map();
// we save off the top scope and entry_bb of the function so that we can hoist vars there
ir_func.topScope = new_scope;
ir_func.entry_bb = entry_bb;
ir_func.literalAllocas = Object.create(null);
let allocas = [];
// create allocas for the builtin args
for (let param of n.params) {
let alloca = ir.createAlloca(param.llvm_type, `local_${param.name}`);
alloca.setAlignment(8);
new_scope.set(param.name, alloca);
allocas.push(alloca);
}
// now create allocas for the formal parameters
let first_formal_index = allocas.length;
for (let param of n.formal_params) {
let alloca = this.createAlloca(this.currentFunction, types.EjsValue, `local_${param.name}`);
new_scope.set(param.name, alloca);
allocas.push(alloca);
}
debug.log ( () => {
allocas.map( (alloca) => `alloca ${alloca}`).join('\n');
});
// now store the arguments onto the stack
for (let i = 0, e = n.params.length; i < e; i ++) {
var store = ir.createStore(ir_args[i], allocas[i]);
debug.log ( () => `store ${store} *builtin` );
}
let body_bb = new llvm.BasicBlock("body", ir_func);
ir.setInsertPoint(body_bb);
//this.createCall this.ejs_runtime.log, [consts.string(ir, `entering ${n.ir_name}`)], ""
let insertFunc = body_bb.parent;
this.iifeStack = new Stack();
this.finallyStack = [];
this.visitWithScope(new_scope, [n.body]);
// XXX more needed here - this lacks all sorts of control flow stuff.
// Finish off the function.
this.createRet(this.loadUndefinedEjsValue());
if (n.toplevel) {
this.resolve_modules_bb = new llvm.BasicBlock("resolve_modules", ir_func);
this.toplevel_body_bb = body_bb;
this.toplevel_function = ir_func;
// branch to the resolve_modules_bb from our entry_bb, but only in the toplevel function
ir.setInsertPoint(entry_bb);
ir.createBr(this.resolve_modules_bb);
}
else {
// branch to the body_bb from our entry_bb
ir.setInsertPoint(entry_bb);
ir.createBr(body_bb);
}
this.currentFunction = null;
ir.setInsertPoint(insertBlock);
return ir_func;
}
createRet (x) {
//this.createCall this.ejs_runtime.log, [consts.string(ir, `leaving ${this.currentFunction.name}`)], ""
return this.abi.createRet(this.currentFunction, x);
}
visitUnaryExpression (n) {
debug.log ( () => `operator = '${n.operator}'` );
let builtin = `unop${n.operator}`;
let callee = this.ejs_runtime[builtin];
if (n.operator === "delete") {
if (n.argument.type !== b.MemberExpression) throw "unhandled delete syntax";
let fake_literal = {
type: b.Literal,
value: n.argument.property.name,
raw: `'${n.argument.property.name}'`
};
return this.createCall(callee, [this.visitOrNull(n.argument.object), this.visit(fake_literal)], "result");
}
else if (n.operator === "!") {
let arg_value = this.visitOrNull(n.argument);
if (this.opencode_intrinsics.unaryNot && this.options.target_pointer_size === 64 && arg_value._ejs_returns_ejsval_bool) {
let cmp = this.createEjsvalICmpEq(arg_value, consts.ejsval_true(), "cmpresult");
return this.createEjsBoolSelect(cmp, true);
}
else {
return this.createCall(callee, [arg_value], "result");
}
}
else {
if (!callee) {
throw new Error(`Internal error: unary operator '${n.operator}' not implemented`);
}
return this.createCall(callee, [this.visitOrNull(n.argument)], "result");
}
}
visitSequenceExpression (n) {
let rv = null;
for (let exp of n.expressions)
rv = this.visit(exp);
return rv;
}
visitBinaryExpression (n) {
debug.log ( () => `operator = '${n.operator}'` );
let callee = this.ejs_binops[n.operator];
if (!callee)
throw new Error(`Internal error: unhandled binary operator '${n.operator}'`);
let left_visited = this.visit(n.left);
let right_visited = this.visit(n.right);
if (this.options.record_types)
this.createCall(this.ejs_runtime.record_binop, [consts.int32(this.genRecordId()), consts.string(ir, n.operator), left_visited, right_visited], "");
// call the actual runtime binaryop method
return this.createCall(callee, [left_visited, right_visited], `result_${n.operator}`, !callee.doesNotThrow);
}
visitLogicalExpression (n) {
debug.log ( () => `operator = '${n.operator}'` );
let result = this.createAlloca(this.currentFunction, types.EjsValue, `result_${n.operator}`);
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let left_bb = new llvm.BasicBlock ("cond_left", insertFunc);
let right_bb = new llvm.BasicBlock ("cond_right", insertFunc);
let merge_bb = new llvm.BasicBlock ("cond_merge", insertFunc);
// we invert the test here - check if the condition is false/0
let left_visited = this.generateCondBr(n.left, left_bb, right_bb);
this.doInsideBBlock(left_bb, () => {
// inside the else branch, left was truthy
if (n.operator === "||")
// for || we short circuit out here
ir.createStore(left_visited, result);
else if (n.operator === "&&")
// for && we evaluate the second and store it
ir.createStore(this.visit(n.right), result);
else
throw "Internal error 99.1";
ir.createBr(merge_bb);
});
this.doInsideBBlock(right_bb, () => {
// inside the then branch, left was falsy
if (n.operator === "||")
// for || we evaluate the second and store it
ir.createStore(this.visit(n.right), result);
else if (n.operator === "&&")
// for && we short circuit out here
ir.createStore(left_visited, result);
else
throw "Internal error 99.1";
ir.createBr(merge_bb);
});
ir.setInsertPoint(merge_bb);
return this.createLoad(result, `result_${n.operator}_load`);
}
visitArgsForCall (callee, pullThisFromArg0, args) {
args = args.slice();
let argv = [];
if (callee.takes_builtins) {
let thisArg, closure;
if (pullThisFromArg0 && args[0].type === b.MemberExpression) {
thisArg = this.visit(args[0].object);
closure = this.createPropertyLoad(thisArg, args[0].property, args[0].computed);
}
else {
thisArg = this.loadUndefinedEjsValue();
closure = this.visit(args[0]);
}
let this_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "this_alloca");
ir.createStore(thisArg, this_alloca, "this_alloca_store");
args.shift();
argv.push(closure); // %closure
argv.push(this_alloca); // %this
argv.push(consts.int32(args.length)); // %argc
let args_length = args.length;
if (args_length > 0) {
for (let i = 0; i < args_length; i ++) {
args[i] = this.visitOrNull(args[i]);
}
for (let i = 0; i < args_length; i ++) {
let gep = ir.createGetElementPointer(this.currentFunction.scratch_area, [consts.int32(0), consts.int64(i)], `arg_gep_${i}`);
ir.createStore(args[i], gep, `argv[${i}]-store`);
}
let argsCast = ir.createGetElementPointer(this.currentFunction.scratch_area, [consts.int32(0), consts.int64(0)], "call_args_load");
argv.push(argsCast);
}
else {
argv.push(consts.Null(types.EjsValue.pointerTo()));
}
argv.push(this.loadUndefinedEjsValue()); // %newTarget = undefined
}
else {
for (let a of args)
argv.push(this.visitOrNull(a));
}
return argv;
}
debugLog (str) {
if (this.options.debug_level > 0)
this.createCall(this.ejs_runtime.log, [consts.string(ir, str)], "");
}
visitArgsForConstruct (callee, args, this_loc, newTarget_loc) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
args = args.slice();
let argv = [];
// constructors are always .takes_builtins, so we can skip the other case
//
let ctor = this.visit(args[0]);
args.shift();
argv.push(ctor); // %closure
argv.push(this_loc); // %this
argv.push(consts.int32(args.length)); // %argc
if (args.length > 0) {
let visited = [];
for (let a of args)
visited.push(this.visitOrNull(a));
visited.forEach ((a,i) => {
let gep = ir.createGetElementPointer(this.currentFunction.scratch_area, [consts.int32(0), consts.int64(i)], `arg_gep_${i}`);
ir.createStore(a, gep, `argv[${i}]-store`);
});
let argsCast = ir.createGetElementPointer(this.currentFunction.scratch_area, [consts.int32(0), consts.int64(0)], "call_args_load");
argv.push(argsCast);
}
else {
argv.push(consts.Null(types.EjsValue.pointerTo()));
}
argv.push(newTarget_loc || ctor); // %newTarget = ctor
return argv;
}
visitCallExpression (n) {
debug.log ( () => `visitCall ${JSON.stringify(n)}` );
debug.log ( () => ` arguments length = ${n.arguments.length}`);
debug.log ( () => {
return n.arguments.map ( (a, i) => ` arguments[${i}] = ${JSON.stringify(a)}` ).join('');
});
let unescapedName = n.callee.name.slice(1);
let intrinsicHandler = this.ejs_intrinsics[unescapedName];
if (!intrinsicHandler)
throw new Error(`Internal error: callee should not be null in visitCallExpression (callee = '${n.callee.name}', arguments = ${n.arguments.length})`);
return intrinsicHandler.call(this, n, this.opencode_intrinsics[unescapedName]);
}
visitThisExpression (n) {
debug.log("visitThisExpression");
return this.createLoad(this.createLoad(this.findIdentifierInScope("%this"), "load_this_ptr"), "load_this");
}
visitSpreadElement (n) {
throw new Error("halp");
}
visitIdentifier (n) {
let rv;
debug.log ( () => `identifier ${n.name}` );
let val = n.name;
let source = this.findIdentifierInScope(val);
if (source) {
debug.log ( () => `found identifier in scope, at ${source}` );
rv = this.createLoad(source, `load_${val}`);
return rv;
}
// special handling of the arguments object here, so we
// only initialize/create it if the function is
// actually going to use it.
if (val === "arguments") {
let arguments_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "local_arguments_object");
let saved_insert_point = ir.getInsertBlock();
ir.setInsertPoint(this.currentFunction.entry_bb);
let load_argc = this.createLoad(this.currentFunction.topScope.get("%argc"), "argc_load");
let load_args = this.createLoad(this.currentFunction.topScope.get("%args"), "args_load");
let args_new = this.ejs_runtime.arguments_new;
let arguments_object = this.createCall(args_new, [load_argc, load_args], "argstmp", !args_new.doesNotThrow);
ir.createStore(arguments_object, arguments_alloca);
this.currentFunction.topScope.set("arguments", arguments_alloca);
ir.setInsertPoint(saved_insert_point);
return this.createLoad(arguments_alloca, "load_arguments");
}
rv = null;
debug.log ( () => `calling getFunction for ${val}` );
rv = this.module.getFunction(val);
if (!rv) {
debug.log ( () => `Symbol '${val}' not found in current scope` );
rv = this.loadGlobal(n);
}
debug.log ( () => `returning ${rv}` );
return rv;
}
visitObjectExpression (n) {
let obj_proto = ir.createLoad(this.ejs_globals.Object_prototype, "load_objproto");
let object_create = this.ejs_runtime.object_create;
let obj = this.createCall(object_create, [obj_proto], "objtmp", !object_create.doesNotThrow);
let accessor_map = new Map();
// gather all properties so we can emit get+set as a single call to define_accessor_prop.
for (let property of n.properties) {
if (property.kind === "get" || property.kind === "set") {
if (!accessor_map.has(property.key)) accessor_map.set(property.key, new Map);
if (accessor_map.get(property.key).has(property.kind))
throw new SyntaxError(`a '${property.kind}' method for '${escodegenerate(property.key)}' has already been defined.`);
if (accessor_map.get(property.key).has("init"))
throw new SyntaxError(`${property.key.loc.start.line}: property name ${escodegenerate(property.key)} appears once in object literal.`);
}
else if (property.kind === "init") {
if (accessor_map.get(property.key))
throw new SyntaxError(`${property.key.loc.start.line}: property name ${escodegenerate(property.key)} appears once in object literal.`);
accessor_map.set(property.key, new Map);
}
else {
throw new Error(`unrecognized property kind '${property.kind}'`);
}
if (property.computed) {
accessor_map.get(property.key).set("computed", true);
}
accessor_map.get(property.key).set(property.kind, property);
}
accessor_map.forEach ((prop_map, propkey) => {
// XXX we need something like this line below to handle computed properties, but those are broken at the moment
//key = if property.key.type is Identifier then this.getAtom property.key.name else this.visit property.key
if (prop_map.has("computed"))
propkey = this.visit(propkey);
else if (propkey.type == b.Literal)
propkey = this.getAtom(String(propkey.value));
else if (propkey.type === b.Identifier)
propkey = this.getAtom(propkey.name);
if (prop_map.has("init")) {
let val = this.visit(prop_map.get("init").value);
this.createCall(this.ejs_runtime.object_define_value_prop, [obj, propkey, val, consts.int32(0x77)], `define_value_prop_${propkey}`);
}
else {
let getter = prop_map.get("get");
let setter = prop_map.get("set");
let get_method = getter ? this.visit(getter.value) : this.loadUndefinedEjsValue();
let set_method = setter ? this.visit(setter.value) : this.loadUndefinedEjsValue();
this.createCall(this.ejs_runtime.object_define_accessor_prop, [obj, propkey, get_method, set_method, consts.int32(0x19)], `define_accessor_prop_${propkey}`);
}
});
return obj;
}
visitArrayExpression (n) {
let force_fill = false;
// if there are holes, we need to fill the array at allocation time.
// FIXME(toshok) we could just as easily have the compiler emit code to initialize the holes as well, right?
for (let el of n.elements) {
if (el == null) {
force_fill = true;
break;
}
}
let obj = this.createCall(this.ejs_runtime.array_new, [consts.int32(n.elements.length), consts.bool(force_fill)], "arrtmp", !this.ejs_runtime.array_new.doesNotThrow);
let i = 0;
for (let el of n.elements) {
// don't create property stores for array holes
if (el == null) continue;
let val = this.visit(el);
let index = { type: b.Literal, value: i };
this.createPropertyStore(obj, index, val, true);
i = i + 1;
}
return obj;
}
visitExpressionStatement (n) {
n.expression.result_not_used = true;
return this.visit(n.expression);
}
generateUCS2 (id, jsstr) {
let ucsArrayType = llvm.ArrayType.get(types.JSChar, jsstr.length+1);
let array_data = [];
for (let i = 0, e = jsstr.length; i < e; i ++)
array_data.push(consts.jschar(jsstr.charCodeAt(i)));
array_data.push(consts.jschar(0));
let array = llvm.ConstantArray.get(ucsArrayType, array_data);
let arrayglobal = new llvm.GlobalVariable(this.module, ucsArrayType, `ucs2-${id}`, array, false);
arrayglobal.setAlignment(8);
return arrayglobal;
}
generateEJSPrimString (id, len) {
let strglobal = new llvm.GlobalVariable(this.module, types.EjsPrimString, `primstring-${id}`, llvm.Constant.getAggregateZero(types.EjsPrimString), false);
strglobal.setAlignment(8);
return strglobal;
}
generateEJSValueForString (id) {
let name = `ejsval-${id}`;
let strglobal = new llvm.GlobalVariable(this.module, types.EjsValue, name, llvm.Constant.getAggregateZero(types.EjsValue), false);
strglobal.setAlignment(8);
let val = this.module.getOrInsertGlobal(name, types.EjsValue);
val.setAlignment(8);
return val;
}
addStringLiteralInitialization (name, ucs2, primstr, val, len) {
let saved_insert_point = ir.getInsertBlock();
ir.setInsertPointStartBB(this.literalInitializationBB);
let saved_debug_loc;
if (this.options.debug) {
saved_debug_loc = ir.getCurrentDebugLocation();
ir.setCurrentDebugLocation(llvm.DebugLoc.get(0, 0, this.literalInitializationDebugInfo));
}
let strname = consts.string(ir, name);
let arg0 = strname;
let arg1 = val;
let arg2 = primstr;
let arg3 = ir.createInBoundsGetElementPointer(ucs2, [consts.int32(0), consts.int32(0)], "ucs2");
ir.createCall(this.ejs_runtime.init_string_literal, [arg0, arg1, arg2, arg3, consts.int32(len)], "");
ir.setInsertPoint(saved_insert_point);
if (this.options.debug)
ir.setCurrentDebugLocation(saved_debug_loc);
}
getAtom (str) {
// check if it's an atom (a runtime library constant) first of all
if (hasOwn.call(this.ejs_atoms, str))
return this.createLoad(this.ejs_atoms[str], `${str}_atom_load`);
// if it's not, we create a constant and embed it in this module
if (!this.module_atoms.has(str)) {
let literalId = this.idgen();
let ucs2_data = this.generateUCS2(literalId, str);
let primstring = this.generateEJSPrimString(literalId, str.length);
let ejsval = this.generateEJSValueForString(str);
this.module_atoms.set(str, ejsval);
this.addStringLiteralInitialization(str, ucs2_data, primstring, ejsval, str.length);
}
return this.createLoad(this.module_atoms.get(str), "literal_load");
}
visitLiteral (n) {
// null literals, load _ejs_null
if (n.value === null) {
debug.log("literal: null");
return this.loadNullEjsValue();
}
// undefined literals, load _ejs_undefined
if (n.value === undefined) {
debug.log("literal: undefined");
return this.loadUndefinedEjsValue();
}
// string literals
if (typeof n.raw === "string" && (n.raw[0] === '"' || n.raw[0] === "'")) {
debug.log ( () => `literal string: ${n.value}` );
var strload = this.getAtom(n.value);
strload.literal = n;
debug.log ( () => `strload = ${strload}` );
return strload;
}
// regular expression literals
if (typeof n.raw === "string" && n.raw[0] === '/') {
debug.log ( () => `literal regexp: ${n.raw}` );
let source = consts.string(ir, n.value.source);
let flags = consts.string(ir, `${n.value.global ? 'g' : ''}${n.value.multiline ? 'm' : ''}${n.value.ignoreCase ? 'i' : ''}`);
let regexp_new_utf8 = this.ejs_runtime.regexp_new_utf8;
var regexpcall = this.createCall(regexp_new_utf8, [source, flags], "regexptmp", !regexp_new_utf8.doesNotThrow);
debug.log ( () => `regexpcall = ${regexpcall}` );
return regexpcall;
}
// number literals
if (typeof n.value === "number") {
debug.log ( () => `literal number: ${n.value}` );
return this.loadDoubleEjsValue(n.value);
}
// boolean literals
if (typeof n.value === "boolean") {
debug.log ( () => `literal boolean: ${n.value}` );
return this.loadBoolEjsValue(n.value);
}
throw `Internal error: unrecognized literal of type ${typeof n.value}`;
}
createCall (callee, argv, callname, canThrow=true) {
// if we're inside a try block we have to use createInvoke, and pass two basic blocks:
// the normal block, which is basically this IR instruction's continuation
// the unwind block, where we land if the call throws an exception.
//
// Although for builtins we know won't throw, we can still use createCall.
let calltmp;
if (TryExitableScope.unwindStack.depth === 0 || callee.doesNotThrow || !canThrow) {
//ir.createCall this.ejs_runtime.log, [consts.string(ir, `calling ${callee.name}`)], ""
calltmp = this.abi.createCall(this.currentFunction, callee, argv, callname);
}
else {
let normal_block = new llvm.BasicBlock ("normal", this.currentFunction);
//ir.createCall this.ejs_runtime.log, [consts.string(ir, `invoking ${callee.name}`)], ""
calltmp = this.abi.createInvoke(this.currentFunction, callee, argv, normal_block, TryExitableScope.unwindStack.top.getLandingPadBlock(), callname);
// after we've made our call we need to change the insertion point to our continuation
ir.setInsertPoint(normal_block);
}
return calltmp;
}
visitThrow (n) {
let arg = this.visit(n.argument);
this.createCall(this.ejs_runtime.throw, [arg], "", true);
return ir.createUnreachable();
}
visitTry (n) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let finally_block = null;
let catch_block = null;
// the alloca that stores the reason we ended up in the finally block
if (!this.currentFunction.cleanup_reason)
this.currentFunction.cleanup_reason = this.createAlloca(this.currentFunction, types.Int32, "cleanup_reason");
// if we have a finally clause, create finally_block
if (n.finalizer) {
finally_block = new llvm.BasicBlock ("finally_bb", insertFunc);
this.finallyStack.unshift (finally_block);
}
// the merge bb where everything branches to after falling off the end of a catch/finally block
let merge_block = new llvm.BasicBlock ("try_merge", insertFunc);
let branch_target = finally_block ? finally_block : merge_block;
let scope = new TryExitableScope(this.currentFunction.cleanup_reason, branch_target, (() => new llvm.BasicBlock("exception", insertFunc)), finally_block != null);
this.doInsideExitableScope (scope, () => {
scope.enterTry();
this.visit(n.block);
if (n.finalizer)
this.finallyStack.shift();
// at the end of the try block branch to our branch_target (either the finally block or the merge block after the try{}) with REASON_FALLOFF
scope.exitAft(false);
scope.leaveTry();
});
if (scope.landing_pad_block && n.handlers.length > 0)
catch_block = new llvm.BasicBlock ("catch_bb", insertFunc);
if (scope.landing_pad_block) {
// the scope's landingpad block is created if needed by this.createCall (using that function we pass in as the last argument to TryExitableScope's ctor.)
// if a try block includes no calls, there's no need for an landing pad block as nothing can throw, and we don't bother generating any code for the
// catch clause.
this.doInsideBBlock (scope.landing_pad_block, () => {
let landing_pad_type = llvm.StructType.create("", [types.Int8Pointer, types.Int32]);
// XXX is it an error to have multiple catch handlers, as JS doesn't allow you to filter by type?
let clause_count = n.handlers.length > 0 ? 1 : 0;
let casted_personality = ir.createPointerCast(this.ejs_runtime.personality, types.Int8Pointer, "personality");
let caught_result = ir.createLandingPad(landing_pad_type, casted_personality, clause_count, "caught_result");
caught_result.addClause(ir.createPointerCast(this.ejs_runtime.exception_typeinfo, types.Int8Pointer, ""));
caught_result.setCleanup(true);
let exception = ir.createExtractValue(caught_result, 0, "exception");
if (catch_block)
ir.createBr(catch_block);
else if (finally_block)
ir.createBr(finally_block);
else
throw "this shouldn't happen. a try{} without either a catch{} or finally{}";
// if we have a catch clause, create catch_bb
if (n.handlers.length > 0) {
this.doInsideBBlock (catch_block, () => {
// call _ejs_begin_catch to return the actual exception
let catchval = this.beginCatch(exception);
// create a new scope which maps the catch parameter name (the "e" in "try { } catch (e) { }") to catchval
let catch_scope = new Map;
if (n.handlers[0].param && n.handlers[0].param.name) {
let catch_name = n.handlers[0].param.name;
let alloca = this.createAlloca(this.currentFunction, types.EjsValue, `local_catch_${catch_name}`);
catch_scope.set(catch_name, alloca);
ir.createStore(catchval, alloca);
}
if (n.finalizer)
this.finallyStack.unshift(finally_block);
this.doInsideExitableScope(scope, () => {
this.visitWithScope(catch_scope, [n.handlers[0]]);
});
// unsure about this one - we should likely call end_catch if another exception is thrown from the catch block?
this.endCatch();
if (n.finalizer)
this.finallyStack.shift();
// at the end of the catch block branch to our branch_target (either the finally block or the merge block after the try{}) with REASON_FALLOFF
scope.exitAft(false);
});
}
});
}
// Finally Block
if (n.finalizer) {
this.doInsideBBlock (finally_block, () => {
this.visit(n.finalizer);
let cleanup_reason = this.createLoad(this.currentFunction.cleanup_reason, "cleanup_reason_load");
let return_tramp = null;
if (this.currentFunction.returnValueAlloca) {
return_tramp = new llvm.BasicBlock ("return_tramp", insertFunc);
this.doInsideBBlock (return_tramp, () => {
if (this.finallyStack.length > 0) {
ir.createStore(consts.int32(ExitableScope.REASON_RETURN), this.currentFunction.cleanup_reason);
ir.createBr(this.finallyStack[0]);
}
else {
this.createRet(this.createLoad(this.currentFunction.returnValueAlloca, "rv"));
}
});
}
let switch_stmt = ir.createSwitch(cleanup_reason, merge_block, scope.destinations.length + 1);
if (this.currentFunction.returnValueAlloca)
switch_stmt.addCase(consts.int32(ExitableScope.REASON_RETURN), return_tramp);
let falloff_tramp = new llvm.BasicBlock("falloff_tramp", insertFunc);
this.doInsideBBlock (falloff_tramp, () => {
ir.createBr(merge_block);
});
switch_stmt.addCase(consts.int32(TryExitableScope.REASON_FALLOFF_TRY), falloff_tramp);
for (let s = 0, e = scope.destinations.length; s < e; s ++) {
let dest_tramp = new llvm.BasicBlock("dest_tramp", insertFunc);
var dest = scope.destinations[s];
this.doInsideBBlock (dest_tramp, () => {
if (dest.reason == TryExitableScope.REASON_BREAK)
dest.scope.exitAft(true);
else if (dest.reason == TryExitableScope.REASON_CONTINUE)
dest.scope.exitFore();
});
switch_stmt.addCase(dest.id, dest_tramp);
}
});
}
ir.setInsertPoint(merge_block);
}
handleTemplateDefaultHandlerCall (exp, opencode) {
// we should probably only inline the construction of the string if substitutions.length < $some-number
let cooked_strings = exp.arguments[0].elements;
let substitutions = exp.arguments[1].elements;
let cooked_i = 0;
let sub_i = 0;
let strval = null;
let concat_string = (s) => {
if (!strval)
strval = s;
else
strval = this.createCall(this.ejs_runtime.string_concat, [strval, s], "strconcat");
};
while (cooked_i < cooked_strings.length) {
let c = cooked_strings[cooked_i];
cooked_i += 1;
if (c.length !== 0)
concat_string(this.getAtom(c.value));
if (sub_i < substitutions.length) {
let sub = this.visit(substitutions[sub_i]);
concat_string(this.createCall(this.ejs_runtime.ToString, [sub], "subToString"));
sub_i += 1;
}
}
return strval;
}
handleTemplateCallsite (exp, opencode) {
// we expect to be called with context something of the form:
//
// function generate_callsiteId0 () {
// %templateCallsite(%callsiteId_0,
// [], // raw
// [] // cooked
// });
// }
//
// and we need to generate something along the lines of:
//
// global const %callsiteId_0 = null; // an llvm IR construct
//
// function generate_callsiteId0 () {
// if (!%callsiteId_0) {
// _ejs_gc_add_root(&%callsiteId_0);
// %callsiteId_0 = []; // cooked
// %callsiteId_0.raw = [];
// %callsiteId_0.freeze();
// }
// return callsiteId_0;
// }
//
// our containing function already exists, so we just
// need to replace the intrinsic with the new contents.
//
// XXX there's no reason to dynamically create the
// callsite, other than it being easier for now. The
// callsite id's structure is known at compile time so
// everything could be allocated from the data segment
// and just used from there (much the same way we do
// with string literals.)
let callsite_id = exp.arguments[0].value;
let callsite_raw_literal = exp.arguments[1];
let callsite_cooked_literal = exp.arguments[2];
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
let then_bb = new llvm.BasicBlock ("then", insertFunc);
let merge_bb = new llvm.BasicBlock ("merge", insertFunc);
let callsite_alloca = this.createAlloca(this.currentFunction, types.EjsValue, `local_${callsite_id}`);
let callsite_global = new llvm.GlobalVariable(this.module, types.EjsValue, callsite_id, llvm.Constant.getAggregateZero(types.EjsValue), false);
let global_callsite_load = this.createLoad(callsite_global, "load_global_callsite");
ir.createStore(global_callsite_load, callsite_alloca);
let callsite_load = ir.createLoad(callsite_alloca, "load_local_callsite");
let isnull = this.isNumber(callsite_load);
ir.createCondBr(isnull, then_bb, merge_bb);
this.doInsideBBlock (then_bb, () => {
this.createCall(this.ejs_runtime.gc_add_root, [callsite_global], "");
// XXX missing: register callsite_obj gc root
let callsite_cooked = this.visit(callsite_cooked_literal);
let callsite_raw = this.visit(callsite_raw_literal);
let frozen_raw = this.createCall(this.ejs_runtime.object_freeze, [callsite_raw], "frozen_raw");
this.createCall(this.ejs_runtime.object_setprop, [callsite_cooked, this.visit(b.literal("raw")), frozen_raw], "propstore_raw");
let frozen_cooked = this.createCall(this.ejs_runtime.object_freeze, [callsite_cooked], "frozen_cooked");
ir.createStore(frozen_cooked, callsite_global);
ir.createStore(frozen_cooked, callsite_alloca);
ir.createBr(merge_bb);
});
ir.setInsertPoint(merge_bb);
return ir.createRet(ir.createLoad(callsite_alloca, "load_local_callsite"));
}
handleModuleGet (exp, opencode) {
let moduleString = this.visit(exp.arguments[0].value);
return this.createCall(this.ejs_runtime.module_get, [moduleString], "moduletmp");
}
handleModuleSlotRef (exp, opencode) {
let moduleString = exp.arguments[0].value;
let exportId = exp.arguments[1].value;
let module_global;
if (moduleString.endsWith(".js"))
moduleString = moduleString.substring(0, moduleString.length-3);
if (moduleString === this.this_module_info.path) {
module_global = this.this_module_global;
}
else {
module_global = this.import_module_globals.get(moduleString);
}
module_global = ir.createPointerCast(module_global, types.EjsModule.pointerTo(), "");
let slotnum = this.allModules.get(moduleString).exports.get(exportId).slot_num;
if (opencode && this.options.target_pointer_size === 64) {
return ir.createInBoundsGetElementPointer(module_global, [consts.int64(0), consts.int32(3), consts.int64(slotnum)], "slot_ref");
}
else {
return this.createCall(this.ejs_runtime.module_get_slot_ref, [module_global, consts.int32(slotnum)], "module_slot");
}
}
handleModuleGetSlot (exp, opencode) {
let slot_ref = this.handleModuleSlotRef(exp, opencode);
return ir.createLoad(slot_ref, "module_slot_load");
}
handleModuleSetSlot (exp, opencode) {
let arg = exp.arguments[2];
let slot_ref = this.handleModuleSlotRef(exp, opencode);
this.storeToDest(slot_ref, arg);
return ir.createLoad(slot_ref, "load_slot"); // do we need this? we don't need to keep assignment expression semantics for this
}
handleModuleGetExotic (exp, opencode) {
/*
let moduleString = exp.arguments[0].value;
if (moduleString === this.this_module_info.path) {
let module_global = this.this_module_global;
return this.emitEjsvalFromPtr(module_global, "exotic");
}
else if (this.import_module_globals.has(moduleString)) {
let module_global = this.import_module_globals.get(moduleString)
return this.emitEjsvalFromPtr(module_global, "exotic");
}
else {
*/
return this.createCall(this.ejs_runtime.module_get, [this.visit(exp.arguments[0])], "get_module_exotic");
/*
}
*/
}
handleGetArg (exp, opencode) {
let load_args = this.createLoad(this.currentFunction.topScope.get("%args"), "args_load");
let arg_i = exp.arguments[0].value;
let arg_ptr = ir.createGetElementPointer(load_args, [consts.int32(arg_i)], `arg${arg_i}_ptr`);
return this.createLoad(arg_ptr, `arg${arg_i}`);
}
handleGetNewTarget (exp, opencode) {
return this.createLoad(this.findIdentifierInScope("%newTarget"), "new_target_load");
}
handleGetArgumentsObject (exp, opencode) {
let arguments_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "local_arguments_object");
let saved_insert_point = ir.getInsertBlock();
ir.setInsertPoint(this.currentFunction.entry_bb);
let load_argc = this.createLoad(this.currentFunction.topScope.get("%argc"), "argc_load");
let load_args = this.createLoad(this.currentFunction.topScope.get("%args"), "args_load");
let args_new = this.ejs_runtime.arguments_new;
let arguments_object = this.createCall(args_new, [load_argc, load_args], "argstmp", !args_new.doesNotThrow);
ir.createStore(arguments_object, arguments_alloca);
this.currentFunction.topScope.set("arguments", arguments_alloca);
ir.setInsertPoint(saved_insert_point);
return this.createLoad(arguments_alloca, "load_arguments");
}
handleGetLocal (exp, opencode) { return this.createLoad(this.findIdentifierInScope(exp.arguments[0].name), `load_${exp.arguments[0].name}`); }
handleGetGlobal (exp, opencode) { return this.loadGlobal(exp.arguments[0]); }
handleSetLocal (exp, opencode) {
let dest = this.findIdentifierInScope(exp.arguments[0].name);
if (!dest)
throw new Error(`identifier not found: ${exp.arguments[0].name}`);
let arg = exp.arguments[1];
this.storeToDest(dest, arg);
return ir.createLoad(dest, "load_val");
}
handleSetGlobal (exp, opencode) {
let gname = exp.arguments[0].name;
if (this.options.frozen_global)
throw new SyntaxError(`cannot set global property '${exp.arguments[0].name}' when using --frozen-global`);
let gatom = this.getAtom(gname);
let value = this.visit(exp.arguments[1]);
return this.createCall(this.ejs_runtime.global_setprop, [gatom, value], `globalpropstore_${gname}`);
}
// this method assumes it's called in an opencoded context
emitEjsvalTo (val, type, prefix) {
if (this.options.target_pointer_size === 64) {
let payload = this.createEjsvalAnd(val, consts.int64_lowhi(0x7fff, 0xffffffff), `${prefix}_payload`);
return ir.createIntToPtr(payload, type, `${prefix}_load`);
}
else {
throw new Error("emitEjsvalTo not implemented for this case");
}
}
emitEjsvalFromPtr (ptr, prefix) {
if (this.options.target_pointer_size === 64) {
let fromptr_alloca = this.createAlloca(this.currentFunction, types.EjsValue, `${prefix}_ejsval`);
let intval = ir.createPtrToInt(ptr, types.Int64, `${prefix}_intval`);
let payload = ir.createOr(intval, consts.int64_lowhi(0xFFFC0000, 0x00000000), `${prefix}_payload`);
let alloca_as_int64 = ir.createBitCast(fromptr_alloca, types.Int64.pointerTo(), `${prefix}_alloca_asptr`);
ir.createStore(payload, alloca_as_int64, `${prefix}_store`);
ir.createLoad(fromptr_alloca, `${prefix}_load`);
}
else {
throw new Error("emitEjsvalTo not implemented for this case");
}
}
emitEjsvalToObjectPtr (val) {
return this.emitEjsvalTo(val, types.EjsObject.pointerTo(), "to_objectptr");
}
emitEjsvalToClosureEnvPtr (val) {
return this.emitEjsvalTo(val, types.EjsClosureEnv.pointerTo(), "to_ptr");
}
// this method assumes it's called in an opencoded context
emitLoadSpecops (obj) {
if (this.options.target_pointer_size === 64) {
// %1 = getelementptr inbounds %struct._EJSObject* %obj, i64 0, i32 1
// %specops_load = load %struct.EJSSpecOps** %1, align 8, !tbaa !0
let specops_slot = ir.createInBoundsGetElementPointer(obj, [consts.int64(0), consts.int32(1)], "specops_slot");
return ir.createLoad(specops_slot, "specops_load");
}
else {
throw new Error("emitLoadSpecops not implemented for this case");
}
}
emitThrowNativeError (errorCode, errorMessage) {
this.createCall(this.ejs_runtime.throw_nativeerror_utf8, [consts.int32(errorCode), consts.string(ir, errorMessage)], "", true);
return ir.createUnreachable();
}
// this method assumes it's called in an opencoded context
emitLoadEjsFunctionClosureFunc (closure) {
if (this.options.target_pointer_size === 64) {
let func_slot_gep = ir.createInBoundsGetElementPointer(closure, [consts.int64(1)], "func_slot_gep");
let func_slot = ir.createBitCast(func_slot_gep, this.abi.createFunctionType(types.EjsValue, [types.EjsValue, types.EjsValue, types.Int32, types.EjsValue.pointerTo()]).pointerTo().pointerTo(), "func_slot");
return ir.createLoad(func_slot, "func_load");
}
else {
throw new Error("emitLoadEjsFunctionClosureFunc not implemented for this case");
}
}
// this method assumes it's called in an opencoded context
emitLoadEjsFunctionClosureEnv (closure) {
if (this.options.target_pointer_size === 64) {
let env_slot_gep = ir.createInBoundsGetElementPointer(closure, [consts.int64(1), consts.int32(1)], "env_slot_gep");
let env_slot = ir.createBitCast(env_slot_gep, types.EjsValue.pointerTo(), "env_slot");
return ir.createLoad(env_slot, "env_load");
}
else {
throw new Error("emitLoadEjsFunctionClosureEnv not implemented for this case");
}
}
handleInvokeClosure (exp, opencode) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
if (!this.currentFunction.scratch_area) {
throw new Error(`Internal error: function has no scratch space and makes a [[Call]] call with ${exp.arguments.length} arguments`);
}
let argv = this.visitArgsForCall(this.ejs_runtime.invoke_closure, true, exp.arguments);
if (opencode && this.options.target_pointer_size === 64) {
//
// generate basically the following code:
//
// f = argv[0]
// if (EJSVAL_IS_FUNCTION(F)
// f->func(f->env, argv[1], argv[2], argv[3])
// else
// _ejs_invoke_closure(...argv)
//
let candidate_is_object_bb = new llvm.BasicBlock ("candidate_is_object_bb", insertFunc);
var direct_invoke_bb = new llvm.BasicBlock ("direct_invoke_bb", insertFunc);
var runtime_invoke_bb = new llvm.BasicBlock ("runtime_invoke_bb", insertFunc);
var invoke_merge_bb = new llvm.BasicBlock ("invoke_merge_bb", insertFunc);
let cmp = this.isObject(argv[0]);
ir.createCondBr(cmp, candidate_is_object_bb, runtime_invoke_bb);
var call_result_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "call_result");
this.doInsideBBlock (candidate_is_object_bb, () => {
let closure = this.emitEjsvalToObjectPtr(argv[0]);
let cmp = this.isObjectFunction(closure);
ir.createCondBr(cmp, direct_invoke_bb, runtime_invoke_bb);
// in the successful case we modify our argv with the responses and directly invoke the closure func
this.doInsideBBlock (direct_invoke_bb, () => {
let func_load = this.emitLoadEjsFunctionClosureFunc(closure);
let env_load = this.emitLoadEjsFunctionClosureEnv(closure);
let direct_call_result = this.createCall(func_load, [env_load, argv[1], argv[2], argv[3], argv[4], argv[5]], "callresult");
ir.createStore(direct_call_result, call_result_alloca);
ir.createBr(invoke_merge_bb);
});
this.doInsideBBlock (runtime_invoke_bb, () => {
let runtime_call_result = this.createCall(this.ejs_runtime.invoke_closure, argv, "callresult", true);
ir.createStore(runtime_call_result, call_result_alloca);
ir.createBr(invoke_merge_bb);
});
});
ir.setInsertPoint(invoke_merge_bb);
return ir.createLoad(call_result_alloca, "call_result_load");
}
else {
return this.createCall(this.ejs_runtime.invoke_closure, argv, "call", true);
}
}
handleConstructClosure (exp, opencode) {
let this_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "this_alloca");
this.storeUndefined(this_alloca, "store_undefined_this");
if (!this.currentFunction.scratch_area) {
throw new Error(`Internal error: function has no scratch space and makes a [[Construct]] call with ${exp.arguments.length} arguments`);
}
let argv = this.visitArgsForConstruct(this.ejs_runtime.construct_closure, exp.arguments, this_alloca);
return this.createCall(this.ejs_runtime.construct_closure, argv, "construct", true);
}
handleConstructSuper (exp, opencode) {
let this_ptr = this.createLoad(this.findIdentifierInScope("%this"), "this_ptr");
let newTarget = this.createLoad(this.findIdentifierInScope("%newTarget"), "load_newTarget");
let argv = this.visitArgsForConstruct(this.ejs_runtime.construct_closure, exp.arguments, this_ptr, newTarget);
return this.createCall(this.ejs_runtime.construct_closure, argv, "construct_super", true);
}
handleConstructSuperApply (exp, opencode) {
let this_ptr = this.createLoad(this.findIdentifierInScope("%this"), "this_ptr");
let newTarget = this.createLoad(this.findIdentifierInScope("%newTarget"), "load_newTarget");
let argv = this.visitArgsForConstruct(this.ejs_runtime.construct_closure_apply, exp.arguments, this_ptr, newTarget);
return this.createCall(this.ejs_runtime.construct_closure_apply, argv, "construct_super_apply", true);
}
handleSetConstructorKindDerived (exp, opencode) {
let ctor = this.visit(exp.arguments[0]);
return this.createCall(this.ejs_runtime.set_constructor_kind_derived, [ctor], "");
}
handleSetConstructorKindBase (exp, opencode) {
let ctor = this.visit(exp.arguments[0]);
return this.createCall(this.ejs_runtime.set_constructor_kind_base, [ctor], "");
}
handleMakeGenerator (exp, opencode) {
let argv = this.visitArgsForCall(this.ejs_runtime.make_generator, false, exp.arguments);
return this.createCall(this.ejs_runtime.make_generator, argv, "generator");
}
handleGeneratorYield (exp, opencode) {
let argv = this.visitArgsForCall(this.ejs_runtime.generator_yield, false, exp.arguments);
return this.createCall(this.ejs_runtime.generator_yield, argv, "yield");
}
handleMakeClosure (exp, opencode) {
let argv = this.visitArgsForCall(this.ejs_runtime.make_closure, false, exp.arguments);
return this.createCall(this.ejs_runtime.make_closure, argv, "closure_tmp");
}
handleMakeClosureNoEnv (exp, opencode) {
let argv = this.visitArgsForCall(this.ejs_runtime.make_closure_noenv, false, exp.arguments);
return this.createCall(this.ejs_runtime.make_closure_noenv, argv, "closure_tmp");
}
handleMakeAnonClosure (exp, opencode) {
let argv = this.visitArgsForCall(this.ejs_runtime.make_anon_closure, false, exp.arguments);
return this.createCall(this.ejs_runtime.make_anon_closure, argv, "closure_tmp");
}
handleCreateArgScratchArea (exp, opencode) {
let argsArrayType = llvm.ArrayType.get(types.EjsValue, exp.arguments[0].value);
this.currentFunction.scratch_length = exp.arguments[0].value;
this.currentFunction.scratch_area = this.createAlloca(this.currentFunction, argsArrayType, "args_scratch_area");
this.currentFunction.scratch_area.setAlignment(8);
return this.currentFunction.scratch_area;
}
handleMakeClosureEnv (exp, opencode) {
let size = exp.arguments[0].value;
return this.createCall(this.ejs_runtime.make_closure_env, [consts.int32(size)], "env_tmp");
}
handleGetSlot (exp, opencode) {
//
// %ref = handleSlotRef
// %ret = load %EjsValueType* %ref, align 8
//
let slot_ref = this.handleSlotRef(exp, opencode);
return ir.createLoad(slot_ref, "slot_ref_load");
}
handleSetSlot (exp, opencode) {
let new_slot_val;
if (exp.arguments.length === 4)
new_slot_val = exp.arguments[3];
else
new_slot_val = exp.arguments[2];
let slotref = this.handleSlotRef(exp, opencode);
this.storeToDest(slotref, new_slot_val);
return ir.createLoad(slotref, "load_slot");
}
handleSlotRef (exp, opencode) {
let env = this.visitOrNull(exp.arguments[0]);
let slotnum = exp.arguments[1].value;
if (opencode && this.options.target_pointer_size === 64) {
let envp = this.emitEjsvalToClosureEnvPtr(env);
return ir.createInBoundsGetElementPointer(envp, [consts.int64(0), consts.int32(2), consts.int64(slotnum)], "slot_ref");
}
else {
return this.createCall(this.ejs_runtime.get_env_slot_ref, [env, consts.int32(slotnum)], "slot_ref_tmp", false);
}
}
createEjsBoolSelect (val, falseval = false) {
let rv = ir.createSelect(val, this.loadBoolEjsValue(!falseval), this.loadBoolEjsValue(falseval), "sel");
rv._ejs_returns_ejsval_bool = true;
return rv;
}
getEjsvalBits (arg) {
let bits_alloca;
if (this.currentFunction.bits_alloca)
bits_alloca = this.currentFunction.bits_alloca;
else
bits_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "bits_alloca");
ir.createStore(arg, bits_alloca);
let bits_ptr = ir.createBitCast(bits_alloca, types.Int64.pointerTo(), "bits_ptr");
if (!this.currentFunction.bits_alloca)
this.currentFunction.bits_alloca = bits_alloca;
return ir.createLoad(bits_ptr, "bits_load");
}
createEjsvalICmpUGt (arg, i64_const, name) { return ir.createICmpUGt(this.getEjsvalBits(arg), i64_const, name); }
createEjsvalICmpULt (arg, i64_const, name) { return ir.createICmpULt(this.getEjsvalBits(arg), i64_const, name); }
createEjsvalICmpEq (arg, i64_const, name) { return ir.createICmpEq (this.getEjsvalBits(arg), i64_const, name); }
createEjsvalAnd (arg, i64_const, name) { return ir.createAnd (this.getEjsvalBits(arg), i64_const, name); }
isObject (val) {
if (this.options.target_pointer_size === 64) {
return this.createEjsvalICmpUGt(val, consts.int64_lowhi(0xfffbffff, 0xffffffff), "cmpresult");
}
else {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffffffff, 0x00000000), "mask.i");
return ir.createICmpEq(mask, consts.int64_lowhi(0xffffff88, 0x00000000), "cmpresult");
}
}
isObjectFunction (obj) {
return ir.createICmpEq(this.emitLoadSpecops(obj), this.ejs_runtime.function_specops, "function_specops_cmp");
}
isObjectSymbol (obj) {
return ir.createICmpEq(this.emitLoadSpecops(obj), this.ejs_runtime.symbol_specops, "symbol_specops_cmp");
}
isString (val) {
if (this.options.target_pointer_size === 64) {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffff8000, 0x00000000), "mask.i");
return ir.createICmpEq(mask, consts.int64_lowhi(0xfffa8000, 0x00000000), "cmpresult");
}
else {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffffffff, 0x00000000), "mask.i");
return ir.createICmpEq(mask, consts.int64_lowhi(0xffffff85, 0x00000000), "cmpresult");
}
}
isNumber (val) {
if (this.options.target_pointer_size === 64) {
return this.createEjsvalICmpULt(val, consts.int64_lowhi(0xfff80001, 0x00000000), "cmpresult");
}
else {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffffffff, 0x00000000), "mask.i");
return ir.createICmpUlt(mask, consts.int64_lowhi(0xffffff81, 0x00000000), "cmpresult");
}
}
isBoolean (val) {
if (this.options.target_pointer_size === 64) {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffff8000, 0x00000000), "mask.i");
return ir.createICmpEq(mask, consts.int64_lowhi(0xfff98000, 0x00000000), "cmpresult");
}
else {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffffffff, 0x00000000), "mask.i");
return ir.createICmpEq(mask, consts.int64_lowhi(0xffffff83, 0x00000000), "cmpresult");
}
}
// these two could/should be changed to check for the specific bitpattern of _ejs_true/_ejs_false
isTrue (val) { return ir.createICmpEq(val, consts.ejsval_true(), "cmpresult"); }
isFalse (val) { return ir.createICmpEq(val, consts.ejsval_false(), "cmpresult"); }
isUndefined (val) {
if (this.options.target_pointer_size === 64) {
return this.createEjsvalICmpEq(val, consts.int64_lowhi(0xfff90000, 0x00000000), "cmpresult");
}
else {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffffffff, 0x00000000), "mask.i");
return ir.createICmpEq(mask, consts.int64_lowhi(0xffffff82, 0x00000000), "cmpresult");
}
}
isNull (val) {
if (this.options.target_pointer_size === 64) {
return this.createEjsvalICmpEq(val, consts.int64_lowhi(0xfffb8000, 0x00000000), "cmpresult");
}
else {
let mask = this.createEjsvalAnd(val, consts.int64_lowhi(0xffffffff, 0x00000000), "mask.i");
return ir.createICmpEq(mask, consts.int64_lowhi(0xffffff87, 0x00000000), "cmpresult");
}
}
handleTypeofIsObject (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
return this.createEjsBoolSelect(this.isObject(arg));
}
handleTypeofIsFunction (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
if (opencode && this.options.target_pointer_size === 64) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
var typeofIsFunction_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "typeof_is_function");
var failure_bb = new llvm.BasicBlock ("typeof_function_false", insertFunc);
let is_object_bb = new llvm.BasicBlock ("typeof_function_is_object", insertFunc);
var success_bb = new llvm.BasicBlock ("typeof_function_true", insertFunc);
var merge_bb = new llvm.BasicBlock ("typeof_function_merge", insertFunc);
let cmp = this.isObject(arg, true);
ir.createCondBr(cmp, is_object_bb, failure_bb);
this.doInsideBBlock (is_object_bb, () => {
let obj = this.emitEjsvalToObjectPtr(arg);
let cmp = this.isObjectFunction(obj);
ir.createCondBr(cmp, success_bb, failure_bb);
});
this.doInsideBBlock (success_bb, () => {
this.storeBoolean(typeofIsFunction_alloca, true, "store_typeof");
ir.createBr(merge_bb);
});
this.doInsideBBlock (failure_bb, () => {
this.storeBoolean(typeofIsFunction_alloca, false, "store_typeof");
ir.createBr(merge_bb);
});
ir.setInsertPoint(merge_bb);
let rv = ir.createLoad(typeofIsFunction_alloca, "typeof_is_function");
rv._ejs_returns_ejsval_bool = true;
return rv;
}
else {
return this.createCall(this.ejs_runtime.typeof_is_function, [arg], "is_function", false);
}
}
handleTypeofIsSymbol (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
if (opencode && this.options.target_pointer_size === 64) {
let insertBlock = ir.getInsertBlock();
let insertFunc = insertBlock.parent;
var typeofIsSymbol_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "typeof_is_symbol");
var failure_bb = new llvm.BasicBlock ("typeof_symbol_false", insertFunc);
let is_object_bb = new llvm.BasicBlock ("typeof_symbol_is_object", insertFunc);
var success_bb = new llvm.BasicBlock ("typeof_symbol_true", insertFunc);
var merge_bb = new llvm.BasicBlock ("typeof_symbol_merge", insertFunc);
let cmp = this.isObject(arg, true);
ir.createCondBr(cmp, is_object_bb, failure_bb);
this.doInsideBBlock (is_object_bb, () => {
let obj = this.emitEjsvalToObjectPtr(arg);
let cmp = this.isObjectSymbol(obj);
ir.createCondBr(cmp, success_bb, failure_bb);
});
this.doInsideBBlock (success_bb, () => {
this.storeBoolean(typeofIsSymbol_alloca, true, "store_typeof");
ir.createBr(merge_bb);
});
this.doInsideBBlock (failure_bb, () => {
this.storeBoolean(typeofIsSymbol_alloca, false, "store_typeof");
ir.createBr(merge_bb);
});
ir.setInsertPoint(merge_bb);
let rv = ir.createLoad(typeofIsSymbol_alloca, "typeof_is_symbol");
rv._ejs_returns_ejsval_bool = true;
return rv;
}
else {
return this.createCall(this.ejs_runtime.typeof_is_symbol, [arg], "is_symbol", false);
}
}
handleTypeofIsString (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
return this.createEjsBoolSelect(this.isString(arg));
}
handleTypeofIsNumber (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
return this.createEjsBoolSelect(this.isNumber(arg));
}
handleTypeofIsBoolean (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
return this.createEjsBoolSelect(this.isBoolean(arg));
}
handleIsUndefined (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
return this.createEjsBoolSelect(this.isUndefined(arg));
}
handleIsNull (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
return this.createEjsBoolSelect(this.isNull(arg));
}
handleIsNullOrUndefined (exp, opencode) {
let arg = this.visitOrNull(exp.arguments[0]);
if (opencode)
return this.createEjsBoolSelect(ir.createOr(this.isNull(arg), this.isUndefined(arg), "or"));
else
return this.createCall(this.ejs_binops["=="], [this.loadNullEjsValue(), arg], "is_null_or_undefined", false);
}
handleBuiltinUndefined (exp) { return this.loadUndefinedEjsValue(); }
handleSetPrototypeOf (exp) {
let obj = this.visitOrNull (exp.arguments[0]);
let proto = this.visitOrNull (exp.arguments[1]);
return this.createCall(this.ejs_runtime.object_set_prototype_of, [obj, proto], "set_prototype_of", true);
// we should check the return value of set_prototype_of
}
handleObjectCreate (exp) {
let proto = this.visitOrNull(exp.arguments[0]);
return this.createCall(this.ejs_runtime.object_create, [proto], "object_create", true);
// we should check the return value of object_create
}
handleArrayFromRest (exp) {
let rest_name = exp.arguments[0].value;
let formal_params_length = exp.arguments[1].value;
let has_rest_bb = new llvm.BasicBlock ("has_rest_bb", this.currentFunction);
let no_rest_bb = new llvm.BasicBlock ("no_rest_bb", this.currentFunction);
let rest_merge_bb = new llvm.BasicBlock ("rest_merge", this.currentFunction);
let rest_alloca = this.createAlloca(this.currentFunction, types.EjsValue, "local_rest_object");
let load_argc = this.createLoad(this.currentFunction.topScope.get("%argc"), "argc_load");
let cmp = ir.createICmpSGt(load_argc, consts.int32(formal_params_length), "argcmpresult");
ir.createCondBr(cmp, has_rest_bb, no_rest_bb);
ir.setInsertPoint(has_rest_bb);
// we have > args than are declared, shove the rest into the rest parameter
let load_args = this.createLoad(this.currentFunction.topScope.get("%args"), "args_load");
let gep = ir.createInBoundsGetElementPointer(load_args, [consts.int32(formal_params_length)], "rest_arg_gep");
load_argc = ir.createNswSub(load_argc, consts.int32(formal_params_length));
let rest_value = this.createCall(this.ejs_runtime.array_new_copy, [load_argc, gep], "argstmp", !this.ejs_runtime.array_new_copy.doesNotThrow);
ir.createStore(rest_value, rest_alloca);
ir.createBr(rest_merge_bb);
ir.setInsertPoint(no_rest_bb);
// we have <= args than are declared, so the rest parameter is just an empty array
rest_value = this.createCall(this.ejs_runtime.array_new, [consts.int32(0), consts.False()], "arrtmp", !this.ejs_runtime.array_new.doesNotThrow);
ir.createStore(rest_value, rest_alloca);
ir.createBr(rest_merge_bb);
ir.setInsertPoint(rest_merge_bb);
this.currentFunction.topScope.set(rest_name, rest_alloca);
this.currentFunction.restArgPresent = true;
return ir.createLoad(rest_alloca, "load_rest");
}
handleArrayFromSpread (exp) {
let arg_count = exp.arguments.length;
if (this.currentFunction.scratch_area && this.currentFunction.scratch_length < arg_count) {
let spreadArrayType = llvm.ArrayType.get(types.EjsValue, arg_count);
this.currentFunction.scratch_area = this.createAlloca(this.currentFunction, spreadArrayType, "args_scratch_area");
this.currentFunction.scratch_area.setAlignment(8);
}
// reuse the scratch area
let spread_alloca = this.currentFunction.scratch_area;
let visited = [];
for (let a of exp.arguments)
visited.push(this.visitOrNull(a));
visited.forEach ((a, i) => {
let gep = ir.createGetElementPointer(spread_alloca, [consts.int32(0), consts.int64(i)], `spread_gep_${i}`);
ir.createStore(visited[i], gep, `spread[${i}]-store`);
});
let argsCast = ir.createGetElementPointer(spread_alloca, [consts.int32(0), consts.int64(0)], "spread_call_args_load");
let argv = [consts.int32(arg_count), argsCast];
return this.createCall(this.ejs_runtime.array_from_iterables, argv, "spread_arr");
}
handleArgPresent (exp) {
let arg_num = exp.arguments[0].value;
let load_argc = this.createLoad(this.currentFunction.topScope.get("%argc"), "argc_n_load");
let cmp = ir.createICmpUGE(load_argc, consts.int32(arg_num), "argcmpresult");
if (exp.arguments[1].value) {
// we have a default value for this parameter, so we also need to tell if the value is undefined
let has_slot_bb = new llvm.BasicBlock("has_slot_bb", this.currentFunction);
let has_arg_bb = new llvm.BasicBlock("has_arg_bb", this.currentFunction);
let no_arg_bb = new llvm.BasicBlock("no_arg_bb", this.currentFunction);
let merge_bb = new llvm.BasicBlock("arg_merge_bb", this.currentFunction);
let arg_present_alloca = this.createAlloca(this.currentFunction, types.Int1, `arg_${arg_num}_present`);
ir.createCondBr(cmp, has_slot_bb, no_arg_bb);
this.doInsideBBlock(has_slot_bb, () => {
// we actually have an arg slot for this number, so check if it's undefined
let load_args = this.createLoad(this.currentFunction.topScope.get("%args"), "args_load");
let arg_ptr = ir.createGetElementPointer(load_args, [consts.int32(arg_num-1)], `arg${arg_num}_ptr`);
let arg_load = this.createLoad(arg_ptr, `arg${arg_num}`);
let arg_is_undefined = this.isUndefined(arg_load);
ir.createCondBr(arg_is_undefined, no_arg_bb, has_arg_bb);
ir.createBr(has_arg_bb);
});
this.doInsideBBlock(has_arg_bb, () => {
// we have a slot and arg, win
ir.createStore(consts.int1(1), arg_present_alloca, "store_arg_present");
ir.createBr(merge_bb);
});
this.doInsideBBlock(no_arg_bb, () => {
// either we didn't have the slot, or the arg was undefined
ir.createStore(consts.int1(0), arg_present_alloca, "store_no_arg_present");
ir.createBr(merge_bb);
});
ir.setInsertPoint(merge_bb);
let load = ir.createLoad(arg_present_alloca, "load_arg_present");
cmp = ir.createICmpEq(load, consts.int1(1), "arg_present");
}
cmp._ejs_returns_native_bool = true;
return this.createEjsBoolSelect(cmp);
}
handleCreateIterResult (exp) {
let value = this.visit(exp.arguments[0]);
let done = this.visit(exp.arguments[1]);
return this.createCall(this.ejs_runtime.create_iter_result, [value, done], "iter_result");
}
handleCreateIteratorWrapper (exp) {
let iter = this.visit(exp.arguments[0]);
return this.createCall(this.ejs_runtime.iterator_wrapper_new, [iter], "iter_wrapper");
}
}
class AddFunctionsVisitor extends TreeVisitor {
constructor (module, abi, dibuilder, difile) {
super();
this.module = module;
this.abi = abi;
this.dibuilder = dibuilder;
this.difile = difile;
}
visitFunction (n) {
if (n && n.id && n.id.name)
n.ir_name = n.id.name;
else
n.ir_name = "_ejs_anonymous";
// at this point point n.params includes %env as its first param, and is followed by all the formal parameters from the original
// script source. we remove the %env parameter and save off he rest of the formal parameter names, and replace the list with
// our runtime parameters.
// remove %env from the formal parameter list, but save its name first
let env_name = n.params[0].name;
n.params.splice(0, 1);
// and store the JS formal parameters someplace else
n.formal_params = n.params;
n.params = [];
for (let param of this.abi.ejs_params)
n.params.push ({ type: b.Identifier, name: param.name, llvm_type: param.llvm_type });
n.params[this.abi.env_param_index].name = env_name;
// create the llvm IR function using our platform calling convention
n.ir_func = types.takes_builtins(this.abi.createFunction(this.module, n.ir_name, this.abi.ejs_return_type, n.params.map ( (param) => param.llvm_type )));
if (!n.toplevel) n.ir_func.setInternalLinkage();
let lineno = 0;
let col = 0;
if (n.loc) {
lineno = n.loc.start.line;
col = n.loc.start.column;
}
if (this.dibuilder && this.difile)
n.ir_func.debug_info = this.dibuilder.createFunction(this.difile, n.ir_name, n.displayName || n.ir_name, this.difile, lineno, false, true, lineno, 0, true, n.ir_func);
let ir_args = n.ir_func.args;
n.params.forEach( (param, i) => {
ir_args[i].setName(param.name);
});
// we don't need to recurse here since we won't have nested functions at this point
return n;
}
}
function sanitize_with_regexp (filename) {
return filename.replace(/[.,-\/\\]/g, "_"); // this is insanely inadequate
}
function insert_toplevel_func (tree, moduleInfo) {
let toplevel = {
type: b.FunctionDeclaration,
id: b.identifier(moduleInfo.toplevel_function_name),
displayName: "toplevel",
params: [],
defaults: [],
body: {
type: b.BlockStatement,
body: tree.body,
loc: {
start: {
line: 0,
column: 0
}
}
},
toplevel: true,
loc: {
start: {
line: 0,
column: 0
}
}
};
tree.body = [toplevel];
return tree;
}
export function compile (tree, base_output_filename, source_filename, module_infos, options) {
let abi = (options.target_arch === "armv7" || options.target_arch === "armv7s" || options.target_arch === "x86") ? new SRetABI() : new ABI();
let module_filename = source_filename;
if (module_filename.endsWith(".js"))
module_filename = module_filename.substring(0, module_filename.length-3);
let this_module_info = module_infos.get(module_filename);
tree = insert_toplevel_func(tree, this_module_info);
debug.log ( () => escodegenerate(tree) );
let toplevel_name = tree.body[0].id.name;
//debug.log 1, "before closure conversion"
//debug.log 1, -> escodegenerate tree
tree = closure_convert(tree, source_filename, module_infos, options);
debug.log (1, "after closure conversion" );
debug.log (1, () => escodegenerate(tree) );
/*
tree = typeinfer.run tree
debug.log 1, "after type inference"
debug.log 1, -> escodegenerate tree
*/
tree = optimizations.run(tree);
debug.log (1, "after optimization" );
debug.log (1, () => escodegenerate(tree) );
let module = new llvm.Module(base_output_filename);
module.toplevel_name = toplevel_name;
let module_accessors = [];
this_module_info.exports.forEach ((export_info, key) => {
let module_prop = undefined;
let f = this_module_info.getExportGetter(key);
if (f) {
if (!module_prop) module_prop = { key };
module_prop.getter = f;
tree.body.push(f);
}
f = this_module_info.getExportSetter(key);
if (f) {
if (!module_prop) module_prop = { key };
module_prop.setter = f;
tree.body.push(f);
}
if (module_prop)
module_accessors.push(module_prop);
});
let dibuilder;
let difile;
if (options.debug) {
dibuilder = new llvm.DIBuilder(module);
difile = dibuilder.createFile(source_filename + ".js", process.cwd());
dibuilder.createCompileUnit(source_filename + ".js", process.cwd(), "ejs", true, "", 2);
}
let visitor = new AddFunctionsVisitor(module, abi, dibuilder, difile);
tree = visitor.visit(tree);
debug.log ( () => escodegenerate(tree) );
visitor = new LLVMIRVisitor(module, source_filename, options, abi, module_infos, this_module_info, dibuilder, difile);
if (options.debug)
dibuilder.finalize();
visitor.emitModuleInfo();
visitor.visit(tree);
visitor.emitModuleResolution(module_accessors);
return module;
}
| use this.createRet, not ir.createRet. the former goes through our ABI layer and does the right thing in the face of an ejsval return for 32 bit platforms
| lib/compiler.js | use this.createRet, not ir.createRet. the former goes through our ABI layer and does the right thing in the face of an ejsval return for 32 bit platforms | <ide><path>ib/compiler.js
<ide> ir.createBr(this.toplevel_body_bb);
<ide>
<ide> ir.setInsertPoint(initialized_bb);
<del> return ir.createRet(this.loadUndefinedEjsValue());
<add> return this.createRet(this.loadUndefinedEjsValue());
<ide> }
<ide>
<ide> // result should be the landingpad's value
<ide> });
<ide>
<ide> ir.setInsertPoint(merge_bb);
<del> return ir.createRet(ir.createLoad(callsite_alloca, "load_local_callsite"));
<add> return this.createRet(ir.createLoad(callsite_alloca, "load_local_callsite"));
<ide> }
<ide>
<ide> handleModuleGet (exp, opencode) { |
|
Java | apache-2.0 | 49c80c572142c280113a7afbfdeb3213813c55ca | 0 | bsmith83/rice-1,kuali/kc-rice,ewestfal/rice,kuali/kc-rice,sonamuthu/rice-1,jwillia/kc-rice1,bsmith83/rice-1,gathreya/rice-kc,jwillia/kc-rice1,shahess/rice,shahess/rice,bhutchinson/rice,geothomasp/kualico-rice-kc,UniversityOfHawaiiORS/rice,cniesen/rice,rojlarge/rice-kc,ewestfal/rice,smith750/rice,kuali/kc-rice,bsmith83/rice-1,gathreya/rice-kc,sonamuthu/rice-1,bhutchinson/rice,gathreya/rice-kc,UniversityOfHawaiiORS/rice,smith750/rice,smith750/rice,rojlarge/rice-kc,kuali/kc-rice,UniversityOfHawaiiORS/rice,jwillia/kc-rice1,geothomasp/kualico-rice-kc,ewestfal/rice,gathreya/rice-kc,shahess/rice,bsmith83/rice-1,geothomasp/kualico-rice-kc,cniesen/rice,geothomasp/kualico-rice-kc,gathreya/rice-kc,ewestfal/rice,cniesen/rice,smith750/rice,rojlarge/rice-kc,sonamuthu/rice-1,jwillia/kc-rice1,UniversityOfHawaiiORS/rice,shahess/rice,shahess/rice,cniesen/rice,bhutchinson/rice,bhutchinson/rice,bhutchinson/rice,smith750/rice,sonamuthu/rice-1,ewestfal/rice,rojlarge/rice-kc,jwillia/kc-rice1,cniesen/rice,kuali/kc-rice,geothomasp/kualico-rice-kc,rojlarge/rice-kc,UniversityOfHawaiiORS/rice | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.kew.doctype;
import mocks.MockPostProcessor;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.kuali.rice.core.api.config.property.ConfigContext;
import org.kuali.rice.core.api.util.xml.XmlJotter;
import org.kuali.rice.edl.framework.workflow.EDocLitePostProcessor;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.api.KewApiServiceLocator;
import org.kuali.rice.kew.api.WorkflowDocument;
import org.kuali.rice.kew.api.WorkflowDocumentFactory;
import org.kuali.rice.kew.api.action.ActionTaken;
import org.kuali.rice.kew.api.document.DocumentStatus;
import org.kuali.rice.kew.doctype.bo.DocumentType;
import org.kuali.rice.kew.doctype.service.DocumentTypeService;
import org.kuali.rice.kew.engine.node.NodeType;
import org.kuali.rice.kew.engine.node.ProcessDefinitionBo;
import org.kuali.rice.kew.engine.node.RouteNode;
import org.kuali.rice.kew.export.KewExportDataSet;
import org.kuali.rice.kew.framework.postprocessor.PostProcessor;
import org.kuali.rice.kew.postprocessor.DefaultPostProcessor;
import org.kuali.rice.kew.service.KEWServiceLocator;
import org.kuali.rice.kew.test.KEWTestCase;
import org.kuali.rice.kew.test.TestUtilities;
import org.kuali.rice.kew.xml.export.DocumentTypeXmlExporter;
import org.kuali.rice.kim.api.KimConstants;
import org.kuali.rice.kim.api.group.Group;
import org.kuali.rice.krad.util.KRADUtils;
import org.kuali.rice.test.BaselineTestCase;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
@BaselineTestCase.BaselineMode(BaselineTestCase.Mode.NONE)
public class DocumentTypeTest extends KEWTestCase {
private static final Logger LOG = Logger.getLogger(DocumentTypeTest.class);
protected void loadTestData() throws Exception {
ConfigContext.getCurrentContextConfig().putProperty("test.doctype.workgroup", "TestWorkgroup");
loadXmlFile("DoctypeConfig.xml");
}
@Test public void testDuplicateNodeName() throws Exception {
try {
loadXmlFile("DocTypeConfig_loadDupliateNodes.xml");
fail("loadXmlFile should have thrown routing exception");
} catch (Exception e) {
}
}
@Test public void testDuplicateNodeNameInRoutePath() throws Exception {
loadXmlFile("DocTypeConfig_duplicateNodes.xml");
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "TestDoubleNodeDocumentType");
document.setTitle("");
document.route("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), document.getDocumentId());
assertTrue("user2 should have an approve request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), document.getDocumentId());
assertTrue("user3 should have an approve request", document.isApprovalRequested());
document.approve("");
}
@Test
public void testDocumentTypeParentChildLinking() throws Exception {
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
verifyDocumentTypeLinking();
// scenario 1, update the parent document type and verify that all linking is correct
super.loadXmlFile("ParentWithChildrenDocTypeConfigurationUpdate1.xml");
verifyDocumentTypeLinking();
// scenario 2, update a child document type and verify that all linking is correct
super.loadXmlFile("ParentWithChildrenDocTypeConfigurationUpdate2.xml");
verifyDocumentTypeLinking();
// let's reimport from the beginning as well
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
verifyDocumentTypeLinking();
// scenario 3, try an xml file with child doctype listed first
super.loadXmlFile("ParentWithChildrenDocTypeConfigurationUpdate3.xml");
verifyDocumentTypeLinking();
// try loading each of these in parallel threads to verify caching can
// handle concurrency situations
String[] fileNames = {"ParentWithChildrenDocTypeConfiguration.xml", "DocTypeIngestTestConfig1.xml",
"DocumentTypeAttributeFetchTest.xml", "ChildDocType1.xml", "ChildDocType2.xml", "ChildDocType3.xml",
"ChildDocType4.xml",};
List<Callback> callbacks = new ArrayList<Callback>();
CyclicBarrier barrier = new CyclicBarrier(fileNames.length);
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < fileNames.length; i++) {
Callback callback = new Callback();
callbacks.add(callback);
threads.add(new Thread(new LoadXml(fileNames[i], callback, barrier)));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join(2 * 60 * 1000);
}
// What should have happened here was an optimistic lock being thrown from the
// document type XML import. Currently, that code is catching and just logging
// those errors (not rethrowing), so there's no way for us to check that the
// optimistic lock was thrown. However, the verifyDocumentTypeLinking should pass
// because the update was never made, and we can check to make sure that
// at least one of the above documents failed to be ingested.
boolean atLeastOneFailure = false;
for (Callback callback : callbacks) {
if (!callback.isXmlLoaded()) {
atLeastOneFailure = true;
}
}
assertTrue("At least one of the XML files should have failed the ingestion process", atLeastOneFailure);
verifyDocumentTypeLinking();
// reload again for good measure
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
verifyDocumentTypeLinking();
}
// Temporary logging for KULRICE-12853 investigation.
private void logExtraInfo (String message, WorkflowDocument document) {
LOG.info(" ");
LOG.info("*** " + message + ", docId: " + document.getDocumentId()
+ ", Approval requested: " + document.isApprovalRequested()
+ ", status: " + document.getStatus());
Set<String> nodeNames = document.getNodeNames();
for (String nodeName : nodeNames) {
LOG.info("*** Node name: " + nodeName);
}
List<ActionTaken> actionsTaken = document.getActionsTaken();
for (ActionTaken actionTaken : actionsTaken) {
LOG.info("*** Action taken. Id: " + actionTaken.getId()
+ ", docId: " + actionTaken.getDocumentId()
+ ", principalId: " + actionTaken.getPrincipalId()
+ ", action: " + actionTaken.getActionTaken()
+ ", date: " + actionTaken.getActionDate());
}
LOG.info(" ");
}
// Contains temporary logging for KULRICE-12853 investigation.
@Test public void testNestedDuplicateNodeNameInRoutePath() throws Exception {
int waitMilliSeconds = 5000;
loadXmlFile("DocTypeConfig_nestedNodes.xml");
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "TestDoubleNodeDocumentType");
document.setTitle("");
document.route("");
logExtraInfo("user1 (after route)", document);
// Split1, left (rkirkend --> user2)
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request; the first request", document.isApprovalRequested());
logExtraInfo("rkirkend before approve", document);
document.approve("");
logExtraInfo("rkirkend after approve", document);
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), document.getDocumentId());
assertTrue("user2 should have an approve request", document.isApprovalRequested());
// se10
logExtraInfo("user2 before approve", document);
document.approve("");
logExtraInfo("user2 after approve", document);
// Some temp logging to look into KULRICE-12853.
LOG.info("isApprovalRequested Loop Starts") ;
boolean loopSuccess = false;
int loopPasses = 0;
for (int j=30; j >= 0; j--) {
loopPasses++;
Thread.sleep(waitMilliSeconds);
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user4"), document.getDocumentId());
logExtraInfo("user4 polling for isApprovalRequested", document);
if (document.isApprovalRequested()) {
loopSuccess = true;
break;
}
}
LOG.info("isApprovalRequested Loop Finished") ;
LOG.info("loopSuccess: " + loopSuccess + ". Number of 5 second loop passes: " + loopPasses);
assertTrue("user4 should have an approve request", document.isApprovalRequested());
logExtraInfo("user4 before approve", document);
document.approve("");
logExtraInfo("user4 after approve", document);
// Split1, Right, Innersplit, Left (rkirkend --> user3)
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), document.getDocumentId());
assertTrue("user3 should have an approve request; the first request", document.isApprovalRequested());
logExtraInfo("user3 before approve", document);
document.approve("");
logExtraInfo("user3 after approve", document);
// Split2, Left (rkirkend --> user3) NOTE - Split2, Right is a NoOp node
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request; the second request", document.isApprovalRequested());
logExtraInfo("rkirkend before approve", document);
document.approve("");
logExtraInfo("rkirkend after approve", document);
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), document.getDocumentId());
assertTrue("user3 should have an approve request; the second request", document.isApprovalRequested());
logExtraInfo("user3 after approve", document);
document.approve("");
logExtraInfo("user3 after approve", document);
}
/**
* Verify that enroute documents are not affected if you edit their document type.
* @throws Exception
*/
@Test public void testChangingDocumentTypeOnEnrouteDocument() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "DocumentType");
document.setTitle("");
document.route("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request", document.isApprovalRequested());
org.kuali.rice.kew.api.doctype.DocumentTypeService docTypeService = KewApiServiceLocator.getDocumentTypeService();
Integer version1 = docTypeService.getDocumentTypeByName(document.getDocumentTypeName()).getDocumentTypeVersion();
//update the document type
loadXmlFile("DoctypeSecondVersion.xml");
//verify that we have a new documenttypeid and its a newer version
Integer version2 = docTypeService.getDocumentTypeByName(document.getDocumentTypeName()).getDocumentTypeVersion();
assertTrue("Version2 should be larger than verison1", version2.intValue() > version1.intValue());
//the new version would take the document final
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), document.getDocumentId());
Integer versionDocument = docTypeService.getDocumentTypeById(document.getDocument().getDocumentTypeId()).getDocumentTypeVersion();
assertTrue("user2 should have an approve request", document.isApprovalRequested());
//make sure our document still represents the accurate version
assertEquals("Document has the wrong document type version", version1, versionDocument);
}
/**
* this test will verify that finalapprover node policies work
*
* @throws Exception
*/
@Test public void testFinalApproverRouting() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "FinalApproverDocumentType");
document.setTitle("");
document.route("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
try {
document.approve("");
fail("document should have thrown routing exception");
} catch (Exception e) {
//deal with single transaction issue in test.
TestUtilities.getExceptionThreader().join();
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("Document should be in exception routing", document.isException());
}
}
/**
* this test will verify that a document type with an empty route path will go directly
* to "final" status
*
* @throws Exception
*/
@Test public void testEmptyRoutePath() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "EmptyRoutePathDocumentType");
document.setTitle("");
document.route("");
assertTrue("Document should be in final state", document.isFinal());
}
/**
* Tests that route nodes mark as mandatory send out approve requests
* @throws Exception
*/
@Test public void testMandatoryRoute() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "MandatoryRouteDocumentType");
document.setTitle("");
try {
document.route("");
} catch (Exception e) {
//deal with single transaction issue in test.
TestUtilities.getExceptionThreader().join();
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user1"), document.getDocumentId());
assertTrue("Document should be in exception routing", document.isException());
}
}
/**
* Makes sure the DocumentTypeXmlParser is working. Compare the parsed 'DocumentType' doctype to it's expected values.
* This test does not include multiple processes.
*
* @throws Exception
*/
@Test public void testDocumentTypeXmlParser() throws Exception {
ConfigContext.getCurrentContextConfig().putProperty("test.base.url", "http://someurl/path");
DocumentType parsedDocument = KEWServiceLocator.getDocumentTypeService().findByName("DocumentType");
assertEquals("Wrong name", "DocumentType", parsedDocument.getName());
assertEquals("Wrong description", "TestDocumentType", parsedDocument.getDescription());
assertEquals("Wrong label", "TestDocumentType", parsedDocument.getLabel());
assertEquals("Wrong postprocessor", "org.kuali.rice.kew.postprocessor.DefaultPostProcessor", parsedDocument.getPostProcessorName());
assertEquals("Wrong su workgroup", "TestWorkgroup", parsedDocument.getSuperUserWorkgroup().getName());
// roundabout way of testing to see if the exception workgroup has been processed properly
DocumentTypeXmlExporter exporter = new DocumentTypeXmlExporter();
KewExportDataSet dataSet = new KewExportDataSet();
dataSet.getDocumentTypes().add(parsedDocument);
String regex = "(?s).*<defaultExceptionGroupName namespace=\"" + KimConstants.KIM_GROUP_WORKFLOW_NAMESPACE_CODE + "\">TestWorkgroup</defaultExceptionGroupName>.*";
LOG.warn("Using regex: " + regex);
assertTrue(XmlJotter.jotNode(exporter.export(dataSet.createExportDataSet())).matches(regex));
//assertNotNull(parsedDocument.getDefaultExceptionWorkgroup());
//assertEquals("Wrong default exception workgroup", "TestWorkgroup", parsedDocument.getDefaultExceptionWorkgroup().getDisplayName());
assertEquals("Wrong doc handler url", "http://someurl/path/_blank", parsedDocument.getResolvedDocumentHandlerUrl());
assertEquals("Wrong unresolved doc handler url", "${test.base.url}/_blank", parsedDocument.getUnresolvedDocHandlerUrl());
assertEquals("Wrong help def url", "/_help", parsedDocument.getHelpDefinitionUrl());
assertEquals("Wrong unresolved help def url", "/_help", parsedDocument.getUnresolvedHelpDefinitionUrl());
assertEquals("Wrong blanketApprover workgroup", "TestWorkgroup", parsedDocument.getBlanketApproveWorkgroup().getName());
assertEquals("Wrong blanketApprove policy", null, parsedDocument.getBlanketApprovePolicy());
assertEquals("Wrong DEFAULT_APPROVE policy value", Boolean.FALSE, parsedDocument.getDefaultApprovePolicy().getPolicyValue());
assertEquals("Wrong LOOK_FUTURE", Boolean.TRUE, parsedDocument.getLookIntoFuturePolicy().getPolicyValue());
List processes = parsedDocument.getProcesses();
assertEquals("Should only be 1 process", 1, processes.size());
//this is going against the intended structure and is very brittle
ProcessDefinitionBo process = (ProcessDefinitionBo)processes.get(0);
List flattenedNodeList = KEWServiceLocator.getRouteNodeService().getFlattenedNodes(process);
assertEquals("Should be 6 total route nodes", 6, flattenedNodeList.size());
RouteNode adHocNode = process.getInitialRouteNode();
assertEquals("Wrong node name should be 'AdHoc'", "AdHoc",adHocNode.getRouteNodeName());
assertTrue("Wrong node type", NodeType.START.isAssignableFrom(Class.forName(adHocNode.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", adHocNode.getExceptionWorkgroup().getName());
RouteNode split = (RouteNode)adHocNode.getNextNodes().get(0);
assertEquals("Wrong node name", "Split", split.getRouteNodeName());
assertTrue("Wrong node type", NodeType.SPLIT.isAssignableFrom(Class.forName(split.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", split.getExceptionWorkgroup().getName());
assertTrue(split.getNextNodes().size() == 2);
boolean ruleTemplate1Found = false;
boolean ruleTemplate2Found = false;
for (RouteNode routeNode : split.getNextNodes()) {
if (routeNode.getRouteNodeName().equals("RuleTemplate1")) {
assertTrue("Wrong node type", NodeType.REQUESTS.isAssignableFrom(Class.forName(routeNode.getNodeType())));
assertEquals("Wrong branch name", "B1", routeNode.getBranch().getName());
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", routeNode.getExceptionWorkgroup().getName());
ruleTemplate1Found = true;
}
if (routeNode.getRouteNodeName().equals("RuleTemplate2")) {
assertTrue("Wrong node type", NodeType.REQUESTS.isAssignableFrom(Class.forName(routeNode.getNodeType())));
assertEquals("Wrong branch name", "B2", routeNode.getBranch().getName());
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", routeNode.getExceptionWorkgroup().getName());
ruleTemplate2Found = true;
RouteNode join = (RouteNode)routeNode.getNextNodes().get(0);
assertEquals("Wrong node name", "Join", join.getRouteNodeName());
assertTrue("Wrong node type", NodeType.JOIN.isAssignableFrom(Class.forName(join.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", join.getExceptionWorkgroup().getName());
RouteNode ruleTemplate3 = (RouteNode)join.getNextNodes().get(0);
assertEquals("Wrong node name", "RuleTemplate3", ruleTemplate3.getRouteNodeName());
assertTrue("Wrong node type", NodeType.REQUESTS.isAssignableFrom(Class.forName(ruleTemplate3.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", ruleTemplate3.getExceptionWorkgroup().getName());
}
}
assertTrue(ruleTemplate1Found);
assertTrue(ruleTemplate2Found);
}
//verifies the documenttype hierarchy is intact after multiple uploads
@Test public void testHierarchyUpload() throws Exception {
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
DocumentType parent = KEWServiceLocator.getDocumentTypeService().findByName("UGSDocumentType");
boolean foundRemonstrance = false;
boolean foundNewCourse = false;
boolean foundDelete = false;
for (Iterator iter = parent.getChildrenDocTypes().iterator(); iter.hasNext();) {
DocumentType childDocType = (DocumentType) iter.next();
assertTrue("child documenttype should be current", childDocType.getCurrentInd().booleanValue());
if(childDocType.getName().equals("CourseRemonstranceProcess")) {
foundRemonstrance = true;
} else if (childDocType.getName().equals("NewCourseRequest")) {
foundNewCourse = true;
} else if (childDocType.getName().equals("DeleteCourseRequest")) {
foundDelete = true;
}
}
assertTrue("Didn't find CourseRemonstraneProcess", foundRemonstrance);
assertTrue("Didn't find NewCourseRequest", foundNewCourse);
assertTrue("Didn't find DeleteCourseRequest", foundDelete);
//reload and verify that the structure looks the same - the below is missing one of the children document types
//to verify that a partial upload of the hierarchy doesn't kill the entire hierarchy
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration2.xml");
parent = KEWServiceLocator.getDocumentTypeService().findByName("UGSDocumentType");
foundRemonstrance = false;
foundNewCourse = false;
foundDelete = false;
int i = 0;
for (Iterator iter = parent.getChildrenDocTypes().iterator(); iter.hasNext(); i++) {
DocumentType childDocType = (DocumentType) iter.next();
assertTrue("child documenttype should be current", childDocType.getCurrentInd().booleanValue());
if(childDocType.getName().equals("CourseRemonstranceProcess")) {
foundRemonstrance = true;
} else if (childDocType.getName().equals("NewCourseRequest")) {
foundNewCourse = true;
} else if (childDocType.getName().equals("DeleteCourseRequest")) {
foundDelete = true;
}
}
assertTrue("Didn't find CourseRemonstranceProcess", foundRemonstrance);
assertTrue("Didn't find NewCourseRequest", foundNewCourse);
assertTrue("Didn't find DeleteCourseRequest", foundDelete);
}
//verifies documenttype hierarchy is intact after uploading a series of documenttypes and then
//uploading a parent onto those document types
@Test public void testHierarchyUpload2() throws Exception {
super.loadXmlFile("DocTypesWithoutParent.xml");
//Verify that the document types are there
DocumentType courseRemonstrance1 = KEWServiceLocator.getDocumentTypeService().findByName("CourseRemonstranceProcess");
DocumentType newCourseRequest1 = KEWServiceLocator.getDocumentTypeService().findByName("NewCourseRequest");
DocumentType deleteCourse1 = KEWServiceLocator.getDocumentTypeService().findByName("DeleteCourseRequest");
//upload the new config with the parent and verify we are getting new document types with new versions
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
DocumentType courseRemonstrance2 = null;
DocumentType newCourseRequest2 = null;
DocumentType deleteCourse2 = null;
DocumentType ugsDocumentType = KEWServiceLocator.getDocumentTypeService().findByName("UGSDocumentType");
for (Iterator iter = ugsDocumentType.getChildrenDocTypes().iterator(); iter.hasNext();) {
DocumentType childDocType = (DocumentType) iter.next();
if(childDocType.getName().equals("CourseRemonstranceProcess")) {
courseRemonstrance2 = childDocType;
} else if (childDocType.getName().equals("NewCourseRequest")) {
newCourseRequest2 = childDocType;
} else if (childDocType.getName().equals("DeleteCourseRequest")) {
deleteCourse2 = childDocType;
}
}
assertNotNull(courseRemonstrance2);
assertNotNull(newCourseRequest2);
assertNotNull(deleteCourse2);
assertTrue("Version didn't get incremented", courseRemonstrance1.getVersion().intValue() < courseRemonstrance2.getVersion().intValue());
assertTrue("Version didn't increment", newCourseRequest1.getVersion().intValue() < newCourseRequest2.getVersion().intValue());
assertTrue("Version didn't increment", deleteCourse1.getVersion().intValue() < deleteCourse2.getVersion().intValue());
}
/**
* Tests that the document type ingestion will not create a brand new
* document when only label or description field changes. Relates to
* JIRA's EN-318 and KULOWF-147.
*
* @throws Exception
*/
@Test public void testDocumentTypeIngestion() throws Exception {
// first ingestion
super.loadXmlFile("DocTypeIngestTestConfig1.xml"); // original document
super.loadXmlFile("DocTypeIngestTestConfig2.xml"); // document with changed label and description fields
DocumentType secondIngestDoc = KEWServiceLocator.getDocumentTypeService().findByName("IngestTestDocumentType");
assertNotNull("Second ingested document has empty Previous Version ID after first ingest", secondIngestDoc.getPreviousVersionId());
DocumentType firstIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(secondIngestDoc.getPreviousVersionId());
// the second ingested document should now be set to Current with the first ingested document should no longer be set to Current
assertEquals("First ingested document is still set to Current after first ingest", Boolean.FALSE, firstIngestDoc.getCurrentInd());
assertEquals("Second ingested document is not set to Current after first ingest", Boolean.TRUE, secondIngestDoc.getCurrentInd());
// second ingestion
super.loadXmlFile("DocTypeIngestTestConfig3.xml"); // document setting active to false
firstIngestDoc = null;
secondIngestDoc = null;
DocumentType thirdIngestDoc = KEWServiceLocator.getDocumentTypeService().findByName("IngestTestDocumentType");
assertNotNull("Third ingested document has empty Previous Version ID after second ingest", thirdIngestDoc.getPreviousVersionId());
secondIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(thirdIngestDoc.getPreviousVersionId());
assertNotNull("Second ingested document has empty Previous Version ID after second ingest", secondIngestDoc.getPreviousVersionId());
firstIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(secondIngestDoc.getPreviousVersionId());
// the third ingested document should now be set to Current and Inactive... all others should not be set to Current
assertEquals("First ingested document is set to Current after second ingest", Boolean.FALSE, firstIngestDoc.getCurrentInd());
assertEquals("Second ingested document is set to Current after second ingest", Boolean.FALSE, secondIngestDoc.getCurrentInd());
assertEquals("Third ingested document is not set to Inactive after second ingest", Boolean.FALSE, thirdIngestDoc.getActive());
assertEquals("Third ingested document is not set to Current after second ingest", Boolean.TRUE, thirdIngestDoc.getCurrentInd());
// third ingestion
super.loadXmlFile("DocTypeIngestTestConfig4.xml"); // document setting active to true
firstIngestDoc = null;
secondIngestDoc = null;
thirdIngestDoc = null;
DocumentType fourthIngestDoc = KEWServiceLocator.getDocumentTypeService().findByName("IngestTestDocumentType");
assertNotNull("Fourth ingested document has empty Previous Version ID after third ingest", fourthIngestDoc.getPreviousVersionId());
thirdIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(fourthIngestDoc.getPreviousVersionId());
assertNotNull("Third ingested document has empty Previous Version ID after third ingest", thirdIngestDoc.getPreviousVersionId());
secondIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(thirdIngestDoc.getPreviousVersionId());
assertNotNull("Second ingested document has empty Previous Version ID after third ingest", secondIngestDoc.getPreviousVersionId());
firstIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(secondIngestDoc.getPreviousVersionId());
// the fourth ingested document should now be set to Current and Active... all others should not be set to Current
assertEquals("First ingested document is set to Current after third ingest", Boolean.FALSE, firstIngestDoc.getCurrentInd());
assertEquals("Second ingested document is set to Current after third ingest", Boolean.FALSE, secondIngestDoc.getCurrentInd());
assertEquals("Third ingested document is set to Current after third ingest", Boolean.FALSE, thirdIngestDoc.getCurrentInd());
assertEquals("Fourth ingested document is not set to Active after third ingest", Boolean.TRUE, fourthIngestDoc.getActive());
assertEquals("Fourth ingested document is not set to Current after third ingest", Boolean.TRUE, fourthIngestDoc.getCurrentInd());
}
@Test public void testSameFileChildParentIngestion() throws Exception {
loadXmlFile("ChildParentTestConfig1.xml");
verifyDocumentTypeLinking();
loadXmlFile("ChildParentTestConfig2.xml");
verifyDocumentTypeLinking();
}
@Test
public void testPostProcessor() throws Exception {
loadXmlFile("DoctypePostProcessorConfig.xml");
DocumentType ppTestParent1 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestParent1");
DocumentType ppTestParent2 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestParent2");
DocumentType ppTestChild1 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestChild1");
DocumentType ppTestChild2 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestChild2");
DocumentType ppTestChild3 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestChild3");
assertEquals("Incorrect PostProcessor", MockPostProcessor.class, ppTestParent1.getPostProcessor().getClass());
assertEquals("Incorrect PostProcessor", DefaultPostProcessor.class, ppTestParent2.getPostProcessor().getClass());
assertEquals("Incorrect PostProcessor", MockPostProcessor.class, ppTestChild1.getPostProcessor().getClass());
PostProcessor testChild2PP = ppTestChild2.getPostProcessor();
assertEquals("Incorrect PostProcessorRemote", EDocLitePostProcessor.class, testChild2PP.getClass());
assertEquals("Incorrect PostProcessor", DefaultPostProcessor.class, ppTestChild3.getPostProcessor().getClass());
}
/**
* Tests to ensure that a given document type has its fields updated when the a second XML doc type with the same name is ingested.
*
* NOTE: This unit test is still incomplete.
*
* @throws Exception
*/
@Test public void testUpdateOfDocTypeFields() throws Exception {
//Collection<DocumentTypePolicy> docPolicies = docType.getPolicies();
//List<DocumentTypeAttribute> docAttributes = docType.getDocumentTypeAttributes();
//List firstRouteNode = KEWServiceLocator.getRouteNodeService().getInitialNodeInstances(docType.getDocumentTypeId());
// The expected field values from the test XML files.
String[][] expectedValues = { {"TestWithMostParams1", "TestParent01", "A test of doc type parameters.", "TestWithMostParams1",
"mocks.MockPostProcessor", "KR-WKFLW:TestWorkgroup", null, "any", "KR-WKFLW:TestWorkgroup",
"KR-WKFLW:TestWorkgroup", "_blank", "_blank", "_blank", "_blank", "_blank", "TestCl1", "false", "a.doc.type.authorizer"},
{"TestWithMostParams1", "AnotherParent", "Another test of most parameters.",
"AntoherTestWithMostParams", "org.kuali.rice.kew.postprocessor.DefaultPostProcessor", "KR-WKFLW:WorkflowAdmin",
"KR-WKFLW:WorkflowAdmin", null, "KR-WKFLW:WorkflowAdmin", "KR-WKFLW:WorkflowAdmin", "_nothing", "_nothing",
"_nothing", "_nothing", "_nothing", "KEW", "true", "a.parent.authorizer"}
};
// Ingest each document type, and test the properties of each one.
for (int i = 0; i < expectedValues.length; i++) {
// Load the document type and store its data.
String fileToLoad = "DocTypeWithMostParams" + (i+1) + ".xml";
loadXmlFile(fileToLoad);
DocumentType docType = KEWServiceLocator.getDocumentTypeService().findByName("TestWithMostParams1");
Group baWorkgroup = docType.getBlanketApproveWorkgroup();
Group rpWorkgroup = docType.getReportingWorkgroup();
Group deWorkgroup = getValidDefaultExceptionWorkgroup(docType);
String[] actualValues = {docType.getName(), docType.getParentDocType().getName(), docType.getDescription(),
docType.getLabel(), docType.getPostProcessorName(), constructGroupNameWithNamespace(docType.getSuperUserWorkgroupNoInheritence()),
constructGroupNameWithNamespace(baWorkgroup), docType.getBlanketApprovePolicy(),
constructGroupNameWithNamespace(rpWorkgroup), constructGroupNameWithNamespace(deWorkgroup),
docType.getUnresolvedDocHandlerUrl(), docType.getUnresolvedHelpDefinitionUrl(),
docType.getUnresolvedDocSearchHelpUrl(),
docType.getNotificationFromAddress(), docType.getCustomEmailStylesheet(),
docType.getApplicationId(), docType.getActive().toString(),
docType.getAuthorizer()
};
// Compare the expected field values with the actual ones.
for (int j = 0; j < expectedValues[i].length; j++) {
assertEquals("The document does not have the expected parameter value. (i=" + i + ",j=" + j + ")", expectedValues[i][j], actualValues[j]);
}
}
}
private Group getValidDefaultExceptionWorkgroup(DocumentType documentType) {
List flattenedNodes = KEWServiceLocator.getRouteNodeService().getFlattenedNodes(documentType, false);
assertTrue("Document Type '" + documentType.getName() + "' should have a default exception workgroup.", hasDefaultExceptionWorkgroup(flattenedNodes));
return ((RouteNode)flattenedNodes.get(0)).getExceptionWorkgroup();
}
// this method is duplicated in the DocumentTypeXmlExporter class
private boolean hasDefaultExceptionWorkgroup(List flattenedNodes) {
boolean hasDefaultExceptionWorkgroup = true;
String exceptionWorkgroupName = null;
for (Iterator iterator = flattenedNodes.iterator(); iterator.hasNext();) {
RouteNode node = (RouteNode) iterator.next();
if (exceptionWorkgroupName == null) {
exceptionWorkgroupName = node.getExceptionWorkgroupName();
}
if (exceptionWorkgroupName == null || !exceptionWorkgroupName.equals(node.getExceptionWorkgroupName())) {
hasDefaultExceptionWorkgroup = false;
break;
}
}
return hasDefaultExceptionWorkgroup;
}
private String constructGroupNameWithNamespace(Group group) {
if (group == null) {
return null;
}
return group.getNamespaceCode() + KewApiConstants.KIM_GROUP_NAMESPACE_NAME_DELIMITER_CHARACTER + group.getName();
}
protected void verifyDocumentTypeLinking() throws Exception {
DocumentTypeService service = KEWServiceLocator.getDocumentTypeService();
List rootDocs = service.findAllCurrentRootDocuments();
int numRoots = rootDocs.size();
List documentTypes = service.findAllCurrent();
List<DocumentType> leafs = new ArrayList<DocumentType>();
for (Iterator iterator = documentTypes.iterator(); iterator.hasNext();) {
DocumentType documentType = (DocumentType) iterator.next();
// check that all document types with parents are current
if (KRADUtils.isNotNull(documentType.getParentDocType())) {
assertEquals("Parent of document type '" + documentType.getName() + "' should be Current", Boolean.TRUE, documentType.getParentDocType().getCurrentInd());
}
List children = service.getChildDocumentTypes(documentType.getDocumentTypeId());
if (children.isEmpty()) {
leafs.add(documentType);
} else {
// check that all child document types are current
for (Iterator iterator2 = children.iterator(); iterator2.hasNext();) {
DocumentType childDocType = (DocumentType) iterator2.next();
assertEquals("Any child document type should be Current", Boolean.TRUE, childDocType.getCurrentInd());
}
}
}
Set<String> rootDocIds = new HashSet<String>();
// verify the hierarchy
for (DocumentType leaf : leafs) {
verifyHierarchy(leaf, rootDocIds);
}
// we should have the same number of roots as we did from the original roots query
assertEquals("Should have the same number of roots", numRoots, rootDocIds.size());
}
protected void verifyHierarchy(DocumentType docType, Set<String> rootDocIds) {
assertTrue("DocumentType " + docType.getName() + " should be current.", docType.getCurrentInd().booleanValue());
if (docType.getParentDocType() == null) {
rootDocIds.add(docType.getDocumentTypeId());
} else {
verifyHierarchy(docType.getParentDocType(), rootDocIds);
}
}
private class LoadXml implements Runnable {
private final String xmlFile;
private final Callback callback;
private final CyclicBarrier barrier;
LoadXml(String xmlFile, Callback callback, CyclicBarrier barrier) {
this.xmlFile = xmlFile;
this.callback = callback;
this.barrier = barrier;
}
public void run() {
getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
try {
barrier.await(120, TimeUnit.SECONDS);
} catch (Exception e) {
}
try {
loadXmlFile(xmlFile);
} catch (Throwable t) {
callback.record(xmlFile, t);
}
// try {
// barrier.await(120, TimeUnit.SECONDS);
// } catch (Exception e) {
// }
}
});
}
}
private class Callback {
private String xmlFile;
private Throwable t;
public void record(String xmlFile, Throwable t) {
this.xmlFile = xmlFile;
this.t = t;
}
public boolean isXmlLoaded() {
if (t != null) {
t.printStackTrace();
//fail("Failed to load xml file " + xmlFile);
LOG.info("The XML file " + xmlFile + " failed to load, but this was expected.");
return false;
}
return true;
}
}
}
| rice-middleware/it/kew/src/test/java/org/kuali/rice/kew/doctype/DocumentTypeTest.java | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.kew.doctype;
import mocks.MockPostProcessor;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.kuali.rice.core.api.config.property.ConfigContext;
import org.kuali.rice.core.api.util.xml.XmlJotter;
import org.kuali.rice.edl.framework.workflow.EDocLitePostProcessor;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.api.KewApiServiceLocator;
import org.kuali.rice.kew.api.WorkflowDocument;
import org.kuali.rice.kew.api.WorkflowDocumentFactory;
import org.kuali.rice.kew.doctype.bo.DocumentType;
import org.kuali.rice.kew.doctype.service.DocumentTypeService;
import org.kuali.rice.kew.engine.node.NodeType;
import org.kuali.rice.kew.engine.node.ProcessDefinitionBo;
import org.kuali.rice.kew.engine.node.RouteNode;
import org.kuali.rice.kew.export.KewExportDataSet;
import org.kuali.rice.kew.framework.postprocessor.PostProcessor;
import org.kuali.rice.kew.postprocessor.DefaultPostProcessor;
import org.kuali.rice.kew.service.KEWServiceLocator;
import org.kuali.rice.kew.test.KEWTestCase;
import org.kuali.rice.kew.test.TestUtilities;
import org.kuali.rice.kew.xml.export.DocumentTypeXmlExporter;
import org.kuali.rice.kim.api.KimConstants;
import org.kuali.rice.kim.api.group.Group;
import org.kuali.rice.krad.util.KRADUtils;
import org.kuali.rice.test.BaselineTestCase;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
@BaselineTestCase.BaselineMode(BaselineTestCase.Mode.NONE)
public class DocumentTypeTest extends KEWTestCase {
private static final Logger LOG = Logger.getLogger(DocumentTypeTest.class);
protected void loadTestData() throws Exception {
ConfigContext.getCurrentContextConfig().putProperty("test.doctype.workgroup", "TestWorkgroup");
loadXmlFile("DoctypeConfig.xml");
}
@Test public void testDuplicateNodeName() throws Exception {
try {
loadXmlFile("DocTypeConfig_loadDupliateNodes.xml");
fail("loadXmlFile should have thrown routing exception");
} catch (Exception e) {
}
}
@Test public void testDuplicateNodeNameInRoutePath() throws Exception {
loadXmlFile("DocTypeConfig_duplicateNodes.xml");
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "TestDoubleNodeDocumentType");
document.setTitle("");
document.route("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), document.getDocumentId());
assertTrue("user2 should have an approve request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), document.getDocumentId());
assertTrue("user3 should have an approve request", document.isApprovalRequested());
document.approve("");
}
@Test
public void testDocumentTypeParentChildLinking() throws Exception {
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
verifyDocumentTypeLinking();
// scenario 1, update the parent document type and verify that all linking is correct
super.loadXmlFile("ParentWithChildrenDocTypeConfigurationUpdate1.xml");
verifyDocumentTypeLinking();
// scenario 2, update a child document type and verify that all linking is correct
super.loadXmlFile("ParentWithChildrenDocTypeConfigurationUpdate2.xml");
verifyDocumentTypeLinking();
// let's reimport from the beginning as well
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
verifyDocumentTypeLinking();
// scenario 3, try an xml file with child doctype listed first
super.loadXmlFile("ParentWithChildrenDocTypeConfigurationUpdate3.xml");
verifyDocumentTypeLinking();
// try loading each of these in parallel threads to verify caching can
// handle concurrency situations
String[] fileNames = {"ParentWithChildrenDocTypeConfiguration.xml", "DocTypeIngestTestConfig1.xml",
"DocumentTypeAttributeFetchTest.xml", "ChildDocType1.xml", "ChildDocType2.xml", "ChildDocType3.xml",
"ChildDocType4.xml",};
List<Callback> callbacks = new ArrayList<Callback>();
CyclicBarrier barrier = new CyclicBarrier(fileNames.length);
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < fileNames.length; i++) {
Callback callback = new Callback();
callbacks.add(callback);
threads.add(new Thread(new LoadXml(fileNames[i], callback, barrier)));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join(2 * 60 * 1000);
}
// What should have happened here was an optimistic lock being thrown from the
// document type XML import. Currently, that code is catching and just logging
// those errors (not rethrowing), so there's no way for us to check that the
// optimistic lock was thrown. However, the verifyDocumentTypeLinking should pass
// because the update was never made, and we can check to make sure that
// at least one of the above documents failed to be ingested.
boolean atLeastOneFailure = false;
for (Callback callback : callbacks) {
if (!callback.isXmlLoaded()) {
atLeastOneFailure = true;
}
}
assertTrue("At least one of the XML files should have failed the ingestion process", atLeastOneFailure);
verifyDocumentTypeLinking();
// reload again for good measure
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
verifyDocumentTypeLinking();
}
@Test public void testNestedDuplicateNodeNameInRoutePath() throws Exception {
int waitMilliSeconds = 5000;
loadXmlFile("DocTypeConfig_nestedNodes.xml");
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "TestDoubleNodeDocumentType");
document.setTitle("");
document.route("");
// Split1, left (rkirkend --> user2)
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request; the first request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), document.getDocumentId());
assertTrue("user2 should have an approve request", document.isApprovalRequested());
document.approve("");
// Some temp logging to look into KULRICE-12853.
LOG.info("isApprovalRequested Loop Starts") ;
boolean loopSuccess = false;
int loopPasses = 0;
// Split1, Right, Innersplit, Right (user4)
for (int j=25; j >= 0; j--) {
loopPasses++;
Thread.sleep(waitMilliSeconds);
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user4"), document.getDocumentId());
if (document.isApprovalRequested()) {
loopSuccess = true;
break;
}
}
// Some temp logging to look into KULRICE-12853.
LOG.info("isApprovalRequested Loop Finished") ;
LOG.info("loopSuccess: " + loopSuccess + ". Number of 5 second loop passes: " + loopPasses);
assertTrue("user4 should have an approve request", document.isApprovalRequested());
document.approve("");
// Split1, Right, Innersplit, Left (rkirkend --> user3)
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), document.getDocumentId());
assertTrue("user3 should have an approve request; the first request", document.isApprovalRequested());
document.approve("");
// Split2, Left (rkirkend --> user3) NOTE - Split2, Right is a NoOp node
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request; the second request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), document.getDocumentId());
assertTrue("user3 should have an approve request; the second request", document.isApprovalRequested());
document.approve("");
}
/**
* Verify that enroute documents are not affected if you edit their document type.
* @throws Exception
*/
@Test public void testChangingDocumentTypeOnEnrouteDocument() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "DocumentType");
document.setTitle("");
document.route("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request", document.isApprovalRequested());
org.kuali.rice.kew.api.doctype.DocumentTypeService docTypeService = KewApiServiceLocator.getDocumentTypeService();
Integer version1 = docTypeService.getDocumentTypeByName(document.getDocumentTypeName()).getDocumentTypeVersion();
//update the document type
loadXmlFile("DoctypeSecondVersion.xml");
//verify that we have a new documenttypeid and its a newer version
Integer version2 = docTypeService.getDocumentTypeByName(document.getDocumentTypeName()).getDocumentTypeVersion();
assertTrue("Version2 should be larger than verison1", version2.intValue() > version1.intValue());
//the new version would take the document final
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), document.getDocumentId());
Integer versionDocument = docTypeService.getDocumentTypeById(document.getDocument().getDocumentTypeId()).getDocumentTypeVersion();
assertTrue("user2 should have an approve request", document.isApprovalRequested());
//make sure our document still represents the accurate version
assertEquals("Document has the wrong document type version", version1, versionDocument);
}
/**
* this test will verify that finalapprover node policies work
*
* @throws Exception
*/
@Test public void testFinalApproverRouting() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "FinalApproverDocumentType");
document.setTitle("");
document.route("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
try {
document.approve("");
fail("document should have thrown routing exception");
} catch (Exception e) {
//deal with single transaction issue in test.
TestUtilities.getExceptionThreader().join();
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("Document should be in exception routing", document.isException());
}
}
/**
* this test will verify that a document type with an empty route path will go directly
* to "final" status
*
* @throws Exception
*/
@Test public void testEmptyRoutePath() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "EmptyRoutePathDocumentType");
document.setTitle("");
document.route("");
assertTrue("Document should be in final state", document.isFinal());
}
/**
* Tests that route nodes mark as mandatory send out approve requests
* @throws Exception
*/
@Test public void testMandatoryRoute() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "MandatoryRouteDocumentType");
document.setTitle("");
try {
document.route("");
} catch (Exception e) {
//deal with single transaction issue in test.
TestUtilities.getExceptionThreader().join();
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user1"), document.getDocumentId());
assertTrue("Document should be in exception routing", document.isException());
}
}
/**
* Makes sure the DocumentTypeXmlParser is working. Compare the parsed 'DocumentType' doctype to it's expected values.
* This test does not include multiple processes.
*
* @throws Exception
*/
@Test public void testDocumentTypeXmlParser() throws Exception {
ConfigContext.getCurrentContextConfig().putProperty("test.base.url", "http://someurl/path");
DocumentType parsedDocument = KEWServiceLocator.getDocumentTypeService().findByName("DocumentType");
assertEquals("Wrong name", "DocumentType", parsedDocument.getName());
assertEquals("Wrong description", "TestDocumentType", parsedDocument.getDescription());
assertEquals("Wrong label", "TestDocumentType", parsedDocument.getLabel());
assertEquals("Wrong postprocessor", "org.kuali.rice.kew.postprocessor.DefaultPostProcessor", parsedDocument.getPostProcessorName());
assertEquals("Wrong su workgroup", "TestWorkgroup", parsedDocument.getSuperUserWorkgroup().getName());
// roundabout way of testing to see if the exception workgroup has been processed properly
DocumentTypeXmlExporter exporter = new DocumentTypeXmlExporter();
KewExportDataSet dataSet = new KewExportDataSet();
dataSet.getDocumentTypes().add(parsedDocument);
String regex = "(?s).*<defaultExceptionGroupName namespace=\"" + KimConstants.KIM_GROUP_WORKFLOW_NAMESPACE_CODE + "\">TestWorkgroup</defaultExceptionGroupName>.*";
LOG.warn("Using regex: " + regex);
assertTrue(XmlJotter.jotNode(exporter.export(dataSet.createExportDataSet())).matches(regex));
//assertNotNull(parsedDocument.getDefaultExceptionWorkgroup());
//assertEquals("Wrong default exception workgroup", "TestWorkgroup", parsedDocument.getDefaultExceptionWorkgroup().getDisplayName());
assertEquals("Wrong doc handler url", "http://someurl/path/_blank", parsedDocument.getResolvedDocumentHandlerUrl());
assertEquals("Wrong unresolved doc handler url", "${test.base.url}/_blank", parsedDocument.getUnresolvedDocHandlerUrl());
assertEquals("Wrong help def url", "/_help", parsedDocument.getHelpDefinitionUrl());
assertEquals("Wrong unresolved help def url", "/_help", parsedDocument.getUnresolvedHelpDefinitionUrl());
assertEquals("Wrong blanketApprover workgroup", "TestWorkgroup", parsedDocument.getBlanketApproveWorkgroup().getName());
assertEquals("Wrong blanketApprove policy", null, parsedDocument.getBlanketApprovePolicy());
assertEquals("Wrong DEFAULT_APPROVE policy value", Boolean.FALSE, parsedDocument.getDefaultApprovePolicy().getPolicyValue());
assertEquals("Wrong LOOK_FUTURE", Boolean.TRUE, parsedDocument.getLookIntoFuturePolicy().getPolicyValue());
List processes = parsedDocument.getProcesses();
assertEquals("Should only be 1 process", 1, processes.size());
//this is going against the intended structure and is very brittle
ProcessDefinitionBo process = (ProcessDefinitionBo)processes.get(0);
List flattenedNodeList = KEWServiceLocator.getRouteNodeService().getFlattenedNodes(process);
assertEquals("Should be 6 total route nodes", 6, flattenedNodeList.size());
RouteNode adHocNode = process.getInitialRouteNode();
assertEquals("Wrong node name should be 'AdHoc'", "AdHoc",adHocNode.getRouteNodeName());
assertTrue("Wrong node type", NodeType.START.isAssignableFrom(Class.forName(adHocNode.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", adHocNode.getExceptionWorkgroup().getName());
RouteNode split = (RouteNode)adHocNode.getNextNodes().get(0);
assertEquals("Wrong node name", "Split", split.getRouteNodeName());
assertTrue("Wrong node type", NodeType.SPLIT.isAssignableFrom(Class.forName(split.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", split.getExceptionWorkgroup().getName());
assertTrue(split.getNextNodes().size() == 2);
boolean ruleTemplate1Found = false;
boolean ruleTemplate2Found = false;
for (RouteNode routeNode : split.getNextNodes()) {
if (routeNode.getRouteNodeName().equals("RuleTemplate1")) {
assertTrue("Wrong node type", NodeType.REQUESTS.isAssignableFrom(Class.forName(routeNode.getNodeType())));
assertEquals("Wrong branch name", "B1", routeNode.getBranch().getName());
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", routeNode.getExceptionWorkgroup().getName());
ruleTemplate1Found = true;
}
if (routeNode.getRouteNodeName().equals("RuleTemplate2")) {
assertTrue("Wrong node type", NodeType.REQUESTS.isAssignableFrom(Class.forName(routeNode.getNodeType())));
assertEquals("Wrong branch name", "B2", routeNode.getBranch().getName());
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", routeNode.getExceptionWorkgroup().getName());
ruleTemplate2Found = true;
RouteNode join = (RouteNode)routeNode.getNextNodes().get(0);
assertEquals("Wrong node name", "Join", join.getRouteNodeName());
assertTrue("Wrong node type", NodeType.JOIN.isAssignableFrom(Class.forName(join.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", join.getExceptionWorkgroup().getName());
RouteNode ruleTemplate3 = (RouteNode)join.getNextNodes().get(0);
assertEquals("Wrong node name", "RuleTemplate3", ruleTemplate3.getRouteNodeName());
assertTrue("Wrong node type", NodeType.REQUESTS.isAssignableFrom(Class.forName(ruleTemplate3.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", ruleTemplate3.getExceptionWorkgroup().getName());
}
}
assertTrue(ruleTemplate1Found);
assertTrue(ruleTemplate2Found);
}
//verifies the documenttype hierarchy is intact after multiple uploads
@Test public void testHierarchyUpload() throws Exception {
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
DocumentType parent = KEWServiceLocator.getDocumentTypeService().findByName("UGSDocumentType");
boolean foundRemonstrance = false;
boolean foundNewCourse = false;
boolean foundDelete = false;
for (Iterator iter = parent.getChildrenDocTypes().iterator(); iter.hasNext();) {
DocumentType childDocType = (DocumentType) iter.next();
assertTrue("child documenttype should be current", childDocType.getCurrentInd().booleanValue());
if(childDocType.getName().equals("CourseRemonstranceProcess")) {
foundRemonstrance = true;
} else if (childDocType.getName().equals("NewCourseRequest")) {
foundNewCourse = true;
} else if (childDocType.getName().equals("DeleteCourseRequest")) {
foundDelete = true;
}
}
assertTrue("Didn't find CourseRemonstraneProcess", foundRemonstrance);
assertTrue("Didn't find NewCourseRequest", foundNewCourse);
assertTrue("Didn't find DeleteCourseRequest", foundDelete);
//reload and verify that the structure looks the same - the below is missing one of the children document types
//to verify that a partial upload of the hierarchy doesn't kill the entire hierarchy
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration2.xml");
parent = KEWServiceLocator.getDocumentTypeService().findByName("UGSDocumentType");
foundRemonstrance = false;
foundNewCourse = false;
foundDelete = false;
int i = 0;
for (Iterator iter = parent.getChildrenDocTypes().iterator(); iter.hasNext(); i++) {
DocumentType childDocType = (DocumentType) iter.next();
assertTrue("child documenttype should be current", childDocType.getCurrentInd().booleanValue());
if(childDocType.getName().equals("CourseRemonstranceProcess")) {
foundRemonstrance = true;
} else if (childDocType.getName().equals("NewCourseRequest")) {
foundNewCourse = true;
} else if (childDocType.getName().equals("DeleteCourseRequest")) {
foundDelete = true;
}
}
assertTrue("Didn't find CourseRemonstranceProcess", foundRemonstrance);
assertTrue("Didn't find NewCourseRequest", foundNewCourse);
assertTrue("Didn't find DeleteCourseRequest", foundDelete);
}
//verifies documenttype hierarchy is intact after uploading a series of documenttypes and then
//uploading a parent onto those document types
@Test public void testHierarchyUpload2() throws Exception {
super.loadXmlFile("DocTypesWithoutParent.xml");
//Verify that the document types are there
DocumentType courseRemonstrance1 = KEWServiceLocator.getDocumentTypeService().findByName("CourseRemonstranceProcess");
DocumentType newCourseRequest1 = KEWServiceLocator.getDocumentTypeService().findByName("NewCourseRequest");
DocumentType deleteCourse1 = KEWServiceLocator.getDocumentTypeService().findByName("DeleteCourseRequest");
//upload the new config with the parent and verify we are getting new document types with new versions
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
DocumentType courseRemonstrance2 = null;
DocumentType newCourseRequest2 = null;
DocumentType deleteCourse2 = null;
DocumentType ugsDocumentType = KEWServiceLocator.getDocumentTypeService().findByName("UGSDocumentType");
for (Iterator iter = ugsDocumentType.getChildrenDocTypes().iterator(); iter.hasNext();) {
DocumentType childDocType = (DocumentType) iter.next();
if(childDocType.getName().equals("CourseRemonstranceProcess")) {
courseRemonstrance2 = childDocType;
} else if (childDocType.getName().equals("NewCourseRequest")) {
newCourseRequest2 = childDocType;
} else if (childDocType.getName().equals("DeleteCourseRequest")) {
deleteCourse2 = childDocType;
}
}
assertNotNull(courseRemonstrance2);
assertNotNull(newCourseRequest2);
assertNotNull(deleteCourse2);
assertTrue("Version didn't get incremented", courseRemonstrance1.getVersion().intValue() < courseRemonstrance2.getVersion().intValue());
assertTrue("Version didn't increment", newCourseRequest1.getVersion().intValue() < newCourseRequest2.getVersion().intValue());
assertTrue("Version didn't increment", deleteCourse1.getVersion().intValue() < deleteCourse2.getVersion().intValue());
}
/**
* Tests that the document type ingestion will not create a brand new
* document when only label or description field changes. Relates to
* JIRA's EN-318 and KULOWF-147.
*
* @throws Exception
*/
@Test public void testDocumentTypeIngestion() throws Exception {
// first ingestion
super.loadXmlFile("DocTypeIngestTestConfig1.xml"); // original document
super.loadXmlFile("DocTypeIngestTestConfig2.xml"); // document with changed label and description fields
DocumentType secondIngestDoc = KEWServiceLocator.getDocumentTypeService().findByName("IngestTestDocumentType");
assertNotNull("Second ingested document has empty Previous Version ID after first ingest", secondIngestDoc.getPreviousVersionId());
DocumentType firstIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(secondIngestDoc.getPreviousVersionId());
// the second ingested document should now be set to Current with the first ingested document should no longer be set to Current
assertEquals("First ingested document is still set to Current after first ingest", Boolean.FALSE, firstIngestDoc.getCurrentInd());
assertEquals("Second ingested document is not set to Current after first ingest", Boolean.TRUE, secondIngestDoc.getCurrentInd());
// second ingestion
super.loadXmlFile("DocTypeIngestTestConfig3.xml"); // document setting active to false
firstIngestDoc = null;
secondIngestDoc = null;
DocumentType thirdIngestDoc = KEWServiceLocator.getDocumentTypeService().findByName("IngestTestDocumentType");
assertNotNull("Third ingested document has empty Previous Version ID after second ingest", thirdIngestDoc.getPreviousVersionId());
secondIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(thirdIngestDoc.getPreviousVersionId());
assertNotNull("Second ingested document has empty Previous Version ID after second ingest", secondIngestDoc.getPreviousVersionId());
firstIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(secondIngestDoc.getPreviousVersionId());
// the third ingested document should now be set to Current and Inactive... all others should not be set to Current
assertEquals("First ingested document is set to Current after second ingest", Boolean.FALSE, firstIngestDoc.getCurrentInd());
assertEquals("Second ingested document is set to Current after second ingest", Boolean.FALSE, secondIngestDoc.getCurrentInd());
assertEquals("Third ingested document is not set to Inactive after second ingest", Boolean.FALSE, thirdIngestDoc.getActive());
assertEquals("Third ingested document is not set to Current after second ingest", Boolean.TRUE, thirdIngestDoc.getCurrentInd());
// third ingestion
super.loadXmlFile("DocTypeIngestTestConfig4.xml"); // document setting active to true
firstIngestDoc = null;
secondIngestDoc = null;
thirdIngestDoc = null;
DocumentType fourthIngestDoc = KEWServiceLocator.getDocumentTypeService().findByName("IngestTestDocumentType");
assertNotNull("Fourth ingested document has empty Previous Version ID after third ingest", fourthIngestDoc.getPreviousVersionId());
thirdIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(fourthIngestDoc.getPreviousVersionId());
assertNotNull("Third ingested document has empty Previous Version ID after third ingest", thirdIngestDoc.getPreviousVersionId());
secondIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(thirdIngestDoc.getPreviousVersionId());
assertNotNull("Second ingested document has empty Previous Version ID after third ingest", secondIngestDoc.getPreviousVersionId());
firstIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(secondIngestDoc.getPreviousVersionId());
// the fourth ingested document should now be set to Current and Active... all others should not be set to Current
assertEquals("First ingested document is set to Current after third ingest", Boolean.FALSE, firstIngestDoc.getCurrentInd());
assertEquals("Second ingested document is set to Current after third ingest", Boolean.FALSE, secondIngestDoc.getCurrentInd());
assertEquals("Third ingested document is set to Current after third ingest", Boolean.FALSE, thirdIngestDoc.getCurrentInd());
assertEquals("Fourth ingested document is not set to Active after third ingest", Boolean.TRUE, fourthIngestDoc.getActive());
assertEquals("Fourth ingested document is not set to Current after third ingest", Boolean.TRUE, fourthIngestDoc.getCurrentInd());
}
@Test public void testSameFileChildParentIngestion() throws Exception {
loadXmlFile("ChildParentTestConfig1.xml");
verifyDocumentTypeLinking();
loadXmlFile("ChildParentTestConfig2.xml");
verifyDocumentTypeLinking();
}
@Test
public void testPostProcessor() throws Exception {
loadXmlFile("DoctypePostProcessorConfig.xml");
DocumentType ppTestParent1 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestParent1");
DocumentType ppTestParent2 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestParent2");
DocumentType ppTestChild1 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestChild1");
DocumentType ppTestChild2 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestChild2");
DocumentType ppTestChild3 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestChild3");
assertEquals("Incorrect PostProcessor", MockPostProcessor.class, ppTestParent1.getPostProcessor().getClass());
assertEquals("Incorrect PostProcessor", DefaultPostProcessor.class, ppTestParent2.getPostProcessor().getClass());
assertEquals("Incorrect PostProcessor", MockPostProcessor.class, ppTestChild1.getPostProcessor().getClass());
PostProcessor testChild2PP = ppTestChild2.getPostProcessor();
assertEquals("Incorrect PostProcessorRemote", EDocLitePostProcessor.class, testChild2PP.getClass());
assertEquals("Incorrect PostProcessor", DefaultPostProcessor.class, ppTestChild3.getPostProcessor().getClass());
}
/**
* Tests to ensure that a given document type has its fields updated when the a second XML doc type with the same name is ingested.
*
* NOTE: This unit test is still incomplete.
*
* @throws Exception
*/
@Test public void testUpdateOfDocTypeFields() throws Exception {
//Collection<DocumentTypePolicy> docPolicies = docType.getPolicies();
//List<DocumentTypeAttribute> docAttributes = docType.getDocumentTypeAttributes();
//List firstRouteNode = KEWServiceLocator.getRouteNodeService().getInitialNodeInstances(docType.getDocumentTypeId());
// The expected field values from the test XML files.
String[][] expectedValues = { {"TestWithMostParams1", "TestParent01", "A test of doc type parameters.", "TestWithMostParams1",
"mocks.MockPostProcessor", "KR-WKFLW:TestWorkgroup", null, "any", "KR-WKFLW:TestWorkgroup",
"KR-WKFLW:TestWorkgroup", "_blank", "_blank", "_blank", "_blank", "_blank", "TestCl1", "false", "a.doc.type.authorizer"},
{"TestWithMostParams1", "AnotherParent", "Another test of most parameters.",
"AntoherTestWithMostParams", "org.kuali.rice.kew.postprocessor.DefaultPostProcessor", "KR-WKFLW:WorkflowAdmin",
"KR-WKFLW:WorkflowAdmin", null, "KR-WKFLW:WorkflowAdmin", "KR-WKFLW:WorkflowAdmin", "_nothing", "_nothing",
"_nothing", "_nothing", "_nothing", "KEW", "true", "a.parent.authorizer"}
};
// Ingest each document type, and test the properties of each one.
for (int i = 0; i < expectedValues.length; i++) {
// Load the document type and store its data.
String fileToLoad = "DocTypeWithMostParams" + (i+1) + ".xml";
loadXmlFile(fileToLoad);
DocumentType docType = KEWServiceLocator.getDocumentTypeService().findByName("TestWithMostParams1");
Group baWorkgroup = docType.getBlanketApproveWorkgroup();
Group rpWorkgroup = docType.getReportingWorkgroup();
Group deWorkgroup = getValidDefaultExceptionWorkgroup(docType);
String[] actualValues = {docType.getName(), docType.getParentDocType().getName(), docType.getDescription(),
docType.getLabel(), docType.getPostProcessorName(), constructGroupNameWithNamespace(docType.getSuperUserWorkgroupNoInheritence()),
constructGroupNameWithNamespace(baWorkgroup), docType.getBlanketApprovePolicy(),
constructGroupNameWithNamespace(rpWorkgroup), constructGroupNameWithNamespace(deWorkgroup),
docType.getUnresolvedDocHandlerUrl(), docType.getUnresolvedHelpDefinitionUrl(),
docType.getUnresolvedDocSearchHelpUrl(),
docType.getNotificationFromAddress(), docType.getCustomEmailStylesheet(),
docType.getApplicationId(), docType.getActive().toString(),
docType.getAuthorizer()
};
// Compare the expected field values with the actual ones.
for (int j = 0; j < expectedValues[i].length; j++) {
assertEquals("The document does not have the expected parameter value. (i=" + i + ",j=" + j + ")", expectedValues[i][j], actualValues[j]);
}
}
}
private Group getValidDefaultExceptionWorkgroup(DocumentType documentType) {
List flattenedNodes = KEWServiceLocator.getRouteNodeService().getFlattenedNodes(documentType, false);
assertTrue("Document Type '" + documentType.getName() + "' should have a default exception workgroup.", hasDefaultExceptionWorkgroup(flattenedNodes));
return ((RouteNode)flattenedNodes.get(0)).getExceptionWorkgroup();
}
// this method is duplicated in the DocumentTypeXmlExporter class
private boolean hasDefaultExceptionWorkgroup(List flattenedNodes) {
boolean hasDefaultExceptionWorkgroup = true;
String exceptionWorkgroupName = null;
for (Iterator iterator = flattenedNodes.iterator(); iterator.hasNext();) {
RouteNode node = (RouteNode) iterator.next();
if (exceptionWorkgroupName == null) {
exceptionWorkgroupName = node.getExceptionWorkgroupName();
}
if (exceptionWorkgroupName == null || !exceptionWorkgroupName.equals(node.getExceptionWorkgroupName())) {
hasDefaultExceptionWorkgroup = false;
break;
}
}
return hasDefaultExceptionWorkgroup;
}
private String constructGroupNameWithNamespace(Group group) {
if (group == null) {
return null;
}
return group.getNamespaceCode() + KewApiConstants.KIM_GROUP_NAMESPACE_NAME_DELIMITER_CHARACTER + group.getName();
}
protected void verifyDocumentTypeLinking() throws Exception {
DocumentTypeService service = KEWServiceLocator.getDocumentTypeService();
List rootDocs = service.findAllCurrentRootDocuments();
int numRoots = rootDocs.size();
List documentTypes = service.findAllCurrent();
List<DocumentType> leafs = new ArrayList<DocumentType>();
for (Iterator iterator = documentTypes.iterator(); iterator.hasNext();) {
DocumentType documentType = (DocumentType) iterator.next();
// check that all document types with parents are current
if (KRADUtils.isNotNull(documentType.getParentDocType())) {
assertEquals("Parent of document type '" + documentType.getName() + "' should be Current", Boolean.TRUE, documentType.getParentDocType().getCurrentInd());
}
List children = service.getChildDocumentTypes(documentType.getDocumentTypeId());
if (children.isEmpty()) {
leafs.add(documentType);
} else {
// check that all child document types are current
for (Iterator iterator2 = children.iterator(); iterator2.hasNext();) {
DocumentType childDocType = (DocumentType) iterator2.next();
assertEquals("Any child document type should be Current", Boolean.TRUE, childDocType.getCurrentInd());
}
}
}
Set<String> rootDocIds = new HashSet<String>();
// verify the hierarchy
for (DocumentType leaf : leafs) {
verifyHierarchy(leaf, rootDocIds);
}
// we should have the same number of roots as we did from the original roots query
assertEquals("Should have the same number of roots", numRoots, rootDocIds.size());
}
protected void verifyHierarchy(DocumentType docType, Set<String> rootDocIds) {
assertTrue("DocumentType " + docType.getName() + " should be current.", docType.getCurrentInd().booleanValue());
if (docType.getParentDocType() == null) {
rootDocIds.add(docType.getDocumentTypeId());
} else {
verifyHierarchy(docType.getParentDocType(), rootDocIds);
}
}
private class LoadXml implements Runnable {
private final String xmlFile;
private final Callback callback;
private final CyclicBarrier barrier;
LoadXml(String xmlFile, Callback callback, CyclicBarrier barrier) {
this.xmlFile = xmlFile;
this.callback = callback;
this.barrier = barrier;
}
public void run() {
getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
try {
barrier.await(120, TimeUnit.SECONDS);
} catch (Exception e) {
}
try {
loadXmlFile(xmlFile);
} catch (Throwable t) {
callback.record(xmlFile, t);
}
// try {
// barrier.await(120, TimeUnit.SECONDS);
// } catch (Exception e) {
// }
}
});
}
}
private class Callback {
private String xmlFile;
private Throwable t;
public void record(String xmlFile, Throwable t) {
this.xmlFile = xmlFile;
this.t = t;
}
public boolean isXmlLoaded() {
if (t != null) {
t.printStackTrace();
//fail("Failed to load xml file " + xmlFile);
LOG.info("The XML file " + xmlFile + " failed to load, but this was expected.");
return false;
}
return true;
}
}
}
| KULRICE-12853. Additional logging for investigation.
| rice-middleware/it/kew/src/test/java/org/kuali/rice/kew/doctype/DocumentTypeTest.java | KULRICE-12853. Additional logging for investigation. | <ide><path>ice-middleware/it/kew/src/test/java/org/kuali/rice/kew/doctype/DocumentTypeTest.java
<ide> import org.kuali.rice.kew.api.KewApiServiceLocator;
<ide> import org.kuali.rice.kew.api.WorkflowDocument;
<ide> import org.kuali.rice.kew.api.WorkflowDocumentFactory;
<add>import org.kuali.rice.kew.api.action.ActionTaken;
<add>import org.kuali.rice.kew.api.document.DocumentStatus;
<ide> import org.kuali.rice.kew.doctype.bo.DocumentType;
<ide> import org.kuali.rice.kew.doctype.service.DocumentTypeService;
<ide> import org.kuali.rice.kew.engine.node.NodeType;
<ide> verifyDocumentTypeLinking();
<ide> }
<ide>
<add> // Temporary logging for KULRICE-12853 investigation.
<add> private void logExtraInfo (String message, WorkflowDocument document) {
<add>
<add> LOG.info(" ");
<add> LOG.info("*** " + message + ", docId: " + document.getDocumentId()
<add> + ", Approval requested: " + document.isApprovalRequested()
<add> + ", status: " + document.getStatus());
<add>
<add> Set<String> nodeNames = document.getNodeNames();
<add> for (String nodeName : nodeNames) {
<add> LOG.info("*** Node name: " + nodeName);
<add> }
<add>
<add> List<ActionTaken> actionsTaken = document.getActionsTaken();
<add> for (ActionTaken actionTaken : actionsTaken) {
<add> LOG.info("*** Action taken. Id: " + actionTaken.getId()
<add> + ", docId: " + actionTaken.getDocumentId()
<add> + ", principalId: " + actionTaken.getPrincipalId()
<add> + ", action: " + actionTaken.getActionTaken()
<add> + ", date: " + actionTaken.getActionDate());
<add> }
<add>
<add> LOG.info(" ");
<add> }
<add>
<add> // Contains temporary logging for KULRICE-12853 investigation.
<ide> @Test public void testNestedDuplicateNodeNameInRoutePath() throws Exception {
<ide> int waitMilliSeconds = 5000;
<ide> loadXmlFile("DocTypeConfig_nestedNodes.xml");
<ide> document.setTitle("");
<ide> document.route("");
<ide>
<add> logExtraInfo("user1 (after route)", document);
<add>
<ide> // Split1, left (rkirkend --> user2)
<ide> document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
<ide> assertTrue("rkirkend should have an approve request; the first request", document.isApprovalRequested());
<del> document.approve("");
<add>
<add> logExtraInfo("rkirkend before approve", document);
<add>
<add> document.approve("");
<add>
<add> logExtraInfo("rkirkend after approve", document);
<add>
<ide> document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), document.getDocumentId());
<ide> assertTrue("user2 should have an approve request", document.isApprovalRequested());
<del> document.approve("");
<add>
<add> // se10
<add> logExtraInfo("user2 before approve", document);
<add> document.approve("");
<add> logExtraInfo("user2 after approve", document);
<ide>
<ide> // Some temp logging to look into KULRICE-12853.
<ide> LOG.info("isApprovalRequested Loop Starts") ;
<ide> boolean loopSuccess = false;
<ide> int loopPasses = 0;
<ide>
<del> // Split1, Right, Innersplit, Right (user4)
<del> for (int j=25; j >= 0; j--) {
<add> for (int j=30; j >= 0; j--) {
<ide> loopPasses++;
<ide> Thread.sleep(waitMilliSeconds);
<ide> document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user4"), document.getDocumentId());
<add> logExtraInfo("user4 polling for isApprovalRequested", document);
<ide> if (document.isApprovalRequested()) {
<ide> loopSuccess = true;
<ide> break;
<ide> }
<ide> }
<ide>
<del> // Some temp logging to look into KULRICE-12853.
<ide> LOG.info("isApprovalRequested Loop Finished") ;
<ide> LOG.info("loopSuccess: " + loopSuccess + ". Number of 5 second loop passes: " + loopPasses);
<ide>
<ide> assertTrue("user4 should have an approve request", document.isApprovalRequested());
<del> document.approve("");
<add> logExtraInfo("user4 before approve", document);
<add> document.approve("");
<add> logExtraInfo("user4 after approve", document);
<ide>
<ide> // Split1, Right, Innersplit, Left (rkirkend --> user3)
<ide> document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), document.getDocumentId());
<ide> assertTrue("user3 should have an approve request; the first request", document.isApprovalRequested());
<del> document.approve("");
<add>
<add> logExtraInfo("user3 before approve", document);
<add> document.approve("");
<add> logExtraInfo("user3 after approve", document);
<ide>
<ide> // Split2, Left (rkirkend --> user3) NOTE - Split2, Right is a NoOp node
<ide> document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
<ide> assertTrue("rkirkend should have an approve request; the second request", document.isApprovalRequested());
<del> document.approve("");
<add>
<add> logExtraInfo("rkirkend before approve", document);
<add> document.approve("");
<add> logExtraInfo("rkirkend after approve", document);
<add>
<ide> document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), document.getDocumentId());
<ide> assertTrue("user3 should have an approve request; the second request", document.isApprovalRequested());
<del> document.approve("");
<add>
<add> logExtraInfo("user3 after approve", document);
<add> document.approve("");
<add> logExtraInfo("user3 after approve", document);
<ide> }
<ide> /**
<ide> * Verify that enroute documents are not affected if you edit their document type. |
|
Java | apache-2.0 | a5b3e75633ad129bfc42c55664fbc484bb484b33 | 0 | Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient | package org.sagebionetworks.web.client.widget.entity;
import java.util.List;
import org.gwtbootstrap3.client.ui.Anchor;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.FormGroup;
import org.gwtbootstrap3.client.ui.Heading;
import org.gwtbootstrap3.client.ui.InlineCheckBox;
import org.gwtbootstrap3.client.ui.Modal;
import org.gwtbootstrap3.client.ui.Radio;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.html.Div;
import org.gwtbootstrap3.client.ui.html.Span;
import org.gwtbootstrap3.extras.select.client.ui.Option;
import org.gwtbootstrap3.extras.select.client.ui.Select;
import org.sagebionetworks.evaluation.model.Evaluation;
import org.sagebionetworks.repo.model.Reference;
import org.sagebionetworks.repo.model.Team;
import org.sagebionetworks.web.client.DisplayConstants;
import org.sagebionetworks.web.client.DisplayUtils;
import org.sagebionetworks.web.client.DisplayUtils.SelectedHandler;
import org.sagebionetworks.web.client.PortalGinInjector;
import org.sagebionetworks.web.client.utils.Callback;
import org.sagebionetworks.web.client.widget.entity.browse.EntityFinder;
import org.sagebionetworks.web.client.widget.user.UserBadge;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class EvaluationSubmitterViewImpl implements EvaluationSubmitterView {
public interface EvaluationSubmitterViewImplUiBinder extends UiBinder<Widget, EvaluationSubmitterViewImpl> {}
private Presenter presenter;
private EvaluationList evaluationList;
private EntityFinder entityFinder;
private boolean showEntityFinder;
private Reference selectedReference;
Widget widget;
@UiField
Modal modal1;
@UiField
Modal modal2;
@UiField
Button nextButton;
@UiField
Button okButton;
@UiField
Button entityFinderButton;
@UiField
SimplePanel evaluationListContainer;
@UiField
TextBox submissionNameField;
@UiField
Heading selectedText;
@UiField
FormGroup entityFinderUI;
@UiField
Select teamComboBox;
@UiField
Radio isIndividualRadioButton;
@UiField
Div contributorsPanel;
@UiField
SimplePanel registerTeamDialogContainer;
@UiField
Anchor registerMyTeamLink;
@UiField
Anchor createNewTeamLink;
private PortalGinInjector ginInjector;
private RegisterTeamDialog registerTeamDialog;
@Inject
public EvaluationSubmitterViewImpl(
EvaluationSubmitterViewImplUiBinder binder,
EntityFinder entityFinder,
EvaluationList evaluationList,
PortalGinInjector ginInjector,
RegisterTeamDialog registerTeamDialog) {
widget = binder.createAndBindUi(this);
this.entityFinder = entityFinder;
this.evaluationList = evaluationList;
this.ginInjector = ginInjector;
this.registerTeamDialog = registerTeamDialog;
contributorsPanel.getElement().setAttribute("highlight-box-title", "Contributors");
evaluationListContainer.setWidget(evaluationList.asWidget());
registerTeamDialogContainer.setWidget(registerTeamDialog.asWidget());
initClickHandlers();
}
public void initClickHandlers() {
nextButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Evaluation evaluation = evaluationList.getSelectedEvaluation();
if (evaluation != null) {
if (showEntityFinder) {
if (selectedReference == null || selectedReference.getTargetId() == null) {
//invalid, return.
showErrorMessage(DisplayConstants.NO_ENTITY_SELECTED);
return;
}
}
presenter.nextClicked(selectedReference, submissionNameField.getValue(), evaluation);
} else {
showErrorMessage(DisplayConstants.NO_EVALUATION_SELECTED);
}
}
});
okButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
presenter.doneClicked();
}
});
entityFinderButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
entityFinder.configure(true, new SelectedHandler<Reference>() {
@Override
public void onSelected(Reference selected) {
if(selected.getTargetId() != null) {
selectedReference = selected;
selectedText.setText(DisplayUtils.createEntityVersionString(selected));
entityFinder.hide();
} else {
showErrorMessage(DisplayConstants.PLEASE_MAKE_SELECTION);
}
}
});
entityFinder.show();
}
});
teamComboBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
presenter.teamSelected(teamComboBox.getValue());
}
});
registerMyTeamLink.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
presenter.registerMyTeamLinkClicked();
}
});
createNewTeamLink.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
presenter.createNewTeamClicked();
}
});
}
@Override
public void showRegisterTeamDialog(String challengeId) {
registerTeamDialog.configure(challengeId, new Callback() {
@Override
public void invoke() {
presenter.teamAdded();
}
});
registerTeamDialog.showModal();
}
@Override
public boolean isIndividual() {
return isIndividualRadioButton.isActive();
}
@Override
public void setPresenter(Presenter p) {
presenter = p;
}
@Override
public void showLoading() {
}
@Override
public void clear() {
selectedReference = null;
selectedText.setText("");
}
@Override
public void showSubmissionAcceptedDialogs(String message) {
DisplayUtils.showInfoDialog(DisplayConstants.THANK_YOU_FOR_SUBMISSION, SafeHtmlUtils.htmlEscape(message), null);
}
@Override
public void showInfo(String title, String message) {
DisplayUtils.showInfo(title, message);
}
@Override
public void showErrorMessage(String message) {
DisplayUtils.showErrorMessage(message);
}
@Override
public void showModal1(boolean showEntityFinder, List<Evaluation> evaluations) {
clear();
entityFinderUI.setVisible(showEntityFinder);
evaluationList.configure(evaluations);
this.showEntityFinder = showEntityFinder;
modal1.show();
}
@Override
public void hideModal1() {
modal1.hide();
}
@Override
public void setTeams(List<Team> registeredTeams) {
teamComboBox.clear();
isIndividualRadioButton.setActive(true);
for (Team teamHeader : registeredTeams) {
Option teamOption = new Option();
teamOption.setText(teamHeader.getName());
teamComboBox.add(teamOption);
}
}
@Override
public void showModal2() {
modal2.show();
}
@Override
public void hideModal2() {
modal2.hide();
}
@Override
public Widget asWidget() {
return widget;
}
@Override
public void setContributorsListVisible(boolean isVisible) {
contributorsPanel.setVisible(isVisible);
}
@Override
public void clearContributors() {
contributorsPanel.clear();
}
@Override
public void addEligibleContributor(String principalId) {
contributorsPanel.add(getContributorRow(principalId, true));
}
@Override
public void addInEligibleContributor(String principalId, String reason) {
Div row = getContributorRow(principalId, false);
//also add the reason
Span span = new Span();
span.addStyleName("greyText-imp");
span.setText(reason);
row.add(span);
contributorsPanel.add(row);
}
private Div getContributorRow(String principalId, boolean selectCheckbox) {
Div row = new Div();
InlineCheckBox cb = new InlineCheckBox();
cb.setValue(selectCheckbox);
cb.setEnabled(false);
row.add(cb);
UserBadge badge = ginInjector.getUserBadgeWidget();
badge.configure(principalId);
row.add(badge.asWidget());
return row;
}
}
| src/main/java/org/sagebionetworks/web/client/widget/entity/EvaluationSubmitterViewImpl.java | package org.sagebionetworks.web.client.widget.entity;
import java.util.List;
import org.gwtbootstrap3.client.ui.Anchor;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.FormGroup;
import org.gwtbootstrap3.client.ui.Heading;
import org.gwtbootstrap3.client.ui.InlineCheckBox;
import org.gwtbootstrap3.client.ui.Modal;
import org.gwtbootstrap3.client.ui.Radio;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.html.Div;
import org.gwtbootstrap3.client.ui.html.Span;
import org.gwtbootstrap3.extras.select.client.ui.Option;
import org.gwtbootstrap3.extras.select.client.ui.Select;
import org.sagebionetworks.evaluation.model.Evaluation;
import org.sagebionetworks.repo.model.Reference;
import org.sagebionetworks.repo.model.Team;
import org.sagebionetworks.web.client.DisplayConstants;
import org.sagebionetworks.web.client.DisplayUtils;
import org.sagebionetworks.web.client.DisplayUtils.SelectedHandler;
import org.sagebionetworks.web.client.PortalGinInjector;
import org.sagebionetworks.web.client.utils.Callback;
import org.sagebionetworks.web.client.widget.entity.browse.EntityFinder;
import org.sagebionetworks.web.client.widget.user.UserBadge;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class EvaluationSubmitterViewImpl implements EvaluationSubmitterView {
public interface EvaluationSubmitterViewImplUiBinder extends UiBinder<Widget, EvaluationSubmitterViewImpl> {}
private Presenter presenter;
private EvaluationList evaluationList;
private EntityFinder entityFinder;
private boolean showEntityFinder;
private Reference selectedReference;
Widget widget;
@UiField
Modal modal1;
@UiField
Modal modal2;
@UiField
Button nextButton;
@UiField
Button okButton;
@UiField
Button entityFinderButton;
@UiField
SimplePanel evaluationListContainer;
@UiField
TextBox submissionNameField;
@UiField
Heading selectedText;
@UiField
FormGroup entityFinderUI;
@UiField
Select teamComboBox;
@UiField
Radio isIndividualRadioButton;
@UiField
Div contributorsPanel;
@UiField
SimplePanel registerTeamDialogContainer;
@UiField
Anchor registerMyTeamLink;
@UiField
Anchor createNewTeamLink;
private PortalGinInjector ginInjector;
private RegisterTeamDialog registerTeamDialog;
@Inject
public EvaluationSubmitterViewImpl(
EvaluationSubmitterViewImplUiBinder binder,
EntityFinder entityFinder,
EvaluationList evaluationList,
PortalGinInjector ginInjector,
RegisterTeamDialog registerTeamDialog) {
widget = binder.createAndBindUi(this);
this.entityFinder = entityFinder;
this.evaluationList = evaluationList;
this.ginInjector = ginInjector;
this.registerTeamDialog = registerTeamDialog;
contributorsPanel.getElement().setAttribute("highlight-box-title", "Contributors");
evaluationListContainer.setWidget(evaluationList.asWidget());
registerTeamDialogContainer.setWidget(registerTeamDialog.asWidget());
initClickHandlers();
}
public void initClickHandlers() {
nextButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Evaluation evaluation = evaluationList.getSelectedEvaluation();
if (evaluation != null) {
if (showEntityFinder) {
if (selectedReference == null || selectedReference.getTargetId() == null) {
//invalid, return.
showErrorMessage(DisplayConstants.NO_ENTITY_SELECTED);
return;
}
}
presenter.nextClicked(selectedReference, submissionNameField.getValue(), evaluation);
} else {
showErrorMessage(DisplayConstants.NO_EVALUATION_SELECTED);
}
}
});
okButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
presenter.doneClicked();
}
});
entityFinderButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
entityFinder.configure(true, new SelectedHandler<Reference>() {
@Override
public void onSelected(Reference selected) {
if(selected.getTargetId() != null) {
selectedReference = selected;
selectedText.setText(DisplayUtils.createEntityVersionString(selected));
entityFinder.hide();
} else {
showErrorMessage(DisplayConstants.PLEASE_MAKE_SELECTION);
}
}
});
entityFinder.show();
}
});
teamComboBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
presenter.teamSelected(teamComboBox.getValue());
}
});
registerMyTeamLink.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
presenter.registerMyTeamLinkClicked();
}
});
createNewTeamLink.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
presenter.createNewTeamClicked();
}
});
}
@Override
public void showRegisterTeamDialog(String challengeId) {
registerTeamDialog.configure(challengeId, new Callback() {
@Override
public void invoke() {
presenter.teamAdded();
}
});
}
@Override
public boolean isIndividual() {
return isIndividualRadioButton.isActive();
}
@Override
public void setPresenter(Presenter p) {
presenter = p;
}
@Override
public void showLoading() {
}
@Override
public void clear() {
selectedReference = null;
selectedText.setText("");
}
@Override
public void showSubmissionAcceptedDialogs(String message) {
DisplayUtils.showInfoDialog(DisplayConstants.THANK_YOU_FOR_SUBMISSION, SafeHtmlUtils.htmlEscape(message), null);
}
@Override
public void showInfo(String title, String message) {
DisplayUtils.showInfo(title, message);
}
@Override
public void showErrorMessage(String message) {
DisplayUtils.showErrorMessage(message);
}
@Override
public void showModal1(boolean showEntityFinder, List<Evaluation> evaluations) {
clear();
entityFinderUI.setVisible(showEntityFinder);
evaluationList.configure(evaluations);
this.showEntityFinder = showEntityFinder;
modal1.show();
}
@Override
public void hideModal1() {
modal1.hide();
}
@Override
public void setTeams(List<Team> registeredTeams) {
teamComboBox.clear();
isIndividualRadioButton.setActive(true);
for (Team teamHeader : registeredTeams) {
Option teamOption = new Option();
teamOption.setText(teamHeader.getName());
teamComboBox.add(teamOption);
}
}
@Override
public void showModal2() {
modal2.show();
}
@Override
public void hideModal2() {
modal2.hide();
}
@Override
public Widget asWidget() {
return widget;
}
@Override
public void setContributorsListVisible(boolean isVisible) {
contributorsPanel.setVisible(isVisible);
}
@Override
public void clearContributors() {
contributorsPanel.clear();
}
@Override
public void addEligibleContributor(String principalId) {
contributorsPanel.add(getContributorRow(principalId, true));
}
@Override
public void addInEligibleContributor(String principalId, String reason) {
Div row = getContributorRow(principalId, false);
//also add the reason
Span span = new Span();
span.addStyleName("greyText-imp");
span.setText(reason);
row.add(span);
contributorsPanel.add(row);
}
private Div getContributorRow(String principalId, boolean selectCheckbox) {
Div row = new Div();
InlineCheckBox cb = new InlineCheckBox();
cb.setValue(selectCheckbox);
cb.setEnabled(false);
row.add(cb);
UserBadge badge = ginInjector.getUserBadgeWidget();
badge.configure(principalId);
row.add(badge.asWidget());
return row;
}
}
| show register team modal
| src/main/java/org/sagebionetworks/web/client/widget/entity/EvaluationSubmitterViewImpl.java | show register team modal | <ide><path>rc/main/java/org/sagebionetworks/web/client/widget/entity/EvaluationSubmitterViewImpl.java
<ide> presenter.teamAdded();
<ide> }
<ide> });
<add> registerTeamDialog.showModal();
<ide> }
<ide>
<ide> @Override |
|
Java | mit | 56e4f774606b99542d71db458e2739e3214621b3 | 0 | bitcoin-solutions/multibit-hd,akonring/multibit-hd-modified,oscarguindzberg/multibit-hd,akonring/multibit-hd-modified,akonring/multibit-hd-modified,oscarguindzberg/multibit-hd,bitcoin-solutions/multibit-hd,bitcoin-solutions/multibit-hd,oscarguindzberg/multibit-hd | package org.multibit.hd.ui.views.wizards.use_trezor;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.multibit.hd.core.exceptions.ExceptionHandler;
import org.multibit.hd.core.services.CoreServices;
import org.multibit.hd.hardware.core.HardwareWalletService;
import org.multibit.hd.hardware.core.events.HardwareWalletEvent;
import org.multibit.hd.hardware.core.messages.ButtonRequest;
import org.multibit.hd.hardware.core.messages.Features;
import org.multibit.hd.ui.events.view.ViewEvents;
import org.multibit.hd.ui.languages.MessageKey;
import org.multibit.hd.ui.views.wizards.AbstractHardwareWalletWizardModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.swing.*;
import java.util.concurrent.Callable;
/**
* <p>Model object to provide the following to "use Trezor wizard":</p>
* <ul>
* <li>Storage of PIN entered</li>
* <li>State transition management</li>
* <li>Handling of various Trezor requests</li>
* </ul>
*
* @since 0.0.1
*
*/
public class UseTrezorWizardModel extends AbstractHardwareWalletWizardModel<UseTrezorState> {
private static final Logger log = LoggerFactory.getLogger(UseTrezorWizardModel.class);
/**
* The current selection option as a state
*/
private UseTrezorState currentSelection = UseTrezorState.BUY_TREZOR;
/**
* The features of the attached Trezor
*/
Optional<Features> featuresOptional = Optional.absent();
/**
* The "enter pin" panel view
*/
private UseTrezorEnterPinPanelView enterPinPanelView;
private UseTrezorRequestCipherKeyPanelView requestCipherKeyPanelView;
private UseTrezorReportPanelView reportPanelView;
public UseTrezorWizardModel(UseTrezorState useTrezorState) {
super(useTrezorState);
}
@Override
public String getPanelName() {
return state.name();
}
public UseTrezorEnterPinPanelView getEnterPinPanelView() {
return enterPinPanelView;
}
public void setEnterPinPanelView(UseTrezorEnterPinPanelView enterPinPanelView) {
this.enterPinPanelView = enterPinPanelView;
}
public void setRequestCipherKeyPanelView(UseTrezorRequestCipherKeyPanelView requestCipherKeyPanelView) {
this.requestCipherKeyPanelView = requestCipherKeyPanelView;
}
@Override
public void showNext() {
log.debug("Current selection : {}", getCurrentSelection());
switch (state) {
case SELECT_TREZOR_ACTION:
switch (getCurrentSelection()) {
case SELECT_TREZOR_ACTION:
break;
case USE_TREZOR_WALLET:
//state = UseTrezorState.REQUEST_CIPHER_KEY;
break;
case BUY_TREZOR:
state = UseTrezorState.BUY_TREZOR;
break;
case VERIFY_TREZOR:
state = UseTrezorState.VERIFY_TREZOR;
break;
case REQUEST_WIPE_TREZOR:
state = UseTrezorState.REQUEST_WIPE_TREZOR;
break;
default:
throw new IllegalStateException("Cannot showNext with a state of SELECT_TREZOR_ACTION and a selection of " + getCurrentSelection());
}
break;
case BUY_TREZOR:
state = UseTrezorState.USE_TREZOR_REPORT_PANEL;
break;
case VERIFY_TREZOR:
state = UseTrezorState.USE_TREZOR_REPORT_PANEL;
break;
case REQUEST_WIPE_TREZOR:
// Trezor must have failed and user is clicking through
state = UseTrezorState.USE_TREZOR_REPORT_PANEL;
break;
case CONFIRM_WIPE_TREZOR:
state = UseTrezorState.USE_TREZOR_REPORT_PANEL;
break;
case ENTER_PIN:
break;
case NO_PIN_REQUIRED:
break;
default:
throw new IllegalStateException("Cannot showNext with a state of " + state);
}
}
@Override
public void showPrevious() {
switch (state) {
case BUY_TREZOR:
state = UseTrezorState.SELECT_TREZOR_ACTION;
break;
default:
throw new IllegalStateException("Unknown state: " + state.name());
}
}
@Override
public void showPINEntry(HardwareWalletEvent event) {
// Device is PIN protected
switch (state) {
default:
throw new IllegalStateException("Unknown state: " + state.name());
}
}
@Override
public void showButtonPress(HardwareWalletEvent event) {
log.debug("Received hardwareWalletEvent {}", event);
ButtonRequest buttonRequest = (ButtonRequest) event.getMessage().get();
switch (state) {
case ENTER_PIN:
case NO_PIN_REQUIRED:
// Should be catered for by finish
break;
case REQUEST_WIPE_TREZOR:
switch (buttonRequest.getButtonRequestType()) {
case WIPE_DEVICE:
// Device requires confirmation to wipe
state = UseTrezorState.CONFIRM_WIPE_TREZOR;
break;
default:
throw new IllegalStateException("Unexpected button: " + buttonRequest.getButtonRequestType().name());
}
break;
case VERIFY_TREZOR:
// Should be catered for by finish on Verify Trezor panel
case USE_TREZOR_REPORT_PANEL:
// Should be catered for by finish on Trezor report panel
break;
default:
throw new IllegalStateException("Unknown state: " + state.name());
}
}
@Override
public void showOperationSucceeded(HardwareWalletEvent event) {
switch (state) {
case CONFIRM_WIPE_TREZOR:
// Indicate a successful wipe
state=UseTrezorState.USE_TREZOR_REPORT_PANEL;
setReportMessageKey(MessageKey.TREZOR_WIPE_DEVICE_SUCCESS);
setReportMessageStatus(true);
break;
default:
// TODO Fill in the other states and provide success feedback
log.info(
"Message:'Operation succeeded'\n{}",
event.getMessage().get()
);
}
}
@Override
public void showOperationFailed(HardwareWalletEvent event) {
// In all cases move to the report panel with a failure message
state=UseTrezorState.USE_TREZOR_REPORT_PANEL;
setReportMessageKey(MessageKey.TREZOR_WIPE_DEVICE_FAILURE);
setReportMessageStatus(false);
}
public UseTrezorState getCurrentSelection() {
return currentSelection;
}
public void setCurrentSelection(UseTrezorState currentSelection) {
this.currentSelection = currentSelection;
}
public Optional<Features> getFeaturesOptional() {
return featuresOptional;
}
/**
* <p>Request the Trezor features</p>
*/
public void requestFeatures() {
// Start the features request
ListenableFuture future = hardwareWalletRequestService.submit(
new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Optional<HardwareWalletService> hardwareWalletServiceOptional = CoreServices.getOrCreateHardwareWalletService();
if (hardwareWalletServiceOptional.isPresent()) {
HardwareWalletService hardwareWalletService = hardwareWalletServiceOptional.get();
featuresOptional = hardwareWalletService.getContext().getFeatures();
log.debug("Features : {}", featuresOptional);
} else {
log.error("No hardware wallet service");
}
return true;
}
});
Futures.addCallback(
future, new FutureCallback() {
@Override
public void onSuccess(@Nullable Object result) {
// We now have the features so throw a ComponentChangedEvent for the UI to update
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ViewEvents.fireComponentChangedEvent(UseTrezorState.VERIFY_TREZOR.name(), Optional.absent());
}
});
}
@Override
public void onFailure(Throwable t) {
// Have a failure - add failure text to the text area
}
});
}
/**
* <p>Wipe the Trezor device</p>
*/
public void requestWipeDevice() {
// Start the wipe Trezor
ListenableFuture future = hardwareWalletRequestService.submit(
new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Optional<HardwareWalletService> hardwareWalletServiceOptional = CoreServices.getOrCreateHardwareWalletService();
if (hardwareWalletServiceOptional.isPresent()) {
HardwareWalletService hardwareWalletService = hardwareWalletServiceOptional.get();
if (hardwareWalletService.isWalletPresent()) {
hardwareWalletService.wipeDevice();
log.debug("Wipe device request has been performed");
} else {
log.debug("No wallet present so no need to wipe the device");
}
} else {
log.error("No hardware wallet service");
}
return true;
}
});
Futures.addCallback(
future, new FutureCallback() {
@Override
public void onSuccess(@Nullable Object result) {
// We now wiped the device so throw a ComponentChangedEvent for the UI to update
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ViewEvents.fireComponentChangedEvent(UseTrezorState.REQUEST_WIPE_TREZOR.name(), Optional.absent());
}
});
setReportMessageKey(MessageKey.TREZOR_WIPE_DEVICE_SUCCESS);
setReportMessageStatus(true);
}
@Override
public void onFailure(Throwable t) {
// Have a failure
log.error("Unexpected failure during request wipe", t);
setReportMessageKey(MessageKey.TREZOR_WIPE_DEVICE_FAILURE);
setReportMessageStatus(false);
}
});
}
/**
* @param pinPositions The PIN positions providing a level of obfuscation to protect the PIN
*/
public void requestPinCheck(final String pinPositions) {
ListenableFuture<Boolean> pinCheckFuture = hardwareWalletRequestService.submit(
new Callable<Boolean>() {
@Override
public Boolean call() {
log.debug("Performing a PIN check");
// Talk to the Trezor and get it to check the PIN
// This call to the Trezor will (sometime later) fire a
// HardwareWalletEvent containing the encrypted text (or a PIN failure)
// Expect a SHOW_OPERATION_SUCCEEDED or SHOW_OPERATION_FAILED
Optional<HardwareWalletService> hardwareWalletService = CoreServices.getOrCreateHardwareWalletService();
hardwareWalletService.get().providePIN(pinPositions);
// Must have successfully send the message to be here
return true;
}
});
Futures.addCallback(
pinCheckFuture, new FutureCallback<Boolean>() {
@Override
public void onSuccess(Boolean result) {
// Do nothing - message was successfully relayed to the device
}
@Override
public void onFailure(Throwable t) {
// Device failed to receive the message
getEnterPinPanelView().setPinStatus(false, true);
// Should not have seen an error
ExceptionHandler.handleThrowable(t);
}
}
);
}
}
| mbhd-swing/src/main/java/org/multibit/hd/ui/views/wizards/use_trezor/UseTrezorWizardModel.java | package org.multibit.hd.ui.views.wizards.use_trezor;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.multibit.hd.core.exceptions.ExceptionHandler;
import org.multibit.hd.core.services.CoreServices;
import org.multibit.hd.hardware.core.HardwareWalletService;
import org.multibit.hd.hardware.core.events.HardwareWalletEvent;
import org.multibit.hd.hardware.core.messages.ButtonRequest;
import org.multibit.hd.hardware.core.messages.Features;
import org.multibit.hd.ui.events.view.ViewEvents;
import org.multibit.hd.ui.languages.MessageKey;
import org.multibit.hd.ui.views.wizards.AbstractHardwareWalletWizardModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.concurrent.Callable;
/**
* <p>Model object to provide the following to "use Trezor wizard":</p>
* <ul>
* <li>Storage of PIN entered</li>
* <li>State transition management</li>
* <li>Handling of various Trezor requests</li>
* </ul>
*
* @since 0.0.1
*
*/
public class UseTrezorWizardModel extends AbstractHardwareWalletWizardModel<UseTrezorState> {
private static final Logger log = LoggerFactory.getLogger(UseTrezorWizardModel.class);
/**
* The current selection option as a state
*/
private UseTrezorState currentSelection = UseTrezorState.BUY_TREZOR;
/**
* The features of the attached Trezor
*/
Optional<Features> featuresOptional = Optional.absent();
/**
* The "enter pin" panel view
*/
private UseTrezorEnterPinPanelView enterPinPanelView;
private UseTrezorRequestCipherKeyPanelView requestCipherKeyPanelView;
private UseTrezorReportPanelView reportPanelView;
public UseTrezorWizardModel(UseTrezorState useTrezorState) {
super(useTrezorState);
}
@Override
public String getPanelName() {
return state.name();
}
public UseTrezorEnterPinPanelView getEnterPinPanelView() {
return enterPinPanelView;
}
public void setEnterPinPanelView(UseTrezorEnterPinPanelView enterPinPanelView) {
this.enterPinPanelView = enterPinPanelView;
}
public void setRequestCipherKeyPanelView(UseTrezorRequestCipherKeyPanelView requestCipherKeyPanelView) {
this.requestCipherKeyPanelView = requestCipherKeyPanelView;
}
@Override
public void showNext() {
log.debug("Current selection : {}", getCurrentSelection());
switch (state) {
case SELECT_TREZOR_ACTION:
switch (getCurrentSelection()) {
case SELECT_TREZOR_ACTION:
break;
case USE_TREZOR_WALLET:
//state = UseTrezorState.REQUEST_CIPHER_KEY;
break;
case BUY_TREZOR:
state = UseTrezorState.BUY_TREZOR;
break;
case VERIFY_TREZOR:
state = UseTrezorState.VERIFY_TREZOR;
break;
case REQUEST_WIPE_TREZOR:
state = UseTrezorState.REQUEST_WIPE_TREZOR;
break;
default:
throw new IllegalStateException("Cannot showNext with a state of SELECT_TREZOR_ACTION and a selection of " + getCurrentSelection());
}
break;
case BUY_TREZOR:
state = UseTrezorState.USE_TREZOR_REPORT_PANEL;
break;
case VERIFY_TREZOR:
state = UseTrezorState.USE_TREZOR_REPORT_PANEL;
break;
case REQUEST_WIPE_TREZOR:
// Trezor must have failed and user is clicking through
state = UseTrezorState.USE_TREZOR_REPORT_PANEL;
break;
case CONFIRM_WIPE_TREZOR:
state = UseTrezorState.USE_TREZOR_REPORT_PANEL;
break;
case ENTER_PIN:
break;
case NO_PIN_REQUIRED:
break;
default:
throw new IllegalStateException("Cannot showNext with a state of " + state);
}
}
@Override
public void showPrevious() {
switch (state) {
case BUY_TREZOR:
state = UseTrezorState.SELECT_TREZOR_ACTION;
break;
default:
throw new IllegalStateException("Unknown state: " + state.name());
}
}
@Override
public void showPINEntry(HardwareWalletEvent event) {
// Device is PIN protected
switch (state) {
default:
throw new IllegalStateException("Unknown state: " + state.name());
}
}
@Override
public void showButtonPress(HardwareWalletEvent event) {
log.debug("Received hardwareWalletEvent {}", event);
ButtonRequest buttonRequest = (ButtonRequest) event.getMessage().get();
switch (state) {
case ENTER_PIN:
case NO_PIN_REQUIRED:
// Should be catered for by finish
break;
case REQUEST_WIPE_TREZOR:
switch (buttonRequest.getButtonRequestType()) {
case WIPE_DEVICE:
// Device requires confirmation to wipe
state = UseTrezorState.CONFIRM_WIPE_TREZOR;
break;
default:
throw new IllegalStateException("Unexpected button: " + buttonRequest.getButtonRequestType().name());
}
break;
case VERIFY_TREZOR:
// Should be catered for by finish on Verify Trezor panel
case USE_TREZOR_REPORT_PANEL:
// Should be catered for by finish on Trezor report panel
break;
default:
throw new IllegalStateException("Unknown state: " + state.name());
}
}
@Override
public void showOperationSucceeded(HardwareWalletEvent event) {
switch (state) {
case CONFIRM_WIPE_TREZOR:
// Indicate a successful wipe
state=UseTrezorState.USE_TREZOR_REPORT_PANEL;
setReportMessageKey(MessageKey.TREZOR_WIPE_DEVICE_SUCCESS);
setReportMessageStatus(true);
break;
default:
// TODO Fill in the other states and provide success feedback
log.info(
"Message:'Operation succeeded'\n{}",
event.getMessage().get()
);
}
}
@Override
public void showOperationFailed(HardwareWalletEvent event) {
// In all cases move to the report panel with a failure message
state=UseTrezorState.USE_TREZOR_REPORT_PANEL;
setReportMessageKey(MessageKey.TREZOR_WIPE_DEVICE_FAILURE);
setReportMessageStatus(false);
}
public UseTrezorState getCurrentSelection() {
return currentSelection;
}
public void setCurrentSelection(UseTrezorState currentSelection) {
this.currentSelection = currentSelection;
}
public Optional<Features> getFeaturesOptional() {
return featuresOptional;
}
/**
* <p>Request the Trezor features</p>
*/
public void requestFeatures() {
// Start the features request
ListenableFuture future = hardwareWalletRequestService.submit(
new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Optional<HardwareWalletService> hardwareWalletServiceOptional = CoreServices.getOrCreateHardwareWalletService();
if (hardwareWalletServiceOptional.isPresent()) {
HardwareWalletService hardwareWalletService = hardwareWalletServiceOptional.get();
featuresOptional = hardwareWalletService.getContext().getFeatures();
log.debug("Features : {}", featuresOptional);
} else {
log.error("No hardware wallet service");
}
return true;
}
});
Futures.addCallback(
future, new FutureCallback() {
@Override
public void onSuccess(@Nullable Object result) {
// We now have the features so throw a ComponentChangedEvent for the UI to update
ViewEvents.fireComponentChangedEvent(UseTrezorState.VERIFY_TREZOR.name(), Optional.absent());
}
@Override
public void onFailure(Throwable t) {
// Have a failure - add failure text to the text area
}
});
}
/**
* <p>Wipe the Trezor device</p>
*/
public void requestWipeDevice() {
// Start the wipe Trezor
ListenableFuture future = hardwareWalletRequestService.submit(
new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Optional<HardwareWalletService> hardwareWalletServiceOptional = CoreServices.getOrCreateHardwareWalletService();
if (hardwareWalletServiceOptional.isPresent()) {
HardwareWalletService hardwareWalletService = hardwareWalletServiceOptional.get();
if (hardwareWalletService.isWalletPresent()) {
hardwareWalletService.wipeDevice();
log.debug("Wipe device request has been performed");
} else {
log.debug("No wallet present so no need to wipe the device");
}
} else {
log.error("No hardware wallet service");
}
return true;
}
});
Futures.addCallback(
future, new FutureCallback() {
@Override
public void onSuccess(@Nullable Object result) {
// We now wiped the device so throw a ComponentChangedEvent for the UI to update
ViewEvents.fireComponentChangedEvent(UseTrezorState.REQUEST_WIPE_TREZOR.name(), Optional.absent());
setReportMessageKey(MessageKey.TREZOR_WIPE_DEVICE_SUCCESS);
setReportMessageStatus(true);
}
@Override
public void onFailure(Throwable t) {
// Have a failure
log.error("Unexpected failure during request wipe", t);
setReportMessageKey(MessageKey.TREZOR_WIPE_DEVICE_FAILURE);
setReportMessageStatus(false);
}
});
}
/**
* @param pinPositions The PIN positions providing a level of obfuscation to protect the PIN
*/
public void requestPinCheck(final String pinPositions) {
ListenableFuture<Boolean> pinCheckFuture = hardwareWalletRequestService.submit(
new Callable<Boolean>() {
@Override
public Boolean call() {
log.debug("Performing a PIN check");
// Talk to the Trezor and get it to check the PIN
// This call to the Trezor will (sometime later) fire a
// HardwareWalletEvent containing the encrypted text (or a PIN failure)
// Expect a SHOW_OPERATION_SUCCEEDED or SHOW_OPERATION_FAILED
Optional<HardwareWalletService> hardwareWalletService = CoreServices.getOrCreateHardwareWalletService();
hardwareWalletService.get().providePIN(pinPositions);
// Must have successfully send the message to be here
return true;
}
});
Futures.addCallback(
pinCheckFuture, new FutureCallback<Boolean>() {
@Override
public void onSuccess(Boolean result) {
// Do nothing - message was successfully relayed to the device
}
@Override
public void onFailure(Throwable t) {
// Device failed to receive the message
getEnterPinPanelView().setPinStatus(false, true);
// Should not have seen an error
ExceptionHandler.handleThrowable(t);
}
}
);
}
}
| SwingUtilities#invokeLater rework
| mbhd-swing/src/main/java/org/multibit/hd/ui/views/wizards/use_trezor/UseTrezorWizardModel.java | SwingUtilities#invokeLater rework | <ide><path>bhd-swing/src/main/java/org/multibit/hd/ui/views/wizards/use_trezor/UseTrezorWizardModel.java
<ide> import org.slf4j.LoggerFactory;
<ide>
<ide> import javax.annotation.Nullable;
<add>import javax.swing.*;
<ide> import java.util.concurrent.Callable;
<ide>
<ide> /**
<ide> public void onSuccess(@Nullable Object result) {
<ide>
<ide> // We now have the features so throw a ComponentChangedEvent for the UI to update
<del> ViewEvents.fireComponentChangedEvent(UseTrezorState.VERIFY_TREZOR.name(), Optional.absent());
<add> SwingUtilities.invokeLater(new Runnable() {
<add> @Override
<add> public void run() {
<add> ViewEvents.fireComponentChangedEvent(UseTrezorState.VERIFY_TREZOR.name(), Optional.absent());
<add> }
<add> });
<ide>
<ide> }
<ide>
<ide> public void onSuccess(@Nullable Object result) {
<ide>
<ide> // We now wiped the device so throw a ComponentChangedEvent for the UI to update
<del> ViewEvents.fireComponentChangedEvent(UseTrezorState.REQUEST_WIPE_TREZOR.name(), Optional.absent());
<add> SwingUtilities.invokeLater(new Runnable() {
<add> @Override
<add> public void run() {
<add> ViewEvents.fireComponentChangedEvent(UseTrezorState.REQUEST_WIPE_TREZOR.name(), Optional.absent());
<add> }
<add> });
<ide>
<ide> setReportMessageKey(MessageKey.TREZOR_WIPE_DEVICE_SUCCESS);
<ide> setReportMessageStatus(true); |
|
Java | mit | ca8c3b06de41cb2d918ab97b2d064b78fdb6bac6 | 0 | MinecraftDevin/Rustic_1.7.10_Public | package com.bigbaddevil7.rustic;
import cpw.mods.fml.common.Mod;
/**
* Created by bigbaddevil7 on 9/27/2014.
*/
@Mod(modid="Rustic", name = "Rustic", version = "1.7.2-0.0.1") //Tells Forge that this is a mod
public class Rustic {
@Mod.EventHandler
public void preInit(){
//TODO
}
}
| src/main/java/com/bigbaddevil7/rustic/Rustic.java | package com.bigbaddevil7.rustic;
import cpw.mods.fml.common.Mod;
/**
* Created by bigbaddevil7 on 9/27/2014.
*/
@Mod(modid="Rustic", name = "Rustic", version = "1.7.2-0.0.1") //Tells Forge that this is a mod
public class Rustic {
}
| added preInit
| src/main/java/com/bigbaddevil7/rustic/Rustic.java | added preInit | <ide><path>rc/main/java/com/bigbaddevil7/rustic/Rustic.java
<ide>
<ide> @Mod(modid="Rustic", name = "Rustic", version = "1.7.2-0.0.1") //Tells Forge that this is a mod
<ide> public class Rustic {
<del>
<add> @Mod.EventHandler
<add> public void preInit(){
<add> //TODO
<add> }
<ide> } |
|
Java | apache-2.0 | a80efc959d4835b3d47035c434be8d1e92804221 | 0 | rcordovano/autopsy,esaunders/autopsy,esaunders/autopsy,wschaeferB/autopsy,millmanorama/autopsy,esaunders/autopsy,rcordovano/autopsy,esaunders/autopsy,rcordovano/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,millmanorama/autopsy,millmanorama/autopsy,esaunders/autopsy,wschaeferB/autopsy,rcordovano/autopsy,rcordovano/autopsy,rcordovano/autopsy,millmanorama/autopsy | /*
* Autopsy Forensic Browser
*
* Copyright 2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.commonfilesearch;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttributeInstance;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttributeInstance.Type;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationCase;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationDataSource;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDb;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDbException;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDbUtil;
import org.sleuthkit.autopsy.centralrepository.datamodel.InstanceTableCallback;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.datamodel.TskData;
import org.sleuthkit.datamodel.HashUtility;
/**
* Used to process and return CorrelationCase md5s from the EamDB for
* CommonFilesSearch.
*/
final class InterCaseSearchResultsProcessor {
private Map<Long, String> dataSources;
/**
* The CorrelationAttributeInstance.Type this Processor will query on
*/
private final Type correlationType;
private static final Logger LOGGER = Logger.getLogger(CommonAttributePanel.class.getName());
/**
* The initial CorrelationAttributeInstance ids lookup query.
*/
private final String interCaseWhereClause;
/**
* The single CorrelationAttributeInstance object retrieval query
*/
private final String singleInterCaseWhereClause;
/**
* Used in the InterCaseCommonAttributeSearchers to find common attribute
* instances and generate nodes at the UI level.
*
* @param dataSources the cases to filter and correlate on
* @param theType the type of CR data to search
*/
InterCaseSearchResultsProcessor(Map<Long, String> dataSources, CorrelationAttributeInstance.Type theType) {
this.correlationType = theType;
this.dataSources = dataSources;
interCaseWhereClause = getInterCaseWhereClause();
singleInterCaseWhereClause = getSingleInterCaseWhereClause();
}
private String getInterCaseWhereClause() {
String tableName = EamDbUtil.correlationTypeToInstanceTableName(correlationType);
StringBuilder sqlString = new StringBuilder(6);
sqlString.append("value IN (SELECT value FROM ")
.append(tableName)
.append(" WHERE value IN (SELECT value FROM ")
.append(tableName)
.append(" WHERE case_id=%s AND (known_status !=%s OR known_status IS NULL) GROUP BY value)")
.append(" GROUP BY value HAVING COUNT(DISTINCT case_id) > 1) ORDER BY value");
return sqlString.toString();
}
private String getSingleInterCaseWhereClause() {
String tableName = EamDbUtil.correlationTypeToInstanceTableName(correlationType);
StringBuilder sqlString = new StringBuilder(6);
sqlString.append("value IN (SELECT value FROM ")
.append(tableName)
.append(" WHERE value IN (SELECT value FROM ")
.append(tableName)
.append(" WHERE case_id=%s AND (known_status !=%s OR known_status IS NULL) GROUP BY value)")
.append(" AND (case_id=%s OR case_id=%s) GROUP BY value HAVING COUNT(DISTINCT case_id) > 1) ORDER BY value");
return sqlString.toString();
}
/**
* Used in the CentralRepoCommonAttributeInstance to find common attribute
* instances and generate nodes at the UI level.
*
* @param theType the type of CR data to search
*/
InterCaseSearchResultsProcessor(CorrelationAttributeInstance.Type theType) {
this.correlationType = theType;
interCaseWhereClause = getInterCaseWhereClause();
singleInterCaseWhereClause = getSingleInterCaseWhereClause();
}
/**
* Finds a single CorrelationAttribute given an id.
*
* @param attrbuteId Row of CorrelationAttribute to retrieve from the EamDb
* @return CorrelationAttribute object representation of retrieved match
*/
CorrelationAttributeInstance findSingleCorrelationAttribute(int attrbuteId) {
try {
InterCaseCommonAttributeRowCallback instancetableCallback = new InterCaseCommonAttributeRowCallback();
EamDb DbManager = EamDb.getInstance();
DbManager.processInstanceTableWhere(correlationType, String.format("id = %s", attrbuteId), instancetableCallback);
return instancetableCallback.getCorrelationAttribute();
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error accessing EamDb processing InstanceTable row.", ex);
}
return null;
}
/**
* Given the current case, fins all intercase common files from the EamDb
* and builds maps of obj id to md5 and case.
*
* @param currentCase The current TSK Case.
*/
Map<Integer, List<CommonAttributeValue>> findInterCaseCommonAttributeValues(Case currentCase) {
try {
InterCaseCommonAttributesCallback instancetableCallback = new InterCaseCommonAttributesCallback();
EamDb DbManager = EamDb.getInstance();
int caseId = DbManager.getCase(currentCase).getID();
DbManager.processInstanceTableWhere(correlationType, String.format(interCaseWhereClause, caseId,
TskData.FileKnown.KNOWN.getFileKnownValue()),
instancetableCallback);
return instancetableCallback.getInstanceCollatedCommonFiles();
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error accessing EamDb processing CaseInstancesTable.", ex);
}
return new HashMap<>();
}
/**
* Given the current case, and a specific case of interest, finds common
* files which exist between cases from the EamDb. Builds maps of obj id to
* md5 and case.
*
* @param currentCase The current TSK Case.
* @param singleCase The case of interest. Matches must exist in this case.
*/
Map<Integer, List<CommonAttributeValue>> findSingleInterCaseCommonAttributeValues(Case currentCase, CorrelationCase singleCase) {
try {
InterCaseCommonAttributesCallback instancetableCallback = new InterCaseCommonAttributesCallback();
EamDb DbManager = EamDb.getInstance();
int caseId = DbManager.getCase(currentCase).getID();
int targetCaseId = singleCase.getID();
DbManager.processInstanceTableWhere(correlationType, String.format(singleInterCaseWhereClause, caseId,
TskData.FileKnown.KNOWN.getFileKnownValue(), caseId, targetCaseId), instancetableCallback);
return instancetableCallback.getInstanceCollatedCommonFiles();
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error accessing EamDb processing CaseInstancesTable.", ex);
}
return new HashMap<>();
}
/**
* Callback to use with findInterCaseCommonAttributeValues which generates a
* list of md5s for common files search
*/
private class InterCaseCommonAttributesCallback implements InstanceTableCallback {
final Map<Integer, List<CommonAttributeValue>> instanceCollatedCommonFiles = new HashMap<>();
private CommonAttributeValue commonAttributeValue = null;
private String previousRowMd5 = "";
@Override
public void process(ResultSet resultSet) {
try {
while (resultSet.next()) {
int resultId = InstanceTableCallback.getId(resultSet);
String corValue = InstanceTableCallback.getValue(resultSet);
if (previousRowMd5.isEmpty()) {
previousRowMd5 = corValue;
}
if (corValue == null || HashUtility.isNoDataMd5(corValue)) {
continue;
}
countAndAddCommonAttributes(corValue, resultId);
}
//Add the final instances
ArrayList<CommonAttributeValue> value = new ArrayList<>();
value.add(commonAttributeValue);
instanceCollatedCommonFiles.put(commonAttributeValue.getInstanceCount(), value);
} catch (SQLException ex) {
LOGGER.log(Level.WARNING, "Error getting artifact instances from database.", ex); // NON-NLS
}
}
private void countAndAddCommonAttributes(String corValue, int resultId) {
if (commonAttributeValue == null) {
commonAttributeValue = new CommonAttributeValue(corValue);
}
if (!corValue.equals(previousRowMd5)) {
int size = commonAttributeValue.getInstanceCount();
if (instanceCollatedCommonFiles.containsKey(size)) {
instanceCollatedCommonFiles.get(size).add(commonAttributeValue);
} else {
ArrayList<CommonAttributeValue> value = new ArrayList<>();
value.add(commonAttributeValue);
instanceCollatedCommonFiles.put(size, value);
}
commonAttributeValue = new CommonAttributeValue(corValue);
previousRowMd5 = corValue;
}
// we don't *have* all the information for the rows in the CR,
// so we need to consult the present case via the SleuthkitCase object
// Later, when the FileInstanceNode is built. Therefore, build node generators for now.
AbstractCommonAttributeInstance searchResult = new CentralRepoCommonAttributeInstance(resultId, InterCaseSearchResultsProcessor.this.dataSources, correlationType);
commonAttributeValue.addInstance(searchResult);
}
Map<Integer, List<CommonAttributeValue>> getInstanceCollatedCommonFiles() {
return Collections.unmodifiableMap(instanceCollatedCommonFiles);
}
}
/**
* Callback to use with findSingleCorrelationAttribute which retrieves a
* single CorrelationAttribute from the EamDb.
*/
private class InterCaseCommonAttributeRowCallback implements InstanceTableCallback {
CorrelationAttributeInstance correlationAttributeInstance = null;
@Override
public void process(ResultSet resultSet) {
try {
EamDb DbManager = EamDb.getInstance();
while (resultSet.next()) {
CorrelationCase correlationCase = DbManager.getCaseById(InstanceTableCallback.getCaseId(resultSet));
CorrelationDataSource dataSource = DbManager.getDataSourceById(correlationCase, InstanceTableCallback.getDataSourceId(resultSet));
correlationAttributeInstance = DbManager.getCorrelationAttributeInstance(correlationType,
correlationCase,
dataSource,
InstanceTableCallback.getValue(resultSet),
InstanceTableCallback.getFilePath(resultSet));
}
} catch (SQLException | EamDbException ex) {
LOGGER.log(Level.WARNING, "Error getting single correlation artifact instance from database.", ex); // NON-NLS
}
}
CorrelationAttributeInstance getCorrelationAttribute() {
return correlationAttributeInstance;
}
}
}
| Core/src/org/sleuthkit/autopsy/commonfilesearch/InterCaseSearchResultsProcessor.java | /*
* Autopsy Forensic Browser
*
* Copyright 2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.commonfilesearch;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttributeInstance;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttributeInstance.Type;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationCase;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationDataSource;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDb;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDbException;
import org.sleuthkit.autopsy.centralrepository.datamodel.EamDbUtil;
import org.sleuthkit.autopsy.centralrepository.datamodel.InstanceTableCallback;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.datamodel.TskData;
import org.sleuthkit.datamodel.HashUtility;
/**
* Used to process and return CorrelationCase md5s from the EamDB for
* CommonFilesSearch.
*/
final class InterCaseSearchResultsProcessor {
private Map<Long, String> dataSources;
/**
* The CorrelationAttributeInstance.Type this Processor will query on
*/
private final Type correlationType;
private static final Logger LOGGER = Logger.getLogger(CommonAttributePanel.class.getName());
/**
* The initial CorrelationAttributeInstance ids lookup query.
*/
private final String interCaseWhereClause;
/**
* The single CorrelationAttributeInstance object retrieval query
*/
private final String singleInterCaseWhereClause;
/**
* Used in the InterCaseCommonAttributeSearchers to find common attribute
* instances and generate nodes at the UI level.
*
* @param dataSources the cases to filter and correlate on
* @param theType the type of CR data to search
*/
InterCaseSearchResultsProcessor(Map<Long, String> dataSources, CorrelationAttributeInstance.Type theType) {
this.correlationType = theType;
this.dataSources = dataSources;
interCaseWhereClause = getInterCaseWhereClause();
singleInterCaseWhereClause = getSingleInterCaseWhereClause();
}
private String getInterCaseWhereClause() {
String tableName = EamDbUtil.correlationTypeToInstanceTableName(correlationType);
StringBuilder sqlString = new StringBuilder(6);
sqlString.append("value IN (SELECT value FROM ")
.append(tableName)
.append(" WHERE value IN (SELECT value FROM ")
.append(tableName)
.append(" WHERE case_id=%s AND (known_status !=%s OR known_status IS NULL) GROUP BY value)")
.append(" GROUP BY value HAVING COUNT(DISTINCT case_id) > 1) ORDER BY value");
return sqlString.toString();
}
private String getSingleInterCaseWhereClause() {
String tableName = EamDbUtil.correlationTypeToInstanceTableName(correlationType);
StringBuilder sqlString = new StringBuilder(6);
sqlString.append("value IN (SELECT value FROM ")
.append(tableName)
.append("WHERE value IN (SELECT value FROM ")
.append(tableName)
.append(" WHERE case_id=%s AND (known_status !=%s OR known_status IS NULL) GROUP BY value)")
.append(" AND (case_id=%s OR case_id=%s) GROUP BY value HAVING COUNT(DISTINCT case_id) > 1) ORDER BY value");
return sqlString.toString();
}
/**
* Used in the CentralRepoCommonAttributeInstance to find common attribute
* instances and generate nodes at the UI level.
*
* @param theType the type of CR data to search
*/
InterCaseSearchResultsProcessor(CorrelationAttributeInstance.Type theType) {
this.correlationType = theType;
interCaseWhereClause = getInterCaseWhereClause();
singleInterCaseWhereClause = getSingleInterCaseWhereClause();
}
/**
* Finds a single CorrelationAttribute given an id.
*
* @param attrbuteId Row of CorrelationAttribute to retrieve from the EamDb
* @return CorrelationAttribute object representation of retrieved match
*/
CorrelationAttributeInstance findSingleCorrelationAttribute(int attrbuteId) {
try {
InterCaseCommonAttributeRowCallback instancetableCallback = new InterCaseCommonAttributeRowCallback();
EamDb DbManager = EamDb.getInstance();
DbManager.processInstanceTableWhere(correlationType, String.format("id = %s", attrbuteId), instancetableCallback);
return instancetableCallback.getCorrelationAttribute();
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error accessing EamDb processing InstanceTable row.", ex);
}
return null;
}
/**
* Given the current case, fins all intercase common files from the EamDb
* and builds maps of obj id to md5 and case.
*
* @param currentCase The current TSK Case.
*/
Map<Integer, List<CommonAttributeValue>> findInterCaseCommonAttributeValues(Case currentCase) {
try {
InterCaseCommonAttributesCallback instancetableCallback = new InterCaseCommonAttributesCallback();
EamDb DbManager = EamDb.getInstance();
int caseId = DbManager.getCase(currentCase).getID();
DbManager.processInstanceTableWhere(correlationType, String.format(interCaseWhereClause, caseId,
TskData.FileKnown.KNOWN.getFileKnownValue()),
instancetableCallback);
return instancetableCallback.getInstanceCollatedCommonFiles();
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error accessing EamDb processing CaseInstancesTable.", ex);
}
return new HashMap<>();
}
/**
* Given the current case, and a specific case of interest, finds common
* files which exist between cases from the EamDb. Builds maps of obj id to
* md5 and case.
*
* @param currentCase The current TSK Case.
* @param singleCase The case of interest. Matches must exist in this case.
*/
Map<Integer, List<CommonAttributeValue>> findSingleInterCaseCommonAttributeValues(Case currentCase, CorrelationCase singleCase) {
try {
InterCaseCommonAttributesCallback instancetableCallback = new InterCaseCommonAttributesCallback();
EamDb DbManager = EamDb.getInstance();
int caseId = DbManager.getCase(currentCase).getID();
int targetCaseId = singleCase.getID();
DbManager.processInstanceTableWhere(correlationType, String.format(singleInterCaseWhereClause, caseId,
TskData.FileKnown.KNOWN.getFileKnownValue(), caseId, targetCaseId), instancetableCallback);
return instancetableCallback.getInstanceCollatedCommonFiles();
} catch (EamDbException ex) {
LOGGER.log(Level.SEVERE, "Error accessing EamDb processing CaseInstancesTable.", ex);
}
return new HashMap<>();
}
/**
* Callback to use with findInterCaseCommonAttributeValues which generates a
* list of md5s for common files search
*/
private class InterCaseCommonAttributesCallback implements InstanceTableCallback {
final Map<Integer, List<CommonAttributeValue>> instanceCollatedCommonFiles = new HashMap<>();
private CommonAttributeValue commonAttributeValue = null;
private String previousRowMd5 = "";
@Override
public void process(ResultSet resultSet) {
try {
while (resultSet.next()) {
int resultId = InstanceTableCallback.getId(resultSet);
String corValue = InstanceTableCallback.getValue(resultSet);
if (previousRowMd5.isEmpty()) {
previousRowMd5 = corValue;
}
if (corValue == null || HashUtility.isNoDataMd5(corValue)) {
continue;
}
countAndAddCommonAttributes(corValue, resultId);
}
//Add the final instances
ArrayList<CommonAttributeValue> value = new ArrayList<>();
value.add(commonAttributeValue);
instanceCollatedCommonFiles.put(commonAttributeValue.getInstanceCount(), value);
} catch (SQLException ex) {
LOGGER.log(Level.WARNING, "Error getting artifact instances from database.", ex); // NON-NLS
}
}
private void countAndAddCommonAttributes(String corValue, int resultId) {
if (commonAttributeValue == null) {
commonAttributeValue = new CommonAttributeValue(corValue);
}
if (!corValue.equals(previousRowMd5)) {
int size = commonAttributeValue.getInstanceCount();
if (instanceCollatedCommonFiles.containsKey(size)) {
instanceCollatedCommonFiles.get(size).add(commonAttributeValue);
} else {
ArrayList<CommonAttributeValue> value = new ArrayList<>();
value.add(commonAttributeValue);
instanceCollatedCommonFiles.put(size, value);
}
commonAttributeValue = new CommonAttributeValue(corValue);
previousRowMd5 = corValue;
}
// we don't *have* all the information for the rows in the CR,
// so we need to consult the present case via the SleuthkitCase object
// Later, when the FileInstanceNode is built. Therefore, build node generators for now.
AbstractCommonAttributeInstance searchResult = new CentralRepoCommonAttributeInstance(resultId, InterCaseSearchResultsProcessor.this.dataSources, correlationType);
commonAttributeValue.addInstance(searchResult);
}
Map<Integer, List<CommonAttributeValue>> getInstanceCollatedCommonFiles() {
return Collections.unmodifiableMap(instanceCollatedCommonFiles);
}
}
/**
* Callback to use with findSingleCorrelationAttribute which retrieves a
* single CorrelationAttribute from the EamDb.
*/
private class InterCaseCommonAttributeRowCallback implements InstanceTableCallback {
CorrelationAttributeInstance correlationAttributeInstance = null;
@Override
public void process(ResultSet resultSet) {
try {
EamDb DbManager = EamDb.getInstance();
while (resultSet.next()) {
CorrelationCase correlationCase = DbManager.getCaseById(InstanceTableCallback.getCaseId(resultSet));
CorrelationDataSource dataSource = DbManager.getDataSourceById(correlationCase, InstanceTableCallback.getDataSourceId(resultSet));
correlationAttributeInstance = DbManager.getCorrelationAttributeInstance(correlationType,
correlationCase,
dataSource,
InstanceTableCallback.getValue(resultSet),
InstanceTableCallback.getFilePath(resultSet));
}
} catch (SQLException | EamDbException ex) {
LOGGER.log(Level.WARNING, "Error getting single correlation artifact instance from database.", ex); // NON-NLS
}
}
CorrelationAttributeInstance getCorrelationAttribute() {
return correlationAttributeInstance;
}
}
}
| fix spacing issue in query after switching to string builder.
| Core/src/org/sleuthkit/autopsy/commonfilesearch/InterCaseSearchResultsProcessor.java | fix spacing issue in query after switching to string builder. | <ide><path>ore/src/org/sleuthkit/autopsy/commonfilesearch/InterCaseSearchResultsProcessor.java
<ide> StringBuilder sqlString = new StringBuilder(6);
<ide> sqlString.append("value IN (SELECT value FROM ")
<ide> .append(tableName)
<del> .append("WHERE value IN (SELECT value FROM ")
<add> .append(" WHERE value IN (SELECT value FROM ")
<ide> .append(tableName)
<ide> .append(" WHERE case_id=%s AND (known_status !=%s OR known_status IS NULL) GROUP BY value)")
<ide> .append(" AND (case_id=%s OR case_id=%s) GROUP BY value HAVING COUNT(DISTINCT case_id) > 1) ORDER BY value"); |
|
Java | apache-2.0 | 16cdca614389c539629de211cadd6eba8f04ae71 | 0 | kurtharriger/spring-osgi | /*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.osgi.test;
import junit.framework.TestCase;
import junit.framework.TestResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.osgi.test.platform.EquinoxPlatform;
import org.springframework.osgi.test.platform.FelixPlatform;
import org.springframework.osgi.test.platform.KnopflerfishPlatform;
import org.springframework.osgi.test.platform.OsgiPlatform;
import org.springframework.util.Assert;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
/**
*
* Base teste for OSGi environments. It will start the OSGi platform, install
* the given bundles and then delegate the execution to a test copy which
* executes inside OSGi.
*
* @author Costin Leau
*
*/
public abstract class AbstractOsgiTests extends TestCase implements OsgiJUnitTest {
// JVM shutdown hook
private static Thread shutdownHook;
// the OSGi fixture
private static OsgiPlatform osgiPlatform;
private static BundleContext context;
private static Bundle[] bundles;
// JUnit Service
private static Object service;
// JUnitService trigger
private static Method serviceTrigger;
private ObjectInputStream inputStream;
private ObjectOutputStream outputStream;
// the test results used by the triggering test runner
private TestResult originalResult;
// The OSGi BundleContext
private BundleContext bundleContext;
private static final String ACTIVATOR_REFERENCE = "org.springframework.osgi.test.JUnitTestActivator";
public static final String EQUINOX_PLATFORM = "equinox";
public static final String KNOPFLERFISH_PLATFORM = "knopflerfish";
public static final String FELIX_PLATFORM = "felix";
public static final String OSGI_FRAMEWORK_SELECTOR = "org.springframework.osgi.test.framework";
protected final Log log = LogFactory.getLog(getClass());
private static String getSpringOSGiTestBundleUrl() {
return localMavenArtifact("org.springframework.osgi.test", "1.0-SNAPSHOT");
}
private static String getSpringCoreBundleUrl() {
return localMavenArtifact("spring-core", "2.1-SNAPSHOT");
}
private static String getLog4jLibUrl() {
return localMavenArtifact("log4j.osgi", "1.2.13-SNAPSHOT");
}
private static String getCommonsLoggingLibUrl() {
return localMavenArtifact("commons-logging.osgi", "1.1-SNAPSHOT");
}
private static String getJUnitLibUrl() {
return localMavenArtifact("junit.osgi", "3.8.1-SNAPSHOT");
}
/**
* Answer the url string of the indicated bundle in the local Maven repository
*
* @param groupId - the groupId of the organization supplying the bundle
* @param artifact - the artifact id of the bundle
* @param version - the version of the bundle
* @return the String representing the URL location of this bundle
*/
public static String localMavenBundle(String groupId, String artifact, String version) {
File userHome = new File(System.getProperty("user.home"));
File repositoryHome = new File(userHome, ".m2/repository");
String location = groupId.replace('.', '/');
location += '/';
location += artifact;
location += '/';
location += version;
location += '/';
location += artifact;
location += '-';
location += version;
location += ".jar";
return "file:" + new File(repositoryHome, location).getAbsolutePath();
}
public static String localMavenArtifact(String artifactId, String version) {
try {
File found = new MavenPackagedArtifactFinder(artifactId,version).findPackagedArtifact(new File("."));
return found.toURL().toExternalForm();
} catch (IOException ioEx) {
throw new IllegalStateException(
"Artifact " + artifactId + "-" + version + ".jar" +
" could not be found",ioEx);
}
}
/**
* Bundles that should be installed before the test execution.
*
* @return the array of bundles to install
*/
protected String[] getBundleLocations() {
return new String[] {};
}
/**
* Mandator bundles (part of the test setup).
*
* @return the array of mandatory bundle names
*/
private String[] getMandatoryBundles() {
return new String[] {
getJUnitLibUrl(),
getLog4jLibUrl(),
getCommonsLoggingLibUrl(),
getSpringCoreBundleUrl(),
getSpringOSGiTestBundleUrl() };
}
public AbstractOsgiTests() {
super();
};
public AbstractOsgiTests(String name) {
super(name);
}
/**
* OSGi platform creation. The chooseOsgiPlatform method is called to
* determine what platform will be used by the test - if an invalid/null
* String is returned, Equinox will be used by default.
*
* @return the OSGi platform
*/
protected OsgiPlatform createPlatform() {
String platformName = getPlatformName();
if (platformName != null) {
platformName = platformName.toLowerCase();
if (platformName.contains(FELIX_PLATFORM))
return new FelixPlatform();
if (platformName.contains(KNOPFLERFISH_PLATFORM))
return new KnopflerfishPlatform();
}
return new EquinoxPlatform();
}
/**
* Indicate what OSGi platform to be used by the test suite. By default, the
* 'spring.osgi.test.framework' is used.
*
* @return platform
*/
protected String getPlatformName() {
String systemProperty = System.getProperty(OSGI_FRAMEWORK_SELECTOR);
return (systemProperty == null ? EQUINOX_PLATFORM : systemProperty);
}
protected ResourceLoader getResourceLoader() {
return new DefaultResourceLoader();
}
private Resource[] createResources(String[] bundles) {
Resource[] res = new Resource[bundles.length];
for (int i = 0; i < bundles.length; i++) {
res[i] = getResourceLoader().getResource(bundles[i]);
}
return res;
}
private void invokeOSGiTestExecution() throws Exception {
try {
serviceTrigger.invoke(service, null);
}
catch (InvocationTargetException ex) {
Throwable th = ex.getCause();
if (th instanceof Exception)
throw ((Exception) th);
else
throw ((Error) th);
}
}
/**
* Customized setUp - the OSGi platform will be started (if needed) and
* cached for the test suite execution.
*
* @see junit.framework.TestCase#setUp()
*/
protected final void setUp() throws Exception {
if (getName() == null)
throw new IllegalArgumentException("no test specified");
// write the testname into the System properties
System.getProperties().put(OsgiJUnitTest.OSGI_TEST, getClass().getName());
// create streams first to avoid deadlocks in setting up the stream on
// the OSGi side
setupStreams();
// start OSGi platform (the caching is done inside the method).
try {
startup();
} catch (Exception e) {
log.debug("Caught exception starting up", e);
throw e;
}
log.debug("writing test name to stream:" + getName());
// write test name to OSGi
outputStream.writeUTF(getName());
outputStream.flush();
// invoke OSGi test run
invokeOSGiTestExecution();
}
/**
* Start the OSGi platform and install/start the bundles (happens once for
* the all test runs)
*
* @throws Exception
*/
private void startup() throws Exception {
if (osgiPlatform == null) {
// make sure the platform is closed properly
registerShutdownHook();
log.info("initializing OSGi platform...");
osgiPlatform = createPlatform();
// start platform
osgiPlatform.start();
context = osgiPlatform.getBundleContext();
// merge bundles
String[] mandatoryBundles = getMandatoryBundles();
String[] optionalBundles = getBundleLocations();
String[] allBundles = new String[mandatoryBundles.length + optionalBundles.length];
System.arraycopy(mandatoryBundles, 0, allBundles, 0, mandatoryBundles.length);
System.arraycopy(optionalBundles, 0, allBundles, mandatoryBundles.length, optionalBundles.length);
// install bundles
Resource[] bundleResources = createResources(allBundles);
bundles = new Bundle[bundleResources.length];
for (int i = 0; i < bundleResources.length; i++) {
bundles[i] = installBundle(bundleResources[i]);
}
// start bundles
for (int i = 0; i < bundles.length; i++) {
log.debug("starting bundle " + bundles[i].getBundleId() + "[" + bundles[i].getSymbolicName() + "]");
try {
bundles[i].start();
}
catch (Throwable ex) {
log.warn("can't start bundle " + bundles[i].getBundleId() + "[" + bundles[i].getSymbolicName()
+ "]", ex);
}
}
postProcessBundleContext(context);
// get JUnit test service reference
// this is a loose reference - update it if the Activator class is
// changed.
ServiceReference reference = context.getServiceReference(ACTIVATOR_REFERENCE);
if (reference == null)
throw new IllegalStateException("no OSGi service reference found at " + ACTIVATOR_REFERENCE);
service = context.getService(reference);
if (service == null) {
throw new IllegalStateException("no service found for reference: " + reference);
}
serviceTrigger = service.getClass().getDeclaredMethod("executeTest", null);
if (serviceTrigger == null) {
throw new IllegalStateException("no executeTest() method found on: " + service.getClass());
}
onSetUpBeforeOsgi();
}
}
/**
* Callback for processing the bundle context after the bundles have been
* installed and started.
*
* @param context
*/
protected void postProcessBundleContext(BundleContext context) throws Exception {
}
/**
* Install an OSGi bundle from the given location.
*
* @param location
* @return
* @throws Exception
*/
private Bundle installBundle(Resource location) throws Exception {
Assert.notNull(context);
Assert.notNull(location);
log.debug("installing bundle from location " + location.getDescription());
return context.installBundle(location.getDescription(), location.getInputStream());
}
/**
* Hook for adding behavior after the OSGi platform has been started (is
* this really needed).
*
*/
protected void onSetUpBeforeOsgi() {
}
/**
* the setUp version for the OSGi environment.
*
* @throws Exception
*/
public void onSetUp() throws Exception {
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#tearDown()
*/
public final void tearDown() throws Exception {
cleanupStreams();
onTearDown();
}
public void onTearDown() throws Exception {
}
private void readTestResult() {
// finish stream creation (to avoid circullar dependencies)
createInStream();
log.debug("reading OSGi results for test [" + getName() + "]");
TestUtils.receiveTestResult(this.originalResult, this, inputStream);
log.debug("test[" + getName() + "]'s result read");
}
private void registerShutdownHook() {
if (shutdownHook == null) {
// No shutdown hook registered yet.
shutdownHook = new Thread() {
public void run() {
shutdownTest();
}
};
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
}
private void shutdownTest() {
cleanupStreams();
log.info("shutting down OSGi platform");
if (osgiPlatform != null) {
try {
osgiPlatform.stop();
}
catch (Exception ex) {
// swallow
log.warn("shutdown procedure threw exception " + ex);
}
osgiPlatform = null;
}
}
/**
* Setup the piped streams to get the results out from the OSGi world.
*
* @throws IOException
*/
private void setupStreams() throws IOException {
// 4K seems to be enough
byte[] inArray = new byte[1024 * 4];
byte[] outArray = new byte[1024 * 4];
Properties systemProps = System.getProperties();
// put information for OSGi
systemProps.put(OsgiJUnitTest.FOR_OSGI, inArray);
// get information from OSGi
systemProps.put(OsgiJUnitTest.FROM_OSGI, outArray);
// setup output stream to prevent blocking
outputStream = new ObjectOutputStream(new ConfigurableByteArrayOutputStream(inArray));
// flush header write away
outputStream.flush();
log.debug("OSGi streams setup");
}
private void cleanupStreams() {
try {
if (inputStream != null)
inputStream.close();
}
catch (IOException e) {
// swallow
}
try {
if (outputStream != null)
outputStream.close();
}
catch (IOException e) {
// swallow
}
}
private void createInStream() {
try {
byte[] inputSource = (byte[]) System.getProperties().get(OsgiJUnitTest.FROM_OSGI);
inputStream = new ObjectInputStream(new ByteArrayInputStream(inputSource));
}
catch (IOException ex) {
throw new RuntimeException("cannot open streams " + ex);
}
}
/**
* Change the normal test execution by adding result retrieval from OSGi
* realm.
*
* @see junit.framework.TestCase#run()
*/
public final void runTest() throws Throwable {
readTestResult();
}
/**
* Actual test execution (delegates to the TestCase implementation).
*
* @throws Throwable
*/
public final void osgiRunTest() throws Throwable {
super.runTest();
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#run(junit.framework.TestResult)
*/
public final void run(TestResult result) {
// get a hold of the test result
this.originalResult = result;
super.run(result);
}
public final void setBundleContext(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
public BundleContext getBundleContext() {
return bundleContext;
}
}
| spring-osgi-test-support/org.springframework.osgi.test/src/main/java/org/springframework/osgi/test/AbstractOsgiTests.java | /*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.osgi.test;
import junit.framework.TestCase;
import junit.framework.TestResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.osgi.test.platform.EquinoxPlatform;
import org.springframework.osgi.test.platform.FelixPlatform;
import org.springframework.osgi.test.platform.KnopflerfishPlatform;
import org.springframework.osgi.test.platform.OsgiPlatform;
import org.springframework.util.Assert;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
/**
*
* Base teste for OSGi environments. It will start the OSGi platform, install
* the given bundles and then delegate the execution to a test copy which
* executes inside OSGi.
*
* @author Costin Leau
*
*/
public abstract class AbstractOsgiTests extends TestCase implements OsgiJUnitTest {
// JVM shutdown hook
private static Thread shutdownHook;
// the OSGi fixture
private static OsgiPlatform osgiPlatform;
private static BundleContext context;
private static Bundle[] bundles;
// JUnit Service
private static Object service;
// JUnitService trigger
private static Method serviceTrigger;
private ObjectInputStream inputStream;
private ObjectOutputStream outputStream;
// the test results used by the triggering test runner
private TestResult originalResult;
// The OSGi BundleContext
private BundleContext bundleContext;
private static final String ACTIVATOR_REFERENCE = "org.springframework.osgi.test.JUnitTestActivator";
public static final String EQUINOX_PLATFORM = "equinox";
public static final String KNOPFLERFISH_PLATFORM = "knopflerfish";
public static final String FELIX_PLATFORM = "felix";
public static final String OSGI_FRAMEWORK_SELECTOR = "org.springframework.osgi.test.framework";
protected final Log log = LogFactory.getLog(getClass());
private static String getSpringOSGiTestBundleUrl() {
return localMavenArtifact("org.springframework.osgi.test", "1.0-SNAPSHOT");
}
private static String getSpringCoreBundleUrl() {
return localMavenArtifact("spring-core", "2.1-SNAPSHOT");
}
private static String getLog4jLibUrl() {
return localMavenArtifact("log4j.osgi", "1.2.13-SNAPSHOT");
}
private static String getCommonsLoggingLibUrl() {
return localMavenArtifact("commons-logging.osgi", "1.1-SNAPSHOT");
}
private static String getJUnitLibUrl() {
return localMavenArtifact("junit.osgi", "3.8.1-SNAPSHOT");
}
/**
* Answer the url string of the indicated bundle in the local Maven repository
*
* @param groupId - the groupId of the organization supplying the bundle
* @param artifact - the artifact id of the bundle
* @param version - the version of the bundle
* @return the String representing the URL location of this bundle
*/
public static String localMavenBundle(String groupId, String artifact, String version) {
File userHome = new File(System.getProperty("user.home"));
File repositoryHome = new File(userHome, ".m2/repository");
String location = groupId.replace('.', '/');
location += '/';
location += artifact;
location += '/';
location += version;
location += '/';
location += artifact;
location += '-';
location += version;
location += ".jar";
return "file:" + new File(repositoryHome, location).getAbsolutePath();
}
public static String localMavenArtifact(String artifactId, String version) {
try {
File found = new MavenPackagedArtifactFinder(artifactId,version).findPackagedArtifact(new File("."));
return found.toURL().toExternalForm();
} catch (IOException ioEx) {
throw new IllegalStateException(
"Artifact " + artifactId + "-" + version + ".jar" +
" could not be found",ioEx);
}
}
/**
* Bundles that should be installed before the test execution.
*
* @return the array of bundles to install
*/
protected String[] getBundlesLocations() {
return new String[] {};
}
/**
* Mandator bundles (part of the test setup).
*
* @return the array of mandatory bundle names
*/
private String[] getMandatoryBundles() {
return new String[] {
getJUnitLibUrl(),
getLog4jLibUrl(),
getCommonsLoggingLibUrl(),
getSpringCoreBundleUrl(),
getSpringOSGiTestBundleUrl() };
}
public AbstractOsgiTests() {
super();
};
public AbstractOsgiTests(String name) {
super(name);
}
/**
* OSGi platform creation. The chooseOsgiPlatform method is called to
* determine what platform will be used by the test - if an invalid/null
* String is returned, Equinox will be used by default.
*
* @return the OSGi platform
*/
protected OsgiPlatform createPlatform() {
String platformName = getPlatformName();
if (platformName != null) {
platformName = platformName.toLowerCase();
if (platformName.contains(FELIX_PLATFORM))
return new FelixPlatform();
if (platformName.contains(KNOPFLERFISH_PLATFORM))
return new KnopflerfishPlatform();
}
return new EquinoxPlatform();
}
/**
* Indicate what OSGi platform to be used by the test suite. By default, the
* 'spring.osgi.test.framework' is used.
*
* @return platform
*/
protected String getPlatformName() {
String systemProperty = System.getProperty(OSGI_FRAMEWORK_SELECTOR);
return (systemProperty == null ? EQUINOX_PLATFORM : systemProperty);
}
protected ResourceLoader getResourceLoader() {
return new DefaultResourceLoader();
}
private Resource[] createResources(String[] bundles) {
Resource[] res = new Resource[bundles.length];
for (int i = 0; i < bundles.length; i++) {
res[i] = getResourceLoader().getResource(bundles[i]);
}
return res;
}
private void invokeOSGiTestExecution() throws Exception {
try {
serviceTrigger.invoke(service, null);
}
catch (InvocationTargetException ex) {
Throwable th = ex.getCause();
if (th instanceof Exception)
throw ((Exception) th);
else
throw ((Error) th);
}
}
/**
* Customized setUp - the OSGi platform will be started (if needed) and
* cached for the test suite execution.
*
* @see junit.framework.TestCase#setUp()
*/
protected final void setUp() throws Exception {
if (getName() == null)
throw new IllegalArgumentException("no test specified");
// write the testname into the System properties
System.getProperties().put(OsgiJUnitTest.OSGI_TEST, getClass().getName());
// create streams first to avoid deadlocks in setting up the stream on
// the OSGi side
setupStreams();
// start OSGi platform (the caching is done inside the method).
try {
startup();
} catch (Exception e) {
log.debug("Caught exception starting up", e);
throw e;
}
log.debug("writing test name to stream:" + getName());
// write test name to OSGi
outputStream.writeUTF(getName());
outputStream.flush();
// invoke OSGi test run
invokeOSGiTestExecution();
}
/**
* Start the OSGi platform and install/start the bundles (happens once for
* the all test runs)
*
* @throws Exception
*/
private void startup() throws Exception {
if (osgiPlatform == null) {
// make sure the platform is closed properly
registerShutdownHook();
log.info("initializing OSGi platform...");
osgiPlatform = createPlatform();
// start platform
osgiPlatform.start();
context = osgiPlatform.getBundleContext();
// merge bundles
String[] mandatoryBundles = getMandatoryBundles();
String[] optionalBundles = getBundlesLocations();
String[] allBundles = new String[mandatoryBundles.length + optionalBundles.length];
System.arraycopy(mandatoryBundles, 0, allBundles, 0, mandatoryBundles.length);
System.arraycopy(optionalBundles, 0, allBundles, mandatoryBundles.length, optionalBundles.length);
// install bundles
Resource[] bundleResources = createResources(allBundles);
bundles = new Bundle[bundleResources.length];
for (int i = 0; i < bundleResources.length; i++) {
bundles[i] = installBundle(bundleResources[i]);
}
// start bundles
for (int i = 0; i < bundles.length; i++) {
log.debug("starting bundle " + bundles[i].getBundleId() + "[" + bundles[i].getSymbolicName() + "]");
try {
bundles[i].start();
}
catch (Throwable ex) {
log.warn("can't start bundle " + bundles[i].getBundleId() + "[" + bundles[i].getSymbolicName()
+ "]", ex);
}
}
postProcessBundleContext(context);
// get JUnit test service reference
// this is a loose reference - update it if the Activator class is
// changed.
ServiceReference reference = context.getServiceReference(ACTIVATOR_REFERENCE);
if (reference == null)
throw new IllegalStateException("no OSGi service reference found at " + ACTIVATOR_REFERENCE);
service = context.getService(reference);
if (service == null) {
throw new IllegalStateException("no service found for reference: " + reference);
}
serviceTrigger = service.getClass().getDeclaredMethod("executeTest", null);
if (serviceTrigger == null) {
throw new IllegalStateException("no executeTest() method found on: " + service.getClass());
}
onSetUpBeforeOsgi();
}
}
/**
* Callback for processing the bundle context after the bundles have been
* installed and started.
*
* @param context
*/
protected void postProcessBundleContext(BundleContext context) throws Exception {
}
/**
* Install an OSGi bundle from the given location.
*
* @param location
* @return
* @throws Exception
*/
private Bundle installBundle(Resource location) throws Exception {
Assert.notNull(context);
Assert.notNull(location);
log.debug("installing bundle from location " + location.getDescription());
return context.installBundle(location.getDescription(), location.getInputStream());
}
/**
* Hook for adding behavior after the OSGi platform has been started (is
* this really needed).
*
*/
protected void onSetUpBeforeOsgi() {
}
/**
* the setUp version for the OSGi environment.
*
* @throws Exception
*/
public void onSetUp() throws Exception {
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#tearDown()
*/
public final void tearDown() throws Exception {
cleanupStreams();
onTearDown();
}
public void onTearDown() throws Exception {
}
private void readTestResult() {
// finish stream creation (to avoid circullar dependencies)
createInStream();
log.debug("reading OSGi results for test [" + getName() + "]");
TestUtils.receiveTestResult(this.originalResult, this, inputStream);
log.debug("test[" + getName() + "]'s result read");
}
private void registerShutdownHook() {
if (shutdownHook == null) {
// No shutdown hook registered yet.
shutdownHook = new Thread() {
public void run() {
shutdownTest();
}
};
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
}
private void shutdownTest() {
cleanupStreams();
log.info("shutting down OSGi platform");
if (osgiPlatform != null) {
try {
osgiPlatform.stop();
}
catch (Exception ex) {
// swallow
log.warn("shutdown procedure threw exception " + ex);
}
osgiPlatform = null;
}
}
/**
* Setup the piped streams to get the results out from the OSGi world.
*
* @throws IOException
*/
private void setupStreams() throws IOException {
// 4K seems to be enough
byte[] inArray = new byte[1024 * 4];
byte[] outArray = new byte[1024 * 4];
Properties systemProps = System.getProperties();
// put information for OSGi
systemProps.put(OsgiJUnitTest.FOR_OSGI, inArray);
// get information from OSGi
systemProps.put(OsgiJUnitTest.FROM_OSGI, outArray);
// setup output stream to prevent blocking
outputStream = new ObjectOutputStream(new ConfigurableByteArrayOutputStream(inArray));
// flush header write away
outputStream.flush();
log.debug("OSGi streams setup");
}
private void cleanupStreams() {
try {
if (inputStream != null)
inputStream.close();
}
catch (IOException e) {
// swallow
}
try {
if (outputStream != null)
outputStream.close();
}
catch (IOException e) {
// swallow
}
}
private void createInStream() {
try {
byte[] inputSource = (byte[]) System.getProperties().get(OsgiJUnitTest.FROM_OSGI);
inputStream = new ObjectInputStream(new ByteArrayInputStream(inputSource));
}
catch (IOException ex) {
throw new RuntimeException("cannot open streams " + ex);
}
}
/**
* Change the normal test execution by adding result retrieval from OSGi
* realm.
*
* @see junit.framework.TestCase#run()
*/
public final void runTest() throws Throwable {
readTestResult();
}
/**
* Actual test execution (delegates to the TestCase implementation).
*
* @throws Throwable
*/
public final void osgiRunTest() throws Throwable {
super.runTest();
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#run(junit.framework.TestResult)
*/
public final void run(TestResult result) {
// get a hold of the test result
this.originalResult = result;
super.run(result);
}
public final void setBundleContext(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
public BundleContext getBundleContext() {
return bundleContext;
}
}
| renamed AbstractOsgiTests.getBundlesLocations -> getBundleLocations
| spring-osgi-test-support/org.springframework.osgi.test/src/main/java/org/springframework/osgi/test/AbstractOsgiTests.java | renamed AbstractOsgiTests.getBundlesLocations -> getBundleLocations | <ide><path>pring-osgi-test-support/org.springframework.osgi.test/src/main/java/org/springframework/osgi/test/AbstractOsgiTests.java
<ide> *
<ide> * @return the array of bundles to install
<ide> */
<del> protected String[] getBundlesLocations() {
<add> protected String[] getBundleLocations() {
<ide> return new String[] {};
<ide> }
<ide>
<ide> context = osgiPlatform.getBundleContext();
<ide> // merge bundles
<ide> String[] mandatoryBundles = getMandatoryBundles();
<del> String[] optionalBundles = getBundlesLocations();
<add> String[] optionalBundles = getBundleLocations();
<ide>
<ide> String[] allBundles = new String[mandatoryBundles.length + optionalBundles.length];
<ide> System.arraycopy(mandatoryBundles, 0, allBundles, 0, mandatoryBundles.length); |
|
Java | apache-2.0 | 64bc69ef4c547771f44f6b6b103cda7be2f0922b | 0 | AltitudeDigital/metrics,kevintvh/metrics,rexren/metrics,tempredirect/metrics,wfxiang08/metrics,mtakaki/metrics,randomstatistic/metrics,ind9/metrics,jplock/metrics,bentatham/metrics,mt0803/metrics,ChetnaChaudhari/metrics,jasw/metrics,mspiegel/metrics,chenxianghua2014/metrics,signalfx/metrics | package com.codahale.metrics;
import io.dropwizard.metrics.MetricName;
import java.util.Collections;
import java.util.Map;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Deprecated
public class MetricRegistry {
private static final Logger LOG = LoggerFactory.getLogger(MetricRegistry.class);
final io.dropwizard.metrics.MetricRegistry reg;
public static String name(Class<?> klass, String... names) {
return io.dropwizard.metrics.MetricRegistry
.name(klass.getName(), names).getKey();
}
public static String name(String name, String... names) {
return io.dropwizard.metrics.MetricRegistry.name(name, names).getKey();
}
public MetricRegistry(io.dropwizard.metrics.MetricRegistry reg) {
this.reg = reg;
}
public static MetricRegistry of(io.dropwizard.metrics.MetricRegistry reg) {
return new MetricRegistry(reg);
}
public <T extends Metric> T register(String name, T metric)
throws IllegalArgumentException {
if (metric instanceof MetricSet) {
registerAll(MetricName.build(name), (MetricSet) metric);
} else {
reg.register(name, metric);
}
return metric;
}
public void registerAll(MetricSet metrics) throws IllegalArgumentException {
registerAll(null, metrics);
}
private void registerAll(MetricName prefix, MetricSet metrics)
throws IllegalArgumentException {
if (prefix == null)
prefix = MetricName.EMPTY;
for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) {
if (entry.getValue() instanceof MetricSet) {
registerAll(
MetricName.join(prefix,
MetricName.build(entry.getKey())),
(MetricSet) entry.getValue());
} else {
reg.register(
MetricName.join(prefix,
MetricName.build(entry.getKey())),
entry.getValue());
}
}
}
public Counter counter(String name) {
return new Counter(reg.counter(MetricName.build(name)));
}
public Histogram histogram(String name) {
return new Histogram(reg.histogram(MetricName.build(name)));
}
public Meter meter(String name) {
return new Meter(reg.meter(MetricName.build(name)));
}
public Timer timer(String name) {
return new Timer(reg.timer(MetricName.build(name)));
}
public boolean remove(String name) {
return reg.remove(MetricName.build(name));
}
public void removeMatching(MetricFilter filter) {
reg.removeMatching(transformFilter(filter));
}
// public void addListener(MetricRegistryListener listener) {
// listeners.add(listener);
//
// for (Map.Entry<MetricName, Metric> entry : metrics.entrySet()) {
// notifyListenerOfAddedMetric(listener, entry.getValue(),
// entry.getKey());
// }
// }
//
// public void removeListener(MetricRegistryListener listener) {
// listeners.remove(listener);
// }
public SortedSet<String> getNames() {
SortedSet<String> names = new TreeSet<>();
for(MetricName name: reg.getNames()){
names.add(name.getKey());
}
return Collections.unmodifiableSortedSet(names);
}
@SuppressWarnings("rawtypes")
public SortedMap<String, Gauge> getGauges() {
return getGauges(MetricFilter.ALL);
}
@SuppressWarnings("rawtypes")
public SortedMap<String, Gauge> getGauges(MetricFilter filter) {
return adaptMetrics(Gauge.class, reg.getGauges(transformFilter(filter)));
}
public SortedMap<String, Counter> getCounters() {
return getCounters(MetricFilter.ALL);
}
public SortedMap<String, Counter> getCounters(MetricFilter filter) {
return adaptMetrics(Counter.class, reg.getCounters(transformFilter(filter)));
}
public SortedMap<String, Histogram> getHistograms() {
return getHistograms(MetricFilter.ALL);
}
public SortedMap<String, Histogram> getHistograms(MetricFilter filter) {
return adaptMetrics(Histogram.class, reg.getHistograms(transformFilter(filter)));
}
public SortedMap<String, Meter> getMeters() {
return getMeters(MetricFilter.ALL);
}
public SortedMap<String, Meter> getMeters(MetricFilter filter) {
return adaptMetrics(Meter.class, reg.getMeters(transformFilter(filter)));
}
public SortedMap<String, Timer> getTimers() {
return getTimers(MetricFilter.ALL);
}
public SortedMap<String, Timer> getTimers(MetricFilter filter) {
return adaptMetrics(Timer.class, reg.getTimers(transformFilter(filter)));
}
private io.dropwizard.metrics.MetricFilter transformFilter(final MetricFilter filter) {
return new io.dropwizard.metrics.MetricFilter() {
@Override
public boolean matches(MetricName name, io.dropwizard.metrics.Metric metric) {
try {
return filter.matches(name.getKey(), adaptMetric(metric));
} catch (ClassNotFoundException e) {
LOG.warn("Came accross unadapted metric", e);
return false;
}
}
};
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private Metric adaptMetric(final io.dropwizard.metrics.Metric metric) throws ClassNotFoundException {
if(metric instanceof Metric){
return (Metric) metric;
} else if(metric instanceof io.dropwizard.metrics.Counter){
return new Counter((io.dropwizard.metrics.Counter) metric);
} else if(metric instanceof io.dropwizard.metrics.Histogram){
return new Histogram((io.dropwizard.metrics.Histogram) metric);
} else if(metric instanceof io.dropwizard.metrics.Meter){
return new Meter((io.dropwizard.metrics.Meter) metric);
} else if(metric instanceof io.dropwizard.metrics.Timer){
return new Timer((io.dropwizard.metrics.Timer) metric);
} else if(metric instanceof io.dropwizard.metrics.Gauge){
return new Gauge((io.dropwizard.metrics.Gauge) metric);
}
throw new ClassNotFoundException("Can't find adaptor class for metric of type "+ metric.getClass().getName());
}
@SuppressWarnings("unchecked")
private <T extends Metric, A extends io.dropwizard.metrics.Metric> SortedMap<String, T> adaptMetrics(final Class<T> klass, final SortedMap<MetricName, A> metrics) {
SortedMap<String, T> items = new TreeMap<>();
for(Map.Entry<MetricName, A> metric: metrics.entrySet()){
try {
items.put(metric.getKey().getKey(), (T) adaptMetric(metric.getValue()));
} catch (ClassNotFoundException e) {
LOG.warn("Came accross unadapted metric", e);
}
}
return Collections.unmodifiableSortedMap(items);
}
}
| metrics-adaptor/src/main/java/com/codahale/metrics/MetricRegistry.java | package com.codahale.metrics;
import io.dropwizard.metrics.MetricName;
import java.util.Collections;
import java.util.Map;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Deprecated
public class MetricRegistry {
private static final Logger LOG = LoggerFactory.getLogger(MetricRegistry.class);
final io.dropwizard.metrics.MetricRegistry reg;
public static String name(Class<?> klass, String... names) {
return io.dropwizard.metrics.MetricRegistry
.name(klass.getName(), names).getKey();
}
public static String name(String name, String... names) {
return io.dropwizard.metrics.MetricRegistry.name(name, names).getKey();
}
public MetricRegistry(io.dropwizard.metrics.MetricRegistry reg) {
this.reg = reg;
}
public static MetricRegistry of(io.dropwizard.metrics.MetricRegistry reg) {
return new MetricRegistry(reg);
}
public <T extends Metric> T register(String name, T metric)
throws IllegalArgumentException {
if (metric instanceof MetricSet) {
registerAll(MetricName.build(name), (MetricSet) metric);
} else {
reg.register(name, metric);
}
return metric;
}
public void registerAll(MetricSet metrics) throws IllegalArgumentException {
registerAll(null, metrics);
}
private void registerAll(MetricName prefix, MetricSet metrics)
throws IllegalArgumentException {
if (prefix == null)
prefix = MetricName.EMPTY;
for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) {
if (entry.getValue() instanceof MetricSet) {
registerAll(
MetricName.join(prefix,
MetricName.build(entry.getKey())),
(MetricSet) entry.getValue());
} else {
reg.register(
MetricName.join(prefix,
MetricName.build(entry.getKey())),
entry.getValue());
}
}
}
public Counter counter(String name) {
return new Counter(reg.counter(MetricName.build(name)));
}
public Histogram histogram(String name) {
return new Histogram(reg.histogram(MetricName.build(name)));
}
public Meter meter(String name) {
return new Meter(reg.meter(MetricName.build(name)));
}
public Timer timer(String name) {
return new Timer(reg.timer(MetricName.build(name)));
}
public boolean remove(String name) {
return reg.remove(MetricName.build(name));
}
public void removeMatching(MetricFilter filter) {
reg.removeMatching(transformFilter(filter));
}
// public void addListener(MetricRegistryListener listener) {
// listeners.add(listener);
//
// for (Map.Entry<MetricName, Metric> entry : metrics.entrySet()) {
// notifyListenerOfAddedMetric(listener, entry.getValue(),
// entry.getKey());
// }
// }
//
// public void removeListener(MetricRegistryListener listener) {
// listeners.remove(listener);
// }
public SortedSet<String> getNames() {
SortedSet<String> names = new TreeSet<>();
for(MetricName name: reg.getNames()){
names.add(name.getKey());
}
return Collections.unmodifiableSortedSet(names);
}
@SuppressWarnings("rawtypes")
public SortedMap<String, Gauge> getGauges() {
return getGauges(MetricFilter.ALL);
}
@SuppressWarnings("rawtypes")
public SortedMap<String, Gauge> getGauges(MetricFilter filter) {
return adaptMetrics(Gauge.class, reg.getGauges(transformFilter(filter)));
}
public SortedMap<String, Counter> getCounters() {
return getCounters(MetricFilter.ALL);
}
public SortedMap<String, Counter> getCounters(MetricFilter filter) {
return adaptMetrics(Counter.class, reg.getCounters(transformFilter(filter)));
}
public SortedMap<String, Histogram> getHistograms() {
return getHistograms(MetricFilter.ALL);
}
public SortedMap<String, Histogram> getHistograms(MetricFilter filter) {
return adaptMetrics(Histogram.class, reg.getCounters(transformFilter(filter)));
}
public SortedMap<String, Meter> getMeters() {
return getMeters(MetricFilter.ALL);
}
public SortedMap<String, Meter> getMeters(MetricFilter filter) {
return adaptMetrics(Meter.class, reg.getCounters(transformFilter(filter)));
}
public SortedMap<String, Timer> getTimers() {
return getTimers(MetricFilter.ALL);
}
public SortedMap<String, Timer> getTimers(MetricFilter filter) {
return adaptMetrics(Timer.class, reg.getCounters(transformFilter(filter)));
}
private io.dropwizard.metrics.MetricFilter transformFilter(final MetricFilter filter) {
return new io.dropwizard.metrics.MetricFilter() {
@Override
public boolean matches(MetricName name, io.dropwizard.metrics.Metric metric) {
try {
return filter.matches(name.getKey(), adaptMetric(metric));
} catch (ClassNotFoundException e) {
LOG.warn("Came accross unadapted metric", e);
return false;
}
}
};
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private Metric adaptMetric(final io.dropwizard.metrics.Metric metric) throws ClassNotFoundException {
if(metric instanceof Metric){
return (Metric) metric;
} else if(metric instanceof io.dropwizard.metrics.Counter){
return new Counter((io.dropwizard.metrics.Counter) metric);
} else if(metric instanceof io.dropwizard.metrics.Histogram){
return new Histogram((io.dropwizard.metrics.Histogram) metric);
} else if(metric instanceof io.dropwizard.metrics.Meter){
return new Meter((io.dropwizard.metrics.Meter) metric);
} else if(metric instanceof io.dropwizard.metrics.Timer){
return new Timer((io.dropwizard.metrics.Timer) metric);
} else if(metric instanceof io.dropwizard.metrics.Gauge){
return new Gauge((io.dropwizard.metrics.Gauge) metric);
}
throw new ClassNotFoundException("Can't find adaptor class for metric of type "+ metric.getClass().getName());
}
@SuppressWarnings("unchecked")
private <T extends Metric, A extends io.dropwizard.metrics.Metric> SortedMap<String, T> adaptMetrics(final Class<T> klass, final SortedMap<MetricName, A> metrics) {
SortedMap<String, T> items = new TreeMap<>();
for(Map.Entry<MetricName, A> metric: metrics.entrySet()){
try {
items.put(metric.getKey().getKey(), (T) adaptMetric(metric.getValue()));
} catch (ClassNotFoundException e) {
LOG.warn("Came accross unadapted metric", e);
}
}
return Collections.unmodifiableSortedMap(items);
}
}
| Fix issue with getTimers()
| metrics-adaptor/src/main/java/com/codahale/metrics/MetricRegistry.java | Fix issue with getTimers() | <ide><path>etrics-adaptor/src/main/java/com/codahale/metrics/MetricRegistry.java
<ide> }
<ide>
<ide> public SortedMap<String, Histogram> getHistograms(MetricFilter filter) {
<del> return adaptMetrics(Histogram.class, reg.getCounters(transformFilter(filter)));
<add> return adaptMetrics(Histogram.class, reg.getHistograms(transformFilter(filter)));
<ide> }
<ide>
<ide> public SortedMap<String, Meter> getMeters() {
<ide> }
<ide>
<ide> public SortedMap<String, Meter> getMeters(MetricFilter filter) {
<del> return adaptMetrics(Meter.class, reg.getCounters(transformFilter(filter)));
<add> return adaptMetrics(Meter.class, reg.getMeters(transformFilter(filter)));
<ide> }
<ide>
<ide> public SortedMap<String, Timer> getTimers() {
<ide> }
<ide>
<ide> public SortedMap<String, Timer> getTimers(MetricFilter filter) {
<del> return adaptMetrics(Timer.class, reg.getCounters(transformFilter(filter)));
<add> return adaptMetrics(Timer.class, reg.getTimers(transformFilter(filter)));
<ide> }
<ide>
<ide> private io.dropwizard.metrics.MetricFilter transformFilter(final MetricFilter filter) { |
|
JavaScript | mit | d975a97858c294f1d1cb65139e9c6f906778249a | 0 | blmgeo/eco-model,blmgeo/eco-model | 'use strict'
//non steady state box models
const NonSteadyState = {
state(props) {
if (!props) return this
else return Object.assign(Object.create(this), props)
},
update(props) {
if (props) {
for (let key in props) {
if (this.hasOwnProperty(key)) {
this[key] = props[key]
} else throw 'Property "' + key + '" does not exist.'
}
}
},
flowAt(time) {
let currentFlow = this.flow
currentFlow += (this.deltaFlow * time)
return currentFlow
},
stockAt(time) {
let currentStock = this.stock
currentStock += (this.flow * time)
return currentStock
}
}
module.exports = NonSteadyState
| src/NonSteadyState.js | 'use strict'
//non steady state box models
const NonSteadyState = {
state(props) {
if (!props) return this
else return Object.assign(Object.create(this), props)
},
update(props) {
if (props) {
for (let key in props) {
if (this.hasOwnProperty(key)) {
this[key] = props[key]
} else throw 'Property "' + key + '" does not exist.'
}
}
},
flowAt(time) {
let currentFlow = this.flow
for (let i = 1; i <= time; i++) {
currentFlow += this.flow
}
return currentFlow
},
stockAt(time) {
let currentStock = this.stock
for (let i = 1; i <= time; i++) {
currentStock += this.flow
}
return currentStock
}
}
module.exports = NonSteadyState
| added deltaFlow
| src/NonSteadyState.js | added deltaFlow | <ide><path>rc/NonSteadyState.js
<ide> },
<ide> flowAt(time) {
<ide> let currentFlow = this.flow
<del> for (let i = 1; i <= time; i++) {
<del> currentFlow += this.flow
<del> }
<add> currentFlow += (this.deltaFlow * time)
<ide> return currentFlow
<ide> },
<ide> stockAt(time) {
<ide> let currentStock = this.stock
<del> for (let i = 1; i <= time; i++) {
<del> currentStock += this.flow
<del> }
<add> currentStock += (this.flow * time)
<ide> return currentStock
<ide> }
<ide> } |
|
Java | agpl-3.0 | c50268a42a86ad84de482f0cfee252a8a973adf0 | 0 | victims/victims-lib-java | package com.redhat.victims;
/*
* #%L
* This file is part of victims-lib.
* %%
* Copyright (C) 2013 The Victims Project
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
/**
* This class provides system property keys and default values for all available
* Victims configurations.
*
* @author abn
*
*/
public class VictimsConfig {
public static final HashMap<String, String> DEFAULT_PROPS = new HashMap<String, String>();
static {
DEFAULT_PROPS.put(Key.URI, "http://www.victi.ms/");
DEFAULT_PROPS.put(Key.ENTRY, "service/");
DEFAULT_PROPS.put(Key.ENCODING, "UTF-8");
DEFAULT_PROPS.put(Key.CACHE, FilenameUtils.concat(FileUtils
.getUserDirectory().getAbsolutePath(), ".victims"));
DEFAULT_PROPS.put(Key.DB_DRIVER, "org.h2.Driver");
}
/**
* Return a configured value, or the default.
*
* @param key
* @return If configured, return the system property value, else return a
* default. If a default is also not available, returns an empty
* {@link String}.
*/
private static String getPropertyValue(String key) {
String env = System.getProperty(key);
if (env == null) {
if (DEFAULT_PROPS.containsKey(key)) {
return DEFAULT_PROPS.get(key);
} else {
return "";
}
}
return env;
}
/**
*
* @return Default encoding.
*/
public static Charset charset() {
String enc = getPropertyValue(Key.ENCODING);
return Charset.forName(enc);
}
/**
* Get the webservice base URI.
*
* @return
*/
public static String uri() {
return getPropertyValue(Key.URI);
}
/**
* Get the webservice entry point.
*
* @return
*/
public static String entry() {
return getPropertyValue(Key.ENTRY);
}
/**
* Get a complete webservice uri by merging base and entry point.
*
* @return
* @throws MalformedURLException
*/
public static String serviceURI() throws MalformedURLException {
URL merged = new URL(new URL(uri()), entry());
return merged.toString();
}
/**
* Get the configured cache directory. If the directory does not exist, it
* will be created.
*
* @return
* @throws IOException
*/
public static File cache() throws IOException {
File directory = new File(getPropertyValue(Key.CACHE));
if (!directory.exists()) {
FileUtils.forceMkdir(directory);
}
return directory;
}
/**
* Get the db driver class string in use.
*
* @return
*/
public static String dbDriver() {
return getPropertyValue(Key.DB_DRIVER);
}
/**
* Is a force database update required.
*
* @return
*/
public static boolean forcedUpdate() {
return Boolean.getBoolean(Key.DB_FORCE_UPDATE);
}
public static class Key {
public static final String URI = "victims.service.uri";
public static final String ENTRY = "victims.service.entry";
public static final String ENCODING = "victims.encoding";
public static final String CACHE = "victims.cache";
public static final String DB_DRIVER = "victims.db.driver";
public static final String DB_FORCE_UPDATE = "victims.db.force";
}
}
| src/main/java/com/redhat/victims/VictimsConfig.java | package com.redhat.victims;
/*
* #%L
* This file is part of victims-lib.
* %%
* Copyright (C) 2013 The Victims Project
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
/**
* This class provides system property keys and default values for all available
* Victims configurations.
*
* @author abn
*
*/
public class VictimsConfig {
private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
public static final String URI_KEY = "victims.service.uri";
public static final String ENTRY_KEY = "victims.service.entry";
public static final String CACHE_KEY = "victims.local.cache";
public static final String DB_DRIVER_KEY = "victims.local.db.driver";
public static final HashMap<String, String> DEFAULT_PROPS = new HashMap<String, String>();
static {
DEFAULT_PROPS.put(URI_KEY, "http://www.victi.ms/");
DEFAULT_PROPS.put(ENTRY_KEY, "service/");
DEFAULT_PROPS.put(CACHE_KEY, FilenameUtils.concat(FileUtils
.getUserDirectory().getAbsolutePath(), ".victims"));
DEFAULT_PROPS.put(DB_DRIVER_KEY, "org.h2.Driver");
}
/**
*
* @return Default encoding.
*/
public static Charset charset() {
return DEFAULT_ENCODING;
}
/**
* Return a configured value, or the default.
*
* @param key
* @return If configured, return the system property value, else return a
* default. If a default is also not available, returns an empty
* {@link String}.
*/
private static String getPropertyValue(String key) {
String env = System.getProperty(key);
if (env == null) {
if (DEFAULT_PROPS.containsKey(key)) {
return DEFAULT_PROPS.get(key);
} else {
return "";
}
}
return env;
}
/**
* Get the webservice base URI.
*
* @return
*/
public static String uri() {
return getPropertyValue(URI_KEY);
}
/**
* Get the webservice entry point.
*
* @return
*/
public static String entry() {
return getPropertyValue(ENTRY_KEY);
}
/**
* Get a complete webservice uri by merging base and entry point.
*
* @return
* @throws MalformedURLException
*/
public static String serviceURI() throws MalformedURLException {
URL merged = new URL(new URL(uri()), entry());
return merged.toString();
}
/**
* Get the configured cache directory. If the directory does not exist, it
* will be created.
*
* @return
* @throws IOException
*/
public static File cache() throws IOException {
File directory = new File(getPropertyValue(CACHE_KEY));
if (!directory.exists()) {
FileUtils.forceMkdir(directory);
}
return directory;
}
/**
* Get the db driver class string in use.
*
* @return
*/
public static String dbDriver() {
return getPropertyValue(DB_DRIVER_KEY);
}
}
| Restructured VictimsConfig
| src/main/java/com/redhat/victims/VictimsConfig.java | Restructured VictimsConfig | <ide><path>rc/main/java/com/redhat/victims/VictimsConfig.java
<ide> *
<ide> */
<ide> public class VictimsConfig {
<del> private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
<del>
<del> public static final String URI_KEY = "victims.service.uri";
<del> public static final String ENTRY_KEY = "victims.service.entry";
<del> public static final String CACHE_KEY = "victims.local.cache";
<del> public static final String DB_DRIVER_KEY = "victims.local.db.driver";
<del>
<ide> public static final HashMap<String, String> DEFAULT_PROPS = new HashMap<String, String>();
<ide>
<ide> static {
<del> DEFAULT_PROPS.put(URI_KEY, "http://www.victi.ms/");
<del> DEFAULT_PROPS.put(ENTRY_KEY, "service/");
<del> DEFAULT_PROPS.put(CACHE_KEY, FilenameUtils.concat(FileUtils
<add> DEFAULT_PROPS.put(Key.URI, "http://www.victi.ms/");
<add> DEFAULT_PROPS.put(Key.ENTRY, "service/");
<add> DEFAULT_PROPS.put(Key.ENCODING, "UTF-8");
<add> DEFAULT_PROPS.put(Key.CACHE, FilenameUtils.concat(FileUtils
<ide> .getUserDirectory().getAbsolutePath(), ".victims"));
<del> DEFAULT_PROPS.put(DB_DRIVER_KEY, "org.h2.Driver");
<del> }
<del>
<del> /**
<del> *
<del> * @return Default encoding.
<del> */
<del> public static Charset charset() {
<del> return DEFAULT_ENCODING;
<add> DEFAULT_PROPS.put(Key.DB_DRIVER, "org.h2.Driver");
<ide> }
<ide>
<ide> /**
<ide> }
<ide>
<ide> /**
<add> *
<add> * @return Default encoding.
<add> */
<add> public static Charset charset() {
<add> String enc = getPropertyValue(Key.ENCODING);
<add> return Charset.forName(enc);
<add> }
<add>
<add> /**
<ide> * Get the webservice base URI.
<ide> *
<ide> * @return
<ide> */
<ide> public static String uri() {
<del> return getPropertyValue(URI_KEY);
<add> return getPropertyValue(Key.URI);
<ide> }
<ide>
<ide> /**
<ide> * @return
<ide> */
<ide> public static String entry() {
<del> return getPropertyValue(ENTRY_KEY);
<add> return getPropertyValue(Key.ENTRY);
<ide> }
<ide>
<ide> /**
<ide> * @throws IOException
<ide> */
<ide> public static File cache() throws IOException {
<del> File directory = new File(getPropertyValue(CACHE_KEY));
<add> File directory = new File(getPropertyValue(Key.CACHE));
<ide> if (!directory.exists()) {
<ide> FileUtils.forceMkdir(directory);
<ide> }
<ide> * @return
<ide> */
<ide> public static String dbDriver() {
<del> return getPropertyValue(DB_DRIVER_KEY);
<add> return getPropertyValue(Key.DB_DRIVER);
<add> }
<add>
<add> /**
<add> * Is a force database update required.
<add> *
<add> * @return
<add> */
<add> public static boolean forcedUpdate() {
<add> return Boolean.getBoolean(Key.DB_FORCE_UPDATE);
<add> }
<add>
<add> public static class Key {
<add> public static final String URI = "victims.service.uri";
<add> public static final String ENTRY = "victims.service.entry";
<add> public static final String ENCODING = "victims.encoding";
<add> public static final String CACHE = "victims.cache";
<add> public static final String DB_DRIVER = "victims.db.driver";
<add> public static final String DB_FORCE_UPDATE = "victims.db.force";
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 6c4166d7931f75fe6dbfad57790bee6395bf6b94 | 0 | floviolleau/vector-android,noepitome/neon-android,riot-spanish/riot-android,vector-im/vector-android,vt0r/vector-android,noepitome/neon-android,vector-im/riot-android,vector-im/vector-android,vector-im/riot-android,noepitome/neon-android,vector-im/riot-android,riot-spanish/riot-android,vector-im/riot-android,vector-im/vector-android,riot-spanish/riot-android,vt0r/vector-android,riot-spanish/riot-android,noepitome/neon-android,vt0r/vector-android,vector-im/vector-android,floviolleau/vector-android,floviolleau/vector-android,vector-im/riot-android | /*
* Copyright 2016 OpenMarket Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.fragments;
import android.annotation.SuppressLint;
import android.app.Activity;
//
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Build;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
import android.preference.SwitchPreference;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.Toast;
import org.matrix.androidsdk.MXSession;
import org.matrix.androidsdk.data.Room;
import org.matrix.androidsdk.data.RoomAccountData;
import org.matrix.androidsdk.data.RoomState;
import org.matrix.androidsdk.data.RoomTag;
import org.matrix.androidsdk.listeners.IMXNetworkEventListener;
import org.matrix.androidsdk.listeners.MXEventListener;
import org.matrix.androidsdk.rest.callback.ApiCallback;
import org.matrix.androidsdk.rest.model.ContentResponse;
import org.matrix.androidsdk.rest.model.Event;
import org.matrix.androidsdk.rest.model.MatrixError;
import org.matrix.androidsdk.rest.model.PowerLevels;
import org.matrix.androidsdk.rest.model.RoomMember;
import org.matrix.androidsdk.util.BingRulesManager;
import org.matrix.androidsdk.util.ContentManager;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import im.vector.Matrix;
import im.vector.R;
import im.vector.VectorApp;
import im.vector.activity.CommonActivityUtils;
import im.vector.activity.VectorMediasPickerActivity;
import im.vector.preference.AddressPreference;
import im.vector.preference.RoomAvatarPreference;
import im.vector.preference.VectorCustomActionEditTextPreference;
import im.vector.preference.VectorListPreference;
import im.vector.util.ResourceUtils;
import im.vector.util.VectorUtils;
import static android.preference.PreferenceManager.getDefaultSharedPreferences;
public class VectorRoomSettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
// internal constants values
private static final String LOG_TAG = "VectorRoomSetFragment";
private static final boolean UPDATE_UI = true;
private static final boolean DO_NOT_UPDATE_UI = false;
private static final int REQ_CODE_UPDATE_ROOM_AVATAR = 0x10;
// Room access rules values
private static final String ACCESS_RULES_ONLY_PEOPLE_INVITED = "1";
private static final String ACCESS_RULES_ANYONE_WITH_LINK_APART_GUEST = "2";
private static final String ACCESS_RULES_ANYONE_WITH_LINK_INCLUDING_GUEST = "3";
// fragment extra args keys
private static final String EXTRA_MATRIX_ID = "KEY_EXTRA_MATRIX_ID";
private static final String EXTRA_ROOM_ID = "KEY_EXTRA_ROOM_ID";
// preference keys: public API to access preference
private static final String PREF_KEY_ROOM_PHOTO_AVATAR = "roomPhotoAvatar";
private static final String PREF_KEY_ROOM_NAME = "roomNameEditText";
private static final String PREF_KEY_ROOM_TOPIC = "roomTopicEditText";
private static final String PREF_KEY_ROOM_DIRECTORY_VISIBILITY_SWITCH = "roomNameListedInDirectorySwitch";
private static final String PREF_KEY_ROOM_TAG_LIST = "roomTagList";
private static final String PREF_KEY_ROOM_ACCESS_RULES_LIST = "roomAccessRulesList";
private static final String PREF_KEY_ROOM_HISTORY_READABILITY_LIST = "roomReadHistoryRulesList";
private static final String PREF_KEY_ROOM_MUTE_NOTIFICATIONS_SWITCH = "muteNotificationsSwitch";
private static final String PREF_KEY_ROOM_LEAVE = "roomLeave";
private static final String PREF_KEY_ROOM_INTERNAL_ID = "roomInternalId";
private static final String PREF_KEY_ADDRESSES = "addresses";
private static final String PREF_KEY_BANNED = "banned";
private static final String ADDRESSES_PREFERENCE_KEY_BASE = "ADDRESSES_PREFERENCE_KEY_BASE";
private static final String NO_LOCAL_ADDRESS_PREFERENCE_KEY = "NO_LOCAL_ADDRESS_PREFERENCE_KEY";
private static final String ADD_ADDRESSES_PREFERENCE_KEY = "ADD_ADDRESSES_PREFERENCE_KEY";
private static final String BANNED_PREFERENCE_KEY_BASE = "BANNED_PREFERENCE_KEY_BASE";
private static final String UNKNOWN_VALUE = "UNKNOWN_VALUE";
// business code
private MXSession mSession;
private Room mRoom;
private BingRulesManager mBingRulesManager;
private boolean mIsUiUpdateSkipped;
// addresses
private PreferenceCategory mAddressesSettingsCategory;
// banned members
private PreferenceCategory mBannedMembersSettingsCategory;
// UI elements
private RoomAvatarPreference mRoomPhotoAvatar;
private EditTextPreference mRoomNameEditTxt;
private EditTextPreference mRoomTopicEditTxt;
private SwitchPreference mRoomDirectoryVisibilitySwitch;
private SwitchPreference mRoomMuteNotificationsSwitch;
private ListPreference mRoomTagListPreference;
private VectorListPreference mRoomAccessRulesListPreference;
private ListPreference mRoomHistoryReadabilityRulesListPreference;
private View mParentLoadingView;
private View mParentFragmentContainerView;
// disable some updates if there is
private final IMXNetworkEventListener mNetworkListener = new IMXNetworkEventListener() {
@Override
public void onNetworkConnectionUpdate(boolean isConnected) {
updateUi();
}
};
// update field listener
private final ApiCallback<Void> mUpdateCallback = new ApiCallback<Void>() {
/**
* refresh the fragment.
* @param mode true to force refresh
*/
private void onDone(final String message, final boolean mode) {
if (null != getActivity()) {
if (!TextUtils.isEmpty(message)) {
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
}
// ensure that the response has been sent in the UI thread
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
hideLoadingView(mode);
}
});
}
}
@Override
public void onSuccess(Void info) {
Log.d(LOG_TAG, "##update succeed");
onDone(null, UPDATE_UI);
}
@Override
public void onNetworkError(Exception e) {
Log.w(LOG_TAG, "##NetworkError " + e.getLocalizedMessage());
onDone(e.getLocalizedMessage(), DO_NOT_UPDATE_UI);
}
@Override
public void onMatrixError(MatrixError e) {
Log.w(LOG_TAG, "##MatrixError " + e.getLocalizedMessage());
onDone(e.getLocalizedMessage(), DO_NOT_UPDATE_UI);
}
@Override
public void onUnexpectedError(Exception e) {
Log.w(LOG_TAG, "##UnexpectedError " + e.getLocalizedMessage());
onDone(e.getLocalizedMessage(), DO_NOT_UPDATE_UI);
}
};
// MX system events listener
private final MXEventListener mEventListener = new MXEventListener() {
@Override
public void onLiveEvent(final Event event, RoomState roomState) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// The various events that could possibly change the fragment items
if (Event.EVENT_TYPE_STATE_ROOM_NAME.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_ALIASES.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_MEMBER.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_AVATAR.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_TOPIC.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_POWER_LEVELS.equals(event.type)
|| Event.EVENT_TYPE_STATE_HISTORY_VISIBILITY.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_JOIN_RULES.equals(event.type) // room access rules
|| Event.EVENT_TYPE_STATE_ROOM_GUEST_ACCESS.equals(event.type) // room access rules
)
{
Log.d(LOG_TAG, "## onLiveEvent() event = " + event.type);
updateUi();
}
// aliases
if (Event.EVENT_TYPE_STATE_CANONICAL_ALIAS.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_ALIASES.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_POWER_LEVELS.equals(event.type)
) {
Log.d(LOG_TAG, "## onLiveEvent() refresh the addresses list");
refreshAddresses();
}
if (Event.EVENT_TYPE_STATE_ROOM_MEMBER.equals(event.type)) {
Log.d(LOG_TAG, "## onLiveEvent() refresh the banned members list");
refreshBannedMembersList();
}
}
});
}
@Override
public void onRoomFlush(String roomId) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateUi();
}
});
}
@Override
public void onRoomTagEvent(String roomId) {
Log.d(LOG_TAG, "## onRoomTagEvent()");
updateUi();
}
@Override
public void onBingRulesUpdate() {
updateUi();
}
};
public static VectorRoomSettingsFragment newInstance(String aMatrixId,String aRoomId) {
VectorRoomSettingsFragment theFragment = new VectorRoomSettingsFragment();
Bundle args = new Bundle();
args.putString(EXTRA_MATRIX_ID, aMatrixId);
args.putString(EXTRA_ROOM_ID, aRoomId);
theFragment.setArguments(args);
return theFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(LOG_TAG,"## onCreate() IN");
// retrieve fragment extras
String matrixId = getArguments().getString(EXTRA_MATRIX_ID);
String roomId = getArguments().getString(EXTRA_ROOM_ID);
if(TextUtils.isEmpty(matrixId) || TextUtils.isEmpty(roomId)){
Log.e(LOG_TAG, "## onCreate(): fragment extras (MatrixId or RoomId) are missing");
getActivity().finish();
}
else {
mSession = Matrix.getInstance(getActivity()).getSession(matrixId);
if (null != mSession) {
mRoom = mSession.getDataHandler().getRoom(roomId);
mBingRulesManager = mSession.getDataHandler().getBingRulesManager();
}
if (null == mRoom) {
Log.e(LOG_TAG, "## onCreate(): unable to retrieve Room object");
getActivity().finish();
}
}
// load preference xml file
addPreferencesFromResource(R.xml.vector_room_settings_preferences);
// init preference fields
mRoomPhotoAvatar = (RoomAvatarPreference)findPreference(PREF_KEY_ROOM_PHOTO_AVATAR);
mRoomNameEditTxt = (EditTextPreference)findPreference(PREF_KEY_ROOM_NAME);
mRoomTopicEditTxt = (EditTextPreference)findPreference(PREF_KEY_ROOM_TOPIC);
mRoomDirectoryVisibilitySwitch = (SwitchPreference)findPreference(PREF_KEY_ROOM_DIRECTORY_VISIBILITY_SWITCH);
mRoomMuteNotificationsSwitch = (SwitchPreference)findPreference(PREF_KEY_ROOM_MUTE_NOTIFICATIONS_SWITCH);
mRoomTagListPreference = (ListPreference)findPreference(PREF_KEY_ROOM_TAG_LIST);
mRoomAccessRulesListPreference = (VectorListPreference)findPreference(PREF_KEY_ROOM_ACCESS_RULES_LIST);
mRoomHistoryReadabilityRulesListPreference = (ListPreference)findPreference(PREF_KEY_ROOM_HISTORY_READABILITY_LIST);
mAddressesSettingsCategory = (PreferenceCategory)getPreferenceManager().findPreference(PREF_KEY_ADDRESSES);
mBannedMembersSettingsCategory = (PreferenceCategory)getPreferenceManager().findPreference(PREF_KEY_BANNED);
mRoomAccessRulesListPreference.setOnPreferenceWarningIconClickListener(new VectorListPreference.OnPreferenceWarningIconClickListener() {
@Override
public void onWarningIconClick(Preference preference) {
displayAccessRoomWarning();
}
});
// display the room Id.
EditTextPreference roomInternalIdPreference = (EditTextPreference)findPreference(PREF_KEY_ROOM_INTERNAL_ID);
if (null != roomInternalIdPreference) {
roomInternalIdPreference.setSummary(mRoom.getRoomId());
roomInternalIdPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
VectorUtils.copyToClipboard(getActivity(), mRoom.getRoomId());
return false;
}
});
}
// leave room
EditTextPreference leaveRoomPreference = (EditTextPreference)findPreference(PREF_KEY_ROOM_LEAVE);
if (null != leaveRoomPreference) {
leaveRoomPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
// leave room
new AlertDialog.Builder(VectorApp.getCurrentActivity())
.setTitle(R.string.room_participants_leave_prompt_title)
.setMessage(getActivity().getString(R.string.room_participants_leave_prompt_msg))
.setPositiveButton(R.string.leave, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
displayLoadingView();
mRoom.leave(new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
if (null != getActivity()) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
getActivity().finish();
}
});
}
}
private void onError(final String errorMessage) {
if (null != getActivity()) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
hideLoadingView(true);
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public void onNetworkError(Exception e) {
onError(e.getLocalizedMessage());
}
@Override
public void onMatrixError(MatrixError e) {
onError(e.getLocalizedMessage());
}
@Override
public void onUnexpectedError(Exception e) {
onError(e.getLocalizedMessage());
}
});
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create()
.show();
return true;
}
});
}
// init the room avatar: session and room
mRoomPhotoAvatar.setConfiguration(mSession, mRoom);
mRoomPhotoAvatar.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
if ((null != mRoomPhotoAvatar) && mRoomPhotoAvatar.isEnabled()) {
onRoomAvatarPreferenceChanged();
return true; //True if the click was handled.
} else
return false;
}
});
// listen to preference changes
enableSharedPreferenceListener(true);
setRetainInstance(true);
}
/**
* This method expects a view with the id "settings_loading_layout",
* that is present in the parent activity layout.
* @param view fragment view
* @param savedInstanceState bundle instance state
*/
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// retrieve the loading screen in the parent view
View parent = getView();
if (null == mParentLoadingView) {
while ((null != parent) && (null == mParentLoadingView)) {
mParentLoadingView = parent.findViewById(R.id.settings_loading_layout);
parent = (View) parent.getParent();
}
}
// retrieve the parent fragment container view to disable access to the settings
// while the loading screen is enabled
parent = getView();
if (null == mParentFragmentContainerView) {
while ((null != parent) && (null == mParentFragmentContainerView)) {
mParentFragmentContainerView = parent.findViewById(R.id.room_details_fragment_container);
parent = (View) parent.getParent();
}
}
}
@Override
public void onPause() {
super.onPause();
if (null != mRoom) {
Matrix.getInstance(getActivity()).removeNetworkEventListener(mNetworkListener);
mRoom.removeEventListener(mEventListener);
}
// remove preference changes listener
enableSharedPreferenceListener(false);
}
@Override
public void onResume() {
super.onResume();
if (null != mRoom) {
Matrix.getInstance(getActivity()).addNetworkEventListener(mNetworkListener);
mRoom.addEventListener(mEventListener);
updateUi();
updateRoomDirectoryVisibilityAsync();
refreshAddresses();
refreshBannedMembersList();
}
}
/**
* Enable the preference listener according to the aIsListenerEnabled value.
* @param aIsListenerEnabled true to enable the listener, false otherwise
*/
private void enableSharedPreferenceListener(boolean aIsListenerEnabled) {
Log.d(LOG_TAG, "## enableSharedPreferenceListener(): aIsListenerEnabled=" + aIsListenerEnabled);
mIsUiUpdateSkipped = !aIsListenerEnabled;
try {
//SharedPreferences prefMgr = getActivity().getSharedPreferences("VectorSettingsFile", Context.MODE_PRIVATE);
SharedPreferences prefMgr = getDefaultSharedPreferences(getActivity());
if (aIsListenerEnabled) {
prefMgr.registerOnSharedPreferenceChangeListener(this);
} else {
prefMgr.unregisterOnSharedPreferenceChangeListener(this);
}
} catch (Exception ex){
Log.e(LOG_TAG, "## enableSharedPreferenceListener(): Exception Msg="+ex.getMessage());
}
}
/**
* Update the preferences according to the power levels and its values.
* To prevent the preference change listener to be triggered, the listener
* is removed when the preferences are updated.
*/
private void updateUi(){
// configure the preferences that are allowed to be modified by the user
updatePreferenceAccessFromPowerLevel();
// need to run on the UI thread to be taken into account
// when updatePreferenceUiValues() will be performed
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// disable listener during preferences update, otherwise it will
// be seen as a user action..
enableSharedPreferenceListener(false);
}
});
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// set settings UI values
updatePreferenceUiValues();
// re enable preferences listener..
enableSharedPreferenceListener(true);
}
});
}
/**
* delayed refresh the preferences items.
*/
private void updateUiOnUiThread() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateUi();
}
});
}
/**
* Retrieve the room visibility directory value and update the corresponding preference.
* This is an asynchronous request: the call-back response will be processed on the UI thread.
* For now, the room visibility directory value is not provided in the sync API, a specific request
* must performed.
*/
private void updateRoomDirectoryVisibilityAsync() {
if((null == mRoom) || (null == mRoomDirectoryVisibilitySwitch)) {
Log.w(LOG_TAG,"## updateRoomDirectoryVisibilityUi(): not processed due to invalid parameters");
} else {
displayLoadingView();
// server request: is the room listed in the room directory?
mRoom.getDirectoryVisibility(mRoom.getRoomId(), new ApiCallback<String>() {
private void handleResponseOnUiThread(final String aVisibilityValue){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// only stop loading screen and do not update UI since the
// update is done here below..
hideLoadingView(DO_NOT_UPDATE_UI);
// set checked status
// Note: the preference listener is disabled when the switch is updated, otherwise it will be seen
// as a user action on the preference
boolean isChecked = RoomState.DIRECTORY_VISIBILITY_PUBLIC.equals(aVisibilityValue);
enableSharedPreferenceListener(false);
mRoomDirectoryVisibilitySwitch.setChecked(isChecked);
enableSharedPreferenceListener(true);
}
});
}
@Override
public void onSuccess(String visibility) {
handleResponseOnUiThread(visibility);
}
@Override
public void onNetworkError(Exception e) {
Log.w(LOG_TAG, "## getDirectoryVisibility(): onNetworkError Msg="+e.getLocalizedMessage());
handleResponseOnUiThread(null);
}
@Override
public void onMatrixError(MatrixError matrixError) {
Log.w(LOG_TAG, "## getDirectoryVisibility(): onMatrixError Msg="+matrixError.getLocalizedMessage());
handleResponseOnUiThread(null);
}
@Override
public void onUnexpectedError(Exception e) {
Log.w(LOG_TAG, "## getDirectoryVisibility(): onUnexpectedError Msg="+e.getLocalizedMessage());
handleResponseOnUiThread(null);
}
});
}
}
/**
* Display the access room warning.
*/
private void displayAccessRoomWarning () {
Toast.makeText(getActivity(), R.string.room_settings_room_access_warning, Toast.LENGTH_SHORT).show();
}
/**
* Enable / disable preferences according to the power levels.
*/
private void updatePreferenceAccessFromPowerLevel(){
boolean canUpdateAvatar = false;
boolean canUpdateName = false;
boolean canUpdateTopic = false;
boolean isAdmin = false;
boolean isConnected = Matrix.getInstance(getActivity()).isConnected();
// cannot refresh if there is no valid session / room
if ((null != mRoom) && (null != mSession)) {
PowerLevels powerLevels = mRoom.getLiveState().getPowerLevels();
if (null != powerLevels) {
int powerLevel = powerLevels.getUserPowerLevel(mSession.getMyUserId());
canUpdateAvatar = powerLevel >= powerLevels.minimumPowerLevelForSendingEventAsStateEvent(Event.EVENT_TYPE_STATE_ROOM_AVATAR);
canUpdateName = powerLevel >= powerLevels.minimumPowerLevelForSendingEventAsStateEvent(Event.EVENT_TYPE_STATE_ROOM_NAME);
canUpdateTopic = powerLevel >= powerLevels.minimumPowerLevelForSendingEventAsStateEvent(Event.EVENT_TYPE_STATE_ROOM_TOPIC);
isAdmin = (powerLevel >= CommonActivityUtils.UTILS_POWER_LEVEL_ADMIN);
}
}
else {
Log.w(LOG_TAG, "## updatePreferenceAccessFromPowerLevel(): session or room may be missing");
}
if(null != mRoomPhotoAvatar)
mRoomPhotoAvatar.setEnabled(canUpdateAvatar && isConnected);
if(null != mRoomNameEditTxt)
mRoomNameEditTxt.setEnabled(canUpdateName && isConnected);
if(null != mRoomTopicEditTxt)
mRoomTopicEditTxt.setEnabled(canUpdateTopic && isConnected);
// room present in the directory list: admin only
if(null != mRoomDirectoryVisibilitySwitch)
mRoomDirectoryVisibilitySwitch.setEnabled(isAdmin && isConnected);
// room notification mute setting: no power condition
if(null != mRoomMuteNotificationsSwitch)
mRoomMuteNotificationsSwitch.setEnabled(isConnected);
// room tagging: no power condition
if(null != mRoomTagListPreference)
mRoomTagListPreference.setEnabled(isConnected);
// room access rules: admin only
if(null != mRoomAccessRulesListPreference) {
mRoomAccessRulesListPreference.setEnabled(isAdmin && isConnected);
mRoomAccessRulesListPreference.setWarningIconVisible((0 == mRoom.getAliases().size()) && !TextUtils.equals(RoomState.JOIN_RULE_INVITE, mRoom.getLiveState().join_rule));
}
// room read history: admin only
if(null != mRoomHistoryReadabilityRulesListPreference)
mRoomHistoryReadabilityRulesListPreference.setEnabled(isAdmin && isConnected);
}
/**
* Update the UI preference from the values taken from
* the SDK layer.
*/
private void updatePreferenceUiValues() {
String value;
String summary;
Resources resources;
if ((null == mSession) || (null == mRoom)){
Log.w(LOG_TAG, "## updatePreferenceUiValues(): session or room may be missing");
return;
}
if(null != mRoomPhotoAvatar){
mRoomPhotoAvatar.refreshAvatar();
}
// update the room name preference
if(null != mRoomNameEditTxt) {
value = mRoom.getLiveState().name;
mRoomNameEditTxt.setSummary(value);
mRoomNameEditTxt.setText(value);
}
// update the room topic preference
if(null != mRoomTopicEditTxt) {
value = mRoom.getTopic();
mRoomTopicEditTxt.setSummary(value);
mRoomTopicEditTxt.setText(value);
}
// update the mute notifications preference
if(null != mRoomMuteNotificationsSwitch) {
boolean isChecked = mBingRulesManager.isRoomNotificationsDisabled(mRoom);
mRoomMuteNotificationsSwitch.setChecked(isChecked);
}
// update room directory visibility
// if(null != mRoomDirectoryVisibilitySwitch) {
// boolean isRoomPublic = TextUtils.equals(mRoom.getVisibility()/*getLiveState().visibility ou .isPublic()*/, RoomState.DIRECTORY_VISIBILITY_PUBLIC);
// if(isRoomPublic !isRoomPublic= mRoomDirectoryVisibilitySwitch.isChecked())
// mRoomDirectoryVisibilitySwitch.setChecked(isRoomPublic);
// }
// check if fragment is added to its Activity before calling getResources().
// getResources() may throw an exception ".. not attached to Activity"
if (!isAdded()){
Log.e(LOG_TAG,"## updatePreferenceUiValues(): fragment not added to Activity - isAdded()=false");
return;
} else {
// in some weird cases, even if isAdded() = true, sometimes getResources() may fail,
// so we need to catch the exception
try {
resources = getResources();
} catch (Exception ex) {
Log.e(LOG_TAG,"## updatePreferenceUiValues(): Exception in getResources() - Msg="+ex.getLocalizedMessage());
return;
}
}
// room guest access rules
if((null != mRoomAccessRulesListPreference)&& (null != resources)) {
String joinRule = mRoom.getLiveState().join_rule;
String guestAccessRule = mRoom.getLiveState().getGuestAccess();
if(RoomState.JOIN_RULE_INVITE.equals(joinRule)/* && RoomState.GUEST_ACCESS_CAN_JOIN.equals(guestAccessRule)*/) {
// "Only people who have been invited" requires: {join_rule: "invite"} and {guest_access: "can_join"}
value = ACCESS_RULES_ONLY_PEOPLE_INVITED;
summary = resources.getString(R.string.room_settings_room_access_entry_only_invited);
} else if(RoomState.JOIN_RULE_PUBLIC.equals(joinRule) && RoomState.GUEST_ACCESS_FORBIDDEN.equals(guestAccessRule)) {
// "Anyone who knows the room's link, apart from guests" requires: {join_rule: "public"} and {guest_access: "forbidden"}
value = ACCESS_RULES_ANYONE_WITH_LINK_APART_GUEST;
summary = resources.getString(R.string.room_settings_room_access_entry_anyone_with_link_apart_guest);
} else if(RoomState.JOIN_RULE_PUBLIC.equals(joinRule) && RoomState.GUEST_ACCESS_CAN_JOIN.equals(guestAccessRule)) {
// "Anyone who knows the room's link, including guests" requires: {join_rule: "public"} and {guest_access: "can_join"}
value = ACCESS_RULES_ANYONE_WITH_LINK_INCLUDING_GUEST;
summary = resources.getString(R.string.room_settings_room_access_entry_anyone_with_link_including_guest);
} else {
// unknown combination value
value = null;
summary = null;
Log.w(LOG_TAG, "## updatePreferenceUiValues(): unknown room access configuration joinRule=" + joinRule + " and guestAccessRule="+guestAccessRule);
}
if(null != value){
mRoomAccessRulesListPreference.setValue(value);
mRoomAccessRulesListPreference.setSummary(summary);
} else {
mRoomHistoryReadabilityRulesListPreference.setValue(UNKNOWN_VALUE);
mRoomHistoryReadabilityRulesListPreference.setSummary("");
}
}
// update the room tag preference
if(null != mRoomTagListPreference) {
if(null != mRoom.getAccountData() && (null != resources)) {
//Set<String> customTagList = mRoom.getAccountData().getKeys();
if (null != mRoom.getAccountData().roomTag(RoomTag.ROOM_TAG_FAVOURITE)) {
value = resources.getString(R.string.room_settings_tag_pref_entry_value_favourite);
summary = resources.getString(R.string.room_settings_tag_pref_entry_favourite);
} else if (null != mRoom.getAccountData().roomTag(RoomTag.ROOM_TAG_LOW_PRIORITY)) {
value = resources.getString(R.string.room_settings_tag_pref_entry_value_low_priority);
summary = resources.getString(R.string.room_settings_tag_pref_entry_low_priority);
/* For further use in case of multiple tags support
} else if(!mRoom.getAccountData().getKeys().isEmpty()) {
for(String tag : customTagList){
summary += (!summary.isEmpty()?" ":"") + tag;
}*/
} else {
// no tag associated to the room
value = resources.getString(R.string.room_settings_tag_pref_entry_value_none);
summary = Html.fromHtml("<i>"+getResources().getString(R.string.room_settings_tag_pref_no_tag)+ "</i>").toString();
}
mRoomTagListPreference.setValue(value);
mRoomTagListPreference.setSummary(summary);
}
}
// room history readability
if (null != mRoomHistoryReadabilityRulesListPreference) {
value = mRoom.getLiveState().getHistoryVisibility();
summary = null;
if((null != value) && (null != resources)) {
// get summary value
if (value.equals(resources.getString(R.string.room_settings_read_history_entry_value_anyone))) {
summary = resources.getString(R.string.room_settings_read_history_entry_anyone);
} else if (value.equals(resources.getString(R.string.room_settings_read_history_entry_value_members_only_option_time_shared))) {
summary = resources.getString(R.string.room_settings_read_history_entry_members_only_option_time_shared);
} else if (value.equals(resources.getString(R.string.room_settings_read_history_entry_value_members_only_invited))) {
summary = resources.getString(R.string.room_settings_read_history_entry_members_only_invited);
} else if (value.equals(resources.getString(R.string.room_settings_read_history_entry_value_members_only_joined))) {
summary = resources.getString(R.string.room_settings_read_history_entry_members_only_joined);
} else {
// unknown value
Log.w(LOG_TAG, "## updatePreferenceUiValues(): unknown room read history value=" + value);
summary = null;
}
}
if(null != summary) {
mRoomHistoryReadabilityRulesListPreference.setValue(value);
mRoomHistoryReadabilityRulesListPreference.setSummary(summary);
} else {
mRoomHistoryReadabilityRulesListPreference.setValue(UNKNOWN_VALUE);
mRoomHistoryReadabilityRulesListPreference.setSummary("");
}
}
}
// OnSharedPreferenceChangeListener implementation
/**
* Main entry point handler for any preference changes. For each setting a dedicated handler is
* called to process the setting.
*
* @param aSharedPreferences preference instance
* @param aKey preference key as it is defined in the XML
*/
@Override
public void onSharedPreferenceChanged(SharedPreferences aSharedPreferences, String aKey) {
if(mIsUiUpdateSkipped){
Log.d(LOG_TAG,"## onSharedPreferenceChanged(): Skipped");
return;
}
if (aKey.equals(PREF_KEY_ROOM_PHOTO_AVATAR)) {
// unused flow: onSharedPreferenceChanged not triggered for room avatar photo
onRoomAvatarPreferenceChanged();
}
else if(aKey.equals(PREF_KEY_ROOM_NAME)) {
onRoomNamePreferenceChanged();
}
else if(aKey.equals(PREF_KEY_ROOM_TOPIC)) {
onRoomTopicPreferenceChanged();
} else if(aKey.equals(PREF_KEY_ROOM_MUTE_NOTIFICATIONS_SWITCH)) {
onRoomMuteNotificationsPreferenceChanged();
}
else if(aKey.equals(PREF_KEY_ROOM_DIRECTORY_VISIBILITY_SWITCH)) {
onRoomDirectoryVisibilityPreferenceChanged(); // TBT
}
else if(aKey.equals(PREF_KEY_ROOM_TAG_LIST)) {
onRoomTagPreferenceChanged(); // TBT
}
else if(aKey.equals(PREF_KEY_ROOM_ACCESS_RULES_LIST)) {
onRoomAccessPreferenceChanged();
}
else if(aKey.equals(PREF_KEY_ROOM_HISTORY_READABILITY_LIST)) {
onRoomHistoryReadabilityPreferenceChanged(); // TBT
}
else {
Log.w(LOG_TAG,"## onSharedPreferenceChanged(): unknown aKey = "+ aKey);
}
}
/**
* The room history readability has been updated.
*/
private void onRoomHistoryReadabilityPreferenceChanged() {
// sanity check
if ((null == mRoom) || (null == mRoomHistoryReadabilityRulesListPreference)) {
Log.w(LOG_TAG,"## onRoomHistoryReadabilityPreferenceChanged(): not processed due to invalid parameters");
return;
}
// get new and previous values
String previousValue = mRoom.getLiveState().history_visibility;
String newValue = mRoomHistoryReadabilityRulesListPreference.getValue();
if(!TextUtils.equals(newValue, previousValue)) {
String historyVisibility;
if(newValue.equals(getResources().getString(R.string.room_settings_read_history_entry_value_anyone))) {
historyVisibility = RoomState.HISTORY_VISIBILITY_WORLD_READABLE;
} else if(newValue.equals(getResources().getString(R.string.room_settings_read_history_entry_value_members_only_option_time_shared))) {
historyVisibility = RoomState.HISTORY_VISIBILITY_SHARED;
} else if(newValue.equals(getResources().getString(R.string.room_settings_read_history_entry_value_members_only_invited))) {
historyVisibility = RoomState.HISTORY_VISIBILITY_INVITED;
} else if(newValue.equals(getResources().getString(R.string.room_settings_read_history_entry_value_members_only_joined))) {
historyVisibility = RoomState.HISTORY_VISIBILITY_JOINED;
} else {
// unknown value
Log.w(LOG_TAG,"## onRoomHistoryReadabilityPreferenceChanged(): unknown value:"+newValue);
historyVisibility = null;
}
if(null != historyVisibility) {
displayLoadingView();
mRoom.updateHistoryVisibility(historyVisibility, mUpdateCallback);
}
}
}
private void onRoomTagPreferenceChanged() {
boolean isSupportedTag = true;
// sanity check
if((null == mRoom) || (null == mRoomTagListPreference)) {
Log.w(LOG_TAG,"## onRoomTagPreferenceChanged(): not processed due to invalid parameters");
} else {
String newTag = mRoomTagListPreference.getValue();
String currentTag = null;
Double tagOrder = 0.0;
// retrieve the tag from the room info
RoomAccountData accountData = mRoom.getAccountData();
if ((null != accountData) && accountData.hasTags()) {
currentTag = accountData.getKeys().iterator().next();
}
if(!newTag.equals(currentTag)) {
if(newTag.equals(getResources().getString(R.string.room_settings_tag_pref_entry_value_favourite))) {
newTag = RoomTag.ROOM_TAG_FAVOURITE;
} else if(newTag.equals(getResources().getString(R.string.room_settings_tag_pref_entry_value_low_priority))) {
newTag = RoomTag.ROOM_TAG_LOW_PRIORITY;
} else if(newTag.equals(getResources().getString(R.string.room_settings_tag_pref_entry_value_none))) {
newTag = null;
} else {
// unknown tag.. very unlikely
isSupportedTag = false;
Log.w(LOG_TAG, "## onRoomTagPreferenceChanged() not supported tag = " + newTag);
}
}
if(isSupportedTag) {
displayLoadingView();
mRoom.replaceTag(currentTag, newTag, tagOrder, mUpdateCallback);
}
}
}
private void onRoomAccessPreferenceChanged() {
if((null == mRoom) || (null == mRoomAccessRulesListPreference)) {
Log.w(LOG_TAG,"## onRoomAccessPreferenceChanged(): not processed due to invalid parameters");
} else {
String joinRuleToApply = null;
String guestAccessRuleToApply = null;
// get new and previous values
String previousJoinRule = mRoom.getLiveState().join_rule;
String previousGuestAccessRule = mRoom.getLiveState().getGuestAccess();
String newValue = mRoomAccessRulesListPreference.getValue();
if(ACCESS_RULES_ONLY_PEOPLE_INVITED.equals(newValue)) {
// requires: {join_rule: "invite"} and {guest_access: "can_join"}
joinRuleToApply = !RoomState.JOIN_RULE_INVITE.equals(previousJoinRule)?RoomState.JOIN_RULE_INVITE:null;
guestAccessRuleToApply = !RoomState.GUEST_ACCESS_CAN_JOIN.equals(previousGuestAccessRule)?RoomState.GUEST_ACCESS_CAN_JOIN:null;
} else if(ACCESS_RULES_ANYONE_WITH_LINK_APART_GUEST.equals(newValue)) {
// requires: {join_rule: "public"} and {guest_access: "forbidden"}
joinRuleToApply = !RoomState.JOIN_RULE_PUBLIC.equals(previousJoinRule)?RoomState.JOIN_RULE_PUBLIC:null;
guestAccessRuleToApply = !RoomState.GUEST_ACCESS_FORBIDDEN.equals(previousGuestAccessRule)?RoomState.GUEST_ACCESS_FORBIDDEN:null;
if (0 == mRoom.getAliases().size()) {
displayAccessRoomWarning();
}
} else if(ACCESS_RULES_ANYONE_WITH_LINK_INCLUDING_GUEST.equals(newValue)) {
// requires: {join_rule: "public"} and {guest_access: "can_join"}
joinRuleToApply = !RoomState.JOIN_RULE_PUBLIC.equals(previousJoinRule)?RoomState.JOIN_RULE_PUBLIC:null;
guestAccessRuleToApply = !RoomState.GUEST_ACCESS_CAN_JOIN.equals(previousGuestAccessRule)?RoomState.GUEST_ACCESS_CAN_JOIN:null;
if (0 == mRoom.getAliases().size()) {
displayAccessRoomWarning();
}
} else {
// unknown value
Log.d(LOG_TAG,"## onRoomAccessPreferenceChanged(): unknown selected value = "+newValue);
}
if(null != joinRuleToApply) {
displayLoadingView();
mRoom.updateJoinRules(joinRuleToApply, mUpdateCallback);
}
if(null != guestAccessRuleToApply) {
displayLoadingView();
mRoom.updateGuestAccess(guestAccessRuleToApply, mUpdateCallback);
}
}
}
private void onRoomDirectoryVisibilityPreferenceChanged() {
String visibility;
if((null == mRoom) || (null == mRoomDirectoryVisibilitySwitch)) {
Log.w(LOG_TAG,"## onRoomDirectoryVisibilityPreferenceChanged(): not processed due to invalid parameters");
visibility = null;
} else if(mRoomDirectoryVisibilitySwitch.isChecked()) {
visibility = RoomState.DIRECTORY_VISIBILITY_PUBLIC;
} else {
visibility = RoomState.DIRECTORY_VISIBILITY_PRIVATE;
}
if(null != visibility) {
Log.d(LOG_TAG, "## onRoomDirectoryVisibilityPreferenceChanged(): directory visibility set to "+visibility);
displayLoadingView();
mRoom.updateDirectoryVisibility(visibility, mUpdateCallback);
}
}
/**
* Action when enabling / disabling the rooms notifications.
*/
private void onRoomMuteNotificationsPreferenceChanged(){
// sanity check
if((null == mRoom) || (null == mBingRulesManager) || (null == mRoomMuteNotificationsSwitch)){
return;
}
// get new and previous values
boolean isNotificationsMuted = mRoomMuteNotificationsSwitch.isChecked();
boolean previousValue = mBingRulesManager.isRoomNotificationsDisabled(mRoom);
// update only, if values are different
if(isNotificationsMuted != previousValue) {
displayLoadingView();
mBingRulesManager.muteRoomNotifications(mRoom, isNotificationsMuted, new BingRulesManager.onBingRuleUpdateListener() {
@Override
public void onBingRuleUpdateSuccess() {
Log.d(LOG_TAG, "##onRoomMuteNotificationsPreferenceChanged(): update succeed");
hideLoadingView(UPDATE_UI);
}
@Override
public void onBingRuleUpdateFailure(String errorMessage) {
Log.w(LOG_TAG, "##onRoomMuteNotificationsPreferenceChanged(): BingRuleUpdateFailure");
hideLoadingView(DO_NOT_UPDATE_UI);
}
});
}
}
/**
* Action when updating the room name.
*/
private void onRoomNamePreferenceChanged(){
// sanity check
if((null == mRoom) || (null == mSession) || (null == mRoomNameEditTxt)){
return;
}
// get new and previous values
String previousName = mRoom.getLiveState().name;
String newName = mRoomNameEditTxt.getText();
// update only, if values are different
if (!TextUtils.equals(previousName, newName)) {
displayLoadingView();
Log.d(LOG_TAG, "##onRoomNamePreferenceChanged to " + newName);
mRoom.updateName(newName, mUpdateCallback);
}
}
/**
* Action when updating the room topic.
*/
private void onRoomTopicPreferenceChanged() {
// sanity check
if(null == mRoom){
return;
}
// get new and previous values
String previousTopic = mRoom.getTopic();
String newTopic = mRoomTopicEditTxt.getText();
// update only, if values are different
if (!TextUtils.equals(previousTopic, newTopic)) {
displayLoadingView();
Log.d(LOG_TAG, "## update topic to " + newTopic);
mRoom.updateTopic(newTopic, mUpdateCallback);
}
}
/**
* Update the room avatar.
* Start the camera activity to take the avatar picture.
*/
private void onRoomAvatarPreferenceChanged() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(getActivity(), VectorMediasPickerActivity.class);
intent.putExtra(VectorMediasPickerActivity.EXTRA_AVATAR_MODE, true);
startActivityForResult(intent, REQ_CODE_UPDATE_ROOM_AVATAR);
}
});
}
/**
* Process the result of the room avatar picture.
*
* @param aRequestCode request ID
* @param aResultCode request status code
* @param aData result data
*/
@Override
public void onActivityResult(int aRequestCode, int aResultCode, final Intent aData) {
super.onActivityResult(aRequestCode, aResultCode, aData);
if (REQ_CODE_UPDATE_ROOM_AVATAR == aRequestCode) {
onActivityResultRoomAvatarUpdate(aResultCode, aData);
}
}
/**
* Update the avatar from the data provided the medias picker.
* @param aResultCode the result code.
* @param aData the provided data.
*/
private void onActivityResultRoomAvatarUpdate(int aResultCode, final Intent aData) {
// sanity check
if(null == mSession){
return;
}
if (aResultCode == Activity.RESULT_OK) {
Uri thumbnailUri = VectorUtils.getThumbnailUriFromIntent(getActivity(), aData, mSession.getMediasCache());
if (null != thumbnailUri) {
displayLoadingView();
// save the bitmap URL on the server
ResourceUtils.Resource resource = ResourceUtils.openResource(getActivity(), thumbnailUri, null);
if(null != resource) {
mSession.getContentManager().uploadContent(resource.mContentStream, null, resource.mMimeType, null, new ContentManager.UploadCallback() {
@Override
public void onUploadStart(String uploadId) {
}
@Override
public void onUploadProgress(String anUploadId, int percentageProgress) {
}
@Override
public void onUploadComplete(final String anUploadId, final ContentResponse uploadResponse, final int serverResponseCode, final String serverErrorMessage) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if ((null != uploadResponse) && (null != uploadResponse.contentUri)) {
Log.d(LOG_TAG, "The avatar has been uploaded, update the room avatar");
mRoom.updateAvatarUrl(uploadResponse.contentUri, mUpdateCallback);
} else {
Log.e(LOG_TAG, "Fail to upload the avatar");
hideLoadingView(DO_NOT_UPDATE_UI);
}
}
});
}
});
}
}
}
}
/**
* Display the loading view in the parent activity layout.
* This view is disabled/enabled to achieve a waiting screen.
*/
private void displayLoadingView() {
Activity parentActivity = getActivity();
if(null != parentActivity) {
parentActivity.runOnUiThread(new Runnable() {
public void run() {
// disable the fragment container view to disable preferences access
//enablePreferenceWidgets(false);
// disable preference screen during server updates
if(null != mParentFragmentContainerView)
mParentFragmentContainerView.setEnabled(false);
// display the loading progress bar screen
if (null != mParentLoadingView) {
mParentLoadingView.setVisibility(View.VISIBLE);
}
}
});
}
}
/**
* Hide the loading progress bar screen and
* update the UI if required.
*/
private void hideLoadingView(boolean aIsUiRefreshRequired) {
getActivity().runOnUiThread(new Runnable(){
public void run() {
// enable preference screen after server updates finished
if(null != mParentFragmentContainerView)
mParentFragmentContainerView.setEnabled(true);
// enable preference widgets
//enablePreferenceWidgets(true);
if (null != mParentLoadingView) {
mParentLoadingView.setVisibility(View.GONE);
}
}
});
if(aIsUiRefreshRequired){
updateUiOnUiThread();
}
}
//================================================================================
// Banned members management
//================================================================================
/**
* Refresh the banned users list.
*/
private void refreshBannedMembersList() {
ArrayList<RoomMember> bannedMembers = new ArrayList<>();
Collection<RoomMember> members = mRoom.getMembers();
if (null != members) {
for (RoomMember member : members) {
if (TextUtils.equals(member.membership, RoomMember.MEMBERSHIP_BAN)) {
bannedMembers.add(member);
}
}
}
Collections.sort(bannedMembers, new Comparator<RoomMember>() {
@Override
public int compare(RoomMember m1, RoomMember m2) {
return m1.getUserId().toLowerCase().compareTo(m2.getUserId().toLowerCase());
}
});
PreferenceScreen preferenceScreen = getPreferenceScreen();
preferenceScreen.removePreference(mBannedMembersSettingsCategory);
mBannedMembersSettingsCategory.removeAll();
if (bannedMembers.size() > 0) {
preferenceScreen.addPreference(mBannedMembersSettingsCategory);
for (RoomMember member : bannedMembers) {
VectorCustomActionEditTextPreference preference = new VectorCustomActionEditTextPreference(getActivity());
final String userId = member.getUserId();
preference.setTitle(userId);
preference.setKey(BANNED_PREFERENCE_KEY_BASE + userId);
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
// display the user id in a dialog to make is readable.
new AlertDialog.Builder(VectorApp.getCurrentActivity())
.setMessage(userId)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create()
.show();
return false;
}
});
mBannedMembersSettingsCategory.addPreference(preference);
}
}
}
//================================================================================
// Aliases management
//================================================================================
private final ApiCallback mAliasUpdatesCallback = new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
hideLoadingView(false);
refreshAddresses();
}
});
}
/**
* Error management.
* @param errorMessage the error message
*/
private void onError(final String errorMessage) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
hideLoadingView(false);
refreshAddresses();
}
});
}
@Override
public void onNetworkError(Exception e) {
onError(e.getLocalizedMessage());
}
@Override
public void onMatrixError(MatrixError e) {
onError(e.getLocalizedMessage());
}
@Override
public void onUnexpectedError(Exception e) {
onError(e.getLocalizedMessage());
}
};
/**
* Manage the long click on an address.
* @param roomAlias the room alias.
* @param anchorView the popup menu anchor view.
*/
@SuppressLint("NewApi")
private void onAddressLongClick(final String roomAlias, final View anchorView) {
Context context = getActivity();
final PopupMenu popup = (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) ? new PopupMenu(context, anchorView, Gravity.END) : new PopupMenu(context, anchorView);
popup.getMenuInflater().inflate(R.menu.vector_room_settings_addresses, popup.getMenu());
// force to display the icons
try {
Field[] fields = popup.getClass().getDeclaredFields();
for (Field field : fields) {
if ("mPopup".equals(field.getName())) {
field.setAccessible(true);
Object menuPopupHelper = field.get(popup);
Class<?> classPopupHelper = Class.forName(menuPopupHelper.getClass().getName());
Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class);
setForceIcons.invoke(menuPopupHelper, true);
break;
}
}
} catch (Exception e) {
Log.e(LOG_TAG, "onMessageClick : force to display the icons failed " + e.getLocalizedMessage());
}
Menu menu = popup.getMenu();
if (!canUpdateAliases()) {
menu.findItem(R.id.ic_action_vector_delete_alias).setVisible(false);
}
// display the menu
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(final MenuItem item) {
//
if (item.getItemId() == R.id.ic_action_vector_delete_alias) {
displayLoadingView();
mRoom.removeAlias(roomAlias, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
// when there is only one alias, it becomes the main alias.
if (mRoom.getAliases().size() == 1) {
mRoom.updateCanonicalAlias(mRoom.getAliases().get(0), mAliasUpdatesCallback);
} else {
mAliasUpdatesCallback.onSuccess(info);
}
}
@Override
public void onNetworkError(Exception e) {
mAliasUpdatesCallback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
mAliasUpdatesCallback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
mAliasUpdatesCallback.onUnexpectedError(e);
}
});
} else if (item.getItemId() == R.id.ic_action_vector_room_url) {
VectorUtils.copyToClipboard(getActivity(), VectorUtils.getPermalink(roomAlias, null));
} else {
VectorUtils.copyToClipboard(getActivity(), roomAlias);
}
return true;
}
});
popup.show();
}
/**
* Tells if the current user can updates the room aliases.
* @return true if the user is allowed.
*/
private boolean canUpdateAliases() {
boolean canUpdateAliases = false;
PowerLevels powerLevels = mRoom.getLiveState().getPowerLevels();
if (null != powerLevels) {
int powerLevel = powerLevels.getUserPowerLevel(mSession.getMyUserId());
canUpdateAliases = powerLevel >= powerLevels.minimumPowerLevelForSendingEventAsStateEvent(Event.EVENT_TYPE_STATE_ROOM_ALIASES);
}
return canUpdateAliases;
}
/**
* Refresh the addresses section
*/
private void refreshAddresses() {
final String localSuffix = ":" + mSession.getHomeserverConfig().getHomeserverUri().getHost();
final String canonicalAlias = mRoom.getLiveState().alias;
final ArrayList<String> aliases = new ArrayList<>(mRoom.getAliases());
// remove the displayed preferences
mAddressesSettingsCategory.removeAll();
if (0 == aliases.size()) {
AddressPreference preference = new AddressPreference(getActivity());
preference.setTitle(getString(R.string.room_settings_addresses_no_local_addresses));
preference.setKey(NO_LOCAL_ADDRESS_PREFERENCE_KEY);
mAddressesSettingsCategory.addPreference(preference);
} else {
ArrayList<String> localAliases = new ArrayList<>();
ArrayList<String> remoteAliases = new ArrayList<>();
for(String alias : aliases) {
if (alias.endsWith(localSuffix)) {
localAliases.add(alias);
} else {
remoteAliases.add(alias);
}
}
// the local aliases are displayed first in the list
aliases.clear();
aliases.addAll(localAliases);
aliases.addAll(remoteAliases);
int index = 0;
for (String alias : aliases) {
AddressPreference preference = new AddressPreference(getActivity());
preference.setTitle(alias);
preference.setKey(ADDRESSES_PREFERENCE_KEY_BASE + index);
preference.setMainIconVisible(TextUtils.equals(alias, canonicalAlias));
final String fAlias = alias;
final AddressPreference fAddressPreference = preference;
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
if (TextUtils.equals(fAlias, canonicalAlias)) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.room_settings_addresses_disable_main_address_prompt_msg);
builder.setTitle(R.string.room_settings_addresses_disable_main_address_prompt_title);
builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
displayLoadingView();
mRoom.updateCanonicalAlias(null, mAliasUpdatesCallback);
}
});
builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// nothing
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
displayLoadingView();
mRoom.updateCanonicalAlias(fAlias, mAliasUpdatesCallback);
}
return false;
}
});
preference.setOnPreferenceLongClickListener( new VectorCustomActionEditTextPreference.OnPreferenceLongClickListener() {
@Override
public boolean onPreferenceLongClick(Preference preference) {
onAddressLongClick(fAlias, fAddressPreference.getMainIconView());
return true;
}
});
mAddressesSettingsCategory.addPreference(preference);
index++;
}
}
if (canUpdateAliases()) {
// display the "add addresses" entry
EditTextPreference addAddressPreference = new EditTextPreference(getActivity());
addAddressPreference.setTitle(R.string.room_settings_addresses_add_new_address);
addAddressPreference.setDialogTitle(R.string.room_settings_addresses_add_new_address);
addAddressPreference.setKey(ADD_ADDRESSES_PREFERENCE_KEY);
addAddressPreference.setIcon(getResources().getDrawable(R.drawable.ic_material_add_circle));
addAddressPreference.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String newAddress = ((String) newValue).trim();
// ignore empty alias
if (!TextUtils.isEmpty(newAddress)) {
if (!MXSession.PATTERN_MATRIX_ALIAS.matcher(newAddress).matches()) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.room_settings_addresses_invalid_format_dialog_title);
builder.setMessage(getString(R.string.room_settings_addresses_invalid_format_dialog_body, newAddress));
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else if (aliases.indexOf(newAddress) < 0) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
displayLoadingView();
mRoom.addAlias(newAddress, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
// when there is only one alias, it becomes the main alias.
if (mRoom.getAliases().size() == 1) {
mRoom.updateCanonicalAlias(mRoom.getAliases().get(0), mAliasUpdatesCallback);
} else {
mAliasUpdatesCallback.onSuccess(info);
}
}
@Override
public void onNetworkError(Exception e) {
mAliasUpdatesCallback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
mAliasUpdatesCallback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
mAliasUpdatesCallback.onUnexpectedError(e);
}
});
}
});
}
}
return false;
}
});
mAddressesSettingsCategory.addPreference(addAddressPreference);
}
}
}
| vector/src/main/java/im/vector/fragments/VectorRoomSettingsFragment.java | /*
* Copyright 2016 OpenMarket Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.fragments;
import android.annotation.SuppressLint;
import android.app.Activity;
//
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Build;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
import android.preference.SwitchPreference;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.Toast;
import org.matrix.androidsdk.MXSession;
import org.matrix.androidsdk.data.Room;
import org.matrix.androidsdk.data.RoomAccountData;
import org.matrix.androidsdk.data.RoomState;
import org.matrix.androidsdk.data.RoomTag;
import org.matrix.androidsdk.listeners.IMXNetworkEventListener;
import org.matrix.androidsdk.listeners.MXEventListener;
import org.matrix.androidsdk.rest.callback.ApiCallback;
import org.matrix.androidsdk.rest.model.ContentResponse;
import org.matrix.androidsdk.rest.model.Event;
import org.matrix.androidsdk.rest.model.MatrixError;
import org.matrix.androidsdk.rest.model.PowerLevels;
import org.matrix.androidsdk.rest.model.RoomMember;
import org.matrix.androidsdk.util.BingRulesManager;
import org.matrix.androidsdk.util.ContentManager;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import im.vector.Matrix;
import im.vector.R;
import im.vector.VectorApp;
import im.vector.activity.CommonActivityUtils;
import im.vector.activity.VectorMediasPickerActivity;
import im.vector.preference.AddressPreference;
import im.vector.preference.RoomAvatarPreference;
import im.vector.preference.VectorCustomActionEditTextPreference;
import im.vector.preference.VectorListPreference;
import im.vector.util.ResourceUtils;
import im.vector.util.VectorUtils;
import static android.preference.PreferenceManager.getDefaultSharedPreferences;
public class VectorRoomSettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
// internal constants values
private static final String LOG_TAG = "VectorRoomSetFragment";
private static final boolean UPDATE_UI = true;
private static final boolean DO_NOT_UPDATE_UI = false;
private static final int REQ_CODE_UPDATE_ROOM_AVATAR = 0x10;
// Room access rules values
private static final String ACCESS_RULES_ONLY_PEOPLE_INVITED = "1";
private static final String ACCESS_RULES_ANYONE_WITH_LINK_APART_GUEST = "2";
private static final String ACCESS_RULES_ANYONE_WITH_LINK_INCLUDING_GUEST = "3";
// fragment extra args keys
private static final String EXTRA_MATRIX_ID = "KEY_EXTRA_MATRIX_ID";
private static final String EXTRA_ROOM_ID = "KEY_EXTRA_ROOM_ID";
// preference keys: public API to access preference
private static final String PREF_KEY_ROOM_PHOTO_AVATAR = "roomPhotoAvatar";
private static final String PREF_KEY_ROOM_NAME = "roomNameEditText";
private static final String PREF_KEY_ROOM_TOPIC = "roomTopicEditText";
private static final String PREF_KEY_ROOM_DIRECTORY_VISIBILITY_SWITCH = "roomNameListedInDirectorySwitch";
private static final String PREF_KEY_ROOM_TAG_LIST = "roomTagList";
private static final String PREF_KEY_ROOM_ACCESS_RULES_LIST = "roomAccessRulesList";
private static final String PREF_KEY_ROOM_HISTORY_READABILITY_LIST = "roomReadHistoryRulesList";
private static final String PREF_KEY_ROOM_MUTE_NOTIFICATIONS_SWITCH = "muteNotificationsSwitch";
private static final String PREF_KEY_ROOM_LEAVE = "roomLeave";
private static final String PREF_KEY_ROOM_INTERNAL_ID = "roomInternalId";
private static final String PREF_KEY_ADDRESSES = "addresses";
private static final String PREF_KEY_BANNED = "banned";
private static final String ADDRESSES_PREFERENCE_KEY_BASE = "ADDRESSES_PREFERENCE_KEY_BASE";
private static final String NO_LOCAL_ADDRESS_PREFERENCE_KEY = "NO_LOCAL_ADDRESS_PREFERENCE_KEY";
private static final String ADD_ADDRESSES_PREFERENCE_KEY = "ADD_ADDRESSES_PREFERENCE_KEY";
private static final String BANNED_PREFERENCE_KEY_BASE = "BANNED_PREFERENCE_KEY_BASE";
private static final String UNKNOWN_VALUE = "UNKNOWN_VALUE";
// business code
private MXSession mSession;
private Room mRoom;
private BingRulesManager mBingRulesManager;
private boolean mIsUiUpdateSkipped;
// addresses
private PreferenceCategory mAddressesSettingsCategory;
// banned members
private PreferenceCategory mBannedMembersSettingsCategory;
// UI elements
private RoomAvatarPreference mRoomPhotoAvatar;
private EditTextPreference mRoomNameEditTxt;
private EditTextPreference mRoomTopicEditTxt;
private SwitchPreference mRoomDirectoryVisibilitySwitch;
private SwitchPreference mRoomMuteNotificationsSwitch;
private ListPreference mRoomTagListPreference;
private VectorListPreference mRoomAccessRulesListPreference;
private ListPreference mRoomHistoryReadabilityRulesListPreference;
private View mParentLoadingView;
private View mParentFragmentContainerView;
// disable some updates if there is
private final IMXNetworkEventListener mNetworkListener = new IMXNetworkEventListener() {
@Override
public void onNetworkConnectionUpdate(boolean isConnected) {
updateUi();
}
};
// update field listener
private final ApiCallback<Void> mUpdateCallback = new ApiCallback<Void>() {
/**
* refresh the fragment.
* @param mode true to force refresh
*/
private void onDone(final String message, final boolean mode) {
if (null != getActivity()) {
if (!TextUtils.isEmpty(message)) {
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
}
// ensure that the response has been sent in the UI thread
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
hideLoadingView(mode);
}
});
}
}
@Override
public void onSuccess(Void info) {
Log.d(LOG_TAG, "##update succeed");
onDone(null, UPDATE_UI);
}
@Override
public void onNetworkError(Exception e) {
Log.w(LOG_TAG, "##NetworkError " + e.getLocalizedMessage());
onDone(e.getLocalizedMessage(), DO_NOT_UPDATE_UI);
}
@Override
public void onMatrixError(MatrixError e) {
Log.w(LOG_TAG, "##MatrixError " + e.getLocalizedMessage());
onDone(e.getLocalizedMessage(), DO_NOT_UPDATE_UI);
}
@Override
public void onUnexpectedError(Exception e) {
Log.w(LOG_TAG, "##UnexpectedError " + e.getLocalizedMessage());
onDone(e.getLocalizedMessage(), DO_NOT_UPDATE_UI);
}
};
// MX system events listener
private final MXEventListener mEventListener = new MXEventListener() {
@Override
public void onLiveEvent(final Event event, RoomState roomState) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// The various events that could possibly change the fragment items
if (Event.EVENT_TYPE_STATE_ROOM_NAME.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_ALIASES.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_MEMBER.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_AVATAR.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_TOPIC.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_POWER_LEVELS.equals(event.type)
|| Event.EVENT_TYPE_STATE_HISTORY_VISIBILITY.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_JOIN_RULES.equals(event.type) // room access rules
|| Event.EVENT_TYPE_STATE_ROOM_GUEST_ACCESS.equals(event.type) // room access rules
)
{
Log.d(LOG_TAG, "## onLiveEvent() event = " + event.type);
updateUi();
}
// aliases
if (Event.EVENT_TYPE_STATE_CANONICAL_ALIAS.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_ALIASES.equals(event.type)
|| Event.EVENT_TYPE_STATE_ROOM_POWER_LEVELS.equals(event.type)
) {
Log.d(LOG_TAG, "## onLiveEvent() refresh the addresses list");
refreshAddresses();
}
if (Event.EVENT_TYPE_STATE_ROOM_MEMBER.equals(event.type)) {
Log.d(LOG_TAG, "## onLiveEvent() refresh the banned members list");
refreshBannedMembersList();
}
}
});
}
@Override
public void onRoomFlush(String roomId) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateUi();
}
});
}
@Override
public void onRoomTagEvent(String roomId) {
Log.d(LOG_TAG, "## onRoomTagEvent()");
updateUi();
}
@Override
public void onBingRulesUpdate() {
updateUi();
}
};
public static VectorRoomSettingsFragment newInstance(String aMatrixId,String aRoomId) {
VectorRoomSettingsFragment theFragment = new VectorRoomSettingsFragment();
Bundle args = new Bundle();
args.putString(EXTRA_MATRIX_ID, aMatrixId);
args.putString(EXTRA_ROOM_ID, aRoomId);
theFragment.setArguments(args);
return theFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(LOG_TAG,"## onCreate() IN");
// retrieve fragment extras
String matrixId = getArguments().getString(EXTRA_MATRIX_ID);
String roomId = getArguments().getString(EXTRA_ROOM_ID);
if(TextUtils.isEmpty(matrixId) || TextUtils.isEmpty(roomId)){
Log.e(LOG_TAG, "## onCreate(): fragment extras (MatrixId or RoomId) are missing");
getActivity().finish();
}
else {
mSession = Matrix.getInstance(getActivity()).getSession(matrixId);
if (null != mSession) {
mRoom = mSession.getDataHandler().getRoom(roomId);
mBingRulesManager = mSession.getDataHandler().getBingRulesManager();
}
if (null == mRoom) {
Log.e(LOG_TAG, "## onCreate(): unable to retrieve Room object");
getActivity().finish();
}
}
// load preference xml file
addPreferencesFromResource(R.xml.vector_room_settings_preferences);
// init preference fields
mRoomPhotoAvatar = (RoomAvatarPreference)findPreference(PREF_KEY_ROOM_PHOTO_AVATAR);
mRoomNameEditTxt = (EditTextPreference)findPreference(PREF_KEY_ROOM_NAME);
mRoomTopicEditTxt = (EditTextPreference)findPreference(PREF_KEY_ROOM_TOPIC);
mRoomDirectoryVisibilitySwitch = (SwitchPreference)findPreference(PREF_KEY_ROOM_DIRECTORY_VISIBILITY_SWITCH);
mRoomMuteNotificationsSwitch = (SwitchPreference)findPreference(PREF_KEY_ROOM_MUTE_NOTIFICATIONS_SWITCH);
mRoomTagListPreference = (ListPreference)findPreference(PREF_KEY_ROOM_TAG_LIST);
mRoomAccessRulesListPreference = (VectorListPreference)findPreference(PREF_KEY_ROOM_ACCESS_RULES_LIST);
mRoomHistoryReadabilityRulesListPreference = (ListPreference)findPreference(PREF_KEY_ROOM_HISTORY_READABILITY_LIST);
mAddressesSettingsCategory = (PreferenceCategory)getPreferenceManager().findPreference(PREF_KEY_ADDRESSES);
mBannedMembersSettingsCategory = (PreferenceCategory)getPreferenceManager().findPreference(PREF_KEY_BANNED);
mRoomAccessRulesListPreference.setOnPreferenceWarningIconClickListener(new VectorListPreference.OnPreferenceWarningIconClickListener() {
@Override
public void onWarningIconClick(Preference preference) {
displayAccessRoomWarning();
}
});
// display the room Id.
EditTextPreference roomInternalIdPreference = (EditTextPreference)findPreference(PREF_KEY_ROOM_INTERNAL_ID);
if (null != roomInternalIdPreference) {
roomInternalIdPreference.setSummary(mRoom.getRoomId());
roomInternalIdPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
VectorUtils.copyToClipboard(getActivity(), mRoom.getRoomId());
return false;
}
});
}
// leave room
EditTextPreference leaveRoomPreference = (EditTextPreference)findPreference(PREF_KEY_ROOM_LEAVE);
if (null != leaveRoomPreference) {
leaveRoomPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
// leave room
new AlertDialog.Builder(VectorApp.getCurrentActivity())
.setTitle(R.string.room_participants_leave_prompt_title)
.setMessage(getActivity().getString(R.string.room_participants_leave_prompt_msg))
.setPositiveButton(R.string.leave, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
displayLoadingView();
mRoom.leave(new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
if (null != getActivity()) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
getActivity().finish();
}
});
}
}
private void onError(final String errorMessage) {
if (null != getActivity()) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
hideLoadingView(true);
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public void onNetworkError(Exception e) {
onError(e.getLocalizedMessage());
}
@Override
public void onMatrixError(MatrixError e) {
onError(e.getLocalizedMessage());
}
@Override
public void onUnexpectedError(Exception e) {
onError(e.getLocalizedMessage());
}
});
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create()
.show();
return true;
}
});
}
// init the room avatar: session and room
mRoomPhotoAvatar.setConfiguration(mSession, mRoom);
mRoomPhotoAvatar.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
if ((null != mRoomPhotoAvatar) && mRoomPhotoAvatar.isEnabled()) {
onRoomAvatarPreferenceChanged();
return true; //True if the click was handled.
} else
return false;
}
});
// listen to preference changes
enableSharedPreferenceListener(true);
setRetainInstance(true);
}
/**
* This method expects a view with the id "settings_loading_layout",
* that is present in the parent activity layout.
* @param view fragment view
* @param savedInstanceState bundle instance state
*/
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// retrieve the loading screen in the parent view
View parent = getView();
if (null == mParentLoadingView) {
while ((null != parent) && (null == mParentLoadingView)) {
mParentLoadingView = parent.findViewById(R.id.settings_loading_layout);
parent = (View) parent.getParent();
}
}
// retrieve the parent fragment container view to disable access to the settings
// while the loading screen is enabled
parent = getView();
if (null == mParentFragmentContainerView) {
while ((null != parent) && (null == mParentFragmentContainerView)) {
mParentFragmentContainerView = parent.findViewById(R.id.room_details_fragment_container);
parent = (View) parent.getParent();
}
}
}
@Override
public void onPause() {
super.onPause();
if (null != mRoom) {
Matrix.getInstance(getActivity()).removeNetworkEventListener(mNetworkListener);
mRoom.removeEventListener(mEventListener);
}
// remove preference changes listener
enableSharedPreferenceListener(false);
}
@Override
public void onResume() {
super.onResume();
if (null != mRoom) {
Matrix.getInstance(getActivity()).addNetworkEventListener(mNetworkListener);
mRoom.addEventListener(mEventListener);
updateUi();
updateRoomDirectoryVisibilityAsync();
refreshAddresses();
refreshBannedMembersList();
}
}
/**
* Enable the preference listener according to the aIsListenerEnabled value.
* @param aIsListenerEnabled true to enable the listener, false otherwise
*/
private void enableSharedPreferenceListener(boolean aIsListenerEnabled) {
Log.d(LOG_TAG, "## enableSharedPreferenceListener(): aIsListenerEnabled=" + aIsListenerEnabled);
mIsUiUpdateSkipped = !aIsListenerEnabled;
try {
//SharedPreferences prefMgr = getActivity().getSharedPreferences("VectorSettingsFile", Context.MODE_PRIVATE);
SharedPreferences prefMgr = getDefaultSharedPreferences(getActivity());
if (aIsListenerEnabled) {
prefMgr.registerOnSharedPreferenceChangeListener(this);
} else {
prefMgr.unregisterOnSharedPreferenceChangeListener(this);
}
} catch (Exception ex){
Log.e(LOG_TAG, "## enableSharedPreferenceListener(): Exception Msg="+ex.getMessage());
}
}
/**
* Update the preferences according to the power levels and its values.
* To prevent the preference change listener to be triggered, the listener
* is removed when the preferences are updated.
*/
private void updateUi(){
// configure the preferences that are allowed to be modified by the user
updatePreferenceAccessFromPowerLevel();
// need to run on the UI thread to be taken into account
// when updatePreferenceUiValues() will be performed
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// disable listener during preferences update, otherwise it will
// be seen as a user action..
enableSharedPreferenceListener(false);
}
});
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// set settings UI values
updatePreferenceUiValues();
// re enable preferences listener..
enableSharedPreferenceListener(true);
}
});
}
/**
* delayed refresh the preferences items.
*/
private void updateUiOnUiThread() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateUi();
}
});
}
/**
* Retrieve the room visibility directory value and update the corresponding preference.
* This is an asynchronous request: the call-back response will be processed on the UI thread.
* For now, the room visibility directory value is not provided in the sync API, a specific request
* must performed.
*/
private void updateRoomDirectoryVisibilityAsync() {
if((null == mRoom) || (null == mRoomDirectoryVisibilitySwitch)) {
Log.w(LOG_TAG,"## updateRoomDirectoryVisibilityUi(): not processed due to invalid parameters");
} else {
displayLoadingView();
// server request: is the room listed in the room directory?
mRoom.getDirectoryVisibility(mRoom.getRoomId(), new ApiCallback<String>() {
private void handleResponseOnUiThread(final String aVisibilityValue){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// only stop loading screen and do not update UI since the
// update is done here below..
hideLoadingView(DO_NOT_UPDATE_UI);
// set checked status
// Note: the preference listener is disabled when the switch is updated, otherwise it will be seen
// as a user action on the preference
boolean isChecked = RoomState.DIRECTORY_VISIBILITY_PUBLIC.equals(aVisibilityValue);
enableSharedPreferenceListener(false);
mRoomDirectoryVisibilitySwitch.setChecked(isChecked);
enableSharedPreferenceListener(true);
}
});
}
@Override
public void onSuccess(String visibility) {
handleResponseOnUiThread(visibility);
}
@Override
public void onNetworkError(Exception e) {
Log.w(LOG_TAG, "## getDirectoryVisibility(): onNetworkError Msg="+e.getLocalizedMessage());
handleResponseOnUiThread(null);
}
@Override
public void onMatrixError(MatrixError matrixError) {
Log.w(LOG_TAG, "## getDirectoryVisibility(): onMatrixError Msg="+matrixError.getLocalizedMessage());
handleResponseOnUiThread(null);
}
@Override
public void onUnexpectedError(Exception e) {
Log.w(LOG_TAG, "## getDirectoryVisibility(): onUnexpectedError Msg="+e.getLocalizedMessage());
handleResponseOnUiThread(null);
}
});
}
}
/**
* Display the access room warning.
*/
private void displayAccessRoomWarning () {
Toast.makeText(getActivity(), R.string.room_settings_room_access_warning, Toast.LENGTH_SHORT).show();
}
/**
* Enable / disable preferences according to the power levels.
*/
private void updatePreferenceAccessFromPowerLevel(){
boolean canUpdateAvatar = false;
boolean canUpdateName = false;
boolean canUpdateTopic = false;
boolean isAdmin = false;
boolean isConnected = Matrix.getInstance(getActivity()).isConnected();
// cannot refresh if there is no valid session / room
if ((null != mRoom) && (null != mSession)) {
PowerLevels powerLevels = mRoom.getLiveState().getPowerLevels();
if (null != powerLevels) {
int powerLevel = powerLevels.getUserPowerLevel(mSession.getMyUserId());
canUpdateAvatar = powerLevel >= powerLevels.minimumPowerLevelForSendingEventAsStateEvent(Event.EVENT_TYPE_STATE_ROOM_AVATAR);
canUpdateName = powerLevel >= powerLevels.minimumPowerLevelForSendingEventAsStateEvent(Event.EVENT_TYPE_STATE_ROOM_NAME);
canUpdateTopic = powerLevel >= powerLevels.minimumPowerLevelForSendingEventAsStateEvent(Event.EVENT_TYPE_STATE_ROOM_TOPIC);
isAdmin = (powerLevel >= CommonActivityUtils.UTILS_POWER_LEVEL_ADMIN);
}
}
else {
Log.w(LOG_TAG, "## updatePreferenceAccessFromPowerLevel(): session or room may be missing");
}
if(null != mRoomPhotoAvatar)
mRoomPhotoAvatar.setEnabled(canUpdateAvatar && isConnected);
if(null != mRoomNameEditTxt)
mRoomNameEditTxt.setEnabled(canUpdateName && isConnected);
if(null != mRoomTopicEditTxt)
mRoomTopicEditTxt.setEnabled(canUpdateTopic && isConnected);
// room present in the directory list: admin only
if(null != mRoomDirectoryVisibilitySwitch)
mRoomDirectoryVisibilitySwitch.setEnabled(isAdmin && isConnected);
// room notification mute setting: no power condition
if(null != mRoomMuteNotificationsSwitch)
mRoomMuteNotificationsSwitch.setEnabled(isConnected);
// room tagging: no power condition
if(null != mRoomTagListPreference)
mRoomTagListPreference.setEnabled(isConnected);
// room access rules: admin only
if(null != mRoomAccessRulesListPreference) {
mRoomAccessRulesListPreference.setEnabled(isAdmin && isConnected);
mRoomAccessRulesListPreference.setWarningIconVisible((0 == mRoom.getAliases().size()) && !TextUtils.equals(RoomState.JOIN_RULE_INVITE, mRoom.getLiveState().join_rule));
}
// room read history: admin only
if(null != mRoomHistoryReadabilityRulesListPreference)
mRoomHistoryReadabilityRulesListPreference.setEnabled(isAdmin && isConnected);
}
/**
* Update the UI preference from the values taken from
* the SDK layer.
*/
private void updatePreferenceUiValues() {
String value;
String summary;
Resources resources;
if ((null == mSession) || (null == mRoom)){
Log.w(LOG_TAG, "## updatePreferenceUiValues(): session or room may be missing");
return;
}
if(null != mRoomPhotoAvatar){
mRoomPhotoAvatar.refreshAvatar();
}
// update the room name preference
if(null != mRoomNameEditTxt) {
value = mRoom.getLiveState().name;
mRoomNameEditTxt.setSummary(value);
mRoomNameEditTxt.setText(value);
}
// update the room topic preference
if(null != mRoomTopicEditTxt) {
value = mRoom.getTopic();
mRoomTopicEditTxt.setSummary(value);
mRoomTopicEditTxt.setText(value);
}
// update the mute notifications preference
if(null != mRoomMuteNotificationsSwitch) {
boolean isChecked = mBingRulesManager.isRoomNotificationsDisabled(mRoom);
mRoomMuteNotificationsSwitch.setChecked(isChecked);
}
// update room directory visibility
// if(null != mRoomDirectoryVisibilitySwitch) {
// boolean isRoomPublic = TextUtils.equals(mRoom.getVisibility()/*getLiveState().visibility ou .isPublic()*/, RoomState.DIRECTORY_VISIBILITY_PUBLIC);
// if(isRoomPublic !isRoomPublic= mRoomDirectoryVisibilitySwitch.isChecked())
// mRoomDirectoryVisibilitySwitch.setChecked(isRoomPublic);
// }
// check if fragment is added to its Activity before calling getResources().
// getResources() may throw an exception ".. not attached to Activity"
if (!isAdded()){
Log.e(LOG_TAG,"## updatePreferenceUiValues(): fragment not added to Activity - isAdded()=false");
return;
} else {
// in some weird cases, even if isAdded() = true, sometimes getResources() may fail,
// so we need to catch the exception
try {
resources = getResources();
} catch (Exception ex) {
Log.e(LOG_TAG,"## updatePreferenceUiValues(): Exception in getResources() - Msg="+ex.getLocalizedMessage());
return;
}
}
// room guest access rules
if((null != mRoomAccessRulesListPreference)&& (null != resources)) {
String joinRule = mRoom.getLiveState().join_rule;
String guestAccessRule = mRoom.getLiveState().getGuestAccess();
if(RoomState.JOIN_RULE_INVITE.equals(joinRule)/* && RoomState.GUEST_ACCESS_CAN_JOIN.equals(guestAccessRule)*/) {
// "Only people who have been invited" requires: {join_rule: "invite"} and {guest_access: "can_join"}
value = ACCESS_RULES_ONLY_PEOPLE_INVITED;
summary = resources.getString(R.string.room_settings_room_access_entry_only_invited);
} else if(RoomState.JOIN_RULE_PUBLIC.equals(joinRule) && RoomState.GUEST_ACCESS_FORBIDDEN.equals(guestAccessRule)) {
// "Anyone who knows the room's link, apart from guests" requires: {join_rule: "public"} and {guest_access: "forbidden"}
value = ACCESS_RULES_ANYONE_WITH_LINK_APART_GUEST;
summary = resources.getString(R.string.room_settings_room_access_entry_anyone_with_link_apart_guest);
} else if(RoomState.JOIN_RULE_PUBLIC.equals(joinRule) && RoomState.GUEST_ACCESS_CAN_JOIN.equals(guestAccessRule)) {
// "Anyone who knows the room's link, including guests" requires: {join_rule: "public"} and {guest_access: "can_join"}
value = ACCESS_RULES_ANYONE_WITH_LINK_INCLUDING_GUEST;
summary = resources.getString(R.string.room_settings_room_access_entry_anyone_with_link_including_guest);
} else {
// unknown combination value
value = null;
summary = null;
Log.w(LOG_TAG, "## updatePreferenceUiValues(): unknown room access configuration joinRule=" + joinRule + " and guestAccessRule="+guestAccessRule);
}
if(null != value){
mRoomAccessRulesListPreference.setValue(value);
mRoomAccessRulesListPreference.setSummary(summary);
} else {
mRoomHistoryReadabilityRulesListPreference.setValue(UNKNOWN_VALUE);
mRoomHistoryReadabilityRulesListPreference.setSummary("");
}
}
// update the room tag preference
if(null != mRoomTagListPreference) {
if(null != mRoom.getAccountData() && (null != resources)) {
//Set<String> customTagList = mRoom.getAccountData().getKeys();
if (null != mRoom.getAccountData().roomTag(RoomTag.ROOM_TAG_FAVOURITE)) {
value = resources.getString(R.string.room_settings_tag_pref_entry_value_favourite);
summary = resources.getString(R.string.room_settings_tag_pref_entry_favourite);
} else if (null != mRoom.getAccountData().roomTag(RoomTag.ROOM_TAG_LOW_PRIORITY)) {
value = resources.getString(R.string.room_settings_tag_pref_entry_value_low_priority);
summary = resources.getString(R.string.room_settings_tag_pref_entry_low_priority);
/* For further use in case of multiple tags support
} else if(!mRoom.getAccountData().getKeys().isEmpty()) {
for(String tag : customTagList){
summary += (!summary.isEmpty()?" ":"") + tag;
}*/
} else {
// no tag associated to the room
value = resources.getString(R.string.room_settings_tag_pref_entry_value_none);
summary = Html.fromHtml("<i>"+getResources().getString(R.string.room_settings_tag_pref_no_tag)+ "</i>").toString();
}
mRoomTagListPreference.setValue(value);
mRoomTagListPreference.setSummary(summary);
}
}
// room history readability
if (null != mRoomHistoryReadabilityRulesListPreference) {
value = mRoom.getLiveState().getHistoryVisibility();
summary = null;
if((null != value) && (null != resources)) {
// get summary value
if (value.equals(resources.getString(R.string.room_settings_read_history_entry_value_anyone))) {
summary = resources.getString(R.string.room_settings_read_history_entry_anyone);
} else if (value.equals(resources.getString(R.string.room_settings_read_history_entry_value_members_only_option_time_shared))) {
summary = resources.getString(R.string.room_settings_read_history_entry_members_only_option_time_shared);
} else if (value.equals(resources.getString(R.string.room_settings_read_history_entry_value_members_only_invited))) {
summary = resources.getString(R.string.room_settings_read_history_entry_members_only_invited);
} else if (value.equals(resources.getString(R.string.room_settings_read_history_entry_value_members_only_joined))) {
summary = resources.getString(R.string.room_settings_read_history_entry_members_only_joined);
} else {
// unknown value
Log.w(LOG_TAG, "## updatePreferenceUiValues(): unknown room read history value=" + value);
summary = null;
}
}
if(null != summary) {
mRoomHistoryReadabilityRulesListPreference.setValue(value);
mRoomHistoryReadabilityRulesListPreference.setSummary(summary);
} else {
mRoomHistoryReadabilityRulesListPreference.setValue(UNKNOWN_VALUE);
mRoomHistoryReadabilityRulesListPreference.setSummary("");
}
}
}
// OnSharedPreferenceChangeListener implementation
/**
* Main entry point handler for any preference changes. For each setting a dedicated handler is
* called to process the setting.
*
* @param aSharedPreferences preference instance
* @param aKey preference key as it is defined in the XML
*/
@Override
public void onSharedPreferenceChanged(SharedPreferences aSharedPreferences, String aKey) {
if(mIsUiUpdateSkipped){
Log.d(LOG_TAG,"## onSharedPreferenceChanged(): Skipped");
return;
}
if (aKey.equals(PREF_KEY_ROOM_PHOTO_AVATAR)) {
// unused flow: onSharedPreferenceChanged not triggered for room avatar photo
onRoomAvatarPreferenceChanged();
}
else if(aKey.equals(PREF_KEY_ROOM_NAME)) {
onRoomNamePreferenceChanged();
}
else if(aKey.equals(PREF_KEY_ROOM_TOPIC)) {
onRoomTopicPreferenceChanged();
} else if(aKey.equals(PREF_KEY_ROOM_MUTE_NOTIFICATIONS_SWITCH)) {
onRoomMuteNotificationsPreferenceChanged();
}
else if(aKey.equals(PREF_KEY_ROOM_DIRECTORY_VISIBILITY_SWITCH)) {
onRoomDirectoryVisibilityPreferenceChanged(); // TBT
}
else if(aKey.equals(PREF_KEY_ROOM_TAG_LIST)) {
onRoomTagPreferenceChanged(); // TBT
}
else if(aKey.equals(PREF_KEY_ROOM_ACCESS_RULES_LIST)) {
onRoomAccessPreferenceChanged();
}
else if(aKey.equals(PREF_KEY_ROOM_HISTORY_READABILITY_LIST)) {
onRoomHistoryReadabilityPreferenceChanged(); // TBT
}
else {
Log.w(LOG_TAG,"## onSharedPreferenceChanged(): unknown aKey = "+ aKey);
}
}
/**
* The room history readability has been updated.
*/
private void onRoomHistoryReadabilityPreferenceChanged() {
// sanity check
if ((null == mRoom) || (null == mRoomHistoryReadabilityRulesListPreference)) {
Log.w(LOG_TAG,"## onRoomHistoryReadabilityPreferenceChanged(): not processed due to invalid parameters");
return;
}
// get new and previous values
String previousValue = mRoom.getLiveState().history_visibility;
String newValue = mRoomHistoryReadabilityRulesListPreference.getValue();
if(!TextUtils.equals(newValue, previousValue)) {
String historyVisibility;
if(newValue.equals(getResources().getString(R.string.room_settings_read_history_entry_value_anyone))) {
historyVisibility = RoomState.HISTORY_VISIBILITY_WORLD_READABLE;
} else if(newValue.equals(getResources().getString(R.string.room_settings_read_history_entry_value_members_only_option_time_shared))) {
historyVisibility = RoomState.HISTORY_VISIBILITY_SHARED;
} else if(newValue.equals(getResources().getString(R.string.room_settings_read_history_entry_value_members_only_invited))) {
historyVisibility = RoomState.HISTORY_VISIBILITY_INVITED;
} else if(newValue.equals(getResources().getString(R.string.room_settings_read_history_entry_value_members_only_joined))) {
historyVisibility = RoomState.HISTORY_VISIBILITY_JOINED;
} else {
// unknown value
Log.w(LOG_TAG,"## onRoomHistoryReadabilityPreferenceChanged(): unknown value:"+newValue);
historyVisibility = null;
}
if(null != historyVisibility) {
displayLoadingView();
mRoom.updateHistoryVisibility(historyVisibility, mUpdateCallback);
}
}
}
private void onRoomTagPreferenceChanged() {
boolean isSupportedTag = true;
// sanity check
if((null == mRoom) || (null == mRoomTagListPreference)) {
Log.w(LOG_TAG,"## onRoomTagPreferenceChanged(): not processed due to invalid parameters");
} else {
String newTag = mRoomTagListPreference.getValue();
String currentTag = null;
Double tagOrder = 0.0;
// retrieve the tag from the room info
RoomAccountData accountData = mRoom.getAccountData();
if ((null != accountData) && accountData.hasTags()) {
currentTag = accountData.getKeys().iterator().next();
}
if(!newTag.equals(currentTag)) {
if(newTag.equals(getResources().getString(R.string.room_settings_tag_pref_entry_value_favourite))) {
newTag = RoomTag.ROOM_TAG_FAVOURITE;
} else if(newTag.equals(getResources().getString(R.string.room_settings_tag_pref_entry_value_low_priority))) {
newTag = RoomTag.ROOM_TAG_LOW_PRIORITY;
} else if(newTag.equals(getResources().getString(R.string.room_settings_tag_pref_entry_value_none))) {
newTag = null;
} else {
// unknown tag.. very unlikely
isSupportedTag = false;
Log.w(LOG_TAG, "## onRoomTagPreferenceChanged() not supported tag = " + newTag);
}
}
if(isSupportedTag) {
displayLoadingView();
mRoom.replaceTag(currentTag, newTag, tagOrder, mUpdateCallback);
}
}
}
private void onRoomAccessPreferenceChanged() {
if((null == mRoom) || (null == mRoomAccessRulesListPreference)) {
Log.w(LOG_TAG,"## onRoomAccessPreferenceChanged(): not processed due to invalid parameters");
} else {
String joinRuleToApply = null;
String guestAccessRuleToApply = null;
// get new and previous values
String previousJoinRule = mRoom.getLiveState().join_rule;
String previousGuestAccessRule = mRoom.getLiveState().getGuestAccess();
String newValue = mRoomAccessRulesListPreference.getValue();
if(ACCESS_RULES_ONLY_PEOPLE_INVITED.equals(newValue)) {
// requires: {join_rule: "invite"} and {guest_access: "can_join"}
joinRuleToApply = !RoomState.JOIN_RULE_INVITE.equals(previousJoinRule)?RoomState.JOIN_RULE_INVITE:null;
guestAccessRuleToApply = !RoomState.GUEST_ACCESS_CAN_JOIN.equals(previousGuestAccessRule)?RoomState.GUEST_ACCESS_CAN_JOIN:null;
} else if(ACCESS_RULES_ANYONE_WITH_LINK_APART_GUEST.equals(newValue)) {
// requires: {join_rule: "public"} and {guest_access: "forbidden"}
joinRuleToApply = !RoomState.JOIN_RULE_PUBLIC.equals(previousJoinRule)?RoomState.JOIN_RULE_PUBLIC:null;
guestAccessRuleToApply = !RoomState.GUEST_ACCESS_FORBIDDEN.equals(previousGuestAccessRule)?RoomState.GUEST_ACCESS_FORBIDDEN:null;
if (0 == mRoom.getAliases().size()) {
displayAccessRoomWarning();
}
} else if(ACCESS_RULES_ANYONE_WITH_LINK_INCLUDING_GUEST.equals(newValue)) {
// requires: {join_rule: "public"} and {guest_access: "can_join"}
joinRuleToApply = !RoomState.JOIN_RULE_PUBLIC.equals(previousJoinRule)?RoomState.JOIN_RULE_PUBLIC:null;
guestAccessRuleToApply = !RoomState.GUEST_ACCESS_CAN_JOIN.equals(previousGuestAccessRule)?RoomState.GUEST_ACCESS_CAN_JOIN:null;
if (0 == mRoom.getAliases().size()) {
displayAccessRoomWarning();
}
} else {
// unknown value
Log.d(LOG_TAG,"## onRoomAccessPreferenceChanged(): unknown selected value = "+newValue);
}
if(null != joinRuleToApply) {
displayLoadingView();
mRoom.updateJoinRules(joinRuleToApply, mUpdateCallback);
}
if(null != guestAccessRuleToApply) {
displayLoadingView();
mRoom.updateGuestAccess(guestAccessRuleToApply, mUpdateCallback);
}
}
}
private void onRoomDirectoryVisibilityPreferenceChanged() {
String visibility;
if((null == mRoom) || (null == mRoomDirectoryVisibilitySwitch)) {
Log.w(LOG_TAG,"## onRoomDirectoryVisibilityPreferenceChanged(): not processed due to invalid parameters");
visibility = null;
} else if(mRoomDirectoryVisibilitySwitch.isChecked()) {
visibility = RoomState.DIRECTORY_VISIBILITY_PUBLIC;
} else {
visibility = RoomState.DIRECTORY_VISIBILITY_PRIVATE;
}
if(null != visibility) {
Log.d(LOG_TAG, "## onRoomDirectoryVisibilityPreferenceChanged(): directory visibility set to "+visibility);
displayLoadingView();
mRoom.updateDirectoryVisibility(visibility, mUpdateCallback);
}
}
/**
* Action when enabling / disabling the rooms notifications.
*/
private void onRoomMuteNotificationsPreferenceChanged(){
// sanity check
if((null == mRoom) || (null == mBingRulesManager) || (null == mRoomMuteNotificationsSwitch)){
return;
}
// get new and previous values
boolean isNotificationsMuted = mRoomMuteNotificationsSwitch.isChecked();
boolean previousValue = mBingRulesManager.isRoomNotificationsDisabled(mRoom);
// update only, if values are different
if(isNotificationsMuted != previousValue) {
displayLoadingView();
mBingRulesManager.muteRoomNotifications(mRoom, isNotificationsMuted, new BingRulesManager.onBingRuleUpdateListener() {
@Override
public void onBingRuleUpdateSuccess() {
Log.d(LOG_TAG, "##onRoomMuteNotificationsPreferenceChanged(): update succeed");
hideLoadingView(UPDATE_UI);
}
@Override
public void onBingRuleUpdateFailure(String errorMessage) {
Log.w(LOG_TAG, "##onRoomMuteNotificationsPreferenceChanged(): BingRuleUpdateFailure");
hideLoadingView(DO_NOT_UPDATE_UI);
}
});
}
}
/**
* Action when updating the room name.
*/
private void onRoomNamePreferenceChanged(){
// sanity check
if((null == mRoom) || (null == mSession) || (null == mRoomNameEditTxt)){
return;
}
// get new and previous values
String previousName = mRoom.getLiveState().name;
String newName = mRoomNameEditTxt.getText();
// update only, if values are different
if (!TextUtils.equals(previousName, newName)) {
displayLoadingView();
Log.d(LOG_TAG, "##onRoomNamePreferenceChanged to " + newName);
mRoom.updateName(newName, mUpdateCallback);
}
}
/**
* Action when updating the room topic.
*/
private void onRoomTopicPreferenceChanged() {
// sanity check
if(null == mRoom){
return;
}
// get new and previous values
String previousTopic = mRoom.getTopic();
String newTopic = mRoomTopicEditTxt.getText();
// update only, if values are different
if (!TextUtils.equals(previousTopic, newTopic)) {
displayLoadingView();
Log.d(LOG_TAG, "## update topic to " + newTopic);
mRoom.updateTopic(newTopic, mUpdateCallback);
}
}
/**
* Update the room avatar.
* Start the camera activity to take the avatar picture.
*/
private void onRoomAvatarPreferenceChanged() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(getActivity(), VectorMediasPickerActivity.class);
intent.putExtra(VectorMediasPickerActivity.EXTRA_AVATAR_MODE, true);
startActivityForResult(intent, REQ_CODE_UPDATE_ROOM_AVATAR);
}
});
}
/**
* Process the result of the room avatar picture.
*
* @param aRequestCode request ID
* @param aResultCode request status code
* @param aData result data
*/
@Override
public void onActivityResult(int aRequestCode, int aResultCode, final Intent aData) {
super.onActivityResult(aRequestCode, aResultCode, aData);
if (REQ_CODE_UPDATE_ROOM_AVATAR == aRequestCode) {
onActivityResultRoomAvatarUpdate(aResultCode, aData);
}
}
/**
* Update the avatar from the data provided the medias picker.
* @param aResultCode the result code.
* @param aData the provided data.
*/
private void onActivityResultRoomAvatarUpdate(int aResultCode, final Intent aData) {
// sanity check
if(null == mSession){
return;
}
if (aResultCode == Activity.RESULT_OK) {
Uri thumbnailUri = VectorUtils.getThumbnailUriFromIntent(getActivity(), aData, mSession.getMediasCache());
if (null != thumbnailUri) {
displayLoadingView();
// save the bitmap URL on the server
ResourceUtils.Resource resource = ResourceUtils.openResource(getActivity(), thumbnailUri, null);
if(null != resource) {
mSession.getContentManager().uploadContent(resource.mContentStream, null, resource.mMimeType, null, new ContentManager.UploadCallback() {
@Override
public void onUploadStart(String uploadId) {
}
@Override
public void onUploadProgress(String anUploadId, int percentageProgress) {
}
@Override
public void onUploadComplete(final String anUploadId, final ContentResponse uploadResponse, final int serverResponseCode, final String serverErrorMessage) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if ((null != uploadResponse) && (null != uploadResponse.contentUri)) {
Log.d(LOG_TAG, "The avatar has been uploaded, update the room avatar");
mRoom.updateAvatarUrl(uploadResponse.contentUri, mUpdateCallback);
} else {
Log.e(LOG_TAG, "Fail to upload the avatar");
hideLoadingView(DO_NOT_UPDATE_UI);
}
}
});
}
});
}
}
}
}
/**
* Display the loading view in the parent activity layout.
* This view is disabled/enabled to achieve a waiting screen.
*/
private void displayLoadingView() {
Activity parentActivity = getActivity();
if(null != parentActivity) {
parentActivity.runOnUiThread(new Runnable() {
public void run() {
// disable the fragment container view to disable preferences access
//enablePreferenceWidgets(false);
// disable preference screen during server updates
if(null != mParentFragmentContainerView)
mParentFragmentContainerView.setEnabled(false);
// display the loading progress bar screen
if (null != mParentLoadingView) {
mParentLoadingView.setVisibility(View.VISIBLE);
}
}
});
}
}
/**
* Hide the loading progress bar screen and
* update the UI if required.
*/
private void hideLoadingView(boolean aIsUiRefreshRequired) {
getActivity().runOnUiThread(new Runnable(){
public void run() {
// enable preference screen after server updates finished
if(null != mParentFragmentContainerView)
mParentFragmentContainerView.setEnabled(true);
// enable preference widgets
//enablePreferenceWidgets(true);
if (null != mParentLoadingView) {
mParentLoadingView.setVisibility(View.GONE);
}
}
});
if(aIsUiRefreshRequired){
updateUiOnUiThread();
}
}
//================================================================================
// Banned members management
//================================================================================
/**
* Refresh the addresses section
*/
private void refreshBannedMembersList() {
ArrayList<RoomMember> bannedMembers = new ArrayList<>();
Collection<RoomMember> members = mRoom.getMembers();
if (null != members) {
for (RoomMember member : members) {
if (TextUtils.equals(member.membership, RoomMember.MEMBERSHIP_BAN)) {
bannedMembers.add(member);
}
}
}
Collections.sort(bannedMembers, new Comparator<RoomMember>() {
@Override
public int compare(RoomMember m1, RoomMember m2) {
return m1.getUserId().toLowerCase().compareTo(m2.getUserId().toLowerCase());
}
});
PreferenceScreen preferenceScreen = getPreferenceScreen();
preferenceScreen.removePreference(mBannedMembersSettingsCategory);
mBannedMembersSettingsCategory.removeAll();
if (bannedMembers.size() > 0) {
preferenceScreen.addPreference(mBannedMembersSettingsCategory);
for (RoomMember member : bannedMembers) {
VectorCustomActionEditTextPreference preference = new VectorCustomActionEditTextPreference(getActivity());
final String userId = member.getUserId();
preference.setTitle(userId);
preference.setKey(BANNED_PREFERENCE_KEY_BASE + userId);
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
// The user is trying to leave with unsaved changes. Warn about that
new AlertDialog.Builder(VectorApp.getCurrentActivity())
.setMessage(userId)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create()
.show();
return false;
}
});
mBannedMembersSettingsCategory.addPreference(preference);
}
}
}
//================================================================================
// Aliases management
//================================================================================
private final ApiCallback mAliasUpdatesCallback = new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
hideLoadingView(false);
refreshAddresses();
}
});
}
/**
* Error management.
* @param errorMessage the error message
*/
private void onError(final String errorMessage) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
hideLoadingView(false);
refreshAddresses();
}
});
}
@Override
public void onNetworkError(Exception e) {
onError(e.getLocalizedMessage());
}
@Override
public void onMatrixError(MatrixError e) {
onError(e.getLocalizedMessage());
}
@Override
public void onUnexpectedError(Exception e) {
onError(e.getLocalizedMessage());
}
};
/**
* Manage the long click on an address.
* @param roomAlias the room alias.
* @param anchorView the popup menu anchor view.
*/
@SuppressLint("NewApi")
private void onAddressLongClick(final String roomAlias, final View anchorView) {
Context context = getActivity();
final PopupMenu popup = (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) ? new PopupMenu(context, anchorView, Gravity.END) : new PopupMenu(context, anchorView);
popup.getMenuInflater().inflate(R.menu.vector_room_settings_addresses, popup.getMenu());
// force to display the icons
try {
Field[] fields = popup.getClass().getDeclaredFields();
for (Field field : fields) {
if ("mPopup".equals(field.getName())) {
field.setAccessible(true);
Object menuPopupHelper = field.get(popup);
Class<?> classPopupHelper = Class.forName(menuPopupHelper.getClass().getName());
Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class);
setForceIcons.invoke(menuPopupHelper, true);
break;
}
}
} catch (Exception e) {
Log.e(LOG_TAG, "onMessageClick : force to display the icons failed " + e.getLocalizedMessage());
}
Menu menu = popup.getMenu();
if (!canUpdateAliases()) {
menu.findItem(R.id.ic_action_vector_delete_alias).setVisible(false);
}
// display the menu
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(final MenuItem item) {
//
if (item.getItemId() == R.id.ic_action_vector_delete_alias) {
displayLoadingView();
mRoom.removeAlias(roomAlias, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
// when there is only one alias, it becomes the main alias.
if (mRoom.getAliases().size() == 1) {
mRoom.updateCanonicalAlias(mRoom.getAliases().get(0), mAliasUpdatesCallback);
} else {
mAliasUpdatesCallback.onSuccess(info);
}
}
@Override
public void onNetworkError(Exception e) {
mAliasUpdatesCallback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
mAliasUpdatesCallback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
mAliasUpdatesCallback.onUnexpectedError(e);
}
});
} else if (item.getItemId() == R.id.ic_action_vector_room_url) {
VectorUtils.copyToClipboard(getActivity(), VectorUtils.getPermalink(roomAlias, null));
} else {
VectorUtils.copyToClipboard(getActivity(), roomAlias);
}
return true;
}
});
popup.show();
}
/**
* Tells if the current user can updates the room aliases.
* @return true if the user is allowed.
*/
private boolean canUpdateAliases() {
boolean canUpdateAliases = false;
PowerLevels powerLevels = mRoom.getLiveState().getPowerLevels();
if (null != powerLevels) {
int powerLevel = powerLevels.getUserPowerLevel(mSession.getMyUserId());
canUpdateAliases = powerLevel >= powerLevels.minimumPowerLevelForSendingEventAsStateEvent(Event.EVENT_TYPE_STATE_ROOM_ALIASES);
}
return canUpdateAliases;
}
/**
* Refresh the addresses section
*/
private void refreshAddresses() {
final String localSuffix = ":" + mSession.getHomeserverConfig().getHomeserverUri().getHost();
final String canonicalAlias = mRoom.getLiveState().alias;
final ArrayList<String> aliases = new ArrayList<>(mRoom.getAliases());
// remove the displayed preferences
mAddressesSettingsCategory.removeAll();
if (0 == aliases.size()) {
AddressPreference preference = new AddressPreference(getActivity());
preference.setTitle(getString(R.string.room_settings_addresses_no_local_addresses));
preference.setKey(NO_LOCAL_ADDRESS_PREFERENCE_KEY);
mAddressesSettingsCategory.addPreference(preference);
} else {
ArrayList<String> localAliases = new ArrayList<>();
ArrayList<String> remoteAliases = new ArrayList<>();
for(String alias : aliases) {
if (alias.endsWith(localSuffix)) {
localAliases.add(alias);
} else {
remoteAliases.add(alias);
}
}
// the local aliases are displayed first in the list
aliases.clear();
aliases.addAll(localAliases);
aliases.addAll(remoteAliases);
int index = 0;
for (String alias : aliases) {
AddressPreference preference = new AddressPreference(getActivity());
preference.setTitle(alias);
preference.setKey(ADDRESSES_PREFERENCE_KEY_BASE + index);
preference.setMainIconVisible(TextUtils.equals(alias, canonicalAlias));
final String fAlias = alias;
final AddressPreference fAddressPreference = preference;
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
if (TextUtils.equals(fAlias, canonicalAlias)) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.room_settings_addresses_disable_main_address_prompt_msg);
builder.setTitle(R.string.room_settings_addresses_disable_main_address_prompt_title);
builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
displayLoadingView();
mRoom.updateCanonicalAlias(null, mAliasUpdatesCallback);
}
});
builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// nothing
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
displayLoadingView();
mRoom.updateCanonicalAlias(fAlias, mAliasUpdatesCallback);
}
return false;
}
});
preference.setOnPreferenceLongClickListener( new VectorCustomActionEditTextPreference.OnPreferenceLongClickListener() {
@Override
public boolean onPreferenceLongClick(Preference preference) {
onAddressLongClick(fAlias, fAddressPreference.getMainIconView());
return true;
}
});
mAddressesSettingsCategory.addPreference(preference);
index++;
}
}
if (canUpdateAliases()) {
// display the "add addresses" entry
EditTextPreference addAddressPreference = new EditTextPreference(getActivity());
addAddressPreference.setTitle(R.string.room_settings_addresses_add_new_address);
addAddressPreference.setDialogTitle(R.string.room_settings_addresses_add_new_address);
addAddressPreference.setKey(ADD_ADDRESSES_PREFERENCE_KEY);
addAddressPreference.setIcon(getResources().getDrawable(R.drawable.ic_material_add_circle));
addAddressPreference.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String newAddress = ((String) newValue).trim();
// ignore empty alias
if (!TextUtils.isEmpty(newAddress)) {
if (!MXSession.PATTERN_MATRIX_ALIAS.matcher(newAddress).matches()) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.room_settings_addresses_invalid_format_dialog_title);
builder.setMessage(getString(R.string.room_settings_addresses_invalid_format_dialog_body, newAddress));
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else if (aliases.indexOf(newAddress) < 0) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
displayLoadingView();
mRoom.addAlias(newAddress, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
// when there is only one alias, it becomes the main alias.
if (mRoom.getAliases().size() == 1) {
mRoom.updateCanonicalAlias(mRoom.getAliases().get(0), mAliasUpdatesCallback);
} else {
mAliasUpdatesCallback.onSuccess(info);
}
}
@Override
public void onNetworkError(Exception e) {
mAliasUpdatesCallback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
mAliasUpdatesCallback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
mAliasUpdatesCallback.onUnexpectedError(e);
}
});
}
});
}
}
return false;
}
});
mAddressesSettingsCategory.addPreference(addAddressPreference);
}
}
}
| Updates after PRs
| vector/src/main/java/im/vector/fragments/VectorRoomSettingsFragment.java | Updates after PRs | <ide><path>ector/src/main/java/im/vector/fragments/VectorRoomSettingsFragment.java
<ide> //================================================================================
<ide>
<ide> /**
<del> * Refresh the addresses section
<add> * Refresh the banned users list.
<ide> */
<ide> private void refreshBannedMembersList() {
<ide> ArrayList<RoomMember> bannedMembers = new ArrayList<>();
<ide> preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
<ide> @Override
<ide> public boolean onPreferenceClick(Preference preference) {
<del> // The user is trying to leave with unsaved changes. Warn about that
<add> // display the user id in a dialog to make is readable.
<ide> new AlertDialog.Builder(VectorApp.getCurrentActivity())
<ide> .setMessage(userId)
<ide> .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { |
|
Java | apache-2.0 | 3b100589e11270ec09da266a843fc4cad652327a | 0 | velmuruganvelayutham/certifier,velmuruganvelayutham/certifier,velmuruganvelayutham/git-real,velmuruganvelayutham/certifier,velmuruganvelayutham/git-real,velmuruganvelayutham/git-real,velmuruganvelayutham/certifier | package com.velmurugan.certifier.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* The persistent class for the c_options database table.
*
*/
@Entity
@Table(name = "c_options")
@NamedQuery(name = "COption.findAll", query = "SELECT c FROM COption c")
public class COption implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "c_options_id", unique = true, nullable = false)
private int cOptionsId;
@Column(length = 45, name = "description")
private String choices;
@Column
private boolean isCorrect;
private int no;
// bi-directional many-to-one association to CQuestion
@ManyToOne
@JoinColumn(name = "c_questions_id", nullable = false)
private CQuestion CQuestion;
public COption() {
}
public int getCOptionsId() {
return this.cOptionsId;
}
public void setCOptionsId(int cOptionsId) {
this.cOptionsId = cOptionsId;
}
public String getChoices() {
return this.choices;
}
public void setChoices(String choices) {
this.choices = choices;
}
public boolean isCorrect() {
return isCorrect;
}
public void setCorrect(boolean isCorrect) {
this.isCorrect = isCorrect;
}
public int getNo() {
return this.no;
}
public void setNo(int no) {
this.no = no;
}
public CQuestion getCQuestion() {
return this.CQuestion;
}
public void setCQuestion(CQuestion CQuestion) {
this.CQuestion = CQuestion;
}
} | src/main/java/com/velmurugan/certifier/model/COption.java | package com.velmurugan.certifier.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* The persistent class for the c_options database table.
*
*/
@Entity
@Table(name = "c_options")
@NamedQuery(name = "COption.findAll", query = "SELECT c FROM COption c")
public class COption implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "c_options_id", unique = true, nullable = false)
private int cOptionsId;
@Column(length = 45, name = "description")
private String choices;
@Column
private boolean isCorrect;
private int no;
// bi-directional many-to-one association to CQuestion
@ManyToOne
@JoinColumn(name = "c_questions_id", nullable = false)
private CQuestion CQuestion;
public COption() {
}
public int getCOptionsId() {
return this.cOptionsId;
}
public void setCOptionsId(int cOptionsId) {
this.cOptionsId = cOptionsId;
}
public String getChoices() {
return this.choices;
}
public void setChoices(String choices) {
this.choices = choices;
}
public int getNo() {
return this.no;
}
public void setNo(int no) {
this.no = no;
}
public CQuestion getCQuestion() {
return this.CQuestion;
}
public void setCQuestion(CQuestion CQuestion) {
this.CQuestion = CQuestion;
}
} | added getters/setters for iscorrect
| src/main/java/com/velmurugan/certifier/model/COption.java | added getters/setters for iscorrect | <ide><path>rc/main/java/com/velmurugan/certifier/model/COption.java
<ide> this.choices = choices;
<ide> }
<ide>
<add> public boolean isCorrect() {
<add> return isCorrect;
<add> }
<add>
<add> public void setCorrect(boolean isCorrect) {
<add> this.isCorrect = isCorrect;
<add> }
<add>
<ide> public int getNo() {
<ide> return this.no;
<ide> } |
|
Java | bsd-3-clause | c4a6acb658cd2e410286a9555ff79a17348bf657 | 0 | jimmutable/core,jimmutable/core | package org.jimmutable.cloud.elasticsearch;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
//import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.DocWriteResponse.Result;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.WriteRequest.RefreshPolicy;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryShardException;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.jimmutable.cloud.servlet_utils.common_objects.JSONServletResponse;
import org.jimmutable.cloud.servlet_utils.search.OneSearchResultWithTyping;
import org.jimmutable.cloud.servlet_utils.search.OneSearchResult;
import org.jimmutable.cloud.servlet_utils.search.SearchFieldId;
import org.jimmutable.cloud.servlet_utils.search.SearchResponseError;
import org.jimmutable.cloud.servlet_utils.search.SearchResponseOK;
import org.jimmutable.cloud.servlet_utils.search.SortBy;
import org.jimmutable.cloud.servlet_utils.search.SortDirection;
import org.jimmutable.cloud.servlet_utils.search.StandardSearchRequest;
import org.jimmutable.core.objects.common.time.Instant;
import org.jimmutable.core.objects.common.time.TimeOfDay;
import org.jimmutable.core.serialization.FieldName;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.ICsvListWriter;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Use this class for general searching and document upserts with Elasticsearch
*
* @author trevorbox
*
*/
public class ElasticSearch implements ISearch
{
private static final Logger logger = LogManager.getLogger(ElasticSearch.class);
private static final ExecutorService document_upsert_pool = (ExecutorService) new ThreadPoolExecutor(8, 8, 5, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>());
public static final String ELASTICSEARCH_DEFAULT_TYPE = "default";
public static final String SORT_FIELD_NAME_JIMMUTABLE = "jimmutable_sort_field";
private volatile TransportClient client;
/**
* Useful to call custom searches from the builder class when simple text search
* is not enough. NOTE: Be sure to set the TYPE. For example
* builder.setTypes(ElasticSearch.ELASTICSEARCH_DEFAULT_TYPE); This method will
* not set anything for you in the builder. </br>
* Example: </br>
* SearchRequestBuilder builder =
* CloudExecutionEnvironment.getSimpleCurrent().getSimpleSearch().getBuilder(index_name);</br>
* builder.setTypes(ElasticSearch.ELASTICSEARCH_DEFAULT_TYPE);</br>
* builder.setSize(size); builder.set String my_field_name =
* "the_field_name";</br>
* //get the max value from a field</br>
* builder.addAggregation(AggregationBuilders.max(my_field_name)); </br>
* //order the results ascending by field </br>
* builder.addSort(SortBuilders.fieldSort(my_field_name).order(SortOrder.ASC));</br>
* builder.setQuery(QueryBuilders.queryStringQuery("search string"));</br>
* </br>
*/
@Override
public SearchRequestBuilder getBuilder(IndexDefinition index)
{
if (index == null)
{
throw new RuntimeException("Null IndexDefinition");
}
return client.prepareSearch(index.getSimpleValue());
}
public ElasticSearch(TransportClient client)
{
this.client = client;
}
public boolean writeAllToCSV(IndexDefinition index, String query_string, List<SearchFieldId> sorted_header, ICsvListWriter list_writer, CellProcessor[] cell_processors)
{
if (index == null || query_string == null)
{
return false;
}
SearchResponse scrollResp = client.prepareSearch(index.getSimpleValue()).addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC).setScroll(new TimeValue(60000)).setQuery(QueryBuilders.queryStringQuery(query_string)).setSize(1000).get();
do
{
String[] document;
for (SearchHit hit : scrollResp.getHits().getHits())
{
document = new String[sorted_header.size()];
Map<String, Object> resultMap = hit.getSourceAsMap();
for (int i = 0; i < sorted_header.size(); i++)
{
if (resultMap.containsKey(sorted_header.get(i).getSimpleValue()))
{
document[i] = resultMap.get(sorted_header.get(i).getSimpleValue()).toString();
}
}
try
{
list_writer.write(Arrays.asList(document), cell_processors);
} catch (IOException e)
{
logger.error(e);
return false;
}
}
scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
} while (scrollResp.getHits().getHits().length != 0); // Zero hits mark the end of the scroll and the while
// loop.
return true;
}
/**
* Gracefully shutdown the running threads. Note: the TransportClient should be
* closed where instantiated. This is not handles by this.
*
* @return boolean if shutdown correctly or not
*/
@Override
public boolean shutdownDocumentUpsertThreadPool(int seconds)
{
long start = System.currentTimeMillis();
document_upsert_pool.shutdown();
boolean terminated = true;
try
{
terminated = document_upsert_pool.awaitTermination(seconds, TimeUnit.SECONDS);
} catch (InterruptedException e)
{
logger.log(Level.FATAL, "Shutdown of runnable pool was interrupted!", e);
}
if (!terminated)
{
logger.error("Failed to terminate in %s seconds. Calling shutdownNow...", seconds);
document_upsert_pool.shutdownNow();
}
boolean success = document_upsert_pool.isTerminated();
if (success)
{
logger.warn(String.format("Successfully terminated pool in %s milliseconds", (System.currentTimeMillis() - start)));
} else
{
logger.warn(String.format("Unsuccessful termination of pool in %s milliseconds", (System.currentTimeMillis() - start)));
}
return success;
}
/**
* Runnable class to upsert the document
*
* @author trevorbox
*
*/
private class UpsertDocumentRunnable implements Runnable
{
private Indexable object;
private Map<String, Object> data;
public UpsertDocumentRunnable(Indexable object, Map<String, Object> data)
{
this.object = object;
this.data = data;
}
@Override
public void run()
{
try
{
String index_name = object.getSimpleSearchIndexDefinition().getSimpleValue();
String document_name = object.getSimpleSearchDocumentId().getSimpleValue();
IndexResponse response = client.prepareIndex(index_name, ELASTICSEARCH_DEFAULT_TYPE, document_name).setSource(data).get();
Level level;
switch (response.getResult())
{
case CREATED:
level = Level.INFO;
break;
case UPDATED:
level = Level.INFO;
break;
default:
level = Level.FATAL;
break;
}
logger.log(level, String.format("%s %s/%s/%s %s", response.getResult().name(), index_name, ELASTICSEARCH_DEFAULT_TYPE, document_name, data));
} catch (Exception e)
{
logger.log(Level.FATAL, "Failure during upsert operation!", e);
}
}
}
/**
* Runnable class to upsert the document
*
* @author trevorbox
*
*/
private class UpsertQuietDocumentRunnable implements Runnable
{
private Indexable object;
private Map<String, Object> data;
public UpsertQuietDocumentRunnable(Indexable object, Map<String, Object> data)
{
this.object = object;
this.data = data;
}
@Override
public void run()
{
try
{
String index_name = object.getSimpleSearchIndexDefinition().getSimpleValue();
String document_name = object.getSimpleSearchDocumentId().getSimpleValue();
client.prepareIndex(index_name, ELASTICSEARCH_DEFAULT_TYPE, document_name).setSource(data).get();
} catch (Exception e)
{
logger.log(Level.FATAL, "Failure during upsert operation!", e);
}
}
}
/**
* Upsert a document to a search index asynchronously AND without logging to
* INFO
*
*
* @param object
* The Indexable object
* @return boolean If successful or not
*/
@Override
public boolean upsertQuietDocumentAsync(Indexable object)
{
if (object == null)
{
logger.error("Null object!");
return false;
}
SearchDocumentWriter writer = new SearchDocumentWriter();
object.writeSearchDocument(writer);
Map<String, Object> data = writer.getSimpleFieldsMap();
try
{
document_upsert_pool.execute(new UpsertQuietDocumentRunnable(object, data));
} catch (Exception e)
{
logger.log(Level.FATAL, "Failure during thread pool execution!", e);
return false;
}
return true;
}
/**
* Upsert a document to a search index asynchronously
*
*
* @param object
* The Indexable object
* @return boolean If successful or not
*/
@Override
public boolean upsertDocumentAsync(Indexable object)
{
if (object == null)
{
logger.error("Null object!");
return false;
}
SearchDocumentWriter writer = new SearchDocumentWriter();
object.writeSearchDocument(writer);
Map<String, Object> data = writer.getSimpleFieldsMap();
try
{
document_upsert_pool.execute(new UpsertDocumentRunnable(object, data));
} catch (Exception e)
{
logger.log(Level.FATAL, "Failure during thread pool execution!", e);
return false;
}
return true;
}
/**
* Upsert a document to a search index
*
* @param object
* The Indexable object
* @return boolean If successful or not
*/
@Override
public boolean upsertDocument(Indexable object)
{
if (object == null)
{
logger.error("Null object!");
return false;
}
try
{
SearchDocumentWriter writer = new SearchDocumentWriter();
object.writeSearchDocument(writer);
Map<String, Object> data = writer.getSimpleFieldsMap();
String index_name = object.getSimpleSearchIndexDefinition().getSimpleValue();
String document_name = object.getSimpleSearchDocumentId().getSimpleValue();
IndexResponse response = client.prepareIndex(index_name, ELASTICSEARCH_DEFAULT_TYPE, document_name).setRefreshPolicy(RefreshPolicy.IMMEDIATE).setSource(data).get();
Level level;
switch (response.getResult())
{
case CREATED:
level = Level.INFO;
break;
case UPDATED:
level = Level.INFO;
break;
default:
level = Level.FATAL;
break;
}
logger.log(level, String.format("%s %s/%s/%s %s", response.getResult().name(), index_name, ELASTICSEARCH_DEFAULT_TYPE, document_name, data));
} catch (Exception e)
{
logger.log(Level.FATAL, String.format("Failure during upsert operation of Document id:%s on Index:%s", object.getSimpleSearchDocumentId().getSimpleValue(), object.getSimpleSearchIndexDefinition().getSimpleValue()), e);
return false;
}
return true;
}
/**
* Search an index with a query string.
*
* @see <a href=
* "https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html">query-dsl-query-string-query</a>
*
* @param index
* The IndexDefinition
* @param request
* The StandardSearchRequest
* @return JSONServletResponse
*/
@Override
public JSONServletResponse search(IndexDefinition index, StandardSearchRequest request)
{
if (index == null || request == null)
{
return new SearchResponseError(request, "Null parameter(s)!");
}
try
{
String index_name = index.getSimpleValue();
int from = request.getSimpleStartResultsAfter();
int size = request.getSimpleMaxResults();
SearchRequestBuilder builder = client.prepareSearch(index_name);
builder.setTypes(ELASTICSEARCH_DEFAULT_TYPE);
builder.setFrom(from);
builder.setSize(size);
builder.setQuery(QueryBuilders.queryStringQuery(request.getSimpleQueryString()));
// Sorting
for (SortBy sort_by : request.getSimpleSort().getSimpleSortOrder())
{
FieldSortBuilder sort_builder = getSort(sort_by, null);
if (sort_builder == null)
continue;
builder.addSort(sort_builder);
}
SearchResponse response = builder.get();
List<OneSearchResult> results = new LinkedList<OneSearchResult>();
response.getHits().forEach(hit ->
{
Map<FieldName, String> map = new TreeMap<FieldName, String>();
hit.getSourceAsMap().forEach((k, v) ->
{
map.put(new FieldName(k), v.toString());
});
results.add(new OneSearchResult(map));
});
long total_hits = response.getHits().totalHits;
int next_page = from + size;
int previous_page = (from - size) < 0 ? 0 : (from - size);
boolean has_more_results = total_hits > next_page;
boolean has_previous_results = from > 0;
Level level;
switch (response.status())
{
case OK:
level = Level.INFO;
break;
default:
level = Level.WARN;
break;
}
SearchResponseOK ok = new SearchResponseOK(request, results, from, has_more_results, has_previous_results, next_page, previous_page, total_hits);
logger.log(level, String.format("QUERY:%s INDEX:%s STATUS:%s HITS:%s TOTAL_HITS:%s MAX_RESULTS:%d START_RESULTS_AFTER:%d", ok.getSimpleSearchRequest().getSimpleQueryString(), index.getSimpleValue(), response.status(), results.size(), ok.getSimpleTotalHits(), ok.getSimpleSearchRequest().getSimpleMaxResults(), ok.getSimpleSearchRequest().getSimpleStartResultsAfter()));
logger.trace(String.format("FIRST_RESULT_IDX:%s HAS_MORE_RESULTS:%s HAS_PREVIOUS_RESULTS:%s START_OF_NEXT_PAGE_OF_RESULTS:%s START_OF_PREVIOUS_PAGE_OF_RESULTS:%s", ok.getSimpleFirstResultIdx(), ok.getSimpleHasMoreResults(), ok.getSimpleHasMoreResults(), ok.getSimpleStartOfNextPageOfResults(), ok.getSimpleStartOfPreviousPageOfResults()));
logger.trace(ok.getSimpleResults().toString());
return ok;
} catch (Exception e)
{
if (e.getCause() instanceof QueryShardException)
{
logger.warn(String.format("%s on index %s", e.getCause().getMessage(), index.getSimpleValue()));
return new SearchResponseError(request, e.getCause().getMessage());
} else
{
logger.error(String.format("Search failed for %s on index %s", request.getSimpleQueryString(), index.getSimpleValue()), e);
return new SearchResponseError(request, e.getMessage());
}
}
}
/**
* Search an index with a query string and return a List of OneSearchResult 's.
*
* @see <a href=
* "https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html">query-dsl-query-string-query</a>
*
* @param index
* The IndexDefinition
* @param request
* The StandardSearchRequest
* @param default_value
* The default value should it fail
* @return List<OneSearchResult>
*/
@Override
public List<OneSearchResultWithTyping> search(IndexDefinition index, StandardSearchRequest request, List<OneSearchResultWithTyping> default_value)
{
if (index == null || request == null)
{
logger.warn(String.format("Search failed: Null parameter(s) for %s", request));
return default_value;
}
try
{
String index_name = index.getSimpleValue();
int from = request.getSimpleStartResultsAfter();
int size = request.getSimpleMaxResults();
SearchRequestBuilder builder = client.prepareSearch(index_name);
builder.setTypes(ELASTICSEARCH_DEFAULT_TYPE);
builder.setFrom(from);
builder.setSize(size);
builder.setQuery(QueryBuilders.queryStringQuery(request.getSimpleQueryString()));
// Sorting
for (SortBy sort_by : request.getSimpleSort().getSimpleSortOrder())
{
FieldSortBuilder sort_builder = getSort(sort_by, null);
if (sort_builder == null)
continue;
builder.addSort(sort_builder);
}
SearchResponse response = builder.get();
List<OneSearchResultWithTyping> results = new LinkedList<OneSearchResultWithTyping>();
response.getHits().forEach(hit ->
{
Map<FieldName, String[]> map = new TreeMap<FieldName, String[]>();
hit.getSourceAsMap().forEach((k, v) ->
{
FieldName name = new FieldName(k);
String[] array_val = map.get(name);
String[] new_array_val = null;
if (v instanceof ArrayList<?>)
{
List<Object> array_as_list = (ArrayList<Object>) v;
new_array_val = new String[array_as_list.size()];
for (int i = 0; i < array_as_list.size(); i++)
{
new_array_val[i] = String.valueOf(array_as_list.get(i));
}
} else
{
if (array_val == null)
array_val = new String[0];
new_array_val = new String[]
{ String.valueOf(v) };
}
if (new_array_val != null)
map.put(name, new_array_val);
});
results.add(new OneSearchResultWithTyping(map));
});
int next_page = from + size;
boolean has_more_results = response.getHits().totalHits > next_page;
boolean has_previous_results = from != 0;
Level level;
switch (response.status())
{
case OK:
level = Level.INFO;
break;
default:
level = Level.WARN;
break;
}
logger.log(level, String.format("QUERY:%s INDEX:%s STATUS:%s HITS:%s TOTAL_HITS:%s MAX_RESULTS:%d START_RESULTS_AFTER:%d", request, index.getSimpleValue(), response.status(), results.size(), response.getHits().totalHits, request.getSimpleMaxResults(), request.getSimpleStartResultsAfter()));
logger.trace(String.format("FIRST_RESULT_IDX:%s HAS_MORE_RESULTS:%s HAS_PREVIOUS_RESULTS:%s START_OF_NEXT_PAGE_OF_RESULTS:%s START_OF_PREVIOUS_PAGE_OF_RESULTS:%s", from, has_more_results, has_previous_results, next_page, from));
logger.trace(results.toString());
return results;
} catch (Exception e)
{
logger.warn(String.format("Search failed for %s", request), e);
return default_value;
}
}
/**
* Test if the index exists or not
*
* @param index
* IndexDefinition
* @return boolean if the index exists or not
*/
@Override
public boolean indexExists(IndexDefinition index)
{
if (index == null)
{
logger.fatal("Cannot check the existence of a null Index");
return false;
}
try
{
return client.admin().indices().prepareExists(index.getSimpleValue()).get().isExists();
} catch (Exception e)
{
logger.log(Level.FATAL, "Failed to check if index exists", e);
return false;
}
}
/**
* Test if the index exists or not
*
* @param index
* SearchIndexDefinition
* @return boolean if the index exists or not
*/
@Override
public boolean indexExists(SearchIndexDefinition index)
{
if (index == null)
{
logger.fatal("Cannot check the existence of a null Index");
return false;
}
try
{
return client.admin().indices().prepareExists(index.getSimpleIndex().getSimpleValue()).get().isExists();
} catch (Exception e)
{
logger.log(Level.FATAL, "Failed to check if index exists", e);
return false;
}
}
/**
* An index is properly configured if it exists and its field names and
* datatypes match
*
* @param index
* SearchIndexDefinition
* @return boolean if the index is properly configured or not
*/
@Override
public boolean indexProperlyConfigured(SearchIndexDefinition index)
{
if (index == null)
{
return false;
}
if (indexExists(index))
{
// compare the expected index fields to the actual index fields
Map<String, String> expected = new TreeMap<String, String>();
index.getSimpleFields().forEach(fields ->
{
expected.put(fields.getSimpleFieldName().getSimpleName(), fields.getSimpleType().getSimpleCode());
});
try
{
GetMappingsResponse response = client.admin().indices().prepareGetMappings(index.getSimpleIndex().getSimpleValue()).get();
String json = response.getMappings().get(index.getSimpleIndex().getSimpleValue()).get(ELASTICSEARCH_DEFAULT_TYPE).source().string();
Map<String, String> actual = new TreeMap<String, String>();
new ObjectMapper().readTree(json).get(ELASTICSEARCH_DEFAULT_TYPE).get("properties").fields().forEachRemaining(fieldMapping ->
{
if (!fieldMapping.getKey().contains(SORT_FIELD_NAME_JIMMUTABLE)) // Skip our keyword fields
{
actual.put(fieldMapping.getKey(), fieldMapping.getValue().get("type").asText());
}
});
if (!expected.equals(actual))
{
logger.warn(String.format("Index: %s not properly configured", index.getSimpleIndex().getSimpleValue()));
logger.warn(String.format("Expected fields=%s", expected));
logger.warn(String.format("Actual fields=%s", actual));
if (expected.size() > actual.size())
{
logger.warn("There are field missing in the current index.");
} else if (expected.size() < actual.size())
{
logger.info("There are more fields than expected in the current index.");
}
//
//
// for (String key : expected.keySet())
// {
// String expected_value = expected.get(key);
// String actual_value = actual.get(key);
// if (!expected_value.equals(actual_value))
// {
// logger.info(String.format("Issue lies in that for Field %s the expected field
// value is: %s", key, expected_value));
// logger.info(String.format("However, currently for Field %s the actual field
// value is: %s", key, actual_value));
// }
// }
return false;
}
return true;
} catch (Exception e)
{
logger.log(Level.FATAL, String.format("Failed to get the index mapping for index %s", index.getSimpleIndex().getSimpleValue()), e);
}
}
return false;
}
private boolean createIndex(SearchIndexDefinition index)
{
if (index == null)
{
logger.fatal("Cannot create a null Index");
return false;
}
try
{
CreateIndexResponse createResponse = client.admin().indices().prepareCreate(index.getSimpleIndex().getSimpleValue()).addMapping(ELASTICSEARCH_DEFAULT_TYPE, getMappingBuilder(index, null)).get();
if (!createResponse.isAcknowledged())
{
logger.fatal(String.format("Index Creation not acknowledged for index %s", index.getSimpleIndex().getSimpleValue()));
return false;
}
} catch (Exception e)
{
logger.log(Level.FATAL, String.format("Failed to generate mapping json for index %s", index.getSimpleIndex().getSimpleValue()), e);
return false;
}
logger.info(String.format("Created index %s", index.getSimpleIndex().getSimpleValue()));
return true;
}
/**
* Deletes an entire index
*
* @param index
* SearchIndexDefinition
* @return boolean - true if successfully deleted, else false
*/
public boolean deleteIndex(SearchIndexDefinition index)
{
if (index == null)
{
logger.fatal("Cannot delete a null Index");
return false;
}
try
{
DeleteIndexResponse deleteResponse = client.admin().indices().prepareDelete(index.getSimpleIndex().getSimpleValue()).get();
if (!deleteResponse.isAcknowledged())
{
logger.fatal(String.format("Index Deletion not acknowledged for index %s", index.getSimpleIndex().getSimpleValue()));
return false;
}
} catch (Exception e)
{
logger.fatal(String.format("Index Deletion failed for index %s", index.getSimpleIndex().getSimpleValue()));
return false;
}
logger.info(String.format("Deleted index %s", index.getSimpleIndex().getSimpleValue()));
return true;
}
/**
* Upsert if the index doesn't exist or is not properly configured already
*
* BE CAREFUL!!!
*
* @param index
* SearchIndexDefinition
* @return boolean if the upsert was successful or not
*/
@Override
public boolean upsertIndex(SearchIndexDefinition index)
{
if (index == null)
{
logger.fatal("Cannot upsert a null Index");
return false;
}
// if it exists and is not configured correctly delete and add
if (indexExists(index))
{
if (!indexProperlyConfigured(index))
{
if (deleteIndex(index))
{
return createIndex(index);
} else
{
// deletion failed
return false;
}
}
} else
{
// index is new
return createIndex(index);
}
// index exists and already configured correctly
logger.info(String.format("No upsert needed for index %s", index.getSimpleIndex().getSimpleValue()));
return true;
}
/**
* Delete a document within an index
*
* @param index
* @param document_id
* @return
*/
public boolean deleteDocument(IndexDefinition index, SearchDocumentId document_id)
{
if (index == null || document_id == null)
{
logger.fatal("Null index or document id");
return false;
}
try
{
DeleteResponse response = client.prepareDelete(index.getSimpleValue(), ELASTICSEARCH_DEFAULT_TYPE, document_id.getSimpleValue()).setRefreshPolicy(RefreshPolicy.IMMEDIATE).get();
logger.info(String.format("Result:%s SearchDocumentId:%s IndexDefinition:%s", response.getResult(), response.getId(), response.getIndex()));
return response.getResult().equals(Result.DELETED);
} catch (Exception e)
{
logger.error(e);
return false;
}
}
/**
* Using a SortBy object, construct a SortBuilder used by ElasticSearch. This
* method handles the unique sorting cases for Text, Time of Day, and Instant.
*
* @param sort_by
* @param default_value
* @return
*/
static private FieldSortBuilder getSort(SortBy sort_by, FieldSortBuilder default_value)
{
SortOrder order = null;
if (sort_by.getSimpleDirection() == SortDirection.ASCENDING)
order = SortOrder.ASC;
if (sort_by.getSimpleDirection() == SortDirection.DESCENDING)
order = SortOrder.DESC;
if (order == null)
return default_value;
FieldName field_name = sort_by.getSimpleField().getSimpleFieldName();
String sort_on_string = field_name.getSimpleName();
if (sort_by.getSimpleField().getSimpleType() == SearchIndexFieldType.TEXT)
sort_on_string = getSortFieldNameText(sort_by.getSimpleField().getSimpleFieldName());
if (sort_by.getSimpleField().getSimpleType() == SearchIndexFieldType.TIMEOFDAY)
sort_on_string = getSortFieldNameTimeOfDay(sort_by.getSimpleField().getSimpleFieldName());
if (sort_by.getSimpleField().getSimpleType() == SearchIndexFieldType.INSTANT)
sort_on_string = getSortFieldNameInstant(sort_by.getSimpleField().getSimpleFieldName());
return SortBuilders.fieldSort(sort_on_string).order(order).unmappedType(SearchIndexFieldType.ATOM.getSimpleCode());
}
/**
* Sorting on text fields is impossible without enabling fielddata in
* ElasticSearch. To get around this, we instead use a keyword field for every
* text field written. This solution is recommended by ElasticSearch over
* enabling fielddata. For more information, read here:
*
* https://www.elastic.co/guide/en/elasticsearch/reference/5.4/fielddata.html#before-enabling-fielddata
* https://www.elastic.co/blog/support-in-the-wild-my-biggest-elasticsearch-problem-at-scale
*
* @param field
* @return
*/
static public String getSortFieldNameText(FieldName field)
{
return getSortFieldNameText(field.getSimpleName());
}
/**
* Sorting on text fields is impossible without enabling fielddata in
* ElasticSearch. To get around this, we instead use a keyword field for every
* text field written. This solution is recommended by ElasticSearch over
* enabling fielddata. For more information, read here:
*
* https://www.elastic.co/guide/en/elasticsearch/reference/5.4/fielddata.html#before-enabling-fielddata
* https://www.elastic.co/blog/support-in-the-wild-my-biggest-elasticsearch-problem-at-scale
*
* @param field_name
* @return
*/
static public String getSortFieldNameText(String field_name)
{
return field_name + "_" + SORT_FIELD_NAME_JIMMUTABLE + "_" + SearchIndexFieldType.ATOM.getSimpleCode();
}
/**
* In order to sort TimeOfDay objects, we need to look at the ms_from_midnight
* field from within. This method creates a consistent field name to sort by.
*
* @param field
* @return
*/
static public String getSortFieldNameTimeOfDay(FieldName field)
{
return getSortFieldNameTimeOfDay(field.getSimpleName());
}
/**
* In order to sort TimeOfDay objects, we need to look at the ms_from_midnight
* field from within. This method creates a consistent field name to sort by.
*
* @param field_name
* @return
*/
static public String getSortFieldNameTimeOfDay(String field_name)
{
return field_name + "_" + SORT_FIELD_NAME_JIMMUTABLE + "_" + TimeOfDay.FIELD_MS_FROM_MIDNIGHT.getSimpleFieldName().getSimpleName();
}
/**
* In order to sort Instant objects, we need to look at the ms_from_epoch field
* from within. This method creates a consistent field name to sort by.
*
* @param field
* @return
*/
static public String getSortFieldNameInstant(FieldName field)
{
return getSortFieldNameInstant(field.getSimpleName());
}
/**
* In order to sort Instant objects, we need to look at the ms_from_epoch field
* from within. This method creates a consistent field name to sort by.
*
* @param field_name
* @return
*/
static public String getSortFieldNameInstant(String field_name)
{
return field_name + "_" + SORT_FIELD_NAME_JIMMUTABLE + "_" + Instant.FIELD_MS_FROM_EPOCH.getSimpleFieldName().getSimpleName();
}
private XContentBuilder getMappingBuilder(SearchIndexDefinition index, XContentBuilder default_value)
{
try
{
XContentBuilder mappingBuilder = jsonBuilder();
mappingBuilder.startObject().startObject(ELASTICSEARCH_DEFAULT_TYPE).startObject("properties");
for (SearchIndexFieldDefinition field : index.getSimpleFields())
{
// if (field.getSimpleType().equals(SearchIndexFieldType.OBJECTID))
// {
// // EXPLICIT MAPPING FOR OBJECTID - does not rely on enum's simple code
// // https://www.elastic.co/blog/strings-are-dead-long-live-strings
// mappingBuilder.startObject(field.getSimpleFieldName().getSimpleName());
// /* */mappingBuilder.field("type", "text");
// /* */mappingBuilder.startObject("fields");
// /* */mappingBuilder.startObject("keyword");
// /* */mappingBuilder.field("type", "keyword");
// /* */mappingBuilder.field("ignore_above", 256);
// /* */mappingBuilder.endObject();
// /* */mappingBuilder.endObject();
// mappingBuilder.endObject();
// } else
// {
mappingBuilder.startObject(field.getSimpleFieldName().getSimpleName());
/* */mappingBuilder.field("type", field.getSimpleType().getSimpleCode());
mappingBuilder.endObject();
// }
// Create a keyword for every text field
if (field.getSimpleType() == SearchIndexFieldType.TEXT)
{
mappingBuilder.startObject(getSortFieldNameText(field.getSimpleFieldName()));
mappingBuilder.field("type", SearchIndexFieldType.ATOM.getSimpleCode());
mappingBuilder.endObject();
}
// Create a long field for every instant field
if (field.getSimpleType() == SearchIndexFieldType.INSTANT)
{
mappingBuilder.startObject(getSortFieldNameInstant(field.getSimpleFieldName()));
mappingBuilder.field("type", SearchIndexFieldType.LONG.getSimpleCode());
mappingBuilder.endObject();
}
// Create a long field for every timeofday field
if (field.getSimpleType() == SearchIndexFieldType.TIMEOFDAY)
{
mappingBuilder.startObject(getSortFieldNameTimeOfDay(field.getSimpleFieldName()));
mappingBuilder.field("type", SearchIndexFieldType.LONG.getSimpleCode());
mappingBuilder.endObject();
}
}
mappingBuilder.endObject().endObject().endObject();
return mappingBuilder;
} catch (Exception e)
{
logger.log(Level.FATAL, String.format("Failed to generate mapping json for index %s", index.getSimpleIndex().getSimpleValue()), e);
return default_value;
}
}
/**
* Puts all field mappings into an existing index. If the index doesn't already
* exist or a field name with a different type already exists the operation will
* fail.
*
* @param index
* SearchIndexDefinition
* @return if successful or not
*/
public boolean putAllFieldMappings(SearchIndexDefinition index)
{
if (index == null)
{
logger.fatal("Null index");
return false;
}
if (!indexExists(index))
{
logger.fatal(String.format("Index %s does not exist!", index.getSimpleIndex().getSimpleValue()));
return false;
}
try
{
PutMappingResponse put_response = client.admin().indices().preparePutMapping(index.getSimpleIndex().getSimpleValue()).setType(ELASTICSEARCH_DEFAULT_TYPE).setSource(getMappingBuilder(index, null)).get();
if (!put_response.isAcknowledged())
{
logger.fatal(String.format("Put Mappings result not acknowledged for index %s", index.getSimpleIndex().getSimpleValue()));
return false;
}
} catch (Exception e)
{
logger.log(Level.FATAL, String.format("Failed to generate mapping json for index %s", index.getSimpleIndex().getSimpleValue()), e);
return false;
}
return true;
}
}
| cloud/src/main/java/org/jimmutable/cloud/elasticsearch/ElasticSearch.java | package org.jimmutable.cloud.elasticsearch;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.DocWriteResponse.Result;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.WriteRequest.RefreshPolicy;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryShardException;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.jimmutable.cloud.servlet_utils.common_objects.JSONServletResponse;
import org.jimmutable.cloud.servlet_utils.search.OneSearchResultWithTyping;
import org.jimmutable.cloud.servlet_utils.search.OneSearchResult;
import org.jimmutable.cloud.servlet_utils.search.SearchFieldId;
import org.jimmutable.cloud.servlet_utils.search.SearchResponseError;
import org.jimmutable.cloud.servlet_utils.search.SearchResponseOK;
import org.jimmutable.cloud.servlet_utils.search.SortBy;
import org.jimmutable.cloud.servlet_utils.search.SortDirection;
import org.jimmutable.cloud.servlet_utils.search.StandardSearchRequest;
import org.jimmutable.core.objects.common.time.Instant;
import org.jimmutable.core.objects.common.time.TimeOfDay;
import org.jimmutable.core.serialization.FieldName;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.ICsvListWriter;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Use this class for general searching and document upserts with Elasticsearch
*
* @author trevorbox
*
*/
public class ElasticSearch implements ISearch
{
private static final Logger logger = LogManager.getLogger(ElasticSearch.class);
private static final ExecutorService document_upsert_pool = (ExecutorService) new ThreadPoolExecutor(8, 8, 5, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>());
public static final String ELASTICSEARCH_DEFAULT_TYPE = "default";
public static final String SORT_FIELD_NAME_JIMMUTABLE = "jimmutable_sort_field";
private volatile TransportClient client;
/**
* Useful to call custom searches from the builder class when simple text search
* is not enough. NOTE: Be sure to set the TYPE. For example
* builder.setTypes(ElasticSearch.ELASTICSEARCH_DEFAULT_TYPE); This method will
* not set anything for you in the builder. </br>
* Example: </br>
* SearchRequestBuilder builder =
* CloudExecutionEnvironment.getSimpleCurrent().getSimpleSearch().getBuilder(index_name);</br>
* builder.setTypes(ElasticSearch.ELASTICSEARCH_DEFAULT_TYPE);</br>
* builder.setSize(size); builder.set String my_field_name =
* "the_field_name";</br>
* //get the max value from a field</br>
* builder.addAggregation(AggregationBuilders.max(my_field_name)); </br>
* //order the results ascending by field </br>
* builder.addSort(SortBuilders.fieldSort(my_field_name).order(SortOrder.ASC));</br>
* builder.setQuery(QueryBuilders.queryStringQuery("search string"));</br>
* </br>
*/
@Override
public SearchRequestBuilder getBuilder(IndexDefinition index)
{
if (index == null)
{
throw new RuntimeException("Null IndexDefinition");
}
return client.prepareSearch(index.getSimpleValue());
}
public ElasticSearch(TransportClient client)
{
this.client = client;
}
public boolean writeAllToCSV(IndexDefinition index, String query_string, List<SearchFieldId> sorted_header, ICsvListWriter list_writer, CellProcessor[] cell_processors)
{
if (index == null || query_string == null)
{
return false;
}
SearchResponse scrollResp = client.prepareSearch(index.getSimpleValue()).addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC).setScroll(new TimeValue(60000)).setQuery(QueryBuilders.queryStringQuery(query_string)).setSize(1000).get();
do
{
String[] document;
for (SearchHit hit : scrollResp.getHits().getHits())
{
document = new String[sorted_header.size()];
Map<String, Object> resultMap = hit.getSourceAsMap();
for (int i = 0; i < sorted_header.size(); i++)
{
if (resultMap.containsKey(sorted_header.get(i).getSimpleValue()))
{
document[i] = resultMap.get(sorted_header.get(i).getSimpleValue()).toString();
}
}
try
{
list_writer.write(Arrays.asList(document), cell_processors);
} catch (IOException e)
{
logger.error(e);
return false;
}
}
scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
} while (scrollResp.getHits().getHits().length != 0); // Zero hits mark the end of the scroll and the while
// loop.
return true;
}
/**
* Gracefully shutdown the running threads. Note: the TransportClient should be
* closed where instantiated. This is not handles by this.
*
* @return boolean if shutdown correctly or not
*/
@Override
public boolean shutdownDocumentUpsertThreadPool(int seconds)
{
long start = System.currentTimeMillis();
document_upsert_pool.shutdown();
boolean terminated = true;
try
{
terminated = document_upsert_pool.awaitTermination(seconds, TimeUnit.SECONDS);
} catch (InterruptedException e)
{
logger.log(Level.FATAL, "Shutdown of runnable pool was interrupted!", e);
}
if (!terminated)
{
logger.error("Failed to terminate in %s seconds. Calling shutdownNow...", seconds);
document_upsert_pool.shutdownNow();
}
boolean success = document_upsert_pool.isTerminated();
if (success)
{
logger.warn(String.format("Successfully terminated pool in %s milliseconds", (System.currentTimeMillis() - start)));
} else
{
logger.warn(String.format("Unsuccessful termination of pool in %s milliseconds", (System.currentTimeMillis() - start)));
}
return success;
}
/**
* Runnable class to upsert the document
*
* @author trevorbox
*
*/
private class UpsertDocumentRunnable implements Runnable
{
private Indexable object;
private Map<String, Object> data;
public UpsertDocumentRunnable(Indexable object, Map<String, Object> data)
{
this.object = object;
this.data = data;
}
@Override
public void run()
{
try
{
String index_name = object.getSimpleSearchIndexDefinition().getSimpleValue();
String document_name = object.getSimpleSearchDocumentId().getSimpleValue();
IndexResponse response = client.prepareIndex(index_name, ELASTICSEARCH_DEFAULT_TYPE, document_name).setSource(data).get();
Level level;
switch (response.getResult())
{
case CREATED:
level = Level.INFO;
break;
case UPDATED:
level = Level.INFO;
break;
default:
level = Level.FATAL;
break;
}
logger.log(level, String.format("%s %s/%s/%s %s", response.getResult().name(), index_name, ELASTICSEARCH_DEFAULT_TYPE, document_name, data));
} catch (Exception e)
{
logger.log(Level.FATAL, "Failure during upsert operation!", e);
}
}
}
/**
* Runnable class to upsert the document
*
* @author trevorbox
*
*/
private class UpsertQuietDocumentRunnable implements Runnable
{
private Indexable object;
private Map<String, Object> data;
public UpsertQuietDocumentRunnable(Indexable object, Map<String, Object> data)
{
this.object = object;
this.data = data;
}
@Override
public void run()
{
try
{
String index_name = object.getSimpleSearchIndexDefinition().getSimpleValue();
String document_name = object.getSimpleSearchDocumentId().getSimpleValue();
client.prepareIndex(index_name, ELASTICSEARCH_DEFAULT_TYPE, document_name).setSource(data).get();
} catch (Exception e)
{
logger.log(Level.FATAL, "Failure during upsert operation!", e);
}
}
}
/**
* Upsert a document to a search index asynchronously AND without logging to
* INFO
*
*
* @param object
* The Indexable object
* @return boolean If successful or not
*/
@Override
public boolean upsertQuietDocumentAsync(Indexable object)
{
if (object == null)
{
logger.error("Null object!");
return false;
}
SearchDocumentWriter writer = new SearchDocumentWriter();
object.writeSearchDocument(writer);
Map<String, Object> data = writer.getSimpleFieldsMap();
try
{
document_upsert_pool.execute(new UpsertQuietDocumentRunnable(object, data));
} catch (Exception e)
{
logger.log(Level.FATAL, "Failure during thread pool execution!", e);
return false;
}
return true;
}
/**
* Upsert a document to a search index asynchronously
*
*
* @param object
* The Indexable object
* @return boolean If successful or not
*/
@Override
public boolean upsertDocumentAsync(Indexable object)
{
if (object == null)
{
logger.error("Null object!");
return false;
}
SearchDocumentWriter writer = new SearchDocumentWriter();
object.writeSearchDocument(writer);
Map<String, Object> data = writer.getSimpleFieldsMap();
try
{
document_upsert_pool.execute(new UpsertDocumentRunnable(object, data));
} catch (Exception e)
{
logger.log(Level.FATAL, "Failure during thread pool execution!", e);
return false;
}
return true;
}
/**
* Upsert a document to a search index
*
* @param object
* The Indexable object
* @return boolean If successful or not
*/
@Override
public boolean upsertDocument(Indexable object)
{
if (object == null)
{
logger.error("Null object!");
return false;
}
try
{
SearchDocumentWriter writer = new SearchDocumentWriter();
object.writeSearchDocument(writer);
Map<String, Object> data = writer.getSimpleFieldsMap();
String index_name = object.getSimpleSearchIndexDefinition().getSimpleValue();
String document_name = object.getSimpleSearchDocumentId().getSimpleValue();
IndexResponse response = client.prepareIndex(index_name, ELASTICSEARCH_DEFAULT_TYPE, document_name).setRefreshPolicy(RefreshPolicy.IMMEDIATE).setSource(data).get();
Level level;
switch (response.getResult())
{
case CREATED:
level = Level.INFO;
break;
case UPDATED:
level = Level.INFO;
break;
default:
level = Level.FATAL;
break;
}
logger.log(level, String.format("%s %s/%s/%s %s", response.getResult().name(), index_name, ELASTICSEARCH_DEFAULT_TYPE, document_name, data));
} catch (Exception e)
{
logger.log(Level.FATAL, String.format("Failure during upsert operation of Document id:%s on Index:%s", object.getSimpleSearchDocumentId().getSimpleValue(), object.getSimpleSearchIndexDefinition().getSimpleValue()), e);
return false;
}
return true;
}
/**
* Search an index with a query string.
*
* @see <a href=
* "https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html">query-dsl-query-string-query</a>
*
* @param index
* The IndexDefinition
* @param request
* The StandardSearchRequest
* @return JSONServletResponse
*/
@Override
public JSONServletResponse search(IndexDefinition index, StandardSearchRequest request)
{
if (index == null || request == null)
{
return new SearchResponseError(request, "Null parameter(s)!");
}
try
{
String index_name = index.getSimpleValue();
int from = request.getSimpleStartResultsAfter();
int size = request.getSimpleMaxResults();
SearchRequestBuilder builder = client.prepareSearch(index_name);
builder.setTypes(ELASTICSEARCH_DEFAULT_TYPE);
builder.setFrom(from);
builder.setSize(size);
builder.setQuery(QueryBuilders.queryStringQuery(request.getSimpleQueryString()));
// Sorting
for ( SortBy sort_by : request.getSimpleSort().getSimpleSortOrder() )
{
FieldSortBuilder sort_builder = getSort(sort_by, null);
if ( sort_builder == null ) continue;
builder.addSort(sort_builder);
}
SearchResponse response = builder.get();
List<OneSearchResult> results = new LinkedList<OneSearchResult>();
response.getHits().forEach(hit ->
{
Map<FieldName, String> map = new HashMap<FieldName, String>();
hit.getSourceAsMap().forEach((k, v) ->
{
map.put(new FieldName(k), v.toString());
});
results.add(new OneSearchResult(map));
});
long total_hits = response.getHits().totalHits;
int next_page = from + size;
int previous_page = (from - size) < 0 ? 0 : (from - size);
boolean has_more_results = total_hits > next_page;
boolean has_previous_results = from > 0;
Level level;
switch (response.status())
{
case OK:
level = Level.INFO;
break;
default:
level = Level.WARN;
break;
}
SearchResponseOK ok = new SearchResponseOK(request, results, from, has_more_results, has_previous_results, next_page, previous_page, total_hits);
logger.log(level, String.format("QUERY:%s INDEX:%s STATUS:%s HITS:%s TOTAL_HITS:%s MAX_RESULTS:%d START_RESULTS_AFTER:%d", ok.getSimpleSearchRequest().getSimpleQueryString(), index.getSimpleValue(), response.status(), results.size(), ok.getSimpleTotalHits(), ok.getSimpleSearchRequest().getSimpleMaxResults(), ok.getSimpleSearchRequest().getSimpleStartResultsAfter()));
logger.trace(String.format("FIRST_RESULT_IDX:%s HAS_MORE_RESULTS:%s HAS_PREVIOUS_RESULTS:%s START_OF_NEXT_PAGE_OF_RESULTS:%s START_OF_PREVIOUS_PAGE_OF_RESULTS:%s", ok.getSimpleFirstResultIdx(), ok.getSimpleHasMoreResults(), ok.getSimpleHasMoreResults(), ok.getSimpleStartOfNextPageOfResults(), ok.getSimpleStartOfPreviousPageOfResults()));
logger.trace(ok.getSimpleResults().toString());
return ok;
} catch (Exception e)
{
if (e.getCause() instanceof QueryShardException)
{
logger.warn(String.format("%s on index %s", e.getCause().getMessage(), index.getSimpleValue()));
return new SearchResponseError(request, e.getCause().getMessage());
} else
{
logger.error(String.format("Search failed for %s on index %s", request.getSimpleQueryString(), index.getSimpleValue()), e);
return new SearchResponseError(request, e.getMessage());
}
}
}
/**
* Search an index with a query string and return a List of OneSearchResult 's.
*
* @see <a href=
* "https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html">query-dsl-query-string-query</a>
*
* @param index
* The IndexDefinition
* @param request
* The StandardSearchRequest
* @param default_value
* The default value should it fail
* @return List<OneSearchResult>
*/
@Override
public List<OneSearchResultWithTyping> search(IndexDefinition index, StandardSearchRequest request, List<OneSearchResultWithTyping> default_value)
{
if (index == null || request == null)
{
logger.warn(String.format("Search failed: Null parameter(s) for %s", request));
return default_value;
}
try
{
String index_name = index.getSimpleValue();
int from = request.getSimpleStartResultsAfter();
int size = request.getSimpleMaxResults();
SearchRequestBuilder builder = client.prepareSearch(index_name);
builder.setTypes(ELASTICSEARCH_DEFAULT_TYPE);
builder.setFrom(from);
builder.setSize(size);
builder.setQuery(QueryBuilders.queryStringQuery(request.getSimpleQueryString()));
// Sorting
for ( SortBy sort_by : request.getSimpleSort().getSimpleSortOrder() )
{
FieldSortBuilder sort_builder = getSort(sort_by, null);
if ( sort_builder == null ) continue;
builder.addSort(sort_builder);
}
SearchResponse response = builder.get();
List<OneSearchResultWithTyping> results = new LinkedList<OneSearchResultWithTyping>();
response.getHits().forEach(hit ->
{
Map<FieldName, String[]> map = new HashMap<FieldName, String[]>();
hit.getSourceAsMap().forEach((k, v) ->
{
FieldName name = new FieldName(k);
String[] array_val = map.get(name);
String[] new_array_val = null;
if ( v instanceof ArrayList<?> )
{
List<Object> array_as_list = (ArrayList<Object>) v;
new_array_val = new String[array_as_list.size()];
for ( int i = 0; i < array_as_list.size(); i++ )
{
new_array_val[i] = String.valueOf(array_as_list.get(i));
}
}
else
{
if ( array_val == null ) array_val = new String[0];
new_array_val = new String[] {String.valueOf(v)};
}
if ( new_array_val != null ) map.put(name, new_array_val);
});
results.add(new OneSearchResultWithTyping(map));
});
int next_page = from + size;
boolean has_more_results = response.getHits().totalHits > next_page;
boolean has_previous_results = from != 0;
Level level;
switch (response.status())
{
case OK:
level = Level.INFO;
break;
default:
level = Level.WARN;
break;
}
logger.log(level, String.format("QUERY:%s INDEX:%s STATUS:%s HITS:%s TOTAL_HITS:%s MAX_RESULTS:%d START_RESULTS_AFTER:%d", request, index.getSimpleValue(), response.status(), results.size(), response.getHits().totalHits, request.getSimpleMaxResults(), request.getSimpleStartResultsAfter()));
logger.trace(String.format("FIRST_RESULT_IDX:%s HAS_MORE_RESULTS:%s HAS_PREVIOUS_RESULTS:%s START_OF_NEXT_PAGE_OF_RESULTS:%s START_OF_PREVIOUS_PAGE_OF_RESULTS:%s",from, has_more_results, has_previous_results, next_page, from));
logger.trace(results.toString());
return results;
} catch (Exception e)
{
logger.warn(String.format("Search failed for %s", request), e);
return default_value;
}
}
/**
* Test if the index exists or not
*
* @param index
* IndexDefinition
* @return boolean if the index exists or not
*/
@Override
public boolean indexExists(IndexDefinition index)
{
if (index == null)
{
logger.fatal("Cannot check the existence of a null Index");
return false;
}
try
{
return client.admin().indices().prepareExists(index.getSimpleValue()).get().isExists();
} catch (Exception e)
{
logger.log(Level.FATAL, "Failed to check if index exists", e);
return false;
}
}
/**
* Test if the index exists or not
*
* @param index
* SearchIndexDefinition
* @return boolean if the index exists or not
*/
@Override
public boolean indexExists(SearchIndexDefinition index)
{
if (index == null)
{
logger.fatal("Cannot check the existence of a null Index");
return false;
}
try
{
return client.admin().indices().prepareExists(index.getSimpleIndex().getSimpleValue()).get().isExists();
} catch (Exception e)
{
logger.log(Level.FATAL, "Failed to check if index exists", e);
return false;
}
}
/**
* An index is properly configured if it exists and its field names and
* datatypes match
*
* @param index
* SearchIndexDefinition
* @return boolean if the index is properly configured or not
*/
@Override
public boolean indexProperlyConfigured(SearchIndexDefinition index)
{
if (index == null)
{
return false;
}
if (indexExists(index))
{
// compare the expected index fields to the actual index fields
Map<String, String> expected = new HashMap<String, String>();
index.getSimpleFields().forEach(fields ->
{
expected.put(fields.getSimpleFieldName().getSimpleName(), fields.getSimpleType().getSimpleCode());
});
try
{
GetMappingsResponse response = client.admin().indices().prepareGetMappings(index.getSimpleIndex().getSimpleValue()).get();
String json = response.getMappings().get(index.getSimpleIndex().getSimpleValue()).get(ELASTICSEARCH_DEFAULT_TYPE).source().string();
Map<String, String> actual = new HashMap<String, String>();
new ObjectMapper().readTree(json).get(ELASTICSEARCH_DEFAULT_TYPE).get("properties").fields().forEachRemaining(fieldMapping ->
{
if ( !fieldMapping.getKey().contains(SORT_FIELD_NAME_JIMMUTABLE) ) // Skip our keyword fields
{
actual.put(fieldMapping.getKey(), fieldMapping.getValue().get("type").asText());
}
});
if (!expected.equals(actual))
{
logger.info(String.format("Index: %s not properly configured", index.getSimpleIndex().getSimpleValue()));
logger.info(String.format("Expected fields=%s", expected));
logger.info(String.format("Actual fields=%s", actual));
if (expected.size() > actual.size())
{
logger.info("Issue lies in that an actual search field is missing from what is expected to be written");
}
else if(expected.size() < actual.size())
{
logger.info("Issue lies in that an expected search field is missing from what's actually being written");
}
for (String key : expected.keySet())
{
String expected_value = expected.get(key);
String actual_value = actual.get(key);
if (!expected_value.equals(actual_value))
{
logger.info(String.format("Issue lies in that for Field %s the expected field value is: %s", key, expected_value));
logger.info(String.format("However, currently for Field %s the actual field value is: %s", key, actual_value));
}
}
return false;
}
return true;
} catch (Exception e)
{
logger.log(Level.FATAL, String.format("Failed to get the index mapping for index %s", index.getSimpleIndex().getSimpleValue()), e);
}
}
return false;
}
private boolean createIndex(SearchIndexDefinition index)
{
if (index == null)
{
logger.fatal("Cannot create a null Index");
return false;
}
try
{
XContentBuilder mappingBuilder = jsonBuilder();
mappingBuilder.startObject().startObject(ELASTICSEARCH_DEFAULT_TYPE).startObject("properties");
for (SearchIndexFieldDefinition field : index.getSimpleFields())
{
// if (field.getSimpleType().equals(SearchIndexFieldType.OBJECTID))
// {
// // EXPLICIT MAPPING FOR OBJECTID - does not rely on enum's simple code
// // https://www.elastic.co/blog/strings-are-dead-long-live-strings
// mappingBuilder.startObject(field.getSimpleFieldName().getSimpleName());
// /* */mappingBuilder.field("type", "text");
// /* */mappingBuilder.startObject("fields");
// /* */mappingBuilder.startObject("keyword");
// /* */mappingBuilder.field("type", "keyword");
// /* */mappingBuilder.field("ignore_above", 256);
// /* */mappingBuilder.endObject();
// /* */mappingBuilder.endObject();
// mappingBuilder.endObject();
// } else
// {
mappingBuilder.startObject(field.getSimpleFieldName().getSimpleName());
/* */mappingBuilder.field("type", field.getSimpleType().getSimpleCode());
mappingBuilder.endObject();
// }
// Create a keyword for every text field
if ( field.getSimpleType() == SearchIndexFieldType.TEXT )
{
mappingBuilder.startObject(getSortFieldNameText(field.getSimpleFieldName()));
mappingBuilder.field("type", SearchIndexFieldType.ATOM.getSimpleCode());
mappingBuilder.endObject();
}
// Create a long field for every instant field
if ( field.getSimpleType() == SearchIndexFieldType.INSTANT )
{
mappingBuilder.startObject(getSortFieldNameInstant(field.getSimpleFieldName()));
mappingBuilder.field("type", SearchIndexFieldType.LONG.getSimpleCode());
mappingBuilder.endObject();
}
// Create a long field for every timeofday field
if ( field.getSimpleType() == SearchIndexFieldType.TIMEOFDAY )
{
mappingBuilder.startObject(getSortFieldNameTimeOfDay(field.getSimpleFieldName()));
mappingBuilder.field("type", SearchIndexFieldType.LONG.getSimpleCode());
mappingBuilder.endObject();
}
}
mappingBuilder.endObject().endObject().endObject();
CreateIndexResponse createResponse = client.admin().indices().prepareCreate(index.getSimpleIndex().getSimpleValue()).addMapping(ELASTICSEARCH_DEFAULT_TYPE, mappingBuilder).get();
if (!createResponse.isAcknowledged())
{
logger.fatal(String.format("Index Creation not acknowledged for index %s", index.getSimpleIndex().getSimpleValue()));
return false;
}
} catch (Exception e)
{
logger.log(Level.FATAL, String.format("Failed to generate mapping json for index %s", index.getSimpleIndex().getSimpleValue()), e);
return false;
}
logger.info(String.format("Created index %s", index.getSimpleIndex().getSimpleValue()));
return true;
}
/**
* Deletes an entire index
*
* @param index
* SearchIndexDefinition
* @return boolean - true if successfully deleted, else false
*/
public boolean deleteIndex(SearchIndexDefinition index)
{
if (index == null)
{
logger.fatal("Cannot delete a null Index");
return false;
}
try
{
DeleteIndexResponse deleteResponse = client.admin().indices().prepareDelete(index.getSimpleIndex().getSimpleValue()).get();
if (!deleteResponse.isAcknowledged())
{
logger.fatal(String.format("Index Deletion not acknowledged for index %s", index.getSimpleIndex().getSimpleValue()));
return false;
}
} catch (Exception e)
{
logger.fatal(String.format("Index Deletion failed for index %s", index.getSimpleIndex().getSimpleValue()));
return false;
}
logger.info(String.format("Deleted index %s", index.getSimpleIndex().getSimpleValue()));
return true;
}
/**
* Upsert if the index doesn't exist or is not properly configured already
*
* BE CAREFUL!!!
*
* @param index
* SearchIndexDefinition
* @return boolean if the upsert was successful or not
*/
@Override
public boolean upsertIndex(SearchIndexDefinition index)
{
if (index == null)
{
logger.fatal("Cannot upsert a null Index");
return false;
}
// if it exists and is not configured correctly delete and add
if (indexExists(index))
{
if (!indexProperlyConfigured(index))
{
if (deleteIndex(index))
{
return createIndex(index);
} else
{
// deletion failed
return false;
}
}
} else
{
// index is new
return createIndex(index);
}
// index exists and already configured correctly
logger.info(String.format("No upsert needed for index %s", index.getSimpleIndex().getSimpleValue()));
return true;
}
/**
* Delete a document within an index
*
* @param index
* @param document_id
* @return
*/
public boolean deleteDocument(IndexDefinition index, SearchDocumentId document_id)
{
if (index == null || document_id == null)
{
logger.fatal("Null index or document id");
return false;
}
try
{
DeleteResponse response = client.prepareDelete(index.getSimpleValue(), ELASTICSEARCH_DEFAULT_TYPE, document_id.getSimpleValue()).setRefreshPolicy(RefreshPolicy.IMMEDIATE).get();
logger.info(String.format("Result:%s SearchDocumentId:%s IndexDefinition:%s", response.getResult(), response.getId(), response.getIndex()));
return response.getResult().equals(Result.DELETED);
} catch (Exception e)
{
logger.error(e);
return false;
}
}
/**
* Using a SortBy object, construct a SortBuilder used by ElasticSearch. This method handles the unique sorting cases for Text, Time of Day, and Instant.
*
* @param sort_by
* @param default_value
* @return
*/
static private FieldSortBuilder getSort(SortBy sort_by, FieldSortBuilder default_value)
{
SortOrder order = null;
if ( sort_by.getSimpleDirection() == SortDirection.ASCENDING ) order = SortOrder.ASC;
if ( sort_by.getSimpleDirection() == SortDirection.DESCENDING ) order = SortOrder.DESC;
if ( order == null ) return default_value;
FieldName field_name = sort_by.getSimpleField().getSimpleFieldName();
String sort_on_string = field_name.getSimpleName();
if ( sort_by.getSimpleField().getSimpleType() == SearchIndexFieldType.TEXT ) sort_on_string = getSortFieldNameText(sort_by.getSimpleField().getSimpleFieldName());
if ( sort_by.getSimpleField().getSimpleType() == SearchIndexFieldType.TIMEOFDAY ) sort_on_string = getSortFieldNameTimeOfDay(sort_by.getSimpleField().getSimpleFieldName());
if ( sort_by.getSimpleField().getSimpleType() == SearchIndexFieldType.INSTANT ) sort_on_string = getSortFieldNameInstant(sort_by.getSimpleField().getSimpleFieldName());
return SortBuilders.fieldSort(sort_on_string).order(order).unmappedType(SearchIndexFieldType.ATOM.getSimpleCode());
}
/**
* Sorting on text fields is impossible without enabling fielddata in ElasticSearch. To get around this, we instead use a keyword field for every text field written.
* This solution is recommended by ElasticSearch over enabling fielddata. For more information, read here:
*
* https://www.elastic.co/guide/en/elasticsearch/reference/5.4/fielddata.html#before-enabling-fielddata
* https://www.elastic.co/blog/support-in-the-wild-my-biggest-elasticsearch-problem-at-scale
*
* @param field
* @return
*/
static public String getSortFieldNameText(FieldName field)
{
return getSortFieldNameText(field.getSimpleName());
}
/**
* Sorting on text fields is impossible without enabling fielddata in ElasticSearch. To get around this, we instead use a keyword field for every text field written.
* This solution is recommended by ElasticSearch over enabling fielddata. For more information, read here:
*
* https://www.elastic.co/guide/en/elasticsearch/reference/5.4/fielddata.html#before-enabling-fielddata
* https://www.elastic.co/blog/support-in-the-wild-my-biggest-elasticsearch-problem-at-scale
*
* @param field_name
* @return
*/
static public String getSortFieldNameText(String field_name)
{
return field_name + "_" + SORT_FIELD_NAME_JIMMUTABLE + "_" + SearchIndexFieldType.ATOM.getSimpleCode();
}
/**
* In order to sort TimeOfDay objects, we need to look at the ms_from_midnight field from within. This method creates a consistent field name to sort by.
* @param field
* @return
*/
static public String getSortFieldNameTimeOfDay(FieldName field)
{
return getSortFieldNameTimeOfDay(field.getSimpleName());
}
/**
* In order to sort TimeOfDay objects, we need to look at the ms_from_midnight field from within. This method creates a consistent field name to sort by.
* @param field_name
* @return
*/
static public String getSortFieldNameTimeOfDay(String field_name)
{
return field_name + "_" + SORT_FIELD_NAME_JIMMUTABLE + "_" + TimeOfDay.FIELD_MS_FROM_MIDNIGHT.getSimpleFieldName().getSimpleName();
}
/**
* In order to sort Instant objects, we need to look at the ms_from_epoch field from within. This method creates a consistent field name to sort by.
* @param field
* @return
*/
static public String getSortFieldNameInstant(FieldName field)
{
return getSortFieldNameInstant(field.getSimpleName());
}
/**
* In order to sort Instant objects, we need to look at the ms_from_epoch field from within. This method creates a consistent field name to sort by.
* @param field_name
* @return
*/
static public String getSortFieldNameInstant(String field_name)
{
return field_name + "_" + SORT_FIELD_NAME_JIMMUTABLE + "_" + Instant.FIELD_MS_FROM_EPOCH.getSimpleFieldName().getSimpleName();
}
}
| Same changes to is index properly configured | cloud/src/main/java/org/jimmutable/cloud/elasticsearch/ElasticSearch.java | Same changes to is index properly configured | <ide><path>loud/src/main/java/org/jimmutable/cloud/elasticsearch/ElasticSearch.java
<ide> import java.io.IOException;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<del>import java.util.HashMap;
<add>//import java.util.HashMap;
<ide> import java.util.LinkedList;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.TreeMap;
<ide> import java.util.concurrent.ExecutorService;
<ide> import java.util.concurrent.LinkedBlockingQueue;
<ide> import java.util.concurrent.ThreadPoolExecutor;
<ide> import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
<ide> import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
<ide> import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse;
<add>import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
<ide> import org.elasticsearch.action.delete.DeleteResponse;
<ide> import org.elasticsearch.action.index.IndexResponse;
<ide> import org.elasticsearch.action.search.SearchRequestBuilder;
<ide> builder.setFrom(from);
<ide> builder.setSize(size);
<ide> builder.setQuery(QueryBuilders.queryStringQuery(request.getSimpleQueryString()));
<del>
<add>
<ide> // Sorting
<del> for ( SortBy sort_by : request.getSimpleSort().getSimpleSortOrder() )
<add> for (SortBy sort_by : request.getSimpleSort().getSimpleSortOrder())
<ide> {
<ide> FieldSortBuilder sort_builder = getSort(sort_by, null);
<del> if ( sort_builder == null ) continue;
<del>
<add> if (sort_builder == null)
<add> continue;
<add>
<ide> builder.addSort(sort_builder);
<ide> }
<ide>
<ide>
<ide> response.getHits().forEach(hit ->
<ide> {
<del> Map<FieldName, String> map = new HashMap<FieldName, String>();
<add> Map<FieldName, String> map = new TreeMap<FieldName, String>();
<ide> hit.getSourceAsMap().forEach((k, v) ->
<ide> {
<ide> map.put(new FieldName(k), v.toString());
<ide> }
<ide>
<ide> }
<del>
<add>
<ide> /**
<ide> * Search an index with a query string and return a List of OneSearchResult 's.
<ide> *
<ide> builder.setFrom(from);
<ide> builder.setSize(size);
<ide> builder.setQuery(QueryBuilders.queryStringQuery(request.getSimpleQueryString()));
<del>
<add>
<ide> // Sorting
<del> for ( SortBy sort_by : request.getSimpleSort().getSimpleSortOrder() )
<add> for (SortBy sort_by : request.getSimpleSort().getSimpleSortOrder())
<ide> {
<ide> FieldSortBuilder sort_builder = getSort(sort_by, null);
<del> if ( sort_builder == null ) continue;
<del>
<add> if (sort_builder == null)
<add> continue;
<add>
<ide> builder.addSort(sort_builder);
<ide> }
<ide>
<ide>
<ide> response.getHits().forEach(hit ->
<ide> {
<del> Map<FieldName, String[]> map = new HashMap<FieldName, String[]>();
<add> Map<FieldName, String[]> map = new TreeMap<FieldName, String[]>();
<ide> hit.getSourceAsMap().forEach((k, v) ->
<ide> {
<ide> FieldName name = new FieldName(k);
<ide> String[] array_val = map.get(name);
<del>
<add>
<ide> String[] new_array_val = null;
<del>
<del> if ( v instanceof ArrayList<?> )
<add>
<add> if (v instanceof ArrayList<?>)
<ide> {
<del> List<Object> array_as_list = (ArrayList<Object>) v;
<add> List<Object> array_as_list = (ArrayList<Object>) v;
<ide> new_array_val = new String[array_as_list.size()];
<del>
<del> for ( int i = 0; i < array_as_list.size(); i++ )
<add>
<add> for (int i = 0; i < array_as_list.size(); i++)
<ide> {
<ide> new_array_val[i] = String.valueOf(array_as_list.get(i));
<ide> }
<add> } else
<add> {
<add> if (array_val == null)
<add> array_val = new String[0];
<add> new_array_val = new String[]
<add> { String.valueOf(v) };
<ide> }
<del> else
<del> {
<del> if ( array_val == null ) array_val = new String[0];
<del> new_array_val = new String[] {String.valueOf(v)};
<del> }
<del>
<del> if ( new_array_val != null ) map.put(name, new_array_val);
<add>
<add> if (new_array_val != null)
<add> map.put(name, new_array_val);
<ide> });
<ide> results.add(new OneSearchResultWithTyping(map));
<ide> });
<ide> }
<ide>
<ide> logger.log(level, String.format("QUERY:%s INDEX:%s STATUS:%s HITS:%s TOTAL_HITS:%s MAX_RESULTS:%d START_RESULTS_AFTER:%d", request, index.getSimpleValue(), response.status(), results.size(), response.getHits().totalHits, request.getSimpleMaxResults(), request.getSimpleStartResultsAfter()));
<del> logger.trace(String.format("FIRST_RESULT_IDX:%s HAS_MORE_RESULTS:%s HAS_PREVIOUS_RESULTS:%s START_OF_NEXT_PAGE_OF_RESULTS:%s START_OF_PREVIOUS_PAGE_OF_RESULTS:%s",from, has_more_results, has_previous_results, next_page, from));
<add> logger.trace(String.format("FIRST_RESULT_IDX:%s HAS_MORE_RESULTS:%s HAS_PREVIOUS_RESULTS:%s START_OF_NEXT_PAGE_OF_RESULTS:%s START_OF_PREVIOUS_PAGE_OF_RESULTS:%s", from, has_more_results, has_previous_results, next_page, from));
<ide> logger.trace(results.toString());
<ide>
<ide> return results;
<ide> {
<ide>
<ide> // compare the expected index fields to the actual index fields
<del> Map<String, String> expected = new HashMap<String, String>();
<add> Map<String, String> expected = new TreeMap<String, String>();
<ide> index.getSimpleFields().forEach(fields ->
<ide> {
<ide> expected.put(fields.getSimpleFieldName().getSimpleName(), fields.getSimpleType().getSimpleCode());
<ide>
<ide> String json = response.getMappings().get(index.getSimpleIndex().getSimpleValue()).get(ELASTICSEARCH_DEFAULT_TYPE).source().string();
<ide>
<del> Map<String, String> actual = new HashMap<String, String>();
<add> Map<String, String> actual = new TreeMap<String, String>();
<ide>
<ide> new ObjectMapper().readTree(json).get(ELASTICSEARCH_DEFAULT_TYPE).get("properties").fields().forEachRemaining(fieldMapping ->
<ide> {
<del> if ( !fieldMapping.getKey().contains(SORT_FIELD_NAME_JIMMUTABLE) ) // Skip our keyword fields
<add> if (!fieldMapping.getKey().contains(SORT_FIELD_NAME_JIMMUTABLE)) // Skip our keyword fields
<ide> {
<ide> actual.put(fieldMapping.getKey(), fieldMapping.getValue().get("type").asText());
<ide> }
<ide> if (!expected.equals(actual))
<ide> {
<ide>
<del> logger.info(String.format("Index: %s not properly configured", index.getSimpleIndex().getSimpleValue()));
<del> logger.info(String.format("Expected fields=%s", expected));
<del> logger.info(String.format("Actual fields=%s", actual));
<del>
<add> logger.warn(String.format("Index: %s not properly configured", index.getSimpleIndex().getSimpleValue()));
<add> logger.warn(String.format("Expected fields=%s", expected));
<add> logger.warn(String.format("Actual fields=%s", actual));
<add>
<ide> if (expected.size() > actual.size())
<ide> {
<del> logger.info("Issue lies in that an actual search field is missing from what is expected to be written");
<add> logger.warn("There are field missing in the current index.");
<add> } else if (expected.size() < actual.size())
<add> {
<add> logger.info("There are more fields than expected in the current index.");
<ide> }
<del> else if(expected.size() < actual.size())
<del> {
<del> logger.info("Issue lies in that an expected search field is missing from what's actually being written");
<del> }
<del> for (String key : expected.keySet())
<del> {
<del> String expected_value = expected.get(key);
<del> String actual_value = actual.get(key);
<del> if (!expected_value.equals(actual_value))
<del> {
<del> logger.info(String.format("Issue lies in that for Field %s the expected field value is: %s", key, expected_value));
<del> logger.info(String.format("However, currently for Field %s the actual field value is: %s", key, actual_value));
<del> }
<del> }
<add>
<add> //
<add> //
<add> // for (String key : expected.keySet())
<add> // {
<add> // String expected_value = expected.get(key);
<add> // String actual_value = actual.get(key);
<add> // if (!expected_value.equals(actual_value))
<add> // {
<add> // logger.info(String.format("Issue lies in that for Field %s the expected field
<add> // value is: %s", key, expected_value));
<add> // logger.info(String.format("However, currently for Field %s the actual field
<add> // value is: %s", key, actual_value));
<add> // }
<add> // }
<ide>
<ide> return false;
<ide> }
<ide>
<ide> }
<ide>
<del>
<ide> private boolean createIndex(SearchIndexDefinition index)
<ide> {
<ide> if (index == null)
<ide> try
<ide> {
<ide>
<add> CreateIndexResponse createResponse = client.admin().indices().prepareCreate(index.getSimpleIndex().getSimpleValue()).addMapping(ELASTICSEARCH_DEFAULT_TYPE, getMappingBuilder(index, null)).get();
<add>
<add> if (!createResponse.isAcknowledged())
<add> {
<add> logger.fatal(String.format("Index Creation not acknowledged for index %s", index.getSimpleIndex().getSimpleValue()));
<add> return false;
<add> }
<add>
<add> } catch (Exception e)
<add> {
<add> logger.log(Level.FATAL, String.format("Failed to generate mapping json for index %s", index.getSimpleIndex().getSimpleValue()), e);
<add> return false;
<add> }
<add>
<add> logger.info(String.format("Created index %s", index.getSimpleIndex().getSimpleValue()));
<add> return true;
<add> }
<add>
<add> /**
<add> * Deletes an entire index
<add> *
<add> * @param index
<add> * SearchIndexDefinition
<add> * @return boolean - true if successfully deleted, else false
<add> */
<add> public boolean deleteIndex(SearchIndexDefinition index)
<add> {
<add> if (index == null)
<add> {
<add> logger.fatal("Cannot delete a null Index");
<add> return false;
<add> }
<add>
<add> try
<add> {
<add> DeleteIndexResponse deleteResponse = client.admin().indices().prepareDelete(index.getSimpleIndex().getSimpleValue()).get();
<add> if (!deleteResponse.isAcknowledged())
<add> {
<add> logger.fatal(String.format("Index Deletion not acknowledged for index %s", index.getSimpleIndex().getSimpleValue()));
<add> return false;
<add> }
<add>
<add> } catch (Exception e)
<add> {
<add> logger.fatal(String.format("Index Deletion failed for index %s", index.getSimpleIndex().getSimpleValue()));
<add> return false;
<add> }
<add> logger.info(String.format("Deleted index %s", index.getSimpleIndex().getSimpleValue()));
<add> return true;
<add>
<add> }
<add>
<add> /**
<add> * Upsert if the index doesn't exist or is not properly configured already
<add> *
<add> * BE CAREFUL!!!
<add> *
<add> * @param index
<add> * SearchIndexDefinition
<add> * @return boolean if the upsert was successful or not
<add> */
<add> @Override
<add> public boolean upsertIndex(SearchIndexDefinition index)
<add> {
<add>
<add> if (index == null)
<add> {
<add> logger.fatal("Cannot upsert a null Index");
<add> return false;
<add> }
<add>
<add> // if it exists and is not configured correctly delete and add
<add> if (indexExists(index))
<add> {
<add> if (!indexProperlyConfigured(index))
<add> {
<add> if (deleteIndex(index))
<add> {
<add> return createIndex(index);
<add> } else
<add> {
<add> // deletion failed
<add> return false;
<add> }
<add> }
<add> } else
<add> {
<add> // index is new
<add> return createIndex(index);
<add> }
<add>
<add> // index exists and already configured correctly
<add> logger.info(String.format("No upsert needed for index %s", index.getSimpleIndex().getSimpleValue()));
<add> return true;
<add> }
<add>
<add> /**
<add> * Delete a document within an index
<add> *
<add> * @param index
<add> * @param document_id
<add> * @return
<add> */
<add> public boolean deleteDocument(IndexDefinition index, SearchDocumentId document_id)
<add> {
<add>
<add> if (index == null || document_id == null)
<add> {
<add> logger.fatal("Null index or document id");
<add> return false;
<add> }
<add>
<add> try
<add> {
<add> DeleteResponse response = client.prepareDelete(index.getSimpleValue(), ELASTICSEARCH_DEFAULT_TYPE, document_id.getSimpleValue()).setRefreshPolicy(RefreshPolicy.IMMEDIATE).get();
<add>
<add> logger.info(String.format("Result:%s SearchDocumentId:%s IndexDefinition:%s", response.getResult(), response.getId(), response.getIndex()));
<add>
<add> return response.getResult().equals(Result.DELETED);
<add> } catch (Exception e)
<add> {
<add> logger.error(e);
<add> return false;
<add> }
<add> }
<add>
<add> /**
<add> * Using a SortBy object, construct a SortBuilder used by ElasticSearch. This
<add> * method handles the unique sorting cases for Text, Time of Day, and Instant.
<add> *
<add> * @param sort_by
<add> * @param default_value
<add> * @return
<add> */
<add> static private FieldSortBuilder getSort(SortBy sort_by, FieldSortBuilder default_value)
<add> {
<add> SortOrder order = null;
<add> if (sort_by.getSimpleDirection() == SortDirection.ASCENDING)
<add> order = SortOrder.ASC;
<add> if (sort_by.getSimpleDirection() == SortDirection.DESCENDING)
<add> order = SortOrder.DESC;
<add>
<add> if (order == null)
<add> return default_value;
<add>
<add> FieldName field_name = sort_by.getSimpleField().getSimpleFieldName();
<add> String sort_on_string = field_name.getSimpleName();
<add>
<add> if (sort_by.getSimpleField().getSimpleType() == SearchIndexFieldType.TEXT)
<add> sort_on_string = getSortFieldNameText(sort_by.getSimpleField().getSimpleFieldName());
<add> if (sort_by.getSimpleField().getSimpleType() == SearchIndexFieldType.TIMEOFDAY)
<add> sort_on_string = getSortFieldNameTimeOfDay(sort_by.getSimpleField().getSimpleFieldName());
<add> if (sort_by.getSimpleField().getSimpleType() == SearchIndexFieldType.INSTANT)
<add> sort_on_string = getSortFieldNameInstant(sort_by.getSimpleField().getSimpleFieldName());
<add>
<add> return SortBuilders.fieldSort(sort_on_string).order(order).unmappedType(SearchIndexFieldType.ATOM.getSimpleCode());
<add> }
<add>
<add> /**
<add> * Sorting on text fields is impossible without enabling fielddata in
<add> * ElasticSearch. To get around this, we instead use a keyword field for every
<add> * text field written. This solution is recommended by ElasticSearch over
<add> * enabling fielddata. For more information, read here:
<add> *
<add> * https://www.elastic.co/guide/en/elasticsearch/reference/5.4/fielddata.html#before-enabling-fielddata
<add> * https://www.elastic.co/blog/support-in-the-wild-my-biggest-elasticsearch-problem-at-scale
<add> *
<add> * @param field
<add> * @return
<add> */
<add> static public String getSortFieldNameText(FieldName field)
<add> {
<add> return getSortFieldNameText(field.getSimpleName());
<add> }
<add>
<add> /**
<add> * Sorting on text fields is impossible without enabling fielddata in
<add> * ElasticSearch. To get around this, we instead use a keyword field for every
<add> * text field written. This solution is recommended by ElasticSearch over
<add> * enabling fielddata. For more information, read here:
<add> *
<add> * https://www.elastic.co/guide/en/elasticsearch/reference/5.4/fielddata.html#before-enabling-fielddata
<add> * https://www.elastic.co/blog/support-in-the-wild-my-biggest-elasticsearch-problem-at-scale
<add> *
<add> * @param field_name
<add> * @return
<add> */
<add> static public String getSortFieldNameText(String field_name)
<add> {
<add> return field_name + "_" + SORT_FIELD_NAME_JIMMUTABLE + "_" + SearchIndexFieldType.ATOM.getSimpleCode();
<add> }
<add>
<add> /**
<add> * In order to sort TimeOfDay objects, we need to look at the ms_from_midnight
<add> * field from within. This method creates a consistent field name to sort by.
<add> *
<add> * @param field
<add> * @return
<add> */
<add> static public String getSortFieldNameTimeOfDay(FieldName field)
<add> {
<add> return getSortFieldNameTimeOfDay(field.getSimpleName());
<add> }
<add>
<add> /**
<add> * In order to sort TimeOfDay objects, we need to look at the ms_from_midnight
<add> * field from within. This method creates a consistent field name to sort by.
<add> *
<add> * @param field_name
<add> * @return
<add> */
<add> static public String getSortFieldNameTimeOfDay(String field_name)
<add> {
<add> return field_name + "_" + SORT_FIELD_NAME_JIMMUTABLE + "_" + TimeOfDay.FIELD_MS_FROM_MIDNIGHT.getSimpleFieldName().getSimpleName();
<add> }
<add>
<add> /**
<add> * In order to sort Instant objects, we need to look at the ms_from_epoch field
<add> * from within. This method creates a consistent field name to sort by.
<add> *
<add> * @param field
<add> * @return
<add> */
<add> static public String getSortFieldNameInstant(FieldName field)
<add> {
<add> return getSortFieldNameInstant(field.getSimpleName());
<add> }
<add>
<add> /**
<add> * In order to sort Instant objects, we need to look at the ms_from_epoch field
<add> * from within. This method creates a consistent field name to sort by.
<add> *
<add> * @param field_name
<add> * @return
<add> */
<add> static public String getSortFieldNameInstant(String field_name)
<add> {
<add> return field_name + "_" + SORT_FIELD_NAME_JIMMUTABLE + "_" + Instant.FIELD_MS_FROM_EPOCH.getSimpleFieldName().getSimpleName();
<add> }
<add>
<add> private XContentBuilder getMappingBuilder(SearchIndexDefinition index, XContentBuilder default_value)
<add> {
<add> try
<add> {
<ide> XContentBuilder mappingBuilder = jsonBuilder();
<ide> mappingBuilder.startObject().startObject(ELASTICSEARCH_DEFAULT_TYPE).startObject("properties");
<ide> for (SearchIndexFieldDefinition field : index.getSimpleFields())
<ide> /* */mappingBuilder.field("type", field.getSimpleType().getSimpleCode());
<ide> mappingBuilder.endObject();
<ide> // }
<del>
<add>
<ide> // Create a keyword for every text field
<del> if ( field.getSimpleType() == SearchIndexFieldType.TEXT )
<add> if (field.getSimpleType() == SearchIndexFieldType.TEXT)
<ide> {
<ide> mappingBuilder.startObject(getSortFieldNameText(field.getSimpleFieldName()));
<del> mappingBuilder.field("type", SearchIndexFieldType.ATOM.getSimpleCode());
<add> mappingBuilder.field("type", SearchIndexFieldType.ATOM.getSimpleCode());
<ide> mappingBuilder.endObject();
<ide> }
<del>
<add>
<ide> // Create a long field for every instant field
<del> if ( field.getSimpleType() == SearchIndexFieldType.INSTANT )
<add> if (field.getSimpleType() == SearchIndexFieldType.INSTANT)
<ide> {
<ide> mappingBuilder.startObject(getSortFieldNameInstant(field.getSimpleFieldName()));
<del> mappingBuilder.field("type", SearchIndexFieldType.LONG.getSimpleCode());
<add> mappingBuilder.field("type", SearchIndexFieldType.LONG.getSimpleCode());
<ide> mappingBuilder.endObject();
<ide> }
<del>
<add>
<ide> // Create a long field for every timeofday field
<del> if ( field.getSimpleType() == SearchIndexFieldType.TIMEOFDAY )
<add> if (field.getSimpleType() == SearchIndexFieldType.TIMEOFDAY)
<ide> {
<ide> mappingBuilder.startObject(getSortFieldNameTimeOfDay(field.getSimpleFieldName()));
<del> mappingBuilder.field("type", SearchIndexFieldType.LONG.getSimpleCode());
<add> mappingBuilder.field("type", SearchIndexFieldType.LONG.getSimpleCode());
<ide> mappingBuilder.endObject();
<del> }
<add> }
<ide> }
<ide> mappingBuilder.endObject().endObject().endObject();
<ide>
<del> CreateIndexResponse createResponse = client.admin().indices().prepareCreate(index.getSimpleIndex().getSimpleValue()).addMapping(ELASTICSEARCH_DEFAULT_TYPE, mappingBuilder).get();
<del>
<del> if (!createResponse.isAcknowledged())
<del> {
<del> logger.fatal(String.format("Index Creation not acknowledged for index %s", index.getSimpleIndex().getSimpleValue()));
<del> return false;
<del> }
<add> return mappingBuilder;
<ide>
<ide> } catch (Exception e)
<ide> {
<ide> logger.log(Level.FATAL, String.format("Failed to generate mapping json for index %s", index.getSimpleIndex().getSimpleValue()), e);
<del> return false;
<del> }
<del>
<del> logger.info(String.format("Created index %s", index.getSimpleIndex().getSimpleValue()));
<del> return true;
<del> }
<del>
<del> /**
<del> * Deletes an entire index
<add> return default_value;
<add> }
<add> }
<add>
<add> /**
<add> * Puts all field mappings into an existing index. If the index doesn't already
<add> * exist or a field name with a different type already exists the operation will
<add> * fail.
<ide> *
<ide> * @param index
<ide> * SearchIndexDefinition
<del> * @return boolean - true if successfully deleted, else false
<del> */
<del> public boolean deleteIndex(SearchIndexDefinition index)
<del> {
<add> * @return if successful or not
<add> */
<add> public boolean putAllFieldMappings(SearchIndexDefinition index)
<add> {
<add>
<ide> if (index == null)
<ide> {
<del> logger.fatal("Cannot delete a null Index");
<del> return false;
<del> }
<del>
<del> try
<del> {
<del> DeleteIndexResponse deleteResponse = client.admin().indices().prepareDelete(index.getSimpleIndex().getSimpleValue()).get();
<del> if (!deleteResponse.isAcknowledged())
<del> {
<del> logger.fatal(String.format("Index Deletion not acknowledged for index %s", index.getSimpleIndex().getSimpleValue()));
<add> logger.fatal("Null index");
<add> return false;
<add> }
<add>
<add> if (!indexExists(index))
<add> {
<add> logger.fatal(String.format("Index %s does not exist!", index.getSimpleIndex().getSimpleValue()));
<add> return false;
<add> }
<add>
<add> try
<add> {
<add>
<add> PutMappingResponse put_response = client.admin().indices().preparePutMapping(index.getSimpleIndex().getSimpleValue()).setType(ELASTICSEARCH_DEFAULT_TYPE).setSource(getMappingBuilder(index, null)).get();
<add>
<add> if (!put_response.isAcknowledged())
<add> {
<add> logger.fatal(String.format("Put Mappings result not acknowledged for index %s", index.getSimpleIndex().getSimpleValue()));
<ide> return false;
<ide> }
<ide>
<ide> } catch (Exception e)
<ide> {
<del> logger.fatal(String.format("Index Deletion failed for index %s", index.getSimpleIndex().getSimpleValue()));
<del> return false;
<del> }
<del> logger.info(String.format("Deleted index %s", index.getSimpleIndex().getSimpleValue()));
<add> logger.log(Level.FATAL, String.format("Failed to generate mapping json for index %s", index.getSimpleIndex().getSimpleValue()), e);
<add> return false;
<add> }
<add>
<ide> return true;
<ide>
<ide> }
<del>
<del> /**
<del> * Upsert if the index doesn't exist or is not properly configured already
<del> *
<del> * BE CAREFUL!!!
<del> *
<del> * @param index
<del> * SearchIndexDefinition
<del> * @return boolean if the upsert was successful or not
<del> */
<del> @Override
<del> public boolean upsertIndex(SearchIndexDefinition index)
<del> {
<del>
<del> if (index == null)
<del> {
<del> logger.fatal("Cannot upsert a null Index");
<del> return false;
<del> }
<del>
<del> // if it exists and is not configured correctly delete and add
<del> if (indexExists(index))
<del> {
<del> if (!indexProperlyConfigured(index))
<del> {
<del> if (deleteIndex(index))
<del> {
<del> return createIndex(index);
<del> } else
<del> {
<del> // deletion failed
<del> return false;
<del> }
<del> }
<del> } else
<del> {
<del> // index is new
<del> return createIndex(index);
<del> }
<del>
<del> // index exists and already configured correctly
<del> logger.info(String.format("No upsert needed for index %s", index.getSimpleIndex().getSimpleValue()));
<del> return true;
<del> }
<del>
<del> /**
<del> * Delete a document within an index
<del> *
<del> * @param index
<del> * @param document_id
<del> * @return
<del> */
<del> public boolean deleteDocument(IndexDefinition index, SearchDocumentId document_id)
<del> {
<del>
<del> if (index == null || document_id == null)
<del> {
<del> logger.fatal("Null index or document id");
<del> return false;
<del> }
<del>
<del> try
<del> {
<del> DeleteResponse response = client.prepareDelete(index.getSimpleValue(), ELASTICSEARCH_DEFAULT_TYPE, document_id.getSimpleValue()).setRefreshPolicy(RefreshPolicy.IMMEDIATE).get();
<del>
<del> logger.info(String.format("Result:%s SearchDocumentId:%s IndexDefinition:%s", response.getResult(), response.getId(), response.getIndex()));
<del>
<del> return response.getResult().equals(Result.DELETED);
<del> } catch (Exception e)
<del> {
<del> logger.error(e);
<del> return false;
<del> }
<del> }
<del>
<del> /**
<del> * Using a SortBy object, construct a SortBuilder used by ElasticSearch. This method handles the unique sorting cases for Text, Time of Day, and Instant.
<del> *
<del> * @param sort_by
<del> * @param default_value
<del> * @return
<del> */
<del> static private FieldSortBuilder getSort(SortBy sort_by, FieldSortBuilder default_value)
<del> {
<del> SortOrder order = null;
<del> if ( sort_by.getSimpleDirection() == SortDirection.ASCENDING ) order = SortOrder.ASC;
<del> if ( sort_by.getSimpleDirection() == SortDirection.DESCENDING ) order = SortOrder.DESC;
<del>
<del> if ( order == null ) return default_value;
<del>
<del> FieldName field_name = sort_by.getSimpleField().getSimpleFieldName();
<del> String sort_on_string = field_name.getSimpleName();
<del>
<del> if ( sort_by.getSimpleField().getSimpleType() == SearchIndexFieldType.TEXT ) sort_on_string = getSortFieldNameText(sort_by.getSimpleField().getSimpleFieldName());
<del> if ( sort_by.getSimpleField().getSimpleType() == SearchIndexFieldType.TIMEOFDAY ) sort_on_string = getSortFieldNameTimeOfDay(sort_by.getSimpleField().getSimpleFieldName());
<del> if ( sort_by.getSimpleField().getSimpleType() == SearchIndexFieldType.INSTANT ) sort_on_string = getSortFieldNameInstant(sort_by.getSimpleField().getSimpleFieldName());
<del>
<del> return SortBuilders.fieldSort(sort_on_string).order(order).unmappedType(SearchIndexFieldType.ATOM.getSimpleCode());
<del> }
<del>
<del> /**
<del> * Sorting on text fields is impossible without enabling fielddata in ElasticSearch. To get around this, we instead use a keyword field for every text field written.
<del> * This solution is recommended by ElasticSearch over enabling fielddata. For more information, read here:
<del> *
<del> * https://www.elastic.co/guide/en/elasticsearch/reference/5.4/fielddata.html#before-enabling-fielddata
<del> * https://www.elastic.co/blog/support-in-the-wild-my-biggest-elasticsearch-problem-at-scale
<del> *
<del> * @param field
<del> * @return
<del> */
<del> static public String getSortFieldNameText(FieldName field)
<del> {
<del> return getSortFieldNameText(field.getSimpleName());
<del> }
<del>
<del> /**
<del> * Sorting on text fields is impossible without enabling fielddata in ElasticSearch. To get around this, we instead use a keyword field for every text field written.
<del> * This solution is recommended by ElasticSearch over enabling fielddata. For more information, read here:
<del> *
<del> * https://www.elastic.co/guide/en/elasticsearch/reference/5.4/fielddata.html#before-enabling-fielddata
<del> * https://www.elastic.co/blog/support-in-the-wild-my-biggest-elasticsearch-problem-at-scale
<del> *
<del> * @param field_name
<del> * @return
<del> */
<del> static public String getSortFieldNameText(String field_name)
<del> {
<del> return field_name + "_" + SORT_FIELD_NAME_JIMMUTABLE + "_" + SearchIndexFieldType.ATOM.getSimpleCode();
<del> }
<del>
<del> /**
<del> * In order to sort TimeOfDay objects, we need to look at the ms_from_midnight field from within. This method creates a consistent field name to sort by.
<del> * @param field
<del> * @return
<del> */
<del> static public String getSortFieldNameTimeOfDay(FieldName field)
<del> {
<del> return getSortFieldNameTimeOfDay(field.getSimpleName());
<del> }
<del>
<del> /**
<del> * In order to sort TimeOfDay objects, we need to look at the ms_from_midnight field from within. This method creates a consistent field name to sort by.
<del> * @param field_name
<del> * @return
<del> */
<del> static public String getSortFieldNameTimeOfDay(String field_name)
<del> {
<del> return field_name + "_" + SORT_FIELD_NAME_JIMMUTABLE + "_" + TimeOfDay.FIELD_MS_FROM_MIDNIGHT.getSimpleFieldName().getSimpleName();
<del> }
<del>
<del> /**
<del> * In order to sort Instant objects, we need to look at the ms_from_epoch field from within. This method creates a consistent field name to sort by.
<del> * @param field
<del> * @return
<del> */
<del> static public String getSortFieldNameInstant(FieldName field)
<del> {
<del> return getSortFieldNameInstant(field.getSimpleName());
<del> }
<del>
<del> /**
<del> * In order to sort Instant objects, we need to look at the ms_from_epoch field from within. This method creates a consistent field name to sort by.
<del> * @param field_name
<del> * @return
<del> */
<del> static public String getSortFieldNameInstant(String field_name)
<del> {
<del> return field_name + "_" + SORT_FIELD_NAME_JIMMUTABLE + "_" + Instant.FIELD_MS_FROM_EPOCH.getSimpleFieldName().getSimpleName();
<del> }
<ide> } |
|
Java | epl-1.0 | 6b033ad0d2a447cab6183c7c7b42a606f48647e7 | 0 | rohitmohan96/ceylon-ide-eclipse,rohitmohan96/ceylon-ide-eclipse | package com.redhat.ceylon.eclipse.code.quickfix;
/*******************************************************************************
* Copyright (c) 2005, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.getIdentifyingNode;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.link.LinkedPosition;
import org.eclipse.jface.text.link.LinkedPositionGroup;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.tree.NaturalVisitor;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.BaseMemberOrTypeExpression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.BaseType;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Identifier;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ImportMemberOrType;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
import com.redhat.ceylon.eclipse.code.editor.CeylonEditor;
import com.redhat.ceylon.eclipse.code.refactor.AbstractRenameLinkedMode;
class EnterAliasLinkedMode extends AbstractRenameLinkedMode {
private final ImportMemberOrType element;
private final Declaration dec;
private final class LinkedPositionsVisitor
extends Visitor implements NaturalVisitor {
private final int adjust;
private final IDocument document;
private final LinkedPositionGroup linkedPositionGroup;
int i=1;
private LinkedPositionsVisitor(int adjust, IDocument document,
LinkedPositionGroup linkedPositionGroup) {
this.adjust = adjust;
this.document = document;
this.linkedPositionGroup = linkedPositionGroup;
}
@Override
public void visit(BaseMemberOrTypeExpression that) {
super.visit(that);
addLinkedPosition(document, that.getIdentifier(),
that.getDeclaration());
}
@Override
public void visit(BaseType that) {
super.visit(that);
addLinkedPosition(document, that.getIdentifier(),
that.getDeclarationModel());
}
protected void addLinkedPosition(final IDocument document,
Identifier id, Declaration d) {
if (id!=null && d!=null && dec.equals(d)) {
try {
int pos = id.getStartIndex()+adjust;
int len = id.getText().length();
linkedPositionGroup.addPosition(new LinkedPosition(document,
pos, len, i++));
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}
public EnterAliasLinkedMode(ImportMemberOrType element,
Declaration dec, CeylonEditor editor) {
super(editor);
this.element = element;
this.dec = dec;
}
@Override
protected String getName() {
Tree.Alias alias = element.getAlias();
if (alias==null) {
return dec.getName();
}
else {
return alias.getIdentifier().getText();
}
}
@Override
public String getHintTemplate() {
return "Enter alias for " + linkedPositionGroup.getPositions().length +
" occurrences of '" + dec.getName() + "' {0}";
}
@Override
protected int init(IDocument document) {
Tree.Alias alias = ((Tree.ImportMemberOrType) element).getAlias();
if (alias==null) {
try {
int start = element.getStartIndex();
document.set(document.get(0,start) + dec.getName() + "=" +
document.get(start, document.getLength()-start));
return dec.getName().length()+1;
}
catch (BadLocationException e) {
e.printStackTrace();
return -1;
}
}
else {
return 0;
}
}
@Override
protected int getIdentifyingOffset() {
Tree.Alias alias = element.getAlias();
if (alias!=null) {
return alias.getStartIndex();
}
else {
return getIdentifyingNode(element).getStartIndex();
}
}
@Override
public void addLinkedPositions(final IDocument document, Tree.CompilationUnit rootNode,
final int adjust, final LinkedPositionGroup linkedPositionGroup) {
rootNode.visit(new LinkedPositionsVisitor(adjust, document, linkedPositionGroup));
}
}
| plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/quickfix/EnterAliasLinkedMode.java | package com.redhat.ceylon.eclipse.code.quickfix;
/*******************************************************************************
* Copyright (c) 2005, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.getIdentifyingNode;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.link.LinkedPosition;
import org.eclipse.jface.text.link.LinkedPositionGroup;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.tree.NaturalVisitor;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.BaseMemberOrTypeExpression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.BaseType;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Identifier;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ImportMemberOrType;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
import com.redhat.ceylon.eclipse.code.editor.CeylonEditor;
import com.redhat.ceylon.eclipse.code.refactor.AbstractRenameLinkedMode;
class EnterAliasLinkedMode extends AbstractRenameLinkedMode {
private final ImportMemberOrType element;
private final Declaration dec;
private final class LinkedPositionsVisitor
extends Visitor implements NaturalVisitor {
private final int adjust;
private final IDocument document;
private final LinkedPositionGroup linkedPositionGroup;
int i=1;
private LinkedPositionsVisitor(int adjust, IDocument document,
LinkedPositionGroup linkedPositionGroup) {
this.adjust = adjust;
this.document = document;
this.linkedPositionGroup = linkedPositionGroup;
}
@Override
public void visit(BaseMemberOrTypeExpression that) {
super.visit(that);
addLinkedPosition(document, that.getIdentifier(),
that.getDeclaration());
}
@Override
public void visit(BaseType that) {
super.visit(that);
addLinkedPosition(document, that.getIdentifier(),
that.getDeclarationModel());
}
protected void addLinkedPosition(final IDocument document,
Identifier id, Declaration d) {
if (id!=null && d!=null && dec.equals(d)) {
try {
int pos = id.getStartIndex()+adjust;
int len = id.getText().length();
linkedPositionGroup.addPosition(new LinkedPosition(document,
pos, len, i++));
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}
public EnterAliasLinkedMode(ImportMemberOrType element,
Declaration dec, CeylonEditor editor) {
super(editor);
this.element = element;
this.dec = dec;
}
@Override
protected String getName() {
Tree.Alias alias = element.getAlias();
if (alias==null) {
return dec.getName();
}
else {
return alias.getIdentifier().getText();
}
}
@Override
public String getHintTemplate() {
return "Enter alias for '" + dec.getName() + "' {0}";
}
@Override
protected int init(IDocument document) {
Tree.Alias alias = ((Tree.ImportMemberOrType) element).getAlias();
if (alias==null) {
try {
int start = element.getStartIndex();
document.set(document.get(0,start) + dec.getName() + "=" +
document.get(start, document.getLength()-start));
return dec.getName().length()+1;
}
catch (BadLocationException e) {
e.printStackTrace();
return -1;
}
}
else {
return 0;
}
}
@Override
protected int getIdentifyingOffset() {
Tree.Alias alias = element.getAlias();
if (alias!=null) {
return alias.getStartIndex();
}
else {
return getIdentifyingNode(element).getStartIndex();
}
}
@Override
public void addLinkedPositions(final IDocument document, Tree.CompilationUnit rootNode,
final int adjust, final LinkedPositionGroup linkedPositionGroup) {
rootNode.visit(new LinkedPositionsVisitor(adjust, document, linkedPositionGroup));
}
}
| display count of occurrences of alias | plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/quickfix/EnterAliasLinkedMode.java | display count of occurrences of alias | <ide><path>lugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/quickfix/EnterAliasLinkedMode.java
<ide>
<ide> @Override
<ide> public String getHintTemplate() {
<del> return "Enter alias for '" + dec.getName() + "' {0}";
<add> return "Enter alias for " + linkedPositionGroup.getPositions().length +
<add> " occurrences of '" + dec.getName() + "' {0}";
<ide> }
<ide>
<ide> @Override |
|
JavaScript | apache-2.0 | e057b0a6fdfbe4ef0523f463f12fff3a63782831 | 0 | OpusCapitaBES/js-node-showroom-server | 'use strict';
let markdownToAst = require('markdown-to-ast');
let fill = require('lodash/fill');
function getSectionIndexRange(ast, headerName) {
let targetHeaderIndex = ast.children.reduce((result, branch, index) => {
if (result === null && branch.type === 'Header' && branch.children[0].value === headerName) {
return index + 1;
}
return result;
}, null);
let nextHeaderIndex = targetHeaderIndex === null ? null :
ast.children.reduce((result, branch, index) => {
if (result === null && index > targetHeaderIndex && branch.type === 'Header') {
return index;
}
return result;
}, null);
let countOfSections = nextHeaderIndex === null ? 1 : nextHeaderIndex - targetHeaderIndex;
if (countOfSections > 0) {
return fill(Array(countOfSections), '').map((el, i) => i + targetHeaderIndex);
}
return [];
}
function parseDocumentation(markdown) {
let ast = markdownToAst.parse(markdown);
return {
componentName:
ast.children[getSectionIndexRange(ast, 'Component Name')[0]] &&
ast.children[getSectionIndexRange(ast, 'Component Name')[0]].children[0].value,
tags:
ast.children[getSectionIndexRange(ast, 'Tags')[0]] &&
ast.children[getSectionIndexRange(ast, 'Tags')[0]].children[0].value,
demoProps:
ast.children[getSectionIndexRange(ast, 'Code Example')[0]] &&
ast.children[getSectionIndexRange(ast, 'Code Example')[0]].value
};
}
module.exports = parseDocumentation;
| src/tools/npm-scanner/parseDocumentation.js | 'use strict';
let markdownToAst = require('markdown-to-ast');
let fill = require('lodash/fill');
function getSectionIndexRange(ast, headerName) {
let targetHeaderIndex = ast.children.reduce((result, branch, index) => {
if (result === null && branch.type === 'Header' && branch.children[0].value === headerName) {
return index + 1;
}
return result;
}, null);
let nextHeaderIndex = targetHeaderIndex === null ? null :
ast.children.reduce((result, branch, index) => {
if (result === null && index > targetHeaderIndex && branch.type === 'Header') {
return index;
}
return result;
}, null);
let countOfSections = nextHeaderIndex - targetHeaderIndex;
if (countOfSections > 0) {
return fill(Array(countOfSections), '').map((el, i) => i + targetHeaderIndex);
}
return [];
}
function parseDocumentation(markdown) {
let ast = markdownToAst.parse(markdown);
return {
componentName:
ast.children[getSectionIndexRange(ast, 'Component Name')[0]] &&
ast.children[getSectionIndexRange(ast, 'Component Name')[0]].children[0].value,
tags:
ast.children[getSectionIndexRange(ast, 'Tags')[0]] &&
ast.children[getSectionIndexRange(ast, 'Tags')[0]].children[0].value,
demoProps:
ast.children[getSectionIndexRange(ast, 'Code Example')[0]] &&
ast.children[getSectionIndexRange(ast, 'Code Example')[0]].value
};
}
module.exports = parseDocumentation;
| Fix markdown documentation files parsing
| src/tools/npm-scanner/parseDocumentation.js | Fix markdown documentation files parsing | <ide><path>rc/tools/npm-scanner/parseDocumentation.js
<ide> return result;
<ide> }, null);
<ide>
<del> let countOfSections = nextHeaderIndex - targetHeaderIndex;
<add> let countOfSections = nextHeaderIndex === null ? 1 : nextHeaderIndex - targetHeaderIndex;
<ide> if (countOfSections > 0) {
<ide> return fill(Array(countOfSections), '').map((el, i) => i + targetHeaderIndex);
<ide> } |
|
Java | apache-2.0 | 0d13de0cf350cd6f5bef985303fe41fd8d769731 | 0 | speddy93/nifi,apsaltis/nifi,Xsixteen/nifi,jskora/nifi,jtstorck/nifi,YolandaMDavis/nifi,ijokarumawak/nifi,tijoparacka/nifi,pvillard31/nifi,Xsixteen/nifi,patricker/nifi,alopresto/nifi,zhengsg/nifi,MikeThomsen/nifi,m-hogue/nifi,aperepel/nifi,Xsixteen/nifi,patricker/nifi,qfdk/nifi,patricker/nifi,MikeThomsen/nifi,PuspenduBanerjee/nifi,InspurUSA/nifi,Wesley-Lawrence/nifi,mattyb149/nifi,joetrite/nifi,jtstorck/nifi,WilliamNouet/ApacheNiFi,PuspenduBanerjee/nifi,zhengsg/nifi,tijoparacka/nifi,joewitt/incubator-nifi,joewitt/incubator-nifi,jtstorck/nifi,MikeThomsen/nifi,InspurUSA/nifi,joetrite/nifi,aperepel/nifi,aperepel/nifi,WilliamNouet/ApacheNiFi,tijoparacka/nifi,alopresto/nifi,jtstorck/nifi,bbende/nifi,ijokarumawak/nifi,tijoparacka/nifi,jskora/nifi,josephxsxn/nifi,tequalsme/nifi,peter-gergely-horvath/nifi,tequalsme/nifi,jjmeyer0/nifi,InspurUSA/nifi,ShellyLC/nifi,jfrazee/nifi,peter-gergely-horvath/nifi,dlukyanov/nifi,m-hogue/nifi,pvillard31/nifi,mans2singh/nifi,jskora/nifi,YolandaMDavis/nifi,peter-gergely-horvath/nifi,WilliamNouet/nifi,jfrazee/nifi,pvillard31/nifi,tijoparacka/nifi,trixpan/nifi,mans2singh/nifi,jfrazee/nifi,jfrazee/nifi,mcgilman/nifi,peter-gergely-horvath/nifi,mcgilman/nifi,trixpan/nifi,josephxsxn/nifi,josephxsxn/nifi,ShellyLC/nifi,speddy93/nifi,WilliamNouet/nifi,jjmeyer0/nifi,dlukyanov/nifi,WilliamNouet/nifi,michalklempa/nifi,michalklempa/nifi,mans2singh/nifi,trixpan/nifi,jskora/nifi,joetrite/nifi,ijokarumawak/nifi,peter-gergely-horvath/nifi,patricker/nifi,m-hogue/nifi,qfdk/nifi,dlukyanov/nifi,alopresto/nifi,dlukyanov/nifi,mcgilman/nifi,apsaltis/nifi,YolandaMDavis/nifi,mcgilman/nifi,ShellyLC/nifi,zhengsg/nifi,michalklempa/nifi,zhengsg/nifi,PuspenduBanerjee/nifi,thesolson/nifi,michalklempa/nifi,WilliamNouet/ApacheNiFi,Wesley-Lawrence/nifi,alopresto/nifi,mattyb149/nifi,ShellyLC/nifi,peter-gergely-horvath/nifi,Xsixteen/nifi,pvillard31/nifi,ijokarumawak/nifi,trixpan/nifi,joewitt/incubator-nifi,InspurUSA/nifi,mattyb149/nifi,m-hogue/nifi,tequalsme/nifi,aperepel/nifi,WilliamNouet/nifi,YolandaMDavis/nifi,patricker/nifi,apsaltis/nifi,speddy93/nifi,qfdk/nifi,joewitt/incubator-nifi,m-hogue/nifi,jskora/nifi,josephxsxn/nifi,pvillard31/nifi,trixpan/nifi,YolandaMDavis/nifi,MikeThomsen/nifi,MikeThomsen/nifi,thesolson/nifi,WilliamNouet/ApacheNiFi,qfdk/nifi,aperepel/nifi,mcgilman/nifi,patricker/nifi,apsaltis/nifi,bbende/nifi,bbende/nifi,m-hogue/nifi,joetrite/nifi,zhengsg/nifi,jjmeyer0/nifi,jtstorck/nifi,apsaltis/nifi,alopresto/nifi,jskora/nifi,patricker/nifi,MikeThomsen/nifi,mans2singh/nifi,mattyb149/nifi,tequalsme/nifi,alopresto/nifi,mattyb149/nifi,michalklempa/nifi,InspurUSA/nifi,pvillard31/nifi,jjmeyer0/nifi,bbende/nifi,trixpan/nifi,jfrazee/nifi,ijokarumawak/nifi,aperepel/nifi,joetrite/nifi,mans2singh/nifi,YolandaMDavis/nifi,PuspenduBanerjee/nifi,Wesley-Lawrence/nifi,jtstorck/nifi,mattyb149/nifi,Wesley-Lawrence/nifi,jjmeyer0/nifi,pvillard31/nifi,WilliamNouet/nifi,josephxsxn/nifi,michalklempa/nifi,thesolson/nifi,joetrite/nifi,qfdk/nifi,Wesley-Lawrence/nifi,dlukyanov/nifi,tijoparacka/nifi,speddy93/nifi,speddy93/nifi,jfrazee/nifi,mattyb149/nifi,WilliamNouet/ApacheNiFi,tequalsme/nifi,tequalsme/nifi,jfrazee/nifi,jjmeyer0/nifi,mcgilman/nifi,ShellyLC/nifi,thesolson/nifi,zhengsg/nifi,pvillard31/nifi,bbende/nifi,ijokarumawak/nifi,bbende/nifi,qfdk/nifi,Wesley-Lawrence/nifi,MikeThomsen/nifi,Xsixteen/nifi,speddy93/nifi,WilliamNouet/ApacheNiFi,YolandaMDavis/nifi,joewitt/incubator-nifi,mans2singh/nifi,thesolson/nifi,PuspenduBanerjee/nifi,apsaltis/nifi,mcgilman/nifi,ShellyLC/nifi,dlukyanov/nifi,jfrazee/nifi,alopresto/nifi,thesolson/nifi,josephxsxn/nifi,PuspenduBanerjee/nifi,WilliamNouet/nifi,Xsixteen/nifi,m-hogue/nifi,joewitt/incubator-nifi,InspurUSA/nifi,jtstorck/nifi | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.web;
import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.stream.io.StreamUtils;
import org.apache.nifi.web.ViewableContent.DisplayMode;
import org.apache.tika.detect.DefaultDetector;
import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
/**
* Controller servlet for viewing content. This is responsible for generating
* the markup for the header and footer of the page. Included in that is the
* combo that allows the user to choose how they wait to view the data
* (original, formatted, hex). If a data viewer is registered for the detected
* content type, it will include the markup it generates in the response.
*/
public class ContentViewerController extends HttpServlet {
private static final Logger logger = LoggerFactory.getLogger(ContentViewerController.class);
// 1.5kb - multiple of 12 (3 bytes = 4 base 64 encoded chars)
private final static int BUFFER_LENGTH = 1536;
/**
* Gets the content and defers to registered viewers to generate the markup.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
// specify the charset in a response header
response.addHeader("Content-Type", "text/html; charset=UTF-8");
// get the content
final ServletContext servletContext = request.getServletContext();
final ContentAccess contentAccess = (ContentAccess) servletContext.getAttribute("nifi-content-access");
final ContentRequestContext contentRequest;
try {
contentRequest = getContentRequest(request);
} catch (final Exception e) {
request.setAttribute("title", "Error");
request.setAttribute("messages", "Unable to interpret content request.");
// forward to the error page
final ServletContext viewerContext = servletContext.getContext("/nifi");
viewerContext.getRequestDispatcher("/message").forward(request, response);
return;
}
if (contentRequest.getDataUri() == null) {
request.setAttribute("title", "Error");
request.setAttribute("messages", "The data reference must be specified.");
// forward to the error page
final ServletContext viewerContext = servletContext.getContext("/nifi");
viewerContext.getRequestDispatcher("/message").forward(request, response);
return;
}
// get the content
final DownloadableContent downloadableContent;
try {
downloadableContent = contentAccess.getContent(contentRequest);
} catch (final ResourceNotFoundException rnfe) {
request.setAttribute("title", "Error");
request.setAttribute("messages", "Unable to find the specified content");
// forward to the error page
final ServletContext viewerContext = servletContext.getContext("/nifi");
viewerContext.getRequestDispatcher("/message").forward(request, response);
return;
} catch (final AccessDeniedException ade) {
request.setAttribute("title", "Acess Denied");
request.setAttribute("messages", "Unable to approve access to the specified content: " + ade.getMessage());
// forward to the error page
final ServletContext viewerContext = servletContext.getContext("/nifi");
viewerContext.getRequestDispatcher("/message").forward(request, response);
return;
} catch (final Exception e) {
request.setAttribute("title", "Error");
request.setAttribute("messages", "An unexcepted error has occurred: " + e.getMessage());
// forward to the error page
final ServletContext viewerContext = servletContext.getContext("/nifi");
viewerContext.getRequestDispatcher("/message").forward(request, response);
return;
}
// determine how we want to view the data
String mode = request.getParameter("mode");
// if the name isn't set, use original
if (mode == null) {
mode = DisplayMode.Original.name();
}
// determine the display mode
final DisplayMode displayMode;
try {
displayMode = DisplayMode.valueOf(mode);
} catch (final IllegalArgumentException iae) {
request.setAttribute("title", "Error");
request.setAttribute("messages", "Invalid display mode: " + mode);
// forward to the error page
final ServletContext viewerContext = servletContext.getContext("/nifi");
viewerContext.getRequestDispatcher("/message").forward(request, response);
return;
}
// buffer the content to support reseting in case we need to detect the content type or char encoding
try (final BufferedInputStream bis = new BufferedInputStream(downloadableContent.getContent());) {
final String mimeType;
final String normalizedMimeType;
// when standalone and we don't know the type is null as we were able to directly access the content bypassing the rest endpoint,
// when clustered and we don't know the type set to octet stream since the content was retrieved from the node's rest endpoint
if (downloadableContent.getType() == null || StringUtils.startsWithIgnoreCase(downloadableContent.getType(), MediaType.OCTET_STREAM.toString())) {
// attempt to detect the content stream if we don't know what it is ()
final DefaultDetector detector = new DefaultDetector();
// create the stream for tika to process, buffered to support reseting
final TikaInputStream tikaStream = TikaInputStream.get(bis);
// provide a hint based on the filename
final Metadata metadata = new Metadata();
metadata.set(Metadata.RESOURCE_NAME_KEY, downloadableContent.getFilename());
// Get mime type
final MediaType mediatype = detector.detect(tikaStream, metadata);
mimeType = mediatype.toString();
} else {
mimeType = downloadableContent.getType();
}
// Extract only mime type and subtype from content type (anything after the first ; are parameters)
// Lowercase so subsequent code does not need to implement case insensitivity
normalizedMimeType = mimeType.split(";",2)[0].toLowerCase();
// add attributes needed for the header
request.setAttribute("filename", downloadableContent.getFilename());
request.setAttribute("contentType", mimeType);
// generate the header
request.getRequestDispatcher("/WEB-INF/jsp/header.jsp").include(request, response);
// remove the attributes needed for the header
request.removeAttribute("filename");
request.removeAttribute("contentType");
// generate the markup for the content based on the display mode
if (DisplayMode.Hex.equals(displayMode)) {
final byte[] buffer = new byte[BUFFER_LENGTH];
final int read = StreamUtils.fillBuffer(bis, buffer, false);
// trim the byte array if necessary
byte[] bytes = buffer;
if (read != buffer.length) {
bytes = new byte[read];
System.arraycopy(buffer, 0, bytes, 0, read);
}
// convert bytes into the base 64 bytes
final String base64 = Base64.encodeBase64String(bytes);
// defer to the jsp
request.setAttribute("content", base64);
request.getRequestDispatcher("/WEB-INF/jsp/hexview.jsp").include(request, response);
} else {
// lookup a viewer for the content
final String contentViewerUri = servletContext.getInitParameter(normalizedMimeType);
// handle no viewer for content type
if (contentViewerUri == null) {
request.getRequestDispatcher("/WEB-INF/jsp/no-viewer.jsp").include(request, response);
} else {
// create a request attribute for accessing the content
request.setAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE, new ViewableContent() {
@Override
public InputStream getContentStream() {
return bis;
}
@Override
public String getContent() throws IOException {
// detect the charset
final CharsetDetector detector = new CharsetDetector();
detector.setText(bis);
detector.enableInputFilter(true);
final CharsetMatch match = detector.detect();
// ensure we were able to detect the charset
if (match == null) {
throw new IOException("Unable to detect character encoding.");
}
// convert the stream using the detected charset
return IOUtils.toString(bis, match.getName());
}
@Override
public ViewableContent.DisplayMode getDisplayMode() {
return displayMode;
}
@Override
public String getFileName() {
return downloadableContent.getFilename();
}
@Override
public String getContentType() {
return normalizedMimeType;
}
@Override
public String getRawContentType() {
return mimeType;
}
});
try {
// generate the content
final ServletContext viewerContext = servletContext.getContext(contentViewerUri);
viewerContext.getRequestDispatcher("/view-content").include(request, response);
} catch (final Exception e) {
String message = e.getMessage() != null ? e.getMessage() : e.toString();
message = "Unable to generate view of data: " + message;
// log the error
logger.error(message);
if (logger.isDebugEnabled()) {
logger.error(StringUtils.EMPTY, e);
}
// populate the request attributes
request.setAttribute("title", "Error");
request.setAttribute("messages", message);
// forward to the error page
final ServletContext viewerContext = servletContext.getContext("/nifi");
viewerContext.getRequestDispatcher("/message").forward(request, response);
return;
}
// remove the request attribute
request.removeAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE);
}
}
// generate footer
request.getRequestDispatcher("/WEB-INF/jsp/footer.jsp").include(request, response);
}
}
/**
* @param request request
* @return Get the content request context based on the specified request
*/
private ContentRequestContext getContentRequest(final HttpServletRequest request) {
final String ref = request.getParameter("ref");
final String clientId = request.getParameter("clientId");
final String proxiedEntitiesChain = request.getHeader("X-ProxiedEntitiesChain");
final URI refUri = URI.create(ref);
final String query = refUri.getQuery();
String rawClusterNodeId = null;
if (query != null) {
final String[] queryParameters = query.split("&");
for (int i = 0; i < queryParameters.length; i++) {
if (queryParameters[0].startsWith("clusterNodeId=")) {
rawClusterNodeId = StringUtils.substringAfterLast(queryParameters[0], "clusterNodeId=");
}
}
}
final String clusterNodeId = rawClusterNodeId;
return new ContentRequestContext() {
@Override
public String getDataUri() {
return ref;
}
@Override
public String getClusterNodeId() {
return clusterNodeId;
}
@Override
public String getClientId() {
return clientId;
}
@Override
public String getProxiedEntitiesChain() {
return proxiedEntitiesChain;
}
};
}
}
| nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-content-viewer/src/main/java/org/apache/nifi/web/ContentViewerController.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.web;
import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.stream.io.StreamUtils;
import org.apache.nifi.web.ViewableContent.DisplayMode;
import org.apache.tika.detect.DefaultDetector;
import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
/**
* Controller servlet for viewing content. This is responsible for generating
* the markup for the header and footer of the page. Included in that is the
* combo that allows the user to choose how they wait to view the data
* (original, formatted, hex). If a data viewer is registered for the detected
* content type, it will include the markup it generates in the response.
*/
public class ContentViewerController extends HttpServlet {
private static final Logger logger = LoggerFactory.getLogger(ContentViewerController.class);
// 1.5kb - multiple of 12 (3 bytes = 4 base 64 encoded chars)
private final static int BUFFER_LENGTH = 1536;
/**
* Gets the content and defers to registered viewers to generate the markup.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
// specify the charset in a response header
response.addHeader("Content-Type", "text/html; charset=UTF-8");
// get the content
final ServletContext servletContext = request.getServletContext();
final ContentAccess contentAccess = (ContentAccess) servletContext.getAttribute("nifi-content-access");
final ContentRequestContext contentRequest;
try {
contentRequest = getContentRequest(request);
} catch (final Exception e) {
request.setAttribute("title", "Error");
request.setAttribute("messages", "Unable to interpret content request.");
// forward to the error page
final ServletContext viewerContext = servletContext.getContext("/nifi");
viewerContext.getRequestDispatcher("/message").forward(request, response);
return;
}
if (contentRequest.getDataUri() == null) {
request.setAttribute("title", "Error");
request.setAttribute("messages", "The data reference must be specified.");
// forward to the error page
final ServletContext viewerContext = servletContext.getContext("/nifi");
viewerContext.getRequestDispatcher("/message").forward(request, response);
return;
}
// get the content
final DownloadableContent downloadableContent;
try {
downloadableContent = contentAccess.getContent(contentRequest);
} catch (final ResourceNotFoundException rnfe) {
request.setAttribute("title", "Error");
request.setAttribute("messages", "Unable to find the specified content");
// forward to the error page
final ServletContext viewerContext = servletContext.getContext("/nifi");
viewerContext.getRequestDispatcher("/message").forward(request, response);
return;
} catch (final AccessDeniedException ade) {
request.setAttribute("title", "Acess Denied");
request.setAttribute("messages", "Unable to approve access to the specified content: " + ade.getMessage());
// forward to the error page
final ServletContext viewerContext = servletContext.getContext("/nifi");
viewerContext.getRequestDispatcher("/message").forward(request, response);
return;
} catch (final Exception e) {
request.setAttribute("title", "Error");
request.setAttribute("messages", "An unexcepted error has occurred: " + e.getMessage());
// forward to the error page
final ServletContext viewerContext = servletContext.getContext("/nifi");
viewerContext.getRequestDispatcher("/message").forward(request, response);
return;
}
// determine how we want to view the data
String mode = request.getParameter("mode");
// if the name isn't set, use original
if (mode == null) {
mode = DisplayMode.Original.name();
}
// determine the display mode
final DisplayMode displayMode;
try {
displayMode = DisplayMode.valueOf(mode);
} catch (final IllegalArgumentException iae) {
request.setAttribute("title", "Error");
request.setAttribute("messages", "Invalid display mode: " + mode);
// forward to the error page
final ServletContext viewerContext = servletContext.getContext("/nifi");
viewerContext.getRequestDispatcher("/message").forward(request, response);
return;
}
// buffer the content to support reseting in case we need to detect the content type or char encoding
try (final BufferedInputStream bis = new BufferedInputStream(downloadableContent.getContent());) {
final String mimeType;
final String normalizedMimeType;
// when standalone and we don't know the type is null as we were able to directly access the content bypassing the rest endpoint,
// when clustered and we don't know the type set to octet stream since the content was retrieved from the node's rest endpoint
if (downloadableContent.getType() == null || downloadableContent.getType().equals(MediaType.OCTET_STREAM.toString())) {
// attempt to detect the content stream if we don't know what it is ()
final DefaultDetector detector = new DefaultDetector();
// create the stream for tika to process, buffered to support reseting
final TikaInputStream tikaStream = TikaInputStream.get(bis);
// provide a hint based on the filename
final Metadata metadata = new Metadata();
metadata.set(Metadata.RESOURCE_NAME_KEY, downloadableContent.getFilename());
// Get mime type
final MediaType mediatype = detector.detect(tikaStream, metadata);
mimeType = mediatype.toString();
} else {
mimeType = downloadableContent.getType();
}
// Extract only mime type and subtype from content type (anything after the first ; are parameters)
// Lowercase so subsequent code does not need to implement case insensitivity
normalizedMimeType = mimeType.split(";",2)[0].toLowerCase();
// add attributes needed for the header
request.setAttribute("filename", downloadableContent.getFilename());
request.setAttribute("contentType", mimeType);
// generate the header
request.getRequestDispatcher("/WEB-INF/jsp/header.jsp").include(request, response);
// remove the attributes needed for the header
request.removeAttribute("filename");
request.removeAttribute("contentType");
// generate the markup for the content based on the display mode
if (DisplayMode.Hex.equals(displayMode)) {
final byte[] buffer = new byte[BUFFER_LENGTH];
final int read = StreamUtils.fillBuffer(bis, buffer, false);
// trim the byte array if necessary
byte[] bytes = buffer;
if (read != buffer.length) {
bytes = new byte[read];
System.arraycopy(buffer, 0, bytes, 0, read);
}
// convert bytes into the base 64 bytes
final String base64 = Base64.encodeBase64String(bytes);
// defer to the jsp
request.setAttribute("content", base64);
request.getRequestDispatcher("/WEB-INF/jsp/hexview.jsp").include(request, response);
} else {
// lookup a viewer for the content
final String contentViewerUri = servletContext.getInitParameter(normalizedMimeType);
// handle no viewer for content type
if (contentViewerUri == null) {
request.getRequestDispatcher("/WEB-INF/jsp/no-viewer.jsp").include(request, response);
} else {
// create a request attribute for accessing the content
request.setAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE, new ViewableContent() {
@Override
public InputStream getContentStream() {
return bis;
}
@Override
public String getContent() throws IOException {
// detect the charset
final CharsetDetector detector = new CharsetDetector();
detector.setText(bis);
detector.enableInputFilter(true);
final CharsetMatch match = detector.detect();
// ensure we were able to detect the charset
if (match == null) {
throw new IOException("Unable to detect character encoding.");
}
// convert the stream using the detected charset
return IOUtils.toString(bis, match.getName());
}
@Override
public ViewableContent.DisplayMode getDisplayMode() {
return displayMode;
}
@Override
public String getFileName() {
return downloadableContent.getFilename();
}
@Override
public String getContentType() {
return normalizedMimeType;
}
@Override
public String getRawContentType() {
return mimeType;
}
});
try {
// generate the content
final ServletContext viewerContext = servletContext.getContext(contentViewerUri);
viewerContext.getRequestDispatcher("/view-content").include(request, response);
} catch (final Exception e) {
String message = e.getMessage() != null ? e.getMessage() : e.toString();
message = "Unable to generate view of data: " + message;
// log the error
logger.error(message);
if (logger.isDebugEnabled()) {
logger.error(StringUtils.EMPTY, e);
}
// populate the request attributes
request.setAttribute("title", "Error");
request.setAttribute("messages", message);
// forward to the error page
final ServletContext viewerContext = servletContext.getContext("/nifi");
viewerContext.getRequestDispatcher("/message").forward(request, response);
return;
}
// remove the request attribute
request.removeAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE);
}
}
// generate footer
request.getRequestDispatcher("/WEB-INF/jsp/footer.jsp").include(request, response);
}
}
/**
* @param request request
* @return Get the content request context based on the specified request
*/
private ContentRequestContext getContentRequest(final HttpServletRequest request) {
final String ref = request.getParameter("ref");
final String clientId = request.getParameter("clientId");
final String proxiedEntitiesChain = request.getHeader("X-ProxiedEntitiesChain");
final URI refUri = URI.create(ref);
final String query = refUri.getQuery();
String rawClusterNodeId = null;
if (query != null) {
final String[] queryParameters = query.split("&");
for (int i = 0; i < queryParameters.length; i++) {
if (queryParameters[0].startsWith("clusterNodeId=")) {
rawClusterNodeId = StringUtils.substringAfterLast(queryParameters[0], "clusterNodeId=");
}
}
}
final String clusterNodeId = rawClusterNodeId;
return new ContentRequestContext() {
@Override
public String getDataUri() {
return ref;
}
@Override
public String getClusterNodeId() {
return clusterNodeId;
}
@Override
public String getClientId() {
return clientId;
}
@Override
public String getProxiedEntitiesChain() {
return proxiedEntitiesChain;
}
};
}
}
| NIFI-1539: - Comparing octet stream content type by using starts with and ignores case.
| nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-content-viewer/src/main/java/org/apache/nifi/web/ContentViewerController.java | NIFI-1539: - Comparing octet stream content type by using starts with and ignores case. | <ide><path>ifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-content-viewer/src/main/java/org/apache/nifi/web/ContentViewerController.java
<ide>
<ide> // when standalone and we don't know the type is null as we were able to directly access the content bypassing the rest endpoint,
<ide> // when clustered and we don't know the type set to octet stream since the content was retrieved from the node's rest endpoint
<del> if (downloadableContent.getType() == null || downloadableContent.getType().equals(MediaType.OCTET_STREAM.toString())) {
<add> if (downloadableContent.getType() == null || StringUtils.startsWithIgnoreCase(downloadableContent.getType(), MediaType.OCTET_STREAM.toString())) {
<ide> // attempt to detect the content stream if we don't know what it is ()
<ide> final DefaultDetector detector = new DefaultDetector();
<ide> |
|
JavaScript | mit | d51e3e404645827c42db009b53a077f8b1fbeb6e | 0 | phetsims/scenery-phet,phetsims/scenery-phet,phetsims/scenery-phet | // Copyright 2014-2017, University of Colorado Boulder
/**
* A rectangle with pseudo-3D shading.
*
* @author Jonathan Olson <[email protected]>
*/
define( function( require ) {
'use strict';
// modules
var Color = require( 'SCENERY/util/Color' );
var inherit = require( 'PHET_CORE/inherit' );
var LinearGradient = require( 'SCENERY/util/LinearGradient' );
var Node = require( 'SCENERY/nodes/Node' );
var PaintColorProperty = require( 'SCENERY/util/PaintColorProperty' );
var Path = require( 'SCENERY/nodes/Path' );
var RadialGradient = require( 'SCENERY/util/RadialGradient' );
var Rectangle = require( 'SCENERY/nodes/Rectangle' );
var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
var Shape = require( 'KITE/Shape' );
/**
* Creates a pseudo-3D shaded rounded rectangle that takes up rectBounds {Bounds2} in size. See below documentation
* for options (it is passed through to the Node also).
*
* @param {Bounds2} rectBounds
* @param {Object} [options]
* @constructor
*/
function ShadedRectangle( rectBounds, options ) {
Node.call( this );
options = _.extend( {
// {Color|string} default base color
baseColor: new Color( 80, 130, 230 ),
// {number} how much lighter the "light" parts (top and left) are
lightFactor: 0.5,
// {number} how much lighter is the top than the left
lighterFactor: 0.1,
// {number} how much darker the "dark" parts (bottom and right) are
darkFactor: 0.5,
// {number} how much darker the bottom is than the right
darkerFactor: 0.1,
// the radius of curvature at the corners (also determines the size of the faux-3D shading)
cornerRadius: 10,
lightSource: 'leftTop', // {string}, one of 'leftTop', 'rightTop', 'leftBottom', 'rightBottom',
// {number} What fraction of the cornerRadius should the light and dark gradients extend into the rectangle?
// Should always be less than 1.
lightOffset: 0.525,
darkOffset: 0.375
}, options );
assert && assert( options.lightSource === 'leftTop' ||
options.lightSource === 'rightTop' ||
options.lightSource === 'leftBottom' ||
options.lightSource === 'rightBottom',
'The lightSource ' + options.lightSource + ' is not supported' );
assert && assert( options.lightOffset < 1, 'options.lightOffset needs to be less than 1' );
assert && assert( options.darkOffset < 1, 'options.darkOffset needs to be less than 1' );
var lightFromLeft = options.lightSource.indexOf( 'left' ) >= 0;
var lightFromTop = options.lightSource.indexOf( 'Top' ) >= 0;
var cornerRadius = options.cornerRadius;
// @private {Property.<Color>} - compute our colors
this.lighterPaint = new PaintColorProperty( options.baseColor, { factor: options.lightFactor + options.lighterFactor } );
this.lightPaint = new PaintColorProperty( options.baseColor, { factor: options.lightFactor } );
this.darkPaint = new PaintColorProperty( options.baseColor, { factor: options.darkFactor } );
this.darkerPaint = new PaintColorProperty( options.baseColor, { factor: options.darkFactor + options.darkerFactor } );
// change colors based on orientation
var topColor = lightFromTop ? this.lighterPaint : this.darkerPaint;
var leftColor = lightFromLeft ? this.lightPaint : this.darkPaint;
var rightColor = lightFromLeft ? this.darkPaint : this.lightPaint;
var bottomColor = lightFromTop ? this.darkerPaint : this.lighterPaint;
// how far our light and dark gradients will extend into the rectangle
var lightOffset = options.lightOffset * cornerRadius;
var darkOffset = options.darkOffset * cornerRadius;
// change offsets based on orientation
var topOffset = lightFromTop ? lightOffset : darkOffset;
var leftOffset = lightFromLeft ? lightOffset : darkOffset;
var rightOffset = lightFromLeft ? darkOffset : lightOffset;
var bottomOffset = lightFromTop ? darkOffset : lightOffset;
// we layer two gradients on top of each other as the base (using the same rounded rectangle shape)
var horizontalNode = Rectangle.roundedBounds( rectBounds, cornerRadius, cornerRadius, { pickable: false } );
var verticalNode = Rectangle.roundedBounds( rectBounds, cornerRadius, cornerRadius, { pickable: false } );
horizontalNode.fill = new LinearGradient( horizontalNode.left, 0, horizontalNode.right, 0 )
.addColorStop( 0, leftColor )
.addColorStop( leftOffset / verticalNode.width, options.baseColor )
.addColorStop( 1 - rightOffset / verticalNode.width, options.baseColor )
.addColorStop( 1, rightColor );
verticalNode.fill = new LinearGradient( 0, verticalNode.top, 0, verticalNode.bottom )
.addColorStop( 0, topColor )
.addColorStop( topOffset / verticalNode.height, topColor.withAlpha( 0 ) )
.addColorStop( 1 - bottomOffset / verticalNode.height, bottomColor.withAlpha( 0 ) )
.addColorStop( 1, bottomColor );
// shape of our corner (in this case, top-right)
var cornerShape = new Shape().moveTo( 0, 0 )
.arc( 0, 0, cornerRadius, -Math.PI / 2, 0, false )
.close();
// rotation needed to move the cornerShape into the proper orientation as the light corner (Math.PI more for dark corner)
var lightCornerRotation = {
leftTop: -Math.PI / 2,
rightTop: 0,
rightBottom: Math.PI / 2,
leftBottom: Math.PI
}[ options.lightSource ];
var innerBounds = rectBounds.eroded( cornerRadius );
// since both the top and left are "lighter", we have a rounded gradient along that corner
var lightCorner = new Path( cornerShape, {
x: lightFromLeft ? innerBounds.minX : innerBounds.maxX,
y: lightFromTop ? innerBounds.minY : innerBounds.maxY,
rotation: lightCornerRotation,
fill: new RadialGradient( 0, 0, 0, 0, 0, cornerRadius )
.addColorStop( 0, options.baseColor )
.addColorStop( 1 - lightOffset / cornerRadius, options.baseColor )
.addColorStop( 1, this.lighterPaint ),
pickable: false
} );
// since both the bottom and right are "darker", we have a rounded gradient along that corner
var darkCorner = new Path( cornerShape, {
x: lightFromLeft ? innerBounds.maxX : innerBounds.minX,
y: lightFromTop ? innerBounds.maxY : innerBounds.minY,
rotation: lightCornerRotation + Math.PI, // opposite direction from our light corner
fill: new RadialGradient( 0, 0, 0, 0, 0, cornerRadius )
.addColorStop( 0, options.baseColor )
.addColorStop( 1 - darkOffset / cornerRadius, options.baseColor )
.addColorStop( 1, this.darkerPaint ),
pickable: false
} );
// the stroke around the outside
var panelStroke = Rectangle.roundedBounds( rectBounds, cornerRadius, cornerRadius, {
stroke: rightColor.withAlpha( 0.4 )
} );
// layout
this.addChild( horizontalNode );
this.addChild( verticalNode );
this.addChild( lightCorner );
this.addChild( darkCorner );
this.addChild( panelStroke ); // NOTE: this is the pickable child used for hit testing. Ensure something is pickable.
this.mutate( options );
}
sceneryPhet.register( 'ShadedRectangle', ShadedRectangle );
return inherit( Node, ShadedRectangle, {
/**
* Releases references.
* @public
* @override
*/
dispose: function() {
this.lighterPaint.dispose();
this.lightPaint.dispose();
this.darkPaint.dispose();
this.darkerPaint.dispose();
Node.prototype.dispose.call( this );
}
} );
} );
| js/ShadedRectangle.js | // Copyright 2014-2017, University of Colorado Boulder
/**
* A rectangle with pseudo-3D shading.
*
* @author Jonathan Olson <[email protected]>
*/
define( function( require ) {
'use strict';
// modules
var Color = require( 'SCENERY/util/Color' );
var inherit = require( 'PHET_CORE/inherit' );
var LinearGradient = require( 'SCENERY/util/LinearGradient' );
var Node = require( 'SCENERY/nodes/Node' );
var Path = require( 'SCENERY/nodes/Path' );
var RadialGradient = require( 'SCENERY/util/RadialGradient' );
var Rectangle = require( 'SCENERY/nodes/Rectangle' );
var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
var Shape = require( 'KITE/Shape' );
/**
* Creates a pseudo-3D shaded rounded rectangle that takes up rectBounds {Bounds2} in size. See below documentation
* for options (it is passed through to the Node also).
*
* @param {Bounds2} rectBounds
* @param {Object} [options]
* @constructor
*/
function ShadedRectangle( rectBounds, options ) {
Node.call( this );
options = _.extend( {
// {Color|string} default base color
baseColor: new Color( 80, 130, 230 ),
// {number} how much lighter the "light" parts (top and left) are
lightFactor: 0.5,
// {number} how much lighter is the top than the left
lighterFactor: 0.1,
// {number} how much darker the "dark" parts (bottom and right) are
darkFactor: 0.5,
// {number} how much darker the bottom is than the right
darkerFactor: 0.1,
// the radius of curvature at the corners (also determines the size of the faux-3D shading)
cornerRadius: 10,
lightSource: 'leftTop', // {string}, one of 'leftTop', 'rightTop', 'leftBottom', 'rightBottom',
// {number} What fraction of the cornerRadius should the light and dark gradients extend into the rectangle?
// Should always be less than 1.
lightOffset: 0.525,
darkOffset: 0.375
}, options );
assert && assert( options.lightSource === 'leftTop' ||
options.lightSource === 'rightTop' ||
options.lightSource === 'leftBottom' ||
options.lightSource === 'rightBottom',
'The lightSource ' + options.lightSource + ' is not supported' );
assert && assert( options.lightOffset < 1, 'options.lightOffset needs to be less than 1' );
assert && assert( options.darkOffset < 1, 'options.darkOffset needs to be less than 1' );
var lightFromLeft = options.lightSource.indexOf( 'left' ) >= 0;
var lightFromTop = options.lightSource.indexOf( 'Top' ) >= 0;
var cornerRadius = options.cornerRadius;
// compute our colors
var baseColor = options.baseColor instanceof Color ? options.baseColor : new Color( options.baseColor );
var lighterColor = baseColor.colorUtilsBrighter( options.lightFactor + options.lighterFactor );
var lightColor = baseColor.colorUtilsBrighter( options.lightFactor );
var darkColor = baseColor.colorUtilsDarker( options.darkFactor );
var darkerColor = baseColor.colorUtilsDarker( options.darkFactor + options.darkerFactor );
// change colors based on orientation
var topColor = lightFromTop ? lighterColor : darkerColor;
var leftColor = lightFromLeft ? lightColor : darkColor;
var rightColor = lightFromLeft ? darkColor : lightColor;
var bottomColor = lightFromTop ? darkerColor : lighterColor;
// how far our light and dark gradients will extend into the rectangle
var lightOffset = options.lightOffset * cornerRadius;
var darkOffset = options.darkOffset * cornerRadius;
// change offsets based on orientation
var topOffset = lightFromTop ? lightOffset : darkOffset;
var leftOffset = lightFromLeft ? lightOffset : darkOffset;
var rightOffset = lightFromLeft ? darkOffset : lightOffset;
var bottomOffset = lightFromTop ? darkOffset : lightOffset;
// we layer two gradients on top of each other as the base (using the same rounded rectangle shape)
var horizontalNode = Rectangle.roundedBounds( rectBounds, cornerRadius, cornerRadius, { pickable: false } );
var verticalNode = Rectangle.roundedBounds( rectBounds, cornerRadius, cornerRadius, { pickable: false } );
horizontalNode.fill = new LinearGradient( horizontalNode.left, 0, horizontalNode.right, 0 )
.addColorStop( 0, leftColor )
.addColorStop( leftOffset / verticalNode.width, baseColor )
.addColorStop( 1 - rightOffset / verticalNode.width, baseColor )
.addColorStop( 1, rightColor );
verticalNode.fill = new LinearGradient( 0, verticalNode.top, 0, verticalNode.bottom )
.addColorStop( 0, topColor )
.addColorStop( topOffset / verticalNode.height, topColor.withAlpha( 0 ) )
.addColorStop( 1 - bottomOffset / verticalNode.height, bottomColor.withAlpha( 0 ) )
.addColorStop( 1, bottomColor );
// shape of our corner (in this case, top-right)
var cornerShape = new Shape().moveTo( 0, 0 )
.arc( 0, 0, cornerRadius, -Math.PI / 2, 0, false )
.close();
// rotation needed to move the cornerShape into the proper orientation as the light corner (Math.PI more for dark corner)
var lightCornerRotation = {
leftTop: -Math.PI / 2,
rightTop: 0,
rightBottom: Math.PI / 2,
leftBottom: Math.PI
}[ options.lightSource ];
var innerBounds = rectBounds.eroded( cornerRadius );
// since both the top and left are "lighter", we have a rounded gradient along that corner
var lightCorner = new Path( cornerShape, {
x: lightFromLeft ? innerBounds.minX : innerBounds.maxX,
y: lightFromTop ? innerBounds.minY : innerBounds.maxY,
rotation: lightCornerRotation,
fill: new RadialGradient( 0, 0, 0, 0, 0, cornerRadius )
.addColorStop( 0, baseColor )
.addColorStop( 1 - lightOffset / cornerRadius, baseColor )
.addColorStop( 1, lighterColor ),
pickable: false
} );
// since both the bottom and right are "darker", we have a rounded gradient along that corner
var darkCorner = new Path( cornerShape, {
x: lightFromLeft ? innerBounds.maxX : innerBounds.minX,
y: lightFromTop ? innerBounds.maxY : innerBounds.minY,
rotation: lightCornerRotation + Math.PI, // opposite direction from our light corner
fill: new RadialGradient( 0, 0, 0, 0, 0, cornerRadius )
.addColorStop( 0, baseColor )
.addColorStop( 1 - darkOffset / cornerRadius, baseColor )
.addColorStop( 1, darkerColor ),
pickable: false
} );
// the stroke around the outside
var panelStroke = Rectangle.roundedBounds( rectBounds, cornerRadius, cornerRadius, {
stroke: rightColor.withAlpha( 0.4 )
} );
// layout
this.addChild( horizontalNode );
this.addChild( verticalNode );
this.addChild( lightCorner );
this.addChild( darkCorner );
this.addChild( panelStroke ); // NOTE: this is the pickable child used for hit testing. Ensure something is pickable.
this.mutate( options );
}
sceneryPhet.register( 'ShadedRectangle', ShadedRectangle );
return inherit( Node, ShadedRectangle );
} );
| Color property support for ShadedRectangle, see https://github.com/phetsims/sun/issues/362
| js/ShadedRectangle.js | Color property support for ShadedRectangle, see https://github.com/phetsims/sun/issues/362 | <ide><path>s/ShadedRectangle.js
<ide> var inherit = require( 'PHET_CORE/inherit' );
<ide> var LinearGradient = require( 'SCENERY/util/LinearGradient' );
<ide> var Node = require( 'SCENERY/nodes/Node' );
<add> var PaintColorProperty = require( 'SCENERY/util/PaintColorProperty' );
<ide> var Path = require( 'SCENERY/nodes/Path' );
<ide> var RadialGradient = require( 'SCENERY/util/RadialGradient' );
<ide> var Rectangle = require( 'SCENERY/nodes/Rectangle' );
<ide>
<ide> var cornerRadius = options.cornerRadius;
<ide>
<del> // compute our colors
<del> var baseColor = options.baseColor instanceof Color ? options.baseColor : new Color( options.baseColor );
<del> var lighterColor = baseColor.colorUtilsBrighter( options.lightFactor + options.lighterFactor );
<del> var lightColor = baseColor.colorUtilsBrighter( options.lightFactor );
<del> var darkColor = baseColor.colorUtilsDarker( options.darkFactor );
<del> var darkerColor = baseColor.colorUtilsDarker( options.darkFactor + options.darkerFactor );
<add> // @private {Property.<Color>} - compute our colors
<add> this.lighterPaint = new PaintColorProperty( options.baseColor, { factor: options.lightFactor + options.lighterFactor } );
<add> this.lightPaint = new PaintColorProperty( options.baseColor, { factor: options.lightFactor } );
<add> this.darkPaint = new PaintColorProperty( options.baseColor, { factor: options.darkFactor } );
<add> this.darkerPaint = new PaintColorProperty( options.baseColor, { factor: options.darkFactor + options.darkerFactor } );
<ide>
<ide> // change colors based on orientation
<del> var topColor = lightFromTop ? lighterColor : darkerColor;
<del> var leftColor = lightFromLeft ? lightColor : darkColor;
<del> var rightColor = lightFromLeft ? darkColor : lightColor;
<del> var bottomColor = lightFromTop ? darkerColor : lighterColor;
<add> var topColor = lightFromTop ? this.lighterPaint : this.darkerPaint;
<add> var leftColor = lightFromLeft ? this.lightPaint : this.darkPaint;
<add> var rightColor = lightFromLeft ? this.darkPaint : this.lightPaint;
<add> var bottomColor = lightFromTop ? this.darkerPaint : this.lighterPaint;
<ide>
<ide> // how far our light and dark gradients will extend into the rectangle
<ide> var lightOffset = options.lightOffset * cornerRadius;
<ide>
<ide> horizontalNode.fill = new LinearGradient( horizontalNode.left, 0, horizontalNode.right, 0 )
<ide> .addColorStop( 0, leftColor )
<del> .addColorStop( leftOffset / verticalNode.width, baseColor )
<del> .addColorStop( 1 - rightOffset / verticalNode.width, baseColor )
<add> .addColorStop( leftOffset / verticalNode.width, options.baseColor )
<add> .addColorStop( 1 - rightOffset / verticalNode.width, options.baseColor )
<ide> .addColorStop( 1, rightColor );
<ide>
<ide> verticalNode.fill = new LinearGradient( 0, verticalNode.top, 0, verticalNode.bottom )
<ide> y: lightFromTop ? innerBounds.minY : innerBounds.maxY,
<ide> rotation: lightCornerRotation,
<ide> fill: new RadialGradient( 0, 0, 0, 0, 0, cornerRadius )
<del> .addColorStop( 0, baseColor )
<del> .addColorStop( 1 - lightOffset / cornerRadius, baseColor )
<del> .addColorStop( 1, lighterColor ),
<add> .addColorStop( 0, options.baseColor )
<add> .addColorStop( 1 - lightOffset / cornerRadius, options.baseColor )
<add> .addColorStop( 1, this.lighterPaint ),
<ide> pickable: false
<ide> } );
<ide>
<ide> y: lightFromTop ? innerBounds.maxY : innerBounds.minY,
<ide> rotation: lightCornerRotation + Math.PI, // opposite direction from our light corner
<ide> fill: new RadialGradient( 0, 0, 0, 0, 0, cornerRadius )
<del> .addColorStop( 0, baseColor )
<del> .addColorStop( 1 - darkOffset / cornerRadius, baseColor )
<del> .addColorStop( 1, darkerColor ),
<add> .addColorStop( 0, options.baseColor )
<add> .addColorStop( 1 - darkOffset / cornerRadius, options.baseColor )
<add> .addColorStop( 1, this.darkerPaint ),
<ide> pickable: false
<ide> } );
<ide>
<ide>
<ide> sceneryPhet.register( 'ShadedRectangle', ShadedRectangle );
<ide>
<del> return inherit( Node, ShadedRectangle );
<add> return inherit( Node, ShadedRectangle, {
<add> /**
<add> * Releases references.
<add> * @public
<add> * @override
<add> */
<add> dispose: function() {
<add> this.lighterPaint.dispose();
<add> this.lightPaint.dispose();
<add> this.darkPaint.dispose();
<add> this.darkerPaint.dispose();
<add>
<add> Node.prototype.dispose.call( this );
<add> }
<add> } );
<ide> } );
<ide> |
|
Java | epl-1.0 | f878283bf2283b1ce1578109a127df797ee0a550 | 0 | ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio | /*******************************************************************************
* Copyright (c) 2010 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package org.csstudio.trends.databrowser2.model;
import org.csstudio.data.values.IMinMaxDoubleValue;
import org.csstudio.data.values.INumericMetaData;
import org.csstudio.data.values.ISeverity;
import org.csstudio.data.values.ITimestamp;
import org.csstudio.data.values.IValue;
import org.csstudio.data.values.TimestampFactory;
import org.csstudio.data.values.ValueFactory;
import org.csstudio.data.values.ValueUtil;
import org.csstudio.swt.xygraph.dataprovider.ISample;
import org.csstudio.trends.databrowser2.Messages;
import org.eclipse.osgi.util.NLS;
/** Data Sample from control system (IValue)
* with interface for XYGraph (ISample)
* @author Kay Kasemir
* @author Takashi Nakamoto changed PlotSample to handle waveform index.
*/
public class PlotSample implements ISample
{
final public static INumericMetaData dummy_meta = ValueFactory.createNumericMetaData(0, 0, 0, 0, 0, 0, 1, "a.u."); //$NON-NLS-1$
final public static ISeverity ok_severity = ValueFactory.createOKSeverity();
/** Value contained in this sample */
final private IValue value;
/** Source of the data */
final private String source;
/** Info string.
* @see #getInfo()
*/
private String info;
/** Waveform index */
private int waveform_index = 0;
/** Initialize with valid control system value
* @param source Info about the source of this sample
* @param value
*/
public PlotSample(final String source, final IValue value)
{
this.value = value;
this.source = source;
info = null;
}
/** Initialize with (error) info, creating a non-plottable sample 'now'
* @param info Text used for info as well as error message
*/
public PlotSample(final String source, final String info)
{
this(source, ValueFactory.createDoubleValue(TimestampFactory.now(),
ValueFactory.createInvalidSeverity(), info, dummy_meta,
IValue.Quality.Original, new double[] { Double.NaN }));
this.info = info;
}
/** Package-level constructor, only used in unit tests */
@SuppressWarnings("nls")
PlotSample(final double x, final double y)
{
this("Test",
ValueFactory.createDoubleValue(TimestampFactory.fromDouble(x),
ok_severity, ok_severity.toString(), dummy_meta,
IValue.Quality.Original, new double[] { y }));
}
/** @return Waveform index */
public int getWaveformIndex()
{
return waveform_index;
}
/** @param index Waveform index to plot */
public void setWaveformIndex(int index)
{
this.waveform_index = index;
}
/** @return Source of the data */
public String getSource()
{
return source;
}
/** @return Control system value */
public IValue getValue()
{
return value;
}
/** @return Control system time stamp */
public ITimestamp getTime()
{
return value.getTime();
}
/** Since the 'X' axis is used as a 'Time' axis, this
* returns the time stamp of the control system sample.
* The XYGraph expects it to be milliseconds(!) since 1970.
* @return Time as milliseconds since 1970
*/
@Override
public double getXValue()
{
return value.getTime().toDouble()*1000.0;
}
/** {@inheritDoc} */
@Override
public double getYValue()
{
if (value.getSeverity().hasValue() && waveform_index < ValueUtil.getSize(value)){
return ValueUtil.getDouble(value, waveform_index);
}
// No numeric value or out of range. Plot shows NaN as marker.
return Double.NaN;
}
/** Get sample's info text.
* If not set on construction, the value's text is used.
* @return Sample's info text. */
@Override
public String getInfo()
{
if (info == null)
return toString();
return info;
}
/** {@inheritDoc} */
@Override
public double getXMinusError()
{
return 0;
}
/** {@inheritDoc} */
@Override
public double getXPlusError()
{
return 0;
}
/** {@inheritDoc} */
@Override
public double getYMinusError()
{
if (!(value instanceof IMinMaxDoubleValue))
return 0;
// Although the behavior of getMinimum() method depends on archive
// readers' implementation, at least, RDB and kblog archive readers
// return the minimum value of the first element. This minimum value
// does not make sense to plot error bars when the chart shows other
// elements. Therefore, this method returns 0 if the waveform index
// is not 0.
if (waveform_index != 0)
return 0;
final IMinMaxDoubleValue minmax = (IMinMaxDoubleValue)value;
return minmax.getValue() - minmax.getMinimum();
}
/** {@inheritDoc} */
@Override
public double getYPlusError()
{
if (!(value instanceof IMinMaxDoubleValue))
return 0;
// Although the behavior of getMaximum() method depends on archive
// readers' implementation, at least, RDB and kblog archive readers
// return the maximum value of the first element. This maximum value
// does not make sense to plot error bars when the chart shows other
// elements. Therefore, this method returns 0 if the waveform index
// is not 0.
if (waveform_index != 0)
return 0;
final IMinMaxDoubleValue minmax = (IMinMaxDoubleValue)value;
return minmax.getMaximum() - minmax.getValue();
}
@Override
public String toString()
{
return NLS.bind(Messages.PlotSampleFmt, new Object[] { value, source, value.getQuality().toString() });
}
}
| applications/plugins/org.csstudio.trends.databrowser2/src/org/csstudio/trends/databrowser2/model/PlotSample.java | /*******************************************************************************
* Copyright (c) 2010 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package org.csstudio.trends.databrowser2.model;
import org.csstudio.data.values.IMinMaxDoubleValue;
import org.csstudio.data.values.INumericMetaData;
import org.csstudio.data.values.ISeverity;
import org.csstudio.data.values.ITimestamp;
import org.csstudio.data.values.IValue;
import org.csstudio.data.values.TimestampFactory;
import org.csstudio.data.values.ValueFactory;
import org.csstudio.data.values.ValueUtil;
import org.csstudio.swt.xygraph.dataprovider.ISample;
import org.csstudio.trends.databrowser2.Messages;
import org.eclipse.osgi.util.NLS;
/** Data Sample from control system (IValue)
* with interface for XYGraph (ISample)
* @author Kay Kasemir
* @author Takashi Nakamoto changed PlotSample to handle waveform index.
*/
public class PlotSample implements ISample
{
final public static INumericMetaData dummy_meta = ValueFactory.createNumericMetaData(0, 0, 0, 0, 0, 0, 1, "a.u."); //$NON-NLS-1$
final public static ISeverity ok_severity = ValueFactory.createOKSeverity();
/** Value contained in this sample */
final private IValue value;
/** Source of the data */
final private String source;
/** Info string.
* @see #getInfo()
*/
private String info;
/** Waveform index */
private int waveform_index = 0;
/** Initialize with valid control system value
* @param source Info about the source of this sample
* @param value
*/
public PlotSample(final String source, final IValue value)
{
this.value = value;
this.source = source;
info = null;
}
/** Initialize with (error) info, creating a non-plottable sample 'now'
* @param info Text used for info as well as error message
*/
public PlotSample(final String source, final String info)
{
this(source, ValueFactory.createDoubleValue(TimestampFactory.now(),
ValueFactory.createInvalidSeverity(), info, dummy_meta,
IValue.Quality.Original, new double[] { Double.NaN }));
this.info = info;
}
/** Package-level constructor, only used in unit tests */
@SuppressWarnings("nls")
PlotSample(final double x, final double y)
{
this("Test",
ValueFactory.createDoubleValue(TimestampFactory.fromDouble(x),
ok_severity, ok_severity.toString(), dummy_meta,
IValue.Quality.Original, new double[] { y }));
}
/** @return Waveform index */
public int getWaveformIndex()
{
return waveform_index;
}
/** @param index Waveform index to plot */
public void setWaveformIndex(int index)
{
this.waveform_index = index;
}
/** @return Source of the data */
public String getSource()
{
return source;
}
/** @return Control system value */
public IValue getValue()
{
return value;
}
/** @return Control system time stamp */
public ITimestamp getTime()
{
return value.getTime();
}
/** Since the 'X' axis is used as a 'Time' axis, this
* returns the time stamp of the control system sample.
* The XYGraph expects it to be milliseconds(!) since 1970.
* @return Time as milliseconds since 1970
*/
@Override
public double getXValue()
{
return value.getTime().toDouble()*1000.0;
}
/** {@inheritDoc} */
@Override
public double getYValue()
{
if (value.getSeverity().hasValue() && waveform_index < ValueUtil.getSize(value)){
return ValueUtil.getDouble(value, waveform_index);
}
// No numeric value or out of range. Plot shows NaN as marker.
return Double.NaN;
}
/** Get sample's info text.
* If not set on construction, the value's text is used.
* @return Sample's info text. */
@Override
public String getInfo()
{
if (info == null)
return toString();
return info;
}
/** {@inheritDoc} */
@Override
public double getXMinusError()
{
return 0;
}
/** {@inheritDoc} */
@Override
public double getXPlusError()
{
return 0;
}
/** {@inheritDoc} */
@Override
public double getYMinusError()
{
if (!(value instanceof IMinMaxDoubleValue))
return 0;
/*
* TODO: think of what to be changed.
* What is the meaning of minimum in case the value represents array?
*/
final IMinMaxDoubleValue minmax = (IMinMaxDoubleValue)value;
return minmax.getValue() - minmax.getMinimum();
}
/** {@inheritDoc} */
@Override
public double getYPlusError()
{
if (!(value instanceof IMinMaxDoubleValue))
return 0;
/*
* TODO: think of what to be changed.
* What is the meaning of minimum in case the value represents array?
*/
final IMinMaxDoubleValue minmax = (IMinMaxDoubleValue)value;
return minmax.getMaximum() - minmax.getValue();
}
@Override
public String toString()
{
return NLS.bind(Messages.PlotSampleFmt, new Object[] { value, source, value.getQuality().toString() });
}
}
| o.c.trends.databrowser2: getY[Plus|Minus]Error() returns always 0 when the waveform index is not 0
| applications/plugins/org.csstudio.trends.databrowser2/src/org/csstudio/trends/databrowser2/model/PlotSample.java | o.c.trends.databrowser2: getY[Plus|Minus]Error() returns always 0 when the waveform index is not 0 | <ide><path>pplications/plugins/org.csstudio.trends.databrowser2/src/org/csstudio/trends/databrowser2/model/PlotSample.java
<ide> if (!(value instanceof IMinMaxDoubleValue))
<ide> return 0;
<ide>
<del> /*
<del> * TODO: think of what to be changed.
<del> * What is the meaning of minimum in case the value represents array?
<del> */
<add> // Although the behavior of getMinimum() method depends on archive
<add> // readers' implementation, at least, RDB and kblog archive readers
<add> // return the minimum value of the first element. This minimum value
<add> // does not make sense to plot error bars when the chart shows other
<add> // elements. Therefore, this method returns 0 if the waveform index
<add> // is not 0.
<add> if (waveform_index != 0)
<add> return 0;
<add>
<ide> final IMinMaxDoubleValue minmax = (IMinMaxDoubleValue)value;
<ide> return minmax.getValue() - minmax.getMinimum();
<ide> }
<ide> if (!(value instanceof IMinMaxDoubleValue))
<ide> return 0;
<ide>
<del> /*
<del> * TODO: think of what to be changed.
<del> * What is the meaning of minimum in case the value represents array?
<del> */
<add> // Although the behavior of getMaximum() method depends on archive
<add> // readers' implementation, at least, RDB and kblog archive readers
<add> // return the maximum value of the first element. This maximum value
<add> // does not make sense to plot error bars when the chart shows other
<add> // elements. Therefore, this method returns 0 if the waveform index
<add> // is not 0.
<add> if (waveform_index != 0)
<add> return 0;
<add>
<ide> final IMinMaxDoubleValue minmax = (IMinMaxDoubleValue)value;
<ide> return minmax.getMaximum() - minmax.getValue();
<ide> } |
|
Java | mit | 8c6d29ef196bbd92079c358a8e2bf5554ce3b0ef | 0 | skgadi/Programming,skgadi/Programming,skgadi/Programming,skgadi/Programming,skgadi/Programming,skgadi/Programming | package com.skgadi.progtransit000;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.hoho.android.usbserial.driver.CdcAcmSerialDriver;
import com.hoho.android.usbserial.driver.ProbeTable;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.Phaser;
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
protected UsbManager manager;
ProbeTable customTable;
UsbSerialProber prober;
List<UsbSerialDriver> drivers;
UsbSerialDriver driver;
UsbDeviceConnection connection;
private UsbSerialPort port;
private ProgressBar ProgramProgressBar;
ToggleButton ConnectButton;
Button ProgramButton;
private enum DEVICE_STATE {
DISCONNECTED,
CONNECTED
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Toast.makeText(getApplicationContext(), "First Exception",Toast.LENGTH_SHORT).show();
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(R.string.title_home);
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
return true;
case R.id.navigation_notifications:
mTextMessage.setText(R.string.title_notifications);
return true;
case R.id.navigation_about:
mTextMessage.setText(R.string.title_about);
return true;
}
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
//Added by Suresh Gadi
//Pulling variables from xml
ProgramButton = (Button) findViewById(R.id.programButton);
ConnectButton = (ToggleButton) findViewById(R.id.toggleConnectButton);
ProgramProgressBar = (ProgressBar) findViewById(R.id.ProgramProgressBar);
customTable = new ProbeTable();
customTable.addProduct(0x4D8, 0x000A, CdcAcmSerialDriver.class);
prober = new UsbSerialProber(customTable);
ConnectButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
int status = ConnectUSB ();
if (status == 2)
SetStateAs(DEVICE_STATE.CONNECTED);
else
SetStateAs(DEVICE_STATE.DISCONNECTED);
} else {
try {
SetStateAs(DEVICE_STATE.DISCONNECTED);
port.close();
Toast.makeText(MainActivity.this, R.string.success_device_disconnected,Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, R.string.error_device_disconnect,Toast.LENGTH_SHORT).show();
}
}
}
});
}
private void SetStateAs (DEVICE_STATE state) {
switch (state) {
case CONNECTED:
ConnectButton.setChecked(true);
ProgramButton.setVisibility(View.VISIBLE);
return;
case DISCONNECTED:
ConnectButton.setChecked(false);
ProgramButton.setVisibility(View.INVISIBLE);
//ProgramButton.setVisibility(View.VISIBLE);
return;
}
}
private int ConnectUSB () {
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
drivers = prober.findAllDrivers(manager);
if (drivers.isEmpty()) {
Toast.makeText(MainActivity.this, R.string.error_device_not_connected,Toast.LENGTH_SHORT).show();
return 0;
}
driver = drivers.get(0);
connection = manager.openDevice(driver.getDevice());
if (connection == null) {
// You probably need to call UsbManager.requestPermission(driver.getDevice(), ..)
String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(MainActivity.this, 0, new Intent(ACTION_USB_PERMISSION), 0);
manager.requestPermission(driver.getDevice(), mPermissionIntent);
Toast.makeText(MainActivity.this, R.string.error_device_unable_to_connect,Toast.LENGTH_SHORT).show();
return 1;
}
port = driver.getPorts().get(0);
try {
port.open(connection);
port.setParameters(9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
Toast.makeText(MainActivity.this, R.string.success_device_connected,Toast.LENGTH_SHORT).show();
return 2;
} catch (IOException e) {
Toast.makeText(MainActivity.this, R.string.error_device_open_port,Toast.LENGTH_SHORT).show();
e.printStackTrace();
return 0;
}
}
public void SendAndVerify (View v) {
new ProgramDeviceTask().execute(port);
return;
}
private void setProgressPercent(Integer Percent) {
ProgramProgressBar.setProgress(Percent);
}
private class ProgramDeviceTask extends AsyncTask<UsbSerialPort, Integer, Integer> {
private boolean isSuccessful = true;
private int lastErrorLocation=0;
private int noOfErrors = 0;
private int noOfSuccess = 0;
private byte SendBuffer[] = new byte[6];
private void PrepareSendBufferToWrite(int address, int data) {
SendBuffer[0] = 0x32;
SendBuffer[1] = (byte) ((address & 0xff0000)>>16);
SendBuffer[2] = (byte) ((address & 0x00ff00)>>8);
SendBuffer[3] = (byte) ((address & 0x0000ff));
SendBuffer[4] = (byte) ((data & 0xff00)>>8);
SendBuffer[5] = (byte) ((data & 0x00ff));
return;
}
private void PrepareStartCommand(){
SendBuffer[0] = 0x30;
return;
}
private void PrepareEndCommand(){
SendBuffer[0] = 0x31;
return;
}
protected Integer doInBackground(UsbSerialPort... ports) {
UsbSerialPort port;
port = ports[0];
int RecBuffLength=0;
byte RecBuffer[] = new byte[4];
int MAddress = 0x310000;
byte Data = 0x00;
int EE_Settings[]={0x98, 0xFE, 1, 4, 1, 10, 20, 0xF6, 0xFF, 60, 40, 4, 8, 192, 8, 42, 5, 1, 128, 81, 1, 0, 5, 0xC5, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 160, 0, 1, 0, 5, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, 82, 0x20, 0x90, 0x01, 0x00, 3, 0x22, 0x90, 0x00, 0x00, 6, 0x0C, 0x90, 0x00, 0x00, 2, 0x04, 0x90, 0x08, 0x00, 2, 0x14, 0x90, 0x00, 0x00, 21, 0x24, 0x28, 0x00, 0x00, 2, 0x24, 0x10, 0x00, 0x20, 2, 0x24, 0x50, 0x00, 0x00, 1, 0x00, 0x00, 0x14, 0x20, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, };
for (int i=0; i<5; i++) {
PrepareEndCommand();
try {
port.purgeHwBuffers(true, true);
port.write(SendBuffer, 10);
} catch (IOException e) {
e.printStackTrace();
}
PrepareStartCommand();
try {
port.purgeHwBuffers(true, true);
port.write(SendBuffer, 10);
} catch (IOException e) {
e.printStackTrace();
}
}
/*try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
for (int i=0; i<1024; i++) {
/*try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
PrepareSendBufferToWrite(MAddress++, (byte) EE_Settings[i]);
try {
port.purgeHwBuffers(true, true);
port.write(SendBuffer, 100);
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
RecBuffer[0] = 3;
RecBuffLength = port.read(RecBuffer, 100);
if (RecBuffer[0]==0x30) {
isSuccessful = false;
lastErrorLocation = i;
noOfErrors++;
} else if (RecBuffer[0]==0x31)
noOfSuccess++;
} catch (IOException e) {
e.printStackTrace();
}
publishProgress(((i+1)*100)/1024);
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
PrepareEndCommand();
try {
port.purgeHwBuffers(true, true);
port.write(SendBuffer, 10);
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Integer result) {
if (isSuccessful)
mTextMessage.append("\nDone");
else
mTextMessage.append("\nErrors:"+noOfErrors+"\nSuccess:"+noOfSuccess+"\nLast error at:"+ lastErrorLocation);
mTextMessage.append("\nDone "+"\n"+ Integer.toHexString(SendBuffer[0])+"\n"+ Integer.toHexString(SendBuffer[1])+"\n"+
Integer.toHexString(SendBuffer[2])+"\n"+ Integer.toHexString(SendBuffer[3])
+"\n"+ Integer.toHexString(SendBuffer[4])+"\n"+ Integer.toHexString(SendBuffer[5]));
}
}
// File handling Code
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public File PrepareDirectoryForStoringConfigFiles() {
// Get the directory for the app's private pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "ProgTransitConfigFiles");
if (!file.mkdirs()) {
mTextMessage.append("\nDirectory not created");
} else {
mTextMessage.append("\nDone");
}
return file;
}
public void ListFiles (View v) {
if (isExternalStorageWritable()) {
File file = PrepareDirectoryForStoringConfigFiles();
if (file.exists())
mTextMessage.append("\nDone");
else
mTextMessage.append("\nOpssss...");
} else
mTextMessage.append("\nNo :( ......");
}
}
| Android/ProgTransit000/app/src/main/java/com/skgadi/progtransit000/MainActivity.java | package com.skgadi.progtransit000;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.hoho.android.usbserial.driver.CdcAcmSerialDriver;
import com.hoho.android.usbserial.driver.ProbeTable;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.Phaser;
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
protected UsbManager manager;
ProbeTable customTable;
UsbSerialProber prober;
List<UsbSerialDriver> drivers;
UsbSerialDriver driver;
UsbDeviceConnection connection;
private UsbSerialPort port;
private ProgressBar ProgramProgressBar;
ToggleButton ConnectButton;
Button ProgramButton;
private enum DEVICE_STATE {
DISCONNECTED,
CONNECTED
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Toast.makeText(getApplicationContext(), "First Exception",Toast.LENGTH_SHORT).show();
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(R.string.title_home);
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
return true;
case R.id.navigation_notifications:
mTextMessage.setText(R.string.title_notifications);
return true;
case R.id.navigation_about:
mTextMessage.setText(R.string.title_about);
return true;
}
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
//Added by Suresh Gadi
//Pulling variables from xml
ProgramButton = (Button) findViewById(R.id.programButton);
ConnectButton = (ToggleButton) findViewById(R.id.toggleConnectButton);
ProgramProgressBar = (ProgressBar) findViewById(R.id.ProgramProgressBar);
customTable = new ProbeTable();
customTable.addProduct(0x4D8, 0x000A, CdcAcmSerialDriver.class);
prober = new UsbSerialProber(customTable);
ConnectButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
int status = ConnectUSB ();
if (status == 2)
SetStateAs(DEVICE_STATE.CONNECTED);
else
SetStateAs(DEVICE_STATE.DISCONNECTED);
} else {
try {
SetStateAs(DEVICE_STATE.DISCONNECTED);
port.close();
Toast.makeText(MainActivity.this, R.string.success_device_disconnected,Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, R.string.error_device_disconnect,Toast.LENGTH_SHORT).show();
}
}
}
});
}
private void SetStateAs (DEVICE_STATE state) {
switch (state) {
case CONNECTED:
ConnectButton.setChecked(true);
ProgramButton.setVisibility(View.VISIBLE);
return;
case DISCONNECTED:
ConnectButton.setChecked(false);
ProgramButton.setVisibility(View.INVISIBLE);
//ProgramButton.setVisibility(View.VISIBLE);
return;
}
}
private int ConnectUSB () {
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
drivers = prober.findAllDrivers(manager);
if (drivers.isEmpty()) {
Toast.makeText(MainActivity.this, R.string.error_device_not_connected,Toast.LENGTH_SHORT).show();
return 0;
}
driver = drivers.get(0);
connection = manager.openDevice(driver.getDevice());
if (connection == null) {
// You probably need to call UsbManager.requestPermission(driver.getDevice(), ..)
String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(MainActivity.this, 0, new Intent(ACTION_USB_PERMISSION), 0);
manager.requestPermission(driver.getDevice(), mPermissionIntent);
Toast.makeText(MainActivity.this, R.string.error_device_unable_to_connect,Toast.LENGTH_SHORT).show();
return 1;
}
port = driver.getPorts().get(0);
try {
port.open(connection);
port.setParameters(9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
Toast.makeText(MainActivity.this, R.string.success_device_connected,Toast.LENGTH_SHORT).show();
return 2;
} catch (IOException e) {
Toast.makeText(MainActivity.this, R.string.error_device_open_port,Toast.LENGTH_SHORT).show();
e.printStackTrace();
return 0;
}
}
public void SendAndVerify (View v) {
new ProgramDeviceTask().execute(port);
return;
}
private void setProgressPercent(Integer Percent) {
ProgramProgressBar.setProgress(Percent);
}
private class ProgramDeviceTask extends AsyncTask<UsbSerialPort, Integer, Integer> {
private boolean isSuccessful = true;
private int lastErrorLocation=0;
private int noOfErrors = 0;
private int noOfSuccess = 0;
private byte SendBuffer[] = new byte[6];
private void PrepareSendBufferToWrite(int address, int data) {
SendBuffer[0] = 0x32;
SendBuffer[1] = (byte) ((address & 0xff0000)>>16);
SendBuffer[2] = (byte) ((address & 0x00ff00)>>8);
SendBuffer[3] = (byte) ((address & 0x0000ff));
SendBuffer[4] = (byte) ((data & 0xff00)>>8);
SendBuffer[5] = (byte) ((data & 0x00ff));
return;
}
private void PrepareStartCommand(){
SendBuffer[0] = 0x30;
return;
}
private void PrepareEndCommand(){
SendBuffer[0] = 0x31;
return;
}
protected Integer doInBackground(UsbSerialPort... ports) {
UsbSerialPort port;
port = ports[0];
int RecBuffLength=0;
byte RecBuffer[] = new byte[4];
int MAddress = 0x310000;
byte Data = 0x00;
int EE_Settings[]={0x7A, 0xFE, 1, 4, 1, 10, 20, 0xF6, 0xFF, 60, 40, 4, 8, 192, 8, 42, 5, 1, 128, 81, 1, 0, 5, 0xC5, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 160, 0, 1, 0, 5, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, 82, 0x20, 0x90, 0x01, 0x00, 3, 0x22, 0x90, 0x00, 0x00, 6, 0x0C, 0x90, 0x00, 0x00, 2, 0x04, 0x90, 0x08, 0x00, 2, 0x14, 0x90, 0x00, 0x00, 21, 0x24, 0x28, 0x00, 0x00, 2, 0x24, 0x10, 0x00, 0x20, 2, 0x24, 0x50, 0x00, 0x00, 1, 0x00, 0x00, 0x14, 0x20, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, };
for (int i=0; i<5; i++) {
PrepareEndCommand();
try {
port.purgeHwBuffers(true, true);
port.write(SendBuffer, 10);
} catch (IOException e) {
e.printStackTrace();
}
PrepareStartCommand();
try {
port.purgeHwBuffers(true, true);
port.write(SendBuffer, 10);
} catch (IOException e) {
e.printStackTrace();
}
}
/*try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
for (int i=0; i<1024; i++) {
/*try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
PrepareSendBufferToWrite(MAddress++, (byte) EE_Settings[i]);
try {
port.purgeHwBuffers(true, true);
port.write(SendBuffer, 100);
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
RecBuffer[0] = 3;
RecBuffLength = port.read(RecBuffer, 100);
if (RecBuffer[0]==0x30) {
isSuccessful = false;
lastErrorLocation = i;
noOfErrors++;
} else if (RecBuffer[0]==0x31)
noOfSuccess++;
} catch (IOException e) {
e.printStackTrace();
}
publishProgress(((i+1)*100)/1024);
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
PrepareEndCommand();
try {
port.purgeHwBuffers(true, true);
port.write(SendBuffer, 10);
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Integer result) {
if (isSuccessful)
mTextMessage.append("\nDone");
else
mTextMessage.append("\nErrors:"+noOfErrors+"\nSuccess:"+noOfSuccess+"\nLast error at:"+ lastErrorLocation);
mTextMessage.append("\nDone "+"\n"+ Integer.toHexString(SendBuffer[0])+"\n"+ Integer.toHexString(SendBuffer[1])+"\n"+
Integer.toHexString(SendBuffer[2])+"\n"+ Integer.toHexString(SendBuffer[3])
+"\n"+ Integer.toHexString(SendBuffer[4])+"\n"+ Integer.toHexString(SendBuffer[5]));
}
}
// File handling Code
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public File PrepareDirectoryForStoringConfigFiles() {
// Get the directory for the app's private pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "ProgTransitConfigFiles");
if (!file.mkdirs()) {
mTextMessage.append("\nDirectory not created");
} else {
mTextMessage.append("\nDone");
}
return file;
}
public void ListFiles (View v) {
if (isExternalStorageWritable()) {
File file = PrepareDirectoryForStoringConfigFiles();
if (file.exists())
mTextMessage.append("\nDone");
else
mTextMessage.append("\nOpssss...");
} else
mTextMessage.append("\nNo :( ......");
}
}
| Automatic push
| Android/ProgTransit000/app/src/main/java/com/skgadi/progtransit000/MainActivity.java | Automatic push | <ide><path>ndroid/ProgTransit000/app/src/main/java/com/skgadi/progtransit000/MainActivity.java
<ide> byte RecBuffer[] = new byte[4];
<ide> int MAddress = 0x310000;
<ide> byte Data = 0x00;
<del> int EE_Settings[]={0x7A, 0xFE, 1, 4, 1, 10, 20, 0xF6, 0xFF, 60, 40, 4, 8, 192, 8, 42, 5, 1, 128, 81, 1, 0, 5, 0xC5, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 160, 0, 1, 0, 5, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, 82, 0x20, 0x90, 0x01, 0x00, 3, 0x22, 0x90, 0x00, 0x00, 6, 0x0C, 0x90, 0x00, 0x00, 2, 0x04, 0x90, 0x08, 0x00, 2, 0x14, 0x90, 0x00, 0x00, 21, 0x24, 0x28, 0x00, 0x00, 2, 0x24, 0x10, 0x00, 0x20, 2, 0x24, 0x50, 0x00, 0x00, 1, 0x00, 0x00, 0x14, 0x20, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, };
<add> int EE_Settings[]={0x98, 0xFE, 1, 4, 1, 10, 20, 0xF6, 0xFF, 60, 40, 4, 8, 192, 8, 42, 5, 1, 128, 81, 1, 0, 5, 0xC5, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 160, 0, 1, 0, 5, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, -1, -1, -1, -1, 1, 127, 82, 0x20, 0x90, 0x01, 0x00, 3, 0x22, 0x90, 0x00, 0x00, 6, 0x0C, 0x90, 0x00, 0x00, 2, 0x04, 0x90, 0x08, 0x00, 2, 0x14, 0x90, 0x00, 0x00, 21, 0x24, 0x28, 0x00, 0x00, 2, 0x24, 0x10, 0x00, 0x20, 2, 0x24, 0x50, 0x00, 0x00, 1, 0x00, 0x00, 0x14, 0x20, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, 0, 0x00, 0x00, 0x00, 0x00, };
<ide> for (int i=0; i<5; i++) {
<ide> PrepareEndCommand();
<ide> try { |
|
JavaScript | mit | 4b707dc943849f9262a7138c5f65ef80a165dcce | 0 | zalmoxisus/redux-devtools-extension,zalmoxisus/redux-devtools-extension | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor-filterable';
export default createDevTools(<LogMonitor />);
| src/app/containers/DevTools.js | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor-filtrable';
export default createDevTools(<LogMonitor />);
| Fix a dependency
| src/app/containers/DevTools.js | Fix a dependency | <ide><path>rc/app/containers/DevTools.js
<ide> import React from 'react';
<ide> import { createDevTools } from 'redux-devtools';
<del>import LogMonitor from 'redux-devtools-log-monitor-filtrable';
<add>import LogMonitor from 'redux-devtools-log-monitor-filterable';
<ide>
<ide> export default createDevTools(<LogMonitor />); |
|
Java | apache-2.0 | 27c49dbc929000ac33f71293149f5ac16f99a713 | 0 | TheNightForum/Path-to-Mani,BurntGameProductions/Path-to-Mani,BurntGameProductions/Path-to-Mani,TheNightForum/Path-to-Mani,BurntGameProductions/Path-to-Mani,TheNightForum/Path-to-Mani | /*
* Copyright 2016 BurntGameProductions
*
* 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.pathtomani.entities.maze;
import com.badlogic.gdx.math.Vector2;
import com.pathtomani.common.Const;
import com.pathtomani.common.ManiMath;
import com.pathtomani.game.Faction;
import com.pathtomani.game.ManiGame;
import com.pathtomani.game.ShipConfig;
import com.pathtomani.managers.input.AiPilot;
import com.pathtomani.managers.input.Pilot;
import com.pathtomani.managers.input.StillGuard;
import com.pathtomani.entities.ship.FarShip;
import com.pathtomani.entities.ship.ShipBuilder;
import java.util.ArrayList;
public class MazeBuilder {
public static final float BORDER = 4f;
public static final float TILE_SZ = 3.5f;
private int mySz;
private Vector2 myMazePos;
private float myMazeAngle;
private float myInnerRad;
public void build(ManiGame game, Maze maze) {
myInnerRad = maze.getRadius() - BORDER;
mySz = (int) (myInnerRad * 2 / TILE_SZ);
myMazePos = maze.getPos();
myMazeAngle = ManiMath.rnd(180);
MazeLayout layout = buildMaze(game, maze);
buildEnemies(game, maze, layout);
}
public MazeLayout buildMaze(ManiGame game, Maze maze) {
MazeLayout layout = new MazeLayoutBuilder(mySz).build();
MazeTileObject.Builder builder = new MazeTileObject.Builder();
MazeConfig config = maze.getConfig();
for (int col = 0; col < mySz; col++) {
for (int row = 0; row < mySz; row++) {
boolean ulInner = col > 0 && row > 0 && layout.inners[col][row];
boolean rInner = row > 0 && col < mySz - 1 && layout.inners[col + 1][row];
if (row > 0 && (ulInner || rInner)) {
boolean wall = layout.right[col][row];
boolean inner = ulInner && rInner;
float tileAngle = myMazeAngle - 90;
if (!ulInner) tileAngle += 180;
Vector2 tilePos = cellPos(col, row, TILE_SZ / 2, 0f);
ArrayList<MazeTile> tiles;
if (wall) {
tiles = inner ? config.innerWalls : config.borderWalls;
} else {
tiles = inner ? config.innerPasses : config.borderPasses;
}
MazeTile tile = ManiMath.elemRnd(tiles);
MazeTileObject.MyFar mto = new MazeTileObject.MyFar(tile, tileAngle, new Vector2(tilePos), ManiMath.test(.5f));
game.getObjMan().addFarObjNow(mto);
}
boolean dInner = col > 0 && row < mySz - 1 && layout.inners[col][row + 1];
if (col > 0 && (ulInner || dInner)) {
boolean wall = layout.down[col][row];
boolean inner = ulInner && dInner;
float tileAngle = myMazeAngle;
if (!ulInner) tileAngle += 180;
Vector2 tilePos = cellPos(col, row, 0f, TILE_SZ / 2);
ArrayList<MazeTile> tiles;
if (wall) {
tiles = inner ? config.innerWalls : config.borderWalls;
} else {
tiles = inner ? config.innerPasses : config.borderPasses;
}
MazeTile tile = ManiMath.elemRnd(tiles);
MazeTileObject.MyFar mto = new MazeTileObject.MyFar(tile, tileAngle, new Vector2(tilePos), ManiMath.test(.5f));
game.getObjMan().addFarObjNow(mto);
}
}
}
return layout;
}
private Vector2 cellPos(int col, int row, float xOffset, float yOffset) {
Vector2 res = new Vector2((col - mySz / 2) * TILE_SZ + xOffset, (row - mySz / 2) * TILE_SZ + yOffset);
ManiMath.rotate(res, myMazeAngle);
res.add(myMazePos);
return res;
}
private void buildEnemies(ManiGame game, Maze maze, MazeLayout layout) {
MazeConfig config = maze.getConfig();
float dist = maze.getRadius() - BORDER / 2;
float circleLen = dist * ManiMath.PI * 2;
for (ShipConfig e : config.outerEnemies) {
int count = (int) (e.density * circleLen);
for (int i = 0; i < count; i++) {
Vector2 pos = new Vector2();
ManiMath.fromAl(pos, ManiMath.rnd(180), dist);
pos.add(myMazePos);
buildEnemy(pos, game, e, false);
}
}
boolean[][] occupiedCells = new boolean[mySz][mySz];
occupiedCells[mySz/2][mySz/2] = true;
for (ShipConfig e : config.innerEnemies) {
int count = (int) (e.density * myInnerRad * myInnerRad * ManiMath.PI);
for (int i = 0; i < count; i++) {
Vector2 pos = getFreeCellPos(occupiedCells);
if (pos != null) buildEnemy(pos, game, e, true);
}
}
ShipConfig bossConfig = ManiMath.elemRnd(config.bosses);
Vector2 pos = cellPos(mySz / 2, mySz / 2, 0f, 0f);
buildEnemy(pos, game, bossConfig, true);
}
private Vector2 getFreeCellPos(boolean[][] occupiedCells) {
for (int i = 0; i < 10; i++) {
int col = ManiMath.intRnd(mySz);
int row = ManiMath.intRnd(mySz);
if (occupiedCells[col][row]) continue;
Vector2 pos = cellPos(col, row, 0f, 0f);
if (.8f * myInnerRad < pos.dst(myMazePos)) continue;
occupiedCells[col][row] = true;
return pos;
}
return null;
}
private void buildEnemy(Vector2 pos, ManiGame game, ShipConfig e, boolean inner) {
float angle = ManiMath.rnd(180);
ShipBuilder sb = game.getShipBuilder();
float viewDist = Const.AI_DET_DIST;
if (inner) viewDist = TILE_SZ * 1.25f;
Pilot pilot = new AiPilot(new StillGuard(pos, game, e), false, Faction.EHAR, true, null, viewDist);
int money = e.money;
FarShip s = sb.buildNewFar(game, pos, new Vector2(), angle, 0, pilot, e.items, e.hull, null, false, money, null, true);
game.getObjMan().addFarObjNow(s);
}
}
| main/src/com/pathtomani/entities/maze/MazeBuilder.java | /*
* Copyright 2016 BurntGameProductions
*
* 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.pathtomani.entities.maze;
import com.badlogic.gdx.math.Vector2;
import com.pathtomani.common.Const;
import com.pathtomani.common.ManiMath;
import com.pathtomani.game.Faction;
import com.pathtomani.game.ManiGame;
import com.pathtomani.game.ShipConfig;
import com.pathtomani.game.input.AiPilot;
import com.pathtomani.game.input.Pilot;
import com.pathtomani.game.input.StillGuard;
import com.pathtomani.entities.ship.FarShip;
import com.pathtomani.entities.ship.ShipBuilder;
import java.util.ArrayList;
public class MazeBuilder {
public static final float BORDER = 4f;
public static final float TILE_SZ = 3.5f;
private int mySz;
private Vector2 myMazePos;
private float myMazeAngle;
private float myInnerRad;
public void build(ManiGame game, Maze maze) {
myInnerRad = maze.getRadius() - BORDER;
mySz = (int) (myInnerRad * 2 / TILE_SZ);
myMazePos = maze.getPos();
myMazeAngle = ManiMath.rnd(180);
MazeLayout layout = buildMaze(game, maze);
buildEnemies(game, maze, layout);
}
public MazeLayout buildMaze(ManiGame game, Maze maze) {
MazeLayout layout = new MazeLayoutBuilder(mySz).build();
MazeTileObject.Builder builder = new MazeTileObject.Builder();
MazeConfig config = maze.getConfig();
for (int col = 0; col < mySz; col++) {
for (int row = 0; row < mySz; row++) {
boolean ulInner = col > 0 && row > 0 && layout.inners[col][row];
boolean rInner = row > 0 && col < mySz - 1 && layout.inners[col + 1][row];
if (row > 0 && (ulInner || rInner)) {
boolean wall = layout.right[col][row];
boolean inner = ulInner && rInner;
float tileAngle = myMazeAngle - 90;
if (!ulInner) tileAngle += 180;
Vector2 tilePos = cellPos(col, row, TILE_SZ / 2, 0f);
ArrayList<MazeTile> tiles;
if (wall) {
tiles = inner ? config.innerWalls : config.borderWalls;
} else {
tiles = inner ? config.innerPasses : config.borderPasses;
}
MazeTile tile = ManiMath.elemRnd(tiles);
MazeTileObject.MyFar mto = new MazeTileObject.MyFar(tile, tileAngle, new Vector2(tilePos), ManiMath.test(.5f));
game.getObjMan().addFarObjNow(mto);
}
boolean dInner = col > 0 && row < mySz - 1 && layout.inners[col][row + 1];
if (col > 0 && (ulInner || dInner)) {
boolean wall = layout.down[col][row];
boolean inner = ulInner && dInner;
float tileAngle = myMazeAngle;
if (!ulInner) tileAngle += 180;
Vector2 tilePos = cellPos(col, row, 0f, TILE_SZ / 2);
ArrayList<MazeTile> tiles;
if (wall) {
tiles = inner ? config.innerWalls : config.borderWalls;
} else {
tiles = inner ? config.innerPasses : config.borderPasses;
}
MazeTile tile = ManiMath.elemRnd(tiles);
MazeTileObject.MyFar mto = new MazeTileObject.MyFar(tile, tileAngle, new Vector2(tilePos), ManiMath.test(.5f));
game.getObjMan().addFarObjNow(mto);
}
}
}
return layout;
}
private Vector2 cellPos(int col, int row, float xOffset, float yOffset) {
Vector2 res = new Vector2((col - mySz / 2) * TILE_SZ + xOffset, (row - mySz / 2) * TILE_SZ + yOffset);
ManiMath.rotate(res, myMazeAngle);
res.add(myMazePos);
return res;
}
private void buildEnemies(ManiGame game, Maze maze, MazeLayout layout) {
MazeConfig config = maze.getConfig();
float dist = maze.getRadius() - BORDER / 2;
float circleLen = dist * ManiMath.PI * 2;
for (ShipConfig e : config.outerEnemies) {
int count = (int) (e.density * circleLen);
for (int i = 0; i < count; i++) {
Vector2 pos = new Vector2();
ManiMath.fromAl(pos, ManiMath.rnd(180), dist);
pos.add(myMazePos);
buildEnemy(pos, game, e, false);
}
}
boolean[][] occupiedCells = new boolean[mySz][mySz];
occupiedCells[mySz/2][mySz/2] = true;
for (ShipConfig e : config.innerEnemies) {
int count = (int) (e.density * myInnerRad * myInnerRad * ManiMath.PI);
for (int i = 0; i < count; i++) {
Vector2 pos = getFreeCellPos(occupiedCells);
if (pos != null) buildEnemy(pos, game, e, true);
}
}
ShipConfig bossConfig = ManiMath.elemRnd(config.bosses);
Vector2 pos = cellPos(mySz / 2, mySz / 2, 0f, 0f);
buildEnemy(pos, game, bossConfig, true);
}
private Vector2 getFreeCellPos(boolean[][] occupiedCells) {
for (int i = 0; i < 10; i++) {
int col = ManiMath.intRnd(mySz);
int row = ManiMath.intRnd(mySz);
if (occupiedCells[col][row]) continue;
Vector2 pos = cellPos(col, row, 0f, 0f);
if (.8f * myInnerRad < pos.dst(myMazePos)) continue;
occupiedCells[col][row] = true;
return pos;
}
return null;
}
private void buildEnemy(Vector2 pos, ManiGame game, ShipConfig e, boolean inner) {
float angle = ManiMath.rnd(180);
ShipBuilder sb = game.getShipBuilder();
float viewDist = Const.AI_DET_DIST;
if (inner) viewDist = TILE_SZ * 1.25f;
Pilot pilot = new AiPilot(new StillGuard(pos, game, e), false, Faction.EHAR, true, null, viewDist);
int money = e.money;
FarShip s = sb.buildNewFar(game, pos, new Vector2(), angle, 0, pilot, e.items, e.hull, null, false, money, null, true);
game.getObjMan().addFarObjNow(s);
}
}
| Moving files to Managers.
| main/src/com/pathtomani/entities/maze/MazeBuilder.java | Moving files to Managers. | <ide><path>ain/src/com/pathtomani/entities/maze/MazeBuilder.java
<ide> import com.pathtomani.game.Faction;
<ide> import com.pathtomani.game.ManiGame;
<ide> import com.pathtomani.game.ShipConfig;
<del>import com.pathtomani.game.input.AiPilot;
<del>import com.pathtomani.game.input.Pilot;
<del>import com.pathtomani.game.input.StillGuard;
<add>import com.pathtomani.managers.input.AiPilot;
<add>import com.pathtomani.managers.input.Pilot;
<add>import com.pathtomani.managers.input.StillGuard;
<ide> import com.pathtomani.entities.ship.FarShip;
<ide> import com.pathtomani.entities.ship.ShipBuilder;
<ide> |
|
JavaScript | mit | 0ecca6ae9897d46f3d068a85acbab102c24aaaeb | 0 | zuzak/dbot,zuzak/dbot | var fs = require('fs');
var timers = require('./timer');
var jsbot = require('./jsbot');
require('./snippets');
var DBot = function(timers) {
// Load external files
this.config = JSON.parse(fs.readFileSync('config.json', 'utf-8'));
this.db = null;
var rawDB;
try {
var rawDB = fs.readFileSync('db.json', 'utf-8');
} catch (e) {
this.db = {}; // If no db file, make empty one
}
if(!this.db) { // If it wasn't empty
this.db = JSON.parse(rawDB);
}
// Repair any deficiencies in the DB; if this is a new DB, that's everything
if(!this.db.hasOwnProperty("bans")) {
this.db.bans = {};
}
if(!this.db.bans.hasOwnProperty("*")) {
this.db.bans["*"] = [];
}
if(!this.db.hasOwnProperty("quoteArrs")) {
this.db.quoteArrs = {};
}
if(!this.db.hasOwnProperty("kicks")) {
this.db.kicks = {};
}
if(!this.db.hasOwnProperty("kickers")) {
this.db.kickers = {};
}
if(!this.db.hasOwnProperty("modehate")) {
this.db.modehate = [];
}
if(!this.db.hasOwnProperty("locks")) {
this.db.locks = [];
}
if(!this.db.hasOwnProperty("ignores")) {
this.db.locks = {};
}
// Load the strings file
this.strings = JSON.parse(fs.readFileSync('strings.json', 'utf-8'));
// Populate bot properties with config data
this.name = this.config.name || 'dbox';
this.admin = this.config.admin || [ 'reality' ];
this.password = this.config.password || 'lolturtles';
this.nickserv = this.config.nickserv || 'zippy';
this.server = this.config.server || 'elara.ivixor.net';
this.port = this.config.port || 6667;
this.webPort = this.config.webPort || 443;
this.moduleNames = this.config.modules || [ 'command', 'js', 'admin', 'kick', 'modehate', 'quotes', 'puns', 'spelling', 'web', 'youare', 'autoshorten' ];
this.language = this.config.language || 'english';
this.sessionData = {};
this.timers = timers.create();
this.instance = jsbot.createJSBot(this.name, this.server, this.port, this, function() {
if(this.config.hasOwnProperty('channels')) {
this.config.channels.each(function(channel) {
this.instance.join(channel);
}.bind(this));
}
}.bind(this), this.nickserv, this.password);
// Load the modules and connect to the server
this.reloadModules();
this.instance.connect();
};
// Say something in a channel
DBot.prototype.say = function(channel, data) {
this.instance.say(channel, data);
};
DBot.prototype.act = function(channel, data) {
this.instance.send('PRIVMSG', channel, ':\001ACTION ' + data + '\001');
}
// Save the database file
DBot.prototype.save = function() {
fs.writeFile('db.json', JSON.stringify(this.db, null, ' '));
};
// Hot-reload module files.
DBot.prototype.reloadModules = function() {
if(this.modules) { // Run 'onDestroy' code for each module if it exists.
this.modules.each(function(module) {
if(module.onDestroy) {
module.onDestroy();
}
});
}
this.rawModules = [];
this.modules = [];
this.commands = {};
this.commandMap = {}; // Map of which commands belong to which modules
this.timers.clearTimers();
this.save();
// Enforce having command. it can still be reloaded, but dbot _will not_
// function without it, so not having it should be impossible
if(!this.moduleNames.include("command")) {
this.moduleNames.push("command");
}
// Reload Javascript snippets
var path = require.resolve('./snippets');
delete require.cache[path];
require('./snippets');
this.instance.removeListeners();
this.moduleNames.each(function(name) {
var cacheKey = require.resolve('./modules/' + name);
delete require.cache[cacheKey];
try {
var rawModule = require('./modules/' + name);
var module = rawModule.fetch(this);
this.rawModules.push(rawModule);
if(module.listener) {
this.instance.addListener(module.on, module.listener);
}
if(module.onLoad) {
var newCommands = module.onLoad();
for(key in newCommands) {
if(newCommands.hasOwnProperty(key) && Object.prototype.isFunction(newCommands[key])) {
this.commands[key] = newCommands[key];
}
}
}
this.modules.push(module);
} catch(err) {
console.log(this.strings[this.language].module_load_error.format({'moduleName': name}));
}
}.bind(this));
};
DBot.prototype.cleanNick = function(key) {
key = key.toLowerCase();
while(key.endsWith("_")) {
if(this.db.quoteArrs.hasOwnProperty(key)) {
return key;
}
key = key.substring(0, key.length-1);
}
return key;
}
new DBot(timers);
| run.js | var fs = require('fs');
var timers = require('./timer');
var jsbot = require('./jsbot');
require('./snippets');
var DBot = function(timers) {
// Load external files
this.config = JSON.parse(fs.readFileSync('config.json', 'utf-8'));
this.db = null;
var rawDB;
try {
var rawDB = fs.readFileSync('db.json', 'utf-8');
} catch (e) {
this.db = {}; // If no db file, make empty one
}
if(!this.db) { // If it wasn't empty
this.db = JSON.parse(rawDB);
}
// Repair any deficiencies in the DB; if this is a new DB, that's everything
if(!this.db.hasOwnProperty("bans")) {
this.db.bans = {};
}
if(!this.db.bans.hasOwnProperty("*")) {
this.db.bans["*"] = [];
}
if(!this.db.hasOwnProperty("quoteArrs")) {
this.db.quoteArrs = {};
}
if(!this.db.hasOwnProperty("kicks")) {
this.db.kicks = {};
}
if(!this.db.hasOwnProperty("kickers")) {
this.db.kickers = {};
}
if(!this.db.hasOwnProperty("modehate")) {
this.db.modehate = [];
}
if(!this.db.hasOwnProperty("locks")) {
this.db.locks = [];
}
// Load the strings file
this.strings = JSON.parse(fs.readFileSync('strings.json', 'utf-8'));
// Populate bot properties with config data
this.name = this.config.name || 'dbox';
this.admin = this.config.admin || [ 'reality' ];
this.password = this.config.password || 'lolturtles';
this.nickserv = this.config.nickserv || 'zippy';
this.server = this.config.server || 'elara.ivixor.net';
this.port = this.config.port || 6667;
this.webPort = this.config.webPort || 443;
this.moduleNames = this.config.modules || [ 'command', 'js', 'admin', 'kick', 'modehate', 'quotes', 'puns', 'spelling', 'web', 'youare', 'autoshorten' ];
this.language = this.config.language || 'english';
this.sessionData = {};
this.timers = timers.create();
this.instance = jsbot.createJSBot(this.name, this.server, this.port, this, function() {
if(this.config.hasOwnProperty('channels')) {
this.config.channels.each(function(channel) {
this.instance.join(channel);
}.bind(this));
}
}.bind(this), this.nickserv, this.password);
// Load the modules and connect to the server
this.reloadModules();
this.instance.connect();
};
// Say something in a channel
DBot.prototype.say = function(channel, data) {
this.instance.say(channel, data);
};
DBot.prototype.act = function(channel, data) {
this.instance.send('PRIVMSG', channel, ':\001ACTION ' + data + '\001');
}
// Save the database file
DBot.prototype.save = function() {
fs.writeFile('db.json', JSON.stringify(this.db, null, ' '));
};
// Hot-reload module files.
DBot.prototype.reloadModules = function() {
if(this.modules) { // Run 'onDestroy' code for each module if it exists.
this.modules.each(function(module) {
if(module.onDestroy) {
module.onDestroy();
}
});
}
this.rawModules = [];
this.modules = [];
this.commands = {};
this.timers.clearTimers();
this.save();
// Enforce having command. it can still be reloaded, but dbot _will not_
// function without it, so not having it should be impossible
if(!this.moduleNames.include("command")) {
this.moduleNames.push("command");
}
// Reload Javascript snippets
var path = require.resolve('./snippets');
delete require.cache[path];
require('./snippets');
this.moduleNames.each(function(name) {
var cacheKey = require.resolve('./modules/' + name);
delete require.cache[cacheKey];
try {
this.rawModules.push(require('./modules/' + name));
} catch(err) {
console.log(this.strings[this.language].module_load_error.format({'moduleName': name}));
}
}.bind(this));
this.instance.removeListeners();
this.modules = this.rawModules.collect(function(rawModule) {
var module = rawModule.fetch(this);
if(module.listener) {
this.instance.addListener(module.on, module.listener);
}
if(module.onLoad) {
var newCommands = module.onLoad();
for(key in newCommands) {
if(newCommands.hasOwnProperty(key) && Object.prototype.isFunction(newCommands[key])) {
this.commands[key] = newCommands[key];
}
}
}
return module;
}.bind(this));
};
DBot.prototype.cleanNick = function(key) {
key = key.toLowerCase();
while(key.endsWith("_")) {
if(this.db.quoteArrs.hasOwnProperty(key)) {
return key;
}
key = key.substring(0, key.length-1);
}
return key;
}
new DBot(timers);
| change module loading so there's only one loop through the moduels
| run.js | change module loading so there's only one loop through the moduels | <ide><path>un.js
<ide> }
<ide> if(!this.db.hasOwnProperty("locks")) {
<ide> this.db.locks = [];
<add> }
<add> if(!this.db.hasOwnProperty("ignores")) {
<add> this.db.locks = {};
<ide> }
<ide>
<ide> // Load the strings file
<ide> this.rawModules = [];
<ide> this.modules = [];
<ide> this.commands = {};
<add> this.commandMap = {}; // Map of which commands belong to which modules
<ide> this.timers.clearTimers();
<ide> this.save();
<ide>
<ide> delete require.cache[path];
<ide> require('./snippets');
<ide>
<add> this.instance.removeListeners();
<add>
<ide> this.moduleNames.each(function(name) {
<ide> var cacheKey = require.resolve('./modules/' + name);
<ide> delete require.cache[cacheKey];
<ide> try {
<del> this.rawModules.push(require('./modules/' + name));
<add> var rawModule = require('./modules/' + name);
<add> var module = rawModule.fetch(this);
<add> this.rawModules.push(rawModule);
<add>
<add> if(module.listener) {
<add> this.instance.addListener(module.on, module.listener);
<add> }
<add>
<add> if(module.onLoad) {
<add> var newCommands = module.onLoad();
<add> for(key in newCommands) {
<add> if(newCommands.hasOwnProperty(key) && Object.prototype.isFunction(newCommands[key])) {
<add> this.commands[key] = newCommands[key];
<add> }
<add> }
<add> }
<add>
<add> this.modules.push(module);
<ide> } catch(err) {
<ide> console.log(this.strings[this.language].module_load_error.format({'moduleName': name}));
<ide> }
<del> }.bind(this));
<del>
<del> this.instance.removeListeners();
<del>
<del> this.modules = this.rawModules.collect(function(rawModule) {
<del> var module = rawModule.fetch(this);
<del>
<del> if(module.listener) {
<del> this.instance.addListener(module.on, module.listener);
<del> }
<del>
<del> if(module.onLoad) {
<del> var newCommands = module.onLoad();
<del> for(key in newCommands) {
<del> if(newCommands.hasOwnProperty(key) && Object.prototype.isFunction(newCommands[key])) {
<del> this.commands[key] = newCommands[key];
<del> }
<del> }
<del> }
<del>
<del> return module;
<ide> }.bind(this));
<ide> };
<ide> |
|
Java | apache-2.0 | fd45da1adcfc0ea215a82ad6355bef98bcd4f039 | 0 | inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service | package org.slc.sli.ingestion.transformation;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.slc.sli.ingestion.BatchJobStageType;
import org.slc.sli.ingestion.Job;
import org.slc.sli.ingestion.NeutralRecord;
import org.slc.sli.ingestion.WorkNote;
import org.slc.sli.ingestion.dal.NeutralRecordMongoAccess;
import org.slc.sli.ingestion.model.da.BatchJobDAO;
import org.slc.sli.ingestion.validation.DatabaseLoggingErrorReport;
import org.slc.sli.ingestion.validation.ErrorReport;
/**
* Base TransformationStrategy.
*
* @author dduran
* @author shalka
*/
public abstract class AbstractTransformationStrategy implements TransformationStrategy {
protected static final String BATCH_JOB_ID_KEY = "batchJobId";
protected static final String TYPE_KEY = "type";
private String batchJobId;
private Job job;
private WorkNote workNote;
@Autowired
private NeutralRecordMongoAccess neutralRecordMongoAccess;
@Autowired
private BatchJobDAO batchJobDAO;
@Override
public void perform(Job job) {
this.setJob(job);
this.setBatchJobId(job.getId());
this.performTransformation();
}
@Override
public void perform(Job job, WorkNote workNote) {
this.setJob(job);
this.setBatchJobId(job.getId());
this.setWorkNote(workNote);
this.performTransformation();
}
protected abstract void performTransformation();
/**
* @return the neutralRecordMongoAccess
*/
public NeutralRecordMongoAccess getNeutralRecordMongoAccess() {
return neutralRecordMongoAccess;
}
/**
* @param neutralRecordMongoAccess
* the neutralRecordMongoAccess to set
*/
public void setNeutralRecordMongoAccess(NeutralRecordMongoAccess neutralRecordMongoAccess) {
this.neutralRecordMongoAccess = neutralRecordMongoAccess;
}
public String getBatchJobId() {
return batchJobId;
}
public ErrorReport getErrorReport(String fileName) {
return new DatabaseLoggingErrorReport(this.batchJobId, BatchJobStageType.TRANSFORMATION_PROCESSOR, fileName,
this.batchJobDAO);
}
public void setBatchJobId(String batchJobId) {
this.batchJobId = batchJobId;
}
public Job getJob() {
return job;
}
public void setJob(Job job) {
this.job = job;
}
/**
* Gets the Work Note corresponding to this job.
* @return Work Note containing information about collection and range to operate on.
*/
public WorkNote getWorkNote() {
return workNote;
}
/**
* Sets the Work Note for this job.
* @param workNote Work Note containing information about collection and range to operate on.
*/
public void setWorkNote(WorkNote workNote) {
this.workNote = workNote;
}
/**
* Returns collection entities found in staging ingestion database. If a work note was not provided for
* the job, then all entities in the collection will be returned.
*
* @param collectionName name of collection to be queried for.
*/
public Map<Object, NeutralRecord> getCollectionFromDb(String collectionName) {
Query query = new Query();
Iterable<NeutralRecord> data;
if (getWorkNote() != null) {
WorkNote note = getWorkNote();
Criteria limiter = Criteria.where("locationInSourceFile").gte(note.getRangeMinimum());
Criteria maximum = Criteria.where("locationInSourceFile").lte(note.getRangeMaximum());
query.addCriteria(limiter);
query.addCriteria(maximum);
}
data = getNeutralRecordMongoAccess().getRecordRepository().findByQueryForJob(collectionName, query, getJob().getId());
Map<Object, NeutralRecord> collection = new HashMap<Object, NeutralRecord>();
NeutralRecord tempNr;
Iterator<NeutralRecord> neutralRecordIterator = data.iterator();
while (neutralRecordIterator.hasNext()) {
tempNr = neutralRecordIterator.next();
collection.put(tempNr.getRecordId(), tempNr);
}
return collection;
}
}
| sli/ingestion/ingestion-core/src/main/java/org/slc/sli/ingestion/transformation/AbstractTransformationStrategy.java | package org.slc.sli.ingestion.transformation;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.slc.sli.ingestion.BatchJobStageType;
import org.slc.sli.ingestion.Job;
import org.slc.sli.ingestion.NeutralRecord;
import org.slc.sli.ingestion.WorkNote;
import org.slc.sli.ingestion.dal.NeutralRecordMongoAccess;
import org.slc.sli.ingestion.model.da.BatchJobDAO;
import org.slc.sli.ingestion.validation.DatabaseLoggingErrorReport;
import org.slc.sli.ingestion.validation.ErrorReport;
/**
* Base TransformationStrategy.
*
* @author dduran
* @author shalka
*/
public abstract class AbstractTransformationStrategy implements TransformationStrategy {
protected static final String BATCH_JOB_ID_KEY = "batchJobId";
protected static final String TYPE_KEY = "type";
private String batchJobId;
private Job job;
private WorkNote workNote;
@Autowired
private NeutralRecordMongoAccess neutralRecordMongoAccess;
@Autowired
private BatchJobDAO batchJobDAO;
@Override
public void perform(Job job) {
this.setJob(job);
this.setBatchJobId(job.getId());
this.performTransformation();
}
@Override
public void perform(Job job, WorkNote workNote) {
this.setJob(job);
this.setBatchJobId(job.getId());
this.setWorkNote(workNote);
this.performTransformation();
}
protected abstract void performTransformation();
/**
* @return the neutralRecordMongoAccess
*/
public NeutralRecordMongoAccess getNeutralRecordMongoAccess() {
return neutralRecordMongoAccess;
}
/**
* @param neutralRecordMongoAccess
* the neutralRecordMongoAccess to set
*/
public void setNeutralRecordMongoAccess(NeutralRecordMongoAccess neutralRecordMongoAccess) {
this.neutralRecordMongoAccess = neutralRecordMongoAccess;
}
public String getBatchJobId() {
return batchJobId;
}
public ErrorReport getErrorReport(String fileName) {
return new DatabaseLoggingErrorReport(this.batchJobId, BatchJobStageType.TRANSFORMATION_PROCESSOR, fileName,
this.batchJobDAO);
}
public void setBatchJobId(String batchJobId) {
this.batchJobId = batchJobId;
}
public Job getJob() {
return job;
}
public void setJob(Job job) {
this.job = job;
}
/**
* Gets the Work Note corresponding to this job.
* @return Work Note containing information about collection and range to operate on.
*/
public WorkNote getWorkNote() {
return workNote;
}
/**
* Sets the Work Note for this job.
* @param workNote Work Note containing information about collection and range to operate on.
*/
public void setWorkNote(WorkNote workNote) {
this.workNote = workNote;
}
/**
* Returns collection entities found in staging ingestion database. If a work note was not provided for
* the job, then all entities in the collection will be returned.
*
* @param collectionName name of collection to be queried for.
*/
public Map<Object, NeutralRecord> getCollectionFromDb(String collectionName) {
Query query = new Query();
Iterable<NeutralRecord> data;
int max = 0;
int skip = 0;
if (getWorkNote() != null) {
WorkNote note = getWorkNote();
max = (note.getRangeMaximum() - note.getRangeMinimum() + 1);
skip = note.getRangeMinimum();
Criteria limiter = Criteria.where("locationInSourceFile").gte(note.getRangeMinimum());
Criteria maximum = Criteria.where("locationInSourceFile").lte(note.getRangeMaximum());
query.addCriteria(limiter);
query.addCriteria(maximum);
}
data = getNeutralRecordMongoAccess().getRecordRepository().findByQueryForJob(collectionName, query, getJob().getId());
//data = getNeutralRecordMongoAccess().getRecordRepository().findByQueryForJob(collectionName, query, getJob().getId(), skip, max);
Map<Object, NeutralRecord> collection = new HashMap<Object, NeutralRecord>();
NeutralRecord tempNr;
Iterator<NeutralRecord> neutralRecordIterator = data.iterator();
while (neutralRecordIterator.hasNext()) {
tempNr = neutralRecordIterator.next();
collection.put(tempNr.getRecordId(), tempNr);
}
return collection;
}
}
| clean up
| sli/ingestion/ingestion-core/src/main/java/org/slc/sli/ingestion/transformation/AbstractTransformationStrategy.java | clean up | <ide><path>li/ingestion/ingestion-core/src/main/java/org/slc/sli/ingestion/transformation/AbstractTransformationStrategy.java
<ide> Query query = new Query();
<ide>
<ide> Iterable<NeutralRecord> data;
<del> int max = 0;
<del> int skip = 0;
<ide>
<ide> if (getWorkNote() != null) {
<ide> WorkNote note = getWorkNote();
<del> max = (note.getRangeMaximum() - note.getRangeMinimum() + 1);
<del> skip = note.getRangeMinimum();
<ide>
<ide> Criteria limiter = Criteria.where("locationInSourceFile").gte(note.getRangeMinimum());
<ide> Criteria maximum = Criteria.where("locationInSourceFile").lte(note.getRangeMaximum());
<ide> }
<ide>
<ide> data = getNeutralRecordMongoAccess().getRecordRepository().findByQueryForJob(collectionName, query, getJob().getId());
<del>
<del> //data = getNeutralRecordMongoAccess().getRecordRepository().findByQueryForJob(collectionName, query, getJob().getId(), skip, max);
<ide>
<ide> Map<Object, NeutralRecord> collection = new HashMap<Object, NeutralRecord>();
<ide> NeutralRecord tempNr; |
|
Java | apache-2.0 | bab8e5da0e7efbe054991586e2375287fc4dd281 | 0 | Haufe-Lexware/gocd-plugins,Haufe-Lexware/gocd-plugins,Haufe-Lexware/gocd-plugins | package com.tw.go.task.fetchanyartifact;
import com.thoughtworks.go.plugin.api.task.JobConsoleLogger;
import com.thoughtworks.go.plugin.api.logging.Logger;
import com.tw.go.plugin.common.*;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Map;
import static com.tw.go.plugin.common.GoApiConstants.*;
import static com.tw.go.task.fetchanyartifact.FetchAnyArtifactTask.*;
/**
* Created by thomassc on 19.05.16.
*/
public class FetchAnyArtifactTaskExecutor extends TaskExecutor {
private final Logger logger = Logger.getLoggerFor(FetchAnyArtifactTaskExecutor.class);
public FetchAnyArtifactTaskExecutor(JobConsoleLogger console, Context context, Map config) {
super(console, context, config);
}
@Override
public Result execute() throws Exception {
try {
return runCommand();
} catch (Exception e) {
logException(logger,e);
return new Result(false, getPluginLogPrefix() + e.getMessage(), e);
}
}
public Result runCommand() throws Exception {
if (configVars.isEmpty(ENVVAR_NAME_GO_BUILD_USER) ||
configVars.isEmpty(ENVVAR_NAME_GO_BUILD_USER_PASSWORD)) {
throw new Exception("You must set environment variables '"
+ ENVVAR_NAME_GO_BUILD_USER
+ "' and '"
+ ENVVAR_NAME_GO_BUILD_USER_PASSWORD + "'");
}
//FIXME: refactor to use Urlbuilder instead of string concat (version 16 broke implementation because the base url removed trailing /)
String url = configVars.getValue(ENVVAR_NAME_GO_SERVER_URL) + "/";
GoApiClient apiClient = new GoApiClient(url);
apiClient.setBasicAuthentication(
configVars.getValue(ENVVAR_NAME_GO_BUILD_USER),
configVars.getValue(ENVVAR_NAME_GO_BUILD_USER_PASSWORD));
String artifact = configVars.getValue(FAA_ARTIFACT_SOURCE);
if (!configVars.isChecked(FAA_ARTIFACT_IS_FILE)) {
artifact += ".zip";
}
Path absoluteWokingDir = Paths.get(AbstractCommand.getAbsoluteWorkingDir()).normalize().toAbsolutePath();
Path targetDir = Paths.get(absoluteWokingDir.toString(), configVars.getValue(FAA_ARTIFACT_DESTINATION)).normalize().toAbsolutePath();
if (!targetDir.startsWith(absoluteWokingDir)) {
throw new Exception("Trying to escape working directory");
}
if (!extractArtifactFromPreviousRun(apiClient, artifact, targetDir.toString())) {
console.printLine("No successful pipeline run found (with a valid artifact to retrieve)");
} else {
console.printLine("Successful pipeline run found (with a valid artifact to retrieve)");
}
return new Result(true, "Finished");
}
public boolean extractArtifactFromPreviousRun(GoApiClient apiClient, String artifact, String targetDirectory) throws IOException {
String pipelineName = configVars.getValue(FAA_PIPELINE_NAME);
if (pipelineName.isEmpty()) {
pipelineName = configVars.getValue(ENVVAR_NAME_GO_PIPELINE_NAME);
}
String pipelineStage = configVars.getValue(FAA_STAGE_NAME);
if (pipelineStage.isEmpty()) {
pipelineStage = configVars.getValue(ENVVAR_NAME_GO_STAGE_NAME);
}
String pipelineJob = configVars.getValue(FAA_JOB_NAME);
if (pipelineJob.isEmpty()) {
pipelineJob = configVars.getValue(ENVVAR_NAME_GO_JOB_NAME);
}
console.printLine(String.format("Searching for pipeline run '%s/%s/%s/%s'",pipelineName,pipelineStage,pipelineJob,artifact));
for (int offset = 0; ; ) {
Map history = apiClient.getPipelineHistory(pipelineName, offset);
ArrayList pipelines = Selector.select(history, "pipelines");
int size = pipelines.size();
if (size == 0) {
return false;
}
for (int pidx = 0; pidx < size; pidx++) {
Map pipeline = (Map) pipelines.get(pidx);
Integer pipelineCounter = Selector.select(pipeline, "counter", 0);
ArrayList stages = Selector.select(pipeline, "stages");
for (int sidx = 0; sidx < stages.size(); sidx++) {
Map stage = (Map) stages.get(sidx);
String stageName = Selector.select(stage, "name");
Integer stageCounter = Integer.parseInt(Selector.select(stage, "counter", "0"));
if ("passed".equalsIgnoreCase(Selector.select(stage, "result", "failed")) &&
configVars.isChecked(FAA_FETCH_IF_FAILED)) {
ArrayList jobs = Selector.select(stage, "jobs");
for (int jidx = 0; jidx < jobs.size(); jidx++) {
Map job = (Map) jobs.get(jidx);
String jobName = Selector.select(job, "name");
if (pipelineStage.equalsIgnoreCase(stageName) &&
pipelineJob.equalsIgnoreCase(jobName)) {
try {
InputStream input = apiClient.getArtifact(
pipelineName,
pipelineCounter.toString(),
stageName,
stageCounter.toString(),
jobName,
artifact);
UnzipUtil.unzip(input, targetDirectory);
return true;
} catch (IOException e) {
// There is no artifact to be found
return false;
}
}
}
}
}
}
offset += size;
}
}
@Override
protected String getPluginLogPrefix() {
return "[FetchAnyArtifact] ";
}
} | fetch-any-artifact-plugin/src/com/tw/go/task/fetchanyartifact/FetchAnyArtifactTaskExecutor.java | package com.tw.go.task.fetchanyartifact;
import com.thoughtworks.go.plugin.api.task.JobConsoleLogger;
import com.thoughtworks.go.plugin.api.logging.Logger;
import com.tw.go.plugin.common.*;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Map;
import static com.tw.go.plugin.common.GoApiConstants.*;
import static com.tw.go.task.fetchanyartifact.FetchAnyArtifactTask.*;
/**
* Created by thomassc on 19.05.16.
*/
public class FetchAnyArtifactTaskExecutor extends TaskExecutor {
private final Logger logger = Logger.getLoggerFor(FetchAnyArtifactTaskExecutor.class);
public FetchAnyArtifactTaskExecutor(JobConsoleLogger console, Context context, Map config) {
super(console, context, config);
}
@Override
public Result execute() throws Exception {
try {
return runCommand();
} catch (Exception e) {
logException(logger,e);
return new Result(false, getPluginLogPrefix() + e.getMessage(), e);
}
}
public Result runCommand() throws Exception {
if (configVars.isEmpty(ENVVAR_NAME_GO_BUILD_USER) ||
configVars.isEmpty(ENVVAR_NAME_GO_BUILD_USER_PASSWORD)) {
throw new Exception("You must set environment variables '"
+ ENVVAR_NAME_GO_BUILD_USER
+ "' and '"
+ ENVVAR_NAME_GO_BUILD_USER_PASSWORD + "'");
}
GoApiClient apiClient = new GoApiClient(
configVars.getValue(ENVVAR_NAME_GO_SERVER_URL));
apiClient.setBasicAuthentication(
configVars.getValue(ENVVAR_NAME_GO_BUILD_USER),
configVars.getValue(ENVVAR_NAME_GO_BUILD_USER_PASSWORD));
String artifact = configVars.getValue(FAA_ARTIFACT_SOURCE);
if (!configVars.isChecked(FAA_ARTIFACT_IS_FILE)) {
artifact += ".zip";
}
Path absoluteWokingDir = Paths.get(AbstractCommand.getAbsoluteWorkingDir()).normalize().toAbsolutePath();
Path targetDir = Paths.get(absoluteWokingDir.toString(), configVars.getValue(FAA_ARTIFACT_DESTINATION)).normalize().toAbsolutePath();
if (!targetDir.startsWith(absoluteWokingDir)) {
throw new Exception("Trying to escape working directory");
}
if (!extractArtifactFromPreviousRun(apiClient, artifact, targetDir.toString())) {
console.printLine("No successful pipeline run found (with a valid artifact to retrieve)");
} else {
console.printLine("Successful pipeline run found (with a valid artifact to retrieve)");
}
return new Result(true, "Finished");
}
public boolean extractArtifactFromPreviousRun(GoApiClient apiClient, String artifact, String targetDirectory) throws IOException {
String pipelineName = configVars.getValue(FAA_PIPELINE_NAME);
if (pipelineName.isEmpty()) {
pipelineName = configVars.getValue(ENVVAR_NAME_GO_PIPELINE_NAME);
}
String pipelineStage = configVars.getValue(FAA_STAGE_NAME);
if (pipelineStage.isEmpty()) {
pipelineStage = configVars.getValue(ENVVAR_NAME_GO_STAGE_NAME);
}
String pipelineJob = configVars.getValue(FAA_JOB_NAME);
if (pipelineJob.isEmpty()) {
pipelineJob = configVars.getValue(ENVVAR_NAME_GO_JOB_NAME);
}
console.printLine(String.format("Searching for pipeline run '%s/%s/%s/%s'",pipelineName,pipelineStage,pipelineJob,artifact));
for (int offset = 0; ; ) {
Map history = apiClient.getPipelineHistory(pipelineName, offset);
ArrayList pipelines = Selector.select(history, "pipelines");
int size = pipelines.size();
if (size == 0) {
return false;
}
for (int pidx = 0; pidx < size; pidx++) {
Map pipeline = (Map) pipelines.get(pidx);
Integer pipelineCounter = Selector.select(pipeline, "counter", 0);
ArrayList stages = Selector.select(pipeline, "stages");
for (int sidx = 0; sidx < stages.size(); sidx++) {
Map stage = (Map) stages.get(sidx);
String stageName = Selector.select(stage, "name");
Integer stageCounter = Integer.parseInt(Selector.select(stage, "counter", "0"));
if ("passed".equalsIgnoreCase(Selector.select(stage, "result", "failed")) &&
configVars.isChecked(FAA_FETCH_IF_FAILED)) {
ArrayList jobs = Selector.select(stage, "jobs");
for (int jidx = 0; jidx < jobs.size(); jidx++) {
Map job = (Map) jobs.get(jidx);
String jobName = Selector.select(job, "name");
if (pipelineStage.equalsIgnoreCase(stageName) &&
pipelineJob.equalsIgnoreCase(jobName)) {
try {
InputStream input = apiClient.getArtifact(
pipelineName,
pipelineCounter.toString(),
stageName,
stageCounter.toString(),
jobName,
artifact);
UnzipUtil.unzip(input, targetDirectory);
return true;
} catch (IOException e) {
// There is no artifact to be found
return false;
}
}
}
}
}
}
offset += size;
}
}
@Override
protected String getPluginLogPrefix() {
return "[FetchAnyArtifact] ";
}
} | Temporary fix. Latest version of go.cd removed trailing / from URL
| fetch-any-artifact-plugin/src/com/tw/go/task/fetchanyartifact/FetchAnyArtifactTaskExecutor.java | Temporary fix. Latest version of go.cd removed trailing / from URL | <ide><path>etch-any-artifact-plugin/src/com/tw/go/task/fetchanyartifact/FetchAnyArtifactTaskExecutor.java
<ide> + ENVVAR_NAME_GO_BUILD_USER_PASSWORD + "'");
<ide> }
<ide>
<del> GoApiClient apiClient = new GoApiClient(
<del> configVars.getValue(ENVVAR_NAME_GO_SERVER_URL));
<add> //FIXME: refactor to use Urlbuilder instead of string concat (version 16 broke implementation because the base url removed trailing /)
<add> String url = configVars.getValue(ENVVAR_NAME_GO_SERVER_URL) + "/";
<add>
<add> GoApiClient apiClient = new GoApiClient(url);
<ide>
<ide> apiClient.setBasicAuthentication(
<ide> configVars.getValue(ENVVAR_NAME_GO_BUILD_USER), |
|
Java | apache-2.0 | 49c69fae57f6ec9c6784d49476171408eba3d4f2 | 0 | realityforge/arez,realityforge/arez,realityforge/arez | package org.realityforge.arez;
import java.lang.reflect.Field;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.realityforge.braincheck.BrainCheckTestUtil;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public abstract class AbstractArezTest
{
@BeforeMethod
protected void beforeTest()
throws Exception
{
BrainCheckTestUtil.resetConfig( false );
ArezTestUtil.resetConfig( false );
ArezTestUtil.enableZones();
getProxyLogger().setLogger( new TestLogger() );
}
@AfterMethod
protected void afterTest()
throws Exception
{
BrainCheckTestUtil.resetConfig( true );
ArezTestUtil.resetConfig( true );
}
@Nonnull
final TestLogger getTestLogger()
{
return (TestLogger) getProxyLogger().getLogger();
}
@Nonnull
private ArezLogger.ProxyLogger getProxyLogger()
{
return (ArezLogger.ProxyLogger) ArezLogger.getLogger();
}
@Nonnull
private Field getField( @Nonnull final Class<?> type, @Nonnull final String fieldName )
throws NoSuchFieldException
{
Class clazz = type;
while ( null != clazz && Object.class != clazz )
{
try
{
final Field field = clazz.getDeclaredField( fieldName );
field.setAccessible( true );
return field;
}
catch ( final Throwable t )
{
clazz = clazz.getSuperclass();
}
}
Assert.fail();
throw new IllegalStateException();
}
@SuppressWarnings( "SameParameterValue" )
final void setField( @Nonnull final Object object, @Nonnull final String fieldName, @Nullable final Object value )
throws NoSuchFieldException, IllegalAccessException
{
getField( object.getClass(), fieldName ).set( object, value );
}
/**
* Typically called to stop observer from being deactivate or stop invariant checks failing.
*/
@SuppressWarnings( "UnusedReturnValue" )
@Nonnull
final Observer ensureDerivationHasObserver( @Nonnull final Observer observer )
{
final Observer randomObserver = newReadOnlyObserver( observer.getContext() );
randomObserver.setState( ObserverState.UP_TO_DATE );
observer.getDerivedValue().addObserver( randomObserver );
randomObserver.getDependencies().add( observer.getDerivedValue() );
return randomObserver;
}
@Nonnull
final Observer newReadWriteObserver( @Nonnull final ArezContext context )
{
return new Observer( context,
ValueUtil.randomString(),
null,
TransactionMode.READ_WRITE,
new TestReaction(),
false );
}
@Nonnull
final Observer newDerivation( @Nonnull final ArezContext context )
{
return new ComputedValue<>( context, ValueUtil.randomString(), () -> "", Objects::equals ).getObserver();
}
@Nonnull
final Observer newObserver( @Nonnull final ArezContext context )
{
return newReadOnlyObserver( context );
}
@Nonnull
final Observer newReadOnlyObserver( @Nonnull final ArezContext context )
{
return new Observer( context,
ValueUtil.randomString(),
null,
TransactionMode.READ_ONLY,
new TestReaction(),
false );
}
@Nonnull
final Observable<?> newObservable( final ArezContext context )
{
return new Observable<>( context, ValueUtil.randomString(), null, null, null );
}
final void setCurrentTransaction( @Nonnull final ArezContext context )
{
setCurrentTransaction( newReadOnlyObserver( context ) );
}
final void setCurrentTransaction( @Nonnull final Observer observer )
{
final ArezContext context = observer.getContext();
Transaction.setTransaction( new Transaction( context,
null,
ValueUtil.randomString(),
observer.getMode(),
observer ) );
}
}
| core/src/test/java/org/realityforge/arez/AbstractArezTest.java | package org.realityforge.arez;
import java.lang.reflect.Field;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.realityforge.braincheck.BrainCheckTestUtil;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public abstract class AbstractArezTest
{
@BeforeMethod
protected void beforeTest()
throws Exception
{
BrainCheckTestUtil.resetConfig( false );
ArezTestUtil.resetConfig( false );
ArezTestUtil.enableZones();
getProxyLogger().setLogger( new TestLogger() );
}
@AfterMethod
protected void afterTest()
throws Exception
{
BrainCheckTestUtil.resetConfig( true );
ArezTestUtil.resetConfig( true );
}
@Nonnull
final TestLogger getTestLogger()
{
return (TestLogger) getProxyLogger().getLogger();
}
@Nonnull
private ArezLogger.ProxyLogger getProxyLogger()
{
return (ArezLogger.ProxyLogger) ArezLogger.getLogger();
}
@Nonnull
private Field getField( @Nonnull final Class<?> type, @Nonnull final String fieldName )
throws NoSuchFieldException
{
Class clazz = type;
while ( null != clazz && Object.class != clazz )
{
try
{
final Field field = clazz.getDeclaredField( fieldName );
field.setAccessible( true );
return field;
}
catch ( final Throwable t )
{
clazz = clazz.getSuperclass();
}
}
Assert.fail();
throw new IllegalStateException();
}
@SuppressWarnings( "SameParameterValue" )
final void setField( @Nonnull final Object object, @Nonnull final String fieldName, @Nullable final Object value )
throws NoSuchFieldException, IllegalAccessException
{
getField( object.getClass(), fieldName ).set( object, value );
}
/**
* Typically called to stop observer from being deactivate or stop invariant checks failing.
*/
@SuppressWarnings( "UnusedReturnValue" )
@Nonnull
final Observer ensureDerivationHasObserver( @Nonnull final Observer observer )
{
final Observer randomObserver = newReadOnlyObserver( observer.getContext() );
randomObserver.setState( ObserverState.UP_TO_DATE );
observer.getDerivedValue().addObserver( randomObserver );
randomObserver.getDependencies().add( observer.getDerivedValue() );
return randomObserver;
}
@Nonnull
final Observer newReadWriteObserver( @Nonnull final ArezContext context )
{
return new Observer( context,
ValueUtil.randomString(), null,
TransactionMode.READ_WRITE,
new TestReaction(),
false );
}
@Nonnull
final Observer newDerivation( @Nonnull final ArezContext context )
{
return new ComputedValue<>( context, ValueUtil.randomString(), () -> "", Objects::equals ).getObserver();
}
@Nonnull
final Observer newObserver( @Nonnull final ArezContext context )
{
return newReadOnlyObserver( context );
}
@Nonnull
final Observer newReadOnlyObserver( @Nonnull final ArezContext context )
{
return new Observer( context,
ValueUtil.randomString(),
null,
TransactionMode.READ_ONLY,
new TestReaction(),
false );
}
@Nonnull
final Observable<?> newObservable( final ArezContext context )
{
return new Observable<>( context, ValueUtil.randomString(), null, null, null );
}
final void setCurrentTransaction( @Nonnull final ArezContext context )
{
setCurrentTransaction( newReadOnlyObserver( context ) );
}
final void setCurrentTransaction( @Nonnull final Observer observer )
{
final ArezContext context = observer.getContext();
Transaction.setTransaction( new Transaction( context,
null,
ValueUtil.randomString(),
observer.getMode(),
observer ) );
}
}
| Whitespace
| core/src/test/java/org/realityforge/arez/AbstractArezTest.java | Whitespace | <ide><path>ore/src/test/java/org/realityforge/arez/AbstractArezTest.java
<ide> final Observer newReadWriteObserver( @Nonnull final ArezContext context )
<ide> {
<ide> return new Observer( context,
<del> ValueUtil.randomString(), null,
<add> ValueUtil.randomString(),
<add> null,
<ide> TransactionMode.READ_WRITE,
<ide> new TestReaction(),
<ide> false ); |
|
Java | apache-2.0 | ec79ac51cc2efec85aa30ff84a7349ad1cb07b44 | 0 | NimbleGen/bioinformatics | package com.roche.bioinformatics.common.verification.runs;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.roche.bioinformatics.common.verification.AutoTestPlanCli;
import com.roche.bioinformatics.common.verification.CliStatusConsole;
import com.roche.sequencing.bioinformatics.common.utils.AlphaNumericStringComparator;
import com.roche.sequencing.bioinformatics.common.utils.ArraysUtil;
import com.roche.sequencing.bioinformatics.common.utils.DateUtil;
import com.roche.sequencing.bioinformatics.common.utils.FileUtil;
import com.roche.sequencing.bioinformatics.common.utils.JVMUtil;
import com.roche.sequencing.bioinformatics.common.utils.LoggingUtil;
import com.roche.sequencing.bioinformatics.common.utils.Md5CheckSumUtil;
import com.roche.sequencing.bioinformatics.common.utils.OSUtil;
import com.roche.sequencing.bioinformatics.common.utils.PdfReportUtil;
import com.roche.sequencing.bioinformatics.common.utils.StringUtil;
import com.roche.sequencing.bioinformatics.common.utils.Version;
import com.roche.sequencing.bioinformatics.common.utils.ZipUtil;
public class TestPlan {
public final static Font SMALL_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 6, Font.NORMAL);
public final static Font REGULAR_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.NORMAL);
public final static Font REGULAR_BOLD_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
public final static Font SMALL_BOLD_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 6, Font.BOLD);
public final static Font SMALL_HEADER_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD);
public final static String CONSOLE_OUTPUT_FILE_NAME = "console.output";
public final static String CONSOLE_ERRORS_FILE_NAME = "console.errors";
private final static String ZIP_EXTENSION = ".zip";
private final File testPlanDirectory;
private final List<TestPlanRun> runs;
private final List<Precondition> preconditions;
public TestPlan(File testPlanDirectory) {
super();
this.runs = new ArrayList<TestPlanRun>();
this.preconditions = new ArrayList<Precondition>();
this.testPlanDirectory = testPlanDirectory;
}
private void addRun(TestPlanRun run) {
if (runs.contains(run)) {
throw new IllegalArgumentException("The TestPlanRun[" + run.getDescription() + "] has already been added to the test plan.");
}
runs.add(run);
}
private void addRuns(List<TestPlanRun> runs) {
for (TestPlanRun run : runs) {
addRun(run);
}
}
private void addPrecondition(Precondition precondition) {
if (preconditions.contains(precondition)) {
throw new IllegalArgumentException("The Precondition[" + precondition + "] has already been added to the test plan.");
}
preconditions.add(precondition);
}
public boolean createTestPlan(File outputTestPlan) {
return createTestPlanReport(null, outputTestPlan, null, null, false, false, null);
}
/**
*
* @param testerName
* @param outputReport
* @return true if test plan ran succesfully with no failures, false otherwise
*/
public boolean createTestPlanReport(File applicationToTest, File testPlanExecutionDirectory, File outputReport, File optionalJvmBinPath, boolean createZip, String startingFolder) {
return createTestPlanReport(applicationToTest, outputReport, testPlanExecutionDirectory, optionalJvmBinPath, true, createZip, startingFolder);
}
/**
*
* @param testerName
* @param outputReport
* @return true if test plan ran successfully with no failures, false otherwise
*/
private boolean createTestPlanReport(File applicationToTest, File outputReport, File testPlanExecutionDirectory, File optionalJvmBinPath, boolean createReport, boolean createZip,
String startingFolder) {
String startTime = DateUtil.getCurrentDateINYYYYMMDDHHMMSSwithColons();
if (createReport && !applicationToTest.exists()) {
throw new IllegalArgumentException("The provided applicationToTest[" + applicationToTest.getAbsolutePath() + "] does not exist.");
}
Document pdfDocument = PdfReportUtil.createDocument(outputReport, "", "", "", "");
boolean wasSuccess = true;
Element titleText = null;
if (createReport) {
titleText = new Phrase("Test Plan Report", REGULAR_BOLD_FONT);
} else {
titleText = new Phrase("Test Plan", REGULAR_BOLD_FONT);
}
Paragraph title = new Paragraph();
title.setAlignment(Element.ALIGN_MIDDLE);
title.add(titleText);
try {
pdfDocument.add(titleText);
} catch (DocumentException e) {
throw new IllegalStateException(e.getMessage(), e);
}
Paragraph runPlanTableParagraph = new Paragraph();
runPlanTableParagraph.add(Chunk.NEWLINE);
PdfPTable table = new PdfPTable(6);
try {
table.setWidths(new float[] { 20f, 15f, 50f, 35f, 40f, 20f });
} catch (DocumentException e1) {
e1.printStackTrace();
}
table.addCell(new PdfPCell(new Phrase("Reference Type and No.", SMALL_HEADER_FONT)));
table.addCell(new PdfPCell(new Phrase("Step Number", SMALL_HEADER_FONT)));
table.addCell(new PdfPCell(new Phrase("Test Step", SMALL_HEADER_FONT)));
table.addCell(new PdfPCell(new Phrase("Acceptance Criteria", SMALL_HEADER_FONT)));
table.addCell(new PdfPCell(new Phrase("Acceptance Results", SMALL_HEADER_FONT)));
table.addCell(new PdfPCell(new Phrase("Results (Pass/Fail)", SMALL_HEADER_FONT)));
int totalChecks = 0;
int passedChecks = 0;
PdfPCell grayCell = new PdfPCell();
grayCell.setBackgroundColor(new BaseColor(Color.LIGHT_GRAY));
PdfPCell emptyWhiteCell = new PdfPCell();
emptyWhiteCell.setBackgroundColor(new BaseColor(Color.WHITE));
PdfPCell naCell = new PdfPCell(new Phrase("NA", SMALL_FONT));
naCell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
for (Precondition precondition : preconditions) {
table.addCell(naCell);
table.addCell(new PdfPCell(new Phrase("Precondition", SMALL_FONT)));
table.addCell(new PdfPCell(new Phrase(precondition.getDescription(), SMALL_FONT)));
table.addCell(grayCell);
table.addCell(grayCell);
table.addCell(grayCell);
}
int runNumber = 1;
List<TestPlanRun> sortedRuns = new ArrayList<TestPlanRun>(runs);
Collections.sort(sortedRuns, new Comparator<TestPlanRun>() {
private AlphaNumericStringComparator windowsComparator = new AlphaNumericStringComparator();
@Override
public int compare(TestPlanRun o1, TestPlanRun o2) {
return windowsComparator.compare(o1.getRunDirectory().getName(), o2.getRunDirectory().getName());
}
});
boolean startingFolderFound = true;
if (startingFolder != null) {
boolean startingFolderExists = false;
runLoop: for (TestPlanRun run : sortedRuns) {
String runFolderName = run.getRunDirectory().getName();
startingFolderExists = runFolderName.equals(startingFolder);
if (startingFolderExists) {
break runLoop;
}
}
if (startingFolderExists) {
startingFolderFound = false;
} else {
throw new IllegalStateException("Could not find startFolder[" + startingFolder + "] in test plan directory[" + testPlanDirectory.getAbsolutePath() + "].");
}
}
for (TestPlanRun run : sortedRuns) {
startingFolderFound = startingFolderFound || run.getRunDirectory().getName().equals(startingFolder);
if (startingFolderFound) {
RunResults runResults = null;
CliStatusConsole.logStatus("");
CliStatusConsole.logStatus("Running step " + runNumber + "(" + run.getRunDirectory().getAbsolutePath() + ") : " + run.getDescription());
if (createReport) {
runResults = executeRun(run, applicationToTest, testPlanExecutionDirectory, runNumber, optionalJvmBinPath);
}
table.addCell(naCell);
table.addCell(new PdfPCell(new Phrase("" + runNumber, SMALL_BOLD_FONT)));
table.addCell(new PdfPCell(new Phrase(run.getDescription() + StringUtil.NEWLINE + StringUtil.NEWLINE + "java -jar "
+ ArraysUtil.toString(run.getArguments().toArray(new String[0]), " "), SMALL_FONT)));
table.addCell(grayCell);
table.addCell(grayCell);
table.addCell(grayCell);
if (run.getChecks().size() == 0) {
throw new IllegalStateException("The provided step[" + run.getDescription() + "] has not checks which make it an invalid test.");
}
int checkNumber = 1;
for (TestPlanRunCheck check : run.getChecks()) {
String referenceTypeAndNumbers = "";
for (String requirement : check.getRequirements()) {
referenceTypeAndNumbers += requirement + StringUtil.NEWLINE;
}
String stepNumber = runNumber + "." + checkNumber;
if (referenceTypeAndNumbers.isEmpty()) {
table.addCell(naCell);
} else {
table.addCell(new PdfPCell(new Phrase(referenceTypeAndNumbers, SMALL_FONT)));
}
table.addCell(new PdfPCell(new Phrase(stepNumber, SMALL_FONT)));
table.addCell(new PdfPCell(new Phrase(check.getDescription(), SMALL_FONT)));
table.addCell(new PdfPCell(new Phrase(check.getAcceptanceCriteria(), SMALL_FONT)));
if (runResults != null) {
TestPlanRunCheckResult checkResult = check.check(runResults);
table.addCell(new PdfPCell(new Phrase(checkResult.getResultDescription(), SMALL_FONT)));
boolean wasCheckSuccess = checkResult.isPassed();
if (wasCheckSuccess) {
table.addCell(new PdfPCell(new Phrase("Pass", SMALL_FONT)));
CliStatusConsole.logStatus(" Check " + stepNumber + " passed : " + check.getDescription());
} else {
table.addCell(new PdfPCell(new Phrase("Fail", SMALL_FONT)));
CliStatusConsole.logStatus(" Check " + stepNumber + " failed : " + check.getDescription());
}
if (wasCheckSuccess) {
passedChecks++;
}
wasSuccess = wasSuccess && wasCheckSuccess;
} else {
table.addCell(emptyWhiteCell);
table.addCell(emptyWhiteCell);
}
checkNumber++;
totalChecks++;
}
}
runNumber++;
}
runPlanTableParagraph.add(table);
try {
pdfDocument.add(runPlanTableParagraph);
} catch (DocumentException e) {
throw new IllegalStateException(e.getMessage(), e);
}
if (createReport) {
String stopTime = DateUtil.getCurrentDateINYYYYMMDDHHMMSSwithColons();
// provide details about the system
Paragraph executionDetailsParagraph = new Paragraph();
executionDetailsParagraph.add(new Phrase("Test Plan Report Execution Details", REGULAR_BOLD_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(new Phrase("Report generated by " + AutoTestPlanCli.APPLICATION_NAME + " " + AutoTestPlanCli.getApplicationVersion(), REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
String userName = System.getProperty("user.name");
if (userName != null && !userName.isEmpty()) {
executionDetailsParagraph.add(new Phrase("Report generation initiated by: " + userName, REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
}
try {
InetAddress address = InetAddress.getLocalHost();
if (address != null) {
executionDetailsParagraph.add(new Phrase("Computer IP Address: " + address.getHostAddress(), REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
String hostName = address.getHostName();
if (hostName != null && !hostName.isEmpty()) {
executionDetailsParagraph.add(new Phrase("Computer Host Name: " + hostName, REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
}
}
} catch (UnknownHostException ex) {
}
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(new Phrase("Application to Test: " + applicationToTest.getAbsolutePath(), REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
try {
String md5Sum = Md5CheckSumUtil.md5sum(applicationToTest);
executionDetailsParagraph.add(new Phrase("Jar File Md5Sum: " + md5Sum, REGULAR_FONT));
executionDetailsParagraph.add(new Phrase("Jar File Location: " + applicationToTest.getAbsolutePath()));
executionDetailsParagraph.add(Chunk.NEWLINE);
} catch (IOException e1) {
}
executionDetailsParagraph.add(new Phrase("Test Plan CheckSum: " + checkSum(), REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(new Phrase("Test Plan Directory: " + testPlanDirectory.getAbsolutePath(), REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(new Phrase("Test Plan Results Directory: " + testPlanExecutionDirectory.getAbsolutePath(), REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(new Phrase("Start Time: " + startTime + " (yyyy:MM:dd HH:mm:ss)", REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(new Phrase("Stop Time: " + stopTime + " (yyyy:MM:dd HH:mm:ss)", REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(new Phrase("Operating System: " + OSUtil.getOsName() + " " + OSUtil.getOsBits() + "-bit", REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
String javaBin = getJavaBinPath(optionalJvmBinPath);
executionDetailsParagraph.add(new Phrase("Java Bin Path: " + javaBin, REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
Version javaVersion = JVMUtil.getJavaVersion(new File(javaBin));
executionDetailsParagraph.add(new Phrase("Java Version: " + javaVersion, REGULAR_FONT));
try {
pdfDocument.add(executionDetailsParagraph);
} catch (DocumentException e) {
throw new IllegalStateException(e.getMessage(), e);
}
} else {
// provide details about the system
Paragraph creationDetailsParagraph = new Paragraph();
creationDetailsParagraph.add(new Phrase("Test Plan Creation Details", REGULAR_BOLD_FONT));
creationDetailsParagraph.add(Chunk.NEWLINE);
creationDetailsParagraph.add(new Phrase("Report generated by " + AutoTestPlanCli.APPLICATION_NAME + " " + AutoTestPlanCli.getApplicationVersion(), REGULAR_FONT));
creationDetailsParagraph.add(Chunk.NEWLINE);
String userName = System.getProperty("user.name");
if (userName != null && !userName.isEmpty()) {
creationDetailsParagraph.add(new Phrase("Report generation initiated by: " + userName, REGULAR_FONT));
creationDetailsParagraph.add(Chunk.NEWLINE);
}
try {
InetAddress address = InetAddress.getLocalHost();
if (address != null) {
creationDetailsParagraph.add(new Phrase("Computer IP Address: " + address.getHostAddress(), REGULAR_FONT));
creationDetailsParagraph.add(Chunk.NEWLINE);
String hostName = address.getHostName();
if (hostName != null && !hostName.isEmpty()) {
creationDetailsParagraph.add(new Phrase("Computer Host Name: " + hostName, REGULAR_FONT));
creationDetailsParagraph.add(Chunk.NEWLINE);
}
}
} catch (UnknownHostException ex) {
}
creationDetailsParagraph.add(new Phrase("Test Plan CheckSum: " + checkSum(), REGULAR_FONT));
creationDetailsParagraph.add(Chunk.NEWLINE);
creationDetailsParagraph.add(new Phrase("Test Plan Directory: " + testPlanDirectory.getAbsolutePath(), REGULAR_FONT));
creationDetailsParagraph.add(Chunk.NEWLINE);
try {
pdfDocument.add(creationDetailsParagraph);
} catch (DocumentException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
pdfDocument.close();
CliStatusConsole.logStatus("");
if (createReport) {
int totalRuns = runNumber - 1;
if (totalRuns > 1) {
CliStatusConsole.logStatus(totalRuns + " total runs.");
} else {
CliStatusConsole.logStatus("1 total run.");
}
CliStatusConsole.logStatus(passedChecks + " out of " + totalChecks + " checks passed.");
if (wasSuccess) {
CliStatusConsole.logStatus("The test plan PASSED.");
} else {
CliStatusConsole.logStatus("The test plan FAILED.");
}
CliStatusConsole.logStatus("");
CliStatusConsole.logStatus("Test Plan Report was written to " + outputReport.getAbsolutePath() + ".");
} else {
CliStatusConsole.logStatus("Test Plan was written to " + outputReport.getAbsolutePath() + ".");
}
CliStatusConsole.logStatus("");
if (createZip) {
String zipFileName = testPlanExecutionDirectory.getName() + "_" + DateUtil.getCurrentDateINYYYYMMDDHHMMSS() + ZIP_EXTENSION;
File outputZipFile = new File(testPlanExecutionDirectory.getParentFile(), zipFileName);
CliStatusConsole.logStatus("Creating results Zip file at [" + outputZipFile + "].");
List<File> directoriesAndFilesToZip = new ArrayList<File>();
directoriesAndFilesToZip.add(testPlanExecutionDirectory);
directoriesAndFilesToZip.add(testPlanDirectory);
directoriesAndFilesToZip.add(outputReport);
directoriesAndFilesToZip.add(applicationToTest);
directoriesAndFilesToZip.add(LoggingUtil.getLogFile());
ZipUtil.zipDirectoriesAndFiles(outputZipFile, directoriesAndFilesToZip);
CliStatusConsole.logStatus("Done creating results Zip file at [" + outputZipFile + "].");
CliStatusConsole.logStatus("");
CliStatusConsole.logStatus("Deleting results directory at [" + testPlanExecutionDirectory + "].");
try {
FileUtil.deleteDirectory(testPlanExecutionDirectory);
CliStatusConsole.logStatus("Done deleting results directory at [" + testPlanExecutionDirectory + "].");
} catch (IOException e) {
CliStatusConsole.logStatus("Unable to deleting the results directory at [" + testPlanExecutionDirectory + "].");
CliStatusConsole.logError(e);
}
}
return wasSuccess;
}
private String getJavaBinPath(File optionalJvmBinPath) {
String javaBin = "";
if (optionalJvmBinPath != null) {
javaBin = optionalJvmBinPath.getAbsolutePath();
} else {
String javaHome = System.getProperty("java.home");
javaBin = javaHome + File.separator + "bin" + File.separator;
}
return javaBin;
}
private RunResults executeRun(TestPlanRun run, File applicationToTest, File testPlanExecutionDirectory, int stepNumber, File optionalJvmBinPath) {
String javaBin = getJavaBinPath(optionalJvmBinPath);
List<String> processBuilderArguments = new ArrayList<String>();
processBuilderArguments.add(new File(javaBin, "java").getAbsolutePath());
processBuilderArguments.add("-jar");
processBuilderArguments.add(applicationToTest.getAbsolutePath());
processBuilderArguments.addAll(run.getArguments());
ProcessBuilder processBuilder = new ProcessBuilder(processBuilderArguments);
// set the java working directory
File outputDirectory = new File(testPlanExecutionDirectory, "run_" + stepNumber);
if (outputDirectory.exists()) {
throw new IllegalStateException("The provided Test Plan Execution Directory[" + testPlanExecutionDirectory.getAbsolutePath()
+ "] already contains results. Please provide an empty Test Plan Execution Directory.");
}
try {
FileUtil.createDirectory(outputDirectory);
} catch (IOException e) {
throw new IllegalStateException("Unable to create the execution directory for run " + stepNumber + " at [" + outputDirectory.getAbsolutePath() + "].", e);
}
processBuilder.directory(outputDirectory);
for (Precondition precondition : preconditions) {
precondition.checkPrecondition(outputDirectory, new File(javaBin));
}
String consoleOutputString = "";
String consoleErrorsString = "";
try {
Process process = processBuilder.start();
StreamListener outputStreamListener = new StreamListener(process.getInputStream());
StreamListener errorStreamListener = new StreamListener(process.getErrorStream());
process.waitFor();
consoleOutputString = outputStreamListener.getString();
consoleErrorsString = errorStreamListener.getString();
} catch (IOException | InterruptedException e) {
throw new IllegalStateException("Unable to execute the provide jar file[" + applicationToTest.getAbsolutePath() + "]. " + e.getMessage());
}
try {
FileUtil.writeStringToFile(new File(outputDirectory, CONSOLE_OUTPUT_FILE_NAME), consoleOutputString);
FileUtil.writeStringToFile(new File(outputDirectory, CONSOLE_ERRORS_FILE_NAME), consoleErrorsString);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
File resultsDirectory = outputDirectory;
if (run.getResultsSubDirectory() != null) {
resultsDirectory = new File(resultsDirectory, run.getResultsSubDirectory());
}
return new RunResults(consoleOutputString, consoleErrorsString, resultsDirectory, run.getRunDirectory());
}
private static class StreamListener {
private final StringBuilder string;
public StreamListener(final InputStream inputStream) {
string = new StringBuilder();
new Thread(new Runnable() {
public void run() {
try (Scanner sc = new Scanner(inputStream)) {
while (sc.hasNextLine()) {
string.append(sc.nextLine() + StringUtil.NEWLINE);
}
}
}
}).start();
}
public String getString() {
return string.toString();
}
}
public static TestPlan readFromDirectory(File testPlanDirectory) {
TestPlan testPlan = new TestPlan(testPlanDirectory);
List<Precondition> preconditions = Precondition.readFromDirectory(testPlanDirectory);
for (Precondition precondition : preconditions) {
testPlan.addPrecondition(precondition);
}
TestPlanRun runSettingsToInherit = TestPlanRun.readFromDirectory(testPlanDirectory, testPlanDirectory);
File[] subdirectories = FileUtil.getSubDirectories(testPlanDirectory);
for (File subdirectory : subdirectories) {
testPlan.addRuns(recursivelyReadRunsFromDirectory(subdirectory, testPlanDirectory, runSettingsToInherit));
}
return testPlan;
}
private static List<TestPlanRun> recursivelyReadRunsFromDirectory(File directory, File testPlanDirectory, TestPlanRun runSettingsToInherit) {
List<TestPlanRun> runs = new ArrayList<TestPlanRun>();
TestPlanRun run = TestPlanRun.readFromDirectory(testPlanDirectory, directory, runSettingsToInherit);
if (run != null) {
runs.add(run);
}
File[] subdirectories = FileUtil.getSubDirectories(directory);
for (File subdirectory : subdirectories) {
runs.addAll(recursivelyReadRunsFromDirectory(subdirectory, testPlanDirectory, runSettingsToInherit));
}
return runs;
}
public long checkSum() {
final int prime = 31;
long result = 1;
if (preconditions != null) {
for (Precondition precondition : preconditions) {
result = prime * result + precondition.checkSum();
}
}
if (runs != null) {
for (TestPlanRun run : runs) {
result = prime * result + run.checkSum();
}
}
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((preconditions == null) ? 0 : preconditions.hashCode());
result = prime * result + ((runs == null) ? 0 : runs.hashCode());
result = prime * result + ((testPlanDirectory == null) ? 0 : testPlanDirectory.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TestPlan other = (TestPlan) obj;
if (preconditions == null) {
if (other.preconditions != null)
return false;
} else if (!preconditions.equals(other.preconditions))
return false;
if (runs == null) {
if (other.runs != null)
return false;
} else if (!runs.equals(other.runs))
return false;
if (testPlanDirectory == null) {
if (other.testPlanDirectory != null)
return false;
} else if (!testPlanDirectory.equals(other.testPlanDirectory))
return false;
return true;
}
public static void main(String[] args) {
AlphaNumericStringComparator comp = new AlphaNumericStringComparator();
String[] strings = new String[] { "run01", "run1", "run2", "run02", "run10", "run11", "run12", "run7" };
Arrays.sort(strings, comp);
System.out.println(ArraysUtil.toString(strings, ","));
}
}
| bioinformatics_common/src/main/java/com/roche/bioinformatics/common/verification/runs/TestPlan.java | package com.roche.bioinformatics.common.verification.runs;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.roche.bioinformatics.common.verification.AutoTestPlanCli;
import com.roche.bioinformatics.common.verification.CliStatusConsole;
import com.roche.sequencing.bioinformatics.common.utils.AlphaNumericStringComparator;
import com.roche.sequencing.bioinformatics.common.utils.ArraysUtil;
import com.roche.sequencing.bioinformatics.common.utils.DateUtil;
import com.roche.sequencing.bioinformatics.common.utils.FileUtil;
import com.roche.sequencing.bioinformatics.common.utils.JVMUtil;
import com.roche.sequencing.bioinformatics.common.utils.LoggingUtil;
import com.roche.sequencing.bioinformatics.common.utils.Md5CheckSumUtil;
import com.roche.sequencing.bioinformatics.common.utils.OSUtil;
import com.roche.sequencing.bioinformatics.common.utils.PdfReportUtil;
import com.roche.sequencing.bioinformatics.common.utils.StringUtil;
import com.roche.sequencing.bioinformatics.common.utils.Version;
import com.roche.sequencing.bioinformatics.common.utils.ZipUtil;
public class TestPlan {
public final static Font SMALL_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 6, Font.NORMAL);
public final static Font REGULAR_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.NORMAL);
public final static Font REGULAR_BOLD_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
public final static Font SMALL_BOLD_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 6, Font.BOLD);
public final static Font SMALL_HEADER_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD);
public final static String CONSOLE_OUTPUT_FILE_NAME = "console.output";
public final static String CONSOLE_ERRORS_FILE_NAME = "console.errors";
private final static String ZIP_EXTENSION = ".zip";
private final File testPlanDirectory;
private final List<TestPlanRun> runs;
private final List<Precondition> preconditions;
public TestPlan(File testPlanDirectory) {
super();
this.runs = new ArrayList<TestPlanRun>();
this.preconditions = new ArrayList<Precondition>();
this.testPlanDirectory = testPlanDirectory;
}
private void addRun(TestPlanRun run) {
if (runs.contains(run)) {
throw new IllegalArgumentException("The TestPlanRun[" + run.getDescription() + "] has already been added to the test plan.");
}
runs.add(run);
}
private void addRuns(List<TestPlanRun> runs) {
for (TestPlanRun run : runs) {
addRun(run);
}
}
private void addPrecondition(Precondition precondition) {
if (preconditions.contains(precondition)) {
throw new IllegalArgumentException("The Precondition[" + precondition + "] has already been added to the test plan.");
}
preconditions.add(precondition);
}
public boolean createTestPlan(File outputTestPlan) {
return createTestPlanReport(null, outputTestPlan, null, null, false, false, null);
}
/**
*
* @param testerName
* @param outputReport
* @return true if test plan ran succesfully with no failures, false otherwise
*/
public boolean createTestPlanReport(File applicationToTest, File testPlanExecutionDirectory, File outputReport, File optionalJvmBinPath, boolean createZip, String startingFolder) {
return createTestPlanReport(applicationToTest, outputReport, testPlanExecutionDirectory, optionalJvmBinPath, true, createZip, startingFolder);
}
/**
*
* @param testerName
* @param outputReport
* @return true if test plan ran successfully with no failures, false otherwise
*/
private boolean createTestPlanReport(File applicationToTest, File outputReport, File testPlanExecutionDirectory, File optionalJvmBinPath, boolean createReport, boolean createZip,
String startingFolder) {
String startTime = DateUtil.getCurrentDateINYYYYMMDDHHMMSSwithColons();
if (createReport && !applicationToTest.exists()) {
throw new IllegalArgumentException("The provided applicationToTest[" + applicationToTest.getAbsolutePath() + "] does not exist.");
}
Document pdfDocument = PdfReportUtil.createDocument(outputReport, "", "", "", "");
boolean wasSuccess = true;
Element titleText = null;
if (createReport) {
titleText = new Phrase("Test Plan Report", REGULAR_BOLD_FONT);
} else {
titleText = new Phrase("Test Plan", REGULAR_BOLD_FONT);
}
Paragraph title = new Paragraph();
title.setAlignment(Element.ALIGN_MIDDLE);
title.add(titleText);
try {
pdfDocument.add(titleText);
} catch (DocumentException e) {
throw new IllegalStateException(e.getMessage(), e);
}
Paragraph runPlanTableParagraph = new Paragraph();
runPlanTableParagraph.add(Chunk.NEWLINE);
PdfPTable table = new PdfPTable(6);
try {
table.setWidths(new float[] { 20f, 15f, 50f, 35f, 40f, 20f });
} catch (DocumentException e1) {
e1.printStackTrace();
}
table.addCell(new PdfPCell(new Phrase("Reference Type and No.", SMALL_HEADER_FONT)));
table.addCell(new PdfPCell(new Phrase("Step Number", SMALL_HEADER_FONT)));
table.addCell(new PdfPCell(new Phrase("Test Step", SMALL_HEADER_FONT)));
table.addCell(new PdfPCell(new Phrase("Acceptance Criteria", SMALL_HEADER_FONT)));
table.addCell(new PdfPCell(new Phrase("Acceptance Results", SMALL_HEADER_FONT)));
table.addCell(new PdfPCell(new Phrase("Results (Pass/Fail)", SMALL_HEADER_FONT)));
int totalChecks = 0;
int passedChecks = 0;
PdfPCell grayCell = new PdfPCell();
grayCell.setBackgroundColor(new BaseColor(Color.LIGHT_GRAY));
PdfPCell emptyWhiteCell = new PdfPCell();
emptyWhiteCell.setBackgroundColor(new BaseColor(Color.WHITE));
PdfPCell naCell = new PdfPCell(new Phrase("NA", SMALL_FONT));
naCell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
for (Precondition precondition : preconditions) {
table.addCell(naCell);
table.addCell(new PdfPCell(new Phrase("Precondition", SMALL_FONT)));
table.addCell(new PdfPCell(new Phrase(precondition.getDescription(), SMALL_FONT)));
table.addCell(grayCell);
table.addCell(grayCell);
table.addCell(grayCell);
}
int runNumber = 1;
List<TestPlanRun> sortedRuns = new ArrayList<TestPlanRun>(runs);
Collections.sort(sortedRuns, new Comparator<TestPlanRun>() {
private AlphaNumericStringComparator windowsComparator = new AlphaNumericStringComparator();
@Override
public int compare(TestPlanRun o1, TestPlanRun o2) {
return windowsComparator.compare(o1.getRunDirectory().getName(), o2.getRunDirectory().getName());
}
});
boolean startingFolderExists = false;
runLoop: for (TestPlanRun run : sortedRuns) {
String runFolderName = run.getRunDirectory().getName();
startingFolderExists = runFolderName.equals(startingFolder);
if (startingFolderExists) {
break runLoop;
}
}
boolean startingFolderFound = true;
if (startingFolder != null && startingFolderExists) {
startingFolderFound = false;
} else {
throw new IllegalStateException("Could not find startFolder[" + startingFolder + "] in test plan directory[" + testPlanDirectory.getAbsolutePath() + "].");
}
for (TestPlanRun run : sortedRuns) {
startingFolderFound = startingFolderFound || run.getRunDirectory().getName().equals(startingFolder);
if (startingFolderFound) {
RunResults runResults = null;
CliStatusConsole.logStatus("");
CliStatusConsole.logStatus("Running step " + runNumber + "(" + run.getRunDirectory().getAbsolutePath() + ") : " + run.getDescription());
if (createReport) {
runResults = executeRun(run, applicationToTest, testPlanExecutionDirectory, runNumber, optionalJvmBinPath);
}
table.addCell(naCell);
table.addCell(new PdfPCell(new Phrase("" + runNumber, SMALL_BOLD_FONT)));
table.addCell(new PdfPCell(
new Phrase(run.getDescription() + StringUtil.NEWLINE + StringUtil.NEWLINE + "java -jar " + ArraysUtil.toString(run.getArguments().toArray(new String[0]), " "), SMALL_FONT)));
table.addCell(grayCell);
table.addCell(grayCell);
table.addCell(grayCell);
if (run.getChecks().size() == 0) {
throw new IllegalStateException("The provided step[" + run.getDescription() + "] has not checks which make it an invalid test.");
}
int checkNumber = 1;
for (TestPlanRunCheck check : run.getChecks()) {
String referenceTypeAndNumbers = "";
for (String requirement : check.getRequirements()) {
referenceTypeAndNumbers += requirement + StringUtil.NEWLINE;
}
String stepNumber = runNumber + "." + checkNumber;
if (referenceTypeAndNumbers.isEmpty()) {
table.addCell(naCell);
} else {
table.addCell(new PdfPCell(new Phrase(referenceTypeAndNumbers, SMALL_FONT)));
}
table.addCell(new PdfPCell(new Phrase(stepNumber, SMALL_FONT)));
table.addCell(new PdfPCell(new Phrase(check.getDescription(), SMALL_FONT)));
table.addCell(new PdfPCell(new Phrase(check.getAcceptanceCriteria(), SMALL_FONT)));
if (runResults != null) {
TestPlanRunCheckResult checkResult = check.check(runResults);
table.addCell(new PdfPCell(new Phrase(checkResult.getResultDescription(), SMALL_FONT)));
boolean wasCheckSuccess = checkResult.isPassed();
if (wasCheckSuccess) {
table.addCell(new PdfPCell(new Phrase("Pass", SMALL_FONT)));
CliStatusConsole.logStatus(" Check " + stepNumber + " passed : " + check.getDescription());
} else {
table.addCell(new PdfPCell(new Phrase("Fail", SMALL_FONT)));
CliStatusConsole.logStatus(" Check " + stepNumber + " failed : " + check.getDescription());
}
if (wasCheckSuccess) {
passedChecks++;
}
wasSuccess = wasSuccess && wasCheckSuccess;
} else {
table.addCell(emptyWhiteCell);
table.addCell(emptyWhiteCell);
}
checkNumber++;
totalChecks++;
}
}
runNumber++;
}
runPlanTableParagraph.add(table);
try {
pdfDocument.add(runPlanTableParagraph);
} catch (DocumentException e) {
throw new IllegalStateException(e.getMessage(), e);
}
if (createReport) {
String stopTime = DateUtil.getCurrentDateINYYYYMMDDHHMMSSwithColons();
// provide details about the system
Paragraph executionDetailsParagraph = new Paragraph();
executionDetailsParagraph.add(new Phrase("Test Plan Report Execution Details", REGULAR_BOLD_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(new Phrase("Report generated by " + AutoTestPlanCli.APPLICATION_NAME + " " + AutoTestPlanCli.getApplicationVersion(), REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
String userName = System.getProperty("user.name");
if (userName != null && !userName.isEmpty()) {
executionDetailsParagraph.add(new Phrase("Report generation initiated by: " + userName, REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
}
try {
InetAddress address = InetAddress.getLocalHost();
if (address != null) {
executionDetailsParagraph.add(new Phrase("Computer IP Address: " + address.getHostAddress(), REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
String hostName = address.getHostName();
if (hostName != null && !hostName.isEmpty()) {
executionDetailsParagraph.add(new Phrase("Computer Host Name: " + hostName, REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
}
}
} catch (UnknownHostException ex) {
}
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(new Phrase("Application to Test: " + applicationToTest.getAbsolutePath(), REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
try {
String md5Sum = Md5CheckSumUtil.md5sum(applicationToTest);
executionDetailsParagraph.add(new Phrase("Jar File Md5Sum: " + md5Sum, REGULAR_FONT));
executionDetailsParagraph.add(new Phrase("Jar File Location: " + applicationToTest.getAbsolutePath()));
executionDetailsParagraph.add(Chunk.NEWLINE);
} catch (IOException e1) {
}
executionDetailsParagraph.add(new Phrase("Test Plan CheckSum: " + checkSum(), REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(new Phrase("Test Plan Directory: " + testPlanDirectory.getAbsolutePath(), REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(new Phrase("Test Plan Results Directory: " + testPlanExecutionDirectory.getAbsolutePath(), REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(new Phrase("Start Time: " + startTime + " (yyyy:MM:dd HH:mm:ss)", REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(new Phrase("Stop Time: " + stopTime + " (yyyy:MM:dd HH:mm:ss)", REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(Chunk.NEWLINE);
executionDetailsParagraph.add(new Phrase("Operating System: " + OSUtil.getOsName() + " " + OSUtil.getOsBits() + "-bit", REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
String javaBin = getJavaBinPath(optionalJvmBinPath);
executionDetailsParagraph.add(new Phrase("Java Bin Path: " + javaBin, REGULAR_FONT));
executionDetailsParagraph.add(Chunk.NEWLINE);
Version javaVersion = JVMUtil.getJavaVersion(new File(javaBin));
executionDetailsParagraph.add(new Phrase("Java Version: " + javaVersion, REGULAR_FONT));
try {
pdfDocument.add(executionDetailsParagraph);
} catch (DocumentException e) {
throw new IllegalStateException(e.getMessage(), e);
}
} else {
// provide details about the system
Paragraph creationDetailsParagraph = new Paragraph();
creationDetailsParagraph.add(new Phrase("Test Plan Creation Details", REGULAR_BOLD_FONT));
creationDetailsParagraph.add(Chunk.NEWLINE);
creationDetailsParagraph.add(new Phrase("Report generated by " + AutoTestPlanCli.APPLICATION_NAME + " " + AutoTestPlanCli.getApplicationVersion(), REGULAR_FONT));
creationDetailsParagraph.add(Chunk.NEWLINE);
String userName = System.getProperty("user.name");
if (userName != null && !userName.isEmpty()) {
creationDetailsParagraph.add(new Phrase("Report generation initiated by: " + userName, REGULAR_FONT));
creationDetailsParagraph.add(Chunk.NEWLINE);
}
try {
InetAddress address = InetAddress.getLocalHost();
if (address != null) {
creationDetailsParagraph.add(new Phrase("Computer IP Address: " + address.getHostAddress(), REGULAR_FONT));
creationDetailsParagraph.add(Chunk.NEWLINE);
String hostName = address.getHostName();
if (hostName != null && !hostName.isEmpty()) {
creationDetailsParagraph.add(new Phrase("Computer Host Name: " + hostName, REGULAR_FONT));
creationDetailsParagraph.add(Chunk.NEWLINE);
}
}
} catch (UnknownHostException ex) {
}
creationDetailsParagraph.add(new Phrase("Test Plan CheckSum: " + checkSum(), REGULAR_FONT));
creationDetailsParagraph.add(Chunk.NEWLINE);
creationDetailsParagraph.add(new Phrase("Test Plan Directory: " + testPlanDirectory.getAbsolutePath(), REGULAR_FONT));
creationDetailsParagraph.add(Chunk.NEWLINE);
try {
pdfDocument.add(creationDetailsParagraph);
} catch (DocumentException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
pdfDocument.close();
CliStatusConsole.logStatus("");
if (createReport) {
int totalRuns = runNumber - 1;
if (totalRuns > 1) {
CliStatusConsole.logStatus(totalRuns + " total runs.");
} else {
CliStatusConsole.logStatus("1 total run.");
}
CliStatusConsole.logStatus(passedChecks + " out of " + totalChecks + " checks passed.");
if (wasSuccess) {
CliStatusConsole.logStatus("The test plan PASSED.");
} else {
CliStatusConsole.logStatus("The test plan FAILED.");
}
CliStatusConsole.logStatus("");
CliStatusConsole.logStatus("Test Plan Report was written to " + outputReport.getAbsolutePath() + ".");
} else {
CliStatusConsole.logStatus("Test Plan was written to " + outputReport.getAbsolutePath() + ".");
}
CliStatusConsole.logStatus("");
if (createZip) {
String zipFileName = testPlanExecutionDirectory.getName() + "_" + DateUtil.getCurrentDateINYYYYMMDDHHMMSS() + ZIP_EXTENSION;
File outputZipFile = new File(testPlanExecutionDirectory.getParentFile(), zipFileName);
CliStatusConsole.logStatus("Creating results Zip file at [" + outputZipFile + "].");
List<File> directoriesAndFilesToZip = new ArrayList<File>();
directoriesAndFilesToZip.add(testPlanExecutionDirectory);
directoriesAndFilesToZip.add(testPlanDirectory);
directoriesAndFilesToZip.add(outputReport);
directoriesAndFilesToZip.add(applicationToTest);
directoriesAndFilesToZip.add(LoggingUtil.getLogFile());
ZipUtil.zipDirectoriesAndFiles(outputZipFile, directoriesAndFilesToZip);
CliStatusConsole.logStatus("Done creating results Zip file at [" + outputZipFile + "].");
CliStatusConsole.logStatus("");
CliStatusConsole.logStatus("Deleting results directory at [" + testPlanExecutionDirectory + "].");
try {
FileUtil.deleteDirectory(testPlanExecutionDirectory);
CliStatusConsole.logStatus("Done deleting results directory at [" + testPlanExecutionDirectory + "].");
} catch (IOException e) {
CliStatusConsole.logStatus("Unable to deleting the results directory at [" + testPlanExecutionDirectory + "].");
CliStatusConsole.logError(e);
}
}
return wasSuccess;
}
private String getJavaBinPath(File optionalJvmBinPath) {
String javaBin = "";
if (optionalJvmBinPath != null) {
javaBin = optionalJvmBinPath.getAbsolutePath();
} else {
String javaHome = System.getProperty("java.home");
javaBin = javaHome + File.separator + "bin" + File.separator;
}
return javaBin;
}
private RunResults executeRun(TestPlanRun run, File applicationToTest, File testPlanExecutionDirectory, int stepNumber, File optionalJvmBinPath) {
String javaBin = getJavaBinPath(optionalJvmBinPath);
List<String> processBuilderArguments = new ArrayList<String>();
processBuilderArguments.add(new File(javaBin, "java").getAbsolutePath());
processBuilderArguments.add("-jar");
processBuilderArguments.add(applicationToTest.getAbsolutePath());
processBuilderArguments.addAll(run.getArguments());
ProcessBuilder processBuilder = new ProcessBuilder(processBuilderArguments);
// set the java working directory
File outputDirectory = new File(testPlanExecutionDirectory, "run_" + stepNumber);
if (outputDirectory.exists()) {
throw new IllegalStateException("The provided Test Plan Execution Directory[" + testPlanExecutionDirectory.getAbsolutePath()
+ "] already contains results. Please provide an empty Test Plan Execution Directory.");
}
try {
FileUtil.createDirectory(outputDirectory);
} catch (IOException e) {
throw new IllegalStateException("Unable to create the execution directory for run " + stepNumber + " at [" + outputDirectory.getAbsolutePath() + "].", e);
}
processBuilder.directory(outputDirectory);
for (Precondition precondition : preconditions) {
precondition.checkPrecondition(outputDirectory, new File(javaBin));
}
String consoleOutputString = "";
String consoleErrorsString = "";
try {
Process process = processBuilder.start();
StreamListener outputStreamListener = new StreamListener(process.getInputStream());
StreamListener errorStreamListener = new StreamListener(process.getErrorStream());
process.waitFor();
consoleOutputString = outputStreamListener.getString();
consoleErrorsString = errorStreamListener.getString();
} catch (IOException | InterruptedException e) {
throw new IllegalStateException("Unable to execute the provide jar file[" + applicationToTest.getAbsolutePath() + "]. " + e.getMessage());
}
try {
FileUtil.writeStringToFile(new File(outputDirectory, CONSOLE_OUTPUT_FILE_NAME), consoleOutputString);
FileUtil.writeStringToFile(new File(outputDirectory, CONSOLE_ERRORS_FILE_NAME), consoleErrorsString);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
File resultsDirectory = outputDirectory;
if (run.getResultsSubDirectory() != null) {
resultsDirectory = new File(resultsDirectory, run.getResultsSubDirectory());
}
return new RunResults(consoleOutputString, consoleErrorsString, resultsDirectory, run.getRunDirectory());
}
private static class StreamListener {
private final StringBuilder string;
public StreamListener(final InputStream inputStream) {
string = new StringBuilder();
new Thread(new Runnable() {
public void run() {
try (Scanner sc = new Scanner(inputStream)) {
while (sc.hasNextLine()) {
string.append(sc.nextLine() + StringUtil.NEWLINE);
}
}
}
}).start();
}
public String getString() {
return string.toString();
}
}
public static TestPlan readFromDirectory(File testPlanDirectory) {
TestPlan testPlan = new TestPlan(testPlanDirectory);
List<Precondition> preconditions = Precondition.readFromDirectory(testPlanDirectory);
for (Precondition precondition : preconditions) {
testPlan.addPrecondition(precondition);
}
TestPlanRun runSettingsToInherit = TestPlanRun.readFromDirectory(testPlanDirectory, testPlanDirectory);
File[] subdirectories = FileUtil.getSubDirectories(testPlanDirectory);
for (File subdirectory : subdirectories) {
testPlan.addRuns(recursivelyReadRunsFromDirectory(subdirectory, testPlanDirectory, runSettingsToInherit));
}
return testPlan;
}
private static List<TestPlanRun> recursivelyReadRunsFromDirectory(File directory, File testPlanDirectory, TestPlanRun runSettingsToInherit) {
List<TestPlanRun> runs = new ArrayList<TestPlanRun>();
TestPlanRun run = TestPlanRun.readFromDirectory(testPlanDirectory, directory, runSettingsToInherit);
if (run != null) {
runs.add(run);
}
File[] subdirectories = FileUtil.getSubDirectories(directory);
for (File subdirectory : subdirectories) {
runs.addAll(recursivelyReadRunsFromDirectory(subdirectory, testPlanDirectory, runSettingsToInherit));
}
return runs;
}
public long checkSum() {
final int prime = 31;
long result = 1;
if (preconditions != null) {
for (Precondition precondition : preconditions) {
result = prime * result + precondition.checkSum();
}
}
if (runs != null) {
for (TestPlanRun run : runs) {
result = prime * result + run.checkSum();
}
}
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((preconditions == null) ? 0 : preconditions.hashCode());
result = prime * result + ((runs == null) ? 0 : runs.hashCode());
result = prime * result + ((testPlanDirectory == null) ? 0 : testPlanDirectory.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TestPlan other = (TestPlan) obj;
if (preconditions == null) {
if (other.preconditions != null)
return false;
} else if (!preconditions.equals(other.preconditions))
return false;
if (runs == null) {
if (other.runs != null)
return false;
} else if (!runs.equals(other.runs))
return false;
if (testPlanDirectory == null) {
if (other.testPlanDirectory != null)
return false;
} else if (!testPlanDirectory.equals(other.testPlanDirectory))
return false;
return true;
}
public static void main(String[] args) {
AlphaNumericStringComparator comp = new AlphaNumericStringComparator();
String[] strings = new String[] { "run01", "run1", "run2", "run02", "run10", "run11", "run12", "run7" };
Arrays.sort(strings, comp);
System.out.println(ArraysUtil.toString(strings, ","));
}
}
| fixing issue with startFolder parameter
| bioinformatics_common/src/main/java/com/roche/bioinformatics/common/verification/runs/TestPlan.java | fixing issue with startFolder parameter | <ide><path>ioinformatics_common/src/main/java/com/roche/bioinformatics/common/verification/runs/TestPlan.java
<ide> }
<ide> });
<ide>
<del> boolean startingFolderExists = false;
<del> runLoop: for (TestPlanRun run : sortedRuns) {
<del> String runFolderName = run.getRunDirectory().getName();
<del> startingFolderExists = runFolderName.equals(startingFolder);
<add> boolean startingFolderFound = true;
<add>
<add> if (startingFolder != null) {
<add> boolean startingFolderExists = false;
<add> runLoop: for (TestPlanRun run : sortedRuns) {
<add> String runFolderName = run.getRunDirectory().getName();
<add> startingFolderExists = runFolderName.equals(startingFolder);
<add> if (startingFolderExists) {
<add> break runLoop;
<add> }
<add> }
<add>
<ide> if (startingFolderExists) {
<del> break runLoop;
<del> }
<del> }
<del>
<del> boolean startingFolderFound = true;
<del> if (startingFolder != null && startingFolderExists) {
<del> startingFolderFound = false;
<del> } else {
<del> throw new IllegalStateException("Could not find startFolder[" + startingFolder + "] in test plan directory[" + testPlanDirectory.getAbsolutePath() + "].");
<add> startingFolderFound = false;
<add> } else {
<add> throw new IllegalStateException("Could not find startFolder[" + startingFolder + "] in test plan directory[" + testPlanDirectory.getAbsolutePath() + "].");
<add> }
<ide> }
<ide>
<ide> for (TestPlanRun run : sortedRuns) {
<ide>
<ide> table.addCell(naCell);
<ide> table.addCell(new PdfPCell(new Phrase("" + runNumber, SMALL_BOLD_FONT)));
<del> table.addCell(new PdfPCell(
<del> new Phrase(run.getDescription() + StringUtil.NEWLINE + StringUtil.NEWLINE + "java -jar " + ArraysUtil.toString(run.getArguments().toArray(new String[0]), " "), SMALL_FONT)));
<add> table.addCell(new PdfPCell(new Phrase(run.getDescription() + StringUtil.NEWLINE + StringUtil.NEWLINE + "java -jar "
<add> + ArraysUtil.toString(run.getArguments().toArray(new String[0]), " "), SMALL_FONT)));
<ide>
<ide> table.addCell(grayCell);
<ide> table.addCell(grayCell); |
|
Java | apache-2.0 | 90fa9639021e64c39d99b71f78bee69ad7a86316 | 0 | mapcode-foundation/mapcode-rest-service,mapcode-foundation/mapcode-rest-service,mapcode-foundation/mapcode-rest-service | /*
* Copyright (C) 2016 Stichting Mapcode Foundation (http://www.mapcode.com)
*
* 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.mapcode.services;
import com.mapcode.Alphabet;
import com.mapcode.services.implementation.MapcodeResourceImpl;
import com.mapcode.services.implementation.RootResourceImpl;
import com.mapcode.services.implementation.SystemMetricsImpl;
import com.tomtom.speedtools.maven.MavenProperties;
import com.tomtom.speedtools.rest.Reactor;
import com.tomtom.speedtools.rest.ResourceProcessor;
import com.tomtom.speedtools.testutils.akka.SimpleExecutionContext;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.ExecutionContext;
import javax.annotation.Nonnull;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@SuppressWarnings("JUnitTestMethodWithNoAssertions")
public class ApiResourcesTest {
private static final Logger LOG = LoggerFactory.getLogger(ApiResourcesTest.class);
private static final String TEST_POM_VERSION = "TEST-1";
private static final Double TEST_LAT1 = 50.141706;
private static final Double TEST_LON1 = 6.135864;
private static final String TEST_LATLON1 = TEST_LAT1 + "," + TEST_LON1;
private static final Double TEST_LAT2 = 52.159853;
private static final Double TEST_LON2 = 4.499790;
private static final String TEST_LATLON2 = TEST_LAT2 + "," + TEST_LON2;
private static final String TEST_CODE1 = "VJ0L6.9PNQ";
private static final String TEST_CODE2 = "JL0.KP";
private static final String TEST_CONTEXT2 = "LUX";
private static final int PORT = 8081;
private static final String HOST = "http://localhost:" + PORT;
private TJWSEmbeddedJaxrsServer server;
@Before
public void startServer() {
server = new TJWSEmbeddedJaxrsServer();
server.setPort(PORT);
// Create a simple ResourceProcessor, required for implementation of REST service using the SpeedTools framework.
final Reactor reactor = new Reactor() {
@Nonnull
@Override
public ExecutionContext getExecutionContext() {
return SimpleExecutionContext.getInstance();
}
// This method is stubbed and never used.
@Nonnull
@Override
public DateTime getSystemStartupTime() {
return new DateTime();
}
// This method is stubbed and never used.
@Nonnull
@Override
public <T> T createTopLevelActor(@Nonnull final Class<T> interfaceClass, @Nonnull final Class<? extends T> implementationClass, @Nonnull Object... explicitParameters) {
assert false;
return null;
}
};
final ResourceProcessor resourceProcessor = new ResourceProcessor(reactor);
// Add root resource.
server.getDeployment().getResources().add(new RootResourceImpl(
new MavenProperties(TEST_POM_VERSION),
new SystemMetricsImpl()
));
// Add mapcode resource.
server.getDeployment().getResources().add(new MapcodeResourceImpl(
resourceProcessor,
new SystemMetricsImpl()
));
server.start();
}
@After
public void stopServer() {
server.stop();
}
@Test
public void checkStatus() {
LOG.info("checkStatus");
final Response r = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/version").
request().
get();
Assert.assertNotNull(r);
final int status = r.getStatus();
LOG.info("status = {}", status);
Assert.assertEquals(200, status);
}
@Test
public void checkVersionJson() {
LOG.info("checkVersionJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/version").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"version\":\"TEST-1\"}",
response.readEntity(String.class));
}
@Test
public void checkVersionXml() {
LOG.info("checkVersionXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/version").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><version><version>TEST-1</version></version>",
response.readEntity(String.class));
}
@Test
public void checkCodesJson() {
LOG.info("checkCodesJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1).
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"territory\":\"LUX\"},{\"mapcode\":\"R8RN.07Z\",\"territory\":\"LUX\"},{\"mapcode\":\"SQB.NR3\",\"territory\":\"BEL\"},{\"mapcode\":\"R8RN.07Z\",\"territory\":\"BEL\"},{\"mapcode\":\"0L46.LG9\",\"territory\":\"DEU\"},{\"mapcode\":\"R8RN.07Z\",\"territory\":\"FRA\"},{\"mapcode\":\"VJ0L6.9PNQ\"}]}",
response.readEntity(String.class));
}
@Test
public void checkCodesXml() {
LOG.info("checkCodesXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1).
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>SQB.NR3</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>0L46.LG9</mapcode><territory>DEU</territory></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><territory>FRA</territory></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode></mapcode></mapcodes></mapcodes>",
response.readEntity(String.class));
}
@Test
public void checkCodesPrecision0Json() {
LOG.info("checkCodesPrecision0Json");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?precision=0").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"territory\":\"LUX\"},{\"mapcode\":\"R8RN.07Z\",\"territory\":\"LUX\"},{\"mapcode\":\"SQB.NR3\",\"territory\":\"BEL\"},{\"mapcode\":\"R8RN.07Z\",\"territory\":\"BEL\"},{\"mapcode\":\"0L46.LG9\",\"territory\":\"DEU\"},{\"mapcode\":\"R8RN.07Z\",\"territory\":\"FRA\"},{\"mapcode\":\"VJ0L6.9PNQ\"}]}",
response.readEntity(String.class));
}
@Test
public void checkCodesPrecision0Xml() {
LOG.info("checkCodesPrecision0Xml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?precision=0").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>SQB.NR3</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>0L46.LG9</mapcode><territory>DEU</territory></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><territory>FRA</territory></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode></mapcode></mapcodes></mapcodes>",
response.readEntity(String.class));
}
@Test
public void checkCodesPrecision1Json() {
LOG.info("checkCodesPrecision1Json");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?precision=1").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"international\":{\"mapcode\":\"VJ0L6.9PNQ-0\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP-8\",\"territory\":\"LUX\"},{\"mapcode\":\"R8RN.07Z-M\",\"territory\":\"LUX\"},{\"mapcode\":\"SQB.NR3-P\",\"territory\":\"BEL\"},{\"mapcode\":\"R8RN.07Z-M\",\"territory\":\"BEL\"},{\"mapcode\":\"0L46.LG9-Q\",\"territory\":\"DEU\"},{\"mapcode\":\"R8RN.07Z-M\",\"territory\":\"FRA\"},{\"mapcode\":\"VJ0L6.9PNQ-0\"}]}",
response.readEntity(String.class));
}
@Test
public void checkCodesPrecision1Xml() {
LOG.info("checkCodesPrecision1Xml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?precision=1").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ-0</mapcode></international><mapcodes><mapcode><mapcode>JL0.KP-8</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>R8RN.07Z-M</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>SQB.NR3-P</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>R8RN.07Z-M</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>0L46.LG9-Q</mapcode><territory>DEU</territory></mapcode><mapcode><mapcode>R8RN.07Z-M</mapcode><territory>FRA</territory></mapcode><mapcode><mapcode>VJ0L6.9PNQ-0</mapcode></mapcode></mapcodes></mapcodes>",
response.readEntity(String.class));
}
@Test
public void checkCodesPrecision8Json() {
LOG.info("checkCodesPrecision8Json");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?precision=8").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"international\":{\"mapcode\":\"VJ0L6.9PNQ-03Q7CGV4\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP-81B34315\",\"territory\":\"LUX\"},{\"mapcode\":\"R8RN.07Z-MWPCRQBK\",\"territory\":\"LUX\"},{\"mapcode\":\"SQB.NR3-P6880000\",\"territory\":\"BEL\"},{\"mapcode\":\"R8RN.07Z-MWPCRQBK\",\"territory\":\"BEL\"},{\"mapcode\":\"0L46.LG9-QWPVQVRW\",\"territory\":\"DEU\"},{\"mapcode\":\"R8RN.07Z-MWPCRQBK\",\"territory\":\"FRA\"},{\"mapcode\":\"VJ0L6.9PNQ-03Q7CGV4\"}]}",
response.readEntity(String.class));
}
@Test
public void checkCodesPrecision8Xml() {
LOG.info("checkCodesPrecision8Xml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?precision=8").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ-03Q7CGV4</mapcode></international><mapcodes><mapcode><mapcode>JL0.KP-81B34315</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>R8RN.07Z-MWPCRQBK</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>SQB.NR3-P6880000</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>R8RN.07Z-MWPCRQBK</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>0L46.LG9-QWPVQVRW</mapcode><territory>DEU</territory></mapcode><mapcode><mapcode>R8RN.07Z-MWPCRQBK</mapcode><territory>FRA</territory></mapcode><mapcode><mapcode>VJ0L6.9PNQ-03Q7CGV4</mapcode></mapcode></mapcodes></mapcodes>",
response.readEntity(String.class));
}
@Test
public void checkCodesLocalJson() {
LOG.info("checkCodesLocalJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON2 + "/local").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"mapcode\":\"QKM.N4\",\"territory\":\"NLD\"}",
response.readEntity(String.class));
}
@Test
public void checkCodesLocalXml() {
LOG.info("checkCodesLocalXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON2 + "/local").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcode><mapcode>QKM.N4</mapcode><territory>NLD</territory></mapcode>",
response.readEntity(String.class));
}
@Test
public void checkCodesInternationalJson() {
LOG.info("checkCodesInternationalJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "/International").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"mapcode\":\"VJ0L6.9PNQ\"}",
response.readEntity(String.class));
}
@Test
public void checkCodesInternationalXml() {
LOG.info("checkCodesInternationalXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "/International").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcode><mapcode>VJ0L6.9PNQ</mapcode></mapcode>",
response.readEntity(String.class));
}
@Test
public void checkCodesIncludeJson() {
LOG.info("checkCodesIncludeJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON2 + "?include=offset,territory,alphabet").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"local\":{\"mapcode\":\"QKM.N4\",\"mapcodeInAlphabet\":\"QKM.N4\",\"territory\":\"NLD\",\"territoryInAlphabet\":\"NLD\",\"offsetMeters\":2.843693},\"international\":{\"mapcode\":\"VHVN4.YZ74\",\"mapcodeInAlphabet\":\"VHVN4.YZ74\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"AAA\",\"offsetMeters\":1.907245},\"mapcodes\":[{\"mapcode\":\"QKM.N4\",\"mapcodeInAlphabet\":\"QKM.N4\",\"territory\":\"NLD\",\"territoryInAlphabet\":\"NLD\",\"offsetMeters\":2.843693},{\"mapcode\":\"CZQ.376\",\"mapcodeInAlphabet\":\"CZQ.376\",\"territory\":\"NLD\",\"territoryInAlphabet\":\"NLD\",\"offsetMeters\":5.004936},{\"mapcode\":\"N39J.QW0\",\"mapcodeInAlphabet\":\"N39J.QW0\",\"territory\":\"NLD\",\"territoryInAlphabet\":\"NLD\",\"offsetMeters\":2.836538},{\"mapcode\":\"VHVN4.YZ74\",\"mapcodeInAlphabet\":\"VHVN4.YZ74\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"AAA\",\"offsetMeters\":1.907245}]}",
response.readEntity(String.class));
}
@Test
public void checkCodesIncludeXml() {
LOG.info("checkCodesIncludeXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON2 + "?include=offset,territory,alphabet").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><local><mapcode>QKM.N4</mapcode><mapcodeInAlphabet>QKM.N4</mapcodeInAlphabet><territory>NLD</territory><territoryInAlphabet>NLD</territoryInAlphabet><offsetMeters>2.843693</offsetMeters></local><international><mapcode>VHVN4.YZ74</mapcode><mapcodeInAlphabet>VHVN4.YZ74</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>AAA</territoryInAlphabet><offsetMeters>1.907245</offsetMeters></international><mapcodes><mapcode><mapcode>QKM.N4</mapcode><mapcodeInAlphabet>QKM.N4</mapcodeInAlphabet><territory>NLD</territory><territoryInAlphabet>NLD</territoryInAlphabet><offsetMeters>2.843693</offsetMeters></mapcode><mapcode><mapcode>CZQ.376</mapcode><mapcodeInAlphabet>CZQ.376</mapcodeInAlphabet><territory>NLD</territory><territoryInAlphabet>NLD</territoryInAlphabet><offsetMeters>5.004936</offsetMeters></mapcode><mapcode><mapcode>N39J.QW0</mapcode><mapcodeInAlphabet>N39J.QW0</mapcodeInAlphabet><territory>NLD</territory><territoryInAlphabet>NLD</territoryInAlphabet><offsetMeters>2.836538</offsetMeters></mapcode><mapcode><mapcode>VHVN4.YZ74</mapcode><mapcodeInAlphabet>VHVN4.YZ74</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>AAA</territoryInAlphabet><offsetMeters>1.907245</offsetMeters></mapcode></mapcodes></mapcodes>",
response.readEntity(String.class));
}
private void doCheckJson(@Nonnull final String alphabet, @Nonnull final String expected) {
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?include=territory,alphabet&alphabet=" + alphabet).
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(expected, response.readEntity(String.class));
}
@Test
public void checkCoords1Json() {
LOG.info("checkCoords1Json");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/coords/" + TEST_CODE1).
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"latDeg\":50.141726,\"lonDeg\":6.1358875}",
response.readEntity(String.class));
}
@Test
public void checkCoords1Xml() {
LOG.info("checkCoords1Xml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/coords/" + TEST_CODE1).
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><point><latDeg>50.141726</latDeg><lonDeg>6.1358875</lonDeg></point>",
response.readEntity(String.class));
}
@Test
public void checkCoords2Json() {
LOG.info("checkCoords2Json");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/coords/" + TEST_CODE2 + "?context=" + TEST_CONTEXT2).
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"latDeg\":50.141735,\"lonDeg\":6.135845}",
response.readEntity(String.class));
}
@Test
public void checkCoords2Xml() {
LOG.info("checkCoords2Xml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/coords/" + TEST_CODE2 + "?context=" + TEST_CONTEXT2).
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><point><latDeg>50.141735</latDeg><lonDeg>6.135845</lonDeg></point>",
response.readEntity(String.class));
}
@Test
public void checkTerritoriesJson() {
LOG.info("checkTerritoriesJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/territories").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
final String r = response.readEntity(String.class);
Assert.assertTrue(r.length() > 500);
final String sub1 = r.substring(0, 500);
final String sub2 = r.substring(r.length() - 500, r.length());
Assert.assertEquals("{\"territories\":[{\"aliases\":[\"US\"],\"fullNameAliases\":[\"United States of America\",\"America\"],\"alphaCode\":\"USA\",\"alphaCodeMinimalUnambiguous\":\"USA\",\"alphaCodeMinimal\":\"USA\",\"fullName\":\"USA\"},{\"aliases\":[\"IN\"],\"alphaCode\":\"IND\",\"alphaCodeMinimalUnambiguous\":\"IND\",\"alphaCodeMinimal\":\"IND\",\"fullName\":\"India\"},{\"aliases\":[\"CA\"],\"alphaCode\":\"CAN\",\"alphaCodeMinimalUnambiguous\":\"CAN\",\"alphaCodeMinimal\":\"CAN\",\"fullName\":\"Canada\"},{\"aliases\":[\"AU\"],\"alphaCode\":\"AUS\",\"alphaCodeMinimalUnambiguous\":\"AUS\",\"alph",
sub1);
Assert.assertEquals("aCodeMinimal\":\"XJ\",\"fullName\":\"Xinjiang Uyghur\",\"parentTerritory\":\"CHN\"},{\"aliases\":[\"US-UM\",\"USA-UM\",\"JTN\"],\"alphaCode\":\"UMI\",\"alphaCodeMinimalUnambiguous\":\"UMI\",\"alphaCodeMinimal\":\"UMI\",\"fullName\":\"United States Minor Outlying Islands\"},{\"alphaCode\":\"CPT\",\"alphaCodeMinimalUnambiguous\":\"CPT\",\"alphaCodeMinimal\":\"CPT\",\"fullName\":\"Clipperton Island\"},{\"fullNameAliases\":[\"Worldwide\",\"Earth\"],\"alphaCode\":\"AAA\",\"alphaCodeMinimalUnambiguous\":\"AAA\",\"alphaCodeMinimal\":\"AAA\",\"fullName\":\"International\"}]}",
sub2);
}
@Test
public void checkTerritoriesXml() {
LOG.info("checkTerritoriesXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/territories").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
final String r = response.readEntity(String.class);
Assert.assertTrue(r.length() > 500);
final String sub1 = r.substring(0, 500);
final String sub2 = r.substring(r.length() - 500, r.length());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><territories><territory><alphaCode>USA</alphaCode><alphaCodeMinimalUnambiguous>USA</alphaCodeMinimalUnambiguous><alphaCodeMinimal>USA</alphaCodeMinimal><fullName>USA</fullName><aliases><alias>US</alias></aliases><fullNameAliases><fullNameAlias>United States of America</fullNameAlias><fullNameAlias>America</fullNameAlias></fullNameAliases></territory><territory><alphaCode>IND</alphaCode><alphaCodeMinimalUnambiguous>IND</alphaCodeMinimalUnambi",
sub1);
Assert.assertEquals("<alphaCodeMinimalUnambiguous>CPT</alphaCodeMinimalUnambiguous><alphaCodeMinimal>CPT</alphaCodeMinimal><fullName>Clipperton Island</fullName><aliases/><fullNameAliases/></territory><territory><alphaCode>AAA</alphaCode><alphaCodeMinimalUnambiguous>AAA</alphaCodeMinimalUnambiguous><alphaCodeMinimal>AAA</alphaCodeMinimal><fullName>International</fullName><aliases/><fullNameAliases><fullNameAlias>Worldwide</fullNameAlias><fullNameAlias>Earth</fullNameAlias></fullNameAliases></territory></territories>",
sub2);
}
@Test
public void checkTerritoryJson() {
LOG.info("checkTerritoryJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/territories/nld").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"alphaCode\":\"NLD\",\"alphaCodeMinimalUnambiguous\":\"NLD\",\"alphaCodeMinimal\":\"NLD\",\"fullName\":\"Netherlands\"}",
response.readEntity(String.class));
}
@Test
public void checkTerritoryXml() {
LOG.info("checkTerritoryXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/territories/nld").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><territory><alphaCode>NLD</alphaCode><alphaCodeMinimalUnambiguous>NLD</alphaCodeMinimalUnambiguous><alphaCodeMinimal>NLD</alphaCodeMinimal><fullName>Netherlands</fullName><aliases/><fullNameAliases/></territory>",
response.readEntity(String.class));
}
@Test
public void checkAlphabetsJson() {
LOG.info("checkAlphabetsJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"alphabets\":[{\"name\":\"ROMAN\"},{\"name\":\"GREEK\"},{\"name\":\"CYRILLIC\"},{\"name\":\"HEBREW\"},{\"name\":\"HINDI\"},{\"name\":\"MALAY\"},{\"name\":\"GEORGIAN\"},{\"name\":\"KATAKANA\"},{\"name\":\"THAI\"},{\"name\":\"LAO\"},{\"name\":\"ARMENIAN\"},{\"name\":\"BENGALI\"},{\"name\":\"GURMUKHI\"},{\"name\":\"TIBETAN\"}]}",
response.readEntity(String.class));
}
@Test
public void checkAlphabetsCountJson() {
LOG.info("checkAlphabetsCountJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets?count=2").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"alphabets\":[{\"name\":\"ROMAN\"},{\"name\":\"GREEK\"}]}",
response.readEntity(String.class));
}
@Test
public void checkAlphabetsCountXml() {
LOG.info("checkAlphabetsCountXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets?count=2").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><alphabets><alphabet><name>ROMAN</name></alphabet><alphabet><name>GREEK</name></alphabet></alphabets>",
response.readEntity(String.class));
}
@Test
public void checkAlphabetsCountOffsetJson() {
LOG.info("checkAlphabetsCountOffsetJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets?count=1&offset=1").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"alphabets\":[{\"name\":\"GREEK\"}]}",
response.readEntity(String.class));
}
@Test
public void checkAlphabetsCountOffsetXml() {
LOG.info("checkAlphabetsCountOffsetXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets?count=1&offset=1").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><alphabets><alphabet><name>GREEK</name></alphabet></alphabets>",
response.readEntity(String.class));
}
@Test
public void checkAlphabetsCountOffsetFromEndJson() {
LOG.info("checkAlphabetsCountOffsetFromEndJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets?count=1&offset=-1").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"alphabets\":[{\"name\":\"TIBETAN\"}]}",
response.readEntity(String.class));
}
@Test
public void checkAlphabetsCountOffsetFromEndXml() {
LOG.info("checkAlphabetsCountOffsetXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets?count=1&offset=-1").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><alphabets><alphabet><name>TIBETAN</name></alphabet></alphabets>",
response.readEntity(String.class));
}
@Test
public void checkAlphabetJson() {
LOG.info("checkAlphabetJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets/greek").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"name\":\"GREEK\"}",
response.readEntity(String.class));
}
@Test
public void checkAlphabetXml() {
LOG.info("checkAlphabetXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets/greek").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><alphabet><name>GREEK</name></alphabet>",
response.readEntity(String.class));
}
@Test
public void checkAllAlphabetsJson() {
LOG.info("checkAlphabetsJson");
int i = 0;
for (final Alphabet alphabet : Alphabet.values()) {
doCheckAlphabet(alphabet.name(), MediaType.APPLICATION_JSON_TYPE, EXPECTED_ALPHABETS_JSON[i]);
++i;
}
}
@Test
public void checkAllAlphabetsXml() {
LOG.info("checkAlphabetsXml");
int i = 0;
for (final Alphabet alphabet : Alphabet.values()) {
doCheckAlphabet(alphabet.name(), MediaType.APPLICATION_XML_TYPE, EXPECTED_ALPHABETS_XML[i]);
++i;
}
}
private static void doCheckAlphabet(
@Nonnull final String alphabet,
@Nonnull final MediaType mediaType,
@Nonnull final String expected) {
LOG.info("doCheckAlphabet: alphabet={}, mediaType={}", alphabet, mediaType);
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?include=territory,alphabet&alphabet=" + alphabet).
request().
accept(mediaType).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(expected, response.readEntity(String.class));
}
private final static String[] EXPECTED_ALPHABETS_JSON = {
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"VJ0L6.9PNQ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"AAA\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"JL0.KP\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"LUX\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"R8RN.07Z\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"LUX\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"SQB.NR3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"BEL\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"R8RN.07Z\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"BEL\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0L46.LG9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"DEU\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"R8RN.07Z\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"FRA\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"VJ0L6.9PNQ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"AAA\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ΦΠ0Λ6.9ΡΝΘ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ΑΑΑ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ΠΛ0.ΚΡ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"LUX\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Ψ8ΨΝ.07Ζ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"LUX\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"ΣΘΒ.ΝΨ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"BEL\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Ψ8ΨΝ.07Ζ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"BEL\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0Λ46.ΛΓ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"DEU\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Ψ8ΨΝ.07Ζ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ΕΨΑ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ΦΠ0Λ6.9ΡΝΘ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ΑΑΑ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ЧП0Л6.9РЗФ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ААА\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ПЛ0.КР\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ЛЭХ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Я8ЯЗ.07Б\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ЛЭХ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"ЦФВ.ЗЯ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ВЕЛ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Я8ЯЗ.07Б\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ВЕЛ\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0Л46.ЛГ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"ДЕЭ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Я8ЯЗ.07Б\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ЖЯА\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ЧП0Л6.9РЗФ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ААА\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"צט0ך6.9םלמ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"אאא\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"טך0.ים\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ךץר\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"נ8נל.07ת\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ךץר\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"עמב.לנ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"בףך\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"נ8נל.07ת\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"בףך\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ך46.ךז9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"דףץ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"נ8נל.07ת\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"הנא\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"צט0ך6.9םלמ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"אאא\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"लठ0त6.9नधप\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"अअअ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ठत0.णन\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"तफस\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"भ8भध.07ड\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"तफस\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"मपक.धभ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"कएत\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"भ8भध.07ड\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"कएत\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0त46.तज9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"घएफ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"भ8भध.07ड\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"चभअ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"लठ0त6.9नधप\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"अअअ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ഴഡ0ഥ6.9നധമ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ഒഒഒ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ഡഥ0.തന\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ഥഉശ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ര8രധ.07ഹ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ഥഉശ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"റമക.ധര3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"കഋഥ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ര8രധ.07ഹ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"കഋഥ\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ഥ46.ഥജ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"ഗഋഉ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ര8രധ.07ഹ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ചരഒ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ഴഡ0ഥ6.9നധമ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ഒഒഒ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ႺႮ0Ⴑ6.9ႵႴႶ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ႠႠႠ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ႮႱ0.ႰႵ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ႱႨႽ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Ⴗ8ႷႴ.07Ⴟ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ႱႨႽ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"ႸႶႡ.ႴႷ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ႡႤႱ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Ⴗ8ႷႴ.07Ⴟ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ႡႤႱ\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0Ⴑ46.ႱႫ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"ႦႤႨ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Ⴗ8ႷႴ.07Ⴟ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ႩႷႠ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ႺႮ0Ⴑ6.9ႵႴႶ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ႠႠႠ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"モス0ト6.9ヒヌフ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"アアア\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"スト0.チヒ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"トエラ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ヘ8ヘヌ.07ヲ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"トエラ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"ホフカ.ヌヘ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"カオト\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ヘ8ヘヌ.07ヲ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"カオト\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ト46.トコ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"クオエ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ヘ8ヘヌ.07ヲ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ケヘア\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"モス0ト6.9ヒヌフ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"アアア\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ลช0ด6.9ธทบ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ะะะ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ชด0.ฑธ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ดฬอ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ผ8ผท.07ฯ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ดฬอ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"มบก.ทผ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"กาด\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ผ8ผท.07ฯ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"กาด\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ด46.ดจ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"คาฬ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ผ8ผท.07ฯ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"งผะ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ลช0ด6.9ธทบ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ะะะ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ວຍ0ທ6.9ຜບພ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ະະະ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ຍທ0.ດຜ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ທຽຫ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ມ8ມບ.07ຯ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ທຽຫ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"ຢພກ.ບມ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ກໃທ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ມ8ມບ.07ຯ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ກໃທ\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ທ46.ທຈ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"ຄໃຽ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ມ8ມບ.07ຯ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ງມະ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ວຍ0ທ6.9ຜບພ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ະະະ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ՏԽ0Հ6.9ՇՃՈ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ՖՖՖ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ԽՀ0.ԿՇ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ՀՅՑ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Պ8ՊՃ.07Փ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ՀՅՑ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"ՍՈԲ.ՃՊ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ԲԵՀ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Պ8ՊՃ.07Փ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ԲԵՀ\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0Հ46.ՀԹ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"ԴԵՅ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Պ8ՊՃ.07Փ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ԸՊՖ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ՏԽ0Հ6.9ՇՃՈ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ՖՖՖ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"বঝ0ড6.9তণথ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"অঅঅ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ঝড0.ঠত\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ডওয\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"দ8দণ.07হ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ডওয\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"নথঌ.ণদ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ঌএড\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"দ8দণ.07হ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ঌএড\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ড46.ডঙ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"খএও\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"দ8দণ.07হ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"গদঅ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"বঝ0ড6.9তণথ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"অঅঅ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ਲਠ0ਤ6.9ਨਧਪ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ਅਅਅ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ਠਤ0.ਣਨ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ਤਫਸ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ਭ8ਭਧ.07ਡ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ਤਫਸ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"ਮਪਕ.ਧਭ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ਕਏਤ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ਭ8ਭਧ.07ਡ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ਕਏਤ\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ਤ46.ਤਜ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"ਘਏਫ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ਭ8ਭਧ.07ਡ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ਚਭਅ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ਲਠ0ਤ6.9ਨਧਪ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ਅਅਅ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ཟཇ0ཌ6.9དཏན\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"མམམ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ཇཌ0.ཊད\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ཌཥར\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"པ8པཏ.07ས\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ཌཥར\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"བནཀ.ཏཔ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ཀཤཌ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"པ8པཏ.07ས\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ཀཤཌ\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ཌ46.ཌཅ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"གཤཥ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"པ8པཏ.07ས\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ངཔམ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ཟཇ0ཌ6.9དཏན\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"མམམ\"}]}",
};
private final static String[] EXPECTED_ALPHABETS_XML = {
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>VJ0L6.9PNQ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>AAA</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>JL0.KP</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>LUX</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>R8RN.07Z</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>LUX</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>SQB.NR3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>BEL</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>R8RN.07Z</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>BEL</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0L46.LG9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>DEU</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>R8RN.07Z</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>FRA</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>VJ0L6.9PNQ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>AAA</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ΦΠ0Λ6.9ΡΝΘ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ΑΑΑ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ΠΛ0.ΚΡ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>LUX</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Ψ8ΨΝ.07Ζ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>LUX</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>ΣΘΒ.ΝΨ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>BEL</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Ψ8ΨΝ.07Ζ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>BEL</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0Λ46.ΛΓ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>DEU</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Ψ8ΨΝ.07Ζ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ΕΨΑ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ΦΠ0Λ6.9ΡΝΘ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ΑΑΑ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ЧП0Л6.9РЗФ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ААА</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ПЛ0.КР</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ЛЭХ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Я8ЯЗ.07Б</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ЛЭХ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>ЦФВ.ЗЯ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ВЕЛ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Я8ЯЗ.07Б</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ВЕЛ</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0Л46.ЛГ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>ДЕЭ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Я8ЯЗ.07Б</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ЖЯА</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ЧП0Л6.9РЗФ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ААА</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>צט0ך6.9םלמ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>אאא</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>טך0.ים</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ךץר</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>נ8נל.07ת</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ךץר</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>עמב.לנ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>בףך</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>נ8נל.07ת</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>בףך</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ך46.ךז9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>דףץ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>נ8נל.07ת</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>הנא</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>צט0ך6.9םלמ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>אאא</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>लठ0त6.9नधप</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>अअअ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ठत0.णन</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>तफस</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>भ8भध.07ड</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>तफस</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>मपक.धभ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>कएत</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>भ8भध.07ड</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>कएत</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0त46.तज9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>घएफ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>भ8भध.07ड</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>चभअ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>लठ0त6.9नधप</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>अअअ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ഴഡ0ഥ6.9നധമ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ഒഒഒ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ഡഥ0.തന</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ഥഉശ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ര8രധ.07ഹ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ഥഉശ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>റമക.ധര3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>കഋഥ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ര8രധ.07ഹ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>കഋഥ</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ഥ46.ഥജ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>ഗഋഉ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ര8രധ.07ഹ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ചരഒ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ഴഡ0ഥ6.9നധമ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ഒഒഒ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ႺႮ0Ⴑ6.9ႵႴႶ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ႠႠႠ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ႮႱ0.ႰႵ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ႱႨႽ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Ⴗ8ႷႴ.07Ⴟ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ႱႨႽ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>ႸႶႡ.ႴႷ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ႡႤႱ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Ⴗ8ႷႴ.07Ⴟ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ႡႤႱ</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0Ⴑ46.ႱႫ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>ႦႤႨ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Ⴗ8ႷႴ.07Ⴟ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ႩႷႠ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ႺႮ0Ⴑ6.9ႵႴႶ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ႠႠႠ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>モス0ト6.9ヒヌフ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>アアア</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>スト0.チヒ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>トエラ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ヘ8ヘヌ.07ヲ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>トエラ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>ホフカ.ヌヘ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>カオト</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ヘ8ヘヌ.07ヲ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>カオト</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ト46.トコ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>クオエ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ヘ8ヘヌ.07ヲ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ケヘア</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>モス0ト6.9ヒヌフ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>アアア</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ลช0ด6.9ธทบ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ะะะ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ชด0.ฑธ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ดฬอ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ผ8ผท.07ฯ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ดฬอ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>มบก.ทผ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>กาด</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ผ8ผท.07ฯ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>กาด</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ด46.ดจ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>คาฬ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ผ8ผท.07ฯ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>งผะ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ลช0ด6.9ธทบ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ะะะ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ວຍ0ທ6.9ຜບພ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ະະະ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ຍທ0.ດຜ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ທຽຫ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ມ8ມບ.07ຯ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ທຽຫ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>ຢພກ.ບມ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ກໃທ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ມ8ມບ.07ຯ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ກໃທ</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ທ46.ທຈ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>ຄໃຽ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ມ8ມບ.07ຯ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ງມະ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ວຍ0ທ6.9ຜບພ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ະະະ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ՏԽ0Հ6.9ՇՃՈ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ՖՖՖ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ԽՀ0.ԿՇ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ՀՅՑ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Պ8ՊՃ.07Փ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ՀՅՑ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>ՍՈԲ.ՃՊ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ԲԵՀ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Պ8ՊՃ.07Փ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ԲԵՀ</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0Հ46.ՀԹ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>ԴԵՅ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Պ8ՊՃ.07Փ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ԸՊՖ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ՏԽ0Հ6.9ՇՃՈ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ՖՖՖ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>বঝ0ড6.9তণথ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>অঅঅ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ঝড0.ঠত</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ডওয</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>দ8দণ.07হ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ডওয</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>নথঌ.ণদ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ঌএড</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>দ8দণ.07হ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ঌএড</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ড46.ডঙ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>খএও</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>দ8দণ.07হ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>গদঅ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>বঝ0ড6.9তণথ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>অঅঅ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ਲਠ0ਤ6.9ਨਧਪ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ਅਅਅ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ਠਤ0.ਣਨ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ਤਫਸ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ਭ8ਭਧ.07ਡ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ਤਫਸ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>ਮਪਕ.ਧਭ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ਕਏਤ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ਭ8ਭਧ.07ਡ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ਕਏਤ</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ਤ46.ਤਜ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>ਘਏਫ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ਭ8ਭਧ.07ਡ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ਚਭਅ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ਲਠ0ਤ6.9ਨਧਪ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ਅਅਅ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ཟཇ0ཌ6.9དཏན</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>མམམ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ཇཌ0.ཊད</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ཌཥར</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>པ8པཏ.07ས</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ཌཥར</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>བནཀ.ཏཔ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ཀཤཌ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>པ8པཏ.07ས</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ཀཤཌ</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ཌ46.ཌཅ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>གཤཥ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>པ8པཏ.07ས</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ངཔམ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ཟཇ0ཌ6.9དཏན</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>མམམ</territoryInAlphabet></mapcode></mapcodes></mapcodes>"
};
}
| src/test/java/com/mapcode/services/ApiResourcesTest.java | /*
* Copyright (C) 2016 Stichting Mapcode Foundation (http://www.mapcode.com)
*
* 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.mapcode.services;
import com.mapcode.Alphabet;
import com.mapcode.services.implementation.MapcodeResourceImpl;
import com.mapcode.services.implementation.RootResourceImpl;
import com.mapcode.services.implementation.SystemMetricsImpl;
import com.tomtom.speedtools.maven.MavenProperties;
import com.tomtom.speedtools.rest.Reactor;
import com.tomtom.speedtools.rest.ResourceProcessor;
import com.tomtom.speedtools.testutils.akka.SimpleExecutionContext;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.ExecutionContext;
import javax.annotation.Nonnull;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@SuppressWarnings("JUnitTestMethodWithNoAssertions")
public class ApiResourcesTest {
private static final Logger LOG = LoggerFactory.getLogger(ApiResourcesTest.class);
private static final String TEST_POM_VERSION = "TEST-1";
private static final Double TEST_LAT1 = 50.141706;
private static final Double TEST_LON1 = 6.135864;
private static final String TEST_LATLON1 = TEST_LAT1 + "," + TEST_LON1;
private static final Double TEST_LAT2 = 52.159853;
private static final Double TEST_LON2 = 4.499790;
private static final String TEST_LATLON2 = TEST_LAT2 + "," + TEST_LON2;
private static final String TEST_CODE1 = "VJ0L6.9PNQ";
private static final String TEST_CODE2 = "JL0.KP";
private static final String TEST_CONTEXT2 = "LUX";
private static final int PORT = 8081;
private static final String HOST = "http://localhost:" + PORT;
private TJWSEmbeddedJaxrsServer server;
@Before
public void startServer() {
server = new TJWSEmbeddedJaxrsServer();
server.setPort(PORT);
// Create a simple ResourceProcessor, required for implementation of REST service using the SpeedTools framework.
final Reactor reactor = new Reactor() {
@Nonnull
@Override
public ExecutionContext getExecutionContext() {
return SimpleExecutionContext.getInstance();
}
// This method is stubbed and never used.
@Nonnull
@Override
public DateTime getSystemStartupTime() {
return new DateTime();
}
// This method is stubbed and never used.
@Nonnull
@Override
public <T> T createTopLevelActor(@Nonnull final Class<T> interfaceClass, @Nonnull final Class<? extends T> implementationClass, @Nonnull Object... explicitParameters) {
assert false;
return null;
}
};
final ResourceProcessor resourceProcessor = new ResourceProcessor(reactor);
// Add root resource.
server.getDeployment().getResources().add(new RootResourceImpl(
new MavenProperties(TEST_POM_VERSION),
new SystemMetricsImpl()
));
// Add mapcode resource.
server.getDeployment().getResources().add(new MapcodeResourceImpl(
resourceProcessor,
new SystemMetricsImpl()
));
server.start();
}
@After
public void stopServer() {
server.stop();
}
@Test
public void checkStatus() {
LOG.info("checkStatus");
final Response r = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/version").
request().
get();
Assert.assertNotNull(r);
final int status = r.getStatus();
LOG.info("status = {}", status);
Assert.assertEquals(200, status);
}
@Test
public void checkVersionJson() {
LOG.info("checkVersionJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/version").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"version\":\"TEST-1\"}",
response.readEntity(String.class));
}
@Test
public void checkVersionXml() {
LOG.info("checkVersionXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/version").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><version><version>TEST-1</version></version>",
response.readEntity(String.class));
}
@Test
public void checkCodesJson() {
LOG.info("checkCodesJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1).
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"territory\":\"LUX\"},{\"mapcode\":\"R8RN.07Z\",\"territory\":\"LUX\"},{\"mapcode\":\"SQB.NR3\",\"territory\":\"BEL\"},{\"mapcode\":\"R8RN.07Z\",\"territory\":\"BEL\"},{\"mapcode\":\"0L46.LG9\",\"territory\":\"DEU\"},{\"mapcode\":\"R8RN.07Z\",\"territory\":\"FRA\"},{\"mapcode\":\"VJ0L6.9PNQ\"}]}",
response.readEntity(String.class));
}
@Test
public void checkCodesXml() {
LOG.info("checkCodesXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1).
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>SQB.NR3</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>0L46.LG9</mapcode><territory>DEU</territory></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><territory>FRA</territory></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode></mapcode></mapcodes></mapcodes>",
response.readEntity(String.class));
}
@Test
public void checkCodesPrecision0Json() {
LOG.info("checkCodesPrecision0Json");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?precision=0").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"territory\":\"LUX\"},{\"mapcode\":\"R8RN.07Z\",\"territory\":\"LUX\"},{\"mapcode\":\"SQB.NR3\",\"territory\":\"BEL\"},{\"mapcode\":\"R8RN.07Z\",\"territory\":\"BEL\"},{\"mapcode\":\"0L46.LG9\",\"territory\":\"DEU\"},{\"mapcode\":\"R8RN.07Z\",\"territory\":\"FRA\"},{\"mapcode\":\"VJ0L6.9PNQ\"}]}",
response.readEntity(String.class));
}
@Test
public void checkCodesPrecision0Xml() {
LOG.info("checkCodesPrecision0Xml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?precision=0").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>SQB.NR3</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>0L46.LG9</mapcode><territory>DEU</territory></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><territory>FRA</territory></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode></mapcode></mapcodes></mapcodes>",
response.readEntity(String.class));
}
@Test
public void checkCodesPrecision1Json() {
LOG.info("checkCodesPrecision1Json");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?precision=1").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"international\":{\"mapcode\":\"VJ0L6.9PNQ-0\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP-8\",\"territory\":\"LUX\"},{\"mapcode\":\"R8RN.07Z-M\",\"territory\":\"LUX\"},{\"mapcode\":\"SQB.NR3-P\",\"territory\":\"BEL\"},{\"mapcode\":\"R8RN.07Z-M\",\"territory\":\"BEL\"},{\"mapcode\":\"0L46.LG9-Q\",\"territory\":\"DEU\"},{\"mapcode\":\"R8RN.07Z-M\",\"territory\":\"FRA\"},{\"mapcode\":\"VJ0L6.9PNQ-0\"}]}",
response.readEntity(String.class));
}
@Test
public void checkCodesPrecision1Xml() {
LOG.info("checkCodesPrecision1Xml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?precision=1").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ-0</mapcode></international><mapcodes><mapcode><mapcode>JL0.KP-8</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>R8RN.07Z-M</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>SQB.NR3-P</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>R8RN.07Z-M</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>0L46.LG9-Q</mapcode><territory>DEU</territory></mapcode><mapcode><mapcode>R8RN.07Z-M</mapcode><territory>FRA</territory></mapcode><mapcode><mapcode>VJ0L6.9PNQ-0</mapcode></mapcode></mapcodes></mapcodes>",
response.readEntity(String.class));
}
@Test
public void checkCodesPrecision8Json() {
LOG.info("checkCodesPrecision8Json");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?precision=8").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"international\":{\"mapcode\":\"VJ0L6.9PNQ-03Q7CGV4\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP-81B34315\",\"territory\":\"LUX\"},{\"mapcode\":\"R8RN.07Z-MWPCRQBK\",\"territory\":\"LUX\"},{\"mapcode\":\"SQB.NR3-P6880000\",\"territory\":\"BEL\"},{\"mapcode\":\"R8RN.07Z-MWPCRQBK\",\"territory\":\"BEL\"},{\"mapcode\":\"0L46.LG9-QWPVQVRW\",\"territory\":\"DEU\"},{\"mapcode\":\"R8RN.07Z-MWPCRQBK\",\"territory\":\"FRA\"},{\"mapcode\":\"VJ0L6.9PNQ-03Q7CGV4\"}]}",
response.readEntity(String.class));
}
@Test
public void checkCodesPrecision8Xml() {
LOG.info("checkCodesPrecision8Xml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?precision=8").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ-03Q7CGV4</mapcode></international><mapcodes><mapcode><mapcode>JL0.KP-81B34315</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>R8RN.07Z-MWPCRQBK</mapcode><territory>LUX</territory></mapcode><mapcode><mapcode>SQB.NR3-P6880000</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>R8RN.07Z-MWPCRQBK</mapcode><territory>BEL</territory></mapcode><mapcode><mapcode>0L46.LG9-QWPVQVRW</mapcode><territory>DEU</territory></mapcode><mapcode><mapcode>R8RN.07Z-MWPCRQBK</mapcode><territory>FRA</territory></mapcode><mapcode><mapcode>VJ0L6.9PNQ-03Q7CGV4</mapcode></mapcode></mapcodes></mapcodes>",
response.readEntity(String.class));
}
@Test
public void checkCodesLocalJson() {
LOG.info("checkCodesLocalJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON2 + "/local").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"mapcode\":\"QKM.N4\",\"territory\":\"NLD\"}",
response.readEntity(String.class));
}
@Test
public void checkCodesLocalXml() {
LOG.info("checkCodesLocalXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON2 + "/local").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcode><mapcode>QKM.N4</mapcode><territory>NLD</territory></mapcode>",
response.readEntity(String.class));
}
@Test
public void checkCodesInternationalJson() {
LOG.info("checkCodesInternationalJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "/International").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"mapcode\":\"VJ0L6.9PNQ\"}",
response.readEntity(String.class));
}
@Test
public void checkCodesInternationalXml() {
LOG.info("checkCodesInternationalXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "/International").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcode><mapcode>VJ0L6.9PNQ</mapcode></mapcode>",
response.readEntity(String.class));
}
@Test
public void checkCodesIncludeJson() {
LOG.info("checkCodesIncludeJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON2 + "?include=offset,territory,alphabet").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"local\":{\"mapcode\":\"QKM.N4\",\"mapcodeInAlphabet\":\"QKM.N4\",\"territory\":\"NLD\",\"territoryInAlphabet\":\"NLD\",\"offsetMeters\":2.843693},\"international\":{\"mapcode\":\"VHVN4.YZ74\",\"mapcodeInAlphabet\":\"VHVN4.YZ74\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"AAA\",\"offsetMeters\":1.907245},\"mapcodes\":[{\"mapcode\":\"QKM.N4\",\"mapcodeInAlphabet\":\"QKM.N4\",\"territory\":\"NLD\",\"territoryInAlphabet\":\"NLD\",\"offsetMeters\":2.843693},{\"mapcode\":\"CZQ.376\",\"mapcodeInAlphabet\":\"CZQ.376\",\"territory\":\"NLD\",\"territoryInAlphabet\":\"NLD\",\"offsetMeters\":5.004936},{\"mapcode\":\"N39J.QW0\",\"mapcodeInAlphabet\":\"N39J.QW0\",\"territory\":\"NLD\",\"territoryInAlphabet\":\"NLD\",\"offsetMeters\":2.836538},{\"mapcode\":\"VHVN4.YZ74\",\"mapcodeInAlphabet\":\"VHVN4.YZ74\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"AAA\",\"offsetMeters\":1.907245}]}",
response.readEntity(String.class));
}
@Test
public void checkCodesIncludeXml() {
LOG.info("checkCodesIncludeXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON2 + "?include=offset,territory,alphabet").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><local><mapcode>QKM.N4</mapcode><mapcodeInAlphabet>QKM.N4</mapcodeInAlphabet><territory>NLD</territory><territoryInAlphabet>NLD</territoryInAlphabet><offsetMeters>2.843693</offsetMeters></local><international><mapcode>VHVN4.YZ74</mapcode><mapcodeInAlphabet>VHVN4.YZ74</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>AAA</territoryInAlphabet><offsetMeters>1.907245</offsetMeters></international><mapcodes><mapcode><mapcode>QKM.N4</mapcode><mapcodeInAlphabet>QKM.N4</mapcodeInAlphabet><territory>NLD</territory><territoryInAlphabet>NLD</territoryInAlphabet><offsetMeters>2.843693</offsetMeters></mapcode><mapcode><mapcode>CZQ.376</mapcode><mapcodeInAlphabet>CZQ.376</mapcodeInAlphabet><territory>NLD</territory><territoryInAlphabet>NLD</territoryInAlphabet><offsetMeters>5.004936</offsetMeters></mapcode><mapcode><mapcode>N39J.QW0</mapcode><mapcodeInAlphabet>N39J.QW0</mapcodeInAlphabet><territory>NLD</territory><territoryInAlphabet>NLD</territoryInAlphabet><offsetMeters>2.836538</offsetMeters></mapcode><mapcode><mapcode>VHVN4.YZ74</mapcode><mapcodeInAlphabet>VHVN4.YZ74</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>AAA</territoryInAlphabet><offsetMeters>1.907245</offsetMeters></mapcode></mapcodes></mapcodes>",
response.readEntity(String.class));
}
private void doCheckJson(@Nonnull final String alphabet, @Nonnull final String expected) {
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?include=territory,alphabet&alphabet=" + alphabet).
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(expected, response.readEntity(String.class));
}
@Test
public void checkCoords1Json() {
LOG.info("checkCoords1Json");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/coords/" + TEST_CODE1).
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"latDeg\":50.141726,\"lonDeg\":6.1358875}",
response.readEntity(String.class));
}
@Test
public void checkCoords1Xml() {
LOG.info("checkCoords1Xml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/coords/" + TEST_CODE1).
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><point><latDeg>50.141726</latDeg><lonDeg>6.1358875</lonDeg></point>",
response.readEntity(String.class));
}
@Test
public void checkCoords2Json() {
LOG.info("checkCoords2Json");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/coords/" + TEST_CODE2 + "?context=" + TEST_CONTEXT2).
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"latDeg\":50.141735,\"lonDeg\":6.135845}",
response.readEntity(String.class));
}
@Test
public void checkCoords2Xml() {
LOG.info("checkCoords2Xml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/coords/" + TEST_CODE2 + "?context=" + TEST_CONTEXT2).
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><point><latDeg>50.141735</latDeg><lonDeg>6.135845</lonDeg></point>",
response.readEntity(String.class));
}
@Test
public void checkTerritoriesJson() {
LOG.info("checkTerritoriesJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/territories").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
final String r = response.readEntity(String.class);
LOG.info("response={} chars, body=\n{}", r.length(), r);
Assert.assertTrue(r.length() > 500);
final String sub1 = r.substring(0, 500);
final String sub2 = r.substring(r.length() - 500, r.length());
Assert.assertEquals("{\"territories\":[{\"aliases\":[\"US\"],\"fullNameAliases\":[\"United States of America\",\"America\"],\"alphaCode\":\"USA\",\"alphaCodeMinimalUnambiguous\":\"USA\",\"alphaCodeMinimal\":\"USA\",\"fullName\":\"USA\"},{\"aliases\":[\"IN\"],\"alphaCode\":\"IND\",\"alphaCodeMinimalUnambiguous\":\"IND\",\"alphaCodeMinimal\":\"IND\",\"fullName\":\"India\"},{\"aliases\":[\"CA\"],\"alphaCode\":\"CAN\",\"alphaCodeMinimalUnambiguous\":\"CAN\",\"alphaCodeMinimal\":\"CAN\",\"fullName\":\"Canada\"},{\"aliases\":[\"AU\"],\"alphaCode\":\"AUS\",\"alphaCodeMinimalUnambiguous\":\"AUS\",\"alph",
sub1);
Assert.assertEquals("aCodeMinimal\":\"XJ\",\"fullName\":\"Xinjiang Uyghur\",\"parentTerritory\":\"CHN\"},{\"aliases\":[\"US-UM\",\"USA-UM\",\"JTN\"],\"alphaCode\":\"UMI\",\"alphaCodeMinimalUnambiguous\":\"UMI\",\"alphaCodeMinimal\":\"UMI\",\"fullName\":\"United States Minor Outlying Islands\"},{\"alphaCode\":\"CPT\",\"alphaCodeMinimalUnambiguous\":\"CPT\",\"alphaCodeMinimal\":\"CPT\",\"fullName\":\"Clipperton Island\"},{\"fullNameAliases\":[\"Worldwide\",\"Earth\"],\"alphaCode\":\"AAA\",\"alphaCodeMinimalUnambiguous\":\"AAA\",\"alphaCodeMinimal\":\"AAA\",\"fullName\":\"International\"}]}",
sub2);
}
@Test
public void checkTerritoriesXml() {
LOG.info("checkTerritoriesXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/territories").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
final String r = response.readEntity(String.class);
LOG.info("response={} chars, body=\n{}", r.length(), r);
Assert.assertTrue(r.length() > 500);
final String sub1 = r.substring(0, 500);
final String sub2 = r.substring(r.length() - 500, r.length());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><territories><territory><alphaCode>USA</alphaCode><alphaCodeMinimalUnambiguous>USA</alphaCodeMinimalUnambiguous><alphaCodeMinimal>USA</alphaCodeMinimal><fullName>USA</fullName><aliases><alias>US</alias></aliases><fullNameAliases><fullNameAlias>United States of America</fullNameAlias><fullNameAlias>America</fullNameAlias></fullNameAliases></territory><territory><alphaCode>IND</alphaCode><alphaCodeMinimalUnambiguous>IND</alphaCodeMinimalUnambi",
sub1);
Assert.assertEquals("<alphaCodeMinimalUnambiguous>CPT</alphaCodeMinimalUnambiguous><alphaCodeMinimal>CPT</alphaCodeMinimal><fullName>Clipperton Island</fullName><aliases/><fullNameAliases/></territory><territory><alphaCode>AAA</alphaCode><alphaCodeMinimalUnambiguous>AAA</alphaCodeMinimalUnambiguous><alphaCodeMinimal>AAA</alphaCodeMinimal><fullName>International</fullName><aliases/><fullNameAliases><fullNameAlias>Worldwide</fullNameAlias><fullNameAlias>Earth</fullNameAlias></fullNameAliases></territory></territories>",
sub2);
}
@Test
public void checkTerritoryJson() {
LOG.info("checkTerritoryJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/territories/nld").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"alphaCode\":\"NLD\",\"alphaCodeMinimalUnambiguous\":\"NLD\",\"alphaCodeMinimal\":\"NLD\",\"fullName\":\"Netherlands\"}",
response.readEntity(String.class));
}
@Test
public void checkTerritoryXml() {
LOG.info("checkTerritoryXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/territories/nld").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><territory><alphaCode>NLD</alphaCode><alphaCodeMinimalUnambiguous>NLD</alphaCodeMinimalUnambiguous><alphaCodeMinimal>NLD</alphaCodeMinimal><fullName>Netherlands</fullName><aliases/><fullNameAliases/></territory>",
response.readEntity(String.class));
}
@Test
public void checkAlphabetsJson() {
LOG.info("checkAlphabetsJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"alphabets\":[{\"name\":\"ROMAN\"},{\"name\":\"GREEK\"},{\"name\":\"CYRILLIC\"},{\"name\":\"HEBREW\"},{\"name\":\"HINDI\"},{\"name\":\"MALAY\"},{\"name\":\"GEORGIAN\"},{\"name\":\"KATAKANA\"},{\"name\":\"THAI\"},{\"name\":\"LAO\"},{\"name\":\"ARMENIAN\"},{\"name\":\"BENGALI\"},{\"name\":\"GURMUKHI\"},{\"name\":\"TIBETAN\"}]}",
response.readEntity(String.class));
}
@Test
public void checkAlphabetsCountJson() {
LOG.info("checkAlphabetsCountJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets?count=2").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"alphabets\":[{\"name\":\"ROMAN\"},{\"name\":\"GREEK\"}]}",
response.readEntity(String.class));
}
@Test
public void checkAlphabetsCountXml() {
LOG.info("checkAlphabetsCountXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets?count=2").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><alphabets><alphabet><name>ROMAN</name></alphabet><alphabet><name>GREEK</name></alphabet></alphabets>",
response.readEntity(String.class));
}
@Test
public void checkAlphabetsCountOffsetJson() {
LOG.info("checkAlphabetsCountOffsetJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets?count=1&offset=1").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"alphabets\":[{\"name\":\"GREEK\"}]}",
response.readEntity(String.class));
}
@Test
public void checkAlphabetsCountOffsetXml() {
LOG.info("checkAlphabetsCountOffsetXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets?count=1&offset=1").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><alphabets><alphabet><name>GREEK</name></alphabet></alphabets>",
response.readEntity(String.class));
}
@Test
public void checkAlphabetsCountOffsetFromEndJson() {
LOG.info("checkAlphabetsCountOffsetFromEndJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets?count=1&offset=-1").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"alphabets\":[{\"name\":\"TIBETAN\"}]}",
response.readEntity(String.class));
}
@Test
public void checkAlphabetsCountOffsetFromEndXml() {
LOG.info("checkAlphabetsCountOffsetXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets?count=1&offset=-1").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><alphabets><alphabet><name>TIBETAN</name></alphabet></alphabets>",
response.readEntity(String.class));
}
@Test
public void checkAlphabetJson() {
LOG.info("checkAlphabetJson");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets/greek").
request().
accept(MediaType.APPLICATION_JSON_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("{\"name\":\"GREEK\"}",
response.readEntity(String.class));
}
@Test
public void checkAlphabetXml() {
LOG.info("checkAlphabetXml");
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/alphabets/greek").
request().
accept(MediaType.APPLICATION_XML_TYPE).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><alphabet><name>GREEK</name></alphabet>",
response.readEntity(String.class));
}
@Test
public void checkAllAlphabetsJson() {
LOG.info("checkAlphabetsJson");
int i = 0;
for (final Alphabet alphabet : Alphabet.values()) {
doCheckAlphabet(alphabet.name(), MediaType.APPLICATION_JSON_TYPE, EXPECTED_ALPHABETS_JSON[i]);
++i;
}
}
@Test
public void checkAllAlphabetsXml() {
LOG.info("checkAlphabetsXml");
int i = 0;
for (final Alphabet alphabet : Alphabet.values()) {
doCheckAlphabet(alphabet.name(), MediaType.APPLICATION_XML_TYPE, EXPECTED_ALPHABETS_XML[i]);
++i;
}
}
private static void doCheckAlphabet(
@Nonnull final String alphabet,
@Nonnull final MediaType mediaType,
@Nonnull final String expected) {
LOG.info("doCheckAlphabet: alphabet={}, mediaType={}", alphabet, mediaType);
final Response response = new ResteasyClientBuilder().build().
target(HOST + "/mapcode/codes/" + TEST_LATLON1 + "?include=territory,alphabet&alphabet=" + alphabet).
request().
accept(mediaType).get();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(expected, response.readEntity(String.class));
}
private final static String[] EXPECTED_ALPHABETS_JSON = {
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"VJ0L6.9PNQ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"AAA\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"JL0.KP\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"LUX\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"R8RN.07Z\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"LUX\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"SQB.NR3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"BEL\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"R8RN.07Z\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"BEL\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0L46.LG9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"DEU\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"R8RN.07Z\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"FRA\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"VJ0L6.9PNQ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"AAA\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ΦΠ0Λ6.9ΡΝΘ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ΑΑΑ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ΠΛ0.ΚΡ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"LUX\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Ψ8ΨΝ.07Ζ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"LUX\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"ΣΘΒ.ΝΨ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"BEL\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Ψ8ΨΝ.07Ζ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"BEL\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0Λ46.ΛΓ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"DEU\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Ψ8ΨΝ.07Ζ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ΕΨΑ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ΦΠ0Λ6.9ΡΝΘ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ΑΑΑ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ЧП0Л6.9РЗФ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ААА\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ПЛ0.КР\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ЛЭХ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Я8ЯЗ.07Б\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ЛЭХ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"ЦФВ.ЗЯ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ВЕЛ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Я8ЯЗ.07Б\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ВЕЛ\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0Л46.ЛГ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"ДЕЭ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Я8ЯЗ.07Б\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ЖЯА\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ЧП0Л6.9РЗФ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ААА\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"צט0ך6.9םלמ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"אאא\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"טך0.ים\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ךץר\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"נ8נל.07ת\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ךץר\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"עמב.לנ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"בףך\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"נ8נל.07ת\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"בףך\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ך46.ךז9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"דףץ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"נ8נל.07ת\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"הנא\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"צט0ך6.9םלמ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"אאא\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"लठ0त6.9नधप\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"अअअ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ठत0.णन\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"तफस\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"भ8भध.07ड\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"तफस\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"मपक.धभ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"कएत\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"भ8भध.07ड\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"कएत\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0त46.तज9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"घएफ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"भ8भध.07ड\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"चभअ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"लठ0त6.9नधप\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"अअअ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ഴഡ0ഥ6.9നധമ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ഒഒഒ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ഡഥ0.തന\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ഥഉശ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ര8രധ.07ഹ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ഥഉശ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"റമക.ധര3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"കഋഥ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ര8രധ.07ഹ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"കഋഥ\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ഥ46.ഥജ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"ഗഋഉ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ര8രധ.07ഹ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ചരഒ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ഴഡ0ഥ6.9നധമ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ഒഒഒ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ႺႮ0Ⴑ6.9ႵႴႶ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ႠႠႠ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ႮႱ0.ႰႵ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ႱႨႽ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Ⴗ8ႷႴ.07Ⴟ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ႱႨႽ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"ႸႶႡ.ႴႷ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ႡႤႱ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Ⴗ8ႷႴ.07Ⴟ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ႡႤႱ\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0Ⴑ46.ႱႫ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"ႦႤႨ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Ⴗ8ႷႴ.07Ⴟ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ႩႷႠ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ႺႮ0Ⴑ6.9ႵႴႶ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ႠႠႠ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"モス0ト6.9ヒヌフ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"アアア\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"スト0.チヒ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"トエラ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ヘ8ヘヌ.07ヲ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"トエラ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"ホフカ.ヌヘ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"カオト\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ヘ8ヘヌ.07ヲ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"カオト\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ト46.トコ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"クオエ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ヘ8ヘヌ.07ヲ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ケヘア\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"モス0ト6.9ヒヌフ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"アアア\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ลช0ด6.9ธทบ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ะะะ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ชด0.ฑธ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ดฬอ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ผ8ผท.07ฯ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ดฬอ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"มบก.ทผ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"กาด\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ผ8ผท.07ฯ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"กาด\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ด46.ดจ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"คาฬ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ผ8ผท.07ฯ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"งผะ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ลช0ด6.9ธทบ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ะะะ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ວຍ0ທ6.9ຜບພ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ະະະ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ຍທ0.ດຜ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ທຽຫ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ມ8ມບ.07ຯ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ທຽຫ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"ຢພກ.ບມ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ກໃທ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ມ8ມບ.07ຯ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ກໃທ\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ທ46.ທຈ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"ຄໃຽ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ມ8ມບ.07ຯ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ງມະ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ວຍ0ທ6.9ຜບພ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ະະະ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ՏԽ0Հ6.9ՇՃՈ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ՖՖՖ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ԽՀ0.ԿՇ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ՀՅՑ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Պ8ՊՃ.07Փ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ՀՅՑ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"ՍՈԲ.ՃՊ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ԲԵՀ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Պ8ՊՃ.07Փ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ԲԵՀ\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0Հ46.ՀԹ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"ԴԵՅ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"Պ8ՊՃ.07Փ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ԸՊՖ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ՏԽ0Հ6.9ՇՃՈ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ՖՖՖ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"বঝ0ড6.9তণথ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"অঅঅ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ঝড0.ঠত\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ডওয\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"দ8দণ.07হ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ডওয\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"নথঌ.ণদ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ঌএড\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"দ8দণ.07হ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ঌএড\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ড46.ডঙ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"খএও\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"দ8দণ.07হ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"গদঅ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"বঝ0ড6.9তণথ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"অঅঅ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ਲਠ0ਤ6.9ਨਧਪ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ਅਅਅ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ਠਤ0.ਣਨ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ਤਫਸ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ਭ8ਭਧ.07ਡ\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ਤਫਸ\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"ਮਪਕ.ਧਭ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ਕਏਤ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ਭ8ਭਧ.07ਡ\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ਕਏਤ\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ਤ46.ਤਜ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"ਘਏਫ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"ਭ8ਭਧ.07ਡ\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ਚਭਅ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ਲਠ0ਤ6.9ਨਧਪ\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"ਅਅਅ\"}]}",
"{\"international\":{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ཟཇ0ཌ6.9དཏན\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"མམམ\"},\"mapcodes\":[{\"mapcode\":\"JL0.KP\",\"mapcodeInAlphabet\":\"ཇཌ0.ཊད\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ཌཥར\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"པ8པཏ.07ས\",\"territory\":\"LUX\",\"territoryInAlphabet\":\"ཌཥར\"},{\"mapcode\":\"SQB.NR3\",\"mapcodeInAlphabet\":\"བནཀ.ཏཔ3\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ཀཤཌ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"པ8པཏ.07ས\",\"territory\":\"BEL\",\"territoryInAlphabet\":\"ཀཤཌ\"},{\"mapcode\":\"0L46.LG9\",\"mapcodeInAlphabet\":\"0ཌ46.ཌཅ9\",\"territory\":\"DEU\",\"territoryInAlphabet\":\"གཤཥ\"},{\"mapcode\":\"R8RN.07Z\",\"mapcodeInAlphabet\":\"པ8པཏ.07ས\",\"territory\":\"FRA\",\"territoryInAlphabet\":\"ངཔམ\"},{\"mapcode\":\"VJ0L6.9PNQ\",\"mapcodeInAlphabet\":\"ཟཇ0ཌ6.9དཏན\",\"territory\":\"AAA\",\"territoryInAlphabet\":\"མམམ\"}]}",
};
private final static String[] EXPECTED_ALPHABETS_XML = {
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>VJ0L6.9PNQ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>AAA</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>JL0.KP</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>LUX</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>R8RN.07Z</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>LUX</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>SQB.NR3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>BEL</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>R8RN.07Z</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>BEL</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0L46.LG9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>DEU</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>R8RN.07Z</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>FRA</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>VJ0L6.9PNQ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>AAA</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ΦΠ0Λ6.9ΡΝΘ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ΑΑΑ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ΠΛ0.ΚΡ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>LUX</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Ψ8ΨΝ.07Ζ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>LUX</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>ΣΘΒ.ΝΨ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>BEL</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Ψ8ΨΝ.07Ζ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>BEL</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0Λ46.ΛΓ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>DEU</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Ψ8ΨΝ.07Ζ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ΕΨΑ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ΦΠ0Λ6.9ΡΝΘ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ΑΑΑ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ЧП0Л6.9РЗФ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ААА</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ПЛ0.КР</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ЛЭХ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Я8ЯЗ.07Б</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ЛЭХ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>ЦФВ.ЗЯ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ВЕЛ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Я8ЯЗ.07Б</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ВЕЛ</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0Л46.ЛГ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>ДЕЭ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Я8ЯЗ.07Б</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ЖЯА</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ЧП0Л6.9РЗФ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ААА</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>צט0ך6.9םלמ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>אאא</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>טך0.ים</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ךץר</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>נ8נל.07ת</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ךץר</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>עמב.לנ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>בףך</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>נ8נל.07ת</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>בףך</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ך46.ךז9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>דףץ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>נ8נל.07ת</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>הנא</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>צט0ך6.9םלמ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>אאא</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>लठ0त6.9नधप</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>अअअ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ठत0.णन</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>तफस</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>भ8भध.07ड</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>तफस</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>मपक.धभ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>कएत</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>भ8भध.07ड</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>कएत</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0त46.तज9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>घएफ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>भ8भध.07ड</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>चभअ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>लठ0त6.9नधप</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>अअअ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ഴഡ0ഥ6.9നധമ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ഒഒഒ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ഡഥ0.തന</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ഥഉശ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ര8രധ.07ഹ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ഥഉശ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>റമക.ധര3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>കഋഥ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ര8രധ.07ഹ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>കഋഥ</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ഥ46.ഥജ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>ഗഋഉ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ര8രധ.07ഹ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ചരഒ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ഴഡ0ഥ6.9നധമ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ഒഒഒ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ႺႮ0Ⴑ6.9ႵႴႶ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ႠႠႠ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ႮႱ0.ႰႵ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ႱႨႽ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Ⴗ8ႷႴ.07Ⴟ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ႱႨႽ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>ႸႶႡ.ႴႷ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ႡႤႱ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Ⴗ8ႷႴ.07Ⴟ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ႡႤႱ</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0Ⴑ46.ႱႫ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>ႦႤႨ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Ⴗ8ႷႴ.07Ⴟ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ႩႷႠ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ႺႮ0Ⴑ6.9ႵႴႶ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ႠႠႠ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>モス0ト6.9ヒヌフ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>アアア</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>スト0.チヒ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>トエラ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ヘ8ヘヌ.07ヲ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>トエラ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>ホフカ.ヌヘ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>カオト</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ヘ8ヘヌ.07ヲ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>カオト</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ト46.トコ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>クオエ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ヘ8ヘヌ.07ヲ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ケヘア</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>モス0ト6.9ヒヌフ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>アアア</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ลช0ด6.9ธทบ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ะะะ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ชด0.ฑธ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ดฬอ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ผ8ผท.07ฯ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ดฬอ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>มบก.ทผ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>กาด</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ผ8ผท.07ฯ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>กาด</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ด46.ดจ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>คาฬ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ผ8ผท.07ฯ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>งผะ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ลช0ด6.9ธทบ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ะะะ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ວຍ0ທ6.9ຜບພ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ະະະ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ຍທ0.ດຜ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ທຽຫ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ມ8ມບ.07ຯ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ທຽຫ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>ຢພກ.ບມ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ກໃທ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ມ8ມບ.07ຯ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ກໃທ</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ທ46.ທຈ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>ຄໃຽ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ມ8ມບ.07ຯ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ງມະ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ວຍ0ທ6.9ຜບພ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ະະະ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ՏԽ0Հ6.9ՇՃՈ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ՖՖՖ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ԽՀ0.ԿՇ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ՀՅՑ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Պ8ՊՃ.07Փ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ՀՅՑ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>ՍՈԲ.ՃՊ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ԲԵՀ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Պ8ՊՃ.07Փ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ԲԵՀ</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0Հ46.ՀԹ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>ԴԵՅ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>Պ8ՊՃ.07Փ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ԸՊՖ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ՏԽ0Հ6.9ՇՃՈ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ՖՖՖ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>বঝ0ড6.9তণথ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>অঅঅ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ঝড0.ঠত</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ডওয</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>দ8দণ.07হ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ডওয</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>নথঌ.ণদ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ঌএড</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>দ8দণ.07হ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ঌএড</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ড46.ডঙ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>খএও</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>দ8দণ.07হ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>গদঅ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>বঝ0ড6.9তণথ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>অঅঅ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ਲਠ0ਤ6.9ਨਧਪ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ਅਅਅ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ਠਤ0.ਣਨ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ਤਫਸ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ਭ8ਭਧ.07ਡ</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ਤਫਸ</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>ਮਪਕ.ਧਭ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ਕਏਤ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ਭ8ਭਧ.07ਡ</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ਕਏਤ</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ਤ46.ਤਜ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>ਘਏਫ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>ਭ8ਭਧ.07ਡ</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ਚਭਅ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ਲਠ0ਤ6.9ਨਧਪ</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>ਅਅਅ</territoryInAlphabet></mapcode></mapcodes></mapcodes>",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mapcodes><international><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ཟཇ0ཌ6.9དཏན</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>མམམ</territoryInAlphabet></international><mapcodes><mapcode><mapcode>JL0.KP</mapcode><mapcodeInAlphabet>ཇཌ0.ཊད</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ཌཥར</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>པ8པཏ.07ས</mapcodeInAlphabet><territory>LUX</territory><territoryInAlphabet>ཌཥར</territoryInAlphabet></mapcode><mapcode><mapcode>SQB.NR3</mapcode><mapcodeInAlphabet>བནཀ.ཏཔ3</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ཀཤཌ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>པ8པཏ.07ས</mapcodeInAlphabet><territory>BEL</territory><territoryInAlphabet>ཀཤཌ</territoryInAlphabet></mapcode><mapcode><mapcode>0L46.LG9</mapcode><mapcodeInAlphabet>0ཌ46.ཌཅ9</mapcodeInAlphabet><territory>DEU</territory><territoryInAlphabet>གཤཥ</territoryInAlphabet></mapcode><mapcode><mapcode>R8RN.07Z</mapcode><mapcodeInAlphabet>པ8པཏ.07ས</mapcodeInAlphabet><territory>FRA</territory><territoryInAlphabet>ངཔམ</territoryInAlphabet></mapcode><mapcode><mapcode>VJ0L6.9PNQ</mapcode><mapcodeInAlphabet>ཟཇ0ཌ6.9དཏན</mapcodeInAlphabet><territory>AAA</territory><territoryInAlphabet>མམམ</territoryInAlphabet></mapcode></mapcodes></mapcodes>"
};
}
| Removed large logging
| src/test/java/com/mapcode/services/ApiResourcesTest.java | Removed large logging | <ide><path>rc/test/java/com/mapcode/services/ApiResourcesTest.java
<ide> Assert.assertNotNull(response);
<ide> Assert.assertEquals(200, response.getStatus());
<ide> final String r = response.readEntity(String.class);
<del> LOG.info("response={} chars, body=\n{}", r.length(), r);
<ide> Assert.assertTrue(r.length() > 500);
<ide> final String sub1 = r.substring(0, 500);
<ide> final String sub2 = r.substring(r.length() - 500, r.length());
<ide> Assert.assertNotNull(response);
<ide> Assert.assertEquals(200, response.getStatus());
<ide> final String r = response.readEntity(String.class);
<del> LOG.info("response={} chars, body=\n{}", r.length(), r);
<ide> Assert.assertTrue(r.length() > 500);
<ide> final String sub1 = r.substring(0, 500);
<ide> final String sub2 = r.substring(r.length() - 500, r.length()); |
|
JavaScript | mit | eae4d478866da062a836e785d24d075c1245baf7 | 0 | JeffreyWay/laravel-mix | let path = require('path');
let Mix = require('./Mix');
/**
* We'll fetch some Webpack config plugins here for cleanliness.
*/
module.exports.plugins = {
WebpackNotifierPlugin: require('webpack-notifier'),
WebpackOnBuildPlugin: require('on-build-webpack'),
ExtractTextPlugin: require('extract-text-webpack-plugin'),
CopyWebpackPlugin: require('copy-webpack-plugin')
}
/**
* Register the Webpack entry/output paths.
*
* @param {mixed} entry
* @param {string} output
*/
module.exports.js = (entry, output) => {
entry = new Mix.File(path.resolve(entry)).parsePath();
output = new Mix.File(output).parsePath();
if (output.isDir) {
output = new Mix.File(path.join(output.path, entry.file)).parsePath();
}
Mix.js = (Mix.js || []).concat({ entry, output, vendor: false });
return this;
};
/**
* Register vendor libs that should be extracted.
* This helps drastically with long-term caching.
*
* @param {array} libs
*/
module.exports.extract = (libs) => {
Mix.js.vendor = libs;
return this;
}
/**
* Register Sass compilation.
*
* @param {string} src
* @param {string} output
*/
module.exports.sass = (src, output) => {
return module.exports.preprocess('sass', src, output);
};
/**
* Register Less compilation.
*
* @param {string} src
* @param {string} output
*/
module.exports.less = (src, output) => {
return module.exports.preprocess('less', src, output);
};
/**
* Register a generic CSS preprocessor.
*
* @param {string} type
* @param {string} src
* @param {string} output
*/
module.exports.preprocess = (type, src, output) => {
if (Mix[type]) {
throw new Error(
`Laravel Mix Error: It looks like you've called "mix.${type}()" multiple times.
Please limit your usage to one call alone.`
);
}
src = new Mix.File(path.resolve(src)).parsePath();
output = new Mix.File(output).parsePath();
if (output.isDir) {
output = new Mix.File(
path.join(output.path, src.name + '.css')
).parsePath();
}
Mix[type] = { src, output };
Mix.cssPreprocessor = type;
return this;
};
/**
* Combine a collection of files.
*
* @param {string|array} src
* @param {string} output
*/
module.exports.combine = (src, output) => {
Mix.combine = (Mix.combine || []).concat({ src, output });
return this;
};
/**
* Copy one or more files to a new location.
*
* @param {string} from
* @param {string} to
*/
module.exports.copy = (from, to) => {
Mix.copy = (Mix.copy || []).concat({
from,
to: path.resolve(__dirname, '../../', to)
});
return this;
};
/**
* Minify the provided file.
*
* @param {string|array} src
*/
module.exports.minify = (src) => {
Mix.minify = (Mix.minify || []).concat(src);
return this;
};
/**
* Enable sourcemap support.
*/
module.exports.sourceMaps = () => {
Mix.sourcemaps = (Mix.inProduction ? '#source-map' : '#inline-source-map');
return this;
};
/**
* Enable compiled file versioning.
*/
module.exports.version = () => {
Mix.versioning.enabled = true;
return this;
};
/**
* Disable all OS notifications.
*/
module.exports.disableNotifications = () => {
Mix.notifications = false;
return this;
};
/**
* Set the temporary cache directory.
*
* @param {string} path
*/
module.exports.setCacheDirectory = (path) => {
Mix.cachePath = path;
return this;
};
module.exports.config = Mix;
module.exports.mix = module.exports;
| src/index.js | let path = require('path');
let Mix = require('./Mix');
/**
* We'll fetch some Webpack config plugins here for cleanliness.
*/
module.exports.plugins = {
WebpackNotifierPlugin: require('webpack-notifier'),
WebpackOnBuildPlugin: require('on-build-webpack'),
ExtractTextPlugin: require('extract-text-webpack-plugin'),
CopyWebpackPlugin: require('copy-webpack-plugin')
}
/**
* Register the Webpack entry/output paths.
*
* @param {mixed} entry
* @param {string} output
*/
module.exports.js = (entry, output) => {
entry = new Mix.File(path.resolve(entry)).parsePath();
output = new Mix.File(output).parsePath();
if (output.isDir) {
output = new Mix.File(path.join(output.path, entry.file)).parsePath();
}
Mix.js = (Mix.js || []).concat({ entry, output, vendor: false });
return this;
};
/**
* Register vendor libs that should be extracted.
* This helps drastically with long-term caching.
*
* @param {array} libs
*/
module.exports.extract = (libs) => {
Mix.js.vendor = libs;
return this;
}
/**
* Register Sass compilation.
*
* @param {string} src
* @param {string} output
*/
module.exports.sass = (src, output) => {
return module.exports.preprocess('sass', src, output);
};
/**
* Register Less compilation.
*
* @param {string} src
* @param {string} output
*/
module.exports.less = (src, output) => {
return module.exports.preprocess('less', src, output);
};
/**
* Register a generic CSS preprocessor.
*
* @param {string} type
* @param {string} src
* @param {string} output
*/
module.exports.preprocess = (type, src, output) => {
src = new Mix.File(path.resolve(src)).parsePath();
output = new Mix.File(output).parsePath();
if (output.isDir) {
output = new Mix.File(
path.join(output.path, src.name + '.css')
).parsePath();
}
Mix[type] = { src, output };
Mix.cssPreprocessor = type;
return this;
};
/**
* Combine a collection of files.
*
* @param {string|array} src
* @param {string} output
*/
module.exports.combine = (src, output) => {
Mix.combine = (Mix.combine || []).concat({ src, output });
return this;
};
/**
* Copy one or more files to a new location.
*
* @param {string} from
* @param {string} to
*/
module.exports.copy = (from, to) => {
Mix.copy = (Mix.copy || []).concat({
from,
to: path.resolve(__dirname, '../../', to)
});
return this;
};
/**
* Minify the provided file.
*
* @param {string|array} src
*/
module.exports.minify = (src) => {
Mix.minify = (Mix.minify || []).concat(src);
return this;
};
/**
* Enable sourcemap support.
*/
module.exports.sourceMaps = () => {
Mix.sourcemaps = (Mix.inProduction ? '#source-map' : '#inline-source-map');
return this;
};
/**
* Enable compiled file versioning.
*/
module.exports.version = () => {
Mix.versioning.enabled = true;
return this;
};
/**
* Disable all OS notifications.
*/
module.exports.disableNotifications = () => {
Mix.notifications = false;
return this;
};
/**
* Set the temporary cache directory.
*
* @param {string} path
*/
module.exports.setCacheDirectory = (path) => {
Mix.cachePath = path;
return this;
};
module.exports.config = Mix;
module.exports.mix = module.exports;
| We can only allow one mix.sass() or mix.less() request right now
| src/index.js | We can only allow one mix.sass() or mix.less() request right now | <ide><path>rc/index.js
<ide> * @param {string} output
<ide> */
<ide> module.exports.preprocess = (type, src, output) => {
<add> if (Mix[type]) {
<add> throw new Error(
<add> `Laravel Mix Error: It looks like you've called "mix.${type}()" multiple times.
<add> Please limit your usage to one call alone.`
<add> );
<add> }
<add>
<ide> src = new Mix.File(path.resolve(src)).parsePath();
<ide> output = new Mix.File(output).parsePath();
<ide> |
|
JavaScript | mit | 59e9e4d5987d2403443ae73253111ff76b38d807 | 0 | FormidableLabs/measure-text,FormidableLabs/measure-text | /* eslint-env browser */
// import memoize from "lodash.memoize";
import isFinite from "lodash.isFinite";
const globalCanvas = document.createElement("canvas");
const isNumericOnly = (string) => /^[0-9.,]+$/.test(string);
const parseUnitless = (value) => {
if (isFinite(value)) {
return value;
}
if (isNumericOnly(value)) {
return parseFloat(value);
}
return null;
};
const parseUnit = (value) => {
// http://stackoverflow.com/questions/2868947/split1px-into-1px-1-px-in-javascript
const matches = value.match(/^(\d+(?:\.\d+)?)(.*)$/);
const [, number, unit] = matches;
return { number: parseFloat(number), unit };
};
const calculateHeight = (size, lineHeight) => {
const {
number: sizeNumber,
unit: sizeUnit
} = parseUnit(size);
// If the line-height is unitless,
// multiply it by the font size.
const unitless = parseUnitless(lineHeight);
if (unitless) {
return `${sizeNumber * unitless}${sizeUnit}`;
}
// Otherwise, it's as simple as
// returning the line height.
return lineHeight;
};
const measureText = ({
text,
fontFamily,
fontSize,
lineHeight,
fontWeight = 400,
fontStyle = "normal",
canvas
}) => {
// If the user doesn't pass a reusable canvas,
// just create a new one.
if (!canvas) {
canvas = document.createElement("canvas");
}
// Set the font to get accurate metrics.
canvas.font = `${fontWeight} ${fontStyle} ${fontSize} ${fontFamily}`;
const ctx = canvas.getContext("2d");
const measure = (line) => {
return {
width: ctx.measureText(line).width,
height: calculateHeight(fontSize, lineHeight)
};
};
return Array.isArray(text)
? text.map(measure)
: measure(text);
};
export default measureText;
| src/index.js | /* eslint-env browser */
// import memoize from "lodash.memoize";
import isFinite from "lodash.isFinite";
const isNumericOnly = (string) => /^[0-9.,]+$/.test(string);
const parseUnitless = (value) => {
if (isFinite(value)) {
return value;
}
if (isNumericOnly(value)) {
return parseFloat(value);
}
return null;
};
const parseUnit = (value) => {
// http://stackoverflow.com/questions/2868947/split1px-into-1px-1-px-in-javascript
const matches = value.match(/^(\d+(?:\.\d+)?)(.*)$/);
const [, number, unit] = matches;
return { number: parseFloat(number), unit };
};
const calculateHeight = (size, lineHeight) => {
const {
number: sizeNumber,
unit: sizeUnit
} = parseUnit(size);
// If the line-height is unitless,
// multiply it by the font size.
const unitless = parseUnitless(lineHeight);
if (unitless) {
return `${sizeNumber * unitless}${sizeUnit}`;
}
// Otherwise, it's as simple as
// returning the line height.
return lineHeight;
};
const measureText = ({
text,
fontFamily,
fontSize,
lineHeight,
fontWeight = 400,
fontStyle = "normal",
canvas
}) => {
// If the user doesn't pass a reusable canvas,
// just create a new one.
if (!canvas) {
canvas = document.createElement("canvas");
}
// Set the font to get accurate metrics.
canvas.font = `${fontWeight} ${fontStyle} ${fontSize} ${fontFamily}`;
const ctx = canvas.getContext("2d");
const measure = (line) => {
return {
width: ctx.measureText(line).width,
height: calculateHeight(fontSize, lineHeight)
};
};
return Array.isArray(text)
? text.map(measure)
: measure(text);
};
export default measureText;
| Use a global canvas if none is provided
| src/index.js | Use a global canvas if none is provided | <ide><path>rc/index.js
<ide> /* eslint-env browser */
<ide> // import memoize from "lodash.memoize";
<ide> import isFinite from "lodash.isFinite";
<add>
<add>const globalCanvas = document.createElement("canvas");
<ide>
<ide> const isNumericOnly = (string) => /^[0-9.,]+$/.test(string);
<ide> |
|
JavaScript | apache-2.0 | 52ba0789b045f9fd145f1fceeda6bd467f029439 | 0 | dreemproject/dreemgl,teem2/dreemgl,dreemproject/dreemgl,teem2/dreemgl,teem2/dreemgl,dreemproject/dreemgl,dreemproject/dreemgl,dreemproject/dreemgl,teem2/dreemgl,teem2/dreemgl | define.class('$server/composition', function vectormap(require, $server$, fileio,$ui$, numberbox, button, menubar, label, screen, view, foldcontainer, speakergrid,checkbox, icon, $widgets$, colorpicker, jsviewer, radiogroup){
define.class(this, "mainscreen", function($ui$, view){
define.class(this, "tiledmap", function($ui$, view){
var earcut = require('$system/lib/earcut-port.js')().earcut;
function arctotriangles(arc){
if (!arc) return [];
var verts = [];
var flatverts = [];
var A0 = arc[0];
var nx = A0[0];
var ny = A0[1];
flatverts.push(nx);
flatverts.push(ny);
for (var i =1 ;i<arc.length;i++){
var A = arc[i];
nx += A[0];
ny += A[1];
flatverts.push(nx);
flatverts.push(ny);
}
var triangles = earcut(flatverts);
for(var i = 0;i<triangles.length;i++){
idx = triangles[i];
verts.push(vec2(flatverts[idx*2],flatverts[idx*2 + 1]));
}
return verts;
}
define.class(this, "building", function($ui$, view){
this.attributes = {
buildings:[],
scalefactor: 1.0
}
this.boundscheck = false;
this.onbuildings = function(){
this.pickrange = this.buildings.length;
//console.log("setting pickrange:", this.pickrange);
}
this.mouseover = function(){
var building = this.buildings[this.last_pick_id ];
if (building){
var text = "Building";
//console.log(building);
if (building.kind) text += " " + building.kind;
if (building.name) text += " " + building.name;
if (building.street) text += " " + building.street;
if (building.housenumber) text += " " + building.housenumber;
this.screen.status = text;
}
else{
console.log(this.last_pick_id);
}
}
this.bg = function(){
this.vertexstruct = define.struct({
pos:vec3,
color:vec4,
id: float
})
this.mesh = this.vertexstruct.array();
this.color = function(){
PickGuid = mesh.id;
return mesh.color;
}
this.update = function(){
this.mesh = this.vertexstruct.array();
for(var i = 0;i<this.view.buildings.length;i++){
var building = this.view.buildings[i];
var theH = building.h;
var isofac =0
var isox = (theH*0.5)*isofac
var isoy = (theH)*isofac
if (building.arcs)
for(var j = 0;j<building.arcs.length;j++){
var arc = building.arcs[j];
var tris = arctotriangles(arc);
var A1 = vec2(arc[0][0], arc[0][1])
var OA1 = A1;
var c = 0.3;
for(var a = 1;a<arc.length+1;a++)
{
var ca = arc[a%arc.length];
var A2 = vec2(A1[0] + ca[0], A1[1] + ca[1]);
if (a == arc.length){
A2[1] -= OA1[1];
A2[0] -= OA1[0];
}
c = 0.7 + 0.3 *Math.sin(Math.atan2(A2[1]-A1[1], A2[0]-A1[0]));
this.mesh.push(A1[0],A1[1],0, c,c,c, 1, i);
this.mesh.push(A2[0],A2[1],0, c,c,c, 1, i);
this.mesh.push(A2[0]+isox,A2[1]+isoy,theH, c,c,c, 1, i);
this.mesh.push(A1[0],A1[1],0, c,c,c, 1, i);
this.mesh.push(A2[0]+isox,A2[1]+isoy,theH, c,c,c, 1, i);
this.mesh.push(A1[0]+isox,A1[1]+isoy,theH, c,c,c, 1, i);
A1 = A2;
}
c = 0.4
for(var a = 0;a<tris.length;a++){
this.mesh.push(tris[a][0]+isox,tris[a][1]+isoy,theH, c,c,c, 1, i);
}
}
}
}
this.position = function(){
return vec4(mesh.pos.x, 1000-mesh.pos.y, mesh.pos.z, 1) * view.totalmatrix * view.viewmatrix
}
this.drawtype = this.TRIANGLES
this.linewidth = 4
}
})
define.class(this, "land", function($ui$, view){
this.boundscheck = false;
this.attributes = {
lands:[]
}
this.mouseover = function(evt){
//console.log(this.last_pick_id)
var text = "Land: " + this.lands[this.last_pick_id ].kind;
this.screen.status = text;
}
this.onlands = function(){
this.pickrange = this.lands.length;
}
this.bg = function(){
this.color1 = {retail:vec4(0,0,1,0.5), tower:"white",library:"white",common:"white", sports_centre:"red", bridge:"gray", university:"red", breakwater:"blue", playground:"lime",forest:"darkgreen",pitch:"lime", grass:"lime", village_green:"green", garden:"green",residential:"gray" , footway:"gray", pedestrian:"gray", water:"#40a0ff",pedestrian:"lightgray", parking:"gray", park:"lime", earth:"lime", pier:"#404040", "rail" : vec4("purple"), "minor_road": vec4("orange"), "major_road" : vec4("red"), highway:vec4("black")}
this.color2 = {retail:vec4(0,0,1,0.5), tower:"gray", library:"gray", common:"gray", sports_centre:"white", bridge:"white", university:"black", breakwater:"green", playground:"red", forest:"black",pitch:"green", grass:"green", village_green:"green", garden:"#40d080", residential:"lightgray" , footway:"yellow", pedestrian:"blue",water:"#f0ffff",pedestrian:"yellow", parking:"lightgray", park:"yellow", earth:"green", pier:"gray", "rail" : vec4("purple"), "minor_road": vec4("orange"), "major_road" : vec4("red"), highway:vec4("black")}
this.landoffsets = {
retail:27,
tower:26,
library:25,
common:24,
sports_centre:23,
bridge:22,
university:21,
breakwater:20,
playground:19,
forest:18,
pitch:17,
grass:16,
village_green:15,
garden:14,
residential:13,
footway:12,
pedestrian:11,
water:-50,
pedestrian:9,
parking:8,
park:7,
earth:6,
pier:5,
"rail" : 4,
"minor_road":2,
"major_road" :1, highway:0}
this.vertexstruct = define.struct({
pos:vec3,
color1:vec4,
color2:vec4,
id: float
})
this.mesh = this.vertexstruct.array();
this.color = function(){
var xy = vec2(mesh.pos.xy)*0.2
//var n1 = (noise.noise2d(xy))*0.25 + 0.25;
//var n2 = 0.8*noise.noise2d(xy*2.3)
var themix = 0.5
PickGuid = mesh.id
//mod(mesh.id, 256.)
//PickGuid.y = floor(mesh.id/256.)
return mix(mesh.color1, mesh.color2,themix);
}
this.update = function(){
this.mesh = this.vertexstruct.array();
var z = 0
for(var i = 0;i<this.view.lands.length;i++){
var off = 0;
//z+=0.1;
var land = this.view.lands[i];
var color1 = vec4("black");
var color2 = vec4("black");
if (this.color1[land.kind]) color1 = this.color1[land.kind];else UnhandledKindSet[land.kind] = true;
if (this.color2[land.kind]) color2 = this.color2[land.kind];else UnhandledKindSet[land.kind] = true;
if (this.landoffsets[land.kind]) off = this.landoffsets[land.kind];
if (land.arcs){
for(var j = 0;j<land.arcs.length;j++){
var arc = land.arcs[j];
var tris = arctotriangles(arc);
for(var a = 0;a<tris.length;a++){
this.mesh.push(tris[a],off, vec4(color1), vec4(color2), i);
}
}
}
}
}
this.position = function(){
var r = vec4(mesh.pos.x, 1000-mesh.pos.y, 0, 1) * view.totalmatrix * view.viewmatrix;
r.w -= mesh.pos.z*0.01;
return r
}
this.drawtype = this.TRIANGLES
this.linewidth = 4
}
})
define.class(this, "road", function($ui$, view){
this.boundscheck = false;
this.attributes = {
roads:[],
zoomlevel: 16,
zoomscale: 2.0
}
this.bg = function(){
this.vertexstruct = define.struct({
pos:vec3,
color:vec4,
side: float,
dist: float,
linewidth:float,
sidevec:vec2,
markcolor: vec4
})
this.mesh = this.vertexstruct.array();
this.color = function(){
if (abs(mesh.side) > 0.85) return mix("black", mesh.color, 0.8)
// if (abs(mesh.side) > 0.75) return mix(mesh.markcolor, mesh.color, 0.6)
// if (abs(mesh.side) < 0.1) return mix(mesh.markcolor, mesh.color, 0.6 * (min(1., max(0.0,0.8 + 5.0*sin(mesh.dist*0.5)))))
return mesh.color;
}
this.widths = {water:20, path:2,ferry:4, "rail" : 4, "minor_road": 8, "major_road" : 12, path: 3, highway:12}
this.colors = {water:"#30a0ff", path:"#d0d0d0", ferry:"lightblue", "rail" : vec4("purple"), "minor_road": vec4("#505050"), "major_road" : vec4("#404040"), highway:vec4("#303030")}
this.markcolors = {water:"#30a0ff", major_road:"white", minor_road:"#a0a0a0"}
this.update = function(){
//console.log("updating");
this.mesh = this.vertexstruct.array();
var z = 0.1;
for (var i = 0;i<this.view.roads.length;i++){
// console.log(z);
var R = this.view.roads[i];
//console.log(R);
var linewidth = 3;
var color = vec4("gray") ;
if (this.widths[R.kind]) linewidth = this.widths[R.kind];
if (this.colors[R.kind]) color = vec4(this.colors[R.kind]);
var markcolor = color;
if (this.markcolors[R.kind]) markcolor = vec4(this.markcolors[R.kind]);
// linewidth *= Math.pow(2, this.view.zoomlevel-14);
for(var rr = 0;rr<R.arcs.length;rr++){
//z+=10 ;
var currentarc = R.arcs[rr]
if (currentarc.length == 1){
continue
}
// console.log(R, currentarc, currentarc.length, currentarc[0].length);
//console.log(R, currentarc);
//continue;
var A0 = currentarc[0];
var A1 = vec2(currentarc[1][0]+A0[0],currentarc[1][1]+A0[1]) ;
//this.mesh.push(A0[0], A0[1], this.view.color);
var nx = A0[0];
var ny = A0[1];
var odx = A1[0]-A0[0];
var ody = A1[1]-A0[1];
var predelta = vec2.normalize(vec2(odx, ody));
var presdelta = vec2.rotate(predelta, 3.1415/2.0);
var dist = 0;
var dist2 = 0;
var lastsdelta = vec2(0,0);
// color = vec4("blue");
this.mesh.push(nx,ny,z, color, 1, dist,linewidth,presdelta, markcolor);
this.mesh.push(nx,ny,z, color, -1, dist,linewidth,presdelta, markcolor);
this.mesh.push(nx - predelta[0]*linewidth*0.5,ny - predelta[1]*linewidth*0.5,z, color, 0.5, -10 ,linewidth,presdelta, markcolor);
this.mesh.push(nx - predelta[0]*linewidth*0.5,ny - predelta[1]*linewidth*0.5,z, color, 0.5, -10 ,linewidth,presdelta, markcolor);
this.mesh.push(nx - predelta[0]*linewidth*0.5,ny - predelta[1]*linewidth*0.5,z, color, -0.5, -10 ,linewidth,presdelta, markcolor);
//this.mesh.push(nx,ny, color, 1, dist,linewidth,presdelta, markcolor);
this.mesh.push(nx,ny, z, color, -1, dist,linewidth,presdelta, markcolor);
// color = vec4(0,0,0.03,0.1)
var lastdelta = vec2(0);
for(var a = 1;a<currentarc.length;a++){
var A =currentarc[a];
var tnx = nx + A[0];
var tny = ny + A[1];
var predelt = vec2( tnx - nx, tny - ny);
var delta = vec2.normalize(predelt);
var sdelta = vec2.rotate(delta, PI/2);
var dist2 = dist + vec2.len(predelt);
if (a>1){
this.mesh.push(nx,ny,z, color, 1, dist,linewidth,lastsdelta, markcolor);
this.mesh.push(nx,ny,z, color, 1, dist,linewidth,sdelta, markcolor);
this.mesh.push(nx,ny,z, color, -1, dist,linewidth,sdelta, markcolor);
this.mesh.push(nx,ny,z, color, 1, dist,linewidth,lastsdelta, markcolor);
this.mesh.push(nx,ny,z, color,-1, dist,linewidth,sdelta, markcolor);
this.mesh.push(nx,ny,z, color, -1, dist,linewidth,lastsdelta, markcolor);
}
//color = vec4(0,1,0,0.2)
this.mesh.push( nx, ny,z,color, 1, dist ,linewidth, sdelta, markcolor);
this.mesh.push( nx, ny,z,color,-1, dist ,linewidth, sdelta, markcolor);
this.mesh.push(tnx,tny,z,color, 1, dist2,linewidth, sdelta, markcolor);
this.mesh.push(nx,ny,z,color,-1, dist,linewidth, sdelta, markcolor);
this.mesh.push(tnx,tny,z,color,1,dist2,linewidth, sdelta, markcolor);
this.mesh.push(tnx,tny,z,color,-1, dist2,linewidth, sdelta, markcolor);
lastsdelta = vec2(sdelta[0], sdelta[1]);
dist = dist2;
nx = tnx;
ny = tny;
lastdelta = delta;
}
//color = vec4("red");
this.mesh.push(nx,ny,z, color, 1, dist,linewidth,lastsdelta, markcolor);
this.mesh.push(nx,ny,z, color, -1, dist,linewidth,lastsdelta, markcolor);
this.mesh.push(nx + lastdelta[0]*linewidth*0.5,ny + lastdelta[1]*linewidth*0.5,z, color, 0.5, dist+linewidth*0.5 ,linewidth,lastsdelta, markcolor);
this.mesh.push(nx + lastdelta[0]*linewidth*0.5,ny + lastdelta[1]*linewidth*0.5,z, color, 0.5, dist+linewidth*0.5 ,linewidth,lastsdelta, markcolor);
this.mesh.push(nx + lastdelta[0]*linewidth*0.5,ny + lastdelta[1]*linewidth*0.5,z, color, -0.5, dist+linewidth*0.5,linewidth,lastsdelta, markcolor);
this.mesh.push(nx,ny, z,color, -1, dist,linewidth,presdelta, markcolor);
}
}
}
this.position = function(){
var pos = mesh.pos.xy + mesh.sidevec * mesh.side * view.zoomscale*mesh.linewidth*0.5;
return vec4(pos.x, 1000-pos.y, mesh.pos.z, 1.0) * view.totalmatrix * view.viewmatrix
}
this.drawtype = this.TRIANGLES
this.linewidth = 4;
}
})
var KindSet = this.KindSet = {};
var UnhandledKindSet = this.UnhandledKindSet = {};
var L = 0;
this.attributes = {
mapxcenter: Math.floor(33656/Math.pow(2, L)),
mapycenter: Math.floor(21534/Math.pow(2,L)),
zoomlevel: 16 - L
}
console.log("addfactor:", Math.pow(2, L));
define.class(this, "debugmaptile", function($ui$, view, label){
this.attributes = {
tilex:19295,
tiley:24641,
zoomlevel: 14
}
this.padding =10;
this.width = 1024;
this.height = 1024;
this.position="absolute"
this.borderwidth = 10;
this.bgcolor = "gray";
this.bordercolor = "lightblue"
this.borderradius = 0.1;
this.justifycontent = "flex-start"
this.render =function(){
return [label({fontsize: 40,alignself:"flex-start",bg:0,text:"x: " + this.tilex + " y: " + this.tiley + " zoomlevel: " + this.zoomlevel})]
}
})
this.moveTo = function(x,y,z){
this.mapxcenter = x;
this.mapycenter = y;
this.zoomlevel = z;
}
this.setZoomLevel = function(z, width, height){
//console.log(z, width, height);
var x = Math.ceil((width * z )/ 1024);
var y = Math.ceil((height * z )/ 1024);
// this.find("theroads").zoomscale = z;
//console.log(x,y);
//console.log(z, Math.floor(log(z)/log(2)));
// this.zoomlevel = 16 + Math.floor( log(z)/log(2));
}
this.render = function(){
//console.log( this.screen.width);
var res = []
var scalefac = Math.pow(2, this.zoomlevel - 16);
var scaler = 1024 ;//* scalefac;
console.log("scaler:", scaler);
for(var x = 0;x<6;x++){
for(var y = 0;y<6;y++){
res.push(this.maptile(
{
name:"tile1",
tilex: this.mapxcenter + x,
tiley: this.mapycenter + y,
position:"absolute",
x: x * scaler ,
y: y * scaler ,
scalefac: scalefac,
//width: scaler,
//height: scaler,
zoomlevel: this.zoomlevel,
}
))
}
}
return res;
}
define.class(this, "maptile", function($ui$, view){
this.attributes = {
tilex:19295,
tiley:24641,
zoomlevel: 16,
arcs:[],
buildings:[],
roads:[],
roadpolies:[],
waters:[],
earths:[],
landuses:[] ,
scalefactor: 1.0
}
this.init = function(){
this.rpc.urlfetch.grabmap(this.tilex, this.tiley, this.zoomlevel).then(function(result){
this.loadstring(result.value)
}.bind(this));
}
this.loadstring = function(str){
this.thedata = JSON.parse(str);
var Bset = [];
var Rset = [];
var Wset = [];
var Eset = [];
var Lset = [];
console.log(this.thedata);
for (var i = 0;i<this.thedata.objects.buildings.geometries.length;i++){
var Bb = this.thedata.objects.buildings.geometries[i];
var B = {h:Bb.properties.height?Bb.properties.height:3.0,kind:Bb.properties.kind, name:Bb.properties.name, street: Bb.properties["addr_street"], housenumber: Bb.properties.addr_housenumber, arcs:[]};
if (Bb.arcs){
for(var k = 0;k<Bb.arcs.length;k++){
B.arcs.push(this.thedata.arcs[Bb.arcs[k]]);
}
}
KindSet[B.kind] = true;
Bset.push(B);
}
for (var i = 0;i<this.thedata.objects.water.geometries.length;i++){
var Bb = this.thedata.objects.water.geometries[i];
var B = {arcs:[], kind:"water" };
//console.log(Bb);
if(Bb.arcs)
if (Bb.type == "MultiLineString"){
var arc = [];
for(var k = 0;k<Bb.arcs.length;k++){
var sourcearc = this.thedata.arcs[Bb.arcs[k]];
var x = sourcearc[0][0];
var y = sourcearc[0][1];
arc.push(x,y);
for(var l = 1;l<sourcearc.length;l++)
{
// console.log(l, sourcearc[l]);
x+= sourcearc[l][0];
y+= sourcearc[l][1];
arc.push(x,y);
// arc.push(sourcearc[l]);
}
}
B.arcs.push(arc);
}
else
for(var k = 0;k<Bb.arcs.length;k++){
B.arcs.push(this.thedata.arcs[Bb.arcs[k]]);
}
if (Bb.type == "LineString" ){
//Rset.push(B);
}
else{
Wset.push(B);
}
}
for (var i = 0;i<this.thedata.objects.earth.geometries.length;i++){
var Bb = this.thedata.objects.earth.geometries[i];
var B = {arcs:[], kind:"earth"};
for(var k = 0;k<Bb.arcs.length;k++){
B.arcs.push(this.thedata.arcs[Bb.arcs[k]]);
}
KindSet[B.kind] = true;
Eset.push(B);
}
for (var i = 0;i<this.thedata.objects.landuse.geometries.length;i++){
var Bb = this.thedata.objects.landuse.geometries[i];
var B = {arcs:[], kind:Bb.properties.kind, name:Bb.properties.name};
if (Bb.arcs)
for(var k = 0;k<Bb.arcs.length;k++){
B.arcs.push(this.thedata.arcs[Bb.arcs[k]]);
}
KindSet[B.kind] = true;
Lset.push(B);
}
for (var i = 0;i<this.thedata.objects.roads.geometries.length;i++){
var Bb = this.thedata.objects.roads.geometries[i];
var B = { arcs:[], kind: Bb.properties.kind};
for(var k = 0;k<Bb.arcs.length;k++){
B.arcs.push(this.thedata.arcs[Bb.arcs[k]]);
}
Rset.push(B);
KindSet[B.kind] = true;
}
for (var i = 0;i<this.thedata.objects.transit.geometries.length;i++){
var Bb = this.thedata.objects.transit.geometries[i];
var B = { arcs:[]};
for(var k = 0;k<Bb.arcs.length;k++){
B.arcs.push(this.thedata.arcs[Bb.arcs[k]]);
}
KindSet[B.kind] = true;
//Rset.push(B);
}
this.buildings = Bset;
this.roads = Rset;
this.waters = Wset;
this.earths = Eset;
this.landuses = Lset;
//for(var i in KindSet){console.log(i)};
}
this.load = function(name){
this.rpc.fileio.readfile("$apps/VectorMap/"+name ).then(function(result){
this.loadstring(result.value);
}.bind(this));
}
this.render = function(){
var res = [];
res.push(this.outer.land({lands:this.earths}));
res.push(this.outer.land({lands:this.landuses}));
res.push(this.outer.land({lands:this.waters}));
res.push(this.outer.road({name:"theroads", roads: this.roads, zoomscale:Math.pow(2.0, this.zoomlevel-15)}));
res.push(this.outer.building({buildings: this.buildings}));
return res;
}
})
})
this.render = function(){
return this.tiledmap({name:"themap"});
}
})
define.class(this, "urlfetch", function($server$, service){
this.grabmap = function(x,y,z){
var nodehttp = require('$system/server/nodehttp');
var fs = require('fs');
var cachedname = define.expandVariables(define.classPath(this) + "tilecache/" + x +"_"+y+"_" + z+".json");
if (fs.existsSync(cachedname)){
return fs.readFileSync(cachedname).toString()
}
var fileurl = "http://vector.mapzen.com/osm/all/"+z+"/"+x+"/"+y+".topojson?api_key=vector-tiles-Qpvj7U4"
var P = define.deferPromise()
nodehttp.get(fileurl).then(function(v){
fs.writeFileSync(cachedname, v);
P.resolve(v);
})
return P;
}.bind(this)
})
this.render = function(){ return [
fileio(),
this.urlfetch({name:"urlfetch"}),
screen({name:"index", style:{
$:{
fontsize:12
}
},
moveTo: function(x,y,zoom){
this.find("themap").moveTo(x,y,zoom);
},
onstatus:function(){this.find("themenu").infotext = this.status;},
clearcolor:vec4('#303030'), overflow:'hidden', title:"VectorMap" },
menubar({
name:"themenu",menus:[
{name:"File", commands:[
{name:"Dump KindSet", clickaction:function(){for(var i in this.find("themap").KindSet){console.log(i)};for(var i in this.find("themap").UnhandledKindSet){console.log("unhandled:", i)};}}
]}
]}
),
view({flex:1, overflow:"scroll", bgcolor:"darkblue", clearcolor:"#505050", onzoom: function(){this.find("themap").setZoomLevel(this.zoom, this.layout.width, this.layout.height);}},
this.mainscreen({
camera:[0,0,1000 ], lookat:[1000,1000,0],nearplane:10, farplane:12000, up:[0,0,-1],viewport:"3d",
boundscheck:false, flex:1,
})
//,view({width:2000, height:2000, bg:0})
)
)
,screen({
name:"remote",
style:{$:{fontsize:12}},
init:function(){
console.log(this.rpc.index)
},
clearcolor:vec4('darkgray'), overflow:'hidden', title:"VectorMap remote" },
speakergrid({justifycontent:"center", alignitems:"center" }
,button({text:"Manhattan",click:function(){this.rpc.index.moveTo(9647*2,12320*2, 16);}, margin:2})
,button({text:"Amsterdam",click:function(){this.rpc.index.moveTo(33656,21534, 16);}, margin:2})
,button({text:"Noord Amsterdam",click:function(){this.rpc.index.moveTo(33656,21434, 16);}, margin:2})
,button({text:"Sausalito",click:function(){this.rpc.index.moveTo(9647,12320, 16);}, margin:2})
,button({text:"San Fransisco",click:function(){this.rpc.index.moveTo(9647,12320, 16);}, margin:2})
)
)
]}
})
| apps/VectorMap/index.js | define.class('$server/composition', function vectormap(require, $server$, fileio,$ui$, numberbox, button, menubar, label, screen, view, foldcontainer, speakergrid,checkbox, icon, $widgets$, colorpicker, jsviewer, radiogroup){
define.class(this, "mainscreen", function($ui$, view){
define.class(this, "tiledmap", function($ui$, view){
var KindSet = this.KindSet = {};
var UnhandledKindSet = this.UnhandledKindSet = {};
var L = 0;
this.attributes = {
// mapxcenter: Math.floor(33656/Math.pow(2, L)),
// mapycenter: Math.floor(21534/Math.pow(2,L)),
mapxcenter: Math.floor((9647*2)/Math.pow(2, L)),
mapycenter: Math.floor((12320*2)/Math.pow(2,L)),
zoomlevel: 16 - L
}
console.log("addfactor:", Math.pow(2, L));
define.class(this, "debugmaptile", function($ui$, view, label){
this.attributes = {
tilex:19295,
tiley:24641,
zoomlevel: 14
}
this.padding =10;
this.width = 1024;
this.height = 1024;
this.position="absolute"
this.borderwidth = 10;
this.bgcolor = "gray";
this.bordercolor = "lightblue"
this.borderradius = 0.1;
this.justifycontent = "flex-start"
this.render =function(){
return [label({fontsize: 40,alignself:"flex-start",bg:0,text:"x: " + this.tilex + " y: " + this.tiley + " zoomlevel: " + this.zoomlevel})]
}
})
this.setZoomLevel = function(z, width, height){
//console.log(z, width, height);
var x = Math.ceil((width * z )/ 1024);
var y = Math.ceil((height * z )/ 1024);
// this.find("theroads").zoomscale = z;
//console.log(x,y);
//console.log(z, Math.floor(log(z)/log(2)));
// this.zoomlevel = 16 + Math.floor( log(z)/log(2));
}
this.render = function(){
//console.log( this.screen.width);
var res = []
var scalefac = Math.pow(2, this.zoomlevel - 16);
var scaler = 1024 ;//* scalefac;
console.log("scaler:", scaler);
for(var x = 0;x<6;x++){
for(var y = 0;y<6;y++){
res.push(this.maptile(
{
name:"tile1",
tilex: this.mapxcenter + x,
tiley: this.mapycenter + y,
position:"absolute",
x: x * scaler ,
y: y * scaler ,
scalefac: scalefac,
//width: scaler,
//height: scaler,
zoomlevel: this.zoomlevel,
}
))
}
}
return res;
}
define.class(this, "maptile", function($ui$, view){
var earcut = require('$system/lib/earcut-port.js')().earcut;
this.attributes = {
tilex:19295,
tiley:24641,
zoomlevel: 16,
arcs:[],
buildings:[],
roads:[],
roadpolies:[],
waters:[],
earths:[],
landuses:[] ,
scalefactor: 1.0
}
this.init = function(){
this.rpc.urlfetch.grabmap(this.tilex, this.tiley, this.zoomlevel).then(function(result){
this.loadstring(result.value)
}.bind(this));
}
define.class(this, "building", function($ui$, view){
this.attributes = {
buildings:[],
scalefactor: 1.0
}
this.boundscheck = false;
this.onbuildings = function(){
this.pickrange = this.buildings.length;
//console.log("setting pickrange:", this.pickrange);
}
this.mouseover = function(){
var building = this.buildings[this.last_pick_id ];
if (building){
var text = "Building";
//console.log(building);
if (building.kind) text += " " + building.kind;
if (building.name) text += " " + building.name;
if (building.street) text += " " + building.street;
if (building.housenumber) text += " " + building.housenumber;
this.screen.status = text;
}
else{
console.log(this.last_pick_id);
}
}
this.bg = function(){
this.vertexstruct = define.struct({
pos:vec3,
color:vec4,
id: float
})
this.mesh = this.vertexstruct.array();
this.color = function(){
PickGuid = mesh.id;
return mesh.color;
}
this.update = function(){
this.mesh = this.vertexstruct.array();
for(var i = 0;i<this.view.buildings.length;i++){
var building = this.view.buildings[i];
var theH = building.h;
var isofac =0
var isox = (theH*0.5)*isofac
var isoy = (theH)*isofac
if (building.arcs)
for(var j = 0;j<building.arcs.length;j++){
var arc = building.arcs[j];
var tris = arctotriangles(arc);
var A1 = vec2(arc[0][0], arc[0][1])
var OA1 = A1;
var c = 0.3;
for(var a = 1;a<arc.length+1;a++)
{
var ca = arc[a%arc.length];
var A2 = vec2(A1[0] + ca[0], A1[1] + ca[1]);
if (a == arc.length){
A2[1] -= OA1[1];
A2[0] -= OA1[0];
}
c = 0.7 + 0.3 *Math.sin(Math.atan2(A2[1]-A1[1], A2[0]-A1[0]));
this.mesh.push(A1[0],A1[1],0, c,c,c, 1, i);
this.mesh.push(A2[0],A2[1],0, c,c,c, 1, i);
this.mesh.push(A2[0]+isox,A2[1]+isoy,theH, c,c,c, 1, i);
this.mesh.push(A1[0],A1[1],0, c,c,c, 1, i);
this.mesh.push(A2[0]+isox,A2[1]+isoy,theH, c,c,c, 1, i);
this.mesh.push(A1[0]+isox,A1[1]+isoy,theH, c,c,c, 1, i);
A1 = A2;
}
c = 0.4
for(var a = 0;a<tris.length;a++){
this.mesh.push(tris[a][0]+isox,tris[a][1]+isoy,theH, c,c,c, 1, i);
}
}
}
}
this.position = function(){
return vec4(mesh.pos.x, 1000-mesh.pos.y, mesh.pos.z, 1) * view.totalmatrix * view.viewmatrix
}
this.drawtype = this.TRIANGLES
this.linewidth = 4
}
})
define.class(this, "land", function($ui$, view){
this.boundscheck = false;
this.attributes = {
lands:[]
}
this.mouseover = function(evt){
//console.log(this.last_pick_id)
var text = "Land: " + this.lands[this.last_pick_id ].kind;
this.screen.status = text;
}
this.onlands = function(){
this.pickrange = this.lands.length;
}
this.bg = function(){
this.color1 = {retail:vec4(0,0,1,0.5), tower:"white",library:"white",common:"white", sports_centre:"red", bridge:"gray", university:"red", breakwater:"blue", playground:"lime",forest:"darkgreen",pitch:"lime", grass:"lime", village_green:"green", garden:"green",residential:"gray" , footway:"gray", pedestrian:"gray", water:"#40a0ff",pedestrian:"lightgray", parking:"gray", park:"lime", earth:"lime", pier:"#404040", "rail" : vec4("purple"), "minor_road": vec4("orange"), "major_road" : vec4("red"), highway:vec4("black")}
this.color2 = {retail:vec4(0,0,1,0.5), tower:"gray", library:"gray", common:"gray", sports_centre:"white", bridge:"white", university:"black", breakwater:"green", playground:"red", forest:"black",pitch:"green", grass:"green", village_green:"green", garden:"#40d080", residential:"lightgray" , footway:"yellow", pedestrian:"blue",water:"#f0ffff",pedestrian:"yellow", parking:"lightgray", park:"yellow", earth:"green", pier:"gray", "rail" : vec4("purple"), "minor_road": vec4("orange"), "major_road" : vec4("red"), highway:vec4("black")}
this.vertexstruct = define.struct({
pos:vec2,
color1:vec4,
color2:vec4,
id: float
})
this.mesh = this.vertexstruct.array();
this.color = function(){
var xy = vec2(mesh.pos.xy)*0.2
//var n1 = (noise.noise2d(xy))*0.25 + 0.25;
//var n2 = 0.8*noise.noise2d(xy*2.3)
var themix = 0.5
PickGuid = mesh.id
//mod(mesh.id, 256.)
//PickGuid.y = floor(mesh.id/256.)
return mix(mesh.color1, mesh.color2,themix);
}
this.update = function(){
this.mesh = this.vertexstruct.array();
for(var i = 0;i<this.view.lands.length;i++){
var land = this.view.lands[i];
var color1 = vec4("black");
var color2 = vec4("black");
if (this.color1[land.kind]) color1 = this.color1[land.kind];else UnhandledKindSet[land.kind] = true;
if (this.color2[land.kind]) color2 = this.color2[land.kind];else UnhandledKindSet[land.kind] = true;
if (land.arcs){
for(var j = 0;j<land.arcs.length;j++){
var arc = land.arcs[j];
var tris = arctotriangles(arc);
for(var a = 0;a<tris.length;a++){
this.mesh.push(tris[a], vec4(color1), vec4(color2), i);
}
}
}
}
}
this.position = function(){
return vec4(mesh.pos.x, 1000-mesh.pos.y, 0, 1) * view.totalmatrix * view.viewmatrix
}
this.drawtype = this.TRIANGLES
this.linewidth = 4
}
})
define.class(this, "road", function($ui$, view){
this.boundscheck = false;
this.attributes = {
roads:[],
zoomlevel: 16,
zoomscale: 2.0
}
this.bg = function(){
this.vertexstruct = define.struct({
pos:vec2,
color:vec4,
side: float,
dist: float,
linewidth:float,
sidevec:vec2,
markcolor: vec4
})
this.mesh = this.vertexstruct.array();
this.color = function(){
if (abs(mesh.side) > 0.85) return mix("black", mesh.color, 0.8)
// if (abs(mesh.side) > 0.75) return mix(mesh.markcolor, mesh.color, 0.6)
// if (abs(mesh.side) < 0.1) return mix(mesh.markcolor, mesh.color, 0.6 * (min(1., max(0.0,0.8 + 5.0*sin(mesh.dist*0.5)))))
return mesh.color;
}
this.widths = {water:20, path:2,ferry:4, "rail" : 4, "minor_road": 8, "major_road" : 12, path: 3, highway:12}
this.colors = {water:"#30a0ff", path:"#d0d0d0", ferry:"lightblue", "rail" : vec4("purple"), "minor_road": vec4("#505050"), "major_road" : vec4("#404040"), highway:vec4("#303030")}
this.markcolors = {water:"#30a0ff", major_road:"white", minor_road:"#a0a0a0"}
this.update = function(){
//console.log("updating");
this.mesh = this.vertexstruct.array();
for (var i = 0;i<this.view.roads.length;i++){
var R = this.view.roads[i];
//console.log(R);
var linewidth = 3;
var color = vec4("gray") ;
if (this.widths[R.kind]) linewidth = this.widths[R.kind];
if (this.colors[R.kind]) color = vec4(this.colors[R.kind]);
var markcolor = color;
if (this.markcolors[R.kind]) markcolor = vec4(this.markcolors[R.kind]);
// linewidth *= Math.pow(2, this.view.zoomlevel-14);
for(var rr = 0;rr<R.arcs.length;rr++){
var currentarc = R.arcs[rr]
if (currentarc.length == 1){
continue
}
// console.log(R, currentarc, currentarc.length, currentarc[0].length);
//console.log(R, currentarc);
//continue;
var A0 = currentarc[0];
var A1 = vec2(currentarc[1][0]+A0[0],currentarc[1][1]+A0[1]) ;
//this.mesh.push(A0[0], A0[1], this.view.color);
var nx = A0[0];
var ny = A0[1];
var odx = A1[0]-A0[0];
var ody = A1[1]-A0[1];
var predelta = vec2.normalize(vec2(odx, ody));
var presdelta = vec2.rotate(predelta, 3.1415/2.0);
var dist = 0;
var dist2 = 0;
var lastsdelta = vec2(0,0);
// color = vec4("blue");
this.mesh.push(nx,ny, color, 1, dist,linewidth,presdelta, markcolor);
this.mesh.push(nx,ny, color, -1, dist,linewidth,presdelta, markcolor);
this.mesh.push(nx - predelta[0]*linewidth*0.5,ny - predelta[1]*linewidth*0.5, color, 0.5, -10 ,linewidth,presdelta, markcolor);
this.mesh.push(nx - predelta[0]*linewidth*0.5,ny - predelta[1]*linewidth*0.5, color, 0.5, -10 ,linewidth,presdelta, markcolor);
this.mesh.push(nx - predelta[0]*linewidth*0.5,ny - predelta[1]*linewidth*0.5, color, -0.5, -10 ,linewidth,presdelta, markcolor);
//this.mesh.push(nx,ny, color, 1, dist,linewidth,presdelta, markcolor);
this.mesh.push(nx,ny, color, -1, dist,linewidth,presdelta, markcolor);
// color = vec4(0,0,0.03,0.1)
var lastdelta = vec2(0);
for(var a = 1;a<currentarc.length;a++){
var A =currentarc[a];
var tnx = nx + A[0];
var tny = ny + A[1];
var predelt = vec2( tnx - nx, tny - ny);
var delta = vec2.normalize(predelt);
var sdelta = vec2.rotate(delta, PI/2);
var dist2 = dist + vec2.len(predelt);
if (a>1){
this.mesh.push(nx,ny, color, 1, dist,linewidth,lastsdelta, markcolor);
this.mesh.push(nx,ny, color, 1, dist,linewidth,sdelta, markcolor);
this.mesh.push(nx,ny, color, -1, dist,linewidth,sdelta, markcolor);
this.mesh.push(nx,ny, color, 1, dist,linewidth,lastsdelta, markcolor);
this.mesh.push(nx,ny, color,-1, dist,linewidth,sdelta, markcolor);
this.mesh.push(nx,ny, color, -1, dist,linewidth,lastsdelta, markcolor);
}
//color = vec4(0,1,0,0.2)
this.mesh.push( nx, ny,color, 1, dist ,linewidth, sdelta, markcolor);
this.mesh.push( nx, ny,color,-1, dist ,linewidth, sdelta, markcolor);
this.mesh.push(tnx,tny,color, 1, dist2,linewidth, sdelta, markcolor);
this.mesh.push(nx,ny,color,-1, dist,linewidth, sdelta, markcolor);
this.mesh.push(tnx,tny,color,1,dist2,linewidth, sdelta, markcolor);
this.mesh.push(tnx,tny,color,-1, dist2,linewidth, sdelta, markcolor);
lastsdelta = vec2(sdelta[0], sdelta[1]);
dist = dist2;
nx = tnx;
ny = tny;
lastdelta = delta;
}
// color = vec4("red");
this.mesh.push(nx,ny, color, 1, dist,linewidth,lastsdelta, markcolor);
this.mesh.push(nx,ny, color, -1, dist,linewidth,lastsdelta, markcolor);
this.mesh.push(nx + lastdelta[0]*linewidth*0.5,ny + lastdelta[1]*linewidth*0.5, color, 0.5, dist+linewidth*0.5 ,linewidth,lastsdelta, markcolor);
this.mesh.push(nx + lastdelta[0]*linewidth*0.5,ny + lastdelta[1]*linewidth*0.5, color, 0.5, dist+linewidth*0.5 ,linewidth,lastsdelta, markcolor);
this.mesh.push(nx + lastdelta[0]*linewidth*0.5,ny + lastdelta[1]*linewidth*0.5, color, -0.5, dist+linewidth*0.5,linewidth,lastsdelta, markcolor);
this.mesh.push(nx,ny, color, -1, dist,linewidth,presdelta, markcolor);
}
}
}
this.position = function(){
var pos = mesh.pos + mesh.sidevec * mesh.side * view.zoomscale*mesh.linewidth*0.5;
return vec4(pos.x, 1000-pos.y, 0, 1) * view.totalmatrix * view.viewmatrix
}
this.drawtype = this.TRIANGLES
this.linewidth = 4;
}
})
function arctotriangles(arc){
if (!arc) return [];
var verts = [];
var flatverts = [];
var A0 = arc[0];
var nx = A0[0];
var ny = A0[1];
// verts.push(A0);
flatverts.push(nx);
flatverts.push(ny);
for (var i =1 ;i<arc.length;i++){
var A = arc[i];
nx += A[0];
ny += A[1];
// verts.push(vec2(nx,ny));
flatverts.push(nx);
flatverts.push(ny);
}
var triangles = earcut(flatverts);
for(var i = 0;i<triangles.length;i++){
idx = triangles[i];
verts.push(vec2(flatverts[idx*2],flatverts[idx*2 + 1]));
}
return verts;
}
this.loadstring = function(str){
this.thedata = JSON.parse(str);
var Bset = [];
var Rset = [];
var Wset = [];
var Eset = [];
var Lset = [];
for (var i = 0;i<this.thedata.objects.buildings.geometries.length;i++){
var Bb = this.thedata.objects.buildings.geometries[i];
var B = {h:Bb.properties.height?Bb.properties.height:3.0,kind:Bb.properties.kind, name:Bb.properties.name, street: Bb.properties["addr_street"], housenumber: Bb.properties.addr_housenumber, arcs:[]};
if (Bb.arcs){
for(var k = 0;k<Bb.arcs.length;k++){
B.arcs.push(this.thedata.arcs[Bb.arcs[k]]);
}
}
KindSet[B.kind] = true;
Bset.push(B);
}
for (var i = 0;i<this.thedata.objects.water.geometries.length;i++){
var Bb = this.thedata.objects.water.geometries[i];
var B = {arcs:[], kind:"water" };
//console.log(Bb);
if(Bb.arcs)
if (Bb.type == "MultiLineString"){
var arc = [];
for(var k = 0;k<Bb.arcs.length;k++){
var sourcearc = this.thedata.arcs[Bb.arcs[k]];
var x = sourcearc[0][0];
var y = sourcearc[0][1];
arc.push(x,y);
for(var l = 1;l<sourcearc.length;l++)
{
// console.log(l, sourcearc[l]);
x+= sourcearc[l][0];
y+= sourcearc[l][1];
arc.push(x,y);
// arc.push(sourcearc[l]);
}
}
B.arcs.push(arc);
}
else
for(var k = 0;k<Bb.arcs.length;k++){
B.arcs.push(this.thedata.arcs[Bb.arcs[k]]);
}
if (Bb.type == "LineString" ){
//Rset.push(B);
}
else{
Wset.push(B);
}
}
for (var i = 0;i<this.thedata.objects.earth.geometries.length;i++){
var Bb = this.thedata.objects.earth.geometries[i];
var B = {arcs:[], kind:"earth"};
for(var k = 0;k<Bb.arcs.length;k++){
B.arcs.push(this.thedata.arcs[Bb.arcs[k]]);
}
KindSet[B.kind] = true;
Eset.push(B);
}
for (var i = 0;i<this.thedata.objects.landuse.geometries.length;i++){
var Bb = this.thedata.objects.landuse.geometries[i];
var B = {arcs:[], kind:Bb.properties.kind, name:Bb.properties.name};
if (Bb.arcs)
for(var k = 0;k<Bb.arcs.length;k++){
B.arcs.push(this.thedata.arcs[Bb.arcs[k]]);
}
KindSet[B.kind] = true;
Lset.push(B);
}
for (var i = 0;i<this.thedata.objects.roads.geometries.length;i++){
var Bb = this.thedata.objects.roads.geometries[i];
var B = { arcs:[], kind: Bb.properties.kind};
for(var k = 0;k<Bb.arcs.length;k++){
B.arcs.push(this.thedata.arcs[Bb.arcs[k]]);
}
Rset.push(B);
KindSet[B.kind] = true;
}
for (var i = 0;i<this.thedata.objects.transit.geometries.length;i++){
var Bb = this.thedata.objects.transit.geometries[i];
var B = { arcs:[]};
for(var k = 0;k<Bb.arcs.length;k++){
B.arcs.push(this.thedata.arcs[Bb.arcs[k]]);
}
KindSet[B.kind] = true;
//Rset.push(B);
}
this.buildings = Bset;
this.roads = Rset;
this.waters = Wset;
this.earths = Eset;
this.landuses = Lset;
//for(var i in KindSet){console.log(i)};
}
this.load = function(name){
this.rpc.fileio.readfile("$apps/VectorMap/"+name ).then(function(result){
this.loadstring(result.value);
}.bind(this));
}
this.render = function(){
var res = [];
res.push(this.land({lands:this.earths}));
res.push(this.land({lands:this.landuses}));
res.push(this.land({lands:this.waters}));
res.push(this.road({name:"theroads", roads: this.roads, zoomscale:Math.pow(2.0, this.zoomlevel-15)}));
res.push(this.building({buildings: this.buildings}));
return res;
}
})
})
this.render = function(){
return this.tiledmap({name:"themap"});
}
})
define.class(this, "urlfetch", function($server$, service){
this.grabmap = function(x,y,z){
var nodehttp = require('$system/server/nodehttp');
var fs = require('fs');
var cachedname = define.expandVariables(define.classPath(this) + "tilecache/" + x +"_"+y+"_" + z+".json");
if (fs.existsSync(cachedname)){
return fs.readFileSync(cachedname).toString()
}
var fileurl = "http://vector.mapzen.com/osm/all/"+z+"/"+x+"/"+y+".topojson?api_key=vector-tiles-Qpvj7U4"
var P = define.deferPromise()
nodehttp.get(fileurl).then(function(v){
fs.writeFileSync(cachedname, v);
P.resolve(v);
})
return P;
}.bind(this)
})
this.render = function(){ return [
fileio(),
this.urlfetch({name:"urlfetch"}),
screen({name:"index", style:{
$:{
fontsize:12
}
},
onstatus:function(){this.find("themenu").infotext = this.status;},
clearcolor:vec4('#303030'), overflow:'hidden', title:"VectorMap" },
menubar({
name:"themenu",menus:[
{name:"File", commands:[
{name:"Dump KindSet", clickaction:function(){for(var i in this.find("themap").KindSet){console.log(i)};for(var i in this.find("themap").UnhandledKindSet){console.log("unhandled:", i)};}}
]}
]}
),
view({flex:1, overflow:"scroll", bgcolor:"darkblue", clearcolor:"#505050", onzoom: function(){this.find("themap").setZoomLevel(this.zoom, this.layout.width, this.layout.height);}},
this.mainscreen({
camera:[0,0,1000 ], lookat:[1000,1000,0],nearplane:10, farplane:20000, up:[0,0,-1],viewport:"3d",
boundscheck:false, flex:1,
})
//,view({width:2000, height:2000, bg:0})
)
)
,screen({
name:"remote",
style:{$:{fontsize:12}},
init:function(){
console.log(this.rpc.index)
},
clearcolor:vec4('darkgray'), overflow:'hidden', title:"VectorMap remote" },
speakergrid({justifycontent:"center", alignitems:"center" })
)
]}
})
| Moving stuff around in maprender - rpc crash on remote
| apps/VectorMap/index.js | Moving stuff around in maprender - rpc crash on remote | <ide><path>pps/VectorMap/index.js
<ide>
<ide> define.class(this, "tiledmap", function($ui$, view){
<ide>
<add> var earcut = require('$system/lib/earcut-port.js')().earcut;
<add>
<add> function arctotriangles(arc){
<add> if (!arc) return [];
<add> var verts = [];
<add> var flatverts = [];
<add> var A0 = arc[0];
<add> var nx = A0[0];
<add> var ny = A0[1];
<add> flatverts.push(nx);
<add> flatverts.push(ny);
<add>
<add> for (var i =1 ;i<arc.length;i++){
<add> var A = arc[i];
<add> nx += A[0];
<add> ny += A[1];
<add> flatverts.push(nx);
<add> flatverts.push(ny);
<add> }
<add>
<add> var triangles = earcut(flatverts);
<add>
<add> for(var i = 0;i<triangles.length;i++){
<add> idx = triangles[i];
<add> verts.push(vec2(flatverts[idx*2],flatverts[idx*2 + 1]));
<add> }
<add> return verts;
<add> }
<add>
<add>
<add> define.class(this, "building", function($ui$, view){
<add>
<add> this.attributes = {
<add> buildings:[],
<add> scalefactor: 1.0
<add> }
<add>
<add> this.boundscheck = false;
<add>
<add> this.onbuildings = function(){
<add> this.pickrange = this.buildings.length;
<add> //console.log("setting pickrange:", this.pickrange);
<add> }
<add>
<add>
<add> this.mouseover = function(){
<add> var building = this.buildings[this.last_pick_id ];
<add> if (building){
<add> var text = "Building";
<add> //console.log(building);
<add>
<add> if (building.kind) text += " " + building.kind;
<add> if (building.name) text += " " + building.name;
<add> if (building.street) text += " " + building.street;
<add> if (building.housenumber) text += " " + building.housenumber;
<add> this.screen.status = text;
<add> }
<add> else{
<add> console.log(this.last_pick_id);
<add> }
<add> }
<add>
<add> this.bg = function(){
<add>
<add> this.vertexstruct = define.struct({
<add> pos:vec3,
<add> color:vec4,
<add> id: float
<add> })
<add>
<add> this.mesh = this.vertexstruct.array();
<add> this.color = function(){
<add>
<add> PickGuid = mesh.id;
<add> return mesh.color;
<add> }
<add>
<add> this.update = function(){
<add> this.mesh = this.vertexstruct.array();
<add>
<add> for(var i = 0;i<this.view.buildings.length;i++){
<add> var building = this.view.buildings[i];
<add>
<add> var theH = building.h;
<add> var isofac =0
<add> var isox = (theH*0.5)*isofac
<add> var isoy = (theH)*isofac
<add>
<add> if (building.arcs)
<add> for(var j = 0;j<building.arcs.length;j++){
<add> var arc = building.arcs[j];
<add> var tris = arctotriangles(arc);
<add> var A1 = vec2(arc[0][0], arc[0][1])
<add> var OA1 = A1;
<add> var c = 0.3;
<add> for(var a = 1;a<arc.length+1;a++)
<add> {
<add> var ca = arc[a%arc.length];
<add>
<add> var A2 = vec2(A1[0] + ca[0], A1[1] + ca[1]);
<add> if (a == arc.length){
<add> A2[1] -= OA1[1];
<add> A2[0] -= OA1[0];
<add> }
<add>
<add> c = 0.7 + 0.3 *Math.sin(Math.atan2(A2[1]-A1[1], A2[0]-A1[0]));
<add>
<add> this.mesh.push(A1[0],A1[1],0, c,c,c, 1, i);
<add> this.mesh.push(A2[0],A2[1],0, c,c,c, 1, i);
<add> this.mesh.push(A2[0]+isox,A2[1]+isoy,theH, c,c,c, 1, i);
<add> this.mesh.push(A1[0],A1[1],0, c,c,c, 1, i);
<add> this.mesh.push(A2[0]+isox,A2[1]+isoy,theH, c,c,c, 1, i);
<add> this.mesh.push(A1[0]+isox,A1[1]+isoy,theH, c,c,c, 1, i);
<add> A1 = A2;
<add>
<add> }
<add> c = 0.4
<add> for(var a = 0;a<tris.length;a++){
<add> this.mesh.push(tris[a][0]+isox,tris[a][1]+isoy,theH, c,c,c, 1, i);
<add> }
<add> }
<add> }
<add> }
<add>
<add> this.position = function(){
<add> return vec4(mesh.pos.x, 1000-mesh.pos.y, mesh.pos.z, 1) * view.totalmatrix * view.viewmatrix
<add> }
<add>
<add> this.drawtype = this.TRIANGLES
<add> this.linewidth = 4
<add>
<add> }
<add> })
<add>
<add> define.class(this, "land", function($ui$, view){
<add> this.boundscheck = false;
<add> this.attributes = {
<add> lands:[]
<add> }
<add>
<add> this.mouseover = function(evt){
<add> //console.log(this.last_pick_id)
<add> var text = "Land: " + this.lands[this.last_pick_id ].kind;
<add> this.screen.status = text;
<add> }
<add>
<add>
<add> this.onlands = function(){
<add> this.pickrange = this.lands.length;
<add> }
<add>
<add> this.bg = function(){
<add>
<add> this.color1 = {retail:vec4(0,0,1,0.5), tower:"white",library:"white",common:"white", sports_centre:"red", bridge:"gray", university:"red", breakwater:"blue", playground:"lime",forest:"darkgreen",pitch:"lime", grass:"lime", village_green:"green", garden:"green",residential:"gray" , footway:"gray", pedestrian:"gray", water:"#40a0ff",pedestrian:"lightgray", parking:"gray", park:"lime", earth:"lime", pier:"#404040", "rail" : vec4("purple"), "minor_road": vec4("orange"), "major_road" : vec4("red"), highway:vec4("black")}
<add> this.color2 = {retail:vec4(0,0,1,0.5), tower:"gray", library:"gray", common:"gray", sports_centre:"white", bridge:"white", university:"black", breakwater:"green", playground:"red", forest:"black",pitch:"green", grass:"green", village_green:"green", garden:"#40d080", residential:"lightgray" , footway:"yellow", pedestrian:"blue",water:"#f0ffff",pedestrian:"yellow", parking:"lightgray", park:"yellow", earth:"green", pier:"gray", "rail" : vec4("purple"), "minor_road": vec4("orange"), "major_road" : vec4("red"), highway:vec4("black")}
<add> this.landoffsets = {
<add> retail:27,
<add> tower:26,
<add> library:25,
<add> common:24,
<add> sports_centre:23,
<add> bridge:22,
<add> university:21,
<add> breakwater:20,
<add> playground:19,
<add> forest:18,
<add> pitch:17,
<add> grass:16,
<add> village_green:15,
<add> garden:14,
<add> residential:13,
<add> footway:12,
<add> pedestrian:11,
<add> water:-50,
<add> pedestrian:9,
<add> parking:8,
<add> park:7,
<add> earth:6,
<add> pier:5,
<add> "rail" : 4,
<add> "minor_road":2,
<add> "major_road" :1, highway:0}
<add>
<add> this.vertexstruct = define.struct({
<add> pos:vec3,
<add> color1:vec4,
<add> color2:vec4,
<add> id: float
<add> })
<add>
<add>
<add> this.mesh = this.vertexstruct.array();
<add>
<add> this.color = function(){
<add> var xy = vec2(mesh.pos.xy)*0.2
<add> //var n1 = (noise.noise2d(xy))*0.25 + 0.25;
<add> //var n2 = 0.8*noise.noise2d(xy*2.3)
<add> var themix = 0.5
<add> PickGuid = mesh.id
<add> //mod(mesh.id, 256.)
<add> //PickGuid.y = floor(mesh.id/256.)
<add> return mix(mesh.color1, mesh.color2,themix);
<add> }
<add>
<add> this.update = function(){
<add> this.mesh = this.vertexstruct.array();
<add> var z = 0
<add> for(var i = 0;i<this.view.lands.length;i++){
<add> var off = 0;
<add> //z+=0.1;
<add> var land = this.view.lands[i];
<add>
<add> var color1 = vec4("black");
<add> var color2 = vec4("black");
<add>
<add> if (this.color1[land.kind]) color1 = this.color1[land.kind];else UnhandledKindSet[land.kind] = true;
<add> if (this.color2[land.kind]) color2 = this.color2[land.kind];else UnhandledKindSet[land.kind] = true;
<add> if (this.landoffsets[land.kind]) off = this.landoffsets[land.kind];
<add>
<add> if (land.arcs){
<add> for(var j = 0;j<land.arcs.length;j++){
<add> var arc = land.arcs[j];
<add> var tris = arctotriangles(arc);
<add> for(var a = 0;a<tris.length;a++){
<add> this.mesh.push(tris[a],off, vec4(color1), vec4(color2), i);
<add> }
<add> }
<add> }
<add> }
<add> }
<add>
<add> this.position = function(){
<add> var r = vec4(mesh.pos.x, 1000-mesh.pos.y, 0, 1) * view.totalmatrix * view.viewmatrix;
<add> r.w -= mesh.pos.z*0.01;
<add> return r
<add> }
<add>
<add> this.drawtype = this.TRIANGLES
<add> this.linewidth = 4
<add> }
<add> })
<add>
<add> define.class(this, "road", function($ui$, view){
<add> this.boundscheck = false;
<add>
<add> this.attributes = {
<add> roads:[],
<add> zoomlevel: 16,
<add> zoomscale: 2.0
<add> }
<add> this.bg = function(){
<add> this.vertexstruct = define.struct({
<add> pos:vec3,
<add> color:vec4,
<add> side: float,
<add> dist: float,
<add> linewidth:float,
<add> sidevec:vec2,
<add> markcolor: vec4
<add> })
<add>
<add> this.mesh = this.vertexstruct.array();
<add>
<add> this.color = function(){
<add> if (abs(mesh.side) > 0.85) return mix("black", mesh.color, 0.8)
<add> // if (abs(mesh.side) > 0.75) return mix(mesh.markcolor, mesh.color, 0.6)
<add>// if (abs(mesh.side) < 0.1) return mix(mesh.markcolor, mesh.color, 0.6 * (min(1., max(0.0,0.8 + 5.0*sin(mesh.dist*0.5)))))
<add> return mesh.color;
<add> }
<add>
<add> this.widths = {water:20, path:2,ferry:4, "rail" : 4, "minor_road": 8, "major_road" : 12, path: 3, highway:12}
<add> this.colors = {water:"#30a0ff", path:"#d0d0d0", ferry:"lightblue", "rail" : vec4("purple"), "minor_road": vec4("#505050"), "major_road" : vec4("#404040"), highway:vec4("#303030")}
<add> this.markcolors = {water:"#30a0ff", major_road:"white", minor_road:"#a0a0a0"}
<add>
<add> this.update = function(){
<add> //console.log("updating");
<add> this.mesh = this.vertexstruct.array();
<add> var z = 0.1;
<add>
<add> for (var i = 0;i<this.view.roads.length;i++){
<add>
<add>
<add>// console.log(z);
<add> var R = this.view.roads[i];
<add> //console.log(R);
<add> var linewidth = 3;
<add> var color = vec4("gray") ;
<add> if (this.widths[R.kind]) linewidth = this.widths[R.kind];
<add> if (this.colors[R.kind]) color = vec4(this.colors[R.kind]);
<add> var markcolor = color;
<add> if (this.markcolors[R.kind]) markcolor = vec4(this.markcolors[R.kind]);
<add>
<add> // linewidth *= Math.pow(2, this.view.zoomlevel-14);
<add>
<add> for(var rr = 0;rr<R.arcs.length;rr++){
<add>
<add> //z+=10 ;
<add>
<add> var currentarc = R.arcs[rr]
<add> if (currentarc.length == 1){
<add> continue
<add> }
<add> // console.log(R, currentarc, currentarc.length, currentarc[0].length);
<add>
<add> //console.log(R, currentarc);
<add> //continue;
<add> var A0 = currentarc[0];
<add> var A1 = vec2(currentarc[1][0]+A0[0],currentarc[1][1]+A0[1]) ;
<add>
<add> //this.mesh.push(A0[0], A0[1], this.view.color);
<add> var nx = A0[0];
<add> var ny = A0[1];
<add>
<add> var odx = A1[0]-A0[0];
<add> var ody = A1[1]-A0[1];
<add>
<add> var predelta = vec2.normalize(vec2(odx, ody));
<add> var presdelta = vec2.rotate(predelta, 3.1415/2.0);
<add>
<add>
<add>
<add> var dist = 0;
<add> var dist2 = 0;
<add> var lastsdelta = vec2(0,0);
<add> // color = vec4("blue");
<add> this.mesh.push(nx,ny,z, color, 1, dist,linewidth,presdelta, markcolor);
<add> this.mesh.push(nx,ny,z, color, -1, dist,linewidth,presdelta, markcolor);
<add>
<add> this.mesh.push(nx - predelta[0]*linewidth*0.5,ny - predelta[1]*linewidth*0.5,z, color, 0.5, -10 ,linewidth,presdelta, markcolor);
<add>
<add> this.mesh.push(nx - predelta[0]*linewidth*0.5,ny - predelta[1]*linewidth*0.5,z, color, 0.5, -10 ,linewidth,presdelta, markcolor);
<add> this.mesh.push(nx - predelta[0]*linewidth*0.5,ny - predelta[1]*linewidth*0.5,z, color, -0.5, -10 ,linewidth,presdelta, markcolor);
<add>
<add> //this.mesh.push(nx,ny, color, 1, dist,linewidth,presdelta, markcolor);
<add> this.mesh.push(nx,ny, z, color, -1, dist,linewidth,presdelta, markcolor);
<add>
<add>
<add> // color = vec4(0,0,0.03,0.1)
<add> var lastdelta = vec2(0);
<add> for(var a = 1;a<currentarc.length;a++){
<add> var A =currentarc[a];
<add>
<add> var tnx = nx + A[0];
<add> var tny = ny + A[1];
<add> var predelt = vec2( tnx - nx, tny - ny);
<add> var delta = vec2.normalize(predelt);
<add> var sdelta = vec2.rotate(delta, PI/2);
<add>
<add> var dist2 = dist + vec2.len(predelt);
<add>
<add> if (a>1){
<add> this.mesh.push(nx,ny,z, color, 1, dist,linewidth,lastsdelta, markcolor);
<add> this.mesh.push(nx,ny,z, color, 1, dist,linewidth,sdelta, markcolor);
<add> this.mesh.push(nx,ny,z, color, -1, dist,linewidth,sdelta, markcolor);
<add>
<add> this.mesh.push(nx,ny,z, color, 1, dist,linewidth,lastsdelta, markcolor);
<add> this.mesh.push(nx,ny,z, color,-1, dist,linewidth,sdelta, markcolor);
<add> this.mesh.push(nx,ny,z, color, -1, dist,linewidth,lastsdelta, markcolor);
<add>
<add> }
<add> //color = vec4(0,1,0,0.2)
<add> this.mesh.push( nx, ny,z,color, 1, dist ,linewidth, sdelta, markcolor);
<add> this.mesh.push( nx, ny,z,color,-1, dist ,linewidth, sdelta, markcolor);
<add> this.mesh.push(tnx,tny,z,color, 1, dist2,linewidth, sdelta, markcolor);
<add>
<add> this.mesh.push(nx,ny,z,color,-1, dist,linewidth, sdelta, markcolor);
<add> this.mesh.push(tnx,tny,z,color,1,dist2,linewidth, sdelta, markcolor);
<add> this.mesh.push(tnx,tny,z,color,-1, dist2,linewidth, sdelta, markcolor);
<add>
<add> lastsdelta = vec2(sdelta[0], sdelta[1]);
<add> dist = dist2;
<add> nx = tnx;
<add> ny = tny;
<add> lastdelta = delta;
<add> }
<add> //color = vec4("red");
<add> this.mesh.push(nx,ny,z, color, 1, dist,linewidth,lastsdelta, markcolor);
<add> this.mesh.push(nx,ny,z, color, -1, dist,linewidth,lastsdelta, markcolor);
<add> this.mesh.push(nx + lastdelta[0]*linewidth*0.5,ny + lastdelta[1]*linewidth*0.5,z, color, 0.5, dist+linewidth*0.5 ,linewidth,lastsdelta, markcolor);
<add>
<add> this.mesh.push(nx + lastdelta[0]*linewidth*0.5,ny + lastdelta[1]*linewidth*0.5,z, color, 0.5, dist+linewidth*0.5 ,linewidth,lastsdelta, markcolor);
<add> this.mesh.push(nx + lastdelta[0]*linewidth*0.5,ny + lastdelta[1]*linewidth*0.5,z, color, -0.5, dist+linewidth*0.5,linewidth,lastsdelta, markcolor);
<add> this.mesh.push(nx,ny, z,color, -1, dist,linewidth,presdelta, markcolor);
<add>
<add> }
<add> }
<add> }
<add> this.position = function(){
<add> var pos = mesh.pos.xy + mesh.sidevec * mesh.side * view.zoomscale*mesh.linewidth*0.5;
<add> return vec4(pos.x, 1000-pos.y, mesh.pos.z, 1.0) * view.totalmatrix * view.viewmatrix
<add> }
<add>
<add> this.drawtype = this.TRIANGLES
<add> this.linewidth = 4;
<add>
<add> }
<add> })
<add>
<ide> var KindSet = this.KindSet = {};
<del> var UnhandledKindSet = this.UnhandledKindSet = {};
<del>
<add> var UnhandledKindSet = this.UnhandledKindSet = {};
<ide> var L = 0;
<ide>
<ide> this.attributes = {
<del>// mapxcenter: Math.floor(33656/Math.pow(2, L)),
<del>// mapycenter: Math.floor(21534/Math.pow(2,L)),
<del> mapxcenter: Math.floor((9647*2)/Math.pow(2, L)),
<del> mapycenter: Math.floor((12320*2)/Math.pow(2,L)),
<add> mapxcenter: Math.floor(33656/Math.pow(2, L)),
<add> mapycenter: Math.floor(21534/Math.pow(2,L)),
<ide> zoomlevel: 16 - L
<ide> }
<ide>
<ide> console.log("addfactor:", Math.pow(2, L));
<add>
<ide> define.class(this, "debugmaptile", function($ui$, view, label){
<add>
<ide> this.attributes = {
<ide> tilex:19295,
<ide> tiley:24641,
<ide> zoomlevel: 14
<ide> }
<add>
<ide> this.padding =10;
<ide> this.width = 1024;
<ide> this.height = 1024;
<ide> return [label({fontsize: 40,alignself:"flex-start",bg:0,text:"x: " + this.tilex + " y: " + this.tiley + " zoomlevel: " + this.zoomlevel})]
<ide> }
<ide> })
<del>
<add>
<add> this.moveTo = function(x,y,z){
<add> this.mapxcenter = x;
<add> this.mapycenter = y;
<add> this.zoomlevel = z;
<add> }
<add>
<ide> this.setZoomLevel = function(z, width, height){
<ide> //console.log(z, width, height);
<ide>
<ide> }
<ide>
<ide> define.class(this, "maptile", function($ui$, view){
<del> var earcut = require('$system/lib/earcut-port.js')().earcut;
<del>
<add>
<ide> this.attributes = {
<ide> tilex:19295,
<ide> tiley:24641,
<ide> }.bind(this));
<ide> }
<ide>
<del> define.class(this, "building", function($ui$, view){
<del>
<del> this.attributes = {
<del> buildings:[],
<del> scalefactor: 1.0
<del> }
<del>
<del> this.boundscheck = false;
<del>
<del> this.onbuildings = function(){
<del> this.pickrange = this.buildings.length;
<del> //console.log("setting pickrange:", this.pickrange);
<del> }
<del>
<del>
<del> this.mouseover = function(){
<del> var building = this.buildings[this.last_pick_id ];
<del> if (building){
<del> var text = "Building";
<del> //console.log(building);
<del>
<del> if (building.kind) text += " " + building.kind;
<del> if (building.name) text += " " + building.name;
<del> if (building.street) text += " " + building.street;
<del> if (building.housenumber) text += " " + building.housenumber;
<del> this.screen.status = text;
<del> }
<del> else{
<del> console.log(this.last_pick_id);
<del> }
<del> }
<del>
<del> this.bg = function(){
<del>
<del> this.vertexstruct = define.struct({
<del> pos:vec3,
<del> color:vec4,
<del> id: float
<del> })
<del>
<del> this.mesh = this.vertexstruct.array();
<del> this.color = function(){
<del>
<del> PickGuid = mesh.id;
<del> return mesh.color;
<del> }
<del>
<del> this.update = function(){
<del> this.mesh = this.vertexstruct.array();
<del>
<del> for(var i = 0;i<this.view.buildings.length;i++){
<del> var building = this.view.buildings[i];
<del>
<del> var theH = building.h;
<del> var isofac =0
<del> var isox = (theH*0.5)*isofac
<del> var isoy = (theH)*isofac
<del>
<del> if (building.arcs)
<del> for(var j = 0;j<building.arcs.length;j++){
<del> var arc = building.arcs[j];
<del> var tris = arctotriangles(arc);
<del> var A1 = vec2(arc[0][0], arc[0][1])
<del> var OA1 = A1;
<del> var c = 0.3;
<del> for(var a = 1;a<arc.length+1;a++)
<del> {
<del> var ca = arc[a%arc.length];
<del>
<del> var A2 = vec2(A1[0] + ca[0], A1[1] + ca[1]);
<del> if (a == arc.length){
<del> A2[1] -= OA1[1];
<del> A2[0] -= OA1[0];
<del> }
<del>
<del> c = 0.7 + 0.3 *Math.sin(Math.atan2(A2[1]-A1[1], A2[0]-A1[0]));
<del>
<del> this.mesh.push(A1[0],A1[1],0, c,c,c, 1, i);
<del> this.mesh.push(A2[0],A2[1],0, c,c,c, 1, i);
<del> this.mesh.push(A2[0]+isox,A2[1]+isoy,theH, c,c,c, 1, i);
<del> this.mesh.push(A1[0],A1[1],0, c,c,c, 1, i);
<del> this.mesh.push(A2[0]+isox,A2[1]+isoy,theH, c,c,c, 1, i);
<del> this.mesh.push(A1[0]+isox,A1[1]+isoy,theH, c,c,c, 1, i);
<del> A1 = A2;
<del>
<del> }
<del> c = 0.4
<del> for(var a = 0;a<tris.length;a++){
<del> this.mesh.push(tris[a][0]+isox,tris[a][1]+isoy,theH, c,c,c, 1, i);
<del> }
<del> }
<del> }
<del> }
<del>
<del> this.position = function(){
<del> return vec4(mesh.pos.x, 1000-mesh.pos.y, mesh.pos.z, 1) * view.totalmatrix * view.viewmatrix
<del> }
<del>
<del> this.drawtype = this.TRIANGLES
<del> this.linewidth = 4
<del>
<del> }
<del> })
<del>
<del> define.class(this, "land", function($ui$, view){
<del> this.boundscheck = false;
<del> this.attributes = {
<del> lands:[]
<del> }
<del>
<del> this.mouseover = function(evt){
<del> //console.log(this.last_pick_id)
<del> var text = "Land: " + this.lands[this.last_pick_id ].kind;
<del>
<del> this.screen.status = text;
<del> }
<del>
<del>
<del> this.onlands = function(){
<del> this.pickrange = this.lands.length;
<del> }
<del>
<del> this.bg = function(){
<del>
<del> this.color1 = {retail:vec4(0,0,1,0.5), tower:"white",library:"white",common:"white", sports_centre:"red", bridge:"gray", university:"red", breakwater:"blue", playground:"lime",forest:"darkgreen",pitch:"lime", grass:"lime", village_green:"green", garden:"green",residential:"gray" , footway:"gray", pedestrian:"gray", water:"#40a0ff",pedestrian:"lightgray", parking:"gray", park:"lime", earth:"lime", pier:"#404040", "rail" : vec4("purple"), "minor_road": vec4("orange"), "major_road" : vec4("red"), highway:vec4("black")}
<del> this.color2 = {retail:vec4(0,0,1,0.5), tower:"gray", library:"gray", common:"gray", sports_centre:"white", bridge:"white", university:"black", breakwater:"green", playground:"red", forest:"black",pitch:"green", grass:"green", village_green:"green", garden:"#40d080", residential:"lightgray" , footway:"yellow", pedestrian:"blue",water:"#f0ffff",pedestrian:"yellow", parking:"lightgray", park:"yellow", earth:"green", pier:"gray", "rail" : vec4("purple"), "minor_road": vec4("orange"), "major_road" : vec4("red"), highway:vec4("black")}
<del>
<del> this.vertexstruct = define.struct({
<del> pos:vec2,
<del> color1:vec4,
<del> color2:vec4,
<del> id: float
<del> })
<del>
<del> this.mesh = this.vertexstruct.array();
<del>
<del> this.color = function(){
<del> var xy = vec2(mesh.pos.xy)*0.2
<del> //var n1 = (noise.noise2d(xy))*0.25 + 0.25;
<del> //var n2 = 0.8*noise.noise2d(xy*2.3)
<del> var themix = 0.5
<del> PickGuid = mesh.id
<del> //mod(mesh.id, 256.)
<del> //PickGuid.y = floor(mesh.id/256.)
<del> return mix(mesh.color1, mesh.color2,themix);
<del> }
<del>
<del> this.update = function(){
<del> this.mesh = this.vertexstruct.array();
<del>
<del> for(var i = 0;i<this.view.lands.length;i++){
<del> var land = this.view.lands[i];
<del>
<del> var color1 = vec4("black");
<del> var color2 = vec4("black");
<del>
<del> if (this.color1[land.kind]) color1 = this.color1[land.kind];else UnhandledKindSet[land.kind] = true;
<del> if (this.color2[land.kind]) color2 = this.color2[land.kind];else UnhandledKindSet[land.kind] = true;
<del>
<del> if (land.arcs){
<del> for(var j = 0;j<land.arcs.length;j++){
<del> var arc = land.arcs[j];
<del> var tris = arctotriangles(arc);
<del> for(var a = 0;a<tris.length;a++){
<del> this.mesh.push(tris[a], vec4(color1), vec4(color2), i);
<del> }
<del> }
<del> }
<del> }
<del> }
<del>
<del> this.position = function(){
<del> return vec4(mesh.pos.x, 1000-mesh.pos.y, 0, 1) * view.totalmatrix * view.viewmatrix
<del> }
<del>
<del> this.drawtype = this.TRIANGLES
<del> this.linewidth = 4
<del> }
<del> })
<del>
<del> define.class(this, "road", function($ui$, view){
<del> this.boundscheck = false;
<del>
<del> this.attributes = {
<del> roads:[],
<del> zoomlevel: 16,
<del> zoomscale: 2.0
<del> }
<del> this.bg = function(){
<del> this.vertexstruct = define.struct({
<del> pos:vec2,
<del> color:vec4,
<del> side: float,
<del> dist: float,
<del> linewidth:float,
<del> sidevec:vec2,
<del> markcolor: vec4
<del> })
<del>
<del> this.mesh = this.vertexstruct.array();
<del>
<del> this.color = function(){
<del> if (abs(mesh.side) > 0.85) return mix("black", mesh.color, 0.8)
<del> // if (abs(mesh.side) > 0.75) return mix(mesh.markcolor, mesh.color, 0.6)
<del> // if (abs(mesh.side) < 0.1) return mix(mesh.markcolor, mesh.color, 0.6 * (min(1., max(0.0,0.8 + 5.0*sin(mesh.dist*0.5)))))
<del> return mesh.color;
<del> }
<del>
<del> this.widths = {water:20, path:2,ferry:4, "rail" : 4, "minor_road": 8, "major_road" : 12, path: 3, highway:12}
<del> this.colors = {water:"#30a0ff", path:"#d0d0d0", ferry:"lightblue", "rail" : vec4("purple"), "minor_road": vec4("#505050"), "major_road" : vec4("#404040"), highway:vec4("#303030")}
<del> this.markcolors = {water:"#30a0ff", major_road:"white", minor_road:"#a0a0a0"}
<del>
<del> this.update = function(){
<del> //console.log("updating");
<del> this.mesh = this.vertexstruct.array();
<del>
<del> for (var i = 0;i<this.view.roads.length;i++){
<del> var R = this.view.roads[i];
<del> //console.log(R);
<del> var linewidth = 3;
<del> var color = vec4("gray") ;
<del> if (this.widths[R.kind]) linewidth = this.widths[R.kind];
<del> if (this.colors[R.kind]) color = vec4(this.colors[R.kind]);
<del> var markcolor = color;
<del> if (this.markcolors[R.kind]) markcolor = vec4(this.markcolors[R.kind]);
<del>
<del> // linewidth *= Math.pow(2, this.view.zoomlevel-14);
<del>
<del> for(var rr = 0;rr<R.arcs.length;rr++){
<del>
<del>
<del> var currentarc = R.arcs[rr]
<del> if (currentarc.length == 1){
<del> continue
<del> }
<del> // console.log(R, currentarc, currentarc.length, currentarc[0].length);
<del>
<del> //console.log(R, currentarc);
<del> //continue;
<del> var A0 = currentarc[0];
<del> var A1 = vec2(currentarc[1][0]+A0[0],currentarc[1][1]+A0[1]) ;
<del>
<del> //this.mesh.push(A0[0], A0[1], this.view.color);
<del> var nx = A0[0];
<del> var ny = A0[1];
<del>
<del> var odx = A1[0]-A0[0];
<del> var ody = A1[1]-A0[1];
<del>
<del> var predelta = vec2.normalize(vec2(odx, ody));
<del> var presdelta = vec2.rotate(predelta, 3.1415/2.0);
<del>
<del>
<del>
<del> var dist = 0;
<del> var dist2 = 0;
<del> var lastsdelta = vec2(0,0);
<del> // color = vec4("blue");
<del> this.mesh.push(nx,ny, color, 1, dist,linewidth,presdelta, markcolor);
<del> this.mesh.push(nx,ny, color, -1, dist,linewidth,presdelta, markcolor);
<del>
<del> this.mesh.push(nx - predelta[0]*linewidth*0.5,ny - predelta[1]*linewidth*0.5, color, 0.5, -10 ,linewidth,presdelta, markcolor);
<del>
<del> this.mesh.push(nx - predelta[0]*linewidth*0.5,ny - predelta[1]*linewidth*0.5, color, 0.5, -10 ,linewidth,presdelta, markcolor);
<del> this.mesh.push(nx - predelta[0]*linewidth*0.5,ny - predelta[1]*linewidth*0.5, color, -0.5, -10 ,linewidth,presdelta, markcolor);
<del>
<del> //this.mesh.push(nx,ny, color, 1, dist,linewidth,presdelta, markcolor);
<del> this.mesh.push(nx,ny, color, -1, dist,linewidth,presdelta, markcolor);
<del>
<del>
<del> // color = vec4(0,0,0.03,0.1)
<del> var lastdelta = vec2(0);
<del> for(var a = 1;a<currentarc.length;a++){
<del> var A =currentarc[a];
<del>
<del> var tnx = nx + A[0];
<del> var tny = ny + A[1];
<del> var predelt = vec2( tnx - nx, tny - ny);
<del> var delta = vec2.normalize(predelt);
<del> var sdelta = vec2.rotate(delta, PI/2);
<del>
<del> var dist2 = dist + vec2.len(predelt);
<del>
<del> if (a>1){
<del> this.mesh.push(nx,ny, color, 1, dist,linewidth,lastsdelta, markcolor);
<del> this.mesh.push(nx,ny, color, 1, dist,linewidth,sdelta, markcolor);
<del> this.mesh.push(nx,ny, color, -1, dist,linewidth,sdelta, markcolor);
<del>
<del> this.mesh.push(nx,ny, color, 1, dist,linewidth,lastsdelta, markcolor);
<del> this.mesh.push(nx,ny, color,-1, dist,linewidth,sdelta, markcolor);
<del> this.mesh.push(nx,ny, color, -1, dist,linewidth,lastsdelta, markcolor);
<del>
<del> }
<del> //color = vec4(0,1,0,0.2)
<del> this.mesh.push( nx, ny,color, 1, dist ,linewidth, sdelta, markcolor);
<del> this.mesh.push( nx, ny,color,-1, dist ,linewidth, sdelta, markcolor);
<del> this.mesh.push(tnx,tny,color, 1, dist2,linewidth, sdelta, markcolor);
<del>
<del> this.mesh.push(nx,ny,color,-1, dist,linewidth, sdelta, markcolor);
<del> this.mesh.push(tnx,tny,color,1,dist2,linewidth, sdelta, markcolor);
<del> this.mesh.push(tnx,tny,color,-1, dist2,linewidth, sdelta, markcolor);
<del>
<del> lastsdelta = vec2(sdelta[0], sdelta[1]);
<del> dist = dist2;
<del> nx = tnx;
<del> ny = tny;
<del> lastdelta = delta;
<del> }
<del> // color = vec4("red");
<del> this.mesh.push(nx,ny, color, 1, dist,linewidth,lastsdelta, markcolor);
<del> this.mesh.push(nx,ny, color, -1, dist,linewidth,lastsdelta, markcolor);
<del> this.mesh.push(nx + lastdelta[0]*linewidth*0.5,ny + lastdelta[1]*linewidth*0.5, color, 0.5, dist+linewidth*0.5 ,linewidth,lastsdelta, markcolor);
<del>
<del> this.mesh.push(nx + lastdelta[0]*linewidth*0.5,ny + lastdelta[1]*linewidth*0.5, color, 0.5, dist+linewidth*0.5 ,linewidth,lastsdelta, markcolor);
<del> this.mesh.push(nx + lastdelta[0]*linewidth*0.5,ny + lastdelta[1]*linewidth*0.5, color, -0.5, dist+linewidth*0.5,linewidth,lastsdelta, markcolor);
<del> this.mesh.push(nx,ny, color, -1, dist,linewidth,presdelta, markcolor);
<del>
<del> }
<del> }
<del> }
<del> this.position = function(){
<del> var pos = mesh.pos + mesh.sidevec * mesh.side * view.zoomscale*mesh.linewidth*0.5;
<del> return vec4(pos.x, 1000-pos.y, 0, 1) * view.totalmatrix * view.viewmatrix
<del> }
<del>
<del> this.drawtype = this.TRIANGLES
<del> this.linewidth = 4;
<del>
<del> }
<del>
<del>
<del> })
<del>
<del> function arctotriangles(arc){
<del> if (!arc) return [];
<del> var verts = [];
<del> var flatverts = [];
<del> var A0 = arc[0];
<del> var nx = A0[0];
<del> var ny = A0[1];
<del> // verts.push(A0);
<del> flatverts.push(nx);
<del> flatverts.push(ny);
<del> for (var i =1 ;i<arc.length;i++){
<del> var A = arc[i];
<del> nx += A[0];
<del> ny += A[1];
<del> // verts.push(vec2(nx,ny));
<del> flatverts.push(nx);
<del> flatverts.push(ny);
<del> }
<del>
<del> var triangles = earcut(flatverts);
<del>
<del> for(var i = 0;i<triangles.length;i++){
<del> idx = triangles[i];
<del> verts.push(vec2(flatverts[idx*2],flatverts[idx*2 + 1]));
<del> }
<del> return verts;
<del>
<del> }
<del>
<add>
<ide>
<ide> this.loadstring = function(str){
<ide> this.thedata = JSON.parse(str);
<ide> var Wset = [];
<ide> var Eset = [];
<ide> var Lset = [];
<del>
<add> console.log(this.thedata);
<ide> for (var i = 0;i<this.thedata.objects.buildings.geometries.length;i++){
<ide> var Bb = this.thedata.objects.buildings.geometries[i];
<ide> var B = {h:Bb.properties.height?Bb.properties.height:3.0,kind:Bb.properties.kind, name:Bb.properties.name, street: Bb.properties["addr_street"], housenumber: Bb.properties.addr_housenumber, arcs:[]};
<ide> this.render = function(){
<ide> var res = [];
<ide>
<del> res.push(this.land({lands:this.earths}));
<del>
<del> res.push(this.land({lands:this.landuses}));
<del>
<del> res.push(this.land({lands:this.waters}));
<del>
<del> res.push(this.road({name:"theroads", roads: this.roads, zoomscale:Math.pow(2.0, this.zoomlevel-15)}));
<del>
<del> res.push(this.building({buildings: this.buildings}));
<add> res.push(this.outer.land({lands:this.earths}));
<add>
<add> res.push(this.outer.land({lands:this.landuses}));
<add>
<add> res.push(this.outer.land({lands:this.waters}));
<add>
<add> res.push(this.outer.road({name:"theroads", roads: this.roads, zoomscale:Math.pow(2.0, this.zoomlevel-15)}));
<add>
<add> res.push(this.outer.building({buildings: this.buildings}));
<ide>
<ide> return res;
<ide> }
<ide> this.render = function(){ return [
<ide> fileio(),
<ide> this.urlfetch({name:"urlfetch"}),
<add>
<ide> screen({name:"index", style:{
<ide> $:{
<ide> fontsize:12
<ide> }
<add> },
<add> moveTo: function(x,y,zoom){
<add> this.find("themap").moveTo(x,y,zoom);
<ide> },
<ide> onstatus:function(){this.find("themenu").infotext = this.status;},
<ide> clearcolor:vec4('#303030'), overflow:'hidden', title:"VectorMap" },
<ide> ]}
<ide> ),
<ide> view({flex:1, overflow:"scroll", bgcolor:"darkblue", clearcolor:"#505050", onzoom: function(){this.find("themap").setZoomLevel(this.zoom, this.layout.width, this.layout.height);}},
<del> this.mainscreen({
<del>
<del> camera:[0,0,1000 ], lookat:[1000,1000,0],nearplane:10, farplane:20000, up:[0,0,-1],viewport:"3d",
<del> boundscheck:false, flex:1,
<add> this.mainscreen({
<add> camera:[0,0,1000 ], lookat:[1000,1000,0],nearplane:10, farplane:12000, up:[0,0,-1],viewport:"3d",
<add> boundscheck:false, flex:1,
<ide> })
<del> //,view({width:2000, height:2000, bg:0})
<del> )
<add> //,view({width:2000, height:2000, bg:0})
<add> )
<ide>
<ide>
<ide> )
<ide> console.log(this.rpc.index)
<ide> },
<ide> clearcolor:vec4('darkgray'), overflow:'hidden', title:"VectorMap remote" },
<del> speakergrid({justifycontent:"center", alignitems:"center" })
<add> speakergrid({justifycontent:"center", alignitems:"center" }
<add> ,button({text:"Manhattan",click:function(){this.rpc.index.moveTo(9647*2,12320*2, 16);}, margin:2})
<add> ,button({text:"Amsterdam",click:function(){this.rpc.index.moveTo(33656,21534, 16);}, margin:2})
<add> ,button({text:"Noord Amsterdam",click:function(){this.rpc.index.moveTo(33656,21434, 16);}, margin:2})
<add> ,button({text:"Sausalito",click:function(){this.rpc.index.moveTo(9647,12320, 16);}, margin:2})
<add> ,button({text:"San Fransisco",click:function(){this.rpc.index.moveTo(9647,12320, 16);}, margin:2})
<add> )
<ide> )
<ide> ]}
<ide> }) |
|
Java | agpl-3.0 | c16c76e4c886173f864cb6a9780107ff4f471363 | 0 | wbaumann/SmartReceiptsLibrary,JuliaSoboleva/SmartReceiptsLibrary,JuliaSoboleva/SmartReceiptsLibrary,wbaumann/SmartReceiptsLibrary,JuliaSoboleva/SmartReceiptsLibrary,wbaumann/SmartReceiptsLibrary | package co.smartreceipts.android.receipts;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.github.clans.fab.FloatingActionMenu;
import com.google.common.base.Preconditions;
import com.jakewharton.rxbinding2.view.RxView;
import com.tapadoo.alerter.Alert;
import com.tapadoo.alerter.Alerter;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import co.smartreceipts.android.R;
import co.smartreceipts.android.activities.NavigationHandler;
import co.smartreceipts.android.adapters.ReceiptCardAdapter;
import co.smartreceipts.android.analytics.Analytics;
import co.smartreceipts.android.analytics.events.Events;
import co.smartreceipts.android.config.ConfigurationManager;
import co.smartreceipts.android.fragments.ImportPhotoPdfDialogFragment;
import co.smartreceipts.android.fragments.ReceiptMoveCopyDialogFragment;
import co.smartreceipts.android.fragments.ReportInfoFragment;
import co.smartreceipts.android.imports.AttachmentSendFileImporter;
import co.smartreceipts.android.imports.CameraInteractionController;
import co.smartreceipts.android.imports.RequestCodes;
import co.smartreceipts.android.imports.importer.ActivityFileResultImporter;
import co.smartreceipts.android.imports.intents.IntentImportProcessor;
import co.smartreceipts.android.imports.intents.model.FileType;
import co.smartreceipts.android.imports.intents.model.IntentImportResult;
import co.smartreceipts.android.imports.locator.ActivityFileResultLocator;
import co.smartreceipts.android.imports.locator.ActivityFileResultLocatorResponse;
import co.smartreceipts.android.model.Receipt;
import co.smartreceipts.android.model.Trip;
import co.smartreceipts.android.model.factory.ReceiptBuilderFactory;
import co.smartreceipts.android.ocr.OcrManager;
import co.smartreceipts.android.ocr.widget.alert.OcrStatusAlerterPresenter;
import co.smartreceipts.android.ocr.widget.alert.OcrStatusAlerterView;
import co.smartreceipts.android.permissions.PermissionsDelegate;
import co.smartreceipts.android.permissions.exceptions.PermissionsNotGrantedException;
import co.smartreceipts.android.persistence.PersistenceManager;
import co.smartreceipts.android.persistence.database.controllers.ReceiptTableEventsListener;
import co.smartreceipts.android.persistence.database.controllers.impl.ReceiptTableController;
import co.smartreceipts.android.persistence.database.controllers.impl.StubTableEventsListener;
import co.smartreceipts.android.persistence.database.controllers.impl.TripTableController;
import co.smartreceipts.android.persistence.database.operations.DatabaseOperationMetadata;
import co.smartreceipts.android.persistence.database.operations.OperationFamilyType;
import co.smartreceipts.android.receipts.creator.ReceiptCreateActionPresenter;
import co.smartreceipts.android.receipts.creator.ReceiptCreateActionView;
import co.smartreceipts.android.receipts.delete.DeleteReceiptDialogFragment;
import co.smartreceipts.android.sync.BackupProvidersManager;
import co.smartreceipts.android.utils.log.Logger;
import co.smartreceipts.android.widget.model.UiIndicator;
import co.smartreceipts.android.widget.rxbinding2.RxFloatingActionMenu;
import dagger.android.support.AndroidSupportInjection;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import wb.android.dialog.BetterDialogBuilder;
import wb.android.flex.Flex;
public class ReceiptsListFragment extends ReceiptsFragment implements ReceiptTableEventsListener, ReceiptCreateActionView,
OcrStatusAlerterView {
public static final String READ_PERMISSION = Manifest.permission.READ_EXTERNAL_STORAGE;
// Outstate
private static final String OUT_HIGHLIGHTED_RECEIPT = "out_highlighted_receipt";
private static final String OUT_IMAGE_URI = "out_image_uri";
@Inject
Flex flex;
@Inject
PersistenceManager persistenceManager;
@Inject
ConfigurationManager configurationManager;
@Inject
Analytics analytics;
@Inject
TripTableController tripTableController;
@Inject
ReceiptTableController receiptTableController;
@Inject
BackupProvidersManager backupProvidersManager;
@Inject
OcrManager ocrManager;
@Inject
NavigationHandler navigationHandler;
@Inject
ActivityFileResultImporter activityFileResultImporter;
@Inject
ActivityFileResultLocator activityFileResultLocator;
@Inject
PermissionsDelegate permissionsDelegate;
@Inject
IntentImportProcessor intentImportProcessor;
@Inject
ReceiptCreateActionPresenter receiptCreateActionPresenter;
@Inject
OcrStatusAlerterPresenter ocrStatusAlerterPresenter;
@BindView(R.id.progress)
ProgressBar loadingProgress;
@BindView(R.id.progress_adding_new)
ProgressBar updatingDataProgress;
@BindView(R.id.no_data)
TextView noDataAlert;
@BindView(R.id.receipt_action_camera)
View receiptActionCameraButton;
@BindView(R.id.receipt_action_text)
View receiptActionTextButton;
@BindView(R.id.receipt_action_import)
View receiptActionImportButton;
@BindView(R.id.fab_menu)
FloatingActionMenu floatingActionMenu;
@BindView(R.id.fab_active_mask)
View floatingActionMenuActiveMaskView;
// Non Butter Knife Views
private Alerter alerter;
private Alert alert;
private Unbinder unbinder;
private ReceiptCardAdapter adapter;
private Receipt highlightedReceipt;
private Uri imageUri;
// Note: Some behaviors need to be handled in separate lifecycle events, so we use different Disposables
private CompositeDisposable onCreateCompositeDisposable;
private CompositeDisposable onResumeCompositeDisposable = new CompositeDisposable();
private ActionBarSubtitleUpdatesListener actionBarSubtitleUpdatesListener = new ActionBarSubtitleUpdatesListener();
@Override
public void onAttach(Context context) {
AndroidSupportInjection.inject(this);
super.onAttach(context);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new ReceiptCardAdapter(getActivity(), navigationHandler, persistenceManager.getPreferenceManager(), backupProvidersManager);
if (savedInstanceState != null) {
imageUri = savedInstanceState.getParcelable(OUT_IMAGE_URI);
highlightedReceipt = savedInstanceState.getParcelable(OUT_HIGHLIGHTED_RECEIPT);
}
// we need to subscribe here because of possible permission dialog showing
subscribeOnCreate();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Create our OCR drop-down alerter
this.alerter = Alerter.create(getActivity())
.setTitle(R.string.ocr_status_title)
.setBackgroundColor(R.color.smart_receipts_colorAccent)
.setIcon(R.drawable.ic_receipt_white_24dp);
// And inflate the root view
return inflater.inflate(R.layout.receipt_fragment_layout, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.unbinder = ButterKnife.bind(this, view);
receiptActionTextButton.setVisibility(configurationManager.isTextReceiptsOptionAvailable() ? View.VISIBLE : View.GONE);
floatingActionMenuActiveMaskView.setOnClickListener(v -> {
// Intentional stub to block click events when this view is active
});
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
trip = ((ReportInfoFragment) getParentFragment()).getTrip();
Preconditions.checkNotNull(trip, "A valid trip is required");
setListAdapter(adapter); // Set this here to ensure this has been laid out already
}
@Override
public void onResume() {
super.onResume();
tripTableController.subscribe(actionBarSubtitleUpdatesListener);
receiptTableController.subscribe(this);
receiptTableController.get(trip);
ocrStatusAlerterPresenter.subscribe();
receiptCreateActionPresenter.subscribe();
onResumeCompositeDisposable.add(activityFileResultImporter.getResultStream()
.subscribe(response -> {
Logger.info(ReceiptsListFragment.this, "Handled the import of {}", response);
if (!response.getThrowable().isPresent()) {
switch (response.getRequestCode()) {
case RequestCodes.IMPORT_GALLERY_IMAGE:
case RequestCodes.IMPORT_GALLERY_PDF:
case RequestCodes.NATIVE_NEW_RECEIPT_CAMERA_REQUEST:
navigationHandler.navigateToCreateNewReceiptFragment(trip, response.getFile(), response.getOcrResponse());
break;
case RequestCodes.NATIVE_ADD_PHOTO_CAMERA_REQUEST:
final Receipt updatedReceipt = new ReceiptBuilderFactory(highlightedReceipt).setImage(response.getFile()).build();
receiptTableController.update(highlightedReceipt, updatedReceipt, new DatabaseOperationMetadata());
break;
}
} else {
Toast.makeText(getActivity(), getFlexString(R.string.FILE_SAVE_ERROR), Toast.LENGTH_SHORT).show();
}
highlightedReceipt = null;
if (updatingDataProgress != null) {
updatingDataProgress.setVisibility(View.GONE);
}
// Indicate that we consumed these results to avoid using this same stream on the next event
activityFileResultLocator.markThatResultsWereConsumed();
activityFileResultImporter.markThatResultsWereConsumed();
}));
}
private void subscribeOnCreate() {
onCreateCompositeDisposable = new CompositeDisposable();
onCreateCompositeDisposable.add(activityFileResultLocator.getUriStream()
.observeOn(AndroidSchedulers.mainThread())
.flatMapSingle(response -> {
if (response.getUri().getScheme() != null && response.getUri().getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
return Single.just(response);
} else { // we need to check read external storage permission
return permissionsDelegate.checkPermissionAndMaybeAsk(READ_PERMISSION)
.toSingleDefault(response)
.onErrorReturn(ActivityFileResultLocatorResponse::LocatorError);
}
})
.subscribe(locatorResponse -> {
if (!locatorResponse.getThrowable().isPresent()) {
updatingDataProgress.setVisibility(View.VISIBLE);
activityFileResultImporter.importFile(locatorResponse.getRequestCode(),
locatorResponse.getResultCode(), locatorResponse.getUri(), trip);
} else {
if (locatorResponse.getThrowable().get() instanceof PermissionsNotGrantedException) {
Toast.makeText(getActivity(), getString(R.string.toast_no_storage_permissions), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), getFlexString(R.string.FILE_SAVE_ERROR), Toast.LENGTH_SHORT).show();
}
highlightedReceipt = null;
updatingDataProgress.setVisibility(View.GONE);
activityFileResultLocator.markThatResultsWereConsumed();
}
}));
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getView() != null && isVisibleToUser) {
// Refresh as soon as we're visible
receiptTableController.get(trip);
}
}
@Override
public void onPause() {
onResumeCompositeDisposable.clear();
receiptCreateActionPresenter.unsubscribe();
ocrStatusAlerterPresenter.unsubscribe();
floatingActionMenu.close(false);
receiptTableController.unsubscribe(this);
tripTableController.unsubscribe(actionBarSubtitleUpdatesListener);
super.onPause();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(OUT_IMAGE_URI, imageUri);
outState.putParcelable(OUT_HIGHLIGHTED_RECEIPT, highlightedReceipt);
}
@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
Logger.debug(this, "onActivityResult");
Logger.debug(this, "Result Code: {}", resultCode);
Logger.debug(this, "Request Code: {}", requestCode);
// Need to make this call here, since users with "Don't keep activities" will hit this call
// before any of onCreate/onStart/onResume is called. This should restore our current trip (what
// onResume() would normally do to prevent a variety of crashes that we might encounter
if (trip == null) {
trip = ((ReportInfoFragment) getParentFragment()).getTrip();
}
// Null out the last request
final Uri cachedImageSaveLocation = imageUri;
imageUri = null;
updatingDataProgress.setVisibility(View.VISIBLE);
activityFileResultLocator.onActivityResult(requestCode, resultCode, data, cachedImageSaveLocation);
if (resultCode != Activity.RESULT_OK) {
updatingDataProgress.setVisibility(View.GONE);
}
}
@Override
public void onDestroyView() {
Logger.debug(this, "onDestroyView");
this.alert = null;
this.alerter = null;
this.unbinder.unbind();
super.onDestroyView();
}
@Override
public void onDestroy() {
onCreateCompositeDisposable.clear();
super.onDestroy();
}
@Override
protected PersistenceManager getPersistenceManager() {
return persistenceManager;
}
public final boolean showReceiptMenu(final Receipt receipt) {
highlightedReceipt = receipt;
final BetterDialogBuilder builder = new BetterDialogBuilder(getActivity());
builder.setTitle(receipt.getName()).setCancelable(true).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
final IntentImportResult intentImportResult = intentImportProcessor.getLastResult();
if (intentImportResult != null && (intentImportResult.getFileType() == FileType.Image || intentImportResult.getFileType() == FileType.Pdf)) {
final String[] receiptActions;
final int attachmentStringId = intentImportResult.getFileType() == FileType.Pdf ? R.string.pdf : R.string.image;
final int receiptStringId = receipt.hasPDF() ? R.string.pdf : R.string.image;
final String attachFile = getString(R.string.action_send_attach, getString(attachmentStringId));
final String viewFile = getString(R.string.action_send_view, getString(receiptStringId));
final String replaceFile = getString(R.string.action_send_replace, getString(receipt.hasPDF() ? R.string.pdf : R.string.image));
if (receipt.hasFile()) {
receiptActions = new String[]{viewFile, replaceFile};
} else {
receiptActions = new String[]{attachFile};
}
builder.setItems(receiptActions, (dialog, item) -> {
final String selection = receiptActions[item];
if (selection != null) {
if (selection.equals(viewFile)) { // Show File
if (intentImportResult.getFileType() == FileType.Pdf) {
ReceiptsListFragment.this.showPDF(receipt);
} else {
ReceiptsListFragment.this.showImage(receipt);
}
} else if (selection.equals(attachFile) || selection.equals(replaceFile)) { // Attach File to Receipt
final AttachmentSendFileImporter importer = new AttachmentSendFileImporter(getActivity(), trip, persistenceManager, receiptTableController, analytics);
onCreateCompositeDisposable.add(importer.importAttachment(intentImportResult, receipt)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(file -> {
// Intentional no-op
}, throwable -> Toast.makeText(getActivity(), R.string.database_error, Toast.LENGTH_SHORT).show()));
}
}
});
} else {
final String receiptActionEdit = getString(R.string.receipt_dialog_action_edit);
final String receiptActionView = getString(R.string.receipt_dialog_action_view, getString(receipt.hasPDF() ? R.string.pdf : R.string.image));
final String receiptActionCamera = getString(R.string.receipt_dialog_action_camera);
final String receiptActionDelete = getString(R.string.receipt_dialog_action_delete);
final String receiptActionMoveCopy = getString(R.string.receipt_dialog_action_move_copy);
final String receiptActionSwapUp = getString(R.string.receipt_dialog_action_swap_up);
final String receiptActionSwapDown = getString(R.string.receipt_dialog_action_swap_down);
final String[] receiptActions;
if (!receipt.hasFile()) {
receiptActions = new String[]{receiptActionEdit, receiptActionCamera, receiptActionDelete, receiptActionMoveCopy, receiptActionSwapUp, receiptActionSwapDown};
} else {
receiptActions = new String[]{receiptActionEdit, receiptActionView, receiptActionDelete, receiptActionMoveCopy, receiptActionSwapUp, receiptActionSwapDown};
}
builder.setItems(receiptActions, (dialog, item) -> {
final String selection = receiptActions[item];
if (selection != null) {
if (selection.equals(receiptActionEdit)) { // Edit Receipt
analytics.record(Events.Receipts.ReceiptMenuEdit);
// ReceiptsListFragment.this.receiptMenu(trip, receipt, null);
navigationHandler.navigateToEditReceiptFragment(trip, receipt);
} else if (selection.equals(receiptActionCamera)) { // Take Photo
analytics.record(Events.Receipts.ReceiptMenuRetakePhoto);
imageUri = new CameraInteractionController(ReceiptsListFragment.this).addPhoto();
} else if (selection.equals(receiptActionView)) { // View Photo/PDF
if (receipt.hasPDF()) {
analytics.record(Events.Receipts.ReceiptMenuViewImage);
ReceiptsListFragment.this.showPDF(receipt);
} else {
analytics.record(Events.Receipts.ReceiptMenuViewPdf);
ReceiptsListFragment.this.showImage(receipt);
}
} else if (selection.equals(receiptActionDelete)) { // Delete Receipt
analytics.record(Events.Receipts.ReceiptMenuDelete);
final DeleteReceiptDialogFragment deleteReceiptDialogFragment = DeleteReceiptDialogFragment.newInstance(receipt);
navigationHandler.showDialog(deleteReceiptDialogFragment);
} else if (selection.equals(receiptActionMoveCopy)) {// Move-Copy
analytics.record(Events.Receipts.ReceiptMenuMoveCopy);
ReceiptMoveCopyDialogFragment.newInstance(receipt).show(getFragmentManager(), ReceiptMoveCopyDialogFragment.TAG);
} else if (selection.equals(receiptActionSwapUp)) { // Swap Up
analytics.record(Events.Receipts.ReceiptMenuSwapUp);
receiptTableController.swapUp(receipt);
} else if (selection.equals(receiptActionSwapDown)) { // Swap Down
analytics.record(Events.Receipts.ReceiptMenuSwapDown);
receiptTableController.swapDown(receipt);
}
}
dialog.cancel();
});
}
builder.show();
return true;
}
private void showImage(@NonNull Receipt receipt) {
navigationHandler.navigateToViewReceiptImage(receipt);
}
private void showPDF(@NonNull Receipt receipt) {
navigationHandler.navigateToViewReceiptPdf(receipt);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
showReceiptMenu(adapter.getItem(position));
}
@Override
public void onGetSuccess(@NonNull List<Receipt> receipts, @NonNull Trip trip) {
if (isAdded()) {
loadingProgress.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
if (receipts.isEmpty()) {
noDataAlert.setVisibility(View.VISIBLE);
} else {
noDataAlert.setVisibility(View.INVISIBLE);
}
adapter.notifyDataSetChanged(receipts);
updateActionBarTitle(getUserVisibleHint());
}
}
@Override
public void onGetFailure(@Nullable Throwable e, @NonNull Trip trip) {
Toast.makeText(getActivity(), R.string.database_get_error, Toast.LENGTH_LONG).show();
}
@Override
public void onGetSuccess(@NonNull List<Receipt> list) {
// TODO: Respond?
}
@Override
public void onGetFailure(@Nullable Throwable e) {
Toast.makeText(getActivity(), R.string.database_get_error, Toast.LENGTH_LONG).show();
}
@Override
public void onInsertSuccess(@NonNull Receipt receipt, @NonNull DatabaseOperationMetadata databaseOperationMetadata) {
if (isResumed()) {
receiptTableController.get(trip);
}
}
@Override
public void onInsertFailure(@NonNull Receipt receipt, @Nullable Throwable e, @NonNull DatabaseOperationMetadata databaseOperationMetadata) {
if (isAdded() && databaseOperationMetadata.getOperationFamilyType() != OperationFamilyType.Sync) {
Toast.makeText(getActivity(), getFlexString(R.string.database_error), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onUpdateSuccess(@NonNull Receipt oldReceipt, @NonNull Receipt newReceipt, @NonNull DatabaseOperationMetadata databaseOperationMetadata) {
if (isAdded()) {
if (databaseOperationMetadata.getOperationFamilyType() != OperationFamilyType.Sync) {
if (newReceipt.getFile() != null && newReceipt.getFileLastModifiedTime() != oldReceipt.getFileLastModifiedTime()) {
final int stringId;
if (oldReceipt.getFile() != null) {
if (newReceipt.hasImage()) {
stringId = R.string.toast_receipt_image_replaced;
} else {
stringId = R.string.toast_receipt_pdf_replaced;
}
} else {
if (newReceipt.hasImage()) {
stringId = R.string.toast_receipt_image_added;
} else {
stringId = R.string.toast_receipt_pdf_added;
}
}
Toast.makeText(getActivity(), getString(stringId, newReceipt.getName()), Toast.LENGTH_SHORT).show();
final IntentImportResult intentImportResult = intentImportProcessor.getLastResult();
if (intentImportResult != null) {
intentImportProcessor.markIntentAsSuccessfullyProcessed(getActivity().getIntent());
getActivity().finish();
}
}
}
// But still refresh for sync operations
receiptTableController.get(trip);
}
}
@Override
public void onUpdateFailure(@NonNull Receipt oldReceipt, @Nullable Throwable e, @NonNull DatabaseOperationMetadata databaseOperationMetadata) {
if (isAdded() && databaseOperationMetadata.getOperationFamilyType() != OperationFamilyType.Sync) {
Toast.makeText(getActivity(), getFlexString(R.string.database_error), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDeleteSuccess(@NonNull Receipt receipt, @NonNull DatabaseOperationMetadata databaseOperationMetadata) {
if (isAdded()) {
receiptTableController.get(trip);
}
}
@Override
public void onDeleteFailure(@NonNull Receipt receipt, @Nullable Throwable e, @NonNull DatabaseOperationMetadata databaseOperationMetadata) {
if (isAdded() && databaseOperationMetadata.getOperationFamilyType() != OperationFamilyType.Sync) {
Toast.makeText(getActivity(), getFlexString(R.string.database_error), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCopySuccess(@NonNull Receipt oldReceipt, @NonNull Receipt newReceipt) {
if (isAdded()) {
receiptTableController.get(trip);
Toast.makeText(getActivity(), getFlexString(R.string.toast_receipt_copy), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCopyFailure(@NonNull Receipt oldReceipt, @Nullable Throwable e) {
if (isAdded()) {
Toast.makeText(getActivity(), getFlexString(R.string.COPY_ERROR), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onSwapSuccess() {
receiptTableController.get(trip);
}
@Override
public void onSwapFailure(@Nullable Throwable e) {
// TODO: Respond?
}
@Override
public void onMoveSuccess(@NonNull Receipt oldReceipt, @NonNull Receipt newReceipt) {
if (isAdded()) {
receiptTableController.get(trip);
Toast.makeText(getActivity(), getFlexString(R.string.toast_receipt_move), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onMoveFailure(@NonNull Receipt oldReceipt, @Nullable Throwable e) {
if (isAdded()) {
Toast.makeText(getActivity(), getFlexString(R.string.MOVE_ERROR), Toast.LENGTH_SHORT).show();
}
}
@Override
public void displayReceiptCreationMenuOptions() {
if (floatingActionMenuActiveMaskView.getVisibility() != View.VISIBLE) { // avoid duplicate animations
floatingActionMenuActiveMaskView.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.out_from_bottom_right));
floatingActionMenuActiveMaskView.setVisibility(View.VISIBLE);
}
}
@Override
public void hideReceiptCreationMenuOptions() {
if (floatingActionMenuActiveMaskView.getVisibility() != View.GONE) { // avoid duplicate animations
floatingActionMenuActiveMaskView.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.in_to_bottom_right));
floatingActionMenuActiveMaskView.setVisibility(View.GONE);
}
}
@Override
public void createNewReceiptViaCamera() {
imageUri = new CameraInteractionController(this).takePhoto();
}
@Override
public void createNewReceiptViaPlainText() {
navigationHandler.navigateToCreateNewReceiptFragment(trip, null, null);
}
@Override
public void createNewReceiptViaFileImport() {
final ImportPhotoPdfDialogFragment fragment = new ImportPhotoPdfDialogFragment();
fragment.show(getChildFragmentManager(), ImportPhotoPdfDialogFragment.TAG);
}
@NonNull
@Override
public Observable<Boolean> getCreateNewReceiptMenuButtonToggles() {
return RxFloatingActionMenu.toggleChanges(floatingActionMenu);
}
@NonNull
@Override
public Observable<Object> getCreateNewReceiptFromCameraButtonClicks() {
return RxView.clicks(receiptActionCameraButton);
}
@NonNull
@Override
public Observable<Object> getCreateNewReceiptFromImportedFileButtonClicks() {
return RxView.clicks(receiptActionImportButton);
}
@NonNull
@Override
public Observable<Object> getCreateNewReceiptFromPlainTextButtonClicks() {
return RxView.clicks(receiptActionTextButton);
}
@Override
public void displayOcrStatus(@NonNull UiIndicator<String> ocrStatusIndicator) {
if (ocrStatusIndicator.getState() == UiIndicator.State.Loading) {
if (alert == null) {
alerter.setText(ocrStatusIndicator.getData().get());
alert = alerter.show();
alert.setEnableInfiniteDuration(true);
} else {
alert.setText(ocrStatusIndicator.getData().get());
}
} else if (alert != null) {
alert.hide();
alert = null;
}
}
private class ActionBarSubtitleUpdatesListener extends StubTableEventsListener<Trip> {
@Override
public void onGetSuccess(@NonNull List<Trip> list) {
if (isAdded()) {
updateActionBarTitle(getUserVisibleHint());
}
}
}
private String getFlexString(int id) {
return getFlexString(flex, id);
}
}
| app/src/main/java/co/smartreceipts/android/receipts/ReceiptsListFragment.java | package co.smartreceipts.android.receipts;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.github.clans.fab.FloatingActionMenu;
import com.google.common.base.Preconditions;
import com.jakewharton.rxbinding2.view.RxView;
import com.tapadoo.alerter.Alert;
import com.tapadoo.alerter.Alerter;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import co.smartreceipts.android.R;
import co.smartreceipts.android.activities.NavigationHandler;
import co.smartreceipts.android.adapters.ReceiptCardAdapter;
import co.smartreceipts.android.analytics.Analytics;
import co.smartreceipts.android.analytics.events.Events;
import co.smartreceipts.android.config.ConfigurationManager;
import co.smartreceipts.android.fragments.ImportPhotoPdfDialogFragment;
import co.smartreceipts.android.fragments.ReceiptMoveCopyDialogFragment;
import co.smartreceipts.android.fragments.ReportInfoFragment;
import co.smartreceipts.android.imports.AttachmentSendFileImporter;
import co.smartreceipts.android.imports.CameraInteractionController;
import co.smartreceipts.android.imports.RequestCodes;
import co.smartreceipts.android.imports.importer.ActivityFileResultImporter;
import co.smartreceipts.android.imports.intents.IntentImportProcessor;
import co.smartreceipts.android.imports.intents.model.FileType;
import co.smartreceipts.android.imports.intents.model.IntentImportResult;
import co.smartreceipts.android.imports.locator.ActivityFileResultLocator;
import co.smartreceipts.android.imports.locator.ActivityFileResultLocatorResponse;
import co.smartreceipts.android.model.Receipt;
import co.smartreceipts.android.model.Trip;
import co.smartreceipts.android.model.factory.ReceiptBuilderFactory;
import co.smartreceipts.android.ocr.OcrManager;
import co.smartreceipts.android.ocr.widget.alert.OcrStatusAlerterPresenter;
import co.smartreceipts.android.ocr.widget.alert.OcrStatusAlerterView;
import co.smartreceipts.android.permissions.PermissionsDelegate;
import co.smartreceipts.android.permissions.exceptions.PermissionsNotGrantedException;
import co.smartreceipts.android.persistence.PersistenceManager;
import co.smartreceipts.android.persistence.database.controllers.ReceiptTableEventsListener;
import co.smartreceipts.android.persistence.database.controllers.impl.ReceiptTableController;
import co.smartreceipts.android.persistence.database.controllers.impl.StubTableEventsListener;
import co.smartreceipts.android.persistence.database.controllers.impl.TripTableController;
import co.smartreceipts.android.persistence.database.operations.DatabaseOperationMetadata;
import co.smartreceipts.android.persistence.database.operations.OperationFamilyType;
import co.smartreceipts.android.receipts.creator.ReceiptCreateActionPresenter;
import co.smartreceipts.android.receipts.creator.ReceiptCreateActionView;
import co.smartreceipts.android.receipts.delete.DeleteReceiptDialogFragment;
import co.smartreceipts.android.sync.BackupProvidersManager;
import co.smartreceipts.android.utils.log.Logger;
import co.smartreceipts.android.widget.model.UiIndicator;
import co.smartreceipts.android.widget.rxbinding2.RxFloatingActionMenu;
import dagger.android.support.AndroidSupportInjection;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import wb.android.dialog.BetterDialogBuilder;
import wb.android.flex.Flex;
public class ReceiptsListFragment extends ReceiptsFragment implements ReceiptTableEventsListener, ReceiptCreateActionView,
OcrStatusAlerterView {
public static final String READ_PERMISSION = Manifest.permission.READ_EXTERNAL_STORAGE;
// Outstate
private static final String OUT_HIGHLIGHTED_RECEIPT = "out_highlighted_receipt";
private static final String OUT_IMAGE_URI = "out_image_uri";
@Inject
Flex flex;
@Inject
PersistenceManager persistenceManager;
@Inject
ConfigurationManager configurationManager;
@Inject
Analytics analytics;
@Inject
TripTableController tripTableController;
@Inject
ReceiptTableController receiptTableController;
@Inject
BackupProvidersManager backupProvidersManager;
@Inject
OcrManager ocrManager;
@Inject
NavigationHandler navigationHandler;
@Inject
ActivityFileResultImporter activityFileResultImporter;
@Inject
ActivityFileResultLocator activityFileResultLocator;
@Inject
PermissionsDelegate permissionsDelegate;
@Inject
IntentImportProcessor intentImportProcessor;
@Inject
ReceiptCreateActionPresenter receiptCreateActionPresenter;
@Inject
OcrStatusAlerterPresenter ocrStatusAlerterPresenter;
@BindView(R.id.progress)
ProgressBar loadingProgress;
@BindView(R.id.progress_adding_new)
ProgressBar updatingDataProgress;
@BindView(R.id.no_data)
TextView noDataAlert;
@BindView(R.id.receipt_action_camera)
View receiptActionCameraButton;
@BindView(R.id.receipt_action_text)
View receiptActionTextButton;
@BindView(R.id.receipt_action_import)
View receiptActionImportButton;
@BindView(R.id.fab_menu)
FloatingActionMenu floatingActionMenu;
@BindView(R.id.fab_active_mask)
View floatingActionMenuActiveMaskView;
// Non Butter Knife Views
private Alerter alerter;
private Alert alert;
private Unbinder unbinder;
private ReceiptCardAdapter adapter;
private Receipt highlightedReceipt;
private Uri imageUri;
// Note: Some behaviors need to be handled in separate lifecycle events, so we use different Disposables
private CompositeDisposable onCreateCompositeDisposable;
private CompositeDisposable onResumeCompositeDisposable = new CompositeDisposable();
private ActionBarSubtitleUpdatesListener actionBarSubtitleUpdatesListener = new ActionBarSubtitleUpdatesListener();
@Override
public void onAttach(Context context) {
AndroidSupportInjection.inject(this);
super.onAttach(context);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new ReceiptCardAdapter(getActivity(), navigationHandler, persistenceManager.getPreferenceManager(), backupProvidersManager);
if (savedInstanceState != null) {
imageUri = savedInstanceState.getParcelable(OUT_IMAGE_URI);
highlightedReceipt = savedInstanceState.getParcelable(OUT_HIGHLIGHTED_RECEIPT);
}
// we need to subscribe here because of possible permission dialog showing
subscribeOnCreate();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Create our OCR drop-down alerter
this.alerter = Alerter.create(getActivity())
.setTitle(R.string.ocr_status_title)
.setBackgroundColor(R.color.smart_receipts_colorAccent)
.setIcon(R.drawable.ic_receipt_white_24dp);
// And inflate the root view
return inflater.inflate(R.layout.receipt_fragment_layout, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.unbinder = ButterKnife.bind(this, view);
receiptActionTextButton.setVisibility(configurationManager.isTextReceiptsOptionAvailable() ? View.VISIBLE : View.GONE);
floatingActionMenuActiveMaskView.setOnClickListener(v -> {
// Intentional stub to block click events when this view is active
});
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
trip = ((ReportInfoFragment) getParentFragment()).getTrip();
Preconditions.checkNotNull(trip, "A valid trip is required");
setListAdapter(adapter); // Set this here to ensure this has been laid out already
}
@Override
public void onResume() {
super.onResume();
tripTableController.subscribe(actionBarSubtitleUpdatesListener);
receiptTableController.subscribe(this);
receiptTableController.get(trip);
ocrStatusAlerterPresenter.subscribe();
receiptCreateActionPresenter.subscribe();
onResumeCompositeDisposable.add(activityFileResultImporter.getResultStream()
.subscribe(response -> {
Logger.info(ReceiptsListFragment.this, "Handled the import of {}", response);
if (!response.getThrowable().isPresent()) {
switch (response.getRequestCode()) {
case RequestCodes.IMPORT_GALLERY_IMAGE:
case RequestCodes.IMPORT_GALLERY_PDF:
case RequestCodes.NATIVE_NEW_RECEIPT_CAMERA_REQUEST:
navigationHandler.navigateToCreateNewReceiptFragment(trip, response.getFile(), response.getOcrResponse());
break;
case RequestCodes.NATIVE_ADD_PHOTO_CAMERA_REQUEST:
final Receipt updatedReceipt = new ReceiptBuilderFactory(highlightedReceipt).setImage(response.getFile()).build();
receiptTableController.update(highlightedReceipt, updatedReceipt, new DatabaseOperationMetadata());
break;
}
} else {
Toast.makeText(getActivity(), getFlexString(R.string.FILE_SAVE_ERROR), Toast.LENGTH_SHORT).show();
}
highlightedReceipt = null;
if (updatingDataProgress != null) {
updatingDataProgress.setVisibility(View.GONE);
}
// Indicate that we consumed these results to avoid using this same stream on the next event
activityFileResultLocator.markThatResultsWereConsumed();
activityFileResultImporter.markThatResultsWereConsumed();
}));
}
private void subscribeOnCreate() {
onCreateCompositeDisposable = new CompositeDisposable();
onCreateCompositeDisposable.add(activityFileResultLocator.getUriStream()
.observeOn(AndroidSchedulers.mainThread())
.flatMapSingle(response -> {
if (response.getUri().getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
return Single.just(response);
} else { // we need to check read external storage permission
return permissionsDelegate.checkPermissionAndMaybeAsk(READ_PERMISSION)
.toSingleDefault(response)
.onErrorReturn(ActivityFileResultLocatorResponse::LocatorError);
}
})
.subscribe(locatorResponse -> {
if (!locatorResponse.getThrowable().isPresent()) {
updatingDataProgress.setVisibility(View.VISIBLE);
activityFileResultImporter.importFile(locatorResponse.getRequestCode(),
locatorResponse.getResultCode(), locatorResponse.getUri(), trip);
} else {
if (locatorResponse.getThrowable().get() instanceof PermissionsNotGrantedException) {
Toast.makeText(getActivity(), getString(R.string.toast_no_storage_permissions), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), getFlexString(R.string.FILE_SAVE_ERROR), Toast.LENGTH_SHORT).show();
}
highlightedReceipt = null;
updatingDataProgress.setVisibility(View.GONE);
activityFileResultLocator.markThatResultsWereConsumed();
}
}));
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getView() != null && isVisibleToUser) {
// Refresh as soon as we're visible
receiptTableController.get(trip);
}
}
@Override
public void onPause() {
onResumeCompositeDisposable.clear();
receiptCreateActionPresenter.unsubscribe();
ocrStatusAlerterPresenter.unsubscribe();
floatingActionMenu.close(false);
receiptTableController.unsubscribe(this);
tripTableController.unsubscribe(actionBarSubtitleUpdatesListener);
super.onPause();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(OUT_IMAGE_URI, imageUri);
outState.putParcelable(OUT_HIGHLIGHTED_RECEIPT, highlightedReceipt);
}
@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
Logger.debug(this, "onActivityResult");
Logger.debug(this, "Result Code: {}", resultCode);
Logger.debug(this, "Request Code: {}", requestCode);
// Need to make this call here, since users with "Don't keep activities" will hit this call
// before any of onCreate/onStart/onResume is called. This should restore our current trip (what
// onResume() would normally do to prevent a variety of crashes that we might encounter
if (trip == null) {
trip = ((ReportInfoFragment) getParentFragment()).getTrip();
}
// Null out the last request
final Uri cachedImageSaveLocation = imageUri;
imageUri = null;
updatingDataProgress.setVisibility(View.VISIBLE);
activityFileResultLocator.onActivityResult(requestCode, resultCode, data, cachedImageSaveLocation);
if (resultCode != Activity.RESULT_OK) {
updatingDataProgress.setVisibility(View.GONE);
}
}
@Override
public void onDestroyView() {
Logger.debug(this, "onDestroyView");
this.alert = null;
this.alerter = null;
this.unbinder.unbind();
super.onDestroyView();
}
@Override
public void onDestroy() {
onCreateCompositeDisposable.clear();
super.onDestroy();
}
@Override
protected PersistenceManager getPersistenceManager() {
return persistenceManager;
}
public final boolean showReceiptMenu(final Receipt receipt) {
highlightedReceipt = receipt;
final BetterDialogBuilder builder = new BetterDialogBuilder(getActivity());
builder.setTitle(receipt.getName()).setCancelable(true).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
final IntentImportResult intentImportResult = intentImportProcessor.getLastResult();
if (intentImportResult != null && (intentImportResult.getFileType() == FileType.Image || intentImportResult.getFileType() == FileType.Pdf)) {
final String[] receiptActions;
final int attachmentStringId = intentImportResult.getFileType() == FileType.Pdf ? R.string.pdf : R.string.image;
final int receiptStringId = receipt.hasPDF() ? R.string.pdf : R.string.image;
final String attachFile = getString(R.string.action_send_attach, getString(attachmentStringId));
final String viewFile = getString(R.string.action_send_view, getString(receiptStringId));
final String replaceFile = getString(R.string.action_send_replace, getString(receipt.hasPDF() ? R.string.pdf : R.string.image));
if (receipt.hasFile()) {
receiptActions = new String[]{viewFile, replaceFile};
} else {
receiptActions = new String[]{attachFile};
}
builder.setItems(receiptActions, (dialog, item) -> {
final String selection = receiptActions[item];
if (selection != null) {
if (selection.equals(viewFile)) { // Show File
if (intentImportResult.getFileType() == FileType.Pdf) {
ReceiptsListFragment.this.showPDF(receipt);
} else {
ReceiptsListFragment.this.showImage(receipt);
}
} else if (selection.equals(attachFile) || selection.equals(replaceFile)) { // Attach File to Receipt
final AttachmentSendFileImporter importer = new AttachmentSendFileImporter(getActivity(), trip, persistenceManager, receiptTableController, analytics);
onCreateCompositeDisposable.add(importer.importAttachment(intentImportResult, receipt)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(file -> {
// Intentional no-op
}, throwable -> Toast.makeText(getActivity(), R.string.database_error, Toast.LENGTH_SHORT).show()));
}
}
});
} else {
final String receiptActionEdit = getString(R.string.receipt_dialog_action_edit);
final String receiptActionView = getString(R.string.receipt_dialog_action_view, getString(receipt.hasPDF() ? R.string.pdf : R.string.image));
final String receiptActionCamera = getString(R.string.receipt_dialog_action_camera);
final String receiptActionDelete = getString(R.string.receipt_dialog_action_delete);
final String receiptActionMoveCopy = getString(R.string.receipt_dialog_action_move_copy);
final String receiptActionSwapUp = getString(R.string.receipt_dialog_action_swap_up);
final String receiptActionSwapDown = getString(R.string.receipt_dialog_action_swap_down);
final String[] receiptActions;
if (!receipt.hasFile()) {
receiptActions = new String[]{receiptActionEdit, receiptActionCamera, receiptActionDelete, receiptActionMoveCopy, receiptActionSwapUp, receiptActionSwapDown};
} else {
receiptActions = new String[]{receiptActionEdit, receiptActionView, receiptActionDelete, receiptActionMoveCopy, receiptActionSwapUp, receiptActionSwapDown};
}
builder.setItems(receiptActions, (dialog, item) -> {
final String selection = receiptActions[item];
if (selection != null) {
if (selection.equals(receiptActionEdit)) { // Edit Receipt
analytics.record(Events.Receipts.ReceiptMenuEdit);
// ReceiptsListFragment.this.receiptMenu(trip, receipt, null);
navigationHandler.navigateToEditReceiptFragment(trip, receipt);
} else if (selection.equals(receiptActionCamera)) { // Take Photo
analytics.record(Events.Receipts.ReceiptMenuRetakePhoto);
imageUri = new CameraInteractionController(ReceiptsListFragment.this).addPhoto();
} else if (selection.equals(receiptActionView)) { // View Photo/PDF
if (receipt.hasPDF()) {
analytics.record(Events.Receipts.ReceiptMenuViewImage);
ReceiptsListFragment.this.showPDF(receipt);
} else {
analytics.record(Events.Receipts.ReceiptMenuViewPdf);
ReceiptsListFragment.this.showImage(receipt);
}
} else if (selection.equals(receiptActionDelete)) { // Delete Receipt
analytics.record(Events.Receipts.ReceiptMenuDelete);
final DeleteReceiptDialogFragment deleteReceiptDialogFragment = DeleteReceiptDialogFragment.newInstance(receipt);
navigationHandler.showDialog(deleteReceiptDialogFragment);
} else if (selection.equals(receiptActionMoveCopy)) {// Move-Copy
analytics.record(Events.Receipts.ReceiptMenuMoveCopy);
ReceiptMoveCopyDialogFragment.newInstance(receipt).show(getFragmentManager(), ReceiptMoveCopyDialogFragment.TAG);
} else if (selection.equals(receiptActionSwapUp)) { // Swap Up
analytics.record(Events.Receipts.ReceiptMenuSwapUp);
receiptTableController.swapUp(receipt);
} else if (selection.equals(receiptActionSwapDown)) { // Swap Down
analytics.record(Events.Receipts.ReceiptMenuSwapDown);
receiptTableController.swapDown(receipt);
}
}
dialog.cancel();
});
}
builder.show();
return true;
}
private void showImage(@NonNull Receipt receipt) {
navigationHandler.navigateToViewReceiptImage(receipt);
}
private void showPDF(@NonNull Receipt receipt) {
navigationHandler.navigateToViewReceiptPdf(receipt);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
showReceiptMenu(adapter.getItem(position));
}
@Override
public void onGetSuccess(@NonNull List<Receipt> receipts, @NonNull Trip trip) {
if (isAdded()) {
loadingProgress.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
if (receipts.isEmpty()) {
noDataAlert.setVisibility(View.VISIBLE);
} else {
noDataAlert.setVisibility(View.INVISIBLE);
}
adapter.notifyDataSetChanged(receipts);
updateActionBarTitle(getUserVisibleHint());
}
}
@Override
public void onGetFailure(@Nullable Throwable e, @NonNull Trip trip) {
Toast.makeText(getActivity(), R.string.database_get_error, Toast.LENGTH_LONG).show();
}
@Override
public void onGetSuccess(@NonNull List<Receipt> list) {
// TODO: Respond?
}
@Override
public void onGetFailure(@Nullable Throwable e) {
Toast.makeText(getActivity(), R.string.database_get_error, Toast.LENGTH_LONG).show();
}
@Override
public void onInsertSuccess(@NonNull Receipt receipt, @NonNull DatabaseOperationMetadata databaseOperationMetadata) {
if (isResumed()) {
receiptTableController.get(trip);
}
}
@Override
public void onInsertFailure(@NonNull Receipt receipt, @Nullable Throwable e, @NonNull DatabaseOperationMetadata databaseOperationMetadata) {
if (isAdded() && databaseOperationMetadata.getOperationFamilyType() != OperationFamilyType.Sync) {
Toast.makeText(getActivity(), getFlexString(R.string.database_error), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onUpdateSuccess(@NonNull Receipt oldReceipt, @NonNull Receipt newReceipt, @NonNull DatabaseOperationMetadata databaseOperationMetadata) {
if (isAdded()) {
if (databaseOperationMetadata.getOperationFamilyType() != OperationFamilyType.Sync) {
if (newReceipt.getFile() != null && newReceipt.getFileLastModifiedTime() != oldReceipt.getFileLastModifiedTime()) {
final int stringId;
if (oldReceipt.getFile() != null) {
if (newReceipt.hasImage()) {
stringId = R.string.toast_receipt_image_replaced;
} else {
stringId = R.string.toast_receipt_pdf_replaced;
}
} else {
if (newReceipt.hasImage()) {
stringId = R.string.toast_receipt_image_added;
} else {
stringId = R.string.toast_receipt_pdf_added;
}
}
Toast.makeText(getActivity(), getString(stringId, newReceipt.getName()), Toast.LENGTH_SHORT).show();
final IntentImportResult intentImportResult = intentImportProcessor.getLastResult();
if (intentImportResult != null) {
intentImportProcessor.markIntentAsSuccessfullyProcessed(getActivity().getIntent());
getActivity().finish();
}
}
}
// But still refresh for sync operations
receiptTableController.get(trip);
}
}
@Override
public void onUpdateFailure(@NonNull Receipt oldReceipt, @Nullable Throwable e, @NonNull DatabaseOperationMetadata databaseOperationMetadata) {
if (isAdded() && databaseOperationMetadata.getOperationFamilyType() != OperationFamilyType.Sync) {
Toast.makeText(getActivity(), getFlexString(R.string.database_error), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDeleteSuccess(@NonNull Receipt receipt, @NonNull DatabaseOperationMetadata databaseOperationMetadata) {
if (isAdded()) {
receiptTableController.get(trip);
}
}
@Override
public void onDeleteFailure(@NonNull Receipt receipt, @Nullable Throwable e, @NonNull DatabaseOperationMetadata databaseOperationMetadata) {
if (isAdded() && databaseOperationMetadata.getOperationFamilyType() != OperationFamilyType.Sync) {
Toast.makeText(getActivity(), getFlexString(R.string.database_error), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCopySuccess(@NonNull Receipt oldReceipt, @NonNull Receipt newReceipt) {
if (isAdded()) {
receiptTableController.get(trip);
Toast.makeText(getActivity(), getFlexString(R.string.toast_receipt_copy), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCopyFailure(@NonNull Receipt oldReceipt, @Nullable Throwable e) {
if (isAdded()) {
Toast.makeText(getActivity(), getFlexString(R.string.COPY_ERROR), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onSwapSuccess() {
receiptTableController.get(trip);
}
@Override
public void onSwapFailure(@Nullable Throwable e) {
// TODO: Respond?
}
@Override
public void onMoveSuccess(@NonNull Receipt oldReceipt, @NonNull Receipt newReceipt) {
if (isAdded()) {
receiptTableController.get(trip);
Toast.makeText(getActivity(), getFlexString(R.string.toast_receipt_move), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onMoveFailure(@NonNull Receipt oldReceipt, @Nullable Throwable e) {
if (isAdded()) {
Toast.makeText(getActivity(), getFlexString(R.string.MOVE_ERROR), Toast.LENGTH_SHORT).show();
}
}
@Override
public void displayReceiptCreationMenuOptions() {
if (floatingActionMenuActiveMaskView.getVisibility() != View.VISIBLE) { // avoid duplicate animations
floatingActionMenuActiveMaskView.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.out_from_bottom_right));
floatingActionMenuActiveMaskView.setVisibility(View.VISIBLE);
}
}
@Override
public void hideReceiptCreationMenuOptions() {
if (floatingActionMenuActiveMaskView.getVisibility() != View.GONE) { // avoid duplicate animations
floatingActionMenuActiveMaskView.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.in_to_bottom_right));
floatingActionMenuActiveMaskView.setVisibility(View.GONE);
}
}
@Override
public void createNewReceiptViaCamera() {
imageUri = new CameraInteractionController(this).takePhoto();
}
@Override
public void createNewReceiptViaPlainText() {
navigationHandler.navigateToCreateNewReceiptFragment(trip, null, null);
}
@Override
public void createNewReceiptViaFileImport() {
final ImportPhotoPdfDialogFragment fragment = new ImportPhotoPdfDialogFragment();
fragment.show(getChildFragmentManager(), ImportPhotoPdfDialogFragment.TAG);
}
@NonNull
@Override
public Observable<Boolean> getCreateNewReceiptMenuButtonToggles() {
return RxFloatingActionMenu.toggleChanges(floatingActionMenu);
}
@NonNull
@Override
public Observable<Object> getCreateNewReceiptFromCameraButtonClicks() {
return RxView.clicks(receiptActionCameraButton);
}
@NonNull
@Override
public Observable<Object> getCreateNewReceiptFromImportedFileButtonClicks() {
return RxView.clicks(receiptActionImportButton);
}
@NonNull
@Override
public Observable<Object> getCreateNewReceiptFromPlainTextButtonClicks() {
return RxView.clicks(receiptActionTextButton);
}
@Override
public void displayOcrStatus(@NonNull UiIndicator<String> ocrStatusIndicator) {
if (ocrStatusIndicator.getState() == UiIndicator.State.Loading) {
if (alert == null) {
alerter.setText(ocrStatusIndicator.getData().get());
alert = alerter.show();
alert.setEnableInfiniteDuration(true);
} else {
alert.setText(ocrStatusIndicator.getData().get());
}
} else if (alert != null) {
alert.hide();
alert = null;
}
}
private class ActionBarSubtitleUpdatesListener extends StubTableEventsListener<Trip> {
@Override
public void onGetSuccess(@NonNull List<Trip> list) {
if (isAdded()) {
updateActionBarTitle(getUserVisibleHint());
}
}
}
private String getFlexString(int id) {
return getFlexString(flex, id);
}
}
| Fixed a potential NPE when importing a URI
| app/src/main/java/co/smartreceipts/android/receipts/ReceiptsListFragment.java | Fixed a potential NPE when importing a URI | <ide><path>pp/src/main/java/co/smartreceipts/android/receipts/ReceiptsListFragment.java
<ide> onCreateCompositeDisposable.add(activityFileResultLocator.getUriStream()
<ide> .observeOn(AndroidSchedulers.mainThread())
<ide> .flatMapSingle(response -> {
<del> if (response.getUri().getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
<add> if (response.getUri().getScheme() != null && response.getUri().getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
<ide> return Single.just(response);
<ide> } else { // we need to check read external storage permission
<ide> return permissionsDelegate.checkPermissionAndMaybeAsk(READ_PERMISSION) |
|
Java | apache-2.0 | c4313d5f1d3b169a265b006065f95d70a3b00765 | 0 | alien4cloud/alien4cloud-cloudify3-provider,alien4cloud/alien4cloud-cloudify3-provider,alien4cloud/alien4cloud-cloudify3-provider | package alien4cloud.paas.cloudify3.service;
import java.util.List;
import java.util.Map;
import org.alien4cloud.tosca.model.definitions.AbstractPropertyValue;
import org.alien4cloud.tosca.model.definitions.ConcatPropertyValue;
import org.alien4cloud.tosca.model.definitions.FunctionPropertyValue;
import org.alien4cloud.tosca.model.definitions.IValue;
import org.alien4cloud.tosca.model.definitions.Interface;
import org.alien4cloud.tosca.model.definitions.Operation;
import org.alien4cloud.tosca.model.definitions.ScalarPropertyValue;
import org.alien4cloud.tosca.model.templates.Capability;
import org.alien4cloud.tosca.normative.constants.ToscaFunctionConstants;
import org.alien4cloud.tosca.utils.ToscaTypeUtils;
import org.springframework.stereotype.Component;
import com.google.common.collect.Lists;
import alien4cloud.exception.InvalidArgumentException;
import alien4cloud.paas.IPaaSTemplate;
import alien4cloud.paas.function.FunctionEvaluator;
import alien4cloud.paas.model.PaaSNodeTemplate;
import alien4cloud.paas.model.PaaSRelationshipTemplate;
import alien4cloud.paas.model.PaaSTopologyDeploymentContext;
import alien4cloud.utils.PropertyUtil;
@Component("property-evaluator-service")
public class PropertyEvaluatorService {
private void processAttributes(Map<String, IValue> attributes, IPaaSTemplate node, Map<String, PaaSNodeTemplate> allNodes) {
if (attributes != null) {
for (Map.Entry<String, IValue> attributeEntry : attributes.entrySet()) {
attributeEntry.setValue(process(attributeEntry.getValue(), node, allNodes));
}
}
}
private void processInterfaces(Map<String, Interface> interfaces, IPaaSTemplate node, Map<String, PaaSNodeTemplate> allNodes) {
if (interfaces != null) {
for (Interface interfazz : interfaces.values()) {
Map<String, Operation> operations = interfazz.getOperations();
if (operations != null) {
for (Operation operation : operations.values()) {
Map<String, IValue> inputs = operation.getInputParameters();
if (inputs != null) {
for (Map.Entry<String, IValue> inputEntry : inputs.entrySet()) {
inputEntry.setValue(process(inputEntry.getValue(), node, allNodes));
}
}
}
}
}
}
}
private void processCapability(Capability capability, IPaaSTemplate node, Map<String, PaaSNodeTemplate> allNodes) {
if (capability != null && capability.getProperties() != null) {
for (Map.Entry<String, AbstractPropertyValue> attributeEntry : capability.getProperties().entrySet()) {
attributeEntry.setValue((AbstractPropertyValue) process(attributeEntry.getValue(), node, allNodes));
}
}
}
/**
* Process the deployment topology, every get_property will be replaced by its own static value retrieved from the topology
*
* @param deploymentContext the deployment context
*/
public void processGetPropertyFunction(PaaSTopologyDeploymentContext deploymentContext) {
Map<String, PaaSNodeTemplate> allNodes = deploymentContext.getPaaSTopology().getAllNodes();
for (PaaSNodeTemplate node : allNodes.values()) {
processAttributes(node.getTemplate().getAttributes(), node, allNodes);
processInterfaces(node.getInterfaces(), node, allNodes);
List<PaaSRelationshipTemplate> relationships = node.getRelationshipTemplates();
if (relationships != null) {
for (PaaSRelationshipTemplate relationship : relationships) {
processAttributes(relationship.getTemplate().getAttributes(), relationship, allNodes);
processInterfaces(relationship.getInterfaces(), relationship, allNodes);
}
}
if (node.getTemplate().getCapabilities() != null) {
for (Map.Entry<String, Capability> capabilityEntry : node.getTemplate().getCapabilities().entrySet()) {
processCapability(capabilityEntry.getValue(), node, allNodes);
}
}
}
}
/**
* Process an IValue (it can be a scalar value, a get_property, get_attribute, get_operation_output or a concat) and replace all get_property occurrence
* with its value and return the new IValue with get_property replaced by its value
*
* @param value the value to be processed
* @return the new value with get_property processed
*/
private IValue process(IValue value, IPaaSTemplate node, Map<String, PaaSNodeTemplate> allNodes) {
if (value instanceof FunctionPropertyValue) {
return processSimpleFunction((FunctionPropertyValue) value, node, allNodes);
} else if (value instanceof ConcatPropertyValue) {
return processConcatFunction((ConcatPropertyValue) value, node, allNodes);
} else {
return value;
}
}
private AbstractPropertyValue processSimpleFunction(FunctionPropertyValue value, IPaaSTemplate node, Map<String, PaaSNodeTemplate> allNodes) {
if (ToscaFunctionConstants.GET_PROPERTY.equals(value.getFunction())) {
String reqTargetValue = evaluateReqTarget(value, node, allNodes);
if (reqTargetValue != null) {
return new ScalarPropertyValue(reqTargetValue);
} else {
AbstractPropertyValue processedValue = FunctionEvaluator.processGetPropertyFunction(value, node, allNodes);
if (processedValue == null ) {
return new ScalarPropertyValue(null);
} else if (processedValue instanceof ConcatPropertyValue || processedValue instanceof FunctionPropertyValue
|| processedValue instanceof ScalarPropertyValue) {
return processedValue;
} else {
return new ScalarPropertyValue(PropertyUtil.serializePropertyValue(processedValue));
}
}
} else {
return value;
}
}
private String evaluateReqTarget(FunctionPropertyValue value, IPaaSTemplate node, Map<String, PaaSNodeTemplate> allNodes) {
if (value.getParameters().contains("REQ_TARGET")) {
// Search for the requirement's target by filter the relationships' templates of this node.
// If a target is found, then lookup for the given property name in its capabilities.
String requirementName = value.getCapabilityOrRequirementName();
String propertyName = value.getElementNameToFetch();
if (node instanceof PaaSNodeTemplate && requirementName != null) {
for (PaaSRelationshipTemplate relationshipTemplate : ((PaaSNodeTemplate) node).getRelationshipTemplates()) {
if (node.getId().equals(relationshipTemplate.getSource())
&& requirementName.equals(relationshipTemplate.getTemplate().getRequirementName())) {
PaaSNodeTemplate target = allNodes.get(relationshipTemplate.getTemplate().getTarget());
String evaluated = kubernetesEvaluationWorkaround(value, (PaaSNodeTemplate) node, target, relationshipTemplate, propertyName);
if (evaluated == null) {
// Search the property in capabilities of the target
String targetedCapabilityName = relationshipTemplate.getTemplate().getTargetedCapabilityName();
FunctionPropertyValue func = new FunctionPropertyValue(value.getFunction(),
Lists.newArrayList(ToscaFunctionConstants.SELF, targetedCapabilityName, propertyName));
evaluated = FunctionEvaluator.evaluateGetPropertyFunction(func, target, allNodes);
if (evaluated == null) {
// If not found in the capability, search the property in the target's node itself.
func = new FunctionPropertyValue(value.getFunction(), Lists.newArrayList(ToscaFunctionConstants.SELF, propertyName));
evaluated = FunctionEvaluator.evaluateGetPropertyFunction(func, target, allNodes);
}
}
if (evaluated != null) {
return evaluated;
}
}
}
}
}
return null;
}
private String kubernetesEvaluationWorkaround(FunctionPropertyValue value, PaaSNodeTemplate node, PaaSNodeTemplate target,
PaaSRelationshipTemplate relationshipTemplate, String propertyName) {
// If the node is a docker type, special case for port and ip_address properties
// as it must be handled by the Cloudify's kubernetes plugin
boolean dockerTypeNode = ToscaTypeUtils.isOfType(node.getIndexedToscaElement(), BlueprintService.TOSCA_DOCKER_CONTAINER_TYPE);
boolean connectsToRelationship = relationshipTemplate.instanceOf("tosca.relationships.ConnectsTo");
boolean portOrIpAddress = ("port".equalsIgnoreCase(propertyName) || "ip_address".equalsIgnoreCase(propertyName));
if (dockerTypeNode && connectsToRelationship && portOrIpAddress) {
// Particular treatment for port and ip_address that needs to be retrieved at runtime from the kubernetes plugin of cloudify.
// We need to generate a kind of custom function for the plugin in the generated blueprint.
if ("ip_address".equalsIgnoreCase(propertyName)) {
if (ToscaTypeUtils.isOfType(target.getIndexedToscaElement(), BlueprintService.TOSCA_DOCKER_CONTAINER_TYPE)) {
propertyName = "clusterIP";
} else { // Workaround(cfy3): If the property is 'ip_address', change it to 'ip'
propertyName = "ip";
}
}
// Return a string as "function_name, node_id, property_name" (c.f. kubernetes.yaml.vm)
return String.format("%s,%s,%s", value.getFunction(), relationshipTemplate.getTemplate().getTarget(), propertyName);
}
return null;
}
private IValue processConcatFunction(ConcatPropertyValue concatPropertyValue, IPaaSTemplate node, Map<String, PaaSNodeTemplate> allNodes) {
if (concatPropertyValue.getParameters() == null || concatPropertyValue.getParameters().isEmpty()) {
throw new InvalidArgumentException("Parameter list for concat function is empty");
}
for (int i = 0; i < concatPropertyValue.getParameters().size(); i++) {
IValue concatParam = concatPropertyValue.getParameters().get(i);
if (concatParam instanceof FunctionPropertyValue) {
concatPropertyValue.getParameters().set(i, processSimpleFunction((FunctionPropertyValue) concatParam, node, allNodes));
}
}
return concatPropertyValue;
}
}
| alien4cloud-cloudify3-provider/src/main/java/alien4cloud/paas/cloudify3/service/PropertyEvaluatorService.java | package alien4cloud.paas.cloudify3.service;
import java.util.List;
import java.util.Map;
import org.alien4cloud.tosca.model.definitions.AbstractPropertyValue;
import org.alien4cloud.tosca.model.definitions.ConcatPropertyValue;
import org.alien4cloud.tosca.model.definitions.FunctionPropertyValue;
import org.alien4cloud.tosca.model.definitions.IValue;
import org.alien4cloud.tosca.model.definitions.Interface;
import org.alien4cloud.tosca.model.definitions.Operation;
import org.alien4cloud.tosca.model.definitions.ScalarPropertyValue;
import org.alien4cloud.tosca.model.templates.Capability;
import org.alien4cloud.tosca.normative.constants.ToscaFunctionConstants;
import org.alien4cloud.tosca.utils.ToscaTypeUtils;
import org.springframework.stereotype.Component;
import com.google.common.collect.Lists;
import alien4cloud.exception.InvalidArgumentException;
import alien4cloud.paas.IPaaSTemplate;
import alien4cloud.paas.function.FunctionEvaluator;
import alien4cloud.paas.model.PaaSNodeTemplate;
import alien4cloud.paas.model.PaaSRelationshipTemplate;
import alien4cloud.paas.model.PaaSTopologyDeploymentContext;
import alien4cloud.utils.PropertyUtil;
@Component("property-evaluator-service")
public class PropertyEvaluatorService {
private void processAttributes(Map<String, IValue> attributes, IPaaSTemplate node, Map<String, PaaSNodeTemplate> allNodes) {
if (attributes != null) {
for (Map.Entry<String, IValue> attributeEntry : attributes.entrySet()) {
attributeEntry.setValue(process(attributeEntry.getValue(), node, allNodes));
}
}
}
private void processInterfaces(Map<String, Interface> interfaces, IPaaSTemplate node, Map<String, PaaSNodeTemplate> allNodes) {
if (interfaces != null) {
for (Interface interfazz : interfaces.values()) {
Map<String, Operation> operations = interfazz.getOperations();
if (operations != null) {
for (Operation operation : operations.values()) {
Map<String, IValue> inputs = operation.getInputParameters();
if (inputs != null) {
for (Map.Entry<String, IValue> inputEntry : inputs.entrySet()) {
inputEntry.setValue(process(inputEntry.getValue(), node, allNodes));
}
}
}
}
}
}
}
private void processCapability(Capability capability, IPaaSTemplate node, Map<String, PaaSNodeTemplate> allNodes) {
if (capability != null && capability.getProperties() != null) {
for (Map.Entry<String, AbstractPropertyValue> attributeEntry : capability.getProperties().entrySet()) {
attributeEntry.setValue((AbstractPropertyValue) process(attributeEntry.getValue(), node, allNodes));
}
}
}
/**
* Process the deployment topology, every get_property will be replaced by its own static value retrieved from the topology
*
* @param deploymentContext the deployment context
*/
public void processGetPropertyFunction(PaaSTopologyDeploymentContext deploymentContext) {
Map<String, PaaSNodeTemplate> allNodes = deploymentContext.getPaaSTopology().getAllNodes();
for (PaaSNodeTemplate node : allNodes.values()) {
processAttributes(node.getTemplate().getAttributes(), node, allNodes);
processInterfaces(node.getInterfaces(), node, allNodes);
List<PaaSRelationshipTemplate> relationships = node.getRelationshipTemplates();
if (relationships != null) {
for (PaaSRelationshipTemplate relationship : relationships) {
processAttributes(relationship.getTemplate().getAttributes(), relationship, allNodes);
processInterfaces(relationship.getInterfaces(), relationship, allNodes);
}
}
if (node.getTemplate().getCapabilities() != null) {
for (Map.Entry<String, Capability> capabilityEntry : node.getTemplate().getCapabilities().entrySet()) {
processCapability(capabilityEntry.getValue(), node, allNodes);
}
}
}
}
/**
* Process an IValue (it can be a scalar value, a get_property, get_attribute, get_operation_output or a concat) and replace all get_property occurrence
* with its value and return the new IValue with get_property replaced by its value
*
* @param value the value to be processed
* @return the new value with get_property processed
*/
private IValue process(IValue value, IPaaSTemplate node, Map<String, PaaSNodeTemplate> allNodes) {
if (value instanceof FunctionPropertyValue) {
return processSimpleFunction((FunctionPropertyValue) value, node, allNodes);
} else if (value instanceof ConcatPropertyValue) {
return processConcatFunction((ConcatPropertyValue) value, node, allNodes);
} else {
return value;
}
}
private AbstractPropertyValue processSimpleFunction(FunctionPropertyValue value, IPaaSTemplate node, Map<String, PaaSNodeTemplate> allNodes) {
if (ToscaFunctionConstants.GET_PROPERTY.equals(value.getFunction())) {
String reqTargetValue = evaluateReqTarget(value, node, allNodes);
if (reqTargetValue != null) {
return new ScalarPropertyValue(reqTargetValue);
} else {
AbstractPropertyValue processedValue = FunctionEvaluator.processGetPropertyFunction(value, node, allNodes);
if (processedValue == null || processedValue instanceof ConcatPropertyValue || processedValue instanceof FunctionPropertyValue
|| processedValue instanceof ScalarPropertyValue) {
return processedValue;
} else {
return new ScalarPropertyValue(PropertyUtil.serializePropertyValue(processedValue));
}
}
} else {
return value;
}
}
private String evaluateReqTarget(FunctionPropertyValue value, IPaaSTemplate node, Map<String, PaaSNodeTemplate> allNodes) {
if (value.getParameters().contains("REQ_TARGET")) {
// Search for the requirement's target by filter the relationships' templates of this node.
// If a target is found, then lookup for the given property name in its capabilities.
String requirementName = value.getCapabilityOrRequirementName();
String propertyName = value.getElementNameToFetch();
if (node instanceof PaaSNodeTemplate && requirementName != null) {
for (PaaSRelationshipTemplate relationshipTemplate : ((PaaSNodeTemplate) node).getRelationshipTemplates()) {
if (node.getId().equals(relationshipTemplate.getSource())
&& requirementName.equals(relationshipTemplate.getTemplate().getRequirementName())) {
PaaSNodeTemplate target = allNodes.get(relationshipTemplate.getTemplate().getTarget());
String evaluated = kubernetesEvaluationWorkaround(value, (PaaSNodeTemplate) node, target, relationshipTemplate, propertyName);
if (evaluated == null) {
// Search the property in capabilities of the target
String targetedCapabilityName = relationshipTemplate.getTemplate().getTargetedCapabilityName();
FunctionPropertyValue func = new FunctionPropertyValue(value.getFunction(),
Lists.newArrayList(ToscaFunctionConstants.SELF, targetedCapabilityName, propertyName));
evaluated = FunctionEvaluator.evaluateGetPropertyFunction(func, target, allNodes);
if (evaluated == null) {
// If not found in the capability, search the property in the target's node itself.
func = new FunctionPropertyValue(value.getFunction(), Lists.newArrayList(ToscaFunctionConstants.SELF, propertyName));
evaluated = FunctionEvaluator.evaluateGetPropertyFunction(func, target, allNodes);
}
}
if (evaluated != null) {
return evaluated;
}
}
}
}
}
return null;
}
private String kubernetesEvaluationWorkaround(FunctionPropertyValue value, PaaSNodeTemplate node, PaaSNodeTemplate target,
PaaSRelationshipTemplate relationshipTemplate, String propertyName) {
// If the node is a docker type, special case for port and ip_address properties
// as it must be handled by the Cloudify's kubernetes plugin
boolean dockerTypeNode = ToscaTypeUtils.isOfType(node.getIndexedToscaElement(), BlueprintService.TOSCA_DOCKER_CONTAINER_TYPE);
boolean connectsToRelationship = relationshipTemplate.instanceOf("tosca.relationships.ConnectsTo");
boolean portOrIpAddress = ("port".equalsIgnoreCase(propertyName) || "ip_address".equalsIgnoreCase(propertyName));
if (dockerTypeNode && connectsToRelationship && portOrIpAddress) {
// Particular treatment for port and ip_address that needs to be retrieved at runtime from the kubernetes plugin of cloudify.
// We need to generate a kind of custom function for the plugin in the generated blueprint.
if ("ip_address".equalsIgnoreCase(propertyName)) {
if (ToscaTypeUtils.isOfType(target.getIndexedToscaElement(), BlueprintService.TOSCA_DOCKER_CONTAINER_TYPE)) {
propertyName = "clusterIP";
} else { // Workaround(cfy3): If the property is 'ip_address', change it to 'ip'
propertyName = "ip";
}
}
// Return a string as "function_name, node_id, property_name" (c.f. kubernetes.yaml.vm)
return String.format("%s,%s,%s", value.getFunction(), relationshipTemplate.getTemplate().getTarget(), propertyName);
}
return null;
}
private IValue processConcatFunction(ConcatPropertyValue concatPropertyValue, IPaaSTemplate node, Map<String, PaaSNodeTemplate> allNodes) {
if (concatPropertyValue.getParameters() == null || concatPropertyValue.getParameters().isEmpty()) {
throw new InvalidArgumentException("Parameter list for concat function is empty");
}
for (int i = 0; i < concatPropertyValue.getParameters().size(); i++) {
IValue concatParam = concatPropertyValue.getParameters().get(i);
if (concatParam instanceof FunctionPropertyValue) {
concatPropertyValue.getParameters().set(i, processSimpleFunction((FunctionPropertyValue) concatParam, node, allNodes));
}
}
return concatPropertyValue;
}
}
| Fix regression in property evaluation : when an input targets a property that is null, we may have a scalar(null) instead of null
| alien4cloud-cloudify3-provider/src/main/java/alien4cloud/paas/cloudify3/service/PropertyEvaluatorService.java | Fix regression in property evaluation : when an input targets a property that is null, we may have a scalar(null) instead of null | <ide><path>lien4cloud-cloudify3-provider/src/main/java/alien4cloud/paas/cloudify3/service/PropertyEvaluatorService.java
<ide> return new ScalarPropertyValue(reqTargetValue);
<ide> } else {
<ide> AbstractPropertyValue processedValue = FunctionEvaluator.processGetPropertyFunction(value, node, allNodes);
<del> if (processedValue == null || processedValue instanceof ConcatPropertyValue || processedValue instanceof FunctionPropertyValue
<add> if (processedValue == null ) {
<add> return new ScalarPropertyValue(null);
<add> } else if (processedValue instanceof ConcatPropertyValue || processedValue instanceof FunctionPropertyValue
<ide> || processedValue instanceof ScalarPropertyValue) {
<ide> return processedValue;
<ide> } else { |
|
Java | bsd-3-clause | a39f42d084bf5cae907db46fb63d5629d48adf9b | 0 | geneontology/minerva,geneontology/minerva,geneontology/minerva | package org.geneontology.minerva.server;
import java.io.IOException;
import java.util.List;
import java.util.Map.Entry;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.tools.ant.filters.StringInputStream;
import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.ExtendedUriInfo;
import org.glassfish.jersey.server.model.ResourceMethod;
import org.glassfish.jersey.server.monitoring.ApplicationEvent;
import org.glassfish.jersey.server.monitoring.ApplicationEventListener;
import org.glassfish.jersey.server.monitoring.RequestEvent;
import org.glassfish.jersey.server.monitoring.RequestEventListener;
public class LoggingApplicationEventListener implements ApplicationEventListener {
private static final Logger LOG = Logger.getLogger(LoggingApplicationEventListener.class);
private volatile long requestCounter = 0;
@Override
public void onEvent(ApplicationEvent event) {
switch (event.getType()) {
case INITIALIZATION_FINISHED:
LOG.info("Application " + event.getResourceConfig().getApplicationName()
+ " initialization finished.");
break;
case DESTROY_FINISHED:
LOG.info("Application "+ event.getResourceConfig().getApplicationName()+" destroyed.");
break;
default:
break;
}
}
@Override
public RequestEventListener onRequest(RequestEvent requestEvent) {
requestCounter++;
LOG.info("Request " + requestCounter + " started.");
return new LoggingRequestEventListener(requestCounter);
}
private static class LoggingRequestEventListener implements RequestEventListener {
private final long requestNumber;
private final long startTime;
public LoggingRequestEventListener(long requestNumber) {
this.requestNumber = requestNumber;
startTime = System.currentTimeMillis();
}
@Override
public void onEvent(RequestEvent event) {
switch (event.getType()) {
case RESOURCE_METHOD_START:
ExtendedUriInfo uriInfo = event.getUriInfo();
ResourceMethod method = uriInfo.getMatchedResourceMethod();
ContainerRequest containerRequest = event.getContainerRequest();
LOG.info(requestNumber+" Resource method " + method.getHttpMethod() + " started for request " + requestNumber);
LOG.info(requestNumber+" Headers: "+ render(containerRequest.getHeaders()));
LOG.info(requestNumber+" Path: "+uriInfo.getPath());
LOG.info(requestNumber+" PathParameters: "+ render(uriInfo.getPathParameters()));
LOG.info(requestNumber+" QueryParameters: "+ render(uriInfo.getQueryParameters()));
LOG.info(requestNumber+" Body: "+getBody(containerRequest));
break;
case FINISHED:
LOG.info("Request " + requestNumber + " finished. Processing time "
+ (System.currentTimeMillis() - startTime) + " ms.");
break;
default:
break;
}
}
}
private static CharSequence getBody(ContainerRequest request) {
String body = null;
try {
body = IOUtils.toString(request.getEntityStream());
// reading the stream consumes it, need to re-create it for the real thing
request.setEntityStream(new StringInputStream(body));
} catch (IOException e) {
LOG.warn("Couldn't ready body.", e);
}
return body;
}
private static CharSequence render(MultivaluedMap<String, String> map) {
StringBuilder sb = new StringBuilder();
int count = 0;
sb.append('[');
for (Entry<String, List<String>> entry : map.entrySet()) {
if (count > 0) {
sb.append(',');
}
sb.append('{').append(entry.getKey()).append(',').append(entry.getValue()).append('}');
count += 1;
}
sb.append(']');
return sb;
}
}
| minerva-server/src/main/java/org/geneontology/minerva/server/LoggingApplicationEventListener.java | package org.geneontology.minerva.server;
import org.apache.log4j.Logger;
import org.glassfish.jersey.server.monitoring.ApplicationEvent;
import org.glassfish.jersey.server.monitoring.ApplicationEventListener;
import org.glassfish.jersey.server.monitoring.RequestEvent;
import org.glassfish.jersey.server.monitoring.RequestEventListener;
public class LoggingApplicationEventListener implements ApplicationEventListener {
private static final Logger LOG = Logger.getLogger(LoggingApplicationEventListener.class);
private volatile long requestCounter = 0;
@Override
public void onEvent(ApplicationEvent event) {
switch (event.getType()) {
case INITIALIZATION_FINISHED:
LOG.info("Application " + event.getResourceConfig().getApplicationName()
+ " initialization finished.");
break;
case DESTROY_FINISHED:
LOG.info("Application "+ event.getResourceConfig().getApplicationName()+" destroyed.");
break;
default:
break;
}
}
@Override
public RequestEventListener onRequest(RequestEvent requestEvent) {
requestCounter++;
LOG.info("Request " + requestCounter + " started.");
return new LoggingRequestEventListener(requestCounter);
}
private static class LoggingRequestEventListener implements RequestEventListener {
private final long requestNumber;
private final long startTime;
public LoggingRequestEventListener(long requestNumber) {
this.requestNumber = requestNumber;
startTime = System.currentTimeMillis();
}
@Override
public void onEvent(RequestEvent event) {
switch (event.getType()) {
case RESOURCE_METHOD_START:
LOG.info("Resource method " + event.getUriInfo().getMatchedResourceMethod().getHttpMethod()
+ " started for request " + requestNumber);
break;
case FINISHED:
LOG.info("Request " + requestNumber + " finished. Processing time "
+ (System.currentTimeMillis() - startTime) + " ms.");
break;
default:
break;
}
}
}
}
| Verbose logging of requests (for debugging)
* related to issue geneontology/noctua#151
| minerva-server/src/main/java/org/geneontology/minerva/server/LoggingApplicationEventListener.java | Verbose logging of requests (for debugging) | <ide><path>inerva-server/src/main/java/org/geneontology/minerva/server/LoggingApplicationEventListener.java
<ide> package org.geneontology.minerva.server;
<ide>
<add>import java.io.IOException;
<add>import java.util.List;
<add>import java.util.Map.Entry;
<add>
<add>import javax.ws.rs.core.MultivaluedMap;
<add>
<add>import org.apache.commons.io.IOUtils;
<ide> import org.apache.log4j.Logger;
<add>import org.apache.tools.ant.filters.StringInputStream;
<add>import org.glassfish.jersey.server.ContainerRequest;
<add>import org.glassfish.jersey.server.ExtendedUriInfo;
<add>import org.glassfish.jersey.server.model.ResourceMethod;
<ide> import org.glassfish.jersey.server.monitoring.ApplicationEvent;
<ide> import org.glassfish.jersey.server.monitoring.ApplicationEventListener;
<ide> import org.glassfish.jersey.server.monitoring.RequestEvent;
<ide> public void onEvent(RequestEvent event) {
<ide> switch (event.getType()) {
<ide> case RESOURCE_METHOD_START:
<del> LOG.info("Resource method " + event.getUriInfo().getMatchedResourceMethod().getHttpMethod()
<del> + " started for request " + requestNumber);
<add> ExtendedUriInfo uriInfo = event.getUriInfo();
<add> ResourceMethod method = uriInfo.getMatchedResourceMethod();
<add> ContainerRequest containerRequest = event.getContainerRequest();
<add> LOG.info(requestNumber+" Resource method " + method.getHttpMethod() + " started for request " + requestNumber);
<add> LOG.info(requestNumber+" Headers: "+ render(containerRequest.getHeaders()));
<add> LOG.info(requestNumber+" Path: "+uriInfo.getPath());
<add> LOG.info(requestNumber+" PathParameters: "+ render(uriInfo.getPathParameters()));
<add> LOG.info(requestNumber+" QueryParameters: "+ render(uriInfo.getQueryParameters()));
<add> LOG.info(requestNumber+" Body: "+getBody(containerRequest));
<ide> break;
<ide> case FINISHED:
<ide> LOG.info("Request " + requestNumber + " finished. Processing time "
<ide> }
<ide>
<ide> }
<add>
<add> private static CharSequence getBody(ContainerRequest request) {
<add> String body = null;
<add> try {
<add> body = IOUtils.toString(request.getEntityStream());
<add> // reading the stream consumes it, need to re-create it for the real thing
<add> request.setEntityStream(new StringInputStream(body));
<add> } catch (IOException e) {
<add> LOG.warn("Couldn't ready body.", e);
<add> }
<add> return body;
<add> }
<add>
<add> private static CharSequence render(MultivaluedMap<String, String> map) {
<add> StringBuilder sb = new StringBuilder();
<add> int count = 0;
<add> sb.append('[');
<add> for (Entry<String, List<String>> entry : map.entrySet()) {
<add> if (count > 0) {
<add> sb.append(',');
<add> }
<add> sb.append('{').append(entry.getKey()).append(',').append(entry.getValue()).append('}');
<add> count += 1;
<add> }
<add> sb.append(']');
<add> return sb;
<add> }
<ide> } |
|
Java | bsd-3-clause | 22def56db22dee9558054953bd003e6370c288da | 0 | Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java | /*
* Copyright (c) 1998 - 2009. University Corporation for Atmospheric Research/Unidata
* Portions of this software were developed by the Unidata Program at the
* University Corporation for Atmospheric Research.
*
* Access and use of this software shall impose the following obligations
* and understandings on the user. The user is granted the right, without
* any fee or cost, to use, copy, modify, alter, enhance and distribute
* this software, and any derivative works thereof, and its supporting
* documentation for any purpose whatsoever, provided that this entire
* notice appears in all copies of the software, derivative works and
* supporting documentation. Further, UCAR requests that the user credit
* UCAR/Unidata in any publications that result from the use of this
* software or in any product that includes this software. The names UCAR
* and/or Unidata, however, may not be used in any advertising or publicity
* to endorse or promote any products or commercial entity unless specific
* written permission is obtained from UCAR/Unidata. The user also
* understands that UCAR/Unidata is not obligated to provide the user with
* any support, consulting, training or assistance of any kind with regard
* to the use, operation and performance of this software nor to provide
* the user with any updates, revisions, new versions or "bug fixes."
*
* THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package thredds.catalog;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import ucar.nc2.TestAll;
import ucar.unidata.util.TestFileDirUtils;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import thredds.cataloggen.catalogrefexpander.BooleanCatalogRefExpander;
/**
* _more_
*
* @author edavis
* @since 4.0
*/
public class DatasetScanExpandSubdirsTest
{
private String scanPath;
private String scanLocation;
@Before
public void setupScanLocation()
{
File tmpDataDir = new File( TestAll.temporaryLocalDataDir);
File testDir = TestFileDirUtils.createTempDirectory( "dsScanExpandSubdirs", tmpDataDir );
TestFileDirUtils.addFile( testDir, "file1.nc" );
TestFileDirUtils.addFile( testDir, "file2.nc" );
TestFileDirUtils.addFile( testDir, "file3.nc" );
File subdir1 = TestFileDirUtils.addDirectory( testDir, "subdir1" );
TestFileDirUtils.addFile( subdir1, "file4.nc" );
TestFileDirUtils.addFile( subdir1, "file5.nc" );
File subdir2 = TestFileDirUtils.addDirectory( testDir, "subdir2" );
TestFileDirUtils.addFile( subdir2, "file6.nc" );
TestFileDirUtils.addFile( subdir2, "file7.nc" );
File subdir3 = TestFileDirUtils.addDirectory( subdir2, "subdir2_1" );
TestFileDirUtils.addFile( subdir3, "file8.nc" );
TestFileDirUtils.addFile( subdir3, "file9.nc" );
this.scanPath = "test/path";
this.scanLocation = testDir.getPath();
}
@Test
public void checkExpandSubdirs() throws URISyntaxException, IOException
{
InvCatalogImpl configCat = new InvCatalogImpl( "configCat", "1.0.2", new URI( "http://server/thredds/catalog.xml"));
configCat.addService( new InvService( "odap", "OPENDAP", "/thredds/dodsC/", null, null ) );
InvDatasetImpl configRootDs = new InvDatasetImpl( null, "root ds" );
configCat.addDataset( configRootDs );
InvDatasetScan scan = new InvDatasetScan( configRootDs, "test", this.scanPath, this.scanLocation,
null, null, null, null, null, true, null, null, null,
new BooleanCatalogRefExpander( true) );
scan.setServiceName( "odap" );
configRootDs.addDataset( scan );
assertTrue( configCat.finish());
StringBuilder sb = new StringBuilder();
boolean good = scan.check( sb, true );
assertTrue( sb.toString(), good);
assertTrue( sb.toString(), sb.length() == 0 );
assertTrue( scan.isValid());
InvCatalogImpl cat = scan.makeCatalogForDirectory( this.scanPath + "/catalog.xml", new URI( "http://server/thredds/catalogs/test/path/catalog.xml") );
List<InvDataset> dsList = cat.getDatasets();
assertFalse( dsList.isEmpty());
assertEquals( 1, dsList.size());
InvDataset rootDs = dsList.get( 0 );
assertTrue( rootDs.hasNestedDatasets());
dsList= rootDs.getDatasets();
assertFalse( dsList.isEmpty());
assertEquals( 5, dsList.size());
assertEquals( "","file1.nc", dsList.get( 0).getName());
String msg = "expected:<file[2].nc> but was:<"+dsList.get(1).getName() +"> --\n\n" + InvCatalogFactory.getDefaultFactory( false ).writeXML( cat );
assertEquals( "file2.nc", dsList.get( 1).getName());
assertEquals( "file3.nc", dsList.get( 2).getName());
InvDataset invDsSubdir1 = dsList.get( 3 );
InvDataset invDsSubdir2 = dsList.get( 4 );
assertEquals( "subdir1", invDsSubdir1.getName());
dsList = invDsSubdir1.getDatasets();
assertEquals( 2, dsList.size());
assertEquals( "file4.nc", dsList.get( 0 ).getName() );
assertEquals( "file5.nc", dsList.get( 1 ).getName() );
assertEquals( "subdir2", invDsSubdir2.getName());
dsList = invDsSubdir2.getDatasets();
assertEquals( 3, dsList.size() );
assertEquals( "file6.nc", dsList.get( 0 ).getName() );
assertEquals( "file7.nc", dsList.get( 1 ).getName() );
InvDataset invDsSubdir2_1 = dsList.get( 2 );
assertEquals( "subdir2_1", invDsSubdir2_1.getName());
dsList = invDsSubdir2_1.getDatasets();
assertEquals( 2, dsList.size() );
assertEquals( "file8.nc", dsList.get( 0 ).getName() );
assertEquals( "file9.nc", dsList.get( 1 ).getName() );
}
}
| cdm/src/test/java/thredds/catalog/DatasetScanExpandSubdirsTest.java | /*
* Copyright (c) 1998 - 2009. University Corporation for Atmospheric Research/Unidata
* Portions of this software were developed by the Unidata Program at the
* University Corporation for Atmospheric Research.
*
* Access and use of this software shall impose the following obligations
* and understandings on the user. The user is granted the right, without
* any fee or cost, to use, copy, modify, alter, enhance and distribute
* this software, and any derivative works thereof, and its supporting
* documentation for any purpose whatsoever, provided that this entire
* notice appears in all copies of the software, derivative works and
* supporting documentation. Further, UCAR requests that the user credit
* UCAR/Unidata in any publications that result from the use of this
* software or in any product that includes this software. The names UCAR
* and/or Unidata, however, may not be used in any advertising or publicity
* to endorse or promote any products or commercial entity unless specific
* written permission is obtained from UCAR/Unidata. The user also
* understands that UCAR/Unidata is not obligated to provide the user with
* any support, consulting, training or assistance of any kind with regard
* to the use, operation and performance of this software nor to provide
* the user with any updates, revisions, new versions or "bug fixes."
*
* THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package thredds.catalog;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import ucar.nc2.TestAll;
import ucar.unidata.util.TestFileDirUtils;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import thredds.cataloggen.catalogrefexpander.BooleanCatalogRefExpander;
/**
* _more_
*
* @author edavis
* @since 4.0
*/
public class DatasetScanExpandSubdirsTest
{
private String scanPath;
private String scanLocation;
@Before
public void setupScanLocation()
{
File tmpDataDir = new File( TestAll.temporaryLocalDataDir);
File testDir = TestFileDirUtils.createTempDirectory( "dsScanExpandSubdirs", tmpDataDir );
TestFileDirUtils.addFile( testDir, "file1.nc" );
TestFileDirUtils.addFile( testDir, "file2.nc" );
TestFileDirUtils.addFile( testDir, "file3.nc" );
File subdir1 = TestFileDirUtils.addDirectory( testDir, "subdir1" );
TestFileDirUtils.addFile( subdir1, "file4.nc" );
TestFileDirUtils.addFile( subdir1, "file5.nc" );
File subdir2 = TestFileDirUtils.addDirectory( testDir, "subdir2" );
TestFileDirUtils.addFile( subdir2, "file6.nc" );
TestFileDirUtils.addFile( subdir2, "file7.nc" );
File subdir3 = TestFileDirUtils.addDirectory( subdir2, "subdir2_1" );
TestFileDirUtils.addFile( subdir3, "file8.nc" );
TestFileDirUtils.addFile( subdir3, "file9.nc" );
this.scanPath = "test/path";
this.scanLocation = testDir.getPath();
}
@Test
public void checkExpandSubdirs() throws URISyntaxException
{
InvCatalogImpl configCat = new InvCatalogImpl( "configCat", "1.0.2", new URI( "http://server/thredds/catalog.xml"));
configCat.addService( new InvService( "odap", "OPENDAP", "/thredds/dodsC/", null, null ) );
InvDatasetImpl configRootDs = new InvDatasetImpl( null, "root ds" );
configCat.addDataset( configRootDs );
InvDatasetScan scan = new InvDatasetScan( configRootDs, "test", this.scanPath, this.scanLocation,
null, null, null, null, null, true, null, null, null,
new BooleanCatalogRefExpander( true) );
scan.setServiceName( "odap" );
configRootDs.addDataset( scan );
assertTrue( configCat.finish());
StringBuilder sb = new StringBuilder();
boolean good = scan.check( sb, true );
assertTrue( sb.toString(), good);
assertTrue( sb.toString(), sb.length() == 0 );
assertTrue( scan.isValid());
InvCatalogImpl cat = scan.makeCatalogForDirectory( this.scanPath + "/catalog.xml", new URI( "http://server/thredds/catalogs/test/path/catalog.xml") );
List<InvDataset> dsList = cat.getDatasets();
assertFalse( dsList.isEmpty());
assertEquals( 1, dsList.size());
InvDataset rootDs = dsList.get( 0 );
assertTrue( rootDs.hasNestedDatasets());
dsList= rootDs.getDatasets();
assertFalse( dsList.isEmpty());
assertEquals( 5, dsList.size());
assertEquals( "file1.nc", dsList.get( 0).getName());
assertEquals( "file2.nc", dsList.get( 1).getName());
assertEquals( "file3.nc", dsList.get( 2).getName());
InvDataset invDsSubdir1 = dsList.get( 3 );
InvDataset invDsSubdir2 = dsList.get( 4 );
assertEquals( "subdir1", invDsSubdir1.getName());
dsList = invDsSubdir1.getDatasets();
assertEquals( 2, dsList.size());
assertEquals( "file4.nc", dsList.get( 0 ).getName() );
assertEquals( "file5.nc", dsList.get( 1 ).getName() );
assertEquals( "subdir2", invDsSubdir2.getName());
dsList = invDsSubdir2.getDatasets();
assertEquals( 3, dsList.size() );
assertEquals( "file6.nc", dsList.get( 0 ).getName() );
assertEquals( "file7.nc", dsList.get( 1 ).getName() );
InvDataset invDsSubdir2_1 = dsList.get( 2 );
assertEquals( "subdir2_1", invDsSubdir2_1.getName());
dsList = invDsSubdir2_1.getDatasets();
assertEquals( 2, dsList.size() );
assertEquals( "file8.nc", dsList.get( 0 ).getName() );
assertEquals( "file9.nc", dsList.get( 1 ).getName() );
}
}
| Debugging test failure.
| cdm/src/test/java/thredds/catalog/DatasetScanExpandSubdirsTest.java | Debugging test failure. | <ide><path>dm/src/test/java/thredds/catalog/DatasetScanExpandSubdirsTest.java
<ide> import ucar.unidata.util.TestFileDirUtils;
<ide>
<ide> import java.io.File;
<add>import java.io.IOException;
<ide> import java.net.URI;
<ide> import java.net.URISyntaxException;
<ide> import java.util.List;
<ide> }
<ide>
<ide> @Test
<del> public void checkExpandSubdirs() throws URISyntaxException
<add> public void checkExpandSubdirs() throws URISyntaxException, IOException
<ide> {
<ide> InvCatalogImpl configCat = new InvCatalogImpl( "configCat", "1.0.2", new URI( "http://server/thredds/catalog.xml"));
<ide> configCat.addService( new InvService( "odap", "OPENDAP", "/thredds/dodsC/", null, null ) );
<ide> assertFalse( dsList.isEmpty());
<ide> assertEquals( 5, dsList.size());
<ide>
<del> assertEquals( "file1.nc", dsList.get( 0).getName());
<add> assertEquals( "","file1.nc", dsList.get( 0).getName());
<add> String msg = "expected:<file[2].nc> but was:<"+dsList.get(1).getName() +"> --\n\n" + InvCatalogFactory.getDefaultFactory( false ).writeXML( cat );
<ide> assertEquals( "file2.nc", dsList.get( 1).getName());
<ide> assertEquals( "file3.nc", dsList.get( 2).getName());
<ide> |
|
Java | apache-2.0 | acd09fcdd41cd8087aa049fed952f4ff5ed4f43a | 0 | talsma-ict/umldoclet,talsma-ict/umldoclet | /*
* Copyright 2016-2019 Talsma ICT
*
* 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 nl.talsmasoftware.umldoclet;
import jdk.javadoc.doclet.DocletEnvironment;
import jdk.javadoc.doclet.Reporter;
import jdk.javadoc.doclet.StandardDoclet;
import net.sourceforge.plantuml.version.Version;
import nl.talsmasoftware.umldoclet.html.HtmlPostprocessor;
import nl.talsmasoftware.umldoclet.javadoc.DocletConfig;
import nl.talsmasoftware.umldoclet.javadoc.UMLFactory;
import nl.talsmasoftware.umldoclet.javadoc.dependencies.DependenciesElementScanner;
import nl.talsmasoftware.umldoclet.javadoc.dependencies.PackageDependency;
import nl.talsmasoftware.umldoclet.javadoc.dependencies.PackageDependencyCycle;
import nl.talsmasoftware.umldoclet.logging.Message;
import nl.talsmasoftware.umldoclet.uml.DependencyDiagram;
import nl.talsmasoftware.umldoclet.uml.Diagram;
import javax.lang.model.element.Element;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Stream;
import static java.util.stream.Collectors.joining;
import static nl.talsmasoftware.umldoclet.logging.Message.DOCLET_COPYRIGHT;
import static nl.talsmasoftware.umldoclet.logging.Message.DOCLET_VERSION;
import static nl.talsmasoftware.umldoclet.logging.Message.ERROR_UNANTICIPATED_ERROR_GENERATING_UML;
import static nl.talsmasoftware.umldoclet.logging.Message.ERROR_UNSUPPORTED_DELEGATE_DOCLET;
import static nl.talsmasoftware.umldoclet.logging.Message.PLANTUML_COPYRIGHT;
/**
* UML doclet that generates <a href="http://plantuml.com">PlantUML</a> class diagrams from your java code just as
* easily as creating proper JavaDoc comments.<br>
* It actually extends JavaDoc's {@link StandardDoclet} doclet to generate the regular HTML documentation.
*
* @author Sjoerd Talsma
*/
public class UMLDoclet extends StandardDoclet {
private final DocletConfig config;
/**
* Default constructor, as required by {@linkplain jdk.javadoc.doclet.Doclet} specification.
*/
public UMLDoclet() {
super();
this.config = new DocletConfig();
}
/**
* Initializes the {@linkplain Locale} and {@linkplain Reporter} to be used by
* this doclet.
*
* @param locale The locale to be used by this doclet.
* @param reporter The reporter to be used by this doclet.
*/
@Override
public void init(Locale locale, Reporter reporter) {
config.init(locale, reporter);
super.init(locale, reporter);
}
/**
* @return The name of this doclet, minus the {@code "Doclet"} suffix
* since the {@linkplain StandardDoclet} also returns just {@code "Standard"} as its name.
*/
@Override
public String getName() {
return "UML";
}
/**
* Returns all supported options. This includes the options from the {@linkplain StandardDoclet}.
*
* @return The set containing all supported options
*/
@Override
public Set<Option> getSupportedOptions() {
return config.mergeOptionsWith(super.getSupportedOptions());
}
/**
* Perform the main doclet functionality, processing all included elements.
*
* <p>
* For each included class, a {@linkplain nl.talsmasoftware.umldoclet.uml.ClassDiagram} is generated.
* For each included package, a {@linkplain nl.talsmasoftware.umldoclet.uml.PackageDiagram} is genrated.
* Also, a {@linkplain DependencyDiagram} is generated, containing all dependencies that were detected.
*
* <p>
* Depending on the {@linkplain nl.talsmasoftware.umldoclet.configuration.Configuration},
* diagram images or {@code .puml} plantuml source files are generated.
*
* @param environment The doclet environment from which essential information can be extracted
* @return {@code true} if the doclet ran succesfully, {@code false} in case of errors.
*/
@Override
public boolean run(DocletEnvironment environment) {
config.logger().info(DOCLET_COPYRIGHT, DOCLET_VERSION);
config.logger().info(PLANTUML_COPYRIGHT, Version.versionString());
// First generate Standard HTML documentation
String delegateDocletName = config.delegateDocletName().orElse(null);
if (StandardDoclet.class.getName().equals(delegateDocletName)) {
if (!super.run(environment)) return false;
} else if (delegateDocletName != null) {
config.logger().error(ERROR_UNSUPPORTED_DELEGATE_DOCLET, delegateDocletName);
return false; // TODO for a later release (see e.g. issue #102)
}
try {
generateDiagrams(environment).forEach(Diagram::render);
return new HtmlPostprocessor(config).postProcessHtml();
} catch (RuntimeException unanticipatedException) {
config.logger().error(ERROR_UNANTICIPATED_ERROR_GENERATING_UML, unanticipatedException);
return false;
}
}
private Stream<Diagram> generateDiagrams(DocletEnvironment docEnv) {
UMLFactory factory = new UMLFactory(config, docEnv);
return Stream.concat(
docEnv.getIncludedElements().stream()
.map(element -> generateDiagram(factory, element))
.filter(Objects::nonNull),
Stream.of(generatePackageDependencyDiagram(docEnv)));
}
private Diagram generateDiagram(UMLFactory factory, Element element) {
if (element instanceof PackageElement) {
return factory.createPackageDiagram((PackageElement) element);
} else if (element instanceof TypeElement && (element.getKind().isClass() || element.getKind().isInterface())) {
return factory.createClassDiagram((TypeElement) element);
}
return null;
}
private DependencyDiagram generatePackageDependencyDiagram(DocletEnvironment docEnv) {
Set<PackageDependency> packageDependencies = scanPackageDependencies(docEnv);
detectPackageDependencyCycles(packageDependencies);
DependencyDiagram dependencyDiagram = new DependencyDiagram(config, "package-dependencies.puml");
packageDependencies.forEach(dep -> dependencyDiagram.addPackageDependency(dep.fromPackage, dep.toPackage));
return dependencyDiagram;
}
private Set<PackageDependency> scanPackageDependencies(DocletEnvironment docEnv) {
return new DependenciesElementScanner(docEnv, config).scan(docEnv.getIncludedElements(), null);
}
private Set<PackageDependencyCycle> detectPackageDependencyCycles(Set<PackageDependency> packageDependencies) {
Set<PackageDependencyCycle> cycles = PackageDependencyCycle.detectCycles(packageDependencies);
if (!cycles.isEmpty()) {
String cyclesString = cycles.stream().map(cycle -> " - " + cycle).collect(joining("\n", "\n", ""));
if (config.failOnCyclicPackageDependencies()) {
config.logger().error(Message.WARNING_PACKAGE_DEPENDENCY_CYCLES, cyclesString);
} else {
config.logger().warn(Message.WARNING_PACKAGE_DEPENDENCY_CYCLES, cyclesString);
}
}
return cycles;
}
}
| src/main/java/nl/talsmasoftware/umldoclet/UMLDoclet.java | /*
* Copyright 2016-2019 Talsma ICT
*
* 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 nl.talsmasoftware.umldoclet;
import jdk.javadoc.doclet.DocletEnvironment;
import jdk.javadoc.doclet.Reporter;
import jdk.javadoc.doclet.StandardDoclet;
import net.sourceforge.plantuml.version.Version;
import nl.talsmasoftware.umldoclet.html.HtmlPostprocessor;
import nl.talsmasoftware.umldoclet.javadoc.DocletConfig;
import nl.talsmasoftware.umldoclet.javadoc.UMLFactory;
import nl.talsmasoftware.umldoclet.javadoc.dependencies.DependenciesElementScanner;
import nl.talsmasoftware.umldoclet.javadoc.dependencies.PackageDependency;
import nl.talsmasoftware.umldoclet.javadoc.dependencies.PackageDependencyCycle;
import nl.talsmasoftware.umldoclet.logging.Message;
import nl.talsmasoftware.umldoclet.uml.DependencyDiagram;
import nl.talsmasoftware.umldoclet.uml.Diagram;
import javax.lang.model.element.Element;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Stream;
import static java.util.stream.Collectors.joining;
import static nl.talsmasoftware.umldoclet.logging.Message.DOCLET_COPYRIGHT;
import static nl.talsmasoftware.umldoclet.logging.Message.DOCLET_VERSION;
import static nl.talsmasoftware.umldoclet.logging.Message.ERROR_UNANTICIPATED_ERROR_GENERATING_UML;
import static nl.talsmasoftware.umldoclet.logging.Message.ERROR_UNSUPPORTED_DELEGATE_DOCLET;
import static nl.talsmasoftware.umldoclet.logging.Message.PLANTUML_COPYRIGHT;
/**
* UML doclet that generates <a href="http://plantuml.com">PlantUML</a> class diagrams from your java code just as
* easily as creating proper JavaDoc comments.<br>
* It actually extends JavaDoc's {@link StandardDoclet} doclet to generate the regular HTML documentation.
*
* @author Sjoerd Talsma
*/
public class UMLDoclet extends StandardDoclet {
private final DocletConfig config;
public UMLDoclet() {
super();
this.config = new DocletConfig();
}
@Override
public void init(Locale locale, Reporter reporter) {
config.init(locale, reporter);
super.init(locale, reporter);
}
@Override
public String getName() {
return "UML";
}
@Override
public Set<Option> getSupportedOptions() {
return config.mergeOptionsWith(super.getSupportedOptions());
}
@Override
public boolean run(DocletEnvironment docEnv) {
config.logger().info(DOCLET_COPYRIGHT, DOCLET_VERSION);
config.logger().info(PLANTUML_COPYRIGHT, Version.versionString());
// First generate Standard HTML documentation
String delegateDocletName = config.delegateDocletName().orElse(null);
if (StandardDoclet.class.getName().equals(delegateDocletName)) {
if (!super.run(docEnv)) return false;
} else if (delegateDocletName != null) {
config.logger().error(ERROR_UNSUPPORTED_DELEGATE_DOCLET, delegateDocletName);
return false; // TODO for a later release (see e.g. issue #102)
}
try {
generateDiagrams(docEnv).forEach(Diagram::render);
return new HtmlPostprocessor(config).postProcessHtml();
} catch (RuntimeException unanticipatedException) {
config.logger().error(ERROR_UNANTICIPATED_ERROR_GENERATING_UML, unanticipatedException);
return false;
}
}
private Stream<Diagram> generateDiagrams(DocletEnvironment docEnv) {
UMLFactory factory = new UMLFactory(config, docEnv);
return Stream.concat(
docEnv.getIncludedElements().stream()
.map(element -> generateDiagram(factory, element))
.filter(Objects::nonNull),
Stream.of(generatePackageDependencyDiagram(docEnv)));
}
private Diagram generateDiagram(UMLFactory factory, Element element) {
if (element instanceof PackageElement) {
return factory.createPackageDiagram((PackageElement) element);
} else if (element instanceof TypeElement && (element.getKind().isClass() || element.getKind().isInterface())) {
return factory.createClassDiagram((TypeElement) element);
}
return null;
}
private DependencyDiagram generatePackageDependencyDiagram(DocletEnvironment docEnv) {
Set<PackageDependency> packageDependencies = scanPackageDependencies(docEnv);
detectPackageDependencyCycles(packageDependencies);
DependencyDiagram dependencyDiagram = new DependencyDiagram(config, "package-dependencies.puml");
packageDependencies.forEach(dep -> dependencyDiagram.addPackageDependency(dep.fromPackage, dep.toPackage));
return dependencyDiagram;
}
private Set<PackageDependency> scanPackageDependencies(DocletEnvironment docEnv) {
return new DependenciesElementScanner(docEnv, config).scan(docEnv.getIncludedElements(), null);
}
private Set<PackageDependencyCycle> detectPackageDependencyCycles(Set<PackageDependency> packageDependencies) {
Set<PackageDependencyCycle> cycles = PackageDependencyCycle.detectCycles(packageDependencies);
if (!cycles.isEmpty()) {
String cyclesString = cycles.stream().map(cycle -> " - " + cycle).collect(joining("\n", "\n", ""));
if (config.failOnCyclicPackageDependencies()) {
config.logger().error(Message.WARNING_PACKAGE_DEPENDENCY_CYCLES, cyclesString);
} else {
config.logger().warn(Message.WARNING_PACKAGE_DEPENDENCY_CYCLES, cyclesString);
}
}
return cycles;
}
}
| Add javadoc to the `UMLDoclet` class
Signed-off-by: Sjoerd Talsma <[email protected]>
| src/main/java/nl/talsmasoftware/umldoclet/UMLDoclet.java | Add javadoc to the `UMLDoclet` class | <ide><path>rc/main/java/nl/talsmasoftware/umldoclet/UMLDoclet.java
<ide>
<ide> private final DocletConfig config;
<ide>
<add> /**
<add> * Default constructor, as required by {@linkplain jdk.javadoc.doclet.Doclet} specification.
<add> */
<ide> public UMLDoclet() {
<ide> super();
<ide> this.config = new DocletConfig();
<ide> }
<ide>
<add> /**
<add> * Initializes the {@linkplain Locale} and {@linkplain Reporter} to be used by
<add> * this doclet.
<add> *
<add> * @param locale The locale to be used by this doclet.
<add> * @param reporter The reporter to be used by this doclet.
<add> */
<ide> @Override
<ide> public void init(Locale locale, Reporter reporter) {
<ide> config.init(locale, reporter);
<ide> super.init(locale, reporter);
<ide> }
<ide>
<add> /**
<add> * @return The name of this doclet, minus the {@code "Doclet"} suffix
<add> * since the {@linkplain StandardDoclet} also returns just {@code "Standard"} as its name.
<add> */
<ide> @Override
<ide> public String getName() {
<ide> return "UML";
<ide> }
<ide>
<add> /**
<add> * Returns all supported options. This includes the options from the {@linkplain StandardDoclet}.
<add> *
<add> * @return The set containing all supported options
<add> */
<ide> @Override
<ide> public Set<Option> getSupportedOptions() {
<ide> return config.mergeOptionsWith(super.getSupportedOptions());
<ide> }
<ide>
<add> /**
<add> * Perform the main doclet functionality, processing all included elements.
<add> *
<add> * <p>
<add> * For each included class, a {@linkplain nl.talsmasoftware.umldoclet.uml.ClassDiagram} is generated.
<add> * For each included package, a {@linkplain nl.talsmasoftware.umldoclet.uml.PackageDiagram} is genrated.
<add> * Also, a {@linkplain DependencyDiagram} is generated, containing all dependencies that were detected.
<add> *
<add> * <p>
<add> * Depending on the {@linkplain nl.talsmasoftware.umldoclet.configuration.Configuration},
<add> * diagram images or {@code .puml} plantuml source files are generated.
<add> *
<add> * @param environment The doclet environment from which essential information can be extracted
<add> * @return {@code true} if the doclet ran succesfully, {@code false} in case of errors.
<add> */
<ide> @Override
<del> public boolean run(DocletEnvironment docEnv) {
<add> public boolean run(DocletEnvironment environment) {
<ide> config.logger().info(DOCLET_COPYRIGHT, DOCLET_VERSION);
<ide> config.logger().info(PLANTUML_COPYRIGHT, Version.versionString());
<ide>
<ide>
<ide> String delegateDocletName = config.delegateDocletName().orElse(null);
<ide> if (StandardDoclet.class.getName().equals(delegateDocletName)) {
<del> if (!super.run(docEnv)) return false;
<add> if (!super.run(environment)) return false;
<ide> } else if (delegateDocletName != null) {
<ide> config.logger().error(ERROR_UNSUPPORTED_DELEGATE_DOCLET, delegateDocletName);
<ide> return false; // TODO for a later release (see e.g. issue #102)
<ide>
<ide> try {
<ide>
<del> generateDiagrams(docEnv).forEach(Diagram::render);
<add> generateDiagrams(environment).forEach(Diagram::render);
<ide> return new HtmlPostprocessor(config).postProcessHtml();
<ide>
<ide> } catch (RuntimeException unanticipatedException) { |
|
JavaScript | apache-2.0 | 38ef64dbce643e1781cb0d8268fadcb377c68266 | 0 | googleinterns/step132-2020,googleinterns/step132-2020,googleinterns/step132-2020 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Function for progess.html, checks what kind of user the viewer is, and loads progress information
*/
function loadProgress(document, loginStatus, user) {
addEventListeners();
document.getElementById('progress-tracker').style.display = 'block';
getExperiences(document, loginStatus, user);
getGoals(document, loginStatus, user);
getPastSessionsAndTopics(document, loginStatus, user);
}
/** A function that adds event listeners to a DOM objects. */
function addEventListeners() {
document.getElementById("experiences-form").addEventListener('submit', event => {
event.preventDefault();
addExperience(window);
});
document.getElementById("goals-form").addEventListener('submit', event => {
event.preventDefault();
addGoal(window);
});
}
function getExperiences(document, loginStatus, user) {
var queryString = new Array();
window.onload = readComponents(queryString, window);
const studentID = queryString["userID"];
const params = new URLSearchParams();
params.append('studentID', studentID);
fetch('/experience?studentID=' + studentID, {method: 'GET'}).then(response => response.json()).then((experiences) => {
getExperiencesHelper(document, experiences, loginStatus, user);
});
// If user is both a student and a tutor
if (user.student != null ) {
// If user is the one whose profile is being displayed
if (loginStatus.userId == user.student.userId) {
document.getElementById('experiences-form').style.display = "block";
} else {
document.getElementById('experiences-form').style.display = "none";
}
} else if (loginStatus.userId == user.userId) {
document.getElementById('experiences-form').style.display = "block";
} else {
document.getElementById('experiences-form').style.display = "none";
}
}
function getExperiencesHelper(document, experiences, loginStatus, user) {
//if there was an error
if(experiences.error) {
var experienceContainer = document.getElementById('experiences');
var errorMessage = document.createElement("p");
errorMessage.innerText = experiences.error;
experienceContainer.appendChild(errorMessage);
return;
}
if (Object.keys(experiences).length != 0) {
experiences.forEach((experience) => {
document.getElementById('experiences').appendChild(createExperienceBox(experience, loginStatus, user));
})
} else {
var experienceContainer = document.getElementById('experiences');
var errorMessage = document.createElement("p");
errorMessage.innerText = "This user has not set any past experiences";
errorMessage.className = "text-center";
experienceContainer.appendChild(errorMessage);
return;
}
}
function getGoals(document, loginStatus, user) {
var queryString = new Array();
window.onload = readComponents(queryString, window);
const studentID = queryString["userID"];
const params = new URLSearchParams();
params.append('studentID', studentID);
fetch('/goal?studentID=' + studentID, {method: 'GET'}).then(response => response.json()).then((goals) => {
getGoalsHelper(document, goals, loginStatus, user);
});
// If user is both a student and a tutor
if (user.student != null ) {
// If user is the one whose profile is being displayed
if (loginStatus.userId == user.student.userId) {
document.getElementById('goals-form').style.display = "block";
} else {
document.getElementById('goals-form').style.display = "none";
}
} else if (loginStatus.userId == user.userId) {
document.getElementById('goals-form').style.display = "block";
} else {
document.getElementById('goals-form').style.display = "none";
}
}
function getGoalsHelper(document, goals, loginStatus, user) {
//if there was an error
if(goals.error) {
var goalContainer = document.getElementById('goals');
var errorMessage = document.createElement("p");
errorMessage.innerText = goals.error;
goalContainer.appendChild(errorMessage);
return;
}
if (Object.keys(goals).length != 0) {
goals.forEach((goal) => {
document.getElementById('goals').appendChild(createGoalBox(goal, loginStatus, user));
})
} else {
var goalContainer = document.getElementById('goals');
var errorMessage = document.createElement("p");
errorMessage.innerText = "This user has not set any goals";
errorMessage.className = "text-center";
goalContainer.appendChild(errorMessage);
return;
}
}
function getPastSessionsAndTopics(document, loginStatus, user) {
// If the user is both a tutor and a student
if (user.student != null) {
// Do not display past tutoring sessions and past learned topics if the user viewing the profile is not one of the student's tutors or
// the student themselves
if (user.student.tutors.includes(loginStatus.userId) || user.student.userId == loginStatus.userId) {
const studentID = user.student.userId;
const params = new URLSearchParams();
params.append('studentID', studentID);
fetch('/history?studentIDTutorView=' + studentID, {method: 'GET'}).then(response => response.json()).then((tutoringSessions) => {
getPastSessionsAndTopicsHelper(document, tutoringSessions);
});
} else {
document.getElementById("sessionsAndAchievements").style.display = "none";
return;
}
} else {
if (user.tutors.includes(loginStatus.userId) || user.userId == loginStatus.userId) {
const studentID = user.userId;
const params = new URLSearchParams();
params.append('studentID', studentID);
fetch('/history?studentIDTutorView=' + studentID, {method: 'GET'}).then(response => response.json()).then((tutoringSessions) => {
getPastSessionsAndTopicsHelper(document, tutoringSessions);
});
} else {
document.getElementById("sessionsAndAchievements").style.display = "none";
return;
}
}
}
function getPastSessionsAndTopicsHelper(document, tutoringSessions) {
//if there was an error
if(tutoringSessions.error) {
var pastSessions = document.getElementById('past-sessions');
var pastTopics = document.getElementById('past-topics');
var errorMessage1 = document.createElement("p");
var errorMessage2 = document.createElement("p");
errorMessage1.innerText = tutoringSessions.error;
errorMessage2.innerText = tutoringSessions.error;
pastSessions.appendChild(errorMessage1);
pastTopics.appendChild(errorMessage2);
return;
}
if (Object.keys(tutoringSessions).length != 0) {
tutoringSessions.forEach((tutoringSession) => {
document.getElementById('past-sessions').appendChild(createPastSessionBox(tutoringSession));
// If the tutoring session subtopics field is not empty, create a box for it
if (tutoringSession.subtopics != "") {
document.getElementById('past-topics').appendChild(createPastTopicBox(tutoringSession));
}
})
} else {
var pastSessions = document.getElementById('past-sessions');
var pastTopics = document.getElementById('past-topics');
var errorMessage1 = document.createElement("p");
var errorMessage2 = document.createElement("p");
errorMessage1.innerText = "This user has not had any tutoring sessions yet.";
errorMessage2.innerText = "This user has not had any tutoring sessions yet.";
errorMessage1.className = "text-center";
errorMessage2.className = "text-center";
pastSessions.appendChild(errorMessage1);
pastTopics.appendChild(errorMessage2);
return;
}
}
/** Creates a div element containing information about a past tutoring session. */
function createPastSessionBox(tutoringSession) {
var months = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
const sessionContainer = document.createElement("div");
const tutorName = document.createElement("h3");
const date = document.createElement("h6");
setTutorName(tutorName, tutoringSession.tutorID);
var hour = Math.floor(parseInt(tutoringSession.timeslot.start) / 60);
var amOrPm = "am";
if (hour > 12) {
hour = hour - 12;
amOrPm = "pm"
}
var minute = parseInt(tutoringSession.timeslot.start) % 60;
if (minute == 0) {
minute = "00";
}
date.innerText = hour + ":" + minute + amOrPm + " on " + months[tutoringSession.timeslot.date.month] +
" " + tutoringSession.timeslot.date.dayOfMonth + ", " + tutoringSession.timeslot.date.year;
sessionContainer.classList.add("result");
sessionContainer.classList.add("list-group-item");
sessionContainer.appendChild(tutorName);
sessionContainer.appendChild(date);
return sessionContainer;
}
/** Creates a div element containing information about a past topic. */
function createPastTopicBox(tutoringSession) {
const topicContainer = document.createElement("div");
const topic = document.createElement("h3");
topic.innerText = tutoringSession.subtopics;
topic.style.textTransform = "capitalize";
topicContainer.classList.add("result");
topicContainer.classList.add("list-group-item");
topicContainer.appendChild(topic);
return topicContainer;
}
/** Creates a div element containing information about a goal. */
function createGoalBox(goal, loginStatus, user) {
const goalContainer = document.createElement("div");
const description = document.createElement("h3");
description.innerText = goal.goal;
description.style.textTransform = "capitalize";
description.style.display = 'inline';
description.style.padding = '0px 15px 0px 0px';
goalContainer.classList.add("result");
goalContainer.classList.add("list-group-item");
goalContainer.appendChild(description);
// If user is both a student and a tutor
if (user.student != null ) {
// If user is the one whose profile is being displayed, display delete button
if (loginStatus.userId == user.student.userId) {
const deleteGoalButton = document.createElement('button');
deleteGoalButton.innerText = 'Delete';
deleteGoalButton.className = 'btn btn-default btn-lg';
deleteGoalButton.addEventListener('click', () => {
deleteGoal(goal, loginStatus.userId, window);
goalContainer.remove();
});
goalContainer.appendChild(deleteGoalButton);
}
} else if (loginStatus.userId == user.userId) {
const deleteGoalButton = document.createElement('button');
deleteGoalButton.innerText = 'Delete';
deleteGoalButton.className = 'btn btn-default btn-lg';
deleteGoalButton.addEventListener('click', () => {
deleteGoal(goal, loginStatus.userId, window);
goalContainer.remove();
});
goalContainer.appendChild(deleteGoalButton);
}
return goalContainer;
}
/** Creates a div element containing information about an experience. */
function createExperienceBox(experience, loginStatus, user) {
const experienceContainer = document.createElement("div");
const description = document.createElement("h3");
description.innerText = experience.experience;
description.style.textTransform = "capitalize";
description.style.display = 'inline';
description.style.padding = '0px 15px 0px 0px';
experienceContainer.classList.add("result");
experienceContainer.classList.add("list-group-item");
experienceContainer.appendChild(description);
// If user is both a student and a tutor
if (user.student != null ) {
// If user is the one whose profile is being displayed, display delete button
if (loginStatus.userId == user.student.userId) {
const deleteExperienceButton = document.createElement('button');
deleteExperienceButton.innerText = 'Delete';
deleteExperienceButton.className = 'btn btn-default btn-lg';
deleteExperienceButton.addEventListener('click', () => {
deleteExperience(experience, loginStatus.userId, window);
experienceContainer.remove();
});
experienceContainer.appendChild(deleteExperienceButton);
}
} else if (loginStatus.userId == user.userId) {
const deleteExperienceButton = document.createElement('button');
deleteExperienceButton.innerText = 'Delete';
deleteExperienceButton.className = 'btn btn-default btn-lg';
deleteExperienceButton.addEventListener('click', () => {
deleteExperience(experience, loginStatus.userId, window);
experienceContainer.remove();
});
experienceContainer.appendChild(deleteExperienceButton);
}
return experienceContainer;
}
function addGoal(window) {
const params = new URLSearchParams();
var queryString = new Array();
window.onload = readComponents(queryString, window);
const studentID = queryString["userID"];
params.append('goal', document.getElementById('newGoal').value);
fetch('/add-goal', {method: 'POST', body: params}).then((response) => {
//if the student is not the current user or not signed in
if(response.redirected) {
window.location.href = response.url;
alert("You must be signed in to add a goal.");
return;
}
window.location.href = "/profile.html?userID=" + studentID;
});
}
function deleteGoal(goal, window) {
const params = new URLSearchParams();
params.append('id', goal.id);
fetch('/delete-goal', {method: 'POST', body: params}).then((response) => {
//if the student is not the current user or not signed in
if(response.redirected) {
window.location.href = response.url;
alert("You must be signed in to delete a goal.");
return;
}
});
}
function addExperience(window) {
const params = new URLSearchParams();
var queryString = new Array();
window.onload = readComponents(queryString, window);
const studentID = queryString["userID"];
params.append('experience', document.getElementById('newExperience').value);
fetch('/add-experience', {method: 'POST', body: params}).then((response) => {
//if the student is not the current user or not signed in
if(response.redirected) {
window.location.href = response.url;
alert("You must be signed in to add an experience.");
return;
}
window.location.href = "/profile.html?userID=" + studentID;
});
}
function deleteExperience(experience, window) {
const params = new URLSearchParams();
params.append('id', experience.id);
fetch('/delete-experience', {method: 'POST', body: params}).then((response) => {
//if the student is not the current user or not signed in
if(response.redirected) {
window.location.href = response.url;
alert("You must be signed in to delete an experience.");
return;
}
});
}
| src/main/webapp/progress.js | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Function for progess.html, checks what kind of user the viewer is, and loads progress information
*/
function loadProgress(document, loginStatus, user) {
addEventListeners();
document.getElementById('progress-tracker').style.display = 'block';
getExperiences(document, loginStatus, user);
getGoals(document, loginStatus, user);
getPastSessionsAndTopics(document, loginStatus, user);
}
/** A function that adds event listeners to a DOM objects. */
function addEventListeners() {
document.getElementById("experiences-form").addEventListener('submit', event => {
event.preventDefault();
addExperience(window);
});
document.getElementById("goals-form").addEventListener('submit', event => {
event.preventDefault();
addGoal(window);
});
}
function getExperiences(document, loginStatus, user) {
var queryString = new Array();
window.onload = readComponents(queryString, window);
const studentID = queryString["userID"];
const params = new URLSearchParams();
params.append('studentID', studentID);
fetch('/experience?studentID=' + studentID, {method: 'GET'}).then(response => response.json()).then((experiences) => {
getExperiencesHelper(document, experiences, loginStatus, user);
});
// If user is both a student and a tutor
if (user.student != null ) {
// If user is the one whose profile is being displayed
if (loginStatus.userId == user.student.userId) {
document.getElementById('experiences-form').style.display = "block";
} else {
document.getElementById('experiences-form').style.display = "none";
}
} else if (loginStatus.userId == user.userId) {
document.getElementById('experiences-form').style.display = "block";
} else {
document.getElementById('experiences-form').style.display = "none";
}
}
function getExperiencesHelper(document, experiences, loginStatus, user) {
//if there was an error
if(experiences.error) {
var experienceContainer = document.getElementById('experiences');
var errorMessage = document.createElement("p");
errorMessage.innerText = experiences.error;
experienceContainer.appendChild(errorMessage);
return;
}
if (Object.keys(experiences).length != 0) {
experiences.forEach((experience) => {
document.getElementById('experiences').appendChild(createExperienceBox(experience, loginStatus, user));
})
} else {
var experienceContainer = document.getElementById('experiences');
var errorMessage = document.createElement("p");
errorMessage.innerText = "This user has not set any past experiences";
errorMessage.className = "text-center";
experienceContainer.appendChild(errorMessage);
return;
}
}
function getGoals(document, loginStatus, user) {
var queryString = new Array();
window.onload = readComponents(queryString, window);
const studentID = queryString["userID"];
const params = new URLSearchParams();
params.append('studentID', studentID);
fetch('/goal?studentID=' + studentID, {method: 'GET'}).then(response => response.json()).then((goals) => {
getGoalsHelper(document, goals, loginStatus, user);
});
// If user is both a student and a tutor
if (user.student != null ) {
// If user is the one whose profile is being displayed
if (loginStatus.userId == user.student.userId) {
document.getElementById('goals-form').style.display = "block";
} else {
document.getElementById('goals-form').style.display = "none";
}
} else if (loginStatus.userId == user.userId) {
document.getElementById('goals-form').style.display = "block";
} else {
document.getElementById('goals-form').style.display = "none";
}
}
function getGoalsHelper(document, goals, loginStatus, user) {
//if there was an error
if(goals.error) {
var goalContainer = document.getElementById('goals');
var errorMessage = document.createElement("p");
errorMessage.innerText = goals.error;
goalContainer.appendChild(errorMessage);
return;
}
if (Object.keys(goals).length != 0) {
goals.forEach((goal) => {
document.getElementById('goals').appendChild(createGoalBox(goal, loginStatus, user));
})
} else {
var goalContainer = document.getElementById('goals');
var errorMessage = document.createElement("p");
errorMessage.innerText = "This user has not set any goals";
errorMessage.className = "text-center";
goalContainer.appendChild(errorMessage);
return;
}
}
function getPastSessionsAndTopics(document, loginStatus, user) {
// If the user is both a tutor and a student
if (user.student != null) {
// Do not display past tutoring sessions and past learned topics if the user viewing the profile is not one of the student's tutors or
// the student themselves
if (user.student.tutors.includes(loginStatus.userId) || user.student.userId == loginStatus.userId) {
const studentID = user.student.userId;
const params = new URLSearchParams();
params.append('studentID', studentID);
fetch('/history?studentIDTutorView=' + studentID, {method: 'GET'}).then(response => response.json()).then((tutoringSessions) => {
getPastSessionsAndTopicsHelper(document, tutoringSessions);
});
} else {
document.getElementById("sessionsAndAchievements").style.display = "none";
return;
}
} else {
if (user.tutors.includes(loginStatus.userId) || user.userId == loginStatus.userId) {
const studentID = user.userId;
const params = new URLSearchParams();
params.append('studentID', studentID);
fetch('/history?studentIDTutorView=' + studentID, {method: 'GET'}).then(response => response.json()).then((tutoringSessions) => {
getPastSessionsAndTopicsHelper(document, tutoringSessions);
});
} else {
document.getElementById("sessionsAndAchievements").style.display = "none";
return;
}
}
}
function getPastSessionsAndTopicsHelper(document, tutoringSessions) {
//if there was an error
if(tutoringSessions.error) {
var pastSessions = document.getElementById('past-sessions');
var pastTopics = document.getElementById('past-topics');
var errorMessage1 = document.createElement("p");
var errorMessage2 = document.createElement("p");
errorMessage1.innerText = tutoringSessions.error;
errorMessage2.innerText = tutoringSessions.error;
pastSessions.appendChild(errorMessage1);
pastTopics.appendChild(errorMessage2);
return;
}
if (Object.keys(tutoringSessions).length != 0) {
tutoringSessions.forEach((tutoringSession) => {
document.getElementById('past-sessions').appendChild(createPastSessionBox(tutoringSession));
document.getElementById('past-topics').appendChild(createPastTopicBox(tutoringSession));
})
} else {
var pastSessions = document.getElementById('past-sessions');
var pastTopics = document.getElementById('past-topics');
var errorMessage1 = document.createElement("p");
var errorMessage2 = document.createElement("p");
errorMessage1.innerText = "This user has not had any tutoring sessions yet.";
errorMessage2.innerText = "This user has not had any tutoring sessions yet.";
errorMessage1.className = "text-center";
errorMessage2.className = "text-center";
pastSessions.appendChild(errorMessage1);
pastTopics.appendChild(errorMessage2);
return;
}
}
/** Creates a div element containing information about a past tutoring session. */
function createPastSessionBox(tutoringSession) {
var months = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
const sessionContainer = document.createElement("div");
const tutorName = document.createElement("h3");
const date = document.createElement("h6");
setTutorName(tutorName, tutoringSession.tutorID);
var hour = Math.floor(parseInt(tutoringSession.timeslot.start) / 60);
var amOrPm = "am";
if (hour > 12) {
hour = hour - 12;
amOrPm = "pm"
}
var minute = parseInt(tutoringSession.timeslot.start) % 60;
if (minute == 0) {
minute = "00";
}
date.innerText = hour + ":" + minute + amOrPm + " on " + months[tutoringSession.timeslot.date.month] +
" " + tutoringSession.timeslot.date.dayOfMonth + ", " + tutoringSession.timeslot.date.year;
sessionContainer.classList.add("result");
sessionContainer.classList.add("list-group-item");
sessionContainer.appendChild(tutorName);
sessionContainer.appendChild(date);
return sessionContainer;
}
/** Creates a div element containing information about a past topic. */
function createPastTopicBox(tutoringSession) {
const topicContainer = document.createElement("div");
const topic = document.createElement("h3");
topic.innerText = tutoringSession.subtopics;
topic.style.textTransform = "capitalize";
topicContainer.classList.add("result");
topicContainer.classList.add("list-group-item");
topicContainer.appendChild(topic);
return topicContainer;
}
/** Creates a div element containing information about a goal. */
function createGoalBox(goal, loginStatus, user) {
const goalContainer = document.createElement("div");
const description = document.createElement("h3");
description.innerText = goal.goal;
description.style.textTransform = "capitalize";
description.style.display = 'inline';
description.style.padding = '0px 15px 0px 0px';
goalContainer.classList.add("result");
goalContainer.classList.add("list-group-item");
goalContainer.appendChild(description);
// If user is both a student and a tutor
if (user.student != null ) {
// If user is the one whose profile is being displayed, display delete button
if (loginStatus.userId == user.student.userId) {
const deleteGoalButton = document.createElement('button');
deleteGoalButton.innerText = 'Delete';
deleteGoalButton.className = 'btn btn-default btn-lg';
deleteGoalButton.addEventListener('click', () => {
deleteGoal(goal, loginStatus.userId, window);
goalContainer.remove();
});
goalContainer.appendChild(deleteGoalButton);
}
} else if (loginStatus.userId == user.userId) {
const deleteGoalButton = document.createElement('button');
deleteGoalButton.innerText = 'Delete';
deleteGoalButton.className = 'btn btn-default btn-lg';
deleteGoalButton.addEventListener('click', () => {
deleteGoal(goal, loginStatus.userId, window);
goalContainer.remove();
});
goalContainer.appendChild(deleteGoalButton);
}
return goalContainer;
}
/** Creates a div element containing information about an experience. */
function createExperienceBox(experience, loginStatus, user) {
const experienceContainer = document.createElement("div");
const description = document.createElement("h3");
description.innerText = experience.experience;
description.style.textTransform = "capitalize";
description.style.display = 'inline';
description.style.padding = '0px 15px 0px 0px';
experienceContainer.classList.add("result");
experienceContainer.classList.add("list-group-item");
experienceContainer.appendChild(description);
// If user is both a student and a tutor
if (user.student != null ) {
// If user is the one whose profile is being displayed, display delete button
if (loginStatus.userId == user.student.userId) {
const deleteExperienceButton = document.createElement('button');
deleteExperienceButton.innerText = 'Delete';
deleteExperienceButton.className = 'btn btn-default btn-lg';
deleteExperienceButton.addEventListener('click', () => {
deleteExperience(experience, loginStatus.userId, window);
experienceContainer.remove();
});
experienceContainer.appendChild(deleteExperienceButton);
}
} else if (loginStatus.userId == user.userId) {
const deleteExperienceButton = document.createElement('button');
deleteExperienceButton.innerText = 'Delete';
deleteExperienceButton.className = 'btn btn-default btn-lg';
deleteExperienceButton.addEventListener('click', () => {
deleteExperience(experience, loginStatus.userId, window);
experienceContainer.remove();
});
experienceContainer.appendChild(deleteExperienceButton);
}
return experienceContainer;
}
function addGoal(window) {
const params = new URLSearchParams();
var queryString = new Array();
window.onload = readComponents(queryString, window);
const studentID = queryString["userID"];
params.append('goal', document.getElementById('newGoal').value);
fetch('/add-goal', {method: 'POST', body: params}).then((response) => {
//if the student is not the current user or not signed in
if(response.redirected) {
window.location.href = response.url;
alert("You must be signed in to add a goal.");
return;
}
window.location.href = "/profile.html?userID=" + studentID;
});
}
function deleteGoal(goal, window) {
const params = new URLSearchParams();
params.append('id', goal.id);
fetch('/delete-goal', {method: 'POST', body: params}).then((response) => {
//if the student is not the current user or not signed in
if(response.redirected) {
window.location.href = response.url;
alert("You must be signed in to delete a goal.");
return;
}
});
}
function addExperience(window) {
const params = new URLSearchParams();
var queryString = new Array();
window.onload = readComponents(queryString, window);
const studentID = queryString["userID"];
params.append('experience', document.getElementById('newExperience').value);
fetch('/add-experience', {method: 'POST', body: params}).then((response) => {
//if the student is not the current user or not signed in
if(response.redirected) {
window.location.href = response.url;
alert("You must be signed in to add an experience.");
return;
}
window.location.href = "/profile.html?userID=" + studentID;
});
}
function deleteExperience(experience, window) {
const params = new URLSearchParams();
params.append('id', experience.id);
fetch('/delete-experience', {method: 'POST', body: params}).then((response) => {
//if the student is not the current user or not signed in
if(response.redirected) {
window.location.href = response.url;
alert("You must be signed in to delete an experience.");
return;
}
});
}
| Add a check so that only past topics that have been specified are displayed (#134)
| src/main/webapp/progress.js | Add a check so that only past topics that have been specified are displayed (#134) | <ide><path>rc/main/webapp/progress.js
<ide> if (Object.keys(tutoringSessions).length != 0) {
<ide> tutoringSessions.forEach((tutoringSession) => {
<ide> document.getElementById('past-sessions').appendChild(createPastSessionBox(tutoringSession));
<del> document.getElementById('past-topics').appendChild(createPastTopicBox(tutoringSession));
<add> // If the tutoring session subtopics field is not empty, create a box for it
<add> if (tutoringSession.subtopics != "") {
<add> document.getElementById('past-topics').appendChild(createPastTopicBox(tutoringSession));
<add> }
<ide> })
<ide> } else {
<ide> var pastSessions = document.getElementById('past-sessions'); |
|
Java | apache-2.0 | 49bb4ab1a61f0ad1fc204675878ca8d00aebb29b | 0 | rkrell/izpack,izpack/izpack,akuhtz/izpack,mtjandra/izpack,mtjandra/izpack,codehaus/izpack,Helpstone/izpack,rkrell/izpack,mtjandra/izpack,bradcfisher/izpack,izpack/izpack,Murdock01/izpack,tomas-forsman/izpack,stenix71/izpack,stenix71/izpack,rsharipov/izpack,codehaus/izpack,akuhtz/izpack,Sage-ERP-X3/izpack,mtjandra/izpack,kanayo/izpack,yukron/izpack,kanayo/izpack,rsharipov/izpack,codehaus/izpack,tomas-forsman/izpack,Helpstone/izpack,dasapich/izpack,rkrell/izpack,Helpstone/izpack,izpack/izpack,yukron/izpack,rkrell/izpack,codehaus/izpack,rkrell/izpack,stenix71/izpack,bradcfisher/izpack,izpack/izpack,izpack/izpack,yukron/izpack,Murdock01/izpack,optotronic/izpack,maichler/izpack,dasapich/izpack,kanayo/izpack,yukron/izpack,dasapich/izpack,kanayo/izpack,Sage-ERP-X3/izpack,bradcfisher/izpack,Helpstone/izpack,Helpstone/izpack,stenix71/izpack,Murdock01/izpack,tomas-forsman/izpack,akuhtz/izpack,optotronic/izpack,dasapich/izpack,Murdock01/izpack,maichler/izpack,bradcfisher/izpack,maichler/izpack,optotronic/izpack,Helpstone/izpack,dasapich/izpack,Sage-ERP-X3/izpack,optotronic/izpack,mtjandra/izpack,akuhtz/izpack,rsharipov/izpack,codehaus/izpack,Sage-ERP-X3/izpack,Helpstone/izpack,dasapich/izpack,tomas-forsman/izpack,mtjandra/izpack,bradcfisher/izpack,maichler/izpack,tomas-forsman/izpack,awilhelm/izpack-with-ips,akuhtz/izpack,stenix71/izpack,awilhelm/izpack-with-ips,akuhtz/izpack,kanayo/izpack,rkrell/izpack,Murdock01/izpack,rsharipov/izpack,mtjandra/izpack,optotronic/izpack,rsharipov/izpack,codehaus/izpack,bradcfisher/izpack,optotronic/izpack,awilhelm/izpack-with-ips,rsharipov/izpack,Sage-ERP-X3/izpack,stenix71/izpack,akuhtz/izpack,yukron/izpack,codehaus/izpack,kanayo/izpack,maichler/izpack,stenix71/izpack,Sage-ERP-X3/izpack,tomas-forsman/izpack,maichler/izpack,Murdock01/izpack,optotronic/izpack,maichler/izpack,yukron/izpack,rkrell/izpack,yukron/izpack,bradcfisher/izpack,tomas-forsman/izpack,awilhelm/izpack-with-ips,dasapich/izpack,rsharipov/izpack,awilhelm/izpack-with-ips,Sage-ERP-X3/izpack,izpack/izpack,izpack/izpack,Murdock01/izpack | /*
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://www.izforge.com/izpack/
* http://izpack.codehaus.org/
*
* Copyright 2003 Marc Eppelmann
*
* 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.
*/
/*
* This represents a Implementation of the KDE/GNOME DesktopEntry.
* which is standard from
* "Desktop Entry Standard"
* "The format of .desktop files, supported by KDE and GNOME."
* http://www.freedesktop.org/standards/desktop-entry-spec/
*
* [Desktop Entry]
// Comment=$Comment
// Comment[de]=
// Encoding=$UTF-8
// Exec=$'/home/marc/CPS/tomcat/bin/catalina.sh' run
// GenericName=$
// GenericName[de]=$
// Icon=$inetd
// MimeType=$
// Name=$Start Tomcat
// Name[de]=$Start Tomcat
// Path=$/home/marc/CPS/tomcat/bin/
// ServiceTypes=$
// SwallowExec=$
// SwallowTitle=$
// Terminal=$true
// TerminalOptions=$
// Type=$Application
// X-KDE-SubstituteUID=$false
// X-KDE-Username=$
*
*/
package com.izforge.izpack.util.os;
import com.izforge.izpack.installer.AutomatedInstallData;
import com.izforge.izpack.installer.InstallData;
import com.izforge.izpack.installer.ResourceManager;
import com.izforge.izpack.installer.ResourceNotFoundException;
import com.izforge.izpack.util.Debug;
import com.izforge.izpack.util.FileExecutor;
import com.izforge.izpack.util.OsVersion;
import com.izforge.izpack.util.StringTool;
import com.izforge.izpack.util.os.unix.ShellScript;
import com.izforge.izpack.util.os.unix.UnixHelper;
import com.izforge.izpack.util.os.unix.UnixUser;
import com.izforge.izpack.util.os.unix.UnixUsers;
import com.sun.corba.se.impl.orbutil.closure.Constant;
import java.io.*;
import java.util.*;
/**
* This is the Implementation of the RFC-Based Desktop-Link. Used in KDE and GNOME.
*
* @author marc.eppelmann@reddot.de
*/
public class Unix_Shortcut extends Shortcut implements Unix_ShortcutConstants
{
// ~ Static fields/initializers
// *******************************************************************************************************************************
/**
* version = "$Id$"
*/
private static String version = "$Id$";
/**
* rev = "$Revision$"
*/
private static String rev = "$Revision$";
/**
* DESKTOP_EXT = ".desktop"
*/
private static String DESKTOP_EXT = ".desktop";
/**
* template = ""
*/
private static String template = "";
/**
* N = "\n"
*/
private final static String N = "\n";
/**
* H = "#"
*/
private final static String H = "#";
/**
* S = " "
*/
private final static String S = " ";
/**
* C = Comment = H+S = "# "
*/
private final static String C = H + S;
/**
* QM = "\"" : <b>Q</b>uotation<b>M</b>ark
*/
private final static String QM = "\"";
private int ShortcutType;
private static ShellScript rootScript = null;
private static ShellScript uninstallScript = null;
private static ArrayList users = UnixUsers.getUsersWithValidShellsExistingHomesAndDesktops();
// private static ArrayList tempfiles = new ArrayList();
// ~ Instance fields
// ******************************************************************************************************************************************
/**
* internal String createdDirectory
*/
private String createdDirectory;
/**
* internal int itsUserType
*/
private int itsUserType;
/**
* internal String itsGroupName
*/
private String itsGroupName;
/**
* internal String itsName
*/
private String itsName;
/**
* internal String itsFileName
*/
private String itsFileName;
/**
* internal String itsApplnkFolder = "applnk"
*/
private String itsApplnkFolder = "applnk";
/**
* internal Properties Set
*/
private Properties props;
/**
* forAll = new Boolean(false): A flag to indicate that this should created for all users.
*/
private Boolean forAll = Boolean.FALSE;
/**
* Internal Help Buffer
*/
public StringBuffer hlp;
/** my Install ShellScript **/
public ShellScript myInstallScript;
/** Internal Constant: FS = File.separator // **/
public final String FS = File.separator;
/** Internal Constant: myHome = System.getProperty("user.home") **/
public final String myHome = System.getProperty("user.home");
/** Internal Constant: su = UnixHelper.getSuCommand() **/
public final String su = UnixHelper.getSuCommand();
/** Internal Constant: xdgDesktopIconCmd = UnixHelper.getCustomCommand("xdg-desktop-icon") **/
public final String xdgDesktopIconCmd = UnixHelper.getCustomCommand("xdg-desktop-icon");
public String myXdgDesktopIconScript;
public String myXdgDesktopIconCmd;
// ~ Constructors ***********************************************************************
// ~ Constructors
// *********************************************************************************************************************************************
/**
* Creates a new Unix_Shortcut object.
*/
public Unix_Shortcut()
{
hlp = new StringBuffer();
String userLanguage = System.getProperty("user.language", "en");
hlp.append("[Desktop Entry]" + N);
// TODO implement Attribute: X-KDE-StartupNotify=true
hlp.append("Categories=" + $Categories + N);
hlp.append("Comment=" + $Comment + N);
hlp.append("Comment[").append(userLanguage).append("]=" + $Comment + N);
hlp.append("Encoding=" + $Encoding + N);
// this causes too many problems
// hlp.append("TryExec=" + $E_QUOT + $Exec + $E_QUOT + S + $Arguments + N);
hlp.append("Exec=" + $E_QUOT + $Exec + $E_QUOT + S + $Arguments + N);
hlp.append("GenericName=" + $GenericName + N);
hlp.append("GenericName[").append(userLanguage).append("]=" + $GenericName + N);
hlp.append("Icon=" + $Icon + N);
hlp.append("MimeType=" + $MimeType + N);
hlp.append("Name=" + $Name + N);
hlp.append("Name[").append(userLanguage).append("]=" + $Name + N);
hlp.append("Path=" + $P_QUOT + $Path + $P_QUOT + N);
hlp.append("ServiceTypes=" + $ServiceTypes + N);
hlp.append("SwallowExec=" + $SwallowExec + N);
hlp.append("SwallowTitle=" + $SwallowTitle + N);
hlp.append("Terminal=" + $Terminal + N);
hlp.append("TerminalOptions=" + $Options_For_Terminal + N);
hlp.append("Type=" + $Type + N);
hlp.append("URL=" + $URL + N);
hlp.append("X-KDE-SubstituteUID=" + $X_KDE_SubstituteUID + N);
hlp.append("X-KDE-Username=" + $X_KDE_Username + N);
hlp.append(N);
hlp.append(C + "created by" + S).append(getClass().getName()).append(S).append(rev).append(
N);
hlp.append(C).append(version);
template = hlp.toString();
props = new Properties();
initProps();
if (rootScript == null)
{
rootScript = new ShellScript();
}
if (uninstallScript == null)
{
uninstallScript = new ShellScript();
}
if (myInstallScript == null)
{
myInstallScript = new ShellScript();
}
}
// ~ Methods ****************************************************************************
// ~ Methods
// **************************************************************************************************************************************************
/**
* This initialisizes all Properties Values with "".
*/
private void initProps()
{
String[] propsArray = { $Comment, $$LANG_Comment, $Encoding, $Exec, $Arguments,
$GenericName, $$LANG_GenericName, $MimeType, $Name, $$LANG_Name, $Path,
$ServiceTypes, $SwallowExec, $SwallowTitle, $Terminal, $Options_For_Terminal,
$Type, $X_KDE_SubstituteUID, $X_KDE_Username, $Icon, $URL, $E_QUOT, $P_QUOT,
$Categories, $TryExec};
for (String aPropsArray : propsArray)
{
props.put(aPropsArray, "");
}
}
/**
* Overridden Method
*
* @see com.izforge.izpack.util.os.Shortcut#initialize(int, java.lang.String)
*/
public void initialize(int aType, String aName) throws Exception
{
this.itsName = aName;
props.put($Name, aName);
}
/**
* This indicates that Unix will be supported.
*
* @see com.izforge.izpack.util.os.Shortcut#supported()
*/
public boolean supported()
{
return true;
}
/**
* Dummy
*
* @see com.izforge.izpack.util.os.Shortcut#getDirectoryCreated()
*/
public String getDirectoryCreated()
{
return this.createdDirectory; // while not stored...
}
/**
* Dummy
*
* @see com.izforge.izpack.util.os.Shortcut#getFileName()
*/
public String getFileName()
{
return (this.itsFileName);
}
/**
* Overridden compatibility method. Returns all directories in $USER/.kde/share/applink.
*
* @see com.izforge.izpack.util.os.Shortcut#getProgramGroups(int)
*/
public Vector<String> getProgramGroups(int userType)
{
Vector<String> groups = new Vector<String>();
File kdeShareApplnk = getKdeShareApplnkFolder(userType);
try
{
File[] listing = kdeShareApplnk.listFiles();
for (File aListing : listing)
{
if (aListing.isDirectory())
{
groups.add(aListing.getName());
}
}
}
catch (Exception e)
{
// ignore and return an empty vector.
}
return (groups);
}
/**
* Gets the Programsfolder for the given User (non-Javadoc).
*
* @see com.izforge.izpack.util.os.Shortcut#getProgramsFolder(int)
*/
public String getProgramsFolder(int current_user)
{
String result = "";
//
result = getKdeShareApplnkFolder(current_user).toString();
return result;
}
/**
* Gets the XDG path to place the menu shortcuts
*
* @param userType to get for.
* @return handle to the directory
*/
private File getKdeShareApplnkFolder(int userType)
{
if (userType == Shortcut.ALL_USERS)
{
return new File(File.separator + "usr" + File.separator + "share" + File.separator
+ "applications");
}
else
{
return new File(System.getProperty("user.home") + File.separator + ".local"
+ File.separator + "share" + File.separator + "applications");
}
}
/**
* Gets the name of the applink folder for the currently used distribution. Currently
* "applnk-redhat for RedHat, "applnk-mdk" for Mandrake, and simply "applnk" for all others.
*
* @return result
*/
private String getKdeApplinkFolderName()
{
String applinkFolderName = "applnk";
if (OsVersion.IS_REDHAT_LINUX)
{
applinkFolderName = "applnk-redhat";
}
if (OsVersion.IS_MANDRAKE_LINUX)
{
applinkFolderName = "applnk-mdk";
}
return applinkFolderName;
}
/**
* Gets the KDEBasedir for the given User.
*
* @param userType one of root or regular user
* @return the basedir
*/
private File getKdeBase(int userType)
{
File result = null;
if (userType == Shortcut.ALL_USERS)
{
FileExecutor fe = new FileExecutor();
String[] execOut = new String[2];
int execResult = fe.executeCommand(new String[] { "/usr/bin/env", "kde-config",
"--prefix"}, execOut);
result = new File(execOut[0].trim());
}
else
{
result = new File(System.getProperty("user.home") + File.separator + ".kde");
}
return result;
}
/**
* overridden method
*
* @return true
* @see com.izforge.izpack.util.os.Shortcut#multipleUsers()
*/
public boolean multipleUsers()
{
// EVER true for UNIXes ;-)
return (true);
}
/**
* Creates and stores the shortcut-files.
*
* @see com.izforge.izpack.util.os.Shortcut#save()
*/
public void save() throws Exception
{
String target = null;
String shortCutDef = this.replace();
boolean rootUser4All = this.getUserType() == Shortcut.ALL_USERS;
boolean create4All = this.getCreateForAll();
// Create The Desktop Shortcuts
if ("".equals(this.itsGroupName) && (this.getLinkType() == Shortcut.DESKTOP))
{
this.itsFileName = target;
AutomatedInstallData idata;
idata = AutomatedInstallData.getInstance();
// read the userdefined / overridden / wished Shortcut Location
// This can be an absolute Path name or a relative Path to the InstallPath
File shortCutLocation = null;
File ApplicationShortcutPath;
String ApplicationShortcutPathName = idata.getVariable("ApplicationShortcutPath"/**
* TODO
* <-- Put in Docu and in Un/InstallerConstantsClass
*/
);
if (null != ApplicationShortcutPathName && !ApplicationShortcutPathName.equals(""))
{
ApplicationShortcutPath = new File(ApplicationShortcutPathName);
if (ApplicationShortcutPath.isAbsolute())
{
// I know :-) Can be m"ORed" elegant :)
if (!ApplicationShortcutPath.exists() && ApplicationShortcutPath.mkdirs()
&& ApplicationShortcutPath.canWrite())
shortCutLocation = ApplicationShortcutPath;
if (ApplicationShortcutPath.exists() && ApplicationShortcutPath.isDirectory()
&& ApplicationShortcutPath.canWrite())
shortCutLocation = ApplicationShortcutPath;
}
else
{
File relativePath = new File(idata.getInstallPath() + FS
+ ApplicationShortcutPath);
relativePath.mkdirs();
shortCutLocation = new File(relativePath.toString());
}
}
else
shortCutLocation = new File(idata.getInstallPath());
// write the App ShortCut
File writtenDesktopFile = writeAppShortcutWithOutSpace(shortCutLocation.toString(),
this.itsName, shortCutDef);
uninstaller.addFile(writtenDesktopFile.toString(), true);
// Now install my Own with xdg-if available // Note the The reverse Uninstall-Task is on
// TODO: "WHICH another place"
if (xdgDesktopIconCmd != null)
{
createExtXdgDesktopIconCmd(shortCutLocation);
// / TODO: TEST
myInstallScript.appendln(new String[] { myXdgDesktopIconCmd, "install",
"--novendor", StringTool.escapeSpaces(writtenDesktopFile.toString())});
ShellScript myUninstallScript = new ShellScript();
myUninstallScript.appendln(new String[] { myXdgDesktopIconCmd, "uninstall",
"--novendor", StringTool.escapeSpaces(writtenDesktopFile.toString())});
uninstaller.addUninstallScript(myUninstallScript.getContentAsString());
}
else
{
// otherwise copy to my desktop and add to uninstaller
File myDesktopFile;
do
{
myDesktopFile = new File(myHome + FS + "Desktop" + writtenDesktopFile.getName()
+ "-" + System.currentTimeMillis() + DESKTOP_EXT);
}
while (myDesktopFile.exists());
copyTo(writtenDesktopFile, myDesktopFile);
uninstaller.addFile(myDesktopFile.toString(), true);
}
// If I'm root and this Desktop.ShortCut should be for all other users
if (rootUser4All && create4All)
{
if (xdgDesktopIconCmd != null)
{
installDesktopFileToAllUsersDesktop(writtenDesktopFile);
}
else
// OLD ( Backward-Compatible/hardwired-"Desktop"-Foldername Styled Mechanic )
{
copyDesktopFileToAllUsersDesktop(writtenDesktopFile);
}
}
}
// This is - or should be only a Link in the [K?]-Menu
else
{
// the following is for backwards compatibility to older versions of KDE!
// on newer versions of KDE the icons will appear duplicated unless you set
// the category=""
// removed because of compatibility issues
/*
* Object categoryobject = props.getProperty($Categories); if(categoryobject != null &&
* ((String)categoryobject).length()>0) { File kdeHomeShareApplnk =
* getKdeShareApplnkFolder(this.getUserType()); target = kdeHomeShareApplnk.toString() +
* FS + this.itsGroupName + FS + this.itsName + DESKTOP_EXT; this.itsFileName = target;
* File kdemenufile = writeShortCut(target, shortCutDef);
*
* uninstaller.addFile(kdemenufile.toString(), true); }
*/
if (rootUser4All && create4All)
{
{
// write the icon pixmaps into /usr/share/pixmaps
File theIcon = new File(this.getIconLocation());
File commonIcon = new File("/usr/share/pixmaps/" + theIcon.getName());
try
{
copyTo(theIcon, commonIcon);
uninstaller.addFile(commonIcon.toString(), true);
}
catch (Exception cnc)
{
Debug.log("Could Not Copy: " + theIcon + " to " + commonIcon + "( "
+ cnc.getMessage() + " )");
}
// write *.desktop
this.itsFileName = target;
File writtenFile = writeAppShortcut("/usr/share/applications/", this.itsName,
shortCutDef);
setWrittenFileName(writtenFile.getName());
uninstaller.addFile(writtenFile.toString(), true);
}
}
else
// create local XDG shortcuts
{
// System.out.println("Creating gnome shortcut");
String localApps = myHome + "/.local/share/applications/";
String localPixmaps = myHome + "/.local/share/pixmaps/";
// System.out.println("Creating "+localApps);
try
{
java.io.File f = new java.io.File(localApps);
f.mkdirs();
f = new java.io.File(localPixmaps);
f.mkdirs();
}
catch (Exception ignore)
{
// System.out.println("Failed creating "+localApps + " or " + localPixmaps);
Debug.log("Failed creating " + localApps + " or " + localPixmaps);
}
// write the icon pixmaps into ~/share/pixmaps
File theIcon = new File(this.getIconLocation());
File commonIcon = new File(localPixmaps + theIcon.getName());
try
{
copyTo(theIcon, commonIcon);
uninstaller.addFile(commonIcon.toString(), true);
}
catch (Exception cnc)
{
Debug.log("Could Not Copy: " + theIcon + " to " + commonIcon + "( "
+ cnc.getMessage() + " )");
}
// write *.desktop in the local folder
this.itsFileName = target;
File writtenFile = writeAppShortcut(localApps, this.itsName, shortCutDef);
setWrittenFileName(writtenFile.getName());
uninstaller.addFile(writtenFile.toString(), true);
}
}
}
/**
* Ceates Extended Locale Enabled XdgDesktopIcon Command script.
* Fills the File myXdgDesktopIconScript with the content of
* com/izforge/izpack/util/os/unix/xdgscript.sh and uses this to
* creates User Desktop icons
*
* @param shortCutLocation in which folder should this stored.
* @throws IOException
* @throws ResourceNotFoundException
*/
public void createExtXdgDesktopIconCmd(File shortCutLocation) throws IOException,
ResourceNotFoundException
{
ShellScript myXdgDesktopIconScript = new ShellScript(null);
String lines = "";
ResourceManager m = ResourceManager.getInstance();
m.setDefaultOrResourceBasePath("");
lines = m.getTextResource("/com/izforge/izpack/util/os/unix/xdgdesktopiconscript.sh");
m.setDefaultOrResourceBasePath(null);
myXdgDesktopIconScript.append(lines);
myXdgDesktopIconCmd = new String(shortCutLocation + FS
+ "IzPackLocaleEnabledXdgDesktopIconScript.sh" );
myXdgDesktopIconScript.write(myXdgDesktopIconCmd);
FileExecutor.getExecOutput( new String [] { UnixHelper.getCustomCommand("chmod"),"+x", myXdgDesktopIconCmd },true );
}
/**
* Calls and creates the Install/Unistall Script which installs Desktop Icons using
* xdgDesktopIconCmd un-/install
*
* @param writtenDesktopFile An applications desktop file, which should be installed.
*/
private void installDesktopFileToAllUsersDesktop(File writtenDesktopFile)
{
for (Object user1 : users)
{
UnixUser user = ((UnixUser) user1);
if (user.getHome().equals(myHome))
{
Debug.log("need not to copy for itself: " + user.getHome() + "==" + myHome);
continue;
}
try
{
// / THE Following does such as #> su username -c "xdg-desktopicon install
// --novendor /Path/to/Filename\ with\ or\ without\ Space.desktop"
rootScript.append(new String[] { su, user.getName(), "-c" });
rootScript.appendln(new String[] { "\"" + myXdgDesktopIconCmd, "install", "--novendor",
StringTool.escapeSpaces(writtenDesktopFile.toString()) + "\"" });
uninstallScript.append(new String[] { su, user.getName(), "-c" });
uninstallScript
.appendln(new String[] { "\"" + myXdgDesktopIconCmd, "uninstall", "--novendor",
StringTool.escapeSpaces(writtenDesktopFile.toString()) + "\""});
}
catch (Exception e)
{
Debug.log(e.getMessage());
Debug.log(e.toString());
}
}
Debug.log("==============================");
Debug.log(rootScript.getContentAsString());
}
/**
* @param writtenDesktopFile
* @throws IOException
*/
private void copyDesktopFileToAllUsersDesktop(File writtenDesktopFile) throws IOException
{
String chmod = UnixHelper.getCustomCommand("chmod");
String chown = UnixHelper.getCustomCommand("chown");
String rm = UnixHelper.getRmCommand();
String copy = UnixHelper.getCpCommand();
File dest = null;
// Create a tempFileName of this ShortCut
File tempFile = File.createTempFile(this.getClass().getName(), Long.toString(System
.currentTimeMillis())
+ ".tmp");
copyTo(writtenDesktopFile, tempFile);
// Debug.log("Wrote Tempfile: " + tempFile.toString());
FileExecutor.getExecOutput(new String[] { chmod, "uga+rwx", tempFile.toString()});
// su marc.eppelmann -c "/bin/cp /home/marc.eppelmann/backup.job.out.txt
// /home/marc.eppelmann/backup.job.out2.txt"
for (Object user1 : users)
{
UnixUser user = ((UnixUser) user1);
if (user.getHome().equals(myHome))
{
Debug.log("need not to copy for itself: " + user.getHome() + "==" + myHome);
continue;
}
try
{
// aHomePath = userHomesList[idx];
dest = new File(user.getHome() + FS + "Desktop" + FS + writtenDesktopFile.getName());
//
// I'm root and cannot write into Users Home as root;
// But I'm Root and I can slip in every users skin :-)
//
// by# su username
//
// This works as well
// su $username -c "cp /tmp/desktopfile $HOME/Desktop/link.desktop"
// chown $username $HOME/Desktop/link.desktop
// Debug.log("Will Copy: " + tempFile.toString() + " to " + dest.toString());
rootScript.append(su);
rootScript.append(S);
rootScript.append(user.getName());
rootScript.append(S);
rootScript.append("-c");
rootScript.append(S);
rootScript.append('"');
rootScript.append(copy);
rootScript.append(S);
rootScript.append(tempFile.toString());
rootScript.append(S);
rootScript.append(StringTool.replace(dest.toString(), " ", "\\ "));
rootScript.appendln('"');
rootScript.append('\n');
// Debug.log("Will exec: " + script.toString());
rootScript.append(chown);
rootScript.append(S);
rootScript.append(user.getName());
rootScript.append(S);
rootScript.appendln(StringTool.replace(dest.toString(), " ", "\\ "));
rootScript.append('\n');
rootScript.append('\n');
// Debug.log("Will exec: " + script.toString());
uninstallScript.append(su);
uninstallScript.append(S);
uninstallScript.append(user.getName());
uninstallScript.append(S);
uninstallScript.append("-c");
uninstallScript.append(S);
uninstallScript.append('"');
uninstallScript.append(rm);
uninstallScript.append(S);
uninstallScript.append(StringTool.replace(dest.toString(), " ", "\\ "));
uninstallScript.appendln('"');
uninstallScript.appendln();
// Debug.log("Uninstall will exec: " + uninstallScript.toString());
}
catch (Exception rex)
{
System.out.println("Error while su Copy: " + rex.getLocalizedMessage() + "\n\n");
rex.printStackTrace();
/* ignore */
// most distros does not allow root to access any user
// home (ls -la /home/user drwx------)
// But try it anyway...
}
}
rootScript.append(rm);
rootScript.append(S);
rootScript.appendln(tempFile.toString());
rootScript.appendln();
}
/**
* Post Exec Action especially for the Unix Root User. which executes the Root ShortCut
* Shellscript. to copy all ShellScripts to the users Desktop.
*/
public void execPostAction()
{
Debug.log("Call of Impl. execPostAction Method in " + this.getClass().getName());
String pseudoUnique = this.getClass().getName() + Long.toString(System.currentTimeMillis());
String scriptFilename = null;
try
{
scriptFilename = File.createTempFile(pseudoUnique, ".sh").toString();
}
catch (IOException e)
{
scriptFilename = System.getProperty("java.io.tmpdir", "/tmp") + "/" + pseudoUnique
+ ".sh";
e.printStackTrace();
}
rootScript.write(scriptFilename);
rootScript.exec();
Debug.log(rootScript);
// Quick an dirty copy & paste code - will be cleanup in one of 4.1.1++
pseudoUnique = this.getClass().getName() + Long.toString(System.currentTimeMillis());
try
{
scriptFilename = File.createTempFile(pseudoUnique, ".sh").toString();
}
catch (IOException e)
{
scriptFilename = System.getProperty("java.io.tmpdir", "/tmp") + "/" + pseudoUnique
+ ".sh";
e.printStackTrace();
}
myInstallScript.write(scriptFilename);
myInstallScript.exec();
Debug.log(myInstallScript);
// End OF Quick AND Dirty
Debug.log(uninstallScript);
uninstaller.addUninstallScript(uninstallScript.getContentAsString());
}
/**
* Copies the inFile file to outFile using cbuff as buffer.
*
* @param inFile The File to read from.
* @param outFile The targetFile to write to.
* @throws IOException If an IO Error occurs
*/
public static void copyTo(File inFile, File outFile) throws IOException
{
char[] cbuff = new char[32768];
BufferedReader reader = new BufferedReader(new FileReader(inFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
int readedBytes = 0;
long absWrittenBytes = 0;
while ((readedBytes = reader.read(cbuff, 0, cbuff.length)) != -1)
{
writer.write(cbuff, 0, readedBytes);
absWrittenBytes += readedBytes;
}
reader.close();
writer.close();
}
private String writtenFileName;
public String getWrittenFileName()
{
return writtenFileName;
}
protected void setWrittenFileName(String s)
{
writtenFileName = s;
}
/**
* Write the given ShortDefinition in a File $ShortcutName-$timestamp.desktop in the given
* TargetPath.
*
* @param targetPath The Path in which the files should be written.
* @param shortcutName The Name for the File
* @param shortcutDef The Shortcut FileContent
*
* @return The written File
*/
private File writeAppShortcut(String targetPath, String shortcutName, String shortcutDef)
{
return writeAppShortcutWithSimpleSpacehandling(targetPath, shortcutName, shortcutDef, false);
}
/**
* Write the given ShortDefinition in a File $ShortcutName-$timestamp.desktop in the given
* TargetPath. ALSO all WhiteSpaces in the ShortCutName will be repalced with "-"
*
* @param targetPath The Path in which the files should be written.
* @param shortcutName The Name for the File
* @param shortcutDef The Shortcut FileContent
*
* @return The written File
*/
private File writeAppShortcutWithOutSpace(String targetPath, String shortcutName,
String shortcutDef)
{
return writeAppShortcutWithSimpleSpacehandling(targetPath, shortcutName, shortcutDef, true);
}
/**
* Write the given ShortDefinition in a File $ShortcutName-$timestamp.desktop in the given
* TargetPath. If the given replaceSpaces was true ALSO all WhiteSpaces in the ShortCutName will
* be replaced with "-"
*
* @param targetPath The Path in which the files should be written.
* @param shortcutName The Name for the File
* @param shortcutDef The Shortcut FileContent
* @param replaceSpaces Replaces Spaces in the Filename if true was given
* @return The written File
*/
private File writeAppShortcutWithSimpleSpacehandling(String targetPath, String shortcutName,
String shortcutDef, boolean replaceSpacesWithMinus)
{
if (!(targetPath.endsWith("/") || targetPath.endsWith("\\")))
{
targetPath += File.separatorChar;
}
File shortcutFile;
do
{
shortcutFile = new File(targetPath
+ (replaceSpacesWithMinus == true ? StringTool
.replaceSpacesWithMinus(shortcutName) : shortcutName) + "-"
+ System.currentTimeMillis() + DESKTOP_EXT);
}
while (shortcutFile.exists());
FileWriter fileWriter = null;
try
{
fileWriter = new FileWriter(shortcutFile);
}
catch (IOException e1)
{
System.out.println(e1.getMessage());
}
try
{
fileWriter.write(shortcutDef);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
fileWriter.close();
}
catch (IOException e2)
{
e2.printStackTrace();
}
return shortcutFile;
}
/**
* Writes the given Shortcutdefinition to the given Target. Returns the written File.
*
* @param target
* @param shortCutDef
* @return the File of the written shortcut.
*/
private File writeShortCut(String target, String shortCutDef)
{
File targetPath = new File(target.substring(0, target.lastIndexOf(File.separatorChar)));
if (!targetPath.exists())
{
targetPath.mkdirs();
this.createdDirectory = targetPath.toString();
}
File targetFileName = new File(target);
File backupFile = new File(targetPath + File.separator + "." + targetFileName.getName()
+ System.currentTimeMillis());
if (targetFileName.exists())
{
try
{
// create a hidden backup.file of the existing shortcut with a timestamp name.
copyTo(targetFileName, backupFile); // + System.e );
targetFileName.delete();
}
catch (IOException e3)
{
System.out.println("cannot create backup file " + backupFile + " of "
+ targetFileName); // e3.printStackTrace();
}
}
FileWriter fileWriter = null;
try
{
fileWriter = new FileWriter(targetFileName);
}
catch (IOException e1)
{
System.out.println(e1.getMessage());
}
try
{
fileWriter.write(shortCutDef);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
fileWriter.close();
}
catch (IOException e2)
{
e2.printStackTrace();
}
return targetFileName;
}
/**
* Set the Commandline Arguments
*
* @see com.izforge.izpack.util.os.Shortcut#setArguments(java.lang.String)
*/
public void setArguments(String args)
{
props.put($Arguments, args);
}
/**
* Sets the Description
*
* @see com.izforge.izpack.util.os.Shortcut#setDescription(java.lang.String)
*/
public void setDescription(String description)
{
props.put($Comment, description);
}
/**
* Sets The Icon Path
*
* @see com.izforge.izpack.util.os.Shortcut#setIconLocation(java.lang.String, int)
*/
public void setIconLocation(String path, int index)
{
props.put($Icon, path);
}
/**
* Sets the Name of this Shortcut
*
* @see com.izforge.izpack.util.os.Shortcut#setLinkName(java.lang.String)
*/
public void setLinkName(String aName)
{
this.itsName = aName;
props.put($Name, aName);
}
/**
* Sets the type of this Shortcut
*
* @see com.izforge.izpack.util.os.Shortcut#setLinkType(int)
*/
public void setLinkType(int aType) throws IllegalArgumentException,
UnsupportedEncodingException
{
ShortcutType = aType;
}
/**
* Sets the ProgramGroup
*
* @see com.izforge.izpack.util.os.Shortcut#setProgramGroup(java.lang.String)
*/
public void setProgramGroup(String aGroupName)
{
this.itsGroupName = aGroupName;
}
/**
* Sets the ShowMode
*
* @see com.izforge.izpack.util.os.Shortcut#setShowCommand(int)
*/
public void setShowCommand(int show)
{
}
/**
* Sets The TargetPath
*
* @see com.izforge.izpack.util.os.Shortcut#setTargetPath(java.lang.String)
*/
public void setTargetPath(String aPath)
{
StringTokenizer whiteSpaceTester = new StringTokenizer(aPath);
if (whiteSpaceTester.countTokens() > 1)
{
props.put($E_QUOT, QM);
}
props.put($Exec, aPath);
}
/**
* Sets the usertype.
*
* @see com.izforge.izpack.util.os.Shortcut#setUserType(int)
*/
public void setUserType(int aUserType)
{
this.itsUserType = aUserType;
}
/**
* Sets the working-directory
*
* @see com.izforge.izpack.util.os.Shortcut#setWorkingDirectory(java.lang.String)
*/
public void setWorkingDirectory(String aDirectory)
{
StringTokenizer whiteSpaceTester = new StringTokenizer(aDirectory);
if (whiteSpaceTester.countTokens() > 1)
{
props.put($P_QUOT, QM);
}
props.put($Path, aDirectory);
}
/**
* Dumps the Name to console.
*
* @see java.lang.Object#toString()
*/
public String toString()
{
return this.itsName + N + template;
}
/**
* Creates the Shortcut String which will be stored as File.
*
* @return contents of the shortcut file
*/
public String replace()
{
String result = template;
Enumeration enumeration = props.keys();
while (enumeration.hasMoreElements())
{
String key = (String) enumeration.nextElement();
result = StringTool.replace(result, key, props.getProperty(key));
}
return result;
}
/**
* Test Method
*
* @param args
* @throws IOException
* @throws ResourceNotFoundException
*/
public static void main(String[] args) throws IOException, ResourceNotFoundException
{
Unix_Shortcut aSample = new Unix_Shortcut();
System.out.println(">>" + aSample.getClass().getName() + "- Test Main Program\n\n");
try
{
aSample.initialize(APPLICATIONS, "Start Tomcat");
}
catch (Exception exc)
{
System.err.println("Could not init Unix_Shourtcut");
}
aSample.replace();
System.out.println(aSample);
//
//
//
// File targetFileName = new File(System.getProperty("user.home") + File.separator
// + "Start Tomcat" + DESKTOP_EXT);
// FileWriter fileWriter = null;
//
// try
// {
// fileWriter = new FileWriter(targetFileName);
// }
// catch (IOException e1)
// {
// e1.printStackTrace();
// }
//
// try
// {
// fileWriter.write( aSample.toString() );
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
//
// try
// {
// fileWriter.close();
// }
// catch (IOException e2)
// {
// e2.printStackTrace();
// }
aSample.createExtXdgDesktopIconCmd(new File(System.getProperty("user.home")));
System.out.println("DONE.\n");
}
/**
* Sets The Encoding
*
* @see com.izforge.izpack.util.os.Shortcut#setEncoding(java.lang.String)
*/
public void setEncoding(String aEncoding)
{
props.put($Encoding, aEncoding);
}
/**
* Sets The KDE Specific subst UID property
*
* @see com.izforge.izpack.util.os.Shortcut#setKdeSubstUID(java.lang.String)
*/
public void setKdeSubstUID(String trueFalseOrNothing)
{
props.put($X_KDE_SubstituteUID, trueFalseOrNothing);
}
/**
* Sets The KDE Specific subst UID property
*
* @see com.izforge.izpack.util.os.Shortcut#setKdeSubstUID(java.lang.String)
*/
public void setKdeUserName(String aUserName)
{
props.put($X_KDE_Username, aUserName);
}
/**
* Sets the MimeType
*
* @see com.izforge.izpack.util.os.Shortcut#setMimetype(java.lang.String)
*/
public void setMimetype(String aMimetype)
{
props.put($MimeType, aMimetype);
}
/**
* Sets the terminal
*
* @see com.izforge.izpack.util.os.Shortcut#setTerminal(java.lang.String)
*/
public void setTerminal(String trueFalseOrNothing)
{
props.put($Terminal, trueFalseOrNothing);
}
/**
* Sets the terminal options
*
* @see com.izforge.izpack.util.os.Shortcut#setTerminalOptions(java.lang.String)
*/
public void setTerminalOptions(String someTerminalOptions)
{
props.put($Options_For_Terminal, someTerminalOptions);
}
/**
* Sets the Shortcut type (one of Application, Link or Device)
*
* @see com.izforge.izpack.util.os.Shortcut#setType(java.lang.String)
*/
public void setType(String aType)
{
props.put($Type, aType);
}
/**
* Sets the Url for type Link. Can be also a apsolute file/path
*
* @see com.izforge.izpack.util.os.Shortcut#setURL(java.lang.String)
*/
public void setURL(String anUrl)
{
props.put($URL, anUrl);
}
/**
* Gets the Usertype of the Shortcut.
*
* @see com.izforge.izpack.util.os.Shortcut#getUserType()
*/
public int getUserType()
{
return itsUserType;
}
/**
* Sets the Categories Field
*
* @param theCategories the categories
*/
public void setCategories(String theCategories)
{
props.put($Categories, theCategories);
}
/**
* Sets the TryExecField.
*
* @param aTryExec the try exec command
*/
public void setTryExec(String aTryExec)
{
props.put($TryExec, aTryExec);
}
public int getLinkType()
{
return ShortcutType;
// return Shortcut.DESKTOP;
}
}
| src/lib/com/izforge/izpack/util/os/Unix_Shortcut.java | /*
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://www.izforge.com/izpack/
* http://izpack.codehaus.org/
*
* Copyright 2003 Marc Eppelmann
*
* 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.
*/
/*
* This represents a Implementation of the KDE/GNOME DesktopEntry.
* which is standard from
* "Desktop Entry Standard"
* "The format of .desktop files, supported by KDE and GNOME."
* http://www.freedesktop.org/standards/desktop-entry-spec/
*
* [Desktop Entry]
// Comment=$Comment
// Comment[de]=
// Encoding=$UTF-8
// Exec=$'/home/marc/CPS/tomcat/bin/catalina.sh' run
// GenericName=$
// GenericName[de]=$
// Icon=$inetd
// MimeType=$
// Name=$Start Tomcat
// Name[de]=$Start Tomcat
// Path=$/home/marc/CPS/tomcat/bin/
// ServiceTypes=$
// SwallowExec=$
// SwallowTitle=$
// Terminal=$true
// TerminalOptions=$
// Type=$Application
// X-KDE-SubstituteUID=$false
// X-KDE-Username=$
*
*/
package com.izforge.izpack.util.os;
import com.izforge.izpack.installer.AutomatedInstallData;
import com.izforge.izpack.installer.InstallData;
import com.izforge.izpack.installer.ResourceManager;
import com.izforge.izpack.installer.ResourceNotFoundException;
import com.izforge.izpack.util.Debug;
import com.izforge.izpack.util.FileExecutor;
import com.izforge.izpack.util.OsVersion;
import com.izforge.izpack.util.StringTool;
import com.izforge.izpack.util.os.unix.ShellScript;
import com.izforge.izpack.util.os.unix.UnixHelper;
import com.izforge.izpack.util.os.unix.UnixUser;
import com.izforge.izpack.util.os.unix.UnixUsers;
import com.sun.corba.se.impl.orbutil.closure.Constant;
import java.io.*;
import java.util.*;
/**
* This is the Implementation of the RFC-Based Desktop-Link. Used in KDE and GNOME.
*
* @author marc.eppelmann@reddot.de
*/
public class Unix_Shortcut extends Shortcut implements Unix_ShortcutConstants
{
// ~ Static fields/initializers
// *******************************************************************************************************************************
/**
* version = "$Id$"
*/
private static String version = "$Id$";
/**
* rev = "$Revision$"
*/
private static String rev = "$Revision$";
/**
* DESKTOP_EXT = ".desktop"
*/
private static String DESKTOP_EXT = ".desktop";
/**
* template = ""
*/
private static String template = "";
/**
* N = "\n"
*/
private final static String N = "\n";
/**
* H = "#"
*/
private final static String H = "#";
/**
* S = " "
*/
private final static String S = " ";
/**
* C = Comment = H+S = "# "
*/
private final static String C = H + S;
/**
* QM = "\"" : <b>Q</b>uotation<b>M</b>ark
*/
private final static String QM = "\"";
private int ShortcutType;
private static ShellScript rootScript = null;
private static ShellScript uninstallScript = null;
private static ArrayList users = UnixUsers.getUsersWithValidShellsExistingHomesAndDesktops();
// private static ArrayList tempfiles = new ArrayList();
// ~ Instance fields
// ******************************************************************************************************************************************
/**
* internal String createdDirectory
*/
private String createdDirectory;
/**
* internal int itsUserType
*/
private int itsUserType;
/**
* internal String itsGroupName
*/
private String itsGroupName;
/**
* internal String itsName
*/
private String itsName;
/**
* internal String itsFileName
*/
private String itsFileName;
/**
* internal String itsApplnkFolder = "applnk"
*/
private String itsApplnkFolder = "applnk";
/**
* internal Properties Set
*/
private Properties props;
/**
* forAll = new Boolean(false): A flag to indicate that this should created for all users.
*/
private Boolean forAll = Boolean.FALSE;
/**
* Internal Help Buffer
*/
public StringBuffer hlp;
/** my Install ShellScript **/
public ShellScript myInstallScript;
/** Internal Constant: FS = File.separator // **/
public final String FS = File.separator;
/** Internal Constant: myHome = System.getProperty("user.home") **/
public final String myHome = System.getProperty("user.home");
/** Internal Constant: su = UnixHelper.getSuCommand() **/
public final String su = UnixHelper.getSuCommand();
/** Internal Constant: xdgDesktopIconCmd = UnixHelper.getCustomCommand("xdg-desktop-icon") **/
public final String xdgDesktopIconCmd = UnixHelper.getCustomCommand("xdg-desktop-icon");
public String myXdgDesktopIconScript;
public String myXdgDesktopIconCmd;
// ~ Constructors ***********************************************************************
// ~ Constructors
// *********************************************************************************************************************************************
/**
* Creates a new Unix_Shortcut object.
*/
public Unix_Shortcut()
{
hlp = new StringBuffer();
String userLanguage = System.getProperty("user.language", "en");
hlp.append("[Desktop Entry]" + N);
// TODO implement Attribute: X-KDE-StartupNotify=true
hlp.append("Categories=" + $Categories + N);
hlp.append("Comment=" + $Comment + N);
hlp.append("Comment[").append(userLanguage).append("]=" + $Comment + N);
hlp.append("Encoding=" + $Encoding + N);
// this causes too many problems
// hlp.append("TryExec=" + $E_QUOT + $Exec + $E_QUOT + S + $Arguments + N);
hlp.append("Exec=" + $E_QUOT + $Exec + $E_QUOT + S + $Arguments + N);
hlp.append("GenericName=" + $GenericName + N);
hlp.append("GenericName[").append(userLanguage).append("]=" + $GenericName + N);
hlp.append("Icon=" + $Icon + N);
hlp.append("MimeType=" + $MimeType + N);
hlp.append("Name=" + $Name + N);
hlp.append("Name[").append(userLanguage).append("]=" + $Name + N);
hlp.append("Path=" + $P_QUOT + $Path + $P_QUOT + N);
hlp.append("ServiceTypes=" + $ServiceTypes + N);
hlp.append("SwallowExec=" + $SwallowExec + N);
hlp.append("SwallowTitle=" + $SwallowTitle + N);
hlp.append("Terminal=" + $Terminal + N);
hlp.append("TerminalOptions=" + $Options_For_Terminal + N);
hlp.append("Type=" + $Type + N);
hlp.append("URL=" + $URL + N);
hlp.append("X-KDE-SubstituteUID=" + $X_KDE_SubstituteUID + N);
hlp.append("X-KDE-Username=" + $X_KDE_Username + N);
hlp.append(N);
hlp.append(C + "created by" + S).append(getClass().getName()).append(S).append(rev).append(
N);
hlp.append(C).append(version);
template = hlp.toString();
props = new Properties();
initProps();
if (rootScript == null)
{
rootScript = new ShellScript();
}
if (uninstallScript == null)
{
uninstallScript = new ShellScript();
}
if (myInstallScript == null)
{
myInstallScript = new ShellScript();
}
}
// ~ Methods ****************************************************************************
// ~ Methods
// **************************************************************************************************************************************************
/**
* This initialisizes all Properties Values with "".
*/
private void initProps()
{
String[] propsArray = { $Comment, $$LANG_Comment, $Encoding, $Exec, $Arguments,
$GenericName, $$LANG_GenericName, $MimeType, $Name, $$LANG_Name, $Path,
$ServiceTypes, $SwallowExec, $SwallowTitle, $Terminal, $Options_For_Terminal,
$Type, $X_KDE_SubstituteUID, $X_KDE_Username, $Icon, $URL, $E_QUOT, $P_QUOT,
$Categories, $TryExec};
for (String aPropsArray : propsArray)
{
props.put(aPropsArray, "");
}
}
/**
* Overridden Method
*
* @see com.izforge.izpack.util.os.Shortcut#initialize(int, java.lang.String)
*/
public void initialize(int aType, String aName) throws Exception
{
this.itsName = aName;
props.put($Name, aName);
}
/**
* This indicates that Unix will be supported.
*
* @see com.izforge.izpack.util.os.Shortcut#supported()
*/
public boolean supported()
{
return true;
}
/**
* Dummy
*
* @see com.izforge.izpack.util.os.Shortcut#getDirectoryCreated()
*/
public String getDirectoryCreated()
{
return this.createdDirectory; // while not stored...
}
/**
* Dummy
*
* @see com.izforge.izpack.util.os.Shortcut#getFileName()
*/
public String getFileName()
{
return (this.itsFileName);
}
/**
* Overridden compatibility method. Returns all directories in $USER/.kde/share/applink.
*
* @see com.izforge.izpack.util.os.Shortcut#getProgramGroups(int)
*/
public Vector<String> getProgramGroups(int userType)
{
Vector<String> groups = new Vector<String>();
File kdeShareApplnk = getKdeShareApplnkFolder(userType);
try
{
File[] listing = kdeShareApplnk.listFiles();
for (File aListing : listing)
{
if (aListing.isDirectory())
{
groups.add(aListing.getName());
}
}
}
catch (Exception e)
{
// ignore and return an empty vector.
}
return (groups);
}
/**
* Gets the Programsfolder for the given User (non-Javadoc).
*
* @see com.izforge.izpack.util.os.Shortcut#getProgramsFolder(int)
*/
public String getProgramsFolder(int current_user)
{
String result = "";
//
result = getKdeShareApplnkFolder(current_user).toString();
return result;
}
/**
* Gets the XDG path to place the menu shortcuts
*
* @param userType to get for.
* @return handle to the directory
*/
private File getKdeShareApplnkFolder(int userType)
{
if (userType == Shortcut.ALL_USERS)
{
return new File(File.separator + "usr" + File.separator + "share" + File.separator
+ "applications");
}
else
{
return new File(System.getProperty("user.home") + File.separator + ".local"
+ File.separator + "share" + File.separator + "applications");
}
}
/**
* Gets the name of the applink folder for the currently used distribution. Currently
* "applnk-redhat for RedHat, "applnk-mdk" for Mandrake, and simply "applnk" for all others.
*
* @return result
*/
private String getKdeApplinkFolderName()
{
String applinkFolderName = "applnk";
if (OsVersion.IS_REDHAT_LINUX)
{
applinkFolderName = "applnk-redhat";
}
if (OsVersion.IS_MANDRAKE_LINUX)
{
applinkFolderName = "applnk-mdk";
}
return applinkFolderName;
}
/**
* Gets the KDEBasedir for the given User.
*
* @param userType one of root or regular user
* @return the basedir
*/
private File getKdeBase(int userType)
{
File result = null;
if (userType == Shortcut.ALL_USERS)
{
FileExecutor fe = new FileExecutor();
String[] execOut = new String[2];
int execResult = fe.executeCommand(new String[] { "/usr/bin/env", "kde-config",
"--prefix"}, execOut);
result = new File(execOut[0].trim());
}
else
{
result = new File(System.getProperty("user.home") + File.separator + ".kde");
}
return result;
}
/**
* overridden method
*
* @return true
* @see com.izforge.izpack.util.os.Shortcut#multipleUsers()
*/
public boolean multipleUsers()
{
// EVER true for UNIXes ;-)
return (true);
}
/**
* Creates and stores the shortcut-files.
*
* @see com.izforge.izpack.util.os.Shortcut#save()
*/
public void save() throws Exception
{
String target = null;
String shortCutDef = this.replace();
boolean rootUser4All = this.getUserType() == Shortcut.ALL_USERS;
boolean create4All = this.getCreateForAll();
// Create The Desktop Shortcuts
if ("".equals(this.itsGroupName) && (this.getLinkType() == Shortcut.DESKTOP))
{
this.itsFileName = target;
AutomatedInstallData idata;
idata = AutomatedInstallData.getInstance();
// read the userdefined / overridden / wished Shortcut Location
// This can be an absolute Path name or a relative Path to the InstallPath
File shortCutLocation = null;
File ApplicationShortcutPath;
String ApplicationShortcutPathName = idata.getVariable("ApplicationShortcutPath"/**
* TODO
* <-- Put in Docu and in Un/InstallerConstantsClass
*/
);
if (null != ApplicationShortcutPathName && !ApplicationShortcutPathName.equals(""))
{
ApplicationShortcutPath = new File(ApplicationShortcutPathName);
if (ApplicationShortcutPath.isAbsolute())
{
// I know :-) Can be m"ORed" elegant :)
if (!ApplicationShortcutPath.exists() && ApplicationShortcutPath.mkdirs()
&& ApplicationShortcutPath.canWrite())
shortCutLocation = ApplicationShortcutPath;
if (ApplicationShortcutPath.exists() && ApplicationShortcutPath.isDirectory()
&& ApplicationShortcutPath.canWrite())
shortCutLocation = ApplicationShortcutPath;
}
else
{
File relativePath = new File(idata.getInstallPath() + FS
+ ApplicationShortcutPath);
relativePath.mkdirs();
shortCutLocation = new File(relativePath.toString());
}
}
else
shortCutLocation = new File(idata.getInstallPath());
// write the App ShortCut
File writtenDesktopFile = writeAppShortcutWithOutSpace(shortCutLocation.toString(),
this.itsName, shortCutDef);
uninstaller.addFile(writtenDesktopFile.toString(), true);
// Now install my Own with xdg-if available // Note the The reverse Uninstall-Task is on
// TODO: "WHICH another place"
if (xdgDesktopIconCmd != null)
{
createExtXdgDesktopIconCmd(shortCutLocation);
// / TODO: TEST
myInstallScript.appendln(new String[] { myXdgDesktopIconCmd, "install",
"--novendor", StringTool.escapeSpaces(writtenDesktopFile.toString())});
ShellScript myUninstallScript = new ShellScript();
myUninstallScript.appendln(new String[] { myXdgDesktopIconCmd, "uninstall",
"--novendor", StringTool.escapeSpaces(writtenDesktopFile.toString())});
uninstaller.addUninstallScript(myUninstallScript.getContentAsString());
}
else
{
// otherwise copy to my desktop and add to uninstaller
File myDesktopFile;
do
{
myDesktopFile = new File(myHome + FS + "Desktop" + writtenDesktopFile.getName()
+ "-" + System.currentTimeMillis() + DESKTOP_EXT);
}
while (myDesktopFile.exists());
copyTo(writtenDesktopFile, myDesktopFile);
uninstaller.addFile(myDesktopFile.toString(), true);
}
// If I'm root and this Desktop.ShortCut should be for all other users
if (rootUser4All && create4All)
{
if (xdgDesktopIconCmd != null)
{
installDesktopFileToAllUsersDesktop(writtenDesktopFile);
}
else
// OLD ( Backward-Compatible/hardwired-"Desktop"-Foldername Styled Mechanic )
{
copyDesktopFileToAllUsersDesktop(writtenDesktopFile);
}
}
}
// This is - or should be only a Link in the [K?]-Menu
else
{
// the following is for backwards compatibility to older versions of KDE!
// on newer versions of KDE the icons will appear duplicated unless you set
// the category=""
// removed because of compatibility issues
/*
* Object categoryobject = props.getProperty($Categories); if(categoryobject != null &&
* ((String)categoryobject).length()>0) { File kdeHomeShareApplnk =
* getKdeShareApplnkFolder(this.getUserType()); target = kdeHomeShareApplnk.toString() +
* FS + this.itsGroupName + FS + this.itsName + DESKTOP_EXT; this.itsFileName = target;
* File kdemenufile = writeShortCut(target, shortCutDef);
*
* uninstaller.addFile(kdemenufile.toString(), true); }
*/
if (rootUser4All && create4All)
{
{
// write the icon pixmaps into /usr/share/pixmaps
File theIcon = new File(this.getIconLocation());
File commonIcon = new File("/usr/share/pixmaps/" + theIcon.getName());
try
{
copyTo(theIcon, commonIcon);
uninstaller.addFile(commonIcon.toString(), true);
}
catch (Exception cnc)
{
Debug.log("Could Not Copy: " + theIcon + " to " + commonIcon + "( "
+ cnc.getMessage() + " )");
}
// write *.desktop
this.itsFileName = target;
File writtenFile = writeAppShortcut("/usr/share/applications/", this.itsName,
shortCutDef);
setWrittenFileName(writtenFile.getName());
uninstaller.addFile(writtenFile.toString(), true);
}
}
else
// create local XDG shortcuts
{
// System.out.println("Creating gnome shortcut");
String localApps = myHome + "/.local/share/applications/";
String localPixmaps = myHome + "/.local/share/pixmaps/";
// System.out.println("Creating "+localApps);
try
{
java.io.File f = new java.io.File(localApps);
f.mkdirs();
f = new java.io.File(localPixmaps);
f.mkdirs();
}
catch (Exception ignore)
{
// System.out.println("Failed creating "+localApps + " or " + localPixmaps);
Debug.log("Failed creating " + localApps + " or " + localPixmaps);
}
// write the icon pixmaps into ~/share/pixmaps
File theIcon = new File(this.getIconLocation());
File commonIcon = new File(localPixmaps + theIcon.getName());
try
{
copyTo(theIcon, commonIcon);
uninstaller.addFile(commonIcon.toString(), true);
}
catch (Exception cnc)
{
Debug.log("Could Not Copy: " + theIcon + " to " + commonIcon + "( "
+ cnc.getMessage() + " )");
}
// write *.desktop in the local folder
this.itsFileName = target;
File writtenFile = writeAppShortcut(localApps, this.itsName, shortCutDef);
setWrittenFileName(writtenFile.getName());
uninstaller.addFile(writtenFile.toString(), true);
}
}
}
/**
* Ceates Extended Locale Enabled XdgDesktopIcon Command script.
* Fills the File myXdgDesktopIconScript with the content of
* com/izforge/izpack/util/os/unix/xdgscript.sh and uses this to
* creates User Desktop icons
*
* @param shortCutLocation in which folder should this stored.
* @throws IOException
* @throws ResourceNotFoundException
*/
public void createExtXdgDesktopIconCmd(File shortCutLocation) throws IOException,
ResourceNotFoundException
{
ShellScript myXdgDesktopIconScript = new ShellScript(null);
String lines = "";
ResourceManager m = ResourceManager.getInstance();
m.setDefaultOrResourceBasePath("");
lines = m.getTextResource("/com/izforge/izpack/util/os/unix/xdgdesktopiconscript.sh");
m.setDefaultOrResourceBasePath(null);
myXdgDesktopIconScript.append(lines);
myXdgDesktopIconCmd = new String(shortCutLocation + FS
+ "IzPackLocaleEnabledXdgDesktopIconScript.sh" );
myXdgDesktopIconScript.write(myXdgDesktopIconCmd);
FileExecutor.getExecOutput( new String [] { UnixHelper.getCustomCommand("chmod"),"+x", myXdgDesktopIconCmd },true );
}
/**
* Calls and creates the Install/Unistall Script which installs Desktop Icons using
* xdgDesktopIconCmd un-/install
*
* @param writtenDesktopFile An applications desktop file, which should be installed.
*/
private void installDesktopFileToAllUsersDesktop(File writtenDesktopFile)
{
for (Object user1 : users)
{
UnixUser user = ((UnixUser) user1);
if (user.getHome().equals(myHome))
{
Debug.log("need not to copy for itself: " + user.getHome() + "==" + myHome);
continue;
}
try
{
// / THE Following does such as #> su username -c "xdg-desktopicon install
// --novendor /Path/to/Filename\ with\ or\ without\ Space.desktop"
rootScript.append(new String[] { su, user.getName(), "-c", "\""});
rootScript.appendln(new String[] { myXdgDesktopIconCmd, "install", "--novendor",
StringTool.escapeSpaces(writtenDesktopFile.toString()), "\""});
uninstallScript.append(new String[] { su, user.getName(), "-c", "\""});
uninstallScript
.appendln(new String[] { myXdgDesktopIconCmd, "uninstall", "--novendor",
StringTool.escapeSpaces(writtenDesktopFile.toString()), "\""});
}
catch (Exception e)
{
Debug.log(e.getMessage());
Debug.log(e.toString());
}
}
}
/**
* @param writtenDesktopFile
* @throws IOException
*/
private void copyDesktopFileToAllUsersDesktop(File writtenDesktopFile) throws IOException
{
String chmod = UnixHelper.getCustomCommand("chmod");
String chown = UnixHelper.getCustomCommand("chown");
String rm = UnixHelper.getRmCommand();
String copy = UnixHelper.getCpCommand();
File dest = null;
// Create a tempFileName of this ShortCut
File tempFile = File.createTempFile(this.getClass().getName(), Long.toString(System
.currentTimeMillis())
+ ".tmp");
copyTo(writtenDesktopFile, tempFile);
// Debug.log("Wrote Tempfile: " + tempFile.toString());
FileExecutor.getExecOutput(new String[] { chmod, "uga+rwx", tempFile.toString()});
// su marc.eppelmann -c "/bin/cp /home/marc.eppelmann/backup.job.out.txt
// /home/marc.eppelmann/backup.job.out2.txt"
for (Object user1 : users)
{
UnixUser user = ((UnixUser) user1);
if (user.getHome().equals(myHome))
{
Debug.log("need not to copy for itself: " + user.getHome() + "==" + myHome);
continue;
}
try
{
// aHomePath = userHomesList[idx];
dest = new File(user.getHome() + FS + "Desktop" + FS + writtenDesktopFile.getName());
//
// I'm root and cannot write into Users Home as root;
// But I'm Root and I can slip in every users skin :-)
//
// by# su username
//
// This works as well
// su $username -c "cp /tmp/desktopfile $HOME/Desktop/link.desktop"
// chown $username $HOME/Desktop/link.desktop
// Debug.log("Will Copy: " + tempFile.toString() + " to " + dest.toString());
rootScript.append(su);
rootScript.append(S);
rootScript.append(user.getName());
rootScript.append(S);
rootScript.append("-c");
rootScript.append(S);
rootScript.append('"');
rootScript.append(copy);
rootScript.append(S);
rootScript.append(tempFile.toString());
rootScript.append(S);
rootScript.append(StringTool.replace(dest.toString(), " ", "\\ "));
rootScript.appendln('"');
rootScript.append('\n');
// Debug.log("Will exec: " + script.toString());
rootScript.append(chown);
rootScript.append(S);
rootScript.append(user.getName());
rootScript.append(S);
rootScript.appendln(StringTool.replace(dest.toString(), " ", "\\ "));
rootScript.append('\n');
rootScript.append('\n');
// Debug.log("Will exec: " + script.toString());
uninstallScript.append(su);
uninstallScript.append(S);
uninstallScript.append(user.getName());
uninstallScript.append(S);
uninstallScript.append("-c");
uninstallScript.append(S);
uninstallScript.append('"');
uninstallScript.append(rm);
uninstallScript.append(S);
uninstallScript.append(StringTool.replace(dest.toString(), " ", "\\ "));
uninstallScript.appendln('"');
uninstallScript.appendln();
// Debug.log("Uninstall will exec: " + uninstallScript.toString());
}
catch (Exception rex)
{
System.out.println("Error while su Copy: " + rex.getLocalizedMessage() + "\n\n");
rex.printStackTrace();
/* ignore */
// most distros does not allow root to access any user
// home (ls -la /home/user drwx------)
// But try it anyway...
}
}
rootScript.append(rm);
rootScript.append(S);
rootScript.appendln(tempFile.toString());
rootScript.appendln();
}
/**
* Post Exec Action especially for the Unix Root User. which executes the Root ShortCut
* Shellscript. to copy all ShellScripts to the users Desktop.
*/
public void execPostAction()
{
Debug.log("Call of Impl. execPostAction Method in " + this.getClass().getName());
String pseudoUnique = this.getClass().getName() + Long.toString(System.currentTimeMillis());
String scriptFilename = null;
try
{
scriptFilename = File.createTempFile(pseudoUnique, ".sh").toString();
}
catch (IOException e)
{
scriptFilename = System.getProperty("java.io.tmpdir", "/tmp") + "/" + pseudoUnique
+ ".sh";
e.printStackTrace();
}
rootScript.write(scriptFilename);
rootScript.exec();
Debug.log(rootScript);
// Quick an dirty copy & paste code - will be cleanup in one of 4.1.1++
pseudoUnique = this.getClass().getName() + Long.toString(System.currentTimeMillis());
try
{
scriptFilename = File.createTempFile(pseudoUnique, ".sh").toString();
}
catch (IOException e)
{
scriptFilename = System.getProperty("java.io.tmpdir", "/tmp") + "/" + pseudoUnique
+ ".sh";
e.printStackTrace();
}
myInstallScript.write(scriptFilename);
myInstallScript.exec();
Debug.log(myInstallScript);
// End OF Quick AND Dirty
Debug.log(uninstallScript);
uninstaller.addUninstallScript(uninstallScript.getContentAsString());
}
/**
* Copies the inFile file to outFile using cbuff as buffer.
*
* @param inFile The File to read from.
* @param outFile The targetFile to write to.
* @throws IOException If an IO Error occurs
*/
public static void copyTo(File inFile, File outFile) throws IOException
{
char[] cbuff = new char[32768];
BufferedReader reader = new BufferedReader(new FileReader(inFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
int readedBytes = 0;
long absWrittenBytes = 0;
while ((readedBytes = reader.read(cbuff, 0, cbuff.length)) != -1)
{
writer.write(cbuff, 0, readedBytes);
absWrittenBytes += readedBytes;
}
reader.close();
writer.close();
}
private String writtenFileName;
public String getWrittenFileName()
{
return writtenFileName;
}
protected void setWrittenFileName(String s)
{
writtenFileName = s;
}
/**
* Write the given ShortDefinition in a File $ShortcutName-$timestamp.desktop in the given
* TargetPath.
*
* @param targetPath The Path in which the files should be written.
* @param shortcutName The Name for the File
* @param shortcutDef The Shortcut FileContent
*
* @return The written File
*/
private File writeAppShortcut(String targetPath, String shortcutName, String shortcutDef)
{
return writeAppShortcutWithSimpleSpacehandling(targetPath, shortcutName, shortcutDef, false);
}
/**
* Write the given ShortDefinition in a File $ShortcutName-$timestamp.desktop in the given
* TargetPath. ALSO all WhiteSpaces in the ShortCutName will be repalced with "-"
*
* @param targetPath The Path in which the files should be written.
* @param shortcutName The Name for the File
* @param shortcutDef The Shortcut FileContent
*
* @return The written File
*/
private File writeAppShortcutWithOutSpace(String targetPath, String shortcutName,
String shortcutDef)
{
return writeAppShortcutWithSimpleSpacehandling(targetPath, shortcutName, shortcutDef, true);
}
/**
* Write the given ShortDefinition in a File $ShortcutName-$timestamp.desktop in the given
* TargetPath. If the given replaceSpaces was true ALSO all WhiteSpaces in the ShortCutName will
* be replaced with "-"
*
* @param targetPath The Path in which the files should be written.
* @param shortcutName The Name for the File
* @param shortcutDef The Shortcut FileContent
* @param replaceSpaces Replaces Spaces in the Filename if true was given
* @return The written File
*/
private File writeAppShortcutWithSimpleSpacehandling(String targetPath, String shortcutName,
String shortcutDef, boolean replaceSpacesWithMinus)
{
if (!(targetPath.endsWith("/") || targetPath.endsWith("\\")))
{
targetPath += File.separatorChar;
}
File shortcutFile;
do
{
shortcutFile = new File(targetPath
+ (replaceSpacesWithMinus == true ? StringTool
.replaceSpacesWithMinus(shortcutName) : shortcutName) + "-"
+ System.currentTimeMillis() + DESKTOP_EXT);
}
while (shortcutFile.exists());
FileWriter fileWriter = null;
try
{
fileWriter = new FileWriter(shortcutFile);
}
catch (IOException e1)
{
System.out.println(e1.getMessage());
}
try
{
fileWriter.write(shortcutDef);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
fileWriter.close();
}
catch (IOException e2)
{
e2.printStackTrace();
}
return shortcutFile;
}
/**
* Writes the given Shortcutdefinition to the given Target. Returns the written File.
*
* @param target
* @param shortCutDef
* @return the File of the written shortcut.
*/
private File writeShortCut(String target, String shortCutDef)
{
File targetPath = new File(target.substring(0, target.lastIndexOf(File.separatorChar)));
if (!targetPath.exists())
{
targetPath.mkdirs();
this.createdDirectory = targetPath.toString();
}
File targetFileName = new File(target);
File backupFile = new File(targetPath + File.separator + "." + targetFileName.getName()
+ System.currentTimeMillis());
if (targetFileName.exists())
{
try
{
// create a hidden backup.file of the existing shortcut with a timestamp name.
copyTo(targetFileName, backupFile); // + System.e );
targetFileName.delete();
}
catch (IOException e3)
{
System.out.println("cannot create backup file " + backupFile + " of "
+ targetFileName); // e3.printStackTrace();
}
}
FileWriter fileWriter = null;
try
{
fileWriter = new FileWriter(targetFileName);
}
catch (IOException e1)
{
System.out.println(e1.getMessage());
}
try
{
fileWriter.write(shortCutDef);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
fileWriter.close();
}
catch (IOException e2)
{
e2.printStackTrace();
}
return targetFileName;
}
/**
* Set the Commandline Arguments
*
* @see com.izforge.izpack.util.os.Shortcut#setArguments(java.lang.String)
*/
public void setArguments(String args)
{
props.put($Arguments, args);
}
/**
* Sets the Description
*
* @see com.izforge.izpack.util.os.Shortcut#setDescription(java.lang.String)
*/
public void setDescription(String description)
{
props.put($Comment, description);
}
/**
* Sets The Icon Path
*
* @see com.izforge.izpack.util.os.Shortcut#setIconLocation(java.lang.String, int)
*/
public void setIconLocation(String path, int index)
{
props.put($Icon, path);
}
/**
* Sets the Name of this Shortcut
*
* @see com.izforge.izpack.util.os.Shortcut#setLinkName(java.lang.String)
*/
public void setLinkName(String aName)
{
this.itsName = aName;
props.put($Name, aName);
}
/**
* Sets the type of this Shortcut
*
* @see com.izforge.izpack.util.os.Shortcut#setLinkType(int)
*/
public void setLinkType(int aType) throws IllegalArgumentException,
UnsupportedEncodingException
{
ShortcutType = aType;
}
/**
* Sets the ProgramGroup
*
* @see com.izforge.izpack.util.os.Shortcut#setProgramGroup(java.lang.String)
*/
public void setProgramGroup(String aGroupName)
{
this.itsGroupName = aGroupName;
}
/**
* Sets the ShowMode
*
* @see com.izforge.izpack.util.os.Shortcut#setShowCommand(int)
*/
public void setShowCommand(int show)
{
}
/**
* Sets The TargetPath
*
* @see com.izforge.izpack.util.os.Shortcut#setTargetPath(java.lang.String)
*/
public void setTargetPath(String aPath)
{
StringTokenizer whiteSpaceTester = new StringTokenizer(aPath);
if (whiteSpaceTester.countTokens() > 1)
{
props.put($E_QUOT, QM);
}
props.put($Exec, aPath);
}
/**
* Sets the usertype.
*
* @see com.izforge.izpack.util.os.Shortcut#setUserType(int)
*/
public void setUserType(int aUserType)
{
this.itsUserType = aUserType;
}
/**
* Sets the working-directory
*
* @see com.izforge.izpack.util.os.Shortcut#setWorkingDirectory(java.lang.String)
*/
public void setWorkingDirectory(String aDirectory)
{
StringTokenizer whiteSpaceTester = new StringTokenizer(aDirectory);
if (whiteSpaceTester.countTokens() > 1)
{
props.put($P_QUOT, QM);
}
props.put($Path, aDirectory);
}
/**
* Dumps the Name to console.
*
* @see java.lang.Object#toString()
*/
public String toString()
{
return this.itsName + N + template;
}
/**
* Creates the Shortcut String which will be stored as File.
*
* @return contents of the shortcut file
*/
public String replace()
{
String result = template;
Enumeration enumeration = props.keys();
while (enumeration.hasMoreElements())
{
String key = (String) enumeration.nextElement();
result = StringTool.replace(result, key, props.getProperty(key));
}
return result;
}
/**
* Test Method
*
* @param args
* @throws IOException
* @throws ResourceNotFoundException
*/
public static void main(String[] args) throws IOException, ResourceNotFoundException
{
Unix_Shortcut aSample = new Unix_Shortcut();
System.out.println(">>" + aSample.getClass().getName() + "- Test Main Program\n\n");
try
{
aSample.initialize(APPLICATIONS, "Start Tomcat");
}
catch (Exception exc)
{
System.err.println("Could not init Unix_Shourtcut");
}
aSample.replace();
System.out.println(aSample);
//
//
//
// File targetFileName = new File(System.getProperty("user.home") + File.separator
// + "Start Tomcat" + DESKTOP_EXT);
// FileWriter fileWriter = null;
//
// try
// {
// fileWriter = new FileWriter(targetFileName);
// }
// catch (IOException e1)
// {
// e1.printStackTrace();
// }
//
// try
// {
// fileWriter.write( aSample.toString() );
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
//
// try
// {
// fileWriter.close();
// }
// catch (IOException e2)
// {
// e2.printStackTrace();
// }
aSample.createExtXdgDesktopIconCmd(new File(System.getProperty("user.home")));
System.out.println("DONE.\n");
}
/**
* Sets The Encoding
*
* @see com.izforge.izpack.util.os.Shortcut#setEncoding(java.lang.String)
*/
public void setEncoding(String aEncoding)
{
props.put($Encoding, aEncoding);
}
/**
* Sets The KDE Specific subst UID property
*
* @see com.izforge.izpack.util.os.Shortcut#setKdeSubstUID(java.lang.String)
*/
public void setKdeSubstUID(String trueFalseOrNothing)
{
props.put($X_KDE_SubstituteUID, trueFalseOrNothing);
}
/**
* Sets The KDE Specific subst UID property
*
* @see com.izforge.izpack.util.os.Shortcut#setKdeSubstUID(java.lang.String)
*/
public void setKdeUserName(String aUserName)
{
props.put($X_KDE_Username, aUserName);
}
/**
* Sets the MimeType
*
* @see com.izforge.izpack.util.os.Shortcut#setMimetype(java.lang.String)
*/
public void setMimetype(String aMimetype)
{
props.put($MimeType, aMimetype);
}
/**
* Sets the terminal
*
* @see com.izforge.izpack.util.os.Shortcut#setTerminal(java.lang.String)
*/
public void setTerminal(String trueFalseOrNothing)
{
props.put($Terminal, trueFalseOrNothing);
}
/**
* Sets the terminal options
*
* @see com.izforge.izpack.util.os.Shortcut#setTerminalOptions(java.lang.String)
*/
public void setTerminalOptions(String someTerminalOptions)
{
props.put($Options_For_Terminal, someTerminalOptions);
}
/**
* Sets the Shortcut type (one of Application, Link or Device)
*
* @see com.izforge.izpack.util.os.Shortcut#setType(java.lang.String)
*/
public void setType(String aType)
{
props.put($Type, aType);
}
/**
* Sets the Url for type Link. Can be also a apsolute file/path
*
* @see com.izforge.izpack.util.os.Shortcut#setURL(java.lang.String)
*/
public void setURL(String anUrl)
{
props.put($URL, anUrl);
}
/**
* Gets the Usertype of the Shortcut.
*
* @see com.izforge.izpack.util.os.Shortcut#getUserType()
*/
public int getUserType()
{
return itsUserType;
}
/**
* Sets the Categories Field
*
* @param theCategories the categories
*/
public void setCategories(String theCategories)
{
props.put($Categories, theCategories);
}
/**
* Sets the TryExecField.
*
* @param aTryExec the try exec command
*/
public void setTryExec(String aTryExec)
{
props.put($TryExec, aTryExec);
}
public int getLinkType()
{
return ShortcutType;
// return Shortcut.DESKTOP;
}
}
| IZPACK-201 Shortcut creation on non-english Linux (Ubuntu 8.10)
Removed unnneded space
git-svn-id: 408af81b9e4f0a5eaad229a6d9eed76d614c4af6@2440 7d736ef5-cfd4-0310-9c9a-b52d5c14b761
| src/lib/com/izforge/izpack/util/os/Unix_Shortcut.java | IZPACK-201 Shortcut creation on non-english Linux (Ubuntu 8.10) Removed unnneded space | <ide><path>rc/lib/com/izforge/izpack/util/os/Unix_Shortcut.java
<ide> {
<ide> // / THE Following does such as #> su username -c "xdg-desktopicon install
<ide> // --novendor /Path/to/Filename\ with\ or\ without\ Space.desktop"
<del> rootScript.append(new String[] { su, user.getName(), "-c", "\""});
<del> rootScript.appendln(new String[] { myXdgDesktopIconCmd, "install", "--novendor",
<del> StringTool.escapeSpaces(writtenDesktopFile.toString()), "\""});
<del>
<del> uninstallScript.append(new String[] { su, user.getName(), "-c", "\""});
<add> rootScript.append(new String[] { su, user.getName(), "-c" });
<add> rootScript.appendln(new String[] { "\"" + myXdgDesktopIconCmd, "install", "--novendor",
<add> StringTool.escapeSpaces(writtenDesktopFile.toString()) + "\"" });
<add>
<add> uninstallScript.append(new String[] { su, user.getName(), "-c" });
<ide> uninstallScript
<del> .appendln(new String[] { myXdgDesktopIconCmd, "uninstall", "--novendor",
<del> StringTool.escapeSpaces(writtenDesktopFile.toString()), "\""});
<add> .appendln(new String[] { "\"" + myXdgDesktopIconCmd, "uninstall", "--novendor",
<add> StringTool.escapeSpaces(writtenDesktopFile.toString()) + "\""});
<ide> }
<ide> catch (Exception e)
<ide> {
<ide> Debug.log(e.toString());
<ide> }
<ide> }
<add> Debug.log("==============================");
<add> Debug.log(rootScript.getContentAsString());
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | af2e36dc4e53b258fc89ce5696b60e9d967396dc | 0 | google/closure-compiler,google/closure-compiler,monetate/closure-compiler,google/closure-compiler,monetate/closure-compiler,monetate/closure-compiler,monetate/closure-compiler,google/closure-compiler | /*
* Copyright 2021 The Closure Compiler 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.javascript.jscomp;
import com.google.javascript.rhino.Node;
/** GWT compatible no-op replacement for {@code LocaleDataPasses} */
final class LocaleDataPasses {
private LocaleDataPasses() {}
static class ProtectGoogLocale implements CompilerPass {
ProtectGoogLocale(AbstractCompiler compiler) {}
@Override
public void process(Node externs, Node root) {}
}
static class LocaleSubstitutions implements CompilerPass {
LocaleSubstitutions(AbstractCompiler compiler, String locale) {}
public void process(Node externs, Node root) {}
}
}
| src/com/google/javascript/jscomp/j2clbuild/super/com/google/javascript/jscomp/LocaleDataPasses.java | /*
* Copyright 2021 The Closure Compiler 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.javascript.jscomp;
import com.google.javascript.rhino.Node;
// ** GWT compatible no-op replacement for {@code LocaleDataPasses} */
final class LocaleDataPasses {
private LocaleDataPasses() {}
static class ProtectGoogLocale implements CompilerPass {
ProtectGoogLocale(AbstractCompiler compiler) {}
@Override
public void process(Node externs, Node root) {}
}
static class LocaleSubstitutions implements CompilerPass {
LocaleSubstitutions(AbstractCompiler compiler, String locale) {}
public void process(Node externs, Node root) {}
}
}
| Internal change
PiperOrigin-RevId: 481947290
| src/com/google/javascript/jscomp/j2clbuild/super/com/google/javascript/jscomp/LocaleDataPasses.java | Internal change | <ide><path>rc/com/google/javascript/jscomp/j2clbuild/super/com/google/javascript/jscomp/LocaleDataPasses.java
<ide>
<ide> import com.google.javascript.rhino.Node;
<ide>
<del>// ** GWT compatible no-op replacement for {@code LocaleDataPasses} */
<add>/** GWT compatible no-op replacement for {@code LocaleDataPasses} */
<ide> final class LocaleDataPasses {
<ide>
<ide> private LocaleDataPasses() {} |
|
Java | apache-2.0 | 227b40fc27e5cfbe02b8e55296000c3da49662f7 | 0 | MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim | package reb2sac;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.prefs.Preferences;
import javax.swing.*;
import parser.*;
import lhpn2sbml.gui.LHPNEditor;
import lhpn2sbml.parser.Abstraction;
import lhpn2sbml.parser.LhpnFile;
import lhpn2sbml.parser.Translator;
import biomodelsim.*;
import gcm2sbml.gui.GCM2SBMLEditor;
import gcm2sbml.parser.GCMFile;
import graph.*;
import buttons.*;
import sbmleditor.*;
import stategraph.BuildStateGraphThread;
import stategraph.PerfromMarkovAnalysisThread;
import stategraph.StateGraph;
import verification.AbstPane;
/**
* This class creates the properties file that is given to the reb2sac program.
* It also executes the reb2sac program.
*
* @author Curtis Madsen
*/
public class Run implements ActionListener {
private Process reb2sac;
private String separator;
private Reb2Sac r2s;
StateGraph sg;
public Run(Reb2Sac reb2sac) {
r2s = reb2sac;
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
}
/**
* This method is given which buttons are selected and creates the
* properties file from all the other information given.
*
* @param useInterval
*
* @param stem
*/
public void createProperties(double timeLimit, String useInterval, double printInterval,
double minTimeStep, double timeStep, double absError, String outDir, long rndSeed,
int run, String[] termCond, String[] intSpecies, String printer_id,
String printer_track_quantity, String[] getFilename, String selectedButtons,
Component component, String filename, double rap1, double rap2, double qss, int con,
JCheckBox usingSSA, String ssaFile, JCheckBox usingSad, File sadFile, JList preAbs,
JList loopAbs, JList postAbs, AbstPane abstPane) {
Properties abs = new Properties();
if (selectedButtons.contains("abs") || selectedButtons.contains("nary")) {
for (int i = 0; i < preAbs.getModel().getSize(); i++) {
abs.setProperty("reb2sac.abstraction.method.1." + (i + 1), (String) preAbs
.getModel().getElementAt(i));
}
for (int i = 0; i < loopAbs.getModel().getSize(); i++) {
abs.setProperty("reb2sac.abstraction.method.2." + (i + 1), (String) loopAbs
.getModel().getElementAt(i));
}
// abs.setProperty("reb2sac.abstraction.method.0.1",
// "enzyme-kinetic-qssa-1");
// abs.setProperty("reb2sac.abstraction.method.0.2",
// "reversible-to-irreversible-transformer");
// abs.setProperty("reb2sac.abstraction.method.0.3",
// "multiple-products-reaction-eliminator");
// abs.setProperty("reb2sac.abstraction.method.0.4",
// "multiple-reactants-reaction-eliminator");
// abs.setProperty("reb2sac.abstraction.method.0.5",
// "single-reactant-product-reaction-eliminator");
// abs.setProperty("reb2sac.abstraction.method.0.6",
// "dimer-to-monomer-substitutor");
// abs.setProperty("reb2sac.abstraction.method.0.7",
// "inducer-structure-transformer");
// abs.setProperty("reb2sac.abstraction.method.1.1",
// "modifier-structure-transformer");
// abs.setProperty("reb2sac.abstraction.method.1.2",
// "modifier-constant-propagation");
// abs.setProperty("reb2sac.abstraction.method.2.1",
// "operator-site-forward-binding-remover");
// abs.setProperty("reb2sac.abstraction.method.2.3",
// "enzyme-kinetic-rapid-equilibrium-1");
// abs.setProperty("reb2sac.abstraction.method.2.4",
// "irrelevant-species-remover");
// abs.setProperty("reb2sac.abstraction.method.2.5",
// "inducer-structure-transformer");
// abs.setProperty("reb2sac.abstraction.method.2.6",
// "modifier-constant-propagation");
// abs.setProperty("reb2sac.abstraction.method.2.7",
// "similar-reaction-combiner");
// abs.setProperty("reb2sac.abstraction.method.2.8",
// "modifier-constant-propagation");
}
// if (selectedButtons.contains("abs")) {
// abs.setProperty("reb2sac.abstraction.method.2.2",
// "dimerization-reduction");
// }
// else if (selectedButtons.contains("nary")) {
// abs.setProperty("reb2sac.abstraction.method.2.2",
// "dimerization-reduction-level-assignment");
// }
for (int i = 0; i < postAbs.getModel().getSize(); i++) {
abs.setProperty("reb2sac.abstraction.method.3." + (i + 1), (String) postAbs.getModel()
.getElementAt(i));
}
abs.setProperty("simulation.printer", printer_id);
abs.setProperty("simulation.printer.tracking.quantity", printer_track_quantity);
// if (selectedButtons.contains("monteCarlo")) {
// abs.setProperty("reb2sac.abstraction.method.3.1",
// "distribute-transformer");
// abs.setProperty("reb2sac.abstraction.method.3.2",
// "reversible-to-irreversible-transformer");
// abs.setProperty("reb2sac.abstraction.method.3.3",
// "kinetic-law-constants-simplifier");
// }
// else if (selectedButtons.contains("none")) {
// abs.setProperty("reb2sac.abstraction.method.3.1",
// "kinetic-law-constants-simplifier");
// }
for (int i = 0; i < intSpecies.length; i++) {
if (!intSpecies[i].equals("")) {
String[] split = intSpecies[i].split(" ");
abs.setProperty("reb2sac.interesting.species." + (i + 1), split[0]);
if (split.length > 1) {
String[] levels = split[1].split(",");
for (int j = 0; j < levels.length; j++) {
abs.setProperty("reb2sac.concentration.level." + split[0] + "." + (j + 1),
levels[j]);
}
}
}
}
abs.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1);
abs.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2);
abs.setProperty("reb2sac.qssa.condition.1", "" + qss);
abs.setProperty("reb2sac.operator.max.concentration.threshold", "" + con);
if (selectedButtons.contains("none")) {
abs.setProperty("reb2sac.abstraction.method", "none");
}
if (selectedButtons.contains("abs")) {
abs.setProperty("reb2sac.abstraction.method", "abs");
}
else if (selectedButtons.contains("nary")) {
abs.setProperty("reb2sac.abstraction.method", "nary");
}
if (abstPane != null) {
String intVars = "";
for (int i = 0; i < abstPane.listModel.getSize(); i++) {
if (abstPane.listModel.getElementAt(i) != null) {
intVars = intVars + abstPane.listModel.getElementAt(i) + " ";
}
}
if (!intVars.equals("")) {
abs.setProperty("abstraction.interesting", intVars.trim());
}
else {
abs.remove("abstraction.interesting");
}
String xforms = "";
for (int i = 0; i < abstPane.absListModel.getSize(); i++) {
if (abstPane.absListModel.getElementAt(i) != null) {
xforms = xforms + abstPane.absListModel.getElementAt(i) + ", ";
}
}
if (!xforms.equals("")) {
abs.setProperty("abstraction.transforms", xforms.trim());
}
else {
abs.remove("abstraction.transforms");
}
if (!abstPane.factorField.getText().equals("")) {
abs.setProperty("abstraction.factor", abstPane.factorField.getText());
}
if (!abstPane.iterField.getText().equals("")) {
abs.setProperty("abstraction.iterations", abstPane.iterField.getText());
}
}
if (selectedButtons.contains("ODE")) {
abs.setProperty("reb2sac.simulation.method", "ODE");
}
else if (selectedButtons.contains("monteCarlo")) {
abs.setProperty("reb2sac.simulation.method", "monteCarlo");
}
else if (selectedButtons.contains("markov")) {
abs.setProperty("reb2sac.simulation.method", "markov");
}
else if (selectedButtons.contains("sbml")) {
abs.setProperty("reb2sac.simulation.method", "SBML");
}
else if (selectedButtons.contains("dot")) {
abs.setProperty("reb2sac.simulation.method", "Network");
}
else if (selectedButtons.contains("xhtml")) {
abs.setProperty("reb2sac.simulation.method", "Browser");
}
else if (selectedButtons.contains("lhpn")) {
abs.setProperty("reb2sac.simulation.method", "LPN");
}
if (!selectedButtons.contains("monteCarlo")) {
// if (selectedButtons.equals("none_ODE") ||
// selectedButtons.equals("abs_ODE")) {
abs.setProperty("ode.simulation.time.limit", "" + timeLimit);
if (useInterval.equals("Print Interval")) {
abs.setProperty("ode.simulation.print.interval", "" + printInterval);
}
else if (useInterval.equals("Minimum Print Interval")) {
abs.setProperty("ode.simulation.minimum.print.interval", "" + printInterval);
}
else {
abs.setProperty("ode.simulation.number.steps", "" + ((int) printInterval));
}
if (timeStep == Double.MAX_VALUE) {
abs.setProperty("ode.simulation.time.step", "inf");
}
else {
abs.setProperty("ode.simulation.time.step", "" + timeStep);
}
abs.setProperty("ode.simulation.min.time.step", "" + minTimeStep);
abs.setProperty("ode.simulation.absolute.error", "" + absError);
abs.setProperty("ode.simulation.out.dir", outDir);
abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed);
abs.setProperty("monte.carlo.simulation.runs", "" + run);
}
if (!selectedButtons.contains("ODE")) {
// if (selectedButtons.equals("none_monteCarlo") ||
// selectedButtons.equals("abs_monteCarlo")) {
abs.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit);
if (useInterval.equals("Print Interval")) {
abs.setProperty("monte.carlo.simulation.print.interval", "" + printInterval);
}
else if (useInterval.equals("Minimum Print Interval")) {
abs
.setProperty("monte.carlo.simulation.minimum.print.interval", ""
+ printInterval);
}
else {
abs.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval));
}
if (timeStep == Double.MAX_VALUE) {
abs.setProperty("monte.carlo.simulation.time.step", "inf");
}
else {
abs.setProperty("monte.carlo.simulation.time.step", "" + timeStep);
}
abs.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep);
abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed);
abs.setProperty("monte.carlo.simulation.runs", "" + run);
abs.setProperty("monte.carlo.simulation.out.dir", outDir);
if (usingSad.isSelected()) {
abs.setProperty("simulation.run.termination.decider", "sad");
abs.setProperty("computation.analysis.sad.path", sadFile.getName());
}
}
if (!usingSad.isSelected()) {
abs.setProperty("simulation.run.termination.decider", "constraint");
}
if (usingSSA.isSelected() && selectedButtons.contains("monteCarlo")) {
abs.setProperty("simulation.time.series.species.level.file", ssaFile);
}
for (int i = 0; i < termCond.length; i++) {
if (termCond[i] != "") {
abs
.setProperty("simulation.run.termination.condition." + (i + 1), ""
+ termCond[i]);
}
}
try {
if (!getFilename[getFilename.length - 1].contains(".")) {
getFilename[getFilename.length - 1] += ".";
filename += ".";
}
int cut = 0;
for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) {
if (getFilename[getFilename.length - 1].charAt(i) == '.') {
cut = i;
}
}
FileOutputStream store = new FileOutputStream(new File((filename.substring(0, filename
.length()
- getFilename[getFilename.length - 1].length()))
+ getFilename[getFilename.length - 1].substring(0, cut) + ".properties"));
abs.store(store, getFilename[getFilename.length - 1].substring(0, cut) + " Properties");
store.close();
}
catch (Exception except) {
JOptionPane.showMessageDialog(component, "Unable To Save Properties File!"
+ "\nMake sure you select a model for abstraction.", "Unable To Save File",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* This method is given what data is entered into the nary frame and creates
* the nary properties file from that information.
*/
public void createNaryProperties(double timeLimit, String useInterval, double printInterval,
double minTimeStep, double timeStep, String outDir, long rndSeed, int run,
String printer_id, String printer_track_quantity, String[] getFilename,
Component component, String filename, JRadioButton monteCarlo, String stopE,
double stopR, String[] finalS, ArrayList<JTextField> inhib, ArrayList<JList> consLevel,
ArrayList<String> getSpeciesProps, ArrayList<Object[]> conLevel, String[] termCond,
String[] intSpecies, double rap1, double rap2, double qss, int con,
ArrayList<Integer> counts, JCheckBox usingSSA, String ssaFile) {
Properties nary = new Properties();
try {
FileInputStream load = new FileInputStream(new File(outDir + separator
+ "species.properties"));
nary.load(load);
load.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(component, "Species Properties File Not Found!",
"File Not Found", JOptionPane.ERROR_MESSAGE);
}
nary.setProperty("reb2sac.abstraction.method.0.1", "enzyme-kinetic-qssa-1");
nary
.setProperty("reb2sac.abstraction.method.0.2",
"reversible-to-irreversible-transformer");
nary.setProperty("reb2sac.abstraction.method.0.3", "multiple-products-reaction-eliminator");
nary
.setProperty("reb2sac.abstraction.method.0.4",
"multiple-reactants-reaction-eliminator");
nary.setProperty("reb2sac.abstraction.method.0.5",
"single-reactant-product-reaction-eliminator");
nary.setProperty("reb2sac.abstraction.method.0.6", "dimer-to-monomer-substitutor");
nary.setProperty("reb2sac.abstraction.method.0.7", "inducer-structure-transformer");
nary.setProperty("reb2sac.abstraction.method.1.1", "modifier-structure-transformer");
nary.setProperty("reb2sac.abstraction.method.1.2", "modifier-constant-propagation");
nary.setProperty("reb2sac.abstraction.method.2.1", "operator-site-forward-binding-remover");
nary.setProperty("reb2sac.abstraction.method.2.3", "enzyme-kinetic-rapid-equilibrium-1");
nary.setProperty("reb2sac.abstraction.method.2.4", "irrelevant-species-remover");
nary.setProperty("reb2sac.abstraction.method.2.5", "inducer-structure-transformer");
nary.setProperty("reb2sac.abstraction.method.2.6", "modifier-constant-propagation");
nary.setProperty("reb2sac.abstraction.method.2.7", "similar-reaction-combiner");
nary.setProperty("reb2sac.abstraction.method.2.8", "modifier-constant-propagation");
nary.setProperty("reb2sac.abstraction.method.2.2", "dimerization-reduction");
nary.setProperty("reb2sac.abstraction.method.3.1", "nary-order-unary-transformer");
nary.setProperty("reb2sac.abstraction.method.3.2", "modifier-constant-propagation");
nary.setProperty("reb2sac.abstraction.method.3.3", "absolute-inhibition-generator");
nary.setProperty("reb2sac.abstraction.method.3.4", "final-state-generator");
nary.setProperty("reb2sac.abstraction.method.3.5", "stop-flag-generator");
nary.setProperty("reb2sac.nary.order.decider", "distinct");
nary.setProperty("simulation.printer", printer_id);
nary.setProperty("simulation.printer.tracking.quantity", printer_track_quantity);
nary.setProperty("reb2sac.analysis.stop.enabled", stopE);
nary.setProperty("reb2sac.analysis.stop.rate", "" + stopR);
for (int i = 0; i < getSpeciesProps.size(); i++) {
if (!(inhib.get(i).getText().trim() != "<<none>>")) {
nary.setProperty("reb2sac.absolute.inhibition.threshold." + getSpeciesProps.get(i),
inhib.get(i).getText().trim());
}
String[] consLevels = Buttons.getList(conLevel.get(i), consLevel.get(i));
for (int j = 0; j < counts.get(i); j++) {
nary
.remove("reb2sac.concentration.level." + getSpeciesProps.get(i) + "."
+ (j + 1));
}
for (int j = 0; j < consLevels.length; j++) {
nary.setProperty("reb2sac.concentration.level." + getSpeciesProps.get(i) + "."
+ (j + 1), consLevels[j]);
}
}
if (monteCarlo.isSelected()) {
nary.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit);
if (useInterval.equals("Print Interval")) {
nary.setProperty("monte.carlo.simulation.print.interval", "" + printInterval);
}
else if (useInterval.equals("Minimum Print Interval")) {
nary.setProperty("monte.carlo.simulation.minimum.print.interval", ""
+ printInterval);
}
else {
nary.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval));
}
if (timeStep == Double.MAX_VALUE) {
nary.setProperty("monte.carlo.simulation.time.step", "inf");
}
else {
nary.setProperty("monte.carlo.simulation.time.step", "" + timeStep);
}
nary.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep);
nary.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed);
nary.setProperty("monte.carlo.simulation.runs", "" + run);
nary.setProperty("monte.carlo.simulation.out.dir", ".");
}
for (int i = 0; i < finalS.length; i++) {
if (finalS[i].trim() != "<<unknown>>") {
nary.setProperty("reb2sac.final.state." + (i + 1), "" + finalS[i]);
}
}
if (usingSSA.isSelected() && monteCarlo.isSelected()) {
nary.setProperty("simulation.time.series.species.level.file", ssaFile);
}
for (int i = 0; i < intSpecies.length; i++) {
if (intSpecies[i] != "") {
nary.setProperty("reb2sac.interesting.species." + (i + 1), "" + intSpecies[i]);
}
}
nary.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1);
nary.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2);
nary.setProperty("reb2sac.qssa.condition.1", "" + qss);
nary.setProperty("reb2sac.operator.max.concentration.threshold", "" + con);
for (int i = 0; i < termCond.length; i++) {
if (termCond[i] != "") {
nary.setProperty("simulation.run.termination.condition." + (i + 1), ""
+ termCond[i]);
}
}
try {
FileOutputStream store = new FileOutputStream(new File((filename.substring(0, filename
.length()
- getFilename[getFilename.length - 1].length()))
+ getFilename[getFilename.length - 1].substring(0,
getFilename[getFilename.length - 1].length() - 5) + ".properties"));
nary.store(store, getFilename[getFilename.length - 1].substring(0,
getFilename[getFilename.length - 1].length() - 5)
+ " Properties");
store.close();
}
catch (Exception except) {
JOptionPane.showMessageDialog(component, "Unable To Save Properties File!"
+ "\nMake sure you select a model for simulation.", "Unable To Save File",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Executes the reb2sac program. If ODE, monte carlo, or markov is selected,
* this method creates a Graph object.
*
* @param runTime
*/
public int execute(String filename, JRadioButton sbml, JRadioButton dot, JRadioButton xhtml,
JRadioButton lhpn, Component component, JRadioButton ode, JRadioButton monteCarlo,
String sim, String printer_id, String printer_track_quantity, String outDir,
JRadioButton nary, int naryRun, String[] intSpecies, Log log, JCheckBox usingSSA,
String ssaFile, BioSim biomodelsim, JTabbedPane simTab, String root,
JProgressBar progress, String simName, GCM2SBMLEditor gcmEditor, String direct,
double timeLimit, double runTime, String modelFile, AbstPane abstPane,
JRadioButton abstraction, String lpnProperty) {
Runtime exec = Runtime.getRuntime();
int exitValue = 255;
while (outDir.split(separator)[outDir.split(separator).length - 1].equals(".")) {
outDir = outDir.substring(0, outDir.length() - 1
- outDir.split(separator)[outDir.split(separator).length - 1].length());
}
try {
long time1;
String directory = "";
String theFile = "";
String sbmlName = "";
String lhpnName = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
String out = theFile;
if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) {
out = out.substring(0, out.length() - 5);
}
else if (out.length() > 3
&& out.substring(out.length() - 4, out.length()).equals(".xml")) {
out = out.substring(0, out.length() - 4);
}
if (nary.isSelected() && gcmEditor != null
&& (monteCarlo.isSelected() || xhtml.isSelected())) {
String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "").replace(".xml",
"")
+ ".lpn";
ArrayList<String> specs = new ArrayList<String>();
ArrayList<Object[]> conLevel = new ArrayList<Object[]>();
for (int i = 0; i < intSpecies.length; i++) {
if (!intSpecies[i].equals("")) {
String[] split = intSpecies[i].split(" ");
if (split.length > 1) {
String[] levels = split[1].split(",");
if (levels.length > 0) {
specs.add(split[0]);
conLevel.add(levels);
}
}
}
}
GCMFile gcm = gcmEditor.getGCM();
if (gcm.flattenGCM(false) != null) {
LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel);
lpnFile.save(root + separator + simName + separator + lpnName);
time1 = System.nanoTime();
Translator t1 = new Translator();
if (abstraction.isSelected()) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + simName + separator + lpnName);
Abstraction abst = new Abstraction(lhpnFile, abstPane);
abst.abstractSTG(false);
abst.save(root + separator + simName + separator + lpnName + ".temp");
t1.BuildTemplate(
root + separator + simName + separator + lpnName + ".temp",
lpnProperty);
}
else {
t1.BuildTemplate(root + separator + simName + separator + lpnName,
lpnProperty);
}
t1.setFilename(root + separator + simName + separator
+ lpnName.replace(".lpn", ".sbml"));
t1.outputSBML();
}
else {
return 0;
}
}
if (nary.isSelected() && gcmEditor == null && !sim.equals("markov-chain-analysis")
&& !lhpn.isSelected() && naryRun == 1) {
log.addText("Executing:\nreb2sac --target.encoding=nary-level " + filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=nary-level " + theFile, null, work);
}
else if (sbml.isSelected()) {
sbmlName = JOptionPane.showInputDialog(component, "Enter SBML Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (sbmlName != null && !sbmlName.trim().equals("")) {
sbmlName = sbmlName.trim();
if (sbmlName.length() > 4) {
if (!sbmlName.substring(sbmlName.length() - 3).equals(".xml")
|| !sbmlName.substring(sbmlName.length() - 4).equals(".sbml")) {
sbmlName += ".xml";
}
}
else {
sbmlName += ".xml";
}
File f = new File(root + separator + sbmlName);
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(component, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(root + separator + sbmlName);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
}
else {
return 0;
}
}
if (modelFile.contains(".lpn")) {
progress.setIndeterminate(true);
time1 = System.nanoTime();
Translator t1 = new Translator();
if (abstraction.isSelected()) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + modelFile);
Abstraction abst = new Abstraction(lhpnFile, abstPane);
abst.abstractSTG(false);
abst.save(root + separator + simName + separator + modelFile);
t1.BuildTemplate(root + separator + simName + separator + modelFile,
lpnProperty);
}
else {
t1.BuildTemplate(root + separator + modelFile, lpnProperty);
}
t1.setFilename(root + separator + sbmlName);
t1.outputSBML();
exitValue = 0;
}
else if (gcmEditor != null && nary.isSelected()) {
String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "")
.replace(".xml", "")
+ ".lpn";
ArrayList<String> specs = new ArrayList<String>();
ArrayList<Object[]> conLevel = new ArrayList<Object[]>();
for (int i = 0; i < intSpecies.length; i++) {
if (!intSpecies[i].equals("")) {
String[] split = intSpecies[i].split(" ");
if (split.length > 1) {
String[] levels = split[1].split(",");
if (levels.length > 0) {
specs.add(split[0]);
conLevel.add(levels);
}
}
}
}
progress.setIndeterminate(true);
GCMFile gcm = gcmEditor.getGCM();
if (gcm.flattenGCM(false) != null) {
LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel);
lpnFile.save(root + separator + simName + separator + lpnName);
time1 = System.nanoTime();
Translator t1 = new Translator();
if (abstraction.isSelected()) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + simName + separator + lpnName);
Abstraction abst = new Abstraction(lhpnFile, abstPane);
abst.abstractSTG(false);
abst.save(root + separator + simName + separator + lpnName
+ ".temp");
t1.BuildTemplate(root + separator + simName + separator + lpnName
+ ".temp", lpnProperty);
}
else {
t1.BuildTemplate(root + separator + simName + separator + lpnName,
lpnProperty);
}
t1.setFilename(root + separator + sbmlName);
t1.outputSBML();
}
else {
time1 = System.nanoTime();
return 0;
}
exitValue = 0;
}
else {
log.addText("Executing:\nreb2sac --target.encoding=sbml --out=" + ".."
+ separator + sbmlName + " " + filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=sbml --out=" + ".."
+ separator + sbmlName + " " + theFile, null, work);
}
}
else {
time1 = System.nanoTime();
}
}
else if (lhpn.isSelected()) {
lhpnName = JOptionPane.showInputDialog(component, "Enter LPN Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (lhpnName != null && !lhpnName.trim().equals("")) {
lhpnName = lhpnName.trim();
if (lhpnName.length() > 4) {
if (!lhpnName.substring(lhpnName.length() - 3).equals(".lpn")) {
lhpnName += ".lpn";
}
}
else {
lhpnName += ".lpn";
}
File f = new File(root + separator + lhpnName);
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(component, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(root + separator + lhpnName);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
}
else {
return 0;
}
}
if (modelFile.contains(".lpn")) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + modelFile);
lhpnFile.save(root + separator + lhpnName);
time1 = System.nanoTime();
exitValue = 0;
}
else {
ArrayList<String> specs = new ArrayList<String>();
ArrayList<Object[]> conLevel = new ArrayList<Object[]>();
for (int i = 0; i < intSpecies.length; i++) {
if (!intSpecies[i].equals("")) {
String[] split = intSpecies[i].split(" ");
if (split.length > 1) {
String[] levels = split[1].split(",");
if (levels.length > 0) {
specs.add(split[0]);
conLevel.add(levels);
}
}
}
}
progress.setIndeterminate(true);
GCMFile gcm = gcmEditor.getGCM();
if (gcm.flattenGCM(false) != null) {
LhpnFile lhpnFile = gcm.convertToLHPN(specs, conLevel);
lhpnFile.save(root + separator + lhpnName);
log.addText("Saving GCM file as LHPN:\n" + root + separator + lhpnName
+ "\n");
}
else {
return 0;
}
time1 = System.nanoTime();
exitValue = 0;
}
}
else {
time1 = System.nanoTime();
exitValue = 0;
}
}
else if (dot.isSelected()) {
if (nary.isSelected() && gcmEditor != null) {
//String cmd = "atacs -cPllodpl "
// + theFile.replace(".sbml", "").replace(".xml", "") + ".lpn";
LhpnFile lhpnFile = new LhpnFile(log);
lhpnFile.load(directory + separator + theFile.replace(".sbml", "").replace(".xml", "") + ".lpn");
lhpnFile.printDot(directory + separator + theFile.replace(".sbml", "").replace(".xml", "") + ".dot");
time1 = System.nanoTime();
//Process ATACS = exec.exec(cmd, null, work);
//ATACS.waitFor();
//log.addText("Executing:\n" + cmd);
exitValue = 0;
}
else if (modelFile.contains(".lpn")) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + modelFile);
lhpnFile.save(root + separator + simName + separator + modelFile);
lhpnFile.printDot(root + separator + modelFile.replace(".lpn", ".dot"));
//String cmd = "atacs -cPllodpl " + modelFile;
//time1 = System.nanoTime();
//Process ATACS = exec.exec(cmd, null, work);
//ATACS.waitFor();
//log.addText("Executing:\n" + cmd);
time1 = System.nanoTime();
exitValue = 0;
}
else {
log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + out + ".dot "
+ filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot "
+ theFile, null, work);
}
}
else if (xhtml.isSelected()) {
log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + out + ".xhtml "
+ filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml "
+ theFile, null, work);
}
else if (usingSSA.isSelected()) {
log.addText("Executing:\nreb2sac --target.encoding=ssa-with-user-update "
+ filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=ssa-with-user-update " + theFile,
null, work);
}
else {
if (sim.equals("atacs")) {
log.addText("Executing:\nreb2sac --target.encoding=hse2 " + filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=hse2 " + theFile, null, work);
}
else if (sim.equals("markov-chain-analysis")) {
LhpnFile lhpnFile = null;
if (modelFile.contains(".lpn")) {
lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + modelFile);
}
else {
new File(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml",
"")
+ ".lpn").delete();
ArrayList<String> specs = new ArrayList<String>();
ArrayList<Object[]> conLevel = new ArrayList<Object[]>();
for (int i = 0; i < intSpecies.length; i++) {
if (!intSpecies[i].equals("")) {
String[] split = intSpecies[i].split(" ");
if (split.length > 1) {
String[] levels = split[1].split(",");
if (levels.length > 0) {
specs.add(split[0]);
conLevel.add(levels);
}
}
}
}
progress.setIndeterminate(true);
GCMFile gcm = gcmEditor.getGCM();
if (gcm.flattenGCM(false) != null) {
lhpnFile = gcm.convertToLHPN(specs, conLevel);
lhpnFile.save(filename.replace(".gcm", "").replace(".sbml", "")
.replace(".xml", "")
+ ".lpn");
log.addText("Saving GCM file as LHPN:\n"
+ filename.replace(".gcm", "").replace(".sbml", "").replace(
".xml", "") + ".lpn" + "\n");
}
else {
return 0;
}
}
// gcmEditor.getGCM().createLogicalModel(
// filename.replace(".gcm", "").replace(".sbml",
// "").replace(".xml", "")
// + ".lpn",
// log,
// biomodelsim,
// theFile.replace(".gcm", "").replace(".sbml",
// "").replace(".xml", "")
// + ".lpn");
// LHPNFile lhpnFile = new LHPNFile();
// while (new File(filename.replace(".gcm",
// "").replace(".sbml", "").replace(
// ".xml", "")
// + ".lpn.temp").exists()) {
// }
// if (new File(filename.replace(".gcm",
// "").replace(".sbml", "").replace(".xml",
// "")
// + ".lpn").exists()) {
// lhpnFile.load(filename.replace(".gcm",
// "").replace(".sbml", "").replace(
// ".xml", "")
// + ".lpn");
if (lhpnFile != null) {
sg = new StateGraph(lhpnFile);
BuildStateGraphThread buildStateGraph = new BuildStateGraphThread(sg);
buildStateGraph.start();
buildStateGraph.join();
if (!sg.getStop()) {
log.addText("Performing Markov Chain analysis.\n");
PerfromMarkovAnalysisThread performMarkovAnalysis = new PerfromMarkovAnalysisThread(
sg);
if (modelFile.contains(".lpn")) {
performMarkovAnalysis.start(null);
}
else {
performMarkovAnalysis.start(gcmEditor.getGCM().getConditions());
}
performMarkovAnalysis.join();
if (!sg.getStop()) {
String simrep = sg.getMarkovResults();
if (simrep != null) {
FileOutputStream simrepstream = new FileOutputStream(new File(
directory + separator + "sim-rep.txt"));
simrepstream.write((simrep).getBytes());
simrepstream.close();
}
sg.outputStateGraph(filename.replace(".gcm", "").replace(".sbml",
"").replace(".xml", "")
+ "_sg.dot", true);
biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex());
}
}
// if (sg.getNumberOfStates() > 30) {
// String[] options = { "Yes", "No" };
// int value = JOptionPane
// .showOptionDialog(
// BioSim.frame,
// "The state graph contains more than 30 states and may not open well in dotty.\nOpen it with dotty anyway?",
// "More Than 30 States", JOptionPane.YES_NO_OPTION,
// JOptionPane.WARNING_MESSAGE, null, options,
// options[0]);
// if (value == JOptionPane.YES_OPTION) {
// if
// (System.getProperty("os.name").contentEquals("Linux"))
// {
// log.addText("Executing:\ndotty "
// + filename.replace(".gcm", "").replace(".sbml", "")
// .replace(".xml", "") + "_sg.dot" + "\n");
// exec.exec("dotty "
// + theFile.replace(".gcm", "").replace(".sbml",
// "").replace(
// ".xml", "") + "_sg.dot", null, work);
// }
// else if
// (System.getProperty("os.name").toLowerCase().startsWith(
// "mac os")) {
// log.addText("Executing:\nopen "
// + filename.replace(".gcm", "").replace(".sbml", "")
// .replace(".xml", "") + "_sg.dot" + "\n");
// exec.exec("open "
// + theFile.replace(".gcm", "").replace(".sbml",
// "").replace(
// ".xml", "") + "_sg.dot", null, work);
// }
// else {
// log.addText("Executing:\ndotty "
// + filename.replace(".gcm", "").replace(".sbml", "")
// .replace(".xml", "") + "_sg.dot" + "\n");
// exec.exec("dotty "
// + theFile.replace(".gcm", "").replace(".sbml",
// "").replace(
// ".xml", "") + "_sg.dot", null, work);
// }
// }
// }
// }
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("ProbGraph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
simTab
.setComponentAt(i,
new Graph(r2s, printer_track_quantity, outDir
.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results", printer_id,
outDir, "time", biomodelsim, null, log,
null, false, false));
simTab.getComponentAt(i).setName("ProbGraph");
}
}
}
}
time1 = System.nanoTime();
exitValue = 0;
}
else {
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.sim.command", "").equals("")) {
log.addText("Executing:\nreb2sac --target.encoding=" + sim + " " + filename
+ "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=" + sim + " " + theFile,
null, work);
}
else {
String command = biosimrc.get("biosim.sim.command", "");
String fileStem = theFile.replaceAll(".xml", "");
fileStem = fileStem.replaceAll(".sbml", "");
command = command.replaceAll("filename", fileStem);
command = command.replaceAll("sim", sim);
log.addText(command + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec(command, null, work);
}
}
}
String error = "";
try {
InputStream reb = reb2sac.getInputStream();
InputStreamReader isr = new InputStreamReader(reb);
BufferedReader br = new BufferedReader(isr);
// int count = 0;
String line;
double time = 0;
double oldTime = 0;
int runNum = 0;
int prog = 0;
while ((line = br.readLine()) != null) {
try {
if (line.contains("Time")) {
time = Double.parseDouble(line.substring(line.indexOf('=') + 1, line
.length()));
if (oldTime > time) {
runNum++;
}
oldTime = time;
time += (runNum * timeLimit);
double d = ((time * 100) / runTime);
String s = d + "";
double decimal = Double.parseDouble(s.substring(s.indexOf('.'), s
.length()));
if (decimal >= 0.5) {
prog = (int) (Math.ceil(d));
}
else {
prog = (int) (d);
}
}
}
catch (Exception e) {
}
progress.setValue(prog);
// if (steps > 0) {
// count++;
// progress.setValue(count);
// }
// log.addText(output);
}
InputStream reb2 = reb2sac.getErrorStream();
int read = reb2.read();
while (read != -1) {
error += (char) read;
read = reb2.read();
}
br.close();
isr.close();
reb.close();
reb2.close();
}
catch (Exception e) {
}
if (reb2sac != null) {
exitValue = reb2sac.waitFor();
long time2 = System.nanoTime();
long minutes;
long hours;
long days;
double secs = ((time2 - time1) / 1000000000.0);
long seconds = ((time2 - time1) / 1000000000);
secs = secs - seconds;
minutes = seconds / 60;
secs = seconds % 60 + secs;
hours = minutes / 60;
minutes = minutes % 60;
days = hours / 24;
hours = hours % 60;
String time;
String dayLabel;
String hourLabel;
String minuteLabel;
String secondLabel;
if (days == 1) {
dayLabel = " day ";
}
else {
dayLabel = " days ";
}
if (hours == 1) {
hourLabel = " hour ";
}
else {
hourLabel = " hours ";
}
if (minutes == 1) {
minuteLabel = " minute ";
}
else {
minuteLabel = " minutes ";
}
if (seconds == 1) {
secondLabel = " second";
}
else {
secondLabel = " seconds";
}
if (days != 0) {
time = days + dayLabel + hours + hourLabel + minutes + minuteLabel + secs
+ secondLabel;
}
else if (hours != 0) {
time = hours + hourLabel + minutes + minuteLabel + secs + secondLabel;
}
else if (minutes != 0) {
time = minutes + minuteLabel + secs + secondLabel;
}
else {
time = secs + secondLabel;
}
if (!error.equals("")) {
log.addText("Errors:\n" + error + "\n");
}
log.addText("Total Simulation Time: " + time + " for " + simName + "\n\n");
}
if (exitValue != 0) {
if (exitValue == 143) {
JOptionPane.showMessageDialog(BioSim.frame, "The simulation was"
+ " canceled by the user.", "Canceled Simulation",
JOptionPane.ERROR_MESSAGE);
}
else if (exitValue == 139) {
JOptionPane.showMessageDialog(BioSim.frame,
"The selected model is not a valid sbml file."
+ "\nYou must select an sbml file.", "Not An SBML File",
JOptionPane.ERROR_MESSAGE);
}
else {
JOptionPane.showMessageDialog(BioSim.frame, "Error In Execution!\n"
+ "Bad Return Value!\n" + "The reb2sac program returned " + exitValue
+ " as an exit value.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
if (nary.isSelected() && gcmEditor == null && !lhpn.isSelected() && naryRun == 1) {
}
else if (sbml.isSelected()) {
if (sbmlName != null && !sbmlName.trim().equals("")) {
if (!biomodelsim.updateOpenSBML(sbmlName)) {
biomodelsim.addTab(sbmlName, new SBML_Editor(root + separator
+ sbmlName, null, log, biomodelsim, null, null), "SBML Editor");
biomodelsim.addToTree(sbmlName);
}
else {
biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(sbmlName));
}
}
}
else if (lhpn.isSelected()) {
if (lhpnName != null && !lhpnName.trim().equals("")) {
if (!biomodelsim.updateOpenLHPN(lhpnName)) {
biomodelsim.addTab(lhpnName, new LHPNEditor(root, lhpnName, null,
biomodelsim, log), "LHPN Editor");
biomodelsim.addToTree(lhpnName);
}
else {
biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(lhpnName));
}
}
}
else if (dot.isSelected()) {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + out + ".dot" + "\n");
exec.exec("dotty " + out + ".dot", null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + out + ".dot\n");
exec.exec("open " + out + ".dot", null, work);
}
else {
log.addText("Executing:\ndotty " + directory + out + ".dot" + "\n");
exec.exec("dotty " + out + ".dot", null, work);
}
}
else if (xhtml.isSelected()) {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ngnome-open " + directory + out + ".xhtml" + "\n");
exec.exec("gnome-open " + out + ".xhtml", null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + out + ".xhtml" + "\n");
exec.exec("open " + out + ".xhtml", null, work);
}
else {
log
.addText("Executing:\ncmd /c start " + directory + out + ".xhtml"
+ "\n");
exec.exec("cmd /c start " + out + ".xhtml", null, work);
}
}
else if (usingSSA.isSelected()) {
if (!printer_id.equals("null.printer")) {
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("TSD Graph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0,
printer_id.length() - 8);
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
simTab
.setComponentAt(i,
new Graph(r2s, printer_track_quantity, outDir
.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results", printer_id,
outDir, "time", biomodelsim, null, log,
null, true, false));
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0,
printer_id.length() - 8);
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
simTab.getComponentAt(i).setName("TSD Graph");
}
}
if (simTab.getComponentAt(i).getName().equals("ProbGraph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
if (new File(filename.substring(0,
filename.length()
- filename.split(separator)[filename
.split(separator).length - 1].length())
+ "sim-rep.txt").exists()) {
simTab.setComponentAt(i,
new Graph(r2s, printer_track_quantity,
outDir.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results",
printer_id, outDir, "time", biomodelsim,
null, log, null, false, false));
simTab.getComponentAt(i).setName("ProbGraph");
}
}
}
}
}
}
else if (sim.equals("atacs")) {
log.addText("Executing:\natacs -T0.000001 -oqoflhsgllvA "
+ filename
.substring(0,
filename.length()
- filename.split(separator)[filename
.split(separator).length - 1].length())
+ "out.hse\n");
exec.exec("atacs -T0.000001 -oqoflhsgllvA out.hse", null, work);
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("ProbGraph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity,
outDir.split(separator)[outDir.split(separator).length - 1]
+ " simulation results", printer_id, outDir,
"time", biomodelsim, null, log, null, false, false));
simTab.getComponentAt(i).setName("ProbGraph");
}
}
}
// simTab.add("Probability Graph", new
// Graph(printer_track_quantity,
// outDir.split(separator)[outDir.split(separator).length -
// 1] + "
// simulation results",
// printer_id, outDir, "time", biomodelsim, null, log, null,
// false));
// simTab.getComponentAt(simTab.getComponentCount() -
// 1).setName("ProbGraph");
}
else {
if (!printer_id.equals("null.printer")) {
if (ode.isSelected()) {
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("TSD Graph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0, printer_id
.length() - 8);
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i))
.readData(directory + separator + run,
"deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
simTab.setComponentAt(i,
new Graph(r2s, printer_track_quantity,
outDir.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results",
printer_id, outDir, "time", biomodelsim,
null, log, null, true, false));
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0, printer_id
.length() - 8);
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i))
.readData(directory + separator + run,
"deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
simTab.getComponentAt(i).setName("TSD Graph");
}
}
if (simTab.getComponentAt(i).getName().equals("ProbGraph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
if (new File(filename.substring(0, filename.length()
- filename.split(separator)[filename
.split(separator).length - 1].length())
+ "sim-rep.txt").exists()) {
simTab.setComponentAt(i,
new Graph(r2s, printer_track_quantity, outDir
.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results", printer_id,
outDir, "time", biomodelsim, null, log,
null, false, false));
simTab.getComponentAt(i).setName("ProbGraph");
}
}
}
}
}
else if (monteCarlo.isSelected()) {
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("TSD Graph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0, printer_id
.length() - 8);
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i))
.readData(directory + separator + run,
"deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
simTab.setComponentAt(i,
new Graph(r2s, printer_track_quantity,
outDir.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results",
printer_id, outDir, "time", biomodelsim,
null, log, null, true, false));
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0, printer_id
.length() - 8);
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i))
.readData(directory + separator + run,
"deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
simTab.getComponentAt(i).setName("TSD Graph");
}
}
if (simTab.getComponentAt(i).getName().equals("ProbGraph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
if (new File(filename.substring(0, filename.length()
- filename.split(separator)[filename
.split(separator).length - 1].length())
+ "sim-rep.txt").exists()) {
simTab.setComponentAt(i,
new Graph(r2s, printer_track_quantity, outDir
.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results", printer_id,
outDir, "time", biomodelsim, null, log,
null, false, false));
simTab.getComponentAt(i).setName("ProbGraph");
}
}
}
}
}
}
}
}
}
catch (InterruptedException e1) {
JOptionPane.showMessageDialog(BioSim.frame, "Error In Execution!",
"Error In Execution", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(BioSim.frame, "File I/O Error!", "File I/O Error",
JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
return exitValue;
}
/**
* This method is called if a button that cancels the simulation is pressed.
*/
public void actionPerformed(ActionEvent e) {
if (reb2sac != null) {
reb2sac.destroy();
}
if (sg != null) {
sg.stop();
}
}
}
| gui/src/reb2sac/Run.java | package reb2sac;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.prefs.Preferences;
import javax.swing.*;
import parser.*;
import lhpn2sbml.gui.LHPNEditor;
import lhpn2sbml.parser.*;
import biomodelsim.*;
import gcm2sbml.gui.GCM2SBMLEditor;
import gcm2sbml.parser.GCMFile;
import graph.*;
import buttons.*;
import sbmleditor.*;
import stategraph.BuildStateGraphThread;
import stategraph.PerfromMarkovAnalysisThread;
import stategraph.StateGraph;
import verification.AbstPane;
/**
* This class creates the properties file that is given to the reb2sac program.
* It also executes the reb2sac program.
*
* @author Curtis Madsen
*/
public class Run implements ActionListener {
private Process reb2sac;
private String separator;
private Reb2Sac r2s;
StateGraph sg;
public Run(Reb2Sac reb2sac) {
r2s = reb2sac;
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
}
/**
* This method is given which buttons are selected and creates the
* properties file from all the other information given.
*
* @param useInterval
*
* @param stem
*/
public void createProperties(double timeLimit, String useInterval, double printInterval,
double minTimeStep, double timeStep, double absError, String outDir, long rndSeed,
int run, String[] termCond, String[] intSpecies, String printer_id,
String printer_track_quantity, String[] getFilename, String selectedButtons,
Component component, String filename, double rap1, double rap2, double qss, int con,
JCheckBox usingSSA, String ssaFile, JCheckBox usingSad, File sadFile, JList preAbs,
JList loopAbs, JList postAbs, AbstPane abstPane) {
Properties abs = new Properties();
if (selectedButtons.contains("abs") || selectedButtons.contains("nary")) {
for (int i = 0; i < preAbs.getModel().getSize(); i++) {
abs.setProperty("reb2sac.abstraction.method.1." + (i + 1), (String) preAbs
.getModel().getElementAt(i));
}
for (int i = 0; i < loopAbs.getModel().getSize(); i++) {
abs.setProperty("reb2sac.abstraction.method.2." + (i + 1), (String) loopAbs
.getModel().getElementAt(i));
}
// abs.setProperty("reb2sac.abstraction.method.0.1",
// "enzyme-kinetic-qssa-1");
// abs.setProperty("reb2sac.abstraction.method.0.2",
// "reversible-to-irreversible-transformer");
// abs.setProperty("reb2sac.abstraction.method.0.3",
// "multiple-products-reaction-eliminator");
// abs.setProperty("reb2sac.abstraction.method.0.4",
// "multiple-reactants-reaction-eliminator");
// abs.setProperty("reb2sac.abstraction.method.0.5",
// "single-reactant-product-reaction-eliminator");
// abs.setProperty("reb2sac.abstraction.method.0.6",
// "dimer-to-monomer-substitutor");
// abs.setProperty("reb2sac.abstraction.method.0.7",
// "inducer-structure-transformer");
// abs.setProperty("reb2sac.abstraction.method.1.1",
// "modifier-structure-transformer");
// abs.setProperty("reb2sac.abstraction.method.1.2",
// "modifier-constant-propagation");
// abs.setProperty("reb2sac.abstraction.method.2.1",
// "operator-site-forward-binding-remover");
// abs.setProperty("reb2sac.abstraction.method.2.3",
// "enzyme-kinetic-rapid-equilibrium-1");
// abs.setProperty("reb2sac.abstraction.method.2.4",
// "irrelevant-species-remover");
// abs.setProperty("reb2sac.abstraction.method.2.5",
// "inducer-structure-transformer");
// abs.setProperty("reb2sac.abstraction.method.2.6",
// "modifier-constant-propagation");
// abs.setProperty("reb2sac.abstraction.method.2.7",
// "similar-reaction-combiner");
// abs.setProperty("reb2sac.abstraction.method.2.8",
// "modifier-constant-propagation");
}
// if (selectedButtons.contains("abs")) {
// abs.setProperty("reb2sac.abstraction.method.2.2",
// "dimerization-reduction");
// }
// else if (selectedButtons.contains("nary")) {
// abs.setProperty("reb2sac.abstraction.method.2.2",
// "dimerization-reduction-level-assignment");
// }
for (int i = 0; i < postAbs.getModel().getSize(); i++) {
abs.setProperty("reb2sac.abstraction.method.3." + (i + 1), (String) postAbs.getModel()
.getElementAt(i));
}
abs.setProperty("simulation.printer", printer_id);
abs.setProperty("simulation.printer.tracking.quantity", printer_track_quantity);
// if (selectedButtons.contains("monteCarlo")) {
// abs.setProperty("reb2sac.abstraction.method.3.1",
// "distribute-transformer");
// abs.setProperty("reb2sac.abstraction.method.3.2",
// "reversible-to-irreversible-transformer");
// abs.setProperty("reb2sac.abstraction.method.3.3",
// "kinetic-law-constants-simplifier");
// }
// else if (selectedButtons.contains("none")) {
// abs.setProperty("reb2sac.abstraction.method.3.1",
// "kinetic-law-constants-simplifier");
// }
for (int i = 0; i < intSpecies.length; i++) {
if (!intSpecies[i].equals("")) {
String[] split = intSpecies[i].split(" ");
abs.setProperty("reb2sac.interesting.species." + (i + 1), split[0]);
if (split.length > 1) {
String[] levels = split[1].split(",");
for (int j = 0; j < levels.length; j++) {
abs.setProperty("reb2sac.concentration.level." + split[0] + "." + (j + 1),
levels[j]);
}
}
}
}
abs.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1);
abs.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2);
abs.setProperty("reb2sac.qssa.condition.1", "" + qss);
abs.setProperty("reb2sac.operator.max.concentration.threshold", "" + con);
if (selectedButtons.contains("none")) {
abs.setProperty("reb2sac.abstraction.method", "none");
}
if (selectedButtons.contains("abs")) {
abs.setProperty("reb2sac.abstraction.method", "abs");
}
else if (selectedButtons.contains("nary")) {
abs.setProperty("reb2sac.abstraction.method", "nary");
}
if (abstPane != null) {
String intVars = "";
for (int i = 0; i < abstPane.listModel.getSize(); i++) {
if (abstPane.listModel.getElementAt(i) != null) {
intVars = intVars + abstPane.listModel.getElementAt(i) + " ";
}
}
if (!intVars.equals("")) {
abs.setProperty("abstraction.interesting", intVars.trim());
}
else {
abs.remove("abstraction.interesting");
}
String xforms = "";
for (int i = 0; i < abstPane.absListModel.getSize(); i++) {
if (abstPane.absListModel.getElementAt(i) != null) {
xforms = xforms + abstPane.absListModel.getElementAt(i) + ", ";
}
}
if (!xforms.equals("")) {
abs.setProperty("abstraction.transforms", xforms.trim());
}
else {
abs.remove("abstraction.transforms");
}
if (!abstPane.factorField.getText().equals("")) {
abs.setProperty("abstraction.factor", abstPane.factorField.getText());
}
if (!abstPane.iterField.getText().equals("")) {
abs.setProperty("abstraction.iterations", abstPane.iterField.getText());
}
}
if (selectedButtons.contains("ODE")) {
abs.setProperty("reb2sac.simulation.method", "ODE");
}
else if (selectedButtons.contains("monteCarlo")) {
abs.setProperty("reb2sac.simulation.method", "monteCarlo");
}
else if (selectedButtons.contains("markov")) {
abs.setProperty("reb2sac.simulation.method", "markov");
}
else if (selectedButtons.contains("sbml")) {
abs.setProperty("reb2sac.simulation.method", "SBML");
}
else if (selectedButtons.contains("dot")) {
abs.setProperty("reb2sac.simulation.method", "Network");
}
else if (selectedButtons.contains("xhtml")) {
abs.setProperty("reb2sac.simulation.method", "Browser");
}
else if (selectedButtons.contains("lhpn")) {
abs.setProperty("reb2sac.simulation.method", "LPN");
}
if (!selectedButtons.contains("monteCarlo")) {
// if (selectedButtons.equals("none_ODE") ||
// selectedButtons.equals("abs_ODE")) {
abs.setProperty("ode.simulation.time.limit", "" + timeLimit);
if (useInterval.equals("Print Interval")) {
abs.setProperty("ode.simulation.print.interval", "" + printInterval);
}
else if (useInterval.equals("Minimum Print Interval")) {
abs.setProperty("ode.simulation.minimum.print.interval", "" + printInterval);
}
else {
abs.setProperty("ode.simulation.number.steps", "" + ((int) printInterval));
}
if (timeStep == Double.MAX_VALUE) {
abs.setProperty("ode.simulation.time.step", "inf");
}
else {
abs.setProperty("ode.simulation.time.step", "" + timeStep);
}
abs.setProperty("ode.simulation.min.time.step", "" + minTimeStep);
abs.setProperty("ode.simulation.absolute.error", "" + absError);
abs.setProperty("ode.simulation.out.dir", outDir);
abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed);
abs.setProperty("monte.carlo.simulation.runs", "" + run);
}
if (!selectedButtons.contains("ODE")) {
// if (selectedButtons.equals("none_monteCarlo") ||
// selectedButtons.equals("abs_monteCarlo")) {
abs.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit);
if (useInterval.equals("Print Interval")) {
abs.setProperty("monte.carlo.simulation.print.interval", "" + printInterval);
}
else if (useInterval.equals("Minimum Print Interval")) {
abs
.setProperty("monte.carlo.simulation.minimum.print.interval", ""
+ printInterval);
}
else {
abs.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval));
}
if (timeStep == Double.MAX_VALUE) {
abs.setProperty("monte.carlo.simulation.time.step", "inf");
}
else {
abs.setProperty("monte.carlo.simulation.time.step", "" + timeStep);
}
abs.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep);
abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed);
abs.setProperty("monte.carlo.simulation.runs", "" + run);
abs.setProperty("monte.carlo.simulation.out.dir", outDir);
if (usingSad.isSelected()) {
abs.setProperty("simulation.run.termination.decider", "sad");
abs.setProperty("computation.analysis.sad.path", sadFile.getName());
}
}
if (!usingSad.isSelected()) {
abs.setProperty("simulation.run.termination.decider", "constraint");
}
if (usingSSA.isSelected() && selectedButtons.contains("monteCarlo")) {
abs.setProperty("simulation.time.series.species.level.file", ssaFile);
}
for (int i = 0; i < termCond.length; i++) {
if (termCond[i] != "") {
abs
.setProperty("simulation.run.termination.condition." + (i + 1), ""
+ termCond[i]);
}
}
try {
if (!getFilename[getFilename.length - 1].contains(".")) {
getFilename[getFilename.length - 1] += ".";
filename += ".";
}
int cut = 0;
for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) {
if (getFilename[getFilename.length - 1].charAt(i) == '.') {
cut = i;
}
}
FileOutputStream store = new FileOutputStream(new File((filename.substring(0, filename
.length()
- getFilename[getFilename.length - 1].length()))
+ getFilename[getFilename.length - 1].substring(0, cut) + ".properties"));
abs.store(store, getFilename[getFilename.length - 1].substring(0, cut) + " Properties");
store.close();
}
catch (Exception except) {
JOptionPane.showMessageDialog(component, "Unable To Save Properties File!"
+ "\nMake sure you select a model for abstraction.", "Unable To Save File",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* This method is given what data is entered into the nary frame and creates
* the nary properties file from that information.
*/
public void createNaryProperties(double timeLimit, String useInterval, double printInterval,
double minTimeStep, double timeStep, String outDir, long rndSeed, int run,
String printer_id, String printer_track_quantity, String[] getFilename,
Component component, String filename, JRadioButton monteCarlo, String stopE,
double stopR, String[] finalS, ArrayList<JTextField> inhib, ArrayList<JList> consLevel,
ArrayList<String> getSpeciesProps, ArrayList<Object[]> conLevel, String[] termCond,
String[] intSpecies, double rap1, double rap2, double qss, int con,
ArrayList<Integer> counts, JCheckBox usingSSA, String ssaFile) {
Properties nary = new Properties();
try {
FileInputStream load = new FileInputStream(new File(outDir + separator
+ "species.properties"));
nary.load(load);
load.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(component, "Species Properties File Not Found!",
"File Not Found", JOptionPane.ERROR_MESSAGE);
}
nary.setProperty("reb2sac.abstraction.method.0.1", "enzyme-kinetic-qssa-1");
nary
.setProperty("reb2sac.abstraction.method.0.2",
"reversible-to-irreversible-transformer");
nary.setProperty("reb2sac.abstraction.method.0.3", "multiple-products-reaction-eliminator");
nary
.setProperty("reb2sac.abstraction.method.0.4",
"multiple-reactants-reaction-eliminator");
nary.setProperty("reb2sac.abstraction.method.0.5",
"single-reactant-product-reaction-eliminator");
nary.setProperty("reb2sac.abstraction.method.0.6", "dimer-to-monomer-substitutor");
nary.setProperty("reb2sac.abstraction.method.0.7", "inducer-structure-transformer");
nary.setProperty("reb2sac.abstraction.method.1.1", "modifier-structure-transformer");
nary.setProperty("reb2sac.abstraction.method.1.2", "modifier-constant-propagation");
nary.setProperty("reb2sac.abstraction.method.2.1", "operator-site-forward-binding-remover");
nary.setProperty("reb2sac.abstraction.method.2.3", "enzyme-kinetic-rapid-equilibrium-1");
nary.setProperty("reb2sac.abstraction.method.2.4", "irrelevant-species-remover");
nary.setProperty("reb2sac.abstraction.method.2.5", "inducer-structure-transformer");
nary.setProperty("reb2sac.abstraction.method.2.6", "modifier-constant-propagation");
nary.setProperty("reb2sac.abstraction.method.2.7", "similar-reaction-combiner");
nary.setProperty("reb2sac.abstraction.method.2.8", "modifier-constant-propagation");
nary.setProperty("reb2sac.abstraction.method.2.2", "dimerization-reduction");
nary.setProperty("reb2sac.abstraction.method.3.1", "nary-order-unary-transformer");
nary.setProperty("reb2sac.abstraction.method.3.2", "modifier-constant-propagation");
nary.setProperty("reb2sac.abstraction.method.3.3", "absolute-inhibition-generator");
nary.setProperty("reb2sac.abstraction.method.3.4", "final-state-generator");
nary.setProperty("reb2sac.abstraction.method.3.5", "stop-flag-generator");
nary.setProperty("reb2sac.nary.order.decider", "distinct");
nary.setProperty("simulation.printer", printer_id);
nary.setProperty("simulation.printer.tracking.quantity", printer_track_quantity);
nary.setProperty("reb2sac.analysis.stop.enabled", stopE);
nary.setProperty("reb2sac.analysis.stop.rate", "" + stopR);
for (int i = 0; i < getSpeciesProps.size(); i++) {
if (!(inhib.get(i).getText().trim() != "<<none>>")) {
nary.setProperty("reb2sac.absolute.inhibition.threshold." + getSpeciesProps.get(i),
inhib.get(i).getText().trim());
}
String[] consLevels = Buttons.getList(conLevel.get(i), consLevel.get(i));
for (int j = 0; j < counts.get(i); j++) {
nary
.remove("reb2sac.concentration.level." + getSpeciesProps.get(i) + "."
+ (j + 1));
}
for (int j = 0; j < consLevels.length; j++) {
nary.setProperty("reb2sac.concentration.level." + getSpeciesProps.get(i) + "."
+ (j + 1), consLevels[j]);
}
}
if (monteCarlo.isSelected()) {
nary.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit);
if (useInterval.equals("Print Interval")) {
nary.setProperty("monte.carlo.simulation.print.interval", "" + printInterval);
}
else if (useInterval.equals("Minimum Print Interval")) {
nary.setProperty("monte.carlo.simulation.minimum.print.interval", ""
+ printInterval);
}
else {
nary.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval));
}
if (timeStep == Double.MAX_VALUE) {
nary.setProperty("monte.carlo.simulation.time.step", "inf");
}
else {
nary.setProperty("monte.carlo.simulation.time.step", "" + timeStep);
}
nary.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep);
nary.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed);
nary.setProperty("monte.carlo.simulation.runs", "" + run);
nary.setProperty("monte.carlo.simulation.out.dir", ".");
}
for (int i = 0; i < finalS.length; i++) {
if (finalS[i].trim() != "<<unknown>>") {
nary.setProperty("reb2sac.final.state." + (i + 1), "" + finalS[i]);
}
}
if (usingSSA.isSelected() && monteCarlo.isSelected()) {
nary.setProperty("simulation.time.series.species.level.file", ssaFile);
}
for (int i = 0; i < intSpecies.length; i++) {
if (intSpecies[i] != "") {
nary.setProperty("reb2sac.interesting.species." + (i + 1), "" + intSpecies[i]);
}
}
nary.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1);
nary.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2);
nary.setProperty("reb2sac.qssa.condition.1", "" + qss);
nary.setProperty("reb2sac.operator.max.concentration.threshold", "" + con);
for (int i = 0; i < termCond.length; i++) {
if (termCond[i] != "") {
nary.setProperty("simulation.run.termination.condition." + (i + 1), ""
+ termCond[i]);
}
}
try {
FileOutputStream store = new FileOutputStream(new File((filename.substring(0, filename
.length()
- getFilename[getFilename.length - 1].length()))
+ getFilename[getFilename.length - 1].substring(0,
getFilename[getFilename.length - 1].length() - 5) + ".properties"));
nary.store(store, getFilename[getFilename.length - 1].substring(0,
getFilename[getFilename.length - 1].length() - 5)
+ " Properties");
store.close();
}
catch (Exception except) {
JOptionPane.showMessageDialog(component, "Unable To Save Properties File!"
+ "\nMake sure you select a model for simulation.", "Unable To Save File",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Executes the reb2sac program. If ODE, monte carlo, or markov is selected,
* this method creates a Graph object.
*
* @param runTime
*/
public int execute(String filename, JRadioButton sbml, JRadioButton dot, JRadioButton xhtml,
JRadioButton lhpn, Component component, JRadioButton ode, JRadioButton monteCarlo,
String sim, String printer_id, String printer_track_quantity, String outDir,
JRadioButton nary, int naryRun, String[] intSpecies, Log log, JCheckBox usingSSA,
String ssaFile, BioSim biomodelsim, JTabbedPane simTab, String root,
JProgressBar progress, String simName, GCM2SBMLEditor gcmEditor, String direct,
double timeLimit, double runTime, String modelFile, AbstPane abstPane,
JRadioButton abstraction, String lpnProperty) {
Runtime exec = Runtime.getRuntime();
int exitValue = 255;
while (outDir.split(separator)[outDir.split(separator).length - 1].equals(".")) {
outDir = outDir.substring(0, outDir.length() - 1
- outDir.split(separator)[outDir.split(separator).length - 1].length());
}
try {
long time1;
String directory = "";
String theFile = "";
String sbmlName = "";
String lhpnName = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
String out = theFile;
if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) {
out = out.substring(0, out.length() - 5);
}
else if (out.length() > 3
&& out.substring(out.length() - 4, out.length()).equals(".xml")) {
out = out.substring(0, out.length() - 4);
}
if (nary.isSelected() && gcmEditor != null
&& (monteCarlo.isSelected() || xhtml.isSelected())) {
String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "").replace(".xml",
"")
+ ".lpn";
ArrayList<String> specs = new ArrayList<String>();
ArrayList<Object[]> conLevel = new ArrayList<Object[]>();
for (int i = 0; i < intSpecies.length; i++) {
if (!intSpecies[i].equals("")) {
String[] split = intSpecies[i].split(" ");
if (split.length > 1) {
String[] levels = split[1].split(",");
if (levels.length > 0) {
specs.add(split[0]);
conLevel.add(levels);
}
}
}
}
GCMFile gcm = gcmEditor.getGCM();
if (gcm.flattenGCM(false) != null) {
LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel);
lpnFile.save(root + separator + simName + separator + lpnName);
time1 = System.nanoTime();
Translator t1 = new Translator();
if (abstraction.isSelected()) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + simName + separator + lpnName);
Abstraction abst = new Abstraction(lhpnFile, abstPane);
abst.abstractSTG(false);
abst.save(root + separator + simName + separator + lpnName + ".temp");
t1.BuildTemplate(
root + separator + simName + separator + lpnName + ".temp",
lpnProperty);
}
else {
t1.BuildTemplate(root + separator + simName + separator + lpnName,
lpnProperty);
}
t1.setFilename(root + separator + simName + separator
+ lpnName.replace(".lpn", ".sbml"));
t1.outputSBML();
}
else {
return 0;
}
}
if (nary.isSelected() && gcmEditor == null && !sim.equals("markov-chain-analysis")
&& !lhpn.isSelected() && naryRun == 1) {
log.addText("Executing:\nreb2sac --target.encoding=nary-level " + filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=nary-level " + theFile, null, work);
}
else if (sbml.isSelected()) {
sbmlName = JOptionPane.showInputDialog(component, "Enter SBML Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (sbmlName != null && !sbmlName.trim().equals("")) {
sbmlName = sbmlName.trim();
if (sbmlName.length() > 4) {
if (!sbmlName.substring(sbmlName.length() - 3).equals(".xml")
|| !sbmlName.substring(sbmlName.length() - 4).equals(".sbml")) {
sbmlName += ".xml";
}
}
else {
sbmlName += ".xml";
}
File f = new File(root + separator + sbmlName);
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(component, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(root + separator + sbmlName);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
}
else {
return 0;
}
}
if (modelFile.contains(".lpn")) {
progress.setIndeterminate(true);
time1 = System.nanoTime();
Translator t1 = new Translator();
if (abstraction.isSelected()) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + modelFile);
Abstraction abst = new Abstraction(lhpnFile, abstPane);
abst.abstractSTG(false);
abst.save(root + separator + simName + separator + modelFile);
t1.BuildTemplate(root + separator + simName + separator + modelFile,
lpnProperty);
}
else {
t1.BuildTemplate(root + separator + modelFile, lpnProperty);
}
t1.setFilename(root + separator + sbmlName);
t1.outputSBML();
exitValue = 0;
}
else if (gcmEditor != null && nary.isSelected()) {
String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "")
.replace(".xml", "")
+ ".lpn";
ArrayList<String> specs = new ArrayList<String>();
ArrayList<Object[]> conLevel = new ArrayList<Object[]>();
for (int i = 0; i < intSpecies.length; i++) {
if (!intSpecies[i].equals("")) {
String[] split = intSpecies[i].split(" ");
if (split.length > 1) {
String[] levels = split[1].split(",");
if (levels.length > 0) {
specs.add(split[0]);
conLevel.add(levels);
}
}
}
}
progress.setIndeterminate(true);
GCMFile gcm = gcmEditor.getGCM();
if (gcm.flattenGCM(false) != null) {
LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel);
lpnFile.save(root + separator + simName + separator + lpnName);
time1 = System.nanoTime();
Translator t1 = new Translator();
if (abstraction.isSelected()) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + simName + separator + lpnName);
Abstraction abst = new Abstraction(lhpnFile, abstPane);
abst.abstractSTG(false);
abst.save(root + separator + simName + separator + lpnName
+ ".temp");
t1.BuildTemplate(root + separator + simName + separator + lpnName
+ ".temp", lpnProperty);
}
else {
t1.BuildTemplate(root + separator + simName + separator + lpnName,
lpnProperty);
}
t1.setFilename(root + separator + sbmlName);
t1.outputSBML();
}
else {
time1 = System.nanoTime();
return 0;
}
exitValue = 0;
}
else {
log.addText("Executing:\nreb2sac --target.encoding=sbml --out=" + ".."
+ separator + sbmlName + " " + filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=sbml --out=" + ".."
+ separator + sbmlName + " " + theFile, null, work);
}
}
else {
time1 = System.nanoTime();
}
}
else if (lhpn.isSelected()) {
lhpnName = JOptionPane.showInputDialog(component, "Enter LPN Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (lhpnName != null && !lhpnName.trim().equals("")) {
lhpnName = lhpnName.trim();
if (lhpnName.length() > 4) {
if (!lhpnName.substring(lhpnName.length() - 3).equals(".lpn")) {
lhpnName += ".lpn";
}
}
else {
lhpnName += ".lpn";
}
File f = new File(root + separator + lhpnName);
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(component, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(root + separator + lhpnName);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
}
else {
return 0;
}
}
if (modelFile.contains(".lpn")) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + modelFile);
lhpnFile.save(root + separator + lhpnName);
time1 = System.nanoTime();
exitValue = 0;
}
else {
ArrayList<String> specs = new ArrayList<String>();
ArrayList<Object[]> conLevel = new ArrayList<Object[]>();
for (int i = 0; i < intSpecies.length; i++) {
if (!intSpecies[i].equals("")) {
String[] split = intSpecies[i].split(" ");
if (split.length > 1) {
String[] levels = split[1].split(",");
if (levels.length > 0) {
specs.add(split[0]);
conLevel.add(levels);
}
}
}
}
progress.setIndeterminate(true);
GCMFile gcm = gcmEditor.getGCM();
if (gcm.flattenGCM(false) != null) {
LhpnFile lhpnFile = gcm.convertToLHPN(specs, conLevel);
lhpnFile.save(root + separator + lhpnName);
log.addText("Saving GCM file as LHPN:\n" + root + separator + lhpnName
+ "\n");
}
else {
return 0;
}
time1 = System.nanoTime();
exitValue = 0;
}
}
else {
time1 = System.nanoTime();
exitValue = 0;
}
}
else if (dot.isSelected()) {
if (nary.isSelected() && gcmEditor != null) {
//String cmd = "atacs -cPllodpl "
// + theFile.replace(".sbml", "").replace(".xml", "") + ".lpn";
LhpnFile lhpnFile = new LhpnFile(log);
lhpnFile.load(directory + separator + theFile.replace(".sbml", "").replace(".xml", "") + ".lpn");
lhpnFile.printDot(directory + separator + theFile.replace(".sbml", "").replace(".xml", "") + ".dot");
time1 = System.nanoTime();
//Process ATACS = exec.exec(cmd, null, work);
//ATACS.waitFor();
//log.addText("Executing:\n" + cmd);
exitValue = 0;
}
else if (modelFile.contains(".lpn")) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + modelFile);
lhpnFile.save(root + separator + simName + separator + modelFile);
lhpnFile.printDot(root + separator + modelFile.replace(".lpn", ".dot"));
//String cmd = "atacs -cPllodpl " + modelFile;
//time1 = System.nanoTime();
//Process ATACS = exec.exec(cmd, null, work);
//ATACS.waitFor();
//log.addText("Executing:\n" + cmd);
time1 = System.nanoTime();
exitValue = 0;
}
else {
log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + out + ".dot "
+ filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot "
+ theFile, null, work);
}
}
else if (xhtml.isSelected()) {
log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + out + ".xhtml "
+ filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml "
+ theFile, null, work);
}
else if (usingSSA.isSelected()) {
log.addText("Executing:\nreb2sac --target.encoding=ssa-with-user-update "
+ filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=ssa-with-user-update " + theFile,
null, work);
}
else {
if (sim.equals("atacs")) {
log.addText("Executing:\nreb2sac --target.encoding=hse2 " + filename + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=hse2 " + theFile, null, work);
}
else if (sim.equals("markov-chain-analysis")) {
LhpnFile lhpnFile = null;
if (modelFile.contains(".lpn")) {
lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + modelFile);
}
else {
new File(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml",
"")
+ ".lpn").delete();
ArrayList<String> specs = new ArrayList<String>();
ArrayList<Object[]> conLevel = new ArrayList<Object[]>();
for (int i = 0; i < intSpecies.length; i++) {
if (!intSpecies[i].equals("")) {
String[] split = intSpecies[i].split(" ");
if (split.length > 1) {
String[] levels = split[1].split(",");
if (levels.length > 0) {
specs.add(split[0]);
conLevel.add(levels);
}
}
}
}
progress.setIndeterminate(true);
GCMFile gcm = gcmEditor.getGCM();
if (gcm.flattenGCM(false) != null) {
lhpnFile = gcm.convertToLHPN(specs, conLevel);
lhpnFile.save(filename.replace(".gcm", "").replace(".sbml", "")
.replace(".xml", "")
+ ".lpn");
log.addText("Saving GCM file as LHPN:\n"
+ filename.replace(".gcm", "").replace(".sbml", "").replace(
".xml", "") + ".lpn" + "\n");
}
else {
return 0;
}
}
// gcmEditor.getGCM().createLogicalModel(
// filename.replace(".gcm", "").replace(".sbml",
// "").replace(".xml", "")
// + ".lpn",
// log,
// biomodelsim,
// theFile.replace(".gcm", "").replace(".sbml",
// "").replace(".xml", "")
// + ".lpn");
// LHPNFile lhpnFile = new LHPNFile();
// while (new File(filename.replace(".gcm",
// "").replace(".sbml", "").replace(
// ".xml", "")
// + ".lpn.temp").exists()) {
// }
// if (new File(filename.replace(".gcm",
// "").replace(".sbml", "").replace(".xml",
// "")
// + ".lpn").exists()) {
// lhpnFile.load(filename.replace(".gcm",
// "").replace(".sbml", "").replace(
// ".xml", "")
// + ".lpn");
if (lhpnFile != null) {
sg = new StateGraph(lhpnFile);
BuildStateGraphThread buildStateGraph = new BuildStateGraphThread(sg);
buildStateGraph.start();
buildStateGraph.join();
if (!sg.getStop()) {
log.addText("Performing Markov Chain analysis.\n");
PerfromMarkovAnalysisThread performMarkovAnalysis = new PerfromMarkovAnalysisThread(
sg);
if (modelFile.contains(".lpn")) {
performMarkovAnalysis.start(null);
}
else {
performMarkovAnalysis.start(gcmEditor.getGCM().getConditions());
}
performMarkovAnalysis.join();
if (!sg.getStop()) {
String simrep = sg.getMarkovResults();
if (simrep != null) {
FileOutputStream simrepstream = new FileOutputStream(new File(
directory + separator + "sim-rep.txt"));
simrepstream.write((simrep).getBytes());
simrepstream.close();
}
sg.outputStateGraph(filename.replace(".gcm", "").replace(".sbml",
"").replace(".xml", "")
+ "_sg.dot", true);
biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex());
}
}
// if (sg.getNumberOfStates() > 30) {
// String[] options = { "Yes", "No" };
// int value = JOptionPane
// .showOptionDialog(
// BioSim.frame,
// "The state graph contains more than 30 states and may not open well in dotty.\nOpen it with dotty anyway?",
// "More Than 30 States", JOptionPane.YES_NO_OPTION,
// JOptionPane.WARNING_MESSAGE, null, options,
// options[0]);
// if (value == JOptionPane.YES_OPTION) {
// if
// (System.getProperty("os.name").contentEquals("Linux"))
// {
// log.addText("Executing:\ndotty "
// + filename.replace(".gcm", "").replace(".sbml", "")
// .replace(".xml", "") + "_sg.dot" + "\n");
// exec.exec("dotty "
// + theFile.replace(".gcm", "").replace(".sbml",
// "").replace(
// ".xml", "") + "_sg.dot", null, work);
// }
// else if
// (System.getProperty("os.name").toLowerCase().startsWith(
// "mac os")) {
// log.addText("Executing:\nopen "
// + filename.replace(".gcm", "").replace(".sbml", "")
// .replace(".xml", "") + "_sg.dot" + "\n");
// exec.exec("open "
// + theFile.replace(".gcm", "").replace(".sbml",
// "").replace(
// ".xml", "") + "_sg.dot", null, work);
// }
// else {
// log.addText("Executing:\ndotty "
// + filename.replace(".gcm", "").replace(".sbml", "")
// .replace(".xml", "") + "_sg.dot" + "\n");
// exec.exec("dotty "
// + theFile.replace(".gcm", "").replace(".sbml",
// "").replace(
// ".xml", "") + "_sg.dot", null, work);
// }
// }
// }
// }
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("ProbGraph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
simTab
.setComponentAt(i,
new Graph(r2s, printer_track_quantity, outDir
.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results", printer_id,
outDir, "time", biomodelsim, null, log,
null, false, false));
simTab.getComponentAt(i).setName("ProbGraph");
}
}
}
}
time1 = System.nanoTime();
exitValue = 0;
}
else {
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.sim.command", "").equals("")) {
log.addText("Executing:\nreb2sac --target.encoding=" + sim + " " + filename
+ "\n");
time1 = System.nanoTime();
reb2sac = exec.exec("reb2sac --target.encoding=" + sim + " " + theFile,
null, work);
}
else {
String command = biosimrc.get("biosim.sim.command", "");
String fileStem = theFile.replaceAll(".xml", "");
fileStem = fileStem.replaceAll(".sbml", "");
command = command.replaceAll("filename", fileStem);
command = command.replaceAll("sim", sim);
log.addText(command + "\n");
time1 = System.nanoTime();
reb2sac = exec.exec(command, null, work);
}
}
}
String error = "";
try {
InputStream reb = reb2sac.getInputStream();
InputStreamReader isr = new InputStreamReader(reb);
BufferedReader br = new BufferedReader(isr);
// int count = 0;
String line;
double time = 0;
double oldTime = 0;
int runNum = 0;
int prog = 0;
while ((line = br.readLine()) != null) {
try {
if (line.contains("Time")) {
time = Double.parseDouble(line.substring(line.indexOf('=') + 1, line
.length()));
if (oldTime > time) {
runNum++;
}
oldTime = time;
time += (runNum * timeLimit);
double d = ((time * 100) / runTime);
String s = d + "";
double decimal = Double.parseDouble(s.substring(s.indexOf('.'), s
.length()));
if (decimal >= 0.5) {
prog = (int) (Math.ceil(d));
}
else {
prog = (int) (d);
}
}
}
catch (Exception e) {
}
progress.setValue(prog);
// if (steps > 0) {
// count++;
// progress.setValue(count);
// }
// log.addText(output);
}
InputStream reb2 = reb2sac.getErrorStream();
int read = reb2.read();
while (read != -1) {
error += (char) read;
read = reb2.read();
}
br.close();
isr.close();
reb.close();
reb2.close();
}
catch (Exception e) {
}
if (reb2sac != null) {
exitValue = reb2sac.waitFor();
long time2 = System.nanoTime();
long minutes;
long hours;
long days;
double secs = ((time2 - time1) / 1000000000.0);
long seconds = ((time2 - time1) / 1000000000);
secs = secs - seconds;
minutes = seconds / 60;
secs = seconds % 60 + secs;
hours = minutes / 60;
minutes = minutes % 60;
days = hours / 24;
hours = hours % 60;
String time;
String dayLabel;
String hourLabel;
String minuteLabel;
String secondLabel;
if (days == 1) {
dayLabel = " day ";
}
else {
dayLabel = " days ";
}
if (hours == 1) {
hourLabel = " hour ";
}
else {
hourLabel = " hours ";
}
if (minutes == 1) {
minuteLabel = " minute ";
}
else {
minuteLabel = " minutes ";
}
if (seconds == 1) {
secondLabel = " second";
}
else {
secondLabel = " seconds";
}
if (days != 0) {
time = days + dayLabel + hours + hourLabel + minutes + minuteLabel + secs
+ secondLabel;
}
else if (hours != 0) {
time = hours + hourLabel + minutes + minuteLabel + secs + secondLabel;
}
else if (minutes != 0) {
time = minutes + minuteLabel + secs + secondLabel;
}
else {
time = secs + secondLabel;
}
if (!error.equals("")) {
log.addText("Errors:\n" + error + "\n");
}
log.addText("Total Simulation Time: " + time + " for " + simName + "\n\n");
}
if (exitValue != 0) {
if (exitValue == 143) {
JOptionPane.showMessageDialog(BioSim.frame, "The simulation was"
+ " canceled by the user.", "Canceled Simulation",
JOptionPane.ERROR_MESSAGE);
}
else if (exitValue == 139) {
JOptionPane.showMessageDialog(BioSim.frame,
"The selected model is not a valid sbml file."
+ "\nYou must select an sbml file.", "Not An SBML File",
JOptionPane.ERROR_MESSAGE);
}
else {
JOptionPane.showMessageDialog(BioSim.frame, "Error In Execution!\n"
+ "Bad Return Value!\n" + "The reb2sac program returned " + exitValue
+ " as an exit value.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
if (nary.isSelected() && gcmEditor == null && !lhpn.isSelected() && naryRun == 1) {
}
else if (sbml.isSelected()) {
if (sbmlName != null && !sbmlName.trim().equals("")) {
if (!biomodelsim.updateOpenSBML(sbmlName)) {
biomodelsim.addTab(sbmlName, new SBML_Editor(root + separator
+ sbmlName, null, log, biomodelsim, null, null), "SBML Editor");
biomodelsim.addToTree(sbmlName);
}
else {
biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(sbmlName));
}
}
}
else if (lhpn.isSelected()) {
if (lhpnName != null && !lhpnName.trim().equals("")) {
if (!biomodelsim.updateOpenLHPN(lhpnName)) {
biomodelsim.addTab(lhpnName, new LHPNEditor(root, lhpnName, null,
biomodelsim, log), "LHPN Editor");
biomodelsim.addToTree(lhpnName);
}
else {
biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(lhpnName));
}
}
}
else if (dot.isSelected()) {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + out + ".dot" + "\n");
exec.exec("dotty " + out + ".dot", null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + out + ".dot\n");
exec.exec("open " + out + ".dot", null, work);
}
else {
log.addText("Executing:\ndotty " + directory + out + ".dot" + "\n");
exec.exec("dotty " + out + ".dot", null, work);
}
}
else if (xhtml.isSelected()) {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ngnome-open " + directory + out + ".xhtml" + "\n");
exec.exec("gnome-open " + out + ".xhtml", null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + out + ".xhtml" + "\n");
exec.exec("open " + out + ".xhtml", null, work);
}
else {
log
.addText("Executing:\ncmd /c start " + directory + out + ".xhtml"
+ "\n");
exec.exec("cmd /c start " + out + ".xhtml", null, work);
}
}
else if (usingSSA.isSelected()) {
if (!printer_id.equals("null.printer")) {
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("TSD Graph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0,
printer_id.length() - 8);
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
simTab
.setComponentAt(i,
new Graph(r2s, printer_track_quantity, outDir
.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results", printer_id,
outDir, "time", biomodelsim, null, log,
null, true, false));
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0,
printer_id.length() - 8);
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i)).readData(directory + separator
+ run, "deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i)).getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
simTab.getComponentAt(i).setName("TSD Graph");
}
}
if (simTab.getComponentAt(i).getName().equals("ProbGraph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
if (new File(filename.substring(0,
filename.length()
- filename.split(separator)[filename
.split(separator).length - 1].length())
+ "sim-rep.txt").exists()) {
simTab.setComponentAt(i,
new Graph(r2s, printer_track_quantity,
outDir.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results",
printer_id, outDir, "time", biomodelsim,
null, log, null, false, false));
simTab.getComponentAt(i).setName("ProbGraph");
}
}
}
}
}
}
else if (sim.equals("atacs")) {
log.addText("Executing:\natacs -T0.000001 -oqoflhsgllvA "
+ filename
.substring(0,
filename.length()
- filename.split(separator)[filename
.split(separator).length - 1].length())
+ "out.hse\n");
exec.exec("atacs -T0.000001 -oqoflhsgllvA out.hse", null, work);
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("ProbGraph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity,
outDir.split(separator)[outDir.split(separator).length - 1]
+ " simulation results", printer_id, outDir,
"time", biomodelsim, null, log, null, false, false));
simTab.getComponentAt(i).setName("ProbGraph");
}
}
}
// simTab.add("Probability Graph", new
// Graph(printer_track_quantity,
// outDir.split(separator)[outDir.split(separator).length -
// 1] + "
// simulation results",
// printer_id, outDir, "time", biomodelsim, null, log, null,
// false));
// simTab.getComponentAt(simTab.getComponentCount() -
// 1).setName("ProbGraph");
}
else {
if (!printer_id.equals("null.printer")) {
if (ode.isSelected()) {
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("TSD Graph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0, printer_id
.length() - 8);
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i))
.readData(directory + separator + run,
"deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
simTab.setComponentAt(i,
new Graph(r2s, printer_track_quantity,
outDir.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results",
printer_id, outDir, "time", biomodelsim,
null, log, null, true, false));
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0, printer_id
.length() - 8);
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i))
.readData(directory + separator + run,
"deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
simTab.getComponentAt(i).setName("TSD Graph");
}
}
if (simTab.getComponentAt(i).getName().equals("ProbGraph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
if (new File(filename.substring(0, filename.length()
- filename.split(separator)[filename
.split(separator).length - 1].length())
+ "sim-rep.txt").exists()) {
simTab.setComponentAt(i,
new Graph(r2s, printer_track_quantity, outDir
.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results", printer_id,
outDir, "time", biomodelsim, null, log,
null, false, false));
simTab.getComponentAt(i).setName("ProbGraph");
}
}
}
}
}
else if (monteCarlo.isSelected()) {
for (int i = 0; i < simTab.getComponentCount(); i++) {
if (simTab.getComponentAt(i).getName().equals("TSD Graph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0, printer_id
.length() - 8);
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i))
.readData(directory + separator + run,
"deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
simTab.setComponentAt(i,
new Graph(r2s, printer_track_quantity,
outDir.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results",
printer_id, outDir, "time", biomodelsim,
null, log, null, true, false));
boolean outputM = true;
boolean outputV = true;
boolean outputS = true;
boolean warning = false;
int num = -1;
String run = "run-1."
+ printer_id.substring(0, printer_id.length() - 8);
for (String f : work.list()) {
if (f.contains("mean")) {
outputM = false;
}
else if (f.contains("variance")) {
outputV = false;
}
else if (f.contains("standard_deviation")) {
outputS = false;
}
else if (f.contains("run-")) {
String getNumber = f.substring(4, f.length());
String number = "";
for (int j = 0; j < getNumber.length(); j++) {
if (Character.isDigit(getNumber.charAt(j))) {
number += getNumber.charAt(j);
}
else {
break;
}
}
if (num == -1) {
num = Integer.parseInt(number);
}
else if (Integer.parseInt(number) < num) {
num = Integer.parseInt(number);
}
run = "run-"
+ num
+ "."
+ printer_id.substring(0, printer_id
.length() - 8);
}
}
if (outputM) {
ArrayList<ArrayList<Double>> mean = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "average", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), mean);
p2.outputTSD(directory + separator + "mean.tsd");
}
if (outputV) {
ArrayList<ArrayList<Double>> var = ((Graph) simTab
.getComponentAt(i)).readData(directory
+ separator + run, "variance", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), var);
p2.outputTSD(directory + separator + "variance.tsd");
}
if (outputS) {
ArrayList<ArrayList<Double>> stddev = ((Graph) simTab
.getComponentAt(i))
.readData(directory + separator + run,
"deviation", direct, warning);
warning = ((Graph) simTab.getComponentAt(i))
.getWarning();
Parser p = new TSDParser(directory + separator + run,
warning);
warning = p.getWarning();
Parser p2 = new Parser(p.getSpecies(), stddev);
p2.outputTSD(directory + separator
+ "standard_deviation.tsd");
}
simTab.getComponentAt(i).setName("TSD Graph");
}
}
if (simTab.getComponentAt(i).getName().equals("ProbGraph")) {
if (simTab.getComponentAt(i) instanceof Graph) {
((Graph) simTab.getComponentAt(i)).refresh();
}
else {
if (new File(filename.substring(0, filename.length()
- filename.split(separator)[filename
.split(separator).length - 1].length())
+ "sim-rep.txt").exists()) {
simTab.setComponentAt(i,
new Graph(r2s, printer_track_quantity, outDir
.split(separator)[outDir
.split(separator).length - 1]
+ " simulation results", printer_id,
outDir, "time", biomodelsim, null, log,
null, false, false));
simTab.getComponentAt(i).setName("ProbGraph");
}
}
}
}
}
}
}
}
}
catch (InterruptedException e1) {
JOptionPane.showMessageDialog(BioSim.frame, "Error In Execution!",
"Error In Execution", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(BioSim.frame, "File I/O Error!", "File I/O Error",
JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
return exitValue;
}
/**
* This method is called if a button that cancels the simulation is pressed.
*/
public void actionPerformed(ActionEvent e) {
if (reb2sac != null) {
reb2sac.destroy();
}
if (sg != null) {
sg.stop();
}
}
}
| Changes made to remove ambiguous import statement.
| gui/src/reb2sac/Run.java | Changes made to remove ambiguous import statement. | <ide><path>ui/src/reb2sac/Run.java
<ide> import parser.*;
<ide>
<ide> import lhpn2sbml.gui.LHPNEditor;
<del>import lhpn2sbml.parser.*;
<add>import lhpn2sbml.parser.Abstraction;
<add>import lhpn2sbml.parser.LhpnFile;
<add>import lhpn2sbml.parser.Translator;
<ide>
<ide> import biomodelsim.*;
<ide> import gcm2sbml.gui.GCM2SBMLEditor; |
|
Java | apache-2.0 | 3bdc5c83f8d114ef80de3fffa4416975173e2cc3 | 0 | jnidzwetzki/bboxdb,jnidzwetzki/scalephant,jnidzwetzki/scalephant,jnidzwetzki/bboxdb,jnidzwetzki/bboxdb | package de.fernunihagen.dna.jkn.scalephant.distribution.resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import de.fernunihagen.dna.jkn.scalephant.distribution.membership.DistributedInstance;
public class RandomResourcePlacementStrategy implements ResourcePlacementStrategy {
/**
* The random generator
*/
protected final Random randomGenerator;
public RandomResourcePlacementStrategy() {
randomGenerator = new Random();
}
@Override
public DistributedInstance findSystemToAllocate(final Collection<DistributedInstance> systems) {
synchronized (systems) {
final List<DistributedInstance> elements = new ArrayList<DistributedInstance>(systems);
final int element = Math.abs(randomGenerator.nextInt()) % elements.size();
return elements.get(element);
}
}
}
| src/main/java/de/fernunihagen/dna/jkn/scalephant/distribution/resource/RandomResourcePlacementStrategy.java | package de.fernunihagen.dna.jkn.scalephant.distribution.resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import de.fernunihagen.dna.jkn.scalephant.distribution.membership.DistributedInstance;
public class RandomResourcePlacementStrategy implements ResourcePlacementStrategy {
/**
* The random generator
*/
protected final Random randomGenerator;
public RandomResourcePlacementStrategy() {
randomGenerator = new Random();
}
@Override
public DistributedInstance findSystemToAllocate(final Collection<DistributedInstance> systems) {
synchronized (systems) {
final List<DistributedInstance> elements = new ArrayList<DistributedInstance>(systems);
final int element = randomGenerator.nextInt() % elements.size();
return elements.get(element);
}
}
}
| Fixed placement strategy | src/main/java/de/fernunihagen/dna/jkn/scalephant/distribution/resource/RandomResourcePlacementStrategy.java | Fixed placement strategy | <ide><path>rc/main/java/de/fernunihagen/dna/jkn/scalephant/distribution/resource/RandomResourcePlacementStrategy.java
<ide>
<ide> synchronized (systems) {
<ide> final List<DistributedInstance> elements = new ArrayList<DistributedInstance>(systems);
<del> final int element = randomGenerator.nextInt() % elements.size();
<add> final int element = Math.abs(randomGenerator.nextInt()) % elements.size();
<ide> return elements.get(element);
<ide> }
<ide> |
|
JavaScript | mit | dd86e236bc1e2d49e75c4efa1c27f7042da7535c | 0 | jDataView/jBinary,npmcomponent/jDataView-jBinary,dark5un/jBinary,dark5un/jBinary | (function (global) {
'use strict';
// https://github.com/davidchambers/Base64.js (modified)
if (!('atob' in global) || !('btoa' in global)) {
// jshint:skipline
(function(){var t=global,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",n=function(){try{document.createElement("$")}catch(t){return t}}();t.btoa||(t.btoa=function(t){for(var o,e,a=0,c=r,f="";t.charAt(0|a)||(c="=",a%1);f+=c.charAt(63&o>>8-8*(a%1))){if(e=t.charCodeAt(a+=.75),e>255)throw n;o=o<<8|e}return f}),t.atob||(t.atob=function(t){if(t=t.replace(/=+$/,""),1==t.length%4)throw n;for(var o,e,a=0,c=0,f="";e=t.charAt(c++);~e&&(o=a%4?64*o+e:e,a++%4)?f+=String.fromCharCode(255&o>>(6&-2*a)):0)e=r.indexOf(e);return f})})();
}
// http://cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.min.js
if (!('JSON' in global)) {
// jshint:skipline
JSON={};(function(){function k(a){return a<10?"0"+a:a}function o(a){p.lastIndex=0;return p.test(a)?'"'+a.replace(p,function(a){var c=r[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function l(a,j){var c,d,h,m,g=e,f,b=j[a];b&&typeof b==="object"&&typeof b.toJSON==="function"&&(b=b.toJSON(a));typeof i==="function"&&(b=i.call(j,a,b));switch(typeof b){case "string":return o(b);case "number":return isFinite(b)?String(b):"null";case "boolean":case "null":return String(b);case "object":if(!b)return"null";e+=n;f=[];if(Object.prototype.toString.apply(b)==="[object Array]"){m=b.length;for(c=0;c<m;c+=1)f[c]=l(c,b)||"null";h=f.length===0?"[]":e?"[\n"+e+f.join(",\n"+e)+"\n"+g+"]":"["+f.join(",")+"]";e=g;return h}if(i&&typeof i==="object"){m=i.length;for(c=0;c<m;c+=1)typeof i[c]==="string"&&(d=i[c],(h=l(d,b))&&f.push(o(d)+(e?": ":":")+h))}else for(d in b)Object.prototype.hasOwnProperty.call(b,d)&&(h=l(d,b))&&f.push(o(d)+(e?": ":":")+h);h=f.length===0?"{}":e?"{\n"+e+f.join(",\n"+e)+"\n"+g+"}":"{"+f.join(",")+"}";e=g;return h}}if(typeof Date.prototype.toJSON!=="function")Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+k(this.getUTCMonth()+1)+"-"+k(this.getUTCDate())+"T"+k(this.getUTCHours())+":"+k(this.getUTCMinutes())+":"+k(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()};var q=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,p=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,e,n,r={"\u0008":"\\b","\t":"\\t","\n":"\\n","\u000c":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},i;if(typeof JSON.stringify!=="function")JSON.stringify=function(a,j,c){var d;n=e="";if(typeof c==="number")for(d=0;d<c;d+=1)n+=" ";else typeof c==="string"&&(n=c);if((i=j)&&typeof j!=="function"&&(typeof j!=="object"||typeof j.length!=="number"))throw Error("JSON.stringify");return l("",{"":a})};if(typeof JSON.parse!=="function")JSON.parse=function(a,e){function c(a,d){var g,f,b=a[d];if(b&&typeof b==="object")for(g in b)Object.prototype.hasOwnProperty.call(b,g)&&(f=c(b,g),f!==void 0?b[g]=f:delete b[g]);return e.call(a,d,b)}var d,a=String(a);q.lastIndex=0;q.test(a)&&(a=a.replace(q,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)}));if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return d=eval("("+a+")"),typeof e==="function"?c({"":d},""):d;throw new SyntaxError("JSON.parse");}})();
}
var hasRequire = typeof require === 'function';
var jDataView;
function extend(obj) {
for (var i = 1, length = arguments.length; i < length; ++i) {
var source = arguments[i];
for (var prop in source) {
if (source[prop] !== undefined) {
obj[prop] = source[prop];
}
}
}
return obj;
}
var _inherit = Object.create || function (obj) {
var ClonedObject = function () {};
ClonedObject.prototype = obj;
return new ClonedObject();
};
function inherit(obj) {
arguments[0] = _inherit(obj);
return extend.apply(null, arguments);
}
function toValue(obj, binary, value) {
return value instanceof Function ? value.call(obj, binary.contexts[0]) : value;
}
function jBinary(view, typeSet) {
/* jshint validthis:true */
if (!(view instanceof jDataView)) {
view = new jDataView(view, undefined, undefined, typeSet ? typeSet['jBinary.littleEndian'] : undefined);
}
if (!(this instanceof jBinary)) {
return new jBinary(view, typeSet);
}
this.view = view;
this.view.seek(0);
this._bitShift = 0;
this.contexts = [];
if (typeSet) {
this.typeSet = proto.typeSet.isPrototypeOf(typeSet) ? typeSet : inherit(proto.typeSet, typeSet);
this.cacheKey = this._getCached(typeSet, function () { return proto.cacheKey + '.' + (++proto.id) }, true);
}
}
var proto = jBinary.prototype;
proto.cacheKey = 'jBinary.Cache';
proto.id = 0;
var defineProperty = Object.defineProperty;
if (defineProperty) {
// this is needed to detect broken Object.defineProperty in IE8:
try {
defineProperty({}, 'x', {});
} catch (e) {
defineProperty = null;
}
}
if (!defineProperty) {
defineProperty = function (obj, key, descriptor, allowVisible) {
if (allowVisible) {
obj[key] = descriptor.value;
}
};
}
proto._getCached = function (obj, valueAccessor, allowVisible) {
if (!obj.hasOwnProperty(this.cacheKey)) {
var value = valueAccessor.call(this, obj);
defineProperty(obj, this.cacheKey, {value: value}, allowVisible);
return value;
} else {
return obj[this.cacheKey];
}
};
proto.getContext = function (filter) {
switch (typeof filter) {
case 'undefined':
filter = 0;
/* falls through */
case 'number':
return this.contexts[filter];
case 'string':
return this.getContext(function (context) { return filter in context });
case 'function':
for (var i = 0, length = this.contexts.length; i < length; i++) {
var context = this.contexts[i];
if (filter.call(this, context)) {
return context;
}
}
return;
}
};
proto.inContext = function (newContext, callback) {
this.contexts.unshift(newContext);
var result = callback.call(this);
this.contexts.shift();
return result;
};
jBinary.Type = function (config) {
return inherit(jBinary.Type.prototype, config);
};
jBinary.Type.prototype = {
inherit: function (args, getType) {
if (!this.setParams && !this.resolve && (!this.params || args.length === 0)) {
return this;
}
var type = inherit(this);
if (type.params) {
for (var i = 0, length = Math.min(type.params.length, args.length); i < length; i++) {
type[this.params[i]] = args[i];
}
type.params = null;
}
if (type.setParams) {
type.setParams.apply(type, args || []);
type.setParams = null;
}
if (type.resolve) {
type.resolve(getType);
type.resolve = null;
}
return type;
},
createProperty: function (binary) {
return inherit(this, {binary: binary});
},
toValue: function (val, allowResolve) {
if (allowResolve !== false && typeof val === 'string') {
return this.binary.getContext(val)[val];
}
return toValue(this, this.binary, val);
}
};
jBinary.Template = function (config) {
return inherit(jBinary.Template.prototype, config, {
createProperty: function (binary) {
var property = (config.createProperty || jBinary.Template.prototype.createProperty).apply(this, arguments);
if (property.getBaseType) {
property.baseType = property.binary.getType(property.getBaseType(property.binary.contexts[0]));
}
return property;
}
});
};
jBinary.Template.prototype = inherit(jBinary.Type.prototype, {
resolve: function (getType) {
if (this.baseType) {
this.baseType = getType(this.baseType);
}
},
baseRead: function () {
return this.binary.read(this.baseType);
},
baseWrite: function (value) {
return this.binary.write(this.baseType, value);
}
});
jBinary.Template.prototype.read = jBinary.Template.prototype.baseRead;
jBinary.Template.prototype.write = jBinary.Template.prototype.baseWrite;
proto.typeSet = {
'extend': jBinary.Type({
setParams: function () {
this.parts = arguments;
},
resolve: function (getType) {
var parts = this.parts, length = parts.length, partTypes = new Array(length);
for (var i = 0; i < length; i++) {
partTypes[i] = getType(parts[i]);
}
this.parts = partTypes;
},
read: function () {
var parts = this.parts, obj = this.binary.read(parts[0]);
this.binary.inContext(obj, function () {
for (var i = 1, length = parts.length; i < length; i++) {
extend(obj, this.read(parts[i]));
}
});
return obj;
},
write: function (obj) {
var parts = this.parts;
this.binary.inContext(obj, function () {
for (var i = 0, length = parts.length; i < length; i++) {
this.write(parts[i], obj);
}
});
}
}),
'enum': jBinary.Template({
params: ['baseType', 'matches'],
setParams: function (baseType, matches) {
this.backMatches = {};
for (var key in matches) {
this.backMatches[matches[key]] = key;
}
},
read: function () {
var value = this.baseRead();
return value in this.matches ? this.matches[value] : value;
},
write: function (value) {
this.baseWrite(value in this.backMatches ? this.backMatches[value] : value);
}
}),
'string': jBinary.Template({
params: ['length', 'encoding'],
read: function () {
return this.binary.view.getString(this.toValue(this.length), undefined, this.encoding);
},
write: function (value) {
this.binary.view.writeString(value, this.encoding);
}
}),
'string0': jBinary.Type({
params: ['length', 'encoding'],
read: function () {
var view = this.binary.view, maxLength = this.length;
if (maxLength === undefined) {
var startPos = view.tell(), length = 0, code;
maxLength = view.byteLength - startPos;
while (length < maxLength && (code = view.getUint8())) {
length++;
}
var string = view.getString(length, startPos, this.encoding);
if (length < maxLength) {
view.skip(1);
}
return string;
} else {
return view.getString(maxLength, undefined, this.encoding).replace(/\0.*$/, '');
}
},
write: function (value) {
var view = this.binary.view, zeroLength = this.length === undefined ? 1 : this.length - value.length;
view.writeString(value, undefined, this.encoding);
if (zeroLength > 0) {
view.writeUint8(0);
view.skip(zeroLength - 1);
}
}
}),
'array': jBinary.Template({
params: ['baseType', 'length'],
read: function (context) {
var length = this.toValue(this.length);
if (this.baseType === proto.typeSet.uint8) {
return this.binary.view.getBytes(length, undefined, true, true);
}
var results;
if (length !== undefined) {
results = new Array(length);
for (var i = 0; i < length; i++) {
results[i] = this.baseRead(context);
}
} else {
var end = this.binary.view.byteLength;
results = [];
while (this.binary.tell() < end) {
results.push(this.baseRead(context));
}
}
return results;
},
write: function (values, context) {
if (this.baseType === proto.typeSet.uint8) {
return this.binary.view.writeBytes(values);
}
for (var i = 0, length = values.length; i < length; i++) {
this.baseWrite(values[i], context);
}
}
}),
'object': jBinary.Type({
params: ['structure', 'proto'],
resolve: function (getType) {
var structure = {};
for (var key in this.structure) {
structure[key] =
!(this.structure[key] instanceof Function)
? getType(this.structure[key])
: this.structure[key];
}
this.structure = structure;
},
read: function () {
var self = this, structure = this.structure, output = this.proto ? inherit(this.proto) : {};
this.binary.inContext(output, function () {
for (var key in structure) {
var value = !(structure[key] instanceof Function)
? this.read(structure[key])
: structure[key].call(self, this.contexts[0]);
// skipping undefined call results (useful for 'if' statement)
if (value !== undefined) {
output[key] = value;
}
}
});
return output;
},
write: function (data) {
var self = this, structure = this.structure;
this.binary.inContext(data, function () {
for (var key in structure) {
if (!(structure[key] instanceof Function)) {
this.write(structure[key], data[key]);
} else {
data[key] = structure[key].call(self, this.contexts[0]);
}
}
});
}
}),
'bitfield': jBinary.Type({
params: ['bitSize'],
read: function () {
var bitSize = this.bitSize,
binary = this.binary,
fieldValue = 0;
if (binary._bitShift < 0 || binary._bitShift >= 8) {
var byteShift = binary._bitShift >> 3; // Math.floor(_bitShift / 8)
binary.skip(byteShift);
binary._bitShift &= 7; // _bitShift + 8 * Math.floor(_bitShift / 8)
}
if (binary._bitShift > 0 && bitSize >= 8 - binary._bitShift) {
fieldValue = binary.view.getUint8() & ~(-1 << (8 - binary._bitShift));
bitSize -= 8 - binary._bitShift;
binary._bitShift = 0;
}
while (bitSize >= 8) {
fieldValue = binary.view.getUint8() | (fieldValue << 8);
bitSize -= 8;
}
if (bitSize > 0) {
fieldValue = ((binary.view.getUint8() >>> (8 - (binary._bitShift + bitSize))) & ~(-1 << bitSize)) | (fieldValue << bitSize);
binary._bitShift += bitSize - 8; // passing negative value for next pass
}
return fieldValue >>> 0;
},
write: function (value) {
var bitSize = this.bitSize,
binary = this.binary,
pos,
curByte;
if (binary._bitShift < 0 || binary._bitShift >= 8) {
var byteShift = binary._bitShift >> 3; // Math.floor(_bitShift / 8)
binary.skip(byteShift);
binary._bitShift &= 7; // _bitShift + 8 * Math.floor(_bitShift / 8)
}
if (binary._bitShift > 0 && bitSize >= 8 - binary._bitShift) {
pos = binary.tell();
curByte = binary.view.getUint8(pos) & (-1 << (8 - binary._bitShift));
curByte |= value >>> (bitSize - (8 - binary._bitShift));
binary.view.setUint8(pos, curByte);
bitSize -= 8 - binary._bitShift;
binary._bitShift = 0;
}
while (bitSize >= 8) {
binary.view.writeUint8((value >>> (bitSize - 8)) & 0xff);
bitSize -= 8;
}
if (bitSize > 0) {
pos = binary.tell();
curByte = binary.view.getUint8(pos) & ~(~(-1 << bitSize) << (8 - (binary._bitShift + bitSize)));
curByte |= (value & ~(-1 << bitSize)) << (8 - (binary._bitShift + bitSize));
binary.view.setUint8(pos, curByte);
binary._bitShift += bitSize - 8; // passing negative value for next pass
}
}
}),
'if': jBinary.Template({
params: ['condition', 'trueType', 'falseType'],
resolve: function (getType) {
this.trueType = getType(this.trueType);
this.falseType = getType(this.falseType);
},
getBaseType: function (context) {
return this.toValue(this.condition) ? this.trueType : this.falseType;
}
}),
'if_not': jBinary.Template({
setParams: function (condition, falseType, trueType) {
this.baseType = ['if', condition, trueType, falseType];
}
}),
'const': jBinary.Template({
params: ['baseType', 'value', 'strict'],
read: function () {
var value = this.baseRead();
if (this.strict && value !== this.value) {
if (this.strict instanceof Function) {
return this.strict(value);
} else {
throw new TypeError('Unexpected value.');
}
}
return value;
},
write: function (value) {
this.baseWrite((this.strict || value === undefined) ? this.value : value);
}
}),
'skip': jBinary.Type({
setParams: function (length) {
this.read = this.write = function () {
this.binary.view.skip(this.toValue(length));
};
}
}),
'blob': jBinary.Type({
params: ['length'],
read: function () {
return this.binary.view.getBytes(this.toValue(this.length));
},
write: function (bytes) {
this.binary.view.writeBytes(bytes, true);
}
}),
'binary': jBinary.Template({
params: ['length', 'typeSet'],
read: function () {
var startPos = this.binary.tell();
var endPos = this.binary.skip(this.toValue(this.length));
var view = this.binary.view.slice(startPos, endPos);
return new jBinary(view, this.typeSet);
},
write: function (binary) {
this.binary.write('blob', binary instanceof jBinary ? binary.read('blob', 0) : binary);
}
})
};
var dataTypes = [
'Uint8',
'Uint16',
'Uint32',
'Uint64',
'Int8',
'Int16',
'Int32',
'Int64',
'Float32',
'Float64',
'Char'
];
var simpleType = jBinary.Type({
params: ['littleEndian'],
read: function () {
return this.binary.view['get' + this.dataType](undefined, this.littleEndian);
},
write: function (value) {
this.binary.view['write' + this.dataType](value, this.littleEndian);
}
});
for (var i = 0, length = dataTypes.length; i < length; i++) {
var dataType = dataTypes[i];
proto.typeSet[dataType.toLowerCase()] = inherit(simpleType, {dataType: dataType});
}
extend(proto.typeSet, {
'byte': proto.typeSet.uint8,
'float': proto.typeSet.float32,
'double': proto.typeSet.float64
});
proto.toValue = function (value) {
return toValue(this, this, value);
};
proto.seek = function (position, callback) {
position = this.toValue(position);
if (callback !== undefined) {
var oldPos = this.view.tell();
this.view.seek(position);
var result = callback.call(this);
this.view.seek(oldPos);
return result;
} else {
return this.view.seek(position);
}
};
proto.tell = function () {
return this.view.tell();
};
proto.skip = function (offset, callback) {
return this.seek(this.tell() + this.toValue(offset), callback);
};
proto.getType = function (type, args) {
switch (typeof type) {
case 'string':
if (!(type in this.typeSet)) {
throw new ReferenceError('Unknown type `' + type + '`');
}
return this.getType(this.typeSet[type], args);
case 'number':
return this.getType(proto.typeSet.bitfield, [type]);
case 'object':
if (type instanceof jBinary.Type) {
var binary = this;
return type.inherit(args || [], function (type) { return binary.getType(type) });
} else {
var isArray = type instanceof Array;
return this._getCached(
type,
(
isArray
? function (type) { return this.getType(type[0], type.slice(1)) }
: function (structure) { return this.getType(proto.typeSet.object, [structure]) }
),
isArray
);
}
}
};
proto.createProperty = function (type) {
return this.getType(type).createProperty(this);
};
proto._action = function (type, offset, callback) {
if (type === undefined) {
return;
}
return offset !== undefined ? this.seek(offset, callback) : callback.call(this);
};
proto.read = function (type, offset) {
return this._action(
type,
offset,
function () { return this.createProperty(type).read(this.contexts[0]) }
);
};
proto.write = function (type, data, offset) {
this._action(
type,
offset,
function () { this.createProperty(type).write(data, this.contexts[0]) }
);
};
proto._toURI =
('URL' in global && 'createObjectURL' in URL)
? function (type) {
var data = this.seek(0, function () { return this.view.getBytes() });
return URL.createObjectURL(new Blob([data], {type: type}));
}
: function (type) {
var string = this.seek(0, function () { return this.view.getString(undefined, undefined, this.view._isNodeBuffer ? 'base64' : 'binary') });
return 'data:' + type + ';base64,' + (this.view._isNodeBuffer ? string : btoa(string));
};
proto.toURI = function (mimeType) {
return this._toURI(mimeType || this.typeSet['jBinary.mimeType']);
};
proto.slice = function (start, end, forceCopy) {
return new jBinary(this.view.slice(start, end, forceCopy), this.typeSet);
};
jBinary.load = function (source, typeSet, callback) {
function withTypeSet(typeSet) {
jBinary.loadData(source, function (err, data) {
err ? callback(err) : callback(null, new jBinary(data, typeSet));
});
}
if (arguments.length < 3) {
callback = typeSet;
var srcInfo;
if ('Blob' in global && source instanceof Blob) {
srcInfo = {mimeType: source.type};
if (source instanceof File) {
srcInfo.fileName = source.name;
}
} else
if (typeof source === 'string') {
var dataParts = source.match(/^data:(.+?)(;base64)?,/);
srcInfo = dataParts ? {mimeType: dataParts[1]} : {fileName: source};
}
if (srcInfo) {
repo.getAssociation(srcInfo, withTypeSet);
} else {
withTypeSet();
}
} else {
typeof typeSet === 'string' ? repo(typeSet, withTypeSet) : withTypeSet(typeSet);
}
};
jBinary.loadData = function (source, callback) {
if ('Blob' in global && source instanceof Blob) {
var reader = new FileReader();
reader.onload = reader.onerror = function() { callback(this.error, this.result) };
reader.readAsArrayBuffer(source);
} else {
if (typeof source === 'object') {
if (hasRequire && source instanceof require('stream').Readable) {
var buffers = [];
source
.on('readable', function () { buffers.push(this.read()) })
.on('end', function () { callback(null, Buffer.concat(buffers)) })
.on('error', callback);
return;
}
}
if (typeof source !== 'string') {
return callback(new TypeError('Unsupported source type.'));
}
var dataParts = source.match(/^data:(.+?)(;base64)?,(.*)$/);
if (dataParts) {
var isBase64 = dataParts[2],
content = dataParts[3];
try {
callback(
null,
(
(isBase64 && jDataView.prototype.compatibility.NodeBuffer)
? new Buffer(content, 'base64')
: (isBase64 ? atob : decodeURIComponent)(content)
)
);
} catch (e) {
callback(e);
}
} else
if ('XMLHttpRequest' in global) {
var xhr = new XMLHttpRequest();
xhr.open('GET', source, true);
// new browsers (XMLHttpRequest2-compliant)
if ('responseType' in xhr) {
xhr.responseType = 'arraybuffer';
}
// old browsers (XMLHttpRequest-compliant)
else if ('overrideMimeType' in xhr) {
xhr.overrideMimeType('text/plain; charset=x-user-defined');
}
// IE9 (Microsoft.XMLHTTP-compliant)
else {
xhr.setRequestHeader('Accept-Charset', 'x-user-defined');
}
// shim for onload for old IE
if (!('onload' in xhr)) {
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
this.onload();
}
};
}
xhr.onload = function() {
if (this.status !== 0 && this.status !== 200) {
return callback(new Error('HTTP Error #' + this.status + ': ' + this.statusText));
}
// emulating response field for IE9
if (!('response' in this)) {
this.response = new VBArray(this.responseBody).toArray();
}
callback(null, this.response);
};
xhr.send();
} else
if (hasRequire) {
if (/^(https?):\/\//.test(source)) {
require('request').get({
uri: source,
encoding: null
}, function (error, response, body) {
if (!error && response.statusCode !== 200) {
var statusText = require('http').STATUS_CODES[response.statusCode];
error = new Error('HTTP Error #' + response.statusCode + ': ' + statusText);
}
callback(error, body);
});
} else {
require('fs').readFile(source, callback);
}
} else {
callback(new TypeError('Unsupported source type.'));
}
}
};
var getScript = (function () {
if ('window' in global && 'document' in global && document === window.document) {
var head = document.head || document.getElementsByTagName('head')[0];
return function (url, callback) {
var script = document.createElement('script');
script.src = url;
script.defer = true;
if (callback) {
if ('onreadystatechange' in script) {
script.onreadystatechange = function () {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
this.onreadystatechange = null;
// delay to wait until script is executed
setTimeout(function () { callback.call(script) }, 0);
}
};
script.onreadystatechange();
} else {
script.onload = script.onerror = callback;
}
}
head.appendChild(script);
};
} else {
var request = require('request');
return function (url, callback) {
request.get(url, function (error, response, body) {
if (!error && response.statusCode === 200) {
// yes, eval is evil, but we are in Node.js and in strict mode, so let's use this
// jshint:skipline
eval(body);
}
if (callback) {
callback();
}
});
};
}
})();
// helper function for common callback from multiple sources
function whenAll(count, each, done) {
var results = new Array(count);
for (var i = 0; i < count; i++) {
(function () {
var index = i;
each(index, function (result) {
results[index] = result;
if (--count === 0) {
done(results);
}
});
})();
}
}
// "require"-like function+storage for standard file formats from https://github.com/jDataView/jBinary.Repo
var repo = jBinary.Repo = function (names, callback) {
if (!(names instanceof Array)) {
names = [names];
}
whenAll(names.length, function (i, callback) {
var name = names[i], upperName = name.toUpperCase();
if (upperName in repo) {
callback(repo[upperName]);
} else {
getScript('https://rawgithub.com/jDataView/jBinary.Repo/gh-pages/$/$.js'.replace(/\$/g, name.toLowerCase()), function () {
callback(repo[upperName]);
});
}
}, function (typeSets) {
callback.apply(repo, typeSets);
});
};
repo.getAssociations = function (callback) {
// lazy loading data by replacing `jBinary.Repo.getAssociations` itself
getScript('https://rawgithub.com/jDataView/jBinary.Repo/gh-pages/associations.js', function () {
repo.getAssociations(callback);
});
};
repo.getAssociation = function (source, _callback) {
var callback = function (typeSetName) {
repo(typeSetName, _callback);
};
repo.getAssociations(function (assoc) {
if (source.fileName) {
// extracting only longest extension part
var longExtension = source.fileName.match(/^(.*\/)?.*?(\.|$)(.*)$/)[3].toLowerCase();
if (longExtension) {
var fileParts = longExtension.split('.');
// trying everything from longest possible extension to shortest one
for (var i = 0, length = fileParts.length; i < length; i++) {
var extension = fileParts.slice(i).join('.'),
typeSetName = assoc.extensions[extension];
if (typeSetName) {
return callback(typeSetName);
}
}
}
}
if (source.mimeType) {
var typeSetName = assoc.mimeTypes[source.mimeType];
if (typeSetName) {
return callback(typeSetName);
}
}
_callback();
});
};
if (typeof module === 'object' && module && typeof module.exports === 'object') {
jDataView = require('jDataView');
module.exports = jBinary;
} else
if (typeof define === 'function' && define.amd) {
define('jBinary', ['jDataView'], function (_jDataView) {
jDataView = _jDataView;
return jBinary;
});
} else {
jDataView = global.jDataView;
global.jBinary = jBinary;
}
jDataView.prototype.toBinary = function (typeSet) {
return new jBinary(this, typeSet);
};
})((function () { /* jshint strict: false */ return this })());
| src/jBinary.js | (function (global) {
'use strict';
// https://github.com/davidchambers/Base64.js (modified)
if (!('atob' in global) || !('btoa' in global)) {
// jshint:skipline
(function(){var t=global,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",n=function(){try{document.createElement("$")}catch(t){return t}}();t.btoa||(t.btoa=function(t){for(var o,e,a=0,c=r,f="";t.charAt(0|a)||(c="=",a%1);f+=c.charAt(63&o>>8-8*(a%1))){if(e=t.charCodeAt(a+=.75),e>255)throw n;o=o<<8|e}return f}),t.atob||(t.atob=function(t){if(t=t.replace(/=+$/,""),1==t.length%4)throw n;for(var o,e,a=0,c=0,f="";e=t.charAt(c++);~e&&(o=a%4?64*o+e:e,a++%4)?f+=String.fromCharCode(255&o>>(6&-2*a)):0)e=r.indexOf(e);return f})})();
}
// http://cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.min.js
if (!('JSON' in global)) {
// jshint:skipline
JSON={};(function(){function k(a){return a<10?"0"+a:a}function o(a){p.lastIndex=0;return p.test(a)?'"'+a.replace(p,function(a){var c=r[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function l(a,j){var c,d,h,m,g=e,f,b=j[a];b&&typeof b==="object"&&typeof b.toJSON==="function"&&(b=b.toJSON(a));typeof i==="function"&&(b=i.call(j,a,b));switch(typeof b){case "string":return o(b);case "number":return isFinite(b)?String(b):"null";case "boolean":case "null":return String(b);case "object":if(!b)return"null";e+=n;f=[];if(Object.prototype.toString.apply(b)==="[object Array]"){m=b.length;for(c=0;c<m;c+=1)f[c]=l(c,b)||"null";h=f.length===0?"[]":e?"[\n"+e+f.join(",\n"+e)+"\n"+g+"]":"["+f.join(",")+"]";e=g;return h}if(i&&typeof i==="object"){m=i.length;for(c=0;c<m;c+=1)typeof i[c]==="string"&&(d=i[c],(h=l(d,b))&&f.push(o(d)+(e?": ":":")+h))}else for(d in b)Object.prototype.hasOwnProperty.call(b,d)&&(h=l(d,b))&&f.push(o(d)+(e?": ":":")+h);h=f.length===0?"{}":e?"{\n"+e+f.join(",\n"+e)+"\n"+g+"}":"{"+f.join(",")+"}";e=g;return h}}if(typeof Date.prototype.toJSON!=="function")Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+k(this.getUTCMonth()+1)+"-"+k(this.getUTCDate())+"T"+k(this.getUTCHours())+":"+k(this.getUTCMinutes())+":"+k(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()};var q=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,p=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,e,n,r={"\u0008":"\\b","\t":"\\t","\n":"\\n","\u000c":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},i;if(typeof JSON.stringify!=="function")JSON.stringify=function(a,j,c){var d;n=e="";if(typeof c==="number")for(d=0;d<c;d+=1)n+=" ";else typeof c==="string"&&(n=c);if((i=j)&&typeof j!=="function"&&(typeof j!=="object"||typeof j.length!=="number"))throw Error("JSON.stringify");return l("",{"":a})};if(typeof JSON.parse!=="function")JSON.parse=function(a,e){function c(a,d){var g,f,b=a[d];if(b&&typeof b==="object")for(g in b)Object.prototype.hasOwnProperty.call(b,g)&&(f=c(b,g),f!==void 0?b[g]=f:delete b[g]);return e.call(a,d,b)}var d,a=String(a);q.lastIndex=0;q.test(a)&&(a=a.replace(q,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)}));if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return d=eval("("+a+")"),typeof e==="function"?c({"":d},""):d;throw new SyntaxError("JSON.parse");}})();
}
var hasRequire = typeof require === 'function';
var jDataView;
function extend(obj) {
for (var i = 1, length = arguments.length; i < length; ++i) {
var source = arguments[i];
for (var prop in source) {
if (source[prop] !== undefined) {
obj[prop] = source[prop];
}
}
}
return obj;
}
var _inherit = Object.create || function (obj) {
var ClonedObject = function () {};
ClonedObject.prototype = obj;
return new ClonedObject();
};
function inherit(obj) {
arguments[0] = _inherit(obj);
return extend.apply(null, arguments);
}
function toValue(obj, binary, value) {
return value instanceof Function ? value.call(obj, binary.contexts[0]) : value;
}
function jBinary(view, typeSet) {
/* jshint validthis:true */
if (!(view instanceof jDataView)) {
view = new jDataView(view, undefined, undefined, typeSet ? typeSet['jBinary.littleEndian'] : undefined);
}
if (!(this instanceof jBinary)) {
return new jBinary(view, typeSet);
}
this.view = view;
this.view.seek(0);
this._bitShift = 0;
this.contexts = [];
if (typeSet) {
this.typeSet = inherit(proto.typeSet, typeSet);
this.cacheKey = this._getCached(typeSet, function () { return proto.cacheKey + '.' + (++proto.id) }, true);
}
}
var proto = jBinary.prototype;
proto.cacheKey = 'jBinary.Cache';
proto.id = 0;
var defineProperty = Object.defineProperty;
if (defineProperty) {
// this is needed to detect broken Object.defineProperty in IE8:
try {
defineProperty({}, 'x', {});
} catch (e) {
defineProperty = null;
}
}
if (!defineProperty) {
defineProperty = function (obj, key, descriptor, allowVisible) {
if (allowVisible) {
obj[key] = descriptor.value;
}
};
}
proto._getCached = function (obj, valueAccessor, allowVisible) {
if (!obj.hasOwnProperty(this.cacheKey)) {
var value = valueAccessor.call(this, obj);
defineProperty(obj, this.cacheKey, {value: value}, allowVisible);
return value;
} else {
return obj[this.cacheKey];
}
};
proto.getContext = function (filter) {
switch (typeof filter) {
case 'undefined':
filter = 0;
/* falls through */
case 'number':
return this.contexts[filter];
case 'string':
return this.getContext(function (context) { return filter in context });
case 'function':
for (var i = 0, length = this.contexts.length; i < length; i++) {
var context = this.contexts[i];
if (filter.call(this, context)) {
return context;
}
}
return;
}
};
proto.inContext = function (newContext, callback) {
this.contexts.unshift(newContext);
var result = callback.call(this);
this.contexts.shift();
return result;
};
jBinary.Type = function (config) {
return inherit(jBinary.Type.prototype, config);
};
jBinary.Type.prototype = {
inherit: function (args, getType) {
if (!this.setParams && !this.resolve && (!this.params || args.length === 0)) {
return this;
}
var type = inherit(this);
if (type.params) {
for (var i = 0, length = Math.min(type.params.length, args.length); i < length; i++) {
type[this.params[i]] = args[i];
}
type.params = null;
}
if (type.setParams) {
type.setParams.apply(type, args || []);
type.setParams = null;
}
if (type.resolve) {
type.resolve(getType);
type.resolve = null;
}
return type;
},
createProperty: function (binary) {
return inherit(this, {binary: binary});
},
toValue: function (val, allowResolve) {
if (allowResolve !== false && typeof val === 'string') {
return this.binary.getContext(val)[val];
}
return toValue(this, this.binary, val);
}
};
jBinary.Template = function (config) {
return inherit(jBinary.Template.prototype, config, {
createProperty: function (binary) {
var property = (config.createProperty || jBinary.Template.prototype.createProperty).apply(this, arguments);
if (property.getBaseType) {
property.baseType = property.binary.getType(property.getBaseType(property.binary.contexts[0]));
}
return property;
}
});
};
jBinary.Template.prototype = inherit(jBinary.Type.prototype, {
resolve: function (getType) {
if (this.baseType) {
this.baseType = getType(this.baseType);
}
},
baseRead: function () {
return this.binary.read(this.baseType);
},
baseWrite: function (value) {
return this.binary.write(this.baseType, value);
}
});
jBinary.Template.prototype.read = jBinary.Template.prototype.baseRead;
jBinary.Template.prototype.write = jBinary.Template.prototype.baseWrite;
proto.typeSet = {
'extend': jBinary.Type({
setParams: function () {
this.parts = arguments;
},
resolve: function (getType) {
var parts = this.parts, length = parts.length, partTypes = new Array(length);
for (var i = 0; i < length; i++) {
partTypes[i] = getType(parts[i]);
}
this.parts = partTypes;
},
read: function () {
var parts = this.parts, obj = this.binary.read(parts[0]);
this.binary.inContext(obj, function () {
for (var i = 1, length = parts.length; i < length; i++) {
extend(obj, this.read(parts[i]));
}
});
return obj;
},
write: function (obj) {
var parts = this.parts;
this.binary.inContext(obj, function () {
for (var i = 0, length = parts.length; i < length; i++) {
this.write(parts[i], obj);
}
});
}
}),
'enum': jBinary.Template({
params: ['baseType', 'matches'],
setParams: function (baseType, matches) {
this.backMatches = {};
for (var key in matches) {
this.backMatches[matches[key]] = key;
}
},
read: function () {
var value = this.baseRead();
return value in this.matches ? this.matches[value] : value;
},
write: function (value) {
this.baseWrite(value in this.backMatches ? this.backMatches[value] : value);
}
}),
'string': jBinary.Template({
params: ['length', 'encoding'],
read: function () {
return this.binary.view.getString(this.toValue(this.length), undefined, this.encoding);
},
write: function (value) {
this.binary.view.writeString(value, this.encoding);
}
}),
'string0': jBinary.Type({
params: ['length', 'encoding'],
read: function () {
var view = this.binary.view, maxLength = this.length;
if (maxLength === undefined) {
var startPos = view.tell(), length = 0, code;
maxLength = view.byteLength - startPos;
while (length < maxLength && (code = view.getUint8())) {
length++;
}
var string = view.getString(length, startPos, this.encoding);
if (length < maxLength) {
view.skip(1);
}
return string;
} else {
return view.getString(maxLength, undefined, this.encoding).replace(/\0.*$/, '');
}
},
write: function (value) {
var view = this.binary.view, zeroLength = this.length === undefined ? 1 : this.length - value.length;
view.writeString(value, undefined, this.encoding);
if (zeroLength > 0) {
view.writeUint8(0);
view.skip(zeroLength - 1);
}
}
}),
'array': jBinary.Template({
params: ['baseType', 'length'],
read: function (context) {
var length = this.toValue(this.length);
if (this.baseType === proto.typeSet.uint8) {
return this.binary.view.getBytes(length, undefined, true, true);
}
var results;
if (length !== undefined) {
results = new Array(length);
for (var i = 0; i < length; i++) {
results[i] = this.baseRead(context);
}
} else {
var end = this.binary.view.byteLength;
results = [];
while (this.binary.tell() < end) {
results.push(this.baseRead(context));
}
}
return results;
},
write: function (values, context) {
if (this.baseType === proto.typeSet.uint8) {
return this.binary.view.writeBytes(values);
}
for (var i = 0, length = values.length; i < length; i++) {
this.baseWrite(values[i], context);
}
}
}),
'object': jBinary.Type({
params: ['structure', 'proto'],
resolve: function (getType) {
var structure = {};
for (var key in this.structure) {
structure[key] =
!(this.structure[key] instanceof Function)
? getType(this.structure[key])
: this.structure[key];
}
this.structure = structure;
},
read: function () {
var self = this, structure = this.structure, output = this.proto ? inherit(this.proto) : {};
this.binary.inContext(output, function () {
for (var key in structure) {
var value = !(structure[key] instanceof Function)
? this.read(structure[key])
: structure[key].call(self, this.contexts[0]);
// skipping undefined call results (useful for 'if' statement)
if (value !== undefined) {
output[key] = value;
}
}
});
return output;
},
write: function (data) {
var self = this, structure = this.structure;
this.binary.inContext(data, function () {
for (var key in structure) {
if (!(structure[key] instanceof Function)) {
this.write(structure[key], data[key]);
} else {
data[key] = structure[key].call(self, this.contexts[0]);
}
}
});
}
}),
'bitfield': jBinary.Type({
params: ['bitSize'],
read: function () {
var bitSize = this.bitSize,
binary = this.binary,
fieldValue = 0;
if (binary._bitShift < 0 || binary._bitShift >= 8) {
var byteShift = binary._bitShift >> 3; // Math.floor(_bitShift / 8)
binary.skip(byteShift);
binary._bitShift &= 7; // _bitShift + 8 * Math.floor(_bitShift / 8)
}
if (binary._bitShift > 0 && bitSize >= 8 - binary._bitShift) {
fieldValue = binary.view.getUint8() & ~(-1 << (8 - binary._bitShift));
bitSize -= 8 - binary._bitShift;
binary._bitShift = 0;
}
while (bitSize >= 8) {
fieldValue = binary.view.getUint8() | (fieldValue << 8);
bitSize -= 8;
}
if (bitSize > 0) {
fieldValue = ((binary.view.getUint8() >>> (8 - (binary._bitShift + bitSize))) & ~(-1 << bitSize)) | (fieldValue << bitSize);
binary._bitShift += bitSize - 8; // passing negative value for next pass
}
return fieldValue >>> 0;
},
write: function (value) {
var bitSize = this.bitSize,
binary = this.binary,
pos,
curByte;
if (binary._bitShift < 0 || binary._bitShift >= 8) {
var byteShift = binary._bitShift >> 3; // Math.floor(_bitShift / 8)
binary.skip(byteShift);
binary._bitShift &= 7; // _bitShift + 8 * Math.floor(_bitShift / 8)
}
if (binary._bitShift > 0 && bitSize >= 8 - binary._bitShift) {
pos = binary.tell();
curByte = binary.view.getUint8(pos) & (-1 << (8 - binary._bitShift));
curByte |= value >>> (bitSize - (8 - binary._bitShift));
binary.view.setUint8(pos, curByte);
bitSize -= 8 - binary._bitShift;
binary._bitShift = 0;
}
while (bitSize >= 8) {
binary.view.writeUint8((value >>> (bitSize - 8)) & 0xff);
bitSize -= 8;
}
if (bitSize > 0) {
pos = binary.tell();
curByte = binary.view.getUint8(pos) & ~(~(-1 << bitSize) << (8 - (binary._bitShift + bitSize)));
curByte |= (value & ~(-1 << bitSize)) << (8 - (binary._bitShift + bitSize));
binary.view.setUint8(pos, curByte);
binary._bitShift += bitSize - 8; // passing negative value for next pass
}
}
}),
'if': jBinary.Template({
params: ['condition', 'trueType', 'falseType'],
resolve: function (getType) {
this.trueType = getType(this.trueType);
this.falseType = getType(this.falseType);
},
getBaseType: function (context) {
return this.toValue(this.condition) ? this.trueType : this.falseType;
}
}),
'if_not': jBinary.Template({
setParams: function (condition, falseType, trueType) {
this.baseType = ['if', condition, trueType, falseType];
}
}),
'const': jBinary.Template({
params: ['baseType', 'value', 'strict'],
read: function () {
var value = this.baseRead();
if (this.strict && value !== this.value) {
if (this.strict instanceof Function) {
return this.strict(value);
} else {
throw new TypeError('Unexpected value.');
}
}
return value;
},
write: function (value) {
this.baseWrite((this.strict || value === undefined) ? this.value : value);
}
}),
'skip': jBinary.Type({
setParams: function (length) {
this.read = this.write = function () {
this.binary.view.skip(this.toValue(length));
};
}
}),
'blob': jBinary.Type({
params: ['length'],
read: function () {
return this.binary.view.getBytes(this.toValue(this.length));
},
write: function (bytes) {
this.binary.view.writeBytes(bytes, true);
}
}),
'binary': jBinary.Template({
params: ['length', 'typeSet'],
read: function () {
var startPos = this.binary.tell();
var endPos = this.binary.skip(this.toValue(this.length));
var view = this.binary.view.slice(startPos, endPos);
return new jBinary(view, this.typeSet);
},
write: function (binary) {
this.binary.write('blob', binary instanceof jBinary ? binary.read('blob', 0) : binary);
}
})
};
var dataTypes = [
'Uint8',
'Uint16',
'Uint32',
'Uint64',
'Int8',
'Int16',
'Int32',
'Int64',
'Float32',
'Float64',
'Char'
];
var simpleType = jBinary.Type({
params: ['littleEndian'],
read: function () {
return this.binary.view['get' + this.dataType](undefined, this.littleEndian);
},
write: function (value) {
this.binary.view['write' + this.dataType](value, this.littleEndian);
}
});
for (var i = 0, length = dataTypes.length; i < length; i++) {
var dataType = dataTypes[i];
proto.typeSet[dataType.toLowerCase()] = inherit(simpleType, {dataType: dataType});
}
extend(proto.typeSet, {
'byte': proto.typeSet.uint8,
'float': proto.typeSet.float32,
'double': proto.typeSet.float64
});
proto.toValue = function (value) {
return toValue(this, this, value);
};
proto.seek = function (position, callback) {
position = this.toValue(position);
if (callback !== undefined) {
var oldPos = this.view.tell();
this.view.seek(position);
var result = callback.call(this);
this.view.seek(oldPos);
return result;
} else {
return this.view.seek(position);
}
};
proto.tell = function () {
return this.view.tell();
};
proto.skip = function (offset, callback) {
return this.seek(this.tell() + this.toValue(offset), callback);
};
proto.getType = function (type, args) {
switch (typeof type) {
case 'string':
if (!(type in this.typeSet)) {
throw new ReferenceError('Unknown type `' + type + '`');
}
return this.getType(this.typeSet[type], args);
case 'number':
return this.getType(proto.typeSet.bitfield, [type]);
case 'object':
if (type instanceof jBinary.Type) {
var binary = this;
return type.inherit(args || [], function (type) { return binary.getType(type) });
} else {
var isArray = type instanceof Array;
return this._getCached(
type,
(
isArray
? function (type) { return this.getType(type[0], type.slice(1)) }
: function (structure) { return this.getType(proto.typeSet.object, [structure]) }
),
isArray
);
}
}
};
proto.createProperty = function (type) {
return this.getType(type).createProperty(this);
};
proto._action = function (type, offset, callback) {
if (type === undefined) {
return;
}
return offset !== undefined ? this.seek(offset, callback) : callback.call(this);
};
proto.read = function (type, offset) {
return this._action(
type,
offset,
function () { return this.createProperty(type).read(this.contexts[0]) }
);
};
proto.write = function (type, data, offset) {
this._action(
type,
offset,
function () { this.createProperty(type).write(data, this.contexts[0]) }
);
};
proto._toURI =
('URL' in global && 'createObjectURL' in URL)
? function (type) {
var data = this.seek(0, function () { return this.view.getBytes() });
return URL.createObjectURL(new Blob([data], {type: type}));
}
: function (type) {
var string = this.seek(0, function () { return this.view.getString(undefined, undefined, this.view._isNodeBuffer ? 'base64' : 'binary') });
return 'data:' + type + ';base64,' + (this.view._isNodeBuffer ? string : btoa(string));
};
proto.toURI = function (mimeType) {
return this._toURI(mimeType || this.typeSet['jBinary.mimeType']);
};
proto.slice = function (start, end, forceCopy) {
return new jBinary(this.view.slice(start, end, forceCopy), this.typeSet);
};
jBinary.load = function (source, typeSet, callback) {
function withTypeSet(typeSet) {
jBinary.loadData(source, function (err, data) {
err ? callback(err) : callback(null, new jBinary(data, typeSet));
});
}
if (arguments.length < 3) {
callback = typeSet;
var srcInfo;
if ('Blob' in global && source instanceof Blob) {
srcInfo = {mimeType: source.type};
if (source instanceof File) {
srcInfo.fileName = source.name;
}
} else
if (typeof source === 'string') {
var dataParts = source.match(/^data:(.+?)(;base64)?,/);
srcInfo = dataParts ? {mimeType: dataParts[1]} : {fileName: source};
}
if (srcInfo) {
repo.getAssociation(srcInfo, withTypeSet);
} else {
withTypeSet();
}
} else {
typeof typeSet === 'string' ? repo(typeSet, withTypeSet) : withTypeSet(typeSet);
}
};
jBinary.loadData = function (source, callback) {
if ('Blob' in global && source instanceof Blob) {
var reader = new FileReader();
reader.onload = reader.onerror = function() { callback(this.error, this.result) };
reader.readAsArrayBuffer(source);
} else {
if (typeof source === 'object') {
if (hasRequire && source instanceof require('stream').Readable) {
var buffers = [];
source
.on('readable', function () { buffers.push(this.read()) })
.on('end', function () { callback(null, Buffer.concat(buffers)) })
.on('error', callback);
return;
}
}
if (typeof source !== 'string') {
return callback(new TypeError('Unsupported source type.'));
}
var dataParts = source.match(/^data:(.+?)(;base64)?,(.*)$/);
if (dataParts) {
var isBase64 = dataParts[2],
content = dataParts[3];
try {
callback(
null,
(
(isBase64 && jDataView.prototype.compatibility.NodeBuffer)
? new Buffer(content, 'base64')
: (isBase64 ? atob : decodeURIComponent)(content)
)
);
} catch (e) {
callback(e);
}
} else
if ('XMLHttpRequest' in global) {
var xhr = new XMLHttpRequest();
xhr.open('GET', source, true);
// new browsers (XMLHttpRequest2-compliant)
if ('responseType' in xhr) {
xhr.responseType = 'arraybuffer';
}
// old browsers (XMLHttpRequest-compliant)
else if ('overrideMimeType' in xhr) {
xhr.overrideMimeType('text/plain; charset=x-user-defined');
}
// IE9 (Microsoft.XMLHTTP-compliant)
else {
xhr.setRequestHeader('Accept-Charset', 'x-user-defined');
}
// shim for onload for old IE
if (!('onload' in xhr)) {
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
this.onload();
}
};
}
xhr.onload = function() {
if (this.status !== 0 && this.status !== 200) {
return callback(new Error('HTTP Error #' + this.status + ': ' + this.statusText));
}
// emulating response field for IE9
if (!('response' in this)) {
this.response = new VBArray(this.responseBody).toArray();
}
callback(null, this.response);
};
xhr.send();
} else
if (hasRequire) {
if (/^(https?):\/\//.test(source)) {
require('request').get({
uri: source,
encoding: null
}, function (error, response, body) {
if (!error && response.statusCode !== 200) {
var statusText = require('http').STATUS_CODES[response.statusCode];
error = new Error('HTTP Error #' + response.statusCode + ': ' + statusText);
}
callback(error, body);
});
} else {
require('fs').readFile(source, callback);
}
} else {
callback(new TypeError('Unsupported source type.'));
}
}
};
var getScript = (function () {
if ('window' in global && 'document' in global && document === window.document) {
var head = document.head || document.getElementsByTagName('head')[0];
return function (url, callback) {
var script = document.createElement('script');
script.src = url;
script.defer = true;
if (callback) {
if ('onreadystatechange' in script) {
script.onreadystatechange = function () {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
this.onreadystatechange = null;
// delay to wait until script is executed
setTimeout(function () { callback.call(script) }, 0);
}
};
script.onreadystatechange();
} else {
script.onload = script.onerror = callback;
}
}
head.appendChild(script);
};
} else {
var request = require('request');
return function (url, callback) {
request.get(url, function (error, response, body) {
if (!error && response.statusCode === 200) {
// yes, eval is evil, but we are in Node.js and in strict mode, so let's use this
// jshint:skipline
eval(body);
}
if (callback) {
callback();
}
});
};
}
})();
// helper function for common callback from multiple sources
function whenAll(count, each, done) {
var results = new Array(count);
for (var i = 0; i < count; i++) {
(function () {
var index = i;
each(index, function (result) {
results[index] = result;
if (--count === 0) {
done(results);
}
});
})();
}
}
// "require"-like function+storage for standard file formats from https://github.com/jDataView/jBinary.Repo
var repo = jBinary.Repo = function (names, callback) {
if (!(names instanceof Array)) {
names = [names];
}
whenAll(names.length, function (i, callback) {
var name = names[i], upperName = name.toUpperCase();
if (upperName in repo) {
callback(repo[upperName]);
} else {
getScript('https://rawgithub.com/jDataView/jBinary.Repo/gh-pages/$/$.js'.replace(/\$/g, name.toLowerCase()), function () {
callback(repo[upperName]);
});
}
}, function (typeSets) {
callback.apply(repo, typeSets);
});
};
repo.getAssociations = function (callback) {
// lazy loading data by replacing `jBinary.Repo.getAssociations` itself
getScript('https://rawgithub.com/jDataView/jBinary.Repo/gh-pages/associations.js', function () {
repo.getAssociations(callback);
});
};
repo.getAssociation = function (source, _callback) {
var callback = function (typeSetName) {
repo(typeSetName, _callback);
};
repo.getAssociations(function (assoc) {
if (source.fileName) {
// extracting only longest extension part
var longExtension = source.fileName.match(/^(.*\/)?.*?(\.|$)(.*)$/)[3].toLowerCase();
if (longExtension) {
var fileParts = longExtension.split('.');
// trying everything from longest possible extension to shortest one
for (var i = 0, length = fileParts.length; i < length; i++) {
var extension = fileParts.slice(i).join('.'),
typeSetName = assoc.extensions[extension];
if (typeSetName) {
return callback(typeSetName);
}
}
}
}
if (source.mimeType) {
var typeSetName = assoc.mimeTypes[source.mimeType];
if (typeSetName) {
return callback(typeSetName);
}
}
_callback();
});
};
if (typeof module === 'object' && module && typeof module.exports === 'object') {
jDataView = require('jDataView');
module.exports = jBinary;
} else
if (typeof define === 'function' && define.amd) {
define('jBinary', ['jDataView'], function (_jDataView) {
jDataView = _jDataView;
return jBinary;
});
} else {
jDataView = global.jDataView;
global.jBinary = jBinary;
}
jDataView.prototype.toBinary = function (typeSet) {
return new jBinary(this, typeSet);
};
})((function () { /* jshint strict: false */ return this })());
| No need to merge typeSet into default one if it's already inherited from default (i.e., when slicing).
| src/jBinary.js | No need to merge typeSet into default one if it's already inherited from default (i.e., when slicing). | <ide><path>rc/jBinary.js
<ide> this.contexts = [];
<ide>
<ide> if (typeSet) {
<del> this.typeSet = inherit(proto.typeSet, typeSet);
<add> this.typeSet = proto.typeSet.isPrototypeOf(typeSet) ? typeSet : inherit(proto.typeSet, typeSet);
<ide> this.cacheKey = this._getCached(typeSet, function () { return proto.cacheKey + '.' + (++proto.id) }, true);
<ide> }
<ide> } |
|
Java | apache-2.0 | 64608dedf011ed1c7f7e1d32b61d82ecaf3f046d | 0 | tmpgit/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,hurricup/intellij-community,hurricup/intellij-community,signed/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,holmes/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,kool79/intellij-community,akosyakov/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,semonte/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,izonder/intellij-community,nicolargo/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,kool79/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,consulo/consulo,signed/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,ernestp/consulo,gnuhub/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,supersven/intellij-community,ryano144/intellij-community,retomerz/intellij-community,allotria/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,SerCeMan/intellij-community,ernestp/consulo,vladmm/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,caot/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,kool79/intellij-community,allotria/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,caot/intellij-community,signed/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,izonder/intellij-community,semonte/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ibinti/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,xfournet/intellij-community,FHannes/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,ernestp/consulo,dslomov/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,holmes/intellij-community,allotria/intellij-community,ibinti/intellij-community,asedunov/intellij-community,FHannes/intellij-community,FHannes/intellij-community,caot/intellij-community,xfournet/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,supersven/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,caot/intellij-community,kool79/intellij-community,caot/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,slisson/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,da1z/intellij-community,supersven/intellij-community,xfournet/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,allotria/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,signed/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,ibinti/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,samthor/intellij-community,apixandru/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,consulo/consulo,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,adedayo/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,consulo/consulo,allotria/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,vladmm/intellij-community,clumsy/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,slisson/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,caot/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,asedunov/intellij-community,semonte/intellij-community,samthor/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,diorcety/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,slisson/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,semonte/intellij-community,allotria/intellij-community,da1z/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,semonte/intellij-community,signed/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,samthor/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,semonte/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,supersven/intellij-community,slisson/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,izonder/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,kdwink/intellij-community,robovm/robovm-studio,fnouama/intellij-community,diorcety/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,ernestp/consulo,asedunov/intellij-community,amith01994/intellij-community,vladmm/intellij-community,clumsy/intellij-community,kdwink/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,ernestp/consulo,adedayo/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,caot/intellij-community,slisson/intellij-community,izonder/intellij-community,hurricup/intellij-community,ibinti/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,Lekanich/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,da1z/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,FHannes/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,jagguli/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,amith01994/intellij-community,slisson/intellij-community,asedunov/intellij-community,hurricup/intellij-community,allotria/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,samthor/intellij-community,adedayo/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,robovm/robovm-studio,xfournet/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,caot/intellij-community,consulo/consulo,orekyuu/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,signed/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,caot/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,izonder/intellij-community,retomerz/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,da1z/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,slisson/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,diorcety/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,allotria/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,supersven/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,adedayo/intellij-community,kdwink/intellij-community,holmes/intellij-community,retomerz/intellij-community,signed/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,clumsy/intellij-community,xfournet/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,ibinti/intellij-community,retomerz/intellij-community,supersven/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,xfournet/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,blademainer/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,clumsy/intellij-community,signed/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,dslomov/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,fitermay/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,akosyakov/intellij-community,supersven/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,robovm/robovm-studio,xfournet/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,vladmm/intellij-community,asedunov/intellij-community,retomerz/intellij-community,signed/intellij-community,da1z/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,holmes/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,salguarnieri/intellij-community,consulo/consulo,caot/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,apixandru/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,petteyg/intellij-community,ryano144/intellij-community,blademainer/intellij-community,FHannes/intellij-community,supersven/intellij-community,caot/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,apixandru/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,FHannes/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,holmes/intellij-community,hurricup/intellij-community,izonder/intellij-community,asedunov/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,ryano144/intellij-community,semonte/intellij-community | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.intentions.conversions;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.util.MethodSignatureUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.intentions.base.ErrorUtil;
import org.jetbrains.plugins.groovy.intentions.base.Intention;
import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate;
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrBinaryExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrParenthesizedExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
import org.jetbrains.plugins.groovy.lang.psi.util.GrStringUtil;
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames;
/**
* @author Maxim.Medvedev
*/
public class ConvertConcatenationToGstringIntention extends Intention {
private static final String END_BRACE = "}";
private static final String START_BRACE = "${";
@NotNull
@Override
protected PsiElementPredicate getElementPredicate() {
return new MyPredicate();
}
@Override
protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException {
StringBuilder builder = new StringBuilder(element.getTextLength());
if (element instanceof GrBinaryExpression) {
performIntention((GrBinaryExpression)element, builder);
}
else if (element instanceof GrLiteral) {
getOperandText((GrExpression)element, builder);
}
else {
return;
}
String text = builder.toString();
if (builder.indexOf("\n") < 0 && builder.indexOf("\r") < 0) {
text = GrStringUtil.escapeSymbols(builder.toString(), "\"");
}
final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(element.getProject());
final GrExpression newExpr = factory.createExpressionFromText(GrStringUtil.addQuotes(text, true));
final GrExpression expression = ((GrExpression)element).replaceWithExpression(newExpr, true);
if (expression instanceof GrString) {
GrStringUtil.removeUnnecessaryBracesInGString((GrString)expression);
}
}
private static void performIntention(GrBinaryExpression expr, StringBuilder builder) {
GrExpression left = (GrExpression)skipParentheses(expr.getLeftOperand(), false);
GrExpression right = (GrExpression)skipParentheses(expr.getRightOperand(), false);
getOperandText(left, builder);
getOperandText(right, builder);
}
private static void getOperandText(@Nullable GrExpression operand, StringBuilder builder) {
if (operand instanceof GrString) {
builder.append(GrStringUtil.removeQuotes(operand.getText()));
}
else if (operand instanceof GrLiteral) {
final String unescaped = StringUtil.unescapeStringCharacters(GrStringUtil.removeQuotes(operand.getText()));
GrStringUtil.escapeStringCharacters(unescaped.length(), unescaped, "$", false, builder);
}
else if (MyPredicate.satisfiedBy(operand, false)) {
performIntention((GrBinaryExpression)operand, builder);
}
else if (isToStringMethod(operand, builder)) {
//nothing to do
}
else {
builder.append(START_BRACE).append(operand == null ? "" : operand.getText()).append(END_BRACE);
}
}
/**
* append text to builder if the operand is 'something'.toString()
*/
private static boolean isToStringMethod(GrExpression operand, StringBuilder builder) {
if (!(operand instanceof GrMethodCallExpression)) return false;
final GrExpression expression = ((GrMethodCallExpression)operand).getInvokedExpression();
if (!(expression instanceof GrReferenceExpression)) return false;
final GrReferenceExpression refExpr = (GrReferenceExpression)expression;
final GrExpression qualifier = refExpr.getQualifierExpression();
if (qualifier == null) return false;
final GroovyResolveResult[] results = refExpr.multiResolve(false);
if (results.length != 1) return false;
final PsiElement element = results[0].getElement();
if (!(element instanceof PsiMethod)) return false;
final PsiMethod method = (PsiMethod)element;
final PsiClass objectClass =
JavaPsiFacade.getInstance(operand.getProject()).findClass(CommonClassNames.JAVA_LANG_OBJECT, operand.getResolveScope());
if (objectClass == null) return false;
final PsiMethod[] toStringMethod = objectClass.findMethodsByName("toString", true);
if (MethodSignatureUtil.isSubsignature(toStringMethod[0].getHierarchicalMethodSignature(), method.getHierarchicalMethodSignature())) {
builder.append(START_BRACE).append(qualifier.getText()).append(END_BRACE);
return true;
}
return false;
}
@Nullable
private static PsiElement skipParentheses(PsiElement element, boolean up) {
if (up) {
PsiElement parent = element.getParent();
while (parent instanceof GrParenthesizedExpression) {
parent = parent.getParent();
}
return parent;
}
else {
while (element instanceof GrParenthesizedExpression) {
element = ((GrParenthesizedExpression)element).getOperand();
}
return element;
}
}
private static class MyPredicate implements PsiElementPredicate {
public boolean satisfiedBy(PsiElement element) {
return satisfiedBy(element, true);
}
public static boolean satisfiedBy(PsiElement element, boolean checkForParent) {
if (element instanceof GrLiteral && element.getText().startsWith("'")) return true;
if (!(element instanceof GrBinaryExpression)) return false;
GrBinaryExpression binaryExpression = (GrBinaryExpression)element;
if (!GroovyTokenTypes.mPLUS.equals(binaryExpression.getOperationTokenType())) return false;
if (checkForParent) {
PsiElement parent = skipParentheses(binaryExpression, true);
if (parent instanceof GrBinaryExpression && GroovyTokenTypes.mPLUS.equals(((GrBinaryExpression)parent).getOperationTokenType())) {
return false;
}
}
if (ErrorUtil.containsError(element)) return false;
final PsiType type = binaryExpression.getType();
if (type == null) return false;
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(element.getProject());
final PsiClassType stringType = TypesUtil.createType(CommonClassNames.JAVA_LANG_STRING, element);
final PsiClassType gstringType = factory.createTypeByFQClassName(GroovyCommonClassNames.GROOVY_LANG_GSTRING, element.getResolveScope());
if (!(TypeConversionUtil.isAssignable(stringType, type) || TypeConversionUtil.isAssignable(gstringType, type))) return false;
return true;
}
}
}
| plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/ConvertConcatenationToGstringIntention.java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.intentions.conversions;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.util.MethodSignatureUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.intentions.base.ErrorUtil;
import org.jetbrains.plugins.groovy.intentions.base.Intention;
import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate;
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrBinaryExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrParenthesizedExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
import org.jetbrains.plugins.groovy.lang.psi.util.GrStringUtil;
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames;
/**
* @author Maxim.Medvedev
*/
public class ConvertConcatenationToGstringIntention extends Intention {
private static final String END_BRACE = "}";
private static final String START_BRACE = "${";
@NotNull
@Override
protected PsiElementPredicate getElementPredicate() {
return new MyPredicate();
}
@Override
protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException {
StringBuilder builder = new StringBuilder(element.getTextLength());
if (element instanceof GrBinaryExpression) {
performIntention((GrBinaryExpression)element, builder);
}
else if (element instanceof GrLiteral) {
getOperandText((GrExpression)element, builder);
}
else {
return;
}
String text = builder.toString();
if (builder.indexOf("\n") < 0 && builder.indexOf("\r") < 0) {
text = GrStringUtil.escapeSymbols(builder.toString(), "\"");
}
final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(element.getProject());
final GrExpression newExpr = factory.createExpressionFromText(GrStringUtil.addQuotes(text, true));
final GrExpression expression = ((GrExpression)element).replaceWithExpression(newExpr, true);
if (expression instanceof GrString) {
GrStringUtil.removeUnnecessaryBracesInGString((GrString)expression);
}
}
private static void performIntention(GrBinaryExpression expr, StringBuilder builder) {
GrExpression left = (GrExpression)skipParentheses(expr.getLeftOperand(), false);
GrExpression right = (GrExpression)skipParentheses(expr.getRightOperand(), false);
getOperandText(left, builder);
getOperandText(right, builder);
}
private static void getOperandText(@Nullable GrExpression operand, StringBuilder builder) {
if (operand instanceof GrString) {
builder.append(GrStringUtil.removeQuotes(operand.getText()));
}
else if (operand instanceof GrLiteral) {
String text = GrStringUtil.escapeSymbolsForGString(GrStringUtil.removeQuotes(operand.getText()), false);
builder.append(text);
}
else if (MyPredicate.satisfiedBy(operand, false)) {
performIntention((GrBinaryExpression)operand, builder);
}
else if (isToStringMethod(operand, builder)) {
//nothing to do
}
else {
builder.append(START_BRACE).append(operand == null ? "" : operand.getText()).append(END_BRACE);
}
}
/**
* append text to builder if the operand is 'something'.toString()
*/
private static boolean isToStringMethod(GrExpression operand, StringBuilder builder) {
if (!(operand instanceof GrMethodCallExpression)) return false;
final GrExpression expression = ((GrMethodCallExpression)operand).getInvokedExpression();
if (!(expression instanceof GrReferenceExpression)) return false;
final GrReferenceExpression refExpr = (GrReferenceExpression)expression;
final GrExpression qualifier = refExpr.getQualifierExpression();
if (qualifier == null) return false;
final GroovyResolveResult[] results = refExpr.multiResolve(false);
if (results.length != 1) return false;
final PsiElement element = results[0].getElement();
if (!(element instanceof PsiMethod)) return false;
final PsiMethod method = (PsiMethod)element;
final PsiClass objectClass =
JavaPsiFacade.getInstance(operand.getProject()).findClass(CommonClassNames.JAVA_LANG_OBJECT, operand.getResolveScope());
if (objectClass == null) return false;
final PsiMethod[] toStringMethod = objectClass.findMethodsByName("toString", true);
if (MethodSignatureUtil.isSubsignature(toStringMethod[0].getHierarchicalMethodSignature(), method.getHierarchicalMethodSignature())) {
builder.append(START_BRACE).append(qualifier.getText()).append(END_BRACE);
return true;
}
return false;
}
@Nullable
private static PsiElement skipParentheses(PsiElement element, boolean up) {
if (up) {
PsiElement parent = element.getParent();
while (parent instanceof GrParenthesizedExpression) {
parent = parent.getParent();
}
return parent;
}
else {
while (element instanceof GrParenthesizedExpression) {
element = ((GrParenthesizedExpression)element).getOperand();
}
return element;
}
}
private static class MyPredicate implements PsiElementPredicate {
public boolean satisfiedBy(PsiElement element) {
return satisfiedBy(element, true);
}
public static boolean satisfiedBy(PsiElement element, boolean checkForParent) {
if (element instanceof GrLiteral && element.getText().startsWith("'")) return true;
if (!(element instanceof GrBinaryExpression)) return false;
GrBinaryExpression binaryExpression = (GrBinaryExpression)element;
if (!GroovyTokenTypes.mPLUS.equals(binaryExpression.getOperationTokenType())) return false;
if (checkForParent) {
PsiElement parent = skipParentheses(binaryExpression, true);
if (parent instanceof GrBinaryExpression && GroovyTokenTypes.mPLUS.equals(((GrBinaryExpression)parent).getOperationTokenType())) {
return false;
}
}
if (ErrorUtil.containsError(element)) return false;
final PsiType type = binaryExpression.getType();
if (type == null) return false;
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(element.getProject());
final PsiClassType stringType = TypesUtil.createType(CommonClassNames.JAVA_LANG_STRING, element);
final PsiClassType gstringType = factory.createTypeByFQClassName(GroovyCommonClassNames.GROOVY_LANG_GSTRING, element.getResolveScope());
if (!(TypeConversionUtil.isAssignable(stringType, type) || TypeConversionUtil.isAssignable(gstringType, type))) return false;
return true;
}
}
}
| convertConcatenationToGString fix
| plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/ConvertConcatenationToGstringIntention.java | convertConcatenationToGString fix | <ide><path>lugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/ConvertConcatenationToGstringIntention.java
<ide>
<ide> import com.intellij.openapi.editor.Editor;
<ide> import com.intellij.openapi.project.Project;
<add>import com.intellij.openapi.util.text.StringUtil;
<ide> import com.intellij.psi.*;
<ide> import com.intellij.psi.util.MethodSignatureUtil;
<ide> import com.intellij.psi.util.TypeConversionUtil;
<ide> builder.append(GrStringUtil.removeQuotes(operand.getText()));
<ide> }
<ide> else if (operand instanceof GrLiteral) {
<del> String text = GrStringUtil.escapeSymbolsForGString(GrStringUtil.removeQuotes(operand.getText()), false);
<del> builder.append(text);
<add> final String unescaped = StringUtil.unescapeStringCharacters(GrStringUtil.removeQuotes(operand.getText()));
<add> GrStringUtil.escapeStringCharacters(unescaped.length(), unescaped, "$", false, builder);
<ide> }
<ide> else if (MyPredicate.satisfiedBy(operand, false)) {
<ide> performIntention((GrBinaryExpression)operand, builder); |
|
Java | apache-2.0 | 10c658593a13ecb60589edd7147cea00b69c5028 | 0 | iychoi/syndicate,iychoi/syndicate,jcnelson/syndicate,jcnelson/syndicate,jcnelson/syndicate,iychoi/syndicate,iychoi/syndicate,jcnelson/syndicate,jcnelson/syndicate,iychoi/syndicate,iychoi/syndicate,iychoi/syndicate,jcnelson/syndicate,jcnelson/syndicate,iychoi/syndicate,jcnelson/syndicate | /*
* Directory Entry Filler Implementation Class of JSFSFillDir for JSyndicateFS
*/
package JSyndicateFS;
import JSyndicateFSJNI.struct.JSFSFillDir;
import JSyndicateFSJNI.struct.JSFSStat;
import java.util.ArrayList;
/**
*
* @author iychoi
*/
public class DirFillerImpl extends JSFSFillDir {
private static final String[] SKIP_FILES = {".", ".."};
private ArrayList<String> entries = new ArrayList<String>();
DirFillerImpl() {
}
@Override
public void fill(String name, JSFSStat stbuf, long off) {
boolean skip = false;
for(String skip_file : SKIP_FILES) {
if(name.equals(skip_file)) {
skip = true;
}
}
if(!skip) {
entries.add(name);
}
}
public String[] getEntryNames() {
String[] arr = new String[this.entries.size()];
arr = entries.toArray(arr);
return arr;
}
}
| UG-shared/JSyndicateFS/src/JSyndicateFS/DirFillerImpl.java | /*
* Directory Entry Filler Implementation Class of JSFSFillDir for JSyndicateFS
*/
package JSyndicateFS;
import JSyndicateFSJNI.struct.JSFSFillDir;
import JSyndicateFSJNI.struct.JSFSStat;
import java.util.ArrayList;
/**
*
* @author iychoi
*/
public class DirFillerImpl extends JSFSFillDir {
private ArrayList<String> entries = new ArrayList<String>();
DirFillerImpl() {
}
@Override
public void fill(String name, JSFSStat stbuf, long off) {
entries.add(name);
}
public String[] getEntryNames() {
String[] arr = new String[this.entries.size()];
arr = entries.toArray(arr);
return arr;
}
}
| Remove . and .. dirs from list result | UG-shared/JSyndicateFS/src/JSyndicateFS/DirFillerImpl.java | Remove . and .. dirs from list result | <ide><path>G-shared/JSyndicateFS/src/JSyndicateFS/DirFillerImpl.java
<ide> */
<ide> public class DirFillerImpl extends JSFSFillDir {
<ide>
<add> private static final String[] SKIP_FILES = {".", ".."};
<add>
<ide> private ArrayList<String> entries = new ArrayList<String>();
<add>
<ide>
<ide> DirFillerImpl() {
<ide>
<ide>
<ide> @Override
<ide> public void fill(String name, JSFSStat stbuf, long off) {
<del> entries.add(name);
<add> boolean skip = false;
<add> for(String skip_file : SKIP_FILES) {
<add> if(name.equals(skip_file)) {
<add> skip = true;
<add> }
<add> }
<add>
<add> if(!skip) {
<add> entries.add(name);
<add> }
<ide> }
<ide>
<ide> public String[] getEntryNames() { |
|
Java | epl-1.0 | f8df460dc2336cbb6349c120f4e41cb2f6ea0b6f | 0 | jtrfp/terminal-recall,jtrfp/terminal-recall,jtrfp/terminal-recall | /*******************************************************************************
* This file is part of TERMINAL RECALL
* Copyright (c) 2012, 2013 Chuck Ritola.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the COPYING and CREDITS files for more details.
*
* Contributors:
* chuck - initial API and implementation
******************************************************************************/
package org.jtrfp.trcl.core;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.nio.ByteOrder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.media.opengl.GL3;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.BackdropSystem;
import org.jtrfp.trcl.HUDSystem;
import org.jtrfp.trcl.InterpolatingAltitudeMap;
import org.jtrfp.trcl.KeyStatus;
import org.jtrfp.trcl.ManuallySetController;
import org.jtrfp.trcl.NAVSystem;
import org.jtrfp.trcl.OverworldSystem;
import org.jtrfp.trcl.World;
import org.jtrfp.trcl.dbg.Reporter;
import org.jtrfp.trcl.file.VOXFile;
import org.jtrfp.trcl.flow.Game;
import org.jtrfp.trcl.gpu.GPU;
import org.jtrfp.trcl.obj.CollisionManager;
import org.jtrfp.trcl.obj.Player;
public final class TR
{
public static final double unitCircle=65535;
public static final double crossPlatformScalar=16;//Shrinks everything so that we can use floats instead of ints
public static final double mapSquareSize=Math.pow(2, 20)/crossPlatformScalar;
public static final double mapWidth=mapSquareSize*256;
public static final double mapCartOffset=mapWidth/2.;//This is the scaled-down version, not the full version
public static final double visibilityDiameterInMapSquares=35;
public static final int terrainChunkSideLengthInSquares=4;//Keep at power of two for now. 4x4 = 16. 16x6 = 96. 96 vertices per GLSL block means 1 chunk per block.
public static final double antiGamma=1.6;
public static final boolean ANIMATED_TERRAIN=false;
private final GPU gpu = new GPU(this);
private Player player;
private final JFrame frame = new JFrame("Terminal Recall");
private Color [] globalPalette, darkIsClearPalette;
private final KeyStatus keyStatus;
private ResourceManager resourceManager;
public static final ExecutorService threadPool = Executors.newCachedThreadPool();//TODO: Migrate to ThreadManager
private final ThreadManager threadManager;
private final Renderer renderer;
private final CollisionManager collisionManager = new CollisionManager(this);
private final Reporter reporter = new Reporter();
private ManuallySetController throttleMeter, healthMeter;
private OverworldSystem overworldSystem;
private InterpolatingAltitudeMap altitudeMap;
private BackdropSystem backdropSystem;
private Game game = new Game();
private NAVSystem navSystem;
private HUDSystem hudSystem;
/*
private ThreadPoolExecutor threadPool = new ThreadPoolExecutor
(Runtime.getRuntime().availableProcessors(),Runtime.getRuntime().availableProcessors()*2,
2000,TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
*/
private TRConfiguration trConfig;
private GL3 glCache;
private ByteOrder byteOrder;
private final World world;
/**
* Converts legacy coordinate to modern coordinate
* @param v
* @return
* @since Oct 17, 2012
*/
public static double legacy2Modern(double v)
{
return v<0?(v+268435456)/crossPlatformScalar:v/crossPlatformScalar;
}
public static double modern2Legacy(double v)
{
v*=crossPlatformScalar;
return v>134217727?v-268435456:v;
}
public static Vector3D twosComplimentSubtract(Vector3D l, Vector3D r){
return new Vector3D(
deltaRollover(l.getX()-r.getX()),
deltaRollover(l.getY()-r.getY()),
deltaRollover(l.getZ()-r.getZ()));
}
public static double twosComplimentDistance(Vector3D l, Vector3D r){
return twosComplimentSubtract(l,r).getNorm();
}
public static double deltaRollover(double v){
if(v>mapCartOffset)return v-mapWidth;
else if(v<-mapCartOffset)return v+mapWidth;
return v;
}
public TR()
{
keyStatus = new KeyStatus(frame);
try{
SwingUtilities.invokeAndWait(new Runnable()
{
@Override
public void run(){
configureMenuBar();
//frame.setBackground(Color.black);
frame.getContentPane().add(gpu.getComponent());
frame.setVisible(true);
frame.setSize(800,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.pack();
}});
}catch(Exception e){e.printStackTrace();}
gpu.takeGL();
renderer=new Renderer(gpu);
gpu.releaseGL();
setResourceManager(new ResourceManager(this));
world = new World(
256*mapSquareSize,
14.*mapSquareSize,
256*mapSquareSize,
mapSquareSize*visibilityDiameterInMapSquares/2., this);
getRenderer().setRootGrid(world);
threadManager = new ThreadManager(this);
}//end constructor
public void showStopper(final Exception e)
{try{
SwingUtilities.invokeLater(new Runnable(){public void run()
{
int c = JOptionPane.showConfirmDialog(getFrame(), "A component of Terminal Recall triggered a showstopper error:\n"+e.getLocalizedMessage()+"\n\nContinue anyway?",
"Uh Oh...",
JOptionPane.ERROR_MESSAGE);
if(c==1)System.exit(1);
}});
} catch(Exception ite){ite.printStackTrace();}
e.printStackTrace();
}
private void configureMenuBar()
{
frame.setJMenuBar(new JMenuBar());
JMenu file=new JMenu("File"),window=new JMenu("Window");
//And menus to menubar
JMenuItem file_exit=new JMenuItem("Exit");
JMenuItem debugStatesMenuItem = new JMenuItem("Debug States");
//Menu item behaviors
file_exit.addActionListener(new ActionListener(){
@Override public void actionPerformed(ActionEvent arg0){System.exit(1);}});
debugStatesMenuItem.addActionListener(new ActionListener(){
@Override public void actionPerformed(ActionEvent ev){reporter.setVisible(true);};});
final String showDebugStatesOnStartup = System.getProperty("org.jtrfp.trcl.showDebugStates");
if(showDebugStatesOnStartup!=null){if(showDebugStatesOnStartup.toUpperCase().contains("TRUE")){reporter.setVisible(true);}}
file.add(file_exit);
window.add(debugStatesMenuItem);
frame.getJMenuBar().add(file);
frame.getJMenuBar().add(window);
}
public static int bidiMod(int v, int mod)
{
while(v<0)v+=mod;
v%=mod;
return v;
}
/**
* @return the trConfig
*/
public TRConfiguration getTrConfig()
{
return trConfig;
}
/**
* @param trConfig the trConfig to set
*/
public void setTrConfig(TRConfiguration trConfig)
{
this.trConfig = trConfig;
}
/**
* @return the resourceManager
*/
public ResourceManager getResourceManager()
{
return resourceManager;
}
/**
* @param resourceManager the resourceManager to set
*/
public void setResourceManager(ResourceManager resourceManager)
{
this.resourceManager = resourceManager;
}
/**
* @return the frame
*/
public JFrame getFrame()
{
return frame;
}
public static double [] floats2Doubles(float [] toConvert)
{
double [] result = new double[toConvert.length];
for(int i=0; i<toConvert.length;i++)
{
result[i]=toConvert[i];
}
return result;
}//end floats2Doubles
public static float [] doubles2Floats(double [] toConvert)
{
float [] result = new float[toConvert.length];
for(int i=0; i<toConvert.length;i++)
{
result[i]=(float)toConvert[i];
}
return result;
}//end floats2Floats
public boolean isStampingTextures()
{return false;}
public Game newGame(VOXFile mission)
{
return new Game(this, mission);
}//end newGame(...)
/**
* @return the keyStatus
*/
public KeyStatus getKeyStatus()
{
return keyStatus;
}
public void setGlobalPalette(Color[] palette){
globalPalette = palette;
darkIsClearPalette = new Color[256];
for(int i=0; i<256; i++){
float newAlpha=(float)Math.pow(((palette[i].getRed()+palette[i].getGreen()+palette[i].getBlue())/(3f*255f)),.5);
darkIsClearPalette[i]=new Color(palette[i].getRed()/255f,palette[i].getGreen()/255f,palette[i].getBlue()/255f,newAlpha);
}//end for(i)
}
public Color [] getGlobalPalette(){return globalPalette;}
public Color [] getDarkIsClearPalette(){return darkIsClearPalette;}
public GPU getGPU(){return gpu;}
/**
* @return the renderer
*/
public Renderer getRenderer()
{
return renderer;
}
/**
* @return the world
*/
public World getWorld()
{
return world;
}
public ThreadManager getThreadManager()
{return threadManager;}
public CollisionManager getCollisionManager()
{return collisionManager;}
public void setPlayer(Player player)
{this.player=player;}
public Player getPlayer(){return player;}
/**
* @return the reporter
*/
public Reporter getReporter() {
return reporter;
}
public ManuallySetController getThrottleMeter() {
return throttleMeter;
}
/**
* @return the healthMeter
*/
public ManuallySetController getHealthMeter() {
return healthMeter;
}
/**
* @param healthMeter the healthMeter to set
*/
public void setHealthMeter(ManuallySetController healthMeter) {
this.healthMeter = healthMeter;
}
/**
* @param throttleMeter the throttleMeter to set
*/
public void setThrottleMeter(ManuallySetController throttleMeter) {
this.throttleMeter = throttleMeter;
}
public void setOverworldSystem(OverworldSystem overworldSystem) {
this.overworldSystem=overworldSystem;
}
/**
* @return the overworldSystem
*/
public OverworldSystem getOverworldSystem() {
return overworldSystem;
}
/**
* @return the altitudeMap
*/
public InterpolatingAltitudeMap getAltitudeMap() {
return altitudeMap;
}
/**
* @param altitudeMap the altitudeMap to set
*/
public void setAltitudeMap(InterpolatingAltitudeMap altitudeMap) {
this.altitudeMap = altitudeMap;
}
/**
* @return the backdropSystem
*/
public BackdropSystem getBackdropSystem() {
return backdropSystem;
}
/**
* @param backdropSystem the backdropSystem to set
*/
public void setBackdropSystem(BackdropSystem backdropSystem) {
this.backdropSystem = backdropSystem;
}
public Game getGame() {
return game;
}
/**
* @return the navSystem
*/
public NAVSystem getNavSystem() {
return navSystem;
}
/**
* @param navSystem the navSystem to set
*/
public void setNavSystem(NAVSystem navSystem) {
this.navSystem = navSystem;
}
/**
* @return the hudSystem
*/
public HUDSystem getHudSystem() {
return hudSystem;
}
/**
* @param hudSystem the hudSystem to set
*/
public void setHudSystem(HUDSystem hudSystem) {
this.hudSystem = hudSystem;
}
public static double legacy2MapSquare(double z) {
return ((z/crossPlatformScalar)/mapWidth)*255.;
}
}//end TR
| src/main/java/org/jtrfp/trcl/core/TR.java | /*******************************************************************************
* This file is part of TERMINAL RECALL
* Copyright (c) 2012, 2013 Chuck Ritola.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the COPYING and CREDITS files for more details.
*
* Contributors:
* chuck - initial API and implementation
******************************************************************************/
package org.jtrfp.trcl.core;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.nio.ByteOrder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.media.opengl.GL3;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.BackdropSystem;
import org.jtrfp.trcl.HUDSystem;
import org.jtrfp.trcl.InterpolatingAltitudeMap;
import org.jtrfp.trcl.KeyStatus;
import org.jtrfp.trcl.ManuallySetController;
import org.jtrfp.trcl.NAVSystem;
import org.jtrfp.trcl.OverworldSystem;
import org.jtrfp.trcl.World;
import org.jtrfp.trcl.dbg.Reporter;
import org.jtrfp.trcl.file.VOXFile;
import org.jtrfp.trcl.flow.Game;
import org.jtrfp.trcl.gpu.GPU;
import org.jtrfp.trcl.obj.CollisionManager;
import org.jtrfp.trcl.obj.Player;
public final class TR
{
public static final double unitCircle=65535;
public static final double crossPlatformScalar=16;//Shrinks everything so that we can use floats instead of ints
public static final double mapSquareSize=Math.pow(2, 20)/crossPlatformScalar;
public static final double mapWidth=mapSquareSize*256;
public static final double mapCartOffset=mapWidth/2.;//This is the scaled-down version, not the full version
public static final double visibilityDiameterInMapSquares=35;
public static final int terrainChunkSideLengthInSquares=4;//Keep at power of two for now. 4x4 = 16. 16x6 = 96. 96 vertices per GLSL block means 1 chunk per block.
public static final double antiGamma=1.6;
public static final boolean ANIMATED_TERRAIN=false;
private final GPU gpu = new GPU(this);
private Player player;
private final JFrame frame = new JFrame("Terminal Recall");
private Color [] globalPalette, darkIsClearPalette;
private final KeyStatus keyStatus;
private ResourceManager resourceManager;
public static final ExecutorService threadPool = Executors.newCachedThreadPool();//TODO: Migrate to ThreadManager
private final ThreadManager threadManager;
private final Renderer renderer;
private final CollisionManager collisionManager = new CollisionManager(this);
private final Reporter reporter = new Reporter();
private ManuallySetController throttleMeter, healthMeter;
private OverworldSystem overworldSystem;
private InterpolatingAltitudeMap altitudeMap;
private BackdropSystem backdropSystem;
private Game game = new Game();
private NAVSystem navSystem;
private HUDSystem hudSystem;
/*
private ThreadPoolExecutor threadPool = new ThreadPoolExecutor
(Runtime.getRuntime().availableProcessors(),Runtime.getRuntime().availableProcessors()*2,
2000,TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
*/
private TRConfiguration trConfig;
private GL3 glCache;
private ByteOrder byteOrder;
private final World world;
/**
* Converts legacy coordinate to modern coordinate
* @param v
* @return
* @since Oct 17, 2012
*/
public static double legacy2Modern(double v)
{
return v<0?(v+268435456)/crossPlatformScalar:v/crossPlatformScalar;
}
public static double modern2Legacy(double v)
{
v*=crossPlatformScalar;
return v>134217727?v-268435456:v;
}
public static Vector3D twosComplimentSubtract(Vector3D l, Vector3D r){
return new Vector3D(
deltaRollover(l.getX()-r.getX()),
deltaRollover(l.getY()-r.getY()),
deltaRollover(l.getZ()-r.getZ()));
}
public static double twosComplimentDistance(Vector3D l, Vector3D r){
return twosComplimentSubtract(l,r).getNorm();
}
public static double deltaRollover(double v){
if(v>mapCartOffset)return v-mapWidth;
else if(v<-mapCartOffset)return v+mapWidth;
return v;
}
public TR()
{
keyStatus = new KeyStatus(frame);
try{
SwingUtilities.invokeAndWait(new Runnable()
{
@Override
public void run(){
configureMenuBar();
//frame.setBackground(Color.black);
frame.getContentPane().add(gpu.getComponent());
frame.setVisible(true);
frame.setSize(800,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.pack();
}});
}catch(Exception e){e.printStackTrace();}
gpu.takeGL();
renderer=new Renderer(gpu);
gpu.releaseGL();
setResourceManager(new ResourceManager(this));
world = new World(
256*mapSquareSize,
14.*mapSquareSize,
256*mapSquareSize,
mapSquareSize*visibilityDiameterInMapSquares/2., this);
getRenderer().setRootGrid(world);
threadManager = new ThreadManager(this);
}//end constructor
public void showStopper(final Exception e)
{try{
SwingUtilities.invokeLater(new Runnable(){public void run()
{
int c = JOptionPane.showConfirmDialog(getFrame(), "A component of Terminal Recall triggered a showstopper error:\n"+e.getLocalizedMessage()+"\n\nContinue anyway?",
"Uh Oh...",
JOptionPane.ERROR_MESSAGE);
if(c==1)System.exit(1);
}});
} catch(Exception ite){ite.printStackTrace();}
e.printStackTrace();
}
private void configureMenuBar()
{
frame.setJMenuBar(new JMenuBar());
JMenu file=new JMenu("File"),window=new JMenu("Window");
//And menus to menubar
JMenuItem file_exit=new JMenuItem("Exit");
JMenuItem debugStatesMenuItem = new JMenuItem("Debug States");
//Menu item behaviors
file_exit.addActionListener(new ActionListener(){
@Override public void actionPerformed(ActionEvent arg0){System.exit(1);}});
debugStatesMenuItem.addActionListener(new ActionListener(){
@Override public void actionPerformed(ActionEvent ev){reporter.setVisible(true);};});
final String showDebugStatesOnStartup = System.getProperty("org.jtrfp.trcl.showDebugStates");
if(showDebugStatesOnStartup!=null){if(showDebugStatesOnStartup.toUpperCase().contains("TRUE")){reporter.setVisible(true);}}
file.add(file_exit);
window.add(debugStatesMenuItem);
frame.getJMenuBar().add(file);
frame.getJMenuBar().add(window);
}
public static int bidiMod(int v, int mod)
{
while(v<0)v+=mod;
v%=mod;
return v;
}
/**
* @return the trConfig
*/
public TRConfiguration getTrConfig()
{
return trConfig;
}
/**
* @param trConfig the trConfig to set
*/
public void setTrConfig(TRConfiguration trConfig)
{
this.trConfig = trConfig;
}
/**
* @return the resourceManager
*/
public ResourceManager getResourceManager()
{
return resourceManager;
}
/**
* @param resourceManager the resourceManager to set
*/
public void setResourceManager(ResourceManager resourceManager)
{
this.resourceManager = resourceManager;
}
/**
* @return the frame
*/
public JFrame getFrame()
{
return frame;
}
public static double [] floats2Doubles(float [] toConvert)
{
double [] result = new double[toConvert.length];
for(int i=0; i<toConvert.length;i++)
{
result[i]=toConvert[i];
}
return result;
}//end floats2Doubles
public static float [] doubles2Floats(double [] toConvert)
{
float [] result = new float[toConvert.length];
for(int i=0; i<toConvert.length;i++)
{
result[i]=(float)toConvert[i];
}
return result;
}//end floats2Floats
public boolean isStampingTextures()
{return false;}
public Game newGame(VOXFile mission)
{
return new Game(this, mission);
}//end newGame(...)
/**
* @return the keyStatus
*/
public KeyStatus getKeyStatus()
{
return keyStatus;
}
public void setGlobalPalette(Color[] palette){
globalPalette = palette;
darkIsClearPalette = new Color[256];
for(int i=0; i<256; i++){
float newAlpha=(float)Math.pow(((palette[i].getRed()+palette[i].getGreen()+palette[i].getBlue())/(3f*255f)),.5);
darkIsClearPalette[i]=new Color(palette[i].getRed()/255f,palette[i].getGreen()/255f,palette[i].getBlue()/255f,newAlpha);
}//end for(i)
}
public Color [] getGlobalPalette(){return globalPalette;}
public Color [] getDarkIsClearPalette(){return darkIsClearPalette;}
public GPU getGPU(){return gpu;}
/**
* @return the renderer
*/
public Renderer getRenderer()
{
return renderer;
}
/**
* @return the world
*/
public World getWorld()
{
return world;
}
public ThreadManager getThreadManager()
{return threadManager;}
public CollisionManager getCollisionManager()
{return collisionManager;}
public void setPlayer(Player player)
{this.player=player;}
public Player getPlayer(){return player;}
/**
* @return the reporter
*/
public Reporter getReporter() {
return reporter;
}
public ManuallySetController getThrottleMeter() {
return throttleMeter;
}
/**
* @return the healthMeter
*/
public ManuallySetController getHealthMeter() {
return healthMeter;
}
/**
* @param healthMeter the healthMeter to set
*/
public void setHealthMeter(ManuallySetController healthMeter) {
this.healthMeter = healthMeter;
}
/**
* @param throttleMeter the throttleMeter to set
*/
public void setThrottleMeter(ManuallySetController throttleMeter) {
this.throttleMeter = throttleMeter;
}
public void setOverworldSystem(OverworldSystem overworldSystem) {
this.overworldSystem=overworldSystem;
}
/**
* @return the overworldSystem
*/
public OverworldSystem getOverworldSystem() {
return overworldSystem;
}
/**
* @return the altitudeMap
*/
public InterpolatingAltitudeMap getAltitudeMap() {
return altitudeMap;
}
/**
* @param altitudeMap the altitudeMap to set
*/
public void setAltitudeMap(InterpolatingAltitudeMap altitudeMap) {
this.altitudeMap = altitudeMap;
}
/**
* @return the backdropSystem
*/
public BackdropSystem getBackdropSystem() {
return backdropSystem;
}
/**
* @param backdropSystem the backdropSystem to set
*/
public void setBackdropSystem(BackdropSystem backdropSystem) {
this.backdropSystem = backdropSystem;
}
public Game getGame() {
return game;
}
/**
* @return the navSystem
*/
public NAVSystem getNavSystem() {
return navSystem;
}
/**
* @param navSystem the navSystem to set
*/
public void setNavSystem(NAVSystem navSystem) {
this.navSystem = navSystem;
}
/**
* @return the hudSystem
*/
public HUDSystem getHudSystem() {
return hudSystem;
}
/**
* @param hudSystem the hudSystem to set
*/
public void setHudSystem(HUDSystem hudSystem) {
this.hudSystem = hudSystem;
}
}//end TR
| Created legacy2Square static method for calculating texture cells
coordinates from legacy coordinates. | src/main/java/org/jtrfp/trcl/core/TR.java | Created legacy2Square static method for calculating texture cells coordinates from legacy coordinates. | <ide><path>rc/main/java/org/jtrfp/trcl/core/TR.java
<ide> public void setHudSystem(HUDSystem hudSystem) {
<ide> this.hudSystem = hudSystem;
<ide> }
<del> }//end TR
<add>
<add> public static double legacy2MapSquare(double z) {
<add> return ((z/crossPlatformScalar)/mapWidth)*255.;
<add> }
<add>}//end TR |
|
Java | apache-2.0 | bb1bc5db022eb76bd50c3975ca1be3d78fb9efc1 | 0 | utwyko/tmdb-java,UweTrottmann/tmdb-java,GeorgeMe/tmdb-java,ProIcons/tmdb-java,b12kab/tmdblibrary | /*
* Copyright 2012 Uwe Trottmann
*
* 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.uwetrottmann.tmdb.services;
import com.google.gson.reflect.TypeToken;
import com.uwetrottmann.tmdb.TmdbApiBuilder;
import com.uwetrottmann.tmdb.TmdbApiService;
import com.uwetrottmann.tmdb.entities.Movie;
import com.uwetrottmann.tmdb.entities.ResultsPage;
import com.uwetrottmann.tmdb.entities.Trailers;
public class MoviesService extends TmdbApiService {
/**
* Get the basic movie information for a specific movie id.
*
* @param id TMDb id.
* @return Builder instance.
*/
public SummaryBuilder summary(Integer id) {
return new SummaryBuilder(this, id);
}
/**
* Get the trailers for a specific movie id.
*
* @param id TMDb id.
* @return Builder instance.
*/
public TrailerBuilder trailers(Integer id) {
return new TrailerBuilder(this, id);
}
/**
* Get the list of movies playing in theaters. This list refreshes every
* day. The maximum number of items this list will include is 100.
*
* @return Builder instance.
*/
public NowPlayingBuilder nowPlaying() {
return new NowPlayingBuilder(this);
}
/**
* Get the list of popular movies on The Movie Database. This list refreshes
* every day.
*
* @return Builder instance.
*/
public PopularBuilder popular() {
return new PopularBuilder(this);
}
/**
* Get the list of upcoming movies. This list refreshes every day. The
* maximum number of items this list will include is 100.
*
* @return Builder instance.
*/
public UpcomingBuilder upcoming() {
return new UpcomingBuilder(this);
}
public static final class SummaryBuilder extends TmdbApiBuilder<Movie> {
private static final String URI = "/movie/" + FIELD_ID + FIELD_API_KEY + FIELD_LANGUAGE;
private SummaryBuilder(MoviesService service, Integer id) {
super(service, new TypeToken<Movie>() {
}, URI);
field(FIELD_ID, id);
}
/**
* Set the language. Attention: will not default to English, but instead
* will return empty field.
*
* @param languageCode ISO 639-1 code.
*/
public SummaryBuilder language(String languageCode) {
parameter(FIELD_LANGUAGE, languageCode);
return this;
}
}
public static final class TrailerBuilder extends TmdbApiBuilder<Trailers> {
private static final String URI = "/movie/" + FIELD_ID + "/trailers" + FIELD_API_KEY;
private TrailerBuilder(MoviesService service, Integer id) {
super(service, new TypeToken<Trailers>() {
}, URI);
field(FIELD_ID, id);
}
}
public static final class NowPlayingBuilder extends TmdbApiBuilder<ResultsPage> {
private static final String URI = "/movie/now_playing" + FIELD_API_KEY + FIELD_PAGE
+ FIELD_LANGUAGE;
private NowPlayingBuilder(MoviesService service) {
super(service, new TypeToken<ResultsPage>() {
}, URI);
}
/**
* Set the language (optional). Attention: will not default to English,
* but instead will return empty field.
*
* @param languageCode ISO 639-1 code.
*/
public NowPlayingBuilder language(String languageCode) {
parameter(FIELD_LANGUAGE, languageCode);
return this;
}
/**
* Set the page to return (optional). Values start at 1.
*
* @param page Index of the page.
*/
public NowPlayingBuilder page(int page) {
parameter(FIELD_PAGE, page);
return this;
}
}
public static final class PopularBuilder extends TmdbApiBuilder<ResultsPage> {
private static final String URI = "/movie/popular" + FIELD_API_KEY + FIELD_PAGE
+ FIELD_LANGUAGE;
private PopularBuilder(MoviesService service) {
super(service, new TypeToken<ResultsPage>() {
}, URI);
}
/**
* Set the language (optional). Attention: will not default to English,
* but instead will return empty field.
*
* @param languageCode ISO 639-1 code.
*/
public PopularBuilder language(String languageCode) {
parameter(FIELD_LANGUAGE, languageCode);
return this;
}
/**
* Set the page to return (optional). Values start at 1.
*
* @param page Index of the page.
*/
public PopularBuilder page(int page) {
parameter(FIELD_PAGE, page);
return this;
}
}
public static final class UpcomingBuilder extends TmdbApiBuilder<ResultsPage> {
private static final String URI = "/movie/upcoming" + FIELD_API_KEY + FIELD_PAGE
+ FIELD_LANGUAGE;
private UpcomingBuilder(MoviesService service) {
super(service, new TypeToken<ResultsPage>() {
}, URI);
}
/**
* Set the language (optional). Attention: will not default to English,
* but instead will return empty field.
*
* @param languageCode ISO 639-1 code.
*/
public UpcomingBuilder language(String languageCode) {
parameter(FIELD_LANGUAGE, languageCode);
return this;
}
/**
* Set the page to return (optional). Values start at 1.
*
* @param page Index of the page.
*/
public UpcomingBuilder page(int page) {
parameter(FIELD_PAGE, page);
return this;
}
}
}
| src/main/java/com/uwetrottmann/tmdb/services/MoviesService.java | /*
* Copyright 2012 Uwe Trottmann
*
* 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.uwetrottmann.tmdb.services;
import com.google.gson.reflect.TypeToken;
import com.uwetrottmann.tmdb.TmdbApiBuilder;
import com.uwetrottmann.tmdb.TmdbApiService;
import com.uwetrottmann.tmdb.entities.Movie;
import com.uwetrottmann.tmdb.entities.ResultsPage;
import com.uwetrottmann.tmdb.entities.Trailers;
public class MoviesService extends TmdbApiService {
/**
* Get the basic movie information for a specific movie id.
*
* @param id TMDb id.
* @return Builder instance.
*/
public SummaryBuilder summary(Integer id) {
return new SummaryBuilder(this, id);
}
/**
* Get the basic movie information for a specific movie id.
*
* @param id TMDb id.
* @param langCode ISO 639-1 code.
* @return Builder instance.
*/
public SummaryBuilder summary(Integer id, String langCode) {
return new SummaryBuilder(this, id).language(langCode);
}
/**
* Get the trailers for a specific movie id.
*
* @param id TMDb id.
* @return Builder instance.
*/
public TrailerBuilder trailers(Integer id) {
return new TrailerBuilder(this, id);
}
/**
* Get the list of popular movies on The Movie Database. This list refreshes
* every day.
*
* @return Builder instance.
*/
public PopularBuilder popular() {
return new PopularBuilder(this);
}
/**
* Get the list of popular movies on The Movie Database. This list refreshes
* every day.
*
* @param langCode ISO 639-1 code.
* @return Builder instance.
*/
public PopularBuilder popular(String langCode) {
return new PopularBuilder(this).language(langCode);
}
public static final class SummaryBuilder extends TmdbApiBuilder<Movie> {
private static final String URI = "/movie/" + FIELD_ID + FIELD_API_KEY + FIELD_LANGUAGE;
private SummaryBuilder(MoviesService service, Integer id) {
super(service, new TypeToken<Movie>() {
}, URI);
field(FIELD_ID, id);
}
/**
* Set the language. Attention: will not default to English, but instead
* will return empty field.
*
* @param languageCode ISO 639-1 code.
*/
public SummaryBuilder language(String languageCode) {
parameter(FIELD_LANGUAGE, languageCode);
return this;
}
}
public static final class TrailerBuilder extends TmdbApiBuilder<Trailers> {
private static final String URI = "/movie/" + FIELD_ID + "/trailers" + FIELD_API_KEY;
private TrailerBuilder(MoviesService service, Integer id) {
super(service, new TypeToken<Trailers>() {
}, URI);
field(FIELD_ID, id);
}
}
public static final class PopularBuilder extends TmdbApiBuilder<ResultsPage> {
private static final String URI = "/movie/popular" + FIELD_API_KEY + FIELD_PAGE
+ FIELD_LANGUAGE;
private PopularBuilder(MoviesService service) {
super(service, new TypeToken<ResultsPage>() {
}, URI);
}
private PopularBuilder(MoviesService service, int page) {
this(service);
parameter(FIELD_PAGE, page);
}
/**
* Set the language. Attention: will not default to English, but instead
* will return empty field.
*
* @param languageCode ISO 639-1 code.
*/
public PopularBuilder language(String languageCode) {
parameter(FIELD_LANGUAGE, languageCode);
return this;
}
}
}
| Support /3/movie/upcoming, /3/movie/now_playing. Remove optional lang methods, instead call builder method directly.
| src/main/java/com/uwetrottmann/tmdb/services/MoviesService.java | Support /3/movie/upcoming, /3/movie/now_playing. Remove optional lang methods, instead call builder method directly. | <ide><path>rc/main/java/com/uwetrottmann/tmdb/services/MoviesService.java
<ide> }
<ide>
<ide> /**
<del> * Get the basic movie information for a specific movie id.
<del> *
<del> * @param id TMDb id.
<del> * @param langCode ISO 639-1 code.
<del> * @return Builder instance.
<del> */
<del> public SummaryBuilder summary(Integer id, String langCode) {
<del> return new SummaryBuilder(this, id).language(langCode);
<del> }
<del>
<del> /**
<ide> * Get the trailers for a specific movie id.
<ide> *
<ide> * @param id TMDb id.
<ide> }
<ide>
<ide> /**
<add> * Get the list of movies playing in theaters. This list refreshes every
<add> * day. The maximum number of items this list will include is 100.
<add> *
<add> * @return Builder instance.
<add> */
<add> public NowPlayingBuilder nowPlaying() {
<add> return new NowPlayingBuilder(this);
<add> }
<add>
<add> /**
<ide> * Get the list of popular movies on The Movie Database. This list refreshes
<ide> * every day.
<ide> *
<ide> }
<ide>
<ide> /**
<del> * Get the list of popular movies on The Movie Database. This list refreshes
<del> * every day.
<del> *
<del> * @param langCode ISO 639-1 code.
<del> * @return Builder instance.
<del> */
<del> public PopularBuilder popular(String langCode) {
<del> return new PopularBuilder(this).language(langCode);
<add> * Get the list of upcoming movies. This list refreshes every day. The
<add> * maximum number of items this list will include is 100.
<add> *
<add> * @return Builder instance.
<add> */
<add> public UpcomingBuilder upcoming() {
<add> return new UpcomingBuilder(this);
<ide> }
<ide>
<ide> public static final class SummaryBuilder extends TmdbApiBuilder<Movie> {
<ide> }, URI);
<ide>
<ide> field(FIELD_ID, id);
<add> }
<add> }
<add>
<add> public static final class NowPlayingBuilder extends TmdbApiBuilder<ResultsPage> {
<add> private static final String URI = "/movie/now_playing" + FIELD_API_KEY + FIELD_PAGE
<add> + FIELD_LANGUAGE;
<add>
<add> private NowPlayingBuilder(MoviesService service) {
<add> super(service, new TypeToken<ResultsPage>() {
<add> }, URI);
<add> }
<add>
<add> /**
<add> * Set the language (optional). Attention: will not default to English,
<add> * but instead will return empty field.
<add> *
<add> * @param languageCode ISO 639-1 code.
<add> */
<add> public NowPlayingBuilder language(String languageCode) {
<add> parameter(FIELD_LANGUAGE, languageCode);
<add> return this;
<add> }
<add>
<add> /**
<add> * Set the page to return (optional). Values start at 1.
<add> *
<add> * @param page Index of the page.
<add> */
<add> public NowPlayingBuilder page(int page) {
<add> parameter(FIELD_PAGE, page);
<add> return this;
<ide> }
<ide> }
<ide>
<ide> }, URI);
<ide> }
<ide>
<del> private PopularBuilder(MoviesService service, int page) {
<del> this(service);
<del>
<add> /**
<add> * Set the language (optional). Attention: will not default to English,
<add> * but instead will return empty field.
<add> *
<add> * @param languageCode ISO 639-1 code.
<add> */
<add> public PopularBuilder language(String languageCode) {
<add> parameter(FIELD_LANGUAGE, languageCode);
<add> return this;
<add> }
<add>
<add> /**
<add> * Set the page to return (optional). Values start at 1.
<add> *
<add> * @param page Index of the page.
<add> */
<add> public PopularBuilder page(int page) {
<ide> parameter(FIELD_PAGE, page);
<del> }
<del>
<del> /**
<del> * Set the language. Attention: will not default to English, but instead
<del> * will return empty field.
<del> *
<del> * @param languageCode ISO 639-1 code.
<del> */
<del> public PopularBuilder language(String languageCode) {
<del> parameter(FIELD_LANGUAGE, languageCode);
<add> return this;
<add> }
<add> }
<add>
<add> public static final class UpcomingBuilder extends TmdbApiBuilder<ResultsPage> {
<add> private static final String URI = "/movie/upcoming" + FIELD_API_KEY + FIELD_PAGE
<add> + FIELD_LANGUAGE;
<add>
<add> private UpcomingBuilder(MoviesService service) {
<add> super(service, new TypeToken<ResultsPage>() {
<add> }, URI);
<add> }
<add>
<add> /**
<add> * Set the language (optional). Attention: will not default to English,
<add> * but instead will return empty field.
<add> *
<add> * @param languageCode ISO 639-1 code.
<add> */
<add> public UpcomingBuilder language(String languageCode) {
<add> parameter(FIELD_LANGUAGE, languageCode);
<add> return this;
<add> }
<add>
<add> /**
<add> * Set the page to return (optional). Values start at 1.
<add> *
<add> * @param page Index of the page.
<add> */
<add> public UpcomingBuilder page(int page) {
<add> parameter(FIELD_PAGE, page);
<ide> return this;
<ide> }
<ide> } |
|
Java | apache-2.0 | 844270fcb23589ff59e9a8d0e84c51fb2e7f534a | 0 | PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr | package org.apache.solr.util;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* A simple utility class for posting raw updates to a Solr server,
* has a main method so it can be run on the command line.
* View this not as a best-practice code example, but as a standalone
* example built with an explicit purpose of not having external
* jar dependencies.
*/
public class SimplePostTool {
private static final String DEFAULT_POST_URL = "http://localhost:8983/solr/update";
private static final String VERSION_OF_THIS_TOOL = "1.5";
private static final String DEFAULT_COMMIT = "yes";
private static final String DEFAULT_OPTIMIZE = "no";
private static final String DEFAULT_OUT = "no";
private static final String DEFAULT_AUTO = "no";
private static final String DEFAULT_RECURSIVE = "0";
private static final int DEFAULT_WEB_DELAY = 10;
private static final int MAX_WEB_DEPTH = 10;
private static final String DEFAULT_CONTENT_TYPE = "application/xml";
private static final String DEFAULT_FILE_TYPES = "xml,json,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf,htm,html,txt,log";
static final String DATA_MODE_FILES = "files";
static final String DATA_MODE_ARGS = "args";
static final String DATA_MODE_STDIN = "stdin";
static final String DATA_MODE_WEB = "web";
static final String DEFAULT_DATA_MODE = DATA_MODE_FILES;
// Input args
boolean auto = false;
int recursive = 0;
int delay = 0;
String fileTypes;
URL solrUrl;
OutputStream out = null;
String type;
String mode;
boolean commit;
boolean optimize;
String[] args;
private int currentDepth;
static HashMap<String,String> mimeMap;
GlobFileFilter globFileFilter;
// Backlog for crawling
List<LinkedHashSet<URL>> backlog = new ArrayList<LinkedHashSet<URL>>();
Set<URL> visited = new HashSet<URL>();
static final Set<String> DATA_MODES = new HashSet<String>();
static final String USAGE_STRING_SHORT =
"Usage: java [SystemProperties] -jar post.jar [-h|-] [<file|folder|url|arg> [<file|folder|url|arg>...]]";
// Used in tests to avoid doing actual network traffic
static boolean mockMode = false;
static PageFetcher pageFetcher;
static {
DATA_MODES.add(DATA_MODE_FILES);
DATA_MODES.add(DATA_MODE_ARGS);
DATA_MODES.add(DATA_MODE_STDIN);
DATA_MODES.add(DATA_MODE_WEB);
mimeMap = new HashMap<String,String>();
mimeMap.put("xml", "text/xml");
mimeMap.put("csv", "text/csv");
mimeMap.put("json", "application/json");
mimeMap.put("pdf", "application/pdf");
mimeMap.put("rtf", "text/rtf");
mimeMap.put("html", "text/html");
mimeMap.put("htm", "text/html");
mimeMap.put("doc", "application/msword");
mimeMap.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
mimeMap.put("ppt", "application/vnd.ms-powerpoint");
mimeMap.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
mimeMap.put("xls", "application/vnd.ms-excel");
mimeMap.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
mimeMap.put("odt", "application/vnd.oasis.opendocument.text");
mimeMap.put("ott", "application/vnd.oasis.opendocument.text");
mimeMap.put("odp", "application/vnd.oasis.opendocument.presentation");
mimeMap.put("otp", "application/vnd.oasis.opendocument.presentation");
mimeMap.put("ods", "application/vnd.oasis.opendocument.spreadsheet");
mimeMap.put("ots", "application/vnd.oasis.opendocument.spreadsheet");
mimeMap.put("txt", "text/plain");
mimeMap.put("log", "text/plain");
}
/**
* See usage() for valid command line usage
* @param args the params on the command line
*/
public static void main(String[] args) {
info("SimplePostTool version " + VERSION_OF_THIS_TOOL);
if (0 < args.length && ("-help".equals(args[0]) || "--help".equals(args[0]) || "-h".equals(args[0]))) {
usage();
} else {
final SimplePostTool t = parseArgsAndInit(args);
t.execute();
}
}
/**
* After initialization, call execute to start the post job.
* This method delegates to the correct mode method.
*/
public void execute() {
if (DATA_MODE_FILES.equals(mode) && args.length > 0) {
doFilesMode();
} else if(DATA_MODE_ARGS.equals(mode) && args.length > 0) {
doArgsMode();
} else if(DATA_MODE_WEB.equals(mode) && args.length > 0) {
doWebMode();
} else if(DATA_MODE_STDIN.equals(mode)) {
doStdinMode();
} else {
usageShort();
return;
}
if (commit) commit();
if (optimize) optimize();
}
/**
* Parses incoming arguments and system params and initializes the tool
* @param args the incoming cmd line args
* @return an instance of SimplePostTool
*/
protected static SimplePostTool parseArgsAndInit(String[] args) {
String urlStr = null;
try {
// Parse args
final String mode = System.getProperty("data", DEFAULT_DATA_MODE);
if (! DATA_MODES.contains(mode)) {
fatal("System Property 'data' is not valid for this tool: " + mode);
}
String params = System.getProperty("params", "");
urlStr = System.getProperty("url", DEFAULT_POST_URL);
urlStr = SimplePostTool.appendParam(urlStr, params);
URL url = new URL(urlStr);
boolean auto = isOn(System.getProperty("auto", DEFAULT_AUTO));
String type = System.getProperty("type");
// Recursive
int recursive = 0;
String r = System.getProperty("recursive", DEFAULT_RECURSIVE);
try {
recursive = Integer.parseInt(r);
} catch(Exception e) {
if (isOn(r))
recursive = DATA_MODE_WEB.equals(mode)?1:999;
}
// Delay
int delay = DATA_MODE_WEB.equals(mode) ? DEFAULT_WEB_DELAY : 0;
try {
delay = Integer.parseInt(System.getProperty("delay", ""+delay));
} catch(Exception e) { }
OutputStream out = isOn(System.getProperty("out", DEFAULT_OUT)) ? System.out : null;
String fileTypes = System.getProperty("filetypes", DEFAULT_FILE_TYPES);
boolean commit = isOn(System.getProperty("commit",DEFAULT_COMMIT));
boolean optimize = isOn(System.getProperty("optimize",DEFAULT_OPTIMIZE));
return new SimplePostTool(mode, url, auto, type, recursive, delay, fileTypes, out, commit, optimize, args);
} catch (MalformedURLException e) {
fatal("System Property 'url' is not a valid URL: " + urlStr);
return null;
}
}
/**
* Constructor which takes in all mandatory input for the tool to work.
* Also see usage() for further explanation of the params.
* @param mode whether to post files, web pages, params or stdin
* @param url the Solr base Url to post to, should end with /update
* @param auto if true, we'll guess type and add resourcename/url
* @param type content-type of the data you are posting
* @param recursive number of levels for file/web mode, or 0 if one file only
* @param delay if recursive then delay will be the wait time between posts
* @param fileTypes a comma separated list of file-name endings to accept for file/web
* @param out an OutputStream to write output to, e.g. stdout to print to console
* @param commit if true, will commit at end of posting
* @param optimize if true, will optimize at end of posting
* @param args a String[] of arguments, varies between modes
*/
public SimplePostTool(String mode, URL url, boolean auto, String type,
int recursive, int delay, String fileTypes, OutputStream out,
boolean commit, boolean optimize, String[] args) {
this.mode = mode;
this.solrUrl = url;
this.auto = auto;
this.type = type;
this.recursive = recursive;
this.delay = delay;
this.fileTypes = fileTypes;
this.globFileFilter = getFileFilterFromFileTypes(fileTypes);
this.out = out;
this.commit = commit;
this.optimize = optimize;
this.args = args;
pageFetcher = new PageFetcher();
}
public SimplePostTool() {}
//
// Do some action depending on which mode we have
//
private void doFilesMode() {
currentDepth = 0;
// Skip posting files if special param "-" given
if (!args[0].equals("-")) {
info("Posting files to base url " + solrUrl + (!auto?" using content-type "+(type==null?DEFAULT_CONTENT_TYPE:type):"")+"..");
if(auto)
info("Entering auto mode. File endings considered are "+fileTypes);
if(recursive > 0)
info("Entering recursive mode, max depth="+recursive+", delay="+delay+"s");
int numFilesPosted = postFiles(args, 0, out, type);
info(numFilesPosted + " files indexed.");
}
}
private void doArgsMode() {
info("POSTing args to " + solrUrl + "..");
for (String a : args) {
postData(stringToStream(a), null, out, type, solrUrl);
}
}
private int doWebMode() {
reset();
int numPagesPosted = 0;
try {
if(type != null) {
fatal("Specifying content-type with \"-Ddata=web\" is not supported");
}
if (args[0].equals("-")) {
// Skip posting url if special param "-" given
return 0;
}
// Set Extracting handler as default
solrUrl = appendUrlPath(solrUrl, "/extract");
info("Posting web pages to Solr url "+solrUrl);
auto=true;
info("Entering auto mode. Indexing pages with content-types corresponding to file endings "+fileTypes);
if(recursive > 0) {
if(recursive > MAX_WEB_DEPTH) {
recursive = MAX_WEB_DEPTH;
warn("Too large recursion depth for web mode, limiting to "+MAX_WEB_DEPTH+"...");
}
if(delay < DEFAULT_WEB_DELAY)
warn("Never crawl an external web site faster than every 10 seconds, your IP will probably be blocked");
info("Entering recursive mode, depth="+recursive+", delay="+delay+"s");
}
numPagesPosted = postWebPages(args, 0, out);
info(numPagesPosted + " web pages indexed.");
} catch(MalformedURLException e) {
fatal("Wrong URL trying to append /extract to "+solrUrl);
}
return numPagesPosted;
}
private void doStdinMode() {
info("POSTing stdin to " + solrUrl + "..");
postData(System.in, null, out, type, solrUrl);
}
private void reset() {
fileTypes = DEFAULT_FILE_TYPES;
globFileFilter = this.getFileFilterFromFileTypes(fileTypes);
backlog = new ArrayList<LinkedHashSet<URL>>();
visited = new HashSet<URL>();
}
//
// USAGE
//
private static void usageShort() {
System.out.println(USAGE_STRING_SHORT+"\n"+
" Please invoke with -h option for extended usage help.");
}
private static void usage() {
System.out.println
(USAGE_STRING_SHORT+"\n\n" +
"Supported System Properties and their defaults:\n"+
" -Ddata=files|web|args|stdin (default=" + DEFAULT_DATA_MODE + ")\n"+
" -Dtype=<content-type> (default=" + DEFAULT_CONTENT_TYPE + ")\n"+
" -Durl=<solr-update-url> (default=" + DEFAULT_POST_URL + ")\n"+
" -Dauto=yes|no (default=" + DEFAULT_AUTO + ")\n"+
" -Drecursive=yes|no|<depth> (default=" + DEFAULT_RECURSIVE + ")\n"+
" -Ddelay=<seconds> (default=0 for files, 10 for web)\n"+
" -Dfiletypes=<type>[,<type>,...] (default=" + DEFAULT_FILE_TYPES + ")\n"+
" -Dparams=\"<key>=<value>[&<key>=<value>...]\" (values must be URL-encoded)\n"+
" -Dcommit=yes|no (default=" + DEFAULT_COMMIT + ")\n"+
" -Doptimize=yes|no (default=" + DEFAULT_OPTIMIZE + ")\n"+
" -Dout=yes|no (default=" + DEFAULT_OUT + ")\n\n"+
"This is a simple command line tool for POSTing raw data to a Solr\n"+
"port. Data can be read from files specified as commandline args,\n"+
"URLs specified as args, as raw commandline arg strings or via STDIN.\n"+
"Examples:\n"+
" java -jar post.jar *.xml\n"+
" java -Ddata=args -jar post.jar '<delete><id>42</id></delete>'\n"+
" java -Ddata=stdin -jar post.jar < hd.xml\n"+
" java -Ddata=web -jar post.jar http://example.com/\n"+
" java -Dtype=text/csv -jar post.jar *.csv\n"+
" java -Dtype=application/json -jar post.jar *.json\n"+
" java -Durl=http://localhost:8983/solr/update/extract -Dparams=literal.id=a -Dtype=application/pdf -jar post.jar a.pdf\n"+
" java -Dauto -jar post.jar *\n"+
" java -Dauto -Drecursive -jar post.jar afolder\n"+
" java -Dauto -Dfiletypes=ppt,html -jar post.jar afolder\n"+
"The options controlled by System Properties include the Solr\n"+
"URL to POST to, the Content-Type of the data, whether a commit\n"+
"or optimize should be executed, and whether the response should\n"+
"be written to STDOUT. If auto=yes the tool will try to set type\n"+
"and url automatically from file name. When posting rich documents\n"+
"the file name will be propagated as \"resource.name\" and also used\n"+
"as \"literal.id\". You may override these or any other request parameter\n"+
"through the -Dparams property. To do a commit only, use \"-\" as argument.\n"+
"The web mode is a simple crawler following links within domain, default delay=10s.");
}
/** Post all filenames provided in args
* @param args array of file names
* @param startIndexInArgs offset to start
* @param out output stream to post data to
* @param type default content-type to use when posting (may be overridden in auto mode)
* @return number of files posted
* */
public int postFiles(String [] args,int startIndexInArgs, OutputStream out, String type) {
reset();
int filesPosted = 0;
for (int j = startIndexInArgs; j < args.length; j++) {
File srcFile = new File(args[j]);
if(srcFile.isDirectory() && srcFile.canRead()) {
filesPosted += postDirectory(srcFile, out, type);
} else if (srcFile.isFile() && srcFile.canRead()) {
filesPosted += postFiles(new File[] {srcFile}, out, type);
} else {
File parent = srcFile.getParentFile();
if(parent == null) parent = new File(".");
String fileGlob = srcFile.getName();
GlobFileFilter ff = new GlobFileFilter(fileGlob, false);
File[] files = parent.listFiles(ff);
if(files == null || files.length == 0) {
warn("No files or directories matching "+srcFile);
continue;
}
filesPosted += postFiles(parent.listFiles(ff), out, type);
}
}
return filesPosted;
}
/** Post all filenames provided in args
* @param files array of Files
* @param startIndexInArgs offset to start
* @param out output stream to post data to
* @param type default content-type to use when posting (may be overridden in auto mode)
* @return number of files posted
* */
public int postFiles(File[] files, int startIndexInArgs, OutputStream out, String type) {
reset();
int filesPosted = 0;
for (File srcFile : files) {
if(srcFile.isDirectory() && srcFile.canRead()) {
filesPosted += postDirectory(srcFile, out, type);
} else if (srcFile.isFile() && srcFile.canRead()) {
filesPosted += postFiles(new File[] {srcFile}, out, type);
} else {
File parent = srcFile.getParentFile();
if(parent == null) parent = new File(".");
String fileGlob = srcFile.getName();
GlobFileFilter ff = new GlobFileFilter(fileGlob, false);
File[] fileList = parent.listFiles(ff);
if(fileList == null || fileList.length == 0) {
warn("No files or directories matching "+srcFile);
continue;
}
filesPosted += postFiles(fileList, out, type);
}
}
return filesPosted;
}
/**
* Posts a whole directory
* @return number of files posted total
*/
private int postDirectory(File dir, OutputStream out, String type) {
if(dir.isHidden() && !dir.getName().equals("."))
return(0);
info("Indexing directory "+dir.getPath()+" ("+dir.listFiles(globFileFilter).length+" files, depth="+currentDepth+")");
int posted = 0;
posted += postFiles(dir.listFiles(globFileFilter), out, type);
if(recursive > currentDepth) {
for(File d : dir.listFiles()) {
if(d.isDirectory()) {
currentDepth++;
posted += postDirectory(d, out, type);
currentDepth--;
}
}
}
return posted;
}
/**
* Posts a list of file names
* @return number of files posted
*/
int postFiles(File[] files, OutputStream out, String type) {
int filesPosted = 0;
for(File srcFile : files) {
try {
if(!srcFile.isFile() || srcFile.isHidden())
continue;
postFile(srcFile, out, type);
Thread.sleep(delay * 1000);
filesPosted++;
} catch (InterruptedException e) {
throw new RuntimeException();
}
}
return filesPosted;
}
/**
* This method takes as input a list of start URL strings for crawling,
* adds each one to a backlog and then starts crawling
* @param args the raw input args from main()
* @param startIndexInArgs offset for where to start
* @param out outputStream to write results to
* @return the number of web pages posted
*/
public int postWebPages(String[] args, int startIndexInArgs, OutputStream out) {
reset();
LinkedHashSet<URL> s = new LinkedHashSet<URL>();
for (int j = startIndexInArgs; j < args.length; j++) {
try {
URL u = new URL(normalizeUrlEnding(args[j]));
s.add(u);
} catch(MalformedURLException e) {
warn("Skipping malformed input URL: "+args[j]);
}
}
// Add URLs to level 0 of the backlog and start recursive crawling
backlog.add(s);
return webCrawl(0, out);
}
/**
* Normalizes a URL string by removing anchor part and trailing slash
* @return the normalized URL string
*/
protected static String normalizeUrlEnding(String link) {
if(link.indexOf("#") > -1)
link = link.substring(0,link.indexOf("#"));
if(link.endsWith("?"))
link = link.substring(0,link.length()-1);
if(link.endsWith("/"))
link = link.substring(0,link.length()-1);
return link;
}
/**
* A very simple crawler, pulling URLs to fetch from a backlog and then
* recurses N levels deep if recursive>0. Links are parsed from HTML
* through first getting an XHTML version using SolrCell with extractOnly,
* and followed if they are local. The crawler pauses for a default delay
* of 10 seconds between each fetch, this can be configured in the delay
* variable. This is only meant for test purposes, as it does not respect
* robots or anything else fancy :)
* @param level which level to crawl
* @param out output stream to write to
* @return number of pages crawled on this level and below
*/
protected int webCrawl(int level, OutputStream out) {
int numPages = 0;
LinkedHashSet<URL> stack = backlog.get(level);
int rawStackSize = stack.size();
stack.removeAll(visited);
int stackSize = stack.size();
LinkedHashSet<URL> subStack = new LinkedHashSet<URL>();
info("Entering crawl at level "+level+" ("+rawStackSize+" links total, "+stackSize+" new)");
for(URL u : stack) {
try {
visited.add(u);
PageFetcherResult result = pageFetcher.readPageFromUrl(u);
if(result.httpStatus == 200) {
u = (result.redirectUrl != null) ? result.redirectUrl : u;
URL postUrl = new URL(appendParam(solrUrl.toString(),
"literal.id="+URLEncoder.encode(u.toString(),"UTF-8") +
"&literal.url="+URLEncoder.encode(u.toString(),"UTF-8")));
boolean success = postData(new ByteArrayInputStream(result.content), null, out, result.contentType, postUrl);
if (success) {
info("POSTed web resource "+u+" (depth: "+level+")");
Thread.sleep(delay * 1000);
numPages++;
// Pull links from HTML pages only
if(recursive > level && result.contentType.equals("text/html")) {
Set<URL> children = pageFetcher.getLinksFromWebPage(u, new ByteArrayInputStream(result.content), result.contentType, postUrl);
subStack.addAll(children);
}
} else {
warn("An error occurred while posting "+u);
}
} else {
warn("The URL "+u+" returned a HTTP result status of "+result.httpStatus);
}
} catch (IOException e) {
warn("Caught exception when trying to open connection to "+u+": "+e.getMessage());
} catch (InterruptedException e) {
throw new RuntimeException();
}
}
if(!subStack.isEmpty()) {
backlog.add(subStack);
numPages += webCrawl(level+1, out);
}
return numPages;
}
/**
* Reads an input stream into a byte array
* @param is the input stream
* @return the byte array
* @throws IOException If there is a low-level I/O error.
*/
protected byte[] inputStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int next = is.read();
while (next > -1) {
bos.write(next);
next = is.read();
}
bos.flush();
is.close();
return bos.toByteArray();
}
/**
* Computes the full URL based on a base url and a possibly relative link found
* in the href param of an HTML anchor.
* @param baseUrl the base url from where the link was found
* @param link the absolute or relative link
* @return the string version of the full URL
*/
protected String computeFullUrl(URL baseUrl, String link) {
if(link == null || link.length() == 0) {
return null;
}
if(!link.startsWith("http")) {
if(link.startsWith("/")) {
link = baseUrl.getProtocol() + "://" + baseUrl.getAuthority() + link;
} else {
if(link.contains(":")) {
return null; // Skip non-relative URLs
}
String path = baseUrl.getPath();
if(!path.endsWith("/")) {
int sep = path.lastIndexOf("/");
String file = path.substring(sep+1);
if(file.contains(".") || file.contains("?"))
path = path.substring(0,sep);
}
link = baseUrl.getProtocol() + "://" + baseUrl.getAuthority() + path + "/" + link;
}
}
link = normalizeUrlEnding(link);
String l = link.toLowerCase(Locale.ROOT);
// Simple brute force skip images
if(l.endsWith(".jpg") || l.endsWith(".jpeg") || l.endsWith(".png") || l.endsWith(".gif")) {
return null; // Skip images
}
return link;
}
/**
* Uses the mime-type map to reverse lookup whether the file ending for our type
* is supported by the fileTypes option
* @param type what content-type to lookup
* @return true if this is a supported content type
*/
protected boolean typeSupported(String type) {
for(String key : mimeMap.keySet()) {
if(mimeMap.get(key).equals(type)) {
if(fileTypes.contains(key))
return true;
}
}
return false;
}
/**
* Tests if a string is either "true", "on", "yes" or "1"
* @param property the string to test
* @return true if "on"
*/
protected static boolean isOn(String property) {
return("true,on,yes,1".indexOf(property) > -1);
}
static void warn(String msg) {
System.err.println("SimplePostTool: WARNING: " + msg);
}
static void info(String msg) {
System.out.println(msg);
}
static void fatal(String msg) {
System.err.println("SimplePostTool: FATAL: " + msg);
System.exit(2);
}
/**
* Does a simple commit operation
*/
public void commit() {
info("COMMITting Solr index changes to " + solrUrl + "..");
doGet(appendParam(solrUrl.toString(), "commit=true"));
}
/**
* Does a simple optimize operation
*/
public void optimize() {
info("Performing an OPTIMIZE to " + solrUrl + "..");
doGet(appendParam(solrUrl.toString(), "optimize=true"));
}
/**
* Appends a URL query parameter to a URL
* @param url the original URL
* @param param the parameter(s) to append, separated by "&"
* @return the string version of the resulting URL
*/
public static String appendParam(String url, String param) {
String[] pa = param.split("&");
for(String p : pa) {
if(p.trim().length() == 0) continue;
String[] kv = p.split("=");
if(kv.length == 2) {
url = url + (url.indexOf('?')>0 ? "&" : "?") + kv[0] +"="+ kv[1];
} else {
warn("Skipping param "+p+" which is not on form key=value");
}
}
return url;
}
/**
* Opens the file and posts it's contents to the solrUrl,
* writes to response to output.
*/
public void postFile(File file, OutputStream output, String type) {
InputStream is = null;
try {
URL url = solrUrl;
if(auto) {
if(type == null) {
type = guessType(file);
}
if(type != null) {
if(type.equals("text/xml") || type.equals("text/csv") || type.equals("application/json")) {
// Default handler
} else {
// SolrCell
String urlStr = appendUrlPath(solrUrl, "/extract").toString();
if(urlStr.indexOf("resource.name")==-1)
urlStr = appendParam(urlStr, "resource.name=" + URLEncoder.encode(file.getAbsolutePath(), "UTF-8"));
if(urlStr.indexOf("literal.id")==-1)
urlStr = appendParam(urlStr, "literal.id=" + URLEncoder.encode(file.getAbsolutePath(), "UTF-8"));
url = new URL(urlStr);
}
} else {
warn("Skipping "+file.getName()+". Unsupported file type for auto mode.");
return;
}
} else {
if(type == null) type = DEFAULT_CONTENT_TYPE;
}
info("POSTing file " + file.getName() + (auto?" ("+type+")":""));
is = new FileInputStream(file);
postData(is, (int)file.length(), output, type, url);
} catch (IOException e) {
e.printStackTrace();
warn("Can't open/read file: " + file);
} finally {
try {
if(is!=null) is.close();
} catch (IOException e) {
fatal("IOException while closing file: "+ e);
}
}
}
/**
* Appends to the path of the URL
* @param url the URL
* @param append the path to append
* @return the final URL version
*/
protected static URL appendUrlPath(URL url, String append) throws MalformedURLException {
return new URL(url.getProtocol() + "://" + url.getAuthority() + url.getPath() + append + (url.getQuery() != null ? "?"+url.getQuery() : ""));
}
/**
* Guesses the type of a file, based on file name suffix
* @param file the file
* @return the content-type guessed
*/
protected static String guessType(File file) {
String name = file.getName();
String suffix = name.substring(name.lastIndexOf(".")+1);
return mimeMap.get(suffix.toLowerCase(Locale.ROOT));
}
/**
* Performs a simple get on the given URL
*/
public static void doGet(String url) {
try {
doGet(new URL(url));
} catch (MalformedURLException e) {
warn("The specified URL "+url+" is not a valid URL. Please check");
}
}
/**
* Performs a simple get on the given URL
*/
public static void doGet(URL url) {
try {
if(mockMode) return;
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
if (HttpURLConnection.HTTP_OK != urlc.getResponseCode()) {
warn("Solr returned an error #" + urlc.getResponseCode() +
" " + urlc.getResponseMessage() + " for url "+url);
}
} catch (IOException e) {
warn("An error occurred posting data to "+url+". Please check that Solr is running.");
}
}
/**
* Reads data from the data stream and posts it to solr,
* writes to the response to output
* @return true if success
*/
public boolean postData(InputStream data, Integer length, OutputStream output, String type, URL url) {
if(mockMode) return true;
boolean success = true;
if(type == null)
type = DEFAULT_CONTENT_TYPE;
HttpURLConnection urlc = null;
try {
try {
urlc = (HttpURLConnection) url.openConnection();
try {
urlc.setRequestMethod("POST");
} catch (ProtocolException e) {
fatal("Shouldn't happen: HttpURLConnection doesn't support POST??"+e);
}
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setUseCaches(false);
urlc.setAllowUserInteraction(false);
urlc.setRequestProperty("Content-type", type);
if (null != length) urlc.setFixedLengthStreamingMode(length);
} catch (IOException e) {
fatal("Connection error (is Solr running at " + solrUrl + " ?): " + e);
success = false;
}
OutputStream out = null;
try {
out = urlc.getOutputStream();
pipe(data, out);
} catch (IOException e) {
fatal("IOException while posting data: " + e);
success = false;
} finally {
try { if(out!=null) out.close(); } catch (IOException x) { /*NOOP*/ }
}
InputStream in = null;
try {
if (HttpURLConnection.HTTP_OK != urlc.getResponseCode()) {
warn("Solr returned an error #" + urlc.getResponseCode() +
" " + urlc.getResponseMessage());
success = false;
}
in = urlc.getInputStream();
pipe(in, output);
} catch (IOException e) {
warn("IOException while reading response: " + e);
success = false;
} finally {
try { if(in!=null) in.close(); } catch (IOException x) { /*NOOP*/ }
}
} finally {
if(urlc!=null) urlc.disconnect();
}
return success;
}
/**
* Converts a string to an input stream
* @param s the string
* @return the input stream
*/
public static InputStream stringToStream(String s) {
InputStream is = null;
try {
is = new ByteArrayInputStream(s.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
fatal("Shouldn't happen: UTF-8 not supported?!?!?!");
}
return is;
}
/**
* Pipes everything from the source to the dest. If dest is null,
* then everything is read from source and thrown away.
*/
private static void pipe(InputStream source, OutputStream dest) throws IOException {
byte[] buf = new byte[1024];
int read = 0;
while ( (read = source.read(buf) ) >= 0) {
if (null != dest) dest.write(buf, 0, read);
}
if (null != dest) dest.flush();
}
public GlobFileFilter getFileFilterFromFileTypes(String fileTypes) {
String glob;
if(fileTypes.equals("*"))
glob = ".*";
else
glob = "^.*\\.(" + fileTypes.replace(",", "|") + ")$";
return new GlobFileFilter(glob, true);
}
//
// Utility methods for XPath handing
//
/**
* Gets all nodes matching an XPath
*/
public static NodeList getNodesFromXP(Node n, String xpath) throws XPathExpressionException {
XPathFactory factory = XPathFactory.newInstance();
XPath xp = factory.newXPath();
XPathExpression expr = xp.compile(xpath);
return (NodeList) expr.evaluate(n, XPathConstants.NODESET);
}
/**
* Gets the string content of the matching an XPath
* @param n the node (or doc)
* @param xpath the xpath string
* @param concatAll if true, text from all matching nodes will be concatenated, else only the first returned
*/
public static String getXP(Node n, String xpath, boolean concatAll)
throws XPathExpressionException {
NodeList nodes = getNodesFromXP(n, xpath);
StringBuffer sb = new StringBuffer();
if (nodes.getLength() > 0) {
for(int i = 0; i < nodes.getLength() ; i++) {
sb.append(nodes.item(i).getNodeValue() + " ");
if(!concatAll) break;
}
return sb.toString().trim();
} else
return "";
}
/**
* Takes a string as input and returns a DOM
*/
public static Document makeDom(String in, String inputEncoding) throws SAXException, IOException,
ParserConfigurationException {
InputStream is = new ByteArrayInputStream(in
.getBytes(inputEncoding));
Document dom = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(is);
return dom;
}
/**
* Inner class to filter files based on glob wildcards
*/
class GlobFileFilter implements FileFilter
{
private String _pattern;
private Pattern p;
public GlobFileFilter(String pattern, boolean isRegex)
{
_pattern = pattern;
if(!isRegex) {
_pattern = _pattern
.replace("^", "\\^")
.replace("$", "\\$")
.replace(".", "\\.")
.replace("(", "\\(")
.replace(")", "\\)")
.replace("+", "\\+")
.replace("*", ".*")
.replace("?", ".");
_pattern = "^" + _pattern + "$";
}
try {
p = Pattern.compile(_pattern,Pattern.CASE_INSENSITIVE);
} catch(PatternSyntaxException e) {
fatal("Invalid type list "+pattern+". "+e.getDescription());
}
}
@Override
public boolean accept(File file)
{
return p.matcher(file.getName()).find();
}
}
//
// Simple crawler class which can fetch a page and check for robots.txt
//
class PageFetcher {
Map<String, List<String>> robotsCache;
final String DISALLOW = "Disallow:";
public PageFetcher() {
robotsCache = new HashMap<String,List<String>>();
}
public PageFetcherResult readPageFromUrl(URL u) {
PageFetcherResult res = new PageFetcherResult();
try {
if (isDisallowedByRobots(u)) {
warn("The URL "+u+" is disallowed by robots.txt and will not be crawled.");
res.httpStatus = 403;
visited.add(u);
return res;
}
res.httpStatus = 404;
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestProperty("User-Agent", "SimplePostTool-crawler/"+VERSION_OF_THIS_TOOL+" (http://lucene.apache.org/solr/)");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.connect();
res.httpStatus = conn.getResponseCode();
if(!normalizeUrlEnding(conn.getURL().toString()).equals(normalizeUrlEnding(u.toString()))) {
info("The URL "+u+" caused a redirect to "+conn.getURL());
u = conn.getURL();
res.redirectUrl = u;
visited.add(u);
}
if(res.httpStatus == 200) {
// Raw content type of form "text/html; encoding=utf-8"
String rawContentType = conn.getContentType();
String type = rawContentType.split(";")[0];
if(typeSupported(type)) {
String encoding = conn.getContentEncoding();
InputStream is;
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
is = new GZIPInputStream(conn.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
is = new InflaterInputStream(conn.getInputStream(), new Inflater(true));
} else {
is = conn.getInputStream();
}
// Read into memory, so that we later can pull links from the page without re-fetching
res.content = inputStreamToByteArray(is);
is.close();
} else {
warn("Skipping URL with unsupported type "+type);
res.httpStatus = 415;
}
}
} catch(IOException e) {
warn("IOException when reading page from url "+u+": "+e.getMessage());
}
return res;
}
public boolean isDisallowedByRobots(URL url) {
String host = url.getHost();
String strRobot = url.getProtocol() + "://" + host + "/robots.txt";
List<String> disallows = robotsCache.get(host);
if(disallows == null) {
disallows = new ArrayList<String>();
URL urlRobot;
try {
urlRobot = new URL(strRobot);
disallows = parseRobotsTxt(urlRobot.openStream());
} catch (MalformedURLException e) {
return true; // We cannot trust this robots URL, should not happen
} catch (IOException e) {
// There is no robots.txt, will cache an empty disallow list
}
}
robotsCache.put(host, disallows);
String strURL = url.getFile();
for (String path : disallows) {
if (path.equals("/") || strURL.indexOf(path) == 0)
return true;
}
return false;
}
/**
* Very simple robots.txt parser which obeys all Disallow lines regardless
* of user agent or whether there are valid Allow: lines.
* @param is Input stream of the robots.txt file
* @return a list of disallow paths
* @throws IOException if problems reading the stream
*/
protected List<String> parseRobotsTxt(InputStream is) throws IOException {
List<String> disallows = new ArrayList<String>();
BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String l;
while((l = r.readLine()) != null) {
String[] arr = l.split("#");
if(arr.length == 0) continue;
l = arr[0].trim();
if(l.startsWith(DISALLOW)) {
l = l.substring(DISALLOW.length()).trim();
if(l.length() == 0) continue;
disallows.add(l);
}
}
is.close();
return disallows;
}
/**
* Finds links on a web page, using /extract?extractOnly=true
* @param u the URL of the web page
* @param is the input stream of the page
* @param type the content-type
* @param postUrl the URL (typically /solr/extract) in order to pull out links
* @return a set of URLs parsed from the page
*/
protected Set<URL> getLinksFromWebPage(URL u, InputStream is, String type, URL postUrl) {
Set<URL> l = new HashSet<URL>();
URL url = null;
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
URL extractUrl = new URL(appendParam(postUrl.toString(), "extractOnly=true"));
boolean success = postData(is, null, os, type, extractUrl);
if(success) {
String rawXml = os.toString("UTF-8");
Document d = makeDom(rawXml, "UTF-8");
String innerXml = getXP(d, "/response/str/text()[1]", false);
d = makeDom(innerXml, "UTF-8");
NodeList links = getNodesFromXP(d, "/html/body//a/@href");
for(int i = 0; i < links.getLength(); i++) {
String link = links.item(i).getTextContent();
link = computeFullUrl(u, link);
if(link == null)
continue;
url = new URL(link);
if(url.getAuthority() == null || !url.getAuthority().equals(u.getAuthority()))
continue;
l.add(url);
}
}
} catch (MalformedURLException e) {
warn("Malformed URL "+url);
} catch (IOException e) {
warn("IOException opening URL "+url+": "+e.getMessage());
} catch (Exception e) {
throw new RuntimeException();
}
return l;
}
}
/**
* Utility class to hold the result form a page fetch
*/
public class PageFetcherResult {
int httpStatus = 200;
String contentType = "text/html";
URL redirectUrl = null;
byte[] content;
}
}
| solr/core/src/java/org/apache/solr/util/SimplePostTool.java | package org.apache.solr.util;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* A simple utility class for posting raw updates to a Solr server,
* has a main method so it can be run on the command line.
* View this not as a best-practice code example, but as a standalone
* example built with an explicit purpose of not having external
* jar dependencies.
*/
public class SimplePostTool {
private static final String DEFAULT_POST_URL = "http://localhost:8983/solr/update";
private static final String VERSION_OF_THIS_TOOL = "1.5";
private static final String DEFAULT_COMMIT = "yes";
private static final String DEFAULT_OPTIMIZE = "no";
private static final String DEFAULT_OUT = "no";
private static final String DEFAULT_AUTO = "no";
private static final String DEFAULT_RECURSIVE = "0";
private static final int DEFAULT_WEB_DELAY = 10;
private static final int MAX_WEB_DEPTH = 10;
private static final String DEFAULT_CONTENT_TYPE = "application/xml";
private static final String DEFAULT_FILE_TYPES = "xml,json,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf,htm,html,txt,log";
static final String DATA_MODE_FILES = "files";
static final String DATA_MODE_ARGS = "args";
static final String DATA_MODE_STDIN = "stdin";
static final String DATA_MODE_WEB = "web";
static final String DEFAULT_DATA_MODE = DATA_MODE_FILES;
// Input args
boolean auto = false;
int recursive = 0;
int delay = 0;
String fileTypes;
URL solrUrl;
OutputStream out = null;
String type;
String mode;
boolean commit;
boolean optimize;
String[] args;
private int currentDepth;
static HashMap<String,String> mimeMap;
GlobFileFilter globFileFilter;
// Backlog for crawling
List<LinkedHashSet<URL>> backlog = new ArrayList<LinkedHashSet<URL>>();
Set<URL> visited = new HashSet<URL>();
static final Set<String> DATA_MODES = new HashSet<String>();
static final String USAGE_STRING_SHORT =
"Usage: java [SystemProperties] -jar post.jar [-h|-] [<file|folder|url|arg> [<file|folder|url|arg>...]]";
// Used in tests to avoid doing actual network traffic
static boolean mockMode = false;
static PageFetcher pageFetcher;
static {
DATA_MODES.add(DATA_MODE_FILES);
DATA_MODES.add(DATA_MODE_ARGS);
DATA_MODES.add(DATA_MODE_STDIN);
DATA_MODES.add(DATA_MODE_WEB);
mimeMap = new HashMap<String,String>();
mimeMap.put("xml", "text/xml");
mimeMap.put("csv", "text/csv");
mimeMap.put("json", "application/json");
mimeMap.put("pdf", "application/pdf");
mimeMap.put("rtf", "text/rtf");
mimeMap.put("html", "text/html");
mimeMap.put("htm", "text/html");
mimeMap.put("doc", "application/msword");
mimeMap.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
mimeMap.put("ppt", "application/vnd.ms-powerpoint");
mimeMap.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
mimeMap.put("xls", "application/vnd.ms-excel");
mimeMap.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
mimeMap.put("odt", "application/vnd.oasis.opendocument.text");
mimeMap.put("ott", "application/vnd.oasis.opendocument.text");
mimeMap.put("odp", "application/vnd.oasis.opendocument.presentation");
mimeMap.put("otp", "application/vnd.oasis.opendocument.presentation");
mimeMap.put("ods", "application/vnd.oasis.opendocument.spreadsheet");
mimeMap.put("ots", "application/vnd.oasis.opendocument.spreadsheet");
mimeMap.put("txt", "text/plain");
mimeMap.put("log", "text/plain");
}
/**
* See usage() for valid command line usage
* @param args the params on the command line
*/
public static void main(String[] args) {
info("SimplePostTool version " + VERSION_OF_THIS_TOOL);
if (0 < args.length && ("-help".equals(args[0]) || "--help".equals(args[0]) || "-h".equals(args[0]))) {
usage();
} else {
final SimplePostTool t = parseArgsAndInit(args);
t.execute();
}
}
/**
* After initialization, call execute to start the post job.
* This method delegates to the correct mode method.
*/
public void execute() {
if (DATA_MODE_FILES.equals(mode) && args.length > 0) {
doFilesMode();
} else if(DATA_MODE_ARGS.equals(mode) && args.length > 0) {
doArgsMode();
} else if(DATA_MODE_WEB.equals(mode) && args.length > 0) {
doWebMode();
} else if(DATA_MODE_STDIN.equals(mode)) {
doStdinMode();
} else {
usageShort();
return;
}
if (commit) commit();
if (optimize) optimize();
}
/**
* Parses incoming arguments and system params and initializes the tool
* @param args the incoming cmd line args
* @return an instance of SimplePostTool
*/
protected static SimplePostTool parseArgsAndInit(String[] args) {
String urlStr = null;
try {
// Parse args
final String mode = System.getProperty("data", DEFAULT_DATA_MODE);
if (! DATA_MODES.contains(mode)) {
fatal("System Property 'data' is not valid for this tool: " + mode);
}
String params = System.getProperty("params", "");
urlStr = System.getProperty("url", DEFAULT_POST_URL);
urlStr = SimplePostTool.appendParam(urlStr, params);
URL url = new URL(urlStr);
boolean auto = isOn(System.getProperty("auto", DEFAULT_AUTO));
String type = System.getProperty("type");
// Recursive
int recursive = 0;
String r = System.getProperty("recursive", DEFAULT_RECURSIVE);
try {
recursive = Integer.parseInt(r);
} catch(Exception e) {
if (isOn(r))
recursive = DATA_MODE_WEB.equals(mode)?1:999;
}
// Delay
int delay = DATA_MODE_WEB.equals(mode) ? DEFAULT_WEB_DELAY : 0;
try {
delay = Integer.parseInt(System.getProperty("delay", ""+delay));
} catch(Exception e) { }
OutputStream out = isOn(System.getProperty("out", DEFAULT_OUT)) ? System.out : null;
String fileTypes = System.getProperty("filetypes", DEFAULT_FILE_TYPES);
boolean commit = isOn(System.getProperty("commit",DEFAULT_COMMIT));
boolean optimize = isOn(System.getProperty("optimize",DEFAULT_OPTIMIZE));
return new SimplePostTool(mode, url, auto, type, recursive, delay, fileTypes, out, commit, optimize, args);
} catch (MalformedURLException e) {
fatal("System Property 'url' is not a valid URL: " + urlStr);
return null;
}
}
/**
* Constructor which takes in all mandatory input for the tool to work.
* Also see usage() for further explanation of the params.
* @param mode whether to post files, web pages, params or stdin
* @param url the Solr base Url to post to, should end with /update
* @param auto if true, we'll guess type and add resourcename/url
* @param type content-type of the data you are posting
* @param recursive number of levels for file/web mode, or 0 if one file only
* @param delay if recursive then delay will be the wait time between posts
* @param fileTypes a comma separated list of file-name endings to accept for file/web
* @param out an OutputStream to write output to, e.g. stdout to print to console
* @param commit if true, will commit at end of posting
* @param optimize if true, will optimize at end of posting
* @param args a String[] of arguments, varies between modes
*/
public SimplePostTool(String mode, URL url, boolean auto, String type,
int recursive, int delay, String fileTypes, OutputStream out,
boolean commit, boolean optimize, String[] args) {
this.mode = mode;
this.solrUrl = url;
this.auto = auto;
this.type = type;
this.recursive = recursive;
this.delay = delay;
this.fileTypes = fileTypes;
this.globFileFilter = getFileFilterFromFileTypes(fileTypes);
this.out = out;
this.commit = commit;
this.optimize = optimize;
this.args = args;
pageFetcher = new PageFetcher();
}
public SimplePostTool() {}
//
// Do some action depending on which mode we have
//
private void doFilesMode() {
currentDepth = 0;
// Skip posting files if special param "-" given
if (!args[0].equals("-")) {
info("Posting files to base url " + solrUrl + (!auto?" using content-type "+(type==null?DEFAULT_CONTENT_TYPE:type):"")+"..");
if(auto)
info("Entering auto mode. File endings considered are "+fileTypes);
if(recursive > 0)
info("Entering recursive mode, max depth="+recursive+", delay="+delay+"s");
int numFilesPosted = postFiles(args, 0, out, type);
info(numFilesPosted + " files indexed.");
}
}
private void doArgsMode() {
info("POSTing args to " + solrUrl + "..");
for (String a : args) {
postData(stringToStream(a), null, out, type, solrUrl);
}
}
private int doWebMode() {
reset();
int numPagesPosted = 0;
try {
if(type != null) {
fatal("Specifying content-type with \"-Ddata=web\" is not supported");
}
if (args[0].equals("-")) {
// Skip posting url if special param "-" given
return 0;
}
// Set Extracting handler as default
solrUrl = appendUrlPath(solrUrl, "/extract");
info("Posting web pages to Solr url "+solrUrl);
auto=true;
info("Entering auto mode. Indexing pages with content-types corresponding to file endings "+fileTypes);
if(recursive > 0) {
if(recursive > MAX_WEB_DEPTH) {
recursive = MAX_WEB_DEPTH;
warn("Too large recursion depth for web mode, limiting to "+MAX_WEB_DEPTH+"...");
}
if(delay < DEFAULT_WEB_DELAY)
warn("Never crawl an external web site faster than every 10 seconds, your IP will probably be blocked");
info("Entering recursive mode, depth="+recursive+", delay="+delay+"s");
}
numPagesPosted = postWebPages(args, 0, out);
info(numPagesPosted + " web pages indexed.");
} catch(MalformedURLException e) {
fatal("Wrong URL trying to append /extract to "+solrUrl);
}
return numPagesPosted;
}
private void doStdinMode() {
info("POSTing stdin to " + solrUrl + "..");
postData(System.in, null, out, type, solrUrl);
}
private void reset() {
fileTypes = DEFAULT_FILE_TYPES;
globFileFilter = this.getFileFilterFromFileTypes(fileTypes);
backlog = new ArrayList<LinkedHashSet<URL>>();
visited = new HashSet<URL>();
}
//
// USAGE
//
private static void usageShort() {
System.out.println(USAGE_STRING_SHORT+"\n"+
" Please invoke with -h option for extended usage help.");
}
private static void usage() {
System.out.println
(USAGE_STRING_SHORT+"\n\n" +
"Supported System Properties and their defaults:\n"+
" -Ddata=files|web|args|stdin (default=" + DEFAULT_DATA_MODE + ")\n"+
" -Dtype=<content-type> (default=" + DEFAULT_CONTENT_TYPE + ")\n"+
" -Durl=<solr-update-url> (default=" + DEFAULT_POST_URL + ")\n"+
" -Dauto=yes|no (default=" + DEFAULT_AUTO + ")\n"+
" -Drecursive=yes|no|<depth> (default=" + DEFAULT_RECURSIVE + ")\n"+
" -Ddelay=<seconds> (default=0 for files, 10 for web)\n"+
" -Dfiletypes=<type>[,<type>,...] (default=" + DEFAULT_FILE_TYPES + ")\n"+
" -Dparams=\"<key>=<value>[&<key>=<value>...]\" (values must be URL-encoded)\n"+
" -Dcommit=yes|no (default=" + DEFAULT_COMMIT + ")\n"+
" -Doptimize=yes|no (default=" + DEFAULT_OPTIMIZE + ")\n"+
" -Dout=yes|no (default=" + DEFAULT_OUT + ")\n\n"+
"This is a simple command line tool for POSTing raw data to a Solr\n"+
"port. Data can be read from files specified as commandline args,\n"+
"URLs specified as args, as raw commandline arg strings or via STDIN.\n"+
"Examples:\n"+
" java -jar post.jar *.xml\n"+
" java -Ddata=args -jar post.jar '<delete><id>42</id></delete>'\n"+
" java -Ddata=stdin -jar post.jar < hd.xml\n"+
" java -Ddata=web -jar post.jar http://example.com/\n"+
" java -Dtype=text/csv -jar post.jar *.csv\n"+
" java -Dtype=application/json -jar post.jar *.json\n"+
" java -Durl=http://localhost:8983/solr/update/extract -Dparams=literal.id=a -Dtype=application/pdf -jar post.jar a.pdf\n"+
" java -Dauto -jar post.jar *\n"+
" java -Dauto -Drecursive -jar post.jar afolder\n"+
" java -Dauto -Dfiletypes=ppt,html -jar post.jar afolder\n"+
"The options controlled by System Properties include the Solr\n"+
"URL to POST to, the Content-Type of the data, whether a commit\n"+
"or optimize should be executed, and whether the response should\n"+
"be written to STDOUT. If auto=yes the tool will try to set type\n"+
"and url automatically from file name. When posting rich documents\n"+
"the file name will be propagated as \"resource.name\" and also used\n"+
"as \"literal.id\". You may override these or any other request parameter\n"+
"through the -Dparams property. To do a commit only, use \"-\" as argument.\n"+
"The web mode is a simple crawler following links within domain, default delay=10s.");
}
/** Post all filenames provided in args
* @param args array of file names
* @param startIndexInArgs offset to start
* @param out output stream to post data to
* @param type default content-type to use when posting (may be overridden in auto mode)
* @return number of files posted
* */
public int postFiles(String [] args,int startIndexInArgs, OutputStream out, String type) {
reset();
int filesPosted = 0;
for (int j = startIndexInArgs; j < args.length; j++) {
File srcFile = new File(args[j]);
if(srcFile.isDirectory() && srcFile.canRead()) {
filesPosted += postDirectory(srcFile, out, type);
} else if (srcFile.isFile() && srcFile.canRead()) {
filesPosted += postFiles(new File[] {srcFile}, out, type);
} else {
File parent = srcFile.getParentFile();
if(parent == null) parent = new File(".");
String fileGlob = srcFile.getName();
GlobFileFilter ff = new GlobFileFilter(fileGlob, false);
File[] files = parent.listFiles(ff);
if(files == null || files.length == 0) {
warn("No files or directories matching "+srcFile);
continue;
}
filesPosted += postFiles(parent.listFiles(ff), out, type);
}
}
return filesPosted;
}
/** Post all filenames provided in args
* @param files array of Files
* @param startIndexInArgs offset to start
* @param out output stream to post data to
* @param type default content-type to use when posting (may be overridden in auto mode)
* @return number of files posted
* */
public int postFiles(File[] files, int startIndexInArgs, OutputStream out, String type) {
reset();
int filesPosted = 0;
for (File srcFile : files) {
if(srcFile.isDirectory() && srcFile.canRead()) {
filesPosted += postDirectory(srcFile, out, type);
} else if (srcFile.isFile() && srcFile.canRead()) {
filesPosted += postFiles(new File[] {srcFile}, out, type);
} else {
File parent = srcFile.getParentFile();
if(parent == null) parent = new File(".");
String fileGlob = srcFile.getName();
GlobFileFilter ff = new GlobFileFilter(fileGlob, false);
File[] fileList = parent.listFiles(ff);
if(fileList == null || fileList.length == 0) {
warn("No files or directories matching "+srcFile);
continue;
}
filesPosted += postFiles(fileList, out, type);
}
}
return filesPosted;
}
/**
* Posts a whole directory
* @return number of files posted total
*/
private int postDirectory(File dir, OutputStream out, String type) {
if(dir.isHidden() && !dir.getName().equals("."))
return(0);
info("Indexing directory "+dir.getPath()+" ("+dir.listFiles(globFileFilter).length+" files, depth="+currentDepth+")");
int posted = 0;
posted += postFiles(dir.listFiles(globFileFilter), out, type);
if(recursive > currentDepth) {
for(File d : dir.listFiles()) {
if(d.isDirectory()) {
currentDepth++;
posted += postDirectory(d, out, type);
currentDepth--;
}
}
}
return posted;
}
/**
* Posts a list of file names
* @return number of files posted
*/
int postFiles(File[] files, OutputStream out, String type) {
int filesPosted = 0;
for(File srcFile : files) {
try {
if(!srcFile.isFile() || srcFile.isHidden())
continue;
postFile(srcFile, out, type);
Thread.sleep(delay * 1000);
filesPosted++;
} catch (InterruptedException e) {
throw new RuntimeException();
}
}
return filesPosted;
}
/**
* This method takes as input a list of start URL strings for crawling,
* adds each one to a backlog and then starts crawling
* @param args the raw input args from main()
* @param startIndexInArgs offset for where to start
* @param out outputStream to write results to
* @return the number of web pages posted
*/
public int postWebPages(String[] args, int startIndexInArgs, OutputStream out) {
reset();
LinkedHashSet<URL> s = new LinkedHashSet<URL>();
for (int j = startIndexInArgs; j < args.length; j++) {
try {
URL u = new URL(normalizeUrlEnding(args[j]));
s.add(u);
} catch(MalformedURLException e) {
warn("Skipping malformed input URL: "+args[j]);
}
}
// Add URLs to level 0 of the backlog and start recursive crawling
backlog.add(s);
return webCrawl(0, out);
}
/**
* Normalizes a URL string by removing anchor part and trailing slash
* @return the normalized URL string
*/
protected static String normalizeUrlEnding(String link) {
if(link.indexOf("#") > -1)
link = link.substring(0,link.indexOf("#"));
if(link.endsWith("?"))
link = link.substring(0,link.length()-1);
if(link.endsWith("/"))
link = link.substring(0,link.length()-1);
return link;
}
/**
* A very simple crawler, pulling URLs to fetch from a backlog and then
* recurses N levels deep if recursive>0. Links are parsed from HTML
* through first getting an XHTML version using SolrCell with extractOnly,
* and followed if they are local. The crawler pauses for a default delay
* of 10 seconds between each fetch, this can be configured in the delay
* variable. This is only meant for test purposes, as it does not respect
* robots or anything else fancy :)
* @param level which level to crawl
* @param out output stream to write to
* @return number of pages crawled on this level and below
*/
protected int webCrawl(int level, OutputStream out) {
int numPages = 0;
LinkedHashSet<URL> stack = backlog.get(level);
int rawStackSize = stack.size();
stack.removeAll(visited);
int stackSize = stack.size();
LinkedHashSet<URL> subStack = new LinkedHashSet<URL>();
info("Entering crawl at level "+level+" ("+rawStackSize+" links total, "+stackSize+" new)");
for(URL u : stack) {
try {
visited.add(u);
PageFetcherResult result = pageFetcher.readPageFromUrl(u);
if(result.httpStatus == 200) {
u = (result.redirectUrl != null) ? result.redirectUrl : u;
URL postUrl = new URL(appendParam(solrUrl.toString(),
"literal.id="+URLEncoder.encode(u.toString(),"UTF-8") +
"&literal.url="+URLEncoder.encode(u.toString(),"UTF-8")));
boolean success = postData(new ByteArrayInputStream(result.content), null, out, result.contentType, postUrl);
if (success) {
info("POSTed web resource "+u+" (depth: "+level+")");
Thread.sleep(delay * 1000);
numPages++;
// Pull links from HTML pages only
if(recursive > level && result.contentType.equals("text/html")) {
Set<URL> children = pageFetcher.getLinksFromWebPage(u, new ByteArrayInputStream(result.content), result.contentType, postUrl);
subStack.addAll(children);
}
} else {
warn("An error occurred while posting "+u);
}
} else {
warn("The URL "+u+" returned a HTTP result status of "+result.httpStatus);
}
} catch (IOException e) {
warn("Caught exception when trying to open connection to "+u+": "+e.getMessage());
} catch (InterruptedException e) {
throw new RuntimeException();
}
}
if(!subStack.isEmpty()) {
backlog.add(subStack);
numPages += webCrawl(level+1, out);
}
return numPages;
}
/**
* Reads an input stream into a byte array
* @param is the input stream
* @return the byte array
* @throws IOException If there is a low-level I/O error.
*/
protected byte[] inputStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int next = is.read();
while (next > -1) {
bos.write(next);
next = is.read();
}
bos.flush();
is.close();
return bos.toByteArray();
}
/**
* Computes the full URL based on a base url and a possibly relative link found
* in the href param of an HTML anchor.
* @param baseUrl the base url from where the link was found
* @param link the absolute or relative link
* @return the string version of the full URL
*/
protected String computeFullUrl(URL baseUrl, String link) {
if(link == null || link.length() == 0) {
return null;
}
if(!link.startsWith("http")) {
if(link.startsWith("/")) {
link = baseUrl.getProtocol() + "://" + baseUrl.getAuthority() + link;
} else {
if(link.contains(":")) {
return null; // Skip non-relative URLs
}
String path = baseUrl.getPath();
if(!path.endsWith("/")) {
int sep = path.lastIndexOf("/");
String file = path.substring(sep+1);
if(file.contains(".") || file.contains("?"))
path = path.substring(0,sep);
}
link = baseUrl.getProtocol() + "://" + baseUrl.getAuthority() + path + "/" + link;
}
}
link = normalizeUrlEnding(link);
String l = link.toLowerCase(Locale.ROOT);
// Simple brute force skip images
if(l.endsWith(".jpg") || l.endsWith(".jpeg") || l.endsWith(".png") || l.endsWith(".gif")) {
return null; // Skip images
}
return link;
}
/**
* Uses the mime-type map to reverse lookup whether the file ending for our type
* is supported by the fileTypes option
* @param type what content-type to lookup
* @return true if this is a supported content type
*/
protected boolean typeSupported(String type) {
for(String key : mimeMap.keySet()) {
if(mimeMap.get(key).equals(type)) {
if(fileTypes.contains(key))
return true;
}
}
return false;
}
/**
* Tests if a string is either "true", "on", "yes" or "1"
* @param property the string to test
* @return true if "on"
*/
protected static boolean isOn(String property) {
return("true,on,yes,1".indexOf(property) > -1);
}
static void warn(String msg) {
System.err.println("SimplePostTool: WARNING: " + msg);
}
static void info(String msg) {
System.out.println(msg);
}
static void fatal(String msg) {
System.err.println("SimplePostTool: FATAL: " + msg);
System.exit(2);
}
/**
* Does a simple commit operation
*/
public void commit() {
info("COMMITting Solr index changes to " + solrUrl + "..");
doGet(appendParam(solrUrl.toString(), "commit=true"));
}
/**
* Does a simple optimize operation
*/
public void optimize() {
info("Performing an OPTIMIZE to " + solrUrl + "..");
doGet(appendParam(solrUrl.toString(), "optimize=true"));
}
/**
* Appends a URL query parameter to a URL
* @param url the original URL
* @param param the parameter(s) to append, separated by "&"
* @return the string version of the resulting URL
*/
public static String appendParam(String url, String param) {
String[] pa = param.split("&");
for(String p : pa) {
if(p.trim().length() == 0) continue;
String[] kv = p.split("=");
if(kv.length == 2) {
url = url + (url.indexOf('?')>0 ? "&" : "?") + kv[0] +"="+ kv[1];
} else {
warn("Skipping param "+p+" which is not on form key=value");
}
}
return url;
}
/**
* Opens the file and posts it's contents to the solrUrl,
* writes to response to output.
*/
public void postFile(File file, OutputStream output, String type) {
InputStream is = null;
try {
URL url = solrUrl;
if(auto) {
if(type == null) {
type = guessType(file);
}
if(type != null) {
if(type.equals("text/xml") || type.equals("text/csv") || type.equals("application/json")) {
// Default handler
} else {
// SolrCell
String urlStr = appendUrlPath(solrUrl, "/extract").toString();
if(urlStr.indexOf("resource.name")==-1)
urlStr = appendParam(urlStr, "resource.name=" + URLEncoder.encode(file.getAbsolutePath(), "UTF-8"));
if(urlStr.indexOf("literal.id")==-1)
urlStr = appendParam(urlStr, "literal.id=" + URLEncoder.encode(file.getAbsolutePath(), "UTF-8"));
url = new URL(urlStr);
}
} else {
warn("Skipping "+file.getName()+". Unsupported file type for auto mode.");
return;
}
} else {
if(type == null) type = DEFAULT_CONTENT_TYPE;
}
info("POSTing file " + file.getName() + (auto?" ("+type+")":""));
is = new FileInputStream(file);
postData(is, (int)file.length(), output, type, url);
} catch (IOException e) {
e.printStackTrace();
warn("Can't open/read file: " + file);
} finally {
try {
if(is!=null) is.close();
} catch (IOException e) {
fatal("IOException while closing file: "+ e);
}
}
}
/**
* Appends to the path of the URL
* @param url the URL
* @param append the path to append
* @return the final URL version
*/
protected static URL appendUrlPath(URL url, String append) throws MalformedURLException {
return new URL(url.getProtocol() + "://" + url.getAuthority() + url.getPath() + append + (url.getQuery() != null ? "?"+url.getQuery() : ""));
}
/**
* Guesses the type of a file, based on file name suffix
* @param file the file
* @return the content-type guessed
*/
protected static String guessType(File file) {
String name = file.getName();
String suffix = name.substring(name.lastIndexOf(".")+1);
return mimeMap.get(suffix.toLowerCase(Locale.ROOT));
}
/**
* Performs a simple get on the given URL
*/
public static void doGet(String url) {
try {
doGet(new URL(url));
} catch (MalformedURLException e) {
warn("The specified URL "+url+" is not a valid URL. Please check");
}
}
/**
* Performs a simple get on the given URL
*/
public static void doGet(URL url) {
try {
if(mockMode) return;
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
if (HttpURLConnection.HTTP_OK != urlc.getResponseCode()) {
warn("Solr returned an error #" + urlc.getResponseCode() +
" " + urlc.getResponseMessage() + " for url "+url);
}
} catch (IOException e) {
warn("An error occured posting data to "+url+". Please check that Solr is running.");
}
}
/**
* Reads data from the data stream and posts it to solr,
* writes to the response to output
* @return true if success
*/
public boolean postData(InputStream data, Integer length, OutputStream output, String type, URL url) {
if(mockMode) return true;
boolean success = true;
if(type == null)
type = DEFAULT_CONTENT_TYPE;
HttpURLConnection urlc = null;
try {
try {
urlc = (HttpURLConnection) url.openConnection();
try {
urlc.setRequestMethod("POST");
} catch (ProtocolException e) {
fatal("Shouldn't happen: HttpURLConnection doesn't support POST??"+e);
}
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setUseCaches(false);
urlc.setAllowUserInteraction(false);
urlc.setRequestProperty("Content-type", type);
if (null != length) urlc.setFixedLengthStreamingMode(length);
} catch (IOException e) {
fatal("Connection error (is Solr running at " + solrUrl + " ?): " + e);
success = false;
}
OutputStream out = null;
try {
out = urlc.getOutputStream();
pipe(data, out);
} catch (IOException e) {
fatal("IOException while posting data: " + e);
success = false;
} finally {
try { if(out!=null) out.close(); } catch (IOException x) { /*NOOP*/ }
}
InputStream in = null;
try {
if (HttpURLConnection.HTTP_OK != urlc.getResponseCode()) {
warn("Solr returned an error #" + urlc.getResponseCode() +
" " + urlc.getResponseMessage());
success = false;
}
in = urlc.getInputStream();
pipe(in, output);
} catch (IOException e) {
warn("IOException while reading response: " + e);
success = false;
} finally {
try { if(in!=null) in.close(); } catch (IOException x) { /*NOOP*/ }
}
} finally {
if(urlc!=null) urlc.disconnect();
}
return success;
}
/**
* Converts a string to an input stream
* @param s the string
* @return the input stream
*/
public static InputStream stringToStream(String s) {
InputStream is = null;
try {
is = new ByteArrayInputStream(s.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
fatal("Shouldn't happen: UTF-8 not supported?!?!?!");
}
return is;
}
/**
* Pipes everything from the source to the dest. If dest is null,
* then everything is read from source and thrown away.
*/
private static void pipe(InputStream source, OutputStream dest) throws IOException {
byte[] buf = new byte[1024];
int read = 0;
while ( (read = source.read(buf) ) >= 0) {
if (null != dest) dest.write(buf, 0, read);
}
if (null != dest) dest.flush();
}
public GlobFileFilter getFileFilterFromFileTypes(String fileTypes) {
String glob;
if(fileTypes.equals("*"))
glob = ".*";
else
glob = "^.*\\.(" + fileTypes.replace(",", "|") + ")$";
return new GlobFileFilter(glob, true);
}
//
// Utility methods for XPath handing
//
/**
* Gets all nodes matching an XPath
*/
public static NodeList getNodesFromXP(Node n, String xpath) throws XPathExpressionException {
XPathFactory factory = XPathFactory.newInstance();
XPath xp = factory.newXPath();
XPathExpression expr = xp.compile(xpath);
return (NodeList) expr.evaluate(n, XPathConstants.NODESET);
}
/**
* Gets the string content of the matching an XPath
* @param n the node (or doc)
* @param xpath the xpath string
* @param concatAll if true, text from all matching nodes will be concatenated, else only the first returned
*/
public static String getXP(Node n, String xpath, boolean concatAll)
throws XPathExpressionException {
NodeList nodes = getNodesFromXP(n, xpath);
StringBuffer sb = new StringBuffer();
if (nodes.getLength() > 0) {
for(int i = 0; i < nodes.getLength() ; i++) {
sb.append(nodes.item(i).getNodeValue() + " ");
if(!concatAll) break;
}
return sb.toString().trim();
} else
return "";
}
/**
* Takes a string as input and returns a DOM
*/
public static Document makeDom(String in, String inputEncoding) throws SAXException, IOException,
ParserConfigurationException {
InputStream is = new ByteArrayInputStream(in
.getBytes(inputEncoding));
Document dom = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(is);
return dom;
}
/**
* Inner class to filter files based on glob wildcards
*/
class GlobFileFilter implements FileFilter
{
private String _pattern;
private Pattern p;
public GlobFileFilter(String pattern, boolean isRegex)
{
_pattern = pattern;
if(!isRegex) {
_pattern = _pattern
.replace("^", "\\^")
.replace("$", "\\$")
.replace(".", "\\.")
.replace("(", "\\(")
.replace(")", "\\)")
.replace("+", "\\+")
.replace("*", ".*")
.replace("?", ".");
_pattern = "^" + _pattern + "$";
}
try {
p = Pattern.compile(_pattern,Pattern.CASE_INSENSITIVE);
} catch(PatternSyntaxException e) {
fatal("Invalid type list "+pattern+". "+e.getDescription());
}
}
@Override
public boolean accept(File file)
{
return p.matcher(file.getName()).find();
}
}
//
// Simple crawler class which can fetch a page and check for robots.txt
//
class PageFetcher {
Map<String, List<String>> robotsCache;
final String DISALLOW = "Disallow:";
public PageFetcher() {
robotsCache = new HashMap<String,List<String>>();
}
public PageFetcherResult readPageFromUrl(URL u) {
PageFetcherResult res = new PageFetcherResult();
try {
if (isDisallowedByRobots(u)) {
warn("The URL "+u+" is disallowed by robots.txt and will not be crawled.");
res.httpStatus = 403;
visited.add(u);
return res;
}
res.httpStatus = 404;
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestProperty("User-Agent", "SimplePostTool-crawler/"+VERSION_OF_THIS_TOOL+" (http://lucene.apache.org/solr/)");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.connect();
res.httpStatus = conn.getResponseCode();
if(!normalizeUrlEnding(conn.getURL().toString()).equals(normalizeUrlEnding(u.toString()))) {
info("The URL "+u+" caused a redirect to "+conn.getURL());
u = conn.getURL();
res.redirectUrl = u;
visited.add(u);
}
if(res.httpStatus == 200) {
// Raw content type of form "text/html; encoding=utf-8"
String rawContentType = conn.getContentType();
String type = rawContentType.split(";")[0];
if(typeSupported(type)) {
String encoding = conn.getContentEncoding();
InputStream is;
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
is = new GZIPInputStream(conn.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
is = new InflaterInputStream(conn.getInputStream(), new Inflater(true));
} else {
is = conn.getInputStream();
}
// Read into memory, so that we later can pull links from the page without re-fetching
res.content = inputStreamToByteArray(is);
is.close();
} else {
warn("Skipping URL with unsupported type "+type);
res.httpStatus = 415;
}
}
} catch(IOException e) {
warn("IOException when reading page from url "+u+": "+e.getMessage());
}
return res;
}
public boolean isDisallowedByRobots(URL url) {
String host = url.getHost();
String strRobot = url.getProtocol() + "://" + host + "/robots.txt";
List<String> disallows = robotsCache.get(host);
if(disallows == null) {
disallows = new ArrayList<String>();
URL urlRobot;
try {
urlRobot = new URL(strRobot);
disallows = parseRobotsTxt(urlRobot.openStream());
} catch (MalformedURLException e) {
return true; // We cannot trust this robots URL, should not happen
} catch (IOException e) {
// There is no robots.txt, will cache an empty disallow list
}
}
robotsCache.put(host, disallows);
String strURL = url.getFile();
for (String path : disallows) {
if (path.equals("/") || strURL.indexOf(path) == 0)
return true;
}
return false;
}
/**
* Very simple robots.txt parser which obeys all Disallow lines regardless
* of user agent or whether there are valid Allow: lines.
* @param is Input stream of the robots.txt file
* @return a list of disallow paths
* @throws IOException if problems reading the stream
*/
protected List<String> parseRobotsTxt(InputStream is) throws IOException {
List<String> disallows = new ArrayList<String>();
BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String l;
while((l = r.readLine()) != null) {
String[] arr = l.split("#");
if(arr.length == 0) continue;
l = arr[0].trim();
if(l.startsWith(DISALLOW)) {
l = l.substring(DISALLOW.length()).trim();
if(l.length() == 0) continue;
disallows.add(l);
}
}
is.close();
return disallows;
}
/**
* Finds links on a web page, using /extract?extractOnly=true
* @param u the URL of the web page
* @param is the input stream of the page
* @param type the content-type
* @param postUrl the URL (typically /solr/extract) in order to pull out links
* @return a set of URLs parsed from the page
*/
protected Set<URL> getLinksFromWebPage(URL u, InputStream is, String type, URL postUrl) {
Set<URL> l = new HashSet<URL>();
URL url = null;
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
URL extractUrl = new URL(appendParam(postUrl.toString(), "extractOnly=true"));
boolean success = postData(is, null, os, type, extractUrl);
if(success) {
String rawXml = os.toString("UTF-8");
Document d = makeDom(rawXml, "UTF-8");
String innerXml = getXP(d, "/response/str/text()[1]", false);
d = makeDom(innerXml, "UTF-8");
NodeList links = getNodesFromXP(d, "/html/body//a/@href");
for(int i = 0; i < links.getLength(); i++) {
String link = links.item(i).getTextContent();
link = computeFullUrl(u, link);
if(link == null)
continue;
url = new URL(link);
if(url.getAuthority() == null || !url.getAuthority().equals(u.getAuthority()))
continue;
l.add(url);
}
}
} catch (MalformedURLException e) {
warn("Malformed URL "+url);
} catch (IOException e) {
warn("IOException opening URL "+url+": "+e.getMessage());
} catch (Exception e) {
throw new RuntimeException();
}
return l;
}
}
/**
* Utility class to hold the result form a page fetch
*/
public class PageFetcherResult {
int httpStatus = 200;
String contentType = "text/html";
URL redirectUrl = null;
byte[] content;
}
}
| fix misspelling in warning output text (merged from trunk)
git-svn-id: 13f9c63152c129021c7e766f4ef575faaaa595a2@1432938 13f79535-47bb-0310-9956-ffa450edef68
| solr/core/src/java/org/apache/solr/util/SimplePostTool.java | fix misspelling in warning output text (merged from trunk) | <ide><path>olr/core/src/java/org/apache/solr/util/SimplePostTool.java
<ide> " " + urlc.getResponseMessage() + " for url "+url);
<ide> }
<ide> } catch (IOException e) {
<del> warn("An error occured posting data to "+url+". Please check that Solr is running.");
<add> warn("An error occurred posting data to "+url+". Please check that Solr is running.");
<ide> }
<ide> }
<ide> |
|
Java | bsd-2-clause | 0a0a25bf24464a4b2e6d740094d39ff302407dd5 | 0 | TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2012 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package imagej;
import imagej.event.ImageJEvent;
import imagej.plugin.PluginIndex;
import imagej.service.Service;
import imagej.service.ServiceHelper;
import imagej.service.ServiceIndex;
import imagej.util.CheckSezpoz;
import imagej.util.POM;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* Top-level application context for ImageJ, which initializes and maintains a
* list of services.
*
* @author Curtis Rueden
* @see Service
*/
public class ImageJ {
/** @deprecated Use {@link ImageJ#getVersion()} instead. */
@Deprecated
public static final String VERSION = "2.0.0-beta4-DEV";
/** Creates a new ImageJ application context with all available services. */
public static ImageJ createContext() {
try {
if (!CheckSezpoz.check(false)) {
// SezPoz uses ClassLoader.getResources() which will now pick up the apt-generated annotations.
System.err.println("SezPoz generated annotations."); // no log service yet
}
}
catch (final IOException e) {
e.printStackTrace();
}
return createContext((List<Class<? extends Service>>) null);
}
/** Creates a new ImageJ application context with no services. */
public static ImageJ createEmptyContext() {
return createContext(new ArrayList<Class<? extends Service>>());
}
/**
* Creates a new ImageJ application context with the specified service (and
* any required service dependencies).
*/
public static ImageJ createContext(
final Class<? extends Service> serviceClass)
{
// NB: Although the createContext(Class<? extends Service>...) method
// covers a superset of this case, it results in a warning in client code.
// Needing a single service (e.g., for unit testing) is common enough to
// warrant this extra method to avoid the problem for this special case.
final List<Class<? extends Service>> serviceClassList =
new ArrayList<Class<? extends Service>>();
serviceClassList.add(serviceClass);
return createContext(serviceClassList);
}
/**
* Creates a new ImageJ application context with the specified services (and
* any required service dependencies).
*/
public static ImageJ createContext(
final Class<? extends Service>... serviceClasses)
{
final List<Class<? extends Service>> serviceClassList;
if (serviceClasses == null || serviceClasses.length == 0) {
serviceClassList = null;
}
else {
serviceClassList = Arrays.asList(serviceClasses);
}
return createContext(serviceClassList);
}
// TODO - remove this!
private static ImageJ staticContext;
/**
* Creates a new ImageJ application context with the specified services (and
* any required service dependencies).
*/
public static ImageJ createContext(
final Collection<Class<? extends Service>> serviceClasses)
{
final ImageJ context = new ImageJ();
staticContext = context; // TEMP
final ServiceHelper serviceHelper =
new ServiceHelper(context, serviceClasses);
serviceHelper.loadServices();
return context;
}
/**
* Gets the static ImageJ application context.
*
* @deprecated Avoid using this method. If you are writing a plugin, you can
* declare the {@link ImageJ} or {@link Service} you want as a
* parameter, with required=true and persist=false. If you are
* writing a tool, you can obtain the {@link ImageJ} context by
* calling {@link ImageJEvent#getContext()}, and then asking that
* context for needed {@link Service} instances by calling
* {@link ImageJ#getService(Class)}. See the classes in
* core/plugins and core/tools for many examples.
*/
@Deprecated
public static ImageJ getContext() {
return staticContext;
}
/**
* Gets the service of the given class for the current ImageJ application
* context.
*
* @deprecated Avoid using this method. If you are writing a plugin, you can
* annotate the {@link ImageJ} or {@link Service} you want as a
* parameter, with required=true and persist=false. If you are
* writing a tool, you can obtain the {@link ImageJ} context by
* calling {@link ImageJEvent#getContext()}, and then asking that
* context for needed {@link Service} instances by calling
* {@link ImageJ#getService(Class)}. See the classes in
* core/plugins and core/tools for many examples.
*/
@Deprecated
public static <S extends Service> S get(final Class<S> serviceClass) {
final ImageJ context = getContext();
if (context == null) return null; // no context
return context.getService(serviceClass);
}
// -- Fields --
/** Title of the application context. */
private String title = "ImageJ";
private final ServiceIndex serviceIndex;
private final PluginIndex pluginIndex;
/** Creates a new ImageJ context. */
public ImageJ() {
serviceIndex = new ServiceIndex();
pluginIndex = new PluginIndex();
pluginIndex.discover();
}
// -- ImageJ methods --
/**
* Gets the title of the application context. The default value is "ImageJ"
* but it can be overridden by calling {@link #setTitle(String)}.
*/
public String getTitle() {
return title;
}
/** Overrides the title of the application context. */
public void setTitle(final String title) {
this.title = title;
}
/**
* Gets the version of the application.
*
* @return The application version, in <code>major.minor.micro</code> format.
*/
public String getVersion() {
final POM pom = POM.getPOM(ImageJ.class, "net.imagej", "ij-core");
return pom.getVersion();
}
public ServiceIndex getServiceIndex() {
return serviceIndex;
}
public PluginIndex getPluginIndex() {
return pluginIndex;
}
/** Gets the service of the given class. */
public <S extends Service> S getService(final Class<S> c) {
return serviceIndex.getService(c);
}
}
| core/core/src/main/java/imagej/ImageJ.java | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2012 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package imagej;
import imagej.event.ImageJEvent;
import imagej.plugin.PluginIndex;
import imagej.service.Service;
import imagej.service.ServiceHelper;
import imagej.service.ServiceIndex;
import imagej.util.CheckSezpoz;
import imagej.util.POM;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* Top-level application context for ImageJ, which initializes and maintains a
* list of services.
*
* @author Curtis Rueden
* @see Service
*/
public class ImageJ {
/** Version of the ImageJ software. */
public static final String VERSION = "2.0.0-beta4-DEV";
/** Creates a new ImageJ application context with all available services. */
public static ImageJ createContext() {
try {
if (!CheckSezpoz.check(false)) {
// SezPoz uses ClassLoader.getResources() which will now pick up the apt-generated annotations.
System.err.println("SezPoz generated annotations."); // no log service yet
}
}
catch (final IOException e) {
e.printStackTrace();
}
return createContext((List<Class<? extends Service>>) null);
}
/** Creates a new ImageJ application context with no services. */
public static ImageJ createEmptyContext() {
return createContext(new ArrayList<Class<? extends Service>>());
}
/**
* Creates a new ImageJ application context with the specified service (and
* any required service dependencies).
*/
public static ImageJ createContext(
final Class<? extends Service> serviceClass)
{
// NB: Although the createContext(Class<? extends Service>...) method
// covers a superset of this case, it results in a warning in client code.
// Needing a single service (e.g., for unit testing) is common enough to
// warrant this extra method to avoid the problem for this special case.
final List<Class<? extends Service>> serviceClassList =
new ArrayList<Class<? extends Service>>();
serviceClassList.add(serviceClass);
return createContext(serviceClassList);
}
/**
* Creates a new ImageJ application context with the specified services (and
* any required service dependencies).
*/
public static ImageJ createContext(
final Class<? extends Service>... serviceClasses)
{
final List<Class<? extends Service>> serviceClassList;
if (serviceClasses == null || serviceClasses.length == 0) {
serviceClassList = null;
}
else {
serviceClassList = Arrays.asList(serviceClasses);
}
return createContext(serviceClassList);
}
// TODO - remove this!
private static ImageJ staticContext;
/**
* Creates a new ImageJ application context with the specified services (and
* any required service dependencies).
*/
public static ImageJ createContext(
final Collection<Class<? extends Service>> serviceClasses)
{
final ImageJ context = new ImageJ();
staticContext = context; // TEMP
final ServiceHelper serviceHelper =
new ServiceHelper(context, serviceClasses);
serviceHelper.loadServices();
return context;
}
/**
* Gets the static ImageJ application context.
*
* @deprecated Avoid using this method. If you are writing a plugin, you can
* declare the {@link ImageJ} or {@link Service} you want as a
* parameter, with required=true and persist=false. If you are
* writing a tool, you can obtain the {@link ImageJ} context by
* calling {@link ImageJEvent#getContext()}, and then asking that
* context for needed {@link Service} instances by calling
* {@link ImageJ#getService(Class)}. See the classes in
* core/plugins and core/tools for many examples.
*/
@Deprecated
public static ImageJ getContext() {
return staticContext;
}
/**
* Gets the service of the given class for the current ImageJ application
* context.
*
* @deprecated Avoid using this method. If you are writing a plugin, you can
* annotate the {@link ImageJ} or {@link Service} you want as a
* parameter, with required=true and persist=false. If you are
* writing a tool, you can obtain the {@link ImageJ} context by
* calling {@link ImageJEvent#getContext()}, and then asking that
* context for needed {@link Service} instances by calling
* {@link ImageJ#getService(Class)}. See the classes in
* core/plugins and core/tools for many examples.
*/
@Deprecated
public static <S extends Service> S get(final Class<S> serviceClass) {
final ImageJ context = getContext();
if (context == null) return null; // no context
return context.getService(serviceClass);
}
// -- Fields --
/** Title of the application context. */
private String title = "ImageJ";
private final ServiceIndex serviceIndex;
private final PluginIndex pluginIndex;
/** Creates a new ImageJ context. */
public ImageJ() {
serviceIndex = new ServiceIndex();
pluginIndex = new PluginIndex();
pluginIndex.discover();
}
// -- ImageJ methods --
/**
* Gets the title of the application context. The default value is "ImageJ"
* but it can be overridden by calling {@link #setTitle(String)}.
*/
public String getTitle() {
return title;
}
/** Overrides the title of the application context. */
public void setTitle(final String title) {
this.title = title;
}
/**
* Gets the version of the application.
*
* @return The application version, in <code>major.minor.micro</code> format.
*/
public String getVersion() {
final POM pom = POM.getPOM(ImageJ.class, "net.imagej", "ij-core");
return pom.getVersion();
}
public ServiceIndex getServiceIndex() {
return serviceIndex;
}
public PluginIndex getPluginIndex() {
return pluginIndex;
}
/** Gets the service of the given class. */
public <S extends Service> S getService(final Class<S> c) {
return serviceIndex.getService(c);
}
}
| Deprecate ImageJ#VERSION constant
Rather, the preferred way to obtain the version of ImageJ is to ask the
context by calling getVersion().
| core/core/src/main/java/imagej/ImageJ.java | Deprecate ImageJ#VERSION constant | <ide><path>ore/core/src/main/java/imagej/ImageJ.java
<ide> */
<ide> public class ImageJ {
<ide>
<del> /** Version of the ImageJ software. */
<add> /** @deprecated Use {@link ImageJ#getVersion()} instead. */
<add> @Deprecated
<ide> public static final String VERSION = "2.0.0-beta4-DEV";
<ide>
<ide> /** Creates a new ImageJ application context with all available services. */ |
|
Java | apache-2.0 | 431abf146b014bdea8d16100ae32adaa51e7826e | 0 | Jasig/cas,apereo/cas,Jasig/cas,philliprower/cas,apereo/cas,fogbeam/cas_mirror,philliprower/cas,philliprower/cas,philliprower/cas,apereo/cas,apereo/cas,philliprower/cas,fogbeam/cas_mirror,apereo/cas,fogbeam/cas_mirror,rkorn86/cas,fogbeam/cas_mirror,leleuj/cas,pdrados/cas,Jasig/cas,leleuj/cas,rkorn86/cas,pdrados/cas,fogbeam/cas_mirror,leleuj/cas,fogbeam/cas_mirror,apereo/cas,rkorn86/cas,leleuj/cas,pdrados/cas,rkorn86/cas,leleuj/cas,pdrados/cas,Jasig/cas,philliprower/cas,leleuj/cas,apereo/cas,pdrados/cas,pdrados/cas,philliprower/cas | package org.apereo.cas.configuration.model.core.util;
import org.apereo.cas.configuration.model.core.ticket.ProxyGrantingTicketProperties;
import org.apereo.cas.configuration.model.core.ticket.ProxyTicketProperties;
import org.apereo.cas.configuration.model.core.ticket.ServiceTicketProperties;
import org.apereo.cas.configuration.model.core.ticket.TicketGrantingTicketProperties;
import org.apereo.cas.configuration.model.core.ticket.registry.TicketRegistryProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
/**
* Configuration properties class for {@code ticket}.
*
* @author Dmitriy Kopylenko
* @since 5.0.0
*/
public class TicketProperties {
@NestedConfigurationProperty
private ProxyGrantingTicketProperties pgt = new ProxyGrantingTicketProperties();
@NestedConfigurationProperty
private EncryptionJwtSigningJwtCryptographyProperties crypto = new EncryptionJwtSigningJwtCryptographyProperties();
@NestedConfigurationProperty
private ProxyTicketProperties pt = new ProxyTicketProperties();
@NestedConfigurationProperty
private TicketRegistryProperties registry = new TicketRegistryProperties();
@NestedConfigurationProperty
private ServiceTicketProperties st = new ServiceTicketProperties();
@NestedConfigurationProperty
private TicketGrantingTicketProperties tgt = new TicketGrantingTicketProperties();
public TicketProperties() {
this.crypto.setEnabled(false);
}
public ProxyGrantingTicketProperties getPgt() {
return pgt;
}
public void setPgt(final ProxyGrantingTicketProperties pgt) {
this.pgt = pgt;
}
public ProxyTicketProperties getPt() {
return pt;
}
public void setPt(final ProxyTicketProperties pt) {
this.pt = pt;
}
public TicketRegistryProperties getRegistry() {
return registry;
}
public void setRegistry(final TicketRegistryProperties registry) {
this.registry = registry;
}
public ServiceTicketProperties getSt() {
return st;
}
public void setSt(final ServiceTicketProperties st) {
this.st = st;
}
public TicketGrantingTicketProperties getTgt() {
return tgt;
}
public void setTgt(final TicketGrantingTicketProperties tgt) {
this.tgt = tgt;
}
public EncryptionJwtSigningJwtCryptographyProperties getCrypto() {
return crypto;
}
public void setCrypto(final EncryptionJwtSigningJwtCryptographyProperties crypto) {
this.crypto = crypto;
}
}
| core/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/model/core/util/TicketProperties.java | package org.apereo.cas.configuration.model.core.util;
import org.apereo.cas.configuration.model.core.ticket.ProxyGrantingTicketProperties;
import org.apereo.cas.configuration.model.core.ticket.ProxyTicketProperties;
import org.apereo.cas.configuration.model.core.ticket.ServiceTicketProperties;
import org.apereo.cas.configuration.model.core.ticket.TicketGrantingTicketProperties;
import org.apereo.cas.configuration.model.core.ticket.registry.TicketRegistryProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
/**
* Configuration properties class for {@code ticket}.
*
* @author Dmitriy Kopylenko
* @since 5.0.0
*/
public class TicketProperties {
@NestedConfigurationProperty
private ProxyGrantingTicketProperties pgt = new ProxyGrantingTicketProperties();
@NestedConfigurationProperty
private EncryptionJwtSigningJwtCryptographyProperties crypto = new EncryptionJwtSigningJwtCryptographyProperties();
@NestedConfigurationProperty
private ProxyTicketProperties pt = new ProxyTicketProperties();
@NestedConfigurationProperty
private TicketRegistryProperties registry = new TicketRegistryProperties();
@NestedConfigurationProperty
private ServiceTicketProperties st = new ServiceTicketProperties();
@NestedConfigurationProperty
private TicketGrantingTicketProperties tgt = new TicketGrantingTicketProperties();
public ProxyGrantingTicketProperties getPgt() {
return pgt;
}
public void setPgt(final ProxyGrantingTicketProperties pgt) {
this.pgt = pgt;
}
public ProxyTicketProperties getPt() {
return pt;
}
public void setPt(final ProxyTicketProperties pt) {
this.pt = pt;
}
public TicketRegistryProperties getRegistry() {
return registry;
}
public void setRegistry(final TicketRegistryProperties registry) {
this.registry = registry;
}
public ServiceTicketProperties getSt() {
return st;
}
public void setSt(final ServiceTicketProperties st) {
this.st = st;
}
public TicketGrantingTicketProperties getTgt() {
return tgt;
}
public void setTgt(final TicketGrantingTicketProperties tgt) {
this.tgt = tgt;
}
public EncryptionJwtSigningJwtCryptographyProperties getCrypto() {
return crypto;
}
public void setCrypto(final EncryptionJwtSigningJwtCryptographyProperties crypto) {
this.crypto = crypto;
}
}
| disable ticket registry encryption by default asa before
| core/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/model/core/util/TicketProperties.java | disable ticket registry encryption by default asa before | <ide><path>ore/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/model/core/util/TicketProperties.java
<ide>
<ide> @NestedConfigurationProperty
<ide> private TicketGrantingTicketProperties tgt = new TicketGrantingTicketProperties();
<del>
<add>
<add> public TicketProperties() {
<add> this.crypto.setEnabled(false);
<add> }
<add>
<ide> public ProxyGrantingTicketProperties getPgt() {
<ide> return pgt;
<ide> } |
|
Java | mit | f5e8d81fe8100d15bced368b09934f7067f7358a | 0 | commercetools/commercetools-payone-integration,commercetools/commercetools-payone-integration | package com.commercetools.util;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Objects;
/**
* Util to make simple retryable HTTP GET/POST requests.
* <p>
* The http client options: <ul>
* <li>reusable, e.g. one instance per application</li>
* <li>multi-threading</li>
* <li>socket/request/connect timeouts are 10 sec</li>
* <li>retries on connections exceptions up to 3 times, if request has not been sent yet
* (see {@link DefaultHttpRequestRetryHandler#isRequestSentRetryEnabled()}
* and {@link #HTTP_REQUEST_RETRY_ON_SOCKET_TIMEOUT})</li>
* <li>connections pool is 200 connections, up to 20 per route (see {@link #CONNECTION_MAX_TOTAL}
* and {@link #CONNECTION_MAX_PER_ROUTE}</li>
* </ul>
* <p>
* This util is intended to replace <i>Unirest</i> and <i>fluent-hc</i> dependencies, which don't propose any flexible
* way to implement retry strategy.
* <p>
* Implementation notes (for developers):<ul>
* <li>remember, the responses must be closed, otherwise the connections won't be return to the pool,
* no new connections will be available and {@link org.apache.http.conn.ConnectionPoolTimeoutException} will be
* thrown. See {@link #executeReadAndCloseRequest(HttpUriRequest)}</li>
* <li>{@link UrlEncodedFormEntity} the charset should be explicitly set to UTF-8, otherwise
* {@link HTTP#DEF_CONTENT_CHARSET ISO_8859_1} is used, which is not acceptable for German alphabet</li>
* </ul>
*/
public final class HttpRequestUtil {
public static final int REQUEST_TIMEOUT = 10000;
public static final int RETRY_TIMES = 3;
private static final int CONNECTION_MAX_TOTAL = 200;
private static final int CONNECTION_MAX_PER_ROUTE = 20;
/**
* This retry handler implementation overrides default list of <i>nonRetriableClasses</i> excluding
* {@link java.io.InterruptedIOException} and {@link ConnectException} so the client will retry on interruption and
* socket timeouts.
* <p>
* The implementation will retry 3 times.
*/
private static final DefaultHttpRequestRetryHandler HTTP_REQUEST_RETRY_ON_SOCKET_TIMEOUT =
new DefaultHttpRequestRetryHandler(RETRY_TIMES, false, Arrays.asList(
UnknownHostException.class,
SSLException.class)) {
// empty implementation, we just need to use protected constructor
};
private static final CloseableHttpClient CLIENT = HttpClientBuilder.create()
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectionRequestTimeout(REQUEST_TIMEOUT)
.setSocketTimeout(REQUEST_TIMEOUT)
.setConnectTimeout(REQUEST_TIMEOUT)
.build())
.setRetryHandler(HTTP_REQUEST_RETRY_ON_SOCKET_TIMEOUT)
.setConnectionManager(buildDefaultConnectionManager())
.build();
private static final BasicResponseHandler BASIC_RESPONSE_HANDLER = new BasicResponseHandler();
private static PoolingHttpClientConnectionManager buildDefaultConnectionManager() {
final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(CONNECTION_MAX_TOTAL);
connectionManager.setDefaultMaxPerRoute(CONNECTION_MAX_PER_ROUTE);
return connectionManager;
}
/**
* Execute retryable HTTP GET request with default {@link #REQUEST_TIMEOUT}
*
* @param url url to get
* @return response from the {@code url}
* @throws IOException in case of a problem or the connection was aborted
*/
public static HttpResponse executeGetRequest(@Nonnull String url) throws IOException {
return executeReadAndCloseRequest(new HttpGet(url));
}
/**
* Make URL request and return a response string.
*
* @param url URL to get/query
* @return response string from the request
* @throws IOException in case of a problem or the connection was aborted
*/
public static String executeGetRequestToString(@Nonnull String url) throws IOException {
return responseToString(executeGetRequest(url));
}
/**
* Execute retryable HTTP POST request with specified {@code timeoutMsec}
*
* @param url url to post
* @param parameters list of values to send as URL encoded form data. If <b>null</b> - not data is sent, but
* empty POST request is executed.
* @return response from the {@code url}
* @throws IOException in case of a problem or the connection was aborted
*/
public static HttpResponse executePostRequest(@Nonnull String url, @Nullable Iterable<? extends NameValuePair> parameters)
throws IOException {
final HttpPost request = new HttpPost(url);
if (parameters != null) {
request.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8));
}
return executeReadAndCloseRequest(request);
}
/**
* Make URL request and return a response string.
*
* @param url URL to post/query
* @param parameters list of values to send as URL encoded form data. If <b>null</b> - not data is sent, but
* empty POST request is executed.
* @return response string from the request
* @throws IOException in case of a problem or the connection was aborted
*/
public static String executePostRequestToString(@Nonnull String url, @Nullable Iterable<? extends NameValuePair> parameters)
throws IOException {
return responseToString(executePostRequest(url, parameters));
}
/**
* Read string content from {@link HttpResponse}.
*
* @param response response to read
* @return string content of the response
* @throws IOException in case of a problem or the connection was aborted
*/
public static String responseToString(@Nonnull final HttpResponse response) throws IOException {
return BASIC_RESPONSE_HANDLER.handleResponse(response);
}
/**
* Short {@link BasicNameValuePair} factory alias.
*
* @param name request argument name
* @param value request argument value. If value is <b>null</b> - {@link BasicNameValuePair#value} set to <b>null</b>,
* otherwise {@link Object#toString()} is applied.
* @return new instance of {@link BasicNameValuePair} with {@code name} and {@code value}
*/
public static BasicNameValuePair nameValue(@Nonnull final String name, @Nullable final Object value) {
return new BasicNameValuePair(name, Objects.toString(value, null));
}
/**
* By default apache httpclient responses are not closed, thus we should explicitly read the stream and close the
* connection.
* <p>
* The connection will be closed even if read exception occurs.
*
* @param request GET/POST/other request to execute, read and close
* @return read and closed {@link CloseableHttpResponse} instance from {@link CloseableHttpClient#execute(HttpUriRequest)}
* where {@link HttpResponse#getEntity()} is set to read string value.
* @throws IOException if reading failed. Note, even in case of exception the {@code response} will be closed.
*/
private static CloseableHttpResponse executeReadAndCloseRequest(@Nonnull final HttpUriRequest request) throws IOException {
final CloseableHttpResponse response = CLIENT.execute(request);
try {
final HttpEntity entity = response.getEntity();
if (entity != null) {
final ByteArrayEntity byteArrayEntity = new ByteArrayEntity(EntityUtils.toByteArray(entity));
final ContentType contentType = ContentType.getOrDefault(entity);
byteArrayEntity.setContentType(contentType.toString());
response.setEntity(byteArrayEntity);
}
} finally {
response.close();
}
return response;
}
private HttpRequestUtil() {
}
}
| service/src/main/java/com/commercetools/util/HttpRequestUtil.java | package com.commercetools.util;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Objects;
/**
* Util to make simple retryable HTTP GET/POST requests.
* <p>
* The http client options: <ul>
* <li>reusable, e.g. one instance per application</li>
* <li>multi-threading</li>
* <li>socket/request/connect timeouts are 10 sec</li>
* <li>retries on connections exceptions up to 3 times, if request has not been sent yet
* (see {@link DefaultHttpRequestRetryHandler#isRequestSentRetryEnabled()}
* and {@link #HTTP_REQUEST_RETRY_ON_SOCKET_TIMEOUT})</li>
* <li>connections pool is 200 connections, up to 20 per route (see {@link #CONNECTION_MAX_TOTAL}
* and {@link #CONNECTION_MAX_PER_ROUTE}</li>
* </ul>
* <p>
* This util is intended to replace <i>Unirest</i> and <i>fluent-hc</i> dependencies, which don't propose any flexible
* way to implement retry strategy.
* <p>
* Implementation notes (for developers):<ul>
* <li>remember, the responses must be closed, otherwise the connections won't be return to the pool,
* no new connections will be available and {@link org.apache.http.conn.ConnectionPoolTimeoutException} will be
* thrown. See {@link #executeReadAndCloseRequest(HttpUriRequest)}</li>
* <li>{@link UrlEncodedFormEntity} the charset should be explicitly set to UTF-8, otherwise
* {@link HTTP#DEF_CONTENT_CHARSET ISO_8859_1} is used, which is not acceptable for German alphabet</li>
* </ul>
*/
public final class HttpRequestUtil {
public static final int REQUEST_TIMEOUT = 10000;
public static final int RETRY_TIMES = 3;
private static final int CONNECTION_MAX_TOTAL = 200;
private static final int CONNECTION_MAX_PER_ROUTE = 20;
/**
* This retry handler implementation overrides default list of <i>nonRetriableClasses</i> excluding
* {@link java.io.InterruptedIOException} and {@link ConnectException} so the client will retry on interruption and
* socket timeouts.
* <p>
* The implementation will retry 3 times.
*/
private static final DefaultHttpRequestRetryHandler HTTP_REQUEST_RETRY_ON_SOCKET_TIMEOUT =
new DefaultHttpRequestRetryHandler(RETRY_TIMES, false, Arrays.asList(
UnknownHostException.class,
SSLException.class)) {
// empty implementation, we just need to use protected constructor
};
private static final CloseableHttpClient CLIENT = HttpClientBuilder.create()
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectionRequestTimeout(REQUEST_TIMEOUT)
.setSocketTimeout(REQUEST_TIMEOUT * 6)
.setConnectTimeout(REQUEST_TIMEOUT)
.build())
.setRetryHandler(HTTP_REQUEST_RETRY_ON_SOCKET_TIMEOUT)
.setConnectionManager(buildDefaultConnectionManager())
.build();
private static final BasicResponseHandler BASIC_RESPONSE_HANDLER = new BasicResponseHandler();
private static PoolingHttpClientConnectionManager buildDefaultConnectionManager() {
final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(CONNECTION_MAX_TOTAL);
connectionManager.setDefaultMaxPerRoute(CONNECTION_MAX_PER_ROUTE);
return connectionManager;
}
/**
* Execute retryable HTTP GET request with default {@link #REQUEST_TIMEOUT}
*
* @param url url to get
* @return response from the {@code url}
* @throws IOException in case of a problem or the connection was aborted
*/
public static HttpResponse executeGetRequest(@Nonnull String url) throws IOException {
return executeReadAndCloseRequest(new HttpGet(url));
}
/**
* Make URL request and return a response string.
*
* @param url URL to get/query
* @return response string from the request
* @throws IOException in case of a problem or the connection was aborted
*/
public static String executeGetRequestToString(@Nonnull String url) throws IOException {
return responseToString(executeGetRequest(url));
}
/**
* Execute retryable HTTP POST request with specified {@code timeoutMsec}
*
* @param url url to post
* @param parameters list of values to send as URL encoded form data. If <b>null</b> - not data is sent, but
* empty POST request is executed.
* @return response from the {@code url}
* @throws IOException in case of a problem or the connection was aborted
*/
public static HttpResponse executePostRequest(@Nonnull String url, @Nullable Iterable<? extends NameValuePair> parameters)
throws IOException {
final HttpPost request = new HttpPost(url);
if (parameters != null) {
request.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8));
}
return executeReadAndCloseRequest(request);
}
/**
* Make URL request and return a response string.
*
* @param url URL to post/query
* @param parameters list of values to send as URL encoded form data. If <b>null</b> - not data is sent, but
* empty POST request is executed.
* @return response string from the request
* @throws IOException in case of a problem or the connection was aborted
*/
public static String executePostRequestToString(@Nonnull String url, @Nullable Iterable<? extends NameValuePair> parameters)
throws IOException {
return responseToString(executePostRequest(url, parameters));
}
/**
* Read string content from {@link HttpResponse}.
*
* @param response response to read
* @return string content of the response
* @throws IOException in case of a problem or the connection was aborted
*/
public static String responseToString(@Nonnull final HttpResponse response) throws IOException {
return BASIC_RESPONSE_HANDLER.handleResponse(response);
}
/**
* Short {@link BasicNameValuePair} factory alias.
*
* @param name request argument name
* @param value request argument value. If value is <b>null</b> - {@link BasicNameValuePair#value} set to <b>null</b>,
* otherwise {@link Object#toString()} is applied.
* @return new instance of {@link BasicNameValuePair} with {@code name} and {@code value}
*/
public static BasicNameValuePair nameValue(@Nonnull final String name, @Nullable final Object value) {
return new BasicNameValuePair(name, Objects.toString(value, null));
}
/**
* By default apache httpclient responses are not closed, thus we should explicitly read the stream and close the
* connection.
* <p>
* The connection will be closed even if read exception occurs.
*
* @param request GET/POST/other request to execute, read and close
* @return read and closed {@link CloseableHttpResponse} instance from {@link CloseableHttpClient#execute(HttpUriRequest)}
* where {@link HttpResponse#getEntity()} is set to read string value.
* @throws IOException if reading failed. Note, even in case of exception the {@code response} will be closed.
*/
private static CloseableHttpResponse executeReadAndCloseRequest(@Nonnull final HttpUriRequest request) throws IOException {
final CloseableHttpResponse response = CLIENT.execute(request);
try {
final HttpEntity entity = response.getEntity();
if (entity != null) {
final ByteArrayEntity byteArrayEntity = new ByteArrayEntity(EntityUtils.toByteArray(entity));
final ContentType contentType = ContentType.getOrDefault(entity);
byteArrayEntity.setContentType(contentType.toString());
response.setEntity(byteArrayEntity);
}
} finally {
response.close();
}
return response;
}
private HttpRequestUtil() {
}
}
| #185: revert socket timeout
| service/src/main/java/com/commercetools/util/HttpRequestUtil.java | #185: revert socket timeout | <ide><path>ervice/src/main/java/com/commercetools/util/HttpRequestUtil.java
<ide> private static final CloseableHttpClient CLIENT = HttpClientBuilder.create()
<ide> .setDefaultRequestConfig(RequestConfig.custom()
<ide> .setConnectionRequestTimeout(REQUEST_TIMEOUT)
<del> .setSocketTimeout(REQUEST_TIMEOUT * 6)
<add> .setSocketTimeout(REQUEST_TIMEOUT)
<ide> .setConnectTimeout(REQUEST_TIMEOUT)
<ide> .build())
<ide> .setRetryHandler(HTTP_REQUEST_RETRY_ON_SOCKET_TIMEOUT) |
|
JavaScript | mit | dc3ed1207e8fe804f47acc9ea0f60dffbd6c2a27 | 0 | SirWinn3r/gauche-ou-droite-client,SirWinn3r/gauche-ou-droite-client,SirWinn3r/gauche-ou-droite-client | import React from 'react'
const CongressmanCard = ({ congressman, infosToDisplay=[], answer }) => (
<div className="congressman-container" >
<div className={'congressman-photo animated ' + (infosToDisplay.includes('name') ? (answer === congressman.side ? 'pulse' : 'shake') : 'fadeInUp')}>
{infosToDisplay.includes('photo') && <img className="congressman-photo" src={congressman.path} alt="Photo d'un député" />}
</div>
<div className="congressman-infos animated fadeInUp">
{infosToDisplay.includes('name') && <span className="congressman-name">{congressman.name}</span>}
{infosToDisplay.includes('party') && <span className="congressman-party">{congressman.parti}</span>}
{infosToDisplay.includes('successRate') && <i className="congressman-successrate">{congressman.average_success * 100}% ont trouvé</i>}
</div>
</div>
)
export default CongressmanCard
| src/components/Quiz/CongressmanCard.js | import React from 'react'
const CongressmanCard = ({ congressman, infosToDisplay=[], answer }) => (
<div className="congressman-container" >
<div className={'congressman-photo animated ' + (infosToDisplay.includes('name') ? (answer == congressman.side ? 'pulse' : 'shake') : 'fadeInUp')}>
{infosToDisplay.includes('photo') && <img className="congressman-photo" src={congressman.path} alt="Photo d'un député" />}
</div>
<div className="congressman-infos animated fadeInUp">
{infosToDisplay.includes('name') && <span className="congressman-name">{congressman.name}</span>}
{infosToDisplay.includes('party') && <span className="congressman-party">{congressman.parti}</span>}
{infosToDisplay.includes('successRate') && <i className="congressman-successrate">{congressman.average_success * 100}% ont trouvé</i>}
</div>
</div>
)
export default CongressmanCard
| Update CongressmanCard.js | src/components/Quiz/CongressmanCard.js | Update CongressmanCard.js | <ide><path>rc/components/Quiz/CongressmanCard.js
<ide>
<ide> const CongressmanCard = ({ congressman, infosToDisplay=[], answer }) => (
<ide> <div className="congressman-container" >
<del> <div className={'congressman-photo animated ' + (infosToDisplay.includes('name') ? (answer == congressman.side ? 'pulse' : 'shake') : 'fadeInUp')}>
<add> <div className={'congressman-photo animated ' + (infosToDisplay.includes('name') ? (answer === congressman.side ? 'pulse' : 'shake') : 'fadeInUp')}>
<ide> {infosToDisplay.includes('photo') && <img className="congressman-photo" src={congressman.path} alt="Photo d'un député" />}
<ide> </div>
<ide> <div className="congressman-infos animated fadeInUp"> |
|
Java | apache-2.0 | ee89ebd7b0bb52c1ff68e17b70581e27334d8548 | 0 | jerrinot/hazelcast-stabilizer,jerrinot/hazelcast-stabilizer,hazelcast/hazelcast-simulator,pveentjer/hazelcast-simulator,pveentjer/hazelcast-simulator,hazelcast/hazelcast-simulator,Donnerbart/hazelcast-simulator,hazelcast/hazelcast-simulator,Donnerbart/hazelcast-simulator | /*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.simulator.tests.icache;
import com.hazelcast.cache.ICache;
import com.hazelcast.config.CacheConfig;
import com.hazelcast.core.IList;
import com.hazelcast.simulator.test.AbstractTest;
import com.hazelcast.simulator.test.BaseThreadState;
import com.hazelcast.simulator.test.annotations.AfterRun;
import com.hazelcast.simulator.test.annotations.Setup;
import com.hazelcast.simulator.test.annotations.TimeStep;
import com.hazelcast.simulator.test.annotations.Verify;
import javax.cache.CacheManager;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import static com.hazelcast.simulator.tests.icache.helpers.CacheUtils.createCacheManager;
import static org.junit.Assert.fail;
/**
* This test is expecting to work with an ICache which has a max-size policy and an eviction-policy
* defined. The run body of the test simply puts random key value pairs to the ICache, and checks
* the size of the ICache has not grown above the defined max size + a configurable size margin.
* As the max-size policy is not a hard limit we use a configurable size margin in the verification
* of the cache size. The test also logs the global max size of the ICache observed from all test
* participants, providing no assertion errors were throw.
*/
public class EvictionICacheTest extends AbstractTest {
public int partitionCount;
// number of bytes for the value/payload of a key
public int valueSize = 2;
private byte[] value;
private ICache<Object, Object> cache;
private int configuredMaxSize;
private Map<Integer, Object> putAllMap = new HashMap<Integer, Object>();
// find estimated max size (entry count) that cache can reach at max
private int estimatedMaxSize;
@Setup
public void setup() {
partitionCount = targetInstance.getPartitionService().getPartitions().size();
value = new byte[valueSize];
Random random = new Random();
random.nextBytes(value);
CacheManager cacheManager = createCacheManager(targetInstance);
cache = (ICache<Object, Object>) cacheManager.getCache(name);
CacheConfig config = cache.getConfiguration(CacheConfig.class);
logger.info(name + ": " + cache.getName() + " config=" + config);
configuredMaxSize = config.getEvictionConfig().getSize();
// we are explicitly using a random key so that all participants of the test do not put keys 0...max
// the size of putAllMap is not guarantied to be configuredMaxSize / 2 as keys are random
for (int i = 0; i < configuredMaxSize / 2; i++) {
putAllMap.put(random.nextInt(), value);
}
int maxEstimatedPartitionSize = com.hazelcast.cache.impl.maxsize.impl.EntryCountCacheMaxSizeChecker
.calculateMaxPartitionSize(configuredMaxSize, partitionCount);
estimatedMaxSize = maxEstimatedPartitionSize * partitionCount;
}
@TimeStep(prob = 0.8)
public void put(ThreadState state) {
int key = state.randomInt();
cache.put(key, value);
state.counter.put++;
state.assertSize();
}
@TimeStep(prob = 0.1)
public void putAsync(ThreadState state) {
int key = state.randomInt();
cache.putAsync(key, value);
state.counter.putAsync++;
state.assertSize();
}
@TimeStep(prob = 0.1)
public void putAll(ThreadState state) {
cache.putAll(putAllMap);
state.counter.putAll++;
state.assertSize();
}
@AfterRun
public void afterRun(ThreadState state) {
targetInstance.getList(name + "max").add(state.max);
targetInstance.getList(name + "counter").add(state.counter);
}
public class ThreadState extends BaseThreadState {
final Counter counter = new Counter();
int max = 0;
void assertSize() {
int size = cache.size();
if (size > max) {
max = size;
}
if (size > estimatedMaxSize) {
fail(name + ": cache " + cache.getName() + " size=" + cache.size()
+ " configuredMaxSize=" + configuredMaxSize + " estimatedMaxSize=" + estimatedMaxSize);
}
}
}
@Verify
public void globalVerify() {
IList<Integer> results = targetInstance.getList(name + "max");
int observedMaxSize = 0;
for (int m : results) {
if (observedMaxSize < m) {
observedMaxSize = m;
}
}
logger.info(name + ": cache " + cache.getName() + " size=" + cache.size() + " configuredMaxSize=" + configuredMaxSize
+ " observedMaxSize=" + observedMaxSize + " estimatedMaxSize=" + estimatedMaxSize);
IList<Counter> counters = targetInstance.getList(name + "counter");
Counter total = new Counter();
for (Counter c : counters) {
total.add(c);
}
logger.info(name + ": " + total);
logger.info(name + ": putAllMap size=" + putAllMap.size());
}
private static class Counter implements Serializable {
int put = 0;
int putAsync = 0;
int putAll = 0;
public void add(Counter c) {
put += c.put;
putAsync += c.putAsync;
putAll += c.putAll;
}
@Override
public String toString() {
return "Counter{"
+ "put=" + put
+ ", putAsync=" + putAsync
+ ", putAll=" + putAll
+ '}';
}
}
}
| tests/tests-common/src/main/java/com/hazelcast/simulator/tests/icache/EvictionICacheTest.java | /*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.simulator.tests.icache;
import com.hazelcast.cache.ICache;
import com.hazelcast.config.CacheConfig;
import com.hazelcast.core.IList;
import com.hazelcast.simulator.test.AbstractTest;
import com.hazelcast.simulator.test.annotations.RunWithWorker;
import com.hazelcast.simulator.test.annotations.Setup;
import com.hazelcast.simulator.test.annotations.Verify;
import com.hazelcast.simulator.worker.selector.OperationSelectorBuilder;
import com.hazelcast.simulator.worker.tasks.AbstractWorker;
import javax.cache.CacheManager;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import static com.hazelcast.simulator.tests.icache.EvictionICacheTest.Operation.PUT;
import static com.hazelcast.simulator.tests.icache.EvictionICacheTest.Operation.PUT_ALL;
import static com.hazelcast.simulator.tests.icache.EvictionICacheTest.Operation.PUT_ASYNC;
import static com.hazelcast.simulator.tests.icache.helpers.CacheUtils.createCacheManager;
import static org.junit.Assert.fail;
/**
* This test is expecting to work with an ICache which has a max-size policy and an eviction-policy
* defined. The run body of the test simply puts random key value pairs to the ICache, and checks
* the size of the ICache has not grown above the defined max size + a configurable size margin.
* As the max-size policy is not a hard limit we use a configurable size margin in the verification
* of the cache size. The test also logs the global max size of the ICache observed from all test
* participants, providing no assertion errors were throw.
*/
public class EvictionICacheTest extends AbstractTest {
enum Operation {
PUT,
PUT_ASYNC,
PUT_ALL,
}
public int partitionCount;
// number of bytes for the value/payload of a key
public int valueSize = 2;
public double putProb = 0.8;
public double putAsyncProb = 0.1;
public double putAllProb = 0.1;
private byte[] value;
private ICache<Object, Object> cache;
private int configuredMaxSize;
private Map<Integer, Object> putAllMap = new HashMap<Integer, Object>();
// find estimated max size (entry count) that cache can reach at max
private int estimatedMaxSize;
private OperationSelectorBuilder<Operation> operationSelectorBuilder = new OperationSelectorBuilder<Operation>();
@Setup
public void setup() {
partitionCount = targetInstance.getPartitionService().getPartitions().size();
value = new byte[valueSize];
Random random = new Random();
random.nextBytes(value);
CacheManager cacheManager = createCacheManager(targetInstance);
cache = (ICache<Object, Object>) cacheManager.getCache(name);
CacheConfig config = cache.getConfiguration(CacheConfig.class);
logger.info(name + ": " + cache.getName() + " config=" + config);
configuredMaxSize = config.getEvictionConfig().getSize();
// we are explicitly using a random key so that all participants of the test do not put keys 0...max
// the size of putAllMap is not guarantied to be configuredMaxSize / 2 as keys are random
for (int i = 0; i < configuredMaxSize / 2; i++) {
putAllMap.put(random.nextInt(), value);
}
int maxEstimatedPartitionSize = com.hazelcast.cache.impl.maxsize.impl.EntryCountCacheMaxSizeChecker
.calculateMaxPartitionSize(configuredMaxSize, partitionCount);
estimatedMaxSize = maxEstimatedPartitionSize * partitionCount;
operationSelectorBuilder
.addOperation(PUT, putProb)
.addOperation(PUT_ASYNC, putAsyncProb)
.addOperation(PUT_ALL, putAllProb);
}
@RunWithWorker
public Worker createWorker() {
return new Worker();
}
private class Worker extends AbstractWorker<Operation> {
private final Counter counter = new Counter();
private int max = 0;
public Worker() {
super(operationSelectorBuilder);
}
@Override
protected void timeStep(Operation operation) throws Exception {
int key = randomInt();
switch (operation) {
case PUT:
cache.put(key, value);
counter.put++;
break;
case PUT_ASYNC:
cache.putAsync(key, value);
counter.putAsync++;
break;
case PUT_ALL:
cache.putAll(putAllMap);
counter.putAll++;
break;
default:
throw new UnsupportedOperationException();
}
int size = cache.size();
if (size > max) {
max = size;
}
if (size > estimatedMaxSize) {
fail(name + ": cache " + cache.getName() + " size=" + cache.size()
+ " configuredMaxSize=" + configuredMaxSize + " estimatedMaxSize=" + estimatedMaxSize);
}
}
@Override
public void afterRun() throws Exception {
targetInstance.getList(name + "max").add(max);
targetInstance.getList(name + "counter").add(counter);
}
}
@Verify
public void globalVerify() {
IList<Integer> results = targetInstance.getList(name + "max");
int observedMaxSize = 0;
for (int m : results) {
if (observedMaxSize < m) {
observedMaxSize = m;
}
}
logger.info(name + ": cache " + cache.getName() + " size=" + cache.size() + " configuredMaxSize=" + configuredMaxSize
+ " observedMaxSize=" + observedMaxSize + " estimatedMaxSize=" + estimatedMaxSize);
IList<Counter> counters = targetInstance.getList(name + "counter");
Counter total = new Counter();
for (Counter c : counters) {
total.add(c);
}
logger.info(name + ": " + total);
logger.info(name + ": putAllMap size=" + putAllMap.size());
}
private static class Counter implements Serializable {
public int put = 0;
public int putAsync = 0;
public int putAll = 0;
public void add(Counter c) {
put += c.put;
putAsync += c.putAsync;
putAll += c.putAll;
}
@Override
public String toString() {
return "Counter{"
+ "put=" + put
+ ", putAsync=" + putAsync
+ ", putAll=" + putAll
+ '}';
}
}
}
| Converted EvictionICacheTest to new timestep approach
| tests/tests-common/src/main/java/com/hazelcast/simulator/tests/icache/EvictionICacheTest.java | Converted EvictionICacheTest to new timestep approach | <ide><path>ests/tests-common/src/main/java/com/hazelcast/simulator/tests/icache/EvictionICacheTest.java
<ide> import com.hazelcast.config.CacheConfig;
<ide> import com.hazelcast.core.IList;
<ide> import com.hazelcast.simulator.test.AbstractTest;
<del>import com.hazelcast.simulator.test.annotations.RunWithWorker;
<add>import com.hazelcast.simulator.test.BaseThreadState;
<add>import com.hazelcast.simulator.test.annotations.AfterRun;
<ide> import com.hazelcast.simulator.test.annotations.Setup;
<add>import com.hazelcast.simulator.test.annotations.TimeStep;
<ide> import com.hazelcast.simulator.test.annotations.Verify;
<del>import com.hazelcast.simulator.worker.selector.OperationSelectorBuilder;
<del>import com.hazelcast.simulator.worker.tasks.AbstractWorker;
<add>
<ide>
<ide> import javax.cache.CacheManager;
<ide> import java.io.Serializable;
<ide> import java.util.Map;
<ide> import java.util.Random;
<ide>
<del>import static com.hazelcast.simulator.tests.icache.EvictionICacheTest.Operation.PUT;
<del>import static com.hazelcast.simulator.tests.icache.EvictionICacheTest.Operation.PUT_ALL;
<del>import static com.hazelcast.simulator.tests.icache.EvictionICacheTest.Operation.PUT_ASYNC;
<ide> import static com.hazelcast.simulator.tests.icache.helpers.CacheUtils.createCacheManager;
<ide> import static org.junit.Assert.fail;
<ide>
<ide> */
<ide> public class EvictionICacheTest extends AbstractTest {
<ide>
<del> enum Operation {
<del> PUT,
<del> PUT_ASYNC,
<del> PUT_ALL,
<del> }
<del>
<ide> public int partitionCount;
<ide>
<ide> // number of bytes for the value/payload of a key
<ide> public int valueSize = 2;
<del>
<del> public double putProb = 0.8;
<del> public double putAsyncProb = 0.1;
<del> public double putAllProb = 0.1;
<ide>
<ide> private byte[] value;
<ide> private ICache<Object, Object> cache;
<ide>
<ide> // find estimated max size (entry count) that cache can reach at max
<ide> private int estimatedMaxSize;
<del>
<del> private OperationSelectorBuilder<Operation> operationSelectorBuilder = new OperationSelectorBuilder<Operation>();
<ide>
<ide> @Setup
<ide> public void setup() {
<ide> int maxEstimatedPartitionSize = com.hazelcast.cache.impl.maxsize.impl.EntryCountCacheMaxSizeChecker
<ide> .calculateMaxPartitionSize(configuredMaxSize, partitionCount);
<ide> estimatedMaxSize = maxEstimatedPartitionSize * partitionCount;
<del>
<del> operationSelectorBuilder
<del> .addOperation(PUT, putProb)
<del> .addOperation(PUT_ASYNC, putAsyncProb)
<del> .addOperation(PUT_ALL, putAllProb);
<ide> }
<ide>
<del> @RunWithWorker
<del> public Worker createWorker() {
<del> return new Worker();
<add> @TimeStep(prob = 0.8)
<add> public void put(ThreadState state) {
<add> int key = state.randomInt();
<add> cache.put(key, value);
<add> state.counter.put++;
<add> state.assertSize();
<ide> }
<ide>
<del> private class Worker extends AbstractWorker<Operation> {
<del> private final Counter counter = new Counter();
<del> private int max = 0;
<add> @TimeStep(prob = 0.1)
<add> public void putAsync(ThreadState state) {
<add> int key = state.randomInt();
<add> cache.putAsync(key, value);
<add> state.counter.putAsync++;
<add> state.assertSize();
<add> }
<ide>
<del> public Worker() {
<del> super(operationSelectorBuilder);
<del> }
<add> @TimeStep(prob = 0.1)
<add> public void putAll(ThreadState state) {
<add> cache.putAll(putAllMap);
<add> state.counter.putAll++;
<add> state.assertSize();
<add> }
<ide>
<del> @Override
<del> protected void timeStep(Operation operation) throws Exception {
<del> int key = randomInt();
<del> switch (operation) {
<del> case PUT:
<del> cache.put(key, value);
<del> counter.put++;
<del> break;
<del> case PUT_ASYNC:
<del> cache.putAsync(key, value);
<del> counter.putAsync++;
<del> break;
<del> case PUT_ALL:
<del> cache.putAll(putAllMap);
<del> counter.putAll++;
<del> break;
<del> default:
<del> throw new UnsupportedOperationException();
<del> }
<add> @AfterRun
<add> public void afterRun(ThreadState state) {
<add> targetInstance.getList(name + "max").add(state.max);
<add> targetInstance.getList(name + "counter").add(state.counter);
<add> }
<ide>
<add> public class ThreadState extends BaseThreadState {
<add> final Counter counter = new Counter();
<add> int max = 0;
<add>
<add> void assertSize() {
<ide> int size = cache.size();
<ide> if (size > max) {
<ide> max = size;
<ide> fail(name + ": cache " + cache.getName() + " size=" + cache.size()
<ide> + " configuredMaxSize=" + configuredMaxSize + " estimatedMaxSize=" + estimatedMaxSize);
<ide> }
<del> }
<del>
<del> @Override
<del> public void afterRun() throws Exception {
<del> targetInstance.getList(name + "max").add(max);
<del> targetInstance.getList(name + "counter").add(counter);
<ide> }
<ide> }
<ide>
<ide> }
<ide>
<ide> private static class Counter implements Serializable {
<del> public int put = 0;
<del> public int putAsync = 0;
<del> public int putAll = 0;
<add> int put = 0;
<add> int putAsync = 0;
<add> int putAll = 0;
<ide>
<ide> public void add(Counter c) {
<ide> put += c.put; |
|
Java | apache-2.0 | 21ba15e83a5954473d5043a63c564745397db99f | 0 | greg-dove/flex-falcon,greg-dove/flex-falcon,adufilie/flex-falcon,adufilie/flex-falcon,greg-dove/flex-falcon,greg-dove/flex-falcon,adufilie/flex-falcon,adufilie/flex-falcon | /*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flex.compiler.internal.codegen.databinding;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.flex.compiler.definitions.IClassDefinition;
import org.apache.flex.compiler.definitions.IConstantDefinition;
import org.apache.flex.compiler.definitions.IDefinition;
import org.apache.flex.compiler.definitions.IFunctionDefinition;
import org.apache.flex.compiler.definitions.IInterfaceDefinition;
import org.apache.flex.compiler.definitions.ITypeDefinition;
import org.apache.flex.compiler.definitions.IVariableDefinition;
import org.apache.flex.compiler.internal.codegen.databinding.WatcherInfoBase.WatcherType;
import org.apache.flex.compiler.internal.projects.FlexProject;
import org.apache.flex.compiler.internal.tree.as.FunctionCallNode;
import org.apache.flex.compiler.problems.ICompilerProblem;
import org.apache.flex.compiler.projects.ICompilerProject;
import org.apache.flex.compiler.tree.ASTNodeID;
import org.apache.flex.compiler.tree.as.IASNode;
import org.apache.flex.compiler.tree.as.IExpressionNode;
import org.apache.flex.compiler.tree.as.IFunctionCallNode;
import org.apache.flex.compiler.tree.as.IIdentifierNode;
import org.apache.flex.compiler.tree.as.IMemberAccessExpressionNode;
/**
* Analyzes a node that represents a binding expression, an generates all the
* WatcherInfo objects needed to describe the mx.internal.binding.Watchers we will code gen.
*/
public class WatcherAnalyzer
{
/**
* Constructor
*
* @param bindingDataBase - is where the results of the analysis are stored
* @param problems - is where any semantic problems discuvered during analysis are reported
* @param bindingInfo - is an object created by the BindingAnalyzer to represing the mx.internal.binding.Binding object that will control
* this binding expression
*/
public WatcherAnalyzer(
BindingDatabase bindingDataBase,
Collection<ICompilerProblem> problems,
BindingInfo bindingInfo,
ICompilerProject project)
{
this.bindingDataBase = bindingDataBase;
this.problems = problems;
this.bindingInfo = bindingInfo;
this.project = project;
}
//------------------- private state -----------------------------
private final BindingDatabase bindingDataBase;
private final Collection<ICompilerProblem> problems;
private final BindingInfo bindingInfo;
private final ICompilerProject project;
//------------------------ public functions ----------------------
/**
* structure to holder onto temporary information is we do a
* recursive descent parse of the binding expression node
*/
static class AnalysisState
{
/**
* If true, we we will chain watchers as we find new variables. ex: {a.b}
* If false, we will generate independent watchers ex: { foo(a, b) }
*/
public boolean chaining = false;
/**
* as we are building up a chain of dependent property watchers, curChain
* points to the lowest "link" that was build. Will be null if we are not yet building
* up a chain.
*
* It is of the specific type "PropertyWatcherInfo", because that is the only
* info class that knows how to chain.
*/
public WatcherInfoBase curChain = null;
/**
* While we are parsing a function call node, this will
* hold the definition for it's name
*/
public IDefinition functionCallNameDefintion = null;
/**
* If we are parsing an expression like model.a.b.c.d,
* where "Model" is an ObjectProxy or Model tag
*/
public boolean isObjectProxyExpression = false;
/**
* the event name(s) that the ObjectProxy/Model dispatches.
* We need to pass this back up the parse chain so that the subsequent
* property watchers know the event name(s)
*/
List<String> objectProxyEventNames = null;
}
public void analyze()
{
// When there are multiple expression (concatenating case), then we can
// just analyze each one independently
for (IExpressionNode expression : bindingInfo.getExpressionNodesForGetter())
{
doAnalyze(expression, new AnalysisState()); // recursively analyze the sub-tree.
}
}
private void doAnalyze(IASNode node, AnalysisState state)
{
ASTNodeID id = node.getNodeID();
switch(id)
{
case IdentifierID:
analyzeIdentifierNode((IIdentifierNode)node, state);
break;
case MemberAccessExpressionID:
andalyzeMemberAccessExpression( (IMemberAccessExpressionNode) node, state);
break;
case FunctionCallID:
analyzeFunctionCallNode((IFunctionCallNode) node, state);
break;
default:
// For other kinds of nodes, just recurse down looking for something to do
analyzeChildren(node, state);
break;
}
}
private void analyzeChildren(IASNode node, AnalysisState state)
{
// For other kinds of nodes, just recurse down looking for something to do
for (int i=0; i<node.getChildCount(); ++i)
{
IASNode ch = node.getChild(i);
doAnalyze(ch, state);
}
}
private void analyzeFunctionCallNode(IFunctionCallNode node, AnalysisState state)
{
assert state.functionCallNameDefintion == null; // we can't nest (yet?)
// First, let's get the node the represents the function name.
// That's the one that will have the binding metadata
IExpressionNode nameNode = node.getNameNode();
IDefinition nameDef = nameNode.resolve(project);
// we ignore non-bindable functions
// we also ignore functions that don't resolve - they are dynamic, and hence
// not watchable
if (nameDef!=null && nameDef.isBindable())
{
state.functionCallNameDefintion = nameDef;
}
analyzeChildren(node, state); // continue down looking for watchers.
state.functionCallNameDefintion = null; // now we are done with the function call node
}
private void andalyzeMemberAccessExpression(IMemberAccessExpressionNode node, AnalysisState state)
{
final boolean wasChaining = state.chaining;
state.chaining = true; // member access expressions require chained watcher.
// ex: {a.b} - the watcher for b will be a child of a
final IExpressionNode left = node.getLeftOperandNode();
final IExpressionNode right = node.getRightOperandNode();
final IDefinition leftDef = left.resolve(project);
final IDefinition rightDef = right.resolve(project);
if (leftDef instanceof IClassDefinition)
{
// In this case, is foo.prop, where "foo" is a class name.
// We can skip over the left side ("foo"), because when we
// analyze the right side we will still know what it is.
doAnalyze(right, state);
}
else
{
if ((rightDef == null) && (leftDef != null))
{
// maybe we are something like ObjectProxy.dynamicProperty
// (someone who extends ObjectProxy, like Model)
ITypeDefinition leftType= leftDef.resolveType(project);
FlexProject project = (FlexProject)this.project;
String objectProxyClass = project.getObjectProxyClass();
boolean isProxy = leftType==null ? false : leftType.isInstanceOf(objectProxyClass, project);
// If we are proxy.prop, we set this info into the parse state. This does two things:
// 1) tells downstream properties that they can be dynamic, and hence don't need
// to be resolvable.
// 2) Stores off the event names from the proxy so that the chained property watchers
// can use the info
if (isProxy)
{
state.isObjectProxyExpression = true;
state.objectProxyEventNames = leftType.getBindableEventNames();
}
}
doAnalyze(left, state);
doAnalyze(right, state);
}
// If we are finished generating the chain for the top member access expression,
// then shut off chaining. Otherwise the next variable we see might get added to this chain,
// even though is it not related
if (!wasChaining)
{
state.chaining = false;
state.curChain = null;
}
// If we are finished with a chain of ObjectProxy.prop.prop things,
// then clear out the remembered info from the ObjectProxy.
// Note that this "termination condition" is quite different from the one above.
// Above the logic was "I'm going to set this, recursively apply to children, then clear.
// In this case, the logic is "I'm going to set and forget, because my PARENT want these results.
// Eventually I can clear it when my I can determine that my parent is not part of the chain.
if ( state.isObjectProxyExpression)
{
IASNode parent = node.getParent();
if (!(parent instanceof IMemberAccessExpressionNode))
{
state.isObjectProxyExpression = false;
state.objectProxyEventNames = null;
}
}
}
private void analyzeIdentifierNode(IIdentifierNode node, AnalysisState state)
{
IDefinition def = node.resolve(project);
if ((def == null) && !state.isObjectProxyExpression)
{
return; // this is not "defensive programming"!
// we fully expect to get non-resolvable identifiers in some cases:
// a) bad code.
// b) "this"
// It should be fine to skip over these and continue without creating a watcher
// If, on the other hand, we are in an object proxy, then we
// may very well be a dynamic property with no definition,
// so will will continue on (with the knowledge that we have no
// IDefinition
}
if (def instanceof IConstantDefinition)
{
return; // we can ignore constants - they can't be watched
}
assert state.chaining || state.curChain==null; // we shouldn't have a chain if we aren't chaining
// Now round up the arguments to make the watcher info
List<String> eventNames = null;
WatcherType type = WatcherType.ERROR;
String name = null;
Object id = null;
if ((def == null) && state.isObjectProxyExpression)
{
// we are in a dynamic property situation...
type = WatcherType.PROPERTY; // always use property watcher
name = node.getName(); // get the property name from the id node, since
// we have no definition
id = node; //use the parse node as identifier for the watcher, since
// we don't have an identifier to use. Not that this means we can't
// share dynamic property watchers. too bad!
eventNames = state.objectProxyEventNames; // use the event names we remembered from the proxy
}
else
{
// we are a not a dynamic property
// Check to see if we are a cast. If so, we can ignore
if (def instanceof IClassDefinition || def instanceof IInterfaceDefinition)
{
// we are an identifier that resolves to a class. perhaps we are a cast?
// we are a case if the node parent is a function call, but in any case
// if we see a class here it's either a cast, or it's just a class name
// in an expression.
// If it's a cast, there's nothing wrong. If it's a class, we treat it like a constant string
// bottom line: don't try to make a watcher, and don't generate a problem
return;
}
type = determineWatcherType(def); // figure out what kind of watcher to make
if (type == WatcherType.ERROR)
{
System.err.println("can't get watcher for " + def);
return; // This should never happen. If it does, there is presumably a bug.
// But - better to recover here, than to go on and NPE.
// This is a workaround for CMP-1283
}
// if it's a function, make sure it is the one from the function call expression we are parsing
// If it isn't, just return. This might happen if, for example, the function was
// not bindable - then functionCallNameDefintion would be null.
// I suspect there are other cases, too.
if (type == WatcherType.FUNCTION)
{
if (def != state.functionCallNameDefintion)
return;
}
eventNames = WatcherInfoBase.getEventNamesFromDefinition(def, problems, node, project);
name = def.getBaseName();
id = def;
}
makeWatcherOfKnownType(id, type, state, node, eventNames, name, def);
// Now, check if we need to make an XML watcher. These are special:
// We make an XMLWatcher and a property watcher to watch the same thing, so two of them
// are created in this one call
if (def instanceof IVariableDefinition)
{
// Is the def for an XML type variable?
IVariableDefinition var = (IVariableDefinition)def;
ITypeDefinition varType = var.resolveType(project);
// note that varType might be null if code is bad
boolean isVarXML = (varType==null) ? false : varType.isInstanceOf("XML", project);
if (isVarXML)
{
// if XML,then create a watcher for it.
String key = "XML"; // using this unique key will work, but it means we can never
// share these. Which is OK.
List<String> empty = Collections.emptyList();
makeWatcherOfKnownType(key, WatcherType.XML, state, node, empty, name, null);
}
}
}
/**
* Master "factory function" for Watcher Info
* You should always use this factory, rather than instantiating the directly, as it is
* easier and more reliable to user this function.
*
* @param watcherKey is unique object "key" to refer to the created watcher. Often an IDefintion
* @param type is which kind of watcher we want to create
* @param state must be passed in so we can chain watchers as we create them during parse time
* @param node the node that corresponds to the object we will be watching
* @param eventNames the events that the watcher must listen to
* @param name the name of the property or function that we will be watching
* @param optionalDefinition the IDefinition for the node. Only required for Static Property Watchers
*/
private void makeWatcherOfKnownType(
Object watcherKey,
WatcherType type,
AnalysisState state,
IASNode node,
List<String> eventNames,
String name,
IDefinition optionalDefinition)
{
assert(eventNames != null);
assert(name != null);
WatcherInfoBase watcherInfo = bindingDataBase.getOrCreateWatcher(
state.curChain,
type,
watcherKey,
problems,
node,
eventNames);
// After doing the "generic creation" we need to do some type specific
// setup
if (type == WatcherType.FUNCTION)
{
// TODO: couldn't we move this into a ctor somehow?
FunctionWatcherInfo fwi = (FunctionWatcherInfo)watcherInfo;
// fwi.setFunctionName(def.getName());
fwi.setFunctionName(name);
// Note: we might want to retrieve the function arguments in the future.
// But they aren't available on this object - they are on the original FunctionCallExpression node
FunctionCallNode fnNode = (FunctionCallNode)node.getAncestorOfType(FunctionCallNode.class);
IExpressionNode[] paramNodes = fnNode.getArgumentNodes();
fwi.params = paramNodes;
}
else if ((type == WatcherType.STATIC_PROPERTY) || (type == WatcherType.PROPERTY))
{
PropertyWatcherInfo pwi = (PropertyWatcherInfo)watcherInfo;
pwi.setPropertyName(name);
// TODO: can we just have a "name" on the base class??
}
else if (type == WatcherType.XML)
{
XMLWatcherInfo xwi = (XMLWatcherInfo)watcherInfo;
xwi.setPropertyName(name);
}
if (type == WatcherType.STATIC_PROPERTY)
{
assert optionalDefinition != null;
// static property watchers need this extra call
StaticPropertyWatcherInfo pwi = (StaticPropertyWatcherInfo)watcherInfo;
pwi.init(optionalDefinition, project);
}
watcherInfo.addBinding(bindingInfo); // associate our binding with this watcher
// note that one watcher can have more than one binding.
if (state.chaining)
state.curChain = watcherInfo; // mark this as the new bottom link in the chain
}
private static WatcherType determineWatcherType(IDefinition definition)
{
WatcherType ret = WatcherType.ERROR;
if (definition == null) return ret; // there are "special" watchers where this will be null
if (definition instanceof IVariableDefinition)
{
if (!definition.isStatic())
{
// we use regular property watchers on non-static variables
ret = WatcherType.PROPERTY;
}
else
{
ret = WatcherType.STATIC_PROPERTY;
}
}
else if (definition instanceof IFunctionDefinition)
{
ret = WatcherType.FUNCTION;
}
else assert false;
return ret;
}
}
| compiler/src/org/apache/flex/compiler/internal/codegen/databinding/WatcherAnalyzer.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flex.compiler.internal.codegen.databinding;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.flex.compiler.definitions.IClassDefinition;
import org.apache.flex.compiler.definitions.IConstantDefinition;
import org.apache.flex.compiler.definitions.IDefinition;
import org.apache.flex.compiler.definitions.IFunctionDefinition;
import org.apache.flex.compiler.definitions.ITypeDefinition;
import org.apache.flex.compiler.definitions.IVariableDefinition;
import org.apache.flex.compiler.internal.codegen.databinding.WatcherInfoBase.WatcherType;
import org.apache.flex.compiler.internal.projects.FlexProject;
import org.apache.flex.compiler.internal.tree.as.FunctionCallNode;
import org.apache.flex.compiler.problems.ICompilerProblem;
import org.apache.flex.compiler.projects.ICompilerProject;
import org.apache.flex.compiler.tree.ASTNodeID;
import org.apache.flex.compiler.tree.as.IASNode;
import org.apache.flex.compiler.tree.as.IExpressionNode;
import org.apache.flex.compiler.tree.as.IFunctionCallNode;
import org.apache.flex.compiler.tree.as.IIdentifierNode;
import org.apache.flex.compiler.tree.as.IMemberAccessExpressionNode;
/**
* Analyzes a node that represents a binding expression, an generates all the
* WatcherInfo objects needed to describe the mx.internal.binding.Watchers we will code gen.
*/
public class WatcherAnalyzer
{
/**
* Constructor
*
* @param bindingDataBase - is where the results of the analysis are stored
* @param problems - is where any semantic problems discuvered during analysis are reported
* @param bindingInfo - is an object created by the BindingAnalyzer to represing the mx.internal.binding.Binding object that will control
* this binding expression
*/
public WatcherAnalyzer(
BindingDatabase bindingDataBase,
Collection<ICompilerProblem> problems,
BindingInfo bindingInfo,
ICompilerProject project)
{
this.bindingDataBase = bindingDataBase;
this.problems = problems;
this.bindingInfo = bindingInfo;
this.project = project;
}
//------------------- private state -----------------------------
private final BindingDatabase bindingDataBase;
private final Collection<ICompilerProblem> problems;
private final BindingInfo bindingInfo;
private final ICompilerProject project;
//------------------------ public functions ----------------------
/**
* structure to holder onto temporary information is we do a
* recursive descent parse of the binding expression node
*/
static class AnalysisState
{
/**
* If true, we we will chain watchers as we find new variables. ex: {a.b}
* If false, we will generate independent watchers ex: { foo(a, b) }
*/
public boolean chaining = false;
/**
* as we are building up a chain of dependent property watchers, curChain
* points to the lowest "link" that was build. Will be null if we are not yet building
* up a chain.
*
* It is of the specific type "PropertyWatcherInfo", because that is the only
* info class that knows how to chain.
*/
public WatcherInfoBase curChain = null;
/**
* While we are parsing a function call node, this will
* hold the definition for it's name
*/
public IDefinition functionCallNameDefintion = null;
/**
* If we are parsing an expression like model.a.b.c.d,
* where "Model" is an ObjectProxy or Model tag
*/
public boolean isObjectProxyExpression = false;
/**
* the event name(s) that the ObjectProxy/Model dispatches.
* We need to pass this back up the parse chain so that the subsequent
* property watchers know the event name(s)
*/
List<String> objectProxyEventNames = null;
}
public void analyze()
{
// When there are multiple expression (concatenating case), then we can
// just analyze each one independently
for (IExpressionNode expression : bindingInfo.getExpressionNodesForGetter())
{
doAnalyze(expression, new AnalysisState()); // recursively analyze the sub-tree.
}
}
private void doAnalyze(IASNode node, AnalysisState state)
{
ASTNodeID id = node.getNodeID();
switch(id)
{
case IdentifierID:
analyzeIdentifierNode((IIdentifierNode)node, state);
break;
case MemberAccessExpressionID:
andalyzeMemberAccessExpression( (IMemberAccessExpressionNode) node, state);
break;
case FunctionCallID:
analyzeFunctionCallNode((IFunctionCallNode) node, state);
break;
default:
// For other kinds of nodes, just recurse down looking for something to do
analyzeChildren(node, state);
break;
}
}
private void analyzeChildren(IASNode node, AnalysisState state)
{
// For other kinds of nodes, just recurse down looking for something to do
for (int i=0; i<node.getChildCount(); ++i)
{
IASNode ch = node.getChild(i);
doAnalyze(ch, state);
}
}
private void analyzeFunctionCallNode(IFunctionCallNode node, AnalysisState state)
{
assert state.functionCallNameDefintion == null; // we can't nest (yet?)
// First, let's get the node the represents the function name.
// That's the one that will have the binding metadata
IExpressionNode nameNode = node.getNameNode();
IDefinition nameDef = nameNode.resolve(project);
// we ignore non-bindable functions
// we also ignore functions that don't resolve - they are dynamic, and hence
// not watchable
if (nameDef!=null && nameDef.isBindable())
{
state.functionCallNameDefintion = nameDef;
}
analyzeChildren(node, state); // continue down looking for watchers.
state.functionCallNameDefintion = null; // now we are done with the function call node
}
private void andalyzeMemberAccessExpression(IMemberAccessExpressionNode node, AnalysisState state)
{
final boolean wasChaining = state.chaining;
state.chaining = true; // member access expressions require chained watcher.
// ex: {a.b} - the watcher for b will be a child of a
final IExpressionNode left = node.getLeftOperandNode();
final IExpressionNode right = node.getRightOperandNode();
final IDefinition leftDef = left.resolve(project);
final IDefinition rightDef = right.resolve(project);
if (leftDef instanceof IClassDefinition)
{
// In this case, is foo.prop, where "foo" is a class name.
// We can skip over the left side ("foo"), because when we
// analyze the right side we will still know what it is.
doAnalyze(right, state);
}
else
{
if ((rightDef == null) && (leftDef != null))
{
// maybe we are something like ObjectProxy.dynamicProperty
// (someone who extends ObjectProxy, like Model)
ITypeDefinition leftType= leftDef.resolveType(project);
FlexProject project = (FlexProject)this.project;
String objectProxyClass = project.getObjectProxyClass();
boolean isProxy = leftType==null ? false : leftType.isInstanceOf(objectProxyClass, project);
// If we are proxy.prop, we set this info into the parse state. This does two things:
// 1) tells downstream properties that they can be dynamic, and hence don't need
// to be resolvable.
// 2) Stores off the event names from the proxy so that the chained property watchers
// can use the info
if (isProxy)
{
state.isObjectProxyExpression = true;
state.objectProxyEventNames = leftType.getBindableEventNames();
}
}
doAnalyze(left, state);
doAnalyze(right, state);
}
// If we are finished generating the chain for the top member access expression,
// then shut off chaining. Otherwise the next variable we see might get added to this chain,
// even though is it not related
if (!wasChaining)
{
state.chaining = false;
state.curChain = null;
}
// If we are finished with a chain of ObjectProxy.prop.prop things,
// then clear out the remembered info from the ObjectProxy.
// Note that this "termination condition" is quite different from the one above.
// Above the logic was "I'm going to set this, recursively apply to children, then clear.
// In this case, the logic is "I'm going to set and forget, because my PARENT want these results.
// Eventually I can clear it when my I can determine that my parent is not part of the chain.
if ( state.isObjectProxyExpression)
{
IASNode parent = node.getParent();
if (!(parent instanceof IMemberAccessExpressionNode))
{
state.isObjectProxyExpression = false;
state.objectProxyEventNames = null;
}
}
}
private void analyzeIdentifierNode(IIdentifierNode node, AnalysisState state)
{
IDefinition def = node.resolve(project);
if ((def == null) && !state.isObjectProxyExpression)
{
return; // this is not "defensive programming"!
// we fully expect to get non-resolvable identifiers in some cases:
// a) bad code.
// b) "this"
// It should be fine to skip over these and continue without creating a watcher
// If, on the other hand, we are in an object proxy, then we
// may very well be a dynamic property with no definition,
// so will will continue on (with the knowledge that we have no
// IDefinition
}
if (def instanceof IConstantDefinition)
{
return; // we can ignore constants - they can't be watched
}
assert state.chaining || state.curChain==null; // we shouldn't have a chain if we aren't chaining
// Now round up the arguments to make the watcher info
List<String> eventNames = null;
WatcherType type = WatcherType.ERROR;
String name = null;
Object id = null;
if ((def == null) && state.isObjectProxyExpression)
{
// we are in a dynamic property situation...
type = WatcherType.PROPERTY; // always use property watcher
name = node.getName(); // get the property name from the id node, since
// we have no definition
id = node; //use the parse node as identifier for the watcher, since
// we don't have an identifier to use. Not that this means we can't
// share dynamic property watchers. too bad!
eventNames = state.objectProxyEventNames; // use the event names we remembered from the proxy
}
else
{
// we are a not a dynamic property
// Check to see if we are a cast. If so, we can ignore
if (def instanceof IClassDefinition)
{
// we are an identifier that resolves to a class. perhaps we are a cast?
// we are a case if the node parent is a function call, but in any case
// if we see a class here it's either a cast, or it's just a class name
// in an expression.
// If it's a cast, there's nothing wrong. If it's a class, we treat it like a constant string
// bottom line: don't try to make a watcher, and don't generate a problem
return;
}
type = determineWatcherType(def); // figure out what kind of watcher to make
if (type == WatcherType.ERROR)
{
System.err.println("can't get watcher for " + def);
return; // This should never happen. If it does, there is presumably a bug.
// But - better to recover here, than to go on and NPE.
// This is a workaround for CMP-1283
}
// if it's a function, make sure it is the one from the function call expression we are parsing
// If it isn't, just return. This might happen if, for example, the function was
// not bindable - then functionCallNameDefintion would be null.
// I suspect there are other cases, too.
if (type == WatcherType.FUNCTION)
{
if (def != state.functionCallNameDefintion)
return;
}
eventNames = WatcherInfoBase.getEventNamesFromDefinition(def, problems, node, project);
name = def.getBaseName();
id = def;
}
makeWatcherOfKnownType(id, type, state, node, eventNames, name, def);
// Now, check if we need to make an XML watcher. These are special:
// We make an XMLWatcher and a property watcher to watch the same thing, so two of them
// are created in this one call
if (def instanceof IVariableDefinition)
{
// Is the def for an XML type variable?
IVariableDefinition var = (IVariableDefinition)def;
ITypeDefinition varType = var.resolveType(project);
// note that varType might be null if code is bad
boolean isVarXML = (varType==null) ? false : varType.isInstanceOf("XML", project);
if (isVarXML)
{
// if XML,then create a watcher for it.
String key = "XML"; // using this unique key will work, but it means we can never
// share these. Which is OK.
List<String> empty = Collections.emptyList();
makeWatcherOfKnownType(key, WatcherType.XML, state, node, empty, name, null);
}
}
}
/**
* Master "factory function" for Watcher Info
* You should always use this factory, rather than instantiating the directly, as it is
* easier and more reliable to user this function.
*
* @param watcherKey is unique object "key" to refer to the created watcher. Often an IDefintion
* @param type is which kind of watcher we want to create
* @param state must be passed in so we can chain watchers as we create them during parse time
* @param node the node that corresponds to the object we will be watching
* @param eventNames the events that the watcher must listen to
* @param name the name of the property or function that we will be watching
* @param optionalDefinition the IDefinition for the node. Only required for Static Property Watchers
*/
private void makeWatcherOfKnownType(
Object watcherKey,
WatcherType type,
AnalysisState state,
IASNode node,
List<String> eventNames,
String name,
IDefinition optionalDefinition)
{
assert(eventNames != null);
assert(name != null);
WatcherInfoBase watcherInfo = bindingDataBase.getOrCreateWatcher(
state.curChain,
type,
watcherKey,
problems,
node,
eventNames);
// After doing the "generic creation" we need to do some type specific
// setup
if (type == WatcherType.FUNCTION)
{
// TODO: couldn't we move this into a ctor somehow?
FunctionWatcherInfo fwi = (FunctionWatcherInfo)watcherInfo;
// fwi.setFunctionName(def.getName());
fwi.setFunctionName(name);
// Note: we might want to retrieve the function arguments in the future.
// But they aren't available on this object - they are on the original FunctionCallExpression node
FunctionCallNode fnNode = (FunctionCallNode)node.getAncestorOfType(FunctionCallNode.class);
IExpressionNode[] paramNodes = fnNode.getArgumentNodes();
fwi.params = paramNodes;
}
else if ((type == WatcherType.STATIC_PROPERTY) || (type == WatcherType.PROPERTY))
{
PropertyWatcherInfo pwi = (PropertyWatcherInfo)watcherInfo;
pwi.setPropertyName(name);
// TODO: can we just have a "name" on the base class??
}
else if (type == WatcherType.XML)
{
XMLWatcherInfo xwi = (XMLWatcherInfo)watcherInfo;
xwi.setPropertyName(name);
}
if (type == WatcherType.STATIC_PROPERTY)
{
assert optionalDefinition != null;
// static property watchers need this extra call
StaticPropertyWatcherInfo pwi = (StaticPropertyWatcherInfo)watcherInfo;
pwi.init(optionalDefinition, project);
}
watcherInfo.addBinding(bindingInfo); // associate our binding with this watcher
// note that one watcher can have more than one binding.
if (state.chaining)
state.curChain = watcherInfo; // mark this as the new bottom link in the chain
}
private static WatcherType determineWatcherType(IDefinition definition)
{
WatcherType ret = WatcherType.ERROR;
if (definition == null) return ret; // there are "special" watchers where this will be null
if (definition instanceof IVariableDefinition)
{
if (!definition.isStatic())
{
// we use regular property watchers on non-static variables
ret = WatcherType.PROPERTY;
}
else
{
ret = WatcherType.STATIC_PROPERTY;
}
}
else if (definition instanceof IFunctionDefinition)
{
ret = WatcherType.FUNCTION;
}
else assert false;
return ret;
}
}
| Handle interfaces as well as classes
| compiler/src/org/apache/flex/compiler/internal/codegen/databinding/WatcherAnalyzer.java | Handle interfaces as well as classes | <ide><path>ompiler/src/org/apache/flex/compiler/internal/codegen/databinding/WatcherAnalyzer.java
<ide> import org.apache.flex.compiler.definitions.IConstantDefinition;
<ide> import org.apache.flex.compiler.definitions.IDefinition;
<ide> import org.apache.flex.compiler.definitions.IFunctionDefinition;
<add>import org.apache.flex.compiler.definitions.IInterfaceDefinition;
<ide> import org.apache.flex.compiler.definitions.ITypeDefinition;
<ide> import org.apache.flex.compiler.definitions.IVariableDefinition;
<ide> import org.apache.flex.compiler.internal.codegen.databinding.WatcherInfoBase.WatcherType;
<ide> // we are a not a dynamic property
<ide>
<ide> // Check to see if we are a cast. If so, we can ignore
<del> if (def instanceof IClassDefinition)
<add> if (def instanceof IClassDefinition || def instanceof IInterfaceDefinition)
<ide> {
<ide> // we are an identifier that resolves to a class. perhaps we are a cast?
<ide> // we are a case if the node parent is a function call, but in any case |
Subsets and Splits