hexsha
stringlengths
40
40
repo
stringlengths
4
114
path
stringlengths
6
369
license
sequence
language
stringclasses
1 value
identifier
stringlengths
1
123
original_docstring
stringlengths
8
49.2k
docstring
stringlengths
5
8.63k
docstring_tokens
sequence
code
stringlengths
25
988k
code_tokens
sequence
short_docstring
stringlengths
0
6.18k
short_docstring_tokens
sequence
comment
sequence
parameters
list
docstring_params
dict
0e1f3e531fd861ca114785f47953053081d517b1
ghillert/gnss-nmea-demo
src/main/java/com/hillert/gnss/demo/model/GnssStatus.java
[ "Apache-2.0" ]
Java
GnssStatus
/** * Basic status information of the GNSS (GPS, Galileo etc.) data. * * @author Gunnar Hillert * */
Basic status information of the GNSS (GPS, Galileo etc.) data.
[ "Basic", "status", "information", "of", "the", "GNSS", "(", "GPS", "Galileo", "etc", ".", ")", "data", "." ]
public class GnssStatus { private volatile Double altitude; private volatile Double longitude; private volatile Double latitude; private volatile GpsFixQuality fixQuality; private volatile Map<GnssProvider, Integer> satelliteCount = new ConcurrentHashMap<>(); private volatile GpsFixStatus gpsFixStatus; private volatile Double calculatedHorizontalAccuracyInMeters; private volatile Double ubloxHorizontalAccuracyInMeters; private volatile Double ubloxVerticalAccuracyInMeters; public Double getAltitude() { return this.altitude; } public void setAltitude(Double altitude) { this.altitude = altitude; } public GpsFixQuality getFixQuality() { return this.fixQuality; } public void setFixQuality(GpsFixQuality fixQuality) { this.fixQuality = fixQuality; } public Map<GnssProvider, Integer> getSatelliteCount() { return this.satelliteCount; } public void setSatelliteCount(Map<GnssProvider, Integer> satelliteCount) { this.satelliteCount = satelliteCount; } public GpsFixStatus getGpsFixStatus() { return this.gpsFixStatus; } public void setGpsFixStatus(GpsFixStatus gpsFixStatus) { this.gpsFixStatus = gpsFixStatus; } public Double getLongitude() { return this.longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Double getLatitude() { return this.latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public Double getCalculatedHorizontalAccuracyInMeters() { return calculatedHorizontalAccuracyInMeters; } public void setCalculatedHorizontalAccuracyInMeters(Double calculatedHorizontalAccuracyInMeters) { this.calculatedHorizontalAccuracyInMeters = calculatedHorizontalAccuracyInMeters; } public Double getUbloxHorizontalAccuracyInMeters() { return ubloxHorizontalAccuracyInMeters; } public void setUbloxHorizontalAccuracyInMeters(Double ubloxHorizontalAccuracyInMeters) { this.ubloxHorizontalAccuracyInMeters = ubloxHorizontalAccuracyInMeters; } public Double getUbloxVerticalAccuracyInMeters() { return ubloxVerticalAccuracyInMeters; } public void setUbloxVerticalAccuracyInMeters(Double ubloxVerticalAccuracyInMeters) { this.ubloxVerticalAccuracyInMeters = ubloxVerticalAccuracyInMeters; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.altitude == null) ? 0 : this.altitude.hashCode()); result = prime * result + ((this.fixQuality == null) ? 0 : this.fixQuality.hashCode()); result = prime * result + ((this.gpsFixStatus == null) ? 0 : this.gpsFixStatus.hashCode()); result = prime * result + ((this.latitude == null) ? 0 : this.latitude.hashCode()); result = prime * result + ((this.longitude == null) ? 0 : this.longitude.hashCode()); result = prime * result + ((this.satelliteCount == null) ? 0 : this.satelliteCount.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } GnssStatus other = (GnssStatus) obj; if (this.altitude == null) { if (other.altitude != null) { return false; } } else if (!this.altitude.equals(other.altitude)) { return false; } if (this.fixQuality != other.fixQuality) { return false; } if (this.gpsFixStatus != other.gpsFixStatus) { return false; } if (this.latitude == null) { if (other.latitude != null) { return false; } } else if (!this.latitude.equals(other.latitude)) { return false; } if (this.longitude == null) { if (other.longitude != null) { return false; } } else if (!this.longitude.equals(other.longitude)) { return false; } if (this.satelliteCount == null) { if (other.satelliteCount != null) { return false; } } else if (!this.satelliteCount.equals(other.satelliteCount)) { return false; } return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("GnssStatus [altitude="); builder.append(this.altitude); builder.append(", longitude="); builder.append(this.longitude); builder.append(", latitude="); builder.append(this.latitude); builder.append(", fixQuality="); builder.append(this.fixQuality); builder.append(", totalSatelliteCount="); builder.append(getTotalSatelliteCount()); builder.append(", gpsFixStatus="); builder.append(this.gpsFixStatus); builder.append("]"); return builder.toString(); } public int getTotalSatelliteCount() { int totalSatelliteCount = 0; for (Map.Entry<GnssProvider, Integer> satelliteCountEntry : this.satelliteCount.entrySet()) { if (satelliteCountEntry.getValue() != null) { totalSatelliteCount = totalSatelliteCount + satelliteCountEntry.getValue().intValue(); } } return totalSatelliteCount; } }
[ "public", "class", "GnssStatus", "{", "private", "volatile", "Double", "altitude", ";", "private", "volatile", "Double", "longitude", ";", "private", "volatile", "Double", "latitude", ";", "private", "volatile", "GpsFixQuality", "fixQuality", ";", "private", "volatile", "Map", "<", "GnssProvider", ",", "Integer", ">", "satelliteCount", "=", "new", "ConcurrentHashMap", "<", ">", "(", ")", ";", "private", "volatile", "GpsFixStatus", "gpsFixStatus", ";", "private", "volatile", "Double", "calculatedHorizontalAccuracyInMeters", ";", "private", "volatile", "Double", "ubloxHorizontalAccuracyInMeters", ";", "private", "volatile", "Double", "ubloxVerticalAccuracyInMeters", ";", "public", "Double", "getAltitude", "(", ")", "{", "return", "this", ".", "altitude", ";", "}", "public", "void", "setAltitude", "(", "Double", "altitude", ")", "{", "this", ".", "altitude", "=", "altitude", ";", "}", "public", "GpsFixQuality", "getFixQuality", "(", ")", "{", "return", "this", ".", "fixQuality", ";", "}", "public", "void", "setFixQuality", "(", "GpsFixQuality", "fixQuality", ")", "{", "this", ".", "fixQuality", "=", "fixQuality", ";", "}", "public", "Map", "<", "GnssProvider", ",", "Integer", ">", "getSatelliteCount", "(", ")", "{", "return", "this", ".", "satelliteCount", ";", "}", "public", "void", "setSatelliteCount", "(", "Map", "<", "GnssProvider", ",", "Integer", ">", "satelliteCount", ")", "{", "this", ".", "satelliteCount", "=", "satelliteCount", ";", "}", "public", "GpsFixStatus", "getGpsFixStatus", "(", ")", "{", "return", "this", ".", "gpsFixStatus", ";", "}", "public", "void", "setGpsFixStatus", "(", "GpsFixStatus", "gpsFixStatus", ")", "{", "this", ".", "gpsFixStatus", "=", "gpsFixStatus", ";", "}", "public", "Double", "getLongitude", "(", ")", "{", "return", "this", ".", "longitude", ";", "}", "public", "void", "setLongitude", "(", "Double", "longitude", ")", "{", "this", ".", "longitude", "=", "longitude", ";", "}", "public", "Double", "getLatitude", "(", ")", "{", "return", "this", ".", "latitude", ";", "}", "public", "void", "setLatitude", "(", "Double", "latitude", ")", "{", "this", ".", "latitude", "=", "latitude", ";", "}", "public", "Double", "getCalculatedHorizontalAccuracyInMeters", "(", ")", "{", "return", "calculatedHorizontalAccuracyInMeters", ";", "}", "public", "void", "setCalculatedHorizontalAccuracyInMeters", "(", "Double", "calculatedHorizontalAccuracyInMeters", ")", "{", "this", ".", "calculatedHorizontalAccuracyInMeters", "=", "calculatedHorizontalAccuracyInMeters", ";", "}", "public", "Double", "getUbloxHorizontalAccuracyInMeters", "(", ")", "{", "return", "ubloxHorizontalAccuracyInMeters", ";", "}", "public", "void", "setUbloxHorizontalAccuracyInMeters", "(", "Double", "ubloxHorizontalAccuracyInMeters", ")", "{", "this", ".", "ubloxHorizontalAccuracyInMeters", "=", "ubloxHorizontalAccuracyInMeters", ";", "}", "public", "Double", "getUbloxVerticalAccuracyInMeters", "(", ")", "{", "return", "ubloxVerticalAccuracyInMeters", ";", "}", "public", "void", "setUbloxVerticalAccuracyInMeters", "(", "Double", "ubloxVerticalAccuracyInMeters", ")", "{", "this", ".", "ubloxVerticalAccuracyInMeters", "=", "ubloxVerticalAccuracyInMeters", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "final", "int", "prime", "=", "31", ";", "int", "result", "=", "1", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "this", ".", "altitude", "==", "null", ")", "?", "0", ":", "this", ".", "altitude", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "this", ".", "fixQuality", "==", "null", ")", "?", "0", ":", "this", ".", "fixQuality", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "this", ".", "gpsFixStatus", "==", "null", ")", "?", "0", ":", "this", ".", "gpsFixStatus", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "this", ".", "latitude", "==", "null", ")", "?", "0", ":", "this", ".", "latitude", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "this", ".", "longitude", "==", "null", ")", "?", "0", ":", "this", ".", "longitude", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "this", ".", "satelliteCount", "==", "null", ")", "?", "0", ":", "this", ".", "satelliteCount", ".", "hashCode", "(", ")", ")", ";", "return", "result", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "this", "==", "obj", ")", "{", "return", "true", ";", "}", "if", "(", "obj", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "getClass", "(", ")", "!=", "obj", ".", "getClass", "(", ")", ")", "{", "return", "false", ";", "}", "GnssStatus", "other", "=", "(", "GnssStatus", ")", "obj", ";", "if", "(", "this", ".", "altitude", "==", "null", ")", "{", "if", "(", "other", ".", "altitude", "!=", "null", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "!", "this", ".", "altitude", ".", "equals", "(", "other", ".", "altitude", ")", ")", "{", "return", "false", ";", "}", "if", "(", "this", ".", "fixQuality", "!=", "other", ".", "fixQuality", ")", "{", "return", "false", ";", "}", "if", "(", "this", ".", "gpsFixStatus", "!=", "other", ".", "gpsFixStatus", ")", "{", "return", "false", ";", "}", "if", "(", "this", ".", "latitude", "==", "null", ")", "{", "if", "(", "other", ".", "latitude", "!=", "null", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "!", "this", ".", "latitude", ".", "equals", "(", "other", ".", "latitude", ")", ")", "{", "return", "false", ";", "}", "if", "(", "this", ".", "longitude", "==", "null", ")", "{", "if", "(", "other", ".", "longitude", "!=", "null", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "!", "this", ".", "longitude", ".", "equals", "(", "other", ".", "longitude", ")", ")", "{", "return", "false", ";", "}", "if", "(", "this", ".", "satelliteCount", "==", "null", ")", "{", "if", "(", "other", ".", "satelliteCount", "!=", "null", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "!", "this", ".", "satelliteCount", ".", "equals", "(", "other", ".", "satelliteCount", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "builder", ".", "append", "(", "\"", "GnssStatus [altitude=", "\"", ")", ";", "builder", ".", "append", "(", "this", ".", "altitude", ")", ";", "builder", ".", "append", "(", "\"", ", longitude=", "\"", ")", ";", "builder", ".", "append", "(", "this", ".", "longitude", ")", ";", "builder", ".", "append", "(", "\"", ", latitude=", "\"", ")", ";", "builder", ".", "append", "(", "this", ".", "latitude", ")", ";", "builder", ".", "append", "(", "\"", ", fixQuality=", "\"", ")", ";", "builder", ".", "append", "(", "this", ".", "fixQuality", ")", ";", "builder", ".", "append", "(", "\"", ", totalSatelliteCount=", "\"", ")", ";", "builder", ".", "append", "(", "getTotalSatelliteCount", "(", ")", ")", ";", "builder", ".", "append", "(", "\"", ", gpsFixStatus=", "\"", ")", ";", "builder", ".", "append", "(", "this", ".", "gpsFixStatus", ")", ";", "builder", ".", "append", "(", "\"", "]", "\"", ")", ";", "return", "builder", ".", "toString", "(", ")", ";", "}", "public", "int", "getTotalSatelliteCount", "(", ")", "{", "int", "totalSatelliteCount", "=", "0", ";", "for", "(", "Map", ".", "Entry", "<", "GnssProvider", ",", "Integer", ">", "satelliteCountEntry", ":", "this", ".", "satelliteCount", ".", "entrySet", "(", ")", ")", "{", "if", "(", "satelliteCountEntry", ".", "getValue", "(", ")", "!=", "null", ")", "{", "totalSatelliteCount", "=", "totalSatelliteCount", "+", "satelliteCountEntry", ".", "getValue", "(", ")", ".", "intValue", "(", ")", ";", "}", "}", "return", "totalSatelliteCount", ";", "}", "}" ]
Basic status information of the GNSS (GPS, Galileo etc.)
[ "Basic", "status", "information", "of", "the", "GNSS", "(", "GPS", "Galileo", "etc", ".", ")" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "author", "docstring": null, "docstring_tokens": [ "None" ] } ] }
0e1f6e5aca872f71e370794d85fc7143bf1c8c29
BGoldenberg161/Daily-Kata
src/test/java/com/smt/kata/word/RearrangeWordsTest.java
[ "MIT" ]
Java
RearrangeWordsTest
/**************************************************************************** * <b>Title</b>: RearrangeWordsTest.java * <b>Project</b>: SMT-Kata * <b>Description: </b> Unit Test for the Rearrange Words Kata * <b>Copyright:</b> Copyright (c) 2021 * <b>Company:</b> Silicon Mountain Technologies * * @author James Camire * @version 3.0 * @since Aug 30, 2021 * @updates: ****************************************************************************/
@author James Camire @version 3.0 @since Aug 30, 2021 @updates.
[ "@author", "James", "Camire", "@version", "3", ".", "0", "@since", "Aug", "30", "2021", "@updates", "." ]
class RearrangeWordsTest { // Members RearrangeWords rw = new RearrangeWords(); /** * Test method for {@link com.smt.kata.word.RearrangeWords#arrange(java.lang.String)}. */ @Test void testArrangeNull() throws Exception { assertEquals(0, rw.arrange(null).size()); } /** * Test method for {@link com.smt.kata.word.RearrangeWords#arrange(java.lang.String)}. */ @Test void testArrangeEmpty() throws Exception { assertEquals(0, rw.arrange("").size()); } /** * Test method for {@link com.smt.kata.word.RearrangeWords#arrange(java.lang.String)}. */ @Test void testArrangeShort() throws Exception { assertEquals(0, rw.arrange("A").size()); } /** * Test method for {@link com.smt.kata.word.RearrangeWords#arrange(java.lang.String)}. */ @Test void testArrangeInvalid() throws Exception { assertEquals(0, rw.arrange("ABC&^").size()); } /** * Test method for {@link com.smt.kata.word.RearrangeWords#arrange(java.lang.String)}. */ @Test void testArrangeMixedCase() throws Exception { Collection<String> words = rw.arrange("aAabBc"); assertEquals(1, words.size()); assertTrue(words.contains("aAabBc")); } /** * Test method for {@link com.smt.kata.word.RearrangeWords#arrange(java.lang.String)}. */ @Test void testArrangeMain() throws Exception { String[] results = new String[]{ "ababac", "ababca", "abacab", "abacba", "abcaba", "acabab", "acbaba", "babaca", "bacaba", "cababa" }; Collection<String> words = rw.arrange("aaabbc"); assertEquals(10, words.size()); for(String word : results) assertTrue(words.contains(word)); } /** * Test method for {@link com.smt.kata.word.RearrangeWords#arrange(java.lang.String)}. */ @Test void testArrangeNone() throws Exception { Collection<String> words = rw.arrange("aaab"); assertEquals(0, words.size()); } }
[ "class", "RearrangeWordsTest", "{", "RearrangeWords", "rw", "=", "new", "RearrangeWords", "(", ")", ";", "/**\n\t * Test method for {@link com.smt.kata.word.RearrangeWords#arrange(java.lang.String)}.\n\t */", "@", "Test", "void", "testArrangeNull", "(", ")", "throws", "Exception", "{", "assertEquals", "(", "0", ",", "rw", ".", "arrange", "(", "null", ")", ".", "size", "(", ")", ")", ";", "}", "/**\n\t * Test method for {@link com.smt.kata.word.RearrangeWords#arrange(java.lang.String)}.\n\t */", "@", "Test", "void", "testArrangeEmpty", "(", ")", "throws", "Exception", "{", "assertEquals", "(", "0", ",", "rw", ".", "arrange", "(", "\"", "\"", ")", ".", "size", "(", ")", ")", ";", "}", "/**\n\t * Test method for {@link com.smt.kata.word.RearrangeWords#arrange(java.lang.String)}.\n\t */", "@", "Test", "void", "testArrangeShort", "(", ")", "throws", "Exception", "{", "assertEquals", "(", "0", ",", "rw", ".", "arrange", "(", "\"", "A", "\"", ")", ".", "size", "(", ")", ")", ";", "}", "/**\n\t * Test method for {@link com.smt.kata.word.RearrangeWords#arrange(java.lang.String)}.\n\t */", "@", "Test", "void", "testArrangeInvalid", "(", ")", "throws", "Exception", "{", "assertEquals", "(", "0", ",", "rw", ".", "arrange", "(", "\"", "ABC&^", "\"", ")", ".", "size", "(", ")", ")", ";", "}", "/**\n\t * Test method for {@link com.smt.kata.word.RearrangeWords#arrange(java.lang.String)}.\n\t */", "@", "Test", "void", "testArrangeMixedCase", "(", ")", "throws", "Exception", "{", "Collection", "<", "String", ">", "words", "=", "rw", ".", "arrange", "(", "\"", "aAabBc", "\"", ")", ";", "assertEquals", "(", "1", ",", "words", ".", "size", "(", ")", ")", ";", "assertTrue", "(", "words", ".", "contains", "(", "\"", "aAabBc", "\"", ")", ")", ";", "}", "/**\n\t * Test method for {@link com.smt.kata.word.RearrangeWords#arrange(java.lang.String)}.\n\t */", "@", "Test", "void", "testArrangeMain", "(", ")", "throws", "Exception", "{", "String", "[", "]", "results", "=", "new", "String", "[", "]", "{", "\"", "ababac", "\"", ",", "\"", "ababca", "\"", ",", "\"", "abacab", "\"", ",", "\"", "abacba", "\"", ",", "\"", "abcaba", "\"", ",", "\"", "acabab", "\"", ",", "\"", "acbaba", "\"", ",", "\"", "babaca", "\"", ",", "\"", "bacaba", "\"", ",", "\"", "cababa", "\"", "}", ";", "Collection", "<", "String", ">", "words", "=", "rw", ".", "arrange", "(", "\"", "aaabbc", "\"", ")", ";", "assertEquals", "(", "10", ",", "words", ".", "size", "(", ")", ")", ";", "for", "(", "String", "word", ":", "results", ")", "assertTrue", "(", "words", ".", "contains", "(", "word", ")", ")", ";", "}", "/**\n\t * Test method for {@link com.smt.kata.word.RearrangeWords#arrange(java.lang.String)}.\n\t */", "@", "Test", "void", "testArrangeNone", "(", ")", "throws", "Exception", "{", "Collection", "<", "String", ">", "words", "=", "rw", ".", "arrange", "(", "\"", "aaab", "\"", ")", ";", "assertEquals", "(", "0", ",", "words", ".", "size", "(", ")", ")", ";", "}", "}" ]
<b>Title</b>: RearrangeWordsTest.java <b>Project</b>: SMT-Kata <b>Description: </b> Unit Test for the Rearrange Words Kata <b>Copyright:</b> Copyright (c) 2021 <b>Company:</b> Silicon Mountain Technologies
[ "<b", ">", "Title<", "/", "b", ">", ":", "RearrangeWordsTest", ".", "java", "<b", ">", "Project<", "/", "b", ">", ":", "SMT", "-", "Kata", "<b", ">", "Description", ":", "<", "/", "b", ">", "Unit", "Test", "for", "the", "Rearrange", "Words", "Kata", "<b", ">", "Copyright", ":", "<", "/", "b", ">", "Copyright", "(", "c", ")", "2021", "<b", ">", "Company", ":", "<", "/", "b", ">", "Silicon", "Mountain", "Technologies" ]
[ "// Members" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
0e2193886493e3e04667393029071dd7c4ef8a26
Laurens-makel/iaf
cmis/src/main/java/nl/nn/adapterframework/extensions/cmis/server/BridgedCmisService.java
[ "Apache-2.0" ]
Java
BridgedCmisService
/** * After each request the CallContext is removed. * The CmisBinding is kept, unless property cmisbridge.closeConnection = true */
After each request the CallContext is removed. The CmisBinding is kept, unless property cmisbridge.closeConnection = true
[ "After", "each", "request", "the", "CallContext", "is", "removed", ".", "The", "CmisBinding", "is", "kept", "unless", "property", "cmisbridge", ".", "closeConnection", "=", "true" ]
public class BridgedCmisService extends FilterCmisService { private static final long serialVersionUID = 2L; private final Logger log = LogUtil.getLogger(this); private static final AppConstants APP_CONSTANTS = AppConstants.getInstance(); public static final boolean CMIS_BRIDGE_CLOSE_CONNECTION = APP_CONSTANTS.getBoolean(RepositoryConnectorFactory.CMIS_BRIDGE_PROPERTY_PREFIX+"closeConnection", false); private CmisBinding clientBinding; public BridgedCmisService(CallContext context) { setCallContext(context); } public CmisBinding getCmisBinding() { if(clientBinding == null) { clientBinding = createCmisBinding(); log.info("initialized "+toString()); } return clientBinding; } public CmisBinding createCmisBinding() { //Make sure cmisbridge properties are defined if(APP_CONSTANTS.getResolvedProperty(RepositoryConnectorFactory.CMIS_BRIDGE_PROPERTY_PREFIX+"url") == null) throw new CmisConnectionException("no bridge properties found"); CmisSessionBuilder sessionBuilder = new CmisSessionBuilder(); for(Method method: sessionBuilder.getClass().getMethods()) { if(!method.getName().startsWith("set") || method.getParameterTypes().length != 1) continue; //Remove set from the method name String setter = firstCharToLower(method.getName().substring(3)); String value = APP_CONSTANTS.getResolvedProperty(RepositoryConnectorFactory.CMIS_BRIDGE_PROPERTY_PREFIX+setter); if(value == null) continue; //Only always grab the first value because we explicitly check method.getParameterTypes().length != 1 Object castValue = getCastValue(method.getParameterTypes()[0], value); log.debug("trying to set property ["+RepositoryConnectorFactory.CMIS_BRIDGE_PROPERTY_PREFIX+setter+"] with value ["+value+"] of type ["+castValue.getClass().getCanonicalName()+"] on ["+sessionBuilder+"]"); try { method.invoke(sessionBuilder, castValue); } catch (Exception e) { throw new CmisConnectionException("error while calling method ["+setter+"] on CmisSessionBuilder ["+sessionBuilder.toString()+"]", e); } } try { Session session = sessionBuilder.build(); return session.getBinding(); } catch (CmisSessionException e) { log.error(e); throw new CmisConnectionException(e.getMessage()); } } private String firstCharToLower(String input) { return input.substring(0, 1).toLowerCase() + input.substring(1); } private Object getCastValue(Class<?> class1, String value) { String className = class1.getName().toLowerCase(); if("boolean".equals(className)) return Boolean.parseBoolean(value); else if("int".equals(className) || "integer".equals(className)) return Integer.parseInt(value); else return value; } @Override public ObjectService getObjectService() { return new IbisObjectService(getCmisBinding().getObjectService(), getCallContext()); } @Override public RepositoryService getRepositoryService() { return new IbisRepositoryService(getCmisBinding().getRepositoryService(), getCallContext()); } @Override public DiscoveryService getDiscoveryService() { return new IbisDiscoveryService(getCmisBinding().getDiscoveryService(), getCallContext()); } @Override public NavigationService getNavigationService() { return new IbisNavigationService(getCmisBinding().getNavigationService(), getCallContext()); } @Override public VersioningService getVersioningService() { return getCmisBinding().getVersioningService(); } @Override public MultiFilingService getMultiFilingService() { return getCmisBinding().getMultiFilingService(); } @Override public RelationshipService getRelationshipService() { return getCmisBinding().getRelationshipService(); } @Override public AclService getAclService() { return getCmisBinding().getAclService(); } @Override public PolicyService getPolicyService() { return getCmisBinding().getPolicyService(); } /** * Returns Class SimpleName + hash + attribute info * @return BridgedCmisService@abc12345 close[xxx] session[xxx] */ @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(getClass().getSimpleName() + "@" + Integer.toHexString(hashCode())); builder.append(" close ["+CMIS_BRIDGE_CLOSE_CONNECTION+"]"); if(clientBinding != null) { builder.append(" session ["+clientBinding.getSessionId()+"]"); } return builder.toString(); } @Override public void close() { super.close(); if(CMIS_BRIDGE_CLOSE_CONNECTION) { clientBinding = null; log.info("closed "+toString()); } } }
[ "public", "class", "BridgedCmisService", "extends", "FilterCmisService", "{", "private", "static", "final", "long", "serialVersionUID", "=", "2L", ";", "private", "final", "Logger", "log", "=", "LogUtil", ".", "getLogger", "(", "this", ")", ";", "private", "static", "final", "AppConstants", "APP_CONSTANTS", "=", "AppConstants", ".", "getInstance", "(", ")", ";", "public", "static", "final", "boolean", "CMIS_BRIDGE_CLOSE_CONNECTION", "=", "APP_CONSTANTS", ".", "getBoolean", "(", "RepositoryConnectorFactory", ".", "CMIS_BRIDGE_PROPERTY_PREFIX", "+", "\"", "closeConnection", "\"", ",", "false", ")", ";", "private", "CmisBinding", "clientBinding", ";", "public", "BridgedCmisService", "(", "CallContext", "context", ")", "{", "setCallContext", "(", "context", ")", ";", "}", "public", "CmisBinding", "getCmisBinding", "(", ")", "{", "if", "(", "clientBinding", "==", "null", ")", "{", "clientBinding", "=", "createCmisBinding", "(", ")", ";", "log", ".", "info", "(", "\"", "initialized ", "\"", "+", "toString", "(", ")", ")", ";", "}", "return", "clientBinding", ";", "}", "public", "CmisBinding", "createCmisBinding", "(", ")", "{", "if", "(", "APP_CONSTANTS", ".", "getResolvedProperty", "(", "RepositoryConnectorFactory", ".", "CMIS_BRIDGE_PROPERTY_PREFIX", "+", "\"", "url", "\"", ")", "==", "null", ")", "throw", "new", "CmisConnectionException", "(", "\"", "no bridge properties found", "\"", ")", ";", "CmisSessionBuilder", "sessionBuilder", "=", "new", "CmisSessionBuilder", "(", ")", ";", "for", "(", "Method", "method", ":", "sessionBuilder", ".", "getClass", "(", ")", ".", "getMethods", "(", ")", ")", "{", "if", "(", "!", "method", ".", "getName", "(", ")", ".", "startsWith", "(", "\"", "set", "\"", ")", "||", "method", ".", "getParameterTypes", "(", ")", ".", "length", "!=", "1", ")", "continue", ";", "String", "setter", "=", "firstCharToLower", "(", "method", ".", "getName", "(", ")", ".", "substring", "(", "3", ")", ")", ";", "String", "value", "=", "APP_CONSTANTS", ".", "getResolvedProperty", "(", "RepositoryConnectorFactory", ".", "CMIS_BRIDGE_PROPERTY_PREFIX", "+", "setter", ")", ";", "if", "(", "value", "==", "null", ")", "continue", ";", "Object", "castValue", "=", "getCastValue", "(", "method", ".", "getParameterTypes", "(", ")", "[", "0", "]", ",", "value", ")", ";", "log", ".", "debug", "(", "\"", "trying to set property [", "\"", "+", "RepositoryConnectorFactory", ".", "CMIS_BRIDGE_PROPERTY_PREFIX", "+", "setter", "+", "\"", "] with value [", "\"", "+", "value", "+", "\"", "] of type [", "\"", "+", "castValue", ".", "getClass", "(", ")", ".", "getCanonicalName", "(", ")", "+", "\"", "] on [", "\"", "+", "sessionBuilder", "+", "\"", "]", "\"", ")", ";", "try", "{", "method", ".", "invoke", "(", "sessionBuilder", ",", "castValue", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "CmisConnectionException", "(", "\"", "error while calling method [", "\"", "+", "setter", "+", "\"", "] on CmisSessionBuilder [", "\"", "+", "sessionBuilder", ".", "toString", "(", ")", "+", "\"", "]", "\"", ",", "e", ")", ";", "}", "}", "try", "{", "Session", "session", "=", "sessionBuilder", ".", "build", "(", ")", ";", "return", "session", ".", "getBinding", "(", ")", ";", "}", "catch", "(", "CmisSessionException", "e", ")", "{", "log", ".", "error", "(", "e", ")", ";", "throw", "new", "CmisConnectionException", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "private", "String", "firstCharToLower", "(", "String", "input", ")", "{", "return", "input", ".", "substring", "(", "0", ",", "1", ")", ".", "toLowerCase", "(", ")", "+", "input", ".", "substring", "(", "1", ")", ";", "}", "private", "Object", "getCastValue", "(", "Class", "<", "?", ">", "class1", ",", "String", "value", ")", "{", "String", "className", "=", "class1", ".", "getName", "(", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "\"", "boolean", "\"", ".", "equals", "(", "className", ")", ")", "return", "Boolean", ".", "parseBoolean", "(", "value", ")", ";", "else", "if", "(", "\"", "int", "\"", ".", "equals", "(", "className", ")", "||", "\"", "integer", "\"", ".", "equals", "(", "className", ")", ")", "return", "Integer", ".", "parseInt", "(", "value", ")", ";", "else", "return", "value", ";", "}", "@", "Override", "public", "ObjectService", "getObjectService", "(", ")", "{", "return", "new", "IbisObjectService", "(", "getCmisBinding", "(", ")", ".", "getObjectService", "(", ")", ",", "getCallContext", "(", ")", ")", ";", "}", "@", "Override", "public", "RepositoryService", "getRepositoryService", "(", ")", "{", "return", "new", "IbisRepositoryService", "(", "getCmisBinding", "(", ")", ".", "getRepositoryService", "(", ")", ",", "getCallContext", "(", ")", ")", ";", "}", "@", "Override", "public", "DiscoveryService", "getDiscoveryService", "(", ")", "{", "return", "new", "IbisDiscoveryService", "(", "getCmisBinding", "(", ")", ".", "getDiscoveryService", "(", ")", ",", "getCallContext", "(", ")", ")", ";", "}", "@", "Override", "public", "NavigationService", "getNavigationService", "(", ")", "{", "return", "new", "IbisNavigationService", "(", "getCmisBinding", "(", ")", ".", "getNavigationService", "(", ")", ",", "getCallContext", "(", ")", ")", ";", "}", "@", "Override", "public", "VersioningService", "getVersioningService", "(", ")", "{", "return", "getCmisBinding", "(", ")", ".", "getVersioningService", "(", ")", ";", "}", "@", "Override", "public", "MultiFilingService", "getMultiFilingService", "(", ")", "{", "return", "getCmisBinding", "(", ")", ".", "getMultiFilingService", "(", ")", ";", "}", "@", "Override", "public", "RelationshipService", "getRelationshipService", "(", ")", "{", "return", "getCmisBinding", "(", ")", ".", "getRelationshipService", "(", ")", ";", "}", "@", "Override", "public", "AclService", "getAclService", "(", ")", "{", "return", "getCmisBinding", "(", ")", ".", "getAclService", "(", ")", ";", "}", "@", "Override", "public", "PolicyService", "getPolicyService", "(", ")", "{", "return", "getCmisBinding", "(", ")", ".", "getPolicyService", "(", ")", ";", "}", "/**\n\t * Returns Class SimpleName + hash + attribute info\n\t * @return BridgedCmisService@abc12345 close[xxx] session[xxx]\n\t */", "@", "Override", "public", "String", "toString", "(", ")", "{", "final", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "builder", ".", "append", "(", "getClass", "(", ")", ".", "getSimpleName", "(", ")", "+", "\"", "@", "\"", "+", "Integer", ".", "toHexString", "(", "hashCode", "(", ")", ")", ")", ";", "builder", ".", "append", "(", "\"", " close [", "\"", "+", "CMIS_BRIDGE_CLOSE_CONNECTION", "+", "\"", "]", "\"", ")", ";", "if", "(", "clientBinding", "!=", "null", ")", "{", "builder", ".", "append", "(", "\"", " session [", "\"", "+", "clientBinding", ".", "getSessionId", "(", ")", "+", "\"", "]", "\"", ")", ";", "}", "return", "builder", ".", "toString", "(", ")", ";", "}", "@", "Override", "public", "void", "close", "(", ")", "{", "super", ".", "close", "(", ")", ";", "if", "(", "CMIS_BRIDGE_CLOSE_CONNECTION", ")", "{", "clientBinding", "=", "null", ";", "log", ".", "info", "(", "\"", "closed ", "\"", "+", "toString", "(", ")", ")", ";", "}", "}", "}" ]
After each request the CallContext is removed.
[ "After", "each", "request", "the", "CallContext", "is", "removed", "." ]
[ "//Make sure cmisbridge properties are defined", "//Remove set from the method name", "//Only always grab the first value because we explicitly check method.getParameterTypes().length != 1" ]
[ { "param": "FilterCmisService", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "FilterCmisService", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0e221296ee19244adab3f6d9a50d0c13f0bc3333
manmanhensha/ContentProhibited
src/main/java/com/bootdo/reserve_functions/DataSourceMS/DataSourceContextAop.java
[ "MIT" ]
Java
DataSourceContextAop
/** * @author wushiqiang * @date Created in 10:56 2021/1/4 * @description * @modified By */
@author wushiqiang @date Created in 10:56 2021/1/4 @description @modified By
[ "@author", "wushiqiang", "@date", "Created", "in", "10", ":", "56", "2021", "/", "1", "/", "4", "@description", "@modified", "By" ]
@Slf4j @Aspect @Order(value = 1) @Component public class DataSourceContextAop { @Around("@annotation(com.wyq.mysqlreadwriteseparate.annotation.DataSourceSwitcher)") public Object setDynamicDataSource(ProceedingJoinPoint pjp) throws Throwable { boolean clear = false; try { Method method = this.getMethod(pjp); DataSourceSwitcher dataSourceSwitcher = method.getAnnotation(DataSourceSwitcher.class); clear = dataSourceSwitcher.clear(); DataSourceContextHolder.set(dataSourceSwitcher.value().getDataSourceName()); log.info("数据源切换至:{}", dataSourceSwitcher.value().getDataSourceName()); return pjp.proceed(); } finally { if (clear) { DataSourceContextHolder.clear(); } } } private Method getMethod(JoinPoint pjp) { MethodSignature signature = (MethodSignature) pjp.getSignature(); return signature.getMethod(); } }
[ "@", "Slf4j", "@", "Aspect", "@", "Order", "(", "value", "=", "1", ")", "@", "Component", "public", "class", "DataSourceContextAop", "{", "@", "Around", "(", "\"", "@annotation(com.wyq.mysqlreadwriteseparate.annotation.DataSourceSwitcher)", "\"", ")", "public", "Object", "setDynamicDataSource", "(", "ProceedingJoinPoint", "pjp", ")", "throws", "Throwable", "{", "boolean", "clear", "=", "false", ";", "try", "{", "Method", "method", "=", "this", ".", "getMethod", "(", "pjp", ")", ";", "DataSourceSwitcher", "dataSourceSwitcher", "=", "method", ".", "getAnnotation", "(", "DataSourceSwitcher", ".", "class", ")", ";", "clear", "=", "dataSourceSwitcher", ".", "clear", "(", ")", ";", "DataSourceContextHolder", ".", "set", "(", "dataSourceSwitcher", ".", "value", "(", ")", ".", "getDataSourceName", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "数据源切换至:{}\", dataSourceS", "w", "i", "cher.value().getDa", "t", "aSour", "c", "e", "N", "ame());", "", "", "", "", "return", "pjp", ".", "proceed", "(", ")", ";", "}", "finally", "{", "if", "(", "clear", ")", "{", "DataSourceContextHolder", ".", "clear", "(", ")", ";", "}", "}", "}", "private", "Method", "getMethod", "(", "JoinPoint", "pjp", ")", "{", "MethodSignature", "signature", "=", "(", "MethodSignature", ")", "pjp", ".", "getSignature", "(", ")", ";", "return", "signature", ".", "getMethod", "(", ")", ";", "}", "}" ]
@author wushiqiang @date Created in 10:56 2021/1/4 @description @modified By
[ "@author", "wushiqiang", "@date", "Created", "in", "10", ":", "56", "2021", "/", "1", "/", "4", "@description", "@modified", "By" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
0e22920f71f7fa23c89ecb492ef3e3e31e1a98f3
Malesio/CarRent
src/main/java/org/krytonspace/carrent/gui/tablemodels/ContractTableModel.java
[ "MIT" ]
Java
ContractTableModel
/** * Table model handling display for contracts. */
Table model handling display for contracts.
[ "Table", "model", "handling", "display", "for", "contracts", "." ]
public class ContractTableModel extends BaseTableModel { private static final List<ModelFieldPair> COLUMNS = getModelFieldsInfo(ContractModel.class); /** * The controller managing contracts. */ private final ContractController controller; /** * A filter to apply to the cache. */ private Predicate<ContractModel> filter; /** * Contract cache. */ private List<ContractModel> cache; /** * Constructor. * @param controller The controller managing contracts. */ public ContractTableModel(ContractController controller) { this.controller = controller; // Update cache when the controller apply changes. ((ContractModelController) controller).addModelListener(new ModelListener() { @Override public void onModelAdded(ModelEvent e) { updateCache(); } @Override public void onModelRemoving(ModelEvent e) { updateCache(); } @Override public void onModelEdited(ModelEvent e) { // Ignored: cache contents reflects internal model data. } }); // No filter by default. resetFilter(); } /** * Apply a filter to this table model. This will trigger a cache update. * @param filter The filter to apply. */ public void applyFilter(Predicate<ContractModel> filter) { this.filter = filter; updateCache(); } @Override public void updateCache() { cache = controller .query() .filter(filter) // Apply custom filter .sorted(Comparator.comparingInt(Model::getInternalId)) // Sort by internal ID .collect(Collectors.toList()); // Trigger visual update. fireTableDataChanged(); } @Override public void resetFilter() { applyFilter(contract -> true); } @Override public int getRowCount() { return cache.size(); } @Override public int getColumnCount() { return COLUMNS.size(); } @Override public String getColumnName(int columnIndex) { return COLUMNS.get(columnIndex).getName(); } @Override public Class<?> getColumnClass(int columnIndex) { return COLUMNS.get(columnIndex).getType(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { // Values are stored in the cache. if (!cache.isEmpty()) { ContractModel contract = cache.get(rowIndex); switch (columnIndex) { case 0: return contract.getId(); case 1: return contract.getClientId(); case 2: return contract.getVehicleId(); case 3: return contract.getBeginDate(); case 4: return contract.getEndDate(); case 5: return contract.getPlannedMileage(); case 6: return contract.getPlannedPrice(); } } return null; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (!cache.isEmpty()) { ContractModel contract = cache.get(rowIndex); // The controller must be used to edit models. try { switch (columnIndex) { case 3: controller.editContractDateBegin(contract, (Date) aValue); break; case 4: controller.editContractDateEnd(contract, (Date) aValue); break; case 5: controller.editContractPlannedMileage(contract, (Integer) aValue); break; case 6: controller.editContractPlannedPrice(contract, (Integer) aValue); break; } } catch (InvalidDataException e) { Window.notifyException(e); } } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { // Prohibit client and vehicle ID change. A contract is bound to a client and a vehicle. if (columnIndex == 1 || columnIndex == 2) { return false; } return super.isCellEditable(rowIndex, columnIndex); } }
[ "public", "class", "ContractTableModel", "extends", "BaseTableModel", "{", "private", "static", "final", "List", "<", "ModelFieldPair", ">", "COLUMNS", "=", "getModelFieldsInfo", "(", "ContractModel", ".", "class", ")", ";", "/**\n * The controller managing contracts.\n */", "private", "final", "ContractController", "controller", ";", "/**\n * A filter to apply to the cache.\n */", "private", "Predicate", "<", "ContractModel", ">", "filter", ";", "/**\n * Contract cache.\n */", "private", "List", "<", "ContractModel", ">", "cache", ";", "/**\n * Constructor.\n * @param controller The controller managing contracts.\n */", "public", "ContractTableModel", "(", "ContractController", "controller", ")", "{", "this", ".", "controller", "=", "controller", ";", "(", "(", "ContractModelController", ")", "controller", ")", ".", "addModelListener", "(", "new", "ModelListener", "(", ")", "{", "@", "Override", "public", "void", "onModelAdded", "(", "ModelEvent", "e", ")", "{", "updateCache", "(", ")", ";", "}", "@", "Override", "public", "void", "onModelRemoving", "(", "ModelEvent", "e", ")", "{", "updateCache", "(", ")", ";", "}", "@", "Override", "public", "void", "onModelEdited", "(", "ModelEvent", "e", ")", "{", "}", "}", ")", ";", "resetFilter", "(", ")", ";", "}", "/**\n * Apply a filter to this table model. This will trigger a cache update.\n * @param filter The filter to apply.\n */", "public", "void", "applyFilter", "(", "Predicate", "<", "ContractModel", ">", "filter", ")", "{", "this", ".", "filter", "=", "filter", ";", "updateCache", "(", ")", ";", "}", "@", "Override", "public", "void", "updateCache", "(", ")", "{", "cache", "=", "controller", ".", "query", "(", ")", ".", "filter", "(", "filter", ")", ".", "sorted", "(", "Comparator", ".", "comparingInt", "(", "Model", "::", "getInternalId", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "fireTableDataChanged", "(", ")", ";", "}", "@", "Override", "public", "void", "resetFilter", "(", ")", "{", "applyFilter", "(", "contract", "->", "true", ")", ";", "}", "@", "Override", "public", "int", "getRowCount", "(", ")", "{", "return", "cache", ".", "size", "(", ")", ";", "}", "@", "Override", "public", "int", "getColumnCount", "(", ")", "{", "return", "COLUMNS", ".", "size", "(", ")", ";", "}", "@", "Override", "public", "String", "getColumnName", "(", "int", "columnIndex", ")", "{", "return", "COLUMNS", ".", "get", "(", "columnIndex", ")", ".", "getName", "(", ")", ";", "}", "@", "Override", "public", "Class", "<", "?", ">", "getColumnClass", "(", "int", "columnIndex", ")", "{", "return", "COLUMNS", ".", "get", "(", "columnIndex", ")", ".", "getType", "(", ")", ";", "}", "@", "Override", "public", "Object", "getValueAt", "(", "int", "rowIndex", ",", "int", "columnIndex", ")", "{", "if", "(", "!", "cache", ".", "isEmpty", "(", ")", ")", "{", "ContractModel", "contract", "=", "cache", ".", "get", "(", "rowIndex", ")", ";", "switch", "(", "columnIndex", ")", "{", "case", "0", ":", "return", "contract", ".", "getId", "(", ")", ";", "case", "1", ":", "return", "contract", ".", "getClientId", "(", ")", ";", "case", "2", ":", "return", "contract", ".", "getVehicleId", "(", ")", ";", "case", "3", ":", "return", "contract", ".", "getBeginDate", "(", ")", ";", "case", "4", ":", "return", "contract", ".", "getEndDate", "(", ")", ";", "case", "5", ":", "return", "contract", ".", "getPlannedMileage", "(", ")", ";", "case", "6", ":", "return", "contract", ".", "getPlannedPrice", "(", ")", ";", "}", "}", "return", "null", ";", "}", "@", "Override", "public", "void", "setValueAt", "(", "Object", "aValue", ",", "int", "rowIndex", ",", "int", "columnIndex", ")", "{", "if", "(", "!", "cache", ".", "isEmpty", "(", ")", ")", "{", "ContractModel", "contract", "=", "cache", ".", "get", "(", "rowIndex", ")", ";", "try", "{", "switch", "(", "columnIndex", ")", "{", "case", "3", ":", "controller", ".", "editContractDateBegin", "(", "contract", ",", "(", "Date", ")", "aValue", ")", ";", "break", ";", "case", "4", ":", "controller", ".", "editContractDateEnd", "(", "contract", ",", "(", "Date", ")", "aValue", ")", ";", "break", ";", "case", "5", ":", "controller", ".", "editContractPlannedMileage", "(", "contract", ",", "(", "Integer", ")", "aValue", ")", ";", "break", ";", "case", "6", ":", "controller", ".", "editContractPlannedPrice", "(", "contract", ",", "(", "Integer", ")", "aValue", ")", ";", "break", ";", "}", "}", "catch", "(", "InvalidDataException", "e", ")", "{", "Window", ".", "notifyException", "(", "e", ")", ";", "}", "}", "}", "@", "Override", "public", "boolean", "isCellEditable", "(", "int", "rowIndex", ",", "int", "columnIndex", ")", "{", "if", "(", "columnIndex", "==", "1", "||", "columnIndex", "==", "2", ")", "{", "return", "false", ";", "}", "return", "super", ".", "isCellEditable", "(", "rowIndex", ",", "columnIndex", ")", ";", "}", "}" ]
Table model handling display for contracts.
[ "Table", "model", "handling", "display", "for", "contracts", "." ]
[ "// Update cache when the controller apply changes.", "// Ignored: cache contents reflects internal model data.", "// No filter by default.", "// Apply custom filter", "// Sort by internal ID", "// Trigger visual update.", "// Values are stored in the cache.", "// The controller must be used to edit models.", "// Prohibit client and vehicle ID change. A contract is bound to a client and a vehicle." ]
[ { "param": "BaseTableModel", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseTableModel", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0e28b5466d6dc36ffbaadb72435b0371186ff4d0
testadmin1-levelops/sirix
bundles/sirix-core/src/main/java/org/sirix/cache/LRUCache.java
[ "BSD-3-Clause" ]
Java
LRUCache
/** * An LRU cache, based on {@code LinkedHashMap}. This cache can hold an * possible second cache as a second layer for example for storing data in a * persistent way. * * @author Sebastian Graf, University of Konstanz */
An LRU cache, based on LinkedHashMap. This cache can hold an possible second cache as a second layer for example for storing data in a persistent way. @author Sebastian Graf, University of Konstanz
[ "An", "LRU", "cache", "based", "on", "LinkedHashMap", ".", "This", "cache", "can", "hold", "an", "possible", "second", "cache", "as", "a", "second", "layer", "for", "example", "for", "storing", "data", "in", "a", "persistent", "way", ".", "@author", "Sebastian", "Graf", "University", "of", "Konstanz" ]
public final class LRUCache<K, V> implements ICache<K, V> { /** * Capacity of the cache. Number of stored pages. */ static final int CACHE_CAPACITY = 1500; /** * The collection to hold the maps. */ private final Map<K, V> mMap; /** * The reference to the second cache. */ private final ICache<K, V> mSecondCache; /** * Creates a new LRU cache. * * @param pSecondCache * the reference to the second {@link ICache} where the data is stored * when it gets removed from the first one. */ public LRUCache(@Nonnull final ICache<K, V> pSecondCache) { mSecondCache = checkNotNull(pSecondCache); mMap = new LinkedHashMap<K, V>(CACHE_CAPACITY) { private static final long serialVersionUID = 1; @Override protected boolean removeEldestEntry( @Nullable final Map.Entry<K, V> pEldest) { boolean returnVal = false; if (size() > CACHE_CAPACITY) { if (pEldest != null) { final K key = pEldest.getKey(); final V value = pEldest.getValue(); if (key != null && value != null) { mSecondCache.put(key, value); } } returnVal = true; } return returnVal; } }; } public LRUCache() { this(new EmptyCache<K, V>()); } /** * Retrieves an entry from the cache.<br> * The retrieved entry becomes the MRU (most recently used) entry. * * @param pKey * the key whose associated value is to be returned. * @return the value associated to this key, or {@code null} if no value with this * key exists in the cache */ @Override public V get(@Nonnull final K pKey) { V page = mMap.get(pKey); if (page == null) { page = mSecondCache.get(pKey); } return page; } /** * * Adds an entry to this cache. If the cache is full, the LRU (least * recently used) entry is dropped. * * @param pKey * the key with which the specified value is to be associated * @param pValue * a value to be associated with the specified key */ @Override public void put(@Nonnull final K pKey, @Nonnull final V pValue) { mMap.put(pKey, pValue); } /** * Clears the cache. */ @Override public void clear() { mMap.clear(); mSecondCache.clear(); } /** * Returns the number of used entries in the cache. * * @return the number of entries currently in the cache. */ public int usedEntries() { return mMap.size(); } /** * Returns a {@code Collection} that contains a copy of all cache * entries. * * @return a {@code Collection} with a copy of the cache content */ public Collection<Map.Entry<K, V>> getAll() { return new ArrayList<>(mMap.entrySet()); } @Override public String toString() { return Objects.toStringHelper(this).add("First Cache", mMap).add( "Second Cache", mSecondCache).toString(); } @Override public ImmutableMap<K, V> getAll(final @Nonnull Iterable<? extends K> pKeys) { final ImmutableMap.Builder<K, V> builder = new ImmutableMap.Builder<>(); for (final K key : pKeys) { if (mMap.get(key) != null) { builder.put(key, mMap.get(key)); } } return builder.build(); } @Override public void putAll(final @Nonnull Map<K, V> pMap) { mMap.putAll(checkNotNull(pMap)); } @Override public void toSecondCache() { mSecondCache.putAll(mMap); } /** * Get a view of the underlying map. * * @return an unmodifiable view of all entries in the cache */ public Map<K, V> getMap() { return Collections.unmodifiableMap(mMap); } @Override public void remove(final @Nonnull K pKey) { mMap.remove(pKey); if (mSecondCache.get(pKey) != null) { mSecondCache.remove(pKey); } } @Override public void close() { mMap.clear(); mSecondCache.close(); } }
[ "public", "final", "class", "LRUCache", "<", "K", ",", "V", ">", "implements", "ICache", "<", "K", ",", "V", ">", "{", "/**\n * Capacity of the cache. Number of stored pages.\n */", "static", "final", "int", "CACHE_CAPACITY", "=", "1500", ";", "/**\n * The collection to hold the maps.\n */", "private", "final", "Map", "<", "K", ",", "V", ">", "mMap", ";", "/**\n * The reference to the second cache.\n */", "private", "final", "ICache", "<", "K", ",", "V", ">", "mSecondCache", ";", "/**\n * Creates a new LRU cache.\n * \n * @param pSecondCache\n * the reference to the second {@link ICache} where the data is stored\n * when it gets removed from the first one.\n */", "public", "LRUCache", "(", "@", "Nonnull", "final", "ICache", "<", "K", ",", "V", ">", "pSecondCache", ")", "{", "mSecondCache", "=", "checkNotNull", "(", "pSecondCache", ")", ";", "mMap", "=", "new", "LinkedHashMap", "<", "K", ",", "V", ">", "(", "CACHE_CAPACITY", ")", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1", ";", "@", "Override", "protected", "boolean", "removeEldestEntry", "(", "@", "Nullable", "final", "Map", ".", "Entry", "<", "K", ",", "V", ">", "pEldest", ")", "{", "boolean", "returnVal", "=", "false", ";", "if", "(", "size", "(", ")", ">", "CACHE_CAPACITY", ")", "{", "if", "(", "pEldest", "!=", "null", ")", "{", "final", "K", "key", "=", "pEldest", ".", "getKey", "(", ")", ";", "final", "V", "value", "=", "pEldest", ".", "getValue", "(", ")", ";", "if", "(", "key", "!=", "null", "&&", "value", "!=", "null", ")", "{", "mSecondCache", ".", "put", "(", "key", ",", "value", ")", ";", "}", "}", "returnVal", "=", "true", ";", "}", "return", "returnVal", ";", "}", "}", ";", "}", "public", "LRUCache", "(", ")", "{", "this", "(", "new", "EmptyCache", "<", "K", ",", "V", ">", "(", ")", ")", ";", "}", "/**\n * Retrieves an entry from the cache.<br>\n * The retrieved entry becomes the MRU (most recently used) entry.\n * \n * @param pKey\n * the key whose associated value is to be returned.\n * @return the value associated to this key, or {@code null} if no value with this\n * key exists in the cache\n */", "@", "Override", "public", "V", "get", "(", "@", "Nonnull", "final", "K", "pKey", ")", "{", "V", "page", "=", "mMap", ".", "get", "(", "pKey", ")", ";", "if", "(", "page", "==", "null", ")", "{", "page", "=", "mSecondCache", ".", "get", "(", "pKey", ")", ";", "}", "return", "page", ";", "}", "/**\n * \n * Adds an entry to this cache. If the cache is full, the LRU (least\n * recently used) entry is dropped.\n * \n * @param pKey\n * the key with which the specified value is to be associated\n * @param pValue\n * a value to be associated with the specified key\n */", "@", "Override", "public", "void", "put", "(", "@", "Nonnull", "final", "K", "pKey", ",", "@", "Nonnull", "final", "V", "pValue", ")", "{", "mMap", ".", "put", "(", "pKey", ",", "pValue", ")", ";", "}", "/**\n * Clears the cache.\n */", "@", "Override", "public", "void", "clear", "(", ")", "{", "mMap", ".", "clear", "(", ")", ";", "mSecondCache", ".", "clear", "(", ")", ";", "}", "/**\n * Returns the number of used entries in the cache.\n * \n * @return the number of entries currently in the cache.\n */", "public", "int", "usedEntries", "(", ")", "{", "return", "mMap", ".", "size", "(", ")", ";", "}", "/**\n * Returns a {@code Collection} that contains a copy of all cache\n * entries.\n * \n * @return a {@code Collection} with a copy of the cache content\n */", "public", "Collection", "<", "Map", ".", "Entry", "<", "K", ",", "V", ">", ">", "getAll", "(", ")", "{", "return", "new", "ArrayList", "<", ">", "(", "mMap", ".", "entrySet", "(", ")", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "Objects", ".", "toStringHelper", "(", "this", ")", ".", "add", "(", "\"", "First Cache", "\"", ",", "mMap", ")", ".", "add", "(", "\"", "Second Cache", "\"", ",", "mSecondCache", ")", ".", "toString", "(", ")", ";", "}", "@", "Override", "public", "ImmutableMap", "<", "K", ",", "V", ">", "getAll", "(", "final", "@", "Nonnull", "Iterable", "<", "?", "extends", "K", ">", "pKeys", ")", "{", "final", "ImmutableMap", ".", "Builder", "<", "K", ",", "V", ">", "builder", "=", "new", "ImmutableMap", ".", "Builder", "<", ">", "(", ")", ";", "for", "(", "final", "K", "key", ":", "pKeys", ")", "{", "if", "(", "mMap", ".", "get", "(", "key", ")", "!=", "null", ")", "{", "builder", ".", "put", "(", "key", ",", "mMap", ".", "get", "(", "key", ")", ")", ";", "}", "}", "return", "builder", ".", "build", "(", ")", ";", "}", "@", "Override", "public", "void", "putAll", "(", "final", "@", "Nonnull", "Map", "<", "K", ",", "V", ">", "pMap", ")", "{", "mMap", ".", "putAll", "(", "checkNotNull", "(", "pMap", ")", ")", ";", "}", "@", "Override", "public", "void", "toSecondCache", "(", ")", "{", "mSecondCache", ".", "putAll", "(", "mMap", ")", ";", "}", "/**\n * Get a view of the underlying map.\n * \n * @return an unmodifiable view of all entries in the cache\n */", "public", "Map", "<", "K", ",", "V", ">", "getMap", "(", ")", "{", "return", "Collections", ".", "unmodifiableMap", "(", "mMap", ")", ";", "}", "@", "Override", "public", "void", "remove", "(", "final", "@", "Nonnull", "K", "pKey", ")", "{", "mMap", ".", "remove", "(", "pKey", ")", ";", "if", "(", "mSecondCache", ".", "get", "(", "pKey", ")", "!=", "null", ")", "{", "mSecondCache", ".", "remove", "(", "pKey", ")", ";", "}", "}", "@", "Override", "public", "void", "close", "(", ")", "{", "mMap", ".", "clear", "(", ")", ";", "mSecondCache", ".", "close", "(", ")", ";", "}", "}" ]
An LRU cache, based on {@code LinkedHashMap}.
[ "An", "LRU", "cache", "based", "on", "{", "@code", "LinkedHashMap", "}", "." ]
[]
[ { "param": "ICache<K, V>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ICache<K, V>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0e292524244d1c928f73547cf151bd7ebd26bfa8
sofwerx/OSUS-R
mil.dod.th.ose.remote/src/mil/dod/th/ose/remote/EventChannel.java
[ "CC0-1.0" ]
Java
EventChannel
/** * Remote channel used when no remote channel to a system can be found. * * @author cweisenborn */
Remote channel used when no remote channel to a system can be found. @author cweisenborn
[ "Remote", "channel", "used", "when", "no", "remote", "channel", "to", "a", "system", "can", "be", "found", ".", "@author", "cweisenborn" ]
public class EventChannel implements RemoteChannel { private final EventAdmin m_EventAdmin; private final int m_RemoteSystemId; /** * Constructor that accepts the ID of the remote system the channel represents and the event admin used to post * events to the system. * * @param remoteSystemId * ID of the remote system the channel represents. * @param eventAdmin * Event admin service used to post unreachable send events. */ public EventChannel(final int remoteSystemId, final EventAdmin eventAdmin) { m_RemoteSystemId = remoteSystemId; m_EventAdmin = eventAdmin; } public int getRemoteSystemId() { return m_RemoteSystemId; } @Override public boolean trySendMessage(final TerraHarvestMessage message) { final Event unreachableDestEvent = RemoteInterfaceUtilities.createMessageUnreachableSendEvent(message); m_EventAdmin.postEvent(unreachableDestEvent); return true; } @Override public boolean queueMessage(final TerraHarvestMessage message) { final Event unreachableDestEvent = RemoteInterfaceUtilities.createMessageUnreachableSendEvent(message); m_EventAdmin.postEvent(unreachableDestEvent); return true; } @Override public boolean matches(final Map<String, Object> properties) { return false; } @Override public ChannelStatus getStatus() { return null; } @Override public RemoteChannelTypeEnum getChannelType() { return null; } @Override public int getQueuedMessageCount() { return 0; } @Override public long getBytesTransmitted() { return 0; } @Override public long getBytesReceived() { return 0; } @Override public void clearQueuedMessages() { //Empty method. Method should do nothing as no message will ever be place in a queue. } }
[ "public", "class", "EventChannel", "implements", "RemoteChannel", "{", "private", "final", "EventAdmin", "m_EventAdmin", ";", "private", "final", "int", "m_RemoteSystemId", ";", "/**\n * Constructor that accepts the ID of the remote system the channel represents and the event admin used to post\n * events to the system.\n * \n * @param remoteSystemId\n * ID of the remote system the channel represents.\n * @param eventAdmin\n * Event admin service used to post unreachable send events.\n */", "public", "EventChannel", "(", "final", "int", "remoteSystemId", ",", "final", "EventAdmin", "eventAdmin", ")", "{", "m_RemoteSystemId", "=", "remoteSystemId", ";", "m_EventAdmin", "=", "eventAdmin", ";", "}", "public", "int", "getRemoteSystemId", "(", ")", "{", "return", "m_RemoteSystemId", ";", "}", "@", "Override", "public", "boolean", "trySendMessage", "(", "final", "TerraHarvestMessage", "message", ")", "{", "final", "Event", "unreachableDestEvent", "=", "RemoteInterfaceUtilities", ".", "createMessageUnreachableSendEvent", "(", "message", ")", ";", "m_EventAdmin", ".", "postEvent", "(", "unreachableDestEvent", ")", ";", "return", "true", ";", "}", "@", "Override", "public", "boolean", "queueMessage", "(", "final", "TerraHarvestMessage", "message", ")", "{", "final", "Event", "unreachableDestEvent", "=", "RemoteInterfaceUtilities", ".", "createMessageUnreachableSendEvent", "(", "message", ")", ";", "m_EventAdmin", ".", "postEvent", "(", "unreachableDestEvent", ")", ";", "return", "true", ";", "}", "@", "Override", "public", "boolean", "matches", "(", "final", "Map", "<", "String", ",", "Object", ">", "properties", ")", "{", "return", "false", ";", "}", "@", "Override", "public", "ChannelStatus", "getStatus", "(", ")", "{", "return", "null", ";", "}", "@", "Override", "public", "RemoteChannelTypeEnum", "getChannelType", "(", ")", "{", "return", "null", ";", "}", "@", "Override", "public", "int", "getQueuedMessageCount", "(", ")", "{", "return", "0", ";", "}", "@", "Override", "public", "long", "getBytesTransmitted", "(", ")", "{", "return", "0", ";", "}", "@", "Override", "public", "long", "getBytesReceived", "(", ")", "{", "return", "0", ";", "}", "@", "Override", "public", "void", "clearQueuedMessages", "(", ")", "{", "}", "}" ]
Remote channel used when no remote channel to a system can be found.
[ "Remote", "channel", "used", "when", "no", "remote", "channel", "to", "a", "system", "can", "be", "found", "." ]
[ "//Empty method. Method should do nothing as no message will ever be place in a queue." ]
[ { "param": "RemoteChannel", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "RemoteChannel", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0e2a1837ddf2b4601b46766c95a4f014d6874789
blindsubmissions/icse19replication
source/runtime/src/main/java/org/evosuite/runtime/mock/java/io/EvoFileChannel.java
[ "MIT" ]
Java
EvoFileChannel
/** * This is not a mock of FileChannel, as FileChannel is an abstract class. * This class is never instantiated directly from the SUTs, but rather from mock classes (eg MockFileInputStream). * * * @author arcuri * */
This is not a mock of FileChannel, as FileChannel is an abstract class. This class is never instantiated directly from the SUTs, but rather from mock classes . @author arcuri
[ "This", "is", "not", "a", "mock", "of", "FileChannel", "as", "FileChannel", "is", "an", "abstract", "class", ".", "This", "class", "is", "never", "instantiated", "directly", "from", "the", "SUTs", "but", "rather", "from", "mock", "classes", ".", "@author", "arcuri" ]
public class EvoFileChannel extends FileChannel{ //FIXME mock FileChannel /** * The read/write position in the channel */ private final AtomicInteger position; /** * The absolute path of the file this channel is for */ private final String path; /** * Can this channel be used for read operations? */ private final boolean isOpenForRead; /** * Can this channel be used for write operations? */ private final boolean isOpenForWrite; /** * Is this channel closed? Most functions throw an exception if the channel is closed. * Once a channel is closed, it cannot be reopened */ private volatile boolean closed; private final Object readWriteMonitor = new Object(); /** * Main constructor * * @param sharedPosition the position in the channel, which should be shared with the stream this channel was generated from (i.e., same instance reference) * @param path full qualifying path the of the target file * @param isOpenForRead * @param isOpenForWrite */ protected EvoFileChannel(AtomicInteger sharedPosition, String path, boolean isOpenForRead, boolean isOpenForWrite) { super(); this.position = sharedPosition; this.path = path; this.isOpenForRead = isOpenForRead; this.isOpenForWrite = isOpenForWrite; closed = false; } // ----- read -------- @Override public int read(ByteBuffer dst) throws IOException { return read(new ByteBuffer[]{dst},0,1,position); } @Override public int read(ByteBuffer dst, long pos) throws IOException { if(pos < 0){ throw new MockIllegalArgumentException("Negative position: "+pos); } AtomicInteger tmp = new AtomicInteger((int)pos); return read(new ByteBuffer[]{dst},0,1,tmp); } @Override public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { return read(dsts,offset,length,position); } private int read(ByteBuffer[] dsts, int offset, int length, AtomicInteger posToUpdate) throws IOException { if(!isOpenForRead){ throw new NonReadableChannelException(); } throwExceptionIfClosed(); int counter = 0; synchronized(readWriteMonitor){ for(int j=offset; j<length; j++){ ByteBuffer dst = dsts[j]; int r = dst.remaining(); for(int i=0; i<r; i++){ int b = NativeMockedIO.read(path, posToUpdate); if(b < 0){ //end of stream return -1; } if(closed){ throw new AsynchronousCloseException(); } if(Thread.currentThread().isInterrupted()){ close(); throw new ClosedByInterruptException(); } dst.put((byte)b); counter++; } } } return counter; } // -------- write ---------- @Override public int write(ByteBuffer src) throws IOException { return write(new ByteBuffer[]{src},0,1,position); } @Override public int write(ByteBuffer src, long pos) throws IOException { if(pos < 0){ throw new MockIllegalArgumentException("Negative position: "+pos); } AtomicInteger tmp = new AtomicInteger((int)pos); return write(new ByteBuffer[]{src},0,1,tmp); } @Override public long write(ByteBuffer[] srcs, int offset, int length) throws IOException { return write(srcs,offset,length,position); } private int write(ByteBuffer[] srcs, int offset, int length, AtomicInteger posToUpdate) throws IOException { if(!isOpenForWrite){ throw new NonWritableChannelException(); } if( (offset < 0) || (offset > srcs.length) || (length < 0) || (length > srcs.length-offset) ){ throw new IndexOutOfBoundsException(); } throwExceptionIfClosed(); int counter = 0; byte[] buffer = new byte[1]; synchronized(readWriteMonitor){ for(int j=offset; j<length; j++){ ByteBuffer src = srcs[j]; int r = src.remaining(); for(int i=0; i<r; i++){ byte b = src.get(); buffer[0] = b; NativeMockedIO.writeBytes(path, posToUpdate, buffer, 0, 1); counter++; if(closed){ throw new AsynchronousCloseException(); } if(Thread.currentThread().isInterrupted()){ close(); throw new ClosedByInterruptException(); } } } } return counter; } @Override public FileChannel truncate(long size) throws IOException { throwExceptionIfClosed(); if(size < 0){ throw new MockIllegalArgumentException(); } if(!isOpenForWrite){ throw new NonWritableChannelException(); } long currentSize = size(); if(size < currentSize){ NativeMockedIO.setLength(path, position, size); } return this; } //------ others -------- @Override public long position() throws IOException { throwExceptionIfClosed(); VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(path); return position.get(); } @Override public FileChannel position(long newPosition) throws IOException { if(newPosition < 0){ throw new MockIllegalArgumentException(); } throwExceptionIfClosed(); VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(path); position.set((int)newPosition); return this; } @Override public long size() throws IOException { throwExceptionIfClosed(); return NativeMockedIO.size(path); } @Override public void force(boolean metaData) throws IOException { throwExceptionIfClosed(); VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(path); //nothing to do } @Override public long transferTo(long position, long count, WritableByteChannel target) throws IOException { // TODO throw new MockIOException("transferTo is not supported yet"); } @Override public long transferFrom(ReadableByteChannel src, long position, long count) throws IOException { // TODO throw new MockIOException("transferFrom is not supported yet"); } @Override public MappedByteBuffer map(MapMode mode, long position, long size) throws IOException { // TODO throw new MockIOException("MappedByteBuffer mocks are not supported yet"); } @Override public FileLock lock(long position, long size, boolean shared) throws IOException { // TODO throw new MockIOException("FileLock mocks are not supported yet"); } @Override public FileLock tryLock(long position, long size, boolean shared) throws IOException { // TODO throw new MockIOException("FileLock mocks are not supported yet"); } @Override protected void implCloseChannel() throws IOException { closed = true; } private void throwExceptionIfClosed() throws ClosedChannelException{ if(closed){ throw new ClosedChannelException(); } } }
[ "public", "class", "EvoFileChannel", "extends", "FileChannel", "{", "/**\n\t * The read/write position in the channel\n\t */", "private", "final", "AtomicInteger", "position", ";", "/**\n\t * The absolute path of the file this channel is for\n\t */", "private", "final", "String", "path", ";", "/**\n\t * Can this channel be used for read operations?\n\t */", "private", "final", "boolean", "isOpenForRead", ";", "/**\n\t * Can this channel be used for write operations?\n\t */", "private", "final", "boolean", "isOpenForWrite", ";", "/**\n\t * Is this channel closed? Most functions throw an exception if the channel is closed.\n\t * Once a channel is closed, it cannot be reopened\n\t */", "private", "volatile", "boolean", "closed", ";", "private", "final", "Object", "readWriteMonitor", "=", "new", "Object", "(", ")", ";", "/**\n\t * Main constructor\n\t * \n\t * @param sharedPosition the position in the channel, which should be shared with the stream this channel was generated from \n\t \t\t\t\t\t\t\t(i.e., same instance reference) \n\t * @param path\t\t\t\tfull qualifying path the of the target file\n\t * @param isOpenForRead\n\t * @param isOpenForWrite\n\t */", "protected", "EvoFileChannel", "(", "AtomicInteger", "sharedPosition", ",", "String", "path", ",", "boolean", "isOpenForRead", ",", "boolean", "isOpenForWrite", ")", "{", "super", "(", ")", ";", "this", ".", "position", "=", "sharedPosition", ";", "this", ".", "path", "=", "path", ";", "this", ".", "isOpenForRead", "=", "isOpenForRead", ";", "this", ".", "isOpenForWrite", "=", "isOpenForWrite", ";", "closed", "=", "false", ";", "}", "@", "Override", "public", "int", "read", "(", "ByteBuffer", "dst", ")", "throws", "IOException", "{", "return", "read", "(", "new", "ByteBuffer", "[", "]", "{", "dst", "}", ",", "0", ",", "1", ",", "position", ")", ";", "}", "@", "Override", "public", "int", "read", "(", "ByteBuffer", "dst", ",", "long", "pos", ")", "throws", "IOException", "{", "if", "(", "pos", "<", "0", ")", "{", "throw", "new", "MockIllegalArgumentException", "(", "\"", "Negative position: ", "\"", "+", "pos", ")", ";", "}", "AtomicInteger", "tmp", "=", "new", "AtomicInteger", "(", "(", "int", ")", "pos", ")", ";", "return", "read", "(", "new", "ByteBuffer", "[", "]", "{", "dst", "}", ",", "0", ",", "1", ",", "tmp", ")", ";", "}", "@", "Override", "public", "long", "read", "(", "ByteBuffer", "[", "]", "dsts", ",", "int", "offset", ",", "int", "length", ")", "throws", "IOException", "{", "return", "read", "(", "dsts", ",", "offset", ",", "length", ",", "position", ")", ";", "}", "private", "int", "read", "(", "ByteBuffer", "[", "]", "dsts", ",", "int", "offset", ",", "int", "length", ",", "AtomicInteger", "posToUpdate", ")", "throws", "IOException", "{", "if", "(", "!", "isOpenForRead", ")", "{", "throw", "new", "NonReadableChannelException", "(", ")", ";", "}", "throwExceptionIfClosed", "(", ")", ";", "int", "counter", "=", "0", ";", "synchronized", "(", "readWriteMonitor", ")", "{", "for", "(", "int", "j", "=", "offset", ";", "j", "<", "length", ";", "j", "++", ")", "{", "ByteBuffer", "dst", "=", "dsts", "[", "j", "]", ";", "int", "r", "=", "dst", ".", "remaining", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "r", ";", "i", "++", ")", "{", "int", "b", "=", "NativeMockedIO", ".", "read", "(", "path", ",", "posToUpdate", ")", ";", "if", "(", "b", "<", "0", ")", "{", "return", "-", "1", ";", "}", "if", "(", "closed", ")", "{", "throw", "new", "AsynchronousCloseException", "(", ")", ";", "}", "if", "(", "Thread", ".", "currentThread", "(", ")", ".", "isInterrupted", "(", ")", ")", "{", "close", "(", ")", ";", "throw", "new", "ClosedByInterruptException", "(", ")", ";", "}", "dst", ".", "put", "(", "(", "byte", ")", "b", ")", ";", "counter", "++", ";", "}", "}", "}", "return", "counter", ";", "}", "@", "Override", "public", "int", "write", "(", "ByteBuffer", "src", ")", "throws", "IOException", "{", "return", "write", "(", "new", "ByteBuffer", "[", "]", "{", "src", "}", ",", "0", ",", "1", ",", "position", ")", ";", "}", "@", "Override", "public", "int", "write", "(", "ByteBuffer", "src", ",", "long", "pos", ")", "throws", "IOException", "{", "if", "(", "pos", "<", "0", ")", "{", "throw", "new", "MockIllegalArgumentException", "(", "\"", "Negative position: ", "\"", "+", "pos", ")", ";", "}", "AtomicInteger", "tmp", "=", "new", "AtomicInteger", "(", "(", "int", ")", "pos", ")", ";", "return", "write", "(", "new", "ByteBuffer", "[", "]", "{", "src", "}", ",", "0", ",", "1", ",", "tmp", ")", ";", "}", "@", "Override", "public", "long", "write", "(", "ByteBuffer", "[", "]", "srcs", ",", "int", "offset", ",", "int", "length", ")", "throws", "IOException", "{", "return", "write", "(", "srcs", ",", "offset", ",", "length", ",", "position", ")", ";", "}", "private", "int", "write", "(", "ByteBuffer", "[", "]", "srcs", ",", "int", "offset", ",", "int", "length", ",", "AtomicInteger", "posToUpdate", ")", "throws", "IOException", "{", "if", "(", "!", "isOpenForWrite", ")", "{", "throw", "new", "NonWritableChannelException", "(", ")", ";", "}", "if", "(", "(", "offset", "<", "0", ")", "||", "(", "offset", ">", "srcs", ".", "length", ")", "||", "(", "length", "<", "0", ")", "||", "(", "length", ">", "srcs", ".", "length", "-", "offset", ")", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", ")", ";", "}", "throwExceptionIfClosed", "(", ")", ";", "int", "counter", "=", "0", ";", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "1", "]", ";", "synchronized", "(", "readWriteMonitor", ")", "{", "for", "(", "int", "j", "=", "offset", ";", "j", "<", "length", ";", "j", "++", ")", "{", "ByteBuffer", "src", "=", "srcs", "[", "j", "]", ";", "int", "r", "=", "src", ".", "remaining", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "r", ";", "i", "++", ")", "{", "byte", "b", "=", "src", ".", "get", "(", ")", ";", "buffer", "[", "0", "]", "=", "b", ";", "NativeMockedIO", ".", "writeBytes", "(", "path", ",", "posToUpdate", ",", "buffer", ",", "0", ",", "1", ")", ";", "counter", "++", ";", "if", "(", "closed", ")", "{", "throw", "new", "AsynchronousCloseException", "(", ")", ";", "}", "if", "(", "Thread", ".", "currentThread", "(", ")", ".", "isInterrupted", "(", ")", ")", "{", "close", "(", ")", ";", "throw", "new", "ClosedByInterruptException", "(", ")", ";", "}", "}", "}", "}", "return", "counter", ";", "}", "@", "Override", "public", "FileChannel", "truncate", "(", "long", "size", ")", "throws", "IOException", "{", "throwExceptionIfClosed", "(", ")", ";", "if", "(", "size", "<", "0", ")", "{", "throw", "new", "MockIllegalArgumentException", "(", ")", ";", "}", "if", "(", "!", "isOpenForWrite", ")", "{", "throw", "new", "NonWritableChannelException", "(", ")", ";", "}", "long", "currentSize", "=", "size", "(", ")", ";", "if", "(", "size", "<", "currentSize", ")", "{", "NativeMockedIO", ".", "setLength", "(", "path", ",", "position", ",", "size", ")", ";", "}", "return", "this", ";", "}", "@", "Override", "public", "long", "position", "(", ")", "throws", "IOException", "{", "throwExceptionIfClosed", "(", ")", ";", "VirtualFileSystem", ".", "getInstance", "(", ")", ".", "throwSimuledIOExceptionIfNeeded", "(", "path", ")", ";", "return", "position", ".", "get", "(", ")", ";", "}", "@", "Override", "public", "FileChannel", "position", "(", "long", "newPosition", ")", "throws", "IOException", "{", "if", "(", "newPosition", "<", "0", ")", "{", "throw", "new", "MockIllegalArgumentException", "(", ")", ";", "}", "throwExceptionIfClosed", "(", ")", ";", "VirtualFileSystem", ".", "getInstance", "(", ")", ".", "throwSimuledIOExceptionIfNeeded", "(", "path", ")", ";", "position", ".", "set", "(", "(", "int", ")", "newPosition", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "long", "size", "(", ")", "throws", "IOException", "{", "throwExceptionIfClosed", "(", ")", ";", "return", "NativeMockedIO", ".", "size", "(", "path", ")", ";", "}", "@", "Override", "public", "void", "force", "(", "boolean", "metaData", ")", "throws", "IOException", "{", "throwExceptionIfClosed", "(", ")", ";", "VirtualFileSystem", ".", "getInstance", "(", ")", ".", "throwSimuledIOExceptionIfNeeded", "(", "path", ")", ";", "}", "@", "Override", "public", "long", "transferTo", "(", "long", "position", ",", "long", "count", ",", "WritableByteChannel", "target", ")", "throws", "IOException", "{", "throw", "new", "MockIOException", "(", "\"", "transferTo is not supported yet", "\"", ")", ";", "}", "@", "Override", "public", "long", "transferFrom", "(", "ReadableByteChannel", "src", ",", "long", "position", ",", "long", "count", ")", "throws", "IOException", "{", "throw", "new", "MockIOException", "(", "\"", "transferFrom is not supported yet", "\"", ")", ";", "}", "@", "Override", "public", "MappedByteBuffer", "map", "(", "MapMode", "mode", ",", "long", "position", ",", "long", "size", ")", "throws", "IOException", "{", "throw", "new", "MockIOException", "(", "\"", "MappedByteBuffer mocks are not supported yet", "\"", ")", ";", "}", "@", "Override", "public", "FileLock", "lock", "(", "long", "position", ",", "long", "size", ",", "boolean", "shared", ")", "throws", "IOException", "{", "throw", "new", "MockIOException", "(", "\"", "FileLock mocks are not supported yet", "\"", ")", ";", "}", "@", "Override", "public", "FileLock", "tryLock", "(", "long", "position", ",", "long", "size", ",", "boolean", "shared", ")", "throws", "IOException", "{", "throw", "new", "MockIOException", "(", "\"", "FileLock mocks are not supported yet", "\"", ")", ";", "}", "@", "Override", "protected", "void", "implCloseChannel", "(", ")", "throws", "IOException", "{", "closed", "=", "true", ";", "}", "private", "void", "throwExceptionIfClosed", "(", ")", "throws", "ClosedChannelException", "{", "if", "(", "closed", ")", "{", "throw", "new", "ClosedChannelException", "(", ")", ";", "}", "}", "}" ]
This is not a mock of FileChannel, as FileChannel is an abstract class.
[ "This", "is", "not", "a", "mock", "of", "FileChannel", "as", "FileChannel", "is", "an", "abstract", "class", "." ]
[ "//FIXME mock FileChannel", "// ----- read --------", "//end of stream", "// -------- write ----------", "//------ others --------", "//nothing to do", "// TODO \t\t", "// TODO ", "// TODO ", "// TODO ", "// TODO " ]
[ { "param": "FileChannel", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "FileChannel", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0e3323fa261a2fe4b875088a5a6eafbe64cb3c5e
sdfdzx/RichEditor
editor/src/main/java/com/study/xuan/editor/operate/font/FontParamBuilder.java
[ "Apache-2.0" ]
Java
FontParamBuilder
/** * Author : xuan. * Date : 2017/11/21. * Description :input the description of this file. */
Author : xuan.
[ "Author", ":", "xuan", "." ]
public class FontParamBuilder { private FontParam param; public FontParamBuilder() { param = new FontParam(); } /** * 粗体 */ public FontParamBuilder isBold(boolean isbold) { param.isBold = isbold; return this; } /** * 斜体 */ public FontParamBuilder isItalics(boolean isItalics) { param.isItalics = isItalics; return this; } /** * 下划线 */ public FontParamBuilder isUnderLine(boolean isUnderLine) { param.isUnderLine = isUnderLine; return this; } /** * 中划线 */ public FontParamBuilder isCenterLine(boolean isCenterLine) { param.isCenterLine = isCenterLine; return this; } /** * 是否显示字背景色 */ public FontParamBuilder isFontBac(boolean isFontBac) { param.isFontBac = isFontBac; return this; } /** * 设置字背景色 */ public FontParamBuilder fontBac(int fontBac) { if (param.isFontBac) { param.fontBacColor = fontBac; } return this; } /** * 设置字的字号 */ public FontParamBuilder fontSize(int fontSize) { param.fontSize = fontSize; return this; } /** * 设置字的字色 */ public FontParamBuilder fontColor(int fontColor) { param.fontColor = fontColor; return this; } /** * 设置超链接 */ public FontParamBuilder url(String name, String url) { param.name = name; param.url = url; return this; } /** * 重置所有参数 */ public FontParamBuilder reset() { param.reset(); return this; } public FontParam build() { return param; } /** * 获得字的颜色 */ public int getFontColor() { return param.fontColor; } /** * 获得字的字号 */ public int getFontSize() { return param.fontSize; } }
[ "public", "class", "FontParamBuilder", "{", "private", "FontParam", "param", ";", "public", "FontParamBuilder", "(", ")", "{", "param", "=", "new", "FontParam", "(", ")", ";", "}", "/**\n * 粗体\n */", "public", "FontParamBuilder", "isBold", "(", "boolean", "isbold", ")", "{", "param", ".", "isBold", "=", "isbold", ";", "return", "this", ";", "}", "/**\n * 斜体\n */", "public", "FontParamBuilder", "isItalics", "(", "boolean", "isItalics", ")", "{", "param", ".", "isItalics", "=", "isItalics", ";", "return", "this", ";", "}", "/**\n * 下划线\n */", "public", "FontParamBuilder", "isUnderLine", "(", "boolean", "isUnderLine", ")", "{", "param", ".", "isUnderLine", "=", "isUnderLine", ";", "return", "this", ";", "}", "/**\n * 中划线\n */", "public", "FontParamBuilder", "isCenterLine", "(", "boolean", "isCenterLine", ")", "{", "param", ".", "isCenterLine", "=", "isCenterLine", ";", "return", "this", ";", "}", "/**\n * 是否显示字背景色\n */", "public", "FontParamBuilder", "isFontBac", "(", "boolean", "isFontBac", ")", "{", "param", ".", "isFontBac", "=", "isFontBac", ";", "return", "this", ";", "}", "/**\n * 设置字背景色\n */", "public", "FontParamBuilder", "fontBac", "(", "int", "fontBac", ")", "{", "if", "(", "param", ".", "isFontBac", ")", "{", "param", ".", "fontBacColor", "=", "fontBac", ";", "}", "return", "this", ";", "}", "/**\n * 设置字的字号\n */", "public", "FontParamBuilder", "fontSize", "(", "int", "fontSize", ")", "{", "param", ".", "fontSize", "=", "fontSize", ";", "return", "this", ";", "}", "/**\n * 设置字的字色\n */", "public", "FontParamBuilder", "fontColor", "(", "int", "fontColor", ")", "{", "param", ".", "fontColor", "=", "fontColor", ";", "return", "this", ";", "}", "/**\n * 设置超链接\n */", "public", "FontParamBuilder", "url", "(", "String", "name", ",", "String", "url", ")", "{", "param", ".", "name", "=", "name", ";", "param", ".", "url", "=", "url", ";", "return", "this", ";", "}", "/**\n * 重置所有参数\n */", "public", "FontParamBuilder", "reset", "(", ")", "{", "param", ".", "reset", "(", ")", ";", "return", "this", ";", "}", "public", "FontParam", "build", "(", ")", "{", "return", "param", ";", "}", "/**\n * 获得字的颜色\n */", "public", "int", "getFontColor", "(", ")", "{", "return", "param", ".", "fontColor", ";", "}", "/**\n * 获得字的字号\n */", "public", "int", "getFontSize", "(", ")", "{", "return", "param", ".", "fontSize", ";", "}", "}" ]
Author : xuan.
[ "Author", ":", "xuan", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
0e344c7827d8d8185d3efb98221718cd998f732f
xuziming/mycurator
curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessSemaphoreV2.java
[ "Apache-2.0" ]
Java
InterProcessSemaphoreV2
/** * <p> * A counting semaphore that works across JVMs. All processes in all JVMs that * use the same lock path will achieve an inter-process limited set of leases. * Further, this semaphore is mostly "fair" - each user will get a lease in the * order requested (from ZK's point of view). * </p> * <p> * There are two modes for determining the max leases for the semaphore. In the * first mode the max leases is a convention maintained by the users of a given * path. In the second mode a {@link SharedCountReader} is used as the method * for semaphores of a given path to determine the max leases. * </p> * <p> * If a {@link SharedCountReader} is <b>not</b> used, no internal checks are * done to prevent Process A acting as if there are 10 leases and Process B * acting as if there are 20. Therefore, make sure that all instances in all * processes use the same numberOfLeases value. * </p> * <p> * The various acquire methods return {@link Lease} objects that represent * acquired leases. Clients must take care to close lease objects (ideally in a * <code>finally</code> block) else the lease will be lost. However, if the * client session drops (crash, etc.), any leases held by the client are * automatically closed and made available to other clients. * </p> * <p> * Thanks to Ben Bangert (ben@groovie.org) for the algorithm used. * </p> */
A counting semaphore that works across JVMs. All processes in all JVMs that use the same lock path will achieve an inter-process limited set of leases. Further, this semaphore is mostly "fair" - each user will get a lease in the order requested (from ZK's point of view). There are two modes for determining the max leases for the semaphore. In the first mode the max leases is a convention maintained by the users of a given path. In the second mode a SharedCountReader is used as the method for semaphores of a given path to determine the max leases. If a SharedCountReader is not used, no internal checks are done to prevent Process A acting as if there are 10 leases and Process B acting as if there are 20. Therefore, make sure that all instances in all processes use the same numberOfLeases value. The various acquire methods return Lease objects that represent acquired leases. Clients must take care to close lease objects (ideally in a finally block) else the lease will be lost. However, if the client session drops (crash, etc.), any leases held by the client are automatically closed and made available to other clients. Thanks to Ben Bangert (ben@groovie.org) for the algorithm used.
[ "A", "counting", "semaphore", "that", "works", "across", "JVMs", ".", "All", "processes", "in", "all", "JVMs", "that", "use", "the", "same", "lock", "path", "will", "achieve", "an", "inter", "-", "process", "limited", "set", "of", "leases", ".", "Further", "this", "semaphore", "is", "mostly", "\"", "fair", "\"", "-", "each", "user", "will", "get", "a", "lease", "in", "the", "order", "requested", "(", "from", "ZK", "'", "s", "point", "of", "view", ")", ".", "There", "are", "two", "modes", "for", "determining", "the", "max", "leases", "for", "the", "semaphore", ".", "In", "the", "first", "mode", "the", "max", "leases", "is", "a", "convention", "maintained", "by", "the", "users", "of", "a", "given", "path", ".", "In", "the", "second", "mode", "a", "SharedCountReader", "is", "used", "as", "the", "method", "for", "semaphores", "of", "a", "given", "path", "to", "determine", "the", "max", "leases", ".", "If", "a", "SharedCountReader", "is", "not", "used", "no", "internal", "checks", "are", "done", "to", "prevent", "Process", "A", "acting", "as", "if", "there", "are", "10", "leases", "and", "Process", "B", "acting", "as", "if", "there", "are", "20", ".", "Therefore", "make", "sure", "that", "all", "instances", "in", "all", "processes", "use", "the", "same", "numberOfLeases", "value", ".", "The", "various", "acquire", "methods", "return", "Lease", "objects", "that", "represent", "acquired", "leases", ".", "Clients", "must", "take", "care", "to", "close", "lease", "objects", "(", "ideally", "in", "a", "finally", "block", ")", "else", "the", "lease", "will", "be", "lost", ".", "However", "if", "the", "client", "session", "drops", "(", "crash", "etc", ".", ")", "any", "leases", "held", "by", "the", "client", "are", "automatically", "closed", "and", "made", "available", "to", "other", "clients", ".", "Thanks", "to", "Ben", "Bangert", "(", "ben@groovie", ".", "org", ")", "for", "the", "algorithm", "used", "." ]
public class InterProcessSemaphoreV2 { private final Logger log = LoggerFactory.getLogger(getClass()); private final InterProcessMutex lock; private final WatcherRemoveCuratorFramework client; private final String leasesPath; private final Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { client.postSafeNotify(InterProcessSemaphoreV2.this); } }; private volatile byte[] nodeData; private volatile int maxLeases; private static final String LOCK_PARENT = "locks"; private static final String LEASE_PARENT = "leases"; private static final String LEASE_BASE_NAME = "lease-"; public static final Set<String> LOCK_SCHEMA = Sets.newHashSet(LOCK_PARENT, LEASE_PARENT); /** * @param client the client * @param path path for the semaphore * @param maxLeases the max number of leases to allow for this instance */ public InterProcessSemaphoreV2(CuratorFramework client, String path, int maxLeases) { this(client, path, maxLeases, null); } /** * @param client the client * @param path path for the semaphore * @param count the shared count to use for the max leases */ public InterProcessSemaphoreV2(CuratorFramework client, String path, SharedCountReader count) { this(client, path, 0, count); } private InterProcessSemaphoreV2(CuratorFramework client, String path, int maxLeases, SharedCountReader count) { this.client = client.newWatcherRemoveCuratorFramework(); path = PathUtils.validatePath(path); lock = new InterProcessMutex(client, ZKPaths.makePath(path, LOCK_PARENT)); this.maxLeases = (count != null) ? count.getCount() : maxLeases; leasesPath = ZKPaths.makePath(path, LEASE_PARENT); if (count != null) { count.addListener(new SharedCountListener() { @Override public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception { InterProcessSemaphoreV2.this.maxLeases = newCount; client.postSafeNotify(InterProcessSemaphoreV2.this); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { // no need to handle this here - clients should set their own connection state // listener } }); } } /** * Set the data to put for the node created by this semaphore. This must be * called prior to calling one of the acquire() methods. * * @param nodeData node data */ public void setNodeData(byte[] nodeData) { this.nodeData = (nodeData != null) ? Arrays.copyOf(nodeData, nodeData.length) : null; } /** * Return a list of all current nodes participating in the semaphore * * @return list of nodes * @throws Exception ZK errors, interruptions, etc. */ public Collection<String> getParticipantNodes() throws Exception { return client.getChildren().forPath(leasesPath); } /** * Convenience method. Closes all leases in the given collection of leases * * @param leases leases to close */ public void returnAll(Collection<Lease> leases) { for (Lease l : leases) { CloseableUtils.closeQuietly(l); } } /** * Convenience method. Closes the lease * * @param lease lease to close */ public void returnLease(Lease lease) { CloseableUtils.closeQuietly(lease); } /** * <p> * Acquire a lease. If no leases are available, this method blocks until either * the maximum number of leases is increased or another client/process closes a * lease. * </p> * <p> * The client must close the lease when it is done with it. You should do this * in a <code>finally</code> block. * </p> * * @return the new lease * @throws Exception ZK errors, interruptions, etc. */ public Lease acquire() throws Exception { Collection<Lease> leases = acquire(1, 0, null); return leases.iterator().next(); } /** * <p> * Acquire <code>qty</code> leases. If there are not enough leases available, * this method blocks until either the maximum number of leases is increased * enough or other clients/processes close enough leases. * </p> * <p> * The client must close the leases when it is done with them. You should do * this in a <code>finally</code> block. NOTE: You can use * {@link #returnAll(Collection)} for this. * </p> * * @param qty number of leases to acquire * @return the new leases * @throws Exception ZK errors, interruptions, etc. */ public Collection<Lease> acquire(int qty) throws Exception { return acquire(qty, 0, null); } /** * <p> * Acquire a lease. If no leases are available, this method blocks until either * the maximum number of leases is increased or another client/process closes a * lease. However, this method will only block to a maximum of the time * parameters given. * </p> * <p> * The client must close the lease when it is done with it. You should do this * in a <code>finally</code> block. * </p> * * @param time time to wait * @param unit time unit * @return the new lease or null if time ran out * @throws Exception ZK errors, interruptions, etc. */ public Lease acquire(long time, TimeUnit unit) throws Exception { Collection<Lease> leases = acquire(1, time, unit); return (leases != null) ? leases.iterator().next() : null; } /** * <p> * Acquire <code>qty</code> leases. If there are not enough leases available, * this method blocks until either the maximum number of leases is increased * enough or other clients/processes close enough leases. However, this method * will only block to a maximum of the time parameters given. If time expires * before all leases are acquired, the subset of acquired leases are * automatically closed. * </p> * <p> * The client must close the leases when it is done with them. You should do * this in a <code>finally</code> block. NOTE: You can use * {@link #returnAll(Collection)} for this. * </p> * * @param qty number of leases to acquire * @param time time to wait * @param unit time unit * @return the new leases or null if time ran out * @throws Exception ZK errors, interruptions, etc. */ public Collection<Lease> acquire(int qty, long time, TimeUnit unit) throws Exception { long startMs = System.currentTimeMillis(); boolean hasWait = (unit != null); long waitMs = hasWait ? TimeUnit.MILLISECONDS.convert(time, unit) : 0; Preconditions.checkArgument(qty > 0, "qty cannot be 0"); ImmutableList.Builder<Lease> builder = ImmutableList.builder(); boolean success = false; try { while (qty-- > 0) { int retryCount = 0; long startMillis = System.currentTimeMillis(); boolean isDone = false; while (!isDone) { switch (internalAcquire1Lease(builder, startMs, hasWait, waitMs)) { case CONTINUE: { isDone = true; break; } case RETURN_NULL: { return null; } case RETRY_DUE_TO_MISSING_NODE: { // gets thrown by internalAcquire1Lease when it can't find the lock node // this can happen when the session expires, etc. So, if the retry allows, just // try it all again if (!client.getZookeeperClient().getRetryPolicy().allowRetry(retryCount++, System.currentTimeMillis() - startMillis, RetryLoop.getDefaultRetrySleeper())) { throw new KeeperException.NoNodeException( "Sequential path not found - possible session loss"); } // try again break; } } } } success = true; } finally { if (!success) { returnAll(builder.build()); } } return builder.build(); } private enum InternalAcquireResult { CONTINUE, RETURN_NULL, RETRY_DUE_TO_MISSING_NODE } static volatile CountDownLatch debugAcquireLatch = null; static volatile CountDownLatch debugFailedGetChildrenLatch = null; volatile CountDownLatch debugWaitLatch = null; private InternalAcquireResult internalAcquire1Lease(ImmutableList.Builder<Lease> builder, long startMs, boolean hasWait, long waitMs) throws Exception { if (client.getState() != CuratorFrameworkState.STARTED) { return InternalAcquireResult.RETURN_NULL; } if (hasWait) { long thisWaitMs = getThisWaitMs(startMs, waitMs); if (!lock.acquire(thisWaitMs, TimeUnit.MILLISECONDS)) { return InternalAcquireResult.RETURN_NULL; } } else { lock.acquire(); } Lease lease = null; boolean success = false; try { PathAndBytesable<String> createBuilder = client.create().creatingParentContainersIfNeeded().withProtection() .withMode(CreateMode.EPHEMERAL_SEQUENTIAL); String path = (nodeData != null) ? createBuilder.forPath(ZKPaths.makePath(leasesPath, LEASE_BASE_NAME), nodeData) : createBuilder.forPath(ZKPaths.makePath(leasesPath, LEASE_BASE_NAME)); String nodeName = ZKPaths.getNodeFromPath(path); lease = makeLease(path); if (debugAcquireLatch != null) { debugAcquireLatch.await(); } try { synchronized (this) { for (;;) { List<String> children; try { children = client.getChildren().usingWatcher(watcher).forPath(leasesPath); } catch (Exception e) { if (debugFailedGetChildrenLatch != null) { debugFailedGetChildrenLatch.countDown(); } throw e; } if (!children.contains(nodeName)) { log.error("Sequential path not found: " + path); return InternalAcquireResult.RETRY_DUE_TO_MISSING_NODE; } if (children.size() <= maxLeases) { break; } if (hasWait) { long thisWaitMs = getThisWaitMs(startMs, waitMs); if (thisWaitMs <= 0) { return InternalAcquireResult.RETURN_NULL; } if (debugWaitLatch != null) { debugWaitLatch.countDown(); } wait(thisWaitMs); } else { if (debugWaitLatch != null) { debugWaitLatch.countDown(); } wait(); } } success = true; } } finally { if (!success) { returnLease(lease); } client.removeWatchers(); } } finally { lock.release(); } builder.add(Preconditions.checkNotNull(lease)); return InternalAcquireResult.CONTINUE; } private long getThisWaitMs(long startMs, long waitMs) { long elapsedMs = System.currentTimeMillis() - startMs; return waitMs - elapsedMs; } private Lease makeLease(final String path) { return new Lease() { @Override public void close() throws IOException { try { client.delete().guaranteed().forPath(path); } catch (KeeperException.NoNodeException e) { log.warn("Lease already released", e); } catch (Exception e) { ThreadUtils.checkInterrupted(e); throw new IOException(e); } } @Override public byte[] getData() throws Exception { return client.getData().forPath(path); } @Override public String getNodeName() { return ZKPaths.getNodeFromPath(path); } }; } }
[ "public", "class", "InterProcessSemaphoreV2", "{", "private", "final", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "getClass", "(", ")", ")", ";", "private", "final", "InterProcessMutex", "lock", ";", "private", "final", "WatcherRemoveCuratorFramework", "client", ";", "private", "final", "String", "leasesPath", ";", "private", "final", "Watcher", "watcher", "=", "new", "Watcher", "(", ")", "{", "@", "Override", "public", "void", "process", "(", "WatchedEvent", "event", ")", "{", "client", ".", "postSafeNotify", "(", "InterProcessSemaphoreV2", ".", "this", ")", ";", "}", "}", ";", "private", "volatile", "byte", "[", "]", "nodeData", ";", "private", "volatile", "int", "maxLeases", ";", "private", "static", "final", "String", "LOCK_PARENT", "=", "\"", "locks", "\"", ";", "private", "static", "final", "String", "LEASE_PARENT", "=", "\"", "leases", "\"", ";", "private", "static", "final", "String", "LEASE_BASE_NAME", "=", "\"", "lease-", "\"", ";", "public", "static", "final", "Set", "<", "String", ">", "LOCK_SCHEMA", "=", "Sets", ".", "newHashSet", "(", "LOCK_PARENT", ",", "LEASE_PARENT", ")", ";", "/**\n\t * @param client the client\n\t * @param path path for the semaphore\n\t * @param maxLeases the max number of leases to allow for this instance\n\t */", "public", "InterProcessSemaphoreV2", "(", "CuratorFramework", "client", ",", "String", "path", ",", "int", "maxLeases", ")", "{", "this", "(", "client", ",", "path", ",", "maxLeases", ",", "null", ")", ";", "}", "/**\n\t * @param client the client\n\t * @param path path for the semaphore\n\t * @param count the shared count to use for the max leases\n\t */", "public", "InterProcessSemaphoreV2", "(", "CuratorFramework", "client", ",", "String", "path", ",", "SharedCountReader", "count", ")", "{", "this", "(", "client", ",", "path", ",", "0", ",", "count", ")", ";", "}", "private", "InterProcessSemaphoreV2", "(", "CuratorFramework", "client", ",", "String", "path", ",", "int", "maxLeases", ",", "SharedCountReader", "count", ")", "{", "this", ".", "client", "=", "client", ".", "newWatcherRemoveCuratorFramework", "(", ")", ";", "path", "=", "PathUtils", ".", "validatePath", "(", "path", ")", ";", "lock", "=", "new", "InterProcessMutex", "(", "client", ",", "ZKPaths", ".", "makePath", "(", "path", ",", "LOCK_PARENT", ")", ")", ";", "this", ".", "maxLeases", "=", "(", "count", "!=", "null", ")", "?", "count", ".", "getCount", "(", ")", ":", "maxLeases", ";", "leasesPath", "=", "ZKPaths", ".", "makePath", "(", "path", ",", "LEASE_PARENT", ")", ";", "if", "(", "count", "!=", "null", ")", "{", "count", ".", "addListener", "(", "new", "SharedCountListener", "(", ")", "{", "@", "Override", "public", "void", "countHasChanged", "(", "SharedCountReader", "sharedCount", ",", "int", "newCount", ")", "throws", "Exception", "{", "InterProcessSemaphoreV2", ".", "this", ".", "maxLeases", "=", "newCount", ";", "client", ".", "postSafeNotify", "(", "InterProcessSemaphoreV2", ".", "this", ")", ";", "}", "@", "Override", "public", "void", "stateChanged", "(", "CuratorFramework", "client", ",", "ConnectionState", "newState", ")", "{", "}", "}", ")", ";", "}", "}", "/**\n\t * Set the data to put for the node created by this semaphore. This must be\n\t * called prior to calling one of the acquire() methods.\n\t *\n\t * @param nodeData node data\n\t */", "public", "void", "setNodeData", "(", "byte", "[", "]", "nodeData", ")", "{", "this", ".", "nodeData", "=", "(", "nodeData", "!=", "null", ")", "?", "Arrays", ".", "copyOf", "(", "nodeData", ",", "nodeData", ".", "length", ")", ":", "null", ";", "}", "/**\n\t * Return a list of all current nodes participating in the semaphore\n\t *\n\t * @return list of nodes\n\t * @throws Exception ZK errors, interruptions, etc.\n\t */", "public", "Collection", "<", "String", ">", "getParticipantNodes", "(", ")", "throws", "Exception", "{", "return", "client", ".", "getChildren", "(", ")", ".", "forPath", "(", "leasesPath", ")", ";", "}", "/**\n\t * Convenience method. Closes all leases in the given collection of leases\n\t *\n\t * @param leases leases to close\n\t */", "public", "void", "returnAll", "(", "Collection", "<", "Lease", ">", "leases", ")", "{", "for", "(", "Lease", "l", ":", "leases", ")", "{", "CloseableUtils", ".", "closeQuietly", "(", "l", ")", ";", "}", "}", "/**\n\t * Convenience method. Closes the lease\n\t *\n\t * @param lease lease to close\n\t */", "public", "void", "returnLease", "(", "Lease", "lease", ")", "{", "CloseableUtils", ".", "closeQuietly", "(", "lease", ")", ";", "}", "/**\n\t * <p>\n\t * Acquire a lease. If no leases are available, this method blocks until either\n\t * the maximum number of leases is increased or another client/process closes a\n\t * lease.\n\t * </p>\n\t * <p>\n\t * The client must close the lease when it is done with it. You should do this\n\t * in a <code>finally</code> block.\n\t * </p>\n\t *\n\t * @return the new lease\n\t * @throws Exception ZK errors, interruptions, etc.\n\t */", "public", "Lease", "acquire", "(", ")", "throws", "Exception", "{", "Collection", "<", "Lease", ">", "leases", "=", "acquire", "(", "1", ",", "0", ",", "null", ")", ";", "return", "leases", ".", "iterator", "(", ")", ".", "next", "(", ")", ";", "}", "/**\n\t * <p>\n\t * Acquire <code>qty</code> leases. If there are not enough leases available,\n\t * this method blocks until either the maximum number of leases is increased\n\t * enough or other clients/processes close enough leases.\n\t * </p>\n\t * <p>\n\t * The client must close the leases when it is done with them. You should do\n\t * this in a <code>finally</code> block. NOTE: You can use\n\t * {@link #returnAll(Collection)} for this.\n\t * </p>\n\t *\n\t * @param qty number of leases to acquire\n\t * @return the new leases\n\t * @throws Exception ZK errors, interruptions, etc.\n\t */", "public", "Collection", "<", "Lease", ">", "acquire", "(", "int", "qty", ")", "throws", "Exception", "{", "return", "acquire", "(", "qty", ",", "0", ",", "null", ")", ";", "}", "/**\n\t * <p>\n\t * Acquire a lease. If no leases are available, this method blocks until either\n\t * the maximum number of leases is increased or another client/process closes a\n\t * lease. However, this method will only block to a maximum of the time\n\t * parameters given.\n\t * </p>\n\t * <p>\n\t * The client must close the lease when it is done with it. You should do this\n\t * in a <code>finally</code> block.\n\t * </p>\n\t *\n\t * @param time time to wait\n\t * @param unit time unit\n\t * @return the new lease or null if time ran out\n\t * @throws Exception ZK errors, interruptions, etc.\n\t */", "public", "Lease", "acquire", "(", "long", "time", ",", "TimeUnit", "unit", ")", "throws", "Exception", "{", "Collection", "<", "Lease", ">", "leases", "=", "acquire", "(", "1", ",", "time", ",", "unit", ")", ";", "return", "(", "leases", "!=", "null", ")", "?", "leases", ".", "iterator", "(", ")", ".", "next", "(", ")", ":", "null", ";", "}", "/**\n\t * <p>\n\t * Acquire <code>qty</code> leases. If there are not enough leases available,\n\t * this method blocks until either the maximum number of leases is increased\n\t * enough or other clients/processes close enough leases. However, this method\n\t * will only block to a maximum of the time parameters given. If time expires\n\t * before all leases are acquired, the subset of acquired leases are\n\t * automatically closed.\n\t * </p>\n\t * <p>\n\t * The client must close the leases when it is done with them. You should do\n\t * this in a <code>finally</code> block. NOTE: You can use\n\t * {@link #returnAll(Collection)} for this.\n\t * </p>\n\t *\n\t * @param qty number of leases to acquire\n\t * @param time time to wait\n\t * @param unit time unit\n\t * @return the new leases or null if time ran out\n\t * @throws Exception ZK errors, interruptions, etc.\n\t */", "public", "Collection", "<", "Lease", ">", "acquire", "(", "int", "qty", ",", "long", "time", ",", "TimeUnit", "unit", ")", "throws", "Exception", "{", "long", "startMs", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "boolean", "hasWait", "=", "(", "unit", "!=", "null", ")", ";", "long", "waitMs", "=", "hasWait", "?", "TimeUnit", ".", "MILLISECONDS", ".", "convert", "(", "time", ",", "unit", ")", ":", "0", ";", "Preconditions", ".", "checkArgument", "(", "qty", ">", "0", ",", "\"", "qty cannot be 0", "\"", ")", ";", "ImmutableList", ".", "Builder", "<", "Lease", ">", "builder", "=", "ImmutableList", ".", "builder", "(", ")", ";", "boolean", "success", "=", "false", ";", "try", "{", "while", "(", "qty", "--", ">", "0", ")", "{", "int", "retryCount", "=", "0", ";", "long", "startMillis", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "boolean", "isDone", "=", "false", ";", "while", "(", "!", "isDone", ")", "{", "switch", "(", "internalAcquire1Lease", "(", "builder", ",", "startMs", ",", "hasWait", ",", "waitMs", ")", ")", "{", "case", "CONTINUE", ":", "{", "isDone", "=", "true", ";", "break", ";", "}", "case", "RETURN_NULL", ":", "{", "return", "null", ";", "}", "case", "RETRY_DUE_TO_MISSING_NODE", ":", "{", "if", "(", "!", "client", ".", "getZookeeperClient", "(", ")", ".", "getRetryPolicy", "(", ")", ".", "allowRetry", "(", "retryCount", "++", ",", "System", ".", "currentTimeMillis", "(", ")", "-", "startMillis", ",", "RetryLoop", ".", "getDefaultRetrySleeper", "(", ")", ")", ")", "{", "throw", "new", "KeeperException", ".", "NoNodeException", "(", "\"", "Sequential path not found - possible session loss", "\"", ")", ";", "}", "break", ";", "}", "}", "}", "}", "success", "=", "true", ";", "}", "finally", "{", "if", "(", "!", "success", ")", "{", "returnAll", "(", "builder", ".", "build", "(", ")", ")", ";", "}", "}", "return", "builder", ".", "build", "(", ")", ";", "}", "private", "enum", "InternalAcquireResult", "{", "CONTINUE", ",", "RETURN_NULL", ",", "RETRY_DUE_TO_MISSING_NODE", "}", "static", "volatile", "CountDownLatch", "debugAcquireLatch", "=", "null", ";", "static", "volatile", "CountDownLatch", "debugFailedGetChildrenLatch", "=", "null", ";", "volatile", "CountDownLatch", "debugWaitLatch", "=", "null", ";", "private", "InternalAcquireResult", "internalAcquire1Lease", "(", "ImmutableList", ".", "Builder", "<", "Lease", ">", "builder", ",", "long", "startMs", ",", "boolean", "hasWait", ",", "long", "waitMs", ")", "throws", "Exception", "{", "if", "(", "client", ".", "getState", "(", ")", "!=", "CuratorFrameworkState", ".", "STARTED", ")", "{", "return", "InternalAcquireResult", ".", "RETURN_NULL", ";", "}", "if", "(", "hasWait", ")", "{", "long", "thisWaitMs", "=", "getThisWaitMs", "(", "startMs", ",", "waitMs", ")", ";", "if", "(", "!", "lock", ".", "acquire", "(", "thisWaitMs", ",", "TimeUnit", ".", "MILLISECONDS", ")", ")", "{", "return", "InternalAcquireResult", ".", "RETURN_NULL", ";", "}", "}", "else", "{", "lock", ".", "acquire", "(", ")", ";", "}", "Lease", "lease", "=", "null", ";", "boolean", "success", "=", "false", ";", "try", "{", "PathAndBytesable", "<", "String", ">", "createBuilder", "=", "client", ".", "create", "(", ")", ".", "creatingParentContainersIfNeeded", "(", ")", ".", "withProtection", "(", ")", ".", "withMode", "(", "CreateMode", ".", "EPHEMERAL_SEQUENTIAL", ")", ";", "String", "path", "=", "(", "nodeData", "!=", "null", ")", "?", "createBuilder", ".", "forPath", "(", "ZKPaths", ".", "makePath", "(", "leasesPath", ",", "LEASE_BASE_NAME", ")", ",", "nodeData", ")", ":", "createBuilder", ".", "forPath", "(", "ZKPaths", ".", "makePath", "(", "leasesPath", ",", "LEASE_BASE_NAME", ")", ")", ";", "String", "nodeName", "=", "ZKPaths", ".", "getNodeFromPath", "(", "path", ")", ";", "lease", "=", "makeLease", "(", "path", ")", ";", "if", "(", "debugAcquireLatch", "!=", "null", ")", "{", "debugAcquireLatch", ".", "await", "(", ")", ";", "}", "try", "{", "synchronized", "(", "this", ")", "{", "for", "(", ";", ";", ")", "{", "List", "<", "String", ">", "children", ";", "try", "{", "children", "=", "client", ".", "getChildren", "(", ")", ".", "usingWatcher", "(", "watcher", ")", ".", "forPath", "(", "leasesPath", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "if", "(", "debugFailedGetChildrenLatch", "!=", "null", ")", "{", "debugFailedGetChildrenLatch", ".", "countDown", "(", ")", ";", "}", "throw", "e", ";", "}", "if", "(", "!", "children", ".", "contains", "(", "nodeName", ")", ")", "{", "log", ".", "error", "(", "\"", "Sequential path not found: ", "\"", "+", "path", ")", ";", "return", "InternalAcquireResult", ".", "RETRY_DUE_TO_MISSING_NODE", ";", "}", "if", "(", "children", ".", "size", "(", ")", "<=", "maxLeases", ")", "{", "break", ";", "}", "if", "(", "hasWait", ")", "{", "long", "thisWaitMs", "=", "getThisWaitMs", "(", "startMs", ",", "waitMs", ")", ";", "if", "(", "thisWaitMs", "<=", "0", ")", "{", "return", "InternalAcquireResult", ".", "RETURN_NULL", ";", "}", "if", "(", "debugWaitLatch", "!=", "null", ")", "{", "debugWaitLatch", ".", "countDown", "(", ")", ";", "}", "wait", "(", "thisWaitMs", ")", ";", "}", "else", "{", "if", "(", "debugWaitLatch", "!=", "null", ")", "{", "debugWaitLatch", ".", "countDown", "(", ")", ";", "}", "wait", "(", ")", ";", "}", "}", "success", "=", "true", ";", "}", "}", "finally", "{", "if", "(", "!", "success", ")", "{", "returnLease", "(", "lease", ")", ";", "}", "client", ".", "removeWatchers", "(", ")", ";", "}", "}", "finally", "{", "lock", ".", "release", "(", ")", ";", "}", "builder", ".", "add", "(", "Preconditions", ".", "checkNotNull", "(", "lease", ")", ")", ";", "return", "InternalAcquireResult", ".", "CONTINUE", ";", "}", "private", "long", "getThisWaitMs", "(", "long", "startMs", ",", "long", "waitMs", ")", "{", "long", "elapsedMs", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "startMs", ";", "return", "waitMs", "-", "elapsedMs", ";", "}", "private", "Lease", "makeLease", "(", "final", "String", "path", ")", "{", "return", "new", "Lease", "(", ")", "{", "@", "Override", "public", "void", "close", "(", ")", "throws", "IOException", "{", "try", "{", "client", ".", "delete", "(", ")", ".", "guaranteed", "(", ")", ".", "forPath", "(", "path", ")", ";", "}", "catch", "(", "KeeperException", ".", "NoNodeException", "e", ")", "{", "log", ".", "warn", "(", "\"", "Lease already released", "\"", ",", "e", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "ThreadUtils", ".", "checkInterrupted", "(", "e", ")", ";", "throw", "new", "IOException", "(", "e", ")", ";", "}", "}", "@", "Override", "public", "byte", "[", "]", "getData", "(", ")", "throws", "Exception", "{", "return", "client", ".", "getData", "(", ")", ".", "forPath", "(", "path", ")", ";", "}", "@", "Override", "public", "String", "getNodeName", "(", ")", "{", "return", "ZKPaths", ".", "getNodeFromPath", "(", "path", ")", ";", "}", "}", ";", "}", "}" ]
<p> A counting semaphore that works across JVMs.
[ "<p", ">", "A", "counting", "semaphore", "that", "works", "across", "JVMs", "." ]
[ "// no need to handle this here - clients should set their own connection state", "// listener", "// gets thrown by internalAcquire1Lease when it can't find the lock node", "// this can happen when the session expires, etc. So, if the retry allows, just", "// try it all again", "// try again" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
0e3688e428c3d65ec8f5c67ff6f896c9a66a69af
istudens/mjolnir-archive-service
core/src/main/java/org/jboss/set/mjolnir/archive/github/GitHubMembershipBean.java
[ "Apache-2.0" ]
Java
GitHubMembershipBean
/** * Provides user membership management capabilities. */
Provides user membership management capabilities.
[ "Provides", "user", "membership", "management", "capabilities", "." ]
public class GitHubMembershipBean { private final Logger logger = Logger.getLogger(getClass()); private final CustomizedTeamService teamService; private final OrganizationService organizationService; private final EntityManager em; @Inject public GitHubMembershipBean(GitHubClient client, EntityManager em) { teamService = new CustomizedTeamService(client); organizationService = new OrganizationService(client); this.em = em; } /** * Find teams for given organization filter ones in which user got membership and then removes users membership. * * @param gitHubTeam github team * @param gitHubUsername github username */ public void removeUserFromTeam(UserRemoval removal, GitHubTeam gitHubTeam, String gitHubUsername) throws IOException { if (isMember(gitHubUsername, gitHubTeam)) { logger.infof("Removing membership of user %s in team %s", gitHubUsername, gitHubTeam.getName()); try { teamService.removeMember(gitHubTeam.getGithubId(), gitHubUsername); logUnsubscribedTeam(removal, gitHubUsername, gitHubTeam, UnsubscribeStatus.COMPLETED); } catch (IOException e) { logUnsubscribedTeam(removal, gitHubUsername, gitHubTeam, UnsubscribeStatus.FAILED); throw e; } } else { logger.infof("User %s is not a member of team %s", gitHubUsername, gitHubTeam.getName()); } } /** * Removes user's membership in given organization. * * @param organization organization to remove user from * @param gitHubUsername github username */ public void removeUserFromOrganization(UserRemoval removal, GitHubOrganization organization, String gitHubUsername) throws IOException { logger.infof("Removing user %s from organization %s", gitHubUsername, organization.getName()); if (organizationService.isMember(organization.getName(), gitHubUsername)) { try { organizationService.removeMember(organization.getName(), gitHubUsername); logUnsubscribedOrg(removal, gitHubUsername, organization, UnsubscribeStatus.COMPLETED); } catch (IOException e) { logUnsubscribedOrg(removal, gitHubUsername, organization, UnsubscribeStatus.FAILED); throw e; } } } /** * Retrieves members of all organization teams. */ public Map<GitHubTeam, List<User>> getAllTeamsMembers(GitHubOrganization organization) throws IOException { HashMap<GitHubTeam, List<User>> map = new HashMap<>(); for (GitHubTeam team : organization.getTeams()) { List<User> members = teamService.getMembers(organization.getName(), team.getGithubId()); if (members.size() > 0) { map.put(team, members); } } return map; } /** * Retrieves members of a GH team. */ public List<User> getTeamsMembers(GitHubTeam team) throws IOException { return teamService.getMembers(team.getOrganization().getName(), team.getGithubId()); } /** * Retrieves members of an organization. */ public Collection<User> getOrganizationMembers(GitHubOrganization organization) throws IOException { return organizationService.getMembers(organization.getName()); } public boolean isMember(String githubUser, GitHubTeam team) throws IOException { return teamService.isMember(team.getGithubId(), githubUser); } private void logUnsubscribedTeam(UserRemoval removal, String gitHubUsername, GitHubTeam team, UnsubscribeStatus status) { UnsubscribedUserFromTeam unsubscribedUserFromTeam = new UnsubscribedUserFromTeam(); unsubscribedUserFromTeam.setUserRemoval(removal); unsubscribedUserFromTeam.setGithubUsername(gitHubUsername); unsubscribedUserFromTeam.setGithubTeamName(team.getName()); unsubscribedUserFromTeam.setGithubOrgName(team.getOrganization().getName()); unsubscribedUserFromTeam.setStatus(status); em.persist(unsubscribedUserFromTeam); } private void logUnsubscribedOrg(UserRemoval removal, String gitHubUsername, GitHubOrganization org, UnsubscribeStatus status) { UnsubscribedUserFromOrg unsubscribedUserFromOrg = new UnsubscribedUserFromOrg(); unsubscribedUserFromOrg.setUserRemoval(removal); unsubscribedUserFromOrg.setGithubUsername(gitHubUsername); unsubscribedUserFromOrg.setGithubOrgName(org.getName()); unsubscribedUserFromOrg.setStatus(status); em.persist(unsubscribedUserFromOrg); } }
[ "public", "class", "GitHubMembershipBean", "{", "private", "final", "Logger", "logger", "=", "Logger", ".", "getLogger", "(", "getClass", "(", ")", ")", ";", "private", "final", "CustomizedTeamService", "teamService", ";", "private", "final", "OrganizationService", "organizationService", ";", "private", "final", "EntityManager", "em", ";", "@", "Inject", "public", "GitHubMembershipBean", "(", "GitHubClient", "client", ",", "EntityManager", "em", ")", "{", "teamService", "=", "new", "CustomizedTeamService", "(", "client", ")", ";", "organizationService", "=", "new", "OrganizationService", "(", "client", ")", ";", "this", ".", "em", "=", "em", ";", "}", "/**\n * Find teams for given organization filter ones in which user got membership and then removes users membership.\n *\n * @param gitHubTeam github team\n * @param gitHubUsername github username\n */", "public", "void", "removeUserFromTeam", "(", "UserRemoval", "removal", ",", "GitHubTeam", "gitHubTeam", ",", "String", "gitHubUsername", ")", "throws", "IOException", "{", "if", "(", "isMember", "(", "gitHubUsername", ",", "gitHubTeam", ")", ")", "{", "logger", ".", "infof", "(", "\"", "Removing membership of user %s in team %s", "\"", ",", "gitHubUsername", ",", "gitHubTeam", ".", "getName", "(", ")", ")", ";", "try", "{", "teamService", ".", "removeMember", "(", "gitHubTeam", ".", "getGithubId", "(", ")", ",", "gitHubUsername", ")", ";", "logUnsubscribedTeam", "(", "removal", ",", "gitHubUsername", ",", "gitHubTeam", ",", "UnsubscribeStatus", ".", "COMPLETED", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logUnsubscribedTeam", "(", "removal", ",", "gitHubUsername", ",", "gitHubTeam", ",", "UnsubscribeStatus", ".", "FAILED", ")", ";", "throw", "e", ";", "}", "}", "else", "{", "logger", ".", "infof", "(", "\"", "User %s is not a member of team %s", "\"", ",", "gitHubUsername", ",", "gitHubTeam", ".", "getName", "(", ")", ")", ";", "}", "}", "/**\n * Removes user's membership in given organization.\n *\n * @param organization organization to remove user from\n * @param gitHubUsername github username\n */", "public", "void", "removeUserFromOrganization", "(", "UserRemoval", "removal", ",", "GitHubOrganization", "organization", ",", "String", "gitHubUsername", ")", "throws", "IOException", "{", "logger", ".", "infof", "(", "\"", "Removing user %s from organization %s", "\"", ",", "gitHubUsername", ",", "organization", ".", "getName", "(", ")", ")", ";", "if", "(", "organizationService", ".", "isMember", "(", "organization", ".", "getName", "(", ")", ",", "gitHubUsername", ")", ")", "{", "try", "{", "organizationService", ".", "removeMember", "(", "organization", ".", "getName", "(", ")", ",", "gitHubUsername", ")", ";", "logUnsubscribedOrg", "(", "removal", ",", "gitHubUsername", ",", "organization", ",", "UnsubscribeStatus", ".", "COMPLETED", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logUnsubscribedOrg", "(", "removal", ",", "gitHubUsername", ",", "organization", ",", "UnsubscribeStatus", ".", "FAILED", ")", ";", "throw", "e", ";", "}", "}", "}", "/**\n * Retrieves members of all organization teams.\n */", "public", "Map", "<", "GitHubTeam", ",", "List", "<", "User", ">", ">", "getAllTeamsMembers", "(", "GitHubOrganization", "organization", ")", "throws", "IOException", "{", "HashMap", "<", "GitHubTeam", ",", "List", "<", "User", ">", ">", "map", "=", "new", "HashMap", "<", ">", "(", ")", ";", "for", "(", "GitHubTeam", "team", ":", "organization", ".", "getTeams", "(", ")", ")", "{", "List", "<", "User", ">", "members", "=", "teamService", ".", "getMembers", "(", "organization", ".", "getName", "(", ")", ",", "team", ".", "getGithubId", "(", ")", ")", ";", "if", "(", "members", ".", "size", "(", ")", ">", "0", ")", "{", "map", ".", "put", "(", "team", ",", "members", ")", ";", "}", "}", "return", "map", ";", "}", "/**\n * Retrieves members of a GH team.\n */", "public", "List", "<", "User", ">", "getTeamsMembers", "(", "GitHubTeam", "team", ")", "throws", "IOException", "{", "return", "teamService", ".", "getMembers", "(", "team", ".", "getOrganization", "(", ")", ".", "getName", "(", ")", ",", "team", ".", "getGithubId", "(", ")", ")", ";", "}", "/**\n * Retrieves members of an organization.\n */", "public", "Collection", "<", "User", ">", "getOrganizationMembers", "(", "GitHubOrganization", "organization", ")", "throws", "IOException", "{", "return", "organizationService", ".", "getMembers", "(", "organization", ".", "getName", "(", ")", ")", ";", "}", "public", "boolean", "isMember", "(", "String", "githubUser", ",", "GitHubTeam", "team", ")", "throws", "IOException", "{", "return", "teamService", ".", "isMember", "(", "team", ".", "getGithubId", "(", ")", ",", "githubUser", ")", ";", "}", "private", "void", "logUnsubscribedTeam", "(", "UserRemoval", "removal", ",", "String", "gitHubUsername", ",", "GitHubTeam", "team", ",", "UnsubscribeStatus", "status", ")", "{", "UnsubscribedUserFromTeam", "unsubscribedUserFromTeam", "=", "new", "UnsubscribedUserFromTeam", "(", ")", ";", "unsubscribedUserFromTeam", ".", "setUserRemoval", "(", "removal", ")", ";", "unsubscribedUserFromTeam", ".", "setGithubUsername", "(", "gitHubUsername", ")", ";", "unsubscribedUserFromTeam", ".", "setGithubTeamName", "(", "team", ".", "getName", "(", ")", ")", ";", "unsubscribedUserFromTeam", ".", "setGithubOrgName", "(", "team", ".", "getOrganization", "(", ")", ".", "getName", "(", ")", ")", ";", "unsubscribedUserFromTeam", ".", "setStatus", "(", "status", ")", ";", "em", ".", "persist", "(", "unsubscribedUserFromTeam", ")", ";", "}", "private", "void", "logUnsubscribedOrg", "(", "UserRemoval", "removal", ",", "String", "gitHubUsername", ",", "GitHubOrganization", "org", ",", "UnsubscribeStatus", "status", ")", "{", "UnsubscribedUserFromOrg", "unsubscribedUserFromOrg", "=", "new", "UnsubscribedUserFromOrg", "(", ")", ";", "unsubscribedUserFromOrg", ".", "setUserRemoval", "(", "removal", ")", ";", "unsubscribedUserFromOrg", ".", "setGithubUsername", "(", "gitHubUsername", ")", ";", "unsubscribedUserFromOrg", ".", "setGithubOrgName", "(", "org", ".", "getName", "(", ")", ")", ";", "unsubscribedUserFromOrg", ".", "setStatus", "(", "status", ")", ";", "em", ".", "persist", "(", "unsubscribedUserFromOrg", ")", ";", "}", "}" ]
Provides user membership management capabilities.
[ "Provides", "user", "membership", "management", "capabilities", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
0e3ad2e7e1eb14495ced1502a3bce04219d4faeb
shenhaizhilong/algorithm
src/main/java/com/hui/Tree/CheckCompletenessofaBinaryTree.java
[ "BSD-3-Clause" ]
Java
CheckCompletenessofaBinaryTree
/** * @author: shenhaizhilong * @date: 2018/12/26 13:57 * *958. Check Completeness of a Binary Tree * DescriptionHintsSubmissionsDiscussSolution * Given a binary tree, determine if it is a complete binary tree. * * Definition of a complete binary tree from Wikipedia: * In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. * * * * Example 1: * * * * Input: [1,2,3,4,5,6] * Output: true * Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible. * Example 2: * * * * Input: [1,2,3,4,5,null,7] * Output: false * Explanation: The node with value 7 isn't as far left as possible. * * Note: * * The tree will have between 1 and 100 nodes. * */
958. Check Completeness of a Binary Tree DescriptionHintsSubmissionsDiscussSolution Given a binary tree, determine if it is a complete binary tree. Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Example 1. [1,2,3,4,5,6] Output: true Explanation: Every level before the last is full , and all nodes in the last level ({4, 5, 6}) are as far left as possible. Example 2. [1,2,3,4,5,null,7] Output: false Explanation: The node with value 7 isn't as far left as possible. The tree will have between 1 and 100 nodes.
[ "958", ".", "Check", "Completeness", "of", "a", "Binary", "Tree", "DescriptionHintsSubmissionsDiscussSolution", "Given", "a", "binary", "tree", "determine", "if", "it", "is", "a", "complete", "binary", "tree", ".", "Definition", "of", "a", "complete", "binary", "tree", "from", "Wikipedia", ":", "In", "a", "complete", "binary", "tree", "every", "level", "except", "possibly", "the", "last", "is", "completely", "filled", "and", "all", "nodes", "in", "the", "last", "level", "are", "as", "far", "left", "as", "possible", ".", "It", "can", "have", "between", "1", "and", "2h", "nodes", "inclusive", "at", "the", "last", "level", "h", ".", "Example", "1", ".", "[", "1", "2", "3", "4", "5", "6", "]", "Output", ":", "true", "Explanation", ":", "Every", "level", "before", "the", "last", "is", "full", "and", "all", "nodes", "in", "the", "last", "level", "(", "{", "4", "5", "6", "}", ")", "are", "as", "far", "left", "as", "possible", ".", "Example", "2", ".", "[", "1", "2", "3", "4", "5", "null", "7", "]", "Output", ":", "false", "Explanation", ":", "The", "node", "with", "value", "7", "isn", "'", "t", "as", "far", "left", "as", "possible", ".", "The", "tree", "will", "have", "between", "1", "and", "100", "nodes", "." ]
public class CheckCompletenessofaBinaryTree { //https://leetcode.com/problems/check-completeness-of-a-binary-tree/discuss/205682/JavaC++Python-BFS-Level-Order-Traversal //Use BFS to do a level order traversal, //add childrens to the bfs queue, //until we met the first empty node. // //For a complete binary tree, //there should not be any node after we met an empty one. public boolean isCompleteTree(TreeNode root) { if(root == null)return true; LinkedList<TreeNode> queue = new LinkedList<>(); queue.addLast(root); while (queue.peekFirst() != null) { TreeNode curr = queue.pollFirst(); // Optimization if(curr.left == null && curr.right != null)return false; queue.addLast(curr.left); queue.addLast(curr.right); } while (!queue.isEmpty() && queue.peekFirst() == null) { queue.pollFirst(); } return queue.isEmpty(); } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } }
[ "public", "class", "CheckCompletenessofaBinaryTree", "{", "public", "boolean", "isCompleteTree", "(", "TreeNode", "root", ")", "{", "if", "(", "root", "==", "null", ")", "return", "true", ";", "LinkedList", "<", "TreeNode", ">", "queue", "=", "new", "LinkedList", "<", ">", "(", ")", ";", "queue", ".", "addLast", "(", "root", ")", ";", "while", "(", "queue", ".", "peekFirst", "(", ")", "!=", "null", ")", "{", "TreeNode", "curr", "=", "queue", ".", "pollFirst", "(", ")", ";", "if", "(", "curr", ".", "left", "==", "null", "&&", "curr", ".", "right", "!=", "null", ")", "return", "false", ";", "queue", ".", "addLast", "(", "curr", ".", "left", ")", ";", "queue", ".", "addLast", "(", "curr", ".", "right", ")", ";", "}", "while", "(", "!", "queue", ".", "isEmpty", "(", ")", "&&", "queue", ".", "peekFirst", "(", ")", "==", "null", ")", "{", "queue", ".", "pollFirst", "(", ")", ";", "}", "return", "queue", ".", "isEmpty", "(", ")", ";", "}", "public", "class", "TreeNode", "{", "int", "val", ";", "TreeNode", "left", ";", "TreeNode", "right", ";", "TreeNode", "(", "int", "x", ")", "{", "val", "=", "x", ";", "}", "}", "}" ]
@author: shenhaizhilong @date: 2018/12/26 13:57
[ "@author", ":", "shenhaizhilong", "@date", ":", "2018", "/", "12", "/", "26", "13", ":", "57" ]
[ "//https://leetcode.com/problems/check-completeness-of-a-binary-tree/discuss/205682/JavaC++Python-BFS-Level-Order-Traversal\r", "//Use BFS to do a level order traversal,\r", "//add childrens to the bfs queue,\r", "//until we met the first empty node.\r", "//\r", "//For a complete binary tree,\r", "//there should not be any node after we met an empty one.\r", "// Optimization\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
0e3da3c771074619ad0aedaaa640ad5704201352
loonwerks/AGREE
edu.uah.rsesc.aadlsimulator.agree/src/edu/uah/rsesc/aadlsimulator/agree/engine/InputConstraintToLustreConstraintExpression.java
[ "BSD-3-Clause" ]
Java
InputConstraintToLustreConstraintExpression
/** * Builds an expression which is true if a constraint for a specified variable is satisfied. */
Builds an expression which is true if a constraint for a specified variable is satisfied.
[ "Builds", "an", "expression", "which", "is", "true", "if", "a", "constraint", "for", "a", "specified", "variable", "is", "satisfied", "." ]
public class InputConstraintToLustreConstraintExpression { private final InputConstraintToLustreValueExpression innerExprEvaluator; private Expr constrainedVariableExpr; private final InputConstraintSwitch<Expr> evalSwitch = new InputConstraintSwitch<Expr>() { @Override public Expr caseIntervalExpression(final IntervalExpression object) { // Build an expression that is true if the constrained value is in the interval // It is guaranteed that at least one of left/right will be valid. Expr expr = null; if(object.getLeft() != null) { final BinaryOp op = object.isRightClosed() ? BinaryOp.GREATEREQUAL : BinaryOp.GREATER; expr = new BinaryExpr(constrainedVariableExpr, op, innerExprEvaluator.eval(object.getLeft())); } if(object.getRight() != null) { final BinaryOp op = object.isRightClosed() ? BinaryOp.LESSEQUAL : BinaryOp.LESS; final Expr rightExpr = new BinaryExpr(constrainedVariableExpr, op, innerExprEvaluator.eval(object.getRight())); if(expr == null) { expr = rightExpr; } else { expr = new BinaryExpr(expr, BinaryOp.AND, rightExpr); } } return expr; } @Override public Expr caseSetExpression(final SetExpression object) { // Build an expression which is true if the constrained value matches any of the values in the set. Expr expr = null; for(final ScalarExpression se : object.getMembers()) { final Expr newExpr = new BinaryExpr(constrainedVariableExpr, BinaryOp.EQUAL, innerExprEvaluator.eval(se)); if(expr == null) { expr = newExpr; } else { expr = new BinaryExpr(expr, BinaryOp.OR, newExpr); } } return expr; } @Override public Expr caseScalarExpression(final ScalarExpression object) { return new BinaryExpr(constrainedVariableExpr, BinaryOp.EQUAL, innerExprEvaluator.eval(object)); } }; public InputConstraintToLustreConstraintExpression(final ReferenceEvaluator referenceEvaluator) { this.innerExprEvaluator = new InputConstraintToLustreValueExpression(Objects.requireNonNull(referenceEvaluator, "referenceEvaluator must not be null")); } public Expr eval(final InputConstraint ic, final Expr constrainedVariableExpr) { this.constrainedVariableExpr = Objects.requireNonNull(constrainedVariableExpr, "constrainedVariableId must not be null"); return evalSwitch.doSwitch(ic); } }
[ "public", "class", "InputConstraintToLustreConstraintExpression", "{", "private", "final", "InputConstraintToLustreValueExpression", "innerExprEvaluator", ";", "private", "Expr", "constrainedVariableExpr", ";", "private", "final", "InputConstraintSwitch", "<", "Expr", ">", "evalSwitch", "=", "new", "InputConstraintSwitch", "<", "Expr", ">", "(", ")", "{", "@", "Override", "public", "Expr", "caseIntervalExpression", "(", "final", "IntervalExpression", "object", ")", "{", "Expr", "expr", "=", "null", ";", "if", "(", "object", ".", "getLeft", "(", ")", "!=", "null", ")", "{", "final", "BinaryOp", "op", "=", "object", ".", "isRightClosed", "(", ")", "?", "BinaryOp", ".", "GREATEREQUAL", ":", "BinaryOp", ".", "GREATER", ";", "expr", "=", "new", "BinaryExpr", "(", "constrainedVariableExpr", ",", "op", ",", "innerExprEvaluator", ".", "eval", "(", "object", ".", "getLeft", "(", ")", ")", ")", ";", "}", "if", "(", "object", ".", "getRight", "(", ")", "!=", "null", ")", "{", "final", "BinaryOp", "op", "=", "object", ".", "isRightClosed", "(", ")", "?", "BinaryOp", ".", "LESSEQUAL", ":", "BinaryOp", ".", "LESS", ";", "final", "Expr", "rightExpr", "=", "new", "BinaryExpr", "(", "constrainedVariableExpr", ",", "op", ",", "innerExprEvaluator", ".", "eval", "(", "object", ".", "getRight", "(", ")", ")", ")", ";", "if", "(", "expr", "==", "null", ")", "{", "expr", "=", "rightExpr", ";", "}", "else", "{", "expr", "=", "new", "BinaryExpr", "(", "expr", ",", "BinaryOp", ".", "AND", ",", "rightExpr", ")", ";", "}", "}", "return", "expr", ";", "}", "@", "Override", "public", "Expr", "caseSetExpression", "(", "final", "SetExpression", "object", ")", "{", "Expr", "expr", "=", "null", ";", "for", "(", "final", "ScalarExpression", "se", ":", "object", ".", "getMembers", "(", ")", ")", "{", "final", "Expr", "newExpr", "=", "new", "BinaryExpr", "(", "constrainedVariableExpr", ",", "BinaryOp", ".", "EQUAL", ",", "innerExprEvaluator", ".", "eval", "(", "se", ")", ")", ";", "if", "(", "expr", "==", "null", ")", "{", "expr", "=", "newExpr", ";", "}", "else", "{", "expr", "=", "new", "BinaryExpr", "(", "expr", ",", "BinaryOp", ".", "OR", ",", "newExpr", ")", ";", "}", "}", "return", "expr", ";", "}", "@", "Override", "public", "Expr", "caseScalarExpression", "(", "final", "ScalarExpression", "object", ")", "{", "return", "new", "BinaryExpr", "(", "constrainedVariableExpr", ",", "BinaryOp", ".", "EQUAL", ",", "innerExprEvaluator", ".", "eval", "(", "object", ")", ")", ";", "}", "}", ";", "public", "InputConstraintToLustreConstraintExpression", "(", "final", "ReferenceEvaluator", "referenceEvaluator", ")", "{", "this", ".", "innerExprEvaluator", "=", "new", "InputConstraintToLustreValueExpression", "(", "Objects", ".", "requireNonNull", "(", "referenceEvaluator", ",", "\"", "referenceEvaluator must not be null", "\"", ")", ")", ";", "}", "public", "Expr", "eval", "(", "final", "InputConstraint", "ic", ",", "final", "Expr", "constrainedVariableExpr", ")", "{", "this", ".", "constrainedVariableExpr", "=", "Objects", ".", "requireNonNull", "(", "constrainedVariableExpr", ",", "\"", "constrainedVariableId must not be null", "\"", ")", ";", "return", "evalSwitch", ".", "doSwitch", "(", "ic", ")", ";", "}", "}" ]
Builds an expression which is true if a constraint for a specified variable is satisfied.
[ "Builds", "an", "expression", "which", "is", "true", "if", "a", "constraint", "for", "a", "specified", "variable", "is", "satisfied", "." ]
[ "// Build an expression that is true if the constrained value is in the interval", "// It is guaranteed that at least one of left/right will be valid.", "// Build an expression which is true if the constrained value matches any of the values in the set." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
0e4062e7111250d9eee2e9a8c6dbade3faeeb633
CSA-PLLab/STAND
src/chord/analyses/method/DomM.java
[ "BSD-3-Clause" ]
Java
DomM
/** * Domain of methods. * <p> * The 0th element in this domain is the main method of the program. * <p> * The 1st element in this domain is the <tt>start()</tt> method of class <tt>java.lang.Thread</tt>, * if this method is reachable from the main method of the program. * <p> * The above two methods are the entry-point methods of the implicitly created main thread and each * explicitly created thread, respectively. Due to Chord's emphasis on concurrency, these methods * are referenced frequently by various pre-defined program analyses expressed in Datalog, and giving * them special indices makes it convenient to reference them in those analyses. * * @author Mayur Naik (mhn@cs.stanford.edu) */
Domain of methods. The 0th element in this domain is the main method of the program. The 1st element in this domain is the start() method of class java.lang.Thread, if this method is reachable from the main method of the program. The above two methods are the entry-point methods of the implicitly created main thread and each explicitly created thread, respectively. Due to Chord's emphasis on concurrency, these methods are referenced frequently by various pre-defined program analyses expressed in Datalog, and giving them special indices makes it convenient to reference them in those analyses.
[ "Domain", "of", "methods", ".", "The", "0th", "element", "in", "this", "domain", "is", "the", "main", "method", "of", "the", "program", ".", "The", "1st", "element", "in", "this", "domain", "is", "the", "start", "()", "method", "of", "class", "java", ".", "lang", ".", "Thread", "if", "this", "method", "is", "reachable", "from", "the", "main", "method", "of", "the", "program", ".", "The", "above", "two", "methods", "are", "the", "entry", "-", "point", "methods", "of", "the", "implicitly", "created", "main", "thread", "and", "each", "explicitly", "created", "thread", "respectively", ".", "Due", "to", "Chord", "'", "s", "emphasis", "on", "concurrency", "these", "methods", "are", "referenced", "frequently", "by", "various", "pre", "-", "defined", "program", "analyses", "expressed", "in", "Datalog", "and", "giving", "them", "special", "indices", "makes", "it", "convenient", "to", "reference", "them", "in", "those", "analyses", "." ]
@Chord(name = "M") public class DomM extends ProgramDom<jq_Method> implements IMethodVisitor { @Override public void init() { // Reserve index 0 for the main method of the program. // Reserve index 1 for the start() method of java.lang.Thread if it exists. Program program = Program.g(); jq_Method mainMethod = program.getMainMethod(); assert (mainMethod != null); getOrAdd(mainMethod); jq_Method startMethod = program.getThreadStartMethod(); if (startMethod != null) getOrAdd(startMethod); } @Override public void visit(jq_Class c) { } @Override public void visit(jq_Method m) { getOrAdd(m); } @Override public String toXMLAttrsString(jq_Method m) { jq_Class c = m.getDeclaringClass(); String methName = m.getName().toString(); String sign = c.getName() + "."; if (methName.equals("<init>")) sign += "&lt;init&gt;"; else if (methName.equals("<clinit>")) sign += "&lt;clinit&gt;"; else sign += methName; String desc = m.getDesc().toString(); String args = desc.substring(1, desc.indexOf(')')); sign += "(" + Program.typesToStr(args) + ")"; String file = c.getSourceFileName(); int line = m.getLineNumber(0); return "sign=\"" + sign + "\" file=\"" + file + "\" line=\"" + line + "\""; } }
[ "@", "Chord", "(", "name", "=", "\"", "M", "\"", ")", "public", "class", "DomM", "extends", "ProgramDom", "<", "jq_Method", ">", "implements", "IMethodVisitor", "{", "@", "Override", "public", "void", "init", "(", ")", "{", "Program", "program", "=", "Program", ".", "g", "(", ")", ";", "jq_Method", "mainMethod", "=", "program", ".", "getMainMethod", "(", ")", ";", "assert", "(", "mainMethod", "!=", "null", ")", ";", "getOrAdd", "(", "mainMethod", ")", ";", "jq_Method", "startMethod", "=", "program", ".", "getThreadStartMethod", "(", ")", ";", "if", "(", "startMethod", "!=", "null", ")", "getOrAdd", "(", "startMethod", ")", ";", "}", "@", "Override", "public", "void", "visit", "(", "jq_Class", "c", ")", "{", "}", "@", "Override", "public", "void", "visit", "(", "jq_Method", "m", ")", "{", "getOrAdd", "(", "m", ")", ";", "}", "@", "Override", "public", "String", "toXMLAttrsString", "(", "jq_Method", "m", ")", "{", "jq_Class", "c", "=", "m", ".", "getDeclaringClass", "(", ")", ";", "String", "methName", "=", "m", ".", "getName", "(", ")", ".", "toString", "(", ")", ";", "String", "sign", "=", "c", ".", "getName", "(", ")", "+", "\"", ".", "\"", ";", "if", "(", "methName", ".", "equals", "(", "\"", "<init>", "\"", ")", ")", "sign", "+=", "\"", "&lt;init&gt;", "\"", ";", "else", "if", "(", "methName", ".", "equals", "(", "\"", "<clinit>", "\"", ")", ")", "sign", "+=", "\"", "&lt;clinit&gt;", "\"", ";", "else", "sign", "+=", "methName", ";", "String", "desc", "=", "m", ".", "getDesc", "(", ")", ".", "toString", "(", ")", ";", "String", "args", "=", "desc", ".", "substring", "(", "1", ",", "desc", ".", "indexOf", "(", "')'", ")", ")", ";", "sign", "+=", "\"", "(", "\"", "+", "Program", ".", "typesToStr", "(", "args", ")", "+", "\"", ")", "\"", ";", "String", "file", "=", "c", ".", "getSourceFileName", "(", ")", ";", "int", "line", "=", "m", ".", "getLineNumber", "(", "0", ")", ";", "return", "\"", "sign=", "\\\"", "\"", "+", "sign", "+", "\"", "\\\"", " file=", "\\\"", "\"", "+", "file", "+", "\"", "\\\"", " line=", "\\\"", "\"", "+", "line", "+", "\"", "\\\"", "\"", ";", "}", "}" ]
Domain of methods.
[ "Domain", "of", "methods", "." ]
[ "// Reserve index 0 for the main method of the program.\r", "// Reserve index 1 for the start() method of java.lang.Thread if it exists.\r" ]
[ { "param": "IMethodVisitor", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IMethodVisitor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0e45d71213bcadd08a846bb2afdfa013e8fb9b92
ShekharUllah06/user-management-tool
upwork/Internet Mediatech/Web App/PortaleDipendenti/src/java/com/logicaldoc/enterprise/webservice/soap/endpoint/Exception.java
[ "MIT" ]
Java
Exception
/** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.2 * */
This class was generated by the JAX-WS RI.
[ "This", "class", "was", "generated", "by", "the", "JAX", "-", "WS", "RI", "." ]
@WebFault(name = "Exception", targetNamespace = "http://ws.logicaldoc.com") public class Exception extends java.lang.Exception { /** * Java type that goes as soapenv:Fault detail element. * */ private com.logicaldoc.ws.Exception faultInfo; /** * * @param faultInfo * @param message */ public Exception(String message, com.logicaldoc.ws.Exception faultInfo) { super(message); this.faultInfo = faultInfo; } /** * * @param faultInfo * @param cause * @param message */ public Exception(String message, com.logicaldoc.ws.Exception faultInfo, Throwable cause) { super(message, cause); this.faultInfo = faultInfo; } /** * * @return * returns fault bean: com.logicaldoc.ws.Exception */ public com.logicaldoc.ws.Exception getFaultInfo() { return faultInfo; } }
[ "@", "WebFault", "(", "name", "=", "\"", "Exception", "\"", ",", "targetNamespace", "=", "\"", "http://ws.logicaldoc.com", "\"", ")", "public", "class", "Exception", "extends", "java", ".", "lang", ".", "Exception", "{", "/**\n * Java type that goes as soapenv:Fault detail element.\n * \n */", "private", "com", ".", "logicaldoc", ".", "ws", ".", "Exception", "faultInfo", ";", "/**\n * \n * @param faultInfo\n * @param message\n */", "public", "Exception", "(", "String", "message", ",", "com", ".", "logicaldoc", ".", "ws", ".", "Exception", "faultInfo", ")", "{", "super", "(", "message", ")", ";", "this", ".", "faultInfo", "=", "faultInfo", ";", "}", "/**\n * \n * @param faultInfo\n * @param cause\n * @param message\n */", "public", "Exception", "(", "String", "message", ",", "com", ".", "logicaldoc", ".", "ws", ".", "Exception", "faultInfo", ",", "Throwable", "cause", ")", "{", "super", "(", "message", ",", "cause", ")", ";", "this", ".", "faultInfo", "=", "faultInfo", ";", "}", "/**\n * \n * @return\n * returns fault bean: com.logicaldoc.ws.Exception\n */", "public", "com", ".", "logicaldoc", ".", "ws", ".", "Exception", "getFaultInfo", "(", ")", "{", "return", "faultInfo", ";", "}", "}" ]
This class was generated by the JAX-WS RI.
[ "This", "class", "was", "generated", "by", "the", "JAX", "-", "WS", "RI", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
0e464967b19840e0c2d5dd2f7a09c2467822c401
ibaca/gwt-ol3
gwt-ol3-client/src/test/java/ol/interaction/ModifyTest.java
[ "Apache-2.0" ]
Java
ModifyTest
/** * * @author Tino Desjardins * */
@author Tino Desjardins
[ "@author", "Tino", "Desjardins" ]
public class ModifyTest extends GwtOL3BaseTestCase { public void testModify() { ModifyOptions modifyOptions = OLFactory.createOptions(); Collection<Feature> features = new Collection<Feature>(); modifyOptions.setFeatures(features); Modify modify = new Modify(modifyOptions); assertNotNull(modify); assertTrue(modify instanceof Observable); assertTrue(modify instanceof Interaction); } }
[ "public", "class", "ModifyTest", "extends", "GwtOL3BaseTestCase", "{", "public", "void", "testModify", "(", ")", "{", "ModifyOptions", "modifyOptions", "=", "OLFactory", ".", "createOptions", "(", ")", ";", "Collection", "<", "Feature", ">", "features", "=", "new", "Collection", "<", "Feature", ">", "(", ")", ";", "modifyOptions", ".", "setFeatures", "(", "features", ")", ";", "Modify", "modify", "=", "new", "Modify", "(", "modifyOptions", ")", ";", "assertNotNull", "(", "modify", ")", ";", "assertTrue", "(", "modify", "instanceof", "Observable", ")", ";", "assertTrue", "(", "modify", "instanceof", "Interaction", ")", ";", "}", "}" ]
@author Tino Desjardins
[ "@author", "Tino", "Desjardins" ]
[]
[ { "param": "GwtOL3BaseTestCase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "GwtOL3BaseTestCase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0e482e35e25af5f4a7e8c75f2da36ea541f54a11
costa-xdaniel/DBUtilAndroid
zudamue-sqlite/src/main/java/st/zudamue/support/android/sql/builder/Insert.java
[ "Apache-2.0" ]
Java
Insert
/** * Created by xdaniel on 1/7/17. * * @author Daniel Costa <costa.xdaniel@gmail.com> */
Created by xdaniel on 1/7/17. @author Daniel Costa
[ "Created", "by", "xdaniel", "on", "1", "/", "7", "/", "17", ".", "@author", "Daniel", "Costa" ]
public class Insert extends AbstractSQL implements st.zudamue.support.android.sql.Insert, st.zudamue.support.android.sql.Insert.ResultInsertInto, st.zudamue.support.android.sql.Insert.ResultColumn, st.zudamue.support.android.sql.Insert.ResultColumns { private Select select; private List<Object> list; private List<String> listColumns; private String sql; private String table; public Insert() { this.select = new st.zudamue.support.android.sql.builder.Select(); this.list = new LinkedList<>(); this.listColumns = new LinkedList<>(); } @Override public ResultInsertInto insertInto( CharSequence table ) { this.listColumns.clear(); this.list.clear(); if( table instanceof Identifier ) this.table = ((Identifier) table).name(); else table = String.valueOf( table ); this.sql = "INSERT INTO "+table; return this; } @Override public Select as() { return select; } @Override public ResultColumns columns( CharSequence ... columns) { this.sql += "( "; int count = 0; for( CharSequence col: columns) { String column = ( col instanceof Identifier )? ((Identifier) col ).name() : String.valueOf( col ); this.listColumns.add(column); this.sql += column; if(++count < columns.length) this.sql += ", "; } this.sql += " )"; return this; } @Override public Insert values (Object ... values) { this.sql += " VALUES( "; int iCount = 0; for(Object value: values) { this.sql += "?"; this.list.add(value); if(++iCount < values.length) this.sql += ", "; } this.sql+= ") "; return this; } @Override public String sql() { return this.sql; } @Override public List<Object> arguments() { return this.list; } private class PairColumn { private boolean set; private CharSequence column; private Object value; public PairColumn(CharSequence column, CharSequence value, boolean set) { this.column = column; this.value = value; this.set = set; } public PairColumn(CharSequence column) { this.column = column; this.set = false; } public boolean isSet() { return set; } public void value(Object value) { this.value = value; this.set = true; } } }
[ "public", "class", "Insert", "extends", "AbstractSQL", "implements", "st", ".", "zudamue", ".", "support", ".", "android", ".", "sql", ".", "Insert", ",", "st", ".", "zudamue", ".", "support", ".", "android", ".", "sql", ".", "Insert", ".", "ResultInsertInto", ",", "st", ".", "zudamue", ".", "support", ".", "android", ".", "sql", ".", "Insert", ".", "ResultColumn", ",", "st", ".", "zudamue", ".", "support", ".", "android", ".", "sql", ".", "Insert", ".", "ResultColumns", "{", "private", "Select", "select", ";", "private", "List", "<", "Object", ">", "list", ";", "private", "List", "<", "String", ">", "listColumns", ";", "private", "String", "sql", ";", "private", "String", "table", ";", "public", "Insert", "(", ")", "{", "this", ".", "select", "=", "new", "st", ".", "zudamue", ".", "support", ".", "android", ".", "sql", ".", "builder", ".", "Select", "(", ")", ";", "this", ".", "list", "=", "new", "LinkedList", "<", ">", "(", ")", ";", "this", ".", "listColumns", "=", "new", "LinkedList", "<", ">", "(", ")", ";", "}", "@", "Override", "public", "ResultInsertInto", "insertInto", "(", "CharSequence", "table", ")", "{", "this", ".", "listColumns", ".", "clear", "(", ")", ";", "this", ".", "list", ".", "clear", "(", ")", ";", "if", "(", "table", "instanceof", "Identifier", ")", "this", ".", "table", "=", "(", "(", "Identifier", ")", "table", ")", ".", "name", "(", ")", ";", "else", "table", "=", "String", ".", "valueOf", "(", "table", ")", ";", "this", ".", "sql", "=", "\"", "INSERT INTO ", "\"", "+", "table", ";", "return", "this", ";", "}", "@", "Override", "public", "Select", "as", "(", ")", "{", "return", "select", ";", "}", "@", "Override", "public", "ResultColumns", "columns", "(", "CharSequence", "...", "columns", ")", "{", "this", ".", "sql", "+=", "\"", "( ", "\"", ";", "int", "count", "=", "0", ";", "for", "(", "CharSequence", "col", ":", "columns", ")", "{", "String", "column", "=", "(", "col", "instanceof", "Identifier", ")", "?", "(", "(", "Identifier", ")", "col", ")", ".", "name", "(", ")", ":", "String", ".", "valueOf", "(", "col", ")", ";", "this", ".", "listColumns", ".", "add", "(", "column", ")", ";", "this", ".", "sql", "+=", "column", ";", "if", "(", "++", "count", "<", "columns", ".", "length", ")", "this", ".", "sql", "+=", "\"", ", ", "\"", ";", "}", "this", ".", "sql", "+=", "\"", " )", "\"", ";", "return", "this", ";", "}", "@", "Override", "public", "Insert", "values", "(", "Object", "...", "values", ")", "{", "this", ".", "sql", "+=", "\"", " VALUES( ", "\"", ";", "int", "iCount", "=", "0", ";", "for", "(", "Object", "value", ":", "values", ")", "{", "this", ".", "sql", "+=", "\"", "?", "\"", ";", "this", ".", "list", ".", "add", "(", "value", ")", ";", "if", "(", "++", "iCount", "<", "values", ".", "length", ")", "this", ".", "sql", "+=", "\"", ", ", "\"", ";", "}", "this", ".", "sql", "+=", "\"", ") ", "\"", ";", "return", "this", ";", "}", "@", "Override", "public", "String", "sql", "(", ")", "{", "return", "this", ".", "sql", ";", "}", "@", "Override", "public", "List", "<", "Object", ">", "arguments", "(", ")", "{", "return", "this", ".", "list", ";", "}", "private", "class", "PairColumn", "{", "private", "boolean", "set", ";", "private", "CharSequence", "column", ";", "private", "Object", "value", ";", "public", "PairColumn", "(", "CharSequence", "column", ",", "CharSequence", "value", ",", "boolean", "set", ")", "{", "this", ".", "column", "=", "column", ";", "this", ".", "value", "=", "value", ";", "this", ".", "set", "=", "set", ";", "}", "public", "PairColumn", "(", "CharSequence", "column", ")", "{", "this", ".", "column", "=", "column", ";", "this", ".", "set", "=", "false", ";", "}", "public", "boolean", "isSet", "(", ")", "{", "return", "set", ";", "}", "public", "void", "value", "(", "Object", "value", ")", "{", "this", ".", "value", "=", "value", ";", "this", ".", "set", "=", "true", ";", "}", "}", "}" ]
Created by xdaniel on 1/7/17.
[ "Created", "by", "xdaniel", "on", "1", "/", "7", "/", "17", "." ]
[]
[ { "param": "AbstractSQL", "type": null }, { "param": "st.zudamue.support.android.sql.Insert, st.zudamue.support.android.sql.Insert.ResultInsertInto, st.zudamue.support.android.sql.Insert.ResultColumn, st.zudamue.support.android.sql.Insert.ResultColumns", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractSQL", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "st.zudamue.support.android.sql.Insert, st.zudamue.support.android.sql.Insert.ResultInsertInto, st.zudamue.support.android.sql.Insert.ResultColumn, st.zudamue.support.android.sql.Insert.ResultColumns", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0e4efdbf678d1a2a6fc226ed70b668de0d9811dd
mankeyl/elasticsearch
server/src/main/java/org/elasticsearch/cluster/routing/allocation/RoutingExplanations.java
[ "Apache-2.0" ]
Java
RoutingExplanations
/** * Class used to encapsulate a number of {@link RerouteExplanation} * explanations. */
Class used to encapsulate a number of RerouteExplanation explanations.
[ "Class", "used", "to", "encapsulate", "a", "number", "of", "RerouteExplanation", "explanations", "." ]
public class RoutingExplanations implements ToXContentFragment { private final List<RerouteExplanation> explanations; public RoutingExplanations() { this.explanations = new ArrayList<>(); } public RoutingExplanations add(RerouteExplanation explanation) { this.explanations.add(explanation); return this; } public List<RerouteExplanation> explanations() { return this.explanations; } /** * Provides feedback from commands with a YES decision that should be displayed to the user after the command has been applied */ public List<String> getYesDecisionMessages() { return explanations().stream() .filter(explanation -> explanation.decisions().type().equals(Decision.Type.YES)) .map(explanation -> explanation.command().getMessage()) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); } /** * Read in a RoutingExplanations object */ public static RoutingExplanations readFrom(StreamInput in) throws IOException { int exCount = in.readVInt(); RoutingExplanations exp = new RoutingExplanations(); for (int i = 0; i < exCount; i++) { RerouteExplanation explanation = RerouteExplanation.readFrom(in); exp.add(explanation); } return exp; } /** * Write the RoutingExplanations object */ public static void writeTo(RoutingExplanations explanations, StreamOutput out) throws IOException { out.writeVInt(explanations.explanations.size()); for (RerouteExplanation explanation : explanations.explanations) { RerouteExplanation.writeTo(explanation, out); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startArray("explanations"); for (RerouteExplanation explanation : explanations) { explanation.toXContent(builder, params); } builder.endArray(); return builder; } }
[ "public", "class", "RoutingExplanations", "implements", "ToXContentFragment", "{", "private", "final", "List", "<", "RerouteExplanation", ">", "explanations", ";", "public", "RoutingExplanations", "(", ")", "{", "this", ".", "explanations", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "}", "public", "RoutingExplanations", "add", "(", "RerouteExplanation", "explanation", ")", "{", "this", ".", "explanations", ".", "add", "(", "explanation", ")", ";", "return", "this", ";", "}", "public", "List", "<", "RerouteExplanation", ">", "explanations", "(", ")", "{", "return", "this", ".", "explanations", ";", "}", "/**\n * Provides feedback from commands with a YES decision that should be displayed to the user after the command has been applied\n */", "public", "List", "<", "String", ">", "getYesDecisionMessages", "(", ")", "{", "return", "explanations", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "explanation", "->", "explanation", ".", "decisions", "(", ")", ".", "type", "(", ")", ".", "equals", "(", "Decision", ".", "Type", ".", "YES", ")", ")", ".", "map", "(", "explanation", "->", "explanation", ".", "command", "(", ")", ".", "getMessage", "(", ")", ")", ".", "filter", "(", "Optional", "::", "isPresent", ")", ".", "map", "(", "Optional", "::", "get", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}", "/**\n * Read in a RoutingExplanations object\n */", "public", "static", "RoutingExplanations", "readFrom", "(", "StreamInput", "in", ")", "throws", "IOException", "{", "int", "exCount", "=", "in", ".", "readVInt", "(", ")", ";", "RoutingExplanations", "exp", "=", "new", "RoutingExplanations", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "exCount", ";", "i", "++", ")", "{", "RerouteExplanation", "explanation", "=", "RerouteExplanation", ".", "readFrom", "(", "in", ")", ";", "exp", ".", "add", "(", "explanation", ")", ";", "}", "return", "exp", ";", "}", "/**\n * Write the RoutingExplanations object\n */", "public", "static", "void", "writeTo", "(", "RoutingExplanations", "explanations", ",", "StreamOutput", "out", ")", "throws", "IOException", "{", "out", ".", "writeVInt", "(", "explanations", ".", "explanations", ".", "size", "(", ")", ")", ";", "for", "(", "RerouteExplanation", "explanation", ":", "explanations", ".", "explanations", ")", "{", "RerouteExplanation", ".", "writeTo", "(", "explanation", ",", "out", ")", ";", "}", "}", "@", "Override", "public", "XContentBuilder", "toXContent", "(", "XContentBuilder", "builder", ",", "Params", "params", ")", "throws", "IOException", "{", "builder", ".", "startArray", "(", "\"", "explanations", "\"", ")", ";", "for", "(", "RerouteExplanation", "explanation", ":", "explanations", ")", "{", "explanation", ".", "toXContent", "(", "builder", ",", "params", ")", ";", "}", "builder", ".", "endArray", "(", ")", ";", "return", "builder", ";", "}", "}" ]
Class used to encapsulate a number of {@link RerouteExplanation} explanations.
[ "Class", "used", "to", "encapsulate", "a", "number", "of", "{", "@link", "RerouteExplanation", "}", "explanations", "." ]
[]
[ { "param": "ToXContentFragment", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ToXContentFragment", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0e50079dd517dce0264501e0b513bd6b8109a2c0
jkunimune15/Calculator
src/maths/Set.java
[ "MIT" ]
Java
Set
/** * A discrete list of Expressions * * @author jkunimune */
A discrete list of Expressions @author jkunimune
[ "A", "discrete", "list", "of", "Expressions", "@author", "jkunimune" ]
public class Set extends Expression { public static final Set EMPTY = new Set(new LinkedList<Expression>()); private final Expression[] elements; public Set(Expression...expressions) { elements = expressions; } public Set(List<Expression> exps) { elements = exps.toArray(new Expression[0]); //TODO: somewhere I should probably check to make sure the sizes match } @Override public int[] shape() { if (elements.length==0) return null; else return elements[0].shape(); } @Override protected Expression getComponent(int i, int j) { return new Set(super.getComponentAll(elements, i,j)); } @Override public List<String> getInputs(Workspace heap) { return super.getInputsAll(elements, heap); } @Override public Expression replaced(String[] oldStrs, String[] newStrs) { return new Set(super.replaceAll(elements, oldStrs, newStrs)); } @Override public Expression simplified(Workspace heap) throws ArithmeticException { //TODO: maybe I should consider removing duplicates return new Set(super.simplifyAll(elements, heap)); } @Override public Image toImage() { if (elements.length==0) return ImgUtils.drawString("{}"); List<Image> imgs = new LinkedList<Image>(); for (Expression elm: elements) imgs.add(elm.toImage()); return ImgUtils.wrap("{", ImgUtils.link(imgs, ","), "}"); } @Override public String toString() { if (elements.length==0) return "{}"; String output = "{"; for (Expression elm: elements) output += elm+", "; return output.substring(0,output.length()-2)+"}"; } }
[ "public", "class", "Set", "extends", "Expression", "{", "public", "static", "final", "Set", "EMPTY", "=", "new", "Set", "(", "new", "LinkedList", "<", "Expression", ">", "(", ")", ")", ";", "private", "final", "Expression", "[", "]", "elements", ";", "public", "Set", "(", "Expression", "...", "expressions", ")", "{", "elements", "=", "expressions", ";", "}", "public", "Set", "(", "List", "<", "Expression", ">", "exps", ")", "{", "elements", "=", "exps", ".", "toArray", "(", "new", "Expression", "[", "0", "]", ")", ";", "}", "@", "Override", "public", "int", "[", "]", "shape", "(", ")", "{", "if", "(", "elements", ".", "length", "==", "0", ")", "return", "null", ";", "else", "return", "elements", "[", "0", "]", ".", "shape", "(", ")", ";", "}", "@", "Override", "protected", "Expression", "getComponent", "(", "int", "i", ",", "int", "j", ")", "{", "return", "new", "Set", "(", "super", ".", "getComponentAll", "(", "elements", ",", "i", ",", "j", ")", ")", ";", "}", "@", "Override", "public", "List", "<", "String", ">", "getInputs", "(", "Workspace", "heap", ")", "{", "return", "super", ".", "getInputsAll", "(", "elements", ",", "heap", ")", ";", "}", "@", "Override", "public", "Expression", "replaced", "(", "String", "[", "]", "oldStrs", ",", "String", "[", "]", "newStrs", ")", "{", "return", "new", "Set", "(", "super", ".", "replaceAll", "(", "elements", ",", "oldStrs", ",", "newStrs", ")", ")", ";", "}", "@", "Override", "public", "Expression", "simplified", "(", "Workspace", "heap", ")", "throws", "ArithmeticException", "{", "return", "new", "Set", "(", "super", ".", "simplifyAll", "(", "elements", ",", "heap", ")", ")", ";", "}", "@", "Override", "public", "Image", "toImage", "(", ")", "{", "if", "(", "elements", ".", "length", "==", "0", ")", "return", "ImgUtils", ".", "drawString", "(", "\"", "{}", "\"", ")", ";", "List", "<", "Image", ">", "imgs", "=", "new", "LinkedList", "<", "Image", ">", "(", ")", ";", "for", "(", "Expression", "elm", ":", "elements", ")", "imgs", ".", "add", "(", "elm", ".", "toImage", "(", ")", ")", ";", "return", "ImgUtils", ".", "wrap", "(", "\"", "{", "\"", ",", "ImgUtils", ".", "link", "(", "imgs", ",", "\"", ",", "\"", ")", ",", "\"", "}", "\"", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "if", "(", "elements", ".", "length", "==", "0", ")", "return", "\"", "{}", "\"", ";", "String", "output", "=", "\"", "{", "\"", ";", "for", "(", "Expression", "elm", ":", "elements", ")", "output", "+=", "elm", "+", "\"", ", ", "\"", ";", "return", "output", ".", "substring", "(", "0", ",", "output", ".", "length", "(", ")", "-", "2", ")", "+", "\"", "}", "\"", ";", "}", "}" ]
A discrete list of Expressions
[ "A", "discrete", "list", "of", "Expressions" ]
[ "//TODO: somewhere I should probably check to make sure the sizes match", "//TODO: maybe I should consider removing duplicates" ]
[ { "param": "Expression", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Expression", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0e50ca35ad7a044ce53a7397484b04d46fe8903d
getsuryap/platform
src/main/java/org/ospic/platform/patient/insurancecard/service/InsuranceCardWriteServicePrincipleImpl.java
[ "Apache-2.0" ]
Java
InsuranceCardWriteServicePrincipleImpl
/** * This file was created by eli on 03/06/2021 for org.ospic.platform.patient.insurancecard.service * -- * -- * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */
This file was created by eli on 03/06/2021 for org.ospic.platform.patient.insurancecard.service Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
[ "This", "file", "was", "created", "by", "eli", "on", "03", "/", "06", "/", "2021", "for", "org", ".", "ospic", ".", "platform", ".", "patient", ".", "insurancecard", ".", "service", "Licensed", "to", "the", "Apache", "Software", "Foundation", "(", "ASF", ")", "under", "one", "or", "more", "contributor", "license", "agreements", ".", "See", "the", "NOTICE", "file", "distributed", "with", "this", "work", "for", "additional", "information", "regarding", "copyright", "ownership", ".", "The", "ASF", "licenses", "this", "file", "to", "you", "under", "the", "Apache", "License", "Version", "2", ".", "0", "(", "the", "\"", "License", "\"", ")", ";", "you", "may", "not", "use", "this", "file", "except", "in", "compliance", "with", "the", "License", "." ]
@Service @Component public class InsuranceCardWriteServicePrincipleImpl implements InsuranceCardWriteServicePrinciple { private static final Logger log = LoggerFactory.getLogger(InsuranceCardWriteServicePrincipleImpl.class); private final InsuranceRepository insuranceRepository; private final InsuranceCardRepository cardRepository; private final PatientRepository patientRepository; @Autowired public InsuranceCardWriteServicePrincipleImpl(final InsuranceRepository insuranceRepository, final InsuranceCardRepository cardRepository, final PatientRepository patientRepository){ this.insuranceRepository = insuranceRepository; this.cardRepository = cardRepository; this.patientRepository = patientRepository; } @Override public InsuranceCard addInsuranceCard(InsurancePayload payload) { return this.insuranceRepository.findById(payload.getInsuranceId()).map(insurance -> { return this.patientRepository.findById(payload.getPatientId()).map(patient -> { if (payload.getExpireDate().isBefore(payload.getIssuedDate())){ throw new InsuranceCardDateException(); }; InsuranceCard card = new InsuranceCard().fromJson(payload, patient); card.setPatient(patient); card.setInsurance(insurance); return this.cardRepository.save(card); }).orElseThrow(()-> new PatientNotFoundExceptionPlatform(payload.getPatientId())); }).orElseThrow(()->new InsuranceNotFoundException(payload.getInsuranceId())); } @Override public InsuranceCard updateInsuranceCard(Long id, InsurancePayload payload) { return this.cardRepository.findById(id).map(card -> { return this.patientRepository.findById(payload.getPatientId()).map(patient -> { card.setCodeNo(payload.getCodeNo()); card.setExpireDate(payload.getExpireDate()); card.setIssuedDate(payload.getIssuedDate()); card.setMembershipNumber(payload.getMembershipNumber()); card.setVoteNo(payload.getVoteNo()); card.setPatientName(patient.getName()); card.setSex(patient.getGender()); return this.cardRepository.save(card); }).orElseThrow(()->new PatientNotFoundExceptionPlatform(payload.getPatientId())); }).orElseThrow(()->new InsuranceCardNotFoundException(id)); } @Override public InsuranceCard activateInsuranceCard(Long insuranceCardId) { return this.cardRepository.findById(insuranceCardId).map(card -> { card.setIsActive(true); return this.cardRepository.save(card); }).orElseThrow(()->new InsuranceCardNotFoundException(insuranceCardId)); } @Override public InsuranceCard deactivateInsuranceCard(Long insuranceCardId) { return this.cardRepository.findById(insuranceCardId).map(card -> { card.setIsActive(false); return this.cardRepository.save(card); }).orElseThrow(()->new InsuranceCardNotFoundException(insuranceCardId)); } @Scheduled(cron = "0 59 23 * * ?") public void checkCards(){ Collection<InsuranceCard> insuranceCards = this.cardRepository.findAll(); insuranceCards.forEach(card->{ if (card.getExpireDate().isBefore(LocalDate.now())){ card.setIsActive(false); } this.cardRepository.save(card); }); } }
[ "@", "Service", "@", "Component", "public", "class", "InsuranceCardWriteServicePrincipleImpl", "implements", "InsuranceCardWriteServicePrinciple", "{", "private", "static", "final", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "InsuranceCardWriteServicePrincipleImpl", ".", "class", ")", ";", "private", "final", "InsuranceRepository", "insuranceRepository", ";", "private", "final", "InsuranceCardRepository", "cardRepository", ";", "private", "final", "PatientRepository", "patientRepository", ";", "@", "Autowired", "public", "InsuranceCardWriteServicePrincipleImpl", "(", "final", "InsuranceRepository", "insuranceRepository", ",", "final", "InsuranceCardRepository", "cardRepository", ",", "final", "PatientRepository", "patientRepository", ")", "{", "this", ".", "insuranceRepository", "=", "insuranceRepository", ";", "this", ".", "cardRepository", "=", "cardRepository", ";", "this", ".", "patientRepository", "=", "patientRepository", ";", "}", "@", "Override", "public", "InsuranceCard", "addInsuranceCard", "(", "InsurancePayload", "payload", ")", "{", "return", "this", ".", "insuranceRepository", ".", "findById", "(", "payload", ".", "getInsuranceId", "(", ")", ")", ".", "map", "(", "insurance", "->", "{", "return", "this", ".", "patientRepository", ".", "findById", "(", "payload", ".", "getPatientId", "(", ")", ")", ".", "map", "(", "patient", "->", "{", "if", "(", "payload", ".", "getExpireDate", "(", ")", ".", "isBefore", "(", "payload", ".", "getIssuedDate", "(", ")", ")", ")", "{", "throw", "new", "InsuranceCardDateException", "(", ")", ";", "}", ";", "InsuranceCard", "card", "=", "new", "InsuranceCard", "(", ")", ".", "fromJson", "(", "payload", ",", "patient", ")", ";", "card", ".", "setPatient", "(", "patient", ")", ";", "card", ".", "setInsurance", "(", "insurance", ")", ";", "return", "this", ".", "cardRepository", ".", "save", "(", "card", ")", ";", "}", ")", ".", "orElseThrow", "(", "(", ")", "->", "new", "PatientNotFoundExceptionPlatform", "(", "payload", ".", "getPatientId", "(", ")", ")", ")", ";", "}", ")", ".", "orElseThrow", "(", "(", ")", "->", "new", "InsuranceNotFoundException", "(", "payload", ".", "getInsuranceId", "(", ")", ")", ")", ";", "}", "@", "Override", "public", "InsuranceCard", "updateInsuranceCard", "(", "Long", "id", ",", "InsurancePayload", "payload", ")", "{", "return", "this", ".", "cardRepository", ".", "findById", "(", "id", ")", ".", "map", "(", "card", "->", "{", "return", "this", ".", "patientRepository", ".", "findById", "(", "payload", ".", "getPatientId", "(", ")", ")", ".", "map", "(", "patient", "->", "{", "card", ".", "setCodeNo", "(", "payload", ".", "getCodeNo", "(", ")", ")", ";", "card", ".", "setExpireDate", "(", "payload", ".", "getExpireDate", "(", ")", ")", ";", "card", ".", "setIssuedDate", "(", "payload", ".", "getIssuedDate", "(", ")", ")", ";", "card", ".", "setMembershipNumber", "(", "payload", ".", "getMembershipNumber", "(", ")", ")", ";", "card", ".", "setVoteNo", "(", "payload", ".", "getVoteNo", "(", ")", ")", ";", "card", ".", "setPatientName", "(", "patient", ".", "getName", "(", ")", ")", ";", "card", ".", "setSex", "(", "patient", ".", "getGender", "(", ")", ")", ";", "return", "this", ".", "cardRepository", ".", "save", "(", "card", ")", ";", "}", ")", ".", "orElseThrow", "(", "(", ")", "->", "new", "PatientNotFoundExceptionPlatform", "(", "payload", ".", "getPatientId", "(", ")", ")", ")", ";", "}", ")", ".", "orElseThrow", "(", "(", ")", "->", "new", "InsuranceCardNotFoundException", "(", "id", ")", ")", ";", "}", "@", "Override", "public", "InsuranceCard", "activateInsuranceCard", "(", "Long", "insuranceCardId", ")", "{", "return", "this", ".", "cardRepository", ".", "findById", "(", "insuranceCardId", ")", ".", "map", "(", "card", "->", "{", "card", ".", "setIsActive", "(", "true", ")", ";", "return", "this", ".", "cardRepository", ".", "save", "(", "card", ")", ";", "}", ")", ".", "orElseThrow", "(", "(", ")", "->", "new", "InsuranceCardNotFoundException", "(", "insuranceCardId", ")", ")", ";", "}", "@", "Override", "public", "InsuranceCard", "deactivateInsuranceCard", "(", "Long", "insuranceCardId", ")", "{", "return", "this", ".", "cardRepository", ".", "findById", "(", "insuranceCardId", ")", ".", "map", "(", "card", "->", "{", "card", ".", "setIsActive", "(", "false", ")", ";", "return", "this", ".", "cardRepository", ".", "save", "(", "card", ")", ";", "}", ")", ".", "orElseThrow", "(", "(", ")", "->", "new", "InsuranceCardNotFoundException", "(", "insuranceCardId", ")", ")", ";", "}", "@", "Scheduled", "(", "cron", "=", "\"", "0 59 23 * * ?", "\"", ")", "public", "void", "checkCards", "(", ")", "{", "Collection", "<", "InsuranceCard", ">", "insuranceCards", "=", "this", ".", "cardRepository", ".", "findAll", "(", ")", ";", "insuranceCards", ".", "forEach", "(", "card", "->", "{", "if", "(", "card", ".", "getExpireDate", "(", ")", ".", "isBefore", "(", "LocalDate", ".", "now", "(", ")", ")", ")", "{", "card", ".", "setIsActive", "(", "false", ")", ";", "}", "this", ".", "cardRepository", ".", "save", "(", "card", ")", ";", "}", ")", ";", "}", "}" ]
This file was created by eli on 03/06/2021 for org.ospic.platform.patient.insurancecard.service
[ "This", "file", "was", "created", "by", "eli", "on", "03", "/", "06", "/", "2021", "for", "org", ".", "ospic", ".", "platform", ".", "patient", ".", "insurancecard", ".", "service" ]
[]
[ { "param": "InsuranceCardWriteServicePrinciple", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "InsuranceCardWriteServicePrinciple", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card