id
int64 22
34.9k
| original_code
stringlengths 31
107k
| code_wo_comment
stringlengths 29
77.3k
| cleancode
stringlengths 25
62.1k
| repo
stringlengths 6
65
| label
sequencelengths 4
4
|
---|---|---|---|---|---|
8,369 | public static void attachEndpointToSession(Channel channel, Endpoint endpoint) {
// TODO
// Netty allow to set/get attachment on Channel in the near feature, e.g.
// channel.getAttribute(new AttributeKey<Endpoint>(TRANSPORT_SENDER))
endpoints.set(channel, endpoint);
} | public static void attachEndpointToSession(Channel channel, Endpoint endpoint) {
endpoints.set(channel, endpoint);
} | public static void attachendpointtosession(channel channel, endpoint endpoint) { endpoints.set(channel, endpoint); } | tianshaojie/common-framework | [
0,
1,
0,
0
] |
24,782 | private void searchTweets(final String keyword) {
safelyUnsubscribe(subDelayedSearch, subLoadMoreTweets, subSearchTweets);
lastKeyword = keyword;
if (!networkApi.isConnectedToInternet(this)) {
showSnackBar(msgNoInternetConnection);
return;
}
if (!twitterApi.canSearchTweets(keyword)) {
return;
}
subSearchTweets = twitterApi.searchTweets(keyword)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<Status>>() {
@Override
public void onStart() {
}
@Override
public void onCompleted() {
// we don't have to implement this method
}
@Override
public void onError(final Throwable e) {
final String message = getErrorMessage((TwitterException) e);
showSnackBar(message);
showErrorMessageContainer(message, R.drawable.no_tweets);
}
@Override
public void onNext(final List<Status> tweets) {
handleSearchResults(tweets, keyword);
}
});
} | private void searchTweets(final String keyword) {
safelyUnsubscribe(subDelayedSearch, subLoadMoreTweets, subSearchTweets);
lastKeyword = keyword;
if (!networkApi.isConnectedToInternet(this)) {
showSnackBar(msgNoInternetConnection);
return;
}
if (!twitterApi.canSearchTweets(keyword)) {
return;
}
subSearchTweets = twitterApi.searchTweets(keyword)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<Status>>() {
@Override
public void onStart() {
}
@Override
public void onCompleted() {
}
@Override
public void onError(final Throwable e) {
final String message = getErrorMessage((TwitterException) e);
showSnackBar(message);
showErrorMessageContainer(message, R.drawable.no_tweets);
}
@Override
public void onNext(final List<Status> tweets) {
handleSearchResults(tweets, keyword);
}
});
} | private void searchtweets(final string keyword) { safelyunsubscribe(subdelayedsearch, subloadmoretweets, subsearchtweets); lastkeyword = keyword; if (!networkapi.isconnectedtointernet(this)) { showsnackbar(msgnointernetconnection); return; } if (!twitterapi.cansearchtweets(keyword)) { return; } subsearchtweets = twitterapi.searchtweets(keyword) .subscribeon(schedulers.io()) .observeon(androidschedulers.mainthread()) .subscribe(new subscriber<list<status>>() { @override public void onstart() { } @override public void oncompleted() { } @override public void onerror(final throwable e) { final string message = geterrormessage((twitterexception) e); showsnackbar(message); showerrormessagecontainer(message, r.drawable.no_tweets); } @override public void onnext(final list<status> tweets) { handlesearchresults(tweets, keyword); } }); } | umeshbsa/android-twitter-search-api | [
0,
0,
0,
0
] |
24,804 | @SuppressWarnings("restriction")
private void updateDJTSign(ChildVaccinaterecord childVaccinaterecord, Map<String, Object> maplist,
Map<String, Object> code) {
logger.info("获取排号签字数据开始" + childVaccinaterecord.getNid().substring(0, 2) + "||"
+ childVaccinaterecord.getVaccineid());
Object signObjVaccid = CacheUtils.get(CacheUtils.SIGN_CACHE,
childVaccinaterecord.getChildid() + "_" + childVaccinaterecord.getNid().substring(0, 2));
logger.info("signObjVaccid-->" + (signObjVaccid == null));
CacheUtils.remove(CacheUtils.SIGN_CACHE,
childVaccinaterecord.getChildid() + "_" + childVaccinaterecord.getNid().substring(0, 2));
Object signObj = CacheUtils.get(CacheUtils.SIGN_CACHE,
childVaccinaterecord.getChildid() + "_" + childVaccinaterecord.getVaccineid());
logger.info("signObj-->" + (signObj == null));
CacheUtils.remove(CacheUtils.SIGN_CACHE,
childVaccinaterecord.getChildid() + "_" + childVaccinaterecord.getVaccineid());
if (signObj == null) {
signObj = signObjVaccid;
}
logger.info("signObjFinal-->" + (signObj == null));
if (signObj != null) {
String signStr = (String) signObj;
// 初始化记录数据
childVaccinaterecord = childVaccinaterecordService.get(childVaccinaterecord);
if (childVaccinaterecord != null) {
// 判断签字是否存在
// 打印签字信息
code.put("sign", signStr);
// base64 转换签字
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] sign = decoder.decodeBuffer(signStr);
if (null != sign && sign.length > 0) {
childVaccinaterecord.setSignatureData(sign);
childVaccinaterecord.setStype(ChildVaccinaterecord.SIGNATURE_SOURCE_DJT);
// 查询该记录签字是否存在
int count = childVaccinaterecordService.querySignature(childVaccinaterecord);
if (count == 0) {
// 新增签字
childVaccinaterecordService.insertSignatures(childVaccinaterecord);
}
// 修改签字状态
childVaccinaterecord.setSignature(ChildVaccinaterecord.SIGNATURE_YES);
childVaccinaterecordService.updateSignatures(childVaccinaterecord);
}
} catch (Exception e) {
logger.error("微信签字base64转bytes失败", e.getMessage());
}
// 签字状态
}
maplist.put("success", true);
logger.error("打印排号获取签字成功" + childVaccinaterecord.getNid().substring(0, 2) + "||"
+ childVaccinaterecord.getVaccineid());
} else {
logger.error("打印排号获取签字失败" + childVaccinaterecord.getNid().substring(0, 2) + "||"
+ childVaccinaterecord.getVaccineid());
}
} | @SuppressWarnings("restriction")
private void updateDJTSign(ChildVaccinaterecord childVaccinaterecord, Map<String, Object> maplist,
Map<String, Object> code) {
logger.info("获取排号签字数据开始" + childVaccinaterecord.getNid().substring(0, 2) + "||"
+ childVaccinaterecord.getVaccineid());
Object signObjVaccid = CacheUtils.get(CacheUtils.SIGN_CACHE,
childVaccinaterecord.getChildid() + "_" + childVaccinaterecord.getNid().substring(0, 2));
logger.info("signObjVaccid-->" + (signObjVaccid == null));
CacheUtils.remove(CacheUtils.SIGN_CACHE,
childVaccinaterecord.getChildid() + "_" + childVaccinaterecord.getNid().substring(0, 2));
Object signObj = CacheUtils.get(CacheUtils.SIGN_CACHE,
childVaccinaterecord.getChildid() + "_" + childVaccinaterecord.getVaccineid());
logger.info("signObj-->" + (signObj == null));
CacheUtils.remove(CacheUtils.SIGN_CACHE,
childVaccinaterecord.getChildid() + "_" + childVaccinaterecord.getVaccineid());
if (signObj == null) {
signObj = signObjVaccid;
}
logger.info("signObjFinal-->" + (signObj == null));
if (signObj != null) {
String signStr = (String) signObj;
naterecord = childVaccinaterecordService.get(childVaccinaterecord);
if (childVaccinaterecord != null) {
t("sign", signStr);
E64Decoder decoder = new BASE64Decoder();
try {
byte[] sign = decoder.decodeBuffer(signStr);
if (null != sign && sign.length > 0) {
childVaccinaterecord.setSignatureData(sign);
childVaccinaterecord.setStype(ChildVaccinaterecord.SIGNATURE_SOURCE_DJT);
ldVaccinaterecordService.querySignature(childVaccinaterecord);
if (count == 0) {
childVaccinaterecordService.insertSignatures(childVaccinaterecord);
}
Vaccinaterecord.setSignature(ChildVaccinaterecord.SIGNATURE_YES);
childVaccinaterecordService.updateSignatures(childVaccinaterecord);
}
} catch (Exception e) {
logger.error("微信签字base64转bytes失败", e.getMessage());
}
maplist.put("success", true);
logger.error("打印排号获取签字成功" + childVaccinaterecord.getNid().substring(0, 2) + "||"
+ childVaccinaterecord.getVaccineid());
} else {
logger.error("打印排号获取签字失败" + childVaccinaterecord.getNid().substring(0, 2) + "||"
+ childVaccinaterecord.getVaccineid());
}
} | @suppresswarnings("restriction") private void updatedjtsign(childvaccinaterecord childvaccinaterecord, map<string, object> maplist, map<string, object> code) { logger.info("获取排号签字数据开始" + childvaccinaterecord.getnid().substring(0, 2) + "||" + childvaccinaterecord.getvaccineid()); object signobjvaccid = cacheutils.get(cacheutils.sign_cache, childvaccinaterecord.getchildid() + "_" + childvaccinaterecord.getnid().substring(0, 2)); logger.info("signobjvaccid-->" + (signobjvaccid == null)); cacheutils.remove(cacheutils.sign_cache, childvaccinaterecord.getchildid() + "_" + childvaccinaterecord.getnid().substring(0, 2)); object signobj = cacheutils.get(cacheutils.sign_cache, childvaccinaterecord.getchildid() + "_" + childvaccinaterecord.getvaccineid()); logger.info("signobj-->" + (signobj == null)); cacheutils.remove(cacheutils.sign_cache, childvaccinaterecord.getchildid() + "_" + childvaccinaterecord.getvaccineid()); if (signobj == null) { signobj = signobjvaccid; } logger.info("signobjfinal-->" + (signobj == null)); if (signobj != null) { string signstr = (string) signobj; naterecord = childvaccinaterecordservice.get(childvaccinaterecord); if (childvaccinaterecord != null) { t("sign", signstr); e64decoder decoder = new base64decoder(); try { byte[] sign = decoder.decodebuffer(signstr); if (null != sign && sign.length > 0) { childvaccinaterecord.setsignaturedata(sign); childvaccinaterecord.setstype(childvaccinaterecord.signature_source_djt); ldvaccinaterecordservice.querysignature(childvaccinaterecord); if (count == 0) { childvaccinaterecordservice.insertsignatures(childvaccinaterecord); } vaccinaterecord.setsignature(childvaccinaterecord.signature_yes); childvaccinaterecordservice.updatesignatures(childvaccinaterecord); } } catch (exception e) { logger.error("微信签字base64转bytes失败", e.getmessage()); } maplist.put("success", true); logger.error("打印排号获取签字成功" + childvaccinaterecord.getnid().substring(0, 2) + "||" + childvaccinaterecord.getvaccineid()); } else { logger.error("打印排号获取签字失败" + childvaccinaterecord.getnid().substring(0, 2) + "||" + childvaccinaterecord.getvaccineid()); } } | wufang742987117/vaccinate | [
0,
1,
0,
0
] |
24,825 | public synchronized void draw_World(){
//for each cells
ant1nbCells=0;
ant2nbCells=0;
ant3nbCells=0;
ant4nbCells=0;
for (int x=0;x<WIDTH;x++){
for (int y=0;y<HEIGHT;y++){
//test is colorized
if (world.getLocation().get((WIDTH*y)+x).isColorized()){
//System.out.print("(x,y)=("+x+","+y+")&");
//yes draw a point with this color
wimgWorld.getPixelWriter().setColor(x, y, world.getLocation().get((WIDTH*y)+x).getColorS());
if (world.getLocation().get((WIDTH*y)+x).getName().compareTo(ANT1)==0){ant1nbCells++;}
if (world.getLocation().get((WIDTH*y)+x).getName().compareTo(ANT2)==0){ant2nbCells++;}
if (world.getLocation().get((WIDTH*y)+x).getName().compareTo(ANT3)==0){ant3nbCells++;}
if (world.getLocation().get((WIDTH*y)+x).getName().compareTo(ANT4)==0){ant4nbCells++;}
}
else
{
//no draw a black point
wimgWorld.getPixelWriter().setColor(x, y, javafx.scene.paint.Color.BLACK);
}
}
}
imgWorld.setImage(wimgWorld); //show me the result on scsreen
//refresh counters
lbTotalCellsNb.setText(nbTotalCells+" cells");
lbAnt1CellsNb.setText(ant1nbCells+" cells ("+formatter.format(((double)ant1nbCells/nbTotalCells)*100)+"%)");
lbAnt2CellsNb.setText(ant2nbCells+" cells ("+formatter.format(((double)ant2nbCells/nbTotalCells)*100)+"%)");
lbAnt3CellsNb.setText(ant3nbCells+" cells ("+formatter.format(((double)ant3nbCells/nbTotalCells)*100)+"%)");
lbAnt4CellsNb.setText(ant4nbCells+" cells ("+formatter.format(((double)ant4nbCells/nbTotalCells)*100)+"%)");
} | public synchronized void draw_World(){
ant1nbCells=0;
ant2nbCells=0;
ant3nbCells=0;
ant4nbCells=0;
for (int x=0;x<WIDTH;x++){
for (int y=0;y<HEIGHT;y++){
if (world.getLocation().get((WIDTH*y)+x).isColorized()){
wimgWorld.getPixelWriter().setColor(x, y, world.getLocation().get((WIDTH*y)+x).getColorS());
if (world.getLocation().get((WIDTH*y)+x).getName().compareTo(ANT1)==0){ant1nbCells++;}
if (world.getLocation().get((WIDTH*y)+x).getName().compareTo(ANT2)==0){ant2nbCells++;}
if (world.getLocation().get((WIDTH*y)+x).getName().compareTo(ANT3)==0){ant3nbCells++;}
if (world.getLocation().get((WIDTH*y)+x).getName().compareTo(ANT4)==0){ant4nbCells++;}
}
else
{
wimgWorld.getPixelWriter().setColor(x, y, javafx.scene.paint.Color.BLACK);
}
}
}
imgWorld.setImage(wimgWorld);
lbTotalCellsNb.setText(nbTotalCells+" cells");
lbAnt1CellsNb.setText(ant1nbCells+" cells ("+formatter.format(((double)ant1nbCells/nbTotalCells)*100)+"%)");
lbAnt2CellsNb.setText(ant2nbCells+" cells ("+formatter.format(((double)ant2nbCells/nbTotalCells)*100)+"%)");
lbAnt3CellsNb.setText(ant3nbCells+" cells ("+formatter.format(((double)ant3nbCells/nbTotalCells)*100)+"%)");
lbAnt4CellsNb.setText(ant4nbCells+" cells ("+formatter.format(((double)ant4nbCells/nbTotalCells)*100)+"%)");
} | public synchronized void draw_world(){ ant1nbcells=0; ant2nbcells=0; ant3nbcells=0; ant4nbcells=0; for (int x=0;x<width;x++){ for (int y=0;y<height;y++){ if (world.getlocation().get((width*y)+x).iscolorized()){ wimgworld.getpixelwriter().setcolor(x, y, world.getlocation().get((width*y)+x).getcolors()); if (world.getlocation().get((width*y)+x).getname().compareto(ant1)==0){ant1nbcells++;} if (world.getlocation().get((width*y)+x).getname().compareto(ant2)==0){ant2nbcells++;} if (world.getlocation().get((width*y)+x).getname().compareto(ant3)==0){ant3nbcells++;} if (world.getlocation().get((width*y)+x).getname().compareto(ant4)==0){ant4nbcells++;} } else { wimgworld.getpixelwriter().setcolor(x, y, javafx.scene.paint.color.black); } } } imgworld.setimage(wimgworld); lbtotalcellsnb.settext(nbtotalcells+" cells"); lbant1cellsnb.settext(ant1nbcells+" cells ("+formatter.format(((double)ant1nbcells/nbtotalcells)*100)+"%)"); lbant2cellsnb.settext(ant2nbcells+" cells ("+formatter.format(((double)ant2nbcells/nbtotalcells)*100)+"%)"); lbant3cellsnb.settext(ant3nbcells+" cells ("+formatter.format(((double)ant3nbcells/nbtotalcells)*100)+"%)"); lbant4cellsnb.settext(ant4nbcells+" cells ("+formatter.format(((double)ant4nbcells/nbtotalcells)*100)+"%)"); } | tondeur-h/LangTonAnt | [
1,
0,
0,
0
] |
16,665 | public void clearNzSessions() throws IOException, InterruptedException {
String pathToNzSession = System.getProperty(
NZ_SESSION_PATH_KEY, DEFAULT_NZ_SESSION_PATH);
// Run nzsession and capture a list of open transactions.
ArrayList<String> args = new ArrayList<String>();
args.add(pathToNzSession);
args.add("-host");
args.add(NETEZZA_HOST);
args.add("-u");
args.add(ADMIN_USER);
args.add("-pw");
args.add(ADMIN_PASS);
Process p = Runtime.getRuntime().exec(args.toArray(new String[0]));
InputStream is = p.getInputStream();
LineBufferingAsyncSink sink = new LineBufferingAsyncSink();
sink.processStream(is);
// Wait for the process to end.
int result = p.waitFor();
if (0 != result) {
throw new IOException("Session list command terminated with " + result);
}
// Collect all the stdout, and parse the output.
// If the third whitespace-delimited token is the sqooptest user,
// the the first token is the nzsession id. We should kill that id.
sink.join();
List<String> processList = sink.getLines();
for (String processLine : processList) {
if (null == processLine || processLine.length() == 0) {
continue; // Ignore empty lines.
}
String [] tokens = processLine.split(" +");
if (tokens.length < 3) {
continue; // Not enough tokens on this line.
}
if (tokens[2].equalsIgnoreCase(NETEZZA_USER)) {
// Found a match.
killSession(tokens[0]);
}
}
} | public void clearNzSessions() throws IOException, InterruptedException {
String pathToNzSession = System.getProperty(
NZ_SESSION_PATH_KEY, DEFAULT_NZ_SESSION_PATH);
ArrayList<String> args = new ArrayList<String>();
args.add(pathToNzSession);
args.add("-host");
args.add(NETEZZA_HOST);
args.add("-u");
args.add(ADMIN_USER);
args.add("-pw");
args.add(ADMIN_PASS);
Process p = Runtime.getRuntime().exec(args.toArray(new String[0]));
InputStream is = p.getInputStream();
LineBufferingAsyncSink sink = new LineBufferingAsyncSink();
sink.processStream(is);
int result = p.waitFor();
if (0 != result) {
throw new IOException("Session list command terminated with " + result);
}
sink.join();
List<String> processList = sink.getLines();
for (String processLine : processList) {
if (null == processLine || processLine.length() == 0) {
continue;
}
String [] tokens = processLine.split(" +");
if (tokens.length < 3) {
continue;
}
if (tokens[2].equalsIgnoreCase(NETEZZA_USER)) {
killSession(tokens[0]);
}
}
} | public void clearnzsessions() throws ioexception, interruptedexception { string pathtonzsession = system.getproperty( nz_session_path_key, default_nz_session_path); arraylist<string> args = new arraylist<string>(); args.add(pathtonzsession); args.add("-host"); args.add(netezza_host); args.add("-u"); args.add(admin_user); args.add("-pw"); args.add(admin_pass); process p = runtime.getruntime().exec(args.toarray(new string[0])); inputstream is = p.getinputstream(); linebufferingasyncsink sink = new linebufferingasyncsink(); sink.processstream(is); int result = p.waitfor(); if (0 != result) { throw new ioexception("session list command terminated with " + result); } sink.join(); list<string> processlist = sink.getlines(); for (string processline : processlist) { if (null == processline || processline.length() == 0) { continue; } string [] tokens = processline.split(" +"); if (tokens.length < 3) { continue; } if (tokens[2].equalsignorecase(netezza_user)) { killsession(tokens[0]); } } } | viveshs/sqoop-netezza-connector | [
1,
0,
0,
0
] |
16,761 | @CalledByNative
protected void releaseOutputBuffer(int index, boolean render) {
try {
mMediaCodec.releaseOutputBuffer(index, render);
} catch (IllegalStateException e) {
// TODO(qinmin): May need to report the error to the caller. crbug.com/356498.
Log.e(TAG, "Failed to release output buffer", e);
}
} | @CalledByNative
protected void releaseOutputBuffer(int index, boolean render) {
try {
mMediaCodec.releaseOutputBuffer(index, render);
} catch (IllegalStateException e) {
Log.e(TAG, "Failed to release output buffer", e);
}
} | @calledbynative protected void releaseoutputbuffer(int index, boolean render) { try { mmediacodec.releaseoutputbuffer(index, render); } catch (illegalstateexception e) { log.e(tag, "failed to release output buffer", e); } } | zealoussnow/chromium | [
0,
1,
0,
0
] |
16,764 | @Override
public void onError(MediaCodec codec, MediaCodec.CodecException e) {
// TODO(dalecurtis): We may want to drop transient errors here.
Log.e(TAG, "MediaCodec.onError: %s", e.getDiagnosticInfo());
mMediaCodecBridge.onError(e);
} | @Override
public void onError(MediaCodec codec, MediaCodec.CodecException e) {
Log.e(TAG, "MediaCodec.onError: %s", e.getDiagnosticInfo());
mMediaCodecBridge.onError(e);
} | @override public void onerror(mediacodec codec, mediacodec.codecexception e) { log.e(tag, "mediacodec.onerror: %s", e.getdiagnosticinfo()); mmediacodecbridge.onerror(e); } | zealoussnow/chromium | [
0,
1,
0,
0
] |
25,136 | @VisibleForTesting
static RateLimiter create(SleepingStopwatch stopwatch, double permitsPerSecond) {
RateLimiter rateLimiter = new SmoothBursty(stopwatch, 1.0 /* maxBurstSeconds */);
rateLimiter.setRate(permitsPerSecond);
return rateLimiter;
} | @VisibleForTesting
static RateLimiter create(SleepingStopwatch stopwatch, double permitsPerSecond) {
RateLimiter rateLimiter = new SmoothBursty(stopwatch, 1.0);
rateLimiter.setRate(permitsPerSecond);
return rateLimiter;
} | @visiblefortesting static ratelimiter create(sleepingstopwatch stopwatch, double permitspersecond) { ratelimiter ratelimiter = new smoothbursty(stopwatch, 1.0); ratelimiter.setrate(permitspersecond); return ratelimiter; } | xushjie1987/common-utils | [
0,
1,
0,
0
] |
571 | public static void simulateAutoIncrement(Connection connection, String tableName, String columnName) throws SQLException {
String sequenceName = tableName + "_seq";
String triggerName = tableName + "_id";
connection.prepareStatement(
"CREATE sequence " + sequenceName + " start with 1 increment by 1 nocycle"
).executeUpdate();
// The oracle driver is getting confused by this statement, claiming we have to declare some in out parameter,
// when we execute this as a prepared statement. Might be a config issue on our side.
connection
.createStatement()
.execute(
"create or replace trigger " + triggerName +
" before insert on " + tableName +
" for each row " +
" begin " +
" :new." + columnName + " := " + sequenceName + ".nextval; " +
" end;"
);
} | public static void simulateAutoIncrement(Connection connection, String tableName, String columnName) throws SQLException {
String sequenceName = tableName + "_seq";
String triggerName = tableName + "_id";
connection.prepareStatement(
"CREATE sequence " + sequenceName + " start with 1 increment by 1 nocycle"
).executeUpdate();
connection
.createStatement()
.execute(
"create or replace trigger " + triggerName +
" before insert on " + tableName +
" for each row " +
" begin " +
" :new." + columnName + " := " + sequenceName + ".nextval; " +
" end;"
);
} | public static void simulateautoincrement(connection connection, string tablename, string columnname) throws sqlexception { string sequencename = tablename + "_seq"; string triggername = tablename + "_id"; connection.preparestatement( "create sequence " + sequencename + " start with 1 increment by 1 nocycle" ).executeupdate(); connection .createstatement() .execute( "create or replace trigger " + triggername + " before insert on " + tablename + " for each row " + " begin " + " :new." + columnname + " := " + sequencename + ".nextval; " + " end;" ); } | szymek22/AxonFramework | [
0,
0,
1,
0
] |
8,804 | public void handle(ExtendedBlock block, IOException e) {
FsVolumeSpi volume = scanner.volume;
if (e == null) {
LOG.trace("Successfully scanned {} on {}", block, volume);
return;
}
// If the block does not exist anymore, then it's not an error.
if (!volume.getDataset().contains(block)) {
LOG.debug("Volume {}: block {} is no longer in the dataset.",
volume, block);
return;
}
// If the block exists, the exception may due to a race with write:
// The BlockSender got an old block path in rbw. BlockReceiver removed
// the rbw block from rbw to finalized but BlockSender tried to open the
// file before BlockReceiver updated the VolumeMap. The state of the
// block can be changed again now, so ignore this error here. If there
// is a block really deleted by mistake, DirectoryScan should catch it.
if (e instanceof FileNotFoundException ) {
LOG.info("Volume {}: verification failed for {} because of " +
"FileNotFoundException. This may be due to a race with write.",
volume, block);
return;
}
LOG.warn("Reporting bad {} on {}", block, volume);
try {
scanner.datanode.reportBadBlocks(block, volume);
} catch (IOException ie) {
// This is bad, but not bad enough to shut down the scanner.
LOG.warn("Cannot report bad block " + block, ie);
}
} | public void handle(ExtendedBlock block, IOException e) {
FsVolumeSpi volume = scanner.volume;
if (e == null) {
LOG.trace("Successfully scanned {} on {}", block, volume);
return;
}
if (!volume.getDataset().contains(block)) {
LOG.debug("Volume {}: block {} is no longer in the dataset.",
volume, block);
return;
}
if (e instanceof FileNotFoundException ) {
LOG.info("Volume {}: verification failed for {} because of " +
"FileNotFoundException. This may be due to a race with write.",
volume, block);
return;
}
LOG.warn("Reporting bad {} on {}", block, volume);
try {
scanner.datanode.reportBadBlocks(block, volume);
} catch (IOException ie) {
LOG.warn("Cannot report bad block " + block, ie);
}
} | public void handle(extendedblock block, ioexception e) { fsvolumespi volume = scanner.volume; if (e == null) { log.trace("successfully scanned {} on {}", block, volume); return; } if (!volume.getdataset().contains(block)) { log.debug("volume {}: block {} is no longer in the dataset.", volume, block); return; } if (e instanceof filenotfoundexception ) { log.info("volume {}: verification failed for {} because of " + "filenotfoundexception. this may be due to a race with write.", volume, block); return; } log.warn("reporting bad {} on {}", block, volume); try { scanner.datanode.reportbadblocks(block, volume); } catch (ioexception ie) { log.warn("cannot report bad block " + block, ie); } } | xiaojimi/hadoop | [
1,
0,
0,
0
] |
17,001 | @Override
@SuppressWarnings("unchecked")
public Set keySet(Predicate predicate) {
checkTransactionState();
checkNotNull(predicate, "Predicate should not be null!");
checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries!");
MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name);
SerializationService serializationService = getNodeEngine().getSerializationService();
QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.KEY);
Set<Object> queryResult = new QueryResultCollection(serializationService, IterationType.KEY, false, true, result);
// TODO: Can't we just use the original set?
Set<Object> keySet = new HashSet<Object>(queryResult);
Extractors extractors = mapServiceContext.getExtractors(name);
for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) {
Data keyData = entry.getKey();
if (!Type.REMOVED.equals(entry.getValue().type)) {
Object value = (entry.getValue().value instanceof Data)
? toObjectIfNeeded(entry.getValue().value) : entry.getValue().value;
QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService,
keyData, value, extractors);
// apply predicate on txMap
if (predicate.apply(queryEntry)) {
Object keyObject = serializationService.toObject(keyData);
keySet.add(keyObject);
}
} else {
// meanwhile remove keys which are not in txMap
Object keyObject = serializationService.toObject(keyData);
keySet.remove(keyObject);
}
}
return keySet;
} | @Override
@SuppressWarnings("unchecked")
public Set keySet(Predicate predicate) {
checkTransactionState();
checkNotNull(predicate, "Predicate should not be null!");
checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries!");
MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name);
SerializationService serializationService = getNodeEngine().getSerializationService();
QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.KEY);
Set<Object> queryResult = new QueryResultCollection(serializationService, IterationType.KEY, false, true, result);
Set<Object> keySet = new HashSet<Object>(queryResult);
Extractors extractors = mapServiceContext.getExtractors(name);
for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) {
Data keyData = entry.getKey();
if (!Type.REMOVED.equals(entry.getValue().type)) {
Object value = (entry.getValue().value instanceof Data)
? toObjectIfNeeded(entry.getValue().value) : entry.getValue().value;
QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService,
keyData, value, extractors);
if (predicate.apply(queryEntry)) {
Object keyObject = serializationService.toObject(keyData);
keySet.add(keyObject);
}
} else {
Object keyObject = serializationService.toObject(keyData);
keySet.remove(keyObject);
}
}
return keySet;
} | @override @suppresswarnings("unchecked") public set keyset(predicate predicate) { checktransactionstate(); checknotnull(predicate, "predicate should not be null!"); checknotinstanceof(pagingpredicate.class, predicate, "paging is not supported for transactional queries!"); mapqueryengine queryengine = mapservicecontext.getmapqueryengine(name); serializationservice serializationservice = getnodeengine().getserializationservice(); queryresult result = queryengine.invokequeryallpartitions(name, predicate, iterationtype.key); set<object> queryresult = new queryresultcollection(serializationservice, iterationtype.key, false, true, result); set<object> keyset = new hashset<object>(queryresult); extractors extractors = mapservicecontext.getextractors(name); for (map.entry<data, txnvaluewrapper> entry : txmap.entryset()) { data keydata = entry.getkey(); if (!type.removed.equals(entry.getvalue().type)) { object value = (entry.getvalue().value instanceof data) ? toobjectifneeded(entry.getvalue().value) : entry.getvalue().value; queryableentry queryentry = new cachedqueryentry((internalserializationservice) serializationservice, keydata, value, extractors); if (predicate.apply(queryentry)) { object keyobject = serializationservice.toobject(keydata); keyset.add(keyobject); } } else { object keyobject = serializationservice.toobject(keydata); keyset.remove(keyobject); } } return keyset; } | tsasaki609/hazelcast | [
1,
0,
0,
0
] |
17,002 | @Override
@SuppressWarnings("unchecked")
public Collection values(Predicate predicate) {
checkTransactionState();
checkNotNull(predicate, "Predicate can not be null!");
checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries");
MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name);
SerializationService serializationService = getNodeEngine().getSerializationService();
QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.ENTRY);
QueryResultCollection<Map.Entry> queryResult
= new QueryResultCollection<Map.Entry>(serializationService, IterationType.ENTRY, false, true, result);
// TODO: Can't we just use the original set?
List<Object> valueSet = new ArrayList<Object>();
Set<Object> keyWontBeIncluded = new HashSet<Object>();
Extractors extractors = mapServiceContext.getExtractors(name);
// iterate over the txMap and see if the values are updated or removed
for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) {
boolean isRemoved = Type.REMOVED.equals(entry.getValue().type);
boolean isUpdated = Type.UPDATED.equals(entry.getValue().type);
Object keyObject = serializationService.toObject(entry.getKey());
if (isRemoved) {
keyWontBeIncluded.add(keyObject);
} else {
if (isUpdated) {
keyWontBeIncluded.add(keyObject);
}
Object entryValue = entry.getValue().value;
QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService,
entry.getKey(), entryValue, extractors);
if (predicate.apply(queryEntry)) {
valueSet.add(queryEntry.getValue());
}
}
}
removeFromResultSet(queryResult, valueSet, keyWontBeIncluded);
return valueSet;
} | @Override
@SuppressWarnings("unchecked")
public Collection values(Predicate predicate) {
checkTransactionState();
checkNotNull(predicate, "Predicate can not be null!");
checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries");
MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name);
SerializationService serializationService = getNodeEngine().getSerializationService();
QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.ENTRY);
QueryResultCollection<Map.Entry> queryResult
= new QueryResultCollection<Map.Entry>(serializationService, IterationType.ENTRY, false, true, result);
List<Object> valueSet = new ArrayList<Object>();
Set<Object> keyWontBeIncluded = new HashSet<Object>();
Extractors extractors = mapServiceContext.getExtractors(name);
for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) {
boolean isRemoved = Type.REMOVED.equals(entry.getValue().type);
boolean isUpdated = Type.UPDATED.equals(entry.getValue().type);
Object keyObject = serializationService.toObject(entry.getKey());
if (isRemoved) {
keyWontBeIncluded.add(keyObject);
} else {
if (isUpdated) {
keyWontBeIncluded.add(keyObject);
}
Object entryValue = entry.getValue().value;
QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService,
entry.getKey(), entryValue, extractors);
if (predicate.apply(queryEntry)) {
valueSet.add(queryEntry.getValue());
}
}
}
removeFromResultSet(queryResult, valueSet, keyWontBeIncluded);
return valueSet;
} | @override @suppresswarnings("unchecked") public collection values(predicate predicate) { checktransactionstate(); checknotnull(predicate, "predicate can not be null!"); checknotinstanceof(pagingpredicate.class, predicate, "paging is not supported for transactional queries"); mapqueryengine queryengine = mapservicecontext.getmapqueryengine(name); serializationservice serializationservice = getnodeengine().getserializationservice(); queryresult result = queryengine.invokequeryallpartitions(name, predicate, iterationtype.entry); queryresultcollection<map.entry> queryresult = new queryresultcollection<map.entry>(serializationservice, iterationtype.entry, false, true, result); list<object> valueset = new arraylist<object>(); set<object> keywontbeincluded = new hashset<object>(); extractors extractors = mapservicecontext.getextractors(name); for (map.entry<data, txnvaluewrapper> entry : txmap.entryset()) { boolean isremoved = type.removed.equals(entry.getvalue().type); boolean isupdated = type.updated.equals(entry.getvalue().type); object keyobject = serializationservice.toobject(entry.getkey()); if (isremoved) { keywontbeincluded.add(keyobject); } else { if (isupdated) { keywontbeincluded.add(keyobject); } object entryvalue = entry.getvalue().value; queryableentry queryentry = new cachedqueryentry((internalserializationservice) serializationservice, entry.getkey(), entryvalue, extractors); if (predicate.apply(queryentry)) { valueset.add(queryentry.getvalue()); } } } removefromresultset(queryresult, valueset, keywontbeincluded); return valueset; } | tsasaki609/hazelcast | [
1,
0,
0,
0
] |
25,228 | private static void resetStatSpecs(String testId, List testContainers,
String statSpecFileOverride) {
if (testContainers.size() == 1) { // special case
TestContainer testContainer = (TestContainer)testContainers.get(0);
// determine which statspec file to use
String statSpecFile = statSpecFileOverride;
if (statSpecFileOverride == null) {
statSpecFile = getLastStatSpecFile(testContainer);
} // @todo lises support option to use union of all statspecs
// reset the statspec file for each test in the container
List tests = testContainer.getTests();
for (Iterator i = tests.iterator(); i.hasNext();) {
Test test = (Test)i.next();
test.resetStatSpecs(statSpecFile);
}
} else {
// determine which statspec file to use for this test id
String statSpecFile = statSpecFileOverride;
if (statSpecFileOverride == null) {
statSpecFile = getLastStatSpecFile(testId, testContainers);
} // @todo lises support option to use union of all statspecs
// reset the statspec file for each test with the given test id
for (Iterator i = testContainers.iterator(); i.hasNext();) {
TestContainer testContainer = (TestContainer)i.next();
List tests = testContainer.getTestsWithId(testId);
for (Iterator j = tests.iterator(); j.hasNext();) {
Test test = (Test)j.next();
test.resetStatSpecs(statSpecFile);
}
}
}
} | private static void resetStatSpecs(String testId, List testContainers,
String statSpecFileOverride) {
if (testContainers.size() == 1) {
TestContainer testContainer = (TestContainer)testContainers.get(0);
String statSpecFile = statSpecFileOverride;
if (statSpecFileOverride == null) {
statSpecFile = getLastStatSpecFile(testContainer);
}
List tests = testContainer.getTests();
for (Iterator i = tests.iterator(); i.hasNext();) {
Test test = (Test)i.next();
test.resetStatSpecs(statSpecFile);
}
} else {
String statSpecFile = statSpecFileOverride;
if (statSpecFileOverride == null) {
statSpecFile = getLastStatSpecFile(testId, testContainers);
}
for (Iterator i = testContainers.iterator(); i.hasNext();) {
TestContainer testContainer = (TestContainer)i.next();
List tests = testContainer.getTestsWithId(testId);
for (Iterator j = tests.iterator(); j.hasNext();) {
Test test = (Test)j.next();
test.resetStatSpecs(statSpecFile);
}
}
}
} | private static void resetstatspecs(string testid, list testcontainers, string statspecfileoverride) { if (testcontainers.size() == 1) { testcontainer testcontainer = (testcontainer)testcontainers.get(0); string statspecfile = statspecfileoverride; if (statspecfileoverride == null) { statspecfile = getlaststatspecfile(testcontainer); } list tests = testcontainer.gettests(); for (iterator i = tests.iterator(); i.hasnext();) { test test = (test)i.next(); test.resetstatspecs(statspecfile); } } else { string statspecfile = statspecfileoverride; if (statspecfileoverride == null) { statspecfile = getlaststatspecfile(testid, testcontainers); } for (iterator i = testcontainers.iterator(); i.hasnext();) { testcontainer testcontainer = (testcontainer)i.next(); list tests = testcontainer.gettestswithid(testid); for (iterator j = tests.iterator(); j.hasnext();) { test test = (test)j.next(); test.resetstatspecs(statspecfile); } } } } | xyxiaoyou/snappy-store | [
0,
1,
0,
0
] |
25,229 | private static List buildValueComparators(String testId,
List testContainers) {
List comparators = new ArrayList();
for (int i = 0; i < testContainers.size(); i++) {
TestContainer testContainer = (TestContainer)testContainers.get(i);
List tests = testContainer.getTestsWithId(testId);
if (tests.size() == 0) { // test is missing from this container
comparators.add(null);
} else if (tests.size() == 1) {
Test test = (Test)tests.get(0);
ValueComparator comparator = new ValueComparator(i, test);
comparators.add(comparator);
} else { // multiple runs of this test are present
// @todo lises move this check into ValueComparator, for future
// averaging, make ValueComparator accept a list of tests
String s = "Not implemented yet: multiple tests in "
+ testContainer.getTestContainerDir() + " with id=" + testId;
throw new UnsupportedOperationException(s);
}
}
// make each instance read its archives
for (Iterator i = comparators.iterator(); i.hasNext();) {
ValueComparator comparator = (ValueComparator)i.next();
if (comparator != null) {
comparator.readArchives();
}
}
return comparators;
} | private static List buildValueComparators(String testId,
List testContainers) {
List comparators = new ArrayList();
for (int i = 0; i < testContainers.size(); i++) {
TestContainer testContainer = (TestContainer)testContainers.get(i);
List tests = testContainer.getTestsWithId(testId);
if (tests.size() == 0) {
comparators.add(null);
} else if (tests.size() == 1) {
Test test = (Test)tests.get(0);
ValueComparator comparator = new ValueComparator(i, test);
comparators.add(comparator);
} else {
String s = "Not implemented yet: multiple tests in "
+ testContainer.getTestContainerDir() + " with id=" + testId;
throw new UnsupportedOperationException(s);
}
}
for (Iterator i = comparators.iterator(); i.hasNext();) {
ValueComparator comparator = (ValueComparator)i.next();
if (comparator != null) {
comparator.readArchives();
}
}
return comparators;
} | private static list buildvaluecomparators(string testid, list testcontainers) { list comparators = new arraylist(); for (int i = 0; i < testcontainers.size(); i++) { testcontainer testcontainer = (testcontainer)testcontainers.get(i); list tests = testcontainer.gettestswithid(testid); if (tests.size() == 0) { comparators.add(null); } else if (tests.size() == 1) { test test = (test)tests.get(0); valuecomparator comparator = new valuecomparator(i, test); comparators.add(comparator); } else { string s = "not implemented yet: multiple tests in " + testcontainer.gettestcontainerdir() + " with id=" + testid; throw new unsupportedoperationexception(s); } } for (iterator i = comparators.iterator(); i.hasnext();) { valuecomparator comparator = (valuecomparator)i.next(); if (comparator != null) { comparator.readarchives(); } } return comparators; } | xyxiaoyou/snappy-store | [
0,
1,
0,
0
] |
8,858 | private static void addWatermarkText(PDDocument doc, PDPage page, PDFont font, String text)
throws IOException
{
try (PDPageContentStream cs
= new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true))
{
float fontHeight = 100; // arbitrary for short text
float width = page.getMediaBox().getWidth();
float height = page.getMediaBox().getHeight();
float stringWidth = font.getStringWidth(text) / 1000 * fontHeight;
float diagonalLength = (float) Math.sqrt(width * width + height * height);
float angle = (float) Math.atan2(height, width);
float x = (diagonalLength - stringWidth) / 2; // "horizontal" position in rotated world
float y = -fontHeight / 4; // 4 is a trial-and-error thing, this lowers the text a bit
cs.transform(Matrix.getRotateInstance(angle, 0, 0));
cs.setFont(font, fontHeight);
// cs.setRenderingMode(RenderingMode.STROKE) // for "hollow" effect
PDExtendedGraphicsState gs = new PDExtendedGraphicsState();
gs.setNonStrokingAlphaConstant(0.2f);
gs.setStrokingAlphaConstant(0.2f);
gs.setBlendMode(BlendMode.MULTIPLY);
gs.setLineWidth(3f);
cs.setGraphicsStateParameters(gs);
// some API weirdness here. When int, range is 0..255.
// when float, this would be 0..1f
cs.setNonStrokingColor(255, 0, 0);
cs.setStrokingColor(255, 0, 0);
cs.beginText();
cs.newLineAtOffset(x, y);
cs.showText(text);
cs.endText();
}
} | private static void addWatermarkText(PDDocument doc, PDPage page, PDFont font, String text)
throws IOException
{
try (PDPageContentStream cs
= new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true))
{
float fontHeight = 100;
float width = page.getMediaBox().getWidth();
float height = page.getMediaBox().getHeight();
float stringWidth = font.getStringWidth(text) / 1000 * fontHeight;
float diagonalLength = (float) Math.sqrt(width * width + height * height);
float angle = (float) Math.atan2(height, width);
float x = (diagonalLength - stringWidth) / 2;
float y = -fontHeight / 4;
cs.transform(Matrix.getRotateInstance(angle, 0, 0));
cs.setFont(font, fontHeight);
PDExtendedGraphicsState gs = new PDExtendedGraphicsState();
gs.setNonStrokingAlphaConstant(0.2f);
gs.setStrokingAlphaConstant(0.2f);
gs.setBlendMode(BlendMode.MULTIPLY);
gs.setLineWidth(3f);
cs.setGraphicsStateParameters(gs);
cs.setNonStrokingColor(255, 0, 0);
cs.setStrokingColor(255, 0, 0);
cs.beginText();
cs.newLineAtOffset(x, y);
cs.showText(text);
cs.endText();
}
} | private static void addwatermarktext(pddocument doc, pdpage page, pdfont font, string text) throws ioexception { try (pdpagecontentstream cs = new pdpagecontentstream(doc, page, pdpagecontentstream.appendmode.append, true, true)) { float fontheight = 100; float width = page.getmediabox().getwidth(); float height = page.getmediabox().getheight(); float stringwidth = font.getstringwidth(text) / 1000 * fontheight; float diagonallength = (float) math.sqrt(width * width + height * height); float angle = (float) math.atan2(height, width); float x = (diagonallength - stringwidth) / 2; float y = -fontheight / 4; cs.transform(matrix.getrotateinstance(angle, 0, 0)); cs.setfont(font, fontheight); pdextendedgraphicsstate gs = new pdextendedgraphicsstate(); gs.setnonstrokingalphaconstant(0.2f); gs.setstrokingalphaconstant(0.2f); gs.setblendmode(blendmode.multiply); gs.setlinewidth(3f); cs.setgraphicsstateparameters(gs); cs.setnonstrokingcolor(255, 0, 0); cs.setstrokingcolor(255, 0, 0); cs.begintext(); cs.newlineatoffset(x, y); cs.showtext(text); cs.endtext(); } } | vijji432/pdfbox | [
0,
0,
1,
0
] |
17,057 | private void deflateData(boolean force) throws IOException {
//we don't need to flush here, as this should have been called already by the time we get to
//this point
boolean nextCreated = false;
try {
PooledByteBuffer pooled = this.currentBuffer;
final ByteBuffer outputBuffer = pooled.getBuffer();
final boolean shutdown = anyAreSet(state, SHUTDOWN);
byte[] buffer = new byte[1024]; //TODO: we should pool this and make it configurable or something
while (force || !deflater.needsInput() || (shutdown && !deflater.finished())) {
int count = deflater.deflate(buffer, 0, buffer.length, force ? Deflater.SYNC_FLUSH: Deflater.NO_FLUSH);
Connectors.updateResponseBytesSent(exchange, count);
if (count != 0) {
int remaining = outputBuffer.remaining();
if (remaining > count) {
outputBuffer.put(buffer, 0, count);
} else {
if (remaining == count) {
outputBuffer.put(buffer, 0, count);
} else {
outputBuffer.put(buffer, 0, remaining);
additionalBuffer = ByteBuffer.wrap(buffer, remaining, count - remaining);
}
outputBuffer.flip();
this.state |= FLUSHING_BUFFER;
if (next == null) {
nextCreated = true;
this.next = createNextChannel();
}
if (!performFlushIfRequired()) {
return;
}
}
} else {
force = false;
}
}
} finally {
if (nextCreated) {
if (anyAreSet(state, WRITES_RESUMED)) {
next.resumeWrites();
}
}
}
} | private void deflateData(boolean force) throws IOException {
boolean nextCreated = false;
try {
PooledByteBuffer pooled = this.currentBuffer;
final ByteBuffer outputBuffer = pooled.getBuffer();
final boolean shutdown = anyAreSet(state, SHUTDOWN);
byte[] buffer = new byte[1024];
while (force || !deflater.needsInput() || (shutdown && !deflater.finished())) {
int count = deflater.deflate(buffer, 0, buffer.length, force ? Deflater.SYNC_FLUSH: Deflater.NO_FLUSH);
Connectors.updateResponseBytesSent(exchange, count);
if (count != 0) {
int remaining = outputBuffer.remaining();
if (remaining > count) {
outputBuffer.put(buffer, 0, count);
} else {
if (remaining == count) {
outputBuffer.put(buffer, 0, count);
} else {
outputBuffer.put(buffer, 0, remaining);
additionalBuffer = ByteBuffer.wrap(buffer, remaining, count - remaining);
}
outputBuffer.flip();
this.state |= FLUSHING_BUFFER;
if (next == null) {
nextCreated = true;
this.next = createNextChannel();
}
if (!performFlushIfRequired()) {
return;
}
}
} else {
force = false;
}
}
} finally {
if (nextCreated) {
if (anyAreSet(state, WRITES_RESUMED)) {
next.resumeWrites();
}
}
}
} | private void deflatedata(boolean force) throws ioexception { boolean nextcreated = false; try { pooledbytebuffer pooled = this.currentbuffer; final bytebuffer outputbuffer = pooled.getbuffer(); final boolean shutdown = anyareset(state, shutdown); byte[] buffer = new byte[1024]; while (force || !deflater.needsinput() || (shutdown && !deflater.finished())) { int count = deflater.deflate(buffer, 0, buffer.length, force ? deflater.sync_flush: deflater.no_flush); connectors.updateresponsebytessent(exchange, count); if (count != 0) { int remaining = outputbuffer.remaining(); if (remaining > count) { outputbuffer.put(buffer, 0, count); } else { if (remaining == count) { outputbuffer.put(buffer, 0, count); } else { outputbuffer.put(buffer, 0, remaining); additionalbuffer = bytebuffer.wrap(buffer, remaining, count - remaining); } outputbuffer.flip(); this.state |= flushing_buffer; if (next == null) { nextcreated = true; this.next = createnextchannel(); } if (!performflushifrequired()) { return; } } } else { force = false; } } } finally { if (nextcreated) { if (anyareset(state, writes_resumed)) { next.resumewrites(); } } } } | yzy830/undertow-analyze | [
1,
0,
0,
0
] |
33,483 | public void copyData(DataWrapper body, byte[] data, int offset) {
for(int i = 0; i < body.getReadableSize(); i++) {
//TODO: Think about using System.arrayCopy here(what is faster?)
data[offset + i] = body.readByteAt(i);
}
} | public void copyData(DataWrapper body, byte[] data, int offset) {
for(int i = 0; i < body.getReadableSize(); i++) {
data[offset + i] = body.readByteAt(i);
}
} | public void copydata(datawrapper body, byte[] data, int offset) { for(int i = 0; i < body.getreadablesize(); i++) { data[offset + i] = body.readbyteat(i); } } | zreed/webpieces | [
1,
0,
0,
0
] |
33,494 | public boolean expire(Table table) {
if (expirationPeriod <= 0) {
return false;
}
long current = System.currentTimeMillis();
Long last = expirationStatus.putIfAbsent(table.location(), current);
if (last != null && current - last >= expirationPeriod) {
expirationStatus.put(table.location(), current);
ExecutorService executorService = executorService();
executorService.submit(() -> {
logger.debug("Expiring Iceberg table [{}] metadata", table.location());
table.expireSnapshots()
.expireOlderThan(current)
.commit();
// TODO: Replace with table metadata expiration through Iceberg API
// when https://github.com/apache/incubator-iceberg/issues/181 is resolved
// table.expireTableMetadata().expireOlderThan(current).commit();
expireTableMetadata(table);
});
return true;
}
return false;
} | public boolean expire(Table table) {
if (expirationPeriod <= 0) {
return false;
}
long current = System.currentTimeMillis();
Long last = expirationStatus.putIfAbsent(table.location(), current);
if (last != null && current - last >= expirationPeriod) {
expirationStatus.put(table.location(), current);
ExecutorService executorService = executorService();
executorService.submit(() -> {
logger.debug("Expiring Iceberg table [{}] metadata", table.location());
table.expireSnapshots()
.expireOlderThan(current)
.commit();
expireTableMetadata(table);
});
return true;
}
return false;
} | public boolean expire(table table) { if (expirationperiod <= 0) { return false; } long current = system.currenttimemillis(); long last = expirationstatus.putifabsent(table.location(), current); if (last != null && current - last >= expirationperiod) { expirationstatus.put(table.location(), current); executorservice executorservice = executorservice(); executorservice.submit(() -> { logger.debug("expiring iceberg table [{}] metadata", table.location()); table.expiresnapshots() .expireolderthan(current) .commit(); expiretablemetadata(table); }); return true; } return false; } | yanlin-Lynn/drill | [
1,
0,
0,
0
] |
728 | protected boolean shouldNotifyObserversOnSetIndex() {
return true;
} | protected boolean shouldNotifyObserversOnSetIndex() {
return true;
} | protected boolean shouldnotifyobserversonsetindex() { return true; } | zealoussnow/chromium | [
0,
0,
1,
0
] |
8,942 | private void configureEditableItem() {
String editText = item.getText();
etEditItem = (EditText) findViewById(R.id.etEditItem);
etEditItem.setText(editText);
etEditItem.setSelection(editText.length());
// TODO: allow user to not choose a date (and make the datepicker look a lot better)
etDueDate = (EditText) findViewById(R.id.etDueDate);
String dueDate = item.getDueDate();
etDueDate.setText(dueDate);
/*if (dueDate != null) {
SimpleDateFormat sdf = new SimpleDateFormat(TodoItem.DUE_DATE_FORMAT);
Date date = new Date();
try {
date = sdf.parse(dueDate);
} catch (ParseException e) {
Log.w(getClass().getSimpleName(), "Failed to parse due date, '" + dueDate + "' using format " + TodoItem.DUE_DATE_FORMAT);
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
datePicker.updateDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
}*/
spPriority = (Spinner) findViewById(R.id.spinnerPriority);
ArrayAdapter<TodoItem.Priority> priorityAdapter = new ArrayAdapter<TodoItem.Priority>(
this, android.R.layout.simple_list_item_1, TodoItem.Priority.values());
spPriority.setAdapter(priorityAdapter);
int priorityIndex = item.getPriority().ordinal();
spPriority.setSelection(priorityIndex);
} | private void configureEditableItem() {
String editText = item.getText();
etEditItem = (EditText) findViewById(R.id.etEditItem);
etEditItem.setText(editText);
etEditItem.setSelection(editText.length());
etDueDate = (EditText) findViewById(R.id.etDueDate);
String dueDate = item.getDueDate();
etDueDate.setText(dueDate);
spPriority = (Spinner) findViewById(R.id.spinnerPriority);
ArrayAdapter<TodoItem.Priority> priorityAdapter = new ArrayAdapter<TodoItem.Priority>(
this, android.R.layout.simple_list_item_1, TodoItem.Priority.values());
spPriority.setAdapter(priorityAdapter);
int priorityIndex = item.getPriority().ordinal();
spPriority.setSelection(priorityIndex);
} | private void configureeditableitem() { string edittext = item.gettext(); etedititem = (edittext) findviewbyid(r.id.etedititem); etedititem.settext(edittext); etedititem.setselection(edittext.length()); etduedate = (edittext) findviewbyid(r.id.etduedate); string duedate = item.getduedate(); etduedate.settext(duedate); sppriority = (spinner) findviewbyid(r.id.spinnerpriority); arrayadapter<todoitem.priority> priorityadapter = new arrayadapter<todoitem.priority>( this, android.r.layout.simple_list_item_1, todoitem.priority.values()); sppriority.setadapter(priorityadapter); int priorityindex = item.getpriority().ordinal(); sppriority.setselection(priorityindex); } | willieowens/simpletodo | [
1,
0,
0,
0
] |
776 | @Override
public int write(ChannelBuffer cb) {
// TODO This will be implemented in the next version
return 0;
} | @Override
public int write(ChannelBuffer cb) {
return 0;
} | @override public int write(channelbuffer cb) { return 0; } | ustc-fhq/onos | [
0,
1,
0,
0
] |
17,189 | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx; // not a power of two, add one more
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
// TODO: reserving the entire thing is not ideal before we alloc anything. Interleave?
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated(); // TODO: pool of objects?
}
// First try to quickly lock some of the correct-sized free lists and allocate from them.
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1; // Next arena is being allocated.
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) { // TODO: check if it can still happen; count should take care of this.
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
// TODO: this is very hacky.
// We called reserveMemory so we know that somewhere in there, there's memory waiting for us.
// However, we have a class of rare race conditions related to the order of locking/checking of
// different allocation areas. Simple case - say we have 2 arenas, 256Kb available in arena 2.
// We look at arena 1; someone deallocs 256Kb from arena 1 and allocs the same from arena 2;
// we look at arena 2 and find no memory. Or, for single arena, 2 threads reserve 256k each,
// and a single 1Mb block is available. When the 1st thread locks the 1Mb freelist, the 2nd one
// might have already examined the 256k and 512k lists, finding nothing. Blocks placed by (1)
// into smaller lists after its split is done will not be found by (2); given that freelist
// locks don't overlap, (2) may even run completely between the time (1) takes out the 1Mb
// block and the time it returns the remaining 768Kb.
// Two solutions to this are some form of cross-thread helping (threads putting "demand"
// into some sort of queues that deallocate and split will examine), or having and "actor"
// allocator thread (or threads per arena).
// The 2nd one is probably much simpler and will allow us to get rid of a lot of sync code.
// But for now we will just retry 5 times 0_o
for (int attempt = 0; attempt < 5; ++attempt) {
// Try to split bigger blocks. TODO: again, ideally we would tryLock at least once
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break; // Shouldn't happen.
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
// Try to allocate memory if we haven't allocated all the way to maxSize yet; very rare.
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} | @Override
public void allocateMultiple(MemoryBuffer[] dest, int size)
throws AllocatorOutOfMemoryException {
assert size > 0 : "size is " + size;
if (size > maxAllocation) {
throw new RuntimeException("Trying to allocate " + size + "; max is " + maxAllocation);
}
int freeListIx = 31 - Integer.numberOfLeadingZeros(size);
if (size != (1 << freeListIx)) ++freeListIx;
freeListIx = Math.max(freeListIx - minAllocLog2, 0);
int allocLog2 = freeListIx + minAllocLog2;
int allocationSize = 1 << allocLog2;
memoryManager.reserveMemory(dest.length << allocLog2, true);
int ix = 0;
for (int i = 0; i < dest.length; ++i) {
if (dest[i] != null) continue;
dest[i] = createUnallocated();
}
int arenaCount = allocatedArenas.get();
if (arenaCount < 0) {
arenaCount = -arenaCount - 1;
}
long threadId = arenaCount > 1 ? Thread.currentThread().getId() : 0;
{
int startIndex = (int)(threadId % arenaCount), index = startIndex;
do {
int newIx = arenas[index].allocateFast(index, freeListIx, dest, ix, allocationSize);
if (newIx == dest.length) return;
if (newIx != -1) {
ix = newIx;
}
ix = newIx;
if ((++index) == arenaCount) {
index = 0;
}
} while (index != startIndex);
}
for (int attempt = 0; attempt < 5; ++attempt) {
for (int i = 0; i < arenaCount; ++i) {
int newIx = arenas[i].allocateWithSplit(i, freeListIx, dest, ix, allocationSize);
if (newIx == -1) break;
if (newIx == dest.length) return;
ix = newIx;
}
if (attempt == 0) {
for (int i = arenaCount; i < arenas.length; ++i) {
ix = arenas[i].allocateWithExpand(i, freeListIx, dest, ix, allocationSize);
if (ix == dest.length) return;
}
}
LlapIoImpl.LOG.warn("Failed to allocate despite reserved memory; will retry " + attempt);
}
String msg = "Failed to allocate " + size + "; at " + ix + " out of " + dest.length;
LlapIoImpl.LOG.error(msg + "\nALLOCATOR STATE:\n" + debugDump()
+ "\nPARENT STATE:\n" + memoryManager.debugDumpForOom());
throw new AllocatorOutOfMemoryException(msg);
} | @override public void allocatemultiple(memorybuffer[] dest, int size) throws allocatoroutofmemoryexception { assert size > 0 : "size is " + size; if (size > maxallocation) { throw new runtimeexception("trying to allocate " + size + "; max is " + maxallocation); } int freelistix = 31 - integer.numberofleadingzeros(size); if (size != (1 << freelistix)) ++freelistix; freelistix = math.max(freelistix - minalloclog2, 0); int alloclog2 = freelistix + minalloclog2; int allocationsize = 1 << alloclog2; memorymanager.reservememory(dest.length << alloclog2, true); int ix = 0; for (int i = 0; i < dest.length; ++i) { if (dest[i] != null) continue; dest[i] = createunallocated(); } int arenacount = allocatedarenas.get(); if (arenacount < 0) { arenacount = -arenacount - 1; } long threadid = arenacount > 1 ? thread.currentthread().getid() : 0; { int startindex = (int)(threadid % arenacount), index = startindex; do { int newix = arenas[index].allocatefast(index, freelistix, dest, ix, allocationsize); if (newix == dest.length) return; if (newix != -1) { ix = newix; } ix = newix; if ((++index) == arenacount) { index = 0; } } while (index != startindex); } for (int attempt = 0; attempt < 5; ++attempt) { for (int i = 0; i < arenacount; ++i) { int newix = arenas[i].allocatewithsplit(i, freelistix, dest, ix, allocationsize); if (newix == -1) break; if (newix == dest.length) return; ix = newix; } if (attempt == 0) { for (int i = arenacount; i < arenas.length; ++i) { ix = arenas[i].allocatewithexpand(i, freelistix, dest, ix, allocationsize); if (ix == dest.length) return; } } llapioimpl.log.warn("failed to allocate despite reserved memory; will retry " + attempt); } string msg = "failed to allocate " + size + "; at " + ix + " out of " + dest.length; llapioimpl.log.error(msg + "\nallocator state:\n" + debugdump() + "\nparent state:\n" + memorymanager.debugdumpforoom()); throw new allocatoroutofmemoryexception(msg); } | woowahan/hive | [
1,
1,
0,
0
] |
17,191 | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1; // not allocated yet
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
// Try to allocate from target-sized free list, maybe we'll get lucky.
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true); // Header for newly allocated used blocks.
int headerStep = 1 << freeListIx; // Number of headers (smallest blocks) per target block.
int splitListIx = freeListIx + 1; // Next free list from which we will be splitting.
// Each iteration of this loop tries to split blocks from one level of the free list into
// target size blocks; if we cannot satisfy the allocation from the free list containing the
// blocks of a particular size, we'll try to split yet larger blocks, until we run out.
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2; // How many ways each block splits into target size.
int lastSplitBlocksRemaining = -1; // How many target-sized blocks remain from last split.
int lastSplitNextHeader = -1; // The header index for the beginning of the remainder.
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead; // Index of the next free block to split.
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
// We will split the block at headerIx [splitWays] ways, and take [toTake] blocks,
// which will leave [lastSplitBlocksRemaining] free blocks of target size.
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake; // Whatever remains.
// Take toTake blocks by splitting the block at offset.
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
// TODO: this could be done out of the lock, we only need to take the blocks out.
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx; // If anything remains, this is where it starts.
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx); // In the end, update free list head.
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
// We have just obtained all we needed by splitting some block; now we need
// to put the space remaining from that block into lower free lists.
// We'll put at most one block into each list, since 2 blocks can always be combined
// to make a larger-level block. Each bit in the remaining target-sized blocks count
// is one block in a list offset from target-sized list by bit index.
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | private int allocateWithSplit(int arenaIx, int freeListIx,
MemoryBuffer[] dest, int ix, int allocationSize) {
if (data == null) return -1;
FreeList freeList = freeLists[freeListIx];
int remaining = -1;
freeList.lock.lock();
try {
ix = allocateFromFreeListUnderLock(
arenaIx, freeList, freeListIx, dest, ix, allocationSize);
remaining = dest.length - ix;
if (remaining == 0) return ix;
} finally {
freeList.lock.unlock();
}
byte headerData = makeHeader(freeListIx, true);
int headerStep = 1 << freeListIx;
int splitListIx = freeListIx + 1;
while (remaining > 0 && splitListIx < freeLists.length) {
int splitWaysLog2 = (splitListIx - freeListIx);
assert splitWaysLog2 > 0;
int splitWays = 1 << splitWaysLog2;
int lastSplitBlocksRemaining = -1;
int lastSplitNextHeader = -1;
FreeList splitList = freeLists[splitListIx];
splitList.lock.lock();
try {
int headerIx = splitList.listHead;
while (headerIx >= 0 && remaining > 0) {
int origOffset = offsetFromHeaderIndex(headerIx), offset = origOffset;
int toTake = Math.min(splitWays, remaining);
remaining -= toTake;
lastSplitBlocksRemaining = splitWays - toTake;
for (; toTake > 0; ++ix, --toTake, headerIx += headerStep, offset += allocationSize) {
headers[headerIx] = headerData;
((LlapDataBuffer)dest[ix]).initialize(arenaIx, data, offset, allocationSize);
}
lastSplitNextHeader = headerIx;
headerIx = getNextFreeListItem(origOffset);
}
replaceListHeadUnderLock(splitList, headerIx);
} finally {
splitList.lock.unlock();
}
if (remaining == 0) {
int newListIndex = freeListIx;
while (lastSplitBlocksRemaining > 0) {
if ((lastSplitBlocksRemaining & 1) == 1) {
FreeList newFreeList = freeLists[newListIndex];
newFreeList.lock.lock();
headers[lastSplitNextHeader] = makeHeader(newListIndex, false);
try {
addBlockToFreeListUnderLock(newFreeList, lastSplitNextHeader);
} finally {
newFreeList.lock.unlock();
}
lastSplitNextHeader += (1 << newListIndex);
}
lastSplitBlocksRemaining >>>= 1;
++newListIndex;
continue;
}
}
++splitListIx;
}
return ix;
} | private int allocatewithsplit(int arenaix, int freelistix, memorybuffer[] dest, int ix, int allocationsize) { if (data == null) return -1; freelist freelist = freelists[freelistix]; int remaining = -1; freelist.lock.lock(); try { ix = allocatefromfreelistunderlock( arenaix, freelist, freelistix, dest, ix, allocationsize); remaining = dest.length - ix; if (remaining == 0) return ix; } finally { freelist.lock.unlock(); } byte headerdata = makeheader(freelistix, true); int headerstep = 1 << freelistix; int splitlistix = freelistix + 1; while (remaining > 0 && splitlistix < freelists.length) { int splitwayslog2 = (splitlistix - freelistix); assert splitwayslog2 > 0; int splitways = 1 << splitwayslog2; int lastsplitblocksremaining = -1; int lastsplitnextheader = -1; freelist splitlist = freelists[splitlistix]; splitlist.lock.lock(); try { int headerix = splitlist.listhead; while (headerix >= 0 && remaining > 0) { int origoffset = offsetfromheaderindex(headerix), offset = origoffset; int totake = math.min(splitways, remaining); remaining -= totake; lastsplitblocksremaining = splitways - totake; for (; totake > 0; ++ix, --totake, headerix += headerstep, offset += allocationsize) { headers[headerix] = headerdata; ((llapdatabuffer)dest[ix]).initialize(arenaix, data, offset, allocationsize); } lastsplitnextheader = headerix; headerix = getnextfreelistitem(origoffset); } replacelistheadunderlock(splitlist, headerix); } finally { splitlist.lock.unlock(); } if (remaining == 0) { int newlistindex = freelistix; while (lastsplitblocksremaining > 0) { if ((lastsplitblocksremaining & 1) == 1) { freelist newfreelist = freelists[newlistindex]; newfreelist.lock.lock(); headers[lastsplitnextheader] = makeheader(newlistindex, false); try { addblocktofreelistunderlock(newfreelist, lastsplitnextheader); } finally { newfreelist.lock.unlock(); } lastsplitnextheader += (1 << newlistindex); } lastsplitblocksremaining >>>= 1; ++newlistindex; continue; } } ++splitlistix; } return ix; } | woowahan/hive | [
1,
0,
0,
0
] |
17,246 | private boolean checkAccessPermission() throws IOException {
final JobConf jobConf = new JobConf(hiveConf);
Preconditions.checkArgument(updateKey.getCachedEntitiesCount() > 0, "hive partition update key should contain at least one path");
for (FileSystemCachedEntity cachedEntity : updateKey.getCachedEntitiesList()) {
final Path cachedEntityPath;
if (cachedEntity.getPath() == null || cachedEntity.getPath().isEmpty()) {
cachedEntityPath = new Path(updateKey.getPartitionRootDir());
} else {
cachedEntityPath = new Path(updateKey.getPartitionRootDir(), cachedEntity.getPath());
}
// Create filesystem for the given user and given path
// TODO: DX-16001 - make async configurable for Hive.
final HadoopFileSystemWrapper userFS = HiveImpersonationUtil.createFileSystem(user, jobConf, cachedEntityPath);
try {
if (cachedEntity.getIsDir()) {
//DX-7850 : remove once solution for maprfs is found
if (userFS.isMapRfs()) {
userFS.access(cachedEntityPath, FsAction.READ);
} else {
userFS.access(cachedEntityPath, FsAction.READ_EXECUTE);
}
} else {
userFS.access(cachedEntityPath, FsAction.READ);
}
} catch (AccessControlException ace) {
return false;
}
}
return true;
} | private boolean checkAccessPermission() throws IOException {
final JobConf jobConf = new JobConf(hiveConf);
Preconditions.checkArgument(updateKey.getCachedEntitiesCount() > 0, "hive partition update key should contain at least one path");
for (FileSystemCachedEntity cachedEntity : updateKey.getCachedEntitiesList()) {
final Path cachedEntityPath;
if (cachedEntity.getPath() == null || cachedEntity.getPath().isEmpty()) {
cachedEntityPath = new Path(updateKey.getPartitionRootDir());
} else {
cachedEntityPath = new Path(updateKey.getPartitionRootDir(), cachedEntity.getPath());
}
final HadoopFileSystemWrapper userFS = HiveImpersonationUtil.createFileSystem(user, jobConf, cachedEntityPath);
try {
if (cachedEntity.getIsDir()) {
if (userFS.isMapRfs()) {
userFS.access(cachedEntityPath, FsAction.READ);
} else {
userFS.access(cachedEntityPath, FsAction.READ_EXECUTE);
}
} else {
userFS.access(cachedEntityPath, FsAction.READ);
}
} catch (AccessControlException ace) {
return false;
}
}
return true;
} | private boolean checkaccesspermission() throws ioexception { final jobconf jobconf = new jobconf(hiveconf); preconditions.checkargument(updatekey.getcachedentitiescount() > 0, "hive partition update key should contain at least one path"); for (filesystemcachedentity cachedentity : updatekey.getcachedentitieslist()) { final path cachedentitypath; if (cachedentity.getpath() == null || cachedentity.getpath().isempty()) { cachedentitypath = new path(updatekey.getpartitionrootdir()); } else { cachedentitypath = new path(updatekey.getpartitionrootdir(), cachedentity.getpath()); } final hadoopfilesystemwrapper userfs = hiveimpersonationutil.createfilesystem(user, jobconf, cachedentitypath); try { if (cachedentity.getisdir()) { if (userfs.ismaprfs()) { userfs.access(cachedentitypath, fsaction.read); } else { userfs.access(cachedentitypath, fsaction.read_execute); } } else { userfs.access(cachedentitypath, fsaction.read); } } catch (accesscontrolexception ace) { return false; } } return true; } | wangchong6808/dremio-oss | [
1,
1,
0,
0
] |
17,282 | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} | private void ntlmProxyChallenge(String authenticateHeader, Request request
HttpHeaders requestHeaders
Realm proxyRealm
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} | private void ntlmproxychallenge(string authenticateheader, request request httpheaders requestheaders realm proxyrealm nettyresponsefuture<?> future) { if (authenticateheader.equals("ntlm")) { string challengeheader = ntlmengine.instance.generatetype1msg(); requestheaders.set(httpheaders.names.proxy_authorization, "ntlm " + challengeheader); future.getinproxyauth().set(false); } else { string serverchallenge = authenticateheader.substring("ntlm ".length()).trim(); string challengeheader = ntlmengine.instance.generatetype3msg(proxyrealm.getprincipal(), proxyrealm.getpassword(), proxyrealm.getntlmdomain(), proxyrealm.getntlmhost(), serverchallenge); requestheaders.set(httpheaders.names.proxy_authorization, "ntlm " + challengeheader); } } | wsargent/async-http-client | [
0,
0,
1,
0
] |
974 | private void trackWatchForAttempt(WatchedPathInfo watchedPathInfo, WatchKey watchKey) {
assert watchedPathInfo.pathIdentifier != null;
// TODO May be possible to do finer-grained locks.
synchronized (watchesPerAttempt) {
List<WatchKey> list = watchesPerAttempt.get(watchedPathInfo.pathIdentifier);
if (list == null) {
list = new LinkedList<>();
watchesPerAttempt.put(watchedPathInfo.pathIdentifier, list);
}
list.add(watchKey);
}
} | private void trackWatchForAttempt(WatchedPathInfo watchedPathInfo, WatchKey watchKey) {
assert watchedPathInfo.pathIdentifier != null;
synchronized (watchesPerAttempt) {
List<WatchKey> list = watchesPerAttempt.get(watchedPathInfo.pathIdentifier);
if (list == null) {
list = new LinkedList<>();
watchesPerAttempt.put(watchedPathInfo.pathIdentifier, list);
}
list.add(watchKey);
}
} | private void trackwatchforattempt(watchedpathinfo watchedpathinfo, watchkey watchkey) { assert watchedpathinfo.pathidentifier != null; synchronized (watchesperattempt) { list<watchkey> list = watchesperattempt.get(watchedpathinfo.pathidentifier); if (list == null) { list = new linkedlist<>(); watchesperattempt.put(watchedpathinfo.pathidentifier, list); } list.add(watchkey); } } | zem13579/hive | [
1,
0,
0,
0
] |
975 | private void cancelWatchesForAttempt(AttemptPathIdentifier pathIdentifier) {
// TODO May be possible to do finer-grained locks.
synchronized(watchesPerAttempt) {
List<WatchKey> list = watchesPerAttempt.remove(pathIdentifier);
if (list != null) {
for (WatchKey watchKey : list) {
watchKey.cancel();
}
}
}
} | private void cancelWatchesForAttempt(AttemptPathIdentifier pathIdentifier) {
synchronized(watchesPerAttempt) {
List<WatchKey> list = watchesPerAttempt.remove(pathIdentifier);
if (list != null) {
for (WatchKey watchKey : list) {
watchKey.cancel();
}
}
}
} | private void cancelwatchesforattempt(attemptpathidentifier pathidentifier) { synchronized(watchesperattempt) { list<watchkey> list = watchesperattempt.remove(pathidentifier); if (list != null) { for (watchkey watchkey : list) { watchkey.cancel(); } } } } | zem13579/hive | [
1,
0,
0,
0
] |
1,017 | public static String[] textToWords(String text) {
// TODO: strip word-final or -initial apostrophes as in James' or 'cause.
// Currently assuming hyphenated expressions split into two Asr words.
return text.replace('-', ' ').replaceAll("['.!?,:;\"\\(\\)]", " ").toUpperCase(Locale.US).trim().split("\\s+");
} | public static String[] textToWords(String text) {
return text.replace('-', ' ').replaceAll("['.!?,:;\"\\(\\)]", " ").toUpperCase(Locale.US).trim().split("\\s+");
} | public static string[] texttowords(string text) { return text.replace('-', ' ').replaceall("['.!?,:;\"\\(\\)]", " ").touppercase(locale.us).trim().split("\\s+"); } | yejingjie0209/robotutor_china | [
1,
0,
0,
0
] |
1,034 | public void engineSetPadding(String padding)
throws NoSuchPaddingException
{
String paddingName = Strings.toUpperCase(padding);
// TDOD: make this meaningful...
if (paddingName.equals("NOPADDING"))
{
}
else if (paddingName.equals("PKCS5PADDING") || paddingName.equals("PKCS7PADDING"))
{
}
else
{
throw new NoSuchPaddingException("padding not available with IESCipher");
}
} | public void engineSetPadding(String padding)
throws NoSuchPaddingException
{
String paddingName = Strings.toUpperCase(padding);
if (paddingName.equals("NOPADDING"))
{
}
else if (paddingName.equals("PKCS5PADDING") || paddingName.equals("PKCS7PADDING"))
{
}
else
{
throw new NoSuchPaddingException("padding not available with IESCipher");
}
} | public void enginesetpadding(string padding) throws nosuchpaddingexception { string paddingname = strings.touppercase(padding); if (paddingname.equals("nopadding")) { } else if (paddingname.equals("pkcs5padding") || paddingname.equals("pkcs7padding")) { } else { throw new nosuchpaddingexception("padding not available with iescipher"); } } | tonywasher/bc-java | [
1,
0,
0,
0
] |
1,094 | private void addStylesQueueRequest(int start, int length, String s) {
// System.err.println(start + " ---> " + length);
int startNew = backupToPossibleStyleStart(start);
length = length + start - startNew;
start = startNew;
// System.err.println(start + " ---> " + length);
if (syntaxBusy) {
// System.err.println("syntaxBusy, request queued");
styleQueue.add(new StyleQueueItem(start, length, s));
} else {
// Todo: if syntax is not busy but a request got stuck
// System.err.println("request not queued");
if (styleQueue.size() != 0) System.err.println("A request got stuck");
syntaxBusy = true;
addStylesNew(start, length, s);
}
} | private void addStylesQueueRequest(int start, int length, String s) {
int startNew = backupToPossibleStyleStart(start);
length = length + start - startNew;
start = startNew;
if (syntaxBusy) {
styleQueue.add(new StyleQueueItem(start, length, s));
} else {
if (styleQueue.size() != 0) System.err.println("A request got stuck");
syntaxBusy = true;
addStylesNew(start, length, s);
}
} | private void addstylesqueuerequest(int start, int length, string s) { int startnew = backuptopossiblestylestart(start); length = length + start - startnew; start = startnew; if (syntaxbusy) { stylequeue.add(new stylequeueitem(start, length, s)); } else { if (stylequeue.size() != 0) system.err.println("a request got stuck"); syntaxbusy = true; addstylesnew(start, length, s); } } | xmf-xmodeler/MosaicFX | [
1,
0,
0,
0
] |
17,497 | public long getMicrosecondLength()
{
long tickLength = getTickLength();
if (divisionType == PPQ)
{
// FIXME
// How can this possible be computed? PPQ is pulses per quarter-note,
// which is dependent on the tempo of the Sequencer.
throw new
UnsupportedOperationException("Can't compute PPQ based lengths yet");
}
else
{
// This is a fixed tick per frame computation
return (long) ((tickLength * 1000000) / (divisionType * resolution));
}
} | public long getMicrosecondLength()
{
long tickLength = getTickLength();
if (divisionType == PPQ)
{
throw new
UnsupportedOperationException("Can't compute PPQ based lengths yet");
}
else
{
return (long) ((tickLength * 1000000) / (divisionType * resolution));
}
} | public long getmicrosecondlength() { long ticklength = getticklength(); if (divisiontype == ppq) { throw new unsupportedoperationexception("can't compute ppq based lengths yet"); } else { return (long) ((ticklength * 1000000) / (divisiontype * resolution)); } } | vidkidz/crossbridge | [
0,
0,
1,
0
] |
9,309 | @TargetApi(Build.VERSION_CODES.KITKAT)
public static File getBestAvailableCacheRoot(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// In KitKat we can query multiple devices.
// TODO: optimize for stability instead of picking first one
File[] roots = context.getExternalCacheDirs();
if (roots != null) {
for (File root : roots) {
if (root == null) {
continue;
}
if (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(root))) {
return root;
}
}
}
} else if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
// Pre-KitKat, only one external storage device was addressable
return context.getExternalCacheDir();
}
// Worst case, resort to internal storage
return context.getCacheDir();
} | @TargetApi(Build.VERSION_CODES.KITKAT)
public static File getBestAvailableCacheRoot(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
File[] roots = context.getExternalCacheDirs();
if (roots != null) {
for (File root : roots) {
if (root == null) {
continue;
}
if (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(root))) {
return root;
}
}
}
} else if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
return context.getExternalCacheDir();
}
return context.getCacheDir();
} | @targetapi(build.version_codes.kitkat) public static file getbestavailablecacheroot(context context) { if (build.version.sdk_int >= build.version_codes.kitkat) { file[] roots = context.getexternalcachedirs(); if (roots != null) { for (file root : roots) { if (root == null) { continue; } if (environment.media_mounted.equals(environment.getstoragestate(root))) { return root; } } } } else if (environment.media_mounted.equals(environment.getexternalstoragestate())) { return context.getexternalcachedir(); } return context.getcachedir(); } | xxwar/muzei | [
1,
0,
0,
0
] |
9,310 | @TargetApi(Build.VERSION_CODES.KITKAT)
public static File getBestAvailableFilesRoot(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// In KitKat we can query multiple devices.
// TODO: optimize for stability instead of picking first one
File[] roots = context.getExternalFilesDirs(null);
if (roots != null) {
for (File root : roots) {
if (root == null) {
continue;
}
if (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(root))) {
return root;
}
}
}
} else if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
// Pre-KitKat, only one external storage device was addressable
return context.getExternalFilesDir(null);
}
// Worst case, resort to internal storage
return context.getFilesDir();
} | @TargetApi(Build.VERSION_CODES.KITKAT)
public static File getBestAvailableFilesRoot(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
File[] roots = context.getExternalFilesDirs(null);
if (roots != null) {
for (File root : roots) {
if (root == null) {
continue;
}
if (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(root))) {
return root;
}
}
}
} else if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
return context.getExternalFilesDir(null);
}
return context.getFilesDir();
} | @targetapi(build.version_codes.kitkat) public static file getbestavailablefilesroot(context context) { if (build.version.sdk_int >= build.version_codes.kitkat) { file[] roots = context.getexternalfilesdirs(null); if (roots != null) { for (file root : roots) { if (root == null) { continue; } if (environment.media_mounted.equals(environment.getstoragestate(root))) { return root; } } } } else if (environment.media_mounted.equals(environment.getexternalstoragestate())) { return context.getexternalfilesdir(null); } return context.getfilesdir(); } | xxwar/muzei | [
1,
0,
0,
0
] |
1,129 | @Test
public void testMultiColumnPruning() throws IOException {
shell.setHiveSessionValue("hive.cbo.enable", true);
Schema schema1 = new Schema(optional(1, "fk", Types.StringType.get()));
List<Record> records1 = TestHelper.RecordsBuilder.newInstance(schema1).add("fk1").build();
testTables.createTable(shell, "table1", schema1, fileFormat, records1);
Schema schema2 = new Schema(optional(1, "fk", Types.StringType.get()), optional(2, "val", Types.StringType.get()));
List<Record> records2 = TestHelper.RecordsBuilder.newInstance(schema2).add("fk1", "val").build();
testTables.createTable(shell, "table2", schema2, fileFormat, records2);
// MR is needed for the reproduction
shell.setHiveSessionValue("hive.execution.engine", "mr");
String query = "SELECT t2.val FROM table1 t1 JOIN table2 t2 ON t1.fk = t2.fk";
List<Object[]> result = shell.executeStatement(query);
Assert.assertEquals(1, result.size());
Assert.assertArrayEquals(new Object[]{"val"}, result.get(0));
} | @Test
public void testMultiColumnPruning() throws IOException {
shell.setHiveSessionValue("hive.cbo.enable", true);
Schema schema1 = new Schema(optional(1, "fk", Types.StringType.get()));
List<Record> records1 = TestHelper.RecordsBuilder.newInstance(schema1).add("fk1").build();
testTables.createTable(shell, "table1", schema1, fileFormat, records1);
Schema schema2 = new Schema(optional(1, "fk", Types.StringType.get()), optional(2, "val", Types.StringType.get()));
List<Record> records2 = TestHelper.RecordsBuilder.newInstance(schema2).add("fk1", "val").build();
testTables.createTable(shell, "table2", schema2, fileFormat, records2);
shell.setHiveSessionValue("hive.execution.engine", "mr");
String query = "SELECT t2.val FROM table1 t1 JOIN table2 t2 ON t1.fk = t2.fk";
List<Object[]> result = shell.executeStatement(query);
Assert.assertEquals(1, result.size());
Assert.assertArrayEquals(new Object[]{"val"}, result.get(0));
} | @test public void testmulticolumnpruning() throws ioexception { shell.sethivesessionvalue("hive.cbo.enable", true); schema schema1 = new schema(optional(1, "fk", types.stringtype.get())); list<record> records1 = testhelper.recordsbuilder.newinstance(schema1).add("fk1").build(); testtables.createtable(shell, "table1", schema1, fileformat, records1); schema schema2 = new schema(optional(1, "fk", types.stringtype.get()), optional(2, "val", types.stringtype.get())); list<record> records2 = testhelper.recordsbuilder.newinstance(schema2).add("fk1", "val").build(); testtables.createtable(shell, "table2", schema2, fileformat, records2); shell.sethivesessionvalue("hive.execution.engine", "mr"); string query = "select t2.val from table1 t1 join table2 t2 on t1.fk = t2.fk"; list<object[]> result = shell.executestatement(query); assert.assertequals(1, result.size()); assert.assertarrayequals(new object[]{"val"}, result.get(0)); } | zem13579/hive | [
0,
0,
1,
0
] |
17,517 | @Override
protected void render(GLRootView root, GL11 gl) {
Rect p = mPaddings;
int height = getHeight() - p.top - p.bottom;
StringTexture title = mText;
//TODO: cut the text if it is too long
title.draw(root, p.left, p.top + (height - title.getHeight()) / 2);
} | @Override
protected void render(GLRootView root, GL11 gl) {
Rect p = mPaddings;
int height = getHeight() - p.top - p.bottom;
StringTexture title = mText;
title.draw(root, p.left, p.top + (height - title.getHeight()) / 2);
} | @override protected void render(glrootview root, gl11 gl) { rect p = mpaddings; int height = getheight() - p.top - p.bottom; stringtexture title = mtext; title.draw(root, p.left, p.top + (height - title.getheight()) / 2); } | xie-wenjie/AndroidBaseApplicationSourse | [
0,
1,
0,
0
] |
25,738 | boolean getUpdatedDocument(AddUpdateCommand cmd, long versionOnUpdate) throws IOException {
if (!AtomicUpdateDocumentMerger.isAtomicUpdate(cmd)) return false;
Set<String> inPlaceUpdatedFields = AtomicUpdateDocumentMerger.computeInPlaceUpdatableFields(cmd);
if (inPlaceUpdatedFields.size() > 0) { // non-empty means this is suitable for in-place updates
if (docMerger.doInPlaceUpdateMerge(cmd, inPlaceUpdatedFields)) {
return true;
} else {
// in-place update failed, so fall through and re-try the same with a full atomic update
}
}
// full (non-inplace) atomic update
SolrInputDocument sdoc = cmd.getSolrInputDocument();
BytesRef idBytes = cmd.getIndexedId();
String idString = cmd.getPrintableId();
SolrInputDocument oldRootDocWithChildren = RealTimeGetComponent.getInputDocument(cmd.getReq().getCore(), idBytes, RealTimeGetComponent.Resolution.ROOT_WITH_CHILDREN);
if (oldRootDocWithChildren == null) {
if (versionOnUpdate > 0) {
// could just let the optimistic locking throw the error
throw new SolrException(ErrorCode.CONFLICT, "Document not found for update. id=" + idString);
} else if (req.getParams().get(ShardParams._ROUTE_) != null) {
// the specified document could not be found in this shard
// and was explicitly routed using _route_
throw new SolrException(ErrorCode.BAD_REQUEST,
"Could not find document id=" + idString +
", perhaps the wrong \"_route_\" param was supplied");
}
} else {
oldRootDocWithChildren.remove(CommonParams.VERSION_FIELD);
}
SolrInputDocument mergedDoc;
if(idField == null || oldRootDocWithChildren == null) {
// create a new doc by default if an old one wasn't found
mergedDoc = docMerger.merge(sdoc, new SolrInputDocument());
} else {
// Safety check: don't allow an update to an existing doc that has children, unless we actually support this.
if (req.getSchema().isUsableForChildDocs() // however, next line we see it doesn't support child docs
&& req.getSchema().supportsPartialUpdatesOfChildDocs() == false
&& req.getSearcher().count(new TermQuery(new Term(IndexSchema.ROOT_FIELD_NAME, idBytes))) > 1) {
throw new SolrException(ErrorCode.BAD_REQUEST, "This schema does not support partial updates to nested docs. See ref guide.");
}
String oldRootDocRootFieldVal = (String) oldRootDocWithChildren.getFieldValue(IndexSchema.ROOT_FIELD_NAME);
if(req.getSchema().savesChildDocRelations() && oldRootDocRootFieldVal != null &&
!idString.equals(oldRootDocRootFieldVal)) {
// this is an update where the updated doc is not the root document
SolrInputDocument sdocWithChildren = RealTimeGetComponent.getInputDocument(cmd.getReq().getCore(),
idBytes, RealTimeGetComponent.Resolution.DOC_WITH_CHILDREN);
mergedDoc = docMerger.mergeChildDoc(sdoc, oldRootDocWithChildren, sdocWithChildren);
} else {
mergedDoc = docMerger.merge(sdoc, oldRootDocWithChildren);
}
}
cmd.solrDoc = mergedDoc;
return true;
} | boolean getUpdatedDocument(AddUpdateCommand cmd, long versionOnUpdate) throws IOException {
if (!AtomicUpdateDocumentMerger.isAtomicUpdate(cmd)) return false;
Set<String> inPlaceUpdatedFields = AtomicUpdateDocumentMerger.computeInPlaceUpdatableFields(cmd);
if (inPlaceUpdatedFields.size() > 0) {
if (docMerger.doInPlaceUpdateMerge(cmd, inPlaceUpdatedFields)) {
return true;
} else {
}
}
SolrInputDocument sdoc = cmd.getSolrInputDocument();
BytesRef idBytes = cmd.getIndexedId();
String idString = cmd.getPrintableId();
SolrInputDocument oldRootDocWithChildren = RealTimeGetComponent.getInputDocument(cmd.getReq().getCore(), idBytes, RealTimeGetComponent.Resolution.ROOT_WITH_CHILDREN);
if (oldRootDocWithChildren == null) {
if (versionOnUpdate > 0) {
throw new SolrException(ErrorCode.CONFLICT, "Document not found for update. id=" + idString);
} else if (req.getParams().get(ShardParams._ROUTE_) != null) {
throw new SolrException(ErrorCode.BAD_REQUEST,
"Could not find document id=" + idString +
", perhaps the wrong \"_route_\" param was supplied");
}
} else {
oldRootDocWithChildren.remove(CommonParams.VERSION_FIELD);
}
SolrInputDocument mergedDoc;
if(idField == null || oldRootDocWithChildren == null) {
mergedDoc = docMerger.merge(sdoc, new SolrInputDocument());
} else {
if (req.getSchema().isUsableForChildDocs()
&& req.getSchema().supportsPartialUpdatesOfChildDocs() == false
&& req.getSearcher().count(new TermQuery(new Term(IndexSchema.ROOT_FIELD_NAME, idBytes))) > 1) {
throw new SolrException(ErrorCode.BAD_REQUEST, "This schema does not support partial updates to nested docs. See ref guide.");
}
String oldRootDocRootFieldVal = (String) oldRootDocWithChildren.getFieldValue(IndexSchema.ROOT_FIELD_NAME);
if(req.getSchema().savesChildDocRelations() && oldRootDocRootFieldVal != null &&
!idString.equals(oldRootDocRootFieldVal)) {
SolrInputDocument sdocWithChildren = RealTimeGetComponent.getInputDocument(cmd.getReq().getCore(),
idBytes, RealTimeGetComponent.Resolution.DOC_WITH_CHILDREN);
mergedDoc = docMerger.mergeChildDoc(sdoc, oldRootDocWithChildren, sdocWithChildren);
} else {
mergedDoc = docMerger.merge(sdoc, oldRootDocWithChildren);
}
}
cmd.solrDoc = mergedDoc;
return true;
} | boolean getupdateddocument(addupdatecommand cmd, long versiononupdate) throws ioexception { if (!atomicupdatedocumentmerger.isatomicupdate(cmd)) return false; set<string> inplaceupdatedfields = atomicupdatedocumentmerger.computeinplaceupdatablefields(cmd); if (inplaceupdatedfields.size() > 0) { if (docmerger.doinplaceupdatemerge(cmd, inplaceupdatedfields)) { return true; } else { } } solrinputdocument sdoc = cmd.getsolrinputdocument(); bytesref idbytes = cmd.getindexedid(); string idstring = cmd.getprintableid(); solrinputdocument oldrootdocwithchildren = realtimegetcomponent.getinputdocument(cmd.getreq().getcore(), idbytes, realtimegetcomponent.resolution.root_with_children); if (oldrootdocwithchildren == null) { if (versiononupdate > 0) { throw new solrexception(errorcode.conflict, "document not found for update. id=" + idstring); } else if (req.getparams().get(shardparams._route_) != null) { throw new solrexception(errorcode.bad_request, "could not find document id=" + idstring + ", perhaps the wrong \"_route_\" param was supplied"); } } else { oldrootdocwithchildren.remove(commonparams.version_field); } solrinputdocument mergeddoc; if(idfield == null || oldrootdocwithchildren == null) { mergeddoc = docmerger.merge(sdoc, new solrinputdocument()); } else { if (req.getschema().isusableforchilddocs() && req.getschema().supportspartialupdatesofchilddocs() == false && req.getsearcher().count(new termquery(new term(indexschema.root_field_name, idbytes))) > 1) { throw new solrexception(errorcode.bad_request, "this schema does not support partial updates to nested docs. see ref guide."); } string oldrootdocrootfieldval = (string) oldrootdocwithchildren.getfieldvalue(indexschema.root_field_name); if(req.getschema().saveschilddocrelations() && oldrootdocrootfieldval != null && !idstring.equals(oldrootdocrootfieldval)) { solrinputdocument sdocwithchildren = realtimegetcomponent.getinputdocument(cmd.getreq().getcore(), idbytes, realtimegetcomponent.resolution.doc_with_children); mergeddoc = docmerger.mergechilddoc(sdoc, oldrootdocwithchildren, sdocwithchildren); } else { mergeddoc = docmerger.merge(sdoc, oldrootdocwithchildren); } } cmd.solrdoc = mergeddoc; return true; } | yanivru/lucene-solr | [
1,
0,
0,
0
] |
9,374 | @Override
public void close() {
logger.info("CLOSE ZookeeperRiver");
// TODO Your code..
} | @Override
public void close() {
logger.info("CLOSE ZookeeperRiver");
} | @override public void close() { logger.info("close zookeeperriver"); } | xingxiudong/elasticsearch-zkdiscovery | [
0,
1,
0,
0
] |
9,375 | @Override
public void run() {
logger.info("START ZookeeperRiverLogic: " + client.toString());
// TODO Your code..
} | @Override
public void run() {
logger.info("START ZookeeperRiverLogic: " + client.toString());
} | @override public void run() { logger.info("start zookeeperriverlogic: " + client.tostring()); } | xingxiudong/elasticsearch-zkdiscovery | [
0,
1,
0,
0
] |
25,770 | public void testToInternal() throws Exception {
assertFormatParsed("1995-12-31T23:59:59.999", "1995-12-31T23:59:59.999666Z");
assertFormatParsed("1995-12-31T23:59:59.999", "1995-12-31T23:59:59.999Z");
assertFormatParsed("1995-12-31T23:59:59.99", "1995-12-31T23:59:59.99Z");
assertFormatParsed("1995-12-31T23:59:59.9", "1995-12-31T23:59:59.9Z");
assertFormatParsed("1995-12-31T23:59:59", "1995-12-31T23:59:59Z");
// here the input isn't in the canonical form, but we should be forgiving
assertFormatParsed("1995-12-31T23:59:59.99", "1995-12-31T23:59:59.990Z");
assertFormatParsed("1995-12-31T23:59:59.9", "1995-12-31T23:59:59.900Z");
assertFormatParsed("1995-12-31T23:59:59.9", "1995-12-31T23:59:59.90Z");
assertFormatParsed("1995-12-31T23:59:59", "1995-12-31T23:59:59.000Z");
assertFormatParsed("1995-12-31T23:59:59", "1995-12-31T23:59:59.00Z");
assertFormatParsed("1995-12-31T23:59:59", "1995-12-31T23:59:59.0Z");
// kind of kludgy, but we have other tests for the actual date math
assertFormatParsed(DateFormatUtil.formatDate(p.parseMath("/DAY")), "NOW/DAY");
// as of Solr 1.3
assertFormatParsed("1995-12-31T00:00:00", "1995-12-31T23:59:59Z/DAY");
assertFormatParsed("1995-12-31T00:00:00", "1995-12-31T23:59:59.123Z/DAY");
assertFormatParsed("1995-12-31T00:00:00", "1995-12-31T23:59:59.123999Z/DAY");
} | public void testToInternal() throws Exception {
assertFormatParsed("1995-12-31T23:59:59.999", "1995-12-31T23:59:59.999666Z");
assertFormatParsed("1995-12-31T23:59:59.999", "1995-12-31T23:59:59.999Z");
assertFormatParsed("1995-12-31T23:59:59.99", "1995-12-31T23:59:59.99Z");
assertFormatParsed("1995-12-31T23:59:59.9", "1995-12-31T23:59:59.9Z");
assertFormatParsed("1995-12-31T23:59:59", "1995-12-31T23:59:59Z");
assertFormatParsed("1995-12-31T23:59:59.99", "1995-12-31T23:59:59.990Z");
assertFormatParsed("1995-12-31T23:59:59.9", "1995-12-31T23:59:59.900Z");
assertFormatParsed("1995-12-31T23:59:59.9", "1995-12-31T23:59:59.90Z");
assertFormatParsed("1995-12-31T23:59:59", "1995-12-31T23:59:59.000Z");
assertFormatParsed("1995-12-31T23:59:59", "1995-12-31T23:59:59.00Z");
assertFormatParsed("1995-12-31T23:59:59", "1995-12-31T23:59:59.0Z");
assertFormatParsed(DateFormatUtil.formatDate(p.parseMath("/DAY")), "NOW/DAY");
assertFormatParsed("1995-12-31T00:00:00", "1995-12-31T23:59:59Z/DAY");
assertFormatParsed("1995-12-31T00:00:00", "1995-12-31T23:59:59.123Z/DAY");
assertFormatParsed("1995-12-31T00:00:00", "1995-12-31T23:59:59.123999Z/DAY");
} | public void testtointernal() throws exception { assertformatparsed("1995-12-31t23:59:59.999", "1995-12-31t23:59:59.999666z"); assertformatparsed("1995-12-31t23:59:59.999", "1995-12-31t23:59:59.999z"); assertformatparsed("1995-12-31t23:59:59.99", "1995-12-31t23:59:59.99z"); assertformatparsed("1995-12-31t23:59:59.9", "1995-12-31t23:59:59.9z"); assertformatparsed("1995-12-31t23:59:59", "1995-12-31t23:59:59z"); assertformatparsed("1995-12-31t23:59:59.99", "1995-12-31t23:59:59.990z"); assertformatparsed("1995-12-31t23:59:59.9", "1995-12-31t23:59:59.900z"); assertformatparsed("1995-12-31t23:59:59.9", "1995-12-31t23:59:59.90z"); assertformatparsed("1995-12-31t23:59:59", "1995-12-31t23:59:59.000z"); assertformatparsed("1995-12-31t23:59:59", "1995-12-31t23:59:59.00z"); assertformatparsed("1995-12-31t23:59:59", "1995-12-31t23:59:59.0z"); assertformatparsed(dateformatutil.formatdate(p.parsemath("/day")), "now/day"); assertformatparsed("1995-12-31t00:00:00", "1995-12-31t23:59:59z/day"); assertformatparsed("1995-12-31t00:00:00", "1995-12-31t23:59:59.123z/day"); assertformatparsed("1995-12-31t00:00:00", "1995-12-31t23:59:59.123999z/day"); } | yida-lxw/solr-5.3.1 | [
0,
0,
0,
1
] |
33,993 | private static void checkTypeCompatibility(
@NotNull ExpressionTypingContext context,
@Nullable JetType type,
@NotNull JetType subjectType,
@NotNull JetElement reportErrorOn
) {
// TODO : Take smart casts into account?
if (type == null) {
return;
}
if (isIntersectionEmpty(type, subjectType)) {
context.trace.report(INCOMPATIBLE_TYPES.on(reportErrorOn, type, subjectType));
return;
}
// check if the pattern is essentially a 'null' expression
if (KotlinBuiltIns.isNullableNothing(type) && !TypeUtils.isNullableType(subjectType)) {
context.trace.report(SENSELESS_NULL_IN_WHEN.on(reportErrorOn));
}
} | private static void checkTypeCompatibility(
@NotNull ExpressionTypingContext context,
@Nullable JetType type,
@NotNull JetType subjectType,
@NotNull JetElement reportErrorOn
) {
if (type == null) {
return;
}
if (isIntersectionEmpty(type, subjectType)) {
context.trace.report(INCOMPATIBLE_TYPES.on(reportErrorOn, type, subjectType));
return;
}
if (KotlinBuiltIns.isNullableNothing(type) && !TypeUtils.isNullableType(subjectType)) {
context.trace.report(SENSELESS_NULL_IN_WHEN.on(reportErrorOn));
}
} | private static void checktypecompatibility( @notnull expressiontypingcontext context, @nullable jettype type, @notnull jettype subjecttype, @notnull jetelement reporterroron ) { if (type == null) { return; } if (isintersectionempty(type, subjecttype)) { context.trace.report(incompatible_types.on(reporterroron, type, subjecttype)); return; } if (kotlinbuiltins.isnullablenothing(type) && !typeutils.isnullabletype(subjecttype)) { context.trace.report(senseless_null_in_when.on(reporterroron)); } } | zarechenskiy/kotlin | [
1,
0,
0,
0
] |
17,632 | private void readPreference(String file, AndroidView root, Integer preferenceId) {
Document doc;
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(file);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
Element rootElement = doc.getDocumentElement();
String rootTagName = rootElement.getTagName();
if (!(rootTagName.equals("PreferenceScreen")
|| rootTagName.equals("preference-headers")
|| rootTagName.equals("android.support.v7.preference.PreferenceScreen")
|| rootTagName.equals("android.support.v7.preference.preference-headers"))) {
return;
}
LinkedList<Pair<Node, AndroidView>> work = Lists.newLinkedList();
work.add(new Pair<>(rootElement, root));
while (!work.isEmpty()) {
Pair<Node, AndroidView> p = work.removeFirst();
Node node = p.getO1();
AndroidView view = p.getO2();
view.setOrigin(file);
NamedNodeMap attrMap = node.getAttributes();
if (attrMap == null) {
System.out.println(file + "!!!" + node.getClass() + "!!!"
+ node.toString() + "!!!" + node.getTextContent());
}
Node keyNode = attrMap.getNamedItem(KEY_ATTR);
if (keyNode != null) {
String key = keyNode.getTextContent();
view.addAttr(KEY_ATTR, key);
HashMap<Integer, String> maps = preferencesMap.get("preference-screen");
if (maps == null) {
maps = Maps.newHashMap();
}
maps.put(preferenceId, FilenameUtils.removeExtension(new File(file).getName()));
preferencesMap.put("preference-screen", maps);
Set<String> preferenceKeys = preferenceKeyMaps.get(preferenceId);
if (preferenceKeys == null) {
preferenceKeys = new HashSet<>();
preferenceKeyMaps.put(preferenceId, preferenceKeys);
}
preferenceKeys.add(key);
}
Node fragmentNode = attrMap.getNamedItem(FRAGMENT_ATTR);
if (fragmentNode != null) {
view.addAttr(FRAGMENT_ATTR, fragmentNode.getTextContent());
HashMap<Integer, String> maps = preferencesMap.get("preference-header");
if (maps == null) {
maps = Maps.newHashMap();
}
maps.put(preferenceId, FilenameUtils.removeExtension(new File(file).getName()));
preferencesMap.put("preference-header", maps);
}
int guiId = -1;
// Retrieve view type
String guiName = node.getNodeName();
String title = readAndroidTextOrTitle(attrMap, "title");
String summary = readAndroidTextOrTitle(attrMap, "summary");
String tooltip = readAndroidTextOrTitle(attrMap, "tooltipText");
String contentDescription = readAndroidTextOrTitle(attrMap, "contentDescription");
String images = readAndroidImageResource(attrMap);
view.save(guiId, title, summary, tooltip, contentDescription, images, guiName);
//view.save(guiId, title, "", guiName);
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node newNode = children.item(i);
String nodeName = newNode.getNodeName();
if ("#comment".equals(nodeName)) {
continue;
}
if ("#text".equals(nodeName)) {
// possible for XML files created on a different operating system
// than the one our analysis is run on
continue;
}
AndroidView newView = new AndroidView();
// FIXME: we assume that every node has attributes, may be wrong
if (!newNode.hasAttributes()) {
Logger.verb("WARNING", "xml node " + newNode + " has no attributes");
// Fixed: this is wrong for the case group item -> menu -> item
//continue;
} else {
NamedNodeMap attrs = newNode.getAttributes();
for (int idx = 0; idx < attrs.getLength(); idx += 1) {
Node attr = attrs.item(idx);
String name = attr.getNodeName();
String value = attr.getNodeValue();
newView.addAttr(name, value);
}
}
newView.setParent(view);
work.add(new Pair<>(newNode, newView));
}
}
} | private void readPreference(String file, AndroidView root, Integer preferenceId) {
Document doc;
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(file);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
Element rootElement = doc.getDocumentElement();
String rootTagName = rootElement.getTagName();
if (!(rootTagName.equals("PreferenceScreen")
|| rootTagName.equals("preference-headers")
|| rootTagName.equals("android.support.v7.preference.PreferenceScreen")
|| rootTagName.equals("android.support.v7.preference.preference-headers"))) {
return;
}
LinkedList<Pair<Node, AndroidView>> work = Lists.newLinkedList();
work.add(new Pair<>(rootElement, root));
while (!work.isEmpty()) {
Pair<Node, AndroidView> p = work.removeFirst();
Node node = p.getO1();
AndroidView view = p.getO2();
view.setOrigin(file);
NamedNodeMap attrMap = node.getAttributes();
if (attrMap == null) {
System.out.println(file + "!!!" + node.getClass() + "!!!"
+ node.toString() + "!!!" + node.getTextContent());
}
Node keyNode = attrMap.getNamedItem(KEY_ATTR);
if (keyNode != null) {
String key = keyNode.getTextContent();
view.addAttr(KEY_ATTR, key);
HashMap<Integer, String> maps = preferencesMap.get("preference-screen");
if (maps == null) {
maps = Maps.newHashMap();
}
maps.put(preferenceId, FilenameUtils.removeExtension(new File(file).getName()));
preferencesMap.put("preference-screen", maps);
Set<String> preferenceKeys = preferenceKeyMaps.get(preferenceId);
if (preferenceKeys == null) {
preferenceKeys = new HashSet<>();
preferenceKeyMaps.put(preferenceId, preferenceKeys);
}
preferenceKeys.add(key);
}
Node fragmentNode = attrMap.getNamedItem(FRAGMENT_ATTR);
if (fragmentNode != null) {
view.addAttr(FRAGMENT_ATTR, fragmentNode.getTextContent());
HashMap<Integer, String> maps = preferencesMap.get("preference-header");
if (maps == null) {
maps = Maps.newHashMap();
}
maps.put(preferenceId, FilenameUtils.removeExtension(new File(file).getName()));
preferencesMap.put("preference-header", maps);
}
int guiId = -1;
String guiName = node.getNodeName();
String title = readAndroidTextOrTitle(attrMap, "title");
String summary = readAndroidTextOrTitle(attrMap, "summary");
String tooltip = readAndroidTextOrTitle(attrMap, "tooltipText");
String contentDescription = readAndroidTextOrTitle(attrMap, "contentDescription");
String images = readAndroidImageResource(attrMap);
view.save(guiId, title, summary, tooltip, contentDescription, images, guiName);
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node newNode = children.item(i);
String nodeName = newNode.getNodeName();
if ("#comment".equals(nodeName)) {
continue;
}
if ("#text".equals(nodeName)) {
continue;
}
AndroidView newView = new AndroidView();
if (!newNode.hasAttributes()) {
Logger.verb("WARNING", "xml node " + newNode + " has no attributes");
} else {
NamedNodeMap attrs = newNode.getAttributes();
for (int idx = 0; idx < attrs.getLength(); idx += 1) {
Node attr = attrs.item(idx);
String name = attr.getNodeName();
String value = attr.getNodeValue();
newView.addAttr(name, value);
}
}
newView.setParent(view);
work.add(new Pair<>(newNode, newView));
}
}
} | private void readpreference(string file, androidview root, integer preferenceid) { document doc; try { documentbuilderfactory dbfactory = documentbuilderfactory.newinstance(); documentbuilder dbuilder = dbfactory.newdocumentbuilder(); doc = dbuilder.parse(file); } catch (exception ex) { throw new runtimeexception(ex); } element rootelement = doc.getdocumentelement(); string roottagname = rootelement.gettagname(); if (!(roottagname.equals("preferencescreen") || roottagname.equals("preference-headers") || roottagname.equals("android.support.v7.preference.preferencescreen") || roottagname.equals("android.support.v7.preference.preference-headers"))) { return; } linkedlist<pair<node, androidview>> work = lists.newlinkedlist(); work.add(new pair<>(rootelement, root)); while (!work.isempty()) { pair<node, androidview> p = work.removefirst(); node node = p.geto1(); androidview view = p.geto2(); view.setorigin(file); namednodemap attrmap = node.getattributes(); if (attrmap == null) { system.out.println(file + "!!!" + node.getclass() + "!!!" + node.tostring() + "!!!" + node.gettextcontent()); } node keynode = attrmap.getnameditem(key_attr); if (keynode != null) { string key = keynode.gettextcontent(); view.addattr(key_attr, key); hashmap<integer, string> maps = preferencesmap.get("preference-screen"); if (maps == null) { maps = maps.newhashmap(); } maps.put(preferenceid, filenameutils.removeextension(new file(file).getname())); preferencesmap.put("preference-screen", maps); set<string> preferencekeys = preferencekeymaps.get(preferenceid); if (preferencekeys == null) { preferencekeys = new hashset<>(); preferencekeymaps.put(preferenceid, preferencekeys); } preferencekeys.add(key); } node fragmentnode = attrmap.getnameditem(fragment_attr); if (fragmentnode != null) { view.addattr(fragment_attr, fragmentnode.gettextcontent()); hashmap<integer, string> maps = preferencesmap.get("preference-header"); if (maps == null) { maps = maps.newhashmap(); } maps.put(preferenceid, filenameutils.removeextension(new file(file).getname())); preferencesmap.put("preference-header", maps); } int guiid = -1; string guiname = node.getnodename(); string title = readandroidtextortitle(attrmap, "title"); string summary = readandroidtextortitle(attrmap, "summary"); string tooltip = readandroidtextortitle(attrmap, "tooltiptext"); string contentdescription = readandroidtextortitle(attrmap, "contentdescription"); string images = readandroidimageresource(attrmap); view.save(guiid, title, summary, tooltip, contentdescription, images, guiname); nodelist children = node.getchildnodes(); for (int i = 0; i < children.getlength(); i++) { node newnode = children.item(i); string nodename = newnode.getnodename(); if ("#comment".equals(nodename)) { continue; } if ("#text".equals(nodename)) { continue; } androidview newview = new androidview(); if (!newnode.hasattributes()) { logger.verb("warning", "xml node " + newnode + " has no attributes"); } else { namednodemap attrs = newnode.getattributes(); for (int idx = 0; idx < attrs.getlength(); idx += 1) { node attr = attrs.item(idx); string name = attr.getnodename(); string value = attr.getnodevalue(); newview.addattr(name, value); } } newview.setparent(view); work.add(new pair<>(newnode, newview)); } } } | ttincs/guibat | [
0,
0,
1,
0
] |
17,634 | private void resolveIncludes(String resRoot, HashMap<Integer, String> nameMap,
HashMap<Integer, AndroidView> viewMap, boolean isSys) {
HashMap<String, AndroidView> name2View = Maps.newHashMap();
for (Map.Entry<Integer, String> entry : nameMap.entrySet()) {
String name = entry.getValue();
AndroidView view = viewMap.get(entry.getKey());
name2View.put(name, view);
}
// boolean isSys = (viewMap == sysId2View);
LinkedList<AndroidView> work = Lists.newLinkedList();
work.addAll(viewMap.values());
while (!work.isEmpty()) {
AndroidView view = work.remove();
for (int i = 0; i < view.getNumberOfChildren(); i++) {
IAndroidView child = view.getChildInternal(i);
if (child instanceof AndroidView) {
work.add((AndroidView) child);
continue;
}
IncludeAndroidView iav = (IncludeAndroidView) child;
String layoutId = iav.layoutId;
AndroidView tgt = name2View.get(layoutId);
if (tgt != null) {
tgt = (AndroidView) tgt.deepCopy();
tgt.setParent(view, i);
} else if (getLayoutFilePath(resRoot, layoutId, isSys) != null) {
// not exist, let's get it on-demand
String file = getLayoutFilePath(resRoot, layoutId, isSys);
tgt = new AndroidView();
tgt.setParent(view, i);
tgt.setOrigin(file);
readLayout(file, tgt, isSys);
int newId = nonRId--;
viewMap.put(newId, tgt);
nameMap.put(newId, layoutId);
} else if (sysRGeneralIdMap.get("layout").containsKey(layoutId) && sysId2View.containsKey
(sysRGeneralIdMap.get("layout").get(layoutId)
)) {
// <include> is used with an in built android layout id
tgt = (AndroidView) sysId2View.get(sysRGeneralIdMap.get("layout").get(layoutId)).deepCopy();
tgt.setParent(view, i);
} else {
Logger.warn(this.getClass().getSimpleName(), "Unknown layout " + layoutId
+ " included by " + view.getOrigin());
continue;
}
Integer includeeId = iav.includeeId;
if (includeeId != null) {
tgt.setId(includeeId.intValue());
}
work.add(tgt);
}
}
} | private void resolveIncludes(String resRoot, HashMap<Integer, String> nameMap,
HashMap<Integer, AndroidView> viewMap, boolean isSys) {
HashMap<String, AndroidView> name2View = Maps.newHashMap();
for (Map.Entry<Integer, String> entry : nameMap.entrySet()) {
String name = entry.getValue();
AndroidView view = viewMap.get(entry.getKey());
name2View.put(name, view);
}
LinkedList<AndroidView> work = Lists.newLinkedList();
work.addAll(viewMap.values());
while (!work.isEmpty()) {
AndroidView view = work.remove();
for (int i = 0; i < view.getNumberOfChildren(); i++) {
IAndroidView child = view.getChildInternal(i);
if (child instanceof AndroidView) {
work.add((AndroidView) child);
continue;
}
IncludeAndroidView iav = (IncludeAndroidView) child;
String layoutId = iav.layoutId;
AndroidView tgt = name2View.get(layoutId);
if (tgt != null) {
tgt = (AndroidView) tgt.deepCopy();
tgt.setParent(view, i);
} else if (getLayoutFilePath(resRoot, layoutId, isSys) != null) {
String file = getLayoutFilePath(resRoot, layoutId, isSys);
tgt = new AndroidView();
tgt.setParent(view, i);
tgt.setOrigin(file);
readLayout(file, tgt, isSys);
int newId = nonRId--;
viewMap.put(newId, tgt);
nameMap.put(newId, layoutId);
} else if (sysRGeneralIdMap.get("layout").containsKey(layoutId) && sysId2View.containsKey
(sysRGeneralIdMap.get("layout").get(layoutId)
)) {
tgt = (AndroidView) sysId2View.get(sysRGeneralIdMap.get("layout").get(layoutId)).deepCopy();
tgt.setParent(view, i);
} else {
Logger.warn(this.getClass().getSimpleName(), "Unknown layout " + layoutId
+ " included by " + view.getOrigin());
continue;
}
Integer includeeId = iav.includeeId;
if (includeeId != null) {
tgt.setId(includeeId.intValue());
}
work.add(tgt);
}
}
} | private void resolveincludes(string resroot, hashmap<integer, string> namemap, hashmap<integer, androidview> viewmap, boolean issys) { hashmap<string, androidview> name2view = maps.newhashmap(); for (map.entry<integer, string> entry : namemap.entryset()) { string name = entry.getvalue(); androidview view = viewmap.get(entry.getkey()); name2view.put(name, view); } linkedlist<androidview> work = lists.newlinkedlist(); work.addall(viewmap.values()); while (!work.isempty()) { androidview view = work.remove(); for (int i = 0; i < view.getnumberofchildren(); i++) { iandroidview child = view.getchildinternal(i); if (child instanceof androidview) { work.add((androidview) child); continue; } includeandroidview iav = (includeandroidview) child; string layoutid = iav.layoutid; androidview tgt = name2view.get(layoutid); if (tgt != null) { tgt = (androidview) tgt.deepcopy(); tgt.setparent(view, i); } else if (getlayoutfilepath(resroot, layoutid, issys) != null) { string file = getlayoutfilepath(resroot, layoutid, issys); tgt = new androidview(); tgt.setparent(view, i); tgt.setorigin(file); readlayout(file, tgt, issys); int newid = nonrid--; viewmap.put(newid, tgt); namemap.put(newid, layoutid); } else if (sysrgeneralidmap.get("layout").containskey(layoutid) && sysid2view.containskey (sysrgeneralidmap.get("layout").get(layoutid) )) { tgt = (androidview) sysid2view.get(sysrgeneralidmap.get("layout").get(layoutid)).deepcopy(); tgt.setparent(view, i); } else { logger.warn(this.getclass().getsimplename(), "unknown layout " + layoutid + " included by " + view.getorigin()); continue; } integer includeeid = iav.includeeid; if (includeeid != null) { tgt.setid(includeeid.intvalue()); } work.add(tgt); } } } | ttincs/guibat | [
1,
0,
0,
0
] |
17,635 | private void readLayout(String file, AndroidView root, boolean isSys) {
Document doc;
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(file);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
Element rootElement = doc.getDocumentElement();
// In older versions, Preference could be put in layout folder and we do
// not support Prefernce yet.
if (rootElement.getTagName().equals("PreferenceScreen")) {
return;
}
LinkedList<Pair<Node, AndroidView>> work = Lists.newLinkedList();
work.add(new Pair<Node, AndroidView>(rootElement, root));
while (!work.isEmpty()) {
Pair<Node, AndroidView> p = work.removeFirst();
Node node = p.getO1();
AndroidView view = p.getO2();
view.setOrigin(file);
NamedNodeMap attrMap = node.getAttributes();
if (attrMap == null) {
Logger.verb(this.getClass().getSimpleName(), file + "!!!" + node.getClass() + "!!!"
+ node.toString() + "!!!" + node.getTextContent());
}
// Retrieve view id (android:id)
//Node idNode = attrMap.getNamedItem(ID_ATTR);
Node idNode = attrMap.getNamedItemNS(ANDROID_NS, "id");
int guiId = -1;
String id = null;
if (idNode != null) {
String txt = idNode.getTextContent();
Pair<String, Integer> pair = parseAndroidId(txt, isSys);
id = pair.getO1();
Integer guiIdObj = pair.getO2();
if (guiIdObj == null) {
if (!isSys) {
Logger.warn(this.getClass().getSimpleName(),
"unresolved android:id " + id + " in "
+ file);
}
} else {
guiId = guiIdObj.intValue();
if (lookupNameInGeneralMap("id", guiId, isSys) == null) {
extraId2ViewMap.put(guiIdObj, view);
}
}
}
// Retrieve view type
String guiName = node.getNodeName();
if ("view".equals(guiName)) {
// view without class attribute.
// It does happen.
if (attrMap.getNamedItem("class") == null)
continue;
guiName = attrMap.getNamedItem("class").getTextContent();
} else if (guiName.equals("MenuItemView")) {
// FIXME(tony): this is an "approximation".
guiName = "android.view.MenuItem";
}
if (debug) {
Logger.verb(this.getClass().getSimpleName(), guiName + " (" + guiId + ", " + id + ")");
}
//Retrieve callback (android:onClick)
String callback = readAndroidCallback(attrMap, "onClick");
if (callback != null) {
view.setInlineClickHandler(callback);
}
// Retrieve text (android:text)
String text = readAndroidTextOrTitle(attrMap, "text");
// hailong: add hint support
// Retrieve hint (android:hint)
String hint = readAndroidTextOrTitle(attrMap, "hint");
String autofillHints = readAndroidTextOrTitle(attrMap, "autofillHints");
if (hint != null && autofillHints != null) hint += PropertyManager.SEPARATOR + autofillHints;
else if (autofillHints != null) hint = autofillHints;
if(attrMap.getNamedItem("app:menu") != null){
String menuName = attrMap.getNamedItem("app:menu").getTextContent();
if (menuName != null) {
Pair<String, Integer> pair = parseAndroidId(menuName, isSys);
Integer menuId = pair.getO2();
if (menuId != null) {
view.addAttr(AndroidView.Type.APP_MENU, String.valueOf(menuId));
menuId2View.put(menuId, view);
}
}
if (attrMap.getNamedItem("app:headerLayout") != null) {
String headerName = attrMap.getNamedItem("app:headerLayout").getTextContent();
if (headerName != null) {
Pair<String, Integer> pair = parseAndroidId(headerName, isSys);
Integer headerId = pair.getO2();
if (headerId != null) {
view.addAttr(AndroidView.Type.APP_HEADER_LAYOUT, String.valueOf(headerId));
menuHeaderId2View.put(headerId, view);
}
}
}
}
if ("fragment".equals(guiName)) {
Node fragmentNodeAttr = attrMap.getNamedItem("android:name");
if (fragmentNodeAttr != null) {
String fragmentClass = fragmentNodeAttr.getTextContent();
if (fragmentClass.isEmpty()) {
fragmentNodeAttr = attrMap.getNamedItem("class");
if (fragmentNodeAttr != null) {
fragmentClass = fragmentNodeAttr.getTextContent();
}
}
view.addAttr(AndroidView.Type.ANDROID_NAME, fragmentClass);
}
}
String tooltip = readAndroidTextOrTitle(attrMap, "tooltipText");
String contentDescription = readAndroidTextOrTitle(attrMap, "contentDescription");
if (hint != null && autofillHints != null) hint += PropertyManager.SEPARATOR + autofillHints;
else if (autofillHints != null) hint = autofillHints;
String images = readAndroidImageResource(attrMap);
view.save(guiId, text, hint, tooltip, contentDescription, images, guiName);
//view.save(guiId, text, hint, guiName);
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node newNode = children.item(i);
String nodeName = newNode.getNodeName();
if ("#comment".equals(nodeName)) {
continue;
}
if ("#text".equals(nodeName)) {
// possible for XML files created on a different operating system
// than the one our analysis is run on
continue;
}
if (nodeName.equals("requestFocus")) {
continue;
}
if (!newNode.hasAttributes() && !"TableRow".equals(nodeName)
&& !"View".equals(nodeName)) {
Logger.warn(this.getClass().getSimpleName(),
"no attribute node "
+ newNode.getNodeName());
continue;
}
if (newNode.getNodeName().equals("include")) {
attrMap = newNode.getAttributes();
if (attrMap.getNamedItem("layout") == null) {
Logger.warn("XML", "layout not exist in include");
for (int j = 0; j < attrMap.getLength(); j++) {
Logger.trace("XML", attrMap.item(j).getNodeName());
}
Logger.trace("XML", "filename" + file);
continue;
}
String layoutTxt = attrMap.getNamedItem("layout").getTextContent();
String layoutId = null;
if (layoutTxt.startsWith("@layout/")) {
layoutId = layoutTxt.substring("@layout/".length());
} else if (layoutTxt.startsWith("@android:layout/")) {
layoutId = layoutTxt.substring("@android:layout/".length());
} else if (layoutTxt.matches("@\\*android:layout\\/(\\w)+")) {
layoutId = layoutTxt.substring("@*android:layout/".length());
} else {
throw new RuntimeException("[WARNING] Unhandled layout id "
+ layoutTxt + "," + file);
}
Integer includeeId = null;
id = null;
idNode = attrMap.getNamedItemNS(ANDROID_NS, "id");
if (idNode != null) {
String txt = idNode.getTextContent();
Pair<String, Integer> pair = parseAndroidId(txt, isSys);
id = pair.getO1();
Integer guiIdObj = pair.getO2();
if (guiIdObj == null) {
if (!isSys) {
Logger.warn(this.getClass().getSimpleName(),
"unresolved android:id " + id
+ " in " + file);
}
} else {
includeeId = guiIdObj;
}
}
// view.saveInclude(layoutId, includeeId);
IncludeAndroidView iav = new IncludeAndroidView(layoutId, includeeId);
iav.setParent(view);
} else {
AndroidView newView = new AndroidView();
newView.setParent(view);
work.add(new Pair<Node, AndroidView>(newNode, newView));
}
}
}
} | private void readLayout(String file, AndroidView root, boolean isSys) {
Document doc;
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(file);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
Element rootElement = doc.getDocumentElement();
if (rootElement.getTagName().equals("PreferenceScreen")) {
return;
}
LinkedList<Pair<Node, AndroidView>> work = Lists.newLinkedList();
work.add(new Pair<Node, AndroidView>(rootElement, root));
while (!work.isEmpty()) {
Pair<Node, AndroidView> p = work.removeFirst();
Node node = p.getO1();
AndroidView view = p.getO2();
view.setOrigin(file);
NamedNodeMap attrMap = node.getAttributes();
if (attrMap == null) {
Logger.verb(this.getClass().getSimpleName(), file + "!!!" + node.getClass() + "!!!"
+ node.toString() + "!!!" + node.getTextContent());
}
Node idNode = attrMap.getNamedItemNS(ANDROID_NS, "id");
int guiId = -1;
String id = null;
if (idNode != null) {
String txt = idNode.getTextContent();
Pair<String, Integer> pair = parseAndroidId(txt, isSys);
id = pair.getO1();
Integer guiIdObj = pair.getO2();
if (guiIdObj == null) {
if (!isSys) {
Logger.warn(this.getClass().getSimpleName(),
"unresolved android:id " + id + " in "
+ file);
}
} else {
guiId = guiIdObj.intValue();
if (lookupNameInGeneralMap("id", guiId, isSys) == null) {
extraId2ViewMap.put(guiIdObj, view);
}
}
}
String guiName = node.getNodeName();
if ("view".equals(guiName)) {
if (attrMap.getNamedItem("class") == null)
continue;
guiName = attrMap.getNamedItem("class").getTextContent();
} else if (guiName.equals("MenuItemView")) {
guiName = "android.view.MenuItem";
}
if (debug) {
Logger.verb(this.getClass().getSimpleName(), guiName + " (" + guiId + ", " + id + ")");
}
String callback = readAndroidCallback(attrMap, "onClick");
if (callback != null) {
view.setInlineClickHandler(callback);
}
String text = readAndroidTextOrTitle(attrMap, "text");
String hint = readAndroidTextOrTitle(attrMap, "hint");
String autofillHints = readAndroidTextOrTitle(attrMap, "autofillHints");
if (hint != null && autofillHints != null) hint += PropertyManager.SEPARATOR + autofillHints;
else if (autofillHints != null) hint = autofillHints;
if(attrMap.getNamedItem("app:menu") != null){
String menuName = attrMap.getNamedItem("app:menu").getTextContent();
if (menuName != null) {
Pair<String, Integer> pair = parseAndroidId(menuName, isSys);
Integer menuId = pair.getO2();
if (menuId != null) {
view.addAttr(AndroidView.Type.APP_MENU, String.valueOf(menuId));
menuId2View.put(menuId, view);
}
}
if (attrMap.getNamedItem("app:headerLayout") != null) {
String headerName = attrMap.getNamedItem("app:headerLayout").getTextContent();
if (headerName != null) {
Pair<String, Integer> pair = parseAndroidId(headerName, isSys);
Integer headerId = pair.getO2();
if (headerId != null) {
view.addAttr(AndroidView.Type.APP_HEADER_LAYOUT, String.valueOf(headerId));
menuHeaderId2View.put(headerId, view);
}
}
}
}
if ("fragment".equals(guiName)) {
Node fragmentNodeAttr = attrMap.getNamedItem("android:name");
if (fragmentNodeAttr != null) {
String fragmentClass = fragmentNodeAttr.getTextContent();
if (fragmentClass.isEmpty()) {
fragmentNodeAttr = attrMap.getNamedItem("class");
if (fragmentNodeAttr != null) {
fragmentClass = fragmentNodeAttr.getTextContent();
}
}
view.addAttr(AndroidView.Type.ANDROID_NAME, fragmentClass);
}
}
String tooltip = readAndroidTextOrTitle(attrMap, "tooltipText");
String contentDescription = readAndroidTextOrTitle(attrMap, "contentDescription");
if (hint != null && autofillHints != null) hint += PropertyManager.SEPARATOR + autofillHints;
else if (autofillHints != null) hint = autofillHints;
String images = readAndroidImageResource(attrMap);
view.save(guiId, text, hint, tooltip, contentDescription, images, guiName);
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node newNode = children.item(i);
String nodeName = newNode.getNodeName();
if ("#comment".equals(nodeName)) {
continue;
}
if ("#text".equals(nodeName)) {
continue;
}
if (nodeName.equals("requestFocus")) {
continue;
}
if (!newNode.hasAttributes() && !"TableRow".equals(nodeName)
&& !"View".equals(nodeName)) {
Logger.warn(this.getClass().getSimpleName(),
"no attribute node "
+ newNode.getNodeName());
continue;
}
if (newNode.getNodeName().equals("include")) {
attrMap = newNode.getAttributes();
if (attrMap.getNamedItem("layout") == null) {
Logger.warn("XML", "layout not exist in include");
for (int j = 0; j < attrMap.getLength(); j++) {
Logger.trace("XML", attrMap.item(j).getNodeName());
}
Logger.trace("XML", "filename" + file);
continue;
}
String layoutTxt = attrMap.getNamedItem("layout").getTextContent();
String layoutId = null;
if (layoutTxt.startsWith("@layout/")) {
layoutId = layoutTxt.substring("@layout/".length());
} else if (layoutTxt.startsWith("@android:layout/")) {
layoutId = layoutTxt.substring("@android:layout/".length());
} else if (layoutTxt.matches("@\\*android:layout\\/(\\w)+")) {
layoutId = layoutTxt.substring("@*android:layout/".length());
} else {
throw new RuntimeException("[WARNING] Unhandled layout id "
+ layoutTxt + "," + file);
}
Integer includeeId = null;
id = null;
idNode = attrMap.getNamedItemNS(ANDROID_NS, "id");
if (idNode != null) {
String txt = idNode.getTextContent();
Pair<String, Integer> pair = parseAndroidId(txt, isSys);
id = pair.getO1();
Integer guiIdObj = pair.getO2();
if (guiIdObj == null) {
if (!isSys) {
Logger.warn(this.getClass().getSimpleName(),
"unresolved android:id " + id
+ " in " + file);
}
} else {
includeeId = guiIdObj;
}
}
IncludeAndroidView iav = new IncludeAndroidView(layoutId, includeeId);
iav.setParent(view);
} else {
AndroidView newView = new AndroidView();
newView.setParent(view);
work.add(new Pair<Node, AndroidView>(newNode, newView));
}
}
}
} | private void readlayout(string file, androidview root, boolean issys) { document doc; try { documentbuilderfactory dbfactory = documentbuilderfactory.newinstance(); dbfactory.setnamespaceaware(true); documentbuilder dbuilder = dbfactory.newdocumentbuilder(); doc = dbuilder.parse(file); } catch (exception ex) { throw new runtimeexception(ex); } element rootelement = doc.getdocumentelement(); if (rootelement.gettagname().equals("preferencescreen")) { return; } linkedlist<pair<node, androidview>> work = lists.newlinkedlist(); work.add(new pair<node, androidview>(rootelement, root)); while (!work.isempty()) { pair<node, androidview> p = work.removefirst(); node node = p.geto1(); androidview view = p.geto2(); view.setorigin(file); namednodemap attrmap = node.getattributes(); if (attrmap == null) { logger.verb(this.getclass().getsimplename(), file + "!!!" + node.getclass() + "!!!" + node.tostring() + "!!!" + node.gettextcontent()); } node idnode = attrmap.getnameditemns(android_ns, "id"); int guiid = -1; string id = null; if (idnode != null) { string txt = idnode.gettextcontent(); pair<string, integer> pair = parseandroidid(txt, issys); id = pair.geto1(); integer guiidobj = pair.geto2(); if (guiidobj == null) { if (!issys) { logger.warn(this.getclass().getsimplename(), "unresolved android:id " + id + " in " + file); } } else { guiid = guiidobj.intvalue(); if (lookupnameingeneralmap("id", guiid, issys) == null) { extraid2viewmap.put(guiidobj, view); } } } string guiname = node.getnodename(); if ("view".equals(guiname)) { if (attrmap.getnameditem("class") == null) continue; guiname = attrmap.getnameditem("class").gettextcontent(); } else if (guiname.equals("menuitemview")) { guiname = "android.view.menuitem"; } if (debug) { logger.verb(this.getclass().getsimplename(), guiname + " (" + guiid + ", " + id + ")"); } string callback = readandroidcallback(attrmap, "onclick"); if (callback != null) { view.setinlineclickhandler(callback); } string text = readandroidtextortitle(attrmap, "text"); string hint = readandroidtextortitle(attrmap, "hint"); string autofillhints = readandroidtextortitle(attrmap, "autofillhints"); if (hint != null && autofillhints != null) hint += propertymanager.separator + autofillhints; else if (autofillhints != null) hint = autofillhints; if(attrmap.getnameditem("app:menu") != null){ string menuname = attrmap.getnameditem("app:menu").gettextcontent(); if (menuname != null) { pair<string, integer> pair = parseandroidid(menuname, issys); integer menuid = pair.geto2(); if (menuid != null) { view.addattr(androidview.type.app_menu, string.valueof(menuid)); menuid2view.put(menuid, view); } } if (attrmap.getnameditem("app:headerlayout") != null) { string headername = attrmap.getnameditem("app:headerlayout").gettextcontent(); if (headername != null) { pair<string, integer> pair = parseandroidid(headername, issys); integer headerid = pair.geto2(); if (headerid != null) { view.addattr(androidview.type.app_header_layout, string.valueof(headerid)); menuheaderid2view.put(headerid, view); } } } } if ("fragment".equals(guiname)) { node fragmentnodeattr = attrmap.getnameditem("android:name"); if (fragmentnodeattr != null) { string fragmentclass = fragmentnodeattr.gettextcontent(); if (fragmentclass.isempty()) { fragmentnodeattr = attrmap.getnameditem("class"); if (fragmentnodeattr != null) { fragmentclass = fragmentnodeattr.gettextcontent(); } } view.addattr(androidview.type.android_name, fragmentclass); } } string tooltip = readandroidtextortitle(attrmap, "tooltiptext"); string contentdescription = readandroidtextortitle(attrmap, "contentdescription"); if (hint != null && autofillhints != null) hint += propertymanager.separator + autofillhints; else if (autofillhints != null) hint = autofillhints; string images = readandroidimageresource(attrmap); view.save(guiid, text, hint, tooltip, contentdescription, images, guiname); nodelist children = node.getchildnodes(); for (int i = 0; i < children.getlength(); i++) { node newnode = children.item(i); string nodename = newnode.getnodename(); if ("#comment".equals(nodename)) { continue; } if ("#text".equals(nodename)) { continue; } if (nodename.equals("requestfocus")) { continue; } if (!newnode.hasattributes() && !"tablerow".equals(nodename) && !"view".equals(nodename)) { logger.warn(this.getclass().getsimplename(), "no attribute node " + newnode.getnodename()); continue; } if (newnode.getnodename().equals("include")) { attrmap = newnode.getattributes(); if (attrmap.getnameditem("layout") == null) { logger.warn("xml", "layout not exist in include"); for (int j = 0; j < attrmap.getlength(); j++) { logger.trace("xml", attrmap.item(j).getnodename()); } logger.trace("xml", "filename" + file); continue; } string layouttxt = attrmap.getnameditem("layout").gettextcontent(); string layoutid = null; if (layouttxt.startswith("@layout/")) { layoutid = layouttxt.substring("@layout/".length()); } else if (layouttxt.startswith("@android:layout/")) { layoutid = layouttxt.substring("@android:layout/".length()); } else if (layouttxt.matches("@\\*android:layout\\/(\\w)+")) { layoutid = layouttxt.substring("@*android:layout/".length()); } else { throw new runtimeexception("[warning] unhandled layout id " + layouttxt + "," + file); } integer includeeid = null; id = null; idnode = attrmap.getnameditemns(android_ns, "id"); if (idnode != null) { string txt = idnode.gettextcontent(); pair<string, integer> pair = parseandroidid(txt, issys); id = pair.geto1(); integer guiidobj = pair.geto2(); if (guiidobj == null) { if (!issys) { logger.warn(this.getclass().getsimplename(), "unresolved android:id " + id + " in " + file); } } else { includeeid = guiidobj; } } includeandroidview iav = new includeandroidview(layoutid, includeeid); iav.setparent(view); } else { androidview newview = new androidview(); newview.setparent(view); work.add(new pair<node, androidview>(newnode, newview)); } } } } | ttincs/guibat | [
1,
0,
1,
0
] |
17,637 | private void readMenu(String file, AndroidView root, boolean isSys) {
Document doc;
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(file);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
LinkedList<Pair<Node, AndroidView>> worklist = Lists.newLinkedList();
worklist.add(new Pair<Node, AndroidView>(doc.getDocumentElement(), root));
root = null;
while (!worklist.isEmpty()) {
Pair<Node, AndroidView> pair = worklist.remove();
Node node = pair.getO1();
AndroidView view = pair.getO2();
NamedNodeMap attrMap = node.getAttributes();
Node idNode = attrMap.getNamedItemNS(ANDROID_NS, "id");
int guiId = -1;
String id = null;
if (idNode != null) {
String txt = idNode.getTextContent();
Pair<String, Integer> p = parseAndroidId(txt, isSys);
id = p.getO1();
Integer guiIdObj = p.getO2();
if (guiIdObj == null) {
if (!isSys) {
Logger.warn(this.getClass().getSimpleName(),
"unresolved android:id " + id + " in "
+ file);
}
guiId = nonRId--; // negative value to indicate it is a unique id but
// we don't know its value
feedIdIntoGeneralMap("id", id, guiId, isSys);
// if (isSys) {
// sysRIdMap.put(id, guiId);
// invSysRIdMap.put(guiId, id);
// } else {
// rIdMap.put(id, guiId);
// invRIdMap.put(guiId, id);
// }
} else {
guiId = guiIdObj.intValue();
}
}
// FIXME(tony): this is an "approximation"
String guiName = node.getNodeName();
if (guiName.equals("menu")) {
guiName = "android.view.Menu";
} else if (guiName.equals("item")) {
guiName = "android.view.MenuItem";
NodeList childNodes = node.getChildNodes();
if(childNodes!=null) {
for (int i = 0; i < childNodes.getLength(); i++) {
Node newNode = childNodes.item(i);
String nodeName = newNode.getNodeName();
if("menu".equals(nodeName)) {
guiName = "android.view.ViewGroup";
}
}
}
} else if (guiName.equals("group")) {
// TODO(tony): we might want to create a special fake class to
// represent menu groups. But for now, let's simply pretend it's
// a ViewGroup. Also, print a warning when we do see <group>
Logger.trace(this.getClass().getSimpleName(), "[TODO] <group> used in " + file);
guiName = "android.view.ViewGroup";
} else {
Logger.trace("XML", "Unhandled menu tag " + guiName);
//throw new RuntimeException("Unhandled menu tag " + guiName);
}
if (debug) {
Logger.verb(this.getClass().getSimpleName(), guiName + " (" + guiId + ", " + id + ")");
}
String text = readAndroidTextOrTitle(attrMap, "title");
// hailong: add hint support
String hint = readAndroidTextOrTitle(attrMap, "hint");
String autofillHints = readAndroidTextOrTitle(attrMap, "autofillHints");
if (hint != null && autofillHints != null) hint += PropertyManager.SEPARATOR + autofillHints;
else if (autofillHints != null) hint = autofillHints;
String tooltip = readAndroidTextOrTitle(attrMap, "tooltipText");
String contentDescription = readAndroidTextOrTitle(attrMap, "contentDescription");
if (hint != null && autofillHints != null) hint += PropertyManager.SEPARATOR + autofillHints;
else if (autofillHints != null) hint = autofillHints;
String images = readAndroidImageResource(attrMap);
view.save(guiId, text, hint, tooltip, contentDescription, images, guiName);
//view.save(guiId, text, hint, guiName);
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node newNode = children.item(i);
String nodeName = newNode.getNodeName();
if ("#comment".equals(nodeName)) {
continue;
}
if ("#text".equals(nodeName)) {
// possible for XML files created on a different operating system
// than the one our analysis is run on
continue;
}
AndroidView newView = new AndroidView();
// FIXME: we assume that every node has attributes, may be wrong
if (!newNode.hasAttributes()) {
Logger.verb("WARNING", "xml node " + newNode + " has no attributes");
// continue;
} else {
NamedNodeMap attrs = newNode.getAttributes();
for (int idx = 0; idx < attrs.getLength(); idx += 1) {
Node attr = attrs.item(idx);
String name = attr.getNodeName();
String value = attr.getNodeValue();
newView.addAttr(name, value);
}
}
newView.setParent(view);
worklist.add(new Pair<Node, AndroidView>(newNode, newView));
}
}
} | private void readMenu(String file, AndroidView root, boolean isSys) {
Document doc;
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(file);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
LinkedList<Pair<Node, AndroidView>> worklist = Lists.newLinkedList();
worklist.add(new Pair<Node, AndroidView>(doc.getDocumentElement(), root));
root = null;
while (!worklist.isEmpty()) {
Pair<Node, AndroidView> pair = worklist.remove();
Node node = pair.getO1();
AndroidView view = pair.getO2();
NamedNodeMap attrMap = node.getAttributes();
Node idNode = attrMap.getNamedItemNS(ANDROID_NS, "id");
int guiId = -1;
String id = null;
if (idNode != null) {
String txt = idNode.getTextContent();
Pair<String, Integer> p = parseAndroidId(txt, isSys);
id = p.getO1();
Integer guiIdObj = p.getO2();
if (guiIdObj == null) {
if (!isSys) {
Logger.warn(this.getClass().getSimpleName(),
"unresolved android:id " + id + " in "
+ file);
}
guiId = nonRId--;
feedIdIntoGeneralMap("id", id, guiId, isSys);
} else {
guiId = guiIdObj.intValue();
}
}
String guiName = node.getNodeName();
if (guiName.equals("menu")) {
guiName = "android.view.Menu";
} else if (guiName.equals("item")) {
guiName = "android.view.MenuItem";
NodeList childNodes = node.getChildNodes();
if(childNodes!=null) {
for (int i = 0; i < childNodes.getLength(); i++) {
Node newNode = childNodes.item(i);
String nodeName = newNode.getNodeName();
if("menu".equals(nodeName)) {
guiName = "android.view.ViewGroup";
}
}
}
} else if (guiName.equals("group")) {
Logger.trace(this.getClass().getSimpleName(), "[TODO] <group> used in " + file);
guiName = "android.view.ViewGroup";
} else {
Logger.trace("XML", "Unhandled menu tag " + guiName);
}
if (debug) {
Logger.verb(this.getClass().getSimpleName(), guiName + " (" + guiId + ", " + id + ")");
}
String text = readAndroidTextOrTitle(attrMap, "title");
String hint = readAndroidTextOrTitle(attrMap, "hint");
String autofillHints = readAndroidTextOrTitle(attrMap, "autofillHints");
if (hint != null && autofillHints != null) hint += PropertyManager.SEPARATOR + autofillHints;
else if (autofillHints != null) hint = autofillHints;
String tooltip = readAndroidTextOrTitle(attrMap, "tooltipText");
String contentDescription = readAndroidTextOrTitle(attrMap, "contentDescription");
if (hint != null && autofillHints != null) hint += PropertyManager.SEPARATOR + autofillHints;
else if (autofillHints != null) hint = autofillHints;
String images = readAndroidImageResource(attrMap);
view.save(guiId, text, hint, tooltip, contentDescription, images, guiName);
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node newNode = children.item(i);
String nodeName = newNode.getNodeName();
if ("#comment".equals(nodeName)) {
continue;
}
if ("#text".equals(nodeName)) {
continue;
}
AndroidView newView = new AndroidView();
if (!newNode.hasAttributes()) {
Logger.verb("WARNING", "xml node " + newNode + " has no attributes");
} else {
NamedNodeMap attrs = newNode.getAttributes();
for (int idx = 0; idx < attrs.getLength(); idx += 1) {
Node attr = attrs.item(idx);
String name = attr.getNodeName();
String value = attr.getNodeValue();
newView.addAttr(name, value);
}
}
newView.setParent(view);
worklist.add(new Pair<Node, AndroidView>(newNode, newView));
}
}
} | private void readmenu(string file, androidview root, boolean issys) { document doc; try { documentbuilderfactory dbfactory = documentbuilderfactory.newinstance(); dbfactory.setnamespaceaware(true); documentbuilder dbuilder = dbfactory.newdocumentbuilder(); doc = dbuilder.parse(file); } catch (exception ex) { throw new runtimeexception(ex); } linkedlist<pair<node, androidview>> worklist = lists.newlinkedlist(); worklist.add(new pair<node, androidview>(doc.getdocumentelement(), root)); root = null; while (!worklist.isempty()) { pair<node, androidview> pair = worklist.remove(); node node = pair.geto1(); androidview view = pair.geto2(); namednodemap attrmap = node.getattributes(); node idnode = attrmap.getnameditemns(android_ns, "id"); int guiid = -1; string id = null; if (idnode != null) { string txt = idnode.gettextcontent(); pair<string, integer> p = parseandroidid(txt, issys); id = p.geto1(); integer guiidobj = p.geto2(); if (guiidobj == null) { if (!issys) { logger.warn(this.getclass().getsimplename(), "unresolved android:id " + id + " in " + file); } guiid = nonrid--; feedidintogeneralmap("id", id, guiid, issys); } else { guiid = guiidobj.intvalue(); } } string guiname = node.getnodename(); if (guiname.equals("menu")) { guiname = "android.view.menu"; } else if (guiname.equals("item")) { guiname = "android.view.menuitem"; nodelist childnodes = node.getchildnodes(); if(childnodes!=null) { for (int i = 0; i < childnodes.getlength(); i++) { node newnode = childnodes.item(i); string nodename = newnode.getnodename(); if("menu".equals(nodename)) { guiname = "android.view.viewgroup"; } } } } else if (guiname.equals("group")) { logger.trace(this.getclass().getsimplename(), "[todo] <group> used in " + file); guiname = "android.view.viewgroup"; } else { logger.trace("xml", "unhandled menu tag " + guiname); } if (debug) { logger.verb(this.getclass().getsimplename(), guiname + " (" + guiid + ", " + id + ")"); } string text = readandroidtextortitle(attrmap, "title"); string hint = readandroidtextortitle(attrmap, "hint"); string autofillhints = readandroidtextortitle(attrmap, "autofillhints"); if (hint != null && autofillhints != null) hint += propertymanager.separator + autofillhints; else if (autofillhints != null) hint = autofillhints; string tooltip = readandroidtextortitle(attrmap, "tooltiptext"); string contentdescription = readandroidtextortitle(attrmap, "contentdescription"); if (hint != null && autofillhints != null) hint += propertymanager.separator + autofillhints; else if (autofillhints != null) hint = autofillhints; string images = readandroidimageresource(attrmap); view.save(guiid, text, hint, tooltip, contentdescription, images, guiname); nodelist children = node.getchildnodes(); for (int i = 0; i < children.getlength(); i++) { node newnode = children.item(i); string nodename = newnode.getnodename(); if ("#comment".equals(nodename)) { continue; } if ("#text".equals(nodename)) { continue; } androidview newview = new androidview(); if (!newnode.hasattributes()) { logger.verb("warning", "xml node " + newnode + " has no attributes"); } else { namednodemap attrs = newnode.getattributes(); for (int idx = 0; idx < attrs.getlength(); idx += 1) { node attr = attrs.item(idx); string name = attr.getnodename(); string value = attr.getnodevalue(); newview.addattr(name, value); } } newview.setparent(view); worklist.add(new pair<node, androidview>(newnode, newview)); } } } | ttincs/guibat | [
1,
0,
1,
0
] |
34,021 | public static Color getColorByName(String colorName) {
switch (colorName.toLowerCase()) {
case COLOR_BLUE:
return Color.blue;
case COLOR_CYAN:
return Color.cyan;
case COLOR_DARKGRAY:
case COLOR_DARKGREY:
return Color.darkGray;
case COLOR_GRAY:
case COLOR_GREY:
return Color.gray;
case COLOR_LIGHTGRAY:
case COLOR_LIGHTGREY:
return Color.lightGray;
case COLOR_GREEN:
return Color.green;
case COLOR_MAGENTA:
return Color.magenta;
case COLOR_ORANGE:
return Color.orange;
case COLOR_PINK:
return Color.pink;
case COLOR_RED:
return Color.red;
case COLOR_WHITE:
return Color.white;
case COLOR_YELLOW:
return Color.yellow;
case COLOR_BLACK:
default:
return Color.black;
}
} | public static Color getColorByName(String colorName) {
switch (colorName.toLowerCase()) {
case COLOR_BLUE:
return Color.blue;
case COLOR_CYAN:
return Color.cyan;
case COLOR_DARKGRAY:
case COLOR_DARKGREY:
return Color.darkGray;
case COLOR_GRAY:
case COLOR_GREY:
return Color.gray;
case COLOR_LIGHTGRAY:
case COLOR_LIGHTGREY:
return Color.lightGray;
case COLOR_GREEN:
return Color.green;
case COLOR_MAGENTA:
return Color.magenta;
case COLOR_ORANGE:
return Color.orange;
case COLOR_PINK:
return Color.pink;
case COLOR_RED:
return Color.red;
case COLOR_WHITE:
return Color.white;
case COLOR_YELLOW:
return Color.yellow;
case COLOR_BLACK:
default:
return Color.black;
}
} | public static color getcolorbyname(string colorname) { switch (colorname.tolowercase()) { case color_blue: return color.blue; case color_cyan: return color.cyan; case color_darkgray: case color_darkgrey: return color.darkgray; case color_gray: case color_grey: return color.gray; case color_lightgray: case color_lightgrey: return color.lightgray; case color_green: return color.green; case color_magenta: return color.magenta; case color_orange: return color.orange; case color_pink: return color.pink; case color_red: return color.red; case color_white: return color.white; case color_yellow: return color.yellow; case color_black: default: return color.black; } } | yaohuizhou/attpg | [
1,
0,
0,
0
] |
34,026 | public View getView(int position, View convertView, ViewGroup parent)
{
mView = convertView;
if (mView == null)
{
LayoutInflater viewInflator;
viewInflator = LayoutInflater.from(mContext);
mView = viewInflator.inflate(R.layout.adapter_category_tile, null);
}
//TODO add a view holder
mCaptionTextView = (TextView) mView.findViewById(R.id.month_analytics_top_category_name);
mCategoryImageView = (ImageView) mView.findViewById(R.id.month_analytics_top_category_image);
mCategorySum = (TextView) mView.findViewById(R.id.month_analytics_top_category_sum);
if(mCategoryList.get(position) != null)
{
String valueStr = Utils.sumAsCurrency(mCategoryList.get(position).mSecondField);
int resIndex = mCategoryList.get(position).mFirstField;
int resource = Images.getImageByPosition(resIndex, Images.getUnsorted());
mCaptionTextView.setText(Images.getCaptionByImage(resource, Images.getSorted()));
mCategoryImageView.setImageResource(resource);
mCategorySum.setText(valueStr);
}
return mView;
} | public View getView(int position, View convertView, ViewGroup parent)
{
mView = convertView;
if (mView == null)
{
LayoutInflater viewInflator;
viewInflator = LayoutInflater.from(mContext);
mView = viewInflator.inflate(R.layout.adapter_category_tile, null);
}
mCaptionTextView = (TextView) mView.findViewById(R.id.month_analytics_top_category_name);
mCategoryImageView = (ImageView) mView.findViewById(R.id.month_analytics_top_category_image);
mCategorySum = (TextView) mView.findViewById(R.id.month_analytics_top_category_sum);
if(mCategoryList.get(position) != null)
{
String valueStr = Utils.sumAsCurrency(mCategoryList.get(position).mSecondField);
int resIndex = mCategoryList.get(position).mFirstField;
int resource = Images.getImageByPosition(resIndex, Images.getUnsorted());
mCaptionTextView.setText(Images.getCaptionByImage(resource, Images.getSorted()));
mCategoryImageView.setImageResource(resource);
mCategorySum.setText(valueStr);
}
return mView;
} | public view getview(int position, view convertview, viewgroup parent) { mview = convertview; if (mview == null) { layoutinflater viewinflator; viewinflator = layoutinflater.from(mcontext); mview = viewinflator.inflate(r.layout.adapter_category_tile, null); } mcaptiontextview = (textview) mview.findviewbyid(r.id.month_analytics_top_category_name); mcategoryimageview = (imageview) mview.findviewbyid(r.id.month_analytics_top_category_image); mcategorysum = (textview) mview.findviewbyid(r.id.month_analytics_top_category_sum); if(mcategorylist.get(position) != null) { string valuestr = utils.sumascurrency(mcategorylist.get(position).msecondfield); int resindex = mcategorylist.get(position).mfirstfield; int resource = images.getimagebyposition(resindex, images.getunsorted()); mcaptiontextview.settext(images.getcaptionbyimage(resource, images.getsorted())); mcategoryimageview.setimageresource(resource); mcategorysum.settext(valuestr); } return mview; } | zonnie/Coins | [
0,
1,
0,
0
] |
9,519 | protected static Response scoreOne(Frame frame, Model score_model) {
water.ModelMetrics metrics = water.ModelMetrics.getFromDKV(score_model, frame);
if (null == metrics) {
// have to compute
water.util.Log.debug("Cache miss: computing ModelMetrics. . .");
long before = System.currentTimeMillis();
Frame predictions = score_model.score(frame, true); // TODO: for now we're always calling adapt inside score
long after = System.currentTimeMillis();
ConfusionMatrix cm = new ConfusionMatrix(); // for regression this computes the MSE
AUC auc = null;
HitRatio hr = null;
if (score_model.isClassifier()) {
auc = new AUC();
// hr = new HitRatio();
score_model.calcError(frame, frame.vec(score_model.responseName()), predictions, predictions, "Prediction error:",
true, 20, cm, auc, hr);
} else {
score_model.calcError(frame, frame.vec(score_model.responseName()), predictions, predictions, "Prediction error:",
true, 20, cm, null, null);
}
// Now call AUC and ConfusionMatrix and maybe HitRatio
metrics = new water.ModelMetrics(score_model.getUniqueId(),
score_model.getModelCategory(),
frame.getUniqueId(),
after - before,
after,
auc,
cm);
// Put the metrics into the KV store
metrics.putInDKV();
} else {
// it's already cached in the DKV
water.util.Log.debug("using ModelMetrics from the cache. . .");
}
JsonObject metricsJson = metrics.toJSON();
JsonArray metricsArray = new JsonArray();
metricsArray.add(metricsJson);
JsonObject result = new JsonObject();
result.add("metrics", metricsArray);
return Response.done(result);
} | protected static Response scoreOne(Frame frame, Model score_model) {
water.ModelMetrics metrics = water.ModelMetrics.getFromDKV(score_model, frame);
if (null == metrics) {
water.util.Log.debug("Cache miss: computing ModelMetrics. . .");
long before = System.currentTimeMillis();
Frame predictions = score_model.score(frame, true);
long after = System.currentTimeMillis();
ConfusionMatrix cm = new ConfusionMatrix();
AUC auc = null;
HitRatio hr = null;
if (score_model.isClassifier()) {
auc = new AUC();
score_model.calcError(frame, frame.vec(score_model.responseName()), predictions, predictions, "Prediction error:",
true, 20, cm, auc, hr);
} else {
score_model.calcError(frame, frame.vec(score_model.responseName()), predictions, predictions, "Prediction error:",
true, 20, cm, null, null);
}
metrics = new water.ModelMetrics(score_model.getUniqueId(),
score_model.getModelCategory(),
frame.getUniqueId(),
after - before,
after,
auc,
cm);
metrics.putInDKV();
} else {
water.util.Log.debug("using ModelMetrics from the cache. . .");
}
JsonObject metricsJson = metrics.toJSON();
JsonArray metricsArray = new JsonArray();
metricsArray.add(metricsJson);
JsonObject result = new JsonObject();
result.add("metrics", metricsArray);
return Response.done(result);
} | protected static response scoreone(frame frame, model score_model) { water.modelmetrics metrics = water.modelmetrics.getfromdkv(score_model, frame); if (null == metrics) { water.util.log.debug("cache miss: computing modelmetrics. . ."); long before = system.currenttimemillis(); frame predictions = score_model.score(frame, true); long after = system.currenttimemillis(); confusionmatrix cm = new confusionmatrix(); auc auc = null; hitratio hr = null; if (score_model.isclassifier()) { auc = new auc(); score_model.calcerror(frame, frame.vec(score_model.responsename()), predictions, predictions, "prediction error:", true, 20, cm, auc, hr); } else { score_model.calcerror(frame, frame.vec(score_model.responsename()), predictions, predictions, "prediction error:", true, 20, cm, null, null); } metrics = new water.modelmetrics(score_model.getuniqueid(), score_model.getmodelcategory(), frame.getuniqueid(), after - before, after, auc, cm); metrics.putindkv(); } else { water.util.log.debug("using modelmetrics from the cache. . ."); } jsonobject metricsjson = metrics.tojson(); jsonarray metricsarray = new jsonarray(); metricsarray.add(metricsjson); jsonobject result = new jsonobject(); result.add("metrics", metricsarray); return response.done(result); } | vkuznet/h2o | [
1,
0,
0,
0
] |
17,712 | public Range<Token> getRange(ByteBuffer key)
{
// TODO: naive linear search of the token map
Token<?> t = partitioner.getToken(key);
for (Range<Token> range : rangeMap.keySet())
if (range.contains(t))
return range;
throw new RuntimeException("Invalid token information returned by describe_ring: " + rangeMap);
} | public Range<Token> getRange(ByteBuffer key)
{
Token<?> t = partitioner.getToken(key);
for (Range<Token> range : rangeMap.keySet())
if (range.contains(t))
return range;
throw new RuntimeException("Invalid token information returned by describe_ring: " + rangeMap);
} | public range<token> getrange(bytebuffer key) { token<?> t = partitioner.gettoken(key); for (range<token> range : rangemap.keyset()) if (range.contains(t)) return range; throw new runtimeexception("invalid token information returned by describe_ring: " + rangemap); } | tadeegan/eiger-application-aware | [
0,
1,
0,
0
] |
17,718 | private void populateSignatureNames() {
if (acroForm == null) {
return;
}
List<Object[]> sorter = new ArrayList<>();
for (Map.Entry<String, PdfFormField> entry : acroForm.getFormFields().entrySet()) {
PdfFormField field = entry.getValue();
PdfDictionary merged = field.getPdfObject();
if (!PdfName.Sig.equals(merged.get(PdfName.FT)))
continue;
PdfDictionary v = merged.getAsDictionary(PdfName.V);
if (v == null)
continue;
PdfString contents = v.getAsString(PdfName.Contents);
if (contents == null) {
continue;
} else {
contents.markAsUnencryptedObject();
}
PdfArray ro = v.getAsArray(PdfName.ByteRange);
if (ro == null)
continue;
int rangeSize = ro.size();
if (rangeSize < 2)
continue;
int length = ro.getAsNumber(rangeSize - 1).intValue() + ro.getAsNumber(rangeSize - 2).intValue();
sorter.add(new Object[]{entry.getKey(), new int[]{length, 0}});
}
Collections.sort(sorter, new SorterComparator());
if (sorter.size() > 0) {
try {
if (((int[]) sorter.get(sorter.size() - 1)[1])[0] == document.getReader().getFileLength())
totalRevisions = sorter.size();
else
totalRevisions = sorter.size() + 1;
} catch (IOException e) {
// TODO: add exception handling (at least some logger)
}
for (int k = 0; k < sorter.size(); ++k) {
Object[] objs = sorter.get(k);
String name = (String) objs[0];
int[] p = (int[]) objs[1];
p[1] = k + 1;
sigNames.put(name, p);
orderedSignatureNames.add(name);
}
}
} | private void populateSignatureNames() {
if (acroForm == null) {
return;
}
List<Object[]> sorter = new ArrayList<>();
for (Map.Entry<String, PdfFormField> entry : acroForm.getFormFields().entrySet()) {
PdfFormField field = entry.getValue();
PdfDictionary merged = field.getPdfObject();
if (!PdfName.Sig.equals(merged.get(PdfName.FT)))
continue;
PdfDictionary v = merged.getAsDictionary(PdfName.V);
if (v == null)
continue;
PdfString contents = v.getAsString(PdfName.Contents);
if (contents == null) {
continue;
} else {
contents.markAsUnencryptedObject();
}
PdfArray ro = v.getAsArray(PdfName.ByteRange);
if (ro == null)
continue;
int rangeSize = ro.size();
if (rangeSize < 2)
continue;
int length = ro.getAsNumber(rangeSize - 1).intValue() + ro.getAsNumber(rangeSize - 2).intValue();
sorter.add(new Object[]{entry.getKey(), new int[]{length, 0}});
}
Collections.sort(sorter, new SorterComparator());
if (sorter.size() > 0) {
try {
if (((int[]) sorter.get(sorter.size() - 1)[1])[0] == document.getReader().getFileLength())
totalRevisions = sorter.size();
else
totalRevisions = sorter.size() + 1;
} catch (IOException e) {
}
for (int k = 0; k < sorter.size(); ++k) {
Object[] objs = sorter.get(k);
String name = (String) objs[0];
int[] p = (int[]) objs[1];
p[1] = k + 1;
sigNames.put(name, p);
orderedSignatureNames.add(name);
}
}
} | private void populatesignaturenames() { if (acroform == null) { return; } list<object[]> sorter = new arraylist<>(); for (map.entry<string, pdfformfield> entry : acroform.getformfields().entryset()) { pdfformfield field = entry.getvalue(); pdfdictionary merged = field.getpdfobject(); if (!pdfname.sig.equals(merged.get(pdfname.ft))) continue; pdfdictionary v = merged.getasdictionary(pdfname.v); if (v == null) continue; pdfstring contents = v.getasstring(pdfname.contents); if (contents == null) { continue; } else { contents.markasunencryptedobject(); } pdfarray ro = v.getasarray(pdfname.byterange); if (ro == null) continue; int rangesize = ro.size(); if (rangesize < 2) continue; int length = ro.getasnumber(rangesize - 1).intvalue() + ro.getasnumber(rangesize - 2).intvalue(); sorter.add(new object[]{entry.getkey(), new int[]{length, 0}}); } collections.sort(sorter, new sortercomparator()); if (sorter.size() > 0) { try { if (((int[]) sorter.get(sorter.size() - 1)[1])[0] == document.getreader().getfilelength()) totalrevisions = sorter.size(); else totalrevisions = sorter.size() + 1; } catch (ioexception e) { } for (int k = 0; k < sorter.size(); ++k) { object[] objs = sorter.get(k); string name = (string) objs[0]; int[] p = (int[]) objs[1]; p[1] = k + 1; signames.put(name, p); orderedsignaturenames.add(name); } } } | tompecina/itext7 | [
0,
1,
0,
0
] |
25,939 | public void setEnumsSet(Map<String, Set<Object>> enums)
{
Preconditions.checkNotNull(enums);
areEnumsUpdated = true;
Map<String, List<Object>> enumsList = Maps.newHashMap();
//Check that all the given keys are valid
Preconditions.checkArgument(
configurationSchema.getKeyDescriptor().getFields().getFields().containsAll(enums.keySet()),
"The given map doesn't contain valid keys. Valid keys are %s and the provided keys are %s",
configurationSchema.getKeyDescriptor().getFields().getFields(),
enums.keySet());
//Todo check the type of the objects, for now just set them on the enum.
for (Map.Entry<String, Set<Object>> entry : enums.entrySet()) {
String name = entry.getKey();
Set<Object> vals = entry.getValue();
Preconditions.checkNotNull(name);
Preconditions.checkNotNull(vals);
for (Object value : entry.getValue()) {
Preconditions.checkNotNull(value);
}
List<Object> valsList = Lists.newArrayList(vals);
enumsList.put(name, valsList);
}
currentEnumVals = Maps.newHashMap(enumsList);
} | public void setEnumsSet(Map<String, Set<Object>> enums)
{
Preconditions.checkNotNull(enums);
areEnumsUpdated = true;
Map<String, List<Object>> enumsList = Maps.newHashMap();
Preconditions.checkArgument(
configurationSchema.getKeyDescriptor().getFields().getFields().containsAll(enums.keySet()),
"The given map doesn't contain valid keys. Valid keys are %s and the provided keys are %s",
configurationSchema.getKeyDescriptor().getFields().getFields(),
enums.keySet());
for (Map.Entry<String, Set<Object>> entry : enums.entrySet()) {
String name = entry.getKey();
Set<Object> vals = entry.getValue();
Preconditions.checkNotNull(name);
Preconditions.checkNotNull(vals);
for (Object value : entry.getValue()) {
Preconditions.checkNotNull(value);
}
List<Object> valsList = Lists.newArrayList(vals);
enumsList.put(name, valsList);
}
currentEnumVals = Maps.newHashMap(enumsList);
} | public void setenumsset(map<string, set<object>> enums) { preconditions.checknotnull(enums); areenumsupdated = true; map<string, list<object>> enumslist = maps.newhashmap(); preconditions.checkargument( configurationschema.getkeydescriptor().getfields().getfields().containsall(enums.keyset()), "the given map doesn't contain valid keys. valid keys are %s and the provided keys are %s", configurationschema.getkeydescriptor().getfields().getfields(), enums.keyset()); for (map.entry<string, set<object>> entry : enums.entryset()) { string name = entry.getkey(); set<object> vals = entry.getvalue(); preconditions.checknotnull(name); preconditions.checknotnull(vals); for (object value : entry.getvalue()) { preconditions.checknotnull(value); } list<object> valslist = lists.newarraylist(vals); enumslist.put(name, valslist); } currentenumvals = maps.newhashmap(enumslist); } | vijaysbhat/apex-malhar | [
0,
1,
0,
0
] |
25,940 | @SuppressWarnings({"rawtypes", "unchecked"})
public void setEnumsSetComparable(Map<String, Set<Comparable>> enums)
{
Preconditions.checkNotNull(enums);
areEnumsUpdated = true;
Map<String, List<Object>> enumsList = Maps.newHashMap();
//Check that all the given keys are valid
Preconditions.checkArgument(
configurationSchema.getKeyDescriptor().getFields().getFields().containsAll(enums.keySet()),
"The given map doesn't contain valid keys. Valid keys are %s and the provided keys are %s",
configurationSchema.getKeyDescriptor().getFields().getFields(),
enums.keySet());
//Todo check the type of the objects, for now just set them on the enum.
for (Map.Entry<String, Set<Comparable>> entry : enums.entrySet()) {
String name = entry.getKey();
Set<Comparable> vals = entry.getValue();
Preconditions.checkNotNull(name);
Preconditions.checkNotNull(vals);
for (Object value : entry.getValue()) {
Preconditions.checkNotNull(value);
}
List<Comparable> valsListComparable = Lists.newArrayList(vals);
Collections.sort(valsListComparable);
List<Object> valsList = (List)valsListComparable;
enumsList.put(name, valsList);
}
currentEnumVals = Maps.newHashMap(enumsList);
} | @SuppressWarnings({"rawtypes", "unchecked"})
public void setEnumsSetComparable(Map<String, Set<Comparable>> enums)
{
Preconditions.checkNotNull(enums);
areEnumsUpdated = true;
Map<String, List<Object>> enumsList = Maps.newHashMap();
Preconditions.checkArgument(
configurationSchema.getKeyDescriptor().getFields().getFields().containsAll(enums.keySet()),
"The given map doesn't contain valid keys. Valid keys are %s and the provided keys are %s",
configurationSchema.getKeyDescriptor().getFields().getFields(),
enums.keySet());
for (Map.Entry<String, Set<Comparable>> entry : enums.entrySet()) {
String name = entry.getKey();
Set<Comparable> vals = entry.getValue();
Preconditions.checkNotNull(name);
Preconditions.checkNotNull(vals);
for (Object value : entry.getValue()) {
Preconditions.checkNotNull(value);
}
List<Comparable> valsListComparable = Lists.newArrayList(vals);
Collections.sort(valsListComparable);
List<Object> valsList = (List)valsListComparable;
enumsList.put(name, valsList);
}
currentEnumVals = Maps.newHashMap(enumsList);
} | @suppresswarnings({"rawtypes", "unchecked"}) public void setenumssetcomparable(map<string, set<comparable>> enums) { preconditions.checknotnull(enums); areenumsupdated = true; map<string, list<object>> enumslist = maps.newhashmap(); preconditions.checkargument( configurationschema.getkeydescriptor().getfields().getfields().containsall(enums.keyset()), "the given map doesn't contain valid keys. valid keys are %s and the provided keys are %s", configurationschema.getkeydescriptor().getfields().getfields(), enums.keyset()); for (map.entry<string, set<comparable>> entry : enums.entryset()) { string name = entry.getkey(); set<comparable> vals = entry.getvalue(); preconditions.checknotnull(name); preconditions.checknotnull(vals); for (object value : entry.getvalue()) { preconditions.checknotnull(value); } list<comparable> valslistcomparable = lists.newarraylist(vals); collections.sort(valslistcomparable); list<object> valslist = (list)valslistcomparable; enumslist.put(name, valslist); } currentenumvals = maps.newhashmap(enumslist); } | vijaysbhat/apex-malhar | [
0,
1,
0,
0
] |
25,941 | public void setEnumsList(Map<String, List<Object>> enums)
{
Preconditions.checkNotNull(enums);
areEnumsUpdated = true;
//Check that all the given keys are valid
Preconditions.checkArgument(
configurationSchema.getKeyDescriptor().getFields().getFields().containsAll(enums.keySet()),
"The given map doesn't contain valid keys. Valid keys are %s and the provided keys are %s",
configurationSchema.getKeyDescriptor().getFields().getFields(),
enums.keySet());
//Todo check the type of the objects, for now just set them on the enum.
for (Map.Entry<String, List<Object>> entry : enums.entrySet()) {
Preconditions.checkNotNull(entry.getKey());
Preconditions.checkNotNull(entry.getValue());
}
Map<String, List<Object>> tempEnums = Maps.newHashMap();
for (Map.Entry<String, List<Object>> entry : enums.entrySet()) {
String key = entry.getKey();
List<?> enumValues = entry.getValue();
List<Object> tempEnumValues = Lists.newArrayList();
for (Object enumValue : enumValues) {
tempEnumValues.add(enumValue);
}
tempEnums.put(key, tempEnumValues);
}
currentEnumVals = tempEnums;
} | public void setEnumsList(Map<String, List<Object>> enums)
{
Preconditions.checkNotNull(enums);
areEnumsUpdated = true;
Preconditions.checkArgument(
configurationSchema.getKeyDescriptor().getFields().getFields().containsAll(enums.keySet()),
"The given map doesn't contain valid keys. Valid keys are %s and the provided keys are %s",
configurationSchema.getKeyDescriptor().getFields().getFields(),
enums.keySet());
for (Map.Entry<String, List<Object>> entry : enums.entrySet()) {
Preconditions.checkNotNull(entry.getKey());
Preconditions.checkNotNull(entry.getValue());
}
Map<String, List<Object>> tempEnums = Maps.newHashMap();
for (Map.Entry<String, List<Object>> entry : enums.entrySet()) {
String key = entry.getKey();
List<?> enumValues = entry.getValue();
List<Object> tempEnumValues = Lists.newArrayList();
for (Object enumValue : enumValues) {
tempEnumValues.add(enumValue);
}
tempEnums.put(key, tempEnumValues);
}
currentEnumVals = tempEnums;
} | public void setenumslist(map<string, list<object>> enums) { preconditions.checknotnull(enums); areenumsupdated = true; preconditions.checkargument( configurationschema.getkeydescriptor().getfields().getfields().containsall(enums.keyset()), "the given map doesn't contain valid keys. valid keys are %s and the provided keys are %s", configurationschema.getkeydescriptor().getfields().getfields(), enums.keyset()); for (map.entry<string, list<object>> entry : enums.entryset()) { preconditions.checknotnull(entry.getkey()); preconditions.checknotnull(entry.getvalue()); } map<string, list<object>> tempenums = maps.newhashmap(); for (map.entry<string, list<object>> entry : enums.entryset()) { string key = entry.getkey(); list<?> enumvalues = entry.getvalue(); list<object> tempenumvalues = lists.newarraylist(); for (object enumvalue : enumvalues) { tempenumvalues.add(enumvalue); } tempenums.put(key, tempenumvalues); } currentenumvals = tempenums; } | vijaysbhat/apex-malhar | [
0,
1,
0,
0
] |
1,407 | public ByteBuffer allocateBufferIfNeeded() {
ByteBuffer buffer = getCurrentBuffer();
if (buffer != null && buffer.hasRemaining()) {
return buffer;
}
if (currentBufferIndex < bufferList.size() - 1) {
buffer = getBuffer(currentBufferIndex + 1);
} else {
buffer = ByteBuffer.allocate(bufferSize);
bufferList.add(buffer);
}
Preconditions.checkArgument(bufferList.size() <= capacity);
currentBufferIndex++;
// TODO: Turn the below precondition check on when Standalone pipeline
// is removed in the write path in tests
// Preconditions.checkArgument(buffer.position() == 0);
return buffer;
} | public ByteBuffer allocateBufferIfNeeded() {
ByteBuffer buffer = getCurrentBuffer();
if (buffer != null && buffer.hasRemaining()) {
return buffer;
}
if (currentBufferIndex < bufferList.size() - 1) {
buffer = getBuffer(currentBufferIndex + 1);
} else {
buffer = ByteBuffer.allocate(bufferSize);
bufferList.add(buffer);
}
Preconditions.checkArgument(bufferList.size() <= capacity);
currentBufferIndex++;
return buffer;
} | public bytebuffer allocatebufferifneeded() { bytebuffer buffer = getcurrentbuffer(); if (buffer != null && buffer.hasremaining()) { return buffer; } if (currentbufferindex < bufferlist.size() - 1) { buffer = getbuffer(currentbufferindex + 1); } else { buffer = bytebuffer.allocate(buffersize); bufferlist.add(buffer); } preconditions.checkargument(bufferlist.size() <= capacity); currentbufferindex++; return buffer; } | wangfanming/hadoop | [
1,
0,
0,
0
] |
34,186 | @Override
public void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
initViews();
Statistics.INSTANCE.trackConnectionState();
if (MwmApplication.get().nativeIsBenchmarking())
Utils.keepScreenOn(true, getWindow());
// TODO consider implementing other model of listeners connection, without activities being bound
Framework.nativeSetRoutingListener(this);
Framework.nativeSetRouteProgressListener(this);
Framework.nativeSetBalloonListener(this);
mSearchController = new FloatingSearchToolbarController(this);
mLocationPredictor = new LocationPredictor(new Handler(), this);
processIntent(getIntent());
SharingHelper.prepare();
} | @Override
public void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
initViews();
Statistics.INSTANCE.trackConnectionState();
if (MwmApplication.get().nativeIsBenchmarking())
Utils.keepScreenOn(true, getWindow());
Framework.nativeSetRoutingListener(this);
Framework.nativeSetRouteProgressListener(this);
Framework.nativeSetBalloonListener(this);
mSearchController = new FloatingSearchToolbarController(this);
mLocationPredictor = new LocationPredictor(new Handler(), this);
processIntent(getIntent());
SharingHelper.prepare();
} | @override public void oncreate(@nullable bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_map); initviews(); statistics.instance.trackconnectionstate(); if (mwmapplication.get().nativeisbenchmarking()) utils.keepscreenon(true, getwindow()); framework.nativesetroutinglistener(this); framework.nativesetrouteprogresslistener(this); framework.nativesetballoonlistener(this); msearchcontroller = new floatingsearchtoolbarcontroller(this); mlocationpredictor = new locationpredictor(new handler(), this); processintent(getintent()); sharinghelper.prepare(); } | yanncoupin/omim | [
1,
0,
0,
0
] |
34,226 | private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("@");
} | private boolean isEmailValid(String email) {
return email.contains("@");
} | private boolean isemailvalid(string email) { return email.contains("@"); } | xuanliao/MVVM_Samples | [
0,
1,
0,
0
] |
34,227 | private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
} | private boolean isPasswordValid(String password) {
return password.length() > 4;
} | private boolean ispasswordvalid(string password) { return password.length() > 4; } | xuanliao/MVVM_Samples | [
0,
1,
0,
0
] |
34,249 | @Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Sliding Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
} | @Override
public void onStart() {
super.onStart();
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW,
"Sliding Page",
Uri.parse("http://host/path"),
Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
} | @override public void onstart() { super.onstart(); client.connect(); action viewaction = action.newaction( action.type_view, "sliding page", uri.parse("http://host/path"), uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); appindex.appindexapi.start(client, viewaction); } | wangwenwang/sfkc-driver-android | [
1,
1,
0,
0
] |
34,250 | @Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Sliding Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
} | @Override
public void onStop() {
super.onStop();
Action viewAction = Action.newAction(
Action.TYPE_VIEW,
"Sliding Page",
Uri.parse("http://host/path"),
Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
} | @override public void onstop() { super.onstop(); action viewaction = action.newaction( action.type_view, "sliding page", uri.parse("http://host/path"), uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); appindex.appindexapi.end(client, viewaction); client.disconnect(); } | wangwenwang/sfkc-driver-android | [
1,
1,
0,
0
] |
26,213 | @Test
public void canImportTheCorrectNumberOfRecords() throws Throwable {
process(shakParser, shakDao, "data/sks/SHAKCOMPLETE.TXT");
// FIXME: These record counts are only correct iff if duplicate keys are disregarted.
// This is unfortunate. Keys are currently only considered based their SKSKode.
// They should be a combination of type + kode + startdato based on the register doc.
assertEquals(1017, jdbc.queryForInt("SELECT COUNT(*) FROM class_shak WHERE Organisationstype = 'Sygehus'"));
assertEquals(18411, jdbc.queryForInt("SELECT COUNT(*) FROM class_shak WHERE Organisationstype = 'Afdeling'"));
process(sksParser, sksDao, "data/sks/SKScomplete.txt");
assertEquals(573, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'und'"));
assertEquals(8990, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'pro'"));
assertEquals(43857, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'dia'"));
assertEquals(19980, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'opr'"));
assertEquals(10461, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'atc'"));
} | @Test
public void canImportTheCorrectNumberOfRecords() throws Throwable {
process(shakParser, shakDao, "data/sks/SHAKCOMPLETE.TXT");
assertEquals(1017, jdbc.queryForInt("SELECT COUNT(*) FROM class_shak WHERE Organisationstype = 'Sygehus'"));
assertEquals(18411, jdbc.queryForInt("SELECT COUNT(*) FROM class_shak WHERE Organisationstype = 'Afdeling'"));
process(sksParser, sksDao, "data/sks/SKScomplete.txt");
assertEquals(573, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'und'"));
assertEquals(8990, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'pro'"));
assertEquals(43857, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'dia'"));
assertEquals(19980, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'opr'"));
assertEquals(10461, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'atc'"));
} | @test public void canimportthecorrectnumberofrecords() throws throwable { process(shakparser, shakdao, "data/sks/shakcomplete.txt"); assertequals(1017, jdbc.queryforint("select count(*) from class_shak where organisationstype = 'sygehus'")); assertequals(18411, jdbc.queryforint("select count(*) from class_shak where organisationstype = 'afdeling'")); process(sksparser, sksdao, "data/sks/skscomplete.txt"); assertequals(573, jdbc.queryforint("select count(*) from class_sks where type = 'und'")); assertequals(8990, jdbc.queryforint("select count(*) from class_sks where type = 'pro'")); assertequals(43857, jdbc.queryforint("select count(*) from class_sks where type = 'dia'")); assertequals(19980, jdbc.queryforint("select count(*) from class_sks where type = 'opr'")); assertequals(10461, jdbc.queryforint("select count(*) from class_sks where type = 'atc'")); } | trifork/HAIBA-FGRImporter | [
0,
0,
1,
0
] |
26,228 | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
solrQuery.setSort(new SortClause(sortField, sortOrder));
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
solrQuery.setStart(paginationStart);
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
solrSearchResult.setPublicationStatuses(states);
}
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
facetCategory.setFriendlyName(facetField.getName());
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | public solrqueryresponse search(dataverserequest dataverserequest, dataverse dataverse, string query, list<string> filterqueries, string sortfield, string sortorder, int paginationstart, boolean onlydatatrelatedtome, int numresultsperpage, boolean retrieveentities) throws searchexception { if (paginationstart < 0) { throw new illegalargumentexception("paginationstart must be 0 or greater"); } if (numresultsperpage < 1) { throw new illegalargumentexception("numresultsperpage must be 1 or greater"); } solrquery solrquery = new solrquery(); query = searchutil.sanitizequery(query); solrquery.setquery(query); solrquery.setsort(new sortclause(sortfield, sortorder)); solrquery.sethighlight(true).sethighlightsnippets(1); integer fragsize = systemconfig.getsearchhighlightfragmentsize(); if (fragsize != null) { solrquery.sethighlightfragsize(fragsize); } solrquery.sethighlightsimplepre("<span class=\"search-term-match\">"); solrquery.sethighlightsimplepost("</span>"); map<string, string> solrfieldstohightlightonmap = new hashmap<>(); solrfieldstohightlightonmap.put(searchfields.name, "name"); solrfieldstohightlightonmap.put(searchfields.affiliation, "affiliation"); solrfieldstohightlightonmap.put(searchfields.file_type_friendly, "file type"); solrfieldstohightlightonmap.put(searchfields.description, "description"); solrfieldstohightlightonmap.put(searchfields.variable_name, "variable name"); solrfieldstohightlightonmap.put(searchfields.variable_label, "variable label"); solrfieldstohightlightonmap.put(searchfields.file_type_searchable, "file type"); solrfieldstohightlightonmap.put(searchfields.dataset_publication_date, "publication date"); solrfieldstohightlightonmap.put(searchfields.dataset_persistent_id, bundleutil.getstringfrombundle("advanced.search.datasets.persistentid")); solrfieldstohightlightonmap.put(searchfields.file_persistent_id, bundleutil.getstringfrombundle("advanced.search.files.persistentid")); solrfieldstohightlightonmap.put(searchfields.filename_without_extension, "filename without extension"); solrfieldstohightlightonmap.put(searchfields.file_tag_searchable, "file tag"); list<datasetfieldtype> datasetfields = datasetfieldservice.findallorderedbyid(); for (datasetfieldtype datasetfieldtype : datasetfields) { string solrfield = datasetfieldtype.getsolrfield().getnamesearchable(); string displayname = datasetfieldtype.getdisplayname(); solrfieldstohightlightonmap.put(solrfield, displayname); } for (map.entry<string, string> entry : solrfieldstohightlightonmap.entryset()) { string solrfield = entry.getkey(); solrquery.addhighlightfield(solrfield); } solrquery.setparam("fl", "*,score"); solrquery.setparam("qt", "/select"); solrquery.setparam("facet", "true"); solrquery.setparam("facet.query", "*"); for (string filterquery : filterqueries) { solrquery.addfilterquery(filterquery); } string permissionfilterquery = this.getpermissionfilterquery(dataverserequest, solrquery, dataverse, onlydatatrelatedtome); if (permissionfilterquery != null) { solrquery.addfilterquery(permissionfilterquery); } solrquery.addfacetfield(searchfields.dataverse_category); solrquery.addfacetfield(searchfields.metadata_source); solrquery.addfacetfield(searchfields.publication_date); if (dataverse != null) { for (dataversefacet dataversefacet : dataverse.getdataversefacets()) { datasetfieldtype datasetfield = dataversefacet.getdatasetfieldtype(); solrquery.addfacetfield(datasetfield.getsolrfield().getnamefacetable()); } } solrquery.addfacetfield(searchfields.file_type); solrquery.addfacetfield(searchfields.type); solrquery.addfacetfield(searchfields.file_tag); if (!systemconfig.ispublicinstall()) { solrquery.addfacetfield(searchfields.access); } solrquery.setstart(paginationstart); int thisyear = calendar.getinstance().get(calendar.year); final int citationyearrangestart = 1901; final int citationyearrangeend = thisyear; final int citationyearrangespan = 2; solrquery.setrows(numresultsperpage); logger.fine("solr query:" + solrquery); queryresponse queryresponse = null; try { queryresponse = solrserver.query(solrquery); } catch (remotesolrexception ex) { string messagefromsolr = ex.getlocalizedmessage(); string error = "search syntax error: "; string stringtohide = "org.apache.solr.search.syntaxerror: "; if (messagefromsolr.startswith(stringtohide)) { error += messagefromsolr.substring(stringtohide.length()); } else { error += messagefromsolr; } logger.info(error); solrqueryresponse exceptionsolrqueryresponse = new solrqueryresponse(solrquery); exceptionsolrqueryresponse.seterror(error); long zeronumresultsfound = 0; long zerogetresultsstart = 0; list<solrsearchresult> emptysolrsearchresults = new arraylist<>(); list<facetcategory> exceptionfacetcategorylist = new arraylist<>(); map<string, list<string>> emptyspellingsuggestion = new hashmap<>(); exceptionsolrqueryresponse.setnumresultsfound(zeronumresultsfound); exceptionsolrqueryresponse.setresultsstart(zerogetresultsstart); exceptionsolrqueryresponse.setsolrsearchresults(emptysolrsearchresults); exceptionsolrqueryresponse.setfacetcategorylist(exceptionfacetcategorylist); exceptionsolrqueryresponse.settypefacetcategories(exceptionfacetcategorylist); exceptionsolrqueryresponse.setspellingsuggestionsbytoken(emptyspellingsuggestion); return exceptionsolrqueryresponse; } catch (solrserverexception | ioexception ex) { throw new searchexception("internal dataverse search engine error", ex); } solrdocumentlist docs = queryresponse.getresults(); list<solrsearchresult> solrsearchresults = new arraylist<>(); object searchfieldsobject = new searchfields(); field[] staticsearchfields = searchfieldsobject.getclass().getdeclaredfields(); string titlesolrfield = null; try { datasetfieldtype titledatasetfield = datasetfieldservice.findbyname(datasetfieldconstant.title); titlesolrfield = titledatasetfield.getsolrfield().getnamesearchable(); } catch (ejbtransactionrolledbackexception ex) { logger.info("couldn't find " + datasetfieldconstant.title); if (ex.getcause() instanceof transactionrolledbacklocalexception) { if (ex.getcause().getcause() instanceof noresultexception) { logger.info("caught noresultexception"); } } } map<string, string> datasetfieldfriendlynamesbysolrfield = new hashmap<>(); map<string, string> staticsolrfieldfriendlynamesbysolrfield = new hashmap<>(); string baseurl = systemconfig.getdataversesiteurl(); for (solrdocument solrdocument : docs) { string id = (string) solrdocument.getfieldvalue(searchfields.id); long entityid = (long) solrdocument.getfieldvalue(searchfields.entity_id); string type = (string) solrdocument.getfieldvalue(searchfields.type); float score = (float) solrdocument.getfieldvalue(searchfields.relevance); logger.fine("score for " + id + ": " + score); string identifier = (string) solrdocument.getfieldvalue(searchfields.identifier); string citation = (string) solrdocument.getfieldvalue(searchfields.dataset_citation); string citationplainhtml = (string) solrdocument.getfieldvalue(searchfields.dataset_citation_html); string persistenturl = (string) solrdocument.getfieldvalue(searchfields.persistent_url); string name = (string) solrdocument.getfieldvalue(searchfields.name); string namesort = (string) solrdocument.getfieldvalue(searchfields.name_sort); string title = (string) solrdocument.getfieldvalue(titlesolrfield); long datasetversionid = (long) solrdocument.getfieldvalue(searchfields.dataset_version_id); string deaccessionreason = (string) solrdocument.getfieldvalue(searchfields.dataset_deaccession_reason); string filetype = (string) solrdocument.getfieldvalue(searchfields.file_type_friendly); string filecontenttype = (string) solrdocument.getfieldvalue(searchfields.file_content_type); date release_or_create_date = (date) solrdocument.getfieldvalue(searchfields.release_or_create_date); string datetodisplayoncard = (string) solrdocument.getfirstvalue(searchfields.release_or_create_date_searchable_text); string dvtree = (string) solrdocument.getfirstvalue(searchfields.subtree); list<string> matchedfields = new arraylist<>(); list<highlight> highlights = new arraylist<>(); map<solrfield, highlight> highlightsmap = new hashmap<>(); map<solrfield, list<string>> highlightsmap2 = new hashmap<>(); map<string, highlight> highlightsmap3 = new hashmap<>(); if (queryresponse.gethighlighting().get(id) != null) { for (map.entry<string, string> entry : solrfieldstohightlightonmap.entryset()) { string field = entry.getkey(); string displayname = entry.getvalue(); list<string> highlightsnippets = queryresponse.gethighlighting().get(id).get(field); if (highlightsnippets != null) { matchedfields.add(field); solrfield solrfield = new solrfield(field, solrfield.solrtype.string, true, true); highlight highlight = new highlight(solrfield, highlightsnippets, displayname); highlights.add(highlight); highlightsmap.put(solrfield, highlight); highlightsmap2.put(solrfield, highlightsnippets); highlightsmap3.put(field, highlight); } } } solrsearchresult solrsearchresult = new solrsearchresult(query, name); list<string> states = (list<string>) solrdocument.getfieldvalue(searchfields.publication_status); if (states != null) { solrsearchresult.setpublicationstatuses(states); } solrsearchresult.setid(id); solrsearchresult.setentityid(entityid); if (retrieveentities) { solrsearchresult.setentity(dvobjectservice.finddvobject(entityid)); } solrsearchresult.setidentifier(identifier); solrsearchresult.setpersistenturl(persistenturl); solrsearchresult.settype(type); solrsearchresult.setscore(score); solrsearchresult.setnamesort(namesort); solrsearchresult.setreleaseorcreatedate(release_or_create_date); solrsearchresult.setdatetodisplayoncard(datetodisplayoncard); solrsearchresult.setmatchedfields(matchedfields); solrsearchresult.sethighlightsaslist(highlights); solrsearchresult.sethighlightsmap(highlightsmap); solrsearchresult.sethighlightsasmap(highlightsmap3); map<string, string> parent = new hashmap<>(); string description = (string) solrdocument.getfieldvalue(searchfields.description); solrsearchresult.setdescriptionnosnippet(description); solrsearchresult.setdeaccessionreason(deaccessionreason); solrsearchresult.setdvtree(dvtree); string originsource = (string) solrdocument.getfieldvalue(searchfields.metadata_source); if (indexservicebean.harvested.equals(originsource)) { solrsearchresult.setharvested(true); } if (type.equals("dataverses")) { solrsearchresult.setname(name); solrsearchresult.sethtmlurl(baseurl + systemconfig.dataverse_path + identifier); } else if (type.equals("datasets")) { solrsearchresult.sethtmlurl(baseurl + "/dataset.xhtml?globalid=" + identifier); solrsearchresult.setapiurl(baseurl + "/api/datasets/" + entityid); list<string> datasetdescriptions = (list<string>) solrdocument.getfieldvalue(searchfields.dataset_description); if (datasetdescriptions != null) { string firstdatasetdescription = datasetdescriptions.get(0); if (firstdatasetdescription != null) { solrsearchresult.setdescriptionnosnippet(firstdatasetdescription); } } solrsearchresult.setdatasetversionid(datasetversionid); solrsearchresult.setcitation(citation); solrsearchresult.setcitationhtml(citationplainhtml); if (title != null) { solrsearchresult.settitle(title); } else { logger.fine("no title indexed. setting to empty string to prevent npe. dataset id " + entityid + " and version id " + datasetversionid); solrsearchresult.settitle(""); } list<string> authors = (list) solrdocument.getfieldvalues(datasetfieldconstant.authorname); if (authors != null) { solrsearchresult.setdatasetauthors(authors); } } else if (type.equals("files")) { string parentglobalid = null; object parentglobalidobject = solrdocument.getfieldvalue(searchfields.parent_identifier); if (parentglobalidobject != null) { parentglobalid = (string) parentglobalidobject; parent.put(solrsearchresult.parent_identifier, parentglobalid); } solrsearchresult.sethtmlurl(baseurl + "/dataset.xhtml?persistentid=" + parentglobalid); solrsearchresult.setdownloadurl(baseurl + "/api/access/datafile/" + entityid); solrsearchresult.setname(name); solrsearchresult.setfiletype(filetype); solrsearchresult.setfilecontenttype(filecontenttype); object filesizeinbytesobject = solrdocument.getfieldvalue(searchfields.file_size_in_bytes); if (filesizeinbytesobject != null) { try { long filesizeinbyteslong = (long) filesizeinbytesobject; solrsearchresult.setfilesizeinbytes(filesizeinbyteslong); } catch (classcastexception ex) { logger.info("could not cast file " + entityid + " to long for " + searchfields.file_size_in_bytes + ": " + ex.getlocalizedmessage()); } } solrsearchresult.setfilemd5((string) solrdocument.getfieldvalue(searchfields.file_md5)); try { solrsearchresult.setfilechecksumtype(datafile.checksumtype.fromstring((string) solrdocument.getfieldvalue(searchfields.file_checksum_type))); } catch (illegalargumentexception ex) { logger.info("exception setting setfilechecksumtype: " + ex); } solrsearchresult.setfilechecksumvalue((string) solrdocument.getfieldvalue(searchfields.file_checksum_value)); solrsearchresult.setunf((string) solrdocument.getfieldvalue(searchfields.unf)); solrsearchresult.setdatasetversionid(datasetversionid); list<string> filecategories = (list) solrdocument.getfieldvalues(searchfields.file_tag); if (filecategories != null) { solrsearchresult.setfilecategories(filecategories); } list<string> tabulardatatags = (list) solrdocument.getfieldvalues(searchfields.tabdata_tag); if (tabulardatatags != null) { collections.sort(tabulardatatags); solrsearchresult.settabulardatatags(tabulardatatags); } } parent.put("id", (string) solrdocument.getfieldvalue(searchfields.parent_id)); parent.put("name", (string) solrdocument.getfieldvalue(searchfields.parent_name)); parent.put("citation", (string) solrdocument.getfieldvalue(searchfields.parent_citation)); solrsearchresult.setparent(parent); solrsearchresults.add(solrsearchresult); } map<string, list<string>> spellingsuggestionsbytoken = new hashmap<>(); spellcheckresponse spellcheckresponse = queryresponse.getspellcheckresponse(); if (spellcheckresponse != null) { list<spellcheckresponse.suggestion> suggestions = spellcheckresponse.getsuggestions(); for (spellcheckresponse.suggestion suggestion : suggestions) { spellingsuggestionsbytoken.put(suggestion.gettoken(), suggestion.getalternatives()); } } list<facetcategory> facetcategorylist = new arraylist<>(); list<facetcategory> typefacetcategories = new arraylist<>(); boolean hidepublicationstatusfacet = true; boolean draftsavailable = false; boolean unpublishedavailable = false; boolean deaccessionedavailable = false; boolean hidemetadatasourcefacet = true; for (facetfield facetfield : queryresponse.getfacetfields()) { facetcategory facetcategory = new facetcategory(); list<facetlabel> facetlabellist = new arraylist<>(); int nummetadatasources = 0; for (facetfield.count facetfieldcount : facetfield.getvalues()) { if (facetfieldcount.getcount() > 0) { facetlabel facetlabel = new facetlabel(facetfieldcount.getname(), facetfieldcount.getcount()); facetlabel.setfilterquery(facetfield.getname() + ":\"" + facetfieldcount.getname() + "\""); facetlabellist.add(facetlabel); if (facetfield.getname().equals(searchfields.publication_status)) { if (facetlabel.getname().equals(indexservicebean.getunpublished_string())) { unpublishedavailable = true; } else if (facetlabel.getname().equals(indexservicebean.getdraft_string())) { draftsavailable = true; } else if (facetlabel.getname().equals(indexservicebean.getdeaccessioned_string())) { deaccessionedavailable = true; } } if (facetfield.getname().equals(searchfields.metadata_source)) { nummetadatasources++; } } } if (nummetadatasources > 1) { hidemetadatasourcefacet = false; } facetcategory.setname(facetfield.getname()); facetcategory.setfriendlyname(facetfield.getname()); for (datasetfieldtype datasetfield : datasetfields) { string solrfieldnamefordataset = datasetfield.getsolrfield().getnamefacetable(); string friendlyname = datasetfield.getdisplayname(); if (solrfieldnamefordataset != null && facetfield.getname().endswith(datasetfield.gettmpnullfieldtypeidentifier())) { facetcategory.setname(facetfield.getname()); } else if (solrfieldnamefordataset != null && facetfield.getname().equals(solrfieldnamefordataset)) { if (friendlyname != null && !friendlyname.isempty()) { facetcategory.setfriendlyname(friendlyname); break; } } datasetfieldfriendlynamesbysolrfield.put(datasetfield.getsolrfield().getnamefacetable(), friendlyname); } for (field fieldobject : staticsearchfields) { string name = fieldobject.getname(); string staticsearchfield = null; try { staticsearchfield = (string) fieldobject.get(searchfieldsobject); } catch (illegalargumentexception | illegalaccessexception ex) { logger.getlogger(searchservicebean.class.getname()).log(level.severe, null, ex); } if (staticsearchfield != null && facetfield.getname().equals(staticsearchfield)) { string[] parts = name.split("_"); stringbuilder stringbuilder = new stringbuilder(); for (string part : parts) { stringbuilder.append(getcapitalizedname(part.tolowercase()) + " "); } string friendlynamewithtrailingspace = stringbuilder.tostring(); string friendlyname = friendlynamewithtrailingspace.replaceall(" $", ""); facetcategory.setfriendlyname(friendlyname); staticsolrfieldfriendlynamesbysolrfield.put(staticsearchfield, friendlyname); break; } } facetcategory.setfacetlabel(facetlabellist); if (!facetlabellist.isempty()) { if (facetcategory.getname().equals(searchfields.type)) { typefacetcategories.add(facetcategory); } else if (facetcategory.getname().equals(searchfields.publication_status)) { if (unpublishedavailable || draftsavailable || deaccessionedavailable) { hidepublicationstatusfacet = false; } if (!hidepublicationstatusfacet) { facetcategorylist.add(facetcategory); } } else if (facetcategory.getname().equals(searchfields.metadata_source)) { if (!hidemetadatasourcefacet) { facetcategorylist.add(facetcategory); } } else { facetcategorylist.add(facetcategory); } } } for (rangefacet<string, string> rangefacet : queryresponse.getfacetranges()) { facetcategory facetcategory = new facetcategory(); list<facetlabel> facetlabellist = new arraylist<>(); for (object rfobj : rangefacet.getcounts()) { rangefacet.count rangefacetcount = (rangefacet.count) rfobj; string valuestring = rangefacetcount.getvalue(); integer start = integer.parseint(valuestring); integer end = start + integer.parseint(rangefacet.getgap().tostring()); end = end - 1; if (rangefacetcount.getcount() > 0) { facetlabel facetlabel = new facetlabel(start + "-" + end, new long(rangefacetcount.getcount())); facetlabel.setfilterquery(rangefacet.getname() + ":" + "[" + start + " to " + end + "]"); facetlabellist.add(facetlabel); } } facetcategory.setname(rangefacet.getname()); facetcategory.setfacetlabel(facetlabellist); list<facetlabel> facetlabellistreversed = new arraylist<>(); listiterator<facetlabel> li = facetlabellist.listiterator(facetlabellist.size()); while (li.hasprevious()) { facetlabellistreversed.add(li.previous()); } facetcategory.setfacetlabel(facetlabellistreversed); if (!facetlabellist.isempty()) { facetcategorylist.add(facetcategory); } } solrqueryresponse solrqueryresponse = new solrqueryresponse(solrquery); solrqueryresponse.setsolrsearchresults(solrsearchresults); solrqueryresponse.setspellingsuggestionsbytoken(spellingsuggestionsbytoken); solrqueryresponse.setfacetcategorylist(facetcategorylist); solrqueryresponse.settypefacetcategories(typefacetcategories); solrqueryresponse.setnumresultsfound(queryresponse.getresults().getnumfound()); solrqueryresponse.setresultsstart(queryresponse.getresults().getstart()); solrqueryresponse.setdatasetfieldfriendlynamesbysolrfield(datasetfieldfriendlynamesbysolrfield); solrqueryresponse.setstaticsolrfieldfriendlynamesbysolrfield(staticsolrfieldfriendlynamesbysolrfield); string[] filterqueriesarray = solrquery.getfilterqueries(); if (filterqueriesarray != null) { list<string> actualfilterqueries = arrays.aslist(filterqueriesarray); logger.fine("actual filter queries: " + actualfilterqueries); solrqueryresponse.setfilterqueriesactual(actualfilterqueries); } else { logger.info("solrquery.getfilterqueries() was null"); } solrqueryresponse.setdvobjectcounts(queryresponse.getfacetfield("dvobjecttype")); solrqueryresponse.setpublicationstatuscounts(queryresponse.getfacetfield("publicationstatus")); return solrqueryresponse; } | tkmonson/dataverse | [
1,
1,
1,
0
] |
1,664 | public AccumulatedAnimationValue getAccumulatedAnimationValue(AdditiveAnimation animation) {
// TODO: is there any way to make this `get()` faster?
AccumulatedAnimationValue accumulatedAnimationValue = accumulatedAnimationValues.get(animation);
if(accumulatedAnimationValue != null) {
return accumulatedAnimationValue;
}
accumulatedAnimationValue = new AccumulatedAnimationValue(animation);
accumulatedAnimationValues.put(animation, accumulatedAnimationValue);
return accumulatedAnimationValue;
} | public AccumulatedAnimationValue getAccumulatedAnimationValue(AdditiveAnimation animation) {
AccumulatedAnimationValue accumulatedAnimationValue = accumulatedAnimationValues.get(animation);
if(accumulatedAnimationValue != null) {
return accumulatedAnimationValue;
}
accumulatedAnimationValue = new AccumulatedAnimationValue(animation);
accumulatedAnimationValues.put(animation, accumulatedAnimationValue);
return accumulatedAnimationValue;
} | public accumulatedanimationvalue getaccumulatedanimationvalue(additiveanimation animation) { accumulatedanimationvalue accumulatedanimationvalue = accumulatedanimationvalues.get(animation); if(accumulatedanimationvalue != null) { return accumulatedanimationvalue; } accumulatedanimationvalue = new accumulatedanimationvalue(animation); accumulatedanimationvalues.put(animation, accumulatedanimationvalue); return accumulatedanimationvalue; } | wirecube/android_additive_animations | [
1,
0,
0,
0
] |
26,242 | public DialerCall getCallWithState(int state, int positionToFind) {
DialerCall retval = null;
int position = 0;
for (DialerCall call : callById.values()) {
if (call.getState() == state) {
if (position >= positionToFind) {
retval = call;
break;
} else {
position++;
}
}
}
return retval;
} | public DialerCall getCallWithState(int state, int positionToFind) {
DialerCall retval = null;
int position = 0;
for (DialerCall call : callById.values()) {
if (call.getState() == state) {
if (position >= positionToFind) {
retval = call;
break;
} else {
position++;
}
}
}
return retval;
} | public dialercall getcallwithstate(int state, int positiontofind) { dialercall retval = null; int position = 0; for (dialercall call : callbyid.values()) { if (call.getstate() == state) { if (position >= positiontofind) { retval = call; break; } else { position++; } } } return retval; } | unisoc-android/android_packages_apps_Dialer | [
1,
0,
0,
0
] |
18,099 | private void process(String str) {
QuotedStringTokenizer tok = new QuotedStringTokenizer(str);
String cmd = tok.nextToken().trim();
String retstr = "";
if (cmd.equals("no-op")) {
// Does nothing
}
// syntax: vnmrjcmd('SQ start [<macro>]')
else if (cmd.equals(START)) {
mgr.setExecuting(true);
mgr.setPaused(false);
}
// syntax: vnmrjcmd('SQ pause [<macro>]')
else if (cmd.equals(PAUSE)) {
mgr.setExecuting(false);
mgr.setPaused(true);
}
// syntax: vnmrjcmd('SQ stop [<macro>]')
else if (cmd.equals(STOP)) {
mgr.setExecuting(false);
mgr.setPaused(false);
}
// syntax: vnmrjcmd('SQ NormalMode [<macro>]')
else if (cmd.equalsIgnoreCase(NORMAL_MODE)) {
mgr.setMode(NORMAL_MODE);
}
// syntax: vnmrjcmd('SQ SubmitMode [<macro>]')
else if (cmd.equalsIgnoreCase(SUBMIT_MODE)) {
mgr.setMode(SUBMIT_MODE);
}
// syntax: vnmrjcmd('SQ read filename.xml [<macro>]')
else if (cmd.equals(READ)) {
String fn = tok.nextToken().trim();
if (mgr.isExecuting()) {
postWarning("cannot load a new study while queue is executing");
return;
} else {
String path = FileUtil.openPath(fn);
if (path == null) {
postError("cannot load study file " + fn);
return;
}
mgr.newTree(path);
// set sqdirs[jviewport]=path
sendSQpath(path);
}
}
// syntax: vnmrjcmd('SQ write filename.xml [<macro>]')
else if (cmd.equals(WRITE)) {
String fn = tok.nextToken().trim();
String path = FileUtil.savePath(fn);
if (path == null) {
postError("could not write study file " + fn);
return;
}
mgr.save(path);
// set sqdirs[jviewport]=path
sendSQpath(path);
}
// syntax: vnmrjcmd('SQ nwrite filename.xml [<macro>]')
else if (cmd.equals(NWRITE)) {
String id;
String path;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
if (tok.hasMoreTokens())
path = FileUtil.savePath(tok.nextToken().trim());
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
return;
}
mgr.writeElement(dst, path);
}
// syntax: vnmrjcmd('SQ setids')
else if (cmd.equals(SETIDS)) {
mgr.setIds();
}
// syntax: vnmrjcmd('SQ nesting = {true,false}")
else if (cmd.equals(NESTING)) {
String token;
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (!token.equals("=")) {
postError("syntax error " + "SQ " + str);
return;
}
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (token.equals("no") || token.equals("false"))
mgr.setAllowNesting(false);
else if (token.equals("yes") || token.equals("true"))
mgr.setAllowNesting(true);
}
// syntax: vnmrjcmd('SQ validate {move,copy,all,none}")
else if (cmd.equals(VALIDATE)) {
String token;
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
mgr.setValidateMove(false);
mgr.setValidateCopy(false);
if (token.equals("all")) {
mgr.setValidateMove(true);
mgr.setValidateCopy(true);
return;
} else if (token.equals("move")) {
mgr.setValidateMove(true);
return;
} else if (token.equals("copy")) {
mgr.setValidateCopy(true);
return;
} else if (token.equals("none")) {
mgr.setValidateMove(false);
mgr.setValidateCopy(false);
return;
} else {
postError("syntax error " + "SQ " + str);
return;
}
}
// syntax: vnmrjcmd('SQ delete <id>")
else if (cmd.equals(DELETE)) {
String id;
if (tok.hasMoreTokens())
id = tok.nextToken();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (getCondition(id) == ProtocolBuilder.ALL) {
mgr.clearTree();
// set sqdirs[jviewport]=''
sendSQpath("");
} else {
VElement obj = mgr.getElement(id);
if (obj == null) {
if ( ! id.equals("tmpstudy")) {
postError("node " + id + " not found " + "SQ " + cmd);
}
return;
}
mgr.deleteElement(obj);
}
}
else if (cmd.equals(ADD_QUEUE)) {
String queueDir = tok.nextToken();
mgr.addQueue(queueDir);
}
// syntax: vnmrjcmd('SQ add <file> [<cond>] [<dst>] [<macro>]')
// vnmrjcmd('SQ add new <type> [<cond>] [<dst>] [<macro>]')
else if (cmd.equals(ADD)) {
String id = tok.nextToken().trim();
String fn = null;
String type = "protocol";
if (id.equals("new")) {
type = tok.nextToken();
Messages.postDebug("SQ", "--- SQ ADD: type=" + type);
if (type.equals("action"))
fn = new_action_file;
else
fn = new_protocol_file;
} else
fn = id;
String path = FileUtil.openPath(fn);
if (path == null) {
postError("cannot read protocol file " + fn);
return;
}
id = null;
if (tok.hasMoreTokens()) {
id = tok.nextToken();
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
id = tok.nextToken().trim();
}
}
VElement dst;
if (id == null)
dst = mgr.lastElement();
else
dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
mgr.insertProtocol(dst, path);
mgr.setInsertMode(0);
new_elem = mgr.getSelected();
}
// syntax: vnmrjcmd('SQ move <src> [<cond>] <dst> [true,false] [<macro>]')
else if (cmd.equals(MOVE)) {
String id;
boolean ignorelock = false;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
// postError("insufficient command arguments SQ " + cmd);
return;
}
VElement src = mgr.getElement(id);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
// postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
if (tok.hasMoreTokens()) {
String s = tok.nextToken().trim();
if (s.equals("false"))
ignorelock = true;
else if (s.equals("true"))
ignorelock = false;
else
retstr = s;
}
mgr.moveElement(src, dst, ignorelock);
mgr.setInsertMode(0);
}
// syntax: vnmrjcmd('SQ {lmove,pmove} <src> [<cond>] <dst> [<macro>]')
else if (cmd.equals(PMOVE) || cmd.equals(LMOVE)) {
String id;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
VElement src = mgr.getElement(id);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
id = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
boolean bpmove = false;
if (cmd.equals(PMOVE))
bpmove = true;
boolean ballownesting = mgr.allowNesting();
if (bpmove && !ballownesting)
mgr.setAllowNesting(true);
ArrayList alist = (ArrayList) mgr.getHiddenNodes().clone();
if (!bpmove)
mgr.showElementAll("true");
mgr.moveElement(src, dst, true);
mgr.setHiddenNodes(alist);
if (bpmove)
mgr.setAllowNesting(ballownesting);
else
mgr.hideElements();
mgr.setInsertMode(0);
}
// syntax: vnmrjcmd('SQ show <attr> <id> [<macro>]')
else if (cmd.equals(SHOW)) {
String value;
if (tok.hasMoreTokens())
value = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
ArrayList aListElem = new ArrayList();
while (tok.hasMoreTokens()) {
String id = tok.nextToken().trim();
VElement src = mgr.getElement(id);
if (src == null)
{
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
}
else
{
aListElem.add(src);
}
}
mgr.showElement(aListElem, value);
}
// syntax: vnmrjcmd('SQ copy <id> <cond> <dst> [<macro>]')
else if (cmd.equals(COPY)) {
String id_src;
String id_dst;
if (tok.hasMoreTokens())
id_src = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
if (tok.hasMoreTokens())
id_dst = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id_dst);
if (cond != 0) {
mgr.setInsertMode(cond);
id_dst = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id_dst);
if (dst == null) {
if ( ! id_dst.equals("tmpstudy"))
postError("invalid node id " + id_dst);
return;
}
VElement src = mgr.getElement(id_src);
if (src == null) {
src = mgr.readElement(id_src, dst);
if (src == null) {
if ( ! id_src.equals("tmpstudy"))
postError("invalid node id " + id_src);
return;
}
} else
mgr.copyElement(src, dst);
}
// syntax: vnmrjcmd('SQ {get,set} <type> [<cond> <id>] <attr> <val> [<macro>]')
else if (cmd.equals(SET) || cmd.equals(GET)) {
String arg;
// first token
if (tok.hasMoreTokens())
arg = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
// second token
if (!tok.hasMoreTokens()) {
postError("insufficient command arguments SQ " + cmd);
return;
}
int type = 0;
int scope = 0;
int cond = getCondition(arg);
String apar = null;
String vpar = null;
String id = null;
VElement obj = null;
switch (cond) {
case ProtocolBuilder.FIRST:
case ProtocolBuilder.ALL:
arg = tok.nextToken();
type = getType(arg);
scope = getScope(arg);
apar = tok.nextToken();
vpar = tok.nextToken();
break;
default:
type = getType(arg);
if (type == 0 || type == ProtocolBuilder.NEW) {
if (type == ProtocolBuilder.NEW) {
if (new_elem == null) {
postError("must call SQ add before using new");
return;
}
obj = new_elem;
} else {
// e.g. set p2.a2 Lock on
obj = mgr.getElement(arg);
if (obj == null) {
// NB: This can happen when chempack adds protocols
// Ugly but harmless error
Messages.postDebug("SQ",
"unknown identifier SQ " + str);
return;
}
}
cond = ProtocolBuilder.ONE;
type = ProtocolBuilder.ANY;
scope = SINGLE;
} else {
// e.g. set actions > p2.a2 Lock on
scope = getScope(arg);
arg = tok.nextToken().trim();
cond = getCondition(arg);
if (scope == SINGLE) {
// e.g. set actions after p2.a2 Lock on
if (cond == ProtocolBuilder.GT)
cond = ProtocolBuilder.AFTER;
else if (cond == ProtocolBuilder.LT)
cond = ProtocolBuilder.BEFORE;
}
if (cond == 0) {
id = arg;
cond = ProtocolBuilder.ONE;
} else
id = tok.nextToken();
obj = mgr.getElement(id);
}
apar = tok.nextToken();
vpar = tok.nextToken();
if (vpar.startsWith("\"")) {
try {
vpar = vpar.substring(1) + tok.nextToken("\"");
} catch (NoSuchElementException e) {
vpar = vpar.substring(1, vpar.length() - 1);
}
}
break;
} // switch
if (apar == null || vpar == null) {
postError("syntax error " + "SQ " + str);
return;
}
ArrayList list;
// looking for nodes in id will return a null list if id does not exist
if ((obj == null) && (cond == ProtocolBuilder.EQ) )
list = new ArrayList();
else
list = mgr.getElements(obj, cond, type);
if (cmd.equals(SET)) {
for (int i = 0; i < list.size(); i++) {
obj = (VElement) list.get(i);
mgr.setAttribute(obj, apar, vpar);
}
//mgr.invalidateTree();
} else { // get
if (scope == SINGLE) {
if (list.size() > 1) {
postError("syntax error " + "SQ " + str);
return;
}
String alist = apar + "=`";
String vlist = vpar + "=`";
if (list.size() == 1) {
obj = (VElement) list.get(0);
list = mgr.getAttributes(obj);
for (int i = 0; i < list.size(); i += 2) {
String name = (String) list.get(i);
String value = (String) list.get(i + 1);
alist += name;
vlist += value;
if (i < list.size() - 2) {
alist += "`,`";
vlist += "`,`";
}
}
}
alist += "`";
vlist += "`";
retstr = alist + " " + vlist;
} else {
retstr = vpar + "=`";
for (int i = 0; i < list.size(); i++) {
obj = (VElement) list.get(i);
String value = obj.getAttribute(apar);
retstr += value;
if (i < list.size() - 1)
retstr += "`,`";
}
retstr += "`";
}
}
} else if (cmd.equals(WATCH)) {
// E.g.: vnmrjcmd('SQ watch auto ', cursqexp, autodir, svfdir)
ArrayList<String> args = new ArrayList<String>();
while (tok.hasMoreTokens()) {
args.add(tok.nextToken());
}
if (!SQUpdater.processCommand(this, args.toArray(new String[0]))) {
Messages.postDebug("Bad format for 'watch' cmd: " + str);
}
// if (tok.countTokens() != 3) {
// Messages.postDebug("Bad format for 'watch' cmd: " + str);
// } else {
// String studydir = tok.nextToken();
// String autodir = tok.nextToken();
// String datadir = tok.nextToken();
// SQUpdater.startUpdates(this, studydir, autodir, datadir);
// }
} else {
postError("command not recognized " + "SQ " + cmd);
return;
}
while (tok.hasMoreTokens())
retstr += " " + tok.nextToken().trim();
if (retstr.length() > 0) {
setDebug(retstr);
Util.sendToVnmr(retstr);
}
} | private void process(String str) {
QuotedStringTokenizer tok = new QuotedStringTokenizer(str);
String cmd = tok.nextToken().trim();
String retstr = "";
if (cmd.equals("no-op")) {
}
else if (cmd.equals(START)) {
mgr.setExecuting(true);
mgr.setPaused(false);
}
else if (cmd.equals(PAUSE)) {
mgr.setExecuting(false);
mgr.setPaused(true);
}
else if (cmd.equals(STOP)) {
mgr.setExecuting(false);
mgr.setPaused(false);
}
else if (cmd.equalsIgnoreCase(NORMAL_MODE)) {
mgr.setMode(NORMAL_MODE);
}
else if (cmd.equalsIgnoreCase(SUBMIT_MODE)) {
mgr.setMode(SUBMIT_MODE);
}
else if (cmd.equals(READ)) {
String fn = tok.nextToken().trim();
if (mgr.isExecuting()) {
postWarning("cannot load a new study while queue is executing");
return;
} else {
String path = FileUtil.openPath(fn);
if (path == null) {
postError("cannot load study file " + fn);
return;
}
mgr.newTree(path);
sendSQpath(path);
}
}
else if (cmd.equals(WRITE)) {
String fn = tok.nextToken().trim();
String path = FileUtil.savePath(fn);
if (path == null) {
postError("could not write study file " + fn);
return;
}
mgr.save(path);
sendSQpath(path);
}
else if (cmd.equals(NWRITE)) {
String id;
String path;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
if (tok.hasMoreTokens())
path = FileUtil.savePath(tok.nextToken().trim());
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
return;
}
mgr.writeElement(dst, path);
}
else if (cmd.equals(SETIDS)) {
mgr.setIds();
}
else if (cmd.equals(NESTING)) {
String token;
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (!token.equals("=")) {
postError("syntax error " + "SQ " + str);
return;
}
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (token.equals("no") || token.equals("false"))
mgr.setAllowNesting(false);
else if (token.equals("yes") || token.equals("true"))
mgr.setAllowNesting(true);
}
else if (cmd.equals(VALIDATE)) {
String token;
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
mgr.setValidateMove(false);
mgr.setValidateCopy(false);
if (token.equals("all")) {
mgr.setValidateMove(true);
mgr.setValidateCopy(true);
return;
} else if (token.equals("move")) {
mgr.setValidateMove(true);
return;
} else if (token.equals("copy")) {
mgr.setValidateCopy(true);
return;
} else if (token.equals("none")) {
mgr.setValidateMove(false);
mgr.setValidateCopy(false);
return;
} else {
postError("syntax error " + "SQ " + str);
return;
}
}
else if (cmd.equals(DELETE)) {
String id;
if (tok.hasMoreTokens())
id = tok.nextToken();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (getCondition(id) == ProtocolBuilder.ALL) {
mgr.clearTree();
sendSQpath("");
} else {
VElement obj = mgr.getElement(id);
if (obj == null) {
if ( ! id.equals("tmpstudy")) {
postError("node " + id + " not found " + "SQ " + cmd);
}
return;
}
mgr.deleteElement(obj);
}
}
else if (cmd.equals(ADD_QUEUE)) {
String queueDir = tok.nextToken();
mgr.addQueue(queueDir);
}
else if (cmd.equals(ADD)) {
String id = tok.nextToken().trim();
String fn = null;
String type = "protocol";
if (id.equals("new")) {
type = tok.nextToken();
Messages.postDebug("SQ", "--- SQ ADD: type=" + type);
if (type.equals("action"))
fn = new_action_file;
else
fn = new_protocol_file;
} else
fn = id;
String path = FileUtil.openPath(fn);
if (path == null) {
postError("cannot read protocol file " + fn);
return;
}
id = null;
if (tok.hasMoreTokens()) {
id = tok.nextToken();
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
id = tok.nextToken().trim();
}
}
VElement dst;
if (id == null)
dst = mgr.lastElement();
else
dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
mgr.insertProtocol(dst, path);
mgr.setInsertMode(0);
new_elem = mgr.getSelected();
}
else if (cmd.equals(MOVE)) {
String id;
boolean ignorelock = false;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
return;
}
VElement src = mgr.getElement(id);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
return;
}
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
if (tok.hasMoreTokens()) {
String s = tok.nextToken().trim();
if (s.equals("false"))
ignorelock = true;
else if (s.equals("true"))
ignorelock = false;
else
retstr = s;
}
mgr.moveElement(src, dst, ignorelock);
mgr.setInsertMode(0);
}
else if (cmd.equals(PMOVE) || cmd.equals(LMOVE)) {
String id;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
VElement src = mgr.getElement(id);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
id = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
boolean bpmove = false;
if (cmd.equals(PMOVE))
bpmove = true;
boolean ballownesting = mgr.allowNesting();
if (bpmove && !ballownesting)
mgr.setAllowNesting(true);
ArrayList alist = (ArrayList) mgr.getHiddenNodes().clone();
if (!bpmove)
mgr.showElementAll("true");
mgr.moveElement(src, dst, true);
mgr.setHiddenNodes(alist);
if (bpmove)
mgr.setAllowNesting(ballownesting);
else
mgr.hideElements();
mgr.setInsertMode(0);
}
else if (cmd.equals(SHOW)) {
String value;
if (tok.hasMoreTokens())
value = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
ArrayList aListElem = new ArrayList();
while (tok.hasMoreTokens()) {
String id = tok.nextToken().trim();
VElement src = mgr.getElement(id);
if (src == null)
{
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
}
else
{
aListElem.add(src);
}
}
mgr.showElement(aListElem, value);
}
else if (cmd.equals(COPY)) {
String id_src;
String id_dst;
if (tok.hasMoreTokens())
id_src = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
if (tok.hasMoreTokens())
id_dst = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id_dst);
if (cond != 0) {
mgr.setInsertMode(cond);
id_dst = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id_dst);
if (dst == null) {
if ( ! id_dst.equals("tmpstudy"))
postError("invalid node id " + id_dst);
return;
}
VElement src = mgr.getElement(id_src);
if (src == null) {
src = mgr.readElement(id_src, dst);
if (src == null) {
if ( ! id_src.equals("tmpstudy"))
postError("invalid node id " + id_src);
return;
}
} else
mgr.copyElement(src, dst);
}
else if (cmd.equals(SET) || cmd.equals(GET)) {
String arg;
if (tok.hasMoreTokens())
arg = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
if (!tok.hasMoreTokens()) {
postError("insufficient command arguments SQ " + cmd);
return;
}
int type = 0;
int scope = 0;
int cond = getCondition(arg);
String apar = null;
String vpar = null;
String id = null;
VElement obj = null;
switch (cond) {
case ProtocolBuilder.FIRST:
case ProtocolBuilder.ALL:
arg = tok.nextToken();
type = getType(arg);
scope = getScope(arg);
apar = tok.nextToken();
vpar = tok.nextToken();
break;
default:
type = getType(arg);
if (type == 0 || type == ProtocolBuilder.NEW) {
if (type == ProtocolBuilder.NEW) {
if (new_elem == null) {
postError("must call SQ add before using new");
return;
}
obj = new_elem;
} else {
obj = mgr.getElement(arg);
if (obj == null) {
Messages.postDebug("SQ",
"unknown identifier SQ " + str);
return;
}
}
cond = ProtocolBuilder.ONE;
type = ProtocolBuilder.ANY;
scope = SINGLE;
} else {
scope = getScope(arg);
arg = tok.nextToken().trim();
cond = getCondition(arg);
if (scope == SINGLE) {
if (cond == ProtocolBuilder.GT)
cond = ProtocolBuilder.AFTER;
else if (cond == ProtocolBuilder.LT)
cond = ProtocolBuilder.BEFORE;
}
if (cond == 0) {
id = arg;
cond = ProtocolBuilder.ONE;
} else
id = tok.nextToken();
obj = mgr.getElement(id);
}
apar = tok.nextToken();
vpar = tok.nextToken();
if (vpar.startsWith("\"")) {
try {
vpar = vpar.substring(1) + tok.nextToken("\"");
} catch (NoSuchElementException e) {
vpar = vpar.substring(1, vpar.length() - 1);
}
}
break;
}
if (apar == null || vpar == null) {
postError("syntax error " + "SQ " + str);
return;
}
ArrayList list;
if ((obj == null) && (cond == ProtocolBuilder.EQ) )
list = new ArrayList();
else
list = mgr.getElements(obj, cond, type);
if (cmd.equals(SET)) {
for (int i = 0; i < list.size(); i++) {
obj = (VElement) list.get(i);
mgr.setAttribute(obj, apar, vpar);
}
} else {
if (scope == SINGLE) {
if (list.size() > 1) {
postError("syntax error " + "SQ " + str);
return;
}
String alist = apar + "=`";
String vlist = vpar + "=`";
if (list.size() == 1) {
obj = (VElement) list.get(0);
list = mgr.getAttributes(obj);
for (int i = 0; i < list.size(); i += 2) {
String name = (String) list.get(i);
String value = (String) list.get(i + 1);
alist += name;
vlist += value;
if (i < list.size() - 2) {
alist += "`,`";
vlist += "`,`";
}
}
}
alist += "`";
vlist += "`";
retstr = alist + " " + vlist;
} else {
retstr = vpar + "=`";
for (int i = 0; i < list.size(); i++) {
obj = (VElement) list.get(i);
String value = obj.getAttribute(apar);
retstr += value;
if (i < list.size() - 1)
retstr += "`,`";
}
retstr += "`";
}
}
} else if (cmd.equals(WATCH)) {
ArrayList<String> args = new ArrayList<String>();
while (tok.hasMoreTokens()) {
args.add(tok.nextToken());
}
if (!SQUpdater.processCommand(this, args.toArray(new String[0]))) {
Messages.postDebug("Bad format for 'watch' cmd: " + str);
}
} else {
postError("command not recognized " + "SQ " + cmd);
return;
}
while (tok.hasMoreTokens())
retstr += " " + tok.nextToken().trim();
if (retstr.length() > 0) {
setDebug(retstr);
Util.sendToVnmr(retstr);
}
} | private void process(string str) { quotedstringtokenizer tok = new quotedstringtokenizer(str); string cmd = tok.nexttoken().trim(); string retstr = ""; if (cmd.equals("no-op")) { } else if (cmd.equals(start)) { mgr.setexecuting(true); mgr.setpaused(false); } else if (cmd.equals(pause)) { mgr.setexecuting(false); mgr.setpaused(true); } else if (cmd.equals(stop)) { mgr.setexecuting(false); mgr.setpaused(false); } else if (cmd.equalsignorecase(normal_mode)) { mgr.setmode(normal_mode); } else if (cmd.equalsignorecase(submit_mode)) { mgr.setmode(submit_mode); } else if (cmd.equals(read)) { string fn = tok.nexttoken().trim(); if (mgr.isexecuting()) { postwarning("cannot load a new study while queue is executing"); return; } else { string path = fileutil.openpath(fn); if (path == null) { posterror("cannot load study file " + fn); return; } mgr.newtree(path); sendsqpath(path); } } else if (cmd.equals(write)) { string fn = tok.nexttoken().trim(); string path = fileutil.savepath(fn); if (path == null) { posterror("could not write study file " + fn); return; } mgr.save(path); sendsqpath(path); } else if (cmd.equals(nwrite)) { string id; string path; if (tok.hasmoretokens()) id = tok.nexttoken().trim(); else { posterror("insufficient command arguments sq " + cmd); return; } if (tok.hasmoretokens()) path = fileutil.savepath(tok.nexttoken().trim()); else { posterror("insufficient command arguments sq " + cmd); return; } velement dst = mgr.getelement(id); if (dst == null) { if ( ! id.equals("tmpstudy")) posterror("invalid node id " + id); return; } mgr.writeelement(dst, path); } else if (cmd.equals(setids)) { mgr.setids(); } else if (cmd.equals(nesting)) { string token; if (tok.hasmoretokens()) token = tok.nexttoken().trim(); else { posterror("insufficient command arguments " + "sq " + cmd); return; } if (!token.equals("=")) { posterror("syntax error " + "sq " + str); return; } if (tok.hasmoretokens()) token = tok.nexttoken().trim(); else { posterror("insufficient command arguments " + "sq " + cmd); return; } if (token.equals("no") || token.equals("false")) mgr.setallownesting(false); else if (token.equals("yes") || token.equals("true")) mgr.setallownesting(true); } else if (cmd.equals(validate)) { string token; if (tok.hasmoretokens()) token = tok.nexttoken().trim(); else { posterror("insufficient command arguments " + "sq " + cmd); return; } mgr.setvalidatemove(false); mgr.setvalidatecopy(false); if (token.equals("all")) { mgr.setvalidatemove(true); mgr.setvalidatecopy(true); return; } else if (token.equals("move")) { mgr.setvalidatemove(true); return; } else if (token.equals("copy")) { mgr.setvalidatecopy(true); return; } else if (token.equals("none")) { mgr.setvalidatemove(false); mgr.setvalidatecopy(false); return; } else { posterror("syntax error " + "sq " + str); return; } } else if (cmd.equals(delete)) { string id; if (tok.hasmoretokens()) id = tok.nexttoken(); else { posterror("insufficient command arguments " + "sq " + cmd); return; } if (getcondition(id) == protocolbuilder.all) { mgr.cleartree(); sendsqpath(""); } else { velement obj = mgr.getelement(id); if (obj == null) { if ( ! id.equals("tmpstudy")) { posterror("node " + id + " not found " + "sq " + cmd); } return; } mgr.deleteelement(obj); } } else if (cmd.equals(add_queue)) { string queuedir = tok.nexttoken(); mgr.addqueue(queuedir); } else if (cmd.equals(add)) { string id = tok.nexttoken().trim(); string fn = null; string type = "protocol"; if (id.equals("new")) { type = tok.nexttoken(); messages.postdebug("sq", "--- sq add: type=" + type); if (type.equals("action")) fn = new_action_file; else fn = new_protocol_file; } else fn = id; string path = fileutil.openpath(fn); if (path == null) { posterror("cannot read protocol file " + fn); return; } id = null; if (tok.hasmoretokens()) { id = tok.nexttoken(); int cond = getcondition(id); if (cond != 0) { mgr.setinsertmode(cond); id = tok.nexttoken().trim(); } } velement dst; if (id == null) dst = mgr.lastelement(); else dst = mgr.getelement(id); if (dst == null) { if ( ! id.equals("tmpstudy")) posterror("invalid node id " + id); mgr.setinsertmode(0); return; } mgr.insertprotocol(dst, path); mgr.setinsertmode(0); new_elem = mgr.getselected(); } else if (cmd.equals(move)) { string id; boolean ignorelock = false; if (tok.hasmoretokens()) id = tok.nexttoken().trim(); else { return; } velement src = mgr.getelement(id); if (tok.hasmoretokens()) id = tok.nexttoken().trim(); else { return; } int cond = getcondition(id); if (cond != 0) { mgr.setinsertmode(cond); if (tok.hasmoretokens()) id = tok.nexttoken().trim(); } velement dst = mgr.getelement(id); if (dst == null) { if ( ! id.equals("tmpstudy")) posterror("invalid node id " + id); mgr.setinsertmode(0); return; } if (tok.hasmoretokens()) { string s = tok.nexttoken().trim(); if (s.equals("false")) ignorelock = true; else if (s.equals("true")) ignorelock = false; else retstr = s; } mgr.moveelement(src, dst, ignorelock); mgr.setinsertmode(0); } else if (cmd.equals(pmove) || cmd.equals(lmove)) { string id; if (tok.hasmoretokens()) id = tok.nexttoken().trim(); else { posterror("insufficient command arguments sq " + cmd); return; } velement src = mgr.getelement(id); if (tok.hasmoretokens()) id = tok.nexttoken().trim(); else { posterror("insufficient command arguments sq " + cmd); return; } int cond = getcondition(id); if (cond != 0) { mgr.setinsertmode(cond); id = tok.nexttoken().trim(); } velement dst = mgr.getelement(id); if (dst == null) { if ( ! id.equals("tmpstudy")) posterror("invalid node id " + id); mgr.setinsertmode(0); return; } boolean bpmove = false; if (cmd.equals(pmove)) bpmove = true; boolean ballownesting = mgr.allownesting(); if (bpmove && !ballownesting) mgr.setallownesting(true); arraylist alist = (arraylist) mgr.gethiddennodes().clone(); if (!bpmove) mgr.showelementall("true"); mgr.moveelement(src, dst, true); mgr.sethiddennodes(alist); if (bpmove) mgr.setallownesting(ballownesting); else mgr.hideelements(); mgr.setinsertmode(0); } else if (cmd.equals(show)) { string value; if (tok.hasmoretokens()) value = tok.nexttoken().trim(); else { posterror("insufficient command arguments sq " + cmd); return; } arraylist alistelem = new arraylist(); while (tok.hasmoretokens()) { string id = tok.nexttoken().trim(); velement src = mgr.getelement(id); if (src == null) { if ( ! id.equals("tmpstudy")) posterror("invalid node id " + id); } else { alistelem.add(src); } } mgr.showelement(alistelem, value); } else if (cmd.equals(copy)) { string id_src; string id_dst; if (tok.hasmoretokens()) id_src = tok.nexttoken().trim(); else { posterror("insufficient command arguments sq " + cmd); return; } if (tok.hasmoretokens()) id_dst = tok.nexttoken().trim(); else { posterror("insufficient command arguments sq " + cmd); return; } int cond = getcondition(id_dst); if (cond != 0) { mgr.setinsertmode(cond); id_dst = tok.nexttoken().trim(); } velement dst = mgr.getelement(id_dst); if (dst == null) { if ( ! id_dst.equals("tmpstudy")) posterror("invalid node id " + id_dst); return; } velement src = mgr.getelement(id_src); if (src == null) { src = mgr.readelement(id_src, dst); if (src == null) { if ( ! id_src.equals("tmpstudy")) posterror("invalid node id " + id_src); return; } } else mgr.copyelement(src, dst); } else if (cmd.equals(set) || cmd.equals(get)) { string arg; if (tok.hasmoretokens()) arg = tok.nexttoken().trim(); else { posterror("insufficient command arguments sq " + cmd); return; } if (!tok.hasmoretokens()) { posterror("insufficient command arguments sq " + cmd); return; } int type = 0; int scope = 0; int cond = getcondition(arg); string apar = null; string vpar = null; string id = null; velement obj = null; switch (cond) { case protocolbuilder.first: case protocolbuilder.all: arg = tok.nexttoken(); type = gettype(arg); scope = getscope(arg); apar = tok.nexttoken(); vpar = tok.nexttoken(); break; default: type = gettype(arg); if (type == 0 || type == protocolbuilder.new) { if (type == protocolbuilder.new) { if (new_elem == null) { posterror("must call sq add before using new"); return; } obj = new_elem; } else { obj = mgr.getelement(arg); if (obj == null) { messages.postdebug("sq", "unknown identifier sq " + str); return; } } cond = protocolbuilder.one; type = protocolbuilder.any; scope = single; } else { scope = getscope(arg); arg = tok.nexttoken().trim(); cond = getcondition(arg); if (scope == single) { if (cond == protocolbuilder.gt) cond = protocolbuilder.after; else if (cond == protocolbuilder.lt) cond = protocolbuilder.before; } if (cond == 0) { id = arg; cond = protocolbuilder.one; } else id = tok.nexttoken(); obj = mgr.getelement(id); } apar = tok.nexttoken(); vpar = tok.nexttoken(); if (vpar.startswith("\"")) { try { vpar = vpar.substring(1) + tok.nexttoken("\""); } catch (nosuchelementexception e) { vpar = vpar.substring(1, vpar.length() - 1); } } break; } if (apar == null || vpar == null) { posterror("syntax error " + "sq " + str); return; } arraylist list; if ((obj == null) && (cond == protocolbuilder.eq) ) list = new arraylist(); else list = mgr.getelements(obj, cond, type); if (cmd.equals(set)) { for (int i = 0; i < list.size(); i++) { obj = (velement) list.get(i); mgr.setattribute(obj, apar, vpar); } } else { if (scope == single) { if (list.size() > 1) { posterror("syntax error " + "sq " + str); return; } string alist = apar + "=`"; string vlist = vpar + "=`"; if (list.size() == 1) { obj = (velement) list.get(0); list = mgr.getattributes(obj); for (int i = 0; i < list.size(); i += 2) { string name = (string) list.get(i); string value = (string) list.get(i + 1); alist += name; vlist += value; if (i < list.size() - 2) { alist += "`,`"; vlist += "`,`"; } } } alist += "`"; vlist += "`"; retstr = alist + " " + vlist; } else { retstr = vpar + "=`"; for (int i = 0; i < list.size(); i++) { obj = (velement) list.get(i); string value = obj.getattribute(apar); retstr += value; if (i < list.size() - 1) retstr += "`,`"; } retstr += "`"; } } } else if (cmd.equals(watch)) { arraylist<string> args = new arraylist<string>(); while (tok.hasmoretokens()) { args.add(tok.nexttoken()); } if (!squpdater.processcommand(this, args.toarray(new string[0]))) { messages.postdebug("bad format for 'watch' cmd: " + str); } } else { posterror("command not recognized " + "sq " + cmd); return; } while (tok.hasmoretokens()) retstr += " " + tok.nexttoken().trim(); if (retstr.length() > 0) { setdebug(retstr); util.sendtovnmr(retstr); } } | timburrow/openvnmrj-source | [
1,
0,
0,
0
] |
1,780 | @Override
public boolean onTouch(View v, MotionEvent event) {
Layout layout = ((TextView) v).getLayout();
if (layout == null) {
return false;
}
int x = (int) event.getX();
int y = (int) event.getY();
int line = layout.getLineForVertical(y);
int offset = layout.getOffsetForHorizontal(line, x);
TextView tv = (TextView) v;
SpannableString value = SpannableString.valueOf(tv.getText());
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
MyURLSpan[] urlSpans = value.getSpans(0, value.length(), MyURLSpan.class);
int findStart = 0;
int findEnd = 0;
for (MyURLSpan urlSpan : urlSpans) {
int start = value.getSpanStart(urlSpan);
int end = value.getSpanEnd(urlSpan);
if (start <= offset && offset <= end) {
find = true;
findStart = start;
findEnd = end;
break;
}
}
float lineWidth = layout.getLineWidth(line);
find &= (lineWidth >= x);
if (find) {
LongClickableLinkMovementMethod.getInstance().onTouchEvent(tv, value, event);
BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(0xFFE9E9E9);
value.setSpan(backgroundColorSpan, findStart, findEnd,
Spanned.SPAN_INCLUSIVE_INCLUSIVE);
//Android has a bug, sometime TextView wont change its value when you modify SpannableString,
// so you must setText again, test on Android 4.3 Nexus4
tv.setText(value);
}
return find;
case MotionEvent.ACTION_MOVE:
if (find) {
LongClickableLinkMovementMethod.getInstance().onTouchEvent(tv, value, event);
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (find) {
LongClickableLinkMovementMethod.getInstance().onTouchEvent(tv, value, event);
LongClickableLinkMovementMethod.getInstance().removeLongClickCallback();
BackgroundColorSpan[] backgroundColorSpans = value
.getSpans(0, value.length(), BackgroundColorSpan.class);
for (BackgroundColorSpan backgroundColorSpan : backgroundColorSpans) {
value.removeSpan(backgroundColorSpan);
}
tv.setText(value);
find = false;
}
break;
}
return false;
} | @Override
public boolean onTouch(View v, MotionEvent event) {
Layout layout = ((TextView) v).getLayout();
if (layout == null) {
return false;
}
int x = (int) event.getX();
int y = (int) event.getY();
int line = layout.getLineForVertical(y);
int offset = layout.getOffsetForHorizontal(line, x);
TextView tv = (TextView) v;
SpannableString value = SpannableString.valueOf(tv.getText());
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
MyURLSpan[] urlSpans = value.getSpans(0, value.length(), MyURLSpan.class);
int findStart = 0;
int findEnd = 0;
for (MyURLSpan urlSpan : urlSpans) {
int start = value.getSpanStart(urlSpan);
int end = value.getSpanEnd(urlSpan);
if (start <= offset && offset <= end) {
find = true;
findStart = start;
findEnd = end;
break;
}
}
float lineWidth = layout.getLineWidth(line);
find &= (lineWidth >= x);
if (find) {
LongClickableLinkMovementMethod.getInstance().onTouchEvent(tv, value, event);
BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(0xFFE9E9E9);
value.setSpan(backgroundColorSpan, findStart, findEnd,
Spanned.SPAN_INCLUSIVE_INCLUSIVE);
tv.setText(value);
}
return find;
case MotionEvent.ACTION_MOVE:
if (find) {
LongClickableLinkMovementMethod.getInstance().onTouchEvent(tv, value, event);
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (find) {
LongClickableLinkMovementMethod.getInstance().onTouchEvent(tv, value, event);
LongClickableLinkMovementMethod.getInstance().removeLongClickCallback();
BackgroundColorSpan[] backgroundColorSpans = value
.getSpans(0, value.length(), BackgroundColorSpan.class);
for (BackgroundColorSpan backgroundColorSpan : backgroundColorSpans) {
value.removeSpan(backgroundColorSpan);
}
tv.setText(value);
find = false;
}
break;
}
return false;
} | @override public boolean ontouch(view v, motionevent event) { layout layout = ((textview) v).getlayout(); if (layout == null) { return false; } int x = (int) event.getx(); int y = (int) event.gety(); int line = layout.getlineforvertical(y); int offset = layout.getoffsetforhorizontal(line, x); textview tv = (textview) v; spannablestring value = spannablestring.valueof(tv.gettext()); switch (event.getactionmasked()) { case motionevent.action_down: myurlspan[] urlspans = value.getspans(0, value.length(), myurlspan.class); int findstart = 0; int findend = 0; for (myurlspan urlspan : urlspans) { int start = value.getspanstart(urlspan); int end = value.getspanend(urlspan); if (start <= offset && offset <= end) { find = true; findstart = start; findend = end; break; } } float linewidth = layout.getlinewidth(line); find &= (linewidth >= x); if (find) { longclickablelinkmovementmethod.getinstance().ontouchevent(tv, value, event); backgroundcolorspan backgroundcolorspan = new backgroundcolorspan(0xffe9e9e9); value.setspan(backgroundcolorspan, findstart, findend, spanned.span_inclusive_inclusive); tv.settext(value); } return find; case motionevent.action_move: if (find) { longclickablelinkmovementmethod.getinstance().ontouchevent(tv, value, event); } break; case motionevent.action_cancel: case motionevent.action_up: if (find) { longclickablelinkmovementmethod.getinstance().ontouchevent(tv, value, event); longclickablelinkmovementmethod.getinstance().removelongclickcallback(); backgroundcolorspan[] backgroundcolorspans = value .getspans(0, value.length(), backgroundcolorspan.class); for (backgroundcolorspan backgroundcolorspan : backgroundcolorspans) { value.removespan(backgroundcolorspan); } tv.settext(value); find = false; } break; } return false; } | zhe525069676/WeiBoLayout | [
0,
0,
1,
0
] |
34,679 | @Override
public Subscriber getSubscriber(Set<? extends ConfigKey<?>> configKeys) {
Set<ConfigKey<ConfigInstance>> subscriptionKeys = new HashSet<>();
for(ConfigKey<?> key: configKeys) {
@SuppressWarnings("unchecked") // ConfigKey is defined as <CONFIGCLASS extends ConfigInstance>
ConfigKey<ConfigInstance> invariant = (ConfigKey<ConfigInstance>) key;
subscriptionKeys.add(invariant);
}
CloudSubscriber subscriber = new CloudSubscriber(subscriptionKeys, configSource);
testGeneration.ifPresent(subscriber.subscriber::reload); // TODO: test specific code, remove
activeSubscribers.put(subscriber, 0);
return subscriber;
} | @Override
public Subscriber getSubscriber(Set<? extends ConfigKey<?>> configKeys) {
Set<ConfigKey<ConfigInstance>> subscriptionKeys = new HashSet<>();
for(ConfigKey<?> key: configKeys) {
@SuppressWarnings("unchecked")
ConfigKey<ConfigInstance> invariant = (ConfigKey<ConfigInstance>) key;
subscriptionKeys.add(invariant);
}
CloudSubscriber subscriber = new CloudSubscriber(subscriptionKeys, configSource);
testGeneration.ifPresent(subscriber.subscriber::reload);
activeSubscribers.put(subscriber, 0);
return subscriber;
} | @override public subscriber getsubscriber(set<? extends configkey<?>> configkeys) { set<configkey<configinstance>> subscriptionkeys = new hashset<>(); for(configkey<?> key: configkeys) { @suppresswarnings("unchecked") configkey<configinstance> invariant = (configkey<configinstance>) key; subscriptionkeys.add(invariant); } cloudsubscriber subscriber = new cloudsubscriber(subscriptionkeys, configsource); testgeneration.ifpresent(subscriber.subscriber::reload); activesubscribers.put(subscriber, 0); return subscriber; } | yehzu/vespa | [
0,
0,
0,
1
] |
34,680 | @Override
public void reloadActiveSubscribers(long generation) {
testGeneration = Optional.of(generation);
List<CloudSubscriber> subscribers = new ArrayList<>(activeSubscribers.keySet());
subscribers.forEach(s -> s.subscriber.reload(generation));
} | @Override
public void reloadActiveSubscribers(long generation) {
testGeneration = Optional.of(generation);
List<CloudSubscriber> subscribers = new ArrayList<>(activeSubscribers.keySet());
subscribers.forEach(s -> s.subscriber.reload(generation));
} | @override public void reloadactivesubscribers(long generation) { testgeneration = optional.of(generation); list<cloudsubscriber> subscribers = new arraylist<>(activesubscribers.keyset()); subscribers.foreach(s -> s.subscriber.reload(generation)); } | yehzu/vespa | [
0,
0,
0,
1
] |
1,975 | @Override
protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
// TODO filtering??? request.getParameter("filter"); // filter=1,2,3 /groups/*/*
Map<String,Object> structure = generateStructure(getBroker(), Broker.class);
sendJsonResponse(structure, request, response);
} | @Override
protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
Map<String,Object> structure = generateStructure(getBroker(), Broker.class);
sendJsonResponse(structure, request, response);
} | @override protected void dogetwithsubjectandactor(httpservletrequest request, httpservletresponse response) throws ioexception, servletexception { map<string,object> structure = generatestructure(getbroker(), broker.class); sendjsonresponse(structure, request, response); } | vbohinc/qpid-java | [
0,
1,
0,
0
] |
2,003 | @Test
public void testTest1() throws IOException
{
final InputEntityReader reader = createReader(
new TimestampSpec("timestamp", "auto", null),
new DimensionsSpec(DimensionsSpec.getDefaultSchemas(ImmutableList.of("col1", "col2"))),
new OrcInputFormat(null, null, new Configuration()),
"example/test_1.orc"
);
try (CloseableIterator<InputRow> iterator = reader.read()) {
Assert.assertTrue(iterator.hasNext());
final InputRow row = iterator.next();
Assert.assertEquals(DateTimes.of("2016-01-01T00:00:00.000Z"), row.getTimestamp());
Assert.assertEquals("bar", Iterables.getOnlyElement(row.getDimension("col1")));
Assert.assertEquals(ImmutableList.of("dat1", "dat2", "dat3"), row.getDimension("col2"));
Assert.assertEquals(1.1, row.getMetric("val1").doubleValue(), 0.001);
Assert.assertFalse(iterator.hasNext());
}
} | @Test
public void testTest1() throws IOException
{
final InputEntityReader reader = createReader(
new TimestampSpec("timestamp", "auto", null),
new DimensionsSpec(DimensionsSpec.getDefaultSchemas(ImmutableList.of("col1", "col2"))),
new OrcInputFormat(null, null, new Configuration()),
"example/test_1.orc"
);
try (CloseableIterator<InputRow> iterator = reader.read()) {
Assert.assertTrue(iterator.hasNext());
final InputRow row = iterator.next();
Assert.assertEquals(DateTimes.of("2016-01-01T00:00:00.000Z"), row.getTimestamp());
Assert.assertEquals("bar", Iterables.getOnlyElement(row.getDimension("col1")));
Assert.assertEquals(ImmutableList.of("dat1", "dat2", "dat3"), row.getDimension("col2"));
Assert.assertEquals(1.1, row.getMetric("val1").doubleValue(), 0.001);
Assert.assertFalse(iterator.hasNext());
}
} | @test public void testtest1() throws ioexception { final inputentityreader reader = createreader( new timestampspec("timestamp", "auto", null), new dimensionsspec(dimensionsspec.getdefaultschemas(immutablelist.of("col1", "col2"))), new orcinputformat(null, null, new configuration()), "example/test_1.orc" ); try (closeableiterator<inputrow> iterator = reader.read()) { assert.asserttrue(iterator.hasnext()); final inputrow row = iterator.next(); assert.assertequals(datetimes.of("2016-01-01t00:00:00.000z"), row.gettimestamp()); assert.assertequals("bar", iterables.getonlyelement(row.getdimension("col1"))); assert.assertequals(immutablelist.of("dat1", "dat2", "dat3"), row.getdimension("col2")); assert.assertequals(1.1, row.getmetric("val1").doublevalue(), 0.001); assert.assertfalse(iterator.hasnext()); } } | weishiuntsai/druid | [
0,
0,
0,
0
] |
2,004 | @Test
public void testTest2() throws IOException
{
final InputFormat inputFormat = new OrcInputFormat(
new JSONPathSpec(
true,
Collections.singletonList(new JSONPathFieldSpec(JSONPathFieldType.PATH, "col7-subcol7", "$.col7.subcol7"))
),
null,
new Configuration()
);
final InputEntityReader reader = createReader(
new TimestampSpec("timestamp", "auto", null),
new DimensionsSpec(null),
inputFormat,
"example/test_2.orc"
);
try (CloseableIterator<InputRow> iterator = reader.read()) {
Assert.assertTrue(iterator.hasNext());
final InputRow row = iterator.next();
Assert.assertEquals(DateTimes.of("2016-01-01T00:00:00.000Z"), row.getTimestamp());
Assert.assertEquals("bar", Iterables.getOnlyElement(row.getDimension("col1")));
Assert.assertEquals(ImmutableList.of("dat1", "dat2", "dat3"), row.getDimension("col2"));
Assert.assertEquals("1.1", Iterables.getOnlyElement(row.getDimension("col3")));
Assert.assertEquals("2", Iterables.getOnlyElement(row.getDimension("col4")));
Assert.assertEquals("3.5", Iterables.getOnlyElement(row.getDimension("col5")));
Assert.assertTrue(row.getDimension("col6").isEmpty());
Assert.assertFalse(iterator.hasNext());
}
} | @Test
public void testTest2() throws IOException
{
final InputFormat inputFormat = new OrcInputFormat(
new JSONPathSpec(
true,
Collections.singletonList(new JSONPathFieldSpec(JSONPathFieldType.PATH, "col7-subcol7", "$.col7.subcol7"))
),
null,
new Configuration()
);
final InputEntityReader reader = createReader(
new TimestampSpec("timestamp", "auto", null),
new DimensionsSpec(null),
inputFormat,
"example/test_2.orc"
);
try (CloseableIterator<InputRow> iterator = reader.read()) {
Assert.assertTrue(iterator.hasNext());
final InputRow row = iterator.next();
Assert.assertEquals(DateTimes.of("2016-01-01T00:00:00.000Z"), row.getTimestamp());
Assert.assertEquals("bar", Iterables.getOnlyElement(row.getDimension("col1")));
Assert.assertEquals(ImmutableList.of("dat1", "dat2", "dat3"), row.getDimension("col2"));
Assert.assertEquals("1.1", Iterables.getOnlyElement(row.getDimension("col3")));
Assert.assertEquals("2", Iterables.getOnlyElement(row.getDimension("col4")));
Assert.assertEquals("3.5", Iterables.getOnlyElement(row.getDimension("col5")));
Assert.assertTrue(row.getDimension("col6").isEmpty());
Assert.assertFalse(iterator.hasNext());
}
} | @test public void testtest2() throws ioexception { final inputformat inputformat = new orcinputformat( new jsonpathspec( true, collections.singletonlist(new jsonpathfieldspec(jsonpathfieldtype.path, "col7-subcol7", "$.col7.subcol7")) ), null, new configuration() ); final inputentityreader reader = createreader( new timestampspec("timestamp", "auto", null), new dimensionsspec(null), inputformat, "example/test_2.orc" ); try (closeableiterator<inputrow> iterator = reader.read()) { assert.asserttrue(iterator.hasnext()); final inputrow row = iterator.next(); assert.assertequals(datetimes.of("2016-01-01t00:00:00.000z"), row.gettimestamp()); assert.assertequals("bar", iterables.getonlyelement(row.getdimension("col1"))); assert.assertequals(immutablelist.of("dat1", "dat2", "dat3"), row.getdimension("col2")); assert.assertequals("1.1", iterables.getonlyelement(row.getdimension("col3"))); assert.assertequals("2", iterables.getonlyelement(row.getdimension("col4"))); assert.assertequals("3.5", iterables.getonlyelement(row.getdimension("col5"))); assert.asserttrue(row.getdimension("col6").isempty()); assert.assertfalse(iterator.hasnext()); } } | weishiuntsai/druid | [
0,
0,
0,
0
] |
2,005 | @Test
public void testOrcFile11Format() throws IOException
{
final OrcInputFormat inputFormat = new OrcInputFormat(
new JSONPathSpec(
true,
ImmutableList.of(
new JSONPathFieldSpec(JSONPathFieldType.PATH, "struct_list_struct_int", "$.middle.list[1].int1"),
new JSONPathFieldSpec(JSONPathFieldType.PATH, "struct_list_struct_intlist", "$.middle.list[*].int1"),
new JSONPathFieldSpec(JSONPathFieldType.PATH, "list_struct_string", "$.list[0].string1"),
new JSONPathFieldSpec(JSONPathFieldType.PATH, "map_struct_int", "$.map.chani.int1")
)
),
null,
new Configuration()
);
final InputEntityReader reader = createReader(
new TimestampSpec("ts", "millis", null),
new DimensionsSpec(null),
inputFormat,
"example/orc-file-11-format.orc"
);
try (CloseableIterator<InputRow> iterator = reader.read()) {
int actualRowCount = 0;
// Check the first row
Assert.assertTrue(iterator.hasNext());
InputRow row = iterator.next();
actualRowCount++;
Assert.assertEquals("false", Iterables.getOnlyElement(row.getDimension("boolean1")));
Assert.assertEquals("1", Iterables.getOnlyElement(row.getDimension("byte1")));
Assert.assertEquals("1024", Iterables.getOnlyElement(row.getDimension("short1")));
Assert.assertEquals("65536", Iterables.getOnlyElement(row.getDimension("int1")));
Assert.assertEquals("9223372036854775807", Iterables.getOnlyElement(row.getDimension("long1")));
Assert.assertEquals("1.0", Iterables.getOnlyElement(row.getDimension("float1")));
Assert.assertEquals("-15.0", Iterables.getOnlyElement(row.getDimension("double1")));
Assert.assertEquals("AAECAwQAAA==", Iterables.getOnlyElement(row.getDimension("bytes1")));
Assert.assertEquals("hi", Iterables.getOnlyElement(row.getDimension("string1")));
Assert.assertEquals("1.23456786547456E7", Iterables.getOnlyElement(row.getDimension("decimal1")));
Assert.assertEquals("2", Iterables.getOnlyElement(row.getDimension("struct_list_struct_int")));
Assert.assertEquals(ImmutableList.of("1", "2"), row.getDimension("struct_list_struct_intlist"));
Assert.assertEquals("good", Iterables.getOnlyElement(row.getDimension("list_struct_string")));
Assert.assertEquals(DateTimes.of("2000-03-12T15:00:00.0Z"), row.getTimestamp());
while (iterator.hasNext()) {
actualRowCount++;
row = iterator.next();
}
// Check the last row
Assert.assertEquals("true", Iterables.getOnlyElement(row.getDimension("boolean1")));
Assert.assertEquals("100", Iterables.getOnlyElement(row.getDimension("byte1")));
Assert.assertEquals("2048", Iterables.getOnlyElement(row.getDimension("short1")));
Assert.assertEquals("65536", Iterables.getOnlyElement(row.getDimension("int1")));
Assert.assertEquals("9223372036854775807", Iterables.getOnlyElement(row.getDimension("long1")));
Assert.assertEquals("2.0", Iterables.getOnlyElement(row.getDimension("float1")));
Assert.assertEquals("-5.0", Iterables.getOnlyElement(row.getDimension("double1")));
Assert.assertEquals("", Iterables.getOnlyElement(row.getDimension("bytes1")));
Assert.assertEquals("bye", Iterables.getOnlyElement(row.getDimension("string1")));
Assert.assertEquals("1.23456786547457E7", Iterables.getOnlyElement(row.getDimension("decimal1")));
Assert.assertEquals("2", Iterables.getOnlyElement(row.getDimension("struct_list_struct_int")));
Assert.assertEquals(ImmutableList.of("1", "2"), row.getDimension("struct_list_struct_intlist"));
Assert.assertEquals("cat", Iterables.getOnlyElement(row.getDimension("list_struct_string")));
Assert.assertEquals("5", Iterables.getOnlyElement(row.getDimension("map_struct_int")));
Assert.assertEquals(DateTimes.of("2000-03-12T15:00:01.000Z"), row.getTimestamp());
Assert.assertEquals(7500, actualRowCount);
}
} | @Test
public void testOrcFile11Format() throws IOException
{
final OrcInputFormat inputFormat = new OrcInputFormat(
new JSONPathSpec(
true,
ImmutableList.of(
new JSONPathFieldSpec(JSONPathFieldType.PATH, "struct_list_struct_int", "$.middle.list[1].int1"),
new JSONPathFieldSpec(JSONPathFieldType.PATH, "struct_list_struct_intlist", "$.middle.list[*].int1"),
new JSONPathFieldSpec(JSONPathFieldType.PATH, "list_struct_string", "$.list[0].string1"),
new JSONPathFieldSpec(JSONPathFieldType.PATH, "map_struct_int", "$.map.chani.int1")
)
),
null,
new Configuration()
);
final InputEntityReader reader = createReader(
new TimestampSpec("ts", "millis", null),
new DimensionsSpec(null),
inputFormat,
"example/orc-file-11-format.orc"
);
try (CloseableIterator<InputRow> iterator = reader.read()) {
int actualRowCount = 0;
Assert.assertTrue(iterator.hasNext());
InputRow row = iterator.next();
actualRowCount++;
Assert.assertEquals("false", Iterables.getOnlyElement(row.getDimension("boolean1")));
Assert.assertEquals("1", Iterables.getOnlyElement(row.getDimension("byte1")));
Assert.assertEquals("1024", Iterables.getOnlyElement(row.getDimension("short1")));
Assert.assertEquals("65536", Iterables.getOnlyElement(row.getDimension("int1")));
Assert.assertEquals("9223372036854775807", Iterables.getOnlyElement(row.getDimension("long1")));
Assert.assertEquals("1.0", Iterables.getOnlyElement(row.getDimension("float1")));
Assert.assertEquals("-15.0", Iterables.getOnlyElement(row.getDimension("double1")));
Assert.assertEquals("AAECAwQAAA==", Iterables.getOnlyElement(row.getDimension("bytes1")));
Assert.assertEquals("hi", Iterables.getOnlyElement(row.getDimension("string1")));
Assert.assertEquals("1.23456786547456E7", Iterables.getOnlyElement(row.getDimension("decimal1")));
Assert.assertEquals("2", Iterables.getOnlyElement(row.getDimension("struct_list_struct_int")));
Assert.assertEquals(ImmutableList.of("1", "2"), row.getDimension("struct_list_struct_intlist"));
Assert.assertEquals("good", Iterables.getOnlyElement(row.getDimension("list_struct_string")));
Assert.assertEquals(DateTimes.of("2000-03-12T15:00:00.0Z"), row.getTimestamp());
while (iterator.hasNext()) {
actualRowCount++;
row = iterator.next();
}
Assert.assertEquals("true", Iterables.getOnlyElement(row.getDimension("boolean1")));
Assert.assertEquals("100", Iterables.getOnlyElement(row.getDimension("byte1")));
Assert.assertEquals("2048", Iterables.getOnlyElement(row.getDimension("short1")));
Assert.assertEquals("65536", Iterables.getOnlyElement(row.getDimension("int1")));
Assert.assertEquals("9223372036854775807", Iterables.getOnlyElement(row.getDimension("long1")));
Assert.assertEquals("2.0", Iterables.getOnlyElement(row.getDimension("float1")));
Assert.assertEquals("-5.0", Iterables.getOnlyElement(row.getDimension("double1")));
Assert.assertEquals("", Iterables.getOnlyElement(row.getDimension("bytes1")));
Assert.assertEquals("bye", Iterables.getOnlyElement(row.getDimension("string1")));
Assert.assertEquals("1.23456786547457E7", Iterables.getOnlyElement(row.getDimension("decimal1")));
Assert.assertEquals("2", Iterables.getOnlyElement(row.getDimension("struct_list_struct_int")));
Assert.assertEquals(ImmutableList.of("1", "2"), row.getDimension("struct_list_struct_intlist"));
Assert.assertEquals("cat", Iterables.getOnlyElement(row.getDimension("list_struct_string")));
Assert.assertEquals("5", Iterables.getOnlyElement(row.getDimension("map_struct_int")));
Assert.assertEquals(DateTimes.of("2000-03-12T15:00:01.000Z"), row.getTimestamp());
Assert.assertEquals(7500, actualRowCount);
}
} | @test public void testorcfile11format() throws ioexception { final orcinputformat inputformat = new orcinputformat( new jsonpathspec( true, immutablelist.of( new jsonpathfieldspec(jsonpathfieldtype.path, "struct_list_struct_int", "$.middle.list[1].int1"), new jsonpathfieldspec(jsonpathfieldtype.path, "struct_list_struct_intlist", "$.middle.list[*].int1"), new jsonpathfieldspec(jsonpathfieldtype.path, "list_struct_string", "$.list[0].string1"), new jsonpathfieldspec(jsonpathfieldtype.path, "map_struct_int", "$.map.chani.int1") ) ), null, new configuration() ); final inputentityreader reader = createreader( new timestampspec("ts", "millis", null), new dimensionsspec(null), inputformat, "example/orc-file-11-format.orc" ); try (closeableiterator<inputrow> iterator = reader.read()) { int actualrowcount = 0; assert.asserttrue(iterator.hasnext()); inputrow row = iterator.next(); actualrowcount++; assert.assertequals("false", iterables.getonlyelement(row.getdimension("boolean1"))); assert.assertequals("1", iterables.getonlyelement(row.getdimension("byte1"))); assert.assertequals("1024", iterables.getonlyelement(row.getdimension("short1"))); assert.assertequals("65536", iterables.getonlyelement(row.getdimension("int1"))); assert.assertequals("9223372036854775807", iterables.getonlyelement(row.getdimension("long1"))); assert.assertequals("1.0", iterables.getonlyelement(row.getdimension("float1"))); assert.assertequals("-15.0", iterables.getonlyelement(row.getdimension("double1"))); assert.assertequals("aaecawqaaa==", iterables.getonlyelement(row.getdimension("bytes1"))); assert.assertequals("hi", iterables.getonlyelement(row.getdimension("string1"))); assert.assertequals("1.23456786547456e7", iterables.getonlyelement(row.getdimension("decimal1"))); assert.assertequals("2", iterables.getonlyelement(row.getdimension("struct_list_struct_int"))); assert.assertequals(immutablelist.of("1", "2"), row.getdimension("struct_list_struct_intlist")); assert.assertequals("good", iterables.getonlyelement(row.getdimension("list_struct_string"))); assert.assertequals(datetimes.of("2000-03-12t15:00:00.0z"), row.gettimestamp()); while (iterator.hasnext()) { actualrowcount++; row = iterator.next(); } assert.assertequals("true", iterables.getonlyelement(row.getdimension("boolean1"))); assert.assertequals("100", iterables.getonlyelement(row.getdimension("byte1"))); assert.assertequals("2048", iterables.getonlyelement(row.getdimension("short1"))); assert.assertequals("65536", iterables.getonlyelement(row.getdimension("int1"))); assert.assertequals("9223372036854775807", iterables.getonlyelement(row.getdimension("long1"))); assert.assertequals("2.0", iterables.getonlyelement(row.getdimension("float1"))); assert.assertequals("-5.0", iterables.getonlyelement(row.getdimension("double1"))); assert.assertequals("", iterables.getonlyelement(row.getdimension("bytes1"))); assert.assertequals("bye", iterables.getonlyelement(row.getdimension("string1"))); assert.assertequals("1.23456786547457e7", iterables.getonlyelement(row.getdimension("decimal1"))); assert.assertequals("2", iterables.getonlyelement(row.getdimension("struct_list_struct_int"))); assert.assertequals(immutablelist.of("1", "2"), row.getdimension("struct_list_struct_intlist")); assert.assertequals("cat", iterables.getonlyelement(row.getdimension("list_struct_string"))); assert.assertequals("5", iterables.getonlyelement(row.getdimension("map_struct_int"))); assert.assertequals(datetimes.of("2000-03-12t15:00:01.000z"), row.gettimestamp()); assert.assertequals(7500, actualrowcount); } } | weishiuntsai/druid | [
0,
0,
0,
0
] |
2,006 | @Test
public void testOrcSplitElim() throws IOException
{
final InputEntityReader reader = createReader(
new TimestampSpec("ts", "millis", null),
new DimensionsSpec(null),
new OrcInputFormat(new JSONPathSpec(true, null), null, new Configuration()),
"example/orc_split_elim.orc"
);
try (CloseableIterator<InputRow> iterator = reader.read()) {
int actualRowCount = 0;
Assert.assertTrue(iterator.hasNext());
final InputRow row = iterator.next();
actualRowCount++;
Assert.assertEquals(DateTimes.of("1969-12-31T16:00:00.0Z"), row.getTimestamp());
Assert.assertEquals("2", Iterables.getOnlyElement(row.getDimension("userid")));
Assert.assertEquals("foo", Iterables.getOnlyElement(row.getDimension("string1")));
Assert.assertEquals("0.8", Iterables.getOnlyElement(row.getDimension("subtype")));
Assert.assertEquals("1.2", Iterables.getOnlyElement(row.getDimension("decimal1")));
while (iterator.hasNext()) {
actualRowCount++;
iterator.next();
}
Assert.assertEquals(25000, actualRowCount);
}
} | @Test
public void testOrcSplitElim() throws IOException
{
final InputEntityReader reader = createReader(
new TimestampSpec("ts", "millis", null),
new DimensionsSpec(null),
new OrcInputFormat(new JSONPathSpec(true, null), null, new Configuration()),
"example/orc_split_elim.orc"
);
try (CloseableIterator<InputRow> iterator = reader.read()) {
int actualRowCount = 0;
Assert.assertTrue(iterator.hasNext());
final InputRow row = iterator.next();
actualRowCount++;
Assert.assertEquals(DateTimes.of("1969-12-31T16:00:00.0Z"), row.getTimestamp());
Assert.assertEquals("2", Iterables.getOnlyElement(row.getDimension("userid")));
Assert.assertEquals("foo", Iterables.getOnlyElement(row.getDimension("string1")));
Assert.assertEquals("0.8", Iterables.getOnlyElement(row.getDimension("subtype")));
Assert.assertEquals("1.2", Iterables.getOnlyElement(row.getDimension("decimal1")));
while (iterator.hasNext()) {
actualRowCount++;
iterator.next();
}
Assert.assertEquals(25000, actualRowCount);
}
} | @test public void testorcsplitelim() throws ioexception { final inputentityreader reader = createreader( new timestampspec("ts", "millis", null), new dimensionsspec(null), new orcinputformat(new jsonpathspec(true, null), null, new configuration()), "example/orc_split_elim.orc" ); try (closeableiterator<inputrow> iterator = reader.read()) { int actualrowcount = 0; assert.asserttrue(iterator.hasnext()); final inputrow row = iterator.next(); actualrowcount++; assert.assertequals(datetimes.of("1969-12-31t16:00:00.0z"), row.gettimestamp()); assert.assertequals("2", iterables.getonlyelement(row.getdimension("userid"))); assert.assertequals("foo", iterables.getonlyelement(row.getdimension("string1"))); assert.assertequals("0.8", iterables.getonlyelement(row.getdimension("subtype"))); assert.assertequals("1.2", iterables.getonlyelement(row.getdimension("decimal1"))); while (iterator.hasnext()) { actualrowcount++; iterator.next(); } assert.assertequals(25000, actualrowcount); } } | weishiuntsai/druid | [
0,
0,
0,
0
] |
2,007 | @Test
public void testDate1900() throws IOException
{
final InputEntityReader reader = createReader(
new TimestampSpec("time", "millis", null),
new DimensionsSpec(null, Collections.singletonList("time"), null),
new OrcInputFormat(new JSONPathSpec(true, null), null, new Configuration()),
"example/TestOrcFile.testDate1900.orc"
);
try (CloseableIterator<InputRow> iterator = reader.read()) {
int actualRowCount = 0;
Assert.assertTrue(iterator.hasNext());
final InputRow row = iterator.next();
actualRowCount++;
Assert.assertEquals(1, row.getDimensions().size());
Assert.assertEquals(DateTimes.of("1900-05-05T12:34:56.1Z"), row.getTimestamp());
Assert.assertEquals("1900-12-25T00:00:00.000Z", Iterables.getOnlyElement(row.getDimension("date")));
while (iterator.hasNext()) {
actualRowCount++;
iterator.next();
}
Assert.assertEquals(70000, actualRowCount);
}
} | @Test
public void testDate1900() throws IOException
{
final InputEntityReader reader = createReader(
new TimestampSpec("time", "millis", null),
new DimensionsSpec(null, Collections.singletonList("time"), null),
new OrcInputFormat(new JSONPathSpec(true, null), null, new Configuration()),
"example/TestOrcFile.testDate1900.orc"
);
try (CloseableIterator<InputRow> iterator = reader.read()) {
int actualRowCount = 0;
Assert.assertTrue(iterator.hasNext());
final InputRow row = iterator.next();
actualRowCount++;
Assert.assertEquals(1, row.getDimensions().size());
Assert.assertEquals(DateTimes.of("1900-05-05T12:34:56.1Z"), row.getTimestamp());
Assert.assertEquals("1900-12-25T00:00:00.000Z", Iterables.getOnlyElement(row.getDimension("date")));
while (iterator.hasNext()) {
actualRowCount++;
iterator.next();
}
Assert.assertEquals(70000, actualRowCount);
}
} | @test public void testdate1900() throws ioexception { final inputentityreader reader = createreader( new timestampspec("time", "millis", null), new dimensionsspec(null, collections.singletonlist("time"), null), new orcinputformat(new jsonpathspec(true, null), null, new configuration()), "example/testorcfile.testdate1900.orc" ); try (closeableiterator<inputrow> iterator = reader.read()) { int actualrowcount = 0; assert.asserttrue(iterator.hasnext()); final inputrow row = iterator.next(); actualrowcount++; assert.assertequals(1, row.getdimensions().size()); assert.assertequals(datetimes.of("1900-05-05t12:34:56.1z"), row.gettimestamp()); assert.assertequals("1900-12-25t00:00:00.000z", iterables.getonlyelement(row.getdimension("date"))); while (iterator.hasnext()) { actualrowcount++; iterator.next(); } assert.assertequals(70000, actualrowcount); } } | weishiuntsai/druid | [
0,
0,
0,
0
] |
2,008 | @Test
public void testDate2038() throws IOException
{
final InputEntityReader reader = createReader(
new TimestampSpec("time", "millis", null),
new DimensionsSpec(null, Collections.singletonList("time"), null),
new OrcInputFormat(new JSONPathSpec(true, null), null, new Configuration()),
"example/TestOrcFile.testDate2038.orc"
);
try (CloseableIterator<InputRow> iterator = reader.read()) {
int actualRowCount = 0;
Assert.assertTrue(iterator.hasNext());
final InputRow row = iterator.next();
actualRowCount++;
Assert.assertEquals(1, row.getDimensions().size());
Assert.assertEquals(DateTimes.of("2038-05-05T12:34:56.1Z"), row.getTimestamp());
Assert.assertEquals("2038-12-25T00:00:00.000Z", Iterables.getOnlyElement(row.getDimension("date")));
while (iterator.hasNext()) {
actualRowCount++;
iterator.next();
}
Assert.assertEquals(212000, actualRowCount);
}
} | @Test
public void testDate2038() throws IOException
{
final InputEntityReader reader = createReader(
new TimestampSpec("time", "millis", null),
new DimensionsSpec(null, Collections.singletonList("time"), null),
new OrcInputFormat(new JSONPathSpec(true, null), null, new Configuration()),
"example/TestOrcFile.testDate2038.orc"
);
try (CloseableIterator<InputRow> iterator = reader.read()) {
int actualRowCount = 0;
Assert.assertTrue(iterator.hasNext());
final InputRow row = iterator.next();
actualRowCount++;
Assert.assertEquals(1, row.getDimensions().size());
Assert.assertEquals(DateTimes.of("2038-05-05T12:34:56.1Z"), row.getTimestamp());
Assert.assertEquals("2038-12-25T00:00:00.000Z", Iterables.getOnlyElement(row.getDimension("date")));
while (iterator.hasNext()) {
actualRowCount++;
iterator.next();
}
Assert.assertEquals(212000, actualRowCount);
}
} | @test public void testdate2038() throws ioexception { final inputentityreader reader = createreader( new timestampspec("time", "millis", null), new dimensionsspec(null, collections.singletonlist("time"), null), new orcinputformat(new jsonpathspec(true, null), null, new configuration()), "example/testorcfile.testdate2038.orc" ); try (closeableiterator<inputrow> iterator = reader.read()) { int actualrowcount = 0; assert.asserttrue(iterator.hasnext()); final inputrow row = iterator.next(); actualrowcount++; assert.assertequals(1, row.getdimensions().size()); assert.assertequals(datetimes.of("2038-05-05t12:34:56.1z"), row.gettimestamp()); assert.assertequals("2038-12-25t00:00:00.000z", iterables.getonlyelement(row.getdimension("date"))); while (iterator.hasnext()) { actualrowcount++; iterator.next(); } assert.assertequals(212000, actualrowcount); } } | weishiuntsai/druid | [
0,
0,
0,
0
] |
34,800 | public HttpResponse doAct(@QueryParameter String no) throws IOException {
if(no!=null) { // dismiss
disable(true);
// of course the irony is that this redirect won't work
return HttpResponses.redirectViaContextPath("/manage");
} else {
return new HttpRedirect("https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+says+my+reverse+proxy+setup+is+broken");
}
} | public HttpResponse doAct(@QueryParameter String no) throws IOException {
if(no!=null) {
disable(true);
return HttpResponses.redirectViaContextPath("/manage");
} else {
return new HttpRedirect("https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+says+my+reverse+proxy+setup+is+broken");
}
} | public httpresponse doact(@queryparameter string no) throws ioexception { if(no!=null) { disable(true); return httpresponses.redirectviacontextpath("/manage"); } else { return new httpredirect("https://wiki.jenkins-ci.org/display/jenkins/jenkins+says+my+reverse+proxy+setup+is+broken"); } } | wasimdocker/hudson | [
0,
0,
1,
0
] |
18,435 | private void bnt0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bnt0ActionPerformed
// TODO add your handling code here:
// JOptionPane.showMessageDialog(null,evt.paramString());
if (isBtigual() ){
setBtigual(false);
textResult.setText("");
this.vtmp=0;
textResult.setText(textResult.getText() + evt.getActionCommand());
textResult.requestFocusInWindow(); //posicionar cursor
}else{
textResult.setText(textResult.getText() + evt.getActionCommand());
textResult.requestFocusInWindow(); //posicionar cursor
}
} | private void bnt0ActionPerformed(java.awt.event.ActionEvent evt) {
if (isBtigual() ){
setBtigual(false);
textResult.setText("");
this.vtmp=0;
textResult.setText(textResult.getText() + evt.getActionCommand());
textResult.requestFocusInWindow();
}else{
textResult.setText(textResult.getText() + evt.getActionCommand());
textResult.requestFocusInWindow();
}
} | private void bnt0actionperformed(java.awt.event.actionevent evt) { if (isbtigual() ){ setbtigual(false); textresult.settext(""); this.vtmp=0; textresult.settext(textresult.gettext() + evt.getactioncommand()); textresult.requestfocusinwindow(); }else{ textresult.settext(textresult.gettext() + evt.getactioncommand()); textresult.requestfocusinwindow(); } } | vinte2/Calc | [
0,
1,
0,
0
] |
18,533 | private void showClearIcon(boolean show) {
// TODO: should probably use setVisibility method, but seems to not working.
if (clearDrawable != null) {
clearDrawable.setAlpha(show ? 255 : 0);
}
} | private void showClearIcon(boolean show) {
if (clearDrawable != null) {
clearDrawable.setAlpha(show ? 255 : 0);
}
} | private void showclearicon(boolean show) { if (cleardrawable != null) { cleardrawable.setalpha(show ? 255 : 0); } } | wellplayedstudios/twilio-video-app-android | [
1,
0,
0,
0
] |
18,549 | private Map<String, Object> validateJwt(String token, JWTPolicyBean config)
throws ExpiredJwtException, PrematureJwtException, MalformedJwtException, SignatureException, InvalidClaimException {
// check if we have to use jwk(s)
if (urlValidator.isValid(config.getSigningKeyString())){
if (provider == null){
provider = getNewJwksProvider(config.getSigningKeyString());
}
Jwk jwk;
try {
jwk = provider.get(config.getKid());
if (config.getSigningKey() == null || !(config.getSigningKey().equals(jwk.getPublicKey()))) {
config.setSigningKey(jwk.getPublicKey());
}
} catch (JwkException e) {
throw new SignatureException("JWK was not found with kid: " + config.getKid(), e);
}
}
JwtParser parser = Jwts.parser()
.setSigningKey(config.getSigningKey())
.setAllowedClockSkewSeconds(config.getAllowedClockSkew());
// Set all claims
config.getRequiredClaims().stream() // TODO add type variable to allow dates, etc
.forEach(requiredClaim -> parser.require(requiredClaim.getClaimName(), requiredClaim.getClaimValue()));
return parser.parse(token, new ConfigCheckingJwtHandler(config));
} | private Map<String, Object> validateJwt(String token, JWTPolicyBean config)
throws ExpiredJwtException, PrematureJwtException, MalformedJwtException, SignatureException, InvalidClaimException {
if (urlValidator.isValid(config.getSigningKeyString())){
if (provider == null){
provider = getNewJwksProvider(config.getSigningKeyString());
}
Jwk jwk;
try {
jwk = provider.get(config.getKid());
if (config.getSigningKey() == null || !(config.getSigningKey().equals(jwk.getPublicKey()))) {
config.setSigningKey(jwk.getPublicKey());
}
} catch (JwkException e) {
throw new SignatureException("JWK was not found with kid: " + config.getKid(), e);
}
}
JwtParser parser = Jwts.parser()
.setSigningKey(config.getSigningKey())
.setAllowedClockSkewSeconds(config.getAllowedClockSkew());
config.getRequiredClaims().stream()
.forEach(requiredClaim -> parser.require(requiredClaim.getClaimName(), requiredClaim.getClaimValue()));
return parser.parse(token, new ConfigCheckingJwtHandler(config));
} | private map<string, object> validatejwt(string token, jwtpolicybean config) throws expiredjwtexception, prematurejwtexception, malformedjwtexception, signatureexception, invalidclaimexception { if (urlvalidator.isvalid(config.getsigningkeystring())){ if (provider == null){ provider = getnewjwksprovider(config.getsigningkeystring()); } jwk jwk; try { jwk = provider.get(config.getkid()); if (config.getsigningkey() == null || !(config.getsigningkey().equals(jwk.getpublickey()))) { config.setsigningkey(jwk.getpublickey()); } } catch (jwkexception e) { throw new signatureexception("jwk was not found with kid: " + config.getkid(), e); } } jwtparser parser = jwts.parser() .setsigningkey(config.getsigningkey()) .setallowedclockskewseconds(config.getallowedclockskew()); config.getrequiredclaims().stream() .foreach(requiredclaim -> parser.require(requiredclaim.getclaimname(), requiredclaim.getclaimvalue())); return parser.parse(token, new configcheckingjwthandler(config)); } | tevosouza/apiman-plugins | [
0,
1,
0,
0
] |
18,600 | public PrismObject<ShadowType> getResourceObject(ProvisioningContext ctx,
Collection<? extends ResourceAttribute<?>> identifiers, boolean fetchAssociations, OperationResult parentResult)
throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException,
SecurityViolationException, GenericConnectorException, ExpressionEvaluationException {
LOGGER.trace("Getting resource object {}", identifiers);
AttributesToReturn attributesToReturn = ProvisioningUtil.createAttributesToReturn(ctx);
PrismObject<ShadowType> resourceShadow = fetchResourceObject(ctx, identifiers,
attributesToReturn, fetchAssociations, parentResult); // todo consider whether it is always necessary to fetch the entitlements
LOGGER.trace("Got resource object\n{}", resourceShadow.debugDumpLazily());
return resourceShadow;
} | public PrismObject<ShadowType> getResourceObject(ProvisioningContext ctx,
Collection<? extends ResourceAttribute<?>> identifiers, boolean fetchAssociations, OperationResult parentResult)
throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException,
SecurityViolationException, GenericConnectorException, ExpressionEvaluationException {
LOGGER.trace("Getting resource object {}", identifiers);
AttributesToReturn attributesToReturn = ProvisioningUtil.createAttributesToReturn(ctx);
PrismObject<ShadowType> resourceShadow = fetchResourceObject(ctx, identifiers,
attributesToReturn, fetchAssociations, parentResult);
LOGGER.trace("Got resource object\n{}", resourceShadow.debugDumpLazily());
return resourceShadow;
} | public prismobject<shadowtype> getresourceobject(provisioningcontext ctx, collection<? extends resourceattribute<?>> identifiers, boolean fetchassociations, operationresult parentresult) throws objectnotfoundexception, communicationexception, schemaexception, configurationexception, securityviolationexception, genericconnectorexception, expressionevaluationexception { logger.trace("getting resource object {}", identifiers); attributestoreturn attributestoreturn = provisioningutil.createattributestoreturn(ctx); prismobject<shadowtype> resourceshadow = fetchresourceobject(ctx, identifiers, attributestoreturn, fetchassociations, parentresult); logger.trace("got resource object\n{}", resourceshadow.debugdumplazily()); return resourceshadow; } | valtri/midpoint | [
1,
0,
0,
0
] |
18,601 | public PrismObject<ShadowType> locateResourceObject(ProvisioningContext ctx,
Collection<? extends ResourceAttribute<?>> identifiers, OperationResult parentResult) throws ObjectNotFoundException,
CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, GenericConnectorException, ExpressionEvaluationException {
LOGGER.trace("Locating resource object {}", identifiers);
ConnectorInstance connector = ctx.getConnector(ReadCapabilityType.class, parentResult);
AttributesToReturn attributesToReturn = ProvisioningUtil.createAttributesToReturn(ctx);
if (hasAllIdentifiers(identifiers, ctx.getObjectClassDefinition())) {
return fetchResourceObject(ctx, identifiers,
attributesToReturn, true, parentResult); // todo consider whether it is always necessary to fetch the entitlements
} else {
// Search
Collection<? extends RefinedAttributeDefinition> secondaryIdentifierDefs = ctx.getObjectClassDefinition().getSecondaryIdentifiers();
// Assume single secondary identifier for simplicity
if (secondaryIdentifierDefs.size() > 1) {
throw new UnsupportedOperationException("Composite secondary identifier is not supported yet");
} else if (secondaryIdentifierDefs.isEmpty()) {
throw new SchemaException("No secondary identifier defined, cannot search");
}
RefinedAttributeDefinition<String> secondaryIdentifierDef = secondaryIdentifierDefs.iterator().next();
ResourceAttribute<?> secondaryIdentifier = null;
for (ResourceAttribute<?> identifier: identifiers) {
if (identifier.getElementName().equals(secondaryIdentifierDef.getName())) {
secondaryIdentifier = identifier;
}
}
if (secondaryIdentifier == null) {
throw new SchemaException("No secondary identifier present, cannot search. Identifiers: "+identifiers);
}
final ResourceAttribute<?> finalSecondaryIdentifier = secondaryIdentifier;
List<PrismPropertyValue<String>> secondaryIdentifierValues = (List) secondaryIdentifier.getValues();
PrismPropertyValue<String> secondaryIdentifierValue;
if (secondaryIdentifierValues.size() > 1) {
throw new IllegalStateException("Secondary identifier has more than one value: " + secondaryIdentifier.getValues());
} else if (secondaryIdentifierValues.size() == 1) {
secondaryIdentifierValue = secondaryIdentifierValues.get(0).clone();
} else {
secondaryIdentifierValue = null;
}
ObjectQuery query = prismContext.queryFor(ShadowType.class)
.itemWithDef(secondaryIdentifierDef, ShadowType.F_ATTRIBUTES, secondaryIdentifierDef.getName()).eq(secondaryIdentifierValue)
.build();
final Holder<PrismObject<ShadowType>> shadowHolder = new Holder<>();
ShadowResultHandler handler = new ShadowResultHandler() {
@Override
public boolean handle(PrismObject<ShadowType> shadow) {
if (!shadowHolder.isEmpty()) {
throw new IllegalStateException("More than one value found for secondary identifier "+finalSecondaryIdentifier);
}
shadowHolder.setValue(shadow);
return true;
}
};
try {
connector.search(ctx.getObjectClassDefinition(), query, handler, attributesToReturn, null, null, ctx, parentResult);
if (shadowHolder.isEmpty()) {
throw new ObjectNotFoundException("No object found for secondary identifier "+secondaryIdentifier);
}
PrismObject<ShadowType> shadow = shadowHolder.getValue();
PrismObject<ShadowType> finalShadow = postProcessResourceObjectRead(ctx, shadow, true, parentResult);
LOGGER.trace("Located resource object {}", finalShadow);
return finalShadow;
} catch (GenericFrameworkException e) {
throw new GenericConnectorException(e.getMessage(), e);
}
}
} | public PrismObject<ShadowType> locateResourceObject(ProvisioningContext ctx,
Collection<? extends ResourceAttribute<?>> identifiers, OperationResult parentResult) throws ObjectNotFoundException,
CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, GenericConnectorException, ExpressionEvaluationException {
LOGGER.trace("Locating resource object {}", identifiers);
ConnectorInstance connector = ctx.getConnector(ReadCapabilityType.class, parentResult);
AttributesToReturn attributesToReturn = ProvisioningUtil.createAttributesToReturn(ctx);
if (hasAllIdentifiers(identifiers, ctx.getObjectClassDefinition())) {
return fetchResourceObject(ctx, identifiers,
attributesToReturn, true, parentResult);
} else {
Collection<? extends RefinedAttributeDefinition> secondaryIdentifierDefs = ctx.getObjectClassDefinition().getSecondaryIdentifiers();
if (secondaryIdentifierDefs.size() > 1) {
throw new UnsupportedOperationException("Composite secondary identifier is not supported yet");
} else if (secondaryIdentifierDefs.isEmpty()) {
throw new SchemaException("No secondary identifier defined, cannot search");
}
RefinedAttributeDefinition<String> secondaryIdentifierDef = secondaryIdentifierDefs.iterator().next();
ResourceAttribute<?> secondaryIdentifier = null;
for (ResourceAttribute<?> identifier: identifiers) {
if (identifier.getElementName().equals(secondaryIdentifierDef.getName())) {
secondaryIdentifier = identifier;
}
}
if (secondaryIdentifier == null) {
throw new SchemaException("No secondary identifier present, cannot search. Identifiers: "+identifiers);
}
final ResourceAttribute<?> finalSecondaryIdentifier = secondaryIdentifier;
List<PrismPropertyValue<String>> secondaryIdentifierValues = (List) secondaryIdentifier.getValues();
PrismPropertyValue<String> secondaryIdentifierValue;
if (secondaryIdentifierValues.size() > 1) {
throw new IllegalStateException("Secondary identifier has more than one value: " + secondaryIdentifier.getValues());
} else if (secondaryIdentifierValues.size() == 1) {
secondaryIdentifierValue = secondaryIdentifierValues.get(0).clone();
} else {
secondaryIdentifierValue = null;
}
ObjectQuery query = prismContext.queryFor(ShadowType.class)
.itemWithDef(secondaryIdentifierDef, ShadowType.F_ATTRIBUTES, secondaryIdentifierDef.getName()).eq(secondaryIdentifierValue)
.build();
final Holder<PrismObject<ShadowType>> shadowHolder = new Holder<>();
ShadowResultHandler handler = new ShadowResultHandler() {
@Override
public boolean handle(PrismObject<ShadowType> shadow) {
if (!shadowHolder.isEmpty()) {
throw new IllegalStateException("More than one value found for secondary identifier "+finalSecondaryIdentifier);
}
shadowHolder.setValue(shadow);
return true;
}
};
try {
connector.search(ctx.getObjectClassDefinition(), query, handler, attributesToReturn, null, null, ctx, parentResult);
if (shadowHolder.isEmpty()) {
throw new ObjectNotFoundException("No object found for secondary identifier "+secondaryIdentifier);
}
PrismObject<ShadowType> shadow = shadowHolder.getValue();
PrismObject<ShadowType> finalShadow = postProcessResourceObjectRead(ctx, shadow, true, parentResult);
LOGGER.trace("Located resource object {}", finalShadow);
return finalShadow;
} catch (GenericFrameworkException e) {
throw new GenericConnectorException(e.getMessage(), e);
}
}
} | public prismobject<shadowtype> locateresourceobject(provisioningcontext ctx, collection<? extends resourceattribute<?>> identifiers, operationresult parentresult) throws objectnotfoundexception, communicationexception, schemaexception, configurationexception, securityviolationexception, genericconnectorexception, expressionevaluationexception { logger.trace("locating resource object {}", identifiers); connectorinstance connector = ctx.getconnector(readcapabilitytype.class, parentresult); attributestoreturn attributestoreturn = provisioningutil.createattributestoreturn(ctx); if (hasallidentifiers(identifiers, ctx.getobjectclassdefinition())) { return fetchresourceobject(ctx, identifiers, attributestoreturn, true, parentresult); } else { collection<? extends refinedattributedefinition> secondaryidentifierdefs = ctx.getobjectclassdefinition().getsecondaryidentifiers(); if (secondaryidentifierdefs.size() > 1) { throw new unsupportedoperationexception("composite secondary identifier is not supported yet"); } else if (secondaryidentifierdefs.isempty()) { throw new schemaexception("no secondary identifier defined, cannot search"); } refinedattributedefinition<string> secondaryidentifierdef = secondaryidentifierdefs.iterator().next(); resourceattribute<?> secondaryidentifier = null; for (resourceattribute<?> identifier: identifiers) { if (identifier.getelementname().equals(secondaryidentifierdef.getname())) { secondaryidentifier = identifier; } } if (secondaryidentifier == null) { throw new schemaexception("no secondary identifier present, cannot search. identifiers: "+identifiers); } final resourceattribute<?> finalsecondaryidentifier = secondaryidentifier; list<prismpropertyvalue<string>> secondaryidentifiervalues = (list) secondaryidentifier.getvalues(); prismpropertyvalue<string> secondaryidentifiervalue; if (secondaryidentifiervalues.size() > 1) { throw new illegalstateexception("secondary identifier has more than one value: " + secondaryidentifier.getvalues()); } else if (secondaryidentifiervalues.size() == 1) { secondaryidentifiervalue = secondaryidentifiervalues.get(0).clone(); } else { secondaryidentifiervalue = null; } objectquery query = prismcontext.queryfor(shadowtype.class) .itemwithdef(secondaryidentifierdef, shadowtype.f_attributes, secondaryidentifierdef.getname()).eq(secondaryidentifiervalue) .build(); final holder<prismobject<shadowtype>> shadowholder = new holder<>(); shadowresulthandler handler = new shadowresulthandler() { @override public boolean handle(prismobject<shadowtype> shadow) { if (!shadowholder.isempty()) { throw new illegalstateexception("more than one value found for secondary identifier "+finalsecondaryidentifier); } shadowholder.setvalue(shadow); return true; } }; try { connector.search(ctx.getobjectclassdefinition(), query, handler, attributestoreturn, null, null, ctx, parentresult); if (shadowholder.isempty()) { throw new objectnotfoundexception("no object found for secondary identifier "+secondaryidentifier); } prismobject<shadowtype> shadow = shadowholder.getvalue(); prismobject<shadowtype> finalshadow = postprocessresourceobjectread(ctx, shadow, true, parentresult); logger.trace("located resource object {}", finalshadow); return finalshadow; } catch (genericframeworkexception e) { throw new genericconnectorexception(e.getmessage(), e); } } } | valtri/midpoint | [
1,
0,
0,
0
] |
18,602 | private void updateQuantum(ProvisioningContext ctx, ConnectorInstance connectorUsedForOperation, AsynchronousOperationResult aResult, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
ConnectorInstance readConnector = ctx.getConnector(ReadCapabilityType.class, parentResult);
if (readConnector != connectorUsedForOperation) {
// Writing by different connector that we are going to use for reading: danger of quantum effects
aResult.setQuantumOperation(true);
}
} | private void updateQuantum(ProvisioningContext ctx, ConnectorInstance connectorUsedForOperation, AsynchronousOperationResult aResult, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
ConnectorInstance readConnector = ctx.getConnector(ReadCapabilityType.class, parentResult);
if (readConnector != connectorUsedForOperation) {
aResult.setQuantumOperation(true);
}
} | private void updatequantum(provisioningcontext ctx, connectorinstance connectorusedforoperation, asynchronousoperationresult aresult, operationresult parentresult) throws objectnotfoundexception, schemaexception, communicationexception, configurationexception, expressionevaluationexception { connectorinstance readconnector = ctx.getconnector(readcapabilitytype.class, parentresult); if (readconnector != connectorusedforoperation) { aresult.setquantumoperation(true); } } | valtri/midpoint | [
1,
0,
0,
0
] |
18,608 | public List<Change> fetchChanges(ProvisioningContext ctx, PrismProperty<?> lastToken,
OperationResult parentResult) throws SchemaException,
CommunicationException, ConfigurationException, SecurityViolationException, GenericFrameworkException, ObjectNotFoundException, ExpressionEvaluationException {
Validate.notNull(parentResult, "Operation result must not be null.");
LOGGER.trace("START fetch changes, objectClass: {}", ctx.getObjectClassDefinition());
AttributesToReturn attrsToReturn = null;
if (!ctx.isWildcard()) {
attrsToReturn = ProvisioningUtil.createAttributesToReturn(ctx);
}
ConnectorInstance connector = ctx.getConnector(LiveSyncCapabilityType.class, parentResult);
// get changes from the connector
List<Change> changes = connector.fetchChanges(ctx.getObjectClassDefinition(), lastToken, attrsToReturn, ctx, parentResult);
Iterator<Change> iterator = changes.iterator();
while (iterator.hasNext()) {
Change change = iterator.next();
LOGGER.trace("Original change:\n{}", change.debugDump());
if (change.isTokenOnly()) {
continue;
}
ProvisioningContext shadowCtx = ctx;
AttributesToReturn shadowAttrsToReturn = attrsToReturn;
PrismObject<ShadowType> currentShadow = change.getCurrentShadow();
ObjectClassComplexTypeDefinition changeObjectClassDefinition = change.getObjectClassDefinition();
if (changeObjectClassDefinition == null) {
if (!ctx.isWildcard() || change.getObjectDelta() == null || !change.getObjectDelta().isDelete()) {
throw new SchemaException("No object class definition in change "+change);
}
}
if (ctx.isWildcard() && changeObjectClassDefinition != null) {
shadowCtx = ctx.spawn(changeObjectClassDefinition.getTypeName());
if (shadowCtx.isWildcard()) {
String message = "Unkown object class "+changeObjectClassDefinition.getTypeName()+" found in synchronization delta";
parentResult.recordFatalError(message);
throw new SchemaException(message);
}
change.setObjectClassDefinition(shadowCtx.getObjectClassDefinition());
shadowAttrsToReturn = ProvisioningUtil.createAttributesToReturn(shadowCtx);
}
if (change.getObjectDelta() == null || !change.getObjectDelta().isDelete()) {
if (currentShadow == null) {
// There is no current shadow in a change. Add it by fetching it explicitly.
try {
LOGGER.trace("Re-fetching object {} because it is not in the change", change.getIdentifiers());
currentShadow = fetchResourceObject(shadowCtx,
change.getIdentifiers(), shadowAttrsToReturn, true, parentResult); // todo consider whether it is always necessary to fetch the entitlements
change.setCurrentShadow(currentShadow);
} catch (ObjectNotFoundException ex) {
parentResult.recordHandledError(
"Object detected in change log no longer exist on the resource. Skipping processing this object.", ex);
LOGGER.warn("Object detected in change log no longer exist on the resource. Skipping processing this object "
+ ex.getMessage());
// TODO: Maybe change to DELETE instead of this?
iterator.remove();
continue;
}
} else {
if (ctx.isWildcard()) {
if (!MiscUtil.equals(shadowAttrsToReturn, attrsToReturn)) {
// re-fetch the shadow if necessary (if attributesToGet does not match)
ResourceObjectIdentification identification = ResourceObjectIdentification.create(shadowCtx.getObjectClassDefinition(),
change.getIdentifiers());
identification.validatePrimaryIdenfiers();
LOGGER.trace("Re-fetching object {} because of attrsToReturn", identification);
currentShadow = connector.fetchObject(identification, shadowAttrsToReturn, ctx, parentResult);
}
}
PrismObject<ShadowType> processedCurrentShadow = postProcessResourceObjectRead(shadowCtx,
currentShadow, true, parentResult);
change.setCurrentShadow(processedCurrentShadow);
}
}
LOGGER.trace("Processed change\n:{}", change.debugDump());
}
computeResultStatus(parentResult);
LOGGER.trace("END fetch changes ({} changes)", changes == null ? "null" : changes.size());
return changes;
} | public List<Change> fetchChanges(ProvisioningContext ctx, PrismProperty<?> lastToken,
OperationResult parentResult) throws SchemaException,
CommunicationException, ConfigurationException, SecurityViolationException, GenericFrameworkException, ObjectNotFoundException, ExpressionEvaluationException {
Validate.notNull(parentResult, "Operation result must not be null.");
LOGGER.trace("START fetch changes, objectClass: {}", ctx.getObjectClassDefinition());
AttributesToReturn attrsToReturn = null;
if (!ctx.isWildcard()) {
attrsToReturn = ProvisioningUtil.createAttributesToReturn(ctx);
}
ConnectorInstance connector = ctx.getConnector(LiveSyncCapabilityType.class, parentResult);
List<Change> changes = connector.fetchChanges(ctx.getObjectClassDefinition(), lastToken, attrsToReturn, ctx, parentResult);
Iterator<Change> iterator = changes.iterator();
while (iterator.hasNext()) {
Change change = iterator.next();
LOGGER.trace("Original change:\n{}", change.debugDump());
if (change.isTokenOnly()) {
continue;
}
ProvisioningContext shadowCtx = ctx;
AttributesToReturn shadowAttrsToReturn = attrsToReturn;
PrismObject<ShadowType> currentShadow = change.getCurrentShadow();
ObjectClassComplexTypeDefinition changeObjectClassDefinition = change.getObjectClassDefinition();
if (changeObjectClassDefinition == null) {
if (!ctx.isWildcard() || change.getObjectDelta() == null || !change.getObjectDelta().isDelete()) {
throw new SchemaException("No object class definition in change "+change);
}
}
if (ctx.isWildcard() && changeObjectClassDefinition != null) {
shadowCtx = ctx.spawn(changeObjectClassDefinition.getTypeName());
if (shadowCtx.isWildcard()) {
String message = "Unkown object class "+changeObjectClassDefinition.getTypeName()+" found in synchronization delta";
parentResult.recordFatalError(message);
throw new SchemaException(message);
}
change.setObjectClassDefinition(shadowCtx.getObjectClassDefinition());
shadowAttrsToReturn = ProvisioningUtil.createAttributesToReturn(shadowCtx);
}
if (change.getObjectDelta() == null || !change.getObjectDelta().isDelete()) {
if (currentShadow == null) {
try {
LOGGER.trace("Re-fetching object {} because it is not in the change", change.getIdentifiers());
currentShadow = fetchResourceObject(shadowCtx,
change.getIdentifiers(), shadowAttrsToReturn, true, parentResult);
change.setCurrentShadow(currentShadow);
} catch (ObjectNotFoundException ex) {
parentResult.recordHandledError(
"Object detected in change log no longer exist on the resource. Skipping processing this object.", ex);
LOGGER.warn("Object detected in change log no longer exist on the resource. Skipping processing this object "
+ ex.getMessage());
iterator.remove();
continue;
}
} else {
if (ctx.isWildcard()) {
if (!MiscUtil.equals(shadowAttrsToReturn, attrsToReturn)) {
ResourceObjectIdentification identification = ResourceObjectIdentification.create(shadowCtx.getObjectClassDefinition(),
change.getIdentifiers());
identification.validatePrimaryIdenfiers();
LOGGER.trace("Re-fetching object {} because of attrsToReturn", identification);
currentShadow = connector.fetchObject(identification, shadowAttrsToReturn, ctx, parentResult);
}
}
PrismObject<ShadowType> processedCurrentShadow = postProcessResourceObjectRead(shadowCtx,
currentShadow, true, parentResult);
change.setCurrentShadow(processedCurrentShadow);
}
}
LOGGER.trace("Processed change\n:{}", change.debugDump());
}
computeResultStatus(parentResult);
LOGGER.trace("END fetch changes ({} changes)", changes == null ? "null" : changes.size());
return changes;
} | public list<change> fetchchanges(provisioningcontext ctx, prismproperty<?> lasttoken, operationresult parentresult) throws schemaexception, communicationexception, configurationexception, securityviolationexception, genericframeworkexception, objectnotfoundexception, expressionevaluationexception { validate.notnull(parentresult, "operation result must not be null."); logger.trace("start fetch changes, objectclass: {}", ctx.getobjectclassdefinition()); attributestoreturn attrstoreturn = null; if (!ctx.iswildcard()) { attrstoreturn = provisioningutil.createattributestoreturn(ctx); } connectorinstance connector = ctx.getconnector(livesynccapabilitytype.class, parentresult); list<change> changes = connector.fetchchanges(ctx.getobjectclassdefinition(), lasttoken, attrstoreturn, ctx, parentresult); iterator<change> iterator = changes.iterator(); while (iterator.hasnext()) { change change = iterator.next(); logger.trace("original change:\n{}", change.debugdump()); if (change.istokenonly()) { continue; } provisioningcontext shadowctx = ctx; attributestoreturn shadowattrstoreturn = attrstoreturn; prismobject<shadowtype> currentshadow = change.getcurrentshadow(); objectclasscomplextypedefinition changeobjectclassdefinition = change.getobjectclassdefinition(); if (changeobjectclassdefinition == null) { if (!ctx.iswildcard() || change.getobjectdelta() == null || !change.getobjectdelta().isdelete()) { throw new schemaexception("no object class definition in change "+change); } } if (ctx.iswildcard() && changeobjectclassdefinition != null) { shadowctx = ctx.spawn(changeobjectclassdefinition.gettypename()); if (shadowctx.iswildcard()) { string message = "unkown object class "+changeobjectclassdefinition.gettypename()+" found in synchronization delta"; parentresult.recordfatalerror(message); throw new schemaexception(message); } change.setobjectclassdefinition(shadowctx.getobjectclassdefinition()); shadowattrstoreturn = provisioningutil.createattributestoreturn(shadowctx); } if (change.getobjectdelta() == null || !change.getobjectdelta().isdelete()) { if (currentshadow == null) { try { logger.trace("re-fetching object {} because it is not in the change", change.getidentifiers()); currentshadow = fetchresourceobject(shadowctx, change.getidentifiers(), shadowattrstoreturn, true, parentresult); change.setcurrentshadow(currentshadow); } catch (objectnotfoundexception ex) { parentresult.recordhandlederror( "object detected in change log no longer exist on the resource. skipping processing this object.", ex); logger.warn("object detected in change log no longer exist on the resource. skipping processing this object " + ex.getmessage()); iterator.remove(); continue; } } else { if (ctx.iswildcard()) { if (!miscutil.equals(shadowattrstoreturn, attrstoreturn)) { resourceobjectidentification identification = resourceobjectidentification.create(shadowctx.getobjectclassdefinition(), change.getidentifiers()); identification.validateprimaryidenfiers(); logger.trace("re-fetching object {} because of attrstoreturn", identification); currentshadow = connector.fetchobject(identification, shadowattrstoreturn, ctx, parentresult); } } prismobject<shadowtype> processedcurrentshadow = postprocessresourceobjectread(shadowctx, currentshadow, true, parentresult); change.setcurrentshadow(processedcurrentshadow); } } logger.trace("processed change\n:{}", change.debugdump()); } computeresultstatus(parentresult); logger.trace("end fetch changes ({} changes)", changes == null ? "null" : changes.size()); return changes; } | valtri/midpoint | [
1,
0,
0,
0
] |
10,424 | @Override
public void run() {
if (TokenList.this.cancel.get()) {
return ;
}
topLevel = TokenHierarchy.get(doc).tokenSequence();
topLevelIsJava = topLevel.language() == JavaTokenId.language();
if (topLevelIsJava) {
ts = topLevel;
ts.moveStart();
ts.moveNext(); //XXX: what about empty document
}
} | @Override
public void run() {
if (TokenList.this.cancel.get()) {
return ;
}
topLevel = TokenHierarchy.get(doc).tokenSequence();
topLevelIsJava = topLevel.language() == JavaTokenId.language();
if (topLevelIsJava) {
ts = topLevel;
ts.moveStart();
ts.moveNext();
}
} | @override public void run() { if (tokenlist.this.cancel.get()) { return ; } toplevel = tokenhierarchy.get(doc).tokensequence(); toplevelisjava = toplevel.language() == javatokenid.language(); if (toplevelisjava) { ts = toplevel; ts.movestart(); ts.movenext(); } } | timfel/netbeans | [
0,
0,
1,
0
] |
18,754 | @RequestMapping(value = "/products", method=RequestMethod.GET)
@ResponseBody
public ReadableProductList getFiltered(
@RequestParam(value = "lang", required=false) String lang,
@RequestParam(value = "category", required=false) Long category,
@RequestParam(value = "manufacturer", required=false) Long manufacturer,
@RequestParam(value = "status", required=false) String status,
@RequestParam(value = "owner", required=false) Long owner,
@RequestParam(value = "start", required=false) Integer start,
@RequestParam(value = "count", required=false) Integer count,
HttpServletRequest request, HttpServletResponse response) throws Exception {
ProductCriteria criteria = new ProductCriteria();
if(!StringUtils.isBlank(lang)) {
criteria.setLanguage(lang);
}
if(!StringUtils.isBlank(status)) {
criteria.setStatus(status);
}
if(category != null) {
List<Long> categoryIds = new ArrayList<Long>();
categoryIds.add(category);
criteria.setCategoryIds(categoryIds);
}
if(manufacturer != null) {
criteria.setManufacturerId(manufacturer);
}
if(owner != null) {
criteria.setOwnerId(owner);
}
if(start != null) {
criteria.setStartIndex(start);
}
if(count != null) {
criteria.setMaxCount(count);
}
//TODO
//RENTAL add filter by owner
//REPOSITORY to use the new filters
try {
MerchantStore merchantStore = storeFacade.getByCode(com.salesmanager.core.business.constants.Constants.DEFAULT_STORE);
Language language = languageUtils.getRESTLanguage(request, merchantStore);
ReadableProductList productList = productFacade.getProductListsByCriterias(merchantStore, language, criteria);
return productList;
} catch(Exception e) {
LOGGER.error("Error while filtering products product",e);
try {
response.sendError(503, "Error while filtering products " + e.getMessage());
} catch (Exception ignore) {
}
return null;
}
} | @RequestMapping(value = "/products", method=RequestMethod.GET)
@ResponseBody
public ReadableProductList getFiltered(
@RequestParam(value = "lang", required=false) String lang,
@RequestParam(value = "category", required=false) Long category,
@RequestParam(value = "manufacturer", required=false) Long manufacturer,
@RequestParam(value = "status", required=false) String status,
@RequestParam(value = "owner", required=false) Long owner,
@RequestParam(value = "start", required=false) Integer start,
@RequestParam(value = "count", required=false) Integer count,
HttpServletRequest request, HttpServletResponse response) throws Exception {
ProductCriteria criteria = new ProductCriteria();
if(!StringUtils.isBlank(lang)) {
criteria.setLanguage(lang);
}
if(!StringUtils.isBlank(status)) {
criteria.setStatus(status);
}
if(category != null) {
List<Long> categoryIds = new ArrayList<Long>();
categoryIds.add(category);
criteria.setCategoryIds(categoryIds);
}
if(manufacturer != null) {
criteria.setManufacturerId(manufacturer);
}
if(owner != null) {
criteria.setOwnerId(owner);
}
if(start != null) {
criteria.setStartIndex(start);
}
if(count != null) {
criteria.setMaxCount(count);
}
try {
MerchantStore merchantStore = storeFacade.getByCode(com.salesmanager.core.business.constants.Constants.DEFAULT_STORE);
Language language = languageUtils.getRESTLanguage(request, merchantStore);
ReadableProductList productList = productFacade.getProductListsByCriterias(merchantStore, language, criteria);
return productList;
} catch(Exception e) {
LOGGER.error("Error while filtering products product",e);
try {
response.sendError(503, "Error while filtering products " + e.getMessage());
} catch (Exception ignore) {
}
return null;
}
} | @requestmapping(value = "/products", method=requestmethod.get) @responsebody public readableproductlist getfiltered( @requestparam(value = "lang", required=false) string lang, @requestparam(value = "category", required=false) long category, @requestparam(value = "manufacturer", required=false) long manufacturer, @requestparam(value = "status", required=false) string status, @requestparam(value = "owner", required=false) long owner, @requestparam(value = "start", required=false) integer start, @requestparam(value = "count", required=false) integer count, httpservletrequest request, httpservletresponse response) throws exception { productcriteria criteria = new productcriteria(); if(!stringutils.isblank(lang)) { criteria.setlanguage(lang); } if(!stringutils.isblank(status)) { criteria.setstatus(status); } if(category != null) { list<long> categoryids = new arraylist<long>(); categoryids.add(category); criteria.setcategoryids(categoryids); } if(manufacturer != null) { criteria.setmanufacturerid(manufacturer); } if(owner != null) { criteria.setownerid(owner); } if(start != null) { criteria.setstartindex(start); } if(count != null) { criteria.setmaxcount(count); } try { merchantstore merchantstore = storefacade.getbycode(com.salesmanager.core.business.constants.constants.default_store); language language = languageutils.getrestlanguage(request, merchantstore); readableproductlist productlist = productfacade.getproductlistsbycriterias(merchantstore, language, criteria); return productlist; } catch(exception e) { logger.error("error while filtering products product",e); try { response.senderror(503, "error while filtering products " + e.getmessage()); } catch (exception ignore) { } return null; } } | wxlfrank/shopizer | [
0,
1,
0,
0
] |
10,651 | public synchronized void updateState(ServiceStateProcessor<T> processor) {
// String transactionId = null;
// try {
// javax.transaction.TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager();
// TransactionImple transaction = (TransactionImple) transactionManager.getTransaction();
// if (transaction == null)
// return;
//
// int status = transaction.getStatus();
// transactionId = transaction.get_uid().stringForm();
// //transactionId = TransactionManager.getTransactionId();
// } catch (Exception e) {
// e.printStackTrace();
// return;
// }
BasicAction currentAction = ThreadActionData.currentAction();
if (currentAction == null)
return;
String transactionId = ThreadActionData.currentAction().get_uid().toString();
if (transactionId == null)
//TODO follow specified TX policy
return;
// we cannot proceed while a (another) prepare is in progress
while (isLocked()) {
try {
wait();
} catch (InterruptedException e) {
// ignore
}
}
T derivedState = getDerivedState(transactionId);
if (derivedState != null) {
if (!processor.validateState(derivedState)) {
//TODO get error message from processor
throw new WebServiceException("Invalid request");
}
// update the number of booked and free seats in the derived state
processor.updateState(derivedState);
} else {
if (!processor.validateState(currentState)) {
//TODO get error message from processor
throw new WebServiceException("Invalid request");
}
// create a state derived from the current state which holds the new value(s)
T childState = currentState.getDerivedState();
// updates current state using values from the specified derived state
processor.updateState(childState);
// install the specified derived state as the current transaction state
putDerivedState(transactionId, childState);
//currentState = childState;
}
} | public synchronized void updateState(ServiceStateProcessor<T> processor) {
BasicAction currentAction = ThreadActionData.currentAction();
if (currentAction == null)
return;
String transactionId = ThreadActionData.currentAction().get_uid().toString();
if (transactionId == null)
return;
while (isLocked()) {
try {
wait();
} catch (InterruptedException e) {
}
}
T derivedState = getDerivedState(transactionId);
if (derivedState != null) {
if (!processor.validateState(derivedState)) {
throw new WebServiceException("Invalid request");
}
processor.updateState(derivedState);
} else {
if (!processor.validateState(currentState)) {
throw new WebServiceException("Invalid request");
}
T childState = currentState.getDerivedState();
processor.updateState(childState);
putDerivedState(transactionId, childState);
}
} | public synchronized void updatestate(servicestateprocessor<t> processor) { basicaction currentaction = threadactiondata.currentaction(); if (currentaction == null) return; string transactionid = threadactiondata.currentaction().get_uid().tostring(); if (transactionid == null) return; while (islocked()) { try { wait(); } catch (interruptedexception e) { } } t derivedstate = getderivedstate(transactionid); if (derivedstate != null) { if (!processor.validatestate(derivedstate)) { throw new webserviceexception("invalid request"); } processor.updatestate(derivedstate); } else { if (!processor.validatestate(currentstate)) { throw new webserviceexception("invalid request"); } t childstate = currentstate.getderivedstate(); processor.updatestate(childstate); putderivedstate(transactionid, childstate); } } | tfisher1226/ARIES | [
1,
1,
0,
0
] |
10,652 | public synchronized void execute(ServiceStateProcessor<T> processor, String transactionId) {
// we cannot proceed while a (another) prepare is in progress
while (isLocked()) {
try {
wait();
} catch (InterruptedException e) {
// ignore
}
}
T derivedState = getDerivedState(transactionId);
if (derivedState != null) {
if (!processor.validateState(derivedState)) {
//TODO get error message from processor
throw new WebServiceException("Invalid request");
}
// update the number of booked and free seats in the derived state
processor.updateState(derivedState);
} else {
if (!processor.validateState(currentState)) {
//TODO get error message from processor
throw new WebServiceException("Invalid request");
}
// create a state derived from the current state which holds the new value(s)
T childState = currentState.getDerivedState();
// updates the current state using values from the specified derived state
processor.updateState(childState);
// install the specified derived state as the current transaction state
putDerivedState(transactionId, childState);
}
} | public synchronized void execute(ServiceStateProcessor<T> processor, String transactionId) {
while (isLocked()) {
try {
wait();
} catch (InterruptedException e) {
}
}
T derivedState = getDerivedState(transactionId);
if (derivedState != null) {
if (!processor.validateState(derivedState)) {
throw new WebServiceException("Invalid request");
}
processor.updateState(derivedState);
} else {
if (!processor.validateState(currentState)) {
throw new WebServiceException("Invalid request");
}
T childState = currentState.getDerivedState();
processor.updateState(childState);
putDerivedState(transactionId, childState);
}
} | public synchronized void execute(servicestateprocessor<t> processor, string transactionid) { while (islocked()) { try { wait(); } catch (interruptedexception e) { } } t derivedstate = getderivedstate(transactionid); if (derivedstate != null) { if (!processor.validatestate(derivedstate)) { throw new webserviceexception("invalid request"); } processor.updatestate(derivedstate); } else { if (!processor.validatestate(currentstate)) { throw new webserviceexception("invalid request"); } t childstate = currentstate.getderivedstate(); processor.updatestate(childstate); putderivedstate(transactionid, childstate); } } | tfisher1226/ARIES | [
0,
1,
0,
0
] |
2,461 | private void startIce4j(BundleContext bundleContext, ConfigurationService cfg) {
// TODO Packet logging for ice4j is not supported at this time.
StunStack.setPacketLogger(null);
// Make all ice4j properties system properties.
if (cfg != null) {
List<String> ice4jPropertyNames = cfg.getPropertyNamesByPrefix("org.ice4j.", false);
if (ice4jPropertyNames != null && !ice4jPropertyNames.isEmpty()) {
for (String propertyName : ice4jPropertyNames) {
String propertyValue = cfg.getString(propertyName);
// we expect the getString to return either null or a
// non-empty String object.
if (propertyValue != null)
System.setProperty(propertyName, propertyValue);
}
}
// These properties are moved to ice4j. This is to make sure that we
// still support the old names.
String oldPrefix = "org.jitsi.videobridge";
String newPrefix = "org.ice4j.ice.harvest";
for (String propertyName : new String[] { HarvesterConfiguration.NAT_HARVESTER_LOCAL_ADDRESS,
HarvesterConfiguration.NAT_HARVESTER_PUBLIC_ADDRESS, HarvesterConfiguration.DISABLE_AWS_HARVESTER,
HarvesterConfiguration.FORCE_AWS_HARVESTER,
HarvesterConfiguration.STUN_MAPPING_HARVESTER_ADDRESSES }) {
String propertyValue = cfg.getString(propertyName);
if (propertyValue != null) {
String newPropertyName = newPrefix + propertyName.substring(oldPrefix.length());
System.setProperty(newPropertyName, propertyValue);
}
}
String enableLipSync = cfg.getString(Endpoint.ENABLE_LIPSYNC_HACK_PNAME);
if (enableLipSync != null) {
System.setProperty(VideoChannel.ENABLE_LIPSYNC_HACK_PNAME, enableLipSync);
}
String disableNackTerminaton = cfg.getString(VideoChannel.DISABLE_NACK_TERMINATION_PNAME);
if (disableNackTerminaton != null) {
System.setProperty(RtxTransformer.DISABLE_NACK_TERMINATION_PNAME, disableNackTerminaton);
}
}
// Initialize the the host candidate interface filters in the ice4j
// stack.
try {
HostCandidateHarvester.initializeInterfaceFilters();
} catch (Exception e) {
logger.warn("There were errors during host candidate interface filters" + " initialization.", e);
}
// Start the initialization of the mapping candidate harvesters.
// Asynchronous, because the AWS and STUN harvester may take a long
// time to initialize.
new Thread(MappingCandidateHarvesters::initialize).start();
} | private void startIce4j(BundleContext bundleContext, ConfigurationService cfg) {
StunStack.setPacketLogger(null);
if (cfg != null) {
List<String> ice4jPropertyNames = cfg.getPropertyNamesByPrefix("org.ice4j.", false);
if (ice4jPropertyNames != null && !ice4jPropertyNames.isEmpty()) {
for (String propertyName : ice4jPropertyNames) {
String propertyValue = cfg.getString(propertyName);
if (propertyValue != null)
System.setProperty(propertyName, propertyValue);
}
}
String oldPrefix = "org.jitsi.videobridge";
String newPrefix = "org.ice4j.ice.harvest";
for (String propertyName : new String[] { HarvesterConfiguration.NAT_HARVESTER_LOCAL_ADDRESS,
HarvesterConfiguration.NAT_HARVESTER_PUBLIC_ADDRESS, HarvesterConfiguration.DISABLE_AWS_HARVESTER,
HarvesterConfiguration.FORCE_AWS_HARVESTER,
HarvesterConfiguration.STUN_MAPPING_HARVESTER_ADDRESSES }) {
String propertyValue = cfg.getString(propertyName);
if (propertyValue != null) {
String newPropertyName = newPrefix + propertyName.substring(oldPrefix.length());
System.setProperty(newPropertyName, propertyValue);
}
}
String enableLipSync = cfg.getString(Endpoint.ENABLE_LIPSYNC_HACK_PNAME);
if (enableLipSync != null) {
System.setProperty(VideoChannel.ENABLE_LIPSYNC_HACK_PNAME, enableLipSync);
}
String disableNackTerminaton = cfg.getString(VideoChannel.DISABLE_NACK_TERMINATION_PNAME);
if (disableNackTerminaton != null) {
System.setProperty(RtxTransformer.DISABLE_NACK_TERMINATION_PNAME, disableNackTerminaton);
}
}
try {
HostCandidateHarvester.initializeInterfaceFilters();
} catch (Exception e) {
logger.warn("There were errors during host candidate interface filters" + " initialization.", e);
}
new Thread(MappingCandidateHarvesters::initialize).start();
} | private void startice4j(bundlecontext bundlecontext, configurationservice cfg) { stunstack.setpacketlogger(null); if (cfg != null) { list<string> ice4jpropertynames = cfg.getpropertynamesbyprefix("org.ice4j.", false); if (ice4jpropertynames != null && !ice4jpropertynames.isempty()) { for (string propertyname : ice4jpropertynames) { string propertyvalue = cfg.getstring(propertyname); if (propertyvalue != null) system.setproperty(propertyname, propertyvalue); } } string oldprefix = "org.jitsi.videobridge"; string newprefix = "org.ice4j.ice.harvest"; for (string propertyname : new string[] { harvesterconfiguration.nat_harvester_local_address, harvesterconfiguration.nat_harvester_public_address, harvesterconfiguration.disable_aws_harvester, harvesterconfiguration.force_aws_harvester, harvesterconfiguration.stun_mapping_harvester_addresses }) { string propertyvalue = cfg.getstring(propertyname); if (propertyvalue != null) { string newpropertyname = newprefix + propertyname.substring(oldprefix.length()); system.setproperty(newpropertyname, propertyvalue); } } string enablelipsync = cfg.getstring(endpoint.enable_lipsync_hack_pname); if (enablelipsync != null) { system.setproperty(videochannel.enable_lipsync_hack_pname, enablelipsync); } string disablenackterminaton = cfg.getstring(videochannel.disable_nack_termination_pname); if (disablenackterminaton != null) { system.setproperty(rtxtransformer.disable_nack_termination_pname, disablenackterminaton); } } try { hostcandidateharvester.initializeinterfacefilters(); } catch (exception e) { logger.warn("there were errors during host candidate interface filters" + " initialization.", e); } new thread(mappingcandidateharvesters::initialize).start(); } | yatyanng/jvb | [
0,
0,
1,
0
] |
10,668 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
private void registerDisplayListener() {
final DisplayManager displayManager =
(DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
final Handler handler = new Handler(Looper.getMainLooper());
displayManager.registerDisplayListener(mDisplayListener, handler);
} | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
private void registerDisplayListener() {
final DisplayManager displayManager =
(DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
final Handler handler = new Handler(Looper.getMainLooper());
displayManager.registerDisplayListener(mDisplayListener, handler);
} | @requiresapi(api = build.version_codes.jelly_bean_mr1) private void registerdisplaylistener() { final displaymanager displaymanager = (displaymanager) getsystemservice(context.display_service); final handler handler = new handler(looper.getmainlooper()); displaymanager.registerdisplaylistener(mdisplaylistener, handler); } | thereiskeks/HayaiLauncher | [
0,
0,
0,
0
] |
10,727 | private Point getAbsoluteLocation() throws UiGuardException {
if(UiGuardSettings.isIECore()){
return getIECoreAbsoluteLocation();
}else if(UiGuardSettings.isChromeCore()){
return getChromeCoreAbsoluteLocation();
}else if(UiGuardSettings.isFirefoxCore()){
return getFireFoxCoreAbsoluteLocation();
}else{
//TODO more browser should be supported
throw new UiGuardException("[Error][This function only support IE,CHROME,FIREFOX by this time]");
}
} | private Point getAbsoluteLocation() throws UiGuardException {
if(UiGuardSettings.isIECore()){
return getIECoreAbsoluteLocation();
}else if(UiGuardSettings.isChromeCore()){
return getChromeCoreAbsoluteLocation();
}else if(UiGuardSettings.isFirefoxCore()){
return getFireFoxCoreAbsoluteLocation();
}else{
throw new UiGuardException("[Error][This function only support IE,CHROME,FIREFOX by this time]");
}
} | private point getabsolutelocation() throws uiguardexception { if(uiguardsettings.isiecore()){ return getiecoreabsolutelocation(); }else if(uiguardsettings.ischromecore()){ return getchromecoreabsolutelocation(); }else if(uiguardsettings.isfirefoxcore()){ return getfirefoxcoreabsolutelocation(); }else{ throw new uiguardexception("[error][this function only support ie,chrome,firefox by this time]"); } } | uiguard/uiguard | [
0,
1,
0,
0
] |
10,867 | public static void addJsonToGrid (
OutputStream outputStream,
AccessibilityResult accessibilityResult,
List<TaskError> scenarioApplicationWarnings,
List<TaskError> scenarioApplicationInfo,
PathResult pathResult
) throws IOException {
var jsonBlock = new GridJsonBlock();
jsonBlock.scenarioApplicationInfo = scenarioApplicationInfo;
jsonBlock.scenarioApplicationWarnings = scenarioApplicationWarnings;
if (accessibilityResult != null) {
// Due to the application of distance decay functions, we may want to make the shift to non-integer
// accessibility values (especially for cases where there are relatively few opportunities across the whole
// study area). But we'd need to control the number of decimal places serialized into the JSON.
jsonBlock.accessibility = accessibilityResult.getIntValues();
}
jsonBlock.pathSummaries = pathResult == null ? Collections.EMPTY_LIST : pathResult.getPathIterationsForDestination();
LOG.debug("Travel time surface written, appending {}.", jsonBlock);
// We could do this when setting up the Spark handler, supplying writeValue as the response transformer
// But then you also have to handle the case where you are returning raw bytes.
JsonUtilities.objectMapper.writeValue(outputStream, jsonBlock);
LOG.debug("Done writing");
} | public static void addJsonToGrid (
OutputStream outputStream,
AccessibilityResult accessibilityResult,
List<TaskError> scenarioApplicationWarnings,
List<TaskError> scenarioApplicationInfo,
PathResult pathResult
) throws IOException {
var jsonBlock = new GridJsonBlock();
jsonBlock.scenarioApplicationInfo = scenarioApplicationInfo;
jsonBlock.scenarioApplicationWarnings = scenarioApplicationWarnings;
if (accessibilityResult != null) {
jsonBlock.accessibility = accessibilityResult.getIntValues();
}
jsonBlock.pathSummaries = pathResult == null ? Collections.EMPTY_LIST : pathResult.getPathIterationsForDestination();
LOG.debug("Travel time surface written, appending {}.", jsonBlock);
JsonUtilities.objectMapper.writeValue(outputStream, jsonBlock);
LOG.debug("Done writing");
} | public static void addjsontogrid ( outputstream outputstream, accessibilityresult accessibilityresult, list<taskerror> scenarioapplicationwarnings, list<taskerror> scenarioapplicationinfo, pathresult pathresult ) throws ioexception { var jsonblock = new gridjsonblock(); jsonblock.scenarioapplicationinfo = scenarioapplicationinfo; jsonblock.scenarioapplicationwarnings = scenarioapplicationwarnings; if (accessibilityresult != null) { jsonblock.accessibility = accessibilityresult.getintvalues(); } jsonblock.pathsummaries = pathresult == null ? collections.empty_list : pathresult.getpathiterationsfordestination(); log.debug("travel time surface written, appending {}.", jsonblock); jsonutilities.objectmapper.writevalue(outputstream, jsonblock); log.debug("done writing"); } | vlc/r5 | [
1,
0,
0,
0
] |
2,693 | public void testArrayEnumerationWithDataModification() throws CouchbaseLiteException {
MutableArray array = new MutableArray();
for (int i = 0; i < 2; i++)
array.addValue(i);
Iterator<Object> itr = array.iterator();
int count = 0;
try {
while (itr.hasNext()) {
itr.next();
if (count++ == 0)
array.addValue(2);
}
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException e) {
}
assertEquals(3, array.count());
assertEquals(Arrays.asList(0, 1, 2).toString(), array.toList().toString());
MutableDocument doc = createMutableDocument("doc1");
doc.setValue("array", array);
doc = save(doc).toMutable();
array = doc.getArray("array");
itr = array.iterator();
count = 0;
try {
while (itr.hasNext()) {
itr.next();
if (count++ == 0)
array.addValue(3);
}
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException e) {
}
assertEquals(4, array.count());
assertEquals(Arrays.asList(0, 1, 2, 3).toString(), array.toList().toString());
} | public void testArrayEnumerationWithDataModification() throws CouchbaseLiteException {
MutableArray array = new MutableArray();
for (int i = 0; i < 2; i++)
array.addValue(i);
Iterator<Object> itr = array.iterator();
int count = 0;
try {
while (itr.hasNext()) {
itr.next();
if (count++ == 0)
array.addValue(2);
}
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException e) {
}
assertEquals(3, array.count());
assertEquals(Arrays.asList(0, 1, 2).toString(), array.toList().toString());
MutableDocument doc = createMutableDocument("doc1");
doc.setValue("array", array);
doc = save(doc).toMutable();
array = doc.getArray("array");
itr = array.iterator();
count = 0;
try {
while (itr.hasNext()) {
itr.next();
if (count++ == 0)
array.addValue(3);
}
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException e) {
}
assertEquals(4, array.count());
assertEquals(Arrays.asList(0, 1, 2, 3).toString(), array.toList().toString());
} | public void testarrayenumerationwithdatamodification() throws couchbaseliteexception { mutablearray array = new mutablearray(); for (int i = 0; i < 2; i++) array.addvalue(i); iterator<object> itr = array.iterator(); int count = 0; try { while (itr.hasnext()) { itr.next(); if (count++ == 0) array.addvalue(2); } fail("expected concurrentmodificationexception"); } catch (concurrentmodificationexception e) { } assertequals(3, array.count()); assertequals(arrays.aslist(0, 1, 2).tostring(), array.tolist().tostring()); mutabledocument doc = createmutabledocument("doc1"); doc.setvalue("array", array); doc = save(doc).tomutable(); array = doc.getarray("array"); itr = array.iterator(); count = 0; try { while (itr.hasnext()) { itr.next(); if (count++ == 0) array.addvalue(3); } fail("expected concurrentmodificationexception"); } catch (concurrentmodificationexception e) { } assertequals(4, array.count()); assertequals(arrays.aslist(0, 1, 2, 3).tostring(), array.tolist().tostring()); } | zebra1024/couchbase-lite-android | [
0,
0,
0,
1
] |
19,120 | @GET
@Path("updates")
public Uni<Collection<World>> updates(@QueryParam("queries") String queries) {
return worldRepository.inSession(session -> {
// FIXME: not supported
// session.setJdbcBatchSize(worlds.size());
session.setFlushMode(FlushMode.MANUAL);
var worlds = randomWorldForRead(session, parseQueryCount(queries));
return worlds.flatMap(worldsCollection -> {
worldsCollection.forEach( w -> {
//Read the one field, as required by the following rule:
// # vi. At least the randomNumber field must be read from the database result set.
final int previousRead = w.getRandomNumber();
//Update it, but make sure to exclude the current number as Hibernate optimisations would have us "fail"
//the verification:
w.setRandomNumber(randomWorldNumber(previousRead));
} );
return worldRepository.update(session, worldsCollection);
});
});
} | @GET
@Path("updates")
public Uni<Collection<World>> updates(@QueryParam("queries") String queries) {
return worldRepository.inSession(session -> {
session.setFlushMode(FlushMode.MANUAL);
var worlds = randomWorldForRead(session, parseQueryCount(queries));
return worlds.flatMap(worldsCollection -> {
worldsCollection.forEach( w -> {
final int previousRead = w.getRandomNumber();
w.setRandomNumber(randomWorldNumber(previousRead));
} );
return worldRepository.update(session, worldsCollection);
});
});
} | @get @path("updates") public uni<collection<world>> updates(@queryparam("queries") string queries) { return worldrepository.insession(session -> { session.setflushmode(flushmode.manual); var worlds = randomworldforread(session, parsequerycount(queries)); return worlds.flatmap(worldscollection -> { worldscollection.foreach( w -> { final int previousread = w.getrandomnumber(); w.setrandomnumber(randomworldnumber(previousread)); } ); return worldrepository.update(session, worldscollection); }); }); } | tommilligan/FrameworkBenchmarks | [
0,
0,
1,
0
] |
19,230 | public static LocalDefUse fromBundleFragment(Map<String, Object> bundleFragment) {
// TODO deserialize the lambda block...
return new LocalDefUse(null);
} | public static LocalDefUse fromBundleFragment(Map<String, Object> bundleFragment) {
return new LocalDefUse(null);
} | public static localdefuse frombundlefragment(map<string, object> bundlefragment) { return new localdefuse(null); } | undeadinu/viskell | [
0,
1,
0,
0
] |
19,238 | int getRankInBlock(int rankPosition) {
if (rank == null) {
return -1;
}
assert rankPosition == denseRankPosition(rankPosition);
int rankIndex = rankPosition >> RANK_BLOCK_BITS;
return rankIndex >= rank.size() ? -1 : (int) rank.get(rankIndex);
} | int getRankInBlock(int rankPosition) {
if (rank == null) {
return -1;
}
assert rankPosition == denseRankPosition(rankPosition);
int rankIndex = rankPosition >> RANK_BLOCK_BITS;
return rankIndex >= rank.size() ? -1 : (int) rank.get(rankIndex);
} | int getrankinblock(int rankposition) { if (rank == null) { return -1; } assert rankposition == denserankposition(rankposition); int rankindex = rankposition >> rank_block_bits; return rankindex >= rank.size() ? -1 : (int) rank.get(rankindex); } | tafgit/ToF-Test | [
1,
0,
0,
0
] |
2,942 | @Override
public Boolean visit(CFieldReference pE) {
return !alreadyAssigned.contains(pE);
} | @Override
public Boolean visit(CFieldReference pE) {
return !alreadyAssigned.contains(pE);
} | @override public boolean visit(cfieldreference pe) { return !alreadyassigned.contains(pe); } | wqythu13/Test | [
1,
0,
0,
0
] |
3,182 | protected List<T> getList(String[] projection, String selection, String[] selectionArgs,
String sortOrder, Integer limit) {
List<T> rows = new ArrayList<>();
//noinspection TryWithIdenticalCatches
try {
Cursor c = mCr.query(mUri, projection, selection, selectionArgs, sortOrder);
if (c != null) {
if (c.moveToFirst()) {
int i = 0;
Constructor<T> constructor =
mTableRowClass.getConstructor(this.getClass(), Cursor.class);
do {
rows.add(constructor.newInstance(this, c));
i++;
} while ((limit == null || limit > i) && c.moveToNext());
}
c.close();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
// We don't want to pass the exceptions up or rethrow a more generic exception, since
// then, we would have to handle this on every object instantiation, but these
// exceptions should never throw in production, since these are static code issues
// (wrongly defined classes) which should be handled once, straight away and then
// never change again.
System.exit(-1);
} catch (InstantiationException e) {
e.printStackTrace();
System.exit(-1);
} catch (IllegalAccessException e) {
e.printStackTrace();
System.exit(-1);
} catch (InvocationTargetException e) {
e.printStackTrace();
System.exit(-1);
}
return rows;
} | protected List<T> getList(String[] projection, String selection, String[] selectionArgs,
String sortOrder, Integer limit) {
List<T> rows = new ArrayList<>();
try {
Cursor c = mCr.query(mUri, projection, selection, selectionArgs, sortOrder);
if (c != null) {
if (c.moveToFirst()) {
int i = 0;
Constructor<T> constructor =
mTableRowClass.getConstructor(this.getClass(), Cursor.class);
do {
rows.add(constructor.newInstance(this, c));
i++;
} while ((limit == null || limit > i) && c.moveToNext());
}
c.close();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
System.exit(-1);
} catch (InstantiationException e) {
e.printStackTrace();
System.exit(-1);
} catch (IllegalAccessException e) {
e.printStackTrace();
System.exit(-1);
} catch (InvocationTargetException e) {
e.printStackTrace();
System.exit(-1);
}
return rows;
} | protected list<t> getlist(string[] projection, string selection, string[] selectionargs, string sortorder, integer limit) { list<t> rows = new arraylist<>(); try { cursor c = mcr.query(muri, projection, selection, selectionargs, sortorder); if (c != null) { if (c.movetofirst()) { int i = 0; constructor<t> constructor = mtablerowclass.getconstructor(this.getclass(), cursor.class); do { rows.add(constructor.newinstance(this, c)); i++; } while ((limit == null || limit > i) && c.movetonext()); } c.close(); } } catch (nosuchmethodexception e) { e.printstacktrace(); system.exit(-1); } catch (instantiationexception e) { e.printstacktrace(); system.exit(-1); } catch (illegalaccessexception e) { e.printstacktrace(); system.exit(-1); } catch (invocationtargetexception e) { e.printstacktrace(); system.exit(-1); } return rows; } | tladesignz/DNATools | [
0,
0,
1,
0
] |
3,186 | protected List<T> getList(String selection) {
return getList(selection, null);
} | protected List<T> getList(String selection) {
return getList(selection, null);
} | protected list<t> getlist(string selection) { return getlist(selection, null); } | tladesignz/DNATools | [
0,
0,
1,
0
] |
3,187 | @SuppressWarnings("unused")
protected List<T> getList() {
return getList(null);
} | @SuppressWarnings("unused")
protected List<T> getList() {
return getList(null);
} | @suppresswarnings("unused") protected list<t> getlist() { return getlist(null); } | tladesignz/DNATools | [
0,
0,
1,
0
] |
3,192 | @SuppressWarnings("unused")
protected T get(String[] selectionArgs) {
return get(mUniqueRowSelection, selectionArgs);
} | @SuppressWarnings("unused")
protected T get(String[] selectionArgs) {
return get(mUniqueRowSelection, selectionArgs);
} | @suppresswarnings("unused") protected t get(string[] selectionargs) { return get(muniquerowselection, selectionargs); } | tladesignz/DNATools | [
0,
0,
1,
0
] |
19,585 | @Override
public boolean onPaymentAppCreated(PaymentApp paymentApp) {
// Ignores the service worker payment apps in WebLayer until -
// TODO(crbug.com/1224420): WebLayer supports Service worker payment apps.
return paymentApp.getPaymentAppType() != PaymentAppType.SERVICE_WORKER_APP;
} | @Override
public boolean onPaymentAppCreated(PaymentApp paymentApp) {
return paymentApp.getPaymentAppType() != PaymentAppType.SERVICE_WORKER_APP;
} | @override public boolean onpaymentappcreated(paymentapp paymentapp) { return paymentapp.getpaymentapptype() != paymentapptype.service_worker_app; } | zealoussnow/chromium | [
0,
1,
0,
0
] |
11,432 | public String toXml(int indentLevel){
String indent = "";
for (int i = 1; i <= indentLevel; i++)
indent = indent + "\t";
String xml = indent + "<MonitorCategory id='" + this.id + "' name='" +
this.name + "' priority='" + this.priority + "' status='" +
this.status + "' delete_time='" +
this.deleteTime + "' note='" +
this.note + "' />";
return xml;
} | public String toXml(int indentLevel){
String indent = "";
for (int i = 1; i <= indentLevel; i++)
indent = indent + "\t";
String xml = indent + "<MonitorCategory id='" + this.id + "' name='" +
this.name + "' priority='" + this.priority + "' status='" +
this.status + "' delete_time='" +
this.deleteTime + "' note='" +
this.note + "' />";
return xml;
} | public string toxml(int indentlevel){ string indent = ""; for (int i = 1; i <= indentlevel; i++) indent = indent + "\t"; string xml = indent + "<monitorcategory id='" + this.id + "' name='" + this.name + "' priority='" + this.priority + "' status='" + this.status + "' delete_time='" + this.deletetime + "' note='" + this.note + "' />"; return xml; } | tabneib/petimo | [
0,
0,
0,
0
] |