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
|
---|---|---|---|---|---|
19,939 | public boolean reachedAllGoals ( ) {
for ( EarliestLayerSVA goal : this.g ) {
if ( goal == null || goal.earliestLayer == -1 ) {
return false;
}
}
return true;
} | public boolean reachedAllGoals ( ) {
for ( EarliestLayerSVA goal : this.g ) {
if ( goal == null || goal.earliestLayer == -1 ) {
return false;
}
}
return true;
} | public boolean reachedallgoals ( ) { for ( earliestlayersva goal : this.g ) { if ( goal == null || goal.earliestlayer == -1 ) { return false; } } return true; } | uwe-koeckemann/SpiderPlan | [
0,
0,
0,
1
] |
19,996 | @Override
public void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) {
/*
// TODO Need to code this check somehow =/
[5D 00] // Opcode
[02] // Map Portal
[06 00 68 69 64 65 30 32] //the entered portal name
[6B 0D] // to x
[30 01] // to y
[C5 00] // x
[C4 01] // y
slea.readByte();
String portal = slea.readMapleAsciiString();
int toX = slea.readShort();
int toY = slea.readShort();
int X = slea.readShort();
int Y = slea.readShort();
log.info("[Hacks] Player {} is trying to jump to a different map portal rather than the correct one");
*/
} | @Override
public void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) {
} | @override public void handlepacket(seekablelittleendianaccessor slea, mapleclient c) { } | xzs603/codeLearning | [
0,
1,
0,
0
] |
20,016 | private HashMap<String, Object> createAttributesMap () {
HashMap<String, Object> attributes = new HashMap<String, Object>(2);
// XXX add more if requested
if(getInfo() != null) {
attributes.put(ATTRIBUTE_DISPLAY_NAME, getDisplayName());
attributes.put(ATTRIBUTE_URL, getUrl());
}
return attributes;
} | private HashMap<String, Object> createAttributesMap () {
HashMap<String, Object> attributes = new HashMap<String, Object>(2);
if(getInfo() != null) {
attributes.put(ATTRIBUTE_DISPLAY_NAME, getDisplayName());
attributes.put(ATTRIBUTE_URL, getUrl());
}
return attributes;
} | private hashmap<string, object> createattributesmap () { hashmap<string, object> attributes = new hashmap<string, object>(2); if(getinfo() != null) { attributes.put(attribute_display_name, getdisplayname()); attributes.put(attribute_url, geturl()); } return attributes; } | timfel/netbeans | [
0,
1,
0,
0
] |
3,666 | public static Boolean isMuted () {
return muteAudio_b;
} | public static Boolean isMuted () {
return muteAudio_b;
} | public static boolean ismuted () { return muteaudio_b; } | tuxjsmith/logFarmDMS | [
0,
0,
0,
0
] |
3,667 | public static void setMuteAudio ( Boolean b ) {
muteAudio_b = b;
} | public static void setMuteAudio ( Boolean b ) {
muteAudio_b = b;
} | public static void setmuteaudio ( boolean b ) { muteaudio_b = b; } | tuxjsmith/logFarmDMS | [
0,
0,
0,
0
] |
3,668 | public Boolean getSliderHasBeenMoved () {
return sliderHasBeenMoved_b;
} | public Boolean getSliderHasBeenMoved () {
return sliderHasBeenMoved_b;
} | public boolean getsliderhasbeenmoved () { return sliderhasbeenmoved_b; } | tuxjsmith/logFarmDMS | [
0,
0,
0,
0
] |
3,669 | public void setSliderHasBeenMoved ( Boolean b ) {
sliderHasBeenMoved_b = b;
} | public void setSliderHasBeenMoved ( Boolean b ) {
sliderHasBeenMoved_b = b;
} | public void setsliderhasbeenmoved ( boolean b ) { sliderhasbeenmoved_b = b; } | tuxjsmith/logFarmDMS | [
0,
0,
0,
0
] |
3,670 | public static Boolean getCaptureAudio () {
return captureAudio_b;
} | public static Boolean getCaptureAudio () {
return captureAudio_b;
} | public static boolean getcaptureaudio () { return captureaudio_b; } | tuxjsmith/logFarmDMS | [
0,
0,
0,
0
] |
3,671 | public static void setCaptureAudio ( Boolean b ) {
captureAudio_b = b;
} | public static void setCaptureAudio ( Boolean b ) {
captureAudio_b = b;
} | public static void setcaptureaudio ( boolean b ) { captureaudio_b = b; } | tuxjsmith/logFarmDMS | [
0,
0,
0,
0
] |
3,672 | public static LFDMS_GUI getAudioPlaybackOwner () {
return audioPlaybackOwner;
} | public static LFDMS_GUI getAudioPlaybackOwner () {
return audioPlaybackOwner;
} | public static lfdms_gui getaudioplaybackowner () { return audioplaybackowner; } | tuxjsmith/logFarmDMS | [
0,
0,
0,
0
] |
20,094 | private ClusterConfig buildNormalClusterConfig(DalConnectionStringConfigure configure) {
ClusterConfigWithNoVersion clusterConfig =
new ClusterConfigWithNoVersion(configure.getName(), ClusterType.NORMAL, DatabaseCategory.MYSQL);
DatabaseShardConfigImpl databaseShardConfig = new DatabaseShardConfigImpl(clusterConfig, 0);
DatabaseConfigImpl databaseConfig = new DatabaseConfigImpl(databaseShardConfig);
HostAndPort hostAndPort = ConnectionStringParser.parseHostPortFromURL(configure.getConnectionUrl());
databaseConfig.setIp(hostAndPort.getHost());
databaseConfig.setPort(hostAndPort.getPort());
databaseConfig.setDbName(provider.getDbName());
databaseConfig.setUid(configure.getUserName());
databaseConfig.setPwd(configure.getPassword());
databaseShardConfig.addDatabaseConfig(databaseConfig);
clusterConfig.addDatabaseShardConfig(databaseShardConfig);
// todo-lhj make configurable RouteStrategy of
clusterConfig.setRouteStrategyConfig(new DefaultClusterRouteStrategyConfig(RouteStrategyEnum.READ_MASTER.name()));
clusterConfig.setCustomizedOption(new DefaultDalConfigCustomizedOption());
return clusterConfig;
} | private ClusterConfig buildNormalClusterConfig(DalConnectionStringConfigure configure) {
ClusterConfigWithNoVersion clusterConfig =
new ClusterConfigWithNoVersion(configure.getName(), ClusterType.NORMAL, DatabaseCategory.MYSQL);
DatabaseShardConfigImpl databaseShardConfig = new DatabaseShardConfigImpl(clusterConfig, 0);
DatabaseConfigImpl databaseConfig = new DatabaseConfigImpl(databaseShardConfig);
HostAndPort hostAndPort = ConnectionStringParser.parseHostPortFromURL(configure.getConnectionUrl());
databaseConfig.setIp(hostAndPort.getHost());
databaseConfig.setPort(hostAndPort.getPort());
databaseConfig.setDbName(provider.getDbName());
databaseConfig.setUid(configure.getUserName());
databaseConfig.setPwd(configure.getPassword());
databaseShardConfig.addDatabaseConfig(databaseConfig);
clusterConfig.addDatabaseShardConfig(databaseShardConfig);
clusterConfig.setRouteStrategyConfig(new DefaultClusterRouteStrategyConfig(RouteStrategyEnum.READ_MASTER.name()));
clusterConfig.setCustomizedOption(new DefaultDalConfigCustomizedOption());
return clusterConfig;
} | private clusterconfig buildnormalclusterconfig(dalconnectionstringconfigure configure) { clusterconfigwithnoversion clusterconfig = new clusterconfigwithnoversion(configure.getname(), clustertype.normal, databasecategory.mysql); databaseshardconfigimpl databaseshardconfig = new databaseshardconfigimpl(clusterconfig, 0); databaseconfigimpl databaseconfig = new databaseconfigimpl(databaseshardconfig); hostandport hostandport = connectionstringparser.parsehostportfromurl(configure.getconnectionurl()); databaseconfig.setip(hostandport.gethost()); databaseconfig.setport(hostandport.getport()); databaseconfig.setdbname(provider.getdbname()); databaseconfig.setuid(configure.getusername()); databaseconfig.setpwd(configure.getpassword()); databaseshardconfig.adddatabaseconfig(databaseconfig); clusterconfig.adddatabaseshardconfig(databaseshardconfig); clusterconfig.setroutestrategyconfig(new defaultclusterroutestrategyconfig(routestrategyenum.read_master.name())); clusterconfig.setcustomizedoption(new defaultdalconfigcustomizedoption()); return clusterconfig; } | wwjiang007/dal | [
1,
0,
0,
0
] |
20,104 | static BookmarkId addBookmarkInternal(Context context, BookmarkModel bookmarkModel,
String title, GURL url, WebContents webContents, @Nullable BookmarkId parent,
@BookmarkType int bookmarkType) {
parent = parent == null ? getLastUsedParent(context, bookmarkModel) : parent;
BookmarkItem parentItem = null;
if (parent != null) {
parentItem = bookmarkModel.getBookmarkById(parent);
}
if (parent == null || parentItem == null || parentItem.isManaged()
|| !parentItem.isFolder()) {
parent = bookmarkModel.getDefaultFolder();
}
// Reading list items will be added when either one of the 2 conditions is met:
// 1. The bookmark type explicitly specifies READING_LIST.
// 2. The last used parent implicitly specifies READING_LIST.
if (ReadingListFeatures.isReadingListEnabled()
&& (bookmarkType == BookmarkType.READING_LIST
|| parent.getType() == BookmarkType.READING_LIST)) {
return bookmarkModel.addToReadingList(title, url);
}
BookmarkId bookmarkId = null;
// Use "New tab" as title for both incognito and regular NTP.
if (url.getSpec().equals(UrlConstants.NTP_URL)) {
title = context.getResources().getString(R.string.new_tab_title);
}
// The shopping list experiment saves extra metadata along with the bookmark.
if (ChromeFeatureList.isInitialized()
&& ChromeFeatureList.isEnabled(ChromeFeatureList.SHOPPING_LIST)) {
bookmarkId = bookmarkModel.addPowerBookmark(
webContents, parent, bookmarkModel.getChildCount(parent), title, url);
} else {
bookmarkId = bookmarkModel.addBookmark(
parent, bookmarkModel.getChildCount(parent), title, url);
}
// TODO(lazzzis): remove log after bookmark sync is fixed, crbug.com/986978
if (bookmarkId == null) {
Log.e(TAG,
"Failed to add bookmarks: parentTypeAndId %s, defaultFolderTypeAndId %s, "
+ "mobileFolderTypeAndId %s, parentEditable Managed isFolder %s,",
parent, bookmarkModel.getDefaultFolder(), bookmarkModel.getMobileFolderId(),
parentItem == null ? "null"
: (parentItem.isEditable() + " " + parentItem.isManaged()
+ " " + parentItem.isFolder()));
setLastUsedParent(context, bookmarkModel.getDefaultFolder());
}
return bookmarkId;
} | static BookmarkId addBookmarkInternal(Context context, BookmarkModel bookmarkModel,
String title, GURL url, WebContents webContents, @Nullable BookmarkId parent,
@BookmarkType int bookmarkType) {
parent = parent == null ? getLastUsedParent(context, bookmarkModel) : parent;
BookmarkItem parentItem = null;
if (parent != null) {
parentItem = bookmarkModel.getBookmarkById(parent);
}
if (parent == null || parentItem == null || parentItem.isManaged()
|| !parentItem.isFolder()) {
parent = bookmarkModel.getDefaultFolder();
}
if (ReadingListFeatures.isReadingListEnabled()
&& (bookmarkType == BookmarkType.READING_LIST
|| parent.getType() == BookmarkType.READING_LIST)) {
return bookmarkModel.addToReadingList(title, url);
}
BookmarkId bookmarkId = null;
if (url.getSpec().equals(UrlConstants.NTP_URL)) {
title = context.getResources().getString(R.string.new_tab_title);
}
if (ChromeFeatureList.isInitialized()
&& ChromeFeatureList.isEnabled(ChromeFeatureList.SHOPPING_LIST)) {
bookmarkId = bookmarkModel.addPowerBookmark(
webContents, parent, bookmarkModel.getChildCount(parent), title, url);
} else {
bookmarkId = bookmarkModel.addBookmark(
parent, bookmarkModel.getChildCount(parent), title, url);
}
if (bookmarkId == null) {
Log.e(TAG,
"Failed to add bookmarks: parentTypeAndId %s, defaultFolderTypeAndId %s, "
+ "mobileFolderTypeAndId %s, parentEditable Managed isFolder %s,",
parent, bookmarkModel.getDefaultFolder(), bookmarkModel.getMobileFolderId(),
parentItem == null ? "null"
: (parentItem.isEditable() + " " + parentItem.isManaged()
+ " " + parentItem.isFolder()));
setLastUsedParent(context, bookmarkModel.getDefaultFolder());
}
return bookmarkId;
} | static bookmarkid addbookmarkinternal(context context, bookmarkmodel bookmarkmodel, string title, gurl url, webcontents webcontents, @nullable bookmarkid parent, @bookmarktype int bookmarktype) { parent = parent == null ? getlastusedparent(context, bookmarkmodel) : parent; bookmarkitem parentitem = null; if (parent != null) { parentitem = bookmarkmodel.getbookmarkbyid(parent); } if (parent == null || parentitem == null || parentitem.ismanaged() || !parentitem.isfolder()) { parent = bookmarkmodel.getdefaultfolder(); } if (readinglistfeatures.isreadinglistenabled() && (bookmarktype == bookmarktype.reading_list || parent.gettype() == bookmarktype.reading_list)) { return bookmarkmodel.addtoreadinglist(title, url); } bookmarkid bookmarkid = null; if (url.getspec().equals(urlconstants.ntp_url)) { title = context.getresources().getstring(r.string.new_tab_title); } if (chromefeaturelist.isinitialized() && chromefeaturelist.isenabled(chromefeaturelist.shopping_list)) { bookmarkid = bookmarkmodel.addpowerbookmark( webcontents, parent, bookmarkmodel.getchildcount(parent), title, url); } else { bookmarkid = bookmarkmodel.addbookmark( parent, bookmarkmodel.getchildcount(parent), title, url); } if (bookmarkid == null) { log.e(tag, "failed to add bookmarks: parenttypeandid %s, defaultfoldertypeandid %s, " + "mobilefoldertypeandid %s, parenteditable managed isfolder %s,", parent, bookmarkmodel.getdefaultfolder(), bookmarkmodel.getmobilefolderid(), parentitem == null ? "null" : (parentitem.iseditable() + " " + parentitem.ismanaged() + " " + parentitem.isfolder())); setlastusedparent(context, bookmarkmodel.getdefaultfolder()); } return bookmarkid; } | zealoussnow/chromium | [
1,
0,
0,
0
] |
3,803 | public void testPartionedQuadtreeNodeIndex() throws Exception {
PartitionedQuadtreeNodeIndexFile pf = new PartitionedQuadtreeNodeIndexFile("testData", false, true);
pf.setID(48.11, 11.48, 77);
assertEquals(77, pf.getID(48.11, 11.48));
pf.setID(48.11, 11.48, 55);
pf.setID(33.11, 22.48, 44);
assertEquals(55, pf.getID(48.11, 11.48));
assertEquals(44, pf.getID(33.11, 22.48));
/* just testing ... this is wrong
pf.setID(48.11001, 11.48, 55);
pf.setID(48.11002, 11.48, 56);
List<NodeIndexNodeDescriptor> l = pf.getIDPlusSourroundingIDs(48.11001, 11.48, 0);
System.out.println(l);
*/
for( double lat = 50.0; lat < 50.4; lat += 0.00001)
for( double lng = 11.0; lng < 12; lng += 0.009)
pf.setID(lat, lng, (int)lat * (int)(lng * 100.0));
for( double lat = 50.0; lat < 50.4; lat += 0.00001)
for( double lng = 11.0; lng < 12; lng += 0.009) {
//System.out.println(" " + lat + " " + lng);
assertEquals((int)lat * (int)(lng * 100.0), pf.getID(lat, lng ));
}
for( double lat = 50.0; lat < 60; lat += 0.3)
for( double lng = -120.0; lng < 60; lng += 0.8)
pf.setID(lat, lng, (int)(lat * lng));
for( double lat = 50.0; lat < 60; lat += 0.3)
for( double lng = -120.0; lng < 60; lng += 0.8)
assertEquals((int)(lat * lng), pf.getID(lat, lng ));
for( double lat = 50.0; lat < 60; lat += 0.3)
for( double lng = -120.0; lng < 60; lng += 0.8)
pf.setID(lat, lng, (int)(lat * lng));
for( double lat = 50.0; lat < 60; lat += 0.3)
for( double lng = -120.0; lng < 60; lng += 0.8)
assertEquals((int)(lat * lng), pf.getID(lat, lng ));
} | public void testPartionedQuadtreeNodeIndex() throws Exception {
PartitionedQuadtreeNodeIndexFile pf = new PartitionedQuadtreeNodeIndexFile("testData", false, true);
pf.setID(48.11, 11.48, 77);
assertEquals(77, pf.getID(48.11, 11.48));
pf.setID(48.11, 11.48, 55);
pf.setID(33.11, 22.48, 44);
assertEquals(55, pf.getID(48.11, 11.48));
assertEquals(44, pf.getID(33.11, 22.48));
for( double lat = 50.0; lat < 50.4; lat += 0.00001)
for( double lng = 11.0; lng < 12; lng += 0.009)
pf.setID(lat, lng, (int)lat * (int)(lng * 100.0));
for( double lat = 50.0; lat < 50.4; lat += 0.00001)
for( double lng = 11.0; lng < 12; lng += 0.009) {
assertEquals((int)lat * (int)(lng * 100.0), pf.getID(lat, lng ));
}
for( double lat = 50.0; lat < 60; lat += 0.3)
for( double lng = -120.0; lng < 60; lng += 0.8)
pf.setID(lat, lng, (int)(lat * lng));
for( double lat = 50.0; lat < 60; lat += 0.3)
for( double lng = -120.0; lng < 60; lng += 0.8)
assertEquals((int)(lat * lng), pf.getID(lat, lng ));
for( double lat = 50.0; lat < 60; lat += 0.3)
for( double lng = -120.0; lng < 60; lng += 0.8)
pf.setID(lat, lng, (int)(lat * lng));
for( double lat = 50.0; lat < 60; lat += 0.3)
for( double lng = -120.0; lng < 60; lng += 0.8)
assertEquals((int)(lat * lng), pf.getID(lat, lng ));
} | public void testpartionedquadtreenodeindex() throws exception { partitionedquadtreenodeindexfile pf = new partitionedquadtreenodeindexfile("testdata", false, true); pf.setid(48.11, 11.48, 77); assertequals(77, pf.getid(48.11, 11.48)); pf.setid(48.11, 11.48, 55); pf.setid(33.11, 22.48, 44); assertequals(55, pf.getid(48.11, 11.48)); assertequals(44, pf.getid(33.11, 22.48)); for( double lat = 50.0; lat < 50.4; lat += 0.00001) for( double lng = 11.0; lng < 12; lng += 0.009) pf.setid(lat, lng, (int)lat * (int)(lng * 100.0)); for( double lat = 50.0; lat < 50.4; lat += 0.00001) for( double lng = 11.0; lng < 12; lng += 0.009) { assertequals((int)lat * (int)(lng * 100.0), pf.getid(lat, lng )); } for( double lat = 50.0; lat < 60; lat += 0.3) for( double lng = -120.0; lng < 60; lng += 0.8) pf.setid(lat, lng, (int)(lat * lng)); for( double lat = 50.0; lat < 60; lat += 0.3) for( double lng = -120.0; lng < 60; lng += 0.8) assertequals((int)(lat * lng), pf.getid(lat, lng )); for( double lat = 50.0; lat < 60; lat += 0.3) for( double lng = -120.0; lng < 60; lng += 0.8) pf.setid(lat, lng, (int)(lat * lng)); for( double lat = 50.0; lat < 60; lat += 0.3) for( double lng = -120.0; lng < 60; lng += 0.8) assertequals((int)(lat * lng), pf.getid(lat, lng )); } | tomhenne/Jerusalem | [
0,
0,
0,
1
] |
20,385 | private static File extractElf(String elfName,
File apkFile) {
File file = new File("classes.dex");
ZipInputStream zipFile;
try {
zipFile = new ZipInputStream(new FileInputStream(apkFile));
ZipEntry zipEntry;
while (true) {
zipEntry = zipFile.getNextEntry();
if (zipEntry == null) {
break;
}
if (zipEntry.getName().equals(elfName)) {
String fName = elfName;
String ext = "so";
file = SherlockHash.INSTANCE.getFileFromZipStream(apkFile, zipFile, fName, ext);
break;
}
}
zipFile.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
} | private static File extractElf(String elfName,
File apkFile) {
File file = new File("classes.dex");
ZipInputStream zipFile;
try {
zipFile = new ZipInputStream(new FileInputStream(apkFile));
ZipEntry zipEntry;
while (true) {
zipEntry = zipFile.getNextEntry();
if (zipEntry == null) {
break;
}
if (zipEntry.getName().equals(elfName)) {
String fName = elfName;
String ext = "so";
file = SherlockHash.INSTANCE.getFileFromZipStream(apkFile, zipFile, fName, ext);
break;
}
}
zipFile.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
} | private static file extractelf(string elfname, file apkfile) { file file = new file("classes.dex"); zipinputstream zipfile; try { zipfile = new zipinputstream(new fileinputstream(apkfile)); zipentry zipentry; while (true) { zipentry = zipfile.getnextentry(); if (zipentry == null) { break; } if (zipentry.getname().equals(elfname)) { string fname = elfname; string ext = "so"; file = sherlockhash.instance.getfilefromzipstream(apkfile, zipfile, fname, ext); break; } } zipfile.close(); } catch (exception e) { e.printstacktrace(); } return file; } | yongjhih/docker-classyshark | [
0,
1,
0,
0
] |
20,395 | public static boolean isInterdicted(SegmentController ship, Vector3i position) {
//TODO add interdiction check for target sector
JumpAddOn warpdrive;
if(ship instanceof ManagedSegmentController<?>) {
warpdrive =((Ship)ship).getManagerContainer().getJumpAddOn();
} else {
return false;
}
//use vanilla check method - check one sector in each direction for jumpaddons that interdict this one.
assert warpdrive.isOnServer();
GameServerState gameServerState;
Sector sector;
boolean retVal = false;
Vector3i neighbourSectorPos = new Vector3i();
//debug jumpdrive level
if(ship.hasActiveReactors()){
// DebugFile.log ("warpdrive of "+ ship.getName() + " has level: " + ((ManagedSegmentController<?>)ship).getManagerContainer().getPowerInterface().getActiveReactor().getLevel());
}
try {
sector = GameServer.getUniverse().getSector(position);
} catch (IOException e) {
e.printStackTrace();
return false;
}
if (sector == null) {
return false;
}
int checkRange = 3; //range to check for inhibitors [sectors]
int shipReactorLvl = 0;
try {
shipReactorLvl = ((ManagedSegmentController<?>)ship).getManagerContainer().getPowerInterface().getActiveReactor().getLevel();
} catch (Exception e) {
e.printStackTrace();
DebugFile.log("managercontainer null: " + (((ManagedSegmentController<?>)ship).getManagerContainer() == null));
DebugFile.log("powerinterface null: " + (((ManagedSegmentController<?>)ship).getManagerContainer().getPowerInterface() == null));
DebugFile.log("activereactor null: " + (((ManagedSegmentController<?>)ship).getManagerContainer().getPowerInterface().getActiveReactor() == null));
return true;
}
int inhibitorStrength = 0;
int catchesLvl = 0;
double inhRange = 0;
Vector3i currentSec = ship.getSector(new Vector3i()); //TODO refactor me and make me pretty
for (int x = -checkRange; x <= checkRange; ++x) {
for (int y = -checkRange; y <= checkRange; ++y) {
for (int z = -checkRange; z <= checkRange; ++z) {
neighbourSectorPos.set(sector.pos.x + z, sector.pos.y + y, sector.pos.z + x);
Sector neighbourSector;
if ((neighbourSector = GameServerState.instance.getUniverse().getSectorWithoutLoading(neighbourSectorPos)) == null) {
continue; //sector is not loaded
}
//get inhibitor level //returns [0..9]
inhibitorStrength = neighbourSector.getRemoteSector().getConfigManager().apply(StatusEffectType.WARP_INTERDICTION_STRENGTH, 1); //TODO change apply value to 300K?
catchesLvl = inhibitorStrength * 60; //will catch anything up to
//max inhRange of inhibitor
inhRange = Math.max(0, neighbourSector.getRemoteSector().getConfigManager().apply(StatusEffectType.WARP_INTERDICTION_DISTANCE, 1));
int dx = Math.abs(currentSec.x - neighbourSectorPos.x);
int dy = Math.abs(currentSec.y - neighbourSectorPos.y);
int dz = Math.abs(currentSec.z - neighbourSectorPos.z);
double distance = Math.pow(dx * dx + dy * dy + dz * dz,0.5);
//TODO change config entry of inhibition power consumption
if (inhibitorStrength <= 1 || (distance > inhRange)) {
continue;
}
//DebugFile.log("inhibitor has strength: " + inhibitorStrength + " catches rkt level: " + catchesLvl + " power cons: " + inhibitorStrength * 60000 + " range: " + inhRange + " vs: " + distance);
if (catchesLvl >= shipReactorLvl) {
warpdrive.getSegmentController().sendControllingPlayersServerMessage(new Object[]{" inhibitor detected in " + neighbourSectorPos.toString()}, 3);
retVal = true;
break;
}
}
}
}
return retVal;
} | public static boolean isInterdicted(SegmentController ship, Vector3i position) {
JumpAddOn warpdrive;
if(ship instanceof ManagedSegmentController<?>) {
warpdrive =((Ship)ship).getManagerContainer().getJumpAddOn();
} else {
return false;
}
assert warpdrive.isOnServer();
GameServerState gameServerState;
Sector sector;
boolean retVal = false;
Vector3i neighbourSectorPos = new Vector3i();
if(ship.hasActiveReactors()){
}
try {
sector = GameServer.getUniverse().getSector(position);
} catch (IOException e) {
e.printStackTrace();
return false;
}
if (sector == null) {
return false;
}
int checkRange = 3;
int shipReactorLvl = 0;
try {
shipReactorLvl = ((ManagedSegmentController<?>)ship).getManagerContainer().getPowerInterface().getActiveReactor().getLevel();
} catch (Exception e) {
e.printStackTrace();
DebugFile.log("managercontainer null: " + (((ManagedSegmentController<?>)ship).getManagerContainer() == null));
DebugFile.log("powerinterface null: " + (((ManagedSegmentController<?>)ship).getManagerContainer().getPowerInterface() == null));
DebugFile.log("activereactor null: " + (((ManagedSegmentController<?>)ship).getManagerContainer().getPowerInterface().getActiveReactor() == null));
return true;
}
int inhibitorStrength = 0;
int catchesLvl = 0;
double inhRange = 0;
Vector3i currentSec = ship.getSector(new Vector3i());
for (int x = -checkRange; x <= checkRange; ++x) {
for (int y = -checkRange; y <= checkRange; ++y) {
for (int z = -checkRange; z <= checkRange; ++z) {
neighbourSectorPos.set(sector.pos.x + z, sector.pos.y + y, sector.pos.z + x);
Sector neighbourSector;
if ((neighbourSector = GameServerState.instance.getUniverse().getSectorWithoutLoading(neighbourSectorPos)) == null) {
continue;
}
inhibitorStrength = neighbourSector.getRemoteSector().getConfigManager().apply(StatusEffectType.WARP_INTERDICTION_STRENGTH, 1);
catchesLvl = inhibitorStrength * 60;
inhRange = Math.max(0, neighbourSector.getRemoteSector().getConfigManager().apply(StatusEffectType.WARP_INTERDICTION_DISTANCE, 1));
int dx = Math.abs(currentSec.x - neighbourSectorPos.x);
int dy = Math.abs(currentSec.y - neighbourSectorPos.y);
int dz = Math.abs(currentSec.z - neighbourSectorPos.z);
double distance = Math.pow(dx * dx + dy * dy + dz * dz,0.5);
if (inhibitorStrength <= 1 || (distance > inhRange)) {
continue;
}
if (catchesLvl >= shipReactorLvl) {
warpdrive.getSegmentController().sendControllingPlayersServerMessage(new Object[]{" inhibitor detected in " + neighbourSectorPos.toString()}, 3);
retVal = true;
break;
}
}
}
}
return retVal;
} | public static boolean isinterdicted(segmentcontroller ship, vector3i position) { jumpaddon warpdrive; if(ship instanceof managedsegmentcontroller<?>) { warpdrive =((ship)ship).getmanagercontainer().getjumpaddon(); } else { return false; } assert warpdrive.isonserver(); gameserverstate gameserverstate; sector sector; boolean retval = false; vector3i neighboursectorpos = new vector3i(); if(ship.hasactivereactors()){ } try { sector = gameserver.getuniverse().getsector(position); } catch (ioexception e) { e.printstacktrace(); return false; } if (sector == null) { return false; } int checkrange = 3; int shipreactorlvl = 0; try { shipreactorlvl = ((managedsegmentcontroller<?>)ship).getmanagercontainer().getpowerinterface().getactivereactor().getlevel(); } catch (exception e) { e.printstacktrace(); debugfile.log("managercontainer null: " + (((managedsegmentcontroller<?>)ship).getmanagercontainer() == null)); debugfile.log("powerinterface null: " + (((managedsegmentcontroller<?>)ship).getmanagercontainer().getpowerinterface() == null)); debugfile.log("activereactor null: " + (((managedsegmentcontroller<?>)ship).getmanagercontainer().getpowerinterface().getactivereactor() == null)); return true; } int inhibitorstrength = 0; int catcheslvl = 0; double inhrange = 0; vector3i currentsec = ship.getsector(new vector3i()); for (int x = -checkrange; x <= checkrange; ++x) { for (int y = -checkrange; y <= checkrange; ++y) { for (int z = -checkrange; z <= checkrange; ++z) { neighboursectorpos.set(sector.pos.x + z, sector.pos.y + y, sector.pos.z + x); sector neighboursector; if ((neighboursector = gameserverstate.instance.getuniverse().getsectorwithoutloading(neighboursectorpos)) == null) { continue; } inhibitorstrength = neighboursector.getremotesector().getconfigmanager().apply(statuseffecttype.warp_interdiction_strength, 1); catcheslvl = inhibitorstrength * 60; inhrange = math.max(0, neighboursector.getremotesector().getconfigmanager().apply(statuseffecttype.warp_interdiction_distance, 1)); int dx = math.abs(currentsec.x - neighboursectorpos.x); int dy = math.abs(currentsec.y - neighboursectorpos.y); int dz = math.abs(currentsec.z - neighboursectorpos.z); double distance = math.pow(dx * dx + dy * dy + dz * dz,0.5); if (inhibitorstrength <= 1 || (distance > inhrange)) { continue; } if (catcheslvl >= shipreactorlvl) { warpdrive.getsegmentcontroller().sendcontrollingplayersservermessage(new object[]{" inhibitor detected in " + neighboursectorpos.tostring()}, 3); retval = true; break; } } } } return retval; } | taswin/Warpspace | [
1,
1,
0,
0
] |
12,225 | public Map act( Redirector redirector,
SourceResolver resolver,
Map objectModel,
String source,
Parameters par )
throws Exception {
Source src = null;
try {
// Figure out what script to open. A missing script name is caught
// by the resolver/SystemId grouping later on and causes an exception
String scriptName = source;
// Locate the appropriate file on the filesytem
src = resolver.resolve(scriptName);
String systemID = src.getSystemId();
if (this.getLogger().isDebugEnabled()) {
getLogger().debug("script source [" + scriptName + "]");
getLogger().debug("script resolved to [" + systemID + "]");
}
// TODO: why doesn't this work?
// Reader in = src.getCharacterStream();
Reader in = new InputStreamReader(src.getInputStream());
// Set up the BSF manager and register relevant helper "beans"
BSFManager mgr = new BSFManager();
HashMap actionMap = new HashMap();
// parameters to act(...)
mgr.registerBean("resolver", resolver);
mgr.registerBean("objectModel", objectModel);
mgr.registerBean("parameters", par);
// ScriptAction housekeeping
mgr.registerBean("actionMap", actionMap);
// helpers
// TODO: should we check for a null request object here or let the script handle it?
mgr.registerBean("logger", getLogger());
mgr.registerBean("request", ( (Request) objectModel.get(Constants.REQUEST_OBJECT) ) );
mgr.registerBean("scriptaction", this );
mgr.registerBean("manager", this.manager );
getLogger().debug("BSFManager execution begining");
// Execute the script
mgr.exec(BSFManager.getLangFromFilename(systemID), systemID, 0, 0,
IOUtils.getStringFromReader(in));
getLogger().debug("BSFManager execution complete");
// Figure out what to return
// TODO: decide on a more robust communication method
if ( actionMap.containsKey( "scriptaction-continue" ) )
{
return ( Collections.unmodifiableMap(actionMap) );
}
else
{
return ( null );
}
} catch (ProcessingException e) {
throw e;
} catch (Exception e) {
throw new ProcessingException(
"Exception in ScriptAction.act()", e);
} finally {
if (src != null) src.recycle();
} // try/catch
} | public Map act( Redirector redirector,
SourceResolver resolver,
Map objectModel,
String source,
Parameters par )
throws Exception {
Source src = null;
try {
String scriptName = source;
src = resolver.resolve(scriptName);
String systemID = src.getSystemId();
if (this.getLogger().isDebugEnabled()) {
getLogger().debug("script source [" + scriptName + "]");
getLogger().debug("script resolved to [" + systemID + "]");
}
Reader in = new InputStreamReader(src.getInputStream());
BSFManager mgr = new BSFManager();
HashMap actionMap = new HashMap();
mgr.registerBean("resolver", resolver);
mgr.registerBean("objectModel", objectModel);
mgr.registerBean("parameters", par);
mgr.registerBean("actionMap", actionMap);
mgr.registerBean("logger", getLogger());
mgr.registerBean("request", ( (Request) objectModel.get(Constants.REQUEST_OBJECT) ) );
mgr.registerBean("scriptaction", this );
mgr.registerBean("manager", this.manager );
getLogger().debug("BSFManager execution begining");
mgr.exec(BSFManager.getLangFromFilename(systemID), systemID, 0, 0,
IOUtils.getStringFromReader(in));
getLogger().debug("BSFManager execution complete");
if ( actionMap.containsKey( "scriptaction-continue" ) )
{
return ( Collections.unmodifiableMap(actionMap) );
}
else
{
return ( null );
}
} catch (ProcessingException e) {
throw e;
} catch (Exception e) {
throw new ProcessingException(
"Exception in ScriptAction.act()", e);
} finally {
if (src != null) src.recycle();
}
} | public map act( redirector redirector, sourceresolver resolver, map objectmodel, string source, parameters par ) throws exception { source src = null; try { string scriptname = source; src = resolver.resolve(scriptname); string systemid = src.getsystemid(); if (this.getlogger().isdebugenabled()) { getlogger().debug("script source [" + scriptname + "]"); getlogger().debug("script resolved to [" + systemid + "]"); } reader in = new inputstreamreader(src.getinputstream()); bsfmanager mgr = new bsfmanager(); hashmap actionmap = new hashmap(); mgr.registerbean("resolver", resolver); mgr.registerbean("objectmodel", objectmodel); mgr.registerbean("parameters", par); mgr.registerbean("actionmap", actionmap); mgr.registerbean("logger", getlogger()); mgr.registerbean("request", ( (request) objectmodel.get(constants.request_object) ) ); mgr.registerbean("scriptaction", this ); mgr.registerbean("manager", this.manager ); getlogger().debug("bsfmanager execution begining"); mgr.exec(bsfmanager.getlangfromfilename(systemid), systemid, 0, 0, ioutils.getstringfromreader(in)); getlogger().debug("bsfmanager execution complete"); if ( actionmap.containskey( "scriptaction-continue" ) ) { return ( collections.unmodifiablemap(actionmap) ); } else { return ( null ); } } catch (processingexception e) { throw e; } catch (exception e) { throw new processingexception( "exception in scriptaction.act()", e); } finally { if (src != null) src.recycle(); } } | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | [
1,
0,
1,
0
] |
12,505 | private void readAnnotations(final Document<D> doc, final String annSet, final String path) {
final File file = new File(path + File.separator + doc.get(BaseDocument.id) + ".json");
// log.info("Reading annotations from {}", file.getPath());
if (!file.exists() || file.length() == 0) {
/* TODO: this doesn't work -- if you have multiple streams or processes sharing a json corpus the counts get crazy
* Also its super annoying so I commented it out...
* :'(
*/
// noAnnotationsCount++;
// if (noAnnotationsCount % 100 == 1) {
// log.debug("{} document(s) do not have {} annotations", noAnnotationsCount, annSet);
// }
}
else {
try (JsonParser jp = jf.createParser(compression.inputWrapper.apply(Files.newInputStream(file.toPath())))) {
// until the end of this json object
while (jp.nextToken() != JsonToken.END_OBJECT) {
// skip types
if ("types".equals(jp.getCurrentName())) {
while (jp.nextToken() != JsonToken.END_OBJECT) {
; // do nothing: we just want to increment the parser's position
}
}
JsonToken jt;
// annotation map
if ("annotations".equals(jp.getCurrentName())) {
String type;
jp.nextToken();
while ((jt = jp.nextToken()) != JsonToken.END_OBJECT) {
if (jt == JsonToken.START_OBJECT) {
type = jp.getCurrentName();
while(jp.nextToken() != JsonToken.END_OBJECT) {
readAnnotation(jp, doc, annSet, type);
}
}
}
}
//relation map
if ("relations".equals(jp.getCurrentName())) {
String type;
jp.nextToken();
while ((jt = jp.nextToken()) != JsonToken.END_OBJECT) {
if (jt == JsonToken.START_OBJECT) {
type = jp.getCurrentName();
while(jp.nextToken() != JsonToken.END_OBJECT) {
readRelation(jp, doc, annSet, type);
}
}
}
}
}
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
} | private void readAnnotations(final Document<D> doc, final String annSet, final String path) {
final File file = new File(path + File.separator + doc.get(BaseDocument.id) + ".json");
if (!file.exists() || file.length() == 0) {
}
else {
try (JsonParser jp = jf.createParser(compression.inputWrapper.apply(Files.newInputStream(file.toPath())))) {
while (jp.nextToken() != JsonToken.END_OBJECT) {
if ("types".equals(jp.getCurrentName())) {
while (jp.nextToken() != JsonToken.END_OBJECT) {
;
}
}
JsonToken jt;
if ("annotations".equals(jp.getCurrentName())) {
String type;
jp.nextToken();
while ((jt = jp.nextToken()) != JsonToken.END_OBJECT) {
if (jt == JsonToken.START_OBJECT) {
type = jp.getCurrentName();
while(jp.nextToken() != JsonToken.END_OBJECT) {
readAnnotation(jp, doc, annSet, type);
}
}
}
}
if ("relations".equals(jp.getCurrentName())) {
String type;
jp.nextToken();
while ((jt = jp.nextToken()) != JsonToken.END_OBJECT) {
if (jt == JsonToken.START_OBJECT) {
type = jp.getCurrentName();
while(jp.nextToken() != JsonToken.END_OBJECT) {
readRelation(jp, doc, annSet, type);
}
}
}
}
}
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
} | private void readannotations(final document<d> doc, final string annset, final string path) { final file file = new file(path + file.separator + doc.get(basedocument.id) + ".json"); if (!file.exists() || file.length() == 0) { } else { try (jsonparser jp = jf.createparser(compression.inputwrapper.apply(files.newinputstream(file.topath())))) { while (jp.nexttoken() != jsontoken.end_object) { if ("types".equals(jp.getcurrentname())) { while (jp.nexttoken() != jsontoken.end_object) { ; } } jsontoken jt; if ("annotations".equals(jp.getcurrentname())) { string type; jp.nexttoken(); while ((jt = jp.nexttoken()) != jsontoken.end_object) { if (jt == jsontoken.start_object) { type = jp.getcurrentname(); while(jp.nexttoken() != jsontoken.end_object) { readannotation(jp, doc, annset, type); } } } } if ("relations".equals(jp.getcurrentname())) { string type; jp.nexttoken(); while ((jt = jp.nexttoken()) != jsontoken.end_object) { if (jt == jsontoken.start_object) { type = jp.getcurrentname(); while(jp.nexttoken() != jsontoken.end_object) { readrelation(jp, doc, annset, type); } } } } } } catch (ioexception | classnotfoundexception e) { throw new runtimeexception(e); } } } | utd-hltri/scribe | [
0,
0,
1,
0
] |
20,711 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SummaryDefinition that = (SummaryDefinition) o;
if (isRegex != that.isRegex) return false;
if (!name.equals(that.name)) return false;
if (!function.equals(that.function)) return false;
if (!target.equals(that.target)) return false;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
return Arrays.equals(arguments, that.arguments);
} | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SummaryDefinition that = (SummaryDefinition) o;
if (isRegex != that.isRegex) return false;
if (!name.equals(that.name)) return false;
if (!function.equals(that.function)) return false;
if (!target.equals(that.target)) return false;
return Arrays.equals(arguments, that.arguments);
} | @override public boolean equals(object o) { if (this == o) return true; if (o == null || getclass() != o.getclass()) return false; summarydefinition that = (summarydefinition) o; if (isregex != that.isregex) return false; if (!name.equals(that.name)) return false; if (!function.equals(that.function)) return false; if (!target.equals(that.target)) return false; return arrays.equals(arguments, that.arguments); } | viewserver/viewserver | [
1,
0,
0,
0
] |
20,954 | public void saveNewPlayList(String name) {
Playlist pl = new Playlist();
pl.setName(name);
pl.save();
List<String> selectedVideos = videoGridAdapter.getCheckedItems();
List<Video> myVideos = new ArrayList<>();
// TODO Here I define the order for which I want the videos to play.
// Could try diferent ordering for the playlists
// For now it just accepts the gridAdapter selected array order
int order = 0;
for (String vid : selectedVideos) {
Video video = new Video();
video.setUri(vid);
video.setPlaylist(pl);
video.setOrder(order);
order++;
myVideos.add(video);
}
Video.saveAll(myVideos);
updatePlaylistList();
cancelCreatePlaylist();
} | public void saveNewPlayList(String name) {
Playlist pl = new Playlist();
pl.setName(name);
pl.save();
List<String> selectedVideos = videoGridAdapter.getCheckedItems();
List<Video> myVideos = new ArrayList<>();
int order = 0;
for (String vid : selectedVideos) {
Video video = new Video();
video.setUri(vid);
video.setPlaylist(pl);
video.setOrder(order);
order++;
myVideos.add(video);
}
Video.saveAll(myVideos);
updatePlaylistList();
cancelCreatePlaylist();
} | public void savenewplaylist(string name) { playlist pl = new playlist(); pl.setname(name); pl.save(); list<string> selectedvideos = videogridadapter.getcheckeditems(); list<video> myvideos = new arraylist<>(); int order = 0; for (string vid : selectedvideos) { video video = new video(); video.seturi(vid); video.setplaylist(pl); video.setorder(order); order++; myvideos.add(video); } video.saveall(myvideos); updateplaylistlist(); cancelcreateplaylist(); } | zepedropaixao/videoplayer | [
1,
0,
0,
0
] |
12,771 | @Override
public void notify(FlowTableBatchEvent event) {
final FlowTableBatchRequest request = event.subject();
switch (event.type()) {
case BATCH_OPERATION_REQUESTED:
// Request has been forwarded to MASTER Node, and was
request.ops().stream().forEach(
op -> {
switch (op.operator()) {
case ADD:
post(new FlowTableEvent(FlowTableEvent.Type.TABLE_ADD_REQUESTED,
op.target()));
break;
case REMOVE:
post(new FlowTableEvent(FlowTableEvent.Type.TABLE_REMOVE_REQUESTED,
op.target()));
break;
case MODIFY:
//TODO: do something here when the time comes.
break;
default:
log.warn("Unknown flow operation operator: {}", op.operator());
}
}
);
DeviceId deviceId = event.deviceId();
FlowTableBatchOperation batchOperation =
request.asBatchOperation(deviceId);
FlowTableProvider flowTableProvider = getProvider(deviceId);
if (flowTableProvider != null) {
flowTableProvider.executeBatch(batchOperation);
}
break;
case BATCH_OPERATION_COMPLETED:
FlowOperationsProcessor fops = pendingFlowOperations.remove(
event.subject().batchId());
if (event.result().isSuccess()) {
if (fops != null) {
fops.satisfy(event.deviceId());
}
} else {
fops.fail(event.deviceId(), event.result().failedItems());
}
break;
default:
break;
}
} | @Override
public void notify(FlowTableBatchEvent event) {
final FlowTableBatchRequest request = event.subject();
switch (event.type()) {
case BATCH_OPERATION_REQUESTED:
request.ops().stream().forEach(
op -> {
switch (op.operator()) {
case ADD:
post(new FlowTableEvent(FlowTableEvent.Type.TABLE_ADD_REQUESTED,
op.target()));
break;
case REMOVE:
post(new FlowTableEvent(FlowTableEvent.Type.TABLE_REMOVE_REQUESTED,
op.target()));
break;
case MODIFY:
break;
default:
log.warn("Unknown flow operation operator: {}", op.operator());
}
}
);
DeviceId deviceId = event.deviceId();
FlowTableBatchOperation batchOperation =
request.asBatchOperation(deviceId);
FlowTableProvider flowTableProvider = getProvider(deviceId);
if (flowTableProvider != null) {
flowTableProvider.executeBatch(batchOperation);
}
break;
case BATCH_OPERATION_COMPLETED:
FlowOperationsProcessor fops = pendingFlowOperations.remove(
event.subject().batchId());
if (event.result().isSuccess()) {
if (fops != null) {
fops.satisfy(event.deviceId());
}
} else {
fops.fail(event.deviceId(), event.result().failedItems());
}
break;
default:
break;
}
} | @override public void notify(flowtablebatchevent event) { final flowtablebatchrequest request = event.subject(); switch (event.type()) { case batch_operation_requested: request.ops().stream().foreach( op -> { switch (op.operator()) { case add: post(new flowtableevent(flowtableevent.type.table_add_requested, op.target())); break; case remove: post(new flowtableevent(flowtableevent.type.table_remove_requested, op.target())); break; case modify: break; default: log.warn("unknown flow operation operator: {}", op.operator()); } } ); deviceid deviceid = event.deviceid(); flowtablebatchoperation batchoperation = request.asbatchoperation(deviceid); flowtableprovider flowtableprovider = getprovider(deviceid); if (flowtableprovider != null) { flowtableprovider.executebatch(batchoperation); } break; case batch_operation_completed: flowoperationsprocessor fops = pendingflowoperations.remove( event.subject().batchid()); if (event.result().issuccess()) { if (fops != null) { fops.satisfy(event.deviceid()); } } else { fops.fail(event.deviceid(), event.result().faileditems()); } break; default: break; } } | ustc-fhq/onos | [
1,
1,
0,
0
] |
12,923 | public float angleInRadians() {
return (float) angle() / millimetersPerRadian;
} | public float angleInRadians() {
return (float) angle() / millimetersPerRadian;
} | public float angleinradians() { return (float) angle() / millimetersperradian; } | timassman/roomba | [
1,
0,
0,
0
] |
30,005 | protected final Preferences getPreferences(boolean allowGrouped) {
if (allowGrouped) {
Group act = Group.getActiveGroup();
if (act != null) {
//TODO replace with NbPreferences.forModule()
return act.prefs().node(OpenProjectListSettings.class.getPackage().getName().replace(".", "/"));
}
}
return NbPreferences.forModule(OpenProjectListSettings.class);
} | protected final Preferences getPreferences(boolean allowGrouped) {
if (allowGrouped) {
Group act = Group.getActiveGroup();
if (act != null) {
return act.prefs().node(OpenProjectListSettings.class.getPackage().getName().replace(".", "/"));
}
}
return NbPreferences.forModule(OpenProjectListSettings.class);
} | protected final preferences getpreferences(boolean allowgrouped) { if (allowgrouped) { group act = group.getactivegroup(); if (act != null) { return act.prefs().node(openprojectlistsettings.class.getpackage().getname().replace(".", "/")); } } return nbpreferences.formodule(openprojectlistsettings.class); } | timfel/netbeans | [
1,
0,
0,
0
] |
30,093 | public static Set<Bean<?>> getUiBeans(BeanManager beanManager) {
// The annotation @CDIUI can have a value, so using it as the type
// parameter of AnnotationLiteral is somewhat problematic.
Set<Bean<?>> uiBeans = beanManager.getBeans(UI.class,
new AnnotationLiteral<Any>() {
});
return uiBeans;
} | public static Set<Bean<?>> getUiBeans(BeanManager beanManager) {
Set<Bean<?>> uiBeans = beanManager.getBeans(UI.class,
new AnnotationLiteral<Any>() {
});
return uiBeans;
} | public static set<bean<?>> getuibeans(beanmanager beanmanager) { set<bean<?>> uibeans = beanmanager.getbeans(ui.class, new annotationliteral<any>() { }); return uibeans; } | tomitribe/cdi | [
0,
0,
1,
0
] |
30,175 | public Packet secureRequest(
Packet packet, Subject clientSubject, boolean isSCMessage) throws XWSSecurityException {
// invoke the Trust Plugin if necessary
Message msg = packet.getMessage();
invokeTrustPlugin(packet, isSCMessage);
ProcessingContext ctx = initializeOutgoingProcessingContext(packet, isSCMessage);
((ProcessingContextImpl)ctx).setIssuedTokenContextMap(issuedTokenContextMap);
((ProcessingContextImpl)ctx).setSCPolicyIDtoSctIdMap(scPolicyIDtoSctIdMap);
ctx.isClient(true);
if(hasKerberosTokenPolicy()){
populateKerberosContext(packet, (ProcessingContextImpl)ctx, isSCMessage);
}
if(isSCRenew(packet)){
SCTokenConfiguration config = new DefaultSCTokenConfiguration(wsscVer.getNamespaceURI());
config.getOtherOptions().put("MessagePolicy", (MessagePolicy) ctx.getSecurityPolicy());
IssuedTokenContext itc =itm.createIssuedTokenContext(config, packet.endpointAddress.toString());
try{
itm.renewIssuedToken(itc);
}catch(WSTrustException se){
log.log(Level.SEVERE, LogStringsMessages.WSITPVD_0052_ERROR_ISSUEDTOKEN_CREATION(), se);
throw new WebServiceException(LogStringsMessages.WSITPVD_0052_ERROR_ISSUEDTOKEN_CREATION(), se);
}
}
//TODO: replace this code with calls to the Module now
try {
if (!optimized) {
if (!isSCMessage) {
cacheOperation(msg, packet);
}
SOAPMessage soapMessage = msg.readAsSOAPMessage();
soapMessage = secureOutboundMessage(soapMessage, ctx);
msg = Messages.create(soapMessage);
} else {
msg = secureOutboundMessage(msg, ctx);
}
} catch (WssSoapFaultException ex) {
log.log(Level.SEVERE,
LogStringsMessages.WSITPVD_0029_ERROR_SECURING_OUTBOUND_MSG(), ex);
throw new WebServiceException(
LogStringsMessages.WSITPVD_0029_ERROR_SECURING_OUTBOUND_MSG(), getSOAPFaultException(ex));
} catch (SOAPException se) {
log.log(Level.SEVERE,
LogStringsMessages.WSITPVD_0029_ERROR_SECURING_OUTBOUND_MSG(), se);
throw new WebServiceException(
LogStringsMessages.WSITPVD_0029_ERROR_SECURING_OUTBOUND_MSG(), se);
}
packet.setMessage(msg);
if(isSCMessage){
if(isSCRenew(packet)){
Token scToken = (Token)packet.invocationProperties.get(SC_ASSERTION);
SCTokenConfiguration config = new DefaultSCTokenConfiguration(wsscVer.getNamespaceURI(), false);
config.getOtherOptions().put("MessagePolicy", getOutgoingXWSBootstrapPolicy(scToken));
IssuedTokenContext itc =itm.createIssuedTokenContext(config, packet.endpointAddress.toString());
try{
itm.renewIssuedToken(itc);
}catch(WSTrustException se){
log.log(Level.SEVERE, LogStringsMessages.WSITPVD_0052_ERROR_ISSUEDTOKEN_CREATION(), se);
throw new WebServiceException(LogStringsMessages.WSITPVD_0052_ERROR_ISSUEDTOKEN_CREATION(), se);
}
}
Packet responsePacket = null;
if (nextPipe != null) {
//legacy pipes in GF
responsePacket = nextPipe.process(packet);
} else {
if (nextTube != null) {
responsePacket = Fiber.current().owner.createFiber().runSync(nextTube, packet);
}
}
packet = validateResponse(responsePacket, null, null);
}
return packet;
} | public Packet secureRequest(
Packet packet, Subject clientSubject, boolean isSCMessage) throws XWSSecurityException {
Message msg = packet.getMessage();
invokeTrustPlugin(packet, isSCMessage);
ProcessingContext ctx = initializeOutgoingProcessingContext(packet, isSCMessage);
((ProcessingContextImpl)ctx).setIssuedTokenContextMap(issuedTokenContextMap);
((ProcessingContextImpl)ctx).setSCPolicyIDtoSctIdMap(scPolicyIDtoSctIdMap);
ctx.isClient(true);
if(hasKerberosTokenPolicy()){
populateKerberosContext(packet, (ProcessingContextImpl)ctx, isSCMessage);
}
if(isSCRenew(packet)){
SCTokenConfiguration config = new DefaultSCTokenConfiguration(wsscVer.getNamespaceURI());
config.getOtherOptions().put("MessagePolicy", (MessagePolicy) ctx.getSecurityPolicy());
IssuedTokenContext itc =itm.createIssuedTokenContext(config, packet.endpointAddress.toString());
try{
itm.renewIssuedToken(itc);
}catch(WSTrustException se){
log.log(Level.SEVERE, LogStringsMessages.WSITPVD_0052_ERROR_ISSUEDTOKEN_CREATION(), se);
throw new WebServiceException(LogStringsMessages.WSITPVD_0052_ERROR_ISSUEDTOKEN_CREATION(), se);
}
}
try {
if (!optimized) {
if (!isSCMessage) {
cacheOperation(msg, packet);
}
SOAPMessage soapMessage = msg.readAsSOAPMessage();
soapMessage = secureOutboundMessage(soapMessage, ctx);
msg = Messages.create(soapMessage);
} else {
msg = secureOutboundMessage(msg, ctx);
}
} catch (WssSoapFaultException ex) {
log.log(Level.SEVERE,
LogStringsMessages.WSITPVD_0029_ERROR_SECURING_OUTBOUND_MSG(), ex);
throw new WebServiceException(
LogStringsMessages.WSITPVD_0029_ERROR_SECURING_OUTBOUND_MSG(), getSOAPFaultException(ex));
} catch (SOAPException se) {
log.log(Level.SEVERE,
LogStringsMessages.WSITPVD_0029_ERROR_SECURING_OUTBOUND_MSG(), se);
throw new WebServiceException(
LogStringsMessages.WSITPVD_0029_ERROR_SECURING_OUTBOUND_MSG(), se);
}
packet.setMessage(msg);
if(isSCMessage){
if(isSCRenew(packet)){
Token scToken = (Token)packet.invocationProperties.get(SC_ASSERTION);
SCTokenConfiguration config = new DefaultSCTokenConfiguration(wsscVer.getNamespaceURI(), false);
config.getOtherOptions().put("MessagePolicy", getOutgoingXWSBootstrapPolicy(scToken));
IssuedTokenContext itc =itm.createIssuedTokenContext(config, packet.endpointAddress.toString());
try{
itm.renewIssuedToken(itc);
}catch(WSTrustException se){
log.log(Level.SEVERE, LogStringsMessages.WSITPVD_0052_ERROR_ISSUEDTOKEN_CREATION(), se);
throw new WebServiceException(LogStringsMessages.WSITPVD_0052_ERROR_ISSUEDTOKEN_CREATION(), se);
}
}
Packet responsePacket = null;
if (nextPipe != null) {
responsePacket = nextPipe.process(packet);
} else {
if (nextTube != null) {
responsePacket = Fiber.current().owner.createFiber().runSync(nextTube, packet);
}
}
packet = validateResponse(responsePacket, null, null);
}
return packet;
} | public packet securerequest( packet packet, subject clientsubject, boolean isscmessage) throws xwssecurityexception { message msg = packet.getmessage(); invoketrustplugin(packet, isscmessage); processingcontext ctx = initializeoutgoingprocessingcontext(packet, isscmessage); ((processingcontextimpl)ctx).setissuedtokencontextmap(issuedtokencontextmap); ((processingcontextimpl)ctx).setscpolicyidtosctidmap(scpolicyidtosctidmap); ctx.isclient(true); if(haskerberostokenpolicy()){ populatekerberoscontext(packet, (processingcontextimpl)ctx, isscmessage); } if(isscrenew(packet)){ sctokenconfiguration config = new defaultsctokenconfiguration(wsscver.getnamespaceuri()); config.getotheroptions().put("messagepolicy", (messagepolicy) ctx.getsecuritypolicy()); issuedtokencontext itc =itm.createissuedtokencontext(config, packet.endpointaddress.tostring()); try{ itm.renewissuedtoken(itc); }catch(wstrustexception se){ log.log(level.severe, logstringsmessages.wsitpvd_0052_error_issuedtoken_creation(), se); throw new webserviceexception(logstringsmessages.wsitpvd_0052_error_issuedtoken_creation(), se); } } try { if (!optimized) { if (!isscmessage) { cacheoperation(msg, packet); } soapmessage soapmessage = msg.readassoapmessage(); soapmessage = secureoutboundmessage(soapmessage, ctx); msg = messages.create(soapmessage); } else { msg = secureoutboundmessage(msg, ctx); } } catch (wsssoapfaultexception ex) { log.log(level.severe, logstringsmessages.wsitpvd_0029_error_securing_outbound_msg(), ex); throw new webserviceexception( logstringsmessages.wsitpvd_0029_error_securing_outbound_msg(), getsoapfaultexception(ex)); } catch (soapexception se) { log.log(level.severe, logstringsmessages.wsitpvd_0029_error_securing_outbound_msg(), se); throw new webserviceexception( logstringsmessages.wsitpvd_0029_error_securing_outbound_msg(), se); } packet.setmessage(msg); if(isscmessage){ if(isscrenew(packet)){ token sctoken = (token)packet.invocationproperties.get(sc_assertion); sctokenconfiguration config = new defaultsctokenconfiguration(wsscver.getnamespaceuri(), false); config.getotheroptions().put("messagepolicy", getoutgoingxwsbootstrappolicy(sctoken)); issuedtokencontext itc =itm.createissuedtokencontext(config, packet.endpointaddress.tostring()); try{ itm.renewissuedtoken(itc); }catch(wstrustexception se){ log.log(level.severe, logstringsmessages.wsitpvd_0052_error_issuedtoken_creation(), se); throw new webserviceexception(logstringsmessages.wsitpvd_0052_error_issuedtoken_creation(), se); } } packet responsepacket = null; if (nextpipe != null) { responsepacket = nextpipe.process(packet); } else { if (nexttube != null) { responsepacket = fiber.current().owner.createfiber().runsync(nexttube, packet); } } packet = validateresponse(responsepacket, null, null); } return packet; } | torstenwerner/metro2.0 | [
1,
0,
0,
0
] |
30,177 | @Messages({
"# {0} - variable name",
"ERR_NeitherReadOrWritten=Variable {0} is neither read or written to",
"# {0} - variable name",
"ERR_NotWritten=Variable {0} is never written to",
"# {0} - variable name",
"ERR_NotRead=Variable {0} is never read",
"# {0} - element name",
"ERR_NotUsed={0} is never used",
"ERR_NotUsedConstructor=Constructor is never used",
})
private static ErrorDescription convertUnused(HintContext ctx, UnusedDescription ud) {
//TODO: switch expression candidate!
String name = ud.unusedElement.getSimpleName().toString();
String message;
switch (ud.reason) {
case NOT_WRITTEN_READ: message = Bundle.ERR_NeitherReadOrWritten(name); break;
case NOT_WRITTEN: message = Bundle.ERR_NotWritten(name); break;
case NOT_READ: message = Bundle.ERR_NotRead(name); break;
case NOT_USED:
if (ud.unusedElement.getKind() == ElementKind.CONSTRUCTOR) {
message = Bundle.ERR_NotUsedConstructor();
} else {
message = Bundle.ERR_NotUsed(name);
}
break;
default:
throw new IllegalStateException("Unknown unused type: " + ud.reason);
}
return ErrorDescriptionFactory.forName(ctx, ud.unusedElementPath, message);
} | @Messages({
"# {0} - variable name",
"ERR_NeitherReadOrWritten=Variable {0} is neither read or written to",
"# {0} - variable name",
"ERR_NotWritten=Variable {0} is never written to",
"# {0} - variable name",
"ERR_NotRead=Variable {0} is never read",
"# {0} - element name",
"ERR_NotUsed={0} is never used",
"ERR_NotUsedConstructor=Constructor is never used",
})
private static ErrorDescription convertUnused(HintContext ctx, UnusedDescription ud) {
String name = ud.unusedElement.getSimpleName().toString();
String message;
switch (ud.reason) {
case NOT_WRITTEN_READ: message = Bundle.ERR_NeitherReadOrWritten(name); break;
case NOT_WRITTEN: message = Bundle.ERR_NotWritten(name); break;
case NOT_READ: message = Bundle.ERR_NotRead(name); break;
case NOT_USED:
if (ud.unusedElement.getKind() == ElementKind.CONSTRUCTOR) {
message = Bundle.ERR_NotUsedConstructor();
} else {
message = Bundle.ERR_NotUsed(name);
}
break;
default:
throw new IllegalStateException("Unknown unused type: " + ud.reason);
}
return ErrorDescriptionFactory.forName(ctx, ud.unusedElementPath, message);
} | @messages({ "# {0} - variable name", "err_neitherreadorwritten=variable {0} is neither read or written to", "# {0} - variable name", "err_notwritten=variable {0} is never written to", "# {0} - variable name", "err_notread=variable {0} is never read", "# {0} - element name", "err_notused={0} is never used", "err_notusedconstructor=constructor is never used", }) private static errordescription convertunused(hintcontext ctx, unuseddescription ud) { string name = ud.unusedelement.getsimplename().tostring(); string message; switch (ud.reason) { case not_written_read: message = bundle.err_neitherreadorwritten(name); break; case not_written: message = bundle.err_notwritten(name); break; case not_read: message = bundle.err_notread(name); break; case not_used: if (ud.unusedelement.getkind() == elementkind.constructor) { message = bundle.err_notusedconstructor(); } else { message = bundle.err_notused(name); } break; default: throw new illegalstateexception("unknown unused type: " + ud.reason); } return errordescriptionfactory.forname(ctx, ud.unusedelementpath, message); } | timfel/netbeans | [
1,
0,
0,
0
] |
14,028 | public String getHost() {
return "localhost";
} | public String getHost() {
return "localhost";
} | public string gethost() { return "localhost"; } | timboudreau/netbeans-contrib | [
1,
0,
0,
0
] |
30,445 | private AMQProducerBrokerExchange getProducerBrokerExchange(ProducerId id) throws IOException {
AMQProducerBrokerExchange result = producerExchanges.get(id);
if (result == null) {
synchronized (producerExchanges) {
result = new AMQProducerBrokerExchange();
result.setConnectionContext(context);
//todo implement reconnect https://issues.apache.org/jira/browse/ARTEMIS-194
//todo: this used to check for && this.acceptorUsed.isAuditNetworkProducers()
if (context.isReconnect() || (context.isNetworkConnection())) {
// once implemented ARTEMIS-194, we need to set the storedSequenceID here somehow
// We have different semantics on Artemis Journal, but we could adapt something for this
// TBD during the implemetnation of ARTEMIS-194
result.setLastStoredSequenceId(0);
}
SessionState ss = state.getSessionState(id.getParentId());
if (ss != null) {
result.setProducerState(ss.getProducerState(id));
ProducerState producerState = ss.getProducerState(id);
if (producerState != null && producerState.getInfo() != null) {
ProducerInfo info = producerState.getInfo();
result.setMutable(info.getDestination() == null || info.getDestination().isComposite());
}
}
producerExchanges.put(id, result);
}
}
return result;
} | private AMQProducerBrokerExchange getProducerBrokerExchange(ProducerId id) throws IOException {
AMQProducerBrokerExchange result = producerExchanges.get(id);
if (result == null) {
synchronized (producerExchanges) {
result = new AMQProducerBrokerExchange();
result.setConnectionContext(context);
if (context.isReconnect() || (context.isNetworkConnection())) {
result.setLastStoredSequenceId(0);
}
SessionState ss = state.getSessionState(id.getParentId());
if (ss != null) {
result.setProducerState(ss.getProducerState(id));
ProducerState producerState = ss.getProducerState(id);
if (producerState != null && producerState.getInfo() != null) {
ProducerInfo info = producerState.getInfo();
result.setMutable(info.getDestination() == null || info.getDestination().isComposite());
}
}
producerExchanges.put(id, result);
}
}
return result;
} | private amqproducerbrokerexchange getproducerbrokerexchange(producerid id) throws ioexception { amqproducerbrokerexchange result = producerexchanges.get(id); if (result == null) { synchronized (producerexchanges) { result = new amqproducerbrokerexchange(); result.setconnectioncontext(context); if (context.isreconnect() || (context.isnetworkconnection())) { result.setlaststoredsequenceid(0); } sessionstate ss = state.getsessionstate(id.getparentid()); if (ss != null) { result.setproducerstate(ss.getproducerstate(id)); producerstate producerstate = ss.getproducerstate(id); if (producerstate != null && producerstate.getinfo() != null) { producerinfo info = producerstate.getinfo(); result.setmutable(info.getdestination() == null || info.getdestination().iscomposite()); } } producerexchanges.put(id, result); } } return result; } | treblereel/activemq-artemis-wildfly | [
1,
1,
0,
0
] |
14,150 | @Override
public boolean shouldVisit(Page referringPage, WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches()
&& href.startsWith("http://www.ics.uci.edu/");
} | @Override
public boolean shouldVisit(Page referringPage, WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches()
&& href.startsWith("http://www.ics.uci.edu/");
} | @override public boolean shouldvisit(page referringpage, weburl url) { string href = url.geturl().tolowercase(); return !filters.matcher(href).matches() && href.startswith("http://www.ics.uci.edu/"); } | vjymits/musicFinder | [
0,
1,
0,
0
] |
22,813 | public boolean syncPingSupplicant(AsyncChannel channel) {
Message resultMsg = channel.sendMessageSynchronously(CMD_PING_SUPPLICANT);
boolean result = (resultMsg.arg1 != FAILURE);
resultMsg.recycle();
return result;
} | public boolean syncPingSupplicant(AsyncChannel channel) {
Message resultMsg = channel.sendMessageSynchronously(CMD_PING_SUPPLICANT);
boolean result = (resultMsg.arg1 != FAILURE);
resultMsg.recycle();
return result;
} | public boolean syncpingsupplicant(asyncchannel channel) { message resultmsg = channel.sendmessagesynchronously(cmd_ping_supplicant); boolean result = (resultmsg.arg1 != failure); resultmsg.recycle(); return result; } | zipated/src | [
0,
0,
0,
0
] |
22,816 | public void setSupplicantRunning(boolean enable) {
if (enable) {
sendMessage(CMD_START_SUPPLICANT);
} else {
sendMessage(CMD_STOP_SUPPLICANT);
}
} | public void setSupplicantRunning(boolean enable) {
if (enable) {
sendMessage(CMD_START_SUPPLICANT);
} else {
sendMessage(CMD_STOP_SUPPLICANT);
}
} | public void setsupplicantrunning(boolean enable) { if (enable) { sendmessage(cmd_start_supplicant); } else { sendmessage(cmd_stop_supplicant); } } | zipated/src | [
0,
0,
0,
0
] |
22,817 | public void setHostApRunning(WifiConfiguration wifiConfig, boolean enable) {
if (enable) {
sendMessage(CMD_START_AP, wifiConfig);
} else {
sendMessage(CMD_STOP_AP);
}
} | public void setHostApRunning(WifiConfiguration wifiConfig, boolean enable) {
if (enable) {
sendMessage(CMD_START_AP, wifiConfig);
} else {
sendMessage(CMD_STOP_AP);
}
} | public void sethostaprunning(wificonfiguration wificonfig, boolean enable) { if (enable) { sendmessage(cmd_start_ap, wificonfig); } else { sendmessage(cmd_stop_ap); } } | zipated/src | [
0,
0,
0,
0
] |
22,818 | public int syncGetWifiState() {
return mWifiState.get();
} | public int syncGetWifiState() {
return mWifiState.get();
} | public int syncgetwifistate() { return mwifistate.get(); } | zipated/src | [
0,
0,
0,
0
] |
22,819 | public String syncGetWifiStateByName() {
switch (mWifiState.get()) {
case WIFI_STATE_DISABLING:
return "disabling";
case WIFI_STATE_DISABLED:
return "disabled";
case WIFI_STATE_ENABLING:
return "enabling";
case WIFI_STATE_ENABLED:
return "enabled";
case WIFI_STATE_UNKNOWN:
return "unknown state";
default:
return "[invalid state]";
}
} | public String syncGetWifiStateByName() {
switch (mWifiState.get()) {
case WIFI_STATE_DISABLING:
return "disabling";
case WIFI_STATE_DISABLED:
return "disabled";
case WIFI_STATE_ENABLING:
return "enabling";
case WIFI_STATE_ENABLED:
return "enabled";
case WIFI_STATE_UNKNOWN:
return "unknown state";
default:
return "[invalid state]";
}
} | public string syncgetwifistatebyname() { switch (mwifistate.get()) { case wifi_state_disabling: return "disabling"; case wifi_state_disabled: return "disabled"; case wifi_state_enabling: return "enabling"; case wifi_state_enabled: return "enabled"; case wifi_state_unknown: return "unknown state"; default: return "[invalid state]"; } } | zipated/src | [
0,
0,
0,
0
] |
22,820 | public int syncGetWifiApState() {
return mWifiApState.get();
} | public int syncGetWifiApState() {
return mWifiApState.get();
} | public int syncgetwifiapstate() { return mwifiapstate.get(); } | zipated/src | [
0,
0,
0,
0
] |
22,821 | public String syncGetWifiApStateByName() {
switch (mWifiApState.get()) {
case WIFI_AP_STATE_DISABLING:
return "disabling";
case WIFI_AP_STATE_DISABLED:
return "disabled";
case WIFI_AP_STATE_ENABLING:
return "enabling";
case WIFI_AP_STATE_ENABLED:
return "enabled";
case WIFI_AP_STATE_FAILED:
return "failed";
default:
return "[invalid state]";
}
} | public String syncGetWifiApStateByName() {
switch (mWifiApState.get()) {
case WIFI_AP_STATE_DISABLING:
return "disabling";
case WIFI_AP_STATE_DISABLED:
return "disabled";
case WIFI_AP_STATE_ENABLING:
return "enabling";
case WIFI_AP_STATE_ENABLED:
return "enabled";
case WIFI_AP_STATE_FAILED:
return "failed";
default:
return "[invalid state]";
}
} | public string syncgetwifiapstatebyname() { switch (mwifiapstate.get()) { case wifi_ap_state_disabling: return "disabling"; case wifi_ap_state_disabled: return "disabled"; case wifi_ap_state_enabling: return "enabling"; case wifi_ap_state_enabled: return "enabled"; case wifi_ap_state_failed: return "failed"; default: return "[invalid state]"; } } | zipated/src | [
0,
0,
0,
0
] |
22,822 | public void setDriverStart(boolean enable) {
if (enable) {
sendMessage(CMD_START_DRIVER);
} else {
sendMessage(CMD_STOP_DRIVER);
}
} | public void setDriverStart(boolean enable) {
if (enable) {
sendMessage(CMD_START_DRIVER);
} else {
sendMessage(CMD_STOP_DRIVER);
}
} | public void setdriverstart(boolean enable) { if (enable) { sendmessage(cmd_start_driver); } else { sendmessage(cmd_stop_driver); } } | zipated/src | [
0,
0,
0,
0
] |
22,823 | public void setOperationalMode(int mode) {
if (DBG) log("setting operational mode to " + String.valueOf(mode));
sendMessage(CMD_SET_OPERATIONAL_MODE, mode, 0);
} | public void setOperationalMode(int mode) {
if (DBG) log("setting operational mode to " + String.valueOf(mode));
sendMessage(CMD_SET_OPERATIONAL_MODE, mode, 0);
} | public void setoperationalmode(int mode) { if (dbg) log("setting operational mode to " + string.valueof(mode)); sendmessage(cmd_set_operational_mode, mode, 0); } | zipated/src | [
0,
0,
0,
0
] |
22,824 | public List<ScanResult> syncGetScanResultsList() {
synchronized (mScanResultsLock) {
List<ScanResult> scanList = new ArrayList<ScanResult>();
for (ScanDetail result : mScanResults) {
scanList.add(new ScanResult(result.getScanResult()));
}
return scanList;
}
} | public List<ScanResult> syncGetScanResultsList() {
synchronized (mScanResultsLock) {
List<ScanResult> scanList = new ArrayList<ScanResult>();
for (ScanDetail result : mScanResults) {
scanList.add(new ScanResult(result.getScanResult()));
}
return scanList;
}
} | public list<scanresult> syncgetscanresultslist() { synchronized (mscanresultslock) { list<scanresult> scanlist = new arraylist<scanresult>(); for (scandetail result : mscanresults) { scanlist.add(new scanresult(result.getscanresult())); } return scanlist; } } | zipated/src | [
0,
0,
0,
0
] |
31,206 | public static void createAppointment(Appointment TemplateAppointment) {
// look up key to keys and "insert" to make everything work; //To change body of generated methods, choose Tools | Templates.
String sql = "INSERT INTO appointments Values(NULL, ?, ?,?,?,?,?,Now(),'',Now(),'',?,?,?)";
// (Appointment_ID,Title,Description, Type, Phone, Division_ID) VALUES (5, '', 'test', '', 'test','')" ;
try {
PreparedStatement ps = DBConnection.getConnection().prepareStatement(sql);
ps.setString(1, TemplateAppointment.getTitle());
ps.setString(2, TemplateAppointment.getDescription());
ps.setString(3, TemplateAppointment.getLocation());
ps.setString(4, TemplateAppointment.getType());
LocalDateTime start = LocalDateTime.of(TemplateAppointment.getDate(), TemplateAppointment.getStartTime());
start = WashTimeZone(start, ZoneId.systemDefault(), ZoneId.of("UTC"));
LocalDateTime end = LocalDateTime.of(TemplateAppointment.getDate(), TemplateAppointment.getEndTime());
end = WashTimeZone(end, ZoneId.systemDefault(), ZoneId.of("UTC"));
Timestamp Tstart = Timestamp.valueOf(start);
Timestamp Tend = Timestamp.valueOf(end);
ps.setTimestamp(5, Tstart);
ps.setTimestamp(6, Tend);
//timezone work needs to happen here
ps.setInt(7, TemplateAppointment.getCustomerid());
ps.setInt(8, TemplateAppointment.getUserid());
ps.setInt(9, TemplateAppointment.getContactid());
ps.execute();
} catch (SQLException ex) {
ex.printStackTrace();
}
} | public static void createAppointment(Appointment TemplateAppointment) {
String sql = "INSERT INTO appointments Values(NULL, ?, ?,?,?,?,?,Now(),'',Now(),'',?,?,?)";
try {
PreparedStatement ps = DBConnection.getConnection().prepareStatement(sql);
ps.setString(1, TemplateAppointment.getTitle());
ps.setString(2, TemplateAppointment.getDescription());
ps.setString(3, TemplateAppointment.getLocation());
ps.setString(4, TemplateAppointment.getType());
LocalDateTime start = LocalDateTime.of(TemplateAppointment.getDate(), TemplateAppointment.getStartTime());
start = WashTimeZone(start, ZoneId.systemDefault(), ZoneId.of("UTC"));
LocalDateTime end = LocalDateTime.of(TemplateAppointment.getDate(), TemplateAppointment.getEndTime());
end = WashTimeZone(end, ZoneId.systemDefault(), ZoneId.of("UTC"));
Timestamp Tstart = Timestamp.valueOf(start);
Timestamp Tend = Timestamp.valueOf(end);
ps.setTimestamp(5, Tstart);
ps.setTimestamp(6, Tend);
ps.setInt(7, TemplateAppointment.getCustomerid());
ps.setInt(8, TemplateAppointment.getUserid());
ps.setInt(9, TemplateAppointment.getContactid());
ps.execute();
} catch (SQLException ex) {
ex.printStackTrace();
}
} | public static void createappointment(appointment templateappointment) { string sql = "insert into appointments values(null, ?, ?,?,?,?,?,now(),'',now(),'',?,?,?)"; try { preparedstatement ps = dbconnection.getconnection().preparestatement(sql); ps.setstring(1, templateappointment.gettitle()); ps.setstring(2, templateappointment.getdescription()); ps.setstring(3, templateappointment.getlocation()); ps.setstring(4, templateappointment.gettype()); localdatetime start = localdatetime.of(templateappointment.getdate(), templateappointment.getstarttime()); start = washtimezone(start, zoneid.systemdefault(), zoneid.of("utc")); localdatetime end = localdatetime.of(templateappointment.getdate(), templateappointment.getendtime()); end = washtimezone(end, zoneid.systemdefault(), zoneid.of("utc")); timestamp tstart = timestamp.valueof(start); timestamp tend = timestamp.valueof(end); ps.settimestamp(5, tstart); ps.settimestamp(6, tend); ps.setint(7, templateappointment.getcustomerid()); ps.setint(8, templateappointment.getuserid()); ps.setint(9, templateappointment.getcontactid()); ps.execute(); } catch (sqlexception ex) { ex.printstacktrace(); } } | yinwil27/PortfolioRepositorySQLJava | [
0,
1,
0,
0
] |
31,207 | public static void updateAppointments(Appointment PlaceholderAppointment) {
// look up key to keys and "insert" to make everything work; //To change body of generated methods, choose Tools | Templates.
String sql = "UPDATE appointments SET Title =?, Description=?, Location=?, Type=?, start=?, end=?, Customer_ID=?, User_ID=?, Contact_ID=? WHERE Appointment_ID = ?";
try {
PreparedStatement ps = DBConnection.getConnection().prepareStatement(sql);
ps.setString(1, PlaceholderAppointment.getTitle());
ps.setString(2, PlaceholderAppointment.getDescription());
ps.setString(3, PlaceholderAppointment.getLocation());
ps.setString(4, PlaceholderAppointment.getType());
LocalDateTime start = LocalDateTime.of(PlaceholderAppointment.getDate(), PlaceholderAppointment.getStartTime());
start = WashTimeZone(start, ZoneId.systemDefault(), ZoneId.of("UTC"));
LocalDateTime end = LocalDateTime.of(PlaceholderAppointment.getDate(), PlaceholderAppointment.getEndTime());
end = WashTimeZone(end, ZoneId.systemDefault(), ZoneId.of("UTC"));
Timestamp Tstart = Timestamp.valueOf(start);
Timestamp Tend = Timestamp.valueOf(end);
ps.setTimestamp(5, Tstart);
ps.setTimestamp(6, Tend);
//timezone work needs to happen here
ps.setInt(7, PlaceholderAppointment.getCustomerid());
ps.setInt(8, PlaceholderAppointment.getUserid());
ps.setInt(9, PlaceholderAppointment.getContactid());
ps.setInt(10, PlaceholderAppointment.getAppointment_ID());
ps.execute();
} catch (SQLException ex) {
ex.printStackTrace();
}
} | public static void updateAppointments(Appointment PlaceholderAppointment) {
String sql = "UPDATE appointments SET Title =?, Description=?, Location=?, Type=?, start=?, end=?, Customer_ID=?, User_ID=?, Contact_ID=? WHERE Appointment_ID = ?";
try {
PreparedStatement ps = DBConnection.getConnection().prepareStatement(sql);
ps.setString(1, PlaceholderAppointment.getTitle());
ps.setString(2, PlaceholderAppointment.getDescription());
ps.setString(3, PlaceholderAppointment.getLocation());
ps.setString(4, PlaceholderAppointment.getType());
LocalDateTime start = LocalDateTime.of(PlaceholderAppointment.getDate(), PlaceholderAppointment.getStartTime());
start = WashTimeZone(start, ZoneId.systemDefault(), ZoneId.of("UTC"));
LocalDateTime end = LocalDateTime.of(PlaceholderAppointment.getDate(), PlaceholderAppointment.getEndTime());
end = WashTimeZone(end, ZoneId.systemDefault(), ZoneId.of("UTC"));
Timestamp Tstart = Timestamp.valueOf(start);
Timestamp Tend = Timestamp.valueOf(end);
ps.setTimestamp(5, Tstart);
ps.setTimestamp(6, Tend);
ps.setInt(7, PlaceholderAppointment.getCustomerid());
ps.setInt(8, PlaceholderAppointment.getUserid());
ps.setInt(9, PlaceholderAppointment.getContactid());
ps.setInt(10, PlaceholderAppointment.getAppointment_ID());
ps.execute();
} catch (SQLException ex) {
ex.printStackTrace();
}
} | public static void updateappointments(appointment placeholderappointment) { string sql = "update appointments set title =?, description=?, location=?, type=?, start=?, end=?, customer_id=?, user_id=?, contact_id=? where appointment_id = ?"; try { preparedstatement ps = dbconnection.getconnection().preparestatement(sql); ps.setstring(1, placeholderappointment.gettitle()); ps.setstring(2, placeholderappointment.getdescription()); ps.setstring(3, placeholderappointment.getlocation()); ps.setstring(4, placeholderappointment.gettype()); localdatetime start = localdatetime.of(placeholderappointment.getdate(), placeholderappointment.getstarttime()); start = washtimezone(start, zoneid.systemdefault(), zoneid.of("utc")); localdatetime end = localdatetime.of(placeholderappointment.getdate(), placeholderappointment.getendtime()); end = washtimezone(end, zoneid.systemdefault(), zoneid.of("utc")); timestamp tstart = timestamp.valueof(start); timestamp tend = timestamp.valueof(end); ps.settimestamp(5, tstart); ps.settimestamp(6, tend); ps.setint(7, placeholderappointment.getcustomerid()); ps.setint(8, placeholderappointment.getuserid()); ps.setint(9, placeholderappointment.getcontactid()); ps.setint(10, placeholderappointment.getappointment_id()); ps.execute(); } catch (sqlexception ex) { ex.printstacktrace(); } } | yinwil27/PortfolioRepositorySQLJava | [
0,
1,
0,
0
] |
23,126 | public String replaceTokens(Pattern pattern, String userAgentString, String format)
{
// System.out.println("UserAgent: " + userAgentString);
// System.out.println("Regexp: " + pattern.toString());
// System.out.println("Replacement: " + format);
Matcher m = pattern.matcher(userAgentString);
// Move the group content into an array
List<String> groupContent = new ArrayList<String>();
// System.out.println("Group Count: "+m.groupCount());
m.find();
for(int i=0; i<=m.groupCount(); i++)
{
String s = m.group(i);
// System.out.println("--"+s);
groupContent.add(s);
}
// Replace the tokens in the pattern
for(int i=0; i<groupContent.size(); i++)
{
String token = "#\\{\\$"+i+"\\}";
// System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]");
format = format.replaceAll(token, groupContent.get(i));
}
// System.out.println("Response: "+format);
return format;
} | public String replaceTokens(Pattern pattern, String userAgentString, String format)
{
Matcher m = pattern.matcher(userAgentString);
List<String> groupContent = new ArrayList<String>();
m.find();
for(int i=0; i<=m.groupCount(); i++)
{
String s = m.group(i);
groupContent.add(s);
}
for(int i=0; i<groupContent.size(); i++)
{
String token = "#\\{\\$"+i+"\\}";
format = format.replaceAll(token, groupContent.get(i));
}
return format;
} | public string replacetokens(pattern pattern, string useragentstring, string format) { matcher m = pattern.matcher(useragentstring); list<string> groupcontent = new arraylist<string>(); m.find(); for(int i=0; i<=m.groupcount(); i++) { string s = m.group(i); groupcontent.add(s); } for(int i=0; i<groupcontent.size(); i++) { string token = "#\\{\\$"+i+"\\}"; format = format.replaceall(token, groupcontent.get(i)); } return format; } | ysc972/UserAgentParser | [
1,
0,
0,
0
] |
15,012 | private void doTestServerEventsInSystemClient() throws Exception {
// KIRK: this test fails intermittently with bug 37482
final boolean[] firedSystem = new boolean[3];
final DistributedMember[] memberSystem = new DistributedMember[3];
final String[] memberIdSystem = new String[3];
final boolean[] isClientSystem = new boolean[3];
final boolean[] firedAdapter = new boolean[3];
final DistributedMember[] memberAdapter = new DistributedMember[3];
final String[] memberIdAdapter = new String[3];
final boolean[] isClientAdapter = new boolean[3];
final boolean[] firedBridge = new boolean[3];
final DistributedMember[] memberBridge = new DistributedMember[3];
final String[] memberIdBridge = new String[3];
final boolean[] isClientBridge = new boolean[3];
final boolean[] firedSystemDuplicate = new boolean[3];
final boolean[] firedAdapterDuplicate = new boolean[3];
final boolean[] firedBridgeDuplicate = new boolean[3];
SystemMembershipListener systemListener = new SystemMembershipListener() {
public synchronized void memberJoined(SystemMembershipEvent event) {
firedSystemDuplicate[JOINED] = firedSystem[JOINED];
firedSystem[JOINED] = true;
memberSystem[JOINED] = event.getDistributedMember();
memberIdSystem[JOINED] = event.getMemberId();
notify();
}
public synchronized void memberLeft(SystemMembershipEvent event) {
firedSystemDuplicate[LEFT] = firedSystem[LEFT];
firedSystem[LEFT] = true;
memberSystem[LEFT] = event.getDistributedMember();
memberIdSystem[LEFT] = event.getMemberId();
notify();
}
public synchronized void memberCrashed(SystemMembershipEvent event) {
firedSystemDuplicate[CRASHED] = firedSystem[CRASHED];
firedSystem[CRASHED] = true;
memberSystem[CRASHED] = event.getDistributedMember();
memberIdSystem[CRASHED] = event.getMemberId();
notify();
}
};
UniversalMembershipListenerAdapter adapter =
new UniversalMembershipListenerAdapter() {
@Override
public synchronized void memberJoined(SystemMembershipEvent event) {
getLogWriter().info("[testServerEventsInSystemClient] memberJoined >" + event.getMemberId() + "<");
firedAdapterDuplicate[JOINED] = firedAdapter[JOINED];
firedAdapter[JOINED] = true;
memberAdapter[JOINED] = event.getDistributedMember();
memberIdAdapter[JOINED] = event.getMemberId();
if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) {
isClientAdapter[JOINED] =
((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient();
}
notify();
}
@Override
public synchronized void memberLeft(SystemMembershipEvent event) {
getLogWriter().info("[testServerEventsInSystemClient] memberLeft >" + event.getMemberId() + "<");
firedAdapterDuplicate[LEFT] = firedAdapter[LEFT];
firedAdapter[LEFT] = true;
memberAdapter[LEFT] = event.getDistributedMember();
memberIdAdapter[LEFT] = event.getMemberId();
if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) {
isClientAdapter[LEFT] =
((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient();
}
notify();
}
@Override
public synchronized void memberCrashed(SystemMembershipEvent event) {
getLogWriter().info("[testServerEventsInSystemClient] memberCrashed >" + event.getMemberId() + "<");
firedAdapterDuplicate[CRASHED] = firedAdapter[CRASHED];
firedAdapter[CRASHED] = true;
memberAdapter[CRASHED] = event.getDistributedMember();
memberIdAdapter[CRASHED] = event.getMemberId();
if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) {
isClientAdapter[CRASHED] =
((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient();
}
notify();
}
};
BridgeMembershipListener bridgeListener = new BridgeMembershipListener() {
public synchronized void memberJoined(BridgeMembershipEvent event) {
firedBridgeDuplicate[JOINED] = firedBridge[JOINED];
firedBridge[JOINED] = true;
memberBridge[JOINED] = event.getMember();
memberIdBridge[JOINED] = event.getMemberId();
isClientBridge[JOINED] = event.isClient();
notify();
}
public synchronized void memberLeft(BridgeMembershipEvent event) {
firedBridgeDuplicate[LEFT] = firedBridge[LEFT];
firedBridge[LEFT] = true;
memberBridge[LEFT] = event.getMember();
memberIdBridge[LEFT] = event.getMemberId();
isClientBridge[LEFT] = event.isClient();
notify();
}
public synchronized void memberCrashed(BridgeMembershipEvent event) {
firedBridgeDuplicate[CRASHED] = firedBridge[CRASHED];
firedBridge[CRASHED] = true;
memberBridge[CRASHED] = event.getMember();
memberIdBridge[CRASHED] = event.getMemberId();
isClientBridge[CRASHED] = event.isClient();
notify();
}
};
final Host host = Host.getHost(0);
final VM vm0 = host.getVM(0);
final String name = this.getUniqueName();
final int[] ports = new int[]
{ AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) };
assertTrue(ports[0] != 0);
// getLogWriter().info("[testServerEventsInSystemClient] create bridge client");
// Properties config = new Properties();
// config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
// config.setProperty(DistributionConfig.LOCATORS_NAME, "");
// getSystem(config);
// AttributesFactory factory = new AttributesFactory();
// factory.setScope(Scope.LOCAL);
// BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null);
// createRegion(name, factory.create());
// assertNotNull(getRootRegion().getSubregion(name));
getLogWriter().info("[testServerEventsInSystemClient] create system bridge client");
getSystem();
final Properties clientProperties = getSystemProperties();
// register the bridge listener
BridgeMembership.registerBridgeMembershipListener(bridgeListener);
DistributedSystemConfig config =
AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null);
AdminDistributedSystem adminDS =
AdminDistributedSystemFactory.getDistributedSystem(config);
adminDS.connect();
assertTrue(adminDS.waitToBeConnected(5 * 1000));
// register the system listener
adminDS.addMembershipListener(systemListener);
// register the universal adapter
adapter.registerMembershipListener(adminDS);
// create BridgeServer in vm0...
SerializableRunnable createBridgeServer =
new CacheSerializableRunnable("Create BridgeServer") {
@Override
public void run2() throws CacheException {
getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer");
getSystem(clientProperties);
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
Region region = createRegion(name, factory.create());
assertNotNull(region);
assertNotNull(getRootRegion().getSubregion(name));
try {
testServerEventsInSystemClient_port = startBridgeServer(ports[0]);
}
catch (IOException e) {
getLogWriter().error(e);
fail(e.getMessage());
}
}
};
vm0.invoke(createBridgeServer);
// gather details for later creation of BridgeLoader...
assertEquals(ports[0],
vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class,
"getTestServerEventsInSystemClient_port"));
String serverMemberId = (String) vm0.invoke(
UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId");
DistributedMember serverMember = (DistributedMember) vm0.invoke(
UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember");
getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]);
getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId);
getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember);
// create region which connects to bridge server
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null);
createRegion(name, factory.create());
assertNotNull(getRootRegion().getSubregion(name));
synchronized(systemListener) {
if (!firedSystem[JOINED]) {
systemListener.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
synchronized(adapter) {
if (!firedAdapter[JOINED]) {
adapter.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
synchronized(bridgeListener) {
if (!firedBridge[JOINED]) {
bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join");
assertFalse(firedSystemDuplicate);
// TODO: sometimes get adapter duplicate since memberId isn't endpoint
// initial impl uses Endpoint.toString() for memberId of server; final
// impl should have server send its real memberId to client via HandShake
//assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.",
// firedAdapterDuplicate);
assertFalse(firedBridgeDuplicate);
assertTrue(firedBridge[JOINED]);
assertEquals(serverMember, memberBridge[JOINED]);
assertEquals(serverMemberId, memberIdBridge[JOINED]);
assertNotNull(memberBridge[JOINED]);
assertNotNull(memberIdBridge[JOINED]);
assertFalse(isClientBridge[JOINED]);
assertFalse(firedBridge[LEFT]);
assertNull(memberBridge[LEFT]);
assertNull(memberIdBridge[LEFT]);
assertFalse(isClientBridge[LEFT]);
assertFalse(firedBridge[CRASHED]);
assertNull(memberBridge[CRASHED]);
assertNull(memberIdBridge[CRASHED]);
assertFalse(isClientBridge[CRASHED]);
resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge);
assertTrue(firedSystem[JOINED]);
assertEquals(serverMember, memberSystem[JOINED]);
assertEquals(serverMemberId, memberIdSystem[JOINED]);
assertFalse(isClientSystem[JOINED]);
assertFalse(firedSystem[LEFT]);
assertNull(memberSystem[LEFT]);
assertNull(memberIdSystem[LEFT]);
assertFalse(isClientSystem[LEFT]);
assertFalse(firedSystem[CRASHED]);
assertNull(memberSystem[CRASHED]);
assertNull(memberIdSystem[CRASHED]);
assertFalse(isClientSystem[CRASHED]);
resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem);
assertTrue(firedAdapter[JOINED]);
assertNotNull(memberAdapter[JOINED]);
assertNotNull(memberIdAdapter[JOINED]);
assertEquals(serverMember, memberAdapter[JOINED]);
assertEquals(serverMemberId, memberIdAdapter[JOINED]);
assertFalse(isClientAdapter[JOINED]);
assertFalse(firedAdapter[LEFT]);
assertNull(memberAdapter[LEFT]);
assertNull(memberIdAdapter[LEFT]);
assertFalse(isClientAdapter[LEFT]);
assertFalse(firedAdapter[CRASHED]);
assertNull(memberAdapter[CRASHED]);
assertNull(memberIdAdapter[CRASHED]);
assertFalse(isClientAdapter[CRASHED]);
resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter);
getLogWriter().info("[testServerEventsInSystemClient] wait for client to fully connect");
final String pl =
getRootRegion().getSubregion(name).getAttributes().getPoolName();
PoolImpl pi = (PoolImpl)PoolManager.find(pl);
waitForClientToFullyConnect(pi);
LogWriter bgexecLogger =
new LocalLogWriter(LogWriterImpl.ALL_LEVEL, System.out);
bgexecLogger.info("<ExpectedException action=add>" +
"java.io.IOException" + "</ExpectedException>");
final ExpectedException ex = addExpectedException(
ServerConnectivityException.class.getName());
try {
vm0.invoke(new SerializableRunnable("Disconnect bridge server") {
public void run() {
getLogWriter().info("[testServerEventsInSystemClient] disconnect bridge server");
closeCache();
disconnectFromDS();
}
});
synchronized(systemListener) {
if (!firedSystem[LEFT]) {
systemListener.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
synchronized(adapter) {
if (!firedAdapter[LEFT]) {
adapter.wait(ASYNC_EVENT_WAIT_MILLIS); // KIRK: did increasing this solve problem on balrog?
}
}
synchronized(bridgeListener) {
if (!firedBridge[LEFT]) {
bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
}
finally {
bgexecLogger.info("<ExpectedException action=remove>" +
"java.io.IOException" + "</ExpectedException>");
ex.remove();
}
getLogWriter().info("[testServerEventsInSystemClient] assert client detected server crashed");
assertFalse(firedSystemDuplicate);
// TODO: sometimes get adapter duplicate since memberId isn't endpoint
// initial impl uses Endpoint.toString() for memberId of server; final
// impl should have server send its real memberId to client via HandShake
//assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.",
// firedAdapterDuplicate);
assertFalse(firedAdapterDuplicate);
assertFalse(firedBridgeDuplicate);
assertFalse(firedBridge[JOINED]);
assertNull(memberIdBridge[JOINED]);
assertNull(memberBridge[JOINED]);
assertFalse(isClientBridge[JOINED]);
assertFalse("Please update testServerEventsInSystemClient to handle memberLeft for BridgeServer.",
firedBridge[LEFT]);
assertNull(memberBridge[LEFT]);
assertNull(memberIdBridge[LEFT]);
assertFalse(isClientBridge[LEFT]);
assertTrue(firedBridge[CRASHED]);
assertNotNull(memberBridge[CRASHED]);
assertNotNull(memberIdBridge[CRASHED]);
assertEquals(serverMemberId, memberIdBridge[CRASHED]);
assertEquals(serverMember, memberBridge[CRASHED]);
assertFalse(isClientBridge[CRASHED]);
resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge);
assertFalse(firedSystem[JOINED]);
assertNull(memberSystem[JOINED]);
assertNull(memberIdSystem[JOINED]);
assertFalse(isClientSystem[JOINED]);
assertTrue(firedSystem[LEFT]);
assertEquals(serverMember, memberSystem[LEFT]);
assertEquals(serverMemberId, memberIdSystem[LEFT]);
assertFalse(isClientSystem[LEFT]);
assertFalse(firedSystem[CRASHED]);
assertNull(memberSystem[CRASHED]);
assertNull(memberIdSystem[CRASHED]);
assertFalse(isClientSystem[CRASHED]);
resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem);
assertFalse("this intermittently fails", firedAdapter[JOINED]); // KIRK --> this fails on balrog occasionally
assertNull(memberIdAdapter[JOINED]);
assertFalse(isClientAdapter[JOINED]);
// LEFT fired by System listener
assertTrue(firedAdapter[LEFT]);
assertEquals(serverMember, memberAdapter[LEFT]);
assertEquals(serverMemberId, memberIdAdapter[LEFT]);
assertFalse(isClientAdapter[LEFT]);
// There won't be an adapter crashed event because since the two VMs
// are in the same distributed system, and the server's real member
// id is used now. In this case, two events are sent - one from
// jgroups (memberDeparted), and one from the server (a memberCrshed).
// The memberCrashed event is deemed a duplicate and not sent - see
// UniversalMembershipListenerAdapter.SystemMembershipListener.isDuplicate
assertFalse(firedAdapter[CRASHED]);
assertNull(memberAdapter[CRASHED]);
assertNull(memberIdAdapter[CRASHED]);
assertFalse(isClientAdapter[CRASHED]);
resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter);
// reconnect bridge client to test for crashed event
vm0.invoke(createBridgeServer);
// gather details for later creation of BridgeLoader...
assertEquals(ports[0],
vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class,
"getTestServerEventsInSystemClient_port"));
serverMemberId = (String) vm0.invoke(
UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId");
serverMember = (DistributedMember) vm0.invoke(
UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember");
getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]);
getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId);
getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember);
synchronized(systemListener) {
if (!firedSystem[JOINED]) {
systemListener.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
synchronized(adapter) {
if (!firedAdapter[JOINED]) {
adapter.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
synchronized(bridgeListener) {
if (!firedBridge[JOINED]) {
bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
getLogWriter().info("[testServerEventsInSystemClient] assert client detected server re-join");
assertFalse(firedSystemDuplicate);
// TODO: sometimes get adapter duplicate since memberId isn't endpoint
// initial impl uses Endpoint.toString() for memberId of server; final
// impl should have server send its real memberId to client via HandShake
//assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.",
// firedAdapterDuplicate);
assertFalse(firedBridgeDuplicate);
assertTrue(firedBridge[JOINED]);
assertNotNull(memberBridge[JOINED]);
assertNotNull(memberIdBridge[JOINED]);
assertEquals(serverMember, memberBridge[JOINED]);
assertEquals(serverMemberId, memberIdBridge[JOINED]);
assertFalse(isClientBridge[JOINED]);
assertFalse(firedBridge[LEFT]);
assertNull(memberBridge[LEFT]);
assertNull(memberIdBridge[LEFT]);
assertFalse(isClientBridge[LEFT]);
assertFalse(firedBridge[CRASHED]);
assertNull(memberBridge[CRASHED]);
assertNull(memberIdBridge[CRASHED]);
assertFalse(isClientBridge[CRASHED]);
resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge);
assertTrue(firedSystem[JOINED]);
assertEquals(serverMember, memberSystem[JOINED]);
assertEquals(serverMemberId, memberIdSystem[JOINED]);
assertFalse(isClientSystem[JOINED]);
assertFalse(firedSystem[LEFT]);
assertNull(memberSystem[LEFT]);
assertNull(memberIdSystem[LEFT]);
assertFalse(isClientSystem[LEFT]);
assertFalse(firedSystem[CRASHED]);
assertNull(memberSystem[CRASHED]);
assertNull(memberIdSystem[CRASHED]);
assertFalse(isClientSystem[CRASHED]);
resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem);
assertTrue(firedAdapter[JOINED]);
assertNotNull(memberAdapter[JOINED]);
assertNotNull(memberIdAdapter[JOINED]);
assertEquals(serverMember, memberAdapter[JOINED]);
assertEquals(serverMemberId, memberIdAdapter[JOINED]);
assertFalse(isClientAdapter[JOINED]);
assertFalse(firedAdapter[LEFT]);
assertNull(memberAdapter[LEFT]);
assertNull(memberIdAdapter[LEFT]);
assertFalse(isClientAdapter[LEFT]);
assertFalse(firedAdapter[CRASHED]);
assertNull(memberAdapter[CRASHED]);
assertNull(memberIdAdapter[CRASHED]);
assertFalse(isClientAdapter[CRASHED]);
resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter);
} | private void doTestServerEventsInSystemClient() throws Exception {
final boolean[] firedSystem = new boolean[3];
final DistributedMember[] memberSystem = new DistributedMember[3];
final String[] memberIdSystem = new String[3];
final boolean[] isClientSystem = new boolean[3];
final boolean[] firedAdapter = new boolean[3];
final DistributedMember[] memberAdapter = new DistributedMember[3];
final String[] memberIdAdapter = new String[3];
final boolean[] isClientAdapter = new boolean[3];
final boolean[] firedBridge = new boolean[3];
final DistributedMember[] memberBridge = new DistributedMember[3];
final String[] memberIdBridge = new String[3];
final boolean[] isClientBridge = new boolean[3];
final boolean[] firedSystemDuplicate = new boolean[3];
final boolean[] firedAdapterDuplicate = new boolean[3];
final boolean[] firedBridgeDuplicate = new boolean[3];
SystemMembershipListener systemListener = new SystemMembershipListener() {
public synchronized void memberJoined(SystemMembershipEvent event) {
firedSystemDuplicate[JOINED] = firedSystem[JOINED];
firedSystem[JOINED] = true;
memberSystem[JOINED] = event.getDistributedMember();
memberIdSystem[JOINED] = event.getMemberId();
notify();
}
public synchronized void memberLeft(SystemMembershipEvent event) {
firedSystemDuplicate[LEFT] = firedSystem[LEFT];
firedSystem[LEFT] = true;
memberSystem[LEFT] = event.getDistributedMember();
memberIdSystem[LEFT] = event.getMemberId();
notify();
}
public synchronized void memberCrashed(SystemMembershipEvent event) {
firedSystemDuplicate[CRASHED] = firedSystem[CRASHED];
firedSystem[CRASHED] = true;
memberSystem[CRASHED] = event.getDistributedMember();
memberIdSystem[CRASHED] = event.getMemberId();
notify();
}
};
UniversalMembershipListenerAdapter adapter =
new UniversalMembershipListenerAdapter() {
@Override
public synchronized void memberJoined(SystemMembershipEvent event) {
getLogWriter().info("[testServerEventsInSystemClient] memberJoined >" + event.getMemberId() + "<");
firedAdapterDuplicate[JOINED] = firedAdapter[JOINED];
firedAdapter[JOINED] = true;
memberAdapter[JOINED] = event.getDistributedMember();
memberIdAdapter[JOINED] = event.getMemberId();
if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) {
isClientAdapter[JOINED] =
((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient();
}
notify();
}
@Override
public synchronized void memberLeft(SystemMembershipEvent event) {
getLogWriter().info("[testServerEventsInSystemClient] memberLeft >" + event.getMemberId() + "<");
firedAdapterDuplicate[LEFT] = firedAdapter[LEFT];
firedAdapter[LEFT] = true;
memberAdapter[LEFT] = event.getDistributedMember();
memberIdAdapter[LEFT] = event.getMemberId();
if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) {
isClientAdapter[LEFT] =
((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient();
}
notify();
}
@Override
public synchronized void memberCrashed(SystemMembershipEvent event) {
getLogWriter().info("[testServerEventsInSystemClient] memberCrashed >" + event.getMemberId() + "<");
firedAdapterDuplicate[CRASHED] = firedAdapter[CRASHED];
firedAdapter[CRASHED] = true;
memberAdapter[CRASHED] = event.getDistributedMember();
memberIdAdapter[CRASHED] = event.getMemberId();
if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) {
isClientAdapter[CRASHED] =
((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient();
}
notify();
}
};
BridgeMembershipListener bridgeListener = new BridgeMembershipListener() {
public synchronized void memberJoined(BridgeMembershipEvent event) {
firedBridgeDuplicate[JOINED] = firedBridge[JOINED];
firedBridge[JOINED] = true;
memberBridge[JOINED] = event.getMember();
memberIdBridge[JOINED] = event.getMemberId();
isClientBridge[JOINED] = event.isClient();
notify();
}
public synchronized void memberLeft(BridgeMembershipEvent event) {
firedBridgeDuplicate[LEFT] = firedBridge[LEFT];
firedBridge[LEFT] = true;
memberBridge[LEFT] = event.getMember();
memberIdBridge[LEFT] = event.getMemberId();
isClientBridge[LEFT] = event.isClient();
notify();
}
public synchronized void memberCrashed(BridgeMembershipEvent event) {
firedBridgeDuplicate[CRASHED] = firedBridge[CRASHED];
firedBridge[CRASHED] = true;
memberBridge[CRASHED] = event.getMember();
memberIdBridge[CRASHED] = event.getMemberId();
isClientBridge[CRASHED] = event.isClient();
notify();
}
};
final Host host = Host.getHost(0);
final VM vm0 = host.getVM(0);
final String name = this.getUniqueName();
final int[] ports = new int[]
{ AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) };
assertTrue(ports[0] != 0);
getLogWriter().info("[testServerEventsInSystemClient] create system bridge client");
getSystem();
final Properties clientProperties = getSystemProperties();
BridgeMembership.registerBridgeMembershipListener(bridgeListener);
DistributedSystemConfig config =
AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null);
AdminDistributedSystem adminDS =
AdminDistributedSystemFactory.getDistributedSystem(config);
adminDS.connect();
assertTrue(adminDS.waitToBeConnected(5 * 1000));
adminDS.addMembershipListener(systemListener);
adapter.registerMembershipListener(adminDS);
SerializableRunnable createBridgeServer =
new CacheSerializableRunnable("Create BridgeServer") {
@Override
public void run2() throws CacheException {
getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer");
getSystem(clientProperties);
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
Region region = createRegion(name, factory.create());
assertNotNull(region);
assertNotNull(getRootRegion().getSubregion(name));
try {
testServerEventsInSystemClient_port = startBridgeServer(ports[0]);
}
catch (IOException e) {
getLogWriter().error(e);
fail(e.getMessage());
}
}
};
vm0.invoke(createBridgeServer);
assertEquals(ports[0],
vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class,
"getTestServerEventsInSystemClient_port"));
String serverMemberId = (String) vm0.invoke(
UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId");
DistributedMember serverMember = (DistributedMember) vm0.invoke(
UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember");
getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]);
getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId);
getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember);
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null);
createRegion(name, factory.create());
assertNotNull(getRootRegion().getSubregion(name));
synchronized(systemListener) {
if (!firedSystem[JOINED]) {
systemListener.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
synchronized(adapter) {
if (!firedAdapter[JOINED]) {
adapter.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
synchronized(bridgeListener) {
if (!firedBridge[JOINED]) {
bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join");
assertFalse(firedSystemDuplicate);
assertFalse(firedBridgeDuplicate);
assertTrue(firedBridge[JOINED]);
assertEquals(serverMember, memberBridge[JOINED]);
assertEquals(serverMemberId, memberIdBridge[JOINED]);
assertNotNull(memberBridge[JOINED]);
assertNotNull(memberIdBridge[JOINED]);
assertFalse(isClientBridge[JOINED]);
assertFalse(firedBridge[LEFT]);
assertNull(memberBridge[LEFT]);
assertNull(memberIdBridge[LEFT]);
assertFalse(isClientBridge[LEFT]);
assertFalse(firedBridge[CRASHED]);
assertNull(memberBridge[CRASHED]);
assertNull(memberIdBridge[CRASHED]);
assertFalse(isClientBridge[CRASHED]);
resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge);
assertTrue(firedSystem[JOINED]);
assertEquals(serverMember, memberSystem[JOINED]);
assertEquals(serverMemberId, memberIdSystem[JOINED]);
assertFalse(isClientSystem[JOINED]);
assertFalse(firedSystem[LEFT]);
assertNull(memberSystem[LEFT]);
assertNull(memberIdSystem[LEFT]);
assertFalse(isClientSystem[LEFT]);
assertFalse(firedSystem[CRASHED]);
assertNull(memberSystem[CRASHED]);
assertNull(memberIdSystem[CRASHED]);
assertFalse(isClientSystem[CRASHED]);
resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem);
assertTrue(firedAdapter[JOINED]);
assertNotNull(memberAdapter[JOINED]);
assertNotNull(memberIdAdapter[JOINED]);
assertEquals(serverMember, memberAdapter[JOINED]);
assertEquals(serverMemberId, memberIdAdapter[JOINED]);
assertFalse(isClientAdapter[JOINED]);
assertFalse(firedAdapter[LEFT]);
assertNull(memberAdapter[LEFT]);
assertNull(memberIdAdapter[LEFT]);
assertFalse(isClientAdapter[LEFT]);
assertFalse(firedAdapter[CRASHED]);
assertNull(memberAdapter[CRASHED]);
assertNull(memberIdAdapter[CRASHED]);
assertFalse(isClientAdapter[CRASHED]);
resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter);
getLogWriter().info("[testServerEventsInSystemClient] wait for client to fully connect");
final String pl =
getRootRegion().getSubregion(name).getAttributes().getPoolName();
PoolImpl pi = (PoolImpl)PoolManager.find(pl);
waitForClientToFullyConnect(pi);
LogWriter bgexecLogger =
new LocalLogWriter(LogWriterImpl.ALL_LEVEL, System.out);
bgexecLogger.info("<ExpectedException action=add>" +
"java.io.IOException" + "</ExpectedException>");
final ExpectedException ex = addExpectedException(
ServerConnectivityException.class.getName());
try {
vm0.invoke(new SerializableRunnable("Disconnect bridge server") {
public void run() {
getLogWriter().info("[testServerEventsInSystemClient] disconnect bridge server");
closeCache();
disconnectFromDS();
}
});
synchronized(systemListener) {
if (!firedSystem[LEFT]) {
systemListener.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
synchronized(adapter) {
if (!firedAdapter[LEFT]) {
adapter.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
synchronized(bridgeListener) {
if (!firedBridge[LEFT]) {
bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
}
finally {
bgexecLogger.info("<ExpectedException action=remove>" +
"java.io.IOException" + "</ExpectedException>");
ex.remove();
}
getLogWriter().info("[testServerEventsInSystemClient] assert client detected server crashed");
assertFalse(firedSystemDuplicate);
assertFalse(firedAdapterDuplicate);
assertFalse(firedBridgeDuplicate);
assertFalse(firedBridge[JOINED]);
assertNull(memberIdBridge[JOINED]);
assertNull(memberBridge[JOINED]);
assertFalse(isClientBridge[JOINED]);
assertFalse("Please update testServerEventsInSystemClient to handle memberLeft for BridgeServer.",
firedBridge[LEFT]);
assertNull(memberBridge[LEFT]);
assertNull(memberIdBridge[LEFT]);
assertFalse(isClientBridge[LEFT]);
assertTrue(firedBridge[CRASHED]);
assertNotNull(memberBridge[CRASHED]);
assertNotNull(memberIdBridge[CRASHED]);
assertEquals(serverMemberId, memberIdBridge[CRASHED]);
assertEquals(serverMember, memberBridge[CRASHED]);
assertFalse(isClientBridge[CRASHED]);
resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge);
assertFalse(firedSystem[JOINED]);
assertNull(memberSystem[JOINED]);
assertNull(memberIdSystem[JOINED]);
assertFalse(isClientSystem[JOINED]);
assertTrue(firedSystem[LEFT]);
assertEquals(serverMember, memberSystem[LEFT]);
assertEquals(serverMemberId, memberIdSystem[LEFT]);
assertFalse(isClientSystem[LEFT]);
assertFalse(firedSystem[CRASHED]);
assertNull(memberSystem[CRASHED]);
assertNull(memberIdSystem[CRASHED]);
assertFalse(isClientSystem[CRASHED]);
resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem);
assertFalse("this intermittently fails", firedAdapter[JOINED]);
assertNull(memberIdAdapter[JOINED]);
assertFalse(isClientAdapter[JOINED]);
assertTrue(firedAdapter[LEFT]);
assertEquals(serverMember, memberAdapter[LEFT]);
assertEquals(serverMemberId, memberIdAdapter[LEFT]);
assertFalse(isClientAdapter[LEFT]);
assertFalse(firedAdapter[CRASHED]);
assertNull(memberAdapter[CRASHED]);
assertNull(memberIdAdapter[CRASHED]);
assertFalse(isClientAdapter[CRASHED]);
resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter);
vm0.invoke(createBridgeServer);
assertEquals(ports[0],
vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class,
"getTestServerEventsInSystemClient_port"));
serverMemberId = (String) vm0.invoke(
UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId");
serverMember = (DistributedMember) vm0.invoke(
UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember");
getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]);
getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId);
getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember);
synchronized(systemListener) {
if (!firedSystem[JOINED]) {
systemListener.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
synchronized(adapter) {
if (!firedAdapter[JOINED]) {
adapter.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
synchronized(bridgeListener) {
if (!firedBridge[JOINED]) {
bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS);
}
}
getLogWriter().info("[testServerEventsInSystemClient] assert client detected server re-join");
assertFalse(firedSystemDuplicate);
assertFalse(firedBridgeDuplicate);
assertTrue(firedBridge[JOINED]);
assertNotNull(memberBridge[JOINED]);
assertNotNull(memberIdBridge[JOINED]);
assertEquals(serverMember, memberBridge[JOINED]);
assertEquals(serverMemberId, memberIdBridge[JOINED]);
assertFalse(isClientBridge[JOINED]);
assertFalse(firedBridge[LEFT]);
assertNull(memberBridge[LEFT]);
assertNull(memberIdBridge[LEFT]);
assertFalse(isClientBridge[LEFT]);
assertFalse(firedBridge[CRASHED]);
assertNull(memberBridge[CRASHED]);
assertNull(memberIdBridge[CRASHED]);
assertFalse(isClientBridge[CRASHED]);
resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge);
assertTrue(firedSystem[JOINED]);
assertEquals(serverMember, memberSystem[JOINED]);
assertEquals(serverMemberId, memberIdSystem[JOINED]);
assertFalse(isClientSystem[JOINED]);
assertFalse(firedSystem[LEFT]);
assertNull(memberSystem[LEFT]);
assertNull(memberIdSystem[LEFT]);
assertFalse(isClientSystem[LEFT]);
assertFalse(firedSystem[CRASHED]);
assertNull(memberSystem[CRASHED]);
assertNull(memberIdSystem[CRASHED]);
assertFalse(isClientSystem[CRASHED]);
resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem);
assertTrue(firedAdapter[JOINED]);
assertNotNull(memberAdapter[JOINED]);
assertNotNull(memberIdAdapter[JOINED]);
assertEquals(serverMember, memberAdapter[JOINED]);
assertEquals(serverMemberId, memberIdAdapter[JOINED]);
assertFalse(isClientAdapter[JOINED]);
assertFalse(firedAdapter[LEFT]);
assertNull(memberAdapter[LEFT]);
assertNull(memberIdAdapter[LEFT]);
assertFalse(isClientAdapter[LEFT]);
assertFalse(firedAdapter[CRASHED]);
assertNull(memberAdapter[CRASHED]);
assertNull(memberIdAdapter[CRASHED]);
assertFalse(isClientAdapter[CRASHED]);
resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter);
} | private void dotestservereventsinsystemclient() throws exception { final boolean[] firedsystem = new boolean[3]; final distributedmember[] membersystem = new distributedmember[3]; final string[] memberidsystem = new string[3]; final boolean[] isclientsystem = new boolean[3]; final boolean[] firedadapter = new boolean[3]; final distributedmember[] memberadapter = new distributedmember[3]; final string[] memberidadapter = new string[3]; final boolean[] isclientadapter = new boolean[3]; final boolean[] firedbridge = new boolean[3]; final distributedmember[] memberbridge = new distributedmember[3]; final string[] memberidbridge = new string[3]; final boolean[] isclientbridge = new boolean[3]; final boolean[] firedsystemduplicate = new boolean[3]; final boolean[] firedadapterduplicate = new boolean[3]; final boolean[] firedbridgeduplicate = new boolean[3]; systemmembershiplistener systemlistener = new systemmembershiplistener() { public synchronized void memberjoined(systemmembershipevent event) { firedsystemduplicate[joined] = firedsystem[joined]; firedsystem[joined] = true; membersystem[joined] = event.getdistributedmember(); memberidsystem[joined] = event.getmemberid(); notify(); } public synchronized void memberleft(systemmembershipevent event) { firedsystemduplicate[left] = firedsystem[left]; firedsystem[left] = true; membersystem[left] = event.getdistributedmember(); memberidsystem[left] = event.getmemberid(); notify(); } public synchronized void membercrashed(systemmembershipevent event) { firedsystemduplicate[crashed] = firedsystem[crashed]; firedsystem[crashed] = true; membersystem[crashed] = event.getdistributedmember(); memberidsystem[crashed] = event.getmemberid(); notify(); } }; universalmembershiplisteneradapter adapter = new universalmembershiplisteneradapter() { @override public synchronized void memberjoined(systemmembershipevent event) { getlogwriter().info("[testservereventsinsystemclient] memberjoined >" + event.getmemberid() + "<"); firedadapterduplicate[joined] = firedadapter[joined]; firedadapter[joined] = true; memberadapter[joined] = event.getdistributedmember(); memberidadapter[joined] = event.getmemberid(); if (event instanceof universalmembershiplisteneradapter.adaptedmembershipevent) { isclientadapter[joined] = ((universalmembershiplisteneradapter.adaptedmembershipevent)event).isclient(); } notify(); } @override public synchronized void memberleft(systemmembershipevent event) { getlogwriter().info("[testservereventsinsystemclient] memberleft >" + event.getmemberid() + "<"); firedadapterduplicate[left] = firedadapter[left]; firedadapter[left] = true; memberadapter[left] = event.getdistributedmember(); memberidadapter[left] = event.getmemberid(); if (event instanceof universalmembershiplisteneradapter.adaptedmembershipevent) { isclientadapter[left] = ((universalmembershiplisteneradapter.adaptedmembershipevent)event).isclient(); } notify(); } @override public synchronized void membercrashed(systemmembershipevent event) { getlogwriter().info("[testservereventsinsystemclient] membercrashed >" + event.getmemberid() + "<"); firedadapterduplicate[crashed] = firedadapter[crashed]; firedadapter[crashed] = true; memberadapter[crashed] = event.getdistributedmember(); memberidadapter[crashed] = event.getmemberid(); if (event instanceof universalmembershiplisteneradapter.adaptedmembershipevent) { isclientadapter[crashed] = ((universalmembershiplisteneradapter.adaptedmembershipevent)event).isclient(); } notify(); } }; bridgemembershiplistener bridgelistener = new bridgemembershiplistener() { public synchronized void memberjoined(bridgemembershipevent event) { firedbridgeduplicate[joined] = firedbridge[joined]; firedbridge[joined] = true; memberbridge[joined] = event.getmember(); memberidbridge[joined] = event.getmemberid(); isclientbridge[joined] = event.isclient(); notify(); } public synchronized void memberleft(bridgemembershipevent event) { firedbridgeduplicate[left] = firedbridge[left]; firedbridge[left] = true; memberbridge[left] = event.getmember(); memberidbridge[left] = event.getmemberid(); isclientbridge[left] = event.isclient(); notify(); } public synchronized void membercrashed(bridgemembershipevent event) { firedbridgeduplicate[crashed] = firedbridge[crashed]; firedbridge[crashed] = true; memberbridge[crashed] = event.getmember(); memberidbridge[crashed] = event.getmemberid(); isclientbridge[crashed] = event.isclient(); notify(); } }; final host host = host.gethost(0); final vm vm0 = host.getvm(0); final string name = this.getuniquename(); final int[] ports = new int[] { availableport.getrandomavailableport(availableport.socket) }; asserttrue(ports[0] != 0); getlogwriter().info("[testservereventsinsystemclient] create system bridge client"); getsystem(); final properties clientproperties = getsystemproperties(); bridgemembership.registerbridgemembershiplistener(bridgelistener); distributedsystemconfig config = admindistributedsystemfactory.definedistributedsystem(getsystem(), null); admindistributedsystem adminds = admindistributedsystemfactory.getdistributedsystem(config); adminds.connect(); asserttrue(adminds.waittobeconnected(5 * 1000)); adminds.addmembershiplistener(systemlistener); adapter.registermembershiplistener(adminds); serializablerunnable createbridgeserver = new cacheserializablerunnable("create bridgeserver") { @override public void run2() throws cacheexception { getlogwriter().info("[testservereventsinsystemclient] create bridgeserver"); getsystem(clientproperties); attributesfactory factory = new attributesfactory(); factory.setscope(scope.local); region region = createregion(name, factory.create()); assertnotnull(region); assertnotnull(getrootregion().getsubregion(name)); try { testservereventsinsystemclient_port = startbridgeserver(ports[0]); } catch (ioexception e) { getlogwriter().error(e); fail(e.getmessage()); } } }; vm0.invoke(createbridgeserver); assertequals(ports[0], vm0.invokeint(universalmembershiplisteneradapterdunittest.class, "gettestservereventsinsystemclient_port")); string servermemberid = (string) vm0.invoke( universalmembershiplisteneradapterdunittest.class, "getmemberid"); distributedmember servermember = (distributedmember) vm0.invoke( universalmembershiplisteneradapterdunittest.class, "getdistributedmember"); getlogwriter().info("[testservereventsinsystemclient] ports[0]=" + ports[0]); getlogwriter().info("[testservereventsinsystemclient] servermemberid=" + servermemberid); getlogwriter().info("[testservereventsinsystemclient] servermember=" + servermember); attributesfactory factory = new attributesfactory(); factory.setscope(scope.local); bridgetestcase.configureconnectionpool(factory, getserverhostname(host), ports, false, -1, -1, null); createregion(name, factory.create()); assertnotnull(getrootregion().getsubregion(name)); synchronized(systemlistener) { if (!firedsystem[joined]) { systemlistener.wait(async_event_wait_millis); } } synchronized(adapter) { if (!firedadapter[joined]) { adapter.wait(async_event_wait_millis); } } synchronized(bridgelistener) { if (!firedbridge[joined]) { bridgelistener.wait(async_event_wait_millis); } } getlogwriter().info("[testservereventsinsystemclient] assert client detected server join"); assertfalse(firedsystemduplicate); assertfalse(firedbridgeduplicate); asserttrue(firedbridge[joined]); assertequals(servermember, memberbridge[joined]); assertequals(servermemberid, memberidbridge[joined]); assertnotnull(memberbridge[joined]); assertnotnull(memberidbridge[joined]); assertfalse(isclientbridge[joined]); assertfalse(firedbridge[left]); assertnull(memberbridge[left]); assertnull(memberidbridge[left]); assertfalse(isclientbridge[left]); assertfalse(firedbridge[crashed]); assertnull(memberbridge[crashed]); assertnull(memberidbridge[crashed]); assertfalse(isclientbridge[crashed]); resetarraysfortesting(firedbridge, memberbridge, memberidbridge, isclientbridge); asserttrue(firedsystem[joined]); assertequals(servermember, membersystem[joined]); assertequals(servermemberid, memberidsystem[joined]); assertfalse(isclientsystem[joined]); assertfalse(firedsystem[left]); assertnull(membersystem[left]); assertnull(memberidsystem[left]); assertfalse(isclientsystem[left]); assertfalse(firedsystem[crashed]); assertnull(membersystem[crashed]); assertnull(memberidsystem[crashed]); assertfalse(isclientsystem[crashed]); resetarraysfortesting(firedsystem, membersystem, memberidsystem, isclientsystem); asserttrue(firedadapter[joined]); assertnotnull(memberadapter[joined]); assertnotnull(memberidadapter[joined]); assertequals(servermember, memberadapter[joined]); assertequals(servermemberid, memberidadapter[joined]); assertfalse(isclientadapter[joined]); assertfalse(firedadapter[left]); assertnull(memberadapter[left]); assertnull(memberidadapter[left]); assertfalse(isclientadapter[left]); assertfalse(firedadapter[crashed]); assertnull(memberadapter[crashed]); assertnull(memberidadapter[crashed]); assertfalse(isclientadapter[crashed]); resetarraysfortesting(firedadapter, memberadapter, memberidadapter, isclientadapter); getlogwriter().info("[testservereventsinsystemclient] wait for client to fully connect"); final string pl = getrootregion().getsubregion(name).getattributes().getpoolname(); poolimpl pi = (poolimpl)poolmanager.find(pl); waitforclienttofullyconnect(pi); logwriter bgexeclogger = new locallogwriter(logwriterimpl.all_level, system.out); bgexeclogger.info("<expectedexception action=add>" + "java.io.ioexception" + "</expectedexception>"); final expectedexception ex = addexpectedexception( serverconnectivityexception.class.getname()); try { vm0.invoke(new serializablerunnable("disconnect bridge server") { public void run() { getlogwriter().info("[testservereventsinsystemclient] disconnect bridge server"); closecache(); disconnectfromds(); } }); synchronized(systemlistener) { if (!firedsystem[left]) { systemlistener.wait(async_event_wait_millis); } } synchronized(adapter) { if (!firedadapter[left]) { adapter.wait(async_event_wait_millis); } } synchronized(bridgelistener) { if (!firedbridge[left]) { bridgelistener.wait(async_event_wait_millis); } } } finally { bgexeclogger.info("<expectedexception action=remove>" + "java.io.ioexception" + "</expectedexception>"); ex.remove(); } getlogwriter().info("[testservereventsinsystemclient] assert client detected server crashed"); assertfalse(firedsystemduplicate); assertfalse(firedadapterduplicate); assertfalse(firedbridgeduplicate); assertfalse(firedbridge[joined]); assertnull(memberidbridge[joined]); assertnull(memberbridge[joined]); assertfalse(isclientbridge[joined]); assertfalse("please update testservereventsinsystemclient to handle memberleft for bridgeserver.", firedbridge[left]); assertnull(memberbridge[left]); assertnull(memberidbridge[left]); assertfalse(isclientbridge[left]); asserttrue(firedbridge[crashed]); assertnotnull(memberbridge[crashed]); assertnotnull(memberidbridge[crashed]); assertequals(servermemberid, memberidbridge[crashed]); assertequals(servermember, memberbridge[crashed]); assertfalse(isclientbridge[crashed]); resetarraysfortesting(firedbridge, memberbridge, memberidbridge, isclientbridge); assertfalse(firedsystem[joined]); assertnull(membersystem[joined]); assertnull(memberidsystem[joined]); assertfalse(isclientsystem[joined]); asserttrue(firedsystem[left]); assertequals(servermember, membersystem[left]); assertequals(servermemberid, memberidsystem[left]); assertfalse(isclientsystem[left]); assertfalse(firedsystem[crashed]); assertnull(membersystem[crashed]); assertnull(memberidsystem[crashed]); assertfalse(isclientsystem[crashed]); resetarraysfortesting(firedsystem, membersystem, memberidsystem, isclientsystem); assertfalse("this intermittently fails", firedadapter[joined]); assertnull(memberidadapter[joined]); assertfalse(isclientadapter[joined]); asserttrue(firedadapter[left]); assertequals(servermember, memberadapter[left]); assertequals(servermemberid, memberidadapter[left]); assertfalse(isclientadapter[left]); assertfalse(firedadapter[crashed]); assertnull(memberadapter[crashed]); assertnull(memberidadapter[crashed]); assertfalse(isclientadapter[crashed]); resetarraysfortesting(firedadapter, memberadapter, memberidadapter, isclientadapter); vm0.invoke(createbridgeserver); assertequals(ports[0], vm0.invokeint(universalmembershiplisteneradapterdunittest.class, "gettestservereventsinsystemclient_port")); servermemberid = (string) vm0.invoke( universalmembershiplisteneradapterdunittest.class, "getmemberid"); servermember = (distributedmember) vm0.invoke( universalmembershiplisteneradapterdunittest.class, "getdistributedmember"); getlogwriter().info("[testservereventsinsystemclient] ports[0]=" + ports[0]); getlogwriter().info("[testservereventsinsystemclient] servermemberid=" + servermemberid); getlogwriter().info("[testservereventsinsystemclient] servermember=" + servermember); synchronized(systemlistener) { if (!firedsystem[joined]) { systemlistener.wait(async_event_wait_millis); } } synchronized(adapter) { if (!firedadapter[joined]) { adapter.wait(async_event_wait_millis); } } synchronized(bridgelistener) { if (!firedbridge[joined]) { bridgelistener.wait(async_event_wait_millis); } } getlogwriter().info("[testservereventsinsystemclient] assert client detected server re-join"); assertfalse(firedsystemduplicate); assertfalse(firedbridgeduplicate); asserttrue(firedbridge[joined]); assertnotnull(memberbridge[joined]); assertnotnull(memberidbridge[joined]); assertequals(servermember, memberbridge[joined]); assertequals(servermemberid, memberidbridge[joined]); assertfalse(isclientbridge[joined]); assertfalse(firedbridge[left]); assertnull(memberbridge[left]); assertnull(memberidbridge[left]); assertfalse(isclientbridge[left]); assertfalse(firedbridge[crashed]); assertnull(memberbridge[crashed]); assertnull(memberidbridge[crashed]); assertfalse(isclientbridge[crashed]); resetarraysfortesting(firedbridge, memberbridge, memberidbridge, isclientbridge); asserttrue(firedsystem[joined]); assertequals(servermember, membersystem[joined]); assertequals(servermemberid, memberidsystem[joined]); assertfalse(isclientsystem[joined]); assertfalse(firedsystem[left]); assertnull(membersystem[left]); assertnull(memberidsystem[left]); assertfalse(isclientsystem[left]); assertfalse(firedsystem[crashed]); assertnull(membersystem[crashed]); assertnull(memberidsystem[crashed]); assertfalse(isclientsystem[crashed]); resetarraysfortesting(firedsystem, membersystem, memberidsystem, isclientsystem); asserttrue(firedadapter[joined]); assertnotnull(memberadapter[joined]); assertnotnull(memberidadapter[joined]); assertequals(servermember, memberadapter[joined]); assertequals(servermemberid, memberidadapter[joined]); assertfalse(isclientadapter[joined]); assertfalse(firedadapter[left]); assertnull(memberadapter[left]); assertnull(memberidadapter[left]); assertfalse(isclientadapter[left]); assertfalse(firedadapter[crashed]); assertnull(memberadapter[crashed]); assertnull(memberidadapter[crashed]); assertfalse(isclientadapter[crashed]); resetarraysfortesting(firedadapter, memberadapter, memberidadapter, isclientadapter); } | xyxiaoyou/snappy-store | [
1,
0,
0,
1
] |
23,257 | @Override protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
// TODO: manage mem if needed
mTransactionModel.getTransactionsList().clear();
mTransactionModel = null;
} | @Override protected void onReset() {
super.onReset();
onStopLoading();
mTransactionModel.getTransactionsList().clear();
mTransactionModel = null;
} | @override protected void onreset() { super.onreset(); onstoploading(); mtransactionmodel.gettransactionslist().clear(); mtransactionmodel = null; } | vulko/TransactionsTestTask | [
0,
1,
0,
0
] |
23,465 | public IResource loadResource(IRestfulClient theClient) throws IOException {
if (myResource != null) {
return myResource;
}
IdDt resourceId = getReference();
if (resourceId == null) {
throw new IllegalStateException("Reference has no resource ID defined");
}
String resourceUrl = resourceId.getValue();
ourLog.debug("Loading resource at URL: {}", resourceUrl);
HttpClient httpClient = theClient.getHttpClient();
FhirContext context = theClient.getFhirContext();
if (!resourceUrl.startsWith("http")) {
resourceUrl = theClient.getServerBase() + resourceUrl;
}
HttpGet get = new HttpGet(resourceUrl);
HttpResponse response = httpClient.execute(get);
try {
// TODO: choose appropriate parser based on response CT
IParser parser = context.newXmlParser();
Reader responseReader = BaseClient.createReaderFromResponse(response);
myResource = parser.parseResource(responseReader);
} finally {
if (response instanceof CloseableHttpResponse) {
((CloseableHttpResponse) response).close();
}
}
return myResource;
} | public IResource loadResource(IRestfulClient theClient) throws IOException {
if (myResource != null) {
return myResource;
}
IdDt resourceId = getReference();
if (resourceId == null) {
throw new IllegalStateException("Reference has no resource ID defined");
}
String resourceUrl = resourceId.getValue();
ourLog.debug("Loading resource at URL: {}", resourceUrl);
HttpClient httpClient = theClient.getHttpClient();
FhirContext context = theClient.getFhirContext();
if (!resourceUrl.startsWith("http")) {
resourceUrl = theClient.getServerBase() + resourceUrl;
}
HttpGet get = new HttpGet(resourceUrl);
HttpResponse response = httpClient.execute(get);
try {
IParser parser = context.newXmlParser();
Reader responseReader = BaseClient.createReaderFromResponse(response);
myResource = parser.parseResource(responseReader);
} finally {
if (response instanceof CloseableHttpResponse) {
((CloseableHttpResponse) response).close();
}
}
return myResource;
} | public iresource loadresource(irestfulclient theclient) throws ioexception { if (myresource != null) { return myresource; } iddt resourceid = getreference(); if (resourceid == null) { throw new illegalstateexception("reference has no resource id defined"); } string resourceurl = resourceid.getvalue(); ourlog.debug("loading resource at url: {}", resourceurl); httpclient httpclient = theclient.gethttpclient(); fhircontext context = theclient.getfhircontext(); if (!resourceurl.startswith("http")) { resourceurl = theclient.getserverbase() + resourceurl; } httpget get = new httpget(resourceurl); httpresponse response = httpclient.execute(get); try { iparser parser = context.newxmlparser(); reader responsereader = baseclient.createreaderfromresponse(response); myresource = parser.parseresource(responsereader); } finally { if (response instanceof closeablehttpresponse) { ((closeablehttpresponse) response).close(); } } return myresource; } | wdebeau1/hapi-fhir | [
0,
1,
0,
0
] |
31,699 | public static String weekdayCodeToString(int weekday) {
String[] weekdays = DATE_FORMAT_SYMBOLS.getWeekdays();
return weekdays[weekday];
} | public static String weekdayCodeToString(int weekday) {
String[] weekdays = DATE_FORMAT_SYMBOLS.getWeekdays();
return weekdays[weekday];
} | public static string weekdaycodetostring(int weekday) { string[] weekdays = date_format_symbols.getweekdays(); return weekdays[weekday]; } | tovganesh/metastudio | [
1,
0,
0,
0
] |
31,700 | public static String weekInMonthToString(int count) {
switch (count) {
case SerialDate.FIRST_WEEK_IN_MONTH : return "First";
case SerialDate.SECOND_WEEK_IN_MONTH : return "Second";
case SerialDate.THIRD_WEEK_IN_MONTH : return "Third";
case SerialDate.FOURTH_WEEK_IN_MONTH : return "Fourth";
case SerialDate.LAST_WEEK_IN_MONTH : return "Last";
default :
return "SerialDate.weekInMonthToString(...): invalid code.";
}
} | public static String weekInMonthToString(int count) {
switch (count) {
case SerialDate.FIRST_WEEK_IN_MONTH : return "First";
case SerialDate.SECOND_WEEK_IN_MONTH : return "Second";
case SerialDate.THIRD_WEEK_IN_MONTH : return "Third";
case SerialDate.FOURTH_WEEK_IN_MONTH : return "Fourth";
case SerialDate.LAST_WEEK_IN_MONTH : return "Last";
default :
return "SerialDate.weekInMonthToString(...): invalid code.";
}
} | public static string weekinmonthtostring(int count) { switch (count) { case serialdate.first_week_in_month : return "first"; case serialdate.second_week_in_month : return "second"; case serialdate.third_week_in_month : return "third"; case serialdate.fourth_week_in_month : return "fourth"; case serialdate.last_week_in_month : return "last"; default : return "serialdate.weekinmonthtostring(...): invalid code."; } } | tovganesh/metastudio | [
1,
0,
0,
0
] |
31,761 | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
// unencrypted key pair
decryptor = null;
}
secretKeys = KeyRingSubKeyFixUtil.repairSubkeyPackets(secretKeys, decryptor, encryptor);
final InMemoryKeyring keyring;
if (passphrase.isEmpty()) {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
} else {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(passphrase.getChars()));
}
keyring.addSecretKeyRing(secretKeys);
keyring.addPublicKeyRing(publicKeys);
passphrase.clear();
return keyring;
} | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
encryptor = null;
}
final KeySpec certKeySpec = keySpecs.get(0);
keySpecs.remove(0);
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
decryptor = null;
}
secretKeys = KeyRingSubKeyFixUtil.repairSubkeyPackets(secretKeys, decryptor, encryptor);
final InMemoryKeyring keyring;
if (passphrase.isEmpty()) {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
} else {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(passphrase.getChars()));
}
keyring.addSecretKeyRing(secretKeys);
keyring.addPublicKeyRing(publicKeys);
passphrase.clear();
return keyring;
} | @override public keyringconfig build() throws nosuchalgorithmexception, pgpexception, nosuchproviderexception, invalidalgorithmparameterexception, ioexception { final pgpdigestcalculator calculator = new jcapgpdigestcalculatorproviderbuilder() .setprovider(bouncycastleprovider.provider_name) .build() .get(pgphashalgorithms.sha1.getalgorithmid()); final boolean withpassphrase = !passphrase.isempty(); @nullable final pbesecretkeyencryptor encryptor; if (withpassphrase) { encryptor = new jcepbesecretkeyencryptorbuilder(pgpencrypteddata.aes_256, calculator) .setprovider(bouncycastleprovider.provider_name) .build(passphrase.getchars()); } else { encryptor = null; } final keyspec certkeyspec = keyspecs.get(0); keyspecs.remove(0); final pgpkeypair certkey = generatekeypair(certkeyspec); final pgpcontentsignerbuilder signer = new jcapgpcontentsignerbuilder( certkey.getpublickey().getalgorithm(), pgphashalgorithms.sha_512.getalgorithmid()) .setprovider(bouncycastleprovider.provider_name); final pgpsignaturesubpacketvector hashedsubpackets = certkeyspec.getsubpackets(); final pgpkeyringgenerator ringgenerator = new pgpkeyringgenerator( pgpsignature.positive_certification, certkey, userid, calculator, hashedsubpackets, null, signer, encryptor); for (final keyspec subkeyspec : keyspecs) { final pgpkeypair subkey = generatekeypair(subkeyspec); if (subkeyspec.isinheritedsubpackets()) { ringgenerator.addsubkey(subkey); } else { ringgenerator.addsubkey(subkey, subkeyspec.getsubpackets(), null); } } final pgppublickeyring publickeys = ringgenerator.generatepublickeyring(); pgpsecretkeyring secretkeys = ringgenerator.generatesecretkeyring(); final pbesecretkeydecryptor decryptor; if (withpassphrase) { decryptor = new jcepbesecretkeydecryptorbuilder( new jcapgpdigestcalculatorproviderbuilder() .setprovider(bouncycastleprovider.provider_name) .build()).build(passphrase.getchars()); } else { decryptor = null; } secretkeys = keyringsubkeyfixutil.repairsubkeypackets(secretkeys, decryptor, encryptor); final inmemorykeyring keyring; if (passphrase.isempty()) { keyring = keyringconfigs .forgpgexportedkeys(keyringconfigcallbacks.withunprotectedkeys()); } else { keyring = keyringconfigs .forgpgexportedkeys(keyringconfigcallbacks.withpassword(passphrase.getchars())); } keyring.addsecretkeyring(secretkeys); keyring.addpublickeyring(publickeys); passphrase.clear(); return keyring; } | user9209/bouncy-gpg | [
1,
0,
0,
0
] |
31,979 | public Map<SkbShellArgument, Object> getArgMap(SkbShellArgument[] arguments){
Map<SkbShellArgument, Object> ret = new LinkedHashMap<SkbShellArgument, Object>();
if(arguments!=null){
for(Entry<String, String> entry : this.getArgMap().entrySet()){
for(SkbShellArgument ssa : arguments){
if(ssa.getKey().equals(entry.getKey())){
switch(ssa.getType()){
case Boolean:
ret.put(ssa, Boolean.valueOf(entry.getValue()));
break;
case Double:
ret.put(ssa, Double.valueOf(entry.getValue()));
break;
case Integer:
ret.put(ssa, Integer.valueOf(entry.getValue()));
break;
case String:
ret.put(ssa, entry.getValue());
break;
case ListString:
String[] ar = StringUtils.split(entry.getValue(), ';');
if(ar!=null){
List<String> val = new ArrayList<>();
for(String s : ar){
val.add(s);
}
ret.put(ssa, val);
}
break;
case ListInteger:
String[] arInt = StringUtils.split(entry.getValue(), ';');
if(arInt!=null){
List<Integer> valInt = new ArrayList<>();
for(String s : arInt){
valInt.add(Integer.valueOf(s));
}
ret.put(ssa, valInt);
}
break;
default:
System.err.println("parser.getArgMap --> argument type not yet supported: " + ssa.getType());//TODO do not use syserr prints
break;
}
}
}
}
}
return ret;
} | public Map<SkbShellArgument, Object> getArgMap(SkbShellArgument[] arguments){
Map<SkbShellArgument, Object> ret = new LinkedHashMap<SkbShellArgument, Object>();
if(arguments!=null){
for(Entry<String, String> entry : this.getArgMap().entrySet()){
for(SkbShellArgument ssa : arguments){
if(ssa.getKey().equals(entry.getKey())){
switch(ssa.getType()){
case Boolean:
ret.put(ssa, Boolean.valueOf(entry.getValue()));
break;
case Double:
ret.put(ssa, Double.valueOf(entry.getValue()));
break;
case Integer:
ret.put(ssa, Integer.valueOf(entry.getValue()));
break;
case String:
ret.put(ssa, entry.getValue());
break;
case ListString:
String[] ar = StringUtils.split(entry.getValue(), ';');
if(ar!=null){
List<String> val = new ArrayList<>();
for(String s : ar){
val.add(s);
}
ret.put(ssa, val);
}
break;
case ListInteger:
String[] arInt = StringUtils.split(entry.getValue(), ';');
if(arInt!=null){
List<Integer> valInt = new ArrayList<>();
for(String s : arInt){
valInt.add(Integer.valueOf(s));
}
ret.put(ssa, valInt);
}
break;
default:
System.err.println("parser.getArgMap --> argument type not yet supported: " + ssa.getType())
break;
}
}
}
}
}
return ret;
} | public map<skbshellargument, object> getargmap(skbshellargument[] arguments){ map<skbshellargument, object> ret = new linkedhashmap<skbshellargument, object>(); if(arguments!=null){ for(entry<string, string> entry : this.getargmap().entryset()){ for(skbshellargument ssa : arguments){ if(ssa.getkey().equals(entry.getkey())){ switch(ssa.gettype()){ case boolean: ret.put(ssa, boolean.valueof(entry.getvalue())); break; case double: ret.put(ssa, double.valueof(entry.getvalue())); break; case integer: ret.put(ssa, integer.valueof(entry.getvalue())); break; case string: ret.put(ssa, entry.getvalue()); break; case liststring: string[] ar = stringutils.split(entry.getvalue(), ';'); if(ar!=null){ list<string> val = new arraylist<>(); for(string s : ar){ val.add(s); } ret.put(ssa, val); } break; case listinteger: string[] arint = stringutils.split(entry.getvalue(), ';'); if(arint!=null){ list<integer> valint = new arraylist<>(); for(string s : arint){ valint.add(integer.valueof(s)); } ret.put(ssa, valint); } break; default: system.err.println("parser.getargmap --> argument type not yet supported: " + ssa.gettype()) break; } } } } } return ret; } | vdmeer/skb-java-base | [
1,
0,
0,
0
] |
15,630 | protected void rename(String oldName, String newName) throws IOException {
File of = getFile (oldName);
File nf = getFile (newName);
// #7086 - (nf.exists() && !nf.equals(of)) instead of nf.exists() - fix for Win32
if ((nf.exists() && !nf.equals(of)) || !of.renameTo (nf)) {
FSException.io ("EXC_CannotRename", oldName, getDisplayName (), newName); // NOI18N
}
} | protected void rename(String oldName, String newName) throws IOException {
File of = getFile (oldName);
File nf = getFile (newName);
if ((nf.exists() && !nf.equals(of)) || !of.renameTo (nf)) {
FSException.io ("EXC_CannotRename", oldName, getDisplayName (), newName);
}
} | protected void rename(string oldname, string newname) throws ioexception { file of = getfile (oldname); file nf = getfile (newname); if ((nf.exists() && !nf.equals(of)) || !of.renameto (nf)) { fsexception.io ("exc_cannotrename", oldname, getdisplayname (), newname); } } | tszielin/q-lab-editor | [
0,
0,
0,
0
] |
32,069 | private void init() throws Exception {
loadDB();//deserialize the database
outer:
while (true) {
//show options
System.out.println("Main menu:");
System.out.println("1:Start Parsing\n2:Start Browsing\n3:Start Configuration System\n4:Export Current Database\n5:Import a database\n6:Exit");
switch (Integer.parseInt(br.readLine())) {
case 1://start the parser
BufferedReader br2 = new BufferedReader(new FileReader(FILES[2]));
String s = br2.readLine();
while (s != null) {
ar.add(s);//read the options in the parser configuration file
s = br2.readLine();
}
Codes.fixInput(ar);//same as before
Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser
p.parse();//handing control to the parser
break;
case 2://start the editor
Editor e = new Editor(db, auto_entry);//initializing the editor
e.browse();
break;//the editor is capable of returning to the main menu
case 3://configure everything again?
ConfigCLI.init();//configuration system is self-initialising, just hand over control to it
break outer;//that's all, after configuration, the program needs to be restarted anyway
case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel
new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it!
break;//we can come back to the main menu
case 5://import an existing exported database(using this program on a different computer?)
new ExportImport().importer(db, auto_entry);//now it's the import system
break;//same as case 4
case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?)
System.out.println("Exiting...");
System.exit(0);//Bye-Bye
default://Stop making mistakes in input!
//I'm very considerate, I give everybody infinite chances
}
}
} | private void init() throws Exception {
loadDB()
outer:
while (true) {
System.out.println("Main menu:");
System.out.println("1:Start Parsing\n2:Start Browsing\n3:Start Configuration System\n4:Export Current Database\n5:Import a database\n6:Exit");
switch (Integer.parseInt(br.readLine())) {
case 1
BufferedReader br2 = new BufferedReader(new FileReader(FILES[2]));
String s = br2.readLine();
while (s != null) {
ar.add(s)
s = br2.readLine();
}
Codes.fixInput(ar)
Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status)
p.parse()
break;
case 2
Editor e = new Editor(db, auto_entry)
e.browse();
break
case 3
ConfigCLI.init()
break outer
case 4
new ExportImport().exporter(db, auto_entry)
break
case 5
new ExportImport().importer(db, auto_entry)
break
case 6
System.out.println("Exiting...");
System.exit(0)
default
}
}
} | private void init() throws exception { loaddb() outer: while (true) { system.out.println("main menu:"); system.out.println("1:start parsing\n2:start browsing\n3:start configuration system\n4:export current database\n5:import a database\n6:exit"); switch (integer.parseint(br.readline())) { case 1 bufferedreader br2 = new bufferedreader(new filereader(files[2])); string s = br2.readline(); while (s != null) { ar.add(s) s = br2.readline(); } codes.fixinput(ar) parser p = new parser(db, ar.toarray(new string[ar.size()]), status) p.parse() break; case 2 editor e = new editor(db, auto_entry) e.browse(); break case 3 configcli.init() break outer case 4 new exportimport().exporter(db, auto_entry) break case 5 new exportimport().importer(db, auto_entry) break case 6 system.out.println("exiting..."); system.exit(0) default } } } | tamchow/inventory-management | [
0,
0,
0,
0
] |
15,703 | private StoreSynchronizer.SyncResults synchronizeMailboxGeneric(
final EmailContent.Account account, final EmailContent.Mailbox folder)
throws MessagingException {
Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***");
ContentResolver resolver = mContext.getContentResolver();
// 0. We do not ever sync DRAFTS or OUTBOX (down or up)
if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) {
int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null);
return new StoreSynchronizer.SyncResults(totalMessages, 0);
}
// 1. Get the message list from the local store and create an index of the uids
Cursor localUidCursor = null;
HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>();
try {
localUidCursor = resolver.query(
EmailContent.Message.CONTENT_URI,
LocalMessageInfo.PROJECTION,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
},
null);
while (localUidCursor.moveToNext()) {
LocalMessageInfo info = new LocalMessageInfo(localUidCursor);
localMessageMap.put(info.mServerId, info);
}
} finally {
if (localUidCursor != null) {
localUidCursor.close();
}
}
// 1a. Count the unread messages before changing anything
int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?" +
" AND " + MessageColumns.FLAG_READ + "=0",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
});
// 2. Open the remote folder and create the remote folder if necessary
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName);
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT
|| folder.mType == Mailbox.TYPE_DRAFTS) {
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
return new StoreSynchronizer.SyncResults(0, 0);
}
}
}
// 3, Open the remote folder. This pre-loads certain metadata like message count.
remoteFolder.open(OpenMode.READ_WRITE, null);
// 4. Trash any remote messages that are marked as trashed locally.
// TODO - this comment was here, but no code was here.
// 5. Get the remote message count.
int remoteMessageCount = remoteFolder.getMessageCount();
// 6. Determine the limit # of messages to download
int visibleLimit = folder.mVisibleLimit;
if (visibleLimit <= 0) {
Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext),
mContext);
visibleLimit = info.mVisibleLimitDefault;
}
// 7. Create a list of messages to download
Message[] remoteMessages = new Message[0];
final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
int newMessageCount = 0;
if (remoteMessageCount > 0) {
/*
* Message numbers start at 1.
*/
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null);
for (Message message : remoteMessages) {
remoteUidMap.put(message.getUid(), message);
}
/*
* Get a list of the messages that are in the remote list but not on the
* local store, or messages that are in the local store but failed to download
* on the last sync. These are the new messages that we will download.
* Note, we also skip syncing messages which are flagged as "deleted message" sentinels,
* because they are locally deleted and we don't need or want the old message from
* the server.
*/
for (Message message : remoteMessages) {
LocalMessageInfo localMessage = localMessageMap.get(message.getUid());
if (localMessage == null) {
newMessageCount++;
}
// localMessage == null -> message has never been created (not even headers)
// mFlagLoaded = UNLOADED -> message created, but none of body loaded
// mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded
// mFlagLoaded = COMPLETE -> message body has been completely loaded
// mFlagLoaded = DELETED -> message has been deleted
// Only the first two of these are "unsynced", so let's retrieve them
if (localMessage == null ||
(localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) {
unsyncedMessages.add(message);
}
}
}
// 8. Download basic info about the new/unloaded messages (if any)
/*
* A list of messages that were downloaded and which did not have the Seen flag set.
* This will serve to indicate the true "new" message count that will be reported to
* the user via notification.
*/
final ArrayList<Message> newMessages = new ArrayList<Message>();
/*
* Fetch the flags and envelope only of the new messages. This is intended to get us
* critical data as fast as possible, and then we'll fill in the details.
*/
if (unsyncedMessages.size() > 0) {
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
fp.add(FetchProfile.Item.ENVELOPE);
final HashMap<String, LocalMessageInfo> localMapCopy =
new HashMap<String, LocalMessageInfo>(localMessageMap);
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
try {
// Determine if the new message was already known (e.g. partial)
// And create or reload the full message info
LocalMessageInfo localMessageInfo =
localMapCopy.get(message.getUid());
EmailContent.Message localMessage = null;
if (localMessageInfo == null) {
localMessage = new EmailContent.Message();
} else {
localMessage = EmailContent.Message.restoreMessageWithId(
mContext, localMessageInfo.mId);
}
if (localMessage != null) {
try {
// Copy the fields that are available into the message
LegacyConversions.updateMessageFields(localMessage,
message, account.mId, folder.mId);
// Commit the message to the local store
saveOrUpdate(localMessage);
// Track the "new" ness of the downloaded message
if (!message.isSet(Flag.SEEN)) {
newMessages.add(message);
}
} catch (MessagingException me) {
Log.e(Email.LOG_TAG,
"Error while copying downloaded message." + me);
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG,
"Error while storing downloaded message." + e.toString());
}
}
});
}
// 9. Refresh the flags for any messages in the local store that we didn't just download.
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
remoteFolder.fetch(remoteMessages, fp, null);
boolean remoteSupportsSeen = false;
boolean remoteSupportsFlagged = false;
for (Flag flag : remoteFolder.getPermanentFlags()) {
if (flag == Flag.SEEN) {
remoteSupportsSeen = true;
}
if (flag == Flag.FLAGGED) {
remoteSupportsFlagged = true;
}
}
// Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3)
if (remoteSupportsSeen || remoteSupportsFlagged) {
for (Message remoteMessage : remoteMessages) {
LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid());
if (localMessageInfo == null) {
continue;
}
boolean localSeen = localMessageInfo.mFlagRead;
boolean remoteSeen = remoteMessage.isSet(Flag.SEEN);
boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen));
boolean localFlagged = localMessageInfo.mFlagFavorite;
boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED);
boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged));
if (newSeen || newFlagged) {
Uri uri = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, localMessageInfo.mId);
ContentValues updateValues = new ContentValues();
updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen);
updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged);
resolver.update(uri, updateValues, null, null);
}
}
}
// 10. Compute and store the unread message count.
// -- no longer necessary - Provider uses DB triggers to keep track
// int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
// if (remoteUnreadMessageCount == -1) {
// if (remoteSupportsSeenFlag) {
// /*
// * If remote folder doesn't supported unread message count but supports
// * seen flag, use local folder's unread message count and the size of
// * new messages. This mode is not used for POP3, or IMAP.
// */
//
// remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size();
// } else {
// /*
// * If remote folder doesn't supported unread message count and doesn't
// * support seen flag, use localUnreadCount and newMessageCount which
// * don't rely on remote SEEN flag. This mode is used by POP3.
// */
// remoteUnreadMessageCount = localUnreadCount + newMessageCount;
// }
// } else {
// /*
// * If remote folder supports unread message count, use remoteUnreadMessageCount.
// * This mode is used by IMAP.
// */
// }
// Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId);
// ContentValues updateValues = new ContentValues();
// updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount);
// resolver.update(uri, updateValues, null, null);
// 11. Remove any messages that are in the local store but no longer on the remote store.
HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet());
localUidsToDelete.removeAll(remoteUidMap.keySet());
for (String uidToDelete : localUidsToDelete) {
LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete);
// Delete associated data (attachment files)
// Attachment & Body records are auto-deleted when we delete the Message record
AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId);
// Delete the message itself
Uri uriToDelete = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, infoToDelete.mId);
resolver.delete(uriToDelete, null, null);
// Delete extra rows (e.g. synced or deleted)
Uri syncRowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(syncRowToDelete, null, null);
Uri deletERowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(deletERowToDelete, null, null);
}
// 12. Divide the unsynced messages into small & large (by size)
// TODO doing this work here (synchronously) is problematic because it prevents the UI
// from affecting the order (e.g. download a message because the user requested it.) Much
// of this logic should move out to a different sync loop that attempts to update small
// groups of messages at a time, as a background task. However, we can't just return
// (yet) because POP messages don't have an envelope yet....
ArrayList<Message> largeMessages = new ArrayList<Message>();
ArrayList<Message> smallMessages = new ArrayList<Message>();
for (Message message : unsyncedMessages) {
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) {
largeMessages.add(message);
} else {
smallMessages.add(message);
}
}
// 13. Download small messages
// TODO Problems with this implementation. 1. For IMAP, where we get a real envelope,
// this is going to be inefficient and duplicate work we've already done. 2. It's going
// back to the DB for a local message that we already had (and discarded).
// For small messages, we specify "body", which returns everything (incl. attachments)
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
});
// 14. Download large messages. We ask the server to give us the message structure,
// but not all of the attachments.
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
// POP doesn't support STRUCTURE mode, so we'll just do a partial download
// (hopefully enough to see some/all of the body) and mark the message for
// further download.
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
// TODO a good optimization here would be to make sure that all Stores set
// the proper size after this fetch and compare the before and after size. If
// they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the partially-loaded message and mark it partially loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_PARTIAL);
} else {
// We have a structure to deal with, from which
// we can pull down the parts we want to actually store.
// Build a list of parts we are interested in. Text parts will be downloaded
// right now, attachments will be left for later.
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
// Download the viewables immediately
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
}
// 15. Clean up and report results
remoteFolder.close(false);
// TODO - more
// Original sync code. Using for reference, will delete when done.
if (false) {
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]),
fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
// localFolder.appendMessages(new Message[] {
// message
// });
// Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
// localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
} else {
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally
// localFolder.appendMessages(new Message[] {
// message
// });
// Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
// localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
// Update the listener with what we've found
// synchronized (mListeners) {
// for (MessagingListener l : mListeners) {
// l.synchronizeMailboxNewMessage(
// account,
// folder,
// localFolder.getMessage(message.getUid()));
// }
// }
}
/*
* Report successful sync
*/
StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults(
remoteFolder.getMessageCount(), newMessages.size());
remoteFolder.close(false);
// localFolder.close(false);
return results;
}
return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size());
} | private StoreSynchronizer.SyncResults synchronizeMailboxGeneric(
final EmailContent.Account account, final EmailContent.Mailbox folder)
throws MessagingException {
Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***");
ContentResolver resolver = mContext.getContentResolver();
if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) {
int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null);
return new StoreSynchronizer.SyncResults(totalMessages, 0);
}
Cursor localUidCursor = null;
HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>();
try {
localUidCursor = resolver.query(
EmailContent.Message.CONTENT_URI,
LocalMessageInfo.PROJECTION,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
},
null);
while (localUidCursor.moveToNext()) {
LocalMessageInfo info = new LocalMessageInfo(localUidCursor);
localMessageMap.put(info.mServerId, info);
}
} finally {
if (localUidCursor != null) {
localUidCursor.close();
}
}
int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?" +
" AND " + MessageColumns.FLAG_READ + "=0",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
});
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName);
if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT
|| folder.mType == Mailbox.TYPE_DRAFTS) {
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
return new StoreSynchronizer.SyncResults(0, 0);
}
}
}
remoteFolder.open(OpenMode.READ_WRITE, null);
int remoteMessageCount = remoteFolder.getMessageCount();
int visibleLimit = folder.mVisibleLimit;
if (visibleLimit <= 0) {
Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext),
mContext);
visibleLimit = info.mVisibleLimitDefault;
}
Message[] remoteMessages = new Message[0];
final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
int newMessageCount = 0;
if (remoteMessageCount > 0) {
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null);
for (Message message : remoteMessages) {
remoteUidMap.put(message.getUid(), message);
}
for (Message message : remoteMessages) {
LocalMessageInfo localMessage = localMessageMap.get(message.getUid());
if (localMessage == null) {
newMessageCount++;
}
if (localMessage == null ||
(localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) {
unsyncedMessages.add(message);
}
}
}
final ArrayList<Message> newMessages = new ArrayList<Message>();
if (unsyncedMessages.size() > 0) {
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
fp.add(FetchProfile.Item.ENVELOPE);
final HashMap<String, LocalMessageInfo> localMapCopy =
new HashMap<String, LocalMessageInfo>(localMessageMap);
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
try {
LocalMessageInfo localMessageInfo =
localMapCopy.get(message.getUid());
EmailContent.Message localMessage = null;
if (localMessageInfo == null) {
localMessage = new EmailContent.Message();
} else {
localMessage = EmailContent.Message.restoreMessageWithId(
mContext, localMessageInfo.mId);
}
if (localMessage != null) {
try {
LegacyConversions.updateMessageFields(localMessage,
message, account.mId, folder.mId);
saveOrUpdate(localMessage);
if (!message.isSet(Flag.SEEN)) {
newMessages.add(message);
}
} catch (MessagingException me) {
Log.e(Email.LOG_TAG,
"Error while copying downloaded message." + me);
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG,
"Error while storing downloaded message." + e.toString());
}
}
});
}
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
remoteFolder.fetch(remoteMessages, fp, null);
boolean remoteSupportsSeen = false;
boolean remoteSupportsFlagged = false;
for (Flag flag : remoteFolder.getPermanentFlags()) {
if (flag == Flag.SEEN) {
remoteSupportsSeen = true;
}
if (flag == Flag.FLAGGED) {
remoteSupportsFlagged = true;
}
}
if (remoteSupportsSeen || remoteSupportsFlagged) {
for (Message remoteMessage : remoteMessages) {
LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid());
if (localMessageInfo == null) {
continue;
}
boolean localSeen = localMessageInfo.mFlagRead;
boolean remoteSeen = remoteMessage.isSet(Flag.SEEN);
boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen));
boolean localFlagged = localMessageInfo.mFlagFavorite;
boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED);
boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged));
if (newSeen || newFlagged) {
Uri uri = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, localMessageInfo.mId);
ContentValues updateValues = new ContentValues();
updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen);
updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged);
resolver.update(uri, updateValues, null, null);
}
}
}
HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet());
localUidsToDelete.removeAll(remoteUidMap.keySet());
for (String uidToDelete : localUidsToDelete) {
LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete);
AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId);
Uri uriToDelete = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, infoToDelete.mId);
resolver.delete(uriToDelete, null, null);
Uri syncRowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(syncRowToDelete, null, null);
Uri deletERowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(deletERowToDelete, null, null);
}
ArrayList<Message> largeMessages = new ArrayList<Message>();
ArrayList<Message> smallMessages = new ArrayList<Message>();
for (Message message : unsyncedMessages) {
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) {
largeMessages.add(message);
} else {
smallMessages.add(message);
}
}
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
});
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
remoteFolder.fetch(new Message[] { message }, fp, null);
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_PARTIAL);
} else {
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
for (Part part : viewables) {
fp.clear();
fp.add(part);
remoteFolder.fetch(new Message[] { message }, fp, null);
}
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
}
remoteFolder.close(false);
if (false) {
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]),
fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
remoteFolder.fetch(new Message[] { message }, fp, null);
} else {
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
for (Part part : viewables) {
fp.clear();
fp.add(part);
remoteFolder.fetch(new Message[] { message }, fp, null);
}
}
}
StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults(
remoteFolder.getMessageCount(), newMessages.size());
remoteFolder.close(false);
return results;
}
return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size());
} | private storesynchronizer.syncresults synchronizemailboxgeneric( final emailcontent.account account, final emailcontent.mailbox folder) throws messagingexception { log.d(email.log_tag, "*** synchronizemailboxgeneric ***"); contentresolver resolver = mcontext.getcontentresolver(); if (folder.mtype == mailbox.type_drafts || folder.mtype == mailbox.type_outbox) { int totalmessages = emailcontent.count(mcontext, folder.geturi(), null, null); return new storesynchronizer.syncresults(totalmessages, 0); } cursor localuidcursor = null; hashmap<string, localmessageinfo> localmessagemap = new hashmap<string, localmessageinfo>(); try { localuidcursor = resolver.query( emailcontent.message.content_uri, localmessageinfo.projection, emailcontent.messagecolumns.account_key + "=?" + " and " + messagecolumns.mailbox_key + "=?", new string[] { string.valueof(account.mid), string.valueof(folder.mid) }, null); while (localuidcursor.movetonext()) { localmessageinfo info = new localmessageinfo(localuidcursor); localmessagemap.put(info.mserverid, info); } } finally { if (localuidcursor != null) { localuidcursor.close(); } } int localunreadcount = emailcontent.count(mcontext, emailcontent.message.content_uri, emailcontent.messagecolumns.account_key + "=?" + " and " + messagecolumns.mailbox_key + "=?" + " and " + messagecolumns.flag_read + "=0", new string[] { string.valueof(account.mid), string.valueof(folder.mid) }); store remotestore = store.getinstance(account.getstoreuri(mcontext), mcontext, null); folder remotefolder = remotestore.getfolder(folder.mdisplayname); if (folder.mtype == mailbox.type_trash || folder.mtype == mailbox.type_sent || folder.mtype == mailbox.type_drafts) { if (!remotefolder.exists()) { if (!remotefolder.create(foldertype.holds_messages)) { return new storesynchronizer.syncresults(0, 0); } } } remotefolder.open(openmode.read_write, null); int remotemessagecount = remotefolder.getmessagecount(); int visiblelimit = folder.mvisiblelimit; if (visiblelimit <= 0) { store.storeinfo info = store.storeinfo.getstoreinfo(account.getstoreuri(mcontext), mcontext); visiblelimit = info.mvisiblelimitdefault; } message[] remotemessages = new message[0]; final arraylist<message> unsyncedmessages = new arraylist<message>(); hashmap<string, message> remoteuidmap = new hashmap<string, message>(); int newmessagecount = 0; if (remotemessagecount > 0) { int remotestart = math.max(0, remotemessagecount - visiblelimit) + 1; int remoteend = remotemessagecount; remotemessages = remotefolder.getmessages(remotestart, remoteend, null); for (message message : remotemessages) { remoteuidmap.put(message.getuid(), message); } for (message message : remotemessages) { localmessageinfo localmessage = localmessagemap.get(message.getuid()); if (localmessage == null) { newmessagecount++; } if (localmessage == null || (localmessage.mflagloaded == emailcontent.message.flag_loaded_unloaded)) { unsyncedmessages.add(message); } } } final arraylist<message> newmessages = new arraylist<message>(); if (unsyncedmessages.size() > 0) { fetchprofile fp = new fetchprofile(); fp.add(fetchprofile.item.flags); fp.add(fetchprofile.item.envelope); final hashmap<string, localmessageinfo> localmapcopy = new hashmap<string, localmessageinfo>(localmessagemap); remotefolder.fetch(unsyncedmessages.toarray(new message[0]), fp, new messageretrievallistener() { public void messageretrieved(message message) { try { localmessageinfo localmessageinfo = localmapcopy.get(message.getuid()); emailcontent.message localmessage = null; if (localmessageinfo == null) { localmessage = new emailcontent.message(); } else { localmessage = emailcontent.message.restoremessagewithid( mcontext, localmessageinfo.mid); } if (localmessage != null) { try { legacyconversions.updatemessagefields(localmessage, message, account.mid, folder.mid); saveorupdate(localmessage); if (!message.isset(flag.seen)) { newmessages.add(message); } } catch (messagingexception me) { log.e(email.log_tag, "error while copying downloaded message." + me); } } } catch (exception e) { log.e(email.log_tag, "error while storing downloaded message." + e.tostring()); } } }); } fetchprofile fp = new fetchprofile(); fp.add(fetchprofile.item.flags); remotefolder.fetch(remotemessages, fp, null); boolean remotesupportsseen = false; boolean remotesupportsflagged = false; for (flag flag : remotefolder.getpermanentflags()) { if (flag == flag.seen) { remotesupportsseen = true; } if (flag == flag.flagged) { remotesupportsflagged = true; } } if (remotesupportsseen || remotesupportsflagged) { for (message remotemessage : remotemessages) { localmessageinfo localmessageinfo = localmessagemap.get(remotemessage.getuid()); if (localmessageinfo == null) { continue; } boolean localseen = localmessageinfo.mflagread; boolean remoteseen = remotemessage.isset(flag.seen); boolean newseen = (remotesupportsseen && (remoteseen != localseen)); boolean localflagged = localmessageinfo.mflagfavorite; boolean remoteflagged = remotemessage.isset(flag.flagged); boolean newflagged = (remotesupportsflagged && (localflagged != remoteflagged)); if (newseen || newflagged) { uri uri = contenturis.withappendedid( emailcontent.message.content_uri, localmessageinfo.mid); contentvalues updatevalues = new contentvalues(); updatevalues.put(emailcontent.message.flag_read, remoteseen); updatevalues.put(emailcontent.message.flag_favorite, remoteflagged); resolver.update(uri, updatevalues, null, null); } } } hashset<string> localuidstodelete = new hashset<string>(localmessagemap.keyset()); localuidstodelete.removeall(remoteuidmap.keyset()); for (string uidtodelete : localuidstodelete) { localmessageinfo infotodelete = localmessagemap.get(uidtodelete); attachmentprovider.deleteallattachmentfiles(mcontext, account.mid, infotodelete.mid); uri uritodelete = contenturis.withappendedid( emailcontent.message.content_uri, infotodelete.mid); resolver.delete(uritodelete, null, null); uri syncrowtodelete = contenturis.withappendedid( emailcontent.message.updated_content_uri, infotodelete.mid); resolver.delete(syncrowtodelete, null, null); uri deleterowtodelete = contenturis.withappendedid( emailcontent.message.updated_content_uri, infotodelete.mid); resolver.delete(deleterowtodelete, null, null); } arraylist<message> largemessages = new arraylist<message>(); arraylist<message> smallmessages = new arraylist<message>(); for (message message : unsyncedmessages) { if (message.getsize() > (max_small_message_size)) { largemessages.add(message); } else { smallmessages.add(message); } } fp = new fetchprofile(); fp.add(fetchprofile.item.body); remotefolder.fetch(smallmessages.toarray(new message[smallmessages.size()]), fp, new messageretrievallistener() { public void messageretrieved(message message) { copyonemessagetoprovider(message, account, folder, emailcontent.message.flag_loaded_complete); } }); fp.clear(); fp.add(fetchprofile.item.structure); remotefolder.fetch(largemessages.toarray(new message[largemessages.size()]), fp, null); for (message message : largemessages) { if (message.getbody() == null) { fp.clear(); fp.add(fetchprofile.item.body_sane); remotefolder.fetch(new message[] { message }, fp, null); copyonemessagetoprovider(message, account, folder, emailcontent.message.flag_loaded_partial); } else { arraylist<part> viewables = new arraylist<part>(); arraylist<part> attachments = new arraylist<part>(); mimeutility.collectparts(message, viewables, attachments); for (part part : viewables) { fp.clear(); fp.add(part); remotefolder.fetch(new message[] { message }, fp, null); } copyonemessagetoprovider(message, account, folder, emailcontent.message.flag_loaded_complete); } } remotefolder.close(false); if (false) { fp.clear(); fp.add(fetchprofile.item.structure); remotefolder.fetch(largemessages.toarray(new message[largemessages.size()]), fp, null); for (message message : largemessages) { if (message.getbody() == null) { fp.clear(); fp.add(fetchprofile.item.body_sane); remotefolder.fetch(new message[] { message }, fp, null); } else { arraylist<part> viewables = new arraylist<part>(); arraylist<part> attachments = new arraylist<part>(); mimeutility.collectparts(message, viewables, attachments); for (part part : viewables) { fp.clear(); fp.add(part); remotefolder.fetch(new message[] { message }, fp, null); } } } storesynchronizer.syncresults results = new storesynchronizer.syncresults( remotefolder.getmessagecount(), newmessages.size()); remotefolder.close(false); return results; } return new storesynchronizer.syncresults(remotemessagecount, newmessages.size()); } | xie-wenjie/AndroidBaseApplicationSourse | [
1,
1,
1,
0
] |
15,705 | private void processPendingMoveToTrash(Store remoteStore,
EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage,
final EmailContent.Message newMessage) throws MessagingException {
// 0. No remote move if the message is local-only
if (newMessage.mServerId == null || newMessage.mServerId.equals("")
|| newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) {
return;
}
// 1. Escape early if we can't find the local mailbox
// TODO smaller projection here
Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey);
if (oldMailbox == null) {
// can't find old mailbox, it may have been deleted. just return.
return;
}
// 2. We don't support delete-from-trash here
if (oldMailbox.mType == Mailbox.TYPE_TRASH) {
return;
}
// 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return
//
// This sentinel takes the place of the server-side message, and locally "deletes" it
// by inhibiting future sync or display of the message. It will eventually go out of
// scope when it becomes old, or is deleted on the server, and the regular sync code
// will clean it up for us.
if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) {
EmailContent.Message sentinel = new EmailContent.Message();
sentinel.mAccountKey = oldMessage.mAccountKey;
sentinel.mMailboxKey = oldMessage.mMailboxKey;
sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED;
sentinel.mFlagRead = true;
sentinel.mServerId = oldMessage.mServerId;
sentinel.save(mContext);
return;
}
// The rest of this method handles server-side deletion
// 4. Find the remote mailbox (that we deleted from), and open it
Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName);
if (!remoteFolder.exists()) {
return;
}
remoteFolder.open(OpenMode.READ_WRITE, null);
if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
remoteFolder.close(false);
return;
}
// 5. Find the remote original message
Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId);
if (remoteMessage == null) {
remoteFolder.close(false);
return;
}
// 6. Find the remote trash folder, and create it if not found
Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName);
if (!remoteTrashFolder.exists()) {
/*
* If the remote trash folder doesn't exist we try to create it.
*/
remoteTrashFolder.create(FolderType.HOLDS_MESSAGES);
}
// 7. Try to copy the message into the remote trash folder
// Note, this entire section will be skipped for POP3 because there's no remote trash
if (remoteTrashFolder.exists()) {
/*
* Because remoteTrashFolder may be new, we need to explicitly open it
*/
remoteTrashFolder.open(OpenMode.READ_WRITE, null);
if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) {
remoteFolder.close(false);
remoteTrashFolder.close(false);
return;
}
remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder,
new Folder.MessageUpdateCallbacks() {
public void onMessageUidChange(Message message, String newUid) {
// update the UID in the local trash folder, because some stores will
// have to change it when copying to remoteTrashFolder
ContentValues cv = new ContentValues();
cv.put(EmailContent.Message.SERVER_ID, newUid);
mContext.getContentResolver().update(newMessage.getUri(), cv, null, null);
}
/**
* This will be called if the deleted message doesn't exist and can't be
* deleted (e.g. it was already deleted from the server.) In this case,
* attempt to delete the local copy as well.
*/
public void onMessageNotFound(Message message) {
mContext.getContentResolver().delete(newMessage.getUri(), null, null);
}
}
);
remoteTrashFolder.close(false);
}
// 8. Delete the message from the remote source folder
remoteMessage.setFlag(Flag.DELETED, true);
remoteFolder.expunge();
remoteFolder.close(false);
} | private void processPendingMoveToTrash(Store remoteStore,
EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage,
final EmailContent.Message newMessage) throws MessagingException {
if (newMessage.mServerId == null || newMessage.mServerId.equals("")
|| newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) {
return;
}
Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey);
if (oldMailbox == null) {
return;
}
if (oldMailbox.mType == Mailbox.TYPE_TRASH) {
return;
}
if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) {
EmailContent.Message sentinel = new EmailContent.Message();
sentinel.mAccountKey = oldMessage.mAccountKey;
sentinel.mMailboxKey = oldMessage.mMailboxKey;
sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED;
sentinel.mFlagRead = true;
sentinel.mServerId = oldMessage.mServerId;
sentinel.save(mContext);
return;
}
Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName);
if (!remoteFolder.exists()) {
return;
}
remoteFolder.open(OpenMode.READ_WRITE, null);
if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
remoteFolder.close(false);
return;
}
Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId);
if (remoteMessage == null) {
remoteFolder.close(false);
return;
}
Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName);
if (!remoteTrashFolder.exists()) {
remoteTrashFolder.create(FolderType.HOLDS_MESSAGES);
}
if (remoteTrashFolder.exists()) {
remoteTrashFolder.open(OpenMode.READ_WRITE, null);
if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) {
remoteFolder.close(false);
remoteTrashFolder.close(false);
return;
}
remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder,
new Folder.MessageUpdateCallbacks() {
public void onMessageUidChange(Message message, String newUid) {
ContentValues cv = new ContentValues();
cv.put(EmailContent.Message.SERVER_ID, newUid);
mContext.getContentResolver().update(newMessage.getUri(), cv, null, null);
}
public void onMessageNotFound(Message message) {
mContext.getContentResolver().delete(newMessage.getUri(), null, null);
}
}
);
remoteTrashFolder.close(false);
}
remoteMessage.setFlag(Flag.DELETED, true);
remoteFolder.expunge();
remoteFolder.close(false);
} | private void processpendingmovetotrash(store remotestore, emailcontent.account account, mailbox newmailbox, emailcontent.message oldmessage, final emailcontent.message newmessage) throws messagingexception { if (newmessage.mserverid == null || newmessage.mserverid.equals("") || newmessage.mserverid.startswith(local_serverid_prefix)) { return; } mailbox oldmailbox = mailbox.restoremailboxwithid(mcontext, oldmessage.mmailboxkey); if (oldmailbox == null) { return; } if (oldmailbox.mtype == mailbox.type_trash) { return; } if (account.getdeletepolicy() == account.delete_policy_never) { emailcontent.message sentinel = new emailcontent.message(); sentinel.maccountkey = oldmessage.maccountkey; sentinel.mmailboxkey = oldmessage.mmailboxkey; sentinel.mflagloaded = emailcontent.message.flag_loaded_deleted; sentinel.mflagread = true; sentinel.mserverid = oldmessage.mserverid; sentinel.save(mcontext); return; } folder remotefolder = remotestore.getfolder(oldmailbox.mdisplayname); if (!remotefolder.exists()) { return; } remotefolder.open(openmode.read_write, null); if (remotefolder.getmode() != openmode.read_write) { remotefolder.close(false); return; } message remotemessage = remotefolder.getmessage(oldmessage.mserverid); if (remotemessage == null) { remotefolder.close(false); return; } folder remotetrashfolder = remotestore.getfolder(newmailbox.mdisplayname); if (!remotetrashfolder.exists()) { remotetrashfolder.create(foldertype.holds_messages); } if (remotetrashfolder.exists()) { remotetrashfolder.open(openmode.read_write, null); if (remotetrashfolder.getmode() != openmode.read_write) { remotefolder.close(false); remotetrashfolder.close(false); return; } remotefolder.copymessages(new message[] { remotemessage }, remotetrashfolder, new folder.messageupdatecallbacks() { public void onmessageuidchange(message message, string newuid) { contentvalues cv = new contentvalues(); cv.put(emailcontent.message.server_id, newuid); mcontext.getcontentresolver().update(newmessage.geturi(), cv, null, null); } public void onmessagenotfound(message message) { mcontext.getcontentresolver().delete(newmessage.geturi(), null, null); } } ); remotetrashfolder.close(false); } remotemessage.setflag(flag.deleted, true); remotefolder.expunge(); remotefolder.close(false); } | xie-wenjie/AndroidBaseApplicationSourse | [
0,
1,
0,
0
] |
32,108 | private static boolean step(int faceIndex) {
Triangle t = faces.get(faceIndex);
// 2. Get most distant point of the face's point set
Vector3f furthestPoint = null;
int furthestPointID = -1;
Vector3f A = vertices.get(t.a);
List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex);
float distance = 0;
for (int i = 0; i < facepoints.size(); i++) {
Vector3f P = facepoints.get(i);
float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal);
if (dist >= distance) {
distance = dist;
furthestPoint = P;
furthestPointID = i;
}
}
if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check
return true;
}
facepoints.remove(furthestPointID);
vertices.add(furthestPoint);
furthestPointID = vertices.size() - 1;
lastremovedTriangles.clear();
lastremovedTriangles.add(faces.remove(faceIndex));
listsOfFacePoints.remove(faceIndex);
// 3. Find all faces that can be seen from this point
HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why.
lightFaceVertices.add(t.a);
lightFaceVertices.add(t.b);
lightFaceVertices.add(t.c);
List<Triangle> vertsA = new ArrayList<Triangle>();
List<Triangle> vertsB = new ArrayList<Triangle>();
List<Triangle> vertsC = new ArrayList<Triangle>();
vertsA.add(t);
vertsB.add(t);
vertsC.add(t);
lightFaceVerticesToTriangles.clear();
lightFaceVerticesToTriangles.put(t.a, vertsA);
lightFaceVerticesToTriangles.put(t.b, vertsB);
lightFaceVerticesToTriangles.put(t.c, vertsC);
for (int i = faces.size() - 1; i >= 0; i--) {
Triangle tri = faces.get(i);
Vector3f triA = vertices.get(tri.a);
if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) {
lastremovedTriangles.add(faces.remove(i));
lightFaceVertices.add(tri.a);
lightFaceVertices.add(tri.b);
lightFaceVertices.add(tri.c);
if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) {
vertsA.add(tri);
} else {
vertsA = new ArrayList<Triangle>();
vertsA.add(tri);
lightFaceVerticesToTriangles.put(tri.a, vertsA);
}
if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) {
vertsB.add(tri);
} else {
vertsB = new ArrayList<Triangle>();
vertsB.add(tri);
lightFaceVerticesToTriangles.put(tri.b, vertsB);
}
if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) {
vertsC.add(tri);
} else {
vertsC = new ArrayList<Triangle>();
vertsC.add(tri);
lightFaceVerticesToTriangles.put(tri.c, vertsC);
}
facepoints.addAll(listsOfFacePoints.remove(i));
}
}
// 4.0 Remove all vertices that are only connected to lightFaceVertices
Iterator<Integer> iter = lightFaceVertices.iterator();
toRemove.clear();
for (int i = 0; i < lightFaceVertices.size(); i++) {
int vert = iter.next(); // TODO: check
if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) {
toRemove.add(vert);
}
}
for (Integer i : toRemove) {
for (Integer adj : adjacentsMap.get(i)) {
adjacentsMap.get(adj).remove(i);
tmppair.set(i, adj);
edgesToTriangles.remove(tmppair);
}
lightFaceVertices.remove((int) i);
vertices.set((int) i, null);
freeVertexPositions.add(i);
}
// 4.1 Get vertices on border between lit and unlit triangles
HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED
for (Integer vert : lightFaceVertices) {
vertsOnEdge.add(vert);
}
// 4.2 Get edges on border
int currentVert = vertsOnEdge.iterator().next();
edge.clear(); // TODO: make HashSet (no! has to be ordered list!)
for (int i = 0; i < vertsOnEdge.size(); i++) {
edge.add(currentVert);
ArrayList<Integer> adjs = adjacentsMap.get(currentVert);
List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert);
for (int j = 0; j < adjs.size(); j++) {
Integer currAdj = adjs.get(j);
if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) {
int tricount = 0;
for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) {
Triangle kTri = vertexLightTriangles.get(k);
if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) {
tricount++;
}
}
if (tricount == 1) {
currentVert = currAdj;
break;
}
}
}
}
// 4.2.1 remove old adjacents (crossing triangle hole)
int edgesize = edge.size();
int edgesizeMinusOne = edgesize - 1;
for (int i = 0; i < edgesize; i++) {
currentVert = edge.get(i);
removeAdj.clear();
for (Integer adj : adjacentsMap.get(currentVert)) {
if (edge.contains(adj)) {
int adjIndexOnEdge = edge.indexOf(adj);
if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne)
&& !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) {
tmppair.set(currentVert, adj);
Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair);
// TODO: performance
if (lastremovedTriangles.contains(edgeTriangles.getFirst())
&& lastremovedTriangles.contains(edgeTriangles.getSecond())) {
removeAdj.add(adj);
edgesToTriangles.remove(edgeTriangles);
}
}
}
}
for (Integer removAdjacent : removeAdj) { // TODO: make faster
adjacentsMap.get(currentVert).remove(removAdjacent);
}
}
// 4.3 Stitch holes using edge
newLightFaces.clear();
ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size());
A = vertices.get(edge.get(0));
Vector3f B = vertices.get(edge.get(1));
Vector3f C = vertices.get(edge.get(2));
for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) {
C = vertices.get(edge.get(i));
}
Vector3f normal = VecMath.computeNormal(A, B, C);
boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0;
int vertIDb = edge.get(0);
for (int i = 0; i < edge.size(); i++) {
int vertIDa = vertIDb;
if (i < edge.size() - 1) {
vertIDb = edge.get(i + 1);
} else {
vertIDb = edge.get(0);
}
Vector3f vA = vertices.get(vertIDa);
Vector3f vB = vertices.get(vertIDb);
Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint);
Triangle stitchTriangle;
if (correctOrientation) {
stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm);
} else {
norm.negate();
stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm);
}
faces.add(0, stitchTriangle);
newLightFaces.add(stitchTriangle);
// Update adjacents map
adjacentsMap.get(vertIDa).add(furthestPointID);
tmppair.set(vertIDa, vertIDb);
Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair);
// find out which triangle got deleted
if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) {
oldEdgeInfo.setFirst(stitchTriangle);
} else {
oldEdgeInfo.setSecond(stitchTriangle);
}
tmppair.set(vertIDa, furthestPointID);
oldEdgeInfo = edgesToTriangles.get(tmppair);
if (oldEdgeInfo != null) {
oldEdgeInfo.setSecond(stitchTriangle);
} else {
// TODO: just relevant for first iteration, move before loop
edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID),
new Pair<Triangle, Triangle>(null, stitchTriangle));
}
tmppair.set(vertIDb, furthestPointID);
oldEdgeInfo = edgesToTriangles.get(tmppair);
if (oldEdgeInfo != null) {
// TODO: just relevant for last iteration
oldEdgeInfo.setFirst(stitchTriangle);
} else {
edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID),
new Pair<Triangle, Triangle>(stitchTriangle, null));
}
furthestPointNeighbours.add(vertIDa);
}
// 5. Assign all points of all light-faces to the new created faces
adjacentsMap.put(furthestPointID, furthestPointNeighbours);
for (Triangle tri : newLightFaces) {
listsOfFacePoints.add(0, getLightPoints(tri, facepoints));
}
// 6. Push new created faces on the stack and start at (1))
return false;
} | private static boolean step(int faceIndex) {
Triangle t = faces.get(faceIndex);
Vector3f furthestPoint = null;
int furthestPointID = -1;
Vector3f A = vertices.get(t.a);
List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex);
float distance = 0;
for (int i = 0; i < facepoints.size(); i++) {
Vector3f P = facepoints.get(i);
float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal);
if (dist >= distance) {
distance = dist;
furthestPoint = P;
furthestPointID = i;
}
}
if (furthestPointID == -1 || vertices.contains(furthestPoint)) {
return true;
}
facepoints.remove(furthestPointID);
vertices.add(furthestPoint);
furthestPointID = vertices.size() - 1;
lastremovedTriangles.clear();
lastremovedTriangles.add(faces.remove(faceIndex));
listsOfFacePoints.remove(faceIndex);
HashSet<Integer> lightFaceVertices = new HashSet<Integer>();
lightFaceVertices.add(t.a);
lightFaceVertices.add(t.b);
lightFaceVertices.add(t.c);
List<Triangle> vertsA = new ArrayList<Triangle>();
List<Triangle> vertsB = new ArrayList<Triangle>();
List<Triangle> vertsC = new ArrayList<Triangle>();
vertsA.add(t);
vertsB.add(t);
vertsC.add(t);
lightFaceVerticesToTriangles.clear();
lightFaceVerticesToTriangles.put(t.a, vertsA);
lightFaceVerticesToTriangles.put(t.b, vertsB);
lightFaceVerticesToTriangles.put(t.c, vertsC);
for (int i = faces.size() - 1; i >= 0; i--) {
Triangle tri = faces.get(i);
Vector3f triA = vertices.get(tri.a);
if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) {
lastremovedTriangles.add(faces.remove(i));
lightFaceVertices.add(tri.a);
lightFaceVertices.add(tri.b);
lightFaceVertices.add(tri.c);
if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) {
vertsA.add(tri);
} else {
vertsA = new ArrayList<Triangle>();
vertsA.add(tri);
lightFaceVerticesToTriangles.put(tri.a, vertsA);
}
if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) {
vertsB.add(tri);
} else {
vertsB = new ArrayList<Triangle>();
vertsB.add(tri);
lightFaceVerticesToTriangles.put(tri.b, vertsB);
}
if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) {
vertsC.add(tri);
} else {
vertsC = new ArrayList<Triangle>();
vertsC.add(tri);
lightFaceVerticesToTriangles.put(tri.c, vertsC);
}
facepoints.addAll(listsOfFacePoints.remove(i));
}
}
Iterator<Integer> iter = lightFaceVertices.iterator();
toRemove.clear();
for (int i = 0; i < lightFaceVertices.size(); i++) {
int vert = iter.next();
if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) {
toRemove.add(vert);
}
}
for (Integer i : toRemove) {
for (Integer adj : adjacentsMap.get(i)) {
adjacentsMap.get(adj).remove(i);
tmppair.set(i, adj);
edgesToTriangles.remove(tmppair);
}
lightFaceVertices.remove((int) i);
vertices.set((int) i, null);
freeVertexPositions.add(i);
}
HashSet<Integer> vertsOnEdge = new HashSet<Integer>();
for (Integer vert : lightFaceVertices) {
vertsOnEdge.add(vert);
}
int currentVert = vertsOnEdge.iterator().next();
edge.clear();
for (int i = 0; i < vertsOnEdge.size(); i++) {
edge.add(currentVert);
ArrayList<Integer> adjs = adjacentsMap.get(currentVert);
List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert);
for (int j = 0; j < adjs.size(); j++) {
Integer currAdj = adjs.get(j);
if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) {
int tricount = 0;
for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) {
Triangle kTri = vertexLightTriangles.get(k);
if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) {
tricount++;
}
}
if (tricount == 1) {
currentVert = currAdj;
break;
}
}
}
}
int edgesize = edge.size();
int edgesizeMinusOne = edgesize - 1;
for (int i = 0; i < edgesize; i++) {
currentVert = edge.get(i);
removeAdj.clear();
for (Integer adj : adjacentsMap.get(currentVert)) {
if (edge.contains(adj)) {
int adjIndexOnEdge = edge.indexOf(adj);
if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne)
&& !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) {
tmppair.set(currentVert, adj);
Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair);
if (lastremovedTriangles.contains(edgeTriangles.getFirst())
&& lastremovedTriangles.contains(edgeTriangles.getSecond())) {
removeAdj.add(adj);
edgesToTriangles.remove(edgeTriangles);
}
}
}
}
for (Integer removAdjacent : removeAdj) {
adjacentsMap.get(currentVert).remove(removAdjacent);
}
}
newLightFaces.clear();
ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size());
A = vertices.get(edge.get(0));
Vector3f B = vertices.get(edge.get(1));
Vector3f C = vertices.get(edge.get(2));
for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) {
C = vertices.get(edge.get(i));
}
Vector3f normal = VecMath.computeNormal(A, B, C);
boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0;
int vertIDb = edge.get(0);
for (int i = 0; i < edge.size(); i++) {
int vertIDa = vertIDb;
if (i < edge.size() - 1) {
vertIDb = edge.get(i + 1);
} else {
vertIDb = edge.get(0);
}
Vector3f vA = vertices.get(vertIDa);
Vector3f vB = vertices.get(vertIDb);
Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint);
Triangle stitchTriangle;
if (correctOrientation) {
stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm);
} else {
norm.negate();
stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm);
}
faces.add(0, stitchTriangle);
newLightFaces.add(stitchTriangle);
adjacentsMap.get(vertIDa).add(furthestPointID);
tmppair.set(vertIDa, vertIDb);
Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair);
if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) {
oldEdgeInfo.setFirst(stitchTriangle);
} else {
oldEdgeInfo.setSecond(stitchTriangle);
}
tmppair.set(vertIDa, furthestPointID);
oldEdgeInfo = edgesToTriangles.get(tmppair);
if (oldEdgeInfo != null) {
oldEdgeInfo.setSecond(stitchTriangle);
} else {
edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID),
new Pair<Triangle, Triangle>(null, stitchTriangle));
}
tmppair.set(vertIDb, furthestPointID);
oldEdgeInfo = edgesToTriangles.get(tmppair);
if (oldEdgeInfo != null) {
oldEdgeInfo.setFirst(stitchTriangle);
} else {
edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID),
new Pair<Triangle, Triangle>(stitchTriangle, null));
}
furthestPointNeighbours.add(vertIDa);
}
adjacentsMap.put(furthestPointID, furthestPointNeighbours);
for (Triangle tri : newLightFaces) {
listsOfFacePoints.add(0, getLightPoints(tri, facepoints));
}
return false;
} | private static boolean step(int faceindex) { triangle t = faces.get(faceindex); vector3f furthestpoint = null; int furthestpointid = -1; vector3f a = vertices.get(t.a); list<vector3f> facepoints = listsoffacepoints.get(faceindex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { vector3f p = facepoints.get(i); float dist = vecmath.dotproduct(vecmath.subtraction(p, a, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestpoint = p; furthestpointid = i; } } if (furthestpointid == -1 || vertices.contains(furthestpoint)) { return true; } facepoints.remove(furthestpointid); vertices.add(furthestpoint); furthestpointid = vertices.size() - 1; lastremovedtriangles.clear(); lastremovedtriangles.add(faces.remove(faceindex)); listsoffacepoints.remove(faceindex); hashset<integer> lightfacevertices = new hashset<integer>(); lightfacevertices.add(t.a); lightfacevertices.add(t.b); lightfacevertices.add(t.c); list<triangle> vertsa = new arraylist<triangle>(); list<triangle> vertsb = new arraylist<triangle>(); list<triangle> vertsc = new arraylist<triangle>(); vertsa.add(t); vertsb.add(t); vertsc.add(t); lightfaceverticestotriangles.clear(); lightfaceverticestotriangles.put(t.a, vertsa); lightfaceverticestotriangles.put(t.b, vertsb); lightfaceverticestotriangles.put(t.c, vertsc); for (int i = faces.size() - 1; i >= 0; i--) { triangle tri = faces.get(i); vector3f tria = vertices.get(tri.a); if (vecmath.dotproduct(tri.normal, vecmath.subtraction(furthestpoint, tria, tmpvec)) > 0) { lastremovedtriangles.add(faces.remove(i)); lightfacevertices.add(tri.a); lightfacevertices.add(tri.b); lightfacevertices.add(tri.c); if ((vertsa = lightfaceverticestotriangles.get(tri.a)) != null) { vertsa.add(tri); } else { vertsa = new arraylist<triangle>(); vertsa.add(tri); lightfaceverticestotriangles.put(tri.a, vertsa); } if ((vertsb = lightfaceverticestotriangles.get(tri.b)) != null) { vertsb.add(tri); } else { vertsb = new arraylist<triangle>(); vertsb.add(tri); lightfaceverticestotriangles.put(tri.b, vertsb); } if ((vertsc = lightfaceverticestotriangles.get(tri.c)) != null) { vertsc.add(tri); } else { vertsc = new arraylist<triangle>(); vertsc.add(tri); lightfaceverticestotriangles.put(tri.c, vertsc); } facepoints.addall(listsoffacepoints.remove(i)); } } iterator<integer> iter = lightfacevertices.iterator(); toremove.clear(); for (int i = 0; i < lightfacevertices.size(); i++) { int vert = iter.next(); if (lightfaceverticestotriangles.get(vert).size() == adjacentsmap.get(vert).size()) { toremove.add(vert); } } for (integer i : toremove) { for (integer adj : adjacentsmap.get(i)) { adjacentsmap.get(adj).remove(i); tmppair.set(i, adj); edgestotriangles.remove(tmppair); } lightfacevertices.remove((int) i); vertices.set((int) i, null); freevertexpositions.add(i); } hashset<integer> vertsonedge = new hashset<integer>(); for (integer vert : lightfacevertices) { vertsonedge.add(vert); } int currentvert = vertsonedge.iterator().next(); edge.clear(); for (int i = 0; i < vertsonedge.size(); i++) { edge.add(currentvert); arraylist<integer> adjs = adjacentsmap.get(currentvert); list<triangle> vertexlighttriangles = lightfaceverticestotriangles.get(currentvert); for (int j = 0; j < adjs.size(); j++) { integer curradj = adjs.get(j); if (vertsonedge.contains(curradj) && !edge.contains(curradj)) { int tricount = 0; for (int k = 0; k < vertexlighttriangles.size() && tricount < 2; k++) { triangle ktri = vertexlighttriangles.get(k); if (ktri.a == curradj || ktri.b == curradj || ktri.c == curradj) { tricount++; } } if (tricount == 1) { currentvert = curradj; break; } } } } int edgesize = edge.size(); int edgesizeminusone = edgesize - 1; for (int i = 0; i < edgesize; i++) { currentvert = edge.get(i); removeadj.clear(); for (integer adj : adjacentsmap.get(currentvert)) { if (edge.contains(adj)) { int adjindexonedge = edge.indexof(adj); if (math.abs(i - adjindexonedge) > 1 && !(i == 0 && adjindexonedge == edgesizeminusone) && !(i == edgesizeminusone && adjindexonedge == 0)) { tmppair.set(currentvert, adj); pair<triangle, triangle> edgetriangles = edgestotriangles.get(tmppair); if (lastremovedtriangles.contains(edgetriangles.getfirst()) && lastremovedtriangles.contains(edgetriangles.getsecond())) { removeadj.add(adj); edgestotriangles.remove(edgetriangles); } } } } for (integer removadjacent : removeadj) { adjacentsmap.get(currentvert).remove(removadjacent); } } newlightfaces.clear(); arraylist<integer> furthestpointneighbours = new arraylist<integer>(edge.size()); a = vertices.get(edge.get(0)); vector3f b = vertices.get(edge.get(1)); vector3f c = vertices.get(edge.get(2)); for (int i = 3; i < edge.size() && !linearindependent(a, b, c); i++) { c = vertices.get(edge.get(i)); } vector3f normal = vecmath.computenormal(a, b, c); boolean correctorientation = vecmath.dotproduct(normal, vecmath.subtraction(a, furthestpoint, tmpvec)) < 0; int vertidb = edge.get(0); for (int i = 0; i < edge.size(); i++) { int vertida = vertidb; if (i < edge.size() - 1) { vertidb = edge.get(i + 1); } else { vertidb = edge.get(0); } vector3f va = vertices.get(vertida); vector3f vb = vertices.get(vertidb); vector3f norm = vecmath.computenormal(va, vb, furthestpoint); triangle stitchtriangle; if (correctorientation) { stitchtriangle = new triangle(vertida, vertidb, furthestpointid, norm); } else { norm.negate(); stitchtriangle = new triangle(vertida, furthestpointid, vertidb, norm); } faces.add(0, stitchtriangle); newlightfaces.add(stitchtriangle); adjacentsmap.get(vertida).add(furthestpointid); tmppair.set(vertida, vertidb); pair<triangle, triangle> oldedgeinfo = edgestotriangles.get(tmppair); if (lastremovedtriangles.contains(oldedgeinfo.getfirst())) { oldedgeinfo.setfirst(stitchtriangle); } else { oldedgeinfo.setsecond(stitchtriangle); } tmppair.set(vertida, furthestpointid); oldedgeinfo = edgestotriangles.get(tmppair); if (oldedgeinfo != null) { oldedgeinfo.setsecond(stitchtriangle); } else { edgestotriangles.put(new pair<integer, integer>(vertida, furthestpointid), new pair<triangle, triangle>(null, stitchtriangle)); } tmppair.set(vertidb, furthestpointid); oldedgeinfo = edgestotriangles.get(tmppair); if (oldedgeinfo != null) { oldedgeinfo.setfirst(stitchtriangle); } else { edgestotriangles.put(new pair<integer, integer>(vertidb, furthestpointid), new pair<triangle, triangle>(stitchtriangle, null)); } furthestpointneighbours.add(vertida); } adjacentsmap.put(furthestpointid, furthestpointneighbours); for (triangle tri : newlightfaces) { listsoffacepoints.add(0, getlightpoints(tri, facepoints)); } return false; } | tdc22/JAwesomeEngine | [
1,
0,
0,
0
] |
32,153 | @Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
if (mContentParent == null) {
installDecor();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
// TODO Augment the scenes/transitions API to support this.
Log.v(TAG, "addContentView does not support content transitions");
}
mContentParent.addView(view, params);
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
} | @Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
if (mContentParent == null) {
installDecor();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
Log.v(TAG, "addContentView does not support content transitions");
}
mContentParent.addView(view, params);
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
} | @override public void addcontentview(view view, viewgroup.layoutparams params) { if (mcontentparent == null) { installdecor(); } if (hasfeature(feature_content_transitions)) { log.v(tag, "addcontentview does not support content transitions"); } mcontentparent.addview(view, params); mcontentparent.requestapplyinsets(); final callback cb = getcallback(); if (cb != null && !isdestroyed()) { cb.oncontentchanged(); } } | yujintao529/android_practice | [
1,
0,
0,
0
] |
16,350 | public PostSubmitCallbackResponse handle(
Callback<AsylumCase> callback
) {
if (!canHandle(callback)) {
throw new IllegalStateException("Cannot handle callback");
}
PostSubmitCallbackResponse postSubmitResponse =
new PostSubmitCallbackResponse();
AsylumCase asylumCase = callback.getCaseDetails().getCaseData();
TimeExtensionDecision decision = getTimeExtensionDecision(asylumCase);
String confirmationHeader = decision == GRANTED
? "# You have granted a time extension"
: "# You have refused a time extension";
postSubmitResponse.setConfirmationHeader(confirmationHeader);
//TODO: Next step Direction name should be dynamic too.
postSubmitResponse.setConfirmationBody(
"#### What happens next\n\n"
+ "The appellant has been notified that their request has been "
+ decision.toString()
+ " and that they must submit their Appeal Reasons by the new due date.<br>"
+ "You will be notified when it is ready to review.\n"
);
return postSubmitResponse;
} | public PostSubmitCallbackResponse handle(
Callback<AsylumCase> callback
) {
if (!canHandle(callback)) {
throw new IllegalStateException("Cannot handle callback");
}
PostSubmitCallbackResponse postSubmitResponse =
new PostSubmitCallbackResponse();
AsylumCase asylumCase = callback.getCaseDetails().getCaseData();
TimeExtensionDecision decision = getTimeExtensionDecision(asylumCase);
String confirmationHeader = decision == GRANTED
? "# You have granted a time extension"
: "# You have refused a time extension";
postSubmitResponse.setConfirmationHeader(confirmationHeader);
postSubmitResponse.setConfirmationBody(
"#### What happens next\n\n"
+ "The appellant has been notified that their request has been "
+ decision.toString()
+ " and that they must submit their Appeal Reasons by the new due date.<br>"
+ "You will be notified when it is ready to review.\n"
);
return postSubmitResponse;
} | public postsubmitcallbackresponse handle( callback<asylumcase> callback ) { if (!canhandle(callback)) { throw new illegalstateexception("cannot handle callback"); } postsubmitcallbackresponse postsubmitresponse = new postsubmitcallbackresponse(); asylumcase asylumcase = callback.getcasedetails().getcasedata(); timeextensiondecision decision = gettimeextensiondecision(asylumcase); string confirmationheader = decision == granted ? "# you have granted a time extension" : "# you have refused a time extension"; postsubmitresponse.setconfirmationheader(confirmationheader); postsubmitresponse.setconfirmationbody( "#### what happens next\n\n" + "the appellant has been notified that their request has been " + decision.tostring() + " and that they must submit their appeal reasons by the new due date.<br>" + "you will be notified when it is ready to review.\n" ); return postsubmitresponse; } | uk-gov-mirror/hmcts.ia-case-api | [
0,
1,
0,
0
] |