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 ([email protected]) 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 ([email protected]) 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 ([email protected]) */
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 <[email protected]> */
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": [] }
0e57407974664469efabe5a2fd4b58e0808c8ae6
GoogleCloudPlatformTraining/cpd200-conference-central-android-app
app/src/main/java/com/google/training/cpd200/conference/android/MainActivity.java
[ "Apache-2.0" ]
Java
MainActivity
/** * Sample Android application for the Conference Central class for Google Cloud Endpoints. */
Sample Android application for the Conference Central class for Google Cloud Endpoints.
[ "Sample", "Android", "application", "for", "the", "Conference", "Central", "class", "for", "Google", "Cloud", "Endpoints", "." ]
public class MainActivity extends ActionBarActivity { private static final String LOG_TAG = "MainActivity"; /** * Activity result indicating a return from the Google account selection intent. */ private static final int ACTIVITY_RESULT_FROM_ACCOUNT_SELECTION = 2222; private AuthorizationCheckTask mAuthTask; private String mEmailAccount; private ConferenceListFragment mConferenceListFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mEmailAccount = Utils.getEmailAccount(this); if (savedInstanceState == null) { mConferenceListFragment = ConferenceListFragment.newInstance(); getSupportFragmentManager().beginTransaction() .add(R.id.container, mConferenceListFragment) .commit(); } } @Override protected void onDestroy() { super.onDestroy(); if (mAuthTask != null) { mAuthTask.cancel(true); mAuthTask = null; } } protected void onResume() { super.onResume(); if (null != mEmailAccount) { performAuthCheck(mEmailAccount); } else { selectAccount(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_clear_account: new AlertDialog.Builder(MainActivity.this).setTitle(null) .setMessage(getString(R.string.clear_account_message)) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Utils.saveEmailAccount(MainActivity.this, null); dialog.cancel(); finish(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }) .create() .show(); break; case R.id.action_reload: mConferenceListFragment.reload(); break; } return true; } /* * Selects an account for talking to Google Play services. If there is more than one account on * the device, it allows user to choose one. */ private void selectAccount() { Account[] accounts = Utils.getGoogleAccounts(this); int numOfAccount = accounts.length; switch (numOfAccount) { case 0: // No accounts registered, nothing to do. Toast.makeText(this, R.string.toast_no_google_accounts_registered, Toast.LENGTH_LONG).show(); break; case 1: mEmailAccount = accounts[0].name; performAuthCheck(mEmailAccount); break; default: // More than one Google Account is present, a chooser is necessary. // Invoke an {@code Intent} to allow the user to select a Google account. Intent accountSelector = AccountPicker.newChooseAccountIntent(null, null, new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}, false, getString(R.string.select_account_for_access), null, null, null); startActivityForResult(accountSelector, ACTIVITY_RESULT_FROM_ACCOUNT_SELECTION); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ACTIVITY_RESULT_FROM_ACCOUNT_SELECTION && resultCode == RESULT_OK) { // This path indicates the account selection activity resulted in the user selecting a // Google account and clicking OK. mEmailAccount = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); } else { finish(); } } /* * Schedule the authorization check. */ private void performAuthCheck(String email) { // Cancel previously running tasks. if (mAuthTask != null) { mAuthTask.cancel(true); } // Start task to check authorization. mAuthTask = new AuthorizationCheckTask(); mAuthTask.execute(email); } /** * Verifies OAuth2 token access for the application and Google account combination with * the {@code AccountManager} and the Play Services installed application. If the appropriate * OAuth2 access hasn't been granted (to this application) then the task may fire an * {@code Intent} to request that the user approve such access. If the appropriate access does * exist then the button that will let the user proceed to the next activity is enabled. */ private class AuthorizationCheckTask extends AsyncTask<String, Integer, Boolean> { private final static boolean SUCCESS = true; private final static boolean FAILURE = false; private Exception mException; @Override protected Boolean doInBackground(String... emailAccounts) { Log.i(LOG_TAG, "Background task started."); if (!Utils.checkGooglePlayServicesAvailable(MainActivity.this)) { publishProgress(R.string.gms_not_available); return FAILURE; } String emailAccount = emailAccounts[0]; // Ensure only one task is running at a time. mAuthTask = this; // Ensure an email was selected. if (TextUtils.isEmpty(emailAccount)) { publishProgress(R.string.toast_no_google_account_selected); return FAILURE; } mEmailAccount = emailAccount; Utils.saveEmailAccount(MainActivity.this, emailAccount); return SUCCESS; } @Override protected void onProgressUpdate(Integer... stringIds) { // Toast only the most recent. Integer stringId = stringIds[0]; Toast.makeText(MainActivity.this, getString(stringId), Toast.LENGTH_SHORT).show(); } @Override protected void onPreExecute() { mAuthTask = this; } @Override protected void onPostExecute(Boolean success) { if (success) { // Authorization check successful, get conferences. ConferenceUtils.build(MainActivity.this, mEmailAccount); getConferencesForList(); } else { // Authorization check unsuccessful. mEmailAccount = null; if (mException != null) { Utils.displayNetworkErrorMessage(MainActivity.this); } } mAuthTask = null; } @Override protected void onCancelled() { mAuthTask = null; } } private void getConferencesForList() { if (TextUtils.isEmpty(mEmailAccount)) { return; } mConferenceListFragment.loadConferences(); } }
[ "public", "class", "MainActivity", "extends", "ActionBarActivity", "{", "private", "static", "final", "String", "LOG_TAG", "=", "\"", "MainActivity", "\"", ";", "/**\n * Activity result indicating a return from the Google account selection intent.\n */", "private", "static", "final", "int", "ACTIVITY_RESULT_FROM_ACCOUNT_SELECTION", "=", "2222", ";", "private", "AuthorizationCheckTask", "mAuthTask", ";", "private", "String", "mEmailAccount", ";", "private", "ConferenceListFragment", "mConferenceListFragment", ";", "@", "Override", "protected", "void", "onCreate", "(", "Bundle", "savedInstanceState", ")", "{", "super", ".", "onCreate", "(", "savedInstanceState", ")", ";", "setContentView", "(", "R", ".", "layout", ".", "activity_main", ")", ";", "mEmailAccount", "=", "Utils", ".", "getEmailAccount", "(", "this", ")", ";", "if", "(", "savedInstanceState", "==", "null", ")", "{", "mConferenceListFragment", "=", "ConferenceListFragment", ".", "newInstance", "(", ")", ";", "getSupportFragmentManager", "(", ")", ".", "beginTransaction", "(", ")", ".", "add", "(", "R", ".", "id", ".", "container", ",", "mConferenceListFragment", ")", ".", "commit", "(", ")", ";", "}", "}", "@", "Override", "protected", "void", "onDestroy", "(", ")", "{", "super", ".", "onDestroy", "(", ")", ";", "if", "(", "mAuthTask", "!=", "null", ")", "{", "mAuthTask", ".", "cancel", "(", "true", ")", ";", "mAuthTask", "=", "null", ";", "}", "}", "protected", "void", "onResume", "(", ")", "{", "super", ".", "onResume", "(", ")", ";", "if", "(", "null", "!=", "mEmailAccount", ")", "{", "performAuthCheck", "(", "mEmailAccount", ")", ";", "}", "else", "{", "selectAccount", "(", ")", ";", "}", "}", "@", "Override", "public", "boolean", "onCreateOptionsMenu", "(", "Menu", "menu", ")", "{", "getMenuInflater", "(", ")", ".", "inflate", "(", "R", ".", "menu", ".", "main", ",", "menu", ")", ";", "return", "true", ";", "}", "@", "Override", "public", "boolean", "onOptionsItemSelected", "(", "MenuItem", "item", ")", "{", "switch", "(", "item", ".", "getItemId", "(", ")", ")", "{", "case", "R", ".", "id", ".", "action_clear_account", ":", "new", "AlertDialog", ".", "Builder", "(", "MainActivity", ".", "this", ")", ".", "setTitle", "(", "null", ")", ".", "setMessage", "(", "getString", "(", "R", ".", "string", ".", "clear_account_message", ")", ")", ".", "setPositiveButton", "(", "R", ".", "string", ".", "ok", ",", "new", "DialogInterface", ".", "OnClickListener", "(", ")", "{", "@", "Override", "public", "void", "onClick", "(", "DialogInterface", "dialog", ",", "int", "id", ")", "{", "Utils", ".", "saveEmailAccount", "(", "MainActivity", ".", "this", ",", "null", ")", ";", "dialog", ".", "cancel", "(", ")", ";", "finish", "(", ")", ";", "}", "}", ")", ".", "setNegativeButton", "(", "R", ".", "string", ".", "cancel", ",", "new", "DialogInterface", ".", "OnClickListener", "(", ")", "{", "@", "Override", "public", "void", "onClick", "(", "DialogInterface", "dialog", ",", "int", "id", ")", "{", "dialog", ".", "cancel", "(", ")", ";", "}", "}", ")", ".", "create", "(", ")", ".", "show", "(", ")", ";", "break", ";", "case", "R", ".", "id", ".", "action_reload", ":", "mConferenceListFragment", ".", "reload", "(", ")", ";", "break", ";", "}", "return", "true", ";", "}", "/*\n * Selects an account for talking to Google Play services. If there is more than one account on\n * the device, it allows user to choose one.\n */", "private", "void", "selectAccount", "(", ")", "{", "Account", "[", "]", "accounts", "=", "Utils", ".", "getGoogleAccounts", "(", "this", ")", ";", "int", "numOfAccount", "=", "accounts", ".", "length", ";", "switch", "(", "numOfAccount", ")", "{", "case", "0", ":", "Toast", ".", "makeText", "(", "this", ",", "R", ".", "string", ".", "toast_no_google_accounts_registered", ",", "Toast", ".", "LENGTH_LONG", ")", ".", "show", "(", ")", ";", "break", ";", "case", "1", ":", "mEmailAccount", "=", "accounts", "[", "0", "]", ".", "name", ";", "performAuthCheck", "(", "mEmailAccount", ")", ";", "break", ";", "default", ":", "Intent", "accountSelector", "=", "AccountPicker", ".", "newChooseAccountIntent", "(", "null", ",", "null", ",", "new", "String", "[", "]", "{", "GoogleAuthUtil", ".", "GOOGLE_ACCOUNT_TYPE", "}", ",", "false", ",", "getString", "(", "R", ".", "string", ".", "select_account_for_access", ")", ",", "null", ",", "null", ",", "null", ")", ";", "startActivityForResult", "(", "accountSelector", ",", "ACTIVITY_RESULT_FROM_ACCOUNT_SELECTION", ")", ";", "}", "}", "@", "Override", "protected", "void", "onActivityResult", "(", "int", "requestCode", ",", "int", "resultCode", ",", "Intent", "data", ")", "{", "super", ".", "onActivityResult", "(", "requestCode", ",", "resultCode", ",", "data", ")", ";", "if", "(", "requestCode", "==", "ACTIVITY_RESULT_FROM_ACCOUNT_SELECTION", "&&", "resultCode", "==", "RESULT_OK", ")", "{", "mEmailAccount", "=", "data", ".", "getStringExtra", "(", "AccountManager", ".", "KEY_ACCOUNT_NAME", ")", ";", "}", "else", "{", "finish", "(", ")", ";", "}", "}", "/*\n * Schedule the authorization check.\n */", "private", "void", "performAuthCheck", "(", "String", "email", ")", "{", "if", "(", "mAuthTask", "!=", "null", ")", "{", "mAuthTask", ".", "cancel", "(", "true", ")", ";", "}", "mAuthTask", "=", "new", "AuthorizationCheckTask", "(", ")", ";", "mAuthTask", ".", "execute", "(", "email", ")", ";", "}", "/**\n * Verifies OAuth2 token access for the application and Google account combination with\n * the {@code AccountManager} and the Play Services installed application. If the appropriate\n * OAuth2 access hasn't been granted (to this application) then the task may fire an\n * {@code Intent} to request that the user approve such access. If the appropriate access does\n * exist then the button that will let the user proceed to the next activity is enabled.\n */", "private", "class", "AuthorizationCheckTask", "extends", "AsyncTask", "<", "String", ",", "Integer", ",", "Boolean", ">", "{", "private", "final", "static", "boolean", "SUCCESS", "=", "true", ";", "private", "final", "static", "boolean", "FAILURE", "=", "false", ";", "private", "Exception", "mException", ";", "@", "Override", "protected", "Boolean", "doInBackground", "(", "String", "...", "emailAccounts", ")", "{", "Log", ".", "i", "(", "LOG_TAG", ",", "\"", "Background task started.", "\"", ")", ";", "if", "(", "!", "Utils", ".", "checkGooglePlayServicesAvailable", "(", "MainActivity", ".", "this", ")", ")", "{", "publishProgress", "(", "R", ".", "string", ".", "gms_not_available", ")", ";", "return", "FAILURE", ";", "}", "String", "emailAccount", "=", "emailAccounts", "[", "0", "]", ";", "mAuthTask", "=", "this", ";", "if", "(", "TextUtils", ".", "isEmpty", "(", "emailAccount", ")", ")", "{", "publishProgress", "(", "R", ".", "string", ".", "toast_no_google_account_selected", ")", ";", "return", "FAILURE", ";", "}", "mEmailAccount", "=", "emailAccount", ";", "Utils", ".", "saveEmailAccount", "(", "MainActivity", ".", "this", ",", "emailAccount", ")", ";", "return", "SUCCESS", ";", "}", "@", "Override", "protected", "void", "onProgressUpdate", "(", "Integer", "...", "stringIds", ")", "{", "Integer", "stringId", "=", "stringIds", "[", "0", "]", ";", "Toast", ".", "makeText", "(", "MainActivity", ".", "this", ",", "getString", "(", "stringId", ")", ",", "Toast", ".", "LENGTH_SHORT", ")", ".", "show", "(", ")", ";", "}", "@", "Override", "protected", "void", "onPreExecute", "(", ")", "{", "mAuthTask", "=", "this", ";", "}", "@", "Override", "protected", "void", "onPostExecute", "(", "Boolean", "success", ")", "{", "if", "(", "success", ")", "{", "ConferenceUtils", ".", "build", "(", "MainActivity", ".", "this", ",", "mEmailAccount", ")", ";", "getConferencesForList", "(", ")", ";", "}", "else", "{", "mEmailAccount", "=", "null", ";", "if", "(", "mException", "!=", "null", ")", "{", "Utils", ".", "displayNetworkErrorMessage", "(", "MainActivity", ".", "this", ")", ";", "}", "}", "mAuthTask", "=", "null", ";", "}", "@", "Override", "protected", "void", "onCancelled", "(", ")", "{", "mAuthTask", "=", "null", ";", "}", "}", "private", "void", "getConferencesForList", "(", ")", "{", "if", "(", "TextUtils", ".", "isEmpty", "(", "mEmailAccount", ")", ")", "{", "return", ";", "}", "mConferenceListFragment", ".", "loadConferences", "(", ")", ";", "}", "}" ]
Sample Android application for the Conference Central class for Google Cloud Endpoints.
[ "Sample", "Android", "application", "for", "the", "Conference", "Central", "class", "for", "Google", "Cloud", "Endpoints", "." ]
[ "// Inflate the menu; this adds items to the action bar if it is present.", "// No accounts registered, nothing to do.", "// More than one Google Account is present, a chooser is necessary.", "// Invoke an {@code Intent} to allow the user to select a Google account.", "// This path indicates the account selection activity resulted in the user selecting a", "// Google account and clicking OK.", "// Cancel previously running tasks.", "// Start task to check authorization.", "// Ensure only one task is running at a time.", "// Ensure an email was selected.", "// Toast only the most recent.", "// Authorization check successful, get conferences.", "// Authorization check unsuccessful." ]
[ { "param": "ActionBarActivity", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ActionBarActivity", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0e57407974664469efabe5a2fd4b58e0808c8ae6
GoogleCloudPlatformTraining/cpd200-conference-central-android-app
app/src/main/java/com/google/training/cpd200/conference/android/MainActivity.java
[ "Apache-2.0" ]
Java
AuthorizationCheckTask
/** * Verifies OAuth2 token access for the application and Google account combination with * the {@code AccountManager} and the Play Services installed application. If the appropriate * OAuth2 access hasn't been granted (to this application) then the task may fire an * {@code Intent} to request that the user approve such access. If the appropriate access does * exist then the button that will let the user proceed to the next activity is enabled. */
Verifies OAuth2 token access for the application and Google account combination with the AccountManager and the Play Services installed application. If the appropriate OAuth2 access hasn't been granted (to this application) then the task may fire an Intent to request that the user approve such access. If the appropriate access does exist then the button that will let the user proceed to the next activity is enabled.
[ "Verifies", "OAuth2", "token", "access", "for", "the", "application", "and", "Google", "account", "combination", "with", "the", "AccountManager", "and", "the", "Play", "Services", "installed", "application", ".", "If", "the", "appropriate", "OAuth2", "access", "hasn", "'", "t", "been", "granted", "(", "to", "this", "application", ")", "then", "the", "task", "may", "fire", "an", "Intent", "to", "request", "that", "the", "user", "approve", "such", "access", ".", "If", "the", "appropriate", "access", "does", "exist", "then", "the", "button", "that", "will", "let", "the", "user", "proceed", "to", "the", "next", "activity", "is", "enabled", "." ]
private class AuthorizationCheckTask extends AsyncTask<String, Integer, Boolean> { private final static boolean SUCCESS = true; private final static boolean FAILURE = false; private Exception mException; @Override protected Boolean doInBackground(String... emailAccounts) { Log.i(LOG_TAG, "Background task started."); if (!Utils.checkGooglePlayServicesAvailable(MainActivity.this)) { publishProgress(R.string.gms_not_available); return FAILURE; } String emailAccount = emailAccounts[0]; // Ensure only one task is running at a time. mAuthTask = this; // Ensure an email was selected. if (TextUtils.isEmpty(emailAccount)) { publishProgress(R.string.toast_no_google_account_selected); return FAILURE; } mEmailAccount = emailAccount; Utils.saveEmailAccount(MainActivity.this, emailAccount); return SUCCESS; } @Override protected void onProgressUpdate(Integer... stringIds) { // Toast only the most recent. Integer stringId = stringIds[0]; Toast.makeText(MainActivity.this, getString(stringId), Toast.LENGTH_SHORT).show(); } @Override protected void onPreExecute() { mAuthTask = this; } @Override protected void onPostExecute(Boolean success) { if (success) { // Authorization check successful, get conferences. ConferenceUtils.build(MainActivity.this, mEmailAccount); getConferencesForList(); } else { // Authorization check unsuccessful. mEmailAccount = null; if (mException != null) { Utils.displayNetworkErrorMessage(MainActivity.this); } } mAuthTask = null; } @Override protected void onCancelled() { mAuthTask = null; } }
[ "private", "class", "AuthorizationCheckTask", "extends", "AsyncTask", "<", "String", ",", "Integer", ",", "Boolean", ">", "{", "private", "final", "static", "boolean", "SUCCESS", "=", "true", ";", "private", "final", "static", "boolean", "FAILURE", "=", "false", ";", "private", "Exception", "mException", ";", "@", "Override", "protected", "Boolean", "doInBackground", "(", "String", "...", "emailAccounts", ")", "{", "Log", ".", "i", "(", "LOG_TAG", ",", "\"", "Background task started.", "\"", ")", ";", "if", "(", "!", "Utils", ".", "checkGooglePlayServicesAvailable", "(", "MainActivity", ".", "this", ")", ")", "{", "publishProgress", "(", "R", ".", "string", ".", "gms_not_available", ")", ";", "return", "FAILURE", ";", "}", "String", "emailAccount", "=", "emailAccounts", "[", "0", "]", ";", "mAuthTask", "=", "this", ";", "if", "(", "TextUtils", ".", "isEmpty", "(", "emailAccount", ")", ")", "{", "publishProgress", "(", "R", ".", "string", ".", "toast_no_google_account_selected", ")", ";", "return", "FAILURE", ";", "}", "mEmailAccount", "=", "emailAccount", ";", "Utils", ".", "saveEmailAccount", "(", "MainActivity", ".", "this", ",", "emailAccount", ")", ";", "return", "SUCCESS", ";", "}", "@", "Override", "protected", "void", "onProgressUpdate", "(", "Integer", "...", "stringIds", ")", "{", "Integer", "stringId", "=", "stringIds", "[", "0", "]", ";", "Toast", ".", "makeText", "(", "MainActivity", ".", "this", ",", "getString", "(", "stringId", ")", ",", "Toast", ".", "LENGTH_SHORT", ")", ".", "show", "(", ")", ";", "}", "@", "Override", "protected", "void", "onPreExecute", "(", ")", "{", "mAuthTask", "=", "this", ";", "}", "@", "Override", "protected", "void", "onPostExecute", "(", "Boolean", "success", ")", "{", "if", "(", "success", ")", "{", "ConferenceUtils", ".", "build", "(", "MainActivity", ".", "this", ",", "mEmailAccount", ")", ";", "getConferencesForList", "(", ")", ";", "}", "else", "{", "mEmailAccount", "=", "null", ";", "if", "(", "mException", "!=", "null", ")", "{", "Utils", ".", "displayNetworkErrorMessage", "(", "MainActivity", ".", "this", ")", ";", "}", "}", "mAuthTask", "=", "null", ";", "}", "@", "Override", "protected", "void", "onCancelled", "(", ")", "{", "mAuthTask", "=", "null", ";", "}", "}" ]
Verifies OAuth2 token access for the application and Google account combination with the {@code AccountManager} and the Play Services installed application.
[ "Verifies", "OAuth2", "token", "access", "for", "the", "application", "and", "Google", "account", "combination", "with", "the", "{", "@code", "AccountManager", "}", "and", "the", "Play", "Services", "installed", "application", "." ]
[ "// Ensure only one task is running at a time.", "// Ensure an email was selected.", "// Toast only the most recent.", "// Authorization check successful, get conferences.", "// Authorization check unsuccessful." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
0e5b92fd591e9d9ffa3e05de9a4bb7ca8f547465
codehaus/coconut
cache/trunk/coconut-cache-api/src/main/java/org/coconut/cache/service/statistics/CacheHitStat.java
[ "Apache-2.0" ]
Java
CacheHitStat
/** * An immutable class holding the hit statistics for a cache. * * @author <a href="mailto:[email protected]">Kasper Nielsen</a> * @version $Id$ */
An immutable class holding the hit statistics for a cache. @author Kasper Nielsen @version $Id$
[ "An", "immutable", "class", "holding", "the", "hit", "statistics", "for", "a", "cache", ".", "@author", "Kasper", "Nielsen", "@version", "$Id$" ]
public class CacheHitStat { /** A CacheHitStat with 0 hits and 0 misses. */ public static final CacheHitStat STAT00 = new CacheHitStat(0, 0); /** The number of cache hits. */ private final long hits; /** The number of cache misses. */ private final long misses; /** * Constructs a new HitStat. * * @param hits * the number of cache hits * @param misses * the number of cache misses */ public CacheHitStat(long hits, long misses) { if (hits < 0) { throw new IllegalArgumentException("hits must be 0 or greater"); } else if (misses < 0) { throw new IllegalArgumentException("misses must be 0 or greater"); } this.misses = misses; this.hits = hits; } /** * Returns the ratio between cache hits and misses or {@link java.lang.Double#NaN} if * no hits or misses has been recorded. * * @return the ratio between cache hits and misses or NaN if no hits or misses has * been recorded */ public float getHitRatio() { final long sum = hits + misses; if (sum == 0) { return Float.NaN; } return (float) hits / sum; } /** * Returns the number of succesfull hits for a cache. A request to a cache is a hit if * the value is already contained within the cache and no external cache backends must * be used to fetch the value. * * @return the number of hits */ public long getNumberOfHits() { return hits; } /** * Returns the number of cache misses. A request is a miss if the value is not already * contained within the cache when it is requested and a cache backend must fetch the * value. * * @return the number of cache misses. */ public long getNumberOfMisses() { return misses; } /** {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof CacheHitStat)) { return false; } CacheHitStat hs = (CacheHitStat) obj; return hs.getNumberOfHits() == hits && hs.getNumberOfMisses() == misses; } /** {@inheritDoc} */ @Override public int hashCode() { long value = hits ^ misses; return (int) (value ^ value >>> 32); } /** {@inheritDoc} */ @Override public String toString() { // We probably can't use a resource bundle, if it needs to be JMX compatible // or we could check if the string was available, otherwise resort to a default // test. //TODO: make sure this class is JMX compatible. return CacheSPI.lookup(getClass(), "toString", getHitRatio(), hits, misses); } }
[ "public", "class", "CacheHitStat", "{", "/** A CacheHitStat with 0 hits and 0 misses. */", "public", "static", "final", "CacheHitStat", "STAT00", "=", "new", "CacheHitStat", "(", "0", ",", "0", ")", ";", "/** The number of cache hits. */", "private", "final", "long", "hits", ";", "/** The number of cache misses. */", "private", "final", "long", "misses", ";", "/**\r\n * Constructs a new HitStat.\r\n *\r\n * @param hits\r\n * the number of cache hits\r\n * @param misses\r\n * the number of cache misses\r\n */", "public", "CacheHitStat", "(", "long", "hits", ",", "long", "misses", ")", "{", "if", "(", "hits", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "hits must be 0 or greater", "\"", ")", ";", "}", "else", "if", "(", "misses", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "misses must be 0 or greater", "\"", ")", ";", "}", "this", ".", "misses", "=", "misses", ";", "this", ".", "hits", "=", "hits", ";", "}", "/**\r\n * Returns the ratio between cache hits and misses or {@link java.lang.Double#NaN} if\r\n * no hits or misses has been recorded.\r\n *\r\n * @return the ratio between cache hits and misses or NaN if no hits or misses has\r\n * been recorded\r\n */", "public", "float", "getHitRatio", "(", ")", "{", "final", "long", "sum", "=", "hits", "+", "misses", ";", "if", "(", "sum", "==", "0", ")", "{", "return", "Float", ".", "NaN", ";", "}", "return", "(", "float", ")", "hits", "/", "sum", ";", "}", "/**\r\n * Returns the number of succesfull hits for a cache. A request to a cache is a hit if\r\n * the value is already contained within the cache and no external cache backends must\r\n * be used to fetch the value.\r\n *\r\n * @return the number of hits\r\n */", "public", "long", "getNumberOfHits", "(", ")", "{", "return", "hits", ";", "}", "/**\r\n * Returns the number of cache misses. A request is a miss if the value is not already\r\n * contained within the cache when it is requested and a cache backend must fetch the\r\n * value.\r\n *\r\n * @return the number of cache misses.\r\n */", "public", "long", "getNumberOfMisses", "(", ")", "{", "return", "misses", ";", "}", "/** {@inheritDoc} */", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "obj", "==", "null", "||", "!", "(", "obj", "instanceof", "CacheHitStat", ")", ")", "{", "return", "false", ";", "}", "CacheHitStat", "hs", "=", "(", "CacheHitStat", ")", "obj", ";", "return", "hs", ".", "getNumberOfHits", "(", ")", "==", "hits", "&&", "hs", ".", "getNumberOfMisses", "(", ")", "==", "misses", ";", "}", "/** {@inheritDoc} */", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "long", "value", "=", "hits", "^", "misses", ";", "return", "(", "int", ")", "(", "value", "^", "value", ">>>", "32", ")", ";", "}", "/** {@inheritDoc} */", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "CacheSPI", ".", "lookup", "(", "getClass", "(", ")", ",", "\"", "toString", "\"", ",", "getHitRatio", "(", ")", ",", "hits", ",", "misses", ")", ";", "}", "}" ]
An immutable class holding the hit statistics for a cache.
[ "An", "immutable", "class", "holding", "the", "hit", "statistics", "for", "a", "cache", "." ]
[ "// We probably can't use a resource bundle, if it needs to be JMX compatible\r", "// or we could check if the string was available, otherwise resort to a default\r", "// test.\r", "//TODO: make sure this class is JMX compatible.\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
0e5cd5e9bd066384d8ce36e40f4980610cde5f44
mathieuravaux/nutchbase
src/plugin/parse-oo/src/java/org/apache/nutch/parse/oo/OOParser.java
[ "Apache-2.0" ]
Java
OOParser
/** * Parser for OpenOffice and OpenDocument formats. This should handle * the following formats: Text, Spreadsheet, Presentation, and * corresponding templates and "master" documents. * * @author Andrzej Bialecki */
@author Andrzej Bialecki
[ "@author", "Andrzej", "Bialecki" ]
public class OOParser implements Parser { public static final Log LOG = LogFactory.getLog(OOParser.class); private Configuration conf; public OOParser () { } public void setConf(Configuration conf) { this.conf = conf; } public Configuration getConf() { return conf; } public ParseResult getParse(Content content) { String text = null; String title = null; Metadata metadata = new Metadata(); ArrayList outlinks = new ArrayList(); try { byte[] raw = content.getContent(); String contentLength = content.getMetadata().get("Content-Length"); if (contentLength != null && raw.length != Integer.parseInt(contentLength)) { return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_TRUNCATED, "Content truncated at "+raw.length +" bytes. Parser can't handle incomplete files.").getEmptyParseResult(content.getUrl(), conf); } ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(raw)); ZipEntry ze = null; while ((ze = zis.getNextEntry()) != null) { if (ze.getName().equals("content.xml")) { text = parseContent(ze, zis, outlinks); } else if (ze.getName().equals("meta.xml")) { parseMeta(ze, zis, metadata); } } zis.close(); } catch (Exception e) { // run time exception e.printStackTrace(LogUtil.getWarnStream(LOG)); return new ParseStatus(ParseStatus.FAILED, "Can't be handled as OO document. " + e).getEmptyParseResult(content.getUrl(), conf); } title = metadata.get(Metadata.TITLE); if (text == null) text = ""; if (title == null) title = ""; Outlink[] links = (Outlink[])outlinks.toArray(new Outlink[outlinks.size()]); ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title, links, metadata); return ParseResult.createParseResult(content.getUrl(), new ParseImpl(text, parseData)); } // extract as much plain text as possible. private String parseContent(ZipEntry ze, ZipInputStream zis, ArrayList outlinks) throws Exception { StringBuffer res = new StringBuffer(); FilterInputStream fis = new FilterInputStream(zis) { public void close() {}; }; SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(fis); Element root = doc.getRootElement(); // XXX this is expensive for very large documents. In those cases another // XXX method (direct processing of SAX events, or XMLPull) should be used. XPath path = new JDOMXPath("//text:span | //text:p | //text:tab | //text:tab-stop | //text:a"); path.addNamespace("text", root.getNamespace("text").getURI()); Namespace xlink = Namespace.getNamespace("xlink", "http://www.w3.org/1999/xlink"); List list = path.selectNodes(doc); boolean lastp = true; for (int i = 0; i < list.size(); i++) { Element el = (Element)list.get(i); String text = el.getText(); if (el.getName().equals("p")) { // skip empty paragraphs if (!text.equals("")) { if (!lastp) res.append("\n"); res.append(text + "\n"); lastp = true; } } else if (el.getName().startsWith("tab")) { res.append("\t"); lastp = false; } else if (el.getName().equals("a")) { List nl = el.getChildren(); String a = null; for (int k = 0; k < nl.size(); k++) { Element anchor = (Element)nl.get(k); String nsName = anchor.getNamespacePrefix() + ":" + anchor.getName(); if (!nsName.equals("text:span")) continue; a = anchor.getText(); break; } String u = el.getAttributeValue("href", xlink); if (u == null) u = a; // often anchors are URLs Outlink o = new Outlink(u, a); outlinks.add(o); if (a != null && !a.equals("")) { if (!lastp) res.append(' '); res.append(a); lastp = false; } } else { if (!text.equals("")) { if (!lastp) res.append(' '); res.append(text); } lastp = false; } } return res.toString(); } // extract metadata and convert them to Nutch format private void parseMeta(ZipEntry ze, ZipInputStream zis, Metadata metadata) throws Exception { FilterInputStream fis = new FilterInputStream(zis) { public void close() {}; }; SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(fis); XPath path = new JDOMXPath("/office:document-meta/office:meta/*"); Element root = doc.getRootElement(); path.addNamespace("office", root.getNamespace("office").getURI()); List list = path.selectNodes(doc); for (int i = 0; i < list.size(); i++) { Element n = (Element)list.get(i); String text = n.getText(); if (text.trim().equals("")) continue; String name = n.getName(); if (name.equals("title")) metadata.add(Metadata.TITLE, text); else if (name.equals("language")) metadata.add(Metadata.LANGUAGE, text); else if (name.equals("creation-date")) metadata.add(Metadata.DATE, text); else if (name.equals("print-date")) metadata.add(Metadata.LAST_PRINTED, text); else if (name.equals("generator")) metadata.add(Metadata.APPLICATION_NAME, text); else if (name.equals("creator")) metadata.add(Metadata.CREATOR, text); } } public static void main(String[] args) throws Exception { OOParser oo = new OOParser(); Configuration conf = NutchConfiguration.create(); oo.setConf(conf); FileInputStream fis = new FileInputStream(args[0]); byte[] bytes = new byte[fis.available()]; fis.read(bytes); fis.close(); Content c = new Content("local", "local", bytes, "application/vnd.oasis.opendocument.text", new Metadata(), conf); Parse p = oo.getParse(c).get(c.getUrl()); System.out.println(p.getData()); System.out.println("Text: '" + p.getText() + "'"); /* // create the test output file OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("e:\\ootest.txt"), "UTF-8"); osw.write(p.getText()); osw.flush(); osw.close(); */ } }
[ "public", "class", "OOParser", "implements", "Parser", "{", "public", "static", "final", "Log", "LOG", "=", "LogFactory", ".", "getLog", "(", "OOParser", ".", "class", ")", ";", "private", "Configuration", "conf", ";", "public", "OOParser", "(", ")", "{", "}", "public", "void", "setConf", "(", "Configuration", "conf", ")", "{", "this", ".", "conf", "=", "conf", ";", "}", "public", "Configuration", "getConf", "(", ")", "{", "return", "conf", ";", "}", "public", "ParseResult", "getParse", "(", "Content", "content", ")", "{", "String", "text", "=", "null", ";", "String", "title", "=", "null", ";", "Metadata", "metadata", "=", "new", "Metadata", "(", ")", ";", "ArrayList", "outlinks", "=", "new", "ArrayList", "(", ")", ";", "try", "{", "byte", "[", "]", "raw", "=", "content", ".", "getContent", "(", ")", ";", "String", "contentLength", "=", "content", ".", "getMetadata", "(", ")", ".", "get", "(", "\"", "Content-Length", "\"", ")", ";", "if", "(", "contentLength", "!=", "null", "&&", "raw", ".", "length", "!=", "Integer", ".", "parseInt", "(", "contentLength", ")", ")", "{", "return", "new", "ParseStatus", "(", "ParseStatus", ".", "FAILED", ",", "ParseStatus", ".", "FAILED_TRUNCATED", ",", "\"", "Content truncated at ", "\"", "+", "raw", ".", "length", "+", "\"", " bytes. Parser can't handle incomplete files.", "\"", ")", ".", "getEmptyParseResult", "(", "content", ".", "getUrl", "(", ")", ",", "conf", ")", ";", "}", "ZipInputStream", "zis", "=", "new", "ZipInputStream", "(", "new", "ByteArrayInputStream", "(", "raw", ")", ")", ";", "ZipEntry", "ze", "=", "null", ";", "while", "(", "(", "ze", "=", "zis", ".", "getNextEntry", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "ze", ".", "getName", "(", ")", ".", "equals", "(", "\"", "content.xml", "\"", ")", ")", "{", "text", "=", "parseContent", "(", "ze", ",", "zis", ",", "outlinks", ")", ";", "}", "else", "if", "(", "ze", ".", "getName", "(", ")", ".", "equals", "(", "\"", "meta.xml", "\"", ")", ")", "{", "parseMeta", "(", "ze", ",", "zis", ",", "metadata", ")", ";", "}", "}", "zis", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", "LogUtil", ".", "getWarnStream", "(", "LOG", ")", ")", ";", "return", "new", "ParseStatus", "(", "ParseStatus", ".", "FAILED", ",", "\"", "Can't be handled as OO document. ", "\"", "+", "e", ")", ".", "getEmptyParseResult", "(", "content", ".", "getUrl", "(", ")", ",", "conf", ")", ";", "}", "title", "=", "metadata", ".", "get", "(", "Metadata", ".", "TITLE", ")", ";", "if", "(", "text", "==", "null", ")", "text", "=", "\"", "\"", ";", "if", "(", "title", "==", "null", ")", "title", "=", "\"", "\"", ";", "Outlink", "[", "]", "links", "=", "(", "Outlink", "[", "]", ")", "outlinks", ".", "toArray", "(", "new", "Outlink", "[", "outlinks", ".", "size", "(", ")", "]", ")", ";", "ParseData", "parseData", "=", "new", "ParseData", "(", "ParseStatus", ".", "STATUS_SUCCESS", ",", "title", ",", "links", ",", "metadata", ")", ";", "return", "ParseResult", ".", "createParseResult", "(", "content", ".", "getUrl", "(", ")", ",", "new", "ParseImpl", "(", "text", ",", "parseData", ")", ")", ";", "}", "private", "String", "parseContent", "(", "ZipEntry", "ze", ",", "ZipInputStream", "zis", ",", "ArrayList", "outlinks", ")", "throws", "Exception", "{", "StringBuffer", "res", "=", "new", "StringBuffer", "(", ")", ";", "FilterInputStream", "fis", "=", "new", "FilterInputStream", "(", "zis", ")", "{", "public", "void", "close", "(", ")", "{", "}", ";", "}", ";", "SAXBuilder", "builder", "=", "new", "SAXBuilder", "(", ")", ";", "Document", "doc", "=", "builder", ".", "build", "(", "fis", ")", ";", "Element", "root", "=", "doc", ".", "getRootElement", "(", ")", ";", "XPath", "path", "=", "new", "JDOMXPath", "(", "\"", "//text:span | //text:p | //text:tab | //text:tab-stop | //text:a", "\"", ")", ";", "path", ".", "addNamespace", "(", "\"", "text", "\"", ",", "root", ".", "getNamespace", "(", "\"", "text", "\"", ")", ".", "getURI", "(", ")", ")", ";", "Namespace", "xlink", "=", "Namespace", ".", "getNamespace", "(", "\"", "xlink", "\"", ",", "\"", "http://www.w3.org/1999/xlink", "\"", ")", ";", "List", "list", "=", "path", ".", "selectNodes", "(", "doc", ")", ";", "boolean", "lastp", "=", "true", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "list", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Element", "el", "=", "(", "Element", ")", "list", ".", "get", "(", "i", ")", ";", "String", "text", "=", "el", ".", "getText", "(", ")", ";", "if", "(", "el", ".", "getName", "(", ")", ".", "equals", "(", "\"", "p", "\"", ")", ")", "{", "if", "(", "!", "text", ".", "equals", "(", "\"", "\"", ")", ")", "{", "if", "(", "!", "lastp", ")", "res", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "res", ".", "append", "(", "text", "+", "\"", "\\n", "\"", ")", ";", "lastp", "=", "true", ";", "}", "}", "else", "if", "(", "el", ".", "getName", "(", ")", ".", "startsWith", "(", "\"", "tab", "\"", ")", ")", "{", "res", ".", "append", "(", "\"", "\\t", "\"", ")", ";", "lastp", "=", "false", ";", "}", "else", "if", "(", "el", ".", "getName", "(", ")", ".", "equals", "(", "\"", "a", "\"", ")", ")", "{", "List", "nl", "=", "el", ".", "getChildren", "(", ")", ";", "String", "a", "=", "null", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "nl", ".", "size", "(", ")", ";", "k", "++", ")", "{", "Element", "anchor", "=", "(", "Element", ")", "nl", ".", "get", "(", "k", ")", ";", "String", "nsName", "=", "anchor", ".", "getNamespacePrefix", "(", ")", "+", "\"", ":", "\"", "+", "anchor", ".", "getName", "(", ")", ";", "if", "(", "!", "nsName", ".", "equals", "(", "\"", "text:span", "\"", ")", ")", "continue", ";", "a", "=", "anchor", ".", "getText", "(", ")", ";", "break", ";", "}", "String", "u", "=", "el", ".", "getAttributeValue", "(", "\"", "href", "\"", ",", "xlink", ")", ";", "if", "(", "u", "==", "null", ")", "u", "=", "a", ";", "Outlink", "o", "=", "new", "Outlink", "(", "u", ",", "a", ")", ";", "outlinks", ".", "add", "(", "o", ")", ";", "if", "(", "a", "!=", "null", "&&", "!", "a", ".", "equals", "(", "\"", "\"", ")", ")", "{", "if", "(", "!", "lastp", ")", "res", ".", "append", "(", "' '", ")", ";", "res", ".", "append", "(", "a", ")", ";", "lastp", "=", "false", ";", "}", "}", "else", "{", "if", "(", "!", "text", ".", "equals", "(", "\"", "\"", ")", ")", "{", "if", "(", "!", "lastp", ")", "res", ".", "append", "(", "' '", ")", ";", "res", ".", "append", "(", "text", ")", ";", "}", "lastp", "=", "false", ";", "}", "}", "return", "res", ".", "toString", "(", ")", ";", "}", "private", "void", "parseMeta", "(", "ZipEntry", "ze", ",", "ZipInputStream", "zis", ",", "Metadata", "metadata", ")", "throws", "Exception", "{", "FilterInputStream", "fis", "=", "new", "FilterInputStream", "(", "zis", ")", "{", "public", "void", "close", "(", ")", "{", "}", ";", "}", ";", "SAXBuilder", "builder", "=", "new", "SAXBuilder", "(", ")", ";", "Document", "doc", "=", "builder", ".", "build", "(", "fis", ")", ";", "XPath", "path", "=", "new", "JDOMXPath", "(", "\"", "/office:document-meta/office:meta/*", "\"", ")", ";", "Element", "root", "=", "doc", ".", "getRootElement", "(", ")", ";", "path", ".", "addNamespace", "(", "\"", "office", "\"", ",", "root", ".", "getNamespace", "(", "\"", "office", "\"", ")", ".", "getURI", "(", ")", ")", ";", "List", "list", "=", "path", ".", "selectNodes", "(", "doc", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "list", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Element", "n", "=", "(", "Element", ")", "list", ".", "get", "(", "i", ")", ";", "String", "text", "=", "n", ".", "getText", "(", ")", ";", "if", "(", "text", ".", "trim", "(", ")", ".", "equals", "(", "\"", "\"", ")", ")", "continue", ";", "String", "name", "=", "n", ".", "getName", "(", ")", ";", "if", "(", "name", ".", "equals", "(", "\"", "title", "\"", ")", ")", "metadata", ".", "add", "(", "Metadata", ".", "TITLE", ",", "text", ")", ";", "else", "if", "(", "name", ".", "equals", "(", "\"", "language", "\"", ")", ")", "metadata", ".", "add", "(", "Metadata", ".", "LANGUAGE", ",", "text", ")", ";", "else", "if", "(", "name", ".", "equals", "(", "\"", "creation-date", "\"", ")", ")", "metadata", ".", "add", "(", "Metadata", ".", "DATE", ",", "text", ")", ";", "else", "if", "(", "name", ".", "equals", "(", "\"", "print-date", "\"", ")", ")", "metadata", ".", "add", "(", "Metadata", ".", "LAST_PRINTED", ",", "text", ")", ";", "else", "if", "(", "name", ".", "equals", "(", "\"", "generator", "\"", ")", ")", "metadata", ".", "add", "(", "Metadata", ".", "APPLICATION_NAME", ",", "text", ")", ";", "else", "if", "(", "name", ".", "equals", "(", "\"", "creator", "\"", ")", ")", "metadata", ".", "add", "(", "Metadata", ".", "CREATOR", ",", "text", ")", ";", "}", "}", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "OOParser", "oo", "=", "new", "OOParser", "(", ")", ";", "Configuration", "conf", "=", "NutchConfiguration", ".", "create", "(", ")", ";", "oo", ".", "setConf", "(", "conf", ")", ";", "FileInputStream", "fis", "=", "new", "FileInputStream", "(", "args", "[", "0", "]", ")", ";", "byte", "[", "]", "bytes", "=", "new", "byte", "[", "fis", ".", "available", "(", ")", "]", ";", "fis", ".", "read", "(", "bytes", ")", ";", "fis", ".", "close", "(", ")", ";", "Content", "c", "=", "new", "Content", "(", "\"", "local", "\"", ",", "\"", "local", "\"", ",", "bytes", ",", "\"", "application/vnd.oasis.opendocument.text", "\"", ",", "new", "Metadata", "(", ")", ",", "conf", ")", ";", "Parse", "p", "=", "oo", ".", "getParse", "(", "c", ")", ".", "get", "(", "c", ".", "getUrl", "(", ")", ")", ";", "System", ".", "out", ".", "println", "(", "p", ".", "getData", "(", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Text: '", "\"", "+", "p", ".", "getText", "(", ")", "+", "\"", "'", "\"", ")", ";", "/*\n // create the test output file\n OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(\"e:\\\\ootest.txt\"), \"UTF-8\");\n osw.write(p.getText());\n osw.flush();\n osw.close();\n */", "}", "}" ]
Parser for OpenOffice and OpenDocument formats.
[ "Parser", "for", "OpenOffice", "and", "OpenDocument", "formats", "." ]
[ "// run time exception", "// extract as much plain text as possible.", "// XXX this is expensive for very large documents. In those cases another", "// XXX method (direct processing of SAX events, or XMLPull) should be used.", "// skip empty paragraphs", "// often anchors are URLs", "// extract metadata and convert them to Nutch format" ]
[ { "param": "Parser", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Parser", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0e5ef277f0de21b31984c504cf94d60c262ec348
Team3039/2021-GameChangers-GME
src/main/java/frc/robot/subsystems/Hopper.java
[ "BSD-3-Clause" ]
Java
Hopper
/** * The Intake delivers "Power Cells" to this subsystem to be transfered to the * Shooter. This subsystem also "indexes" said "Power Cells" for rapid shooting */
The Intake delivers "Power Cells" to this subsystem to be transfered to the Shooter. This subsystem also "indexes" said "Power Cells" for rapid shooting
[ "The", "Intake", "delivers", "\"", "Power", "Cells", "\"", "to", "this", "subsystem", "to", "be", "transfered", "to", "the", "Shooter", ".", "This", "subsystem", "also", "\"", "indexes", "\"", "said", "\"", "Power", "Cells", "\"", "for", "rapid", "shooting" ]
public class Hopper extends SubsystemBase { public TalonSRX kickerWheel = new TalonSRX(RobotMap.kickerWheel); public TalonSRX backFeederBelt = new TalonSRX(RobotMap.backFeederBelt); public TalonSRX frontFeederBeltWheel = new TalonSRX(RobotMap.fronFeederBeltWheel); public DigitalInput topBeam = new DigitalInput(RobotMap.topBeam); public DigitalInput lowBeam = new DigitalInput(RobotMap.lowBeam); public enum HopperControlMode { IDLE, INTAKING, FEEDING, UNJAMMING } public HopperControlMode hopperControlMode = HopperControlMode.IDLE; public synchronized HopperControlMode getControlMode() { return hopperControlMode; } public synchronized void setControlMode(HopperControlMode controlMode) { this.hopperControlMode = controlMode; } public boolean getTopBeam() { return !topBeam.get(); } public boolean getLowBeam() { return !lowBeam.get(); } public Hopper() { backFeederBelt.setInverted(false); frontFeederBeltWheel.setInverted(true); backFeederBelt.setNeutralMode(NeutralMode.Brake); frontFeederBeltWheel.setNeutralMode(NeutralMode.Brake); kickerWheel.setNeutralMode(NeutralMode.Brake); } public void setBackBeltSpeed(double percentOutput) { backFeederBelt.set(ControlMode.PercentOutput, percentOutput); } public void setKickerSpeed(double percentOutput) { kickerWheel.set(ControlMode.PercentOutput, percentOutput); } public void setFeederWheelFrontBeltSpeed(double percentOutput) { frontFeederBeltWheel.set(ControlMode.PercentOutput, percentOutput); } public void setHopperSpeed(double kickerSpeed, double backBeltSpeed, double frontBeltWheelSpeed) { kickerWheel.set(ControlMode.PercentOutput, kickerSpeed); backFeederBelt.set(ControlMode.PercentOutput, backBeltSpeed); frontFeederBeltWheel.set(ControlMode.PercentOutput, frontBeltWheelSpeed); } public void stopSystems() { kickerWheel.set(ControlMode.PercentOutput, 0); backFeederBelt.set(ControlMode.PercentOutput, 0); frontFeederBeltWheel.set(ControlMode.PercentOutput, 0); } @Override public void periodic() { SmartDashboard.putBoolean("Top Beam", getTopBeam()); SmartDashboard.putBoolean("Low Beam", getLowBeam()); synchronized (Hopper.this) { switch (getControlMode()) { case IDLE: stopSystems(); break; case INTAKING: if (!getTopBeam() && !getLowBeam()) { setHopperSpeed(.4, .6, .6); } else if (getTopBeam() && !getLowBeam()) { setKickerSpeed(.2); setBackBeltSpeed(0); setFeederWheelFrontBeltSpeed(.5); } else if (getTopBeam() && getLowBeam()){ setHopperSpeed(0, 0, 0); } else if (!getTopBeam() && getLowBeam()) { setHopperSpeed(.4, .6, .6); } break; case FEEDING: if (RobotContainer.shooter.isFar) { setHopperSpeed(.7, .4, .4); } else { setHopperSpeed(.7, .4, .4); } break; case UNJAMMING: setHopperSpeed(-.4, -.75, -.75); break; } } } }
[ "public", "class", "Hopper", "extends", "SubsystemBase", "{", "public", "TalonSRX", "kickerWheel", "=", "new", "TalonSRX", "(", "RobotMap", ".", "kickerWheel", ")", ";", "public", "TalonSRX", "backFeederBelt", "=", "new", "TalonSRX", "(", "RobotMap", ".", "backFeederBelt", ")", ";", "public", "TalonSRX", "frontFeederBeltWheel", "=", "new", "TalonSRX", "(", "RobotMap", ".", "fronFeederBeltWheel", ")", ";", "public", "DigitalInput", "topBeam", "=", "new", "DigitalInput", "(", "RobotMap", ".", "topBeam", ")", ";", "public", "DigitalInput", "lowBeam", "=", "new", "DigitalInput", "(", "RobotMap", ".", "lowBeam", ")", ";", "public", "enum", "HopperControlMode", "{", "IDLE", ",", "INTAKING", ",", "FEEDING", ",", "UNJAMMING", "}", "public", "HopperControlMode", "hopperControlMode", "=", "HopperControlMode", ".", "IDLE", ";", "public", "synchronized", "HopperControlMode", "getControlMode", "(", ")", "{", "return", "hopperControlMode", ";", "}", "public", "synchronized", "void", "setControlMode", "(", "HopperControlMode", "controlMode", ")", "{", "this", ".", "hopperControlMode", "=", "controlMode", ";", "}", "public", "boolean", "getTopBeam", "(", ")", "{", "return", "!", "topBeam", ".", "get", "(", ")", ";", "}", "public", "boolean", "getLowBeam", "(", ")", "{", "return", "!", "lowBeam", ".", "get", "(", ")", ";", "}", "public", "Hopper", "(", ")", "{", "backFeederBelt", ".", "setInverted", "(", "false", ")", ";", "frontFeederBeltWheel", ".", "setInverted", "(", "true", ")", ";", "backFeederBelt", ".", "setNeutralMode", "(", "NeutralMode", ".", "Brake", ")", ";", "frontFeederBeltWheel", ".", "setNeutralMode", "(", "NeutralMode", ".", "Brake", ")", ";", "kickerWheel", ".", "setNeutralMode", "(", "NeutralMode", ".", "Brake", ")", ";", "}", "public", "void", "setBackBeltSpeed", "(", "double", "percentOutput", ")", "{", "backFeederBelt", ".", "set", "(", "ControlMode", ".", "PercentOutput", ",", "percentOutput", ")", ";", "}", "public", "void", "setKickerSpeed", "(", "double", "percentOutput", ")", "{", "kickerWheel", ".", "set", "(", "ControlMode", ".", "PercentOutput", ",", "percentOutput", ")", ";", "}", "public", "void", "setFeederWheelFrontBeltSpeed", "(", "double", "percentOutput", ")", "{", "frontFeederBeltWheel", ".", "set", "(", "ControlMode", ".", "PercentOutput", ",", "percentOutput", ")", ";", "}", "public", "void", "setHopperSpeed", "(", "double", "kickerSpeed", ",", "double", "backBeltSpeed", ",", "double", "frontBeltWheelSpeed", ")", "{", "kickerWheel", ".", "set", "(", "ControlMode", ".", "PercentOutput", ",", "kickerSpeed", ")", ";", "backFeederBelt", ".", "set", "(", "ControlMode", ".", "PercentOutput", ",", "backBeltSpeed", ")", ";", "frontFeederBeltWheel", ".", "set", "(", "ControlMode", ".", "PercentOutput", ",", "frontBeltWheelSpeed", ")", ";", "}", "public", "void", "stopSystems", "(", ")", "{", "kickerWheel", ".", "set", "(", "ControlMode", ".", "PercentOutput", ",", "0", ")", ";", "backFeederBelt", ".", "set", "(", "ControlMode", ".", "PercentOutput", ",", "0", ")", ";", "frontFeederBeltWheel", ".", "set", "(", "ControlMode", ".", "PercentOutput", ",", "0", ")", ";", "}", "@", "Override", "public", "void", "periodic", "(", ")", "{", "SmartDashboard", ".", "putBoolean", "(", "\"", "Top Beam", "\"", ",", "getTopBeam", "(", ")", ")", ";", "SmartDashboard", ".", "putBoolean", "(", "\"", "Low Beam", "\"", ",", "getLowBeam", "(", ")", ")", ";", "synchronized", "(", "Hopper", ".", "this", ")", "{", "switch", "(", "getControlMode", "(", ")", ")", "{", "case", "IDLE", ":", "stopSystems", "(", ")", ";", "break", ";", "case", "INTAKING", ":", "if", "(", "!", "getTopBeam", "(", ")", "&&", "!", "getLowBeam", "(", ")", ")", "{", "setHopperSpeed", "(", ".4", ",", ".6", ",", ".6", ")", ";", "}", "else", "if", "(", "getTopBeam", "(", ")", "&&", "!", "getLowBeam", "(", ")", ")", "{", "setKickerSpeed", "(", ".2", ")", ";", "setBackBeltSpeed", "(", "0", ")", ";", "setFeederWheelFrontBeltSpeed", "(", ".5", ")", ";", "}", "else", "if", "(", "getTopBeam", "(", ")", "&&", "getLowBeam", "(", ")", ")", "{", "setHopperSpeed", "(", "0", ",", "0", ",", "0", ")", ";", "}", "else", "if", "(", "!", "getTopBeam", "(", ")", "&&", "getLowBeam", "(", ")", ")", "{", "setHopperSpeed", "(", ".4", ",", ".6", ",", ".6", ")", ";", "}", "break", ";", "case", "FEEDING", ":", "if", "(", "RobotContainer", ".", "shooter", ".", "isFar", ")", "{", "setHopperSpeed", "(", ".7", ",", ".4", ",", ".4", ")", ";", "}", "else", "{", "setHopperSpeed", "(", ".7", ",", ".4", ",", ".4", ")", ";", "}", "break", ";", "case", "UNJAMMING", ":", "setHopperSpeed", "(", "-", ".4", ",", "-", ".75", ",", "-", ".75", ")", ";", "break", ";", "}", "}", "}", "}" ]
The Intake delivers "Power Cells" to this subsystem to be transfered to the Shooter.
[ "The", "Intake", "delivers", "\"", "Power", "Cells", "\"", "to", "this", "subsystem", "to", "be", "transfered", "to", "the", "Shooter", "." ]
[]
[ { "param": "SubsystemBase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "SubsystemBase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0e618046c034b34ad30354cb0fab8694076e612e
CraigMcDonaldCodes/quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/FixedProducesHandler.java
[ "Apache-2.0" ]
Java
FixedProducesHandler
/** * Handler that negotiates the content type for endpoints that * only produce a single type. */
Handler that negotiates the content type for endpoints that only produce a single type.
[ "Handler", "that", "negotiates", "the", "content", "type", "for", "endpoints", "that", "only", "produce", "a", "single", "type", "." ]
public class FixedProducesHandler implements ServerRestHandler { final EncodedMediaType mediaType; final String mediaTypeString; final String mediaTypeSubstring; final EntityWriter writer; public FixedProducesHandler(MediaType mediaType, EntityWriter writer) { this.mediaType = new EncodedMediaType(mediaType); this.writer = writer; this.mediaTypeString = mediaType.getType() + "/" + mediaType.getSubtype(); this.mediaTypeSubstring = mediaType.getType() + "/*"; } @Override public void handle(ResteasyReactiveRequestContext requestContext) throws Exception { String accept = requestContext.serverRequest().getRequestHeader(HttpHeaders.ACCEPT); if (accept == null) { requestContext.setResponseContentType(mediaType); requestContext.setEntityWriter(writer); } else { //TODO: this needs to be optimised if (accept.contains(mediaTypeString) || accept.contains("*/*") || accept.contains(mediaTypeSubstring)) { requestContext.setResponseContentType(mediaType); requestContext.setEntityWriter(writer); } else { throw new WebApplicationException( Response.notAcceptable(Variant.mediaTypes(mediaType.getMediaType()).build()).build()); } } } }
[ "public", "class", "FixedProducesHandler", "implements", "ServerRestHandler", "{", "final", "EncodedMediaType", "mediaType", ";", "final", "String", "mediaTypeString", ";", "final", "String", "mediaTypeSubstring", ";", "final", "EntityWriter", "writer", ";", "public", "FixedProducesHandler", "(", "MediaType", "mediaType", ",", "EntityWriter", "writer", ")", "{", "this", ".", "mediaType", "=", "new", "EncodedMediaType", "(", "mediaType", ")", ";", "this", ".", "writer", "=", "writer", ";", "this", ".", "mediaTypeString", "=", "mediaType", ".", "getType", "(", ")", "+", "\"", "/", "\"", "+", "mediaType", ".", "getSubtype", "(", ")", ";", "this", ".", "mediaTypeSubstring", "=", "mediaType", ".", "getType", "(", ")", "+", "\"", "/*", "\"", ";", "}", "@", "Override", "public", "void", "handle", "(", "ResteasyReactiveRequestContext", "requestContext", ")", "throws", "Exception", "{", "String", "accept", "=", "requestContext", ".", "serverRequest", "(", ")", ".", "getRequestHeader", "(", "HttpHeaders", ".", "ACCEPT", ")", ";", "if", "(", "accept", "==", "null", ")", "{", "requestContext", ".", "setResponseContentType", "(", "mediaType", ")", ";", "requestContext", ".", "setEntityWriter", "(", "writer", ")", ";", "}", "else", "{", "if", "(", "accept", ".", "contains", "(", "mediaTypeString", ")", "||", "accept", ".", "contains", "(", "\"", "*/*", "\"", ")", "||", "accept", ".", "contains", "(", "mediaTypeSubstring", ")", ")", "{", "requestContext", ".", "setResponseContentType", "(", "mediaType", ")", ";", "requestContext", ".", "setEntityWriter", "(", "writer", ")", ";", "}", "else", "{", "throw", "new", "WebApplicationException", "(", "Response", ".", "notAcceptable", "(", "Variant", ".", "mediaTypes", "(", "mediaType", ".", "getMediaType", "(", ")", ")", ".", "build", "(", ")", ")", ".", "build", "(", ")", ")", ";", "}", "}", "}", "}" ]
Handler that negotiates the content type for endpoints that only produce a single type.
[ "Handler", "that", "negotiates", "the", "content", "type", "for", "endpoints", "that", "only", "produce", "a", "single", "type", "." ]
[ "//TODO: this needs to be optimised" ]
[ { "param": "ServerRestHandler", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ServerRestHandler", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
697e8fb2243020c5b4e1f010d8bd18aee9a72013
adolfmc/zabbix-parent
zabbix-sisyphus/src/main/java/com/zabbix/sisyphus/crm/entity/CompanyInfo.java
[ "Apache-2.0" ]
Java
CompanyInfo
/** * The persistent class for the crm_t_company_info database table. * */
The persistent class for the crm_t_company_info database table.
[ "The", "persistent", "class", "for", "the", "crm_t_company_info", "database", "table", "." ]
@Entity @Table(name="crm_t_company_info") public class CompanyInfo extends IdEntity implements Serializable { private static final long serialVersionUID = 1L; private String annualSales; private String assetStatus; private String corporateInformation; private String customerCode; private String established; private String flowId; private String industry; private String jobAdress; private String liabilities; private String memo; private String moneyPurpose; private String name; private String operationStatus; private String registeredCapital; private String scale; private String status; private String upsadown; private String phoneNum; public CompanyInfo() { } public String getPhoneNum() { return phoneNum; } public void setPhoneNum(String phoneNum) { this.phoneNum = phoneNum; } public String getAnnualSales() { return this.annualSales; } public void setAnnualSales(String annualSales) { this.annualSales = annualSales; } public String getAssetStatus() { return this.assetStatus; } public void setAssetStatus(String assetStatus) { this.assetStatus = assetStatus; } public String getCorporateInformation() { return this.corporateInformation; } public void setCorporateInformation(String corporateInformation) { this.corporateInformation = corporateInformation; } public String getCustomerCode() { return this.customerCode; } public void setCustomerCode(String customerCode) { this.customerCode = customerCode; } public String getEstablished() { return this.established; } public void setEstablished(String established) { this.established = established; } public String getFlowId() { return this.flowId; } public void setFlowId(String flowId) { this.flowId = flowId; } public String getIndustry() { return this.industry; } public void setIndustry(String industry) { this.industry = industry; } public String getJobAdress() { return this.jobAdress; } public void setJobAdress(String jobAdress) { this.jobAdress = jobAdress; } public String getLiabilities() { return this.liabilities; } public void setLiabilities(String liabilities) { this.liabilities = liabilities; } public String getMemo() { return this.memo; } public void setMemo(String memo) { this.memo = memo; } public String getMoneyPurpose() { return this.moneyPurpose; } public void setMoneyPurpose(String moneyPurpose) { this.moneyPurpose = moneyPurpose; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getOperationStatus() { return this.operationStatus; } public void setOperationStatus(String operationStatus) { this.operationStatus = operationStatus; } public String getRegisteredCapital() { return this.registeredCapital; } public void setRegisteredCapital(String registeredCapital) { this.registeredCapital = registeredCapital; } public String getScale() { return this.scale; } public void setScale(String scale) { this.scale = scale; } public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } public String getUpsadown() { return this.upsadown; } public void setUpsadown(String upsadown) { this.upsadown = upsadown; } public static void main(String[] args) { DateTime datetime = DateTime.now(); System.out.println(datetime.dayOfMonth().roundFloorCopy()); System.out.println(String.format("%04d", 1)); } }
[ "@", "Entity", "@", "Table", "(", "name", "=", "\"", "crm_t_company_info", "\"", ")", "public", "class", "CompanyInfo", "extends", "IdEntity", "implements", "Serializable", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "private", "String", "annualSales", ";", "private", "String", "assetStatus", ";", "private", "String", "corporateInformation", ";", "private", "String", "customerCode", ";", "private", "String", "established", ";", "private", "String", "flowId", ";", "private", "String", "industry", ";", "private", "String", "jobAdress", ";", "private", "String", "liabilities", ";", "private", "String", "memo", ";", "private", "String", "moneyPurpose", ";", "private", "String", "name", ";", "private", "String", "operationStatus", ";", "private", "String", "registeredCapital", ";", "private", "String", "scale", ";", "private", "String", "status", ";", "private", "String", "upsadown", ";", "private", "String", "phoneNum", ";", "public", "CompanyInfo", "(", ")", "{", "}", "public", "String", "getPhoneNum", "(", ")", "{", "return", "phoneNum", ";", "}", "public", "void", "setPhoneNum", "(", "String", "phoneNum", ")", "{", "this", ".", "phoneNum", "=", "phoneNum", ";", "}", "public", "String", "getAnnualSales", "(", ")", "{", "return", "this", ".", "annualSales", ";", "}", "public", "void", "setAnnualSales", "(", "String", "annualSales", ")", "{", "this", ".", "annualSales", "=", "annualSales", ";", "}", "public", "String", "getAssetStatus", "(", ")", "{", "return", "this", ".", "assetStatus", ";", "}", "public", "void", "setAssetStatus", "(", "String", "assetStatus", ")", "{", "this", ".", "assetStatus", "=", "assetStatus", ";", "}", "public", "String", "getCorporateInformation", "(", ")", "{", "return", "this", ".", "corporateInformation", ";", "}", "public", "void", "setCorporateInformation", "(", "String", "corporateInformation", ")", "{", "this", ".", "corporateInformation", "=", "corporateInformation", ";", "}", "public", "String", "getCustomerCode", "(", ")", "{", "return", "this", ".", "customerCode", ";", "}", "public", "void", "setCustomerCode", "(", "String", "customerCode", ")", "{", "this", ".", "customerCode", "=", "customerCode", ";", "}", "public", "String", "getEstablished", "(", ")", "{", "return", "this", ".", "established", ";", "}", "public", "void", "setEstablished", "(", "String", "established", ")", "{", "this", ".", "established", "=", "established", ";", "}", "public", "String", "getFlowId", "(", ")", "{", "return", "this", ".", "flowId", ";", "}", "public", "void", "setFlowId", "(", "String", "flowId", ")", "{", "this", ".", "flowId", "=", "flowId", ";", "}", "public", "String", "getIndustry", "(", ")", "{", "return", "this", ".", "industry", ";", "}", "public", "void", "setIndustry", "(", "String", "industry", ")", "{", "this", ".", "industry", "=", "industry", ";", "}", "public", "String", "getJobAdress", "(", ")", "{", "return", "this", ".", "jobAdress", ";", "}", "public", "void", "setJobAdress", "(", "String", "jobAdress", ")", "{", "this", ".", "jobAdress", "=", "jobAdress", ";", "}", "public", "String", "getLiabilities", "(", ")", "{", "return", "this", ".", "liabilities", ";", "}", "public", "void", "setLiabilities", "(", "String", "liabilities", ")", "{", "this", ".", "liabilities", "=", "liabilities", ";", "}", "public", "String", "getMemo", "(", ")", "{", "return", "this", ".", "memo", ";", "}", "public", "void", "setMemo", "(", "String", "memo", ")", "{", "this", ".", "memo", "=", "memo", ";", "}", "public", "String", "getMoneyPurpose", "(", ")", "{", "return", "this", ".", "moneyPurpose", ";", "}", "public", "void", "setMoneyPurpose", "(", "String", "moneyPurpose", ")", "{", "this", ".", "moneyPurpose", "=", "moneyPurpose", ";", "}", "public", "String", "getName", "(", ")", "{", "return", "this", ".", "name", ";", "}", "public", "void", "setName", "(", "String", "name", ")", "{", "this", ".", "name", "=", "name", ";", "}", "public", "String", "getOperationStatus", "(", ")", "{", "return", "this", ".", "operationStatus", ";", "}", "public", "void", "setOperationStatus", "(", "String", "operationStatus", ")", "{", "this", ".", "operationStatus", "=", "operationStatus", ";", "}", "public", "String", "getRegisteredCapital", "(", ")", "{", "return", "this", ".", "registeredCapital", ";", "}", "public", "void", "setRegisteredCapital", "(", "String", "registeredCapital", ")", "{", "this", ".", "registeredCapital", "=", "registeredCapital", ";", "}", "public", "String", "getScale", "(", ")", "{", "return", "this", ".", "scale", ";", "}", "public", "void", "setScale", "(", "String", "scale", ")", "{", "this", ".", "scale", "=", "scale", ";", "}", "public", "String", "getStatus", "(", ")", "{", "return", "this", ".", "status", ";", "}", "public", "void", "setStatus", "(", "String", "status", ")", "{", "this", ".", "status", "=", "status", ";", "}", "public", "String", "getUpsadown", "(", ")", "{", "return", "this", ".", "upsadown", ";", "}", "public", "void", "setUpsadown", "(", "String", "upsadown", ")", "{", "this", ".", "upsadown", "=", "upsadown", ";", "}", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "DateTime", "datetime", "=", "DateTime", ".", "now", "(", ")", ";", "System", ".", "out", ".", "println", "(", "datetime", ".", "dayOfMonth", "(", ")", ".", "roundFloorCopy", "(", ")", ")", ";", "System", ".", "out", ".", "println", "(", "String", ".", "format", "(", "\"", "%04d", "\"", ",", "1", ")", ")", ";", "}", "}" ]
The persistent class for the crm_t_company_info database table.
[ "The", "persistent", "class", "for", "the", "crm_t_company_info", "database", "table", "." ]
[]
[ { "param": "IdEntity", "type": null }, { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IdEntity", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
6982d4ae494fcf87eefefa3a3794e6f795cf5d6b
bandrefilipe/brewer
brewer-application/src/main/java/io/bandrefilipe/brewer/application/core/domain/vo/SKU.java
[ "MIT" ]
Java
SKU
/** * @author bandrefilipe * @since 2020-10-22 */
@author bandrefilipe @since 2020-10-22
[ "@author", "bandrefilipe", "@since", "2020", "-", "10", "-", "22" ]
@Slf4j @Getter @EqualsAndHashCode public final class SKU { private final String value; private SKU(final String value) { log.debug("Constructing SKU for value \"{}\"", value); if (value == null) { this.value = null; } else { this.value = Optional .ofNullable(Strings.replaceAllNonWordCharacters(value, Strings.EMPTY)) .map(Strings::trimToNull) .map(Strings::toRootUpperCase) .orElseThrow(ParseException::new); } log.debug("SKU \"{}\" constructed", this); } public static SKU empty() { return new SKU(null); } public static SKU valueOf(final String sku) { return new SKU(sku); } @Override public String toString() { return Objects.toString(this.value); } }
[ "@", "Slf4j", "@", "Getter", "@", "EqualsAndHashCode", "public", "final", "class", "SKU", "{", "private", "final", "String", "value", ";", "private", "SKU", "(", "final", "String", "value", ")", "{", "log", ".", "debug", "(", "\"", "Constructing SKU for value ", "\\\"", "{}", "\\\"", "\"", ",", "value", ")", ";", "if", "(", "value", "==", "null", ")", "{", "this", ".", "value", "=", "null", ";", "}", "else", "{", "this", ".", "value", "=", "Optional", ".", "ofNullable", "(", "Strings", ".", "replaceAllNonWordCharacters", "(", "value", ",", "Strings", ".", "EMPTY", ")", ")", ".", "map", "(", "Strings", "::", "trimToNull", ")", ".", "map", "(", "Strings", "::", "toRootUpperCase", ")", ".", "orElseThrow", "(", "ParseException", "::", "new", ")", ";", "}", "log", ".", "debug", "(", "\"", "SKU ", "\\\"", "{}", "\\\"", " constructed", "\"", ",", "this", ")", ";", "}", "public", "static", "SKU", "empty", "(", ")", "{", "return", "new", "SKU", "(", "null", ")", ";", "}", "public", "static", "SKU", "valueOf", "(", "final", "String", "sku", ")", "{", "return", "new", "SKU", "(", "sku", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "Objects", ".", "toString", "(", "this", ".", "value", ")", ";", "}", "}" ]
@author bandrefilipe @since 2020-10-22
[ "@author", "bandrefilipe", "@since", "2020", "-", "10", "-", "22" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
69882aca0d01a5468cde411375b8b0d2af5d469c
gskorupa/signomix-iotdata
src/main/java/com/signomix/iot/chirpstack/uplink/TxInfo.java
[ "MIT" ]
Java
TxInfo
/** * * @author Grzegorz Skorupa <g.skorupa at gmail.com> */
@author Grzegorz Skorupa
[ "@author", "Grzegorz", "Skorupa" ]
public class TxInfo { private long frequency; private long dr; /** * @return the frequency */ public long getFrequency() { return frequency; } /** * @param frequency the frequency to set */ public void setFrequency(long frequency) { this.frequency = frequency; } /** * @return the dr */ public long getDr() { return dr; } /** * @param dr the dr to set */ public void setDr(long dr) { this.dr = dr; } }
[ "public", "class", "TxInfo", "{", "private", "long", "frequency", ";", "private", "long", "dr", ";", "/**\n * @return the frequency\n */", "public", "long", "getFrequency", "(", ")", "{", "return", "frequency", ";", "}", "/**\n * @param frequency the frequency to set\n */", "public", "void", "setFrequency", "(", "long", "frequency", ")", "{", "this", ".", "frequency", "=", "frequency", ";", "}", "/**\n * @return the dr\n */", "public", "long", "getDr", "(", ")", "{", "return", "dr", ";", "}", "/**\n * @param dr the dr to set\n */", "public", "void", "setDr", "(", "long", "dr", ")", "{", "this", ".", "dr", "=", "dr", ";", "}", "}" ]
@author Grzegorz Skorupa <g.skorupa at gmail.com>
[ "@author", "Grzegorz", "Skorupa", "<g", ".", "skorupa", "at", "gmail", ".", "com", ">" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
698b5fbf56e64a14b87dc69759c7d16fb190a77a
tudelft-cse-cp-cg-2/wrath-of-osiris
client/src/main/java/nl/tudelft/context/cg2/client/model/files/Sound.java
[ "CC0-1.0" ]
Java
Sound
/** * Serves as a wrapper class for the Clip class. */
Serves as a wrapper class for the Clip class.
[ "Serves", "as", "a", "wrapper", "class", "for", "the", "Clip", "class", "." ]
public class Sound { private Clip clip; private float volume; /** * Make sure sound objects can only be created by the loadSound method. * @param clip The audio clip. */ Sound(Clip clip) { this.clip = clip; volume = 1f; } /** * Plays the sound from the start. */ public void play() { stop(); clip.setFramePosition(0); clip.start(); } /** * Starts looping the sound from the current frame position. */ public void loop() { clip.loop(Clip.LOOP_CONTINUOUSLY); } /** * Stop playing the sound. */ public void stop() { clip.stop(); } /** * Gets the volume of the sound. * @return The volume between 0.0f and 1.0f. */ public float getVolume() { return volume; } /** * Set the volume of the sound. * @param volume The volume between 0.0f and 1.0f. */ public void setVolume(float volume) { this.volume = volume; FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); float range = gainControl.getMaximum() - gainControl.getMinimum(); float gain = range * volume + gainControl.getMinimum(); gainControl.setValue(gain); } /** * Loads a sound. * @param path The path to the sound. * @return The sound. * @throws Exception When the sound could not be loaded. */ public static Sound loadSound(URL path) throws Exception { Clip clip = AudioSystem.getClip(); AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(path); clip.open(audioInputStream); return new Sound(clip); } }
[ "public", "class", "Sound", "{", "private", "Clip", "clip", ";", "private", "float", "volume", ";", "/**\n * Make sure sound objects can only be created by the loadSound method.\n * @param clip The audio clip.\n */", "Sound", "(", "Clip", "clip", ")", "{", "this", ".", "clip", "=", "clip", ";", "volume", "=", "1f", ";", "}", "/**\n * Plays the sound from the start.\n */", "public", "void", "play", "(", ")", "{", "stop", "(", ")", ";", "clip", ".", "setFramePosition", "(", "0", ")", ";", "clip", ".", "start", "(", ")", ";", "}", "/**\n * Starts looping the sound from the current frame position.\n */", "public", "void", "loop", "(", ")", "{", "clip", ".", "loop", "(", "Clip", ".", "LOOP_CONTINUOUSLY", ")", ";", "}", "/**\n * Stop playing the sound.\n */", "public", "void", "stop", "(", ")", "{", "clip", ".", "stop", "(", ")", ";", "}", "/**\n * Gets the volume of the sound.\n * @return The volume between 0.0f and 1.0f.\n */", "public", "float", "getVolume", "(", ")", "{", "return", "volume", ";", "}", "/**\n * Set the volume of the sound.\n * @param volume The volume between 0.0f and 1.0f.\n */", "public", "void", "setVolume", "(", "float", "volume", ")", "{", "this", ".", "volume", "=", "volume", ";", "FloatControl", "gainControl", "=", "(", "FloatControl", ")", "clip", ".", "getControl", "(", "FloatControl", ".", "Type", ".", "MASTER_GAIN", ")", ";", "float", "range", "=", "gainControl", ".", "getMaximum", "(", ")", "-", "gainControl", ".", "getMinimum", "(", ")", ";", "float", "gain", "=", "range", "*", "volume", "+", "gainControl", ".", "getMinimum", "(", ")", ";", "gainControl", ".", "setValue", "(", "gain", ")", ";", "}", "/**\n * Loads a sound.\n * @param path The path to the sound.\n * @return The sound.\n * @throws Exception When the sound could not be loaded.\n */", "public", "static", "Sound", "loadSound", "(", "URL", "path", ")", "throws", "Exception", "{", "Clip", "clip", "=", "AudioSystem", ".", "getClip", "(", ")", ";", "AudioInputStream", "audioInputStream", "=", "AudioSystem", ".", "getAudioInputStream", "(", "path", ")", ";", "clip", ".", "open", "(", "audioInputStream", ")", ";", "return", "new", "Sound", "(", "clip", ")", ";", "}", "}" ]
Serves as a wrapper class for the Clip class.
[ "Serves", "as", "a", "wrapper", "class", "for", "the", "Clip", "class", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
698b66da024e321cd64c7c91559d929c3be1611c
sganjoo/99-problems
java8/src/main/java/com/shekhargulati/tadm/ch03/Problem3_1.java
[ "MIT" ]
Java
Problem3_1
/** * A common problem for compilers and text editors is determining whether the parentheses in a string are balanced and properly nested. * For example, the string ((())())() contains properly nested pairs of parentheses, which the strings )()( and ()) do not. * Give an algorithm that returns true if a string contains properly nested and balanced parentheses, and false if otherwise. * For full credit, identify the position of the first offending parenthesis if the string is not properly nested and balanced. */
A common problem for compilers and text editors is determining whether the parentheses in a string are balanced and properly nested.
[ "A", "common", "problem", "for", "compilers", "and", "text", "editors", "is", "determining", "whether", "the", "parentheses", "in", "a", "string", "are", "balanced", "and", "properly", "nested", "." ]
public class Problem3_1 { public boolean isBalancedString(final String input) { /* Algorithm: 1. Iterate over all the characters in a String 2. if stack is not empty and character is ')' then pop the element from the stack 3. else push the element into the stack 4. After iteration if stack is empty then return true else return false. */ Stack<Character> stack = new Stack<>(); char[] chars = input.toCharArray(); for (char ch : chars) { if (ch == ')' && !stack.empty()) { stack.pop(); } else { stack.push(ch); } } return stack.isEmpty(); } public int firstOffendingParenthesis(String input) { /* Algorithm: 1. Iterate over all the characters of input String 2. If character is ')' and stack is not empty then remove element from stack 3. Else add the position into the stack 4. After iteration, if stack is empty then return -1 else get the first element and return its value. */ Stack<Integer> stack = new Stack<>(); for (int i = 0; i < input.length(); i++) { if (input.charAt(i) == ')' && !stack.empty()) { stack.pop(); } else { stack.push(i); } } return stack.empty() ? -1 : stack.elementAt(0); } }
[ "public", "class", "Problem3_1", "{", "public", "boolean", "isBalancedString", "(", "final", "String", "input", ")", "{", "/*\n Algorithm:\n 1. Iterate over all the characters in a String\n 2. if stack is not empty and character is ')' then pop the element from the stack\n 3. else push the element into the stack\n 4. After iteration if stack is empty then return true else return false.\n */", "Stack", "<", "Character", ">", "stack", "=", "new", "Stack", "<", ">", "(", ")", ";", "char", "[", "]", "chars", "=", "input", ".", "toCharArray", "(", ")", ";", "for", "(", "char", "ch", ":", "chars", ")", "{", "if", "(", "ch", "==", "')'", "&&", "!", "stack", ".", "empty", "(", ")", ")", "{", "stack", ".", "pop", "(", ")", ";", "}", "else", "{", "stack", ".", "push", "(", "ch", ")", ";", "}", "}", "return", "stack", ".", "isEmpty", "(", ")", ";", "}", "public", "int", "firstOffendingParenthesis", "(", "String", "input", ")", "{", "/*\n Algorithm:\n 1. Iterate over all the characters of input String\n 2. If character is ')' and stack is not empty then remove element from stack\n 3. Else add the position into the stack\n 4. After iteration, if stack is empty then return -1 else get the first element and return its value.\n */", "Stack", "<", "Integer", ">", "stack", "=", "new", "Stack", "<", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "input", ".", "length", "(", ")", ";", "i", "++", ")", "{", "if", "(", "input", ".", "charAt", "(", "i", ")", "==", "')'", "&&", "!", "stack", ".", "empty", "(", ")", ")", "{", "stack", ".", "pop", "(", ")", ";", "}", "else", "{", "stack", ".", "push", "(", "i", ")", ";", "}", "}", "return", "stack", ".", "empty", "(", ")", "?", "-", "1", ":", "stack", ".", "elementAt", "(", "0", ")", ";", "}", "}" ]
A common problem for compilers and text editors is determining whether the parentheses in a string are balanced and properly nested.
[ "A", "common", "problem", "for", "compilers", "and", "text", "editors", "is", "determining", "whether", "the", "parentheses", "in", "a", "string", "are", "balanced", "and", "properly", "nested", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
698e6586836365814b9bd2408cdb2ac31812e765
pasindujw/product-emm
modules/apps/jax-rs/mdm-admin/src/main/java/org/wso2/carbon/mdm/api/Configuration.java
[ "Apache-2.0" ]
Java
Configuration
/** * General Tenant Configuration REST-API implementation. * All end points support JSON, XMl with content negotiation. */
General Tenant Configuration REST-API implementation. All end points support JSON, XMl with content negotiation.
[ "General", "Tenant", "Configuration", "REST", "-", "API", "implementation", ".", "All", "end", "points", "support", "JSON", "XMl", "with", "content", "negotiation", "." ]
@WebService @Produces({ "application/json", "application/xml" }) @Consumes({ "application/json", "application/xml" }) public class Configuration { private static Log log = LogFactory.getLog(Configuration.class); @POST public ResponsePayload saveTenantConfiguration(TenantConfiguration configuration) throws MDMAPIException { ResponsePayload responseMsg = new ResponsePayload(); try { MDMAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration, MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); //Schedule the task service MDMAPIUtils.scheduleTaskService(MDMAPIUtils.getNotifierFrequency(configuration)); Response.status(HttpStatus.SC_CREATED); responseMsg.setMessageFromServer("Tenant configuration saved successfully."); responseMsg.setStatusCode(HttpStatus.SC_CREATED); return responseMsg; } catch (ConfigurationManagementException e) { String msg = "Error occurred while saving the tenant configuration."; log.error(msg, e); throw new MDMAPIException(msg, e); } } @GET public TenantConfiguration getConfiguration() throws MDMAPIException { String msg; try { TenantConfiguration tenantConfiguration = MDMAPIUtils.getTenantConfigurationManagementService(). getConfiguration(MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); ConfigurationEntry configurationEntry = new ConfigurationEntry(); configurationEntry.setContentType("text"); configurationEntry.setName("notifierFrequency"); configurationEntry.setValue(PolicyManagerUtil.getMonitoringFequency()); List<ConfigurationEntry> configList = tenantConfiguration.getConfiguration(); if (configList == null) { configList = new ArrayList<ConfigurationEntry>(); } configList.add(configurationEntry); tenantConfiguration.setConfiguration(configList); return tenantConfiguration; } catch (ConfigurationManagementException e) { msg = "Error occurred while retrieving the tenant configuration."; log.error(msg, e); throw new MDMAPIException(msg, e); } } @PUT public ResponsePayload updateConfiguration(TenantConfiguration configuration) throws MDMAPIException { ResponsePayload responseMsg = new ResponsePayload(); try { MDMAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration, MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); //Schedule the task service MDMAPIUtils.scheduleTaskService(MDMAPIUtils.getNotifierFrequency(configuration)); Response.status(HttpStatus.SC_CREATED); responseMsg.setMessageFromServer("Tenant configuration updated successfully."); responseMsg.setStatusCode(HttpStatus.SC_CREATED); return responseMsg; } catch (ConfigurationManagementException e) { String msg = "Error occurred while updating the tenant configuration."; log.error(msg, e); throw new MDMAPIException(msg, e); } } }
[ "@", "WebService", "@", "Produces", "(", "{", "\"", "application/json", "\"", ",", "\"", "application/xml", "\"", "}", ")", "@", "Consumes", "(", "{", "\"", "application/json", "\"", ",", "\"", "application/xml", "\"", "}", ")", "public", "class", "Configuration", "{", "private", "static", "Log", "log", "=", "LogFactory", ".", "getLog", "(", "Configuration", ".", "class", ")", ";", "@", "POST", "public", "ResponsePayload", "saveTenantConfiguration", "(", "TenantConfiguration", "configuration", ")", "throws", "MDMAPIException", "{", "ResponsePayload", "responseMsg", "=", "new", "ResponsePayload", "(", ")", ";", "try", "{", "MDMAPIUtils", ".", "getTenantConfigurationManagementService", "(", ")", ".", "saveConfiguration", "(", "configuration", ",", "MDMAppConstants", ".", "RegistryConstants", ".", "GENERAL_CONFIG_RESOURCE_PATH", ")", ";", "MDMAPIUtils", ".", "scheduleTaskService", "(", "MDMAPIUtils", ".", "getNotifierFrequency", "(", "configuration", ")", ")", ";", "Response", ".", "status", "(", "HttpStatus", ".", "SC_CREATED", ")", ";", "responseMsg", ".", "setMessageFromServer", "(", "\"", "Tenant configuration saved successfully.", "\"", ")", ";", "responseMsg", ".", "setStatusCode", "(", "HttpStatus", ".", "SC_CREATED", ")", ";", "return", "responseMsg", ";", "}", "catch", "(", "ConfigurationManagementException", "e", ")", "{", "String", "msg", "=", "\"", "Error occurred while saving the tenant configuration.", "\"", ";", "log", ".", "error", "(", "msg", ",", "e", ")", ";", "throw", "new", "MDMAPIException", "(", "msg", ",", "e", ")", ";", "}", "}", "@", "GET", "public", "TenantConfiguration", "getConfiguration", "(", ")", "throws", "MDMAPIException", "{", "String", "msg", ";", "try", "{", "TenantConfiguration", "tenantConfiguration", "=", "MDMAPIUtils", ".", "getTenantConfigurationManagementService", "(", ")", ".", "getConfiguration", "(", "MDMAppConstants", ".", "RegistryConstants", ".", "GENERAL_CONFIG_RESOURCE_PATH", ")", ";", "ConfigurationEntry", "configurationEntry", "=", "new", "ConfigurationEntry", "(", ")", ";", "configurationEntry", ".", "setContentType", "(", "\"", "text", "\"", ")", ";", "configurationEntry", ".", "setName", "(", "\"", "notifierFrequency", "\"", ")", ";", "configurationEntry", ".", "setValue", "(", "PolicyManagerUtil", ".", "getMonitoringFequency", "(", ")", ")", ";", "List", "<", "ConfigurationEntry", ">", "configList", "=", "tenantConfiguration", ".", "getConfiguration", "(", ")", ";", "if", "(", "configList", "==", "null", ")", "{", "configList", "=", "new", "ArrayList", "<", "ConfigurationEntry", ">", "(", ")", ";", "}", "configList", ".", "add", "(", "configurationEntry", ")", ";", "tenantConfiguration", ".", "setConfiguration", "(", "configList", ")", ";", "return", "tenantConfiguration", ";", "}", "catch", "(", "ConfigurationManagementException", "e", ")", "{", "msg", "=", "\"", "Error occurred while retrieving the tenant configuration.", "\"", ";", "log", ".", "error", "(", "msg", ",", "e", ")", ";", "throw", "new", "MDMAPIException", "(", "msg", ",", "e", ")", ";", "}", "}", "@", "PUT", "public", "ResponsePayload", "updateConfiguration", "(", "TenantConfiguration", "configuration", ")", "throws", "MDMAPIException", "{", "ResponsePayload", "responseMsg", "=", "new", "ResponsePayload", "(", ")", ";", "try", "{", "MDMAPIUtils", ".", "getTenantConfigurationManagementService", "(", ")", ".", "saveConfiguration", "(", "configuration", ",", "MDMAppConstants", ".", "RegistryConstants", ".", "GENERAL_CONFIG_RESOURCE_PATH", ")", ";", "MDMAPIUtils", ".", "scheduleTaskService", "(", "MDMAPIUtils", ".", "getNotifierFrequency", "(", "configuration", ")", ")", ";", "Response", ".", "status", "(", "HttpStatus", ".", "SC_CREATED", ")", ";", "responseMsg", ".", "setMessageFromServer", "(", "\"", "Tenant configuration updated successfully.", "\"", ")", ";", "responseMsg", ".", "setStatusCode", "(", "HttpStatus", ".", "SC_CREATED", ")", ";", "return", "responseMsg", ";", "}", "catch", "(", "ConfigurationManagementException", "e", ")", "{", "String", "msg", "=", "\"", "Error occurred while updating the tenant configuration.", "\"", ";", "log", ".", "error", "(", "msg", ",", "e", ")", ";", "throw", "new", "MDMAPIException", "(", "msg", ",", "e", ")", ";", "}", "}", "}" ]
General Tenant Configuration REST-API implementation.
[ "General", "Tenant", "Configuration", "REST", "-", "API", "implementation", "." ]
[ "//Schedule the task service", "//Schedule the task service" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
6990e1e6b01c82de8c0e79c9c03a414d4a26cfc5
mmm-soares/concurrency-java-9
Chapter04/AdvancedServer/src/com/javferna/packtpub/mastering/advancedServer/parallel/log/Logger.java
[ "MIT" ]
Java
Logger
/** * Class that implements a concurrent logger system * @author author * */
Class that implements a concurrent logger system @author author
[ "Class", "that", "implements", "a", "concurrent", "logger", "system", "@author", "author" ]
public class Logger { /** * Queue to store the log messages */ private static ConcurrentLinkedQueue<String> logQueue = new ConcurrentLinkedQueue<String>(); /** * Thread to execute the Log Task */ private static Thread thread; /** * Route to the file where we will write the log */ private static final String ROUTE = "output\\server.log"; /** * Block of code that initializes the Log task */ static { LogTask task = new LogTask(); thread = new Thread(task); thread.start(); } /** * Method that write a message in the log * @param message Message to write in the log */ public static void sendMessage(String message) { StringWriter writer = new StringWriter(); writer.write(new Date().toString()); writer.write(": "); writer.write(message); logQueue.offer(writer.toString()); } /** * Method that write all the messages in the queue to the file */ public static void writeLogs() { String message; Path path = Paths.get(ROUTE); try (BufferedWriter fileWriter = Files.newBufferedWriter(path,StandardOpenOption.CREATE, StandardOpenOption.APPEND)) { while ((message = logQueue.poll()) != null) { StringWriter writer = new StringWriter(); writer.write(new Date().toString()); writer.write(": "); writer.write(message); fileWriter.write(writer.toString()); fileWriter.newLine(); } } catch (IOException e) { e.printStackTrace(); } } /** * Method that clean the file */ public static void initializeLog() { Path path = Paths.get(ROUTE); if (Files.exists(path)) { try (OutputStream out = Files.newOutputStream(path, StandardOpenOption.TRUNCATE_EXISTING)) { } catch (IOException e) { e.printStackTrace(); } } } /** * Method that stops the execution of the log system */ public static void shutdown() { writeLogs(); thread.interrupt(); } }
[ "public", "class", "Logger", "{", "/**\n\t * Queue to store the log messages\n\t */", "private", "static", "ConcurrentLinkedQueue", "<", "String", ">", "logQueue", "=", "new", "ConcurrentLinkedQueue", "<", "String", ">", "(", ")", ";", "/**\n\t * Thread to execute the Log Task \n\t */", "private", "static", "Thread", "thread", ";", "/**\n\t * Route to the file where we will write the log\n\t */", "private", "static", "final", "String", "ROUTE", "=", "\"", "output", "\\\\", "server.log", "\"", ";", "/**\n\t * Block of code that initializes the Log task\n\t */", "static", "{", "LogTask", "task", "=", "new", "LogTask", "(", ")", ";", "thread", "=", "new", "Thread", "(", "task", ")", ";", "thread", ".", "start", "(", ")", ";", "}", "/**\n\t * Method that write a message in the log\n\t * @param message Message to write in the log\n\t */", "public", "static", "void", "sendMessage", "(", "String", "message", ")", "{", "StringWriter", "writer", "=", "new", "StringWriter", "(", ")", ";", "writer", ".", "write", "(", "new", "Date", "(", ")", ".", "toString", "(", ")", ")", ";", "writer", ".", "write", "(", "\"", ": ", "\"", ")", ";", "writer", ".", "write", "(", "message", ")", ";", "logQueue", ".", "offer", "(", "writer", ".", "toString", "(", ")", ")", ";", "}", "/**\n\t * Method that write all the messages in the queue to the file\n\t */", "public", "static", "void", "writeLogs", "(", ")", "{", "String", "message", ";", "Path", "path", "=", "Paths", ".", "get", "(", "ROUTE", ")", ";", "try", "(", "BufferedWriter", "fileWriter", "=", "Files", ".", "newBufferedWriter", "(", "path", ",", "StandardOpenOption", ".", "CREATE", ",", "StandardOpenOption", ".", "APPEND", ")", ")", "{", "while", "(", "(", "message", "=", "logQueue", ".", "poll", "(", ")", ")", "!=", "null", ")", "{", "StringWriter", "writer", "=", "new", "StringWriter", "(", ")", ";", "writer", ".", "write", "(", "new", "Date", "(", ")", ".", "toString", "(", ")", ")", ";", "writer", ".", "write", "(", "\"", ": ", "\"", ")", ";", "writer", ".", "write", "(", "message", ")", ";", "fileWriter", ".", "write", "(", "writer", ".", "toString", "(", ")", ")", ";", "fileWriter", ".", "newLine", "(", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "/**\n\t * Method that clean the file\n\t */", "public", "static", "void", "initializeLog", "(", ")", "{", "Path", "path", "=", "Paths", ".", "get", "(", "ROUTE", ")", ";", "if", "(", "Files", ".", "exists", "(", "path", ")", ")", "{", "try", "(", "OutputStream", "out", "=", "Files", ".", "newOutputStream", "(", "path", ",", "StandardOpenOption", ".", "TRUNCATE_EXISTING", ")", ")", "{", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "}", "/**\n\t * Method that stops the execution of the log system\n\t */", "public", "static", "void", "shutdown", "(", ")", "{", "writeLogs", "(", ")", ";", "thread", ".", "interrupt", "(", ")", ";", "}", "}" ]
Class that implements a concurrent logger system @author author
[ "Class", "that", "implements", "a", "concurrent", "logger", "system", "@author", "author" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
699b931465a587ffd2c3cfa45eadcd82cfc60d29
detnavillus/modular-informatic-designs
search-core/src/main/java/com/modinfodesigns/search/SortProperty.java
[ "Apache-2.0" ]
Java
SortProperty
/** * Describes a Sort request. Sortable field and sort direction. Nesting enables multiple * sort levels to be specified. * * Subclasses of SortProperty can override the getValue( ) method to * format the sort output in a platform-specific manner. * * @author Ted Sullivan * */
Describes a Sort request. Sortable field and sort direction. Nesting enables multiple sort levels to be specified. Subclasses of SortProperty can override the getValue( ) method to format the sort output in a platform-specific manner. @author Ted Sullivan
[ "Describes", "a", "Sort", "request", ".", "Sortable", "field", "and", "sort", "direction", ".", "Nesting", "enables", "multiple", "sort", "levels", "to", "be", "specified", ".", "Subclasses", "of", "SortProperty", "can", "override", "the", "getValue", "(", ")", "method", "to", "format", "the", "sort", "output", "in", "a", "platform", "-", "specific", "manner", ".", "@author", "Ted", "Sullivan" ]
public class SortProperty implements IProperty, IComputableProperties { private static ArrayList<String> intrinsics; public static final String SORT_FIELD = "SortField"; public static final String SORT_DIRECTION = "SortDirection"; public static final String SECONDARY_SORT = "SecondarySort"; public static final String ASCENDING = "ASC"; public static final String DESCENDING = "DESC"; public static final String RELEVANCE = "Relevance"; private String sortField; private String direction = ASCENDING; // ASC | DESC private String delimiter = ":"; private SortProperty secondarySort; static { intrinsics = new ArrayList<String>( ); intrinsics.add( SORT_FIELD ); intrinsics.add( SORT_DIRECTION ); intrinsics.add( SECONDARY_SORT ); } @Override public String getName() { return this.sortField; } @Override public void setName(String name) { setSortField( name ); } public void setSortField( String sortField ) { this.sortField = sortField; } public String getSortField( ) { return this.sortField; } public void setSortDirection( String sortDirection ) { this.direction = sortDirection; } public String getSortDirection( ) { return this.direction; } @Override public String getType() { return "com.modinfodesigns.search.SortProperty"; } @Override public String getValue() { String thisSort = new String( sortField + ":" + direction ); if (secondarySort != null) { thisSort = new String( thisSort + "|" + secondarySort.getValue() ); } return thisSort; } @Override public String getValue(String format) { String thisSort = new String( sortField + ":" + direction ); if (secondarySort != null) { thisSort += "|" + secondarySort.getValue( format ); } return thisSort; } @Override public void setValue(String value, String format) { if (format.equals( IProperty.DELIMITED_FORMAT ) && format.indexOf( delimiter ) > 0) { sortField = format.substring( 0, format.indexOf( delimiter )).trim(); direction = format.substring( format.indexOf( delimiter ) + 1 ).trim(); } else { sortField = value; } } @Override public IProperty copy() { SortProperty copy = new SortProperty( ); copy.sortField = this.sortField; copy.direction = this.direction; copy.secondarySort = (secondarySort != null) ? (SortProperty)secondarySort.copy() : null; return copy; } public void setSecondarySort( SortProperty secondarySort ) { if (this.secondarySort != null) { this.secondarySort.setSecondarySort( secondarySort ); } else { this.secondarySort = secondarySort; } } public SortProperty getSecondarySort( ) { return this.secondarySort; } public SortProperty[] getSortProperties( ) { if (secondarySort == null) { SortProperty[] sortList = new SortProperty[1]; sortList[0] = this; return sortList; } else { ArrayList<SortProperty> sortList = new ArrayList<SortProperty>( ); sortList.add( this ); secondarySort.addToSortList( sortList ); SortProperty[] outputArray = new SortProperty[ sortList.size( ) ]; sortList.toArray( outputArray ); return outputArray; } } private void addToSortList( ArrayList<SortProperty> sortList ) { sortList.add( this ); if (secondarySort != null) secondarySort.addToSortList( sortList ); } @Override public Object getValueObject() { return null; } @Override public String getDefaultFormat() { return null; } @Override public List<String> getIntrinsicProperties() { return intrinsics; } @Override public IProperty getIntrinsicProperty( String name ) { if (name.equals( SORT_FIELD ) && sortField != null) { return new StringProperty( SORT_FIELD, sortField ); } else if (name.equals( SORT_DIRECTION ) && direction != null ) { return new StringProperty( SORT_DIRECTION, direction ); } else if (name.equals( SECONDARY_SORT ) && direction != null ) { return secondarySort; } return null; } @Override public Map<String, String> getComputableProperties() { return null; } @Override public IProperty getComputedProperty( String name, IProperty fromProp ) { return null; } @Override public boolean isMultiValue() { return false; } @Override public String[] getValues(String format) { String[] values = new String[1]; values[0] = getValue( format ); return values; } }
[ "public", "class", "SortProperty", "implements", "IProperty", ",", "IComputableProperties", "{", "private", "static", "ArrayList", "<", "String", ">", "intrinsics", ";", "public", "static", "final", "String", "SORT_FIELD", "=", "\"", "SortField", "\"", ";", "public", "static", "final", "String", "SORT_DIRECTION", "=", "\"", "SortDirection", "\"", ";", "public", "static", "final", "String", "SECONDARY_SORT", "=", "\"", "SecondarySort", "\"", ";", "public", "static", "final", "String", "ASCENDING", "=", "\"", "ASC", "\"", ";", "public", "static", "final", "String", "DESCENDING", "=", "\"", "DESC", "\"", ";", "public", "static", "final", "String", "RELEVANCE", "=", "\"", "Relevance", "\"", ";", "private", "String", "sortField", ";", "private", "String", "direction", "=", "ASCENDING", ";", "private", "String", "delimiter", "=", "\"", ":", "\"", ";", "private", "SortProperty", "secondarySort", ";", "static", "{", "intrinsics", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "intrinsics", ".", "add", "(", "SORT_FIELD", ")", ";", "intrinsics", ".", "add", "(", "SORT_DIRECTION", ")", ";", "intrinsics", ".", "add", "(", "SECONDARY_SORT", ")", ";", "}", "@", "Override", "public", "String", "getName", "(", ")", "{", "return", "this", ".", "sortField", ";", "}", "@", "Override", "public", "void", "setName", "(", "String", "name", ")", "{", "setSortField", "(", "name", ")", ";", "}", "public", "void", "setSortField", "(", "String", "sortField", ")", "{", "this", ".", "sortField", "=", "sortField", ";", "}", "public", "String", "getSortField", "(", ")", "{", "return", "this", ".", "sortField", ";", "}", "public", "void", "setSortDirection", "(", "String", "sortDirection", ")", "{", "this", ".", "direction", "=", "sortDirection", ";", "}", "public", "String", "getSortDirection", "(", ")", "{", "return", "this", ".", "direction", ";", "}", "@", "Override", "public", "String", "getType", "(", ")", "{", "return", "\"", "com.modinfodesigns.search.SortProperty", "\"", ";", "}", "@", "Override", "public", "String", "getValue", "(", ")", "{", "String", "thisSort", "=", "new", "String", "(", "sortField", "+", "\"", ":", "\"", "+", "direction", ")", ";", "if", "(", "secondarySort", "!=", "null", ")", "{", "thisSort", "=", "new", "String", "(", "thisSort", "+", "\"", "|", "\"", "+", "secondarySort", ".", "getValue", "(", ")", ")", ";", "}", "return", "thisSort", ";", "}", "@", "Override", "public", "String", "getValue", "(", "String", "format", ")", "{", "String", "thisSort", "=", "new", "String", "(", "sortField", "+", "\"", ":", "\"", "+", "direction", ")", ";", "if", "(", "secondarySort", "!=", "null", ")", "{", "thisSort", "+=", "\"", "|", "\"", "+", "secondarySort", ".", "getValue", "(", "format", ")", ";", "}", "return", "thisSort", ";", "}", "@", "Override", "public", "void", "setValue", "(", "String", "value", ",", "String", "format", ")", "{", "if", "(", "format", ".", "equals", "(", "IProperty", ".", "DELIMITED_FORMAT", ")", "&&", "format", ".", "indexOf", "(", "delimiter", ")", ">", "0", ")", "{", "sortField", "=", "format", ".", "substring", "(", "0", ",", "format", ".", "indexOf", "(", "delimiter", ")", ")", ".", "trim", "(", ")", ";", "direction", "=", "format", ".", "substring", "(", "format", ".", "indexOf", "(", "delimiter", ")", "+", "1", ")", ".", "trim", "(", ")", ";", "}", "else", "{", "sortField", "=", "value", ";", "}", "}", "@", "Override", "public", "IProperty", "copy", "(", ")", "{", "SortProperty", "copy", "=", "new", "SortProperty", "(", ")", ";", "copy", ".", "sortField", "=", "this", ".", "sortField", ";", "copy", ".", "direction", "=", "this", ".", "direction", ";", "copy", ".", "secondarySort", "=", "(", "secondarySort", "!=", "null", ")", "?", "(", "SortProperty", ")", "secondarySort", ".", "copy", "(", ")", ":", "null", ";", "return", "copy", ";", "}", "public", "void", "setSecondarySort", "(", "SortProperty", "secondarySort", ")", "{", "if", "(", "this", ".", "secondarySort", "!=", "null", ")", "{", "this", ".", "secondarySort", ".", "setSecondarySort", "(", "secondarySort", ")", ";", "}", "else", "{", "this", ".", "secondarySort", "=", "secondarySort", ";", "}", "}", "public", "SortProperty", "getSecondarySort", "(", ")", "{", "return", "this", ".", "secondarySort", ";", "}", "public", "SortProperty", "[", "]", "getSortProperties", "(", ")", "{", "if", "(", "secondarySort", "==", "null", ")", "{", "SortProperty", "[", "]", "sortList", "=", "new", "SortProperty", "[", "1", "]", ";", "sortList", "[", "0", "]", "=", "this", ";", "return", "sortList", ";", "}", "else", "{", "ArrayList", "<", "SortProperty", ">", "sortList", "=", "new", "ArrayList", "<", "SortProperty", ">", "(", ")", ";", "sortList", ".", "add", "(", "this", ")", ";", "secondarySort", ".", "addToSortList", "(", "sortList", ")", ";", "SortProperty", "[", "]", "outputArray", "=", "new", "SortProperty", "[", "sortList", ".", "size", "(", ")", "]", ";", "sortList", ".", "toArray", "(", "outputArray", ")", ";", "return", "outputArray", ";", "}", "}", "private", "void", "addToSortList", "(", "ArrayList", "<", "SortProperty", ">", "sortList", ")", "{", "sortList", ".", "add", "(", "this", ")", ";", "if", "(", "secondarySort", "!=", "null", ")", "secondarySort", ".", "addToSortList", "(", "sortList", ")", ";", "}", "@", "Override", "public", "Object", "getValueObject", "(", ")", "{", "return", "null", ";", "}", "@", "Override", "public", "String", "getDefaultFormat", "(", ")", "{", "return", "null", ";", "}", "@", "Override", "public", "List", "<", "String", ">", "getIntrinsicProperties", "(", ")", "{", "return", "intrinsics", ";", "}", "@", "Override", "public", "IProperty", "getIntrinsicProperty", "(", "String", "name", ")", "{", "if", "(", "name", ".", "equals", "(", "SORT_FIELD", ")", "&&", "sortField", "!=", "null", ")", "{", "return", "new", "StringProperty", "(", "SORT_FIELD", ",", "sortField", ")", ";", "}", "else", "if", "(", "name", ".", "equals", "(", "SORT_DIRECTION", ")", "&&", "direction", "!=", "null", ")", "{", "return", "new", "StringProperty", "(", "SORT_DIRECTION", ",", "direction", ")", ";", "}", "else", "if", "(", "name", ".", "equals", "(", "SECONDARY_SORT", ")", "&&", "direction", "!=", "null", ")", "{", "return", "secondarySort", ";", "}", "return", "null", ";", "}", "@", "Override", "public", "Map", "<", "String", ",", "String", ">", "getComputableProperties", "(", ")", "{", "return", "null", ";", "}", "@", "Override", "public", "IProperty", "getComputedProperty", "(", "String", "name", ",", "IProperty", "fromProp", ")", "{", "return", "null", ";", "}", "@", "Override", "public", "boolean", "isMultiValue", "(", ")", "{", "return", "false", ";", "}", "@", "Override", "public", "String", "[", "]", "getValues", "(", "String", "format", ")", "{", "String", "[", "]", "values", "=", "new", "String", "[", "1", "]", ";", "values", "[", "0", "]", "=", "getValue", "(", "format", ")", ";", "return", "values", ";", "}", "}" ]
Describes a Sort request.
[ "Describes", "a", "Sort", "request", "." ]
[ "// ASC | DESC\r" ]
[ { "param": "IProperty, IComputableProperties", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IProperty, IComputableProperties", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
699dfa199402af141ec7304dc082f45e228d17fa
wfansh/anywhere-api-sample
IntegrationDemoApp/src/main/java/com/sap/integration/erp/dummy/entity/PaymentReport.java
[ "Apache-2.0" ]
Java
PaymentReport
/** * Payment report ERP database entity used by database layer of ERP. This class can be adjusted to reflect your * solution. */
Payment report ERP database entity used by database layer of ERP. This class can be adjusted to reflect your solution.
[ "Payment", "report", "ERP", "database", "entity", "used", "by", "database", "layer", "of", "ERP", ".", "This", "class", "can", "be", "adjusted", "to", "reflect", "your", "solution", "." ]
@Entity public class PaymentReport extends JpaLayer implements Serializable { private static final long serialVersionUID = -5172556604388101066L; private String methodInfo; private Integer numberOfPayments; private Double amount; private Double amountLC; @Convert("DummyJodaDate") private DateTime fromDate; @Convert("DummyJodaDate") private DateTime toDate; public String getMethodInfo() { return methodInfo; } public void setMethodInfo(String methodInfo) { this.methodInfo = methodInfo; } public Integer getNumberOfPayments() { return numberOfPayments; } public void setNumberOfPayments(Integer numberOfPayments) { this.numberOfPayments = numberOfPayments; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } public Double getAmountLC() { return amountLC; } public void setAmountLC(Double amountLC) { this.amountLC = amountLC; } public DateTime getFromDate() { return fromDate; } public void setFromDate(DateTime fromDate) { this.fromDate = fromDate; } public DateTime getToDate() { return toDate; } public void setToDate(DateTime toDate) { this.toDate = toDate; } @Override public String toString() { StringBuilder sb = new StringBuilder(this.getClass().getSimpleName()); sb.append(" [methodInfo="); sb.append(this.methodInfo); sb.append(", numberOfPayments="); sb.append(this.numberOfPayments); sb.append(", amount="); sb.append(this.amount); sb.append(", amountLC="); sb.append(this.amountLC); sb.append(", fromDate="); sb.append(this.fromDate); sb.append(", toDate="); sb.append(this.toDate); sb.append("]"); return sb.toString(); } }
[ "@", "Entity", "public", "class", "PaymentReport", "extends", "JpaLayer", "implements", "Serializable", "{", "private", "static", "final", "long", "serialVersionUID", "=", "-", "5172556604388101066L", ";", "private", "String", "methodInfo", ";", "private", "Integer", "numberOfPayments", ";", "private", "Double", "amount", ";", "private", "Double", "amountLC", ";", "@", "Convert", "(", "\"", "DummyJodaDate", "\"", ")", "private", "DateTime", "fromDate", ";", "@", "Convert", "(", "\"", "DummyJodaDate", "\"", ")", "private", "DateTime", "toDate", ";", "public", "String", "getMethodInfo", "(", ")", "{", "return", "methodInfo", ";", "}", "public", "void", "setMethodInfo", "(", "String", "methodInfo", ")", "{", "this", ".", "methodInfo", "=", "methodInfo", ";", "}", "public", "Integer", "getNumberOfPayments", "(", ")", "{", "return", "numberOfPayments", ";", "}", "public", "void", "setNumberOfPayments", "(", "Integer", "numberOfPayments", ")", "{", "this", ".", "numberOfPayments", "=", "numberOfPayments", ";", "}", "public", "Double", "getAmount", "(", ")", "{", "return", "amount", ";", "}", "public", "void", "setAmount", "(", "Double", "amount", ")", "{", "this", ".", "amount", "=", "amount", ";", "}", "public", "Double", "getAmountLC", "(", ")", "{", "return", "amountLC", ";", "}", "public", "void", "setAmountLC", "(", "Double", "amountLC", ")", "{", "this", ".", "amountLC", "=", "amountLC", ";", "}", "public", "DateTime", "getFromDate", "(", ")", "{", "return", "fromDate", ";", "}", "public", "void", "setFromDate", "(", "DateTime", "fromDate", ")", "{", "this", ".", "fromDate", "=", "fromDate", ";", "}", "public", "DateTime", "getToDate", "(", ")", "{", "return", "toDate", ";", "}", "public", "void", "setToDate", "(", "DateTime", "toDate", ")", "{", "this", ".", "toDate", "=", "toDate", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "this", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ";", "sb", ".", "append", "(", "\"", " [methodInfo=", "\"", ")", ";", "sb", ".", "append", "(", "this", ".", "methodInfo", ")", ";", "sb", ".", "append", "(", "\"", ", numberOfPayments=", "\"", ")", ";", "sb", ".", "append", "(", "this", ".", "numberOfPayments", ")", ";", "sb", ".", "append", "(", "\"", ", amount=", "\"", ")", ";", "sb", ".", "append", "(", "this", ".", "amount", ")", ";", "sb", ".", "append", "(", "\"", ", amountLC=", "\"", ")", ";", "sb", ".", "append", "(", "this", ".", "amountLC", ")", ";", "sb", ".", "append", "(", "\"", ", fromDate=", "\"", ")", ";", "sb", ".", "append", "(", "this", ".", "fromDate", ")", ";", "sb", ".", "append", "(", "\"", ", toDate=", "\"", ")", ";", "sb", ".", "append", "(", "this", ".", "toDate", ")", ";", "sb", ".", "append", "(", "\"", "]", "\"", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "}" ]
Payment report ERP database entity used by database layer of ERP.
[ "Payment", "report", "ERP", "database", "entity", "used", "by", "database", "layer", "of", "ERP", "." ]
[]
[ { "param": "JpaLayer", "type": null }, { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "JpaLayer", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69a0a6adcc78f35a1cd0d23ee6892d8a47ba7bbf
NCIP/psc
authentication/websso-plugin/src/test/java/edu/northwestern/bioinformatics/studycalendar/security/plugin/websso/direct/WebSSODirectAuthenticationProviderTest.java
[ "BSD-3-Clause" ]
Java
WebSSODirectAuthenticationProviderTest
/** * Note that this class only includes tests for differences between * {@link edu.northwestern.bioinformatics.studycalendar.security.plugin.websso.direct.WebSSODirectAuthenticationProvider} * and {@link * * @author Rhett Sutphin */
Note that this class only includes tests for differences between edu.northwestern.bioinformatics.studycalendar.security.plugin.websso.direct.WebSSODirectAuthenticationProvider and {@link @author Rhett Sutphin
[ "Note", "that", "this", "class", "only", "includes", "tests", "for", "differences", "between", "edu", ".", "northwestern", ".", "bioinformatics", ".", "studycalendar", ".", "security", ".", "plugin", ".", "websso", ".", "direct", ".", "WebSSODirectAuthenticationProvider", "and", "{", "@link", "@author", "Rhett", "Sutphin" ]
public class WebSSODirectAuthenticationProviderTest extends AuthenticationTestCase { private static final String CREDENTIAL_PROVIDER = ">Foo Provider"; private static final String ORGANIZATION = "Dorian"; private static final String USERNAME = "joe"; private static final String QUALIFIED_USERNAME = CREDENTIAL_PROVIDER + '\\' + ORGANIZATION + '\\' + USERNAME; private static final String PASSWORD = "eoj"; private static final String LT = "the-ticket"; private WebSSODirectAuthenticationProvider provider; private DirectLoginHttpFacade loginFacade; @Override protected void setUp() throws Exception { super.setUp(); loginFacade = registerMockFor(DirectLoginHttpFacade.class); provider = new WebSSODirectAuthenticationProvider() { @Override protected DirectLoginHttpFacade createLoginFacade() { return loginFacade; } }; provider.setUserDetailsService(userDetailsService); userDetailsService.addUser(USERNAME, PscRole.STUDY_SUBJECT_CALENDAR_MANAGER); } public void testUsernameOnlyPrincipalResultsInNoAuthentication() throws Exception { try { doAuthenticate(USERNAME); fail("Exception not thrown"); } catch (BadCredentialsException bce) { assertEquals("The principal must be of the form credential-provider\\authentication-service-name\\username", bce.getMessage()); } } public void testTooManyEntriesInPrincipalResultsInNoAuthentication() throws Exception { try { doAuthenticate("something\\else\\again\\and-again"); fail("Exception not thrown"); } catch (BadCredentialsException bce) { assertEquals("The principal must be of the form credential-provider\\authentication-service-name\\username", bce.getMessage()); } } public void testBadLoginFormResultsInNoAuthentication() throws Exception { /* expect */ loginFacade.start(); expect(loginFacade.selectCredentialProvider(CREDENTIAL_PROVIDER)).andThrow(new CasDirectException("Bad form")); try { doAuthenticate(); fail("Exception not thrown"); } catch (AuthenticationException ae) { assertContains("Wrong exception message", ae.getMessage(), "Direct CAS login failed"); assertContains("Wrong exception message", ae.getMessage(), "Bad form"); } } public void testUnavailableLoginFormResultsInNoAuthentication() throws Exception { /* expect */ loginFacade.start(); expect(loginFacade.selectCredentialProvider(CREDENTIAL_PROVIDER)).andThrow(new IOException("Bad connection")); try { doAuthenticate(); fail("Exception not thrown"); } catch (AuthenticationException ae) { assertContains("Wrong exception message", ae.getMessage(), "Direct CAS login failed"); assertContains("Wrong exception message", ae.getMessage(), "Bad connection"); } } public void testFailedPostResultsInNoAuthentication() throws Exception { /* expect */ loginFacade.start(); expect(loginFacade.selectCredentialProvider(CREDENTIAL_PROVIDER)). andReturn("<input name='lt' value='the-ticket'/><select id='authenticationServiceURL'><option value='http://dorian!/'>Dorian</select>"); /* expect */ loginFacade.selectAuthenticationService("http://dorian!/"); expect(loginFacade.postCredentials(USERNAME, PASSWORD)).andReturn(false); try { doAuthenticate(); fail("Exception not thrown"); } catch (BadCredentialsException bce) { assertEquals("Credentials are invalid according to direct CAS login", bce.getMessage()); } } public void testUnknownAuthenticationServiceFailsAuthentication() throws Exception { /* expect */ loginFacade.start(); expect(loginFacade.selectCredentialProvider(CREDENTIAL_PROVIDER)). andReturn("<input name='lt' value='the-ticket'/><select id='authenticationServiceURL'><option value='http://dorian!/'>Not Dorian</select>"); try { doAuthenticate(); fail("Exception not thrown"); } catch (BadCredentialsException bce) { assertEquals("The WebSSO server does not know of an authentication service named \"Dorian\"", bce.getMessage()); } } public void testSuccessfulPostResultsInAuthentication() throws Exception { /* expect */ loginFacade.start(); expect(loginFacade.selectCredentialProvider(CREDENTIAL_PROVIDER)). andReturn("<input name='lt' value='the-ticket'/><select id='authenticationServiceURL'><option value='http://dorian!/'>Dorian</select>"); /* expect */ loginFacade.selectAuthenticationService("http://dorian!/"); expect(loginFacade.postCredentials(USERNAME, PASSWORD)).andReturn(true); Authentication actual = doAuthenticate(); assertNotNull(actual); assertTrue(actual.isAuthenticated()); } private Authentication doAuthenticate() { return doAuthenticate(QUALIFIED_USERNAME); } private Authentication doAuthenticate(String qualifiedUsername) { replayMocks(); Authentication actual = provider.authenticate( new CasDirectUsernamePasswordAuthenticationToken(qualifiedUsername, PASSWORD)); verifyMocks(); return actual; } }
[ "public", "class", "WebSSODirectAuthenticationProviderTest", "extends", "AuthenticationTestCase", "{", "private", "static", "final", "String", "CREDENTIAL_PROVIDER", "=", "\"", ">Foo Provider", "\"", ";", "private", "static", "final", "String", "ORGANIZATION", "=", "\"", "Dorian", "\"", ";", "private", "static", "final", "String", "USERNAME", "=", "\"", "joe", "\"", ";", "private", "static", "final", "String", "QUALIFIED_USERNAME", "=", "CREDENTIAL_PROVIDER", "+", "'\\\\'", "+", "ORGANIZATION", "+", "'\\\\'", "+", "USERNAME", ";", "private", "static", "final", "String", "PASSWORD", "=", "\"", "eoj", "\"", ";", "private", "static", "final", "String", "LT", "=", "\"", "the-ticket", "\"", ";", "private", "WebSSODirectAuthenticationProvider", "provider", ";", "private", "DirectLoginHttpFacade", "loginFacade", ";", "@", "Override", "protected", "void", "setUp", "(", ")", "throws", "Exception", "{", "super", ".", "setUp", "(", ")", ";", "loginFacade", "=", "registerMockFor", "(", "DirectLoginHttpFacade", ".", "class", ")", ";", "provider", "=", "new", "WebSSODirectAuthenticationProvider", "(", ")", "{", "@", "Override", "protected", "DirectLoginHttpFacade", "createLoginFacade", "(", ")", "{", "return", "loginFacade", ";", "}", "}", ";", "provider", ".", "setUserDetailsService", "(", "userDetailsService", ")", ";", "userDetailsService", ".", "addUser", "(", "USERNAME", ",", "PscRole", ".", "STUDY_SUBJECT_CALENDAR_MANAGER", ")", ";", "}", "public", "void", "testUsernameOnlyPrincipalResultsInNoAuthentication", "(", ")", "throws", "Exception", "{", "try", "{", "doAuthenticate", "(", "USERNAME", ")", ";", "fail", "(", "\"", "Exception not thrown", "\"", ")", ";", "}", "catch", "(", "BadCredentialsException", "bce", ")", "{", "assertEquals", "(", "\"", "The principal must be of the form credential-provider", "\\\\", "authentication-service-name", "\\\\", "username", "\"", ",", "bce", ".", "getMessage", "(", ")", ")", ";", "}", "}", "public", "void", "testTooManyEntriesInPrincipalResultsInNoAuthentication", "(", ")", "throws", "Exception", "{", "try", "{", "doAuthenticate", "(", "\"", "something", "\\\\", "else", "\\\\", "again", "\\\\", "and-again", "\"", ")", ";", "fail", "(", "\"", "Exception not thrown", "\"", ")", ";", "}", "catch", "(", "BadCredentialsException", "bce", ")", "{", "assertEquals", "(", "\"", "The principal must be of the form credential-provider", "\\\\", "authentication-service-name", "\\\\", "username", "\"", ",", "bce", ".", "getMessage", "(", ")", ")", ";", "}", "}", "public", "void", "testBadLoginFormResultsInNoAuthentication", "(", ")", "throws", "Exception", "{", "/* expect */", "loginFacade", ".", "start", "(", ")", ";", "expect", "(", "loginFacade", ".", "selectCredentialProvider", "(", "CREDENTIAL_PROVIDER", ")", ")", ".", "andThrow", "(", "new", "CasDirectException", "(", "\"", "Bad form", "\"", ")", ")", ";", "try", "{", "doAuthenticate", "(", ")", ";", "fail", "(", "\"", "Exception not thrown", "\"", ")", ";", "}", "catch", "(", "AuthenticationException", "ae", ")", "{", "assertContains", "(", "\"", "Wrong exception message", "\"", ",", "ae", ".", "getMessage", "(", ")", ",", "\"", "Direct CAS login failed", "\"", ")", ";", "assertContains", "(", "\"", "Wrong exception message", "\"", ",", "ae", ".", "getMessage", "(", ")", ",", "\"", "Bad form", "\"", ")", ";", "}", "}", "public", "void", "testUnavailableLoginFormResultsInNoAuthentication", "(", ")", "throws", "Exception", "{", "/* expect */", "loginFacade", ".", "start", "(", ")", ";", "expect", "(", "loginFacade", ".", "selectCredentialProvider", "(", "CREDENTIAL_PROVIDER", ")", ")", ".", "andThrow", "(", "new", "IOException", "(", "\"", "Bad connection", "\"", ")", ")", ";", "try", "{", "doAuthenticate", "(", ")", ";", "fail", "(", "\"", "Exception not thrown", "\"", ")", ";", "}", "catch", "(", "AuthenticationException", "ae", ")", "{", "assertContains", "(", "\"", "Wrong exception message", "\"", ",", "ae", ".", "getMessage", "(", ")", ",", "\"", "Direct CAS login failed", "\"", ")", ";", "assertContains", "(", "\"", "Wrong exception message", "\"", ",", "ae", ".", "getMessage", "(", ")", ",", "\"", "Bad connection", "\"", ")", ";", "}", "}", "public", "void", "testFailedPostResultsInNoAuthentication", "(", ")", "throws", "Exception", "{", "/* expect */", "loginFacade", ".", "start", "(", ")", ";", "expect", "(", "loginFacade", ".", "selectCredentialProvider", "(", "CREDENTIAL_PROVIDER", ")", ")", ".", "andReturn", "(", "\"", "<input name='lt' value='the-ticket'/><select id='authenticationServiceURL'><option value='http://dorian!/'>Dorian</select>", "\"", ")", ";", "/* expect */", "loginFacade", ".", "selectAuthenticationService", "(", "\"", "http://dorian!/", "\"", ")", ";", "expect", "(", "loginFacade", ".", "postCredentials", "(", "USERNAME", ",", "PASSWORD", ")", ")", ".", "andReturn", "(", "false", ")", ";", "try", "{", "doAuthenticate", "(", ")", ";", "fail", "(", "\"", "Exception not thrown", "\"", ")", ";", "}", "catch", "(", "BadCredentialsException", "bce", ")", "{", "assertEquals", "(", "\"", "Credentials are invalid according to direct CAS login", "\"", ",", "bce", ".", "getMessage", "(", ")", ")", ";", "}", "}", "public", "void", "testUnknownAuthenticationServiceFailsAuthentication", "(", ")", "throws", "Exception", "{", "/* expect */", "loginFacade", ".", "start", "(", ")", ";", "expect", "(", "loginFacade", ".", "selectCredentialProvider", "(", "CREDENTIAL_PROVIDER", ")", ")", ".", "andReturn", "(", "\"", "<input name='lt' value='the-ticket'/><select id='authenticationServiceURL'><option value='http://dorian!/'>Not Dorian</select>", "\"", ")", ";", "try", "{", "doAuthenticate", "(", ")", ";", "fail", "(", "\"", "Exception not thrown", "\"", ")", ";", "}", "catch", "(", "BadCredentialsException", "bce", ")", "{", "assertEquals", "(", "\"", "The WebSSO server does not know of an authentication service named ", "\\\"", "Dorian", "\\\"", "\"", ",", "bce", ".", "getMessage", "(", ")", ")", ";", "}", "}", "public", "void", "testSuccessfulPostResultsInAuthentication", "(", ")", "throws", "Exception", "{", "/* expect */", "loginFacade", ".", "start", "(", ")", ";", "expect", "(", "loginFacade", ".", "selectCredentialProvider", "(", "CREDENTIAL_PROVIDER", ")", ")", ".", "andReturn", "(", "\"", "<input name='lt' value='the-ticket'/><select id='authenticationServiceURL'><option value='http://dorian!/'>Dorian</select>", "\"", ")", ";", "/* expect */", "loginFacade", ".", "selectAuthenticationService", "(", "\"", "http://dorian!/", "\"", ")", ";", "expect", "(", "loginFacade", ".", "postCredentials", "(", "USERNAME", ",", "PASSWORD", ")", ")", ".", "andReturn", "(", "true", ")", ";", "Authentication", "actual", "=", "doAuthenticate", "(", ")", ";", "assertNotNull", "(", "actual", ")", ";", "assertTrue", "(", "actual", ".", "isAuthenticated", "(", ")", ")", ";", "}", "private", "Authentication", "doAuthenticate", "(", ")", "{", "return", "doAuthenticate", "(", "QUALIFIED_USERNAME", ")", ";", "}", "private", "Authentication", "doAuthenticate", "(", "String", "qualifiedUsername", ")", "{", "replayMocks", "(", ")", ";", "Authentication", "actual", "=", "provider", ".", "authenticate", "(", "new", "CasDirectUsernamePasswordAuthenticationToken", "(", "qualifiedUsername", ",", "PASSWORD", ")", ")", ";", "verifyMocks", "(", ")", ";", "return", "actual", ";", "}", "}" ]
Note that this class only includes tests for differences between {@link edu.northwestern.bioinformatics.studycalendar.security.plugin.websso.direct.WebSSODirectAuthenticationProvider} and {@link
[ "Note", "that", "this", "class", "only", "includes", "tests", "for", "differences", "between", "{", "@link", "edu", ".", "northwestern", ".", "bioinformatics", ".", "studycalendar", ".", "security", ".", "plugin", ".", "websso", ".", "direct", ".", "WebSSODirectAuthenticationProvider", "}", "and", "{", "@link" ]
[]
[ { "param": "AuthenticationTestCase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AuthenticationTestCase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69a2cac0a2ea20950db1e5f4fd11a8410c22ac8f
worldiety/homunculus
hcf-core/src/main/java/org/homunculusframework/concurrent/ExecutionList.java
[ "Apache-2.0" ]
Java
ExecutionList
/** * A deferred execution list, which executes either when {@link #execute()} is called or when {@link #add(Runnable)} is called. * * @author Torben Schinke * @since 1.0 */
A deferred execution list, which executes either when #execute() is called or when #add(Runnable) is called. @author Torben Schinke @since 1.0
[ "A", "deferred", "execution", "list", "which", "executes", "either", "when", "#execute", "()", "is", "called", "or", "when", "#add", "(", "Runnable", ")", "is", "called", ".", "@author", "Torben", "Schinke", "@since", "1", ".", "0" ]
public final class ExecutionList { private final LinkedList<Runnable> jobs = new LinkedList<>(); private boolean executed; /** * Adds another runnable. If execute has already been called, it is executed immediately. * * @param r */ public void add(Runnable r) { synchronized (jobs) { if (executed) { r.run(); } else { jobs.add(r); } } } /** * Executes all collected jobs once. Subsequent calls will have no effect. After executing all runnables this instance is de-facto free of leaks, and removes all contained runnables. */ public void execute() { synchronized (jobs) { if (executed) { return; } else { try { for (Runnable r : jobs) { r.run(); } } finally { executed = true; jobs.clear(); } } } } public boolean hasExecuted() { synchronized (jobs) { return executed; } } }
[ "public", "final", "class", "ExecutionList", "{", "private", "final", "LinkedList", "<", "Runnable", ">", "jobs", "=", "new", "LinkedList", "<", ">", "(", ")", ";", "private", "boolean", "executed", ";", "/**\n * Adds another runnable. If execute has already been called, it is executed immediately.\n *\n * @param r\n */", "public", "void", "add", "(", "Runnable", "r", ")", "{", "synchronized", "(", "jobs", ")", "{", "if", "(", "executed", ")", "{", "r", ".", "run", "(", ")", ";", "}", "else", "{", "jobs", ".", "add", "(", "r", ")", ";", "}", "}", "}", "/**\n * Executes all collected jobs once. Subsequent calls will have no effect. After executing all runnables this instance is de-facto free of leaks, and removes all contained runnables.\n */", "public", "void", "execute", "(", ")", "{", "synchronized", "(", "jobs", ")", "{", "if", "(", "executed", ")", "{", "return", ";", "}", "else", "{", "try", "{", "for", "(", "Runnable", "r", ":", "jobs", ")", "{", "r", ".", "run", "(", ")", ";", "}", "}", "finally", "{", "executed", "=", "true", ";", "jobs", ".", "clear", "(", ")", ";", "}", "}", "}", "}", "public", "boolean", "hasExecuted", "(", ")", "{", "synchronized", "(", "jobs", ")", "{", "return", "executed", ";", "}", "}", "}" ]
A deferred execution list, which executes either when {@link #execute()} is called or when {@link #add(Runnable)} is called.
[ "A", "deferred", "execution", "list", "which", "executes", "either", "when", "{", "@link", "#execute", "()", "}", "is", "called", "or", "when", "{", "@link", "#add", "(", "Runnable", ")", "}", "is", "called", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
69a6469f622e338da259e69ea821ce77e9392649
duesenklipper/wicketstuff-security
examples/all_in_one/src/main/java/org/apache/wicket/security/examples/multilogin/authentication/Level1Context.java
[ "Apache-2.0" ]
Java
Level1Context
/** * Secondary authentication for topsecret pages like the commit page for transactions. * * @author marrink * */
Secondary authentication for topsecret pages like the commit page for transactions. @author marrink
[ "Secondary", "authentication", "for", "topsecret", "pages", "like", "the", "commit", "page", "for", "transactions", ".", "@author", "marrink" ]
public class Level1Context extends LoginContext { /** * Subject for secondary Login. authenticates all pages. * * @author marrink */ private static final class MySecondarySubject extends DefaultSubject { private static final long serialVersionUID = 1L; /** * @see WicketSubject#isClassAuthenticated(java.lang.Class) */ @Override public boolean isClassAuthenticated(Class< ? > class1) { // we could return true only if the page is a Topsecretpage, // but this way we can also login inmediatly on the second // login page, without being required to go through the first. // if we had a bookmarkable link to this page. return true; } /** * @see WicketSubject#isComponentAuthenticated(org.apache.wicket.Component) */ @Override public boolean isComponentAuthenticated(Component component) { return true; } /** * @see WicketSubject#isModelAuthenticated(org.apache.wicket.model.IModel, * org.apache.wicket.Component) */ @Override public boolean isModelAuthenticated(IModel< ? > model, Component component) { return true; } } private String username; private String token; /** * @param token * @param username */ public Level1Context(String username, String token) { super(1); this.username = username; this.token = token; } /** * @see org.apache.wicket.security.hive.authentication.LoginContext#login() */ @Override public Subject login() throws LoginException { // irrelevant check if (Objects.equal(username, token)) { // usually there will be a db call to verify the credentials DefaultSubject subject = new MySecondarySubject(); // add principals as required // Note if topsecret implied basic we would not have to add it here. // Also we only need this because we can login through a // bookmarkable url, thereby bypassing the first login page. // if we know we always come through the first loginpage we can // remove basic here. subject.addPrincipal(new MyPrincipal("basic")); subject.addPrincipal(new MyPrincipal("topsecret")); return subject; } throw new LoginException("username does not match token"); } /** * * @see org.apache.wicket.security.hive.authentication.LoginContext#preventsAdditionalLogins() */ @Override public boolean preventsAdditionalLogins() { // we don't want / need to upgrade the credentials of this user any // further return true; } }
[ "public", "class", "Level1Context", "extends", "LoginContext", "{", "/**\r\n\t * Subject for secondary Login. authenticates all pages.\r\n\t * \r\n\t * @author marrink\r\n\t */", "private", "static", "final", "class", "MySecondarySubject", "extends", "DefaultSubject", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "/**\r\n\t\t * @see WicketSubject#isClassAuthenticated(java.lang.Class)\r\n\t\t */", "@", "Override", "public", "boolean", "isClassAuthenticated", "(", "Class", "<", "?", ">", "class1", ")", "{", "return", "true", ";", "}", "/**\r\n\t\t * @see WicketSubject#isComponentAuthenticated(org.apache.wicket.Component)\r\n\t\t */", "@", "Override", "public", "boolean", "isComponentAuthenticated", "(", "Component", "component", ")", "{", "return", "true", ";", "}", "/**\r\n\t\t * @see WicketSubject#isModelAuthenticated(org.apache.wicket.model.IModel,\r\n\t\t * org.apache.wicket.Component)\r\n\t\t */", "@", "Override", "public", "boolean", "isModelAuthenticated", "(", "IModel", "<", "?", ">", "model", ",", "Component", "component", ")", "{", "return", "true", ";", "}", "}", "private", "String", "username", ";", "private", "String", "token", ";", "/**\r\n\t * @param token\r\n\t * @param username\r\n\t */", "public", "Level1Context", "(", "String", "username", ",", "String", "token", ")", "{", "super", "(", "1", ")", ";", "this", ".", "username", "=", "username", ";", "this", ".", "token", "=", "token", ";", "}", "/**\r\n\t * @see org.apache.wicket.security.hive.authentication.LoginContext#login()\r\n\t */", "@", "Override", "public", "Subject", "login", "(", ")", "throws", "LoginException", "{", "if", "(", "Objects", ".", "equal", "(", "username", ",", "token", ")", ")", "{", "DefaultSubject", "subject", "=", "new", "MySecondarySubject", "(", ")", ";", "subject", ".", "addPrincipal", "(", "new", "MyPrincipal", "(", "\"", "basic", "\"", ")", ")", ";", "subject", ".", "addPrincipal", "(", "new", "MyPrincipal", "(", "\"", "topsecret", "\"", ")", ")", ";", "return", "subject", ";", "}", "throw", "new", "LoginException", "(", "\"", "username does not match token", "\"", ")", ";", "}", "/**\r\n\t * \r\n\t * @see org.apache.wicket.security.hive.authentication.LoginContext#preventsAdditionalLogins()\r\n\t */", "@", "Override", "public", "boolean", "preventsAdditionalLogins", "(", ")", "{", "return", "true", ";", "}", "}" ]
Secondary authentication for topsecret pages like the commit page for transactions.
[ "Secondary", "authentication", "for", "topsecret", "pages", "like", "the", "commit", "page", "for", "transactions", "." ]
[ "// we could return true only if the page is a Topsecretpage,\r", "// but this way we can also login inmediatly on the second\r", "// login page, without being required to go through the first.\r", "// if we had a bookmarkable link to this page.\r", "// irrelevant check\r", "// usually there will be a db call to verify the credentials\r", "// add principals as required\r", "// Note if topsecret implied basic we would not have to add it here.\r", "// Also we only need this because we can login through a\r", "// bookmarkable url, thereby bypassing the first login page.\r", "// if we know we always come through the first loginpage we can\r", "// remove basic here.\r", "// we don't want / need to upgrade the credentials of this user any\r", "// further\r" ]
[ { "param": "LoginContext", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "LoginContext", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69a6469f622e338da259e69ea821ce77e9392649
duesenklipper/wicketstuff-security
examples/all_in_one/src/main/java/org/apache/wicket/security/examples/multilogin/authentication/Level1Context.java
[ "Apache-2.0" ]
Java
MySecondarySubject
/** * Subject for secondary Login. authenticates all pages. * * @author marrink */
Subject for secondary Login. authenticates all pages. @author marrink
[ "Subject", "for", "secondary", "Login", ".", "authenticates", "all", "pages", ".", "@author", "marrink" ]
private static final class MySecondarySubject extends DefaultSubject { private static final long serialVersionUID = 1L; /** * @see WicketSubject#isClassAuthenticated(java.lang.Class) */ @Override public boolean isClassAuthenticated(Class< ? > class1) { // we could return true only if the page is a Topsecretpage, // but this way we can also login inmediatly on the second // login page, without being required to go through the first. // if we had a bookmarkable link to this page. return true; } /** * @see WicketSubject#isComponentAuthenticated(org.apache.wicket.Component) */ @Override public boolean isComponentAuthenticated(Component component) { return true; } /** * @see WicketSubject#isModelAuthenticated(org.apache.wicket.model.IModel, * org.apache.wicket.Component) */ @Override public boolean isModelAuthenticated(IModel< ? > model, Component component) { return true; } }
[ "private", "static", "final", "class", "MySecondarySubject", "extends", "DefaultSubject", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "/**\r\n\t\t * @see WicketSubject#isClassAuthenticated(java.lang.Class)\r\n\t\t */", "@", "Override", "public", "boolean", "isClassAuthenticated", "(", "Class", "<", "?", ">", "class1", ")", "{", "return", "true", ";", "}", "/**\r\n\t\t * @see WicketSubject#isComponentAuthenticated(org.apache.wicket.Component)\r\n\t\t */", "@", "Override", "public", "boolean", "isComponentAuthenticated", "(", "Component", "component", ")", "{", "return", "true", ";", "}", "/**\r\n\t\t * @see WicketSubject#isModelAuthenticated(org.apache.wicket.model.IModel,\r\n\t\t * org.apache.wicket.Component)\r\n\t\t */", "@", "Override", "public", "boolean", "isModelAuthenticated", "(", "IModel", "<", "?", ">", "model", ",", "Component", "component", ")", "{", "return", "true", ";", "}", "}" ]
Subject for secondary Login.
[ "Subject", "for", "secondary", "Login", "." ]
[ "// we could return true only if the page is a Topsecretpage,\r", "// but this way we can also login inmediatly on the second\r", "// login page, without being required to go through the first.\r", "// if we had a bookmarkable link to this page.\r" ]
[ { "param": "DefaultSubject", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "DefaultSubject", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69a6eb33a5ed2d5f5a298950e32a5d48fa571c0e
koscinskic/Warframe-DPS-Util-V4
src/Math_Utility.java
[ "Unlicense" ]
Java
Math_Utility
/** * The Math_Utility class provides methods for the basic calculation and * manipulation of mathematical combinations. * * "n" denotes the quantity of items available for any given combination * "r" denotes the quantity of items a combination is composed of * * Consequentially, the combination follows the form nCr */
The Math_Utility class provides methods for the basic calculation and manipulation of mathematical combinations. "n" denotes the quantity of items available for any given combination "r" denotes the quantity of items a combination is composed of Consequentially, the combination follows the form nCr
[ "The", "Math_Utility", "class", "provides", "methods", "for", "the", "basic", "calculation", "and", "manipulation", "of", "mathematical", "combinations", ".", "\"", "n", "\"", "denotes", "the", "quantity", "of", "items", "available", "for", "any", "given", "combination", "\"", "r", "\"", "denotes", "the", "quantity", "of", "items", "a", "combination", "is", "composed", "of", "Consequentially", "the", "combination", "follows", "the", "form", "nCr" ]
public class Math_Utility { /** * Generates an initial combination in numerical order given "n" and "r". */ public static int[] generateCombination(int n, int r) { int[] combo = new int[r]; for (int i = 0; i < combo.length; i++) { combo[i] = i + 1; } return combo; } /** * Increments the given combination by one value in numerical order. * Requires the maximum value possible for any index as "n". */ public static int[] incrementCombination(int n, int[] combo) { int r = combo.length; int indexPos = r - 1; // Determines which index to increment for (int i = r - 1; i >= 0; i--) { if (combo[i] + 1 <= (n - r) + i + 1) { indexPos = i; i = 0; } } // Increments said index combo[indexPos]++; // Resets the combination in an ascending order from the said index if the // index has changed since the previous increment. if (indexPos != (r - 1)) { for (int i = indexPos + 1; i < combo.length; i++) { combo[i] = combo[i - 1] + 1; } } return combo; } /** * Method that displays the combination */ public static void printCombo(int[] combo) { System.out.println(); for (int i : combo) { System.out.print(i + " "); } } /** * Recursive factorial calculation */ private static double factorial(double value) { if (value == 1.0) { return 1.0; } else { return (value * factorial(value - 1.0)); } } /** * Formulaic combination calculation using above factorial method */ public static double maxCombination(double valueN, double valueR) { return (factorial(valueN) / (factorial(valueN - valueR) * factorial(valueR))); } }
[ "public", "class", "Math_Utility", "{", "/**\n * Generates an initial combination in numerical order given \"n\" and \"r\".\n */", "public", "static", "int", "[", "]", "generateCombination", "(", "int", "n", ",", "int", "r", ")", "{", "int", "[", "]", "combo", "=", "new", "int", "[", "r", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "combo", ".", "length", ";", "i", "++", ")", "{", "combo", "[", "i", "]", "=", "i", "+", "1", ";", "}", "return", "combo", ";", "}", "/**\n * Increments the given combination by one value in numerical order.\n * Requires the maximum value possible for any index as \"n\".\n */", "public", "static", "int", "[", "]", "incrementCombination", "(", "int", "n", ",", "int", "[", "]", "combo", ")", "{", "int", "r", "=", "combo", ".", "length", ";", "int", "indexPos", "=", "r", "-", "1", ";", "for", "(", "int", "i", "=", "r", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "combo", "[", "i", "]", "+", "1", "<=", "(", "n", "-", "r", ")", "+", "i", "+", "1", ")", "{", "indexPos", "=", "i", ";", "i", "=", "0", ";", "}", "}", "combo", "[", "indexPos", "]", "++", ";", "if", "(", "indexPos", "!=", "(", "r", "-", "1", ")", ")", "{", "for", "(", "int", "i", "=", "indexPos", "+", "1", ";", "i", "<", "combo", ".", "length", ";", "i", "++", ")", "{", "combo", "[", "i", "]", "=", "combo", "[", "i", "-", "1", "]", "+", "1", ";", "}", "}", "return", "combo", ";", "}", "/**\n * Method that displays the combination\n */", "public", "static", "void", "printCombo", "(", "int", "[", "]", "combo", ")", "{", "System", ".", "out", ".", "println", "(", ")", ";", "for", "(", "int", "i", ":", "combo", ")", "{", "System", ".", "out", ".", "print", "(", "i", "+", "\"", " ", "\"", ")", ";", "}", "}", "/**\n * Recursive factorial calculation\n */", "private", "static", "double", "factorial", "(", "double", "value", ")", "{", "if", "(", "value", "==", "1.0", ")", "{", "return", "1.0", ";", "}", "else", "{", "return", "(", "value", "*", "factorial", "(", "value", "-", "1.0", ")", ")", ";", "}", "}", "/**\n * Formulaic combination calculation using above factorial method\n */", "public", "static", "double", "maxCombination", "(", "double", "valueN", ",", "double", "valueR", ")", "{", "return", "(", "factorial", "(", "valueN", ")", "/", "(", "factorial", "(", "valueN", "-", "valueR", ")", "*", "factorial", "(", "valueR", ")", ")", ")", ";", "}", "}" ]
The Math_Utility class provides methods for the basic calculation and manipulation of mathematical combinations.
[ "The", "Math_Utility", "class", "provides", "methods", "for", "the", "basic", "calculation", "and", "manipulation", "of", "mathematical", "combinations", "." ]
[ "// Determines which index to increment", "// Increments said index", "// Resets the combination in an ascending order from the said index if the", "// index has changed since the previous increment." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
69a7af891a698538eedd977f88fd43844d598cf8
g4s8/teletakes
src/main/java/com/g4s8/teletakes/rs/RsReplyKeyboard.java
[ "MIT" ]
Java
RsReplyKeyboard
/** * Response with keyboard. * * @since 1.0 */
Response with keyboard.
[ "Response", "with", "keyboard", "." ]
public final class RsReplyKeyboard implements TmResponse { /** * Origin. */ private final TmResponse origin; /** * Rows. */ private final Iterable<Iterable<Text>> rows; /** * Ctor. * * @param origin Origin response * @param rows Keyboard rows */ public RsReplyKeyboard(final TmResponse origin, final Iterable<Iterable<Text>> rows) { this.origin = origin; this.rows = rows; } @Override public XML xml() throws IOException { final Directives keyboard = new Directives() .xpath("/response") .addIf("message") .addIf("keyboard") .push() .xpath("/response/message/keyboard/*") .remove() .pop() .addIf("reply") .strict(1); for (final Iterable<Text> row : this.rows) { keyboard.add("row"); for (final Text button : row) { keyboard.add("button") .set(new UncheckedScalar<>(button::asString).value()) .up(); } keyboard.up(); } try { return new XMLDocument( new Xembler(keyboard).apply(this.origin.xml().node()) ); } catch (final ImpossibleModificationException err) { throw new IOException("Failed to apply directives", err); } } }
[ "public", "final", "class", "RsReplyKeyboard", "implements", "TmResponse", "{", "/**\n * Origin.\n */", "private", "final", "TmResponse", "origin", ";", "/**\n * Rows.\n */", "private", "final", "Iterable", "<", "Iterable", "<", "Text", ">", ">", "rows", ";", "/**\n * Ctor.\n *\n * @param origin Origin response\n * @param rows Keyboard rows\n */", "public", "RsReplyKeyboard", "(", "final", "TmResponse", "origin", ",", "final", "Iterable", "<", "Iterable", "<", "Text", ">", ">", "rows", ")", "{", "this", ".", "origin", "=", "origin", ";", "this", ".", "rows", "=", "rows", ";", "}", "@", "Override", "public", "XML", "xml", "(", ")", "throws", "IOException", "{", "final", "Directives", "keyboard", "=", "new", "Directives", "(", ")", ".", "xpath", "(", "\"", "/response", "\"", ")", ".", "addIf", "(", "\"", "message", "\"", ")", ".", "addIf", "(", "\"", "keyboard", "\"", ")", ".", "push", "(", ")", ".", "xpath", "(", "\"", "/response/message/keyboard/*", "\"", ")", ".", "remove", "(", ")", ".", "pop", "(", ")", ".", "addIf", "(", "\"", "reply", "\"", ")", ".", "strict", "(", "1", ")", ";", "for", "(", "final", "Iterable", "<", "Text", ">", "row", ":", "this", ".", "rows", ")", "{", "keyboard", ".", "add", "(", "\"", "row", "\"", ")", ";", "for", "(", "final", "Text", "button", ":", "row", ")", "{", "keyboard", ".", "add", "(", "\"", "button", "\"", ")", ".", "set", "(", "new", "UncheckedScalar", "<", ">", "(", "button", "::", "asString", ")", ".", "value", "(", ")", ")", ".", "up", "(", ")", ";", "}", "keyboard", ".", "up", "(", ")", ";", "}", "try", "{", "return", "new", "XMLDocument", "(", "new", "Xembler", "(", "keyboard", ")", ".", "apply", "(", "this", ".", "origin", ".", "xml", "(", ")", ".", "node", "(", ")", ")", ")", ";", "}", "catch", "(", "final", "ImpossibleModificationException", "err", ")", "{", "throw", "new", "IOException", "(", "\"", "Failed to apply directives", "\"", ",", "err", ")", ";", "}", "}", "}" ]
Response with keyboard.
[ "Response", "with", "keyboard", "." ]
[]
[ { "param": "TmResponse", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "TmResponse", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69a8fe9c1578d5e84a448a34cf8fe603cc363adb
reinecke/OpenTimelineIO-Java-Bindings
src/main/java/io/opentimeline/opentimelineio/MissingReference.java
[ "Apache-2.0" ]
Java
MissingReference
/** * Represents media for which a concrete reference is missing. */
Represents media for which a concrete reference is missing.
[ "Represents", "media", "for", "which", "a", "concrete", "reference", "is", "missing", "." ]
public class MissingReference extends MediaReference { protected MissingReference() { } MissingReference(OTIONative otioNative) { this.nativeManager = otioNative; } public MissingReference(String name, TimeRange availableRange, AnyDictionary metadata) { this.initObject(name, availableRange, metadata); } public MissingReference(MissingReference.MissingReferenceBuilder missingReferenceBuilder) { this.initObject( missingReferenceBuilder.name, missingReferenceBuilder.availableRange, missingReferenceBuilder.metadata); } private void initObject(String name, TimeRange availableRange, AnyDictionary metadata) { this.initialize(name, availableRange, metadata); this.nativeManager.className = this.getClass().getCanonicalName(); } private native void initialize(String name, TimeRange availableRange, AnyDictionary metadata); public static class MissingReferenceBuilder { private String name = ""; private TimeRange availableRange = null; private AnyDictionary metadata = new AnyDictionary(); public MissingReferenceBuilder() { } public MissingReference.MissingReferenceBuilder setName(String name) { this.name = name; return this; } public MissingReference.MissingReferenceBuilder setAvailableRange(TimeRange availableRange) { this.availableRange = availableRange; return this; } public MissingReference.MissingReferenceBuilder setMetadata(AnyDictionary metadata) { this.metadata = metadata; return this; } public MissingReference build() { return new MissingReference(this); } } public native boolean isMissingReference(); }
[ "public", "class", "MissingReference", "extends", "MediaReference", "{", "protected", "MissingReference", "(", ")", "{", "}", "MissingReference", "(", "OTIONative", "otioNative", ")", "{", "this", ".", "nativeManager", "=", "otioNative", ";", "}", "public", "MissingReference", "(", "String", "name", ",", "TimeRange", "availableRange", ",", "AnyDictionary", "metadata", ")", "{", "this", ".", "initObject", "(", "name", ",", "availableRange", ",", "metadata", ")", ";", "}", "public", "MissingReference", "(", "MissingReference", ".", "MissingReferenceBuilder", "missingReferenceBuilder", ")", "{", "this", ".", "initObject", "(", "missingReferenceBuilder", ".", "name", ",", "missingReferenceBuilder", ".", "availableRange", ",", "missingReferenceBuilder", ".", "metadata", ")", ";", "}", "private", "void", "initObject", "(", "String", "name", ",", "TimeRange", "availableRange", ",", "AnyDictionary", "metadata", ")", "{", "this", ".", "initialize", "(", "name", ",", "availableRange", ",", "metadata", ")", ";", "this", ".", "nativeManager", ".", "className", "=", "this", ".", "getClass", "(", ")", ".", "getCanonicalName", "(", ")", ";", "}", "private", "native", "void", "initialize", "(", "String", "name", ",", "TimeRange", "availableRange", ",", "AnyDictionary", "metadata", ")", ";", "public", "static", "class", "MissingReferenceBuilder", "{", "private", "String", "name", "=", "\"", "\"", ";", "private", "TimeRange", "availableRange", "=", "null", ";", "private", "AnyDictionary", "metadata", "=", "new", "AnyDictionary", "(", ")", ";", "public", "MissingReferenceBuilder", "(", ")", "{", "}", "public", "MissingReference", ".", "MissingReferenceBuilder", "setName", "(", "String", "name", ")", "{", "this", ".", "name", "=", "name", ";", "return", "this", ";", "}", "public", "MissingReference", ".", "MissingReferenceBuilder", "setAvailableRange", "(", "TimeRange", "availableRange", ")", "{", "this", ".", "availableRange", "=", "availableRange", ";", "return", "this", ";", "}", "public", "MissingReference", ".", "MissingReferenceBuilder", "setMetadata", "(", "AnyDictionary", "metadata", ")", "{", "this", ".", "metadata", "=", "metadata", ";", "return", "this", ";", "}", "public", "MissingReference", "build", "(", ")", "{", "return", "new", "MissingReference", "(", "this", ")", ";", "}", "}", "public", "native", "boolean", "isMissingReference", "(", ")", ";", "}" ]
Represents media for which a concrete reference is missing.
[ "Represents", "media", "for", "which", "a", "concrete", "reference", "is", "missing", "." ]
[]
[ { "param": "MediaReference", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MediaReference", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69adf36ca76ff65ffbe7506d3d18d07de557afab
jheijari/kartta.paikkatietoikkuna.fi
webapp-landing/src/main/java/fi/nls/oskari/DocumentsHandler.java
[ "MIT" ]
Java
DocumentsHandler
/** * Support for old document links, now available under Jetty/resources/legacy-docs */
Support for old document links, now available under Jetty/resources/legacy-docs
[ "Support", "for", "old", "document", "links", "now", "available", "under", "Jetty", "/", "resources", "/", "legacy", "-", "docs" ]
@Controller public class DocumentsHandler { private Map<String, LegacyDocument> docs = new HashMap<>(); /* /documents/108478/f22964f8-cc49-421e-bf2e-084d54be6a04 */ @RequestMapping("/documents/108478/{uuid}") public void documentsPath(@PathVariable("uuid") String uuid, HttpServletResponse response) throws Exception { writeDocument(uuid, response); } /* /c/document_library/get_file?uuid=2c4a9801-b9e6-473f-aebe-58b9ab3d7935&groupId=108478 */ @RequestMapping("/c/document_library/get_file") public void documentsParam(@RequestParam("uuid") String uuid, HttpServletResponse response) throws Exception { writeDocument(uuid, response); } protected void writeDocument(String uuid, HttpServletResponse response) throws Exception { LegacyDocument doc = findDocument(uuid); if(doc.mimeType != null) { response.setContentType(doc.mimeType); } response.setHeader("Content-Disposition", "attachment; filename=\"" + doc.filename + "\""); try (InputStream is = getClass().getResourceAsStream(doc.path)) { response.setContentLength(is.available()); FileCopyUtils.copy(is, response.getOutputStream()); } } protected LegacyDocument findDocument(String uuid) throws Exception { LegacyDocument doc = docs.get(uuid); if (doc == null) { throw new HttpClientErrorException(HttpStatus.NOT_FOUND); } return doc; } @PostConstruct private void readList() throws IOException { Map<String, String> mimeTypes = new HashMap<>(); mimeTypes.put(".pdf", "application/pdf"); mimeTypes.put(".doc", "application/msword"); mimeTypes.put(".docx", "application/msword"); mimeTypes.put(".ppt", "application/mspowerpoint"); mimeTypes.put(".pptx", "application/mspowerpoint"); mimeTypes.put(".zip", "application/zip"); mimeTypes.put(".txt", "plain/text"); mimeTypes.put(".xls", "application/excel"); mimeTypes.put(".xlsx", "application/excel"); mimeTypes.put(".gpx", "application/gpx+xml"); mimeTypes.put(".html", "text/html"); mimeTypes.put(".xml", "text/xml"); mimeTypes.put(".png", "image/png"); mimeTypes.put(".jpg", "image/jpg"); LegacyDocument[] list = getMapper().readValue(getClass().getResourceAsStream(getBasePath() + "/liferay_docs.json"), LegacyDocument[].class); for(LegacyDocument doc : list) { // setup path for classpath resource doc.path = getBasePath() + "/docs/" + doc.path; doc.mimeType = getMimeType(doc.filename, mimeTypes); docs.put(doc.uuid, doc); } } private String getMimeType(String filename, Map<String, String> types) { for( Map.Entry<String, String> e : types.entrySet()) { if(filename.toLowerCase().endsWith(e.getKey())) { return e.getValue(); } } System.out.println("Mimetype missing for: " + filename); return null; } }
[ "@", "Controller", "public", "class", "DocumentsHandler", "{", "private", "Map", "<", "String", ",", "LegacyDocument", ">", "docs", "=", "new", "HashMap", "<", ">", "(", ")", ";", "/*\n /documents/108478/f22964f8-cc49-421e-bf2e-084d54be6a04\n */", "@", "RequestMapping", "(", "\"", "/documents/108478/{uuid}", "\"", ")", "public", "void", "documentsPath", "(", "@", "PathVariable", "(", "\"", "uuid", "\"", ")", "String", "uuid", ",", "HttpServletResponse", "response", ")", "throws", "Exception", "{", "writeDocument", "(", "uuid", ",", "response", ")", ";", "}", "/*\n /c/document_library/get_file?uuid=2c4a9801-b9e6-473f-aebe-58b9ab3d7935&groupId=108478\n */", "@", "RequestMapping", "(", "\"", "/c/document_library/get_file", "\"", ")", "public", "void", "documentsParam", "(", "@", "RequestParam", "(", "\"", "uuid", "\"", ")", "String", "uuid", ",", "HttpServletResponse", "response", ")", "throws", "Exception", "{", "writeDocument", "(", "uuid", ",", "response", ")", ";", "}", "protected", "void", "writeDocument", "(", "String", "uuid", ",", "HttpServletResponse", "response", ")", "throws", "Exception", "{", "LegacyDocument", "doc", "=", "findDocument", "(", "uuid", ")", ";", "if", "(", "doc", ".", "mimeType", "!=", "null", ")", "{", "response", ".", "setContentType", "(", "doc", ".", "mimeType", ")", ";", "}", "response", ".", "setHeader", "(", "\"", "Content-Disposition", "\"", ",", "\"", "attachment; filename=", "\\\"", "\"", "+", "doc", ".", "filename", "+", "\"", "\\\"", "\"", ")", ";", "try", "(", "InputStream", "is", "=", "getClass", "(", ")", ".", "getResourceAsStream", "(", "doc", ".", "path", ")", ")", "{", "response", ".", "setContentLength", "(", "is", ".", "available", "(", ")", ")", ";", "FileCopyUtils", ".", "copy", "(", "is", ",", "response", ".", "getOutputStream", "(", ")", ")", ";", "}", "}", "protected", "LegacyDocument", "findDocument", "(", "String", "uuid", ")", "throws", "Exception", "{", "LegacyDocument", "doc", "=", "docs", ".", "get", "(", "uuid", ")", ";", "if", "(", "doc", "==", "null", ")", "{", "throw", "new", "HttpClientErrorException", "(", "HttpStatus", ".", "NOT_FOUND", ")", ";", "}", "return", "doc", ";", "}", "@", "PostConstruct", "private", "void", "readList", "(", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "String", ">", "mimeTypes", "=", "new", "HashMap", "<", ">", "(", ")", ";", "mimeTypes", ".", "put", "(", "\"", ".pdf", "\"", ",", "\"", "application/pdf", "\"", ")", ";", "mimeTypes", ".", "put", "(", "\"", ".doc", "\"", ",", "\"", "application/msword", "\"", ")", ";", "mimeTypes", ".", "put", "(", "\"", ".docx", "\"", ",", "\"", "application/msword", "\"", ")", ";", "mimeTypes", ".", "put", "(", "\"", ".ppt", "\"", ",", "\"", "application/mspowerpoint", "\"", ")", ";", "mimeTypes", ".", "put", "(", "\"", ".pptx", "\"", ",", "\"", "application/mspowerpoint", "\"", ")", ";", "mimeTypes", ".", "put", "(", "\"", ".zip", "\"", ",", "\"", "application/zip", "\"", ")", ";", "mimeTypes", ".", "put", "(", "\"", ".txt", "\"", ",", "\"", "plain/text", "\"", ")", ";", "mimeTypes", ".", "put", "(", "\"", ".xls", "\"", ",", "\"", "application/excel", "\"", ")", ";", "mimeTypes", ".", "put", "(", "\"", ".xlsx", "\"", ",", "\"", "application/excel", "\"", ")", ";", "mimeTypes", ".", "put", "(", "\"", ".gpx", "\"", ",", "\"", "application/gpx+xml", "\"", ")", ";", "mimeTypes", ".", "put", "(", "\"", ".html", "\"", ",", "\"", "text/html", "\"", ")", ";", "mimeTypes", ".", "put", "(", "\"", ".xml", "\"", ",", "\"", "text/xml", "\"", ")", ";", "mimeTypes", ".", "put", "(", "\"", ".png", "\"", ",", "\"", "image/png", "\"", ")", ";", "mimeTypes", ".", "put", "(", "\"", ".jpg", "\"", ",", "\"", "image/jpg", "\"", ")", ";", "LegacyDocument", "[", "]", "list", "=", "getMapper", "(", ")", ".", "readValue", "(", "getClass", "(", ")", ".", "getResourceAsStream", "(", "getBasePath", "(", ")", "+", "\"", "/liferay_docs.json", "\"", ")", ",", "LegacyDocument", "[", "]", ".", "class", ")", ";", "for", "(", "LegacyDocument", "doc", ":", "list", ")", "{", "doc", ".", "path", "=", "getBasePath", "(", ")", "+", "\"", "/docs/", "\"", "+", "doc", ".", "path", ";", "doc", ".", "mimeType", "=", "getMimeType", "(", "doc", ".", "filename", ",", "mimeTypes", ")", ";", "docs", ".", "put", "(", "doc", ".", "uuid", ",", "doc", ")", ";", "}", "}", "private", "String", "getMimeType", "(", "String", "filename", ",", "Map", "<", "String", ",", "String", ">", "types", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "e", ":", "types", ".", "entrySet", "(", ")", ")", "{", "if", "(", "filename", ".", "toLowerCase", "(", ")", ".", "endsWith", "(", "e", ".", "getKey", "(", ")", ")", ")", "{", "return", "e", ".", "getValue", "(", ")", ";", "}", "}", "System", ".", "out", ".", "println", "(", "\"", "Mimetype missing for: ", "\"", "+", "filename", ")", ";", "return", "null", ";", "}", "}" ]
Support for old document links, now available under Jetty/resources/legacy-docs
[ "Support", "for", "old", "document", "links", "now", "available", "under", "Jetty", "/", "resources", "/", "legacy", "-", "docs" ]
[ "// setup path for classpath resource" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
69b73817c04ea816f54c05e307ff73eb12c2a1ed
masud-technope/ACER-Replication-Package-ASE2017
corpus/class/eclipse.jdt.core/369.java
[ "MIT" ]
Java
LocalVirtualMachine
/** * Wrapper around the external process that is running a local VM. * This allows to kill this process when we exit this vm. */
Wrapper around the external process that is running a local VM. This allows to kill this process when we exit this vm.
[ "Wrapper", "around", "the", "external", "process", "that", "is", "running", "a", "local", "VM", ".", "This", "allows", "to", "kill", "this", "process", "when", "we", "exit", "this", "vm", "." ]
public class LocalVirtualMachine { protected Process process; protected int debugPort; protected String evalTargetPath; /** * Creates a new LocalVirtualMachine that doesn't run and that cannot be debugged nor used to * evaluate. */ public LocalVirtualMachine() { this.process = null; this.debugPort = -1; this.evalTargetPath = null; } /** * Creates a new LocalVirtualMachine from the Process that runs this VM * and with the given debug port number. */ public LocalVirtualMachine(Process p, int debugPort, String evalTargetPath) { this.process = p; this.debugPort = debugPort; this.evalTargetPath = evalTargetPath; } /* * Cleans up the given directory by removing all the files it contains as well * but leaving the directory. * @throws TargetException if the target path could not be cleaned up * private void cleanupDirectory(File directory) throws TargetException { if (!directory.exists()) { return; } String[] fileNames = directory.list(); for (int i = 0; i < fileNames.length; i++) { File file = new File(directory, fileNames[i]); if (file.isDirectory()) { cleanupDirectory(file); if (!file.delete()) { throw new TargetException("Could not delete directory " + directory.getPath()); } } else { if (!file.delete()) { throw new TargetException("Could not delete file " + file.getPath()); } } } } */ /** * Cleans up this context's target path by removing all the files it contains * but leaving the directory. * @throws TargetException if the target path could not be cleaned up */ protected void cleanupTargetPath() throws TargetException { if (this.evalTargetPath == null) return; String targetPath = this.evalTargetPath; if (LocalVMLauncher.TARGET_HAS_FILE_SYSTEM) { Util.delete(new File(targetPath, LocalVMLauncher.REGULAR_CLASSPATH_DIRECTORY)); Util.delete(new File(targetPath, LocalVMLauncher.BOOT_CLASSPATH_DIRECTORY)); File file = new File(targetPath, RuntimeConstants.SUPPORT_ZIP_FILE_NAME); /* workaround pb with Process.exitValue() that returns the process has exited, but it has not free the file yet int count = 10; for (int i = 0; i < count; i++) { if (file.delete()) { break; } try { Thread.sleep(count * 100); } catch (InterruptedException e) { } } */ if (!Util.delete(file)) { throw new TargetException("Could not delete " + file.getPath()); } } else { Util.delete(targetPath); } } /** * Returns the debug port number for this VM. This is the port number that was * passed as the "-debug" option if this VM was launched using a <code>LocalVMLauncher</code>. * Returns -1 if this information is not available or if this VM is not running in * debug mode. */ public int getDebugPortNumber() { return this.debugPort; } /** * Returns an input stream that is connected to the standard error * (<code>System.err</code>) of this target VM. * Bytes that are written to <code>System.err</code> by the target * program become available in the input stream. * <p> * Note 1: This stream is usually unbuffered. * <p> * Note 2: Two calls to this method return the same identical input stream. * <p> * See also <code>java.lang.Process.getErrorStream()</code>. * * @return an input stream connected to the target VM's <code>System.err</code>. * @exception TargetException if the target VM is not reachable. */ public InputStream getErrorStream() throws TargetException { if (this.process == null) throw new TargetException("The VM is not running"); return this.process.getErrorStream(); } /** * Returns an input stream that is connected to the standard output * (<code>System.out</code>) of this target VM. * Bytes that are written to <code>System.out</code> by the target * program become available in the input stream. * <p> * Note 1: This stream is usually buffered. * <p> * Note 2: Two calls to this method return the same identical input stream. * <p> * See also <code>java.lang.Process.getInputStream()</code>. * * @return an input stream connected to the target VM's <code>System.out</code>. * @exception TargetException if the target VM is not reachable. */ public InputStream getInputStream() throws TargetException { if (this.process == null) throw new TargetException("The VM is not running"); // Workaround problem with input stream of a Process return new VMInputStream(this.process, this.process.getInputStream()); } /** * Returns an output stream that is connected to the standard input * (<code>System.in</code>) of this target VM. * Bytes that are written to the output stream by a client become available to the target * program in <code>System.in</code>. * <p> * Note 1: This stream is usually buffered. * <p> * Note 2: Two calls to this method return the same identical output stream. * <p> * See also <code>java.lang.Process.getOutputStream()</code>. * * @return an output stream connected to the target VM's <code>System.in</code>. * @exception TargetException if the target VM is not reachable. */ public OutputStream getOutputStream() throws TargetException { if (this.process == null) throw new TargetException("The VM is not running"); return this.process.getOutputStream(); } /** * Returns whether this target VM is still running. * <p> * Note: This operation may require contacting the target VM to find out * if it is still running. */ public boolean isRunning() { if (this.process == null) { return false; } boolean hasExited; try { this.process.exitValue(); hasExited = true; } catch (IllegalThreadStateException e) { hasExited = false; } return !hasExited; } /** * Shuts down this target VM. * This causes the VM to exit. This operation is ignored * if the VM has already shut down. * * @throws TargetException if the target path could not be cleaned up */ public synchronized void shutDown() throws TargetException { if (this.process != null) { this.process.destroy(); this.process = null; cleanupTargetPath(); } } }
[ "public", "class", "LocalVirtualMachine", "{", "protected", "Process", "process", ";", "protected", "int", "debugPort", ";", "protected", "String", "evalTargetPath", ";", "/**\n * Creates a new LocalVirtualMachine that doesn't run and that cannot be debugged nor used to\n * evaluate.\n */", "public", "LocalVirtualMachine", "(", ")", "{", "this", ".", "process", "=", "null", ";", "this", ".", "debugPort", "=", "-", "1", ";", "this", ".", "evalTargetPath", "=", "null", ";", "}", "/**\n * Creates a new LocalVirtualMachine from the Process that runs this VM\n * and with the given debug port number.\n */", "public", "LocalVirtualMachine", "(", "Process", "p", ",", "int", "debugPort", ",", "String", "evalTargetPath", ")", "{", "this", ".", "process", "=", "p", ";", "this", ".", "debugPort", "=", "debugPort", ";", "this", ".", "evalTargetPath", "=", "evalTargetPath", ";", "}", "/*\n * Cleans up the given directory by removing all the files it contains as well\n * but leaving the directory.\n * @throws TargetException if the target path could not be cleaned up\n *\nprivate void cleanupDirectory(File directory) throws TargetException {\n\tif (!directory.exists()) {\n\t\treturn;\n\t}\n\tString[] fileNames = directory.list();\n\tfor (int i = 0; i < fileNames.length; i++) {\n\t\tFile file = new File(directory, fileNames[i]);\n\t\tif (file.isDirectory()) {\n\t\t\tcleanupDirectory(file);\n\t\t\tif (!file.delete()) {\n\t\t\t\tthrow new TargetException(\"Could not delete directory \" + directory.getPath());\n\t\t\t}\n\t\t} else {\n\t\t\tif (!file.delete()) {\n\t\t\t\tthrow new TargetException(\"Could not delete file \" + file.getPath());\n\t\t\t}\n\t\t}\n\t}\n}\n*/", "/**\n * Cleans up this context's target path by removing all the files it contains\n * but leaving the directory.\n * @throws TargetException if the target path could not be cleaned up\n */", "protected", "void", "cleanupTargetPath", "(", ")", "throws", "TargetException", "{", "if", "(", "this", ".", "evalTargetPath", "==", "null", ")", "return", ";", "String", "targetPath", "=", "this", ".", "evalTargetPath", ";", "if", "(", "LocalVMLauncher", ".", "TARGET_HAS_FILE_SYSTEM", ")", "{", "Util", ".", "delete", "(", "new", "File", "(", "targetPath", ",", "LocalVMLauncher", ".", "REGULAR_CLASSPATH_DIRECTORY", ")", ")", ";", "Util", ".", "delete", "(", "new", "File", "(", "targetPath", ",", "LocalVMLauncher", ".", "BOOT_CLASSPATH_DIRECTORY", ")", ")", ";", "File", "file", "=", "new", "File", "(", "targetPath", ",", "RuntimeConstants", ".", "SUPPORT_ZIP_FILE_NAME", ")", ";", "/* workaround pb with Process.exitValue() that returns the process has exited, but it has not free the file yet\n\t\tint count = 10;\n\t\tfor (int i = 0; i < count; i++) {\n\t\t\tif (file.delete()) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tThread.sleep(count * 100);\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\t*/", "if", "(", "!", "Util", ".", "delete", "(", "file", ")", ")", "{", "throw", "new", "TargetException", "(", "\"", "Could not delete ", "\"", "+", "file", ".", "getPath", "(", ")", ")", ";", "}", "}", "else", "{", "Util", ".", "delete", "(", "targetPath", ")", ";", "}", "}", "/**\n * Returns the debug port number for this VM. This is the port number that was\n * passed as the \"-debug\" option if this VM was launched using a <code>LocalVMLauncher</code>.\n * Returns -1 if this information is not available or if this VM is not running in\n * debug mode.\n */", "public", "int", "getDebugPortNumber", "(", ")", "{", "return", "this", ".", "debugPort", ";", "}", "/**\n * Returns an input stream that is connected to the standard error\n * (<code>System.err</code>) of this target VM.\n * Bytes that are written to <code>System.err</code> by the target\n * program become available in the input stream.\n * <p>\n * Note 1: This stream is usually unbuffered.\n * <p>\n * Note 2: Two calls to this method return the same identical input stream.\n * <p>\n * See also <code>java.lang.Process.getErrorStream()</code>.\n *\n * @return an input stream connected to the target VM's <code>System.err</code>.\n * @exception TargetException if the target VM is not reachable.\n */", "public", "InputStream", "getErrorStream", "(", ")", "throws", "TargetException", "{", "if", "(", "this", ".", "process", "==", "null", ")", "throw", "new", "TargetException", "(", "\"", "The VM is not running", "\"", ")", ";", "return", "this", ".", "process", ".", "getErrorStream", "(", ")", ";", "}", "/**\n * Returns an input stream that is connected to the standard output\n * (<code>System.out</code>) of this target VM.\n * Bytes that are written to <code>System.out</code> by the target\n * program become available in the input stream.\n * <p>\n * Note 1: This stream is usually buffered.\n * <p>\n * Note 2: Two calls to this method return the same identical input stream.\n * <p>\n * See also <code>java.lang.Process.getInputStream()</code>.\n *\n * @return an input stream connected to the target VM's <code>System.out</code>.\n * @exception TargetException if the target VM is not reachable.\n */", "public", "InputStream", "getInputStream", "(", ")", "throws", "TargetException", "{", "if", "(", "this", ".", "process", "==", "null", ")", "throw", "new", "TargetException", "(", "\"", "The VM is not running", "\"", ")", ";", "return", "new", "VMInputStream", "(", "this", ".", "process", ",", "this", ".", "process", ".", "getInputStream", "(", ")", ")", ";", "}", "/**\n * Returns an output stream that is connected to the standard input\n * (<code>System.in</code>) of this target VM.\n * Bytes that are written to the output stream by a client become available to the target\n * program in <code>System.in</code>.\n * <p>\n * Note 1: This stream is usually buffered.\n * <p>\n * Note 2: Two calls to this method return the same identical output stream.\n * <p>\n * See also <code>java.lang.Process.getOutputStream()</code>.\n *\n * @return an output stream connected to the target VM's <code>System.in</code>.\n * @exception TargetException if the target VM is not reachable.\n */", "public", "OutputStream", "getOutputStream", "(", ")", "throws", "TargetException", "{", "if", "(", "this", ".", "process", "==", "null", ")", "throw", "new", "TargetException", "(", "\"", "The VM is not running", "\"", ")", ";", "return", "this", ".", "process", ".", "getOutputStream", "(", ")", ";", "}", "/**\n * Returns whether this target VM is still running.\n * <p>\n * Note: This operation may require contacting the target VM to find out\n * if it is still running.\n */", "public", "boolean", "isRunning", "(", ")", "{", "if", "(", "this", ".", "process", "==", "null", ")", "{", "return", "false", ";", "}", "boolean", "hasExited", ";", "try", "{", "this", ".", "process", ".", "exitValue", "(", ")", ";", "hasExited", "=", "true", ";", "}", "catch", "(", "IllegalThreadStateException", "e", ")", "{", "hasExited", "=", "false", ";", "}", "return", "!", "hasExited", ";", "}", "/**\n * Shuts down this target VM.\n * This causes the VM to exit. This operation is ignored\n * if the VM has already shut down.\n *\n * @throws TargetException if the target path could not be cleaned up\n */", "public", "synchronized", "void", "shutDown", "(", ")", "throws", "TargetException", "{", "if", "(", "this", ".", "process", "!=", "null", ")", "{", "this", ".", "process", ".", "destroy", "(", ")", ";", "this", ".", "process", "=", "null", ";", "cleanupTargetPath", "(", ")", ";", "}", "}", "}" ]
Wrapper around the external process that is running a local VM.
[ "Wrapper", "around", "the", "external", "process", "that", "is", "running", "a", "local", "VM", "." ]
[ "// Workaround problem with input stream of a Process" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
69bab54c0105ffa50f2059388fc409a994681611
lll-jy/tp
src/test/java/seedu/address/logic/commands/project/AddTeammateCommandTest.java
[ "MIT" ]
Java
AddTeammateCommandTest
/** * Contains tests regarding AddTeammateCommand */
Contains tests regarding AddTeammateCommand
[ "Contains", "tests", "regarding", "AddTeammateCommand" ]
public class AddTeammateCommandTest { @Test public void execute_invalidPerson_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> { new AddTeammateCommand(null); }); } @Test public void execute_invalidModel_throwsNullPointerException() { AddTeammateCommand addTeammateCommand = new AddTeammateCommand(DESC_A); Model model = null; assertThrows(NullPointerException.class, () -> { addTeammateCommand.execute(model); }); } @Test public void execute_validModel() { AddTeammateCommand addTeammateCommand = new AddTeammateCommand(DESC_A); Model model = new ModelManager(getTypicalMainCatalogue(), new UserPrefs()); model.updateProjectToBeDisplayedOnDashboard(AI); String expectedResult = String.format(AddTeammateCommand.MESSAGE_NEW_TEAMMATE_SUCCESS, DESC_A.getGitUserNameString()); try { CommandResult commandResult = addTeammateCommand.execute(model); assertEquals(expectedResult, commandResult.getFeedbackToUser()); } catch (Exception e) { fail(); } } @Test public void execute_equals() { AddTeammateCommand addTeammateCommand1 = new AddTeammateCommand(DESC_A); AddTeammateCommand addTeammateCommand2 = new AddTeammateCommand(DESC_B); AddTeammateCommand addTeammateCommand3 = new AddTeammateCommand(DESC_C); // same object -> returns true assertEquals(addTeammateCommand1, addTeammateCommand1); // same values -> returns true AddTeammateCommand addTeammateCommand1Copy = new AddTeammateCommand(DESC_A); assertEquals(addTeammateCommand1Copy, addTeammateCommand1); // different types -> returns false assertNotEquals(addTeammateCommand1, "this test will return false"); // null -> returns false assertNotEquals(addTeammateCommand1, null); // different tasks -> returns false assertNotEquals(addTeammateCommand2, addTeammateCommand1); assertNotEquals(addTeammateCommand3, addTeammateCommand2); } }
[ "public", "class", "AddTeammateCommandTest", "{", "@", "Test", "public", "void", "execute_invalidPerson_throwsNullPointerException", "(", ")", "{", "assertThrows", "(", "NullPointerException", ".", "class", ",", "(", ")", "->", "{", "new", "AddTeammateCommand", "(", "null", ")", ";", "}", ")", ";", "}", "@", "Test", "public", "void", "execute_invalidModel_throwsNullPointerException", "(", ")", "{", "AddTeammateCommand", "addTeammateCommand", "=", "new", "AddTeammateCommand", "(", "DESC_A", ")", ";", "Model", "model", "=", "null", ";", "assertThrows", "(", "NullPointerException", ".", "class", ",", "(", ")", "->", "{", "addTeammateCommand", ".", "execute", "(", "model", ")", ";", "}", ")", ";", "}", "@", "Test", "public", "void", "execute_validModel", "(", ")", "{", "AddTeammateCommand", "addTeammateCommand", "=", "new", "AddTeammateCommand", "(", "DESC_A", ")", ";", "Model", "model", "=", "new", "ModelManager", "(", "getTypicalMainCatalogue", "(", ")", ",", "new", "UserPrefs", "(", ")", ")", ";", "model", ".", "updateProjectToBeDisplayedOnDashboard", "(", "AI", ")", ";", "String", "expectedResult", "=", "String", ".", "format", "(", "AddTeammateCommand", ".", "MESSAGE_NEW_TEAMMATE_SUCCESS", ",", "DESC_A", ".", "getGitUserNameString", "(", ")", ")", ";", "try", "{", "CommandResult", "commandResult", "=", "addTeammateCommand", ".", "execute", "(", "model", ")", ";", "assertEquals", "(", "expectedResult", ",", "commandResult", ".", "getFeedbackToUser", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "fail", "(", ")", ";", "}", "}", "@", "Test", "public", "void", "execute_equals", "(", ")", "{", "AddTeammateCommand", "addTeammateCommand1", "=", "new", "AddTeammateCommand", "(", "DESC_A", ")", ";", "AddTeammateCommand", "addTeammateCommand2", "=", "new", "AddTeammateCommand", "(", "DESC_B", ")", ";", "AddTeammateCommand", "addTeammateCommand3", "=", "new", "AddTeammateCommand", "(", "DESC_C", ")", ";", "assertEquals", "(", "addTeammateCommand1", ",", "addTeammateCommand1", ")", ";", "AddTeammateCommand", "addTeammateCommand1Copy", "=", "new", "AddTeammateCommand", "(", "DESC_A", ")", ";", "assertEquals", "(", "addTeammateCommand1Copy", ",", "addTeammateCommand1", ")", ";", "assertNotEquals", "(", "addTeammateCommand1", ",", "\"", "this test will return false", "\"", ")", ";", "assertNotEquals", "(", "addTeammateCommand1", ",", "null", ")", ";", "assertNotEquals", "(", "addTeammateCommand2", ",", "addTeammateCommand1", ")", ";", "assertNotEquals", "(", "addTeammateCommand3", ",", "addTeammateCommand2", ")", ";", "}", "}" ]
Contains tests regarding AddTeammateCommand
[ "Contains", "tests", "regarding", "AddTeammateCommand" ]
[ "// same object -> returns true", "// same values -> returns true", "// different types -> returns false", "// null -> returns false", "// different tasks -> returns false" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
69bc6db4980ceb3bfbf902087abce585e519d5ca
CeON/dataverse
dataverse-webapp/src/main/java/edu/harvard/iq/dataverse/search/ror/RorSolrDataFinder.java
[ "Apache-2.0" ]
Java
RorSolrDataFinder
/** * Solr data finder dedicated for ROR collection */
Solr data finder dedicated for ROR collection
[ "Solr", "data", "finder", "dedicated", "for", "ROR", "collection" ]
@Stateless public class RorSolrDataFinder { @Inject @RorSolrClient private SolrClient solrClient; @Inject private SolrQuerySanitizer solrQuerySanitizer; public List<RorDto> findRorData(String searchPhrase, int maxResultsCount) { StringBuilder queryBuilder = new StringBuilder(); String cleanQuery = solrQuerySanitizer.sanitizeRorQuery(searchPhrase); String[] slicedPhrases = StringUtils.split(cleanQuery); for (int loopIndex = 0; loopIndex < slicedPhrases.length; loopIndex++) { queryBuilder.append(slicedPhrases[loopIndex]); queryBuilder.append('*'); if (isNotLastWord(slicedPhrases, loopIndex)){ queryBuilder.append(" AND "); } } if (queryBuilder.length() == 0) { queryBuilder.append('*'); } SolrQuery solrQuery = new SolrQuery(queryBuilder.toString()); solrQuery.setRows(maxResultsCount); QueryResponse response = Try.of(() -> solrClient.query(solrQuery)) .getOrElseThrow(throwable -> new IllegalStateException("Unable to query ror collection in solr.", throwable)); return response.getBeans(RorDto.class); } private boolean isNotLastWord(String[] slicedPhrases, int loopIndex) { return loopIndex != slicedPhrases.length - 1; } }
[ "@", "Stateless", "public", "class", "RorSolrDataFinder", "{", "@", "Inject", "@", "RorSolrClient", "private", "SolrClient", "solrClient", ";", "@", "Inject", "private", "SolrQuerySanitizer", "solrQuerySanitizer", ";", "public", "List", "<", "RorDto", ">", "findRorData", "(", "String", "searchPhrase", ",", "int", "maxResultsCount", ")", "{", "StringBuilder", "queryBuilder", "=", "new", "StringBuilder", "(", ")", ";", "String", "cleanQuery", "=", "solrQuerySanitizer", ".", "sanitizeRorQuery", "(", "searchPhrase", ")", ";", "String", "[", "]", "slicedPhrases", "=", "StringUtils", ".", "split", "(", "cleanQuery", ")", ";", "for", "(", "int", "loopIndex", "=", "0", ";", "loopIndex", "<", "slicedPhrases", ".", "length", ";", "loopIndex", "++", ")", "{", "queryBuilder", ".", "append", "(", "slicedPhrases", "[", "loopIndex", "]", ")", ";", "queryBuilder", ".", "append", "(", "'*'", ")", ";", "if", "(", "isNotLastWord", "(", "slicedPhrases", ",", "loopIndex", ")", ")", "{", "queryBuilder", ".", "append", "(", "\"", " AND ", "\"", ")", ";", "}", "}", "if", "(", "queryBuilder", ".", "length", "(", ")", "==", "0", ")", "{", "queryBuilder", ".", "append", "(", "'*'", ")", ";", "}", "SolrQuery", "solrQuery", "=", "new", "SolrQuery", "(", "queryBuilder", ".", "toString", "(", ")", ")", ";", "solrQuery", ".", "setRows", "(", "maxResultsCount", ")", ";", "QueryResponse", "response", "=", "Try", ".", "of", "(", "(", ")", "->", "solrClient", ".", "query", "(", "solrQuery", ")", ")", ".", "getOrElseThrow", "(", "throwable", "->", "new", "IllegalStateException", "(", "\"", "Unable to query ror collection in solr.", "\"", ",", "throwable", ")", ")", ";", "return", "response", ".", "getBeans", "(", "RorDto", ".", "class", ")", ";", "}", "private", "boolean", "isNotLastWord", "(", "String", "[", "]", "slicedPhrases", ",", "int", "loopIndex", ")", "{", "return", "loopIndex", "!=", "slicedPhrases", ".", "length", "-", "1", ";", "}", "}" ]
Solr data finder dedicated for ROR collection
[ "Solr", "data", "finder", "dedicated", "for", "ROR", "collection" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
69bcd1d1e22c225ed1378bea7c0fddf65cf07e59
wmelani/programming-problems-and-algorithms
src/main/java/datastructures/LinkedList.java
[ "MIT" ]
Java
LinkedList
/** * was a pain to implement real list interface, not helpful while practicing algorithms... * <p> * Add O(1) * Delete O(N) * Find O(N) * * @param <T> */
was a pain to implement real list interface, not helpful while practicing algorithms Add O(1) Delete O(N) Find O(N) @param
[ "was", "a", "pain", "to", "implement", "real", "list", "interface", "not", "helpful", "while", "practicing", "algorithms", "Add", "O", "(", "1", ")", "Delete", "O", "(", "N", ")", "Find", "O", "(", "N", ")", "@param" ]
public class LinkedList<T> implements Iterable<T> { private int count; private LinkedListNode<T> start; private LinkedListNode<T> end; public void add(T entry) { if (count == 0) { this.start = new LinkedListNode<>(entry); this.end = this.start; this.count++; return; } if (count > 0) { var newNode = new LinkedListNode<>(entry); this.end.next = newNode; newNode.prev = this.end; this.end = newNode; this.count++; } } public boolean remove(T entry) { var node = this.findNode(entry); if (!node.isPresent()) { return false; } var entryNode = node.get(); if (count == 1) { this.start = null; this.end = null; this.count = 0; return true; } // removing the head if (Objects.equals(this.start, entryNode)) { this.start = this.start.next; } // removing the tail if (Objects.equals(this.end, entryNode)) { this.end = this.end.prev; } // removing a middle element entryNode.prev.next = entryNode.next; count--; return true; } private Optional<LinkedListNode<T>> findNode(T entry) { if (count == 0) { return Optional.empty(); } if (count == 1) { return Optional.of(this.start); } LinkedListNode<T> current = this.start; while (current != null) { if (Objects.equals(current.entry, entry)) { return Optional.of(current); } current = current.next; } return Optional.empty(); } public int size() { return this.count; } public boolean isEmpty() { return this.count == 0; } /** * Not looking to implement java iterator, so this terrible perf loop instead! */ public T getByIndex(int index) { if (index < 0 || index >= this.count) { throw new IndexOutOfBoundsException("index"); } int i = 0; var current = this.start; while (i < index) { current = current.next; i++; } return current.entry; } public Iterator<T> iterator() { return new LinkedListIterator<T>(this); } private static class LinkedListNode<T> { T entry; LinkedListNode<T> prev; LinkedListNode<T> next; LinkedListNode(T entry) { this.entry = entry; } } private static class LinkedListIterator<T> implements Iterator<T> { private final LinkedList<T> tLinkedList; private LinkedListNode<T> it; public LinkedListIterator(LinkedList<T> tLinkedList) { this.tLinkedList = tLinkedList; this.it = tLinkedList.start; } @Override public boolean hasNext() { return this.it.next != null; } @Override public T next() { var entry = it.entry; this.it = it.next; return entry; } } }
[ "public", "class", "LinkedList", "<", "T", ">", "implements", "Iterable", "<", "T", ">", "{", "private", "int", "count", ";", "private", "LinkedListNode", "<", "T", ">", "start", ";", "private", "LinkedListNode", "<", "T", ">", "end", ";", "public", "void", "add", "(", "T", "entry", ")", "{", "if", "(", "count", "==", "0", ")", "{", "this", ".", "start", "=", "new", "LinkedListNode", "<", ">", "(", "entry", ")", ";", "this", ".", "end", "=", "this", ".", "start", ";", "this", ".", "count", "++", ";", "return", ";", "}", "if", "(", "count", ">", "0", ")", "{", "var", "newNode", "=", "new", "LinkedListNode", "<", ">", "(", "entry", ")", ";", "this", ".", "end", ".", "next", "=", "newNode", ";", "newNode", ".", "prev", "=", "this", ".", "end", ";", "this", ".", "end", "=", "newNode", ";", "this", ".", "count", "++", ";", "}", "}", "public", "boolean", "remove", "(", "T", "entry", ")", "{", "var", "node", "=", "this", ".", "findNode", "(", "entry", ")", ";", "if", "(", "!", "node", ".", "isPresent", "(", ")", ")", "{", "return", "false", ";", "}", "var", "entryNode", "=", "node", ".", "get", "(", ")", ";", "if", "(", "count", "==", "1", ")", "{", "this", ".", "start", "=", "null", ";", "this", ".", "end", "=", "null", ";", "this", ".", "count", "=", "0", ";", "return", "true", ";", "}", "if", "(", "Objects", ".", "equals", "(", "this", ".", "start", ",", "entryNode", ")", ")", "{", "this", ".", "start", "=", "this", ".", "start", ".", "next", ";", "}", "if", "(", "Objects", ".", "equals", "(", "this", ".", "end", ",", "entryNode", ")", ")", "{", "this", ".", "end", "=", "this", ".", "end", ".", "prev", ";", "}", "entryNode", ".", "prev", ".", "next", "=", "entryNode", ".", "next", ";", "count", "--", ";", "return", "true", ";", "}", "private", "Optional", "<", "LinkedListNode", "<", "T", ">", ">", "findNode", "(", "T", "entry", ")", "{", "if", "(", "count", "==", "0", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "if", "(", "count", "==", "1", ")", "{", "return", "Optional", ".", "of", "(", "this", ".", "start", ")", ";", "}", "LinkedListNode", "<", "T", ">", "current", "=", "this", ".", "start", ";", "while", "(", "current", "!=", "null", ")", "{", "if", "(", "Objects", ".", "equals", "(", "current", ".", "entry", ",", "entry", ")", ")", "{", "return", "Optional", ".", "of", "(", "current", ")", ";", "}", "current", "=", "current", ".", "next", ";", "}", "return", "Optional", ".", "empty", "(", ")", ";", "}", "public", "int", "size", "(", ")", "{", "return", "this", ".", "count", ";", "}", "public", "boolean", "isEmpty", "(", ")", "{", "return", "this", ".", "count", "==", "0", ";", "}", "/**\n * Not looking to implement java iterator, so this terrible perf loop instead!\n */", "public", "T", "getByIndex", "(", "int", "index", ")", "{", "if", "(", "index", "<", "0", "||", "index", ">=", "this", ".", "count", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", "\"", "index", "\"", ")", ";", "}", "int", "i", "=", "0", ";", "var", "current", "=", "this", ".", "start", ";", "while", "(", "i", "<", "index", ")", "{", "current", "=", "current", ".", "next", ";", "i", "++", ";", "}", "return", "current", ".", "entry", ";", "}", "public", "Iterator", "<", "T", ">", "iterator", "(", ")", "{", "return", "new", "LinkedListIterator", "<", "T", ">", "(", "this", ")", ";", "}", "private", "static", "class", "LinkedListNode", "<", "T", ">", "{", "T", "entry", ";", "LinkedListNode", "<", "T", ">", "prev", ";", "LinkedListNode", "<", "T", ">", "next", ";", "LinkedListNode", "(", "T", "entry", ")", "{", "this", ".", "entry", "=", "entry", ";", "}", "}", "private", "static", "class", "LinkedListIterator", "<", "T", ">", "implements", "Iterator", "<", "T", ">", "{", "private", "final", "LinkedList", "<", "T", ">", "tLinkedList", ";", "private", "LinkedListNode", "<", "T", ">", "it", ";", "public", "LinkedListIterator", "(", "LinkedList", "<", "T", ">", "tLinkedList", ")", "{", "this", ".", "tLinkedList", "=", "tLinkedList", ";", "this", ".", "it", "=", "tLinkedList", ".", "start", ";", "}", "@", "Override", "public", "boolean", "hasNext", "(", ")", "{", "return", "this", ".", "it", ".", "next", "!=", "null", ";", "}", "@", "Override", "public", "T", "next", "(", ")", "{", "var", "entry", "=", "it", ".", "entry", ";", "this", ".", "it", "=", "it", ".", "next", ";", "return", "entry", ";", "}", "}", "}" ]
was a pain to implement real list interface, not helpful while practicing algorithms... <p> Add O(1) Delete O(N) Find O(N)
[ "was", "a", "pain", "to", "implement", "real", "list", "interface", "not", "helpful", "while", "practicing", "algorithms", "...", "<p", ">", "Add", "O", "(", "1", ")", "Delete", "O", "(", "N", ")", "Find", "O", "(", "N", ")" ]
[ "// removing the head", "// removing the tail", "// removing a middle element" ]
[ { "param": "Iterable<T>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Iterable<T>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69bf4a76293e04f6f6f11c4c6fcf89c58e1cbb80
ulkeba/openolat
src/main/java/org/olat/basesecurity/BaseSecurityManager.java
[ "Apache-2.0" ]
Java
BaseSecurityManager
/** * <h3>Description:</h3> * The PersistingManager implements the security manager and provide methods to * manage identities and user objects based on a database persistence mechanism * using hibernate. * <p> * * @author Felix Jost, Florian Gnaegi */
Description: The PersistingManager implements the security manager and provide methods to manage identities and user objects based on a database persistence mechanism using hibernate. @author Felix Jost, Florian Gnaegi
[ "Description", ":", "The", "PersistingManager", "implements", "the", "security", "manager", "and", "provide", "methods", "to", "manage", "identities", "and", "user", "objects", "based", "on", "a", "database", "persistence", "mechanism", "using", "hibernate", ".", "@author", "Felix", "Jost", "Florian", "Gnaegi" ]
public class BaseSecurityManager implements BaseSecurity { private static final OLog log = Tracing.createLoggerFor(BaseSecurityManager.class); private DB dbInstance; private LoginModule loginModule; private OLATResourceManager orm; private InvitationDAO invitationDao; private String dbVendor = ""; private static BaseSecurityManager INSTANCE; private static String GUEST_USERNAME_PREFIX = "guest_"; public static final OLATResourceable IDENTITY_EVENT_CHANNEL = OresHelper.lookupType(Identity.class); /** * [used by spring] */ private BaseSecurityManager() { INSTANCE = this; } /** * * @return the manager */ public static BaseSecurity getInstance() { return INSTANCE; } public void setLoginModule(LoginModule loginModule) { this.loginModule = loginModule; } /** * [used by spring] * @param orm */ public void setResourceManager(OLATResourceManager orm) { this.orm = orm; } /** * [used by Spring] * @param dbInstance */ public void setDbInstance(DB dbInstance) { this.dbInstance = dbInstance; } /** * [used by Spring] * @param invitationDao */ public void setInvitationDao(InvitationDAO invitationDao) { this.invitationDao = invitationDao; } /** * @see org.olat.basesecurity.Manager#init() */ public void init() { // called only once at startup and only from one thread // init the system level groups and its policies initSysGroupAdmin(); dbInstance.commit(); initSysGroupAuthors(); dbInstance.commit(); initSysGroupGroupmanagers(); dbInstance.commit(); initSysGroupPoolsmanagers(); dbInstance.commit(); initSysGroupUsermanagers(); dbInstance.commit(); initSysGroupUsers(); dbInstance.commit(); initSysGroupAnonymous(); dbInstance.commit(); initSysGroupInstitutionalResourceManager(); dbInstance.commitAndCloseSession(); } /** * OLAT system administrators, root, good, whatever you name it... */ private void initSysGroupAdmin() { SecurityGroup adminGroup = findSecurityGroupByName(Constants.GROUP_ADMIN); if (adminGroup == null) adminGroup = createAndPersistNamedSecurityGroup(Constants.GROUP_ADMIN); // we check everthing by policies, so we must give admins the hasRole // permission on the type resource "Admin" createAndPersistPolicyIfNotExists(adminGroup, Constants.PERMISSION_HASROLE, Constants.ORESOURCE_ADMIN); //admins have role "authors" by default createAndPersistPolicyIfNotExists(adminGroup, Constants.PERMISSION_HASROLE, Constants.ORESOURCE_AUTHOR); //admins have a groupmanager policy and access permissions to groupmanaging tools createAndPersistPolicyIfNotExists(adminGroup, Constants.PERMISSION_HASROLE, Constants.ORESOURCE_GROUPMANAGER); //admins have a usemanager policy and access permissions to usermanagement tools createAndPersistPolicyIfNotExists(adminGroup, Constants.PERMISSION_HASROLE, Constants.ORESOURCE_USERMANAGER); //admins are also regular users createAndPersistPolicyIfNotExists(adminGroup, Constants.PERMISSION_HASROLE, Constants.ORESOURCE_USERS); //olat admins have access to all security groups createAndPersistPolicyIfNotExists(adminGroup, Constants.PERMISSION_ACCESS, Constants.ORESOURCE_SECURITYGROUPS); // and to all courses createAndPersistPolicyIfNotExists(adminGroup, Constants.PERMISSION_ADMIN, Constants.ORESOURCE_COURSES); // and to pool admiistration createAndPersistPolicyIfNotExists(adminGroup, Constants.PERMISSION_ADMIN, Constants.ORESOURCE_POOLS); createAndPersistPolicyIfNotExists(adminGroup, Constants.PERMISSION_ACCESS, OresHelper.lookupType(SysinfoController.class)); createAndPersistPolicyIfNotExists(adminGroup, Constants.PERMISSION_ACCESS, OresHelper.lookupType(UserAdminController.class)); createAndPersistPolicyIfNotExists(adminGroup, Constants.PERMISSION_ACCESS, OresHelper.lookupType(UserChangePasswordController.class)); createAndPersistPolicyIfNotExists(adminGroup, Constants.PERMISSION_ACCESS, OresHelper.lookupType(UserCreateController.class)); createAndPersistPolicyIfNotExists(adminGroup, Constants.PERMISSION_ACCESS, OresHelper.lookupType(GenericQuotaEditController.class)); } /** * Every active user that is an active user is in the user group. exceptions: logonDenied and anonymous users */ private void initSysGroupUsers() { SecurityGroup olatuserGroup = findSecurityGroupByName(Constants.GROUP_OLATUSERS); if (olatuserGroup == null) olatuserGroup = createAndPersistNamedSecurityGroup(Constants.GROUP_OLATUSERS); //users have a user policy createAndPersistPolicyIfNotExists(olatuserGroup, Constants.PERMISSION_HASROLE, Constants.ORESOURCE_USERS); createAndPersistPolicyIfNotExists(olatuserGroup, Constants.PERMISSION_ACCESS, OresHelper.lookupType(ChangePasswordController.class)); } /** * Users with access to group context management (groupmanagement that can be used in multiple courses */ private void initSysGroupGroupmanagers() { SecurityGroup olatGroupmanagerGroup = findSecurityGroupByName(Constants.GROUP_GROUPMANAGERS); if (olatGroupmanagerGroup == null) olatGroupmanagerGroup = createAndPersistNamedSecurityGroup(Constants.GROUP_GROUPMANAGERS); //gropumanagers have a groupmanager policy and access permissions to groupmanaging tools createAndPersistPolicyIfNotExists(olatGroupmanagerGroup, Constants.PERMISSION_HASROLE, Constants.ORESOURCE_GROUPMANAGER); } /** * Users with access to group context management (groupmanagement that can be used in multiple courses */ private void initSysGroupPoolsmanagers() { SecurityGroup secGroup = findSecurityGroupByName(Constants.GROUP_POOL_MANAGER); if (secGroup == null) secGroup = createAndPersistNamedSecurityGroup(Constants.GROUP_POOL_MANAGER); //pools managers have a goupmanager policy and access permissions to groupmanaging tools createAndPersistPolicyIfNotExists(secGroup, Constants.PERMISSION_HASROLE, Constants.ORESOURCE_POOLS); } /** * Users with access to user management */ private void initSysGroupUsermanagers() { SecurityGroup olatUsermanagerGroup = findSecurityGroupByName(Constants.GROUP_USERMANAGERS); if (olatUsermanagerGroup == null) olatUsermanagerGroup = createAndPersistNamedSecurityGroup(Constants.GROUP_USERMANAGERS); //gropumanagers have a groupmanager policy and access permissions to groupmanaging tools createAndPersistPolicyIfNotExists(olatUsermanagerGroup, Constants.PERMISSION_HASROLE, Constants.ORESOURCE_USERMANAGER); createAndPersistPolicyIfNotExists(olatUsermanagerGroup, Constants.PERMISSION_ACCESS, OresHelper.lookupType(UserAdminController.class)); createAndPersistPolicyIfNotExists(olatUsermanagerGroup, Constants.PERMISSION_ACCESS, OresHelper.lookupType(UserChangePasswordController.class)); createAndPersistPolicyIfNotExists(olatUsermanagerGroup, Constants.PERMISSION_ACCESS, OresHelper.lookupType(UserCreateController.class)); createAndPersistPolicyIfNotExists(olatUsermanagerGroup, Constants.PERMISSION_ACCESS, OresHelper.lookupType(GenericQuotaEditController.class)); } /** * Users with access to the authoring parts of the learning ressources repository */ private void initSysGroupAuthors() { SecurityGroup olatauthorGroup = findSecurityGroupByName(Constants.GROUP_AUTHORS); if (olatauthorGroup == null) olatauthorGroup = createAndPersistNamedSecurityGroup(Constants.GROUP_AUTHORS); //authors have a author policy and access permissions to authoring tools createAndPersistPolicyIfNotExists(olatauthorGroup, Constants.PERMISSION_HASROLE, Constants.ORESOURCE_AUTHOR); } /** * Users with access to the authoring parts of the learning ressources repository (all resources in his university) */ private void initSysGroupInstitutionalResourceManager() { SecurityGroup institutionalResourceManagerGroup = findSecurityGroupByName(Constants.GROUP_INST_ORES_MANAGER); if (institutionalResourceManagerGroup == null) institutionalResourceManagerGroup = createAndPersistNamedSecurityGroup(Constants.GROUP_INST_ORES_MANAGER); //manager have a author policy and access permissions to authoring tools createAndPersistPolicyIfNotExists(institutionalResourceManagerGroup, Constants.PERMISSION_HASROLE, Constants.ORESOURCE_INSTORESMANAGER); createAndPersistPolicyIfNotExists(institutionalResourceManagerGroup, Constants.PERMISSION_ACCESS, OresHelper.lookupType(GenericQuotaEditController.class)); } /** * Unknown users with guest only rights */ private void initSysGroupAnonymous() { SecurityGroup guestGroup = findSecurityGroupByName(Constants.GROUP_ANONYMOUS); if (guestGroup == null) guestGroup = createAndPersistNamedSecurityGroup(Constants.GROUP_ANONYMOUS); //guest(=anonymous) have a guest policy createAndPersistPolicyIfNotExists(guestGroup, Constants.PERMISSION_HASROLE, Constants.ORESOURCE_GUESTONLY); } /** * @see org.olat.basesecurity.Manager#getPoliciesOfSecurityGroup(org.olat.basesecurity.SecurityGroup) */ @Override public List<Policy> getPoliciesOfSecurityGroup(SecurityGroup secGroup) { if(secGroup == null ) return Collections.emptyList(); StringBuilder sb = new StringBuilder(); sb.append("select poi from ").append(PolicyImpl.class.getName()).append(" as poi where poi.securityGroup.key=:secGroupKey"); List<Policy> policies = DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString(), Policy.class) .setParameter("secGroupKey", secGroup.getKey()) .getResultList(); return policies; } /** * @see org.olat.basesecurity.BaseSecurity#getPoliciesOfResource(org.olat.core.id.OLATResourceable) */ @Override public List<Policy> getPoliciesOfResource(OLATResource resource, SecurityGroup secGroup) { StringBuilder sb = new StringBuilder(); sb.append("select poi from ").append(PolicyImpl.class.getName()).append(" poi where ") .append(" poi.olatResource.key=:resourceKey "); if(secGroup != null) { sb.append(" and poi.securityGroup.key=:secGroupKey"); } TypedQuery<Policy> query = DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString(), Policy.class) .setParameter("resourceKey", resource.getKey()); if(secGroup != null) { query.setParameter("secGroupKey", secGroup.getKey()); } return query.getResultList(); } @Override public boolean isIdentityPermittedOnResourceable(Identity identity, String permission, OLATResourceable olatResourceable) { return isIdentityPermittedOnResourceable(identity, permission, olatResourceable, true); } /** * @see org.olat.basesecurity.Manager#isIdentityPermittedOnResourceable(org.olat.core.id.Identity, java.lang.String, org.olat.core.id.OLATResourceable boolean) */ @Override public boolean isIdentityPermittedOnResourceable(Identity identity, String permission, OLATResourceable olatResourceable, boolean checkTypeRight) { if(identity == null || identity.getKey() == null) return false;//no identity, no permission Long oresid = olatResourceable.getResourceableId(); if (oresid == null) oresid = new Long(0); //TODO: make a method in // OLATResorceManager, since this // is implementation detail String oresName = olatResourceable.getResourceableTypeName(); // if the olatResourceable is not persisted as OLATResource, then the answer // is false, // therefore we can use the query assuming there is an OLATResource TypedQuery<Number> query; if(checkTypeRight) { query = DBFactory.getInstance().getCurrentEntityManager().createNamedQuery("isIdentityPermittedOnResourceableCheckType", Number.class); } else { query = DBFactory.getInstance().getCurrentEntityManager().createNamedQuery("isIdentityPermittedOnResourceable", Number.class); } Number count = query.setParameter("identitykey", identity.getKey()) .setParameter("permission", permission) .setParameter("resid", oresid) .setParameter("resname", oresName) .setHint("org.hibernate.cacheable", Boolean.TRUE) .getSingleResult(); return count.longValue() > 0; } /** * @see org.olat.basesecurity.Manager#getRoles(org.olat.core.id.Identity) */ @Override public Roles getRoles(Identity identity) { boolean isGuestOnly = false; boolean isInvitee = false; List<String> rolesStr = getRolesAsString(identity); boolean admin = rolesStr.contains(Constants.GROUP_ADMIN); boolean author = admin || rolesStr.contains(Constants.GROUP_AUTHORS); boolean groupManager = admin || rolesStr.contains(Constants.GROUP_GROUPMANAGERS); boolean userManager = admin || rolesStr.contains(Constants.GROUP_USERMANAGERS); boolean resourceManager = rolesStr.contains(Constants.GROUP_INST_ORES_MANAGER); boolean poolManager = admin || rolesStr.contains(Constants.GROUP_POOL_MANAGER); if(!rolesStr.contains(Constants.GROUP_OLATUSERS)) { isInvitee = invitationDao.isInvitee(identity); isGuestOnly = isIdentityPermittedOnResourceable(identity, Constants.PERMISSION_HASROLE, Constants.ORESOURCE_GUESTONLY); } return new Roles(admin, userManager, groupManager, author, isGuestOnly, resourceManager, poolManager, isInvitee); } @Override public List<String> getRolesAsString(Identity identity) { StringBuilder sb = new StringBuilder(); sb.append("select ngroup.groupName from ").append(NamedGroupImpl.class.getName()).append(" as ngroup ") .append(" where exists (") .append(" select sgmsi from ").append(SecurityGroupMembershipImpl.class.getName()) .append(" as sgmsi where sgmsi.identity.key=:identityKey and sgmsi.securityGroup=ngroup.securityGroup") .append(" )"); return dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), String.class) .setParameter("identityKey", identity.getKey()) .getResultList(); } @Override public void updateRoles(Identity actingIdentity, Identity updatedIdentity, Roles roles) { SecurityGroup anonymousGroup = findSecurityGroupByName(Constants.GROUP_ANONYMOUS); boolean hasBeenAnonymous = isIdentityInSecurityGroup(updatedIdentity, anonymousGroup); updateRolesInSecurityGroup(actingIdentity, updatedIdentity, anonymousGroup, hasBeenAnonymous, roles.isGuestOnly(), Constants.GROUP_ANONYMOUS); // system users - opposite of anonymous users SecurityGroup usersGroup = findSecurityGroupByName(Constants.GROUP_OLATUSERS); boolean hasBeenUser = isIdentityInSecurityGroup(updatedIdentity, usersGroup); updateRolesInSecurityGroup(actingIdentity, updatedIdentity, usersGroup, hasBeenUser, !roles.isGuestOnly(), Constants.GROUP_OLATUSERS); SecurityGroup groupManagerGroup = findSecurityGroupByName(Constants.GROUP_GROUPMANAGERS); boolean hasBeenGroupManager = isIdentityInSecurityGroup(updatedIdentity, groupManagerGroup); boolean groupManager = roles.isGroupManager() && !roles.isGuestOnly() && !roles.isInvitee(); updateRolesInSecurityGroup(actingIdentity, updatedIdentity, groupManagerGroup, hasBeenGroupManager, groupManager, Constants.GROUP_GROUPMANAGERS); // author SecurityGroup authorGroup = findSecurityGroupByName(Constants.GROUP_AUTHORS); boolean hasBeenAuthor = isIdentityInSecurityGroup(updatedIdentity, authorGroup); boolean isAuthor = (roles.isAuthor() || roles.isInstitutionalResourceManager()) && !roles.isGuestOnly() && !roles.isInvitee(); updateRolesInSecurityGroup(actingIdentity, updatedIdentity, authorGroup, hasBeenAuthor, isAuthor, Constants.GROUP_AUTHORS); // user manager, only allowed by admin SecurityGroup userManagerGroup = findSecurityGroupByName(Constants.GROUP_USERMANAGERS); boolean hasBeenUserManager = isIdentityInSecurityGroup(updatedIdentity, userManagerGroup); boolean userManager = roles.isUserManager() && !roles.isGuestOnly() && !roles.isInvitee(); updateRolesInSecurityGroup(actingIdentity, updatedIdentity, userManagerGroup, hasBeenUserManager, userManager, Constants.GROUP_USERMANAGERS); // institutional resource manager SecurityGroup institutionalResourceManagerGroup = findSecurityGroupByName(Constants.GROUP_INST_ORES_MANAGER); boolean hasBeenInstitutionalResourceManager = isIdentityInSecurityGroup(updatedIdentity, institutionalResourceManagerGroup); boolean institutionalResourceManager = roles.isInstitutionalResourceManager() && !roles.isGuestOnly() && !roles.isInvitee(); updateRolesInSecurityGroup(actingIdentity, updatedIdentity, institutionalResourceManagerGroup, hasBeenInstitutionalResourceManager, institutionalResourceManager, Constants.GROUP_INST_ORES_MANAGER); // institutional resource manager SecurityGroup poolManagerGroup = findSecurityGroupByName(Constants.GROUP_POOL_MANAGER); boolean hasBeenPoolManager = isIdentityInSecurityGroup(updatedIdentity, poolManagerGroup); boolean poolManager = roles.isPoolAdmin() && !roles.isGuestOnly() && !roles.isInvitee(); updateRolesInSecurityGroup(actingIdentity, updatedIdentity, poolManagerGroup, hasBeenPoolManager, poolManager, Constants.GROUP_POOL_MANAGER); // system administrator SecurityGroup adminGroup = findSecurityGroupByName(Constants.GROUP_ADMIN); boolean hasBeenAdmin = isIdentityInSecurityGroup(updatedIdentity, adminGroup); boolean isOLATAdmin = roles.isOLATAdmin() && !roles.isGuestOnly() && !roles.isInvitee(); updateRolesInSecurityGroup(actingIdentity, updatedIdentity, adminGroup, hasBeenAdmin, isOLATAdmin, Constants.GROUP_ADMIN); } private void updateRolesInSecurityGroup(Identity actingIdentity, Identity updatedIdentity, SecurityGroup securityGroup, boolean hasBeenInGroup, boolean isNowInGroup, String groupName) { if (!hasBeenInGroup && isNowInGroup) { // user not yet in security group, add him addIdentityToSecurityGroup(updatedIdentity, securityGroup); log.audit("User::" + (actingIdentity == null ? "unkown" : actingIdentity.getName()) + " added system role::" + groupName + " to user::" + updatedIdentity.getName(), null); } else if (hasBeenInGroup && !isNowInGroup) { // user not anymore in security group, remove him removeIdentityFromSecurityGroup(updatedIdentity, securityGroup); log.audit("User::" + (actingIdentity == null ? "unkown" : actingIdentity.getName()) + " removed system role::" + groupName + " from user::" + updatedIdentity.getName(), null); } } /** * scalar query : select sgi, poi, ori * @param identity * @return List of policies */ @Override public List<Policy> getPoliciesOfIdentity(Identity identity) { StringBuilder sb = new StringBuilder(); sb.append("select poi from ").append(PolicyImpl.class.getName()).append(" as poi ") .append("inner join fetch poi.securityGroup as secGroup ") .append("inner join fetch poi.olatResource as resource ") .append("where secGroup in (select sgmi.securityGroup from ") .append(SecurityGroupMembershipImpl.class.getName()).append(" as sgmi where sgmi.identity.key=:identityKey)"); return DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString(), Policy.class) .setParameter("identityKey", identity.getKey()) .getResultList(); } /** * @see org.olat.basesecurity.Manager#isIdentityInSecurityGroup(org.olat.core.id.Identity, org.olat.basesecurity.SecurityGroup) */ public boolean isIdentityInSecurityGroup(Identity identity, SecurityGroup secGroup) { if (secGroup == null || identity == null) return false; String queryString = "select count(sgmsi) from org.olat.basesecurity.SecurityGroupMembershipImpl as sgmsi where sgmsi.identity = :identitykey and sgmsi.securityGroup = :securityGroup"; DBQuery query = DBFactory.getInstance().createQuery(queryString); query.setLong("identitykey", identity.getKey()); query.setLong("securityGroup", secGroup.getKey()); query.setCacheable(true); List res = query.list(); Long cntL = (Long) res.get(0); if (cntL.longValue() != 0 && cntL.longValue() != 1) throw new AssertException("unique n-to-n must always yield 0 or 1"); return (cntL.longValue() == 1); } @Override public void touchMembership(Identity identity, List<SecurityGroup> secGroups) { if (secGroups == null || secGroups.isEmpty()) return; StringBuilder sb = new StringBuilder(); sb.append("select sgmsi from ").append(SecurityGroupMembershipImpl.class.getName()).append(" as sgmsi ") .append("where sgmsi.identity.key=:identityKey and sgmsi.securityGroup in (:securityGroups)"); List<ModifiedInfo> infos = DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString(), ModifiedInfo.class) .setParameter("identityKey", identity.getKey()) .setParameter("securityGroups", secGroups) .getResultList(); for(ModifiedInfo info:infos) { info.setLastModified(new Date()); DBFactory.getInstance().getCurrentEntityManager().merge(info); } } /** * @see org.olat.basesecurity.Manager#createAndPersistSecurityGroup() */ public SecurityGroup createAndPersistSecurityGroup() { SecurityGroupImpl sgi = new SecurityGroupImpl(); DBFactory.getInstance().saveObject(sgi); return sgi; } /** * @see org.olat.basesecurity.Manager#deleteSecurityGroup(org.olat.basesecurity.SecurityGroup) */ public void deleteSecurityGroup(SecurityGroup secGroup) { // we do not use hibernate cascade="delete", but implement our own (to be // sure to understand our code) DB db = DBFactory.getInstance(); //FIXME: fj: Please review: Create rep entry, restart olat, delete the rep // entry. previous implementation resulted in orange screen // secGroup = (SecurityGroup)db.loadObject(secGroup); // so we can later // delete it (hibernate needs an associated session) secGroup = (SecurityGroup) db.loadObject(secGroup); //o_clusterREVIEW //db.reputInHibernateSessionCache(secGroup); /* * if (!db.contains(secGroup)) { secGroup = (SecurityGroupImpl) * db.loadObject(SecurityGroupImpl.class, secGroup.getKey()); } */ // 1) delete associated users (need to do it manually, hibernate knows // nothing about // the membership, modeled manually via many-to-one and not via set) db.delete("from org.olat.basesecurity.SecurityGroupMembershipImpl as msi where msi.securityGroup.key = ?", new Object[] { secGroup .getKey() }, new Type[] { StandardBasicTypes.LONG }); // 2) delete all policies db.delete("from org.olat.basesecurity.PolicyImpl as poi where poi.securityGroup = ?", new Object[] { secGroup.getKey() }, new Type[] { StandardBasicTypes.LONG }); // 3) delete security group db.deleteObject(secGroup); } /** * * * @see org.olat.basesecurity.Manager#addIdentityToSecurityGroup(org.olat.core.id.Identity, org.olat.basesecurity.SecurityGroup) */ @Override public void addIdentityToSecurityGroup(Identity identity, SecurityGroup secGroup) { SecurityGroupMembershipImpl sgmsi = new SecurityGroupMembershipImpl(); sgmsi.setIdentity(identity); sgmsi.setSecurityGroup(secGroup); sgmsi.setLastModified(new Date()); dbInstance.getCurrentEntityManager().persist(sgmsi); } /** * @see org.olat.basesecurity.Manager#removeIdentityFromSecurityGroup(org.olat.core.id.Identity, org.olat.basesecurity.SecurityGroup) */ @Override public boolean removeIdentityFromSecurityGroup(Identity identity, SecurityGroup secGroup) { return removeIdentityFromSecurityGroups(Collections.singletonList(identity), Collections.singletonList(secGroup)); } @Override public boolean removeIdentityFromSecurityGroups(List<Identity> identities, List<SecurityGroup> secGroups) { if(identities == null || identities.isEmpty()) return true;//nothing to do if(secGroups == null || secGroups.isEmpty()) return true;//nothing to do StringBuilder sb = new StringBuilder(); sb.append("delete from ").append(SecurityGroupMembershipImpl.class.getName()).append(" as msi ") .append(" where msi.identity.key in (:identityKeys) and msi.securityGroup.key in (:secGroupKeys)"); List<Long> identityKeys = new ArrayList<Long>(); for(Identity identity:identities) { identityKeys.add(identity.getKey()); } List<Long> secGroupKeys = new ArrayList<Long>(); for(SecurityGroup secGroup:secGroups) { secGroupKeys.add(secGroup.getKey()); } int rowsAffected = DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString()) .setParameter("identityKeys", identityKeys) .setParameter("secGroupKeys", secGroupKeys) .executeUpdate(); return rowsAffected > 0; } /** * @see org.olat.basesecurity.Manager#createAndPersistPolicy(org.olat.basesecurity.SecurityGroup, java.lang.String, org.olat.core.id.OLATResourceable */ @Override public Policy createAndPersistPolicy(SecurityGroup secGroup, String permission, OLATResourceable olatResourceable) { OLATResource olatResource = orm.findOrPersistResourceable(olatResourceable); return createAndPersistPolicyWithResource(secGroup, permission, null, null, olatResource); } /** * Creates a policy and persists on the database * @see org.olat.basesecurity.BaseSecurity#createAndPersistPolicyWithResource(org.olat.basesecurity.SecurityGroup, java.lang.String, java.util.Date, java.util.Date, org.olat.resource.OLATResource) */ private Policy createAndPersistPolicyWithResource(SecurityGroup secGroup, String permission, Date from, Date to, OLATResource olatResource) { PolicyImpl pi = new PolicyImpl(); pi.setSecurityGroup(secGroup); pi.setOlatResource(olatResource); pi.setPermission(permission); pi.setFrom(from); pi.setTo(to); DBFactory.getInstance().saveObject(pi); return pi; } /** * Helper method that only creates a policy only if no such policy exists in the database * @param secGroup * @param permission * @param olatResourceable * @return Policy */ private Policy createAndPersistPolicyIfNotExists(SecurityGroup secGroup, String permission, OLATResourceable olatResourceable) { OLATResource olatResource = orm.findOrPersistResourceable(olatResourceable); Policy existingPolicy = findPolicy(secGroup, permission, olatResource); if (existingPolicy == null) { return createAndPersistPolicy(secGroup, permission, olatResource); } return existingPolicy; } public Policy findPolicy(SecurityGroup secGroup, String permission, OLATResource olatResource) { StringBuilder sb = new StringBuilder(); sb.append("select poi from ").append(PolicyImpl.class.getName()).append(" as poi ") .append(" where poi.permission=:permission and poi.olatResource.key=:resourceKey and poi.securityGroup.key=:secGroupKey"); List<Policy> policies = DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString(), Policy.class) .setParameter("permission", permission) .setParameter("resourceKey", olatResource.getKey()) .setParameter("secGroupKey", secGroup.getKey()) .getResultList(); if (policies.isEmpty()) { return null; } return policies.get(0); } @Override public void deletePolicies(OLATResource resource) { StringBuilder sb = new StringBuilder(); sb.append("delete from ").append(PolicyImpl.class.getName()).append(" as poi ") .append(" where poi.olatResource.key=:resourceKey"); int rowDeleted = DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString()) .setParameter("resourceKey", resource.getKey()) .executeUpdate(); if(log.isDebug()) { log.debug(rowDeleted + " policies deleted"); } } /** * @param username the username * @param user the presisted User * @param authusername the username used as authentication credential * (=username for provider "OLAT") * @param provider the provider of the authentication ("OLAT" or "AAI"). If null, no * authentication token is generated. * @param credential the credentials or null if not used * @return Identity */ @Override public Identity createAndPersistIdentity(String username, User user, String provider, String authusername, String credential) { IdentityImpl iimpl = new IdentityImpl(username, user); dbInstance.getCurrentEntityManager().persist(iimpl); if (provider != null) { createAndPersistAuthentication(iimpl, provider, authusername, credential, loginModule.getDefaultHashAlgorithm()); } notifyNewIdentityCreated(iimpl); return iimpl; } /** * @param username The username * @param user The unpresisted User * @param provider The provider of the authentication ("OLAT" or "AAI"). If null, no authentication token is generated. * @param authusername The username used as authentication credential (=username for provider "OLAT") * @return Identity */ @Override public Identity createAndPersistIdentityAndUser(String username, String externalId, User user, String provider, String authusername) { dbInstance.getCurrentEntityManager().persist(user); IdentityImpl iimpl = new IdentityImpl(username, user); iimpl.setExternalId(externalId); dbInstance.getCurrentEntityManager().persist(iimpl); if (provider != null) { createAndPersistAuthentication(iimpl, provider, authusername, null, null); } notifyNewIdentityCreated(iimpl); return iimpl; } /** * @param username the username * @param user the unpresisted User * @param authusername the username used as authentication credential * (=username for provider "OLAT") * @param provider the provider of the authentication ("OLAT" or "AAI"). If null, no * authentication token is generated. * @param credential the credentials or null if not used * @return Identity */ @Override public Identity createAndPersistIdentityAndUser(String username, String externalId, User user, String provider, String authusername, String credential) { dbInstance.getCurrentEntityManager().persist(user); IdentityImpl iimpl = new IdentityImpl(username, user); iimpl.setExternalId(externalId); dbInstance.getCurrentEntityManager().persist(iimpl); if (provider != null) { createAndPersistAuthentication(iimpl, provider, authusername, credential, loginModule.getDefaultHashAlgorithm()); } notifyNewIdentityCreated(iimpl); return iimpl; } /** * Persists the given user, creates an identity for it and adds the user to * the users system group * * @param loginName * @param externalId * @param pwd null: no OLAT authentication is generated. If not null, the password will be * encrypted and and an OLAT authentication is generated. * @param newUser unpersisted users * @return Identity */ @Override public Identity createAndPersistIdentityAndUserWithDefaultProviderAndUserGroup(String loginName, String externalId, String pwd, User newUser) { Identity ident = null; if (pwd == null) { // when no password is used the provider must be set to null to not generate // an OLAT authentication token. See method doku. ident = createAndPersistIdentityAndUser(loginName, externalId, newUser, null, null); log.audit("Create an identity without authentication (login=" + loginName + ")"); } else { ident = createAndPersistIdentityAndUser(loginName, externalId, newUser, BaseSecurityModule.getDefaultAuthProviderIdentifier(), loginName, pwd); log.audit("Create an identity with " + BaseSecurityModule.getDefaultAuthProviderIdentifier() + " authentication (login=" + loginName + ")"); } // Add user to system users group SecurityGroup olatuserGroup = findSecurityGroupByName(Constants.GROUP_OLATUSERS); addIdentityToSecurityGroup(ident, olatuserGroup); return ident; } /** * Persists the given user, creates an identity for it and adds the user to * the users system group, create an authentication for an external provider * * @param loginName * @param externalId * @param provider * @param authusername * @param newUser * @return */ @Override public Identity createAndPersistIdentityAndUserWithUserGroup(String loginName, String externalId, String provider, String authusername, User newUser) { Identity ident = createAndPersistIdentityAndUser(loginName, externalId, newUser, provider, authusername, null); log.audit("Create an identity with " + provider + " authentication (login=" + loginName + ",authusername=" + authusername + ")"); // Add user to system users group SecurityGroup olatuserGroup = findSecurityGroupByName(Constants.GROUP_OLATUSERS); addIdentityToSecurityGroup(ident, olatuserGroup); return ident; } private void notifyNewIdentityCreated(Identity newIdentity) { //Save the identity on the DB. So can the listeners of the event retrieve it //in cluster mode DBFactory.getInstance().commit(); CoordinatorManager.getInstance().getCoordinator().getEventBus().fireEventToListenersOf(new NewIdentityCreatedEvent(newIdentity), IDENTITY_EVENT_CHANNEL); } /** * @see org.olat.basesecurity.Manager#getIdentitiesOfSecurityGroup(org.olat.basesecurity.SecurityGroup) */ public List<Identity> getIdentitiesOfSecurityGroup(SecurityGroup secGroup) { if (secGroup == null) { throw new AssertException("getIdentitiesOfSecurityGroup: ERROR secGroup was null !!"); } DB db = DBFactory.getInstance(); if (db == null) { throw new AssertException("getIdentitiesOfSecurityGroup: ERROR db was null !!"); } List<Identity> idents = getIdentitiesOfSecurityGroup(secGroup, 0, -1); return idents; } @Override public List<Identity> getIdentitiesOfSecurityGroup(SecurityGroup secGroup, int firstResult, int maxResults) { if (secGroup == null) { throw new AssertException("getIdentitiesOfSecurityGroup: ERROR secGroup was null !!"); } StringBuilder sb = new StringBuilder(); sb.append("select identity from ").append(SecurityGroupMembershipImpl.class.getName()).append(" as sgmsi ") .append(" inner join sgmsi.identity identity ") .append(" inner join fetch identity.user user ") .append(" where sgmsi.securityGroup=:secGroup"); TypedQuery<Identity> query = DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString(), Identity.class) .setParameter("secGroup", secGroup); if(firstResult >= 0) { query.setFirstResult(firstResult); } if(maxResults > 0) { query.setMaxResults(maxResults); } return query.getResultList(); } /** * Return a list of unique identities which are in the list of security groups * @see org.olat.basesecurity.BaseSecurity#getIdentitiesOfSecurityGroups(java.util.List) */ @Override public List<Identity> getIdentitiesOfSecurityGroups(List<SecurityGroup> secGroups) { if (secGroups == null || secGroups.isEmpty()) { return Collections.emptyList(); } StringBuilder sb = new StringBuilder(); sb.append("select distinct(identity) from ").append(SecurityGroupMembershipImpl.class.getName()).append(" as sgmsi ") .append(" inner join sgmsi.identity identity ") .append(" inner join fetch identity.user user ") .append(" where sgmsi.securityGroup in (:secGroups)"); return dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), Identity.class) .setParameter("secGroups", secGroups) .getResultList(); } /** * @see org.olat.basesecurity.Manager#getIdentitiesAndDateOfSecurityGroup(org.olat.basesecurity.SecurityGroup) */ @Override public List<Object[]> getIdentitiesAndDateOfSecurityGroup(SecurityGroup secGroup) { StringBuilder sb = new StringBuilder(); sb.append("select ii, sgmsi.lastModified from ").append(IdentityImpl.class.getName()).append(" as ii") .append(" inner join fetch ii.user as iuser, ") .append(SecurityGroupMembershipImpl.class.getName()).append(" as sgmsi") .append(" where sgmsi.securityGroup=:secGroup and sgmsi.identity = ii"); return dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), Object[].class) .setParameter("secGroup", secGroup) .getResultList(); } /** * @see org.olat.basesecurity.Manager#countIdentitiesOfSecurityGroup(org.olat.basesecurity.SecurityGroup) */ @Override public int countIdentitiesOfSecurityGroup(SecurityGroup secGroup) { DB db = DBFactory.getInstance(); String q = "select count(sgm) from org.olat.basesecurity.SecurityGroupMembershipImpl sgm where sgm.securityGroup = :group"; DBQuery query = db.createQuery(q); query.setEntity("group", secGroup); query.setCacheable(true); int result = ((Long) query.list().get(0)).intValue(); return result; } /** * @see org.olat.basesecurity.Manager#createAndPersistNamedSecurityGroup(java.lang.String) */ @Override public SecurityGroup createAndPersistNamedSecurityGroup(String groupName) { SecurityGroup secG = createAndPersistSecurityGroup(); NamedGroupImpl ngi = new NamedGroupImpl(groupName, secG); DBFactory.getInstance().saveObject(ngi); return secG; } /** * @see org.olat.basesecurity.Manager#findSecurityGroupByName(java.lang.String) */ @Override public SecurityGroup findSecurityGroupByName(String securityGroupName) { StringBuilder sb = new StringBuilder(); sb.append("select sgi from ").append(NamedGroupImpl.class.getName()).append(" as ngroup ") .append(" inner join ngroup.securityGroup sgi") .append(" where ngroup.groupName=:groupName"); List<SecurityGroup> group = dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), SecurityGroup.class) .setParameter("groupName", securityGroupName) .setHint("org.hibernate.cacheable", Boolean.TRUE) .getResultList(); int size = group.size(); if (size == 0) return null; if (size != 1) throw new AssertException("non unique name in namedgroup: " + securityGroupName); SecurityGroup sg = group.get(0); return sg; } /** * @see org.olat.basesecurity.Manager#findIdentityByName(java.lang.String) */ @Override public Identity findIdentityByName(String identityName) { if (identityName == null) throw new AssertException("findIdentitybyName: name was null"); StringBuilder sb = new StringBuilder(); sb.append("select ident from ").append(IdentityImpl.class.getName()).append(" as ident where ident.name=:username"); List<Identity> identities = DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString(), Identity.class) .setParameter("username", identityName) .getResultList(); if(identities.isEmpty()) { return null; } return identities.get(0); } /** * Custom search operation by BiWa * find identity by student/institution number * @return */ @Override public Identity findIdentityByNumber(String identityNumber) { //default initializations Map<String, String> userPropertiesSearch = new HashMap<String, String>(); // institutional identifier userPropertiesSearch.put(UserConstants.INSTITUTIONALUSERIDENTIFIER, identityNumber); List<Identity> identities = getIdentitiesByPowerSearch(null, userPropertiesSearch, true, null, null, null, null, null, null, null, null); //check for unique search result if(identities.size() == 1) { return identities.get(0); } return null; } @Override public List<Identity> findIdentitiesByNumber(Collection<String> identityNumbers) { if(identityNumbers == null || identityNumbers.isEmpty()) return Collections.emptyList(); StringBuilder sb = new StringBuilder(); sb.append("select identity from ").append(IdentityImpl.class.getName()).append(" identity ") .append(" inner join identity.user user ") .append(" where user.userProperties['").append(UserConstants.INSTITUTIONALUSERIDENTIFIER).append("'] in (:idNumbers) "); return dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), Identity.class) .setParameter("idNumbers", identityNumbers) .getResultList(); } @Override public List<Identity> findIdentitiesByName(Collection<String> identityNames) { if (identityNames == null || identityNames.isEmpty()) return Collections.emptyList(); StringBuilder sb = new StringBuilder(); sb.append("select ident from ").append(IdentityImpl.class.getName()).append(" as ident where ident.name in (:username)"); List<Identity> identities = DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString(), Identity.class) .setParameter("username", identityNames) .getResultList(); return identities; } @Override public Identity findIdentityByUser(User user) { if (user == null) return null; StringBuilder sb = new StringBuilder(); sb.append("select ident from ").append(IdentityImpl.class.getName()).append(" as ident where ident.user.key=:userKey"); List<Identity> identities = DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString(), Identity.class) .setParameter("userKey", user.getKey()) .getResultList(); if(identities.isEmpty()) { return null; } return identities.get(0); } @Override public List<IdentityShort> findShortIdentitiesByName(Collection<String> identityNames) { if (identityNames == null || identityNames.isEmpty()) { return Collections.emptyList(); } StringBuilder sb = new StringBuilder(); sb.append("select ident from ").append(IdentityShort.class.getName()).append(" as ident where ident.name in (:names)"); TypedQuery<IdentityShort> query = dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), IdentityShort.class); int count = 0; int batch = 500; List<String> names = new ArrayList<String>(identityNames); List<IdentityShort> shortIdentities = new ArrayList<IdentityShort>(names.size()); do { int toIndex = Math.min(count + batch, names.size()); List<String> toLoad = names.subList(count, toIndex); List<IdentityShort> allProperties = query.setParameter("names", toLoad).getResultList(); shortIdentities.addAll(allProperties); count += batch; } while(count < names.size()); return shortIdentities; } @Override public List<IdentityShort> findShortIdentitiesByKey(Collection<Long> identityKeys) { if (identityKeys == null || identityKeys.isEmpty()) { return Collections.emptyList(); } StringBuilder sb = new StringBuilder(); sb.append("select ident from ").append(IdentityShort.class.getName()).append(" as ident where ident.key in (:keys)"); TypedQuery<IdentityShort> query = dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), IdentityShort.class); int count = 0; int batch = 500; List<Long> names = new ArrayList<Long>(identityKeys); List<IdentityShort> shortIdentities = new ArrayList<IdentityShort>(names.size()); do { int toIndex = Math.min(count + batch, names.size()); List<Long> toLoad = names.subList(count, toIndex); List<IdentityShort> allProperties = query.setParameter("keys", toLoad).getResultList(); shortIdentities.addAll(allProperties); count += batch; } while(count < names.size()); return shortIdentities; } public List<Identity> findIdentitiesWithoutBusinessGroup(Integer status) { StringBuilder sb = new StringBuilder(); sb.append("select ident from ").append(IdentityImpl.class.getName()).append(" as ident ") .append(" where not exists (") .append(" select bgroup from ").append(BusinessGroupImpl.class.getName()).append(" bgroup, bgroupmember as me") .append(" where me.group=bgroup.baseGroup and me.identity=ident") .append(" )"); if (status != null) { if (status.equals(Identity.STATUS_VISIBLE_LIMIT)) { // search for all status smaller than visible limit sb.append(" and ident.status < :status "); } else { // search for certain status sb.append(" and ident.status = :status "); } } else { sb.append(" and ident.status < ").append(Identity.STATUS_DELETED); } TypedQuery<Identity> query = dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), Identity.class); if (status != null) { query.setParameter("status", status); } return query.getResultList(); } /** * * @see org.olat.basesecurity.Manager#loadIdentityByKey(java.lang.Long) */ public Identity loadIdentityByKey(Long identityKey) { if (identityKey == null) throw new AssertException("findIdentitybyKey: key is null"); if(identityKey.equals(Long.valueOf(0))) return null; return DBFactory.getInstance().loadObject(IdentityImpl.class, identityKey); } @Override public List<Identity> loadIdentityByKeys(Collection<Long> identityKeys) { if (identityKeys == null || identityKeys.isEmpty()) { return Collections.emptyList(); } StringBuilder sb = new StringBuilder(); sb.append("select ident from ").append(Identity.class.getName()).append(" as ident where ident.key in (:keys)"); return DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString(), Identity.class) .setParameter("keys", identityKeys) .getResultList(); } /** * @see org.olat.basesecurity.Manager#loadIdentityByKey(java.lang.Long,boolean) */ public Identity loadIdentityByKey(Long identityKey, boolean strict) { if(strict) return loadIdentityByKey(identityKey); String queryStr = "select ident from org.olat.basesecurity.IdentityImpl as ident where ident.key=:identityKey"; DBQuery dbq = DBFactory.getInstance().createQuery(queryStr); dbq.setLong("identityKey", identityKey); List<Identity> identities = dbq.list(); if (identities.size() == 1) return identities.get(0); return null; } @Override public IdentityShort loadIdentityShortByKey(Long identityKey) { StringBuilder sb = new StringBuilder(); sb.append("select identity from ").append(IdentityShort.class.getName()).append(" as identity ") .append(" where identity.key=:identityKey"); List<IdentityShort> idents = DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString(), IdentityShort.class) .setParameter("identityKey", identityKey) .getResultList(); if(idents.isEmpty()) { return null; } return idents.get(0); } @Override public List<IdentityShort> loadIdentityShortByKeys(Collection<Long> identityKeys) { if (identityKeys == null || identityKeys.isEmpty()) { return Collections.emptyList(); } StringBuilder sb = new StringBuilder(); sb.append("select ident from ").append(IdentityShort.class.getName()).append(" as ident where ident.key in (:keys)"); return DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString(), IdentityShort.class) .setParameter("keys", identityKeys) .getResultList(); } @Override public List<Identity> loadIdentities(int firstResult, int maxResults) { StringBuilder sb = new StringBuilder(); sb.append("select ident from ").append(IdentityImpl.class.getName()).append(" as ident order by ident.key"); return DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString(), Identity.class) .setFirstResult(firstResult) .setMaxResults(maxResults) .getResultList(); } @Override public List<Long> loadVisibleIdentityKeys() { StringBuilder sb = new StringBuilder(); sb.append("select ident.key from ").append(IdentityImpl.class.getName()).append(" as ident") .append(" where ident.status<").append(Identity.STATUS_VISIBLE_LIMIT).append(" order by ident.key"); return DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString(), Long.class) .getResultList(); } /** * * @see org.olat.basesecurity.Manager#countUniqueUserLoginsSince(java.util.Date) */ @Override public Long countUniqueUserLoginsSince (Date lastLoginLimit){ String queryStr ="Select count(ident) from org.olat.core.id.Identity as ident where " + "ident.lastLogin > :lastLoginLimit and ident.lastLogin != ident.creationDate"; DBQuery dbq = DBFactory.getInstance().createQuery(queryStr); dbq.setDate("lastLoginLimit", lastLoginLimit); List res = dbq.list(); Long cntL = (Long) res.get(0); return cntL; } /** * @see org.olat.basesecurity.Manager#getAuthentications(org.olat.core.id.Identity) */ @Override public List<Authentication> getAuthentications(Identity identity) { StringBuilder sb = new StringBuilder(); sb.append("select auth from ").append(AuthenticationImpl.class.getName()).append(" as auth ") .append("inner join fetch auth.identity as ident") .append(" where ident.key=:identityKey"); return dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), Authentication.class) .setParameter("identityKey", identity.getKey()) .getResultList(); } /** * @see org.olat.basesecurity.Manager#createAndPersistAuthentication(org.olat.core.id.Identity, java.lang.String, java.lang.String, java.lang.String) */ @Override public Authentication createAndPersistAuthentication(final Identity ident, final String provider, final String authUserName, final String credentials, final Encoder.Algorithm algorithm) { OLATResourceable resourceable = OresHelper.createOLATResourceableInstanceWithoutCheck(provider, ident.getKey()); return CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(resourceable, new SyncerCallback<Authentication>() { @Override public Authentication execute() { Authentication auth = findAuthentication(ident, provider); if(auth == null) { if(algorithm != null && credentials != null) { String salt = algorithm.isSalted() ? Encoder.getSalt() : null; String hash = Encoder.encrypt(credentials, salt, algorithm); auth = new AuthenticationImpl(ident, provider, authUserName, hash, salt, algorithm.name()); } else { auth = new AuthenticationImpl(ident, provider, authUserName, credentials); } dbInstance.getCurrentEntityManager().persist(auth); log.audit("Create " + provider + " authentication (login=" + ident.getName() + ",authusername=" + authUserName + ")"); } return auth; } }); } /** * @see org.olat.basesecurity.Manager#findAuthentication(org.olat.core.id.Identity, java.lang.String) */ @Override public Authentication findAuthentication(Identity identity, String provider) { if (identity==null) { throw new IllegalArgumentException("identity must not be null"); } StringBuilder sb = new StringBuilder(); sb.append("select auth from ").append(AuthenticationImpl.class.getName()) .append(" as auth where auth.identity.key=:identityKey and auth.provider=:provider"); List<Authentication> results = dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), Authentication.class) .setParameter("identityKey", identity.getKey()) .setParameter("provider", provider) .getResultList(); if (results == null || results.size() == 0) return null; if (results.size() > 1) throw new AssertException("Found more than one Authentication for a given subject and a given provider."); return results.get(0); } /** * @see org.olat.basesecurity.Manager#findAuthentication(org.olat.core.id.Identity, java.lang.String) */ @Override public List<Authentication> findAuthenticationByToken(String provider, String securityToken) { if (provider==null || securityToken==null) { throw new IllegalArgumentException("provider and token must not be null"); } StringBuilder sb = new StringBuilder(); sb.append("select auth from ").append(AuthenticationImpl.class.getName()) .append(" as auth where auth.credential=:credential and auth.provider=:provider"); List<Authentication> results = dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), Authentication.class) .setParameter("credential", securityToken) .setParameter("provider", provider) .getResultList(); return results; } @Override public List<Authentication> findOldAuthentication(String provider, Date creationDate) { if (provider == null || creationDate == null) { throw new IllegalArgumentException("provider and token must not be null"); } StringBuilder sb = new StringBuilder(); sb.append("select auth from ").append(AuthenticationImpl.class.getName()) .append(" as auth where auth.provider=:provider and auth.creationDate<:creationDate"); List<Authentication> results = dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), Authentication.class) .setParameter("creationDate", creationDate, TemporalType.TIMESTAMP) .setParameter("provider", provider) .getResultList(); return results; } @Override public Authentication updateAuthentication(Authentication authentication) { return dbInstance.getCurrentEntityManager().merge(authentication); } @Override public boolean checkCredentials(Authentication authentication, String password) { Algorithm algorithm = Algorithm.find(authentication.getAlgorithm()); String hash = Encoder.encrypt(password, authentication.getSalt(), algorithm); return authentication.getCredential() != null && authentication.getCredential().equals(hash); } @Override public Authentication updateCredentials(Authentication authentication, String password, Algorithm algorithm) { if(authentication.getAlgorithm() != null && authentication.getAlgorithm().equals(algorithm.name())) { //check if update is needed String currentSalt = authentication.getSalt(); String newCredentials = Encoder.encrypt(password, currentSalt, algorithm); if(newCredentials.equals(authentication.getCredential())) { //same credentials return authentication; } } String salt = algorithm.isSalted() ? Encoder.getSalt() : null; String newCredentials = Encoder.encrypt(password, salt, algorithm); authentication.setSalt(salt); authentication.setCredential(newCredentials); authentication.setAlgorithm(algorithm.name()); return updateAuthentication(authentication); } /** * @see org.olat.basesecurity.Manager#deleteAuthentication(org.olat.basesecurity.Authentication) */ @Override public void deleteAuthentication(Authentication auth) { if(auth == null || auth.getKey() == null) return;//nothing to do try { StringBuilder sb = new StringBuilder(); sb.append("select auth from ").append(AuthenticationImpl.class.getName()).append(" as auth") .append(" where auth.key=:authKey"); AuthenticationImpl authRef = dbInstance.getCurrentEntityManager().find(AuthenticationImpl.class, auth.getKey()); if(authRef != null) { dbInstance.getCurrentEntityManager().remove(authRef); } } catch (EntityNotFoundException e) { log.error("", e); } } /** * @see org.olat.basesecurity.Manager#findAuthenticationByAuthusername(java.lang.String, java.lang.String) */ @Override public Authentication findAuthenticationByAuthusername(String authusername, String provider) { StringBuilder sb = new StringBuilder(); sb.append("select auth from ").append(AuthenticationImpl.class.getName()).append(" as auth") .append(" inner join fetch auth.identity ident") .append(" where auth.provider=:provider and auth.authusername=:authusername"); List<Authentication> results = dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), Authentication.class) .setParameter("provider", provider) .setParameter("authusername", authusername) .getResultList(); if (results.size() == 0) return null; if (results.size() != 1) { throw new AssertException("more than one entry for the a given authusername and provider, should never happen (even db has a unique constraint on those columns combined) "); } return results.get(0); } /** * @see org.olat.basesecurity.Manager#getVisibleIdentitiesByPowerSearch(java.lang.String, java.util.Map, boolean, org.olat.basesecurity.SecurityGroup[], org.olat.basesecurity.PermissionOnResourceable[], java.lang.String[], java.util.Date, java.util.Date) */ @Override public List<Identity> getVisibleIdentitiesByPowerSearch(String login, Map<String, String> userproperties, boolean userPropertiesAsIntersectionSearch, SecurityGroup[] groups, PermissionOnResourceable[] permissionOnResources, String[] authProviders, Date createdAfter, Date createdBefore) { return getIdentitiesByPowerSearch(new SearchIdentityParams(login, userproperties, userPropertiesAsIntersectionSearch, groups, permissionOnResources, authProviders, createdAfter, createdBefore, null, null, Identity.STATUS_VISIBLE_LIMIT), 0, -1); } @Override public List<Identity> getVisibleIdentitiesByPowerSearch(String login, Map<String, String> userProperties, boolean userPropertiesAsIntersectionSearch, SecurityGroup[] groups, PermissionOnResourceable[] permissionOnResources, String[] authProviders, Date createdAfter, Date createdBefore, int firstResult, int maxResults) { return getIdentitiesByPowerSearch(new SearchIdentityParams(login, userProperties, userPropertiesAsIntersectionSearch, groups, permissionOnResources, authProviders, createdAfter, createdBefore, null, null, Identity.STATUS_VISIBLE_LIMIT), firstResult, maxResults); } @Override public long countIdentitiesByPowerSearch(String login, Map<String, String> userproperties, boolean userPropertiesAsIntersectionSearch, SecurityGroup[] groups, PermissionOnResourceable[] permissionOnResources, String[] authProviders, Date createdAfter, Date createdBefore, Date userLoginAfter, Date userLoginBefore, Integer status) { DBQuery dbq = createIdentitiesByPowerQuery(new SearchIdentityParams(login, userproperties, userPropertiesAsIntersectionSearch, groups, permissionOnResources, authProviders, createdAfter, createdBefore, userLoginAfter, userLoginBefore, status), true); Number count = (Number)dbq.uniqueResult(); return count.longValue(); } /** * @see org.olat.basesecurity.Manager#getIdentitiesByPowerSearch(java.lang.String, java.util.Map, boolean, org.olat.basesecurity.SecurityGroup[], org.olat.basesecurity.PermissionOnResourceable[], java.lang.String[], java.util.Date, java.util.Date, java.lang.Integer) */ @Override public List<Identity> getIdentitiesByPowerSearch(String login, Map<String, String> userproperties, boolean userPropertiesAsIntersectionSearch, SecurityGroup[] groups, PermissionOnResourceable[] permissionOnResources, String[] authProviders, Date createdAfter, Date createdBefore, Date userLoginAfter, Date userLoginBefore, Integer status) { DBQuery dbq = createIdentitiesByPowerQuery(new SearchIdentityParams(login, userproperties, userPropertiesAsIntersectionSearch, groups, permissionOnResources, authProviders, createdAfter, createdBefore, userLoginAfter, userLoginBefore, status), false); return dbq.list(); } @Override public int countIdentitiesByPowerSearch(SearchIdentityParams params) { DBQuery dbq = createIdentitiesByPowerQuery(params, true); Number count = (Number)dbq.uniqueResult(); return count.intValue(); } @Override public List<Identity> getIdentitiesByPowerSearch(SearchIdentityParams params, int firstResult, int maxResults) { DBQuery dbq = createIdentitiesByPowerQuery(params, false); if(firstResult >= 0) { dbq.setFirstResult(firstResult); } if(maxResults > 0) { dbq.setMaxResults(maxResults); } @SuppressWarnings("unchecked") List<Identity> identities = dbq.list(); return identities; } private DBQuery createIdentitiesByPowerQuery(SearchIdentityParams params, boolean count) { boolean hasGroups = (params.getGroups() != null && params.getGroups().length > 0); boolean hasPermissionOnResources = (params.getPermissionOnResources() != null && params.getPermissionOnResources().length > 0); boolean hasAuthProviders = (params.getAuthProviders() != null && params.getAuthProviders().length > 0); // select identity and inner join with user to optimize query StringBuilder sb = new StringBuilder(5000); if (hasAuthProviders) { // I know, it looks wrong but I need to do the join reversed since it is not possible to // do this query with a left join that starts with the identity using hibernate HQL. A left // or right join is necessary since it is totally ok to have null values as authentication // providers (e.g. when searching for users that do not have any authentication providers at all!). // It took my quite a while to make this work, so think twice before you change anything here! if(count) { sb.append("select count(distinct ident.key) from org.olat.basesecurity.AuthenticationImpl as auth ") .append(" right join auth.identity as ident") .append(" inner join ident.user as user "); } else { sb.append("select distinct ident from org.olat.basesecurity.AuthenticationImpl as auth ") .append(" right join auth.identity as ident") .append(" inner join fetch ident.user as user "); } } else { if(count) { sb.append("select count(distinct ident.key) from org.olat.core.id.Identity as ident ") .append(" inner join ident.user as user "); } else { sb.append("select distinct ident from org.olat.core.id.Identity as ident ") .append(" inner join fetch ident.user as user "); } } // In any case join with the user. Don't join-fetch user, this breaks the query // because of the user fields (don't know exactly why this behaves like // this) if (hasGroups) { // join over security group memberships sb.append(" ,org.olat.basesecurity.SecurityGroupMembershipImpl as sgmsi "); } if (hasPermissionOnResources) { // join over policies sb.append(" ,org.olat.basesecurity.SecurityGroupMembershipImpl as policyGroupMembership "); sb.append(" ,org.olat.basesecurity.PolicyImpl as policy "); sb.append(" ,org.olat.resource.OLATResourceImpl as resource "); } String login = params.getLogin(); Map<String,String> userproperties = params.getUserProperties(); Date createdAfter = params.getCreatedAfter(); Date createdBefore = params.getCreatedBefore(); Integer status = params.getStatus(); Collection<Long> identityKeys = params.getIdentityKeys(); Boolean managed = params.getManaged(); // complex where clause only when values are available if (login != null || (userproperties != null && !userproperties.isEmpty()) || (identityKeys != null && !identityKeys.isEmpty()) || createdAfter != null || createdBefore != null || hasAuthProviders || hasGroups || hasPermissionOnResources || status != null || managed != null) { sb.append(" where "); boolean needsAnd = false; boolean needsUserPropertiesJoin = false; // treat login and userProperties as one element in this query if (login != null && (userproperties != null && !userproperties.isEmpty())) { sb.append(" ( "); } // append query for login if (login != null) { login = makeFuzzyQueryString(login); if (login.contains("_") && dbVendor.equals("oracle")) { //oracle needs special ESCAPE sequence to search for escaped strings sb.append(" lower(ident.name) like :login ESCAPE '\\'"); } else if (dbVendor.equals("mysql")) { sb.append(" ident.name like :login"); } else { sb.append(" lower(ident.name) like :login"); } // if user fields follow a join element is needed needsUserPropertiesJoin = true; // at least one user field used, after this and is required needsAnd = true; } // append queries for user fields if (userproperties != null && !userproperties.isEmpty()) { Map<String, String> emailProperties = new HashMap<String, String>(); Map<String, String> otherProperties = new HashMap<String, String>(); // split the user fields into two groups for (String key : userproperties.keySet()) { if (key.toLowerCase().contains("email")) { emailProperties.put(key, userproperties.get(key)); } else { otherProperties.put(key, userproperties.get(key)); } } // handle email fields special: search in all email fields if (!emailProperties.isEmpty()) { needsUserPropertiesJoin = checkIntersectionInUserProperties(sb, needsUserPropertiesJoin, params.isUserPropertiesAsIntersectionSearch()); boolean moreThanOne = emailProperties.size() > 1; if (moreThanOne) sb.append("("); boolean needsOr = false; for (String key : emailProperties.keySet()) { if (needsOr) sb.append(" or "); sb.append(" exists (select prop").append(key).append(".value from userproperty prop").append(key).append(" where ") .append(" prop").append(key).append(".propertyId.userId=user.key and prop").append(key).append(".propertyId.name ='").append(key).append("'") .append(" and "); if(dbVendor.equals("mysql")) { sb.append(" prop").append(key).append(".value like :").append(key).append("_value "); } else { sb.append(" lower(prop").append(key).append(".value) like :").append(key).append("_value "); } if(dbVendor.equals("oracle")) { sb.append(" escape '\\'"); } sb.append(")"); needsOr = true; } if (moreThanOne) sb.append(")"); // cleanup emailProperties.clear(); } // add other fields for (String key : otherProperties.keySet()) { needsUserPropertiesJoin = checkIntersectionInUserProperties(sb, needsUserPropertiesJoin, params.isUserPropertiesAsIntersectionSearch()); sb.append(" exists (select prop").append(key).append(".value from userproperty prop").append(key).append(" where ") .append(" prop").append(key).append(".propertyId.userId=user.key and prop").append(key).append(".propertyId.name ='").append(key).append("'") .append(" and "); if(dbVendor.equals("mysql")) { sb.append(" prop").append(key).append(".value like :").append(key).append("_value "); } else { sb.append(" lower(prop").append(key).append(".value) like :").append(key).append("_value "); } if(dbVendor.equals("oracle")) { sb.append(" escape '\\'"); } sb.append(")"); needsAnd = true; } // cleanup otherProperties.clear(); // at least one user field used, after this and is required needsAnd = true; } // end of user fields and login part if (login != null && (userproperties != null && !userproperties.isEmpty())) { sb.append(" ) "); } // now continue with the other elements. They are joined with an AND connection // append query for identity primary keys if(identityKeys != null && !identityKeys.isEmpty()) { needsAnd = checkAnd(sb, needsAnd); sb.append("ident.key in (:identityKeys)"); } if(managed != null) { needsAnd = checkAnd(sb, needsAnd); if(managed.booleanValue()) { sb.append("ident.externalId is not null"); } else { sb.append("ident.externalId is null"); } } // append query for named security groups if (hasGroups) { SecurityGroup[] groups = params.getGroups(); needsAnd = checkAnd(sb, needsAnd); sb.append(" ("); for (int i = 0; i < groups.length; i++) { sb.append(" sgmsi.securityGroup=:group_").append(i); if (i < (groups.length - 1)) sb.append(" or "); } sb.append(") "); sb.append(" and sgmsi.identity=ident "); } // append query for policies if (hasPermissionOnResources) { needsAnd = checkAnd(sb, needsAnd); sb.append(" ("); PermissionOnResourceable[] permissionOnResources = params.getPermissionOnResources(); for (int i = 0; i < permissionOnResources.length; i++) { sb.append(" ("); sb.append(" policy.permission=:permission_").append(i); sb.append(" and policy.olatResource = resource "); sb.append(" and resource.resId = :resourceId_").append(i); sb.append(" and resource.resName = :resourceName_").append(i); sb.append(" ) "); if (i < (permissionOnResources.length - 1)) sb.append(" or "); } sb.append(") "); sb.append(" and policy.securityGroup=policyGroupMembership.securityGroup "); sb.append(" and policyGroupMembership.identity=ident "); } // append query for authentication providers if (hasAuthProviders) { needsAnd = checkAnd(sb, needsAnd); sb.append(" ("); String[] authProviders = params.getAuthProviders(); for (int i = 0; i < authProviders.length; i++) { // special case for null auth provider if (authProviders[i] == null) { sb.append(" auth is null "); } else { sb.append(" auth.provider=:authProvider_").append(i); } if (i < (authProviders.length - 1)) sb.append(" or "); } sb.append(") "); } // append query for creation date restrictions if (createdAfter != null) { needsAnd = checkAnd(sb, needsAnd); sb.append(" ident.creationDate >= :createdAfter "); } if (createdBefore != null) { needsAnd = checkAnd(sb, needsAnd); sb.append(" ident.creationDate <= :createdBefore "); } if(params.getUserLoginAfter() != null){ needsAnd = checkAnd(sb, needsAnd); sb.append(" ident.lastLogin >= :lastloginAfter "); } if(params.getUserLoginBefore() != null){ needsAnd = checkAnd(sb, needsAnd); sb.append(" ident.lastLogin <= :lastloginBefore "); } if (status != null) { if (status.equals(Identity.STATUS_VISIBLE_LIMIT)) { // search for all status smaller than visible limit needsAnd = checkAnd(sb, needsAnd); sb.append(" ident.status < :status "); } else { // search for certain status needsAnd = checkAnd(sb, needsAnd); sb.append(" ident.status = :status "); } } } // create query object now from string String query = sb.toString(); DB db = DBFactory.getInstance(); DBQuery dbq = db.createQuery(query); // add user attributes if (login != null) { dbq.setString("login", login.toLowerCase()); } if(identityKeys != null && !identityKeys.isEmpty()) { dbq.setParameterList("identityKeys", identityKeys); } // add user properties attributes if (userproperties != null && !userproperties.isEmpty()) { for (String key : userproperties.keySet()) { String value = userproperties.get(key); value = makeFuzzyQueryString(value); dbq.setString(key + "_value", value.toLowerCase()); } } // add named security group names if (hasGroups) { SecurityGroup[] groups = params.getGroups(); for (int i = 0; i < groups.length; i++) { SecurityGroupImpl group = (SecurityGroupImpl) groups[i]; // need to work with impls dbq.setEntity("group_" + i, group); } } // add policies if (hasPermissionOnResources) { PermissionOnResourceable[] permissionOnResources = params.getPermissionOnResources(); for (int i = 0; i < permissionOnResources.length; i++) { PermissionOnResourceable permissionOnResource = permissionOnResources[i]; dbq.setString("permission_" + i, permissionOnResource.getPermission()); Long id = permissionOnResource.getOlatResourceable().getResourceableId(); dbq.setLong("resourceId_" + i, (id == null ? 0 : id.longValue())); dbq.setString("resourceName_" + i, permissionOnResource.getOlatResourceable().getResourceableTypeName()); } } // add authentication providers if (hasAuthProviders) { String[] authProviders = params.getAuthProviders(); for (int i = 0; i < authProviders.length; i++) { String authProvider = authProviders[i]; if (authProvider != null) { dbq.setString("authProvider_" + i, authProvider); } // ignore null auth provider, already set to null in query } } // add date restrictions if (createdAfter != null) { dbq.setDate("createdAfter", createdAfter); } if (createdBefore != null) { dbq.setDate("createdBefore", createdBefore); } if(params.getUserLoginAfter() != null){ dbq.setDate("lastloginAfter", params.getUserLoginAfter()); } if(params.getUserLoginBefore() != null){ dbq.setDate("lastloginBefore", params.getUserLoginBefore()); } if (status != null) { dbq.setInteger("status", status); } // execute query return dbq; } /** * * @param dbVendor */ public void setDbVendor(String dbVendor) { this.dbVendor = dbVendor; } /** * @see org.olat.basesecurity.Manager#isIdentityVisible(java.lang.String) */ public boolean isIdentityVisible(String identityName) { if (identityName == null) throw new AssertException("findIdentitybyName: name was null"); String queryString = "select count(ident) from org.olat.basesecurity.IdentityImpl as ident where ident.name = :identityName and ident.status < :status"; DBQuery dbq = DBFactory.getInstance().createQuery(queryString); dbq.setString("identityName", identityName); dbq.setInteger("status", Identity.STATUS_VISIBLE_LIMIT); List res = dbq.list(); Long cntL = (Long) res.get(0); return (cntL.longValue() > 0); } @Override public boolean isIdentityVisible(Identity identity) { if(identity == null) return false; Integer status = identity.getStatus(); return (status != null && status.intValue() < Identity.STATUS_VISIBLE_LIMIT); } private boolean checkAnd(StringBuilder sb, boolean needsAnd) { if (needsAnd) sb.append(" and "); return true; } private boolean checkIntersectionInUserProperties(StringBuilder sb, boolean needsJoin, boolean userPropertiesAsIntersectionSearch) { if (needsJoin) { if (userPropertiesAsIntersectionSearch) { sb.append(" and "); } else { sb.append(" or "); } } return true; } /** * Helper method that replaces * with % and appends and * prepends % to the string to make fuzzy SQL match when using like * @param email * @return fuzzized string */ private String makeFuzzyQueryString(String string) { // By default only fuzzyfy at the end. Usually it makes no sense to do a // fuzzy search with % at the beginning, but it makes the query very very // slow since it can not use any index and must perform a fulltext search. // User can always use * to make it a really fuzzy search query // fxdiff FXOLAT-252: use "" to disable this feature and use exact match if (string.length() > 1 && string.startsWith("\"") && string.endsWith("\"")) { string = string.substring(1, string.length()-1); } else { string = string + "%"; string = string.replace('*', '%'); } // with 'LIKE' the character '_' is a wildcard which matches exactly one character. // To test for literal instances of '_', we have to escape it. string = string.replace("_", "\\_"); return string; } /** * @see org.olat.basesecurity.Manager#saveIdentityStatus(org.olat.core.id.Identity) */ @Override public Identity saveIdentityStatus(Identity identity, Integer status) { Identity reloadedIdentity = loadForUpdate(identity); reloadedIdentity.setStatus(status); reloadedIdentity = dbInstance.getCurrentEntityManager().merge(reloadedIdentity); dbInstance.commit(); return reloadedIdentity; } @Override public Identity setIdentityLastLogin(Identity identity) { Identity reloadedIdentity = loadForUpdate(identity); reloadedIdentity.setLastLogin(new Date()); reloadedIdentity = dbInstance.getCurrentEntityManager().merge(reloadedIdentity); dbInstance.commit(); return reloadedIdentity; } @Override public Identity saveIdentityName(Identity identity, String newName) { Identity reloadedIdentity = loadForUpdate(identity); reloadedIdentity.setName(newName); reloadedIdentity = dbInstance.getCurrentEntityManager().merge(reloadedIdentity); dbInstance.commit(); return reloadedIdentity; } @Override public Identity setExternalId(Identity identity, String externalId) { IdentityImpl reloadedIdentity = loadForUpdate(identity); reloadedIdentity.setExternalId(externalId); reloadedIdentity = dbInstance.getCurrentEntityManager().merge(reloadedIdentity); dbInstance.commit(); return reloadedIdentity; } /** * Don't forget to commit/roolback the transaction as soon as possible * @param identityKey * @return */ private IdentityImpl loadForUpdate(Identity identity) { StringBuilder sb = new StringBuilder(); sb.append("select id from ").append(IdentityImpl.class.getName()).append(" as id") .append(" inner join fetch id.user user ") .append(" where id.key=:identityKey"); dbInstance.getCurrentEntityManager().detach(identity); List<IdentityImpl> identities = dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), IdentityImpl.class) .setParameter("identityKey", identity.getKey()) .setLockMode(LockModeType.PESSIMISTIC_WRITE) .getResultList(); if(identities.isEmpty()) { return null; } return identities.get(0); } @Override public List<SecurityGroup> getSecurityGroupsForIdentity(Identity identity) { StringBuilder sb = new StringBuilder(); sb.append("select sgi from ").append(SecurityGroupImpl.class.getName()).append(" as sgi, ") .append(SecurityGroupMembershipImpl.class.getName()).append(" as sgmsi ") .append(" where sgmsi.securityGroup=sgi and sgmsi.identity.key=:identityKey"); List<SecurityGroup> secGroups = DBFactory.getInstance().getCurrentEntityManager() .createQuery(sb.toString(), SecurityGroup.class) .setParameter("identityKey", identity.getKey()) .getResultList(); return secGroups; } /** * @see org.olat.basesecurity.Manager#getAndUpdateAnonymousUserForLanguage(java.util.Locale) */ public Identity getAndUpdateAnonymousUserForLanguage(Locale locale) { Translator trans = Util.createPackageTranslator(UserManager.class, locale); String guestUsername = GUEST_USERNAME_PREFIX + locale.toString(); Identity guestIdentity = findIdentityByName(guestUsername); if (guestIdentity == null) { // Create it lazy on demand User guestUser = UserManager.getInstance().createUser(trans.translate("user.guest"), null, null); guestUser.getPreferences().setLanguage(locale.toString()); guestIdentity = createAndPersistIdentityAndUser(guestUsername, null, guestUser, null, null, null); SecurityGroup anonymousGroup = findSecurityGroupByName(Constants.GROUP_ANONYMOUS); addIdentityToSecurityGroup(guestIdentity, anonymousGroup); } else if (!guestIdentity.getUser().getProperty(UserConstants.FIRSTNAME, locale).equals(trans.translate("user.guest"))) { //Check if guest name has been updated in the i18n tool guestIdentity.getUser().setProperty(UserConstants.FIRSTNAME, trans.translate("user.guest")); guestIdentity = dbInstance.getCurrentEntityManager().merge(guestIdentity); } return guestIdentity; } }
[ "public", "class", "BaseSecurityManager", "implements", "BaseSecurity", "{", "private", "static", "final", "OLog", "log", "=", "Tracing", ".", "createLoggerFor", "(", "BaseSecurityManager", ".", "class", ")", ";", "private", "DB", "dbInstance", ";", "private", "LoginModule", "loginModule", ";", "private", "OLATResourceManager", "orm", ";", "private", "InvitationDAO", "invitationDao", ";", "private", "String", "dbVendor", "=", "\"", "\"", ";", "private", "static", "BaseSecurityManager", "INSTANCE", ";", "private", "static", "String", "GUEST_USERNAME_PREFIX", "=", "\"", "guest_", "\"", ";", "public", "static", "final", "OLATResourceable", "IDENTITY_EVENT_CHANNEL", "=", "OresHelper", ".", "lookupType", "(", "Identity", ".", "class", ")", ";", "/**\n\t * [used by spring]\n\t */", "private", "BaseSecurityManager", "(", ")", "{", "INSTANCE", "=", "this", ";", "}", "/**\n\t * \n\t * @return the manager\n\t */", "public", "static", "BaseSecurity", "getInstance", "(", ")", "{", "return", "INSTANCE", ";", "}", "public", "void", "setLoginModule", "(", "LoginModule", "loginModule", ")", "{", "this", ".", "loginModule", "=", "loginModule", ";", "}", "/**\n\t * [used by spring]\n\t * @param orm\n\t */", "public", "void", "setResourceManager", "(", "OLATResourceManager", "orm", ")", "{", "this", ".", "orm", "=", "orm", ";", "}", "/**\n\t * [used by Spring]\n\t * @param dbInstance\n\t */", "public", "void", "setDbInstance", "(", "DB", "dbInstance", ")", "{", "this", ".", "dbInstance", "=", "dbInstance", ";", "}", "/**\n\t * [used by Spring]\n\t * @param invitationDao\n\t */", "public", "void", "setInvitationDao", "(", "InvitationDAO", "invitationDao", ")", "{", "this", ".", "invitationDao", "=", "invitationDao", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#init()\n\t */", "public", "void", "init", "(", ")", "{", "initSysGroupAdmin", "(", ")", ";", "dbInstance", ".", "commit", "(", ")", ";", "initSysGroupAuthors", "(", ")", ";", "dbInstance", ".", "commit", "(", ")", ";", "initSysGroupGroupmanagers", "(", ")", ";", "dbInstance", ".", "commit", "(", ")", ";", "initSysGroupPoolsmanagers", "(", ")", ";", "dbInstance", ".", "commit", "(", ")", ";", "initSysGroupUsermanagers", "(", ")", ";", "dbInstance", ".", "commit", "(", ")", ";", "initSysGroupUsers", "(", ")", ";", "dbInstance", ".", "commit", "(", ")", ";", "initSysGroupAnonymous", "(", ")", ";", "dbInstance", ".", "commit", "(", ")", ";", "initSysGroupInstitutionalResourceManager", "(", ")", ";", "dbInstance", ".", "commitAndCloseSession", "(", ")", ";", "}", "/**\n\t * OLAT system administrators, root, good, whatever you name it...\n\t */", "private", "void", "initSysGroupAdmin", "(", ")", "{", "SecurityGroup", "adminGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_ADMIN", ")", ";", "if", "(", "adminGroup", "==", "null", ")", "adminGroup", "=", "createAndPersistNamedSecurityGroup", "(", "Constants", ".", "GROUP_ADMIN", ")", ";", "createAndPersistPolicyIfNotExists", "(", "adminGroup", ",", "Constants", ".", "PERMISSION_HASROLE", ",", "Constants", ".", "ORESOURCE_ADMIN", ")", ";", "createAndPersistPolicyIfNotExists", "(", "adminGroup", ",", "Constants", ".", "PERMISSION_HASROLE", ",", "Constants", ".", "ORESOURCE_AUTHOR", ")", ";", "createAndPersistPolicyIfNotExists", "(", "adminGroup", ",", "Constants", ".", "PERMISSION_HASROLE", ",", "Constants", ".", "ORESOURCE_GROUPMANAGER", ")", ";", "createAndPersistPolicyIfNotExists", "(", "adminGroup", ",", "Constants", ".", "PERMISSION_HASROLE", ",", "Constants", ".", "ORESOURCE_USERMANAGER", ")", ";", "createAndPersistPolicyIfNotExists", "(", "adminGroup", ",", "Constants", ".", "PERMISSION_HASROLE", ",", "Constants", ".", "ORESOURCE_USERS", ")", ";", "createAndPersistPolicyIfNotExists", "(", "adminGroup", ",", "Constants", ".", "PERMISSION_ACCESS", ",", "Constants", ".", "ORESOURCE_SECURITYGROUPS", ")", ";", "createAndPersistPolicyIfNotExists", "(", "adminGroup", ",", "Constants", ".", "PERMISSION_ADMIN", ",", "Constants", ".", "ORESOURCE_COURSES", ")", ";", "createAndPersistPolicyIfNotExists", "(", "adminGroup", ",", "Constants", ".", "PERMISSION_ADMIN", ",", "Constants", ".", "ORESOURCE_POOLS", ")", ";", "createAndPersistPolicyIfNotExists", "(", "adminGroup", ",", "Constants", ".", "PERMISSION_ACCESS", ",", "OresHelper", ".", "lookupType", "(", "SysinfoController", ".", "class", ")", ")", ";", "createAndPersistPolicyIfNotExists", "(", "adminGroup", ",", "Constants", ".", "PERMISSION_ACCESS", ",", "OresHelper", ".", "lookupType", "(", "UserAdminController", ".", "class", ")", ")", ";", "createAndPersistPolicyIfNotExists", "(", "adminGroup", ",", "Constants", ".", "PERMISSION_ACCESS", ",", "OresHelper", ".", "lookupType", "(", "UserChangePasswordController", ".", "class", ")", ")", ";", "createAndPersistPolicyIfNotExists", "(", "adminGroup", ",", "Constants", ".", "PERMISSION_ACCESS", ",", "OresHelper", ".", "lookupType", "(", "UserCreateController", ".", "class", ")", ")", ";", "createAndPersistPolicyIfNotExists", "(", "adminGroup", ",", "Constants", ".", "PERMISSION_ACCESS", ",", "OresHelper", ".", "lookupType", "(", "GenericQuotaEditController", ".", "class", ")", ")", ";", "}", "/**\n\t * Every active user that is an active user is in the user group. exceptions: logonDenied and anonymous users\n\t */", "private", "void", "initSysGroupUsers", "(", ")", "{", "SecurityGroup", "olatuserGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_OLATUSERS", ")", ";", "if", "(", "olatuserGroup", "==", "null", ")", "olatuserGroup", "=", "createAndPersistNamedSecurityGroup", "(", "Constants", ".", "GROUP_OLATUSERS", ")", ";", "createAndPersistPolicyIfNotExists", "(", "olatuserGroup", ",", "Constants", ".", "PERMISSION_HASROLE", ",", "Constants", ".", "ORESOURCE_USERS", ")", ";", "createAndPersistPolicyIfNotExists", "(", "olatuserGroup", ",", "Constants", ".", "PERMISSION_ACCESS", ",", "OresHelper", ".", "lookupType", "(", "ChangePasswordController", ".", "class", ")", ")", ";", "}", "/**\n\t * Users with access to group context management (groupmanagement that can be used in multiple courses\n\t */", "private", "void", "initSysGroupGroupmanagers", "(", ")", "{", "SecurityGroup", "olatGroupmanagerGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_GROUPMANAGERS", ")", ";", "if", "(", "olatGroupmanagerGroup", "==", "null", ")", "olatGroupmanagerGroup", "=", "createAndPersistNamedSecurityGroup", "(", "Constants", ".", "GROUP_GROUPMANAGERS", ")", ";", "createAndPersistPolicyIfNotExists", "(", "olatGroupmanagerGroup", ",", "Constants", ".", "PERMISSION_HASROLE", ",", "Constants", ".", "ORESOURCE_GROUPMANAGER", ")", ";", "}", "/**\n\t * Users with access to group context management (groupmanagement that can be used in multiple courses\n\t */", "private", "void", "initSysGroupPoolsmanagers", "(", ")", "{", "SecurityGroup", "secGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_POOL_MANAGER", ")", ";", "if", "(", "secGroup", "==", "null", ")", "secGroup", "=", "createAndPersistNamedSecurityGroup", "(", "Constants", ".", "GROUP_POOL_MANAGER", ")", ";", "createAndPersistPolicyIfNotExists", "(", "secGroup", ",", "Constants", ".", "PERMISSION_HASROLE", ",", "Constants", ".", "ORESOURCE_POOLS", ")", ";", "}", "/**\n\t * Users with access to user management\n\t */", "private", "void", "initSysGroupUsermanagers", "(", ")", "{", "SecurityGroup", "olatUsermanagerGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_USERMANAGERS", ")", ";", "if", "(", "olatUsermanagerGroup", "==", "null", ")", "olatUsermanagerGroup", "=", "createAndPersistNamedSecurityGroup", "(", "Constants", ".", "GROUP_USERMANAGERS", ")", ";", "createAndPersistPolicyIfNotExists", "(", "olatUsermanagerGroup", ",", "Constants", ".", "PERMISSION_HASROLE", ",", "Constants", ".", "ORESOURCE_USERMANAGER", ")", ";", "createAndPersistPolicyIfNotExists", "(", "olatUsermanagerGroup", ",", "Constants", ".", "PERMISSION_ACCESS", ",", "OresHelper", ".", "lookupType", "(", "UserAdminController", ".", "class", ")", ")", ";", "createAndPersistPolicyIfNotExists", "(", "olatUsermanagerGroup", ",", "Constants", ".", "PERMISSION_ACCESS", ",", "OresHelper", ".", "lookupType", "(", "UserChangePasswordController", ".", "class", ")", ")", ";", "createAndPersistPolicyIfNotExists", "(", "olatUsermanagerGroup", ",", "Constants", ".", "PERMISSION_ACCESS", ",", "OresHelper", ".", "lookupType", "(", "UserCreateController", ".", "class", ")", ")", ";", "createAndPersistPolicyIfNotExists", "(", "olatUsermanagerGroup", ",", "Constants", ".", "PERMISSION_ACCESS", ",", "OresHelper", ".", "lookupType", "(", "GenericQuotaEditController", ".", "class", ")", ")", ";", "}", "/**\n\t * Users with access to the authoring parts of the learning ressources repository\n\t */", "private", "void", "initSysGroupAuthors", "(", ")", "{", "SecurityGroup", "olatauthorGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_AUTHORS", ")", ";", "if", "(", "olatauthorGroup", "==", "null", ")", "olatauthorGroup", "=", "createAndPersistNamedSecurityGroup", "(", "Constants", ".", "GROUP_AUTHORS", ")", ";", "createAndPersistPolicyIfNotExists", "(", "olatauthorGroup", ",", "Constants", ".", "PERMISSION_HASROLE", ",", "Constants", ".", "ORESOURCE_AUTHOR", ")", ";", "}", "/**\n\t * Users with access to the authoring parts of the learning ressources repository (all resources in his university)\n\t */", "private", "void", "initSysGroupInstitutionalResourceManager", "(", ")", "{", "SecurityGroup", "institutionalResourceManagerGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_INST_ORES_MANAGER", ")", ";", "if", "(", "institutionalResourceManagerGroup", "==", "null", ")", "institutionalResourceManagerGroup", "=", "createAndPersistNamedSecurityGroup", "(", "Constants", ".", "GROUP_INST_ORES_MANAGER", ")", ";", "createAndPersistPolicyIfNotExists", "(", "institutionalResourceManagerGroup", ",", "Constants", ".", "PERMISSION_HASROLE", ",", "Constants", ".", "ORESOURCE_INSTORESMANAGER", ")", ";", "createAndPersistPolicyIfNotExists", "(", "institutionalResourceManagerGroup", ",", "Constants", ".", "PERMISSION_ACCESS", ",", "OresHelper", ".", "lookupType", "(", "GenericQuotaEditController", ".", "class", ")", ")", ";", "}", "/**\n\t * Unknown users with guest only rights\n\t */", "private", "void", "initSysGroupAnonymous", "(", ")", "{", "SecurityGroup", "guestGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_ANONYMOUS", ")", ";", "if", "(", "guestGroup", "==", "null", ")", "guestGroup", "=", "createAndPersistNamedSecurityGroup", "(", "Constants", ".", "GROUP_ANONYMOUS", ")", ";", "createAndPersistPolicyIfNotExists", "(", "guestGroup", ",", "Constants", ".", "PERMISSION_HASROLE", ",", "Constants", ".", "ORESOURCE_GUESTONLY", ")", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#getPoliciesOfSecurityGroup(org.olat.basesecurity.SecurityGroup)\n\t */", "@", "Override", "public", "List", "<", "Policy", ">", "getPoliciesOfSecurityGroup", "(", "SecurityGroup", "secGroup", ")", "{", "if", "(", "secGroup", "==", "null", ")", "return", "Collections", ".", "emptyList", "(", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select poi from ", "\"", ")", ".", "append", "(", "PolicyImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as poi where poi.securityGroup.key=:secGroupKey", "\"", ")", ";", "List", "<", "Policy", ">", "policies", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Policy", ".", "class", ")", ".", "setParameter", "(", "\"", "secGroupKey", "\"", ",", "secGroup", ".", "getKey", "(", ")", ")", ".", "getResultList", "(", ")", ";", "return", "policies", ";", "}", "/**\n\t * @see org.olat.basesecurity.BaseSecurity#getPoliciesOfResource(org.olat.core.id.OLATResourceable)\n\t */", "@", "Override", "public", "List", "<", "Policy", ">", "getPoliciesOfResource", "(", "OLATResource", "resource", ",", "SecurityGroup", "secGroup", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select poi from ", "\"", ")", ".", "append", "(", "PolicyImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " poi where ", "\"", ")", ".", "append", "(", "\"", " poi.olatResource.key=:resourceKey ", "\"", ")", ";", "if", "(", "secGroup", "!=", "null", ")", "{", "sb", ".", "append", "(", "\"", " and poi.securityGroup.key=:secGroupKey", "\"", ")", ";", "}", "TypedQuery", "<", "Policy", ">", "query", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Policy", ".", "class", ")", ".", "setParameter", "(", "\"", "resourceKey", "\"", ",", "resource", ".", "getKey", "(", ")", ")", ";", "if", "(", "secGroup", "!=", "null", ")", "{", "query", ".", "setParameter", "(", "\"", "secGroupKey", "\"", ",", "secGroup", ".", "getKey", "(", ")", ")", ";", "}", "return", "query", ".", "getResultList", "(", ")", ";", "}", "@", "Override", "public", "boolean", "isIdentityPermittedOnResourceable", "(", "Identity", "identity", ",", "String", "permission", ",", "OLATResourceable", "olatResourceable", ")", "{", "return", "isIdentityPermittedOnResourceable", "(", "identity", ",", "permission", ",", "olatResourceable", ",", "true", ")", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#isIdentityPermittedOnResourceable(org.olat.core.id.Identity, java.lang.String, org.olat.core.id.OLATResourceable boolean)\n\t */", "@", "Override", "public", "boolean", "isIdentityPermittedOnResourceable", "(", "Identity", "identity", ",", "String", "permission", ",", "OLATResourceable", "olatResourceable", ",", "boolean", "checkTypeRight", ")", "{", "if", "(", "identity", "==", "null", "||", "identity", ".", "getKey", "(", ")", "==", "null", ")", "return", "false", ";", "Long", "oresid", "=", "olatResourceable", ".", "getResourceableId", "(", ")", ";", "if", "(", "oresid", "==", "null", ")", "oresid", "=", "new", "Long", "(", "0", ")", ";", "String", "oresName", "=", "olatResourceable", ".", "getResourceableTypeName", "(", ")", ";", "TypedQuery", "<", "Number", ">", "query", ";", "if", "(", "checkTypeRight", ")", "{", "query", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createNamedQuery", "(", "\"", "isIdentityPermittedOnResourceableCheckType", "\"", ",", "Number", ".", "class", ")", ";", "}", "else", "{", "query", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createNamedQuery", "(", "\"", "isIdentityPermittedOnResourceable", "\"", ",", "Number", ".", "class", ")", ";", "}", "Number", "count", "=", "query", ".", "setParameter", "(", "\"", "identitykey", "\"", ",", "identity", ".", "getKey", "(", ")", ")", ".", "setParameter", "(", "\"", "permission", "\"", ",", "permission", ")", ".", "setParameter", "(", "\"", "resid", "\"", ",", "oresid", ")", ".", "setParameter", "(", "\"", "resname", "\"", ",", "oresName", ")", ".", "setHint", "(", "\"", "org.hibernate.cacheable", "\"", ",", "Boolean", ".", "TRUE", ")", ".", "getSingleResult", "(", ")", ";", "return", "count", ".", "longValue", "(", ")", ">", "0", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#getRoles(org.olat.core.id.Identity)\n\t */", "@", "Override", "public", "Roles", "getRoles", "(", "Identity", "identity", ")", "{", "boolean", "isGuestOnly", "=", "false", ";", "boolean", "isInvitee", "=", "false", ";", "List", "<", "String", ">", "rolesStr", "=", "getRolesAsString", "(", "identity", ")", ";", "boolean", "admin", "=", "rolesStr", ".", "contains", "(", "Constants", ".", "GROUP_ADMIN", ")", ";", "boolean", "author", "=", "admin", "||", "rolesStr", ".", "contains", "(", "Constants", ".", "GROUP_AUTHORS", ")", ";", "boolean", "groupManager", "=", "admin", "||", "rolesStr", ".", "contains", "(", "Constants", ".", "GROUP_GROUPMANAGERS", ")", ";", "boolean", "userManager", "=", "admin", "||", "rolesStr", ".", "contains", "(", "Constants", ".", "GROUP_USERMANAGERS", ")", ";", "boolean", "resourceManager", "=", "rolesStr", ".", "contains", "(", "Constants", ".", "GROUP_INST_ORES_MANAGER", ")", ";", "boolean", "poolManager", "=", "admin", "||", "rolesStr", ".", "contains", "(", "Constants", ".", "GROUP_POOL_MANAGER", ")", ";", "if", "(", "!", "rolesStr", ".", "contains", "(", "Constants", ".", "GROUP_OLATUSERS", ")", ")", "{", "isInvitee", "=", "invitationDao", ".", "isInvitee", "(", "identity", ")", ";", "isGuestOnly", "=", "isIdentityPermittedOnResourceable", "(", "identity", ",", "Constants", ".", "PERMISSION_HASROLE", ",", "Constants", ".", "ORESOURCE_GUESTONLY", ")", ";", "}", "return", "new", "Roles", "(", "admin", ",", "userManager", ",", "groupManager", ",", "author", ",", "isGuestOnly", ",", "resourceManager", ",", "poolManager", ",", "isInvitee", ")", ";", "}", "@", "Override", "public", "List", "<", "String", ">", "getRolesAsString", "(", "Identity", "identity", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select ngroup.groupName from ", "\"", ")", ".", "append", "(", "NamedGroupImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as ngroup ", "\"", ")", ".", "append", "(", "\"", " where exists (", "\"", ")", ".", "append", "(", "\"", " select sgmsi from ", "\"", ")", ".", "append", "(", "SecurityGroupMembershipImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as sgmsi where sgmsi.identity.key=:identityKey and sgmsi.securityGroup=ngroup.securityGroup", "\"", ")", ".", "append", "(", "\"", " )", "\"", ")", ";", "return", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "String", ".", "class", ")", ".", "setParameter", "(", "\"", "identityKey", "\"", ",", "identity", ".", "getKey", "(", ")", ")", ".", "getResultList", "(", ")", ";", "}", "@", "Override", "public", "void", "updateRoles", "(", "Identity", "actingIdentity", ",", "Identity", "updatedIdentity", ",", "Roles", "roles", ")", "{", "SecurityGroup", "anonymousGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_ANONYMOUS", ")", ";", "boolean", "hasBeenAnonymous", "=", "isIdentityInSecurityGroup", "(", "updatedIdentity", ",", "anonymousGroup", ")", ";", "updateRolesInSecurityGroup", "(", "actingIdentity", ",", "updatedIdentity", ",", "anonymousGroup", ",", "hasBeenAnonymous", ",", "roles", ".", "isGuestOnly", "(", ")", ",", "Constants", ".", "GROUP_ANONYMOUS", ")", ";", "SecurityGroup", "usersGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_OLATUSERS", ")", ";", "boolean", "hasBeenUser", "=", "isIdentityInSecurityGroup", "(", "updatedIdentity", ",", "usersGroup", ")", ";", "updateRolesInSecurityGroup", "(", "actingIdentity", ",", "updatedIdentity", ",", "usersGroup", ",", "hasBeenUser", ",", "!", "roles", ".", "isGuestOnly", "(", ")", ",", "Constants", ".", "GROUP_OLATUSERS", ")", ";", "SecurityGroup", "groupManagerGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_GROUPMANAGERS", ")", ";", "boolean", "hasBeenGroupManager", "=", "isIdentityInSecurityGroup", "(", "updatedIdentity", ",", "groupManagerGroup", ")", ";", "boolean", "groupManager", "=", "roles", ".", "isGroupManager", "(", ")", "&&", "!", "roles", ".", "isGuestOnly", "(", ")", "&&", "!", "roles", ".", "isInvitee", "(", ")", ";", "updateRolesInSecurityGroup", "(", "actingIdentity", ",", "updatedIdentity", ",", "groupManagerGroup", ",", "hasBeenGroupManager", ",", "groupManager", ",", "Constants", ".", "GROUP_GROUPMANAGERS", ")", ";", "SecurityGroup", "authorGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_AUTHORS", ")", ";", "boolean", "hasBeenAuthor", "=", "isIdentityInSecurityGroup", "(", "updatedIdentity", ",", "authorGroup", ")", ";", "boolean", "isAuthor", "=", "(", "roles", ".", "isAuthor", "(", ")", "||", "roles", ".", "isInstitutionalResourceManager", "(", ")", ")", "&&", "!", "roles", ".", "isGuestOnly", "(", ")", "&&", "!", "roles", ".", "isInvitee", "(", ")", ";", "updateRolesInSecurityGroup", "(", "actingIdentity", ",", "updatedIdentity", ",", "authorGroup", ",", "hasBeenAuthor", ",", "isAuthor", ",", "Constants", ".", "GROUP_AUTHORS", ")", ";", "SecurityGroup", "userManagerGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_USERMANAGERS", ")", ";", "boolean", "hasBeenUserManager", "=", "isIdentityInSecurityGroup", "(", "updatedIdentity", ",", "userManagerGroup", ")", ";", "boolean", "userManager", "=", "roles", ".", "isUserManager", "(", ")", "&&", "!", "roles", ".", "isGuestOnly", "(", ")", "&&", "!", "roles", ".", "isInvitee", "(", ")", ";", "updateRolesInSecurityGroup", "(", "actingIdentity", ",", "updatedIdentity", ",", "userManagerGroup", ",", "hasBeenUserManager", ",", "userManager", ",", "Constants", ".", "GROUP_USERMANAGERS", ")", ";", "SecurityGroup", "institutionalResourceManagerGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_INST_ORES_MANAGER", ")", ";", "boolean", "hasBeenInstitutionalResourceManager", "=", "isIdentityInSecurityGroup", "(", "updatedIdentity", ",", "institutionalResourceManagerGroup", ")", ";", "boolean", "institutionalResourceManager", "=", "roles", ".", "isInstitutionalResourceManager", "(", ")", "&&", "!", "roles", ".", "isGuestOnly", "(", ")", "&&", "!", "roles", ".", "isInvitee", "(", ")", ";", "updateRolesInSecurityGroup", "(", "actingIdentity", ",", "updatedIdentity", ",", "institutionalResourceManagerGroup", ",", "hasBeenInstitutionalResourceManager", ",", "institutionalResourceManager", ",", "Constants", ".", "GROUP_INST_ORES_MANAGER", ")", ";", "SecurityGroup", "poolManagerGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_POOL_MANAGER", ")", ";", "boolean", "hasBeenPoolManager", "=", "isIdentityInSecurityGroup", "(", "updatedIdentity", ",", "poolManagerGroup", ")", ";", "boolean", "poolManager", "=", "roles", ".", "isPoolAdmin", "(", ")", "&&", "!", "roles", ".", "isGuestOnly", "(", ")", "&&", "!", "roles", ".", "isInvitee", "(", ")", ";", "updateRolesInSecurityGroup", "(", "actingIdentity", ",", "updatedIdentity", ",", "poolManagerGroup", ",", "hasBeenPoolManager", ",", "poolManager", ",", "Constants", ".", "GROUP_POOL_MANAGER", ")", ";", "SecurityGroup", "adminGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_ADMIN", ")", ";", "boolean", "hasBeenAdmin", "=", "isIdentityInSecurityGroup", "(", "updatedIdentity", ",", "adminGroup", ")", ";", "boolean", "isOLATAdmin", "=", "roles", ".", "isOLATAdmin", "(", ")", "&&", "!", "roles", ".", "isGuestOnly", "(", ")", "&&", "!", "roles", ".", "isInvitee", "(", ")", ";", "updateRolesInSecurityGroup", "(", "actingIdentity", ",", "updatedIdentity", ",", "adminGroup", ",", "hasBeenAdmin", ",", "isOLATAdmin", ",", "Constants", ".", "GROUP_ADMIN", ")", ";", "}", "private", "void", "updateRolesInSecurityGroup", "(", "Identity", "actingIdentity", ",", "Identity", "updatedIdentity", ",", "SecurityGroup", "securityGroup", ",", "boolean", "hasBeenInGroup", ",", "boolean", "isNowInGroup", ",", "String", "groupName", ")", "{", "if", "(", "!", "hasBeenInGroup", "&&", "isNowInGroup", ")", "{", "addIdentityToSecurityGroup", "(", "updatedIdentity", ",", "securityGroup", ")", ";", "log", ".", "audit", "(", "\"", "User::", "\"", "+", "(", "actingIdentity", "==", "null", "?", "\"", "unkown", "\"", ":", "actingIdentity", ".", "getName", "(", ")", ")", "+", "\"", " added system role::", "\"", "+", "groupName", "+", "\"", " to user::", "\"", "+", "updatedIdentity", ".", "getName", "(", ")", ",", "null", ")", ";", "}", "else", "if", "(", "hasBeenInGroup", "&&", "!", "isNowInGroup", ")", "{", "removeIdentityFromSecurityGroup", "(", "updatedIdentity", ",", "securityGroup", ")", ";", "log", ".", "audit", "(", "\"", "User::", "\"", "+", "(", "actingIdentity", "==", "null", "?", "\"", "unkown", "\"", ":", "actingIdentity", ".", "getName", "(", ")", ")", "+", "\"", " removed system role::", "\"", "+", "groupName", "+", "\"", " from user::", "\"", "+", "updatedIdentity", ".", "getName", "(", ")", ",", "null", ")", ";", "}", "}", "/**\n\t * scalar query : select sgi, poi, ori\n\t * @param identity\n\t * @return List of policies\n\t */", "@", "Override", "public", "List", "<", "Policy", ">", "getPoliciesOfIdentity", "(", "Identity", "identity", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select poi from ", "\"", ")", ".", "append", "(", "PolicyImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as poi ", "\"", ")", ".", "append", "(", "\"", "inner join fetch poi.securityGroup as secGroup ", "\"", ")", ".", "append", "(", "\"", "inner join fetch poi.olatResource as resource ", "\"", ")", ".", "append", "(", "\"", "where secGroup in (select sgmi.securityGroup from ", "\"", ")", ".", "append", "(", "SecurityGroupMembershipImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as sgmi where sgmi.identity.key=:identityKey)", "\"", ")", ";", "return", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Policy", ".", "class", ")", ".", "setParameter", "(", "\"", "identityKey", "\"", ",", "identity", ".", "getKey", "(", ")", ")", ".", "getResultList", "(", ")", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#isIdentityInSecurityGroup(org.olat.core.id.Identity, org.olat.basesecurity.SecurityGroup)\n\t */", "public", "boolean", "isIdentityInSecurityGroup", "(", "Identity", "identity", ",", "SecurityGroup", "secGroup", ")", "{", "if", "(", "secGroup", "==", "null", "||", "identity", "==", "null", ")", "return", "false", ";", "String", "queryString", "=", "\"", "select count(sgmsi) from org.olat.basesecurity.SecurityGroupMembershipImpl as sgmsi where sgmsi.identity = :identitykey and sgmsi.securityGroup = :securityGroup", "\"", ";", "DBQuery", "query", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "createQuery", "(", "queryString", ")", ";", "query", ".", "setLong", "(", "\"", "identitykey", "\"", ",", "identity", ".", "getKey", "(", ")", ")", ";", "query", ".", "setLong", "(", "\"", "securityGroup", "\"", ",", "secGroup", ".", "getKey", "(", ")", ")", ";", "query", ".", "setCacheable", "(", "true", ")", ";", "List", "res", "=", "query", ".", "list", "(", ")", ";", "Long", "cntL", "=", "(", "Long", ")", "res", ".", "get", "(", "0", ")", ";", "if", "(", "cntL", ".", "longValue", "(", ")", "!=", "0", "&&", "cntL", ".", "longValue", "(", ")", "!=", "1", ")", "throw", "new", "AssertException", "(", "\"", "unique n-to-n must always yield 0 or 1", "\"", ")", ";", "return", "(", "cntL", ".", "longValue", "(", ")", "==", "1", ")", ";", "}", "@", "Override", "public", "void", "touchMembership", "(", "Identity", "identity", ",", "List", "<", "SecurityGroup", ">", "secGroups", ")", "{", "if", "(", "secGroups", "==", "null", "||", "secGroups", ".", "isEmpty", "(", ")", ")", "return", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select sgmsi from ", "\"", ")", ".", "append", "(", "SecurityGroupMembershipImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as sgmsi ", "\"", ")", ".", "append", "(", "\"", "where sgmsi.identity.key=:identityKey and sgmsi.securityGroup in (:securityGroups)", "\"", ")", ";", "List", "<", "ModifiedInfo", ">", "infos", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "ModifiedInfo", ".", "class", ")", ".", "setParameter", "(", "\"", "identityKey", "\"", ",", "identity", ".", "getKey", "(", ")", ")", ".", "setParameter", "(", "\"", "securityGroups", "\"", ",", "secGroups", ")", ".", "getResultList", "(", ")", ";", "for", "(", "ModifiedInfo", "info", ":", "infos", ")", "{", "info", ".", "setLastModified", "(", "new", "Date", "(", ")", ")", ";", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "merge", "(", "info", ")", ";", "}", "}", "/**\n\t * @see org.olat.basesecurity.Manager#createAndPersistSecurityGroup()\n\t */", "public", "SecurityGroup", "createAndPersistSecurityGroup", "(", ")", "{", "SecurityGroupImpl", "sgi", "=", "new", "SecurityGroupImpl", "(", ")", ";", "DBFactory", ".", "getInstance", "(", ")", ".", "saveObject", "(", "sgi", ")", ";", "return", "sgi", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#deleteSecurityGroup(org.olat.basesecurity.SecurityGroup)\n\t */", "public", "void", "deleteSecurityGroup", "(", "SecurityGroup", "secGroup", ")", "{", "DB", "db", "=", "DBFactory", ".", "getInstance", "(", ")", ";", "secGroup", "=", "(", "SecurityGroup", ")", "db", ".", "loadObject", "(", "secGroup", ")", ";", "/*\n\t\t * if (!db.contains(secGroup)) { secGroup = (SecurityGroupImpl)\n\t\t * db.loadObject(SecurityGroupImpl.class, secGroup.getKey()); }\n\t\t */", "db", ".", "delete", "(", "\"", "from org.olat.basesecurity.SecurityGroupMembershipImpl as msi where msi.securityGroup.key = ?", "\"", ",", "new", "Object", "[", "]", "{", "secGroup", ".", "getKey", "(", ")", "}", ",", "new", "Type", "[", "]", "{", "StandardBasicTypes", ".", "LONG", "}", ")", ";", "db", ".", "delete", "(", "\"", "from org.olat.basesecurity.PolicyImpl as poi where poi.securityGroup = ?", "\"", ",", "new", "Object", "[", "]", "{", "secGroup", ".", "getKey", "(", ")", "}", ",", "new", "Type", "[", "]", "{", "StandardBasicTypes", ".", "LONG", "}", ")", ";", "db", ".", "deleteObject", "(", "secGroup", ")", ";", "}", "/**\n\t * \n\t * \n\t * @see org.olat.basesecurity.Manager#addIdentityToSecurityGroup(org.olat.core.id.Identity, org.olat.basesecurity.SecurityGroup)\n\t */", "@", "Override", "public", "void", "addIdentityToSecurityGroup", "(", "Identity", "identity", ",", "SecurityGroup", "secGroup", ")", "{", "SecurityGroupMembershipImpl", "sgmsi", "=", "new", "SecurityGroupMembershipImpl", "(", ")", ";", "sgmsi", ".", "setIdentity", "(", "identity", ")", ";", "sgmsi", ".", "setSecurityGroup", "(", "secGroup", ")", ";", "sgmsi", ".", "setLastModified", "(", "new", "Date", "(", ")", ")", ";", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "persist", "(", "sgmsi", ")", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#removeIdentityFromSecurityGroup(org.olat.core.id.Identity, org.olat.basesecurity.SecurityGroup)\n\t */", "@", "Override", "public", "boolean", "removeIdentityFromSecurityGroup", "(", "Identity", "identity", ",", "SecurityGroup", "secGroup", ")", "{", "return", "removeIdentityFromSecurityGroups", "(", "Collections", ".", "singletonList", "(", "identity", ")", ",", "Collections", ".", "singletonList", "(", "secGroup", ")", ")", ";", "}", "@", "Override", "public", "boolean", "removeIdentityFromSecurityGroups", "(", "List", "<", "Identity", ">", "identities", ",", "List", "<", "SecurityGroup", ">", "secGroups", ")", "{", "if", "(", "identities", "==", "null", "||", "identities", ".", "isEmpty", "(", ")", ")", "return", "true", ";", "if", "(", "secGroups", "==", "null", "||", "secGroups", ".", "isEmpty", "(", ")", ")", "return", "true", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "delete from ", "\"", ")", ".", "append", "(", "SecurityGroupMembershipImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as msi ", "\"", ")", ".", "append", "(", "\"", " where msi.identity.key in (:identityKeys) and msi.securityGroup.key in (:secGroupKeys)", "\"", ")", ";", "List", "<", "Long", ">", "identityKeys", "=", "new", "ArrayList", "<", "Long", ">", "(", ")", ";", "for", "(", "Identity", "identity", ":", "identities", ")", "{", "identityKeys", ".", "add", "(", "identity", ".", "getKey", "(", ")", ")", ";", "}", "List", "<", "Long", ">", "secGroupKeys", "=", "new", "ArrayList", "<", "Long", ">", "(", ")", ";", "for", "(", "SecurityGroup", "secGroup", ":", "secGroups", ")", "{", "secGroupKeys", ".", "add", "(", "secGroup", ".", "getKey", "(", ")", ")", ";", "}", "int", "rowsAffected", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ")", ".", "setParameter", "(", "\"", "identityKeys", "\"", ",", "identityKeys", ")", ".", "setParameter", "(", "\"", "secGroupKeys", "\"", ",", "secGroupKeys", ")", ".", "executeUpdate", "(", ")", ";", "return", "rowsAffected", ">", "0", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#createAndPersistPolicy(org.olat.basesecurity.SecurityGroup, java.lang.String, org.olat.core.id.OLATResourceable\n\t */", "@", "Override", "public", "Policy", "createAndPersistPolicy", "(", "SecurityGroup", "secGroup", ",", "String", "permission", ",", "OLATResourceable", "olatResourceable", ")", "{", "OLATResource", "olatResource", "=", "orm", ".", "findOrPersistResourceable", "(", "olatResourceable", ")", ";", "return", "createAndPersistPolicyWithResource", "(", "secGroup", ",", "permission", ",", "null", ",", "null", ",", "olatResource", ")", ";", "}", "/**\n\t * Creates a policy and persists on the database\n\t * @see org.olat.basesecurity.BaseSecurity#createAndPersistPolicyWithResource(org.olat.basesecurity.SecurityGroup, java.lang.String, java.util.Date, java.util.Date, org.olat.resource.OLATResource)\n\t */", "private", "Policy", "createAndPersistPolicyWithResource", "(", "SecurityGroup", "secGroup", ",", "String", "permission", ",", "Date", "from", ",", "Date", "to", ",", "OLATResource", "olatResource", ")", "{", "PolicyImpl", "pi", "=", "new", "PolicyImpl", "(", ")", ";", "pi", ".", "setSecurityGroup", "(", "secGroup", ")", ";", "pi", ".", "setOlatResource", "(", "olatResource", ")", ";", "pi", ".", "setPermission", "(", "permission", ")", ";", "pi", ".", "setFrom", "(", "from", ")", ";", "pi", ".", "setTo", "(", "to", ")", ";", "DBFactory", ".", "getInstance", "(", ")", ".", "saveObject", "(", "pi", ")", ";", "return", "pi", ";", "}", "/**\n\t * Helper method that only creates a policy only if no such policy exists in the database\n\t * @param secGroup\n\t * @param permission\n\t * @param olatResourceable\n\t * @return Policy\n\t */", "private", "Policy", "createAndPersistPolicyIfNotExists", "(", "SecurityGroup", "secGroup", ",", "String", "permission", ",", "OLATResourceable", "olatResourceable", ")", "{", "OLATResource", "olatResource", "=", "orm", ".", "findOrPersistResourceable", "(", "olatResourceable", ")", ";", "Policy", "existingPolicy", "=", "findPolicy", "(", "secGroup", ",", "permission", ",", "olatResource", ")", ";", "if", "(", "existingPolicy", "==", "null", ")", "{", "return", "createAndPersistPolicy", "(", "secGroup", ",", "permission", ",", "olatResource", ")", ";", "}", "return", "existingPolicy", ";", "}", "public", "Policy", "findPolicy", "(", "SecurityGroup", "secGroup", ",", "String", "permission", ",", "OLATResource", "olatResource", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select poi from ", "\"", ")", ".", "append", "(", "PolicyImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as poi ", "\"", ")", ".", "append", "(", "\"", " where poi.permission=:permission and poi.olatResource.key=:resourceKey and poi.securityGroup.key=:secGroupKey", "\"", ")", ";", "List", "<", "Policy", ">", "policies", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Policy", ".", "class", ")", ".", "setParameter", "(", "\"", "permission", "\"", ",", "permission", ")", ".", "setParameter", "(", "\"", "resourceKey", "\"", ",", "olatResource", ".", "getKey", "(", ")", ")", ".", "setParameter", "(", "\"", "secGroupKey", "\"", ",", "secGroup", ".", "getKey", "(", ")", ")", ".", "getResultList", "(", ")", ";", "if", "(", "policies", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "return", "policies", ".", "get", "(", "0", ")", ";", "}", "@", "Override", "public", "void", "deletePolicies", "(", "OLATResource", "resource", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "delete from ", "\"", ")", ".", "append", "(", "PolicyImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as poi ", "\"", ")", ".", "append", "(", "\"", " where poi.olatResource.key=:resourceKey", "\"", ")", ";", "int", "rowDeleted", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ")", ".", "setParameter", "(", "\"", "resourceKey", "\"", ",", "resource", ".", "getKey", "(", ")", ")", ".", "executeUpdate", "(", ")", ";", "if", "(", "log", ".", "isDebug", "(", ")", ")", "{", "log", ".", "debug", "(", "rowDeleted", "+", "\"", " policies deleted", "\"", ")", ";", "}", "}", "/**\n\t * @param username the username\n\t * @param user the presisted User\n\t * @param authusername the username used as authentication credential\n\t * (=username for provider \"OLAT\")\n\t * @param provider the provider of the authentication (\"OLAT\" or \"AAI\"). If null, no \n\t * authentication token is generated.\n\t * @param credential the credentials or null if not used\n\t * @return Identity\n\t */", "@", "Override", "public", "Identity", "createAndPersistIdentity", "(", "String", "username", ",", "User", "user", ",", "String", "provider", ",", "String", "authusername", ",", "String", "credential", ")", "{", "IdentityImpl", "iimpl", "=", "new", "IdentityImpl", "(", "username", ",", "user", ")", ";", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "persist", "(", "iimpl", ")", ";", "if", "(", "provider", "!=", "null", ")", "{", "createAndPersistAuthentication", "(", "iimpl", ",", "provider", ",", "authusername", ",", "credential", ",", "loginModule", ".", "getDefaultHashAlgorithm", "(", ")", ")", ";", "}", "notifyNewIdentityCreated", "(", "iimpl", ")", ";", "return", "iimpl", ";", "}", "/**\n\t * @param username The username\n\t * @param user The unpresisted User\n\t * @param provider The provider of the authentication (\"OLAT\" or \"AAI\"). If null, no authentication token is generated.\n\t * @param authusername The username used as authentication credential (=username for provider \"OLAT\")\n\t * @return Identity\n\t */", "@", "Override", "public", "Identity", "createAndPersistIdentityAndUser", "(", "String", "username", ",", "String", "externalId", ",", "User", "user", ",", "String", "provider", ",", "String", "authusername", ")", "{", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "persist", "(", "user", ")", ";", "IdentityImpl", "iimpl", "=", "new", "IdentityImpl", "(", "username", ",", "user", ")", ";", "iimpl", ".", "setExternalId", "(", "externalId", ")", ";", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "persist", "(", "iimpl", ")", ";", "if", "(", "provider", "!=", "null", ")", "{", "createAndPersistAuthentication", "(", "iimpl", ",", "provider", ",", "authusername", ",", "null", ",", "null", ")", ";", "}", "notifyNewIdentityCreated", "(", "iimpl", ")", ";", "return", "iimpl", ";", "}", "/**\n\t * @param username the username\n\t * @param user the unpresisted User\n\t * @param authusername the username used as authentication credential\n\t * (=username for provider \"OLAT\")\n\t * @param provider the provider of the authentication (\"OLAT\" or \"AAI\"). If null, no \n\t * authentication token is generated.\n\t * @param credential the credentials or null if not used\n\t * @return Identity\n\t */", "@", "Override", "public", "Identity", "createAndPersistIdentityAndUser", "(", "String", "username", ",", "String", "externalId", ",", "User", "user", ",", "String", "provider", ",", "String", "authusername", ",", "String", "credential", ")", "{", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "persist", "(", "user", ")", ";", "IdentityImpl", "iimpl", "=", "new", "IdentityImpl", "(", "username", ",", "user", ")", ";", "iimpl", ".", "setExternalId", "(", "externalId", ")", ";", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "persist", "(", "iimpl", ")", ";", "if", "(", "provider", "!=", "null", ")", "{", "createAndPersistAuthentication", "(", "iimpl", ",", "provider", ",", "authusername", ",", "credential", ",", "loginModule", ".", "getDefaultHashAlgorithm", "(", ")", ")", ";", "}", "notifyNewIdentityCreated", "(", "iimpl", ")", ";", "return", "iimpl", ";", "}", "/**\n\t * Persists the given user, creates an identity for it and adds the user to\n\t * the users system group\n\t * \n\t * @param loginName\n\t * @param externalId\n\t * @param pwd null: no OLAT authentication is generated. If not null, the password will be \n\t * encrypted and and an OLAT authentication is generated.\n\t * @param newUser unpersisted users\n\t * @return Identity\n\t */", "@", "Override", "public", "Identity", "createAndPersistIdentityAndUserWithDefaultProviderAndUserGroup", "(", "String", "loginName", ",", "String", "externalId", ",", "String", "pwd", ",", "User", "newUser", ")", "{", "Identity", "ident", "=", "null", ";", "if", "(", "pwd", "==", "null", ")", "{", "ident", "=", "createAndPersistIdentityAndUser", "(", "loginName", ",", "externalId", ",", "newUser", ",", "null", ",", "null", ")", ";", "log", ".", "audit", "(", "\"", "Create an identity without authentication (login=", "\"", "+", "loginName", "+", "\"", ")", "\"", ")", ";", "}", "else", "{", "ident", "=", "createAndPersistIdentityAndUser", "(", "loginName", ",", "externalId", ",", "newUser", ",", "BaseSecurityModule", ".", "getDefaultAuthProviderIdentifier", "(", ")", ",", "loginName", ",", "pwd", ")", ";", "log", ".", "audit", "(", "\"", "Create an identity with ", "\"", "+", "BaseSecurityModule", ".", "getDefaultAuthProviderIdentifier", "(", ")", "+", "\"", " authentication (login=", "\"", "+", "loginName", "+", "\"", ")", "\"", ")", ";", "}", "SecurityGroup", "olatuserGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_OLATUSERS", ")", ";", "addIdentityToSecurityGroup", "(", "ident", ",", "olatuserGroup", ")", ";", "return", "ident", ";", "}", "/**\n\t * Persists the given user, creates an identity for it and adds the user to\n\t * the users system group, create an authentication for an external provider\n\t * \n\t * @param loginName\n\t * @param externalId\n\t * @param provider\n\t * @param authusername\n\t * @param newUser\n\t * @return\n\t */", "@", "Override", "public", "Identity", "createAndPersistIdentityAndUserWithUserGroup", "(", "String", "loginName", ",", "String", "externalId", ",", "String", "provider", ",", "String", "authusername", ",", "User", "newUser", ")", "{", "Identity", "ident", "=", "createAndPersistIdentityAndUser", "(", "loginName", ",", "externalId", ",", "newUser", ",", "provider", ",", "authusername", ",", "null", ")", ";", "log", ".", "audit", "(", "\"", "Create an identity with ", "\"", "+", "provider", "+", "\"", " authentication (login=", "\"", "+", "loginName", "+", "\"", ",authusername=", "\"", "+", "authusername", "+", "\"", ")", "\"", ")", ";", "SecurityGroup", "olatuserGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_OLATUSERS", ")", ";", "addIdentityToSecurityGroup", "(", "ident", ",", "olatuserGroup", ")", ";", "return", "ident", ";", "}", "private", "void", "notifyNewIdentityCreated", "(", "Identity", "newIdentity", ")", "{", "DBFactory", ".", "getInstance", "(", ")", ".", "commit", "(", ")", ";", "CoordinatorManager", ".", "getInstance", "(", ")", ".", "getCoordinator", "(", ")", ".", "getEventBus", "(", ")", ".", "fireEventToListenersOf", "(", "new", "NewIdentityCreatedEvent", "(", "newIdentity", ")", ",", "IDENTITY_EVENT_CHANNEL", ")", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#getIdentitiesOfSecurityGroup(org.olat.basesecurity.SecurityGroup)\n\t */", "public", "List", "<", "Identity", ">", "getIdentitiesOfSecurityGroup", "(", "SecurityGroup", "secGroup", ")", "{", "if", "(", "secGroup", "==", "null", ")", "{", "throw", "new", "AssertException", "(", "\"", "getIdentitiesOfSecurityGroup: ERROR secGroup was null !!", "\"", ")", ";", "}", "DB", "db", "=", "DBFactory", ".", "getInstance", "(", ")", ";", "if", "(", "db", "==", "null", ")", "{", "throw", "new", "AssertException", "(", "\"", "getIdentitiesOfSecurityGroup: ERROR db was null !!", "\"", ")", ";", "}", "List", "<", "Identity", ">", "idents", "=", "getIdentitiesOfSecurityGroup", "(", "secGroup", ",", "0", ",", "-", "1", ")", ";", "return", "idents", ";", "}", "@", "Override", "public", "List", "<", "Identity", ">", "getIdentitiesOfSecurityGroup", "(", "SecurityGroup", "secGroup", ",", "int", "firstResult", ",", "int", "maxResults", ")", "{", "if", "(", "secGroup", "==", "null", ")", "{", "throw", "new", "AssertException", "(", "\"", "getIdentitiesOfSecurityGroup: ERROR secGroup was null !!", "\"", ")", ";", "}", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select identity from ", "\"", ")", ".", "append", "(", "SecurityGroupMembershipImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as sgmsi ", "\"", ")", ".", "append", "(", "\"", " inner join sgmsi.identity identity ", "\"", ")", ".", "append", "(", "\"", " inner join fetch identity.user user ", "\"", ")", ".", "append", "(", "\"", " where sgmsi.securityGroup=:secGroup", "\"", ")", ";", "TypedQuery", "<", "Identity", ">", "query", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Identity", ".", "class", ")", ".", "setParameter", "(", "\"", "secGroup", "\"", ",", "secGroup", ")", ";", "if", "(", "firstResult", ">=", "0", ")", "{", "query", ".", "setFirstResult", "(", "firstResult", ")", ";", "}", "if", "(", "maxResults", ">", "0", ")", "{", "query", ".", "setMaxResults", "(", "maxResults", ")", ";", "}", "return", "query", ".", "getResultList", "(", ")", ";", "}", "/**\n\t * Return a list of unique identities which are in the list of security groups\n\t * @see org.olat.basesecurity.BaseSecurity#getIdentitiesOfSecurityGroups(java.util.List)\n\t */", "@", "Override", "public", "List", "<", "Identity", ">", "getIdentitiesOfSecurityGroups", "(", "List", "<", "SecurityGroup", ">", "secGroups", ")", "{", "if", "(", "secGroups", "==", "null", "||", "secGroups", ".", "isEmpty", "(", ")", ")", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select distinct(identity) from ", "\"", ")", ".", "append", "(", "SecurityGroupMembershipImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as sgmsi ", "\"", ")", ".", "append", "(", "\"", " inner join sgmsi.identity identity ", "\"", ")", ".", "append", "(", "\"", " inner join fetch identity.user user ", "\"", ")", ".", "append", "(", "\"", " where sgmsi.securityGroup in (:secGroups)", "\"", ")", ";", "return", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Identity", ".", "class", ")", ".", "setParameter", "(", "\"", "secGroups", "\"", ",", "secGroups", ")", ".", "getResultList", "(", ")", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#getIdentitiesAndDateOfSecurityGroup(org.olat.basesecurity.SecurityGroup)\n\t */", "@", "Override", "public", "List", "<", "Object", "[", "]", ">", "getIdentitiesAndDateOfSecurityGroup", "(", "SecurityGroup", "secGroup", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select ii, sgmsi.lastModified from ", "\"", ")", ".", "append", "(", "IdentityImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as ii", "\"", ")", ".", "append", "(", "\"", " inner join fetch ii.user as iuser, ", "\"", ")", ".", "append", "(", "SecurityGroupMembershipImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as sgmsi", "\"", ")", ".", "append", "(", "\"", " where sgmsi.securityGroup=:secGroup and sgmsi.identity = ii", "\"", ")", ";", "return", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Object", "[", "]", ".", "class", ")", ".", "setParameter", "(", "\"", "secGroup", "\"", ",", "secGroup", ")", ".", "getResultList", "(", ")", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#countIdentitiesOfSecurityGroup(org.olat.basesecurity.SecurityGroup)\n\t */", "@", "Override", "public", "int", "countIdentitiesOfSecurityGroup", "(", "SecurityGroup", "secGroup", ")", "{", "DB", "db", "=", "DBFactory", ".", "getInstance", "(", ")", ";", "String", "q", "=", "\"", "select count(sgm) from org.olat.basesecurity.SecurityGroupMembershipImpl sgm where sgm.securityGroup = :group", "\"", ";", "DBQuery", "query", "=", "db", ".", "createQuery", "(", "q", ")", ";", "query", ".", "setEntity", "(", "\"", "group", "\"", ",", "secGroup", ")", ";", "query", ".", "setCacheable", "(", "true", ")", ";", "int", "result", "=", "(", "(", "Long", ")", "query", ".", "list", "(", ")", ".", "get", "(", "0", ")", ")", ".", "intValue", "(", ")", ";", "return", "result", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#createAndPersistNamedSecurityGroup(java.lang.String)\n\t */", "@", "Override", "public", "SecurityGroup", "createAndPersistNamedSecurityGroup", "(", "String", "groupName", ")", "{", "SecurityGroup", "secG", "=", "createAndPersistSecurityGroup", "(", ")", ";", "NamedGroupImpl", "ngi", "=", "new", "NamedGroupImpl", "(", "groupName", ",", "secG", ")", ";", "DBFactory", ".", "getInstance", "(", ")", ".", "saveObject", "(", "ngi", ")", ";", "return", "secG", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#findSecurityGroupByName(java.lang.String)\n\t */", "@", "Override", "public", "SecurityGroup", "findSecurityGroupByName", "(", "String", "securityGroupName", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select sgi from ", "\"", ")", ".", "append", "(", "NamedGroupImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as ngroup ", "\"", ")", ".", "append", "(", "\"", " inner join ngroup.securityGroup sgi", "\"", ")", ".", "append", "(", "\"", " where ngroup.groupName=:groupName", "\"", ")", ";", "List", "<", "SecurityGroup", ">", "group", "=", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "SecurityGroup", ".", "class", ")", ".", "setParameter", "(", "\"", "groupName", "\"", ",", "securityGroupName", ")", ".", "setHint", "(", "\"", "org.hibernate.cacheable", "\"", ",", "Boolean", ".", "TRUE", ")", ".", "getResultList", "(", ")", ";", "int", "size", "=", "group", ".", "size", "(", ")", ";", "if", "(", "size", "==", "0", ")", "return", "null", ";", "if", "(", "size", "!=", "1", ")", "throw", "new", "AssertException", "(", "\"", "non unique name in namedgroup: ", "\"", "+", "securityGroupName", ")", ";", "SecurityGroup", "sg", "=", "group", ".", "get", "(", "0", ")", ";", "return", "sg", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#findIdentityByName(java.lang.String)\n\t */", "@", "Override", "public", "Identity", "findIdentityByName", "(", "String", "identityName", ")", "{", "if", "(", "identityName", "==", "null", ")", "throw", "new", "AssertException", "(", "\"", "findIdentitybyName: name was null", "\"", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select ident from ", "\"", ")", ".", "append", "(", "IdentityImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as ident where ident.name=:username", "\"", ")", ";", "List", "<", "Identity", ">", "identities", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Identity", ".", "class", ")", ".", "setParameter", "(", "\"", "username", "\"", ",", "identityName", ")", ".", "getResultList", "(", ")", ";", "if", "(", "identities", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "return", "identities", ".", "get", "(", "0", ")", ";", "}", "/**\n\t * Custom search operation by BiWa\n\t * find identity by student/institution number \n\t * @return\n\t */", "@", "Override", "public", "Identity", "findIdentityByNumber", "(", "String", "identityNumber", ")", "{", "Map", "<", "String", ",", "String", ">", "userPropertiesSearch", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "userPropertiesSearch", ".", "put", "(", "UserConstants", ".", "INSTITUTIONALUSERIDENTIFIER", ",", "identityNumber", ")", ";", "List", "<", "Identity", ">", "identities", "=", "getIdentitiesByPowerSearch", "(", "null", ",", "userPropertiesSearch", ",", "true", ",", "null", ",", "null", ",", "null", ",", "null", ",", "null", ",", "null", ",", "null", ",", "null", ")", ";", "if", "(", "identities", ".", "size", "(", ")", "==", "1", ")", "{", "return", "identities", ".", "get", "(", "0", ")", ";", "}", "return", "null", ";", "}", "@", "Override", "public", "List", "<", "Identity", ">", "findIdentitiesByNumber", "(", "Collection", "<", "String", ">", "identityNumbers", ")", "{", "if", "(", "identityNumbers", "==", "null", "||", "identityNumbers", ".", "isEmpty", "(", ")", ")", "return", "Collections", ".", "emptyList", "(", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select identity from ", "\"", ")", ".", "append", "(", "IdentityImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " identity ", "\"", ")", ".", "append", "(", "\"", " inner join identity.user user ", "\"", ")", ".", "append", "(", "\"", " where user.userProperties['", "\"", ")", ".", "append", "(", "UserConstants", ".", "INSTITUTIONALUSERIDENTIFIER", ")", ".", "append", "(", "\"", "'] in (:idNumbers) ", "\"", ")", ";", "return", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Identity", ".", "class", ")", ".", "setParameter", "(", "\"", "idNumbers", "\"", ",", "identityNumbers", ")", ".", "getResultList", "(", ")", ";", "}", "@", "Override", "public", "List", "<", "Identity", ">", "findIdentitiesByName", "(", "Collection", "<", "String", ">", "identityNames", ")", "{", "if", "(", "identityNames", "==", "null", "||", "identityNames", ".", "isEmpty", "(", ")", ")", "return", "Collections", ".", "emptyList", "(", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select ident from ", "\"", ")", ".", "append", "(", "IdentityImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as ident where ident.name in (:username)", "\"", ")", ";", "List", "<", "Identity", ">", "identities", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Identity", ".", "class", ")", ".", "setParameter", "(", "\"", "username", "\"", ",", "identityNames", ")", ".", "getResultList", "(", ")", ";", "return", "identities", ";", "}", "@", "Override", "public", "Identity", "findIdentityByUser", "(", "User", "user", ")", "{", "if", "(", "user", "==", "null", ")", "return", "null", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select ident from ", "\"", ")", ".", "append", "(", "IdentityImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as ident where ident.user.key=:userKey", "\"", ")", ";", "List", "<", "Identity", ">", "identities", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Identity", ".", "class", ")", ".", "setParameter", "(", "\"", "userKey", "\"", ",", "user", ".", "getKey", "(", ")", ")", ".", "getResultList", "(", ")", ";", "if", "(", "identities", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "return", "identities", ".", "get", "(", "0", ")", ";", "}", "@", "Override", "public", "List", "<", "IdentityShort", ">", "findShortIdentitiesByName", "(", "Collection", "<", "String", ">", "identityNames", ")", "{", "if", "(", "identityNames", "==", "null", "||", "identityNames", ".", "isEmpty", "(", ")", ")", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select ident from ", "\"", ")", ".", "append", "(", "IdentityShort", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as ident where ident.name in (:names)", "\"", ")", ";", "TypedQuery", "<", "IdentityShort", ">", "query", "=", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "IdentityShort", ".", "class", ")", ";", "int", "count", "=", "0", ";", "int", "batch", "=", "500", ";", "List", "<", "String", ">", "names", "=", "new", "ArrayList", "<", "String", ">", "(", "identityNames", ")", ";", "List", "<", "IdentityShort", ">", "shortIdentities", "=", "new", "ArrayList", "<", "IdentityShort", ">", "(", "names", ".", "size", "(", ")", ")", ";", "do", "{", "int", "toIndex", "=", "Math", ".", "min", "(", "count", "+", "batch", ",", "names", ".", "size", "(", ")", ")", ";", "List", "<", "String", ">", "toLoad", "=", "names", ".", "subList", "(", "count", ",", "toIndex", ")", ";", "List", "<", "IdentityShort", ">", "allProperties", "=", "query", ".", "setParameter", "(", "\"", "names", "\"", ",", "toLoad", ")", ".", "getResultList", "(", ")", ";", "shortIdentities", ".", "addAll", "(", "allProperties", ")", ";", "count", "+=", "batch", ";", "}", "while", "(", "count", "<", "names", ".", "size", "(", ")", ")", ";", "return", "shortIdentities", ";", "}", "@", "Override", "public", "List", "<", "IdentityShort", ">", "findShortIdentitiesByKey", "(", "Collection", "<", "Long", ">", "identityKeys", ")", "{", "if", "(", "identityKeys", "==", "null", "||", "identityKeys", ".", "isEmpty", "(", ")", ")", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select ident from ", "\"", ")", ".", "append", "(", "IdentityShort", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as ident where ident.key in (:keys)", "\"", ")", ";", "TypedQuery", "<", "IdentityShort", ">", "query", "=", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "IdentityShort", ".", "class", ")", ";", "int", "count", "=", "0", ";", "int", "batch", "=", "500", ";", "List", "<", "Long", ">", "names", "=", "new", "ArrayList", "<", "Long", ">", "(", "identityKeys", ")", ";", "List", "<", "IdentityShort", ">", "shortIdentities", "=", "new", "ArrayList", "<", "IdentityShort", ">", "(", "names", ".", "size", "(", ")", ")", ";", "do", "{", "int", "toIndex", "=", "Math", ".", "min", "(", "count", "+", "batch", ",", "names", ".", "size", "(", ")", ")", ";", "List", "<", "Long", ">", "toLoad", "=", "names", ".", "subList", "(", "count", ",", "toIndex", ")", ";", "List", "<", "IdentityShort", ">", "allProperties", "=", "query", ".", "setParameter", "(", "\"", "keys", "\"", ",", "toLoad", ")", ".", "getResultList", "(", ")", ";", "shortIdentities", ".", "addAll", "(", "allProperties", ")", ";", "count", "+=", "batch", ";", "}", "while", "(", "count", "<", "names", ".", "size", "(", ")", ")", ";", "return", "shortIdentities", ";", "}", "public", "List", "<", "Identity", ">", "findIdentitiesWithoutBusinessGroup", "(", "Integer", "status", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select ident from ", "\"", ")", ".", "append", "(", "IdentityImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as ident ", "\"", ")", ".", "append", "(", "\"", " where not exists (", "\"", ")", ".", "append", "(", "\"", " select bgroup from ", "\"", ")", ".", "append", "(", "BusinessGroupImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " bgroup, bgroupmember as me", "\"", ")", ".", "append", "(", "\"", " where me.group=bgroup.baseGroup and me.identity=ident", "\"", ")", ".", "append", "(", "\"", " )", "\"", ")", ";", "if", "(", "status", "!=", "null", ")", "{", "if", "(", "status", ".", "equals", "(", "Identity", ".", "STATUS_VISIBLE_LIMIT", ")", ")", "{", "sb", ".", "append", "(", "\"", " and ident.status < :status ", "\"", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"", " and ident.status = :status ", "\"", ")", ";", "}", "}", "else", "{", "sb", ".", "append", "(", "\"", " and ident.status < ", "\"", ")", ".", "append", "(", "Identity", ".", "STATUS_DELETED", ")", ";", "}", "TypedQuery", "<", "Identity", ">", "query", "=", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Identity", ".", "class", ")", ";", "if", "(", "status", "!=", "null", ")", "{", "query", ".", "setParameter", "(", "\"", "status", "\"", ",", "status", ")", ";", "}", "return", "query", ".", "getResultList", "(", ")", ";", "}", "/**\n\t * \n\t * @see org.olat.basesecurity.Manager#loadIdentityByKey(java.lang.Long)\n\t */", "public", "Identity", "loadIdentityByKey", "(", "Long", "identityKey", ")", "{", "if", "(", "identityKey", "==", "null", ")", "throw", "new", "AssertException", "(", "\"", "findIdentitybyKey: key is null", "\"", ")", ";", "if", "(", "identityKey", ".", "equals", "(", "Long", ".", "valueOf", "(", "0", ")", ")", ")", "return", "null", ";", "return", "DBFactory", ".", "getInstance", "(", ")", ".", "loadObject", "(", "IdentityImpl", ".", "class", ",", "identityKey", ")", ";", "}", "@", "Override", "public", "List", "<", "Identity", ">", "loadIdentityByKeys", "(", "Collection", "<", "Long", ">", "identityKeys", ")", "{", "if", "(", "identityKeys", "==", "null", "||", "identityKeys", ".", "isEmpty", "(", ")", ")", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select ident from ", "\"", ")", ".", "append", "(", "Identity", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as ident where ident.key in (:keys)", "\"", ")", ";", "return", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Identity", ".", "class", ")", ".", "setParameter", "(", "\"", "keys", "\"", ",", "identityKeys", ")", ".", "getResultList", "(", ")", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#loadIdentityByKey(java.lang.Long,boolean)\n\t */", "public", "Identity", "loadIdentityByKey", "(", "Long", "identityKey", ",", "boolean", "strict", ")", "{", "if", "(", "strict", ")", "return", "loadIdentityByKey", "(", "identityKey", ")", ";", "String", "queryStr", "=", "\"", "select ident from org.olat.basesecurity.IdentityImpl as ident where ident.key=:identityKey", "\"", ";", "DBQuery", "dbq", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "createQuery", "(", "queryStr", ")", ";", "dbq", ".", "setLong", "(", "\"", "identityKey", "\"", ",", "identityKey", ")", ";", "List", "<", "Identity", ">", "identities", "=", "dbq", ".", "list", "(", ")", ";", "if", "(", "identities", ".", "size", "(", ")", "==", "1", ")", "return", "identities", ".", "get", "(", "0", ")", ";", "return", "null", ";", "}", "@", "Override", "public", "IdentityShort", "loadIdentityShortByKey", "(", "Long", "identityKey", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select identity from ", "\"", ")", ".", "append", "(", "IdentityShort", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as identity ", "\"", ")", ".", "append", "(", "\"", " where identity.key=:identityKey", "\"", ")", ";", "List", "<", "IdentityShort", ">", "idents", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "IdentityShort", ".", "class", ")", ".", "setParameter", "(", "\"", "identityKey", "\"", ",", "identityKey", ")", ".", "getResultList", "(", ")", ";", "if", "(", "idents", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "return", "idents", ".", "get", "(", "0", ")", ";", "}", "@", "Override", "public", "List", "<", "IdentityShort", ">", "loadIdentityShortByKeys", "(", "Collection", "<", "Long", ">", "identityKeys", ")", "{", "if", "(", "identityKeys", "==", "null", "||", "identityKeys", ".", "isEmpty", "(", ")", ")", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select ident from ", "\"", ")", ".", "append", "(", "IdentityShort", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as ident where ident.key in (:keys)", "\"", ")", ";", "return", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "IdentityShort", ".", "class", ")", ".", "setParameter", "(", "\"", "keys", "\"", ",", "identityKeys", ")", ".", "getResultList", "(", ")", ";", "}", "@", "Override", "public", "List", "<", "Identity", ">", "loadIdentities", "(", "int", "firstResult", ",", "int", "maxResults", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select ident from ", "\"", ")", ".", "append", "(", "IdentityImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as ident order by ident.key", "\"", ")", ";", "return", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Identity", ".", "class", ")", ".", "setFirstResult", "(", "firstResult", ")", ".", "setMaxResults", "(", "maxResults", ")", ".", "getResultList", "(", ")", ";", "}", "@", "Override", "public", "List", "<", "Long", ">", "loadVisibleIdentityKeys", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select ident.key from ", "\"", ")", ".", "append", "(", "IdentityImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as ident", "\"", ")", ".", "append", "(", "\"", " where ident.status<", "\"", ")", ".", "append", "(", "Identity", ".", "STATUS_VISIBLE_LIMIT", ")", ".", "append", "(", "\"", " order by ident.key", "\"", ")", ";", "return", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Long", ".", "class", ")", ".", "getResultList", "(", ")", ";", "}", "/**\n\t * \n\t * @see org.olat.basesecurity.Manager#countUniqueUserLoginsSince(java.util.Date)\n\t */", "@", "Override", "public", "Long", "countUniqueUserLoginsSince", "(", "Date", "lastLoginLimit", ")", "{", "String", "queryStr", "=", "\"", "Select count(ident) from org.olat.core.id.Identity as ident where ", "\"", "+", "\"", "ident.lastLogin > :lastLoginLimit and ident.lastLogin != ident.creationDate", "\"", ";", "DBQuery", "dbq", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "createQuery", "(", "queryStr", ")", ";", "dbq", ".", "setDate", "(", "\"", "lastLoginLimit", "\"", ",", "lastLoginLimit", ")", ";", "List", "res", "=", "dbq", ".", "list", "(", ")", ";", "Long", "cntL", "=", "(", "Long", ")", "res", ".", "get", "(", "0", ")", ";", "return", "cntL", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#getAuthentications(org.olat.core.id.Identity)\n\t */", "@", "Override", "public", "List", "<", "Authentication", ">", "getAuthentications", "(", "Identity", "identity", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select auth from ", "\"", ")", ".", "append", "(", "AuthenticationImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as auth ", "\"", ")", ".", "append", "(", "\"", "inner join fetch auth.identity as ident", "\"", ")", ".", "append", "(", "\"", " where ident.key=:identityKey", "\"", ")", ";", "return", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Authentication", ".", "class", ")", ".", "setParameter", "(", "\"", "identityKey", "\"", ",", "identity", ".", "getKey", "(", ")", ")", ".", "getResultList", "(", ")", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#createAndPersistAuthentication(org.olat.core.id.Identity, java.lang.String, java.lang.String, java.lang.String)\n\t */", "@", "Override", "public", "Authentication", "createAndPersistAuthentication", "(", "final", "Identity", "ident", ",", "final", "String", "provider", ",", "final", "String", "authUserName", ",", "final", "String", "credentials", ",", "final", "Encoder", ".", "Algorithm", "algorithm", ")", "{", "OLATResourceable", "resourceable", "=", "OresHelper", ".", "createOLATResourceableInstanceWithoutCheck", "(", "provider", ",", "ident", ".", "getKey", "(", ")", ")", ";", "return", "CoordinatorManager", ".", "getInstance", "(", ")", ".", "getCoordinator", "(", ")", ".", "getSyncer", "(", ")", ".", "doInSync", "(", "resourceable", ",", "new", "SyncerCallback", "<", "Authentication", ">", "(", ")", "{", "@", "Override", "public", "Authentication", "execute", "(", ")", "{", "Authentication", "auth", "=", "findAuthentication", "(", "ident", ",", "provider", ")", ";", "if", "(", "auth", "==", "null", ")", "{", "if", "(", "algorithm", "!=", "null", "&&", "credentials", "!=", "null", ")", "{", "String", "salt", "=", "algorithm", ".", "isSalted", "(", ")", "?", "Encoder", ".", "getSalt", "(", ")", ":", "null", ";", "String", "hash", "=", "Encoder", ".", "encrypt", "(", "credentials", ",", "salt", ",", "algorithm", ")", ";", "auth", "=", "new", "AuthenticationImpl", "(", "ident", ",", "provider", ",", "authUserName", ",", "hash", ",", "salt", ",", "algorithm", ".", "name", "(", ")", ")", ";", "}", "else", "{", "auth", "=", "new", "AuthenticationImpl", "(", "ident", ",", "provider", ",", "authUserName", ",", "credentials", ")", ";", "}", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "persist", "(", "auth", ")", ";", "log", ".", "audit", "(", "\"", "Create ", "\"", "+", "provider", "+", "\"", " authentication (login=", "\"", "+", "ident", ".", "getName", "(", ")", "+", "\"", ",authusername=", "\"", "+", "authUserName", "+", "\"", ")", "\"", ")", ";", "}", "return", "auth", ";", "}", "}", ")", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#findAuthentication(org.olat.core.id.Identity, java.lang.String)\n\t */", "@", "Override", "public", "Authentication", "findAuthentication", "(", "Identity", "identity", ",", "String", "provider", ")", "{", "if", "(", "identity", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "identity must not be null", "\"", ")", ";", "}", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select auth from ", "\"", ")", ".", "append", "(", "AuthenticationImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as auth where auth.identity.key=:identityKey and auth.provider=:provider", "\"", ")", ";", "List", "<", "Authentication", ">", "results", "=", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Authentication", ".", "class", ")", ".", "setParameter", "(", "\"", "identityKey", "\"", ",", "identity", ".", "getKey", "(", ")", ")", ".", "setParameter", "(", "\"", "provider", "\"", ",", "provider", ")", ".", "getResultList", "(", ")", ";", "if", "(", "results", "==", "null", "||", "results", ".", "size", "(", ")", "==", "0", ")", "return", "null", ";", "if", "(", "results", ".", "size", "(", ")", ">", "1", ")", "throw", "new", "AssertException", "(", "\"", "Found more than one Authentication for a given subject and a given provider.", "\"", ")", ";", "return", "results", ".", "get", "(", "0", ")", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#findAuthentication(org.olat.core.id.Identity, java.lang.String)\n\t */", "@", "Override", "public", "List", "<", "Authentication", ">", "findAuthenticationByToken", "(", "String", "provider", ",", "String", "securityToken", ")", "{", "if", "(", "provider", "==", "null", "||", "securityToken", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "provider and token must not be null", "\"", ")", ";", "}", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select auth from ", "\"", ")", ".", "append", "(", "AuthenticationImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as auth where auth.credential=:credential and auth.provider=:provider", "\"", ")", ";", "List", "<", "Authentication", ">", "results", "=", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Authentication", ".", "class", ")", ".", "setParameter", "(", "\"", "credential", "\"", ",", "securityToken", ")", ".", "setParameter", "(", "\"", "provider", "\"", ",", "provider", ")", ".", "getResultList", "(", ")", ";", "return", "results", ";", "}", "@", "Override", "public", "List", "<", "Authentication", ">", "findOldAuthentication", "(", "String", "provider", ",", "Date", "creationDate", ")", "{", "if", "(", "provider", "==", "null", "||", "creationDate", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "provider and token must not be null", "\"", ")", ";", "}", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select auth from ", "\"", ")", ".", "append", "(", "AuthenticationImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as auth where auth.provider=:provider and auth.creationDate<:creationDate", "\"", ")", ";", "List", "<", "Authentication", ">", "results", "=", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Authentication", ".", "class", ")", ".", "setParameter", "(", "\"", "creationDate", "\"", ",", "creationDate", ",", "TemporalType", ".", "TIMESTAMP", ")", ".", "setParameter", "(", "\"", "provider", "\"", ",", "provider", ")", ".", "getResultList", "(", ")", ";", "return", "results", ";", "}", "@", "Override", "public", "Authentication", "updateAuthentication", "(", "Authentication", "authentication", ")", "{", "return", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "merge", "(", "authentication", ")", ";", "}", "@", "Override", "public", "boolean", "checkCredentials", "(", "Authentication", "authentication", ",", "String", "password", ")", "{", "Algorithm", "algorithm", "=", "Algorithm", ".", "find", "(", "authentication", ".", "getAlgorithm", "(", ")", ")", ";", "String", "hash", "=", "Encoder", ".", "encrypt", "(", "password", ",", "authentication", ".", "getSalt", "(", ")", ",", "algorithm", ")", ";", "return", "authentication", ".", "getCredential", "(", ")", "!=", "null", "&&", "authentication", ".", "getCredential", "(", ")", ".", "equals", "(", "hash", ")", ";", "}", "@", "Override", "public", "Authentication", "updateCredentials", "(", "Authentication", "authentication", ",", "String", "password", ",", "Algorithm", "algorithm", ")", "{", "if", "(", "authentication", ".", "getAlgorithm", "(", ")", "!=", "null", "&&", "authentication", ".", "getAlgorithm", "(", ")", ".", "equals", "(", "algorithm", ".", "name", "(", ")", ")", ")", "{", "String", "currentSalt", "=", "authentication", ".", "getSalt", "(", ")", ";", "String", "newCredentials", "=", "Encoder", ".", "encrypt", "(", "password", ",", "currentSalt", ",", "algorithm", ")", ";", "if", "(", "newCredentials", ".", "equals", "(", "authentication", ".", "getCredential", "(", ")", ")", ")", "{", "return", "authentication", ";", "}", "}", "String", "salt", "=", "algorithm", ".", "isSalted", "(", ")", "?", "Encoder", ".", "getSalt", "(", ")", ":", "null", ";", "String", "newCredentials", "=", "Encoder", ".", "encrypt", "(", "password", ",", "salt", ",", "algorithm", ")", ";", "authentication", ".", "setSalt", "(", "salt", ")", ";", "authentication", ".", "setCredential", "(", "newCredentials", ")", ";", "authentication", ".", "setAlgorithm", "(", "algorithm", ".", "name", "(", ")", ")", ";", "return", "updateAuthentication", "(", "authentication", ")", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#deleteAuthentication(org.olat.basesecurity.Authentication)\n\t */", "@", "Override", "public", "void", "deleteAuthentication", "(", "Authentication", "auth", ")", "{", "if", "(", "auth", "==", "null", "||", "auth", ".", "getKey", "(", ")", "==", "null", ")", "return", ";", "try", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select auth from ", "\"", ")", ".", "append", "(", "AuthenticationImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as auth", "\"", ")", ".", "append", "(", "\"", " where auth.key=:authKey", "\"", ")", ";", "AuthenticationImpl", "authRef", "=", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "find", "(", "AuthenticationImpl", ".", "class", ",", "auth", ".", "getKey", "(", ")", ")", ";", "if", "(", "authRef", "!=", "null", ")", "{", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "remove", "(", "authRef", ")", ";", "}", "}", "catch", "(", "EntityNotFoundException", "e", ")", "{", "log", ".", "error", "(", "\"", "\"", ",", "e", ")", ";", "}", "}", "/**\n\t * @see org.olat.basesecurity.Manager#findAuthenticationByAuthusername(java.lang.String, java.lang.String)\n\t */", "@", "Override", "public", "Authentication", "findAuthenticationByAuthusername", "(", "String", "authusername", ",", "String", "provider", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select auth from ", "\"", ")", ".", "append", "(", "AuthenticationImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as auth", "\"", ")", ".", "append", "(", "\"", " inner join fetch auth.identity ident", "\"", ")", ".", "append", "(", "\"", " where auth.provider=:provider and auth.authusername=:authusername", "\"", ")", ";", "List", "<", "Authentication", ">", "results", "=", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "Authentication", ".", "class", ")", ".", "setParameter", "(", "\"", "provider", "\"", ",", "provider", ")", ".", "setParameter", "(", "\"", "authusername", "\"", ",", "authusername", ")", ".", "getResultList", "(", ")", ";", "if", "(", "results", ".", "size", "(", ")", "==", "0", ")", "return", "null", ";", "if", "(", "results", ".", "size", "(", ")", "!=", "1", ")", "{", "throw", "new", "AssertException", "(", "\"", "more than one entry for the a given authusername and provider, should never happen (even db has a unique constraint on those columns combined) ", "\"", ")", ";", "}", "return", "results", ".", "get", "(", "0", ")", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#getVisibleIdentitiesByPowerSearch(java.lang.String, java.util.Map, boolean, org.olat.basesecurity.SecurityGroup[], org.olat.basesecurity.PermissionOnResourceable[], java.lang.String[], java.util.Date, java.util.Date)\n\t */", "@", "Override", "public", "List", "<", "Identity", ">", "getVisibleIdentitiesByPowerSearch", "(", "String", "login", ",", "Map", "<", "String", ",", "String", ">", "userproperties", ",", "boolean", "userPropertiesAsIntersectionSearch", ",", "SecurityGroup", "[", "]", "groups", ",", "PermissionOnResourceable", "[", "]", "permissionOnResources", ",", "String", "[", "]", "authProviders", ",", "Date", "createdAfter", ",", "Date", "createdBefore", ")", "{", "return", "getIdentitiesByPowerSearch", "(", "new", "SearchIdentityParams", "(", "login", ",", "userproperties", ",", "userPropertiesAsIntersectionSearch", ",", "groups", ",", "permissionOnResources", ",", "authProviders", ",", "createdAfter", ",", "createdBefore", ",", "null", ",", "null", ",", "Identity", ".", "STATUS_VISIBLE_LIMIT", ")", ",", "0", ",", "-", "1", ")", ";", "}", "@", "Override", "public", "List", "<", "Identity", ">", "getVisibleIdentitiesByPowerSearch", "(", "String", "login", ",", "Map", "<", "String", ",", "String", ">", "userProperties", ",", "boolean", "userPropertiesAsIntersectionSearch", ",", "SecurityGroup", "[", "]", "groups", ",", "PermissionOnResourceable", "[", "]", "permissionOnResources", ",", "String", "[", "]", "authProviders", ",", "Date", "createdAfter", ",", "Date", "createdBefore", ",", "int", "firstResult", ",", "int", "maxResults", ")", "{", "return", "getIdentitiesByPowerSearch", "(", "new", "SearchIdentityParams", "(", "login", ",", "userProperties", ",", "userPropertiesAsIntersectionSearch", ",", "groups", ",", "permissionOnResources", ",", "authProviders", ",", "createdAfter", ",", "createdBefore", ",", "null", ",", "null", ",", "Identity", ".", "STATUS_VISIBLE_LIMIT", ")", ",", "firstResult", ",", "maxResults", ")", ";", "}", "@", "Override", "public", "long", "countIdentitiesByPowerSearch", "(", "String", "login", ",", "Map", "<", "String", ",", "String", ">", "userproperties", ",", "boolean", "userPropertiesAsIntersectionSearch", ",", "SecurityGroup", "[", "]", "groups", ",", "PermissionOnResourceable", "[", "]", "permissionOnResources", ",", "String", "[", "]", "authProviders", ",", "Date", "createdAfter", ",", "Date", "createdBefore", ",", "Date", "userLoginAfter", ",", "Date", "userLoginBefore", ",", "Integer", "status", ")", "{", "DBQuery", "dbq", "=", "createIdentitiesByPowerQuery", "(", "new", "SearchIdentityParams", "(", "login", ",", "userproperties", ",", "userPropertiesAsIntersectionSearch", ",", "groups", ",", "permissionOnResources", ",", "authProviders", ",", "createdAfter", ",", "createdBefore", ",", "userLoginAfter", ",", "userLoginBefore", ",", "status", ")", ",", "true", ")", ";", "Number", "count", "=", "(", "Number", ")", "dbq", ".", "uniqueResult", "(", ")", ";", "return", "count", ".", "longValue", "(", ")", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#getIdentitiesByPowerSearch(java.lang.String, java.util.Map, boolean, org.olat.basesecurity.SecurityGroup[], org.olat.basesecurity.PermissionOnResourceable[], java.lang.String[], java.util.Date, java.util.Date, java.lang.Integer)\n */", "@", "Override", "public", "List", "<", "Identity", ">", "getIdentitiesByPowerSearch", "(", "String", "login", ",", "Map", "<", "String", ",", "String", ">", "userproperties", ",", "boolean", "userPropertiesAsIntersectionSearch", ",", "SecurityGroup", "[", "]", "groups", ",", "PermissionOnResourceable", "[", "]", "permissionOnResources", ",", "String", "[", "]", "authProviders", ",", "Date", "createdAfter", ",", "Date", "createdBefore", ",", "Date", "userLoginAfter", ",", "Date", "userLoginBefore", ",", "Integer", "status", ")", "{", "DBQuery", "dbq", "=", "createIdentitiesByPowerQuery", "(", "new", "SearchIdentityParams", "(", "login", ",", "userproperties", ",", "userPropertiesAsIntersectionSearch", ",", "groups", ",", "permissionOnResources", ",", "authProviders", ",", "createdAfter", ",", "createdBefore", ",", "userLoginAfter", ",", "userLoginBefore", ",", "status", ")", ",", "false", ")", ";", "return", "dbq", ".", "list", "(", ")", ";", "}", "@", "Override", "public", "int", "countIdentitiesByPowerSearch", "(", "SearchIdentityParams", "params", ")", "{", "DBQuery", "dbq", "=", "createIdentitiesByPowerQuery", "(", "params", ",", "true", ")", ";", "Number", "count", "=", "(", "Number", ")", "dbq", ".", "uniqueResult", "(", ")", ";", "return", "count", ".", "intValue", "(", ")", ";", "}", "@", "Override", "public", "List", "<", "Identity", ">", "getIdentitiesByPowerSearch", "(", "SearchIdentityParams", "params", ",", "int", "firstResult", ",", "int", "maxResults", ")", "{", "DBQuery", "dbq", "=", "createIdentitiesByPowerQuery", "(", "params", ",", "false", ")", ";", "if", "(", "firstResult", ">=", "0", ")", "{", "dbq", ".", "setFirstResult", "(", "firstResult", ")", ";", "}", "if", "(", "maxResults", ">", "0", ")", "{", "dbq", ".", "setMaxResults", "(", "maxResults", ")", ";", "}", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "List", "<", "Identity", ">", "identities", "=", "dbq", ".", "list", "(", ")", ";", "return", "identities", ";", "}", "private", "DBQuery", "createIdentitiesByPowerQuery", "(", "SearchIdentityParams", "params", ",", "boolean", "count", ")", "{", "boolean", "hasGroups", "=", "(", "params", ".", "getGroups", "(", ")", "!=", "null", "&&", "params", ".", "getGroups", "(", ")", ".", "length", ">", "0", ")", ";", "boolean", "hasPermissionOnResources", "=", "(", "params", ".", "getPermissionOnResources", "(", ")", "!=", "null", "&&", "params", ".", "getPermissionOnResources", "(", ")", ".", "length", ">", "0", ")", ";", "boolean", "hasAuthProviders", "=", "(", "params", ".", "getAuthProviders", "(", ")", "!=", "null", "&&", "params", ".", "getAuthProviders", "(", ")", ".", "length", ">", "0", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "5000", ")", ";", "if", "(", "hasAuthProviders", ")", "{", "if", "(", "count", ")", "{", "sb", ".", "append", "(", "\"", "select count(distinct ident.key) from org.olat.basesecurity.AuthenticationImpl as auth ", "\"", ")", ".", "append", "(", "\"", " right join auth.identity as ident", "\"", ")", ".", "append", "(", "\"", " inner join ident.user as user ", "\"", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"", "select distinct ident from org.olat.basesecurity.AuthenticationImpl as auth ", "\"", ")", ".", "append", "(", "\"", " right join auth.identity as ident", "\"", ")", ".", "append", "(", "\"", " inner join fetch ident.user as user ", "\"", ")", ";", "}", "}", "else", "{", "if", "(", "count", ")", "{", "sb", ".", "append", "(", "\"", "select count(distinct ident.key) from org.olat.core.id.Identity as ident ", "\"", ")", ".", "append", "(", "\"", " inner join ident.user as user ", "\"", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"", "select distinct ident from org.olat.core.id.Identity as ident ", "\"", ")", ".", "append", "(", "\"", " inner join fetch ident.user as user ", "\"", ")", ";", "}", "}", "if", "(", "hasGroups", ")", "{", "sb", ".", "append", "(", "\"", " ,org.olat.basesecurity.SecurityGroupMembershipImpl as sgmsi ", "\"", ")", ";", "}", "if", "(", "hasPermissionOnResources", ")", "{", "sb", ".", "append", "(", "\"", " ,org.olat.basesecurity.SecurityGroupMembershipImpl as policyGroupMembership ", "\"", ")", ";", "sb", ".", "append", "(", "\"", " ,org.olat.basesecurity.PolicyImpl as policy ", "\"", ")", ";", "sb", ".", "append", "(", "\"", " ,org.olat.resource.OLATResourceImpl as resource ", "\"", ")", ";", "}", "String", "login", "=", "params", ".", "getLogin", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "userproperties", "=", "params", ".", "getUserProperties", "(", ")", ";", "Date", "createdAfter", "=", "params", ".", "getCreatedAfter", "(", ")", ";", "Date", "createdBefore", "=", "params", ".", "getCreatedBefore", "(", ")", ";", "Integer", "status", "=", "params", ".", "getStatus", "(", ")", ";", "Collection", "<", "Long", ">", "identityKeys", "=", "params", ".", "getIdentityKeys", "(", ")", ";", "Boolean", "managed", "=", "params", ".", "getManaged", "(", ")", ";", "if", "(", "login", "!=", "null", "||", "(", "userproperties", "!=", "null", "&&", "!", "userproperties", ".", "isEmpty", "(", ")", ")", "||", "(", "identityKeys", "!=", "null", "&&", "!", "identityKeys", ".", "isEmpty", "(", ")", ")", "||", "createdAfter", "!=", "null", "||", "createdBefore", "!=", "null", "||", "hasAuthProviders", "||", "hasGroups", "||", "hasPermissionOnResources", "||", "status", "!=", "null", "||", "managed", "!=", "null", ")", "{", "sb", ".", "append", "(", "\"", " where ", "\"", ")", ";", "boolean", "needsAnd", "=", "false", ";", "boolean", "needsUserPropertiesJoin", "=", "false", ";", "if", "(", "login", "!=", "null", "&&", "(", "userproperties", "!=", "null", "&&", "!", "userproperties", ".", "isEmpty", "(", ")", ")", ")", "{", "sb", ".", "append", "(", "\"", " ( ", "\"", ")", ";", "}", "if", "(", "login", "!=", "null", ")", "{", "login", "=", "makeFuzzyQueryString", "(", "login", ")", ";", "if", "(", "login", ".", "contains", "(", "\"", "_", "\"", ")", "&&", "dbVendor", ".", "equals", "(", "\"", "oracle", "\"", ")", ")", "{", "sb", ".", "append", "(", "\"", " lower(ident.name) like :login ESCAPE '", "\\\\", "'", "\"", ")", ";", "}", "else", "if", "(", "dbVendor", ".", "equals", "(", "\"", "mysql", "\"", ")", ")", "{", "sb", ".", "append", "(", "\"", " ident.name like :login", "\"", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"", " lower(ident.name) like :login", "\"", ")", ";", "}", "needsUserPropertiesJoin", "=", "true", ";", "needsAnd", "=", "true", ";", "}", "if", "(", "userproperties", "!=", "null", "&&", "!", "userproperties", ".", "isEmpty", "(", ")", ")", "{", "Map", "<", "String", ",", "String", ">", "emailProperties", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "otherProperties", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "for", "(", "String", "key", ":", "userproperties", ".", "keySet", "(", ")", ")", "{", "if", "(", "key", ".", "toLowerCase", "(", ")", ".", "contains", "(", "\"", "email", "\"", ")", ")", "{", "emailProperties", ".", "put", "(", "key", ",", "userproperties", ".", "get", "(", "key", ")", ")", ";", "}", "else", "{", "otherProperties", ".", "put", "(", "key", ",", "userproperties", ".", "get", "(", "key", ")", ")", ";", "}", "}", "if", "(", "!", "emailProperties", ".", "isEmpty", "(", ")", ")", "{", "needsUserPropertiesJoin", "=", "checkIntersectionInUserProperties", "(", "sb", ",", "needsUserPropertiesJoin", ",", "params", ".", "isUserPropertiesAsIntersectionSearch", "(", ")", ")", ";", "boolean", "moreThanOne", "=", "emailProperties", ".", "size", "(", ")", ">", "1", ";", "if", "(", "moreThanOne", ")", "sb", ".", "append", "(", "\"", "(", "\"", ")", ";", "boolean", "needsOr", "=", "false", ";", "for", "(", "String", "key", ":", "emailProperties", ".", "keySet", "(", ")", ")", "{", "if", "(", "needsOr", ")", "sb", ".", "append", "(", "\"", " or ", "\"", ")", ";", "sb", ".", "append", "(", "\"", " exists (select prop", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", ".value from userproperty prop", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", " where ", "\"", ")", ".", "append", "(", "\"", " prop", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", ".propertyId.userId=user.key and prop", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", ".propertyId.name ='", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", "'", "\"", ")", ".", "append", "(", "\"", " and ", "\"", ")", ";", "if", "(", "dbVendor", ".", "equals", "(", "\"", "mysql", "\"", ")", ")", "{", "sb", ".", "append", "(", "\"", " prop", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", ".value like :", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", "_value ", "\"", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"", " lower(prop", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", ".value) like :", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", "_value ", "\"", ")", ";", "}", "if", "(", "dbVendor", ".", "equals", "(", "\"", "oracle", "\"", ")", ")", "{", "sb", ".", "append", "(", "\"", " escape '", "\\\\", "'", "\"", ")", ";", "}", "sb", ".", "append", "(", "\"", ")", "\"", ")", ";", "needsOr", "=", "true", ";", "}", "if", "(", "moreThanOne", ")", "sb", ".", "append", "(", "\"", ")", "\"", ")", ";", "emailProperties", ".", "clear", "(", ")", ";", "}", "for", "(", "String", "key", ":", "otherProperties", ".", "keySet", "(", ")", ")", "{", "needsUserPropertiesJoin", "=", "checkIntersectionInUserProperties", "(", "sb", ",", "needsUserPropertiesJoin", ",", "params", ".", "isUserPropertiesAsIntersectionSearch", "(", ")", ")", ";", "sb", ".", "append", "(", "\"", " exists (select prop", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", ".value from userproperty prop", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", " where ", "\"", ")", ".", "append", "(", "\"", " prop", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", ".propertyId.userId=user.key and prop", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", ".propertyId.name ='", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", "'", "\"", ")", ".", "append", "(", "\"", " and ", "\"", ")", ";", "if", "(", "dbVendor", ".", "equals", "(", "\"", "mysql", "\"", ")", ")", "{", "sb", ".", "append", "(", "\"", " prop", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", ".value like :", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", "_value ", "\"", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"", " lower(prop", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", ".value) like :", "\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"", "_value ", "\"", ")", ";", "}", "if", "(", "dbVendor", ".", "equals", "(", "\"", "oracle", "\"", ")", ")", "{", "sb", ".", "append", "(", "\"", " escape '", "\\\\", "'", "\"", ")", ";", "}", "sb", ".", "append", "(", "\"", ")", "\"", ")", ";", "needsAnd", "=", "true", ";", "}", "otherProperties", ".", "clear", "(", ")", ";", "needsAnd", "=", "true", ";", "}", "if", "(", "login", "!=", "null", "&&", "(", "userproperties", "!=", "null", "&&", "!", "userproperties", ".", "isEmpty", "(", ")", ")", ")", "{", "sb", ".", "append", "(", "\"", " ) ", "\"", ")", ";", "}", "if", "(", "identityKeys", "!=", "null", "&&", "!", "identityKeys", ".", "isEmpty", "(", ")", ")", "{", "needsAnd", "=", "checkAnd", "(", "sb", ",", "needsAnd", ")", ";", "sb", ".", "append", "(", "\"", "ident.key in (:identityKeys)", "\"", ")", ";", "}", "if", "(", "managed", "!=", "null", ")", "{", "needsAnd", "=", "checkAnd", "(", "sb", ",", "needsAnd", ")", ";", "if", "(", "managed", ".", "booleanValue", "(", ")", ")", "{", "sb", ".", "append", "(", "\"", "ident.externalId is not null", "\"", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"", "ident.externalId is null", "\"", ")", ";", "}", "}", "if", "(", "hasGroups", ")", "{", "SecurityGroup", "[", "]", "groups", "=", "params", ".", "getGroups", "(", ")", ";", "needsAnd", "=", "checkAnd", "(", "sb", ",", "needsAnd", ")", ";", "sb", ".", "append", "(", "\"", " (", "\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "groups", ".", "length", ";", "i", "++", ")", "{", "sb", ".", "append", "(", "\"", " sgmsi.securityGroup=:group_", "\"", ")", ".", "append", "(", "i", ")", ";", "if", "(", "i", "<", "(", "groups", ".", "length", "-", "1", ")", ")", "sb", ".", "append", "(", "\"", " or ", "\"", ")", ";", "}", "sb", ".", "append", "(", "\"", ") ", "\"", ")", ";", "sb", ".", "append", "(", "\"", " and sgmsi.identity=ident ", "\"", ")", ";", "}", "if", "(", "hasPermissionOnResources", ")", "{", "needsAnd", "=", "checkAnd", "(", "sb", ",", "needsAnd", ")", ";", "sb", ".", "append", "(", "\"", " (", "\"", ")", ";", "PermissionOnResourceable", "[", "]", "permissionOnResources", "=", "params", ".", "getPermissionOnResources", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "permissionOnResources", ".", "length", ";", "i", "++", ")", "{", "sb", ".", "append", "(", "\"", " (", "\"", ")", ";", "sb", ".", "append", "(", "\"", " policy.permission=:permission_", "\"", ")", ".", "append", "(", "i", ")", ";", "sb", ".", "append", "(", "\"", " and policy.olatResource = resource ", "\"", ")", ";", "sb", ".", "append", "(", "\"", " and resource.resId = :resourceId_", "\"", ")", ".", "append", "(", "i", ")", ";", "sb", ".", "append", "(", "\"", " and resource.resName = :resourceName_", "\"", ")", ".", "append", "(", "i", ")", ";", "sb", ".", "append", "(", "\"", " ) ", "\"", ")", ";", "if", "(", "i", "<", "(", "permissionOnResources", ".", "length", "-", "1", ")", ")", "sb", ".", "append", "(", "\"", " or ", "\"", ")", ";", "}", "sb", ".", "append", "(", "\"", ") ", "\"", ")", ";", "sb", ".", "append", "(", "\"", " and policy.securityGroup=policyGroupMembership.securityGroup ", "\"", ")", ";", "sb", ".", "append", "(", "\"", " and policyGroupMembership.identity=ident ", "\"", ")", ";", "}", "if", "(", "hasAuthProviders", ")", "{", "needsAnd", "=", "checkAnd", "(", "sb", ",", "needsAnd", ")", ";", "sb", ".", "append", "(", "\"", " (", "\"", ")", ";", "String", "[", "]", "authProviders", "=", "params", ".", "getAuthProviders", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "authProviders", ".", "length", ";", "i", "++", ")", "{", "if", "(", "authProviders", "[", "i", "]", "==", "null", ")", "{", "sb", ".", "append", "(", "\"", " auth is null ", "\"", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"", " auth.provider=:authProvider_", "\"", ")", ".", "append", "(", "i", ")", ";", "}", "if", "(", "i", "<", "(", "authProviders", ".", "length", "-", "1", ")", ")", "sb", ".", "append", "(", "\"", " or ", "\"", ")", ";", "}", "sb", ".", "append", "(", "\"", ") ", "\"", ")", ";", "}", "if", "(", "createdAfter", "!=", "null", ")", "{", "needsAnd", "=", "checkAnd", "(", "sb", ",", "needsAnd", ")", ";", "sb", ".", "append", "(", "\"", " ident.creationDate >= :createdAfter ", "\"", ")", ";", "}", "if", "(", "createdBefore", "!=", "null", ")", "{", "needsAnd", "=", "checkAnd", "(", "sb", ",", "needsAnd", ")", ";", "sb", ".", "append", "(", "\"", " ident.creationDate <= :createdBefore ", "\"", ")", ";", "}", "if", "(", "params", ".", "getUserLoginAfter", "(", ")", "!=", "null", ")", "{", "needsAnd", "=", "checkAnd", "(", "sb", ",", "needsAnd", ")", ";", "sb", ".", "append", "(", "\"", " ident.lastLogin >= :lastloginAfter ", "\"", ")", ";", "}", "if", "(", "params", ".", "getUserLoginBefore", "(", ")", "!=", "null", ")", "{", "needsAnd", "=", "checkAnd", "(", "sb", ",", "needsAnd", ")", ";", "sb", ".", "append", "(", "\"", " ident.lastLogin <= :lastloginBefore ", "\"", ")", ";", "}", "if", "(", "status", "!=", "null", ")", "{", "if", "(", "status", ".", "equals", "(", "Identity", ".", "STATUS_VISIBLE_LIMIT", ")", ")", "{", "needsAnd", "=", "checkAnd", "(", "sb", ",", "needsAnd", ")", ";", "sb", ".", "append", "(", "\"", " ident.status < :status ", "\"", ")", ";", "}", "else", "{", "needsAnd", "=", "checkAnd", "(", "sb", ",", "needsAnd", ")", ";", "sb", ".", "append", "(", "\"", " ident.status = :status ", "\"", ")", ";", "}", "}", "}", "String", "query", "=", "sb", ".", "toString", "(", ")", ";", "DB", "db", "=", "DBFactory", ".", "getInstance", "(", ")", ";", "DBQuery", "dbq", "=", "db", ".", "createQuery", "(", "query", ")", ";", "if", "(", "login", "!=", "null", ")", "{", "dbq", ".", "setString", "(", "\"", "login", "\"", ",", "login", ".", "toLowerCase", "(", ")", ")", ";", "}", "if", "(", "identityKeys", "!=", "null", "&&", "!", "identityKeys", ".", "isEmpty", "(", ")", ")", "{", "dbq", ".", "setParameterList", "(", "\"", "identityKeys", "\"", ",", "identityKeys", ")", ";", "}", "if", "(", "userproperties", "!=", "null", "&&", "!", "userproperties", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "String", "key", ":", "userproperties", ".", "keySet", "(", ")", ")", "{", "String", "value", "=", "userproperties", ".", "get", "(", "key", ")", ";", "value", "=", "makeFuzzyQueryString", "(", "value", ")", ";", "dbq", ".", "setString", "(", "key", "+", "\"", "_value", "\"", ",", "value", ".", "toLowerCase", "(", ")", ")", ";", "}", "}", "if", "(", "hasGroups", ")", "{", "SecurityGroup", "[", "]", "groups", "=", "params", ".", "getGroups", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "groups", ".", "length", ";", "i", "++", ")", "{", "SecurityGroupImpl", "group", "=", "(", "SecurityGroupImpl", ")", "groups", "[", "i", "]", ";", "dbq", ".", "setEntity", "(", "\"", "group_", "\"", "+", "i", ",", "group", ")", ";", "}", "}", "if", "(", "hasPermissionOnResources", ")", "{", "PermissionOnResourceable", "[", "]", "permissionOnResources", "=", "params", ".", "getPermissionOnResources", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "permissionOnResources", ".", "length", ";", "i", "++", ")", "{", "PermissionOnResourceable", "permissionOnResource", "=", "permissionOnResources", "[", "i", "]", ";", "dbq", ".", "setString", "(", "\"", "permission_", "\"", "+", "i", ",", "permissionOnResource", ".", "getPermission", "(", ")", ")", ";", "Long", "id", "=", "permissionOnResource", ".", "getOlatResourceable", "(", ")", ".", "getResourceableId", "(", ")", ";", "dbq", ".", "setLong", "(", "\"", "resourceId_", "\"", "+", "i", ",", "(", "id", "==", "null", "?", "0", ":", "id", ".", "longValue", "(", ")", ")", ")", ";", "dbq", ".", "setString", "(", "\"", "resourceName_", "\"", "+", "i", ",", "permissionOnResource", ".", "getOlatResourceable", "(", ")", ".", "getResourceableTypeName", "(", ")", ")", ";", "}", "}", "if", "(", "hasAuthProviders", ")", "{", "String", "[", "]", "authProviders", "=", "params", ".", "getAuthProviders", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "authProviders", ".", "length", ";", "i", "++", ")", "{", "String", "authProvider", "=", "authProviders", "[", "i", "]", ";", "if", "(", "authProvider", "!=", "null", ")", "{", "dbq", ".", "setString", "(", "\"", "authProvider_", "\"", "+", "i", ",", "authProvider", ")", ";", "}", "}", "}", "if", "(", "createdAfter", "!=", "null", ")", "{", "dbq", ".", "setDate", "(", "\"", "createdAfter", "\"", ",", "createdAfter", ")", ";", "}", "if", "(", "createdBefore", "!=", "null", ")", "{", "dbq", ".", "setDate", "(", "\"", "createdBefore", "\"", ",", "createdBefore", ")", ";", "}", "if", "(", "params", ".", "getUserLoginAfter", "(", ")", "!=", "null", ")", "{", "dbq", ".", "setDate", "(", "\"", "lastloginAfter", "\"", ",", "params", ".", "getUserLoginAfter", "(", ")", ")", ";", "}", "if", "(", "params", ".", "getUserLoginBefore", "(", ")", "!=", "null", ")", "{", "dbq", ".", "setDate", "(", "\"", "lastloginBefore", "\"", ",", "params", ".", "getUserLoginBefore", "(", ")", ")", ";", "}", "if", "(", "status", "!=", "null", ")", "{", "dbq", ".", "setInteger", "(", "\"", "status", "\"", ",", "status", ")", ";", "}", "return", "dbq", ";", "}", "/**\n\t * \n\t * @param dbVendor\n\t */", "public", "void", "setDbVendor", "(", "String", "dbVendor", ")", "{", "this", ".", "dbVendor", "=", "dbVendor", ";", "}", "/**\n * @see org.olat.basesecurity.Manager#isIdentityVisible(java.lang.String)\n */", "public", "boolean", "isIdentityVisible", "(", "String", "identityName", ")", "{", "if", "(", "identityName", "==", "null", ")", "throw", "new", "AssertException", "(", "\"", "findIdentitybyName: name was null", "\"", ")", ";", "String", "queryString", "=", "\"", "select count(ident) from org.olat.basesecurity.IdentityImpl as ident where ident.name = :identityName and ident.status < :status", "\"", ";", "DBQuery", "dbq", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "createQuery", "(", "queryString", ")", ";", "dbq", ".", "setString", "(", "\"", "identityName", "\"", ",", "identityName", ")", ";", "dbq", ".", "setInteger", "(", "\"", "status", "\"", ",", "Identity", ".", "STATUS_VISIBLE_LIMIT", ")", ";", "List", "res", "=", "dbq", ".", "list", "(", ")", ";", "Long", "cntL", "=", "(", "Long", ")", "res", ".", "get", "(", "0", ")", ";", "return", "(", "cntL", ".", "longValue", "(", ")", ">", "0", ")", ";", "}", "@", "Override", "public", "boolean", "isIdentityVisible", "(", "Identity", "identity", ")", "{", "if", "(", "identity", "==", "null", ")", "return", "false", ";", "Integer", "status", "=", "identity", ".", "getStatus", "(", ")", ";", "return", "(", "status", "!=", "null", "&&", "status", ".", "intValue", "(", ")", "<", "Identity", ".", "STATUS_VISIBLE_LIMIT", ")", ";", "}", "private", "boolean", "checkAnd", "(", "StringBuilder", "sb", ",", "boolean", "needsAnd", ")", "{", "if", "(", "needsAnd", ")", "sb", ".", "append", "(", "\"", " and ", "\"", ")", ";", "return", "true", ";", "}", "private", "boolean", "checkIntersectionInUserProperties", "(", "StringBuilder", "sb", ",", "boolean", "needsJoin", ",", "boolean", "userPropertiesAsIntersectionSearch", ")", "{", "if", "(", "needsJoin", ")", "{", "if", "(", "userPropertiesAsIntersectionSearch", ")", "{", "sb", ".", "append", "(", "\"", " and ", "\"", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"", " or ", "\"", ")", ";", "}", "}", "return", "true", ";", "}", "/**\n\t * Helper method that replaces * with % and appends and\n\t * prepends % to the string to make fuzzy SQL match when using like \n\t * @param email\n\t * @return fuzzized string\n\t */", "private", "String", "makeFuzzyQueryString", "(", "String", "string", ")", "{", "if", "(", "string", ".", "length", "(", ")", ">", "1", "&&", "string", ".", "startsWith", "(", "\"", "\\\"", "\"", ")", "&&", "string", ".", "endsWith", "(", "\"", "\\\"", "\"", ")", ")", "{", "string", "=", "string", ".", "substring", "(", "1", ",", "string", ".", "length", "(", ")", "-", "1", ")", ";", "}", "else", "{", "string", "=", "string", "+", "\"", "%", "\"", ";", "string", "=", "string", ".", "replace", "(", "'*'", ",", "'%'", ")", ";", "}", "string", "=", "string", ".", "replace", "(", "\"", "_", "\"", ",", "\"", "\\\\", "_", "\"", ")", ";", "return", "string", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#saveIdentityStatus(org.olat.core.id.Identity)\n\t */", "@", "Override", "public", "Identity", "saveIdentityStatus", "(", "Identity", "identity", ",", "Integer", "status", ")", "{", "Identity", "reloadedIdentity", "=", "loadForUpdate", "(", "identity", ")", ";", "reloadedIdentity", ".", "setStatus", "(", "status", ")", ";", "reloadedIdentity", "=", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "merge", "(", "reloadedIdentity", ")", ";", "dbInstance", ".", "commit", "(", ")", ";", "return", "reloadedIdentity", ";", "}", "@", "Override", "public", "Identity", "setIdentityLastLogin", "(", "Identity", "identity", ")", "{", "Identity", "reloadedIdentity", "=", "loadForUpdate", "(", "identity", ")", ";", "reloadedIdentity", ".", "setLastLogin", "(", "new", "Date", "(", ")", ")", ";", "reloadedIdentity", "=", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "merge", "(", "reloadedIdentity", ")", ";", "dbInstance", ".", "commit", "(", ")", ";", "return", "reloadedIdentity", ";", "}", "@", "Override", "public", "Identity", "saveIdentityName", "(", "Identity", "identity", ",", "String", "newName", ")", "{", "Identity", "reloadedIdentity", "=", "loadForUpdate", "(", "identity", ")", ";", "reloadedIdentity", ".", "setName", "(", "newName", ")", ";", "reloadedIdentity", "=", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "merge", "(", "reloadedIdentity", ")", ";", "dbInstance", ".", "commit", "(", ")", ";", "return", "reloadedIdentity", ";", "}", "@", "Override", "public", "Identity", "setExternalId", "(", "Identity", "identity", ",", "String", "externalId", ")", "{", "IdentityImpl", "reloadedIdentity", "=", "loadForUpdate", "(", "identity", ")", ";", "reloadedIdentity", ".", "setExternalId", "(", "externalId", ")", ";", "reloadedIdentity", "=", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "merge", "(", "reloadedIdentity", ")", ";", "dbInstance", ".", "commit", "(", ")", ";", "return", "reloadedIdentity", ";", "}", "/**\n\t * Don't forget to commit/roolback the transaction as soon as possible\n\t * @param identityKey\n\t * @return\n\t */", "private", "IdentityImpl", "loadForUpdate", "(", "Identity", "identity", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select id from ", "\"", ")", ".", "append", "(", "IdentityImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as id", "\"", ")", ".", "append", "(", "\"", " inner join fetch id.user user ", "\"", ")", ".", "append", "(", "\"", " where id.key=:identityKey", "\"", ")", ";", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "detach", "(", "identity", ")", ";", "List", "<", "IdentityImpl", ">", "identities", "=", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "IdentityImpl", ".", "class", ")", ".", "setParameter", "(", "\"", "identityKey", "\"", ",", "identity", ".", "getKey", "(", ")", ")", ".", "setLockMode", "(", "LockModeType", ".", "PESSIMISTIC_WRITE", ")", ".", "getResultList", "(", ")", ";", "if", "(", "identities", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "return", "identities", ".", "get", "(", "0", ")", ";", "}", "@", "Override", "public", "List", "<", "SecurityGroup", ">", "getSecurityGroupsForIdentity", "(", "Identity", "identity", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "select sgi from ", "\"", ")", ".", "append", "(", "SecurityGroupImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as sgi, ", "\"", ")", ".", "append", "(", "SecurityGroupMembershipImpl", ".", "class", ".", "getName", "(", ")", ")", ".", "append", "(", "\"", " as sgmsi ", "\"", ")", ".", "append", "(", "\"", " where sgmsi.securityGroup=sgi and sgmsi.identity.key=:identityKey", "\"", ")", ";", "List", "<", "SecurityGroup", ">", "secGroups", "=", "DBFactory", ".", "getInstance", "(", ")", ".", "getCurrentEntityManager", "(", ")", ".", "createQuery", "(", "sb", ".", "toString", "(", ")", ",", "SecurityGroup", ".", "class", ")", ".", "setParameter", "(", "\"", "identityKey", "\"", ",", "identity", ".", "getKey", "(", ")", ")", ".", "getResultList", "(", ")", ";", "return", "secGroups", ";", "}", "/**\n\t * @see org.olat.basesecurity.Manager#getAndUpdateAnonymousUserForLanguage(java.util.Locale)\n\t */", "public", "Identity", "getAndUpdateAnonymousUserForLanguage", "(", "Locale", "locale", ")", "{", "Translator", "trans", "=", "Util", ".", "createPackageTranslator", "(", "UserManager", ".", "class", ",", "locale", ")", ";", "String", "guestUsername", "=", "GUEST_USERNAME_PREFIX", "+", "locale", ".", "toString", "(", ")", ";", "Identity", "guestIdentity", "=", "findIdentityByName", "(", "guestUsername", ")", ";", "if", "(", "guestIdentity", "==", "null", ")", "{", "User", "guestUser", "=", "UserManager", ".", "getInstance", "(", ")", ".", "createUser", "(", "trans", ".", "translate", "(", "\"", "user.guest", "\"", ")", ",", "null", ",", "null", ")", ";", "guestUser", ".", "getPreferences", "(", ")", ".", "setLanguage", "(", "locale", ".", "toString", "(", ")", ")", ";", "guestIdentity", "=", "createAndPersistIdentityAndUser", "(", "guestUsername", ",", "null", ",", "guestUser", ",", "null", ",", "null", ",", "null", ")", ";", "SecurityGroup", "anonymousGroup", "=", "findSecurityGroupByName", "(", "Constants", ".", "GROUP_ANONYMOUS", ")", ";", "addIdentityToSecurityGroup", "(", "guestIdentity", ",", "anonymousGroup", ")", ";", "}", "else", "if", "(", "!", "guestIdentity", ".", "getUser", "(", ")", ".", "getProperty", "(", "UserConstants", ".", "FIRSTNAME", ",", "locale", ")", ".", "equals", "(", "trans", ".", "translate", "(", "\"", "user.guest", "\"", ")", ")", ")", "{", "guestIdentity", ".", "getUser", "(", ")", ".", "setProperty", "(", "UserConstants", ".", "FIRSTNAME", ",", "trans", ".", "translate", "(", "\"", "user.guest", "\"", ")", ")", ";", "guestIdentity", "=", "dbInstance", ".", "getCurrentEntityManager", "(", ")", ".", "merge", "(", "guestIdentity", ")", ";", "}", "return", "guestIdentity", ";", "}", "}" ]
<h3>Description:</h3> The PersistingManager implements the security manager and provide methods to manage identities and user objects based on a database persistence mechanism using hibernate.
[ "<h3", ">", "Description", ":", "<", "/", "h3", ">", "The", "PersistingManager", "implements", "the", "security", "manager", "and", "provide", "methods", "to", "manage", "identities", "and", "user", "objects", "based", "on", "a", "database", "persistence", "mechanism", "using", "hibernate", "." ]
[ "// called only once at startup and only from one thread", "// init the system level groups and its policies", "// we check everthing by policies, so we must give admins the hasRole", "// permission on the type resource \"Admin\"", "//admins have role \"authors\" by default", "//admins have a groupmanager policy and access permissions to groupmanaging tools", "//admins have a usemanager policy and access permissions to usermanagement tools", "//admins are also regular users", "//olat admins have access to all security groups", "// and to all courses", "// and to pool admiistration", "//users have a user policy", "//gropumanagers have a groupmanager policy and access permissions to groupmanaging tools", "//pools managers have a goupmanager policy and access permissions to groupmanaging tools", "//gropumanagers have a groupmanager policy and access permissions to groupmanaging tools", "//authors have a author policy and access permissions to authoring tools", "//manager have a author policy and access permissions to authoring tools", "//guest(=anonymous) have a guest policy", "//no identity, no permission", "//TODO: make a method in", "// OLATResorceManager, since this", "// is implementation detail", "// if the olatResourceable is not persisted as OLATResource, then the answer", "// is false,", "// therefore we can use the query assuming there is an OLATResource", "// system users - opposite of anonymous users", "// author", "// user manager, only allowed by admin", "// institutional resource manager", "// institutional resource manager", "// system administrator", "// user not yet in security group, add him", "// user not anymore in security group, remove him", "// we do not use hibernate cascade=\"delete\", but implement our own (to be", "// sure to understand our code)", "//FIXME: fj: Please review: Create rep entry, restart olat, delete the rep", "// entry. previous implementation resulted in orange screen", "// secGroup = (SecurityGroup)db.loadObject(secGroup); // so we can later", "// delete it (hibernate needs an associated session)", "//o_clusterREVIEW", "//db.reputInHibernateSessionCache(secGroup);", "// 1) delete associated users (need to do it manually, hibernate knows", "// nothing about", "// the membership, modeled manually via many-to-one and not via set)", "// 2) delete all policies", "// 3) delete security group", "//nothing to do", "//nothing to do", "// when no password is used the provider must be set to null to not generate", "// an OLAT authentication token. See method doku.", "// Add user to system users group", "// Add user to system users group", "//Save the identity on the DB. So can the listeners of the event retrieve it", "//in cluster mode", "//default initializations", "// institutional identifier", "//check for unique search result", "// search for all status smaller than visible limit ", "// search for certain status", "//check if update is needed", "//same credentials", "//nothing to do", "// select identity and inner join with user to optimize query", "// I know, it looks wrong but I need to do the join reversed since it is not possible to ", "// do this query with a left join that starts with the identity using hibernate HQL. A left", "// or right join is necessary since it is totally ok to have null values as authentication", "// providers (e.g. when searching for users that do not have any authentication providers at all!).", "// It took my quite a while to make this work, so think twice before you change anything here!", "// In any case join with the user. Don't join-fetch user, this breaks the query", "// because of the user fields (don't know exactly why this behaves like", "// this)", "// join over security group memberships", "// join over policies", "// complex where clause only when values are available", "// treat login and userProperties as one element in this query", "// append query for login", "//oracle needs special ESCAPE sequence to search for escaped strings", "// if user fields follow a join element is needed", "// at least one user field used, after this and is required", "// append queries for user fields", "// split the user fields into two groups", "// handle email fields special: search in all email fields", "// cleanup", "// add other fields", "// cleanup", "// at least one user field used, after this and is required", "// end of user fields and login part", "// now continue with the other elements. They are joined with an AND connection", "// append query for identity primary keys", "// append query for named security groups", "// append query for policies", "// append query for authentication providers", "// special case for null auth provider", "// append query for creation date restrictions", "// search for all status smaller than visible limit ", "// search for certain status", "// create query object now from string", "// add user attributes", "//\t add user properties attributes", "// add named security group names", "// need to work with impls", "// add policies", "// add authentication providers", "// ignore null auth provider, already set to null in query", "// add date restrictions", "// execute query", "// By default only fuzzyfy at the end. Usually it makes no sense to do a", "// fuzzy search with % at the beginning, but it makes the query very very", "// slow since it can not use any index and must perform a fulltext search.", "// User can always use * to make it a really fuzzy search query", "// fxdiff FXOLAT-252: use \"\" to disable this feature and use exact match", "// with 'LIKE' the character '_' is a wildcard which matches exactly one character.", "// To test for literal instances of '_', we have to escape it.", "// Create it lazy on demand", "//Check if guest name has been updated in the i18n tool" ]
[ { "param": "BaseSecurity", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseSecurity", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69c4049e33312b3a2e7ee4590802477012303d52
mbari-media-management/vars-kb
org.mbari.kb.jpa/src/test/java/org/mbari/kb/jpa/knowledgebase/KBCrudTest.java
[ "Apache-2.0" ]
Java
KBCrudTest
/** * Created by IntelliJ IDEA. User: brian Date: Aug 12, 2009 Time: 11:42:53 AM To * change this template use File | Settings | File Templates. */
Created by IntelliJ IDEA.
[ "Created", "by", "IntelliJ", "IDEA", "." ]
@TestInstance(Lifecycle.PER_CLASS) public class KBCrudTest { public final Logger log = LoggerFactory.getLogger(getClass()); KnowledgebaseDAOFactory daoFactory; KnowledgebaseFactory kbFactory; KnowledgebaseTestObjectFactory testObjectFactory; EntityUtilities entityUtilities; @BeforeAll public void setup() { Factories factories = new Factories(DerbyTestDAOFactory.newEntityManagerFactory()); kbFactory = factories.getKnowledgebaseFactory(); testObjectFactory = new KnowledgebaseTestObjectFactory(kbFactory); daoFactory = factories.getKnowledgebaseDAOFactory(); entityUtilities = new EntityUtilities(); ConceptDAO dao = daoFactory.newConceptDAO(); dao.startTransaction(); Concept concept = dao.findRoot(); dao.endTransaction(); if (concept != null) { dao.cascadeRemove(concept); } dao.close(); } @Test public void bigTest() { log.info("---------- TEST: bigTest ----------"); Concept c = testObjectFactory.makeObjectGraph("bigTest", 4); ConceptDAO dao = daoFactory.newConceptDAO(); // log.info("KNOWLEDGEBASE TREE BEFORE TEST:\n" + // entityUtilities.buildTextTree(c)); dao.startTransaction(); dao.persist(c); dao.endTransaction(); Long cId = ((JPAEntity) c).getId(); Assertions.assertNotNull(cId, "Primary Key [ID] was not set!"); dao.startTransaction(); c = dao.findByPrimaryKey(c.getClass(), ((JPAEntity) c).getId()); dao.endTransaction(); Assertions.assertTrue(PrimaryKeyUtilities.checkDbForAllPks(PrimaryKeyUtilities.primaryKeyMap(c), (DAO) dao), "Not all objects were inserted"); // log.info("KNOWLEDGEBASE TREE AFTER INSERT:\n" + // entityUtilities.buildTextTree(c)); // Exercise the DAO methods dao.startTransaction(); Concept root = dao.findRoot(); dao.endTransaction(); Assertions.assertNotNull(root, "Whoops, couldn't get root"); dao.cascadeRemove(root); dao.startTransaction(); c = dao.findByPrimaryKey(c.getClass(), cId); dao.endTransaction(); Assertions.assertNull(c, "Whoops!! We can still lookup the entity after deleteing it"); } @Test public void incrementalBuildAndDeleteByConcept() { log.info("---------- TEST: incrementalBuildAndDeleteByConcept ----------"); ConceptDAO dao = daoFactory.newConceptDAO(); setup: { Concept root = testObjectFactory.makeConcept("__ROOT__"); root.getPrimaryConceptName().setName("__ROOT__"); dao.startTransaction(); dao.persist(root); dao.endTransaction(); // log.info("BUILDING KNOWLEDGEBASE TREE:\n" + // entityUtilities.buildTextTree(root)); // ---- Step 1: Build up each node in the database log.info("---------- Add 2A ----------"); Concept concept2A = testObjectFactory.makeConcept("LEVEL 2 A"); concept2A.getPrimaryConceptName().setName("2A"); dao.startTransaction(); root = dao.findRoot(); root.addChildConcept(concept2A); dao.persist(concept2A); dao.endTransaction(); // log.info("BUILDING KNOWLEDGEBASE TREE:\n" + // entityUtilities.buildTextTree(root)); log.info("---------- Add 3AA and 3AB ----------"); Concept concept3AA = testObjectFactory.makeConcept("LEVEL 3 A A"); concept3AA.getPrimaryConceptName().setName("3AA"); dao.startTransaction(); concept2A = dao.findByName(concept2A.getPrimaryConceptName().getName()); concept2A.addChildConcept(concept3AA); dao.persist(concept3AA); Concept concept3AB = testObjectFactory.makeConcept("LEVEL 3 A B"); concept3AB.getPrimaryConceptName().setName("3AB"); concept2A.addChildConcept(concept3AB); dao.persist(concept3AB); dao.endTransaction(); // log.info("BUILDING KNOWLEDGEBASE TREE:\n" + // entityUtilities.buildTextTree(root)); log.info("---------- Add 4A ----------"); Concept concept4A = testObjectFactory.makeConcept("LEVEL 4 A"); concept4A.getPrimaryConceptName().setName("4A"); dao.startTransaction(); concept3AA = dao.findByName("3AA"); concept3AA.addChildConcept(concept4A); dao.persist(concept4A); dao.endTransaction(); // log.info("BUILDING KNOWLEDGEBASE TREE:\n" + // entityUtilities.buildTextTree(root)); log.info("---------- Add 2B ----------"); Concept concept2B = testObjectFactory.makeConcept("LEVEL 2 B"); dao.startTransaction(); root = dao.findRoot(); concept2B.getPrimaryConceptName().setName("2B"); root.addChildConcept(concept2B); dao.persist(concept2B); dao.endTransaction(); // log.info("BUILDING KNOWLEDGEBASE TREE:\n" + // entityUtilities.buildTextTree(root)); } // ---- Step 2: Let's look up the references form the database so that we have // the correct entities execute: { dao.startTransaction(); Concept root = dao.findByName("__ROOT__"); Concept concept2B = dao.findByName("2B"); Concept concept3AB = dao.findByName("3AB"); Concept concept3AA = dao.findByName("3AA"); // Tear down each node in the database log.info("---------- Remove 2B ----------"); concept2B.getParentConcept().removeChildConcept(concept2B); dao.remove(concept2B); // log.info("---------- Remove 3AB ----------"); concept3AB.getParentConcept().removeChildConcept(concept3AB); dao.remove(concept3AB); dao.endTransaction(); log.info("---------- Remove 3AA ----------"); dao.startTransaction(); dao.merge(concept3AA); concept3AA.getParentConcept().removeChildConcept(concept3AA); dao.endTransaction(); dao.cascadeRemove(concept3AA); dao.startTransaction(); root = dao.findByPrimaryKey(root.getClass(), ((JPAEntity) root).getId()); dao.endTransaction(); // log.info("KNOWLEDGEBASE TREE:\n" + entityUtilities.buildTextTree(root)); log.info("---------- Remove __ROOT__ ----------"); dao.cascadeRemove(root); } } @Test public void bottomUpDelete() { log.info("---------- TEST: bottomUpDelete ----------"); Concept concept = testObjectFactory.makeObjectGraph("BIG-TEST", 1); ConceptDAO dao = daoFactory.newConceptDAO(); dao.startTransaction(); dao.persist(concept); dao.endTransaction(); final Collection<History> histories = new ArrayList<History>(); final Collection<Media> medias = new ArrayList<Media>(); final Collection<LinkTemplate> linkTemplates = new ArrayList<LinkTemplate>(); final Collection<LinkRealization> linkRealizations = new ArrayList<LinkRealization>(); /* * Handy 'Closure' to do all the dirty work of recursively filling in the * collections for us */ class Collector { void collect(Concept c) { ConceptMetadata metadata = c.getConceptMetadata(); histories.addAll(metadata.getHistories()); medias.addAll(metadata.getMedias()); linkTemplates.addAll(metadata.getLinkTemplates()); linkRealizations.addAll(metadata.getLinkRealizations()); for (Concept child : c.getChildConcepts()) { collect(child); } } } Collector collector = new Collector(); collector.collect(concept); // log.info("KNOWLEDGEBASE TREE AFTER INITIAL INSERT:\n" + // entityUtilities.buildTextTree(concept)); dao.startTransaction(); for (LinkRealization linkRealization : linkRealizations) { linkRealization.getConceptMetadata().removeLinkRealization(linkRealization); dao.remove(linkRealization); } dao.endTransaction(); // log.info("KNOWLEDGEBASE TREE AFTER LINKREALIZATION DELETE:\n" + // entityUtilities.buildTextTree(concept)); dao.startTransaction(); for (LinkTemplate linkTemplate : linkTemplates) { linkTemplate.getConceptMetadata().removeLinkTemplate(linkTemplate); dao.remove(linkTemplate); } dao.endTransaction(); // log.info("KNOWLEDGEBASE TREE AFTER LINKTEMPLATE DELETE:\n" + // entityUtilities.buildTextTree(concept)); dao.startTransaction(); for (Media media : medias) { media.getConceptMetadata().removeMedia(media); dao.remove(media); } dao.endTransaction(); // log.info("KNOWLEDGEBASE TREE AFTER MEDIA DELETE:\n" + // entityUtilities.buildTextTree(concept)); dao.startTransaction(); for (History history : histories) { history.getConceptMetadata().removeHistory(history); dao.remove(history); } dao.endTransaction(); // log.info("KNOWLEDGEBASE TREE AFTER HISTORY DELETE:\n" + // entityUtilities.buildTextTree(concept)); dao.cascadeRemove(concept); } @AfterAll public void cleanup() { ConceptDAO dao = daoFactory.newConceptDAO(); dao.startTransaction(); Concept concept = dao.findRoot(); dao.endTransaction(); if (concept != null) { dao.cascadeRemove(concept); } dao.close(); Collection<Concept> badData = daoFactory.newConceptDAO().findAll(); if (badData.size() > 0) { // String s = "Concepts that shouldn't still be in the database:\n"; // for (Concept c : badData) { // s += "\n" + entityUtilities.buildTextTree(c) + "\n"; // } // log.info(s); log.info("There are " + badData.size() + " concepts that are still in the knowledgebase that shouldn't be there."); } } }
[ "@", "TestInstance", "(", "Lifecycle", ".", "PER_CLASS", ")", "public", "class", "KBCrudTest", "{", "public", "final", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "getClass", "(", ")", ")", ";", "KnowledgebaseDAOFactory", "daoFactory", ";", "KnowledgebaseFactory", "kbFactory", ";", "KnowledgebaseTestObjectFactory", "testObjectFactory", ";", "EntityUtilities", "entityUtilities", ";", "@", "BeforeAll", "public", "void", "setup", "(", ")", "{", "Factories", "factories", "=", "new", "Factories", "(", "DerbyTestDAOFactory", ".", "newEntityManagerFactory", "(", ")", ")", ";", "kbFactory", "=", "factories", ".", "getKnowledgebaseFactory", "(", ")", ";", "testObjectFactory", "=", "new", "KnowledgebaseTestObjectFactory", "(", "kbFactory", ")", ";", "daoFactory", "=", "factories", ".", "getKnowledgebaseDAOFactory", "(", ")", ";", "entityUtilities", "=", "new", "EntityUtilities", "(", ")", ";", "ConceptDAO", "dao", "=", "daoFactory", ".", "newConceptDAO", "(", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "Concept", "concept", "=", "dao", ".", "findRoot", "(", ")", ";", "dao", ".", "endTransaction", "(", ")", ";", "if", "(", "concept", "!=", "null", ")", "{", "dao", ".", "cascadeRemove", "(", "concept", ")", ";", "}", "dao", ".", "close", "(", ")", ";", "}", "@", "Test", "public", "void", "bigTest", "(", ")", "{", "log", ".", "info", "(", "\"", "---------- TEST: bigTest ----------", "\"", ")", ";", "Concept", "c", "=", "testObjectFactory", ".", "makeObjectGraph", "(", "\"", "bigTest", "\"", ",", "4", ")", ";", "ConceptDAO", "dao", "=", "daoFactory", ".", "newConceptDAO", "(", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "dao", ".", "persist", "(", "c", ")", ";", "dao", ".", "endTransaction", "(", ")", ";", "Long", "cId", "=", "(", "(", "JPAEntity", ")", "c", ")", ".", "getId", "(", ")", ";", "Assertions", ".", "assertNotNull", "(", "cId", ",", "\"", "Primary Key [ID] was not set!", "\"", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "c", "=", "dao", ".", "findByPrimaryKey", "(", "c", ".", "getClass", "(", ")", ",", "(", "(", "JPAEntity", ")", "c", ")", ".", "getId", "(", ")", ")", ";", "dao", ".", "endTransaction", "(", ")", ";", "Assertions", ".", "assertTrue", "(", "PrimaryKeyUtilities", ".", "checkDbForAllPks", "(", "PrimaryKeyUtilities", ".", "primaryKeyMap", "(", "c", ")", ",", "(", "DAO", ")", "dao", ")", ",", "\"", "Not all objects were inserted", "\"", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "Concept", "root", "=", "dao", ".", "findRoot", "(", ")", ";", "dao", ".", "endTransaction", "(", ")", ";", "Assertions", ".", "assertNotNull", "(", "root", ",", "\"", "Whoops, couldn't get root", "\"", ")", ";", "dao", ".", "cascadeRemove", "(", "root", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "c", "=", "dao", ".", "findByPrimaryKey", "(", "c", ".", "getClass", "(", ")", ",", "cId", ")", ";", "dao", ".", "endTransaction", "(", ")", ";", "Assertions", ".", "assertNull", "(", "c", ",", "\"", "Whoops!! We can still lookup the entity after deleteing it", "\"", ")", ";", "}", "@", "Test", "public", "void", "incrementalBuildAndDeleteByConcept", "(", ")", "{", "log", ".", "info", "(", "\"", "---------- TEST: incrementalBuildAndDeleteByConcept ----------", "\"", ")", ";", "ConceptDAO", "dao", "=", "daoFactory", ".", "newConceptDAO", "(", ")", ";", "setup", ":", "{", "Concept", "root", "=", "testObjectFactory", ".", "makeConcept", "(", "\"", "__ROOT__", "\"", ")", ";", "root", ".", "getPrimaryConceptName", "(", ")", ".", "setName", "(", "\"", "__ROOT__", "\"", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "dao", ".", "persist", "(", "root", ")", ";", "dao", ".", "endTransaction", "(", ")", ";", "log", ".", "info", "(", "\"", "---------- Add 2A ----------", "\"", ")", ";", "Concept", "concept2A", "=", "testObjectFactory", ".", "makeConcept", "(", "\"", "LEVEL 2 A", "\"", ")", ";", "concept2A", ".", "getPrimaryConceptName", "(", ")", ".", "setName", "(", "\"", "2A", "\"", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "root", "=", "dao", ".", "findRoot", "(", ")", ";", "root", ".", "addChildConcept", "(", "concept2A", ")", ";", "dao", ".", "persist", "(", "concept2A", ")", ";", "dao", ".", "endTransaction", "(", ")", ";", "log", ".", "info", "(", "\"", "---------- Add 3AA and 3AB ----------", "\"", ")", ";", "Concept", "concept3AA", "=", "testObjectFactory", ".", "makeConcept", "(", "\"", "LEVEL 3 A A", "\"", ")", ";", "concept3AA", ".", "getPrimaryConceptName", "(", ")", ".", "setName", "(", "\"", "3AA", "\"", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "concept2A", "=", "dao", ".", "findByName", "(", "concept2A", ".", "getPrimaryConceptName", "(", ")", ".", "getName", "(", ")", ")", ";", "concept2A", ".", "addChildConcept", "(", "concept3AA", ")", ";", "dao", ".", "persist", "(", "concept3AA", ")", ";", "Concept", "concept3AB", "=", "testObjectFactory", ".", "makeConcept", "(", "\"", "LEVEL 3 A B", "\"", ")", ";", "concept3AB", ".", "getPrimaryConceptName", "(", ")", ".", "setName", "(", "\"", "3AB", "\"", ")", ";", "concept2A", ".", "addChildConcept", "(", "concept3AB", ")", ";", "dao", ".", "persist", "(", "concept3AB", ")", ";", "dao", ".", "endTransaction", "(", ")", ";", "log", ".", "info", "(", "\"", "---------- Add 4A ----------", "\"", ")", ";", "Concept", "concept4A", "=", "testObjectFactory", ".", "makeConcept", "(", "\"", "LEVEL 4 A", "\"", ")", ";", "concept4A", ".", "getPrimaryConceptName", "(", ")", ".", "setName", "(", "\"", "4A", "\"", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "concept3AA", "=", "dao", ".", "findByName", "(", "\"", "3AA", "\"", ")", ";", "concept3AA", ".", "addChildConcept", "(", "concept4A", ")", ";", "dao", ".", "persist", "(", "concept4A", ")", ";", "dao", ".", "endTransaction", "(", ")", ";", "log", ".", "info", "(", "\"", "---------- Add 2B ----------", "\"", ")", ";", "Concept", "concept2B", "=", "testObjectFactory", ".", "makeConcept", "(", "\"", "LEVEL 2 B", "\"", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "root", "=", "dao", ".", "findRoot", "(", ")", ";", "concept2B", ".", "getPrimaryConceptName", "(", ")", ".", "setName", "(", "\"", "2B", "\"", ")", ";", "root", ".", "addChildConcept", "(", "concept2B", ")", ";", "dao", ".", "persist", "(", "concept2B", ")", ";", "dao", ".", "endTransaction", "(", ")", ";", "}", "execute", ":", "{", "dao", ".", "startTransaction", "(", ")", ";", "Concept", "root", "=", "dao", ".", "findByName", "(", "\"", "__ROOT__", "\"", ")", ";", "Concept", "concept2B", "=", "dao", ".", "findByName", "(", "\"", "2B", "\"", ")", ";", "Concept", "concept3AB", "=", "dao", ".", "findByName", "(", "\"", "3AB", "\"", ")", ";", "Concept", "concept3AA", "=", "dao", ".", "findByName", "(", "\"", "3AA", "\"", ")", ";", "log", ".", "info", "(", "\"", "---------- Remove 2B ----------", "\"", ")", ";", "concept2B", ".", "getParentConcept", "(", ")", ".", "removeChildConcept", "(", "concept2B", ")", ";", "dao", ".", "remove", "(", "concept2B", ")", ";", "concept3AB", ".", "getParentConcept", "(", ")", ".", "removeChildConcept", "(", "concept3AB", ")", ";", "dao", ".", "remove", "(", "concept3AB", ")", ";", "dao", ".", "endTransaction", "(", ")", ";", "log", ".", "info", "(", "\"", "---------- Remove 3AA ----------", "\"", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "dao", ".", "merge", "(", "concept3AA", ")", ";", "concept3AA", ".", "getParentConcept", "(", ")", ".", "removeChildConcept", "(", "concept3AA", ")", ";", "dao", ".", "endTransaction", "(", ")", ";", "dao", ".", "cascadeRemove", "(", "concept3AA", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "root", "=", "dao", ".", "findByPrimaryKey", "(", "root", ".", "getClass", "(", ")", ",", "(", "(", "JPAEntity", ")", "root", ")", ".", "getId", "(", ")", ")", ";", "dao", ".", "endTransaction", "(", ")", ";", "log", ".", "info", "(", "\"", "---------- Remove __ROOT__ ----------", "\"", ")", ";", "dao", ".", "cascadeRemove", "(", "root", ")", ";", "}", "}", "@", "Test", "public", "void", "bottomUpDelete", "(", ")", "{", "log", ".", "info", "(", "\"", "---------- TEST: bottomUpDelete ----------", "\"", ")", ";", "Concept", "concept", "=", "testObjectFactory", ".", "makeObjectGraph", "(", "\"", "BIG-TEST", "\"", ",", "1", ")", ";", "ConceptDAO", "dao", "=", "daoFactory", ".", "newConceptDAO", "(", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "dao", ".", "persist", "(", "concept", ")", ";", "dao", ".", "endTransaction", "(", ")", ";", "final", "Collection", "<", "History", ">", "histories", "=", "new", "ArrayList", "<", "History", ">", "(", ")", ";", "final", "Collection", "<", "Media", ">", "medias", "=", "new", "ArrayList", "<", "Media", ">", "(", ")", ";", "final", "Collection", "<", "LinkTemplate", ">", "linkTemplates", "=", "new", "ArrayList", "<", "LinkTemplate", ">", "(", ")", ";", "final", "Collection", "<", "LinkRealization", ">", "linkRealizations", "=", "new", "ArrayList", "<", "LinkRealization", ">", "(", ")", ";", "/*\n * Handy 'Closure' to do all the dirty work of recursively filling in the\n * collections for us\n */", "class", "Collector", "{", "void", "collect", "(", "Concept", "c", ")", "{", "ConceptMetadata", "metadata", "=", "c", ".", "getConceptMetadata", "(", ")", ";", "histories", ".", "addAll", "(", "metadata", ".", "getHistories", "(", ")", ")", ";", "medias", ".", "addAll", "(", "metadata", ".", "getMedias", "(", ")", ")", ";", "linkTemplates", ".", "addAll", "(", "metadata", ".", "getLinkTemplates", "(", ")", ")", ";", "linkRealizations", ".", "addAll", "(", "metadata", ".", "getLinkRealizations", "(", ")", ")", ";", "for", "(", "Concept", "child", ":", "c", ".", "getChildConcepts", "(", ")", ")", "{", "collect", "(", "child", ")", ";", "}", "}", "}", "Collector", "collector", "=", "new", "Collector", "(", ")", ";", "collector", ".", "collect", "(", "concept", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "for", "(", "LinkRealization", "linkRealization", ":", "linkRealizations", ")", "{", "linkRealization", ".", "getConceptMetadata", "(", ")", ".", "removeLinkRealization", "(", "linkRealization", ")", ";", "dao", ".", "remove", "(", "linkRealization", ")", ";", "}", "dao", ".", "endTransaction", "(", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "for", "(", "LinkTemplate", "linkTemplate", ":", "linkTemplates", ")", "{", "linkTemplate", ".", "getConceptMetadata", "(", ")", ".", "removeLinkTemplate", "(", "linkTemplate", ")", ";", "dao", ".", "remove", "(", "linkTemplate", ")", ";", "}", "dao", ".", "endTransaction", "(", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "for", "(", "Media", "media", ":", "medias", ")", "{", "media", ".", "getConceptMetadata", "(", ")", ".", "removeMedia", "(", "media", ")", ";", "dao", ".", "remove", "(", "media", ")", ";", "}", "dao", ".", "endTransaction", "(", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "for", "(", "History", "history", ":", "histories", ")", "{", "history", ".", "getConceptMetadata", "(", ")", ".", "removeHistory", "(", "history", ")", ";", "dao", ".", "remove", "(", "history", ")", ";", "}", "dao", ".", "endTransaction", "(", ")", ";", "dao", ".", "cascadeRemove", "(", "concept", ")", ";", "}", "@", "AfterAll", "public", "void", "cleanup", "(", ")", "{", "ConceptDAO", "dao", "=", "daoFactory", ".", "newConceptDAO", "(", ")", ";", "dao", ".", "startTransaction", "(", ")", ";", "Concept", "concept", "=", "dao", ".", "findRoot", "(", ")", ";", "dao", ".", "endTransaction", "(", ")", ";", "if", "(", "concept", "!=", "null", ")", "{", "dao", ".", "cascadeRemove", "(", "concept", ")", ";", "}", "dao", ".", "close", "(", ")", ";", "Collection", "<", "Concept", ">", "badData", "=", "daoFactory", ".", "newConceptDAO", "(", ")", ".", "findAll", "(", ")", ";", "if", "(", "badData", ".", "size", "(", ")", ">", "0", ")", "{", "log", ".", "info", "(", "\"", "There are ", "\"", "+", "badData", ".", "size", "(", ")", "+", "\"", " concepts that are still in the knowledgebase that shouldn't be there.", "\"", ")", ";", "}", "}", "}" ]
Created by IntelliJ IDEA.
[ "Created", "by", "IntelliJ", "IDEA", "." ]
[ "// log.info(\"KNOWLEDGEBASE TREE BEFORE TEST:\\n\" +", "// entityUtilities.buildTextTree(c));", "// log.info(\"KNOWLEDGEBASE TREE AFTER INSERT:\\n\" +", "// entityUtilities.buildTextTree(c));", "// Exercise the DAO methods", "// log.info(\"BUILDING KNOWLEDGEBASE TREE:\\n\" +", "// entityUtilities.buildTextTree(root));", "// ---- Step 1: Build up each node in the database", "// log.info(\"BUILDING KNOWLEDGEBASE TREE:\\n\" +", "// entityUtilities.buildTextTree(root));", "// log.info(\"BUILDING KNOWLEDGEBASE TREE:\\n\" +", "// entityUtilities.buildTextTree(root));", "// log.info(\"BUILDING KNOWLEDGEBASE TREE:\\n\" +", "// entityUtilities.buildTextTree(root));", "// log.info(\"BUILDING KNOWLEDGEBASE TREE:\\n\" +", "// entityUtilities.buildTextTree(root));", "// ---- Step 2: Let's look up the references form the database so that we have", "// the correct entities", "// Tear down each node in the database", "// log.info(\"---------- Remove 3AB ----------\");", "// log.info(\"KNOWLEDGEBASE TREE:\\n\" + entityUtilities.buildTextTree(root));", "// log.info(\"KNOWLEDGEBASE TREE AFTER INITIAL INSERT:\\n\" +", "// entityUtilities.buildTextTree(concept));", "// log.info(\"KNOWLEDGEBASE TREE AFTER LINKREALIZATION DELETE:\\n\" +", "// entityUtilities.buildTextTree(concept));", "// log.info(\"KNOWLEDGEBASE TREE AFTER LINKTEMPLATE DELETE:\\n\" +", "// entityUtilities.buildTextTree(concept));", "// log.info(\"KNOWLEDGEBASE TREE AFTER MEDIA DELETE:\\n\" +", "// entityUtilities.buildTextTree(concept));", "// log.info(\"KNOWLEDGEBASE TREE AFTER HISTORY DELETE:\\n\" +", "// entityUtilities.buildTextTree(concept));", "// String s = \"Concepts that shouldn't still be in the database:\\n\";", "// for (Concept c : badData) {", "// s += \"\\n\" + entityUtilities.buildTextTree(c) + \"\\n\";", "// }", "// log.info(s);" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
69c4049e33312b3a2e7ee4590802477012303d52
mbari-media-management/vars-kb
org.mbari.kb.jpa/src/test/java/org/mbari/kb/jpa/knowledgebase/KBCrudTest.java
[ "Apache-2.0" ]
Java
Collector
/* * Handy 'Closure' to do all the dirty work of recursively filling in the * collections for us */
Handy 'Closure' to do all the dirty work of recursively filling in the collections for us
[ "Handy", "'", "Closure", "'", "to", "do", "all", "the", "dirty", "work", "of", "recursively", "filling", "in", "the", "collections", "for", "us" ]
class Collector { void collect(Concept c) { ConceptMetadata metadata = c.getConceptMetadata(); histories.addAll(metadata.getHistories()); medias.addAll(metadata.getMedias()); linkTemplates.addAll(metadata.getLinkTemplates()); linkRealizations.addAll(metadata.getLinkRealizations()); for (Concept child : c.getChildConcepts()) { collect(child); } } }
[ "class", "Collector", "{", "void", "collect", "(", "Concept", "c", ")", "{", "ConceptMetadata", "metadata", "=", "c", ".", "getConceptMetadata", "(", ")", ";", "histories", ".", "addAll", "(", "metadata", ".", "getHistories", "(", ")", ")", ";", "medias", ".", "addAll", "(", "metadata", ".", "getMedias", "(", ")", ")", ";", "linkTemplates", ".", "addAll", "(", "metadata", ".", "getLinkTemplates", "(", ")", ")", ";", "linkRealizations", ".", "addAll", "(", "metadata", ".", "getLinkRealizations", "(", ")", ")", ";", "for", "(", "Concept", "child", ":", "c", ".", "getChildConcepts", "(", ")", ")", "{", "collect", "(", "child", ")", ";", "}", "}", "}" ]
Handy 'Closure' to do all the dirty work of recursively filling in the collections for us
[ "Handy", "'", "Closure", "'", "to", "do", "all", "the", "dirty", "work", "of", "recursively", "filling", "in", "the", "collections", "for", "us" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
69c7edf39040c7280e376e22adc65033cb6ef06b
prabushi/andes
modules/andes-core/broker/src/main/java/org/wso2/andes/server/message/MessageMetaData.java
[ "Apache-2.0" ]
Java
MessageMetaData
/** * Encapsulates a publish body and a content header. In the context of the message store these are treated as a * single unit. */
Encapsulates a publish body and a content header. In the context of the message store these are treated as a single unit.
[ "Encapsulates", "a", "publish", "body", "and", "a", "content", "header", ".", "In", "the", "context", "of", "the", "message", "store", "these", "are", "treated", "as", "a", "single", "unit", "." ]
public class MessageMetaData implements StorableMessageMetaData { private MessagePublishInfo _messagePublishInfo; private ContentHeaderBody _contentHeaderBody; private int _contentChunkCount; private String _clientIP = ""; private long _arrivalTime; private boolean _isCompressed = false; /** * Unique publisher's session id to validate whether subscriber and publisher has the same session */ private long publisherSessionID; private static final byte MANDATORY_FLAG = 1; private static final byte IMMEDIATE_FLAG = 2; public static final MessageMetaDataType.Factory<MessageMetaData> FACTORY = new MetaDataFactory(); public MessageMetaData(MessagePublishInfo publishBody, ContentHeaderBody contentHeaderBody, int contentChunkCount) { this(publishBody,contentHeaderBody, contentChunkCount, System.currentTimeMillis()); } public MessageMetaData(MessagePublishInfo publishBody, ContentHeaderBody contentHeaderBody, int contentChunkCount, long arrivalTime) { _contentHeaderBody = contentHeaderBody; _messagePublishInfo = publishBody; _contentChunkCount = contentChunkCount; _arrivalTime = arrivalTime; } /** * This constructor is used to set session id into message meta data * * @param publishBody Message publish information * @param contentHeaderBody Message content header body * @param sessionID publisher's SessionId * @param contentChunkCount content chunk count */ public MessageMetaData(MessagePublishInfo publishBody, ContentHeaderBody contentHeaderBody, long sessionID, int contentChunkCount) { this(publishBody, contentHeaderBody, sessionID, contentChunkCount, System.currentTimeMillis()); } public MessageMetaData(MessagePublishInfo publishBody, ContentHeaderBody contentHeaderBody, long sessionID, int contentChunkCount, long arrivalTime) { _contentHeaderBody = contentHeaderBody; _messagePublishInfo = publishBody; _contentChunkCount = contentChunkCount; _arrivalTime = arrivalTime; publisherSessionID = sessionID; } /** * This constructor is used to set isCompressed value into message meta data * * @param publishBody Message publish information * @param contentHeaderBody Message content header body * @param sessionID Publisher's SessionId * @param contentChunkCount Content chunk count * @param arrivalTime Arrival time of the message * @param isCompressed Value to indicate, if the message is compressed or not */ public MessageMetaData(MessagePublishInfo publishBody, ContentHeaderBody contentHeaderBody, long sessionID, int contentChunkCount, long arrivalTime, boolean isCompressed) { this(publishBody, contentHeaderBody, sessionID, contentChunkCount, arrivalTime); _isCompressed = isCompressed; } public long getPublisherSessionID() { return publisherSessionID; } public void setPublisherSessionID(long publisherSessionID) { this.publisherSessionID = publisherSessionID; } public int getContentChunkCount() { return _contentChunkCount; } public void setContentChunkCount(int contentChunkCount) { _contentChunkCount = contentChunkCount; } public ContentHeaderBody getContentHeaderBody() { return _contentHeaderBody; } public void setContentHeaderBody(ContentHeaderBody contentHeaderBody) { _contentHeaderBody = contentHeaderBody; } public MessagePublishInfo getMessagePublishInfo() { return _messagePublishInfo; } public void setMessagePublishInfo(MessagePublishInfo messagePublishInfo) { _messagePublishInfo = messagePublishInfo; } public long getArrivalTime() { return _arrivalTime; } public void setArrivalTime(long arrivalTime) { _arrivalTime = arrivalTime; } public MessageMetaDataType getType() { return MessageMetaDataType.META_DATA_0_8; } public boolean isCompressed() { return _isCompressed; } public int getStorableSize() { int size = _contentHeaderBody.getSize(); size += 4; size += EncodingUtils.encodedShortStringLength(_messagePublishInfo.getExchange()); size += EncodingUtils.encodedShortStringLength(_messagePublishInfo.getRoutingKey()); size += 1; // flags for immediate/mandatory size += EncodingUtils.encodedLongLength(); // for sessionID size += EncodingUtils.encodedLongLength(); size += EncodingUtils.encodedBooleanLength(); // for compression state of the message return size; } public int writeToBuffer(int offset, ByteBuffer dest) { ByteBuffer src = ByteBuffer.allocate((int)getStorableSize()); org.apache.mina.common.ByteBuffer minaSrc = org.apache.mina.common.ByteBuffer.wrap(src); EncodingUtils.writeInteger(minaSrc, _contentHeaderBody.getSize()); _contentHeaderBody.writePayload(minaSrc); EncodingUtils.writeShortStringBytes(minaSrc, _messagePublishInfo.getExchange()); EncodingUtils.writeShortStringBytes(minaSrc, _messagePublishInfo.getRoutingKey()); byte flags = 0; if(_messagePublishInfo.isMandatory()) { flags |= MANDATORY_FLAG; } if(_messagePublishInfo.isImmediate()) { flags |= IMMEDIATE_FLAG; } EncodingUtils.writeByte(minaSrc, flags); EncodingUtils.writeLong(minaSrc, publisherSessionID); EncodingUtils.writeLong(minaSrc, _arrivalTime); EncodingUtils.writeBoolean(minaSrc, _isCompressed); src.position(minaSrc.position()); src.flip(); src.position(offset); src = src.slice(); if(dest.remaining() < src.limit()) { src.limit(dest.remaining()); } dest.put(src); return src.limit(); } public int getContentSize() { return (int) _contentHeaderBody.bodySize; } public boolean isPersistent() { BasicContentHeaderProperties properties = (BasicContentHeaderProperties) (_contentHeaderBody.getProperties()); return properties.getDeliveryMode() == BasicContentHeaderProperties.PERSISTENT; } public String get_clientIP() { return _clientIP; } public void set_clientIP(String _clientIP) { this._clientIP = _clientIP; } private static class MetaDataFactory implements MessageMetaDataType.Factory { public MessageMetaData createMetaData(ByteBuffer buf) { try { org.apache.mina.common.ByteBuffer minaSrc = org.apache.mina.common.ByteBuffer.wrap(buf); int size = EncodingUtils.readInteger(minaSrc); ContentHeaderBody chb = ContentHeaderBody.createFromBuffer(minaSrc, size); final AMQShortString exchange = EncodingUtils.readAMQShortString(minaSrc); final AMQShortString routingKey = EncodingUtils.readAMQShortString(minaSrc); final byte flags = EncodingUtils.readByte(minaSrc); long sessionID = EncodingUtils.readLong(minaSrc); long arrivalTime = EncodingUtils.readLong(minaSrc); // isCompressed is an optional property. Thus, can't add properties to MessageMetaData after this. boolean isCompressed = false; if (minaSrc.hasRemaining()) { isCompressed = EncodingUtils.readBoolean(minaSrc); } MessagePublishInfo publishBody = new MessagePublishInfo() { public AMQShortString getExchange() { return exchange; } public void setExchange(AMQShortString exchange) { } @Override public void setRoutingKey(AMQShortString routingKey) { } public boolean isImmediate() { return (flags & IMMEDIATE_FLAG) != 0; } public boolean isMandatory() { return (flags & MANDATORY_FLAG) != 0; } public AMQShortString getRoutingKey() { return routingKey; } }; return new MessageMetaData(publishBody, chb, sessionID, 0, arrivalTime, isCompressed); } catch (AMQException e) { throw new RuntimeException(e); } } }; public AMQMessageHeader getMessageHeader() { return new MessageHeaderAdapter(); } private final class MessageHeaderAdapter implements AMQMessageHeader { private BasicContentHeaderProperties getProperties() { return (BasicContentHeaderProperties) getContentHeaderBody().getProperties(); } public String getCorrelationId() { return getProperties().getCorrelationIdAsString(); } public long getExpiration() { return getProperties().getExpiration(); } public String getMessageId() { return getProperties().getMessageIdAsString(); } public String getMimeType() { return getProperties().getContentTypeAsString(); } public String getEncoding() { return getProperties().getEncodingAsString(); } public byte getPriority() { return getProperties().getPriority(); } public long getTimestamp() { return getProperties().getTimestamp(); } public String getType() { return getProperties().getTypeAsString(); } public String getReplyTo() { return getProperties().getReplyToAsString(); } public String getReplyToExchange() { // TODO return getReplyTo(); } public String getReplyToRoutingKey() { // TODO return getReplyTo(); } public Object getHeader(String name) { FieldTable ft = getProperties().getHeaders(); return ft.get(name); } public boolean containsHeaders(Set<String> names) { FieldTable ft = getProperties().getHeaders(); for(String name : names) { if(!ft.containsKey(name)) { return false; } } return true; } public boolean containsHeader(String name) { FieldTable ft = getProperties().getHeaders(); return ft.containsKey(name); } } }
[ "public", "class", "MessageMetaData", "implements", "StorableMessageMetaData", "{", "private", "MessagePublishInfo", "_messagePublishInfo", ";", "private", "ContentHeaderBody", "_contentHeaderBody", ";", "private", "int", "_contentChunkCount", ";", "private", "String", "_clientIP", "=", "\"", "\"", ";", "private", "long", "_arrivalTime", ";", "private", "boolean", "_isCompressed", "=", "false", ";", "/**\n * Unique publisher's session id to validate whether subscriber and publisher has the same session\n */", "private", "long", "publisherSessionID", ";", "private", "static", "final", "byte", "MANDATORY_FLAG", "=", "1", ";", "private", "static", "final", "byte", "IMMEDIATE_FLAG", "=", "2", ";", "public", "static", "final", "MessageMetaDataType", ".", "Factory", "<", "MessageMetaData", ">", "FACTORY", "=", "new", "MetaDataFactory", "(", ")", ";", "public", "MessageMetaData", "(", "MessagePublishInfo", "publishBody", ",", "ContentHeaderBody", "contentHeaderBody", ",", "int", "contentChunkCount", ")", "{", "this", "(", "publishBody", ",", "contentHeaderBody", ",", "contentChunkCount", ",", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "}", "public", "MessageMetaData", "(", "MessagePublishInfo", "publishBody", ",", "ContentHeaderBody", "contentHeaderBody", ",", "int", "contentChunkCount", ",", "long", "arrivalTime", ")", "{", "_contentHeaderBody", "=", "contentHeaderBody", ";", "_messagePublishInfo", "=", "publishBody", ";", "_contentChunkCount", "=", "contentChunkCount", ";", "_arrivalTime", "=", "arrivalTime", ";", "}", "/**\n * This constructor is used to set session id into message meta data\n *\n * @param publishBody Message publish information\n * @param contentHeaderBody Message content header body\n * @param sessionID publisher's SessionId\n * @param contentChunkCount content chunk count\n */", "public", "MessageMetaData", "(", "MessagePublishInfo", "publishBody", ",", "ContentHeaderBody", "contentHeaderBody", ",", "long", "sessionID", ",", "int", "contentChunkCount", ")", "{", "this", "(", "publishBody", ",", "contentHeaderBody", ",", "sessionID", ",", "contentChunkCount", ",", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "}", "public", "MessageMetaData", "(", "MessagePublishInfo", "publishBody", ",", "ContentHeaderBody", "contentHeaderBody", ",", "long", "sessionID", ",", "int", "contentChunkCount", ",", "long", "arrivalTime", ")", "{", "_contentHeaderBody", "=", "contentHeaderBody", ";", "_messagePublishInfo", "=", "publishBody", ";", "_contentChunkCount", "=", "contentChunkCount", ";", "_arrivalTime", "=", "arrivalTime", ";", "publisherSessionID", "=", "sessionID", ";", "}", "/**\n * This constructor is used to set isCompressed value into message meta data\n *\n * @param publishBody Message publish information\n * @param contentHeaderBody Message content header body\n * @param sessionID Publisher's SessionId\n * @param contentChunkCount Content chunk count\n * @param arrivalTime Arrival time of the message\n * @param isCompressed Value to indicate, if the message is compressed or not\n */", "public", "MessageMetaData", "(", "MessagePublishInfo", "publishBody", ",", "ContentHeaderBody", "contentHeaderBody", ",", "long", "sessionID", ",", "int", "contentChunkCount", ",", "long", "arrivalTime", ",", "boolean", "isCompressed", ")", "{", "this", "(", "publishBody", ",", "contentHeaderBody", ",", "sessionID", ",", "contentChunkCount", ",", "arrivalTime", ")", ";", "_isCompressed", "=", "isCompressed", ";", "}", "public", "long", "getPublisherSessionID", "(", ")", "{", "return", "publisherSessionID", ";", "}", "public", "void", "setPublisherSessionID", "(", "long", "publisherSessionID", ")", "{", "this", ".", "publisherSessionID", "=", "publisherSessionID", ";", "}", "public", "int", "getContentChunkCount", "(", ")", "{", "return", "_contentChunkCount", ";", "}", "public", "void", "setContentChunkCount", "(", "int", "contentChunkCount", ")", "{", "_contentChunkCount", "=", "contentChunkCount", ";", "}", "public", "ContentHeaderBody", "getContentHeaderBody", "(", ")", "{", "return", "_contentHeaderBody", ";", "}", "public", "void", "setContentHeaderBody", "(", "ContentHeaderBody", "contentHeaderBody", ")", "{", "_contentHeaderBody", "=", "contentHeaderBody", ";", "}", "public", "MessagePublishInfo", "getMessagePublishInfo", "(", ")", "{", "return", "_messagePublishInfo", ";", "}", "public", "void", "setMessagePublishInfo", "(", "MessagePublishInfo", "messagePublishInfo", ")", "{", "_messagePublishInfo", "=", "messagePublishInfo", ";", "}", "public", "long", "getArrivalTime", "(", ")", "{", "return", "_arrivalTime", ";", "}", "public", "void", "setArrivalTime", "(", "long", "arrivalTime", ")", "{", "_arrivalTime", "=", "arrivalTime", ";", "}", "public", "MessageMetaDataType", "getType", "(", ")", "{", "return", "MessageMetaDataType", ".", "META_DATA_0_8", ";", "}", "public", "boolean", "isCompressed", "(", ")", "{", "return", "_isCompressed", ";", "}", "public", "int", "getStorableSize", "(", ")", "{", "int", "size", "=", "_contentHeaderBody", ".", "getSize", "(", ")", ";", "size", "+=", "4", ";", "size", "+=", "EncodingUtils", ".", "encodedShortStringLength", "(", "_messagePublishInfo", ".", "getExchange", "(", ")", ")", ";", "size", "+=", "EncodingUtils", ".", "encodedShortStringLength", "(", "_messagePublishInfo", ".", "getRoutingKey", "(", ")", ")", ";", "size", "+=", "1", ";", "size", "+=", "EncodingUtils", ".", "encodedLongLength", "(", ")", ";", "size", "+=", "EncodingUtils", ".", "encodedLongLength", "(", ")", ";", "size", "+=", "EncodingUtils", ".", "encodedBooleanLength", "(", ")", ";", "return", "size", ";", "}", "public", "int", "writeToBuffer", "(", "int", "offset", ",", "ByteBuffer", "dest", ")", "{", "ByteBuffer", "src", "=", "ByteBuffer", ".", "allocate", "(", "(", "int", ")", "getStorableSize", "(", ")", ")", ";", "org", ".", "apache", ".", "mina", ".", "common", ".", "ByteBuffer", "minaSrc", "=", "org", ".", "apache", ".", "mina", ".", "common", ".", "ByteBuffer", ".", "wrap", "(", "src", ")", ";", "EncodingUtils", ".", "writeInteger", "(", "minaSrc", ",", "_contentHeaderBody", ".", "getSize", "(", ")", ")", ";", "_contentHeaderBody", ".", "writePayload", "(", "minaSrc", ")", ";", "EncodingUtils", ".", "writeShortStringBytes", "(", "minaSrc", ",", "_messagePublishInfo", ".", "getExchange", "(", ")", ")", ";", "EncodingUtils", ".", "writeShortStringBytes", "(", "minaSrc", ",", "_messagePublishInfo", ".", "getRoutingKey", "(", ")", ")", ";", "byte", "flags", "=", "0", ";", "if", "(", "_messagePublishInfo", ".", "isMandatory", "(", ")", ")", "{", "flags", "|=", "MANDATORY_FLAG", ";", "}", "if", "(", "_messagePublishInfo", ".", "isImmediate", "(", ")", ")", "{", "flags", "|=", "IMMEDIATE_FLAG", ";", "}", "EncodingUtils", ".", "writeByte", "(", "minaSrc", ",", "flags", ")", ";", "EncodingUtils", ".", "writeLong", "(", "minaSrc", ",", "publisherSessionID", ")", ";", "EncodingUtils", ".", "writeLong", "(", "minaSrc", ",", "_arrivalTime", ")", ";", "EncodingUtils", ".", "writeBoolean", "(", "minaSrc", ",", "_isCompressed", ")", ";", "src", ".", "position", "(", "minaSrc", ".", "position", "(", ")", ")", ";", "src", ".", "flip", "(", ")", ";", "src", ".", "position", "(", "offset", ")", ";", "src", "=", "src", ".", "slice", "(", ")", ";", "if", "(", "dest", ".", "remaining", "(", ")", "<", "src", ".", "limit", "(", ")", ")", "{", "src", ".", "limit", "(", "dest", ".", "remaining", "(", ")", ")", ";", "}", "dest", ".", "put", "(", "src", ")", ";", "return", "src", ".", "limit", "(", ")", ";", "}", "public", "int", "getContentSize", "(", ")", "{", "return", "(", "int", ")", "_contentHeaderBody", ".", "bodySize", ";", "}", "public", "boolean", "isPersistent", "(", ")", "{", "BasicContentHeaderProperties", "properties", "=", "(", "BasicContentHeaderProperties", ")", "(", "_contentHeaderBody", ".", "getProperties", "(", ")", ")", ";", "return", "properties", ".", "getDeliveryMode", "(", ")", "==", "BasicContentHeaderProperties", ".", "PERSISTENT", ";", "}", "public", "String", "get_clientIP", "(", ")", "{", "return", "_clientIP", ";", "}", "public", "void", "set_clientIP", "(", "String", "_clientIP", ")", "{", "this", ".", "_clientIP", "=", "_clientIP", ";", "}", "private", "static", "class", "MetaDataFactory", "implements", "MessageMetaDataType", ".", "Factory", "{", "public", "MessageMetaData", "createMetaData", "(", "ByteBuffer", "buf", ")", "{", "try", "{", "org", ".", "apache", ".", "mina", ".", "common", ".", "ByteBuffer", "minaSrc", "=", "org", ".", "apache", ".", "mina", ".", "common", ".", "ByteBuffer", ".", "wrap", "(", "buf", ")", ";", "int", "size", "=", "EncodingUtils", ".", "readInteger", "(", "minaSrc", ")", ";", "ContentHeaderBody", "chb", "=", "ContentHeaderBody", ".", "createFromBuffer", "(", "minaSrc", ",", "size", ")", ";", "final", "AMQShortString", "exchange", "=", "EncodingUtils", ".", "readAMQShortString", "(", "minaSrc", ")", ";", "final", "AMQShortString", "routingKey", "=", "EncodingUtils", ".", "readAMQShortString", "(", "minaSrc", ")", ";", "final", "byte", "flags", "=", "EncodingUtils", ".", "readByte", "(", "minaSrc", ")", ";", "long", "sessionID", "=", "EncodingUtils", ".", "readLong", "(", "minaSrc", ")", ";", "long", "arrivalTime", "=", "EncodingUtils", ".", "readLong", "(", "minaSrc", ")", ";", "boolean", "isCompressed", "=", "false", ";", "if", "(", "minaSrc", ".", "hasRemaining", "(", ")", ")", "{", "isCompressed", "=", "EncodingUtils", ".", "readBoolean", "(", "minaSrc", ")", ";", "}", "MessagePublishInfo", "publishBody", "=", "new", "MessagePublishInfo", "(", ")", "{", "public", "AMQShortString", "getExchange", "(", ")", "{", "return", "exchange", ";", "}", "public", "void", "setExchange", "(", "AMQShortString", "exchange", ")", "{", "}", "@", "Override", "public", "void", "setRoutingKey", "(", "AMQShortString", "routingKey", ")", "{", "}", "public", "boolean", "isImmediate", "(", ")", "{", "return", "(", "flags", "&", "IMMEDIATE_FLAG", ")", "!=", "0", ";", "}", "public", "boolean", "isMandatory", "(", ")", "{", "return", "(", "flags", "&", "MANDATORY_FLAG", ")", "!=", "0", ";", "}", "public", "AMQShortString", "getRoutingKey", "(", ")", "{", "return", "routingKey", ";", "}", "}", ";", "return", "new", "MessageMetaData", "(", "publishBody", ",", "chb", ",", "sessionID", ",", "0", ",", "arrivalTime", ",", "isCompressed", ")", ";", "}", "catch", "(", "AMQException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}", "}", ";", "public", "AMQMessageHeader", "getMessageHeader", "(", ")", "{", "return", "new", "MessageHeaderAdapter", "(", ")", ";", "}", "private", "final", "class", "MessageHeaderAdapter", "implements", "AMQMessageHeader", "{", "private", "BasicContentHeaderProperties", "getProperties", "(", ")", "{", "return", "(", "BasicContentHeaderProperties", ")", "getContentHeaderBody", "(", ")", ".", "getProperties", "(", ")", ";", "}", "public", "String", "getCorrelationId", "(", ")", "{", "return", "getProperties", "(", ")", ".", "getCorrelationIdAsString", "(", ")", ";", "}", "public", "long", "getExpiration", "(", ")", "{", "return", "getProperties", "(", ")", ".", "getExpiration", "(", ")", ";", "}", "public", "String", "getMessageId", "(", ")", "{", "return", "getProperties", "(", ")", ".", "getMessageIdAsString", "(", ")", ";", "}", "public", "String", "getMimeType", "(", ")", "{", "return", "getProperties", "(", ")", ".", "getContentTypeAsString", "(", ")", ";", "}", "public", "String", "getEncoding", "(", ")", "{", "return", "getProperties", "(", ")", ".", "getEncodingAsString", "(", ")", ";", "}", "public", "byte", "getPriority", "(", ")", "{", "return", "getProperties", "(", ")", ".", "getPriority", "(", ")", ";", "}", "public", "long", "getTimestamp", "(", ")", "{", "return", "getProperties", "(", ")", ".", "getTimestamp", "(", ")", ";", "}", "public", "String", "getType", "(", ")", "{", "return", "getProperties", "(", ")", ".", "getTypeAsString", "(", ")", ";", "}", "public", "String", "getReplyTo", "(", ")", "{", "return", "getProperties", "(", ")", ".", "getReplyToAsString", "(", ")", ";", "}", "public", "String", "getReplyToExchange", "(", ")", "{", "return", "getReplyTo", "(", ")", ";", "}", "public", "String", "getReplyToRoutingKey", "(", ")", "{", "return", "getReplyTo", "(", ")", ";", "}", "public", "Object", "getHeader", "(", "String", "name", ")", "{", "FieldTable", "ft", "=", "getProperties", "(", ")", ".", "getHeaders", "(", ")", ";", "return", "ft", ".", "get", "(", "name", ")", ";", "}", "public", "boolean", "containsHeaders", "(", "Set", "<", "String", ">", "names", ")", "{", "FieldTable", "ft", "=", "getProperties", "(", ")", ".", "getHeaders", "(", ")", ";", "for", "(", "String", "name", ":", "names", ")", "{", "if", "(", "!", "ft", ".", "containsKey", "(", "name", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "public", "boolean", "containsHeader", "(", "String", "name", ")", "{", "FieldTable", "ft", "=", "getProperties", "(", ")", ".", "getHeaders", "(", ")", ";", "return", "ft", ".", "containsKey", "(", "name", ")", ";", "}", "}", "}" ]
Encapsulates a publish body and a content header.
[ "Encapsulates", "a", "publish", "body", "and", "a", "content", "header", "." ]
[ "// flags for immediate/mandatory", "// for sessionID", "// for compression state of the message", "// isCompressed is an optional property. Thus, can't add properties to MessageMetaData after this.", "// TODO", "// TODO" ]
[ { "param": "StorableMessageMetaData", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "StorableMessageMetaData", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69cd84ad6746c69849f8ff8d61a1d8b20719328f
AdamWorthington/omakase
src/test/java/com/salesforce/omakase/broadcast/emitter/AnnotationScannerTest.java
[ "BSD-3-Clause" ]
Java
AnnotationScannerTest
/** * Unit tests for {@link AnnotationScanner}. * * @author nmcwilliams */
Unit tests for AnnotationScanner. @author nmcwilliams
[ "Unit", "tests", "for", "AnnotationScanner", ".", "@author", "nmcwilliams" ]
public class AnnotationScannerTest { private AnnotationScanner scanner; @Before public void setup() { scanner = new AnnotationScanner(); } @Test public void findsRework() { Map<String, Subscription> map = Maps.newHashMap(); for (Subscription subscription : scanner.scanSubscriptions(new AllValid()).get(ClassSelector.class)) { map.put(subscription.method().getName(), subscription); } Subscription subscription = map.get("rework"); assertThat(subscription != null).describedAs("expected to find method annotated with @Rework"); assertThat(subscription.phase()).isSameAs(SubscriptionPhase.PROCESS); } @Test public void errorsIfInvalidRework() { assertThrows(Exception.class, () -> scanner.scanSubscriptions(new InvalidRework())); } @Test public void findsObserve() { Map<String, Subscription> map = Maps.newHashMap(); for (Subscription subscription : scanner.scanSubscriptions(new AllValid()).get(ClassSelector.class)) { map.put(subscription.method().getName(), subscription); } Subscription subscription = map.get("observe"); assertThat(subscription != null).describedAs("expected to find method annotated with @Observe"); assertThat(subscription.phase()).isSameAs(SubscriptionPhase.PROCESS); } @Test public void errorsIfInvalidObserve() { assertThrows(Exception.class, () -> scanner.scanSubscriptions(new InvalidObserve())); } @Test public void findsRefine() { Map<String, Subscription> map = Maps.newHashMap(); for (Subscription subscription : scanner.scanSubscriptions(new AllValid()).get(RawFunction.class)) { map.put(subscription.method().getName(), subscription); } Subscription subscription = map.get("refine"); assertThat(subscription != null).describedAs("expected to find method annotated with @Refine"); assertThat(subscription.phase()).isSameAs(SubscriptionPhase.REFINE); } @Test public void errorsIfInvalidRefine() { assertThrows(Exception.class, () -> scanner.scanSubscriptions(new InvalidRefine())); } @Test public void findsValidate() { Map<String, Subscription> map = Maps.newHashMap(); for (Subscription subscription : scanner.scanSubscriptions(new AllValid()).get(ClassSelector.class)) { map.put(subscription.method().getName(), subscription); } Subscription preprocess = map.get("validate"); assertThat(preprocess != null).describedAs("expected to find method annotated with @Validate"); assertThat(preprocess.phase()).isSameAs(SubscriptionPhase.VALIDATE); } @Test public void errorsIfInvalidValidate() { assertThrows(Exception.class, () -> scanner.scanSubscriptions(new InvalidValidate())); } public static final class AllValid implements Plugin { @Observe public void observe(ClassSelector cs) {} @Rework public void rework(ClassSelector cs) {} @Validate public void validate(ClassSelector cs, ErrorManager em) {} @Refine("foo") public void refine(RawFunction function, Grammar grammar, Broadcaster broadcaster) {} } public static final class InvalidObserve implements Plugin { @Observe public void observe() {} } public static final class InvalidRework implements Plugin { @Rework public void rework() {} } public static final class InvalidValidate implements Plugin { @Validate public void validate() {} } public static final class InvalidRefine implements Plugin { @Refine public void refine() {} } }
[ "public", "class", "AnnotationScannerTest", "{", "private", "AnnotationScanner", "scanner", ";", "@", "Before", "public", "void", "setup", "(", ")", "{", "scanner", "=", "new", "AnnotationScanner", "(", ")", ";", "}", "@", "Test", "public", "void", "findsRework", "(", ")", "{", "Map", "<", "String", ",", "Subscription", ">", "map", "=", "Maps", ".", "newHashMap", "(", ")", ";", "for", "(", "Subscription", "subscription", ":", "scanner", ".", "scanSubscriptions", "(", "new", "AllValid", "(", ")", ")", ".", "get", "(", "ClassSelector", ".", "class", ")", ")", "{", "map", ".", "put", "(", "subscription", ".", "method", "(", ")", ".", "getName", "(", ")", ",", "subscription", ")", ";", "}", "Subscription", "subscription", "=", "map", ".", "get", "(", "\"", "rework", "\"", ")", ";", "assertThat", "(", "subscription", "!=", "null", ")", ".", "describedAs", "(", "\"", "expected to find method annotated with @Rework", "\"", ")", ";", "assertThat", "(", "subscription", ".", "phase", "(", ")", ")", ".", "isSameAs", "(", "SubscriptionPhase", ".", "PROCESS", ")", ";", "}", "@", "Test", "public", "void", "errorsIfInvalidRework", "(", ")", "{", "assertThrows", "(", "Exception", ".", "class", ",", "(", ")", "->", "scanner", ".", "scanSubscriptions", "(", "new", "InvalidRework", "(", ")", ")", ")", ";", "}", "@", "Test", "public", "void", "findsObserve", "(", ")", "{", "Map", "<", "String", ",", "Subscription", ">", "map", "=", "Maps", ".", "newHashMap", "(", ")", ";", "for", "(", "Subscription", "subscription", ":", "scanner", ".", "scanSubscriptions", "(", "new", "AllValid", "(", ")", ")", ".", "get", "(", "ClassSelector", ".", "class", ")", ")", "{", "map", ".", "put", "(", "subscription", ".", "method", "(", ")", ".", "getName", "(", ")", ",", "subscription", ")", ";", "}", "Subscription", "subscription", "=", "map", ".", "get", "(", "\"", "observe", "\"", ")", ";", "assertThat", "(", "subscription", "!=", "null", ")", ".", "describedAs", "(", "\"", "expected to find method annotated with @Observe", "\"", ")", ";", "assertThat", "(", "subscription", ".", "phase", "(", ")", ")", ".", "isSameAs", "(", "SubscriptionPhase", ".", "PROCESS", ")", ";", "}", "@", "Test", "public", "void", "errorsIfInvalidObserve", "(", ")", "{", "assertThrows", "(", "Exception", ".", "class", ",", "(", ")", "->", "scanner", ".", "scanSubscriptions", "(", "new", "InvalidObserve", "(", ")", ")", ")", ";", "}", "@", "Test", "public", "void", "findsRefine", "(", ")", "{", "Map", "<", "String", ",", "Subscription", ">", "map", "=", "Maps", ".", "newHashMap", "(", ")", ";", "for", "(", "Subscription", "subscription", ":", "scanner", ".", "scanSubscriptions", "(", "new", "AllValid", "(", ")", ")", ".", "get", "(", "RawFunction", ".", "class", ")", ")", "{", "map", ".", "put", "(", "subscription", ".", "method", "(", ")", ".", "getName", "(", ")", ",", "subscription", ")", ";", "}", "Subscription", "subscription", "=", "map", ".", "get", "(", "\"", "refine", "\"", ")", ";", "assertThat", "(", "subscription", "!=", "null", ")", ".", "describedAs", "(", "\"", "expected to find method annotated with @Refine", "\"", ")", ";", "assertThat", "(", "subscription", ".", "phase", "(", ")", ")", ".", "isSameAs", "(", "SubscriptionPhase", ".", "REFINE", ")", ";", "}", "@", "Test", "public", "void", "errorsIfInvalidRefine", "(", ")", "{", "assertThrows", "(", "Exception", ".", "class", ",", "(", ")", "->", "scanner", ".", "scanSubscriptions", "(", "new", "InvalidRefine", "(", ")", ")", ")", ";", "}", "@", "Test", "public", "void", "findsValidate", "(", ")", "{", "Map", "<", "String", ",", "Subscription", ">", "map", "=", "Maps", ".", "newHashMap", "(", ")", ";", "for", "(", "Subscription", "subscription", ":", "scanner", ".", "scanSubscriptions", "(", "new", "AllValid", "(", ")", ")", ".", "get", "(", "ClassSelector", ".", "class", ")", ")", "{", "map", ".", "put", "(", "subscription", ".", "method", "(", ")", ".", "getName", "(", ")", ",", "subscription", ")", ";", "}", "Subscription", "preprocess", "=", "map", ".", "get", "(", "\"", "validate", "\"", ")", ";", "assertThat", "(", "preprocess", "!=", "null", ")", ".", "describedAs", "(", "\"", "expected to find method annotated with @Validate", "\"", ")", ";", "assertThat", "(", "preprocess", ".", "phase", "(", ")", ")", ".", "isSameAs", "(", "SubscriptionPhase", ".", "VALIDATE", ")", ";", "}", "@", "Test", "public", "void", "errorsIfInvalidValidate", "(", ")", "{", "assertThrows", "(", "Exception", ".", "class", ",", "(", ")", "->", "scanner", ".", "scanSubscriptions", "(", "new", "InvalidValidate", "(", ")", ")", ")", ";", "}", "public", "static", "final", "class", "AllValid", "implements", "Plugin", "{", "@", "Observe", "public", "void", "observe", "(", "ClassSelector", "cs", ")", "{", "}", "@", "Rework", "public", "void", "rework", "(", "ClassSelector", "cs", ")", "{", "}", "@", "Validate", "public", "void", "validate", "(", "ClassSelector", "cs", ",", "ErrorManager", "em", ")", "{", "}", "@", "Refine", "(", "\"", "foo", "\"", ")", "public", "void", "refine", "(", "RawFunction", "function", ",", "Grammar", "grammar", ",", "Broadcaster", "broadcaster", ")", "{", "}", "}", "public", "static", "final", "class", "InvalidObserve", "implements", "Plugin", "{", "@", "Observe", "public", "void", "observe", "(", ")", "{", "}", "}", "public", "static", "final", "class", "InvalidRework", "implements", "Plugin", "{", "@", "Rework", "public", "void", "rework", "(", ")", "{", "}", "}", "public", "static", "final", "class", "InvalidValidate", "implements", "Plugin", "{", "@", "Validate", "public", "void", "validate", "(", ")", "{", "}", "}", "public", "static", "final", "class", "InvalidRefine", "implements", "Plugin", "{", "@", "Refine", "public", "void", "refine", "(", ")", "{", "}", "}", "}" ]
Unit tests for {@link AnnotationScanner}.
[ "Unit", "tests", "for", "{", "@link", "AnnotationScanner", "}", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
69d1022f959b55e21dab159f7b156b6419d04ce2
woowade/jellyfish
jellyfish-packaging/com.ngc.seaside.jellyfish.cli.gradle.plugins/src/main/java/com/ngc/seaside/jellyfish/cli/gradle/JellyFishProjectGenerator.java
[ "MIT" ]
Java
JellyFishProjectGenerator
/** * A utility to run an instance of Jellyfish within Gradle. */
A utility to run an instance of Jellyfish within Gradle.
[ "A", "utility", "to", "run", "an", "instance", "of", "Jellyfish", "within", "Gradle", "." ]
public class JellyFishProjectGenerator { private final Logger logger; private String command; private boolean failBuildOnException = true; private Map<String, String> arguments = new HashMap<>(); private Supplier<Boolean> executionCondition = () -> true; /** * Creates a new generator. */ public JellyFishProjectGenerator(Logger logger) { this.logger = logger; } /** * generates a jellyfish project */ public void generate() { if (executionCondition.get()) { try { logger.debug("Running JellyFish command " + command + "."); // Avoid issues when calling this from Gradle. If we don't do this we can get exceptions like // GStringImpl cannot be cast to java.lang.String Jellyfish.getService().run(command, asPureJavaTypes(arguments), Collections.singleton(new GradleJellyfishModule())); logger.debug("JellyFish command " + command + " executed successfully."); } catch (Throwable t) { if (failBuildOnException) { throw new GradleException("Jellyfish command " + command + " failed!", t); } else { logger.error("JellyFish command " + command + " failed!", t); } } } } public String getCommand() { return command; } public JellyFishProjectGenerator setCommand(String command) { this.command = command; return this; } public boolean isFailBuildOnException() { return failBuildOnException; } public JellyFishProjectGenerator setFailBuildOnException(boolean failBuildOnException) { this.failBuildOnException = failBuildOnException; return this; } public Map<String, String> getArguments() { return arguments; } public JellyFishProjectGenerator setArguments(Map<String, String> arguments) { this.arguments = arguments; return this; } public Supplier<Boolean> getExecutionCondition() { return executionCondition; } public JellyFishProjectGenerator setExecutionCondition(Supplier<Boolean> executionCondition) { this.executionCondition = executionCondition; return this; } private static Map<String, String> asPureJavaTypes(Map<?, ?> map) { Map<String, String> pure = new HashMap<>(); for (Map.Entry<?, ?> entry : map.entrySet()) { Object key = entry.getKey(); Object value = entry.getValue(); if (key != null && value != null) { pure.put(key.toString(), value.toString()); } } return pure; } }
[ "public", "class", "JellyFishProjectGenerator", "{", "private", "final", "Logger", "logger", ";", "private", "String", "command", ";", "private", "boolean", "failBuildOnException", "=", "true", ";", "private", "Map", "<", "String", ",", "String", ">", "arguments", "=", "new", "HashMap", "<", ">", "(", ")", ";", "private", "Supplier", "<", "Boolean", ">", "executionCondition", "=", "(", ")", "->", "true", ";", "/**\n * Creates a new generator.\n */", "public", "JellyFishProjectGenerator", "(", "Logger", "logger", ")", "{", "this", ".", "logger", "=", "logger", ";", "}", "/**\n * generates a jellyfish project\n */", "public", "void", "generate", "(", ")", "{", "if", "(", "executionCondition", ".", "get", "(", ")", ")", "{", "try", "{", "logger", ".", "debug", "(", "\"", "Running JellyFish command ", "\"", "+", "command", "+", "\"", ".", "\"", ")", ";", "Jellyfish", ".", "getService", "(", ")", ".", "run", "(", "command", ",", "asPureJavaTypes", "(", "arguments", ")", ",", "Collections", ".", "singleton", "(", "new", "GradleJellyfishModule", "(", ")", ")", ")", ";", "logger", ".", "debug", "(", "\"", "JellyFish command ", "\"", "+", "command", "+", "\"", " executed successfully.", "\"", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "if", "(", "failBuildOnException", ")", "{", "throw", "new", "GradleException", "(", "\"", "Jellyfish command ", "\"", "+", "command", "+", "\"", " failed!", "\"", ",", "t", ")", ";", "}", "else", "{", "logger", ".", "error", "(", "\"", "JellyFish command ", "\"", "+", "command", "+", "\"", " failed!", "\"", ",", "t", ")", ";", "}", "}", "}", "}", "public", "String", "getCommand", "(", ")", "{", "return", "command", ";", "}", "public", "JellyFishProjectGenerator", "setCommand", "(", "String", "command", ")", "{", "this", ".", "command", "=", "command", ";", "return", "this", ";", "}", "public", "boolean", "isFailBuildOnException", "(", ")", "{", "return", "failBuildOnException", ";", "}", "public", "JellyFishProjectGenerator", "setFailBuildOnException", "(", "boolean", "failBuildOnException", ")", "{", "this", ".", "failBuildOnException", "=", "failBuildOnException", ";", "return", "this", ";", "}", "public", "Map", "<", "String", ",", "String", ">", "getArguments", "(", ")", "{", "return", "arguments", ";", "}", "public", "JellyFishProjectGenerator", "setArguments", "(", "Map", "<", "String", ",", "String", ">", "arguments", ")", "{", "this", ".", "arguments", "=", "arguments", ";", "return", "this", ";", "}", "public", "Supplier", "<", "Boolean", ">", "getExecutionCondition", "(", ")", "{", "return", "executionCondition", ";", "}", "public", "JellyFishProjectGenerator", "setExecutionCondition", "(", "Supplier", "<", "Boolean", ">", "executionCondition", ")", "{", "this", ".", "executionCondition", "=", "executionCondition", ";", "return", "this", ";", "}", "private", "static", "Map", "<", "String", ",", "String", ">", "asPureJavaTypes", "(", "Map", "<", "?", ",", "?", ">", "map", ")", "{", "Map", "<", "String", ",", "String", ">", "pure", "=", "new", "HashMap", "<", ">", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "?", ",", "?", ">", "entry", ":", "map", ".", "entrySet", "(", ")", ")", "{", "Object", "key", "=", "entry", ".", "getKey", "(", ")", ";", "Object", "value", "=", "entry", ".", "getValue", "(", ")", ";", "if", "(", "key", "!=", "null", "&&", "value", "!=", "null", ")", "{", "pure", ".", "put", "(", "key", ".", "toString", "(", ")", ",", "value", ".", "toString", "(", ")", ")", ";", "}", "}", "return", "pure", ";", "}", "}" ]
A utility to run an instance of Jellyfish within Gradle.
[ "A", "utility", "to", "run", "an", "instance", "of", "Jellyfish", "within", "Gradle", "." ]
[ "// Avoid issues when calling this from Gradle. If we don't do this we can get exceptions like", "// GStringImpl cannot be cast to java.lang.String" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
69d249bf5012379f2b5d0f7072f2228cc0dd3d4b
buralin/YoinkwithJBlas
yoink-core-molecular/src/main/java/org/wallerlab/yoink/molecular/domain/SimpleMolecularSystem.java
[ "Apache-2.0" ]
Java
SimpleMolecularSystem
/** * the domain model for molecular system. * * @author Min Zheng * */
the domain model for molecular system. @author Min Zheng
[ "the", "domain", "model", "for", "molecular", "system", ".", "@author", "Min", "Zheng" ]
public class SimpleMolecularSystem implements MolecularSystem { private final List<Molecule> molecules; public SimpleMolecularSystem(List<Molecule> molecules) { this.molecules = molecules; } /** * get all atoms in the molecular system. */ @Override public List<Atom> getAtoms() { List<Atom> atoms = new ArrayList<Atom>(); for (Molecule molecule : molecules) { for (Atom atom : molecule.getAtoms()) { atoms.add(atom); } } return atoms; } /** * get all molecules in molecular system. */ @Override public List<Molecule> getMolecules() { return this.molecules; } }
[ "public", "class", "SimpleMolecularSystem", "implements", "MolecularSystem", "{", "private", "final", "List", "<", "Molecule", ">", "molecules", ";", "public", "SimpleMolecularSystem", "(", "List", "<", "Molecule", ">", "molecules", ")", "{", "this", ".", "molecules", "=", "molecules", ";", "}", "/**\n\t * get all atoms in the molecular system.\n\t */", "@", "Override", "public", "List", "<", "Atom", ">", "getAtoms", "(", ")", "{", "List", "<", "Atom", ">", "atoms", "=", "new", "ArrayList", "<", "Atom", ">", "(", ")", ";", "for", "(", "Molecule", "molecule", ":", "molecules", ")", "{", "for", "(", "Atom", "atom", ":", "molecule", ".", "getAtoms", "(", ")", ")", "{", "atoms", ".", "add", "(", "atom", ")", ";", "}", "}", "return", "atoms", ";", "}", "/**\n\t * get all molecules in molecular system.\n\t */", "@", "Override", "public", "List", "<", "Molecule", ">", "getMolecules", "(", ")", "{", "return", "this", ".", "molecules", ";", "}", "}" ]
the domain model for molecular system.
[ "the", "domain", "model", "for", "molecular", "system", "." ]
[]
[ { "param": "MolecularSystem", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MolecularSystem", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69d3b8d73c885447318f90cd9b2148c0474abd49
elastisys/scale.cloudadapters
azure/src/main/java/com/elastisys/scale/cloudpool/azure/driver/requests/TagVmRequest.java
[ "Apache-2.0" ]
Java
TagVmRequest
/** * An Azure request that, when called, tags a VM. */
An Azure request that, when called, tags a VM.
[ "An", "Azure", "request", "that", "when", "called", "tags", "a", "VM", "." ]
public class TagVmRequest extends AzureRequest<Void> { /** * The fully qualified id of the VM to tag. Typically of form * {@code /subscriptions/<subscription-id>/resourceGroups/<group>/providers/Microsoft.Compute/virtualMachines/<name>} */ private final String vmId; /** Tags to assign to VM. */ private final Map<String, String> tags; /** * @param apiAccess * Azure API access credentials and settings. * @param vmId * The fully qualified id of the VM to delete. Typically of form * {@code /subscriptions/<subscription-id>/resourceGroups/<group>/providers/Microsoft.Compute/virtualMachines/<name>} * @param tags * Tags to assign to VM. */ public TagVmRequest(AzureApiAccess apiAccess, String vmId, Map<String, String> tags) { super(apiAccess); this.vmId = vmId; this.tags = tags; } @Override public Void doRequest(Azure api) throws NotFoundException, AzureException { LOG.debug("tagging vm {}: {} ...", this.vmId, this.tags); VirtualMachine vm = new GetVmRequest(apiAccess(), this.vmId).call(); // append tags to existing vm tags Map<String, String> newTags = new HashMap<>(vm.tags()); newTags.putAll(this.tags); try { vm.update().withTags(newTags).apply(); LOG.debug("vm {} tagged.", this.vmId); return null; } catch (Exception e) { throw new AzureException("failed to tag vm: " + e.getMessage(), e); } } }
[ "public", "class", "TagVmRequest", "extends", "AzureRequest", "<", "Void", ">", "{", "/**\n * The fully qualified id of the VM to tag. Typically of form\n * {@code /subscriptions/<subscription-id>/resourceGroups/<group>/providers/Microsoft.Compute/virtualMachines/<name>}\n */", "private", "final", "String", "vmId", ";", "/** Tags to assign to VM. */", "private", "final", "Map", "<", "String", ",", "String", ">", "tags", ";", "/**\n * @param apiAccess\n * Azure API access credentials and settings.\n * @param vmId\n * The fully qualified id of the VM to delete. Typically of form\n * {@code /subscriptions/<subscription-id>/resourceGroups/<group>/providers/Microsoft.Compute/virtualMachines/<name>}\n * @param tags\n * Tags to assign to VM.\n */", "public", "TagVmRequest", "(", "AzureApiAccess", "apiAccess", ",", "String", "vmId", ",", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "super", "(", "apiAccess", ")", ";", "this", ".", "vmId", "=", "vmId", ";", "this", ".", "tags", "=", "tags", ";", "}", "@", "Override", "public", "Void", "doRequest", "(", "Azure", "api", ")", "throws", "NotFoundException", ",", "AzureException", "{", "LOG", ".", "debug", "(", "\"", "tagging vm {}: {} ...", "\"", ",", "this", ".", "vmId", ",", "this", ".", "tags", ")", ";", "VirtualMachine", "vm", "=", "new", "GetVmRequest", "(", "apiAccess", "(", ")", ",", "this", ".", "vmId", ")", ".", "call", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "newTags", "=", "new", "HashMap", "<", ">", "(", "vm", ".", "tags", "(", ")", ")", ";", "newTags", ".", "putAll", "(", "this", ".", "tags", ")", ";", "try", "{", "vm", ".", "update", "(", ")", ".", "withTags", "(", "newTags", ")", ".", "apply", "(", ")", ";", "LOG", ".", "debug", "(", "\"", "vm {} tagged.", "\"", ",", "this", ".", "vmId", ")", ";", "return", "null", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "AzureException", "(", "\"", "failed to tag vm: ", "\"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}", "}" ]
An Azure request that, when called, tags a VM.
[ "An", "Azure", "request", "that", "when", "called", "tags", "a", "VM", "." ]
[ "// append tags to existing vm tags" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
69d85a258354ebc2a080cd3909cb9232be8ec7c3
dmaidaniuk/krazo
core/src/main/java/org/eclipse/krazo/bootstrap/DefaultConfigProvider.java
[ "Apache-2.0" ]
Java
DefaultConfigProvider
/** * Implementation of ConfigProvider which registers all providers of the core module. * * @author Christian Kaltepoth */
Implementation of ConfigProvider which registers all providers of the core module. @author Christian Kaltepoth
[ "Implementation", "of", "ConfigProvider", "which", "registers", "all", "providers", "of", "the", "core", "module", ".", "@author", "Christian", "Kaltepoth" ]
public class DefaultConfigProvider implements ConfigProvider { public static final Set<Class<?>> PROVIDERS = new HashSet<>( Arrays.asList( ViewResponseFilter.class, ViewableWriter.class, CsrfValidateFilter.class, CsrfProtectFilter.class, CsrfExceptionMapper.class, PreMatchingRequestFilter.class, PostMatchingRequestFilter.class, MvcConverterProvider.class, HiddenMethodFilter.class ) ); @Override public void configure(FeatureContext context) { PROVIDERS.forEach(provider -> register(context, provider)); } private void register(FeatureContext context, Class<?> providerClass) { context.register(providerClass); } }
[ "public", "class", "DefaultConfigProvider", "implements", "ConfigProvider", "{", "public", "static", "final", "Set", "<", "Class", "<", "?", ">", ">", "PROVIDERS", "=", "new", "HashSet", "<", ">", "(", "Arrays", ".", "asList", "(", "ViewResponseFilter", ".", "class", ",", "ViewableWriter", ".", "class", ",", "CsrfValidateFilter", ".", "class", ",", "CsrfProtectFilter", ".", "class", ",", "CsrfExceptionMapper", ".", "class", ",", "PreMatchingRequestFilter", ".", "class", ",", "PostMatchingRequestFilter", ".", "class", ",", "MvcConverterProvider", ".", "class", ",", "HiddenMethodFilter", ".", "class", ")", ")", ";", "@", "Override", "public", "void", "configure", "(", "FeatureContext", "context", ")", "{", "PROVIDERS", ".", "forEach", "(", "provider", "->", "register", "(", "context", ",", "provider", ")", ")", ";", "}", "private", "void", "register", "(", "FeatureContext", "context", ",", "Class", "<", "?", ">", "providerClass", ")", "{", "context", ".", "register", "(", "providerClass", ")", ";", "}", "}" ]
Implementation of ConfigProvider which registers all providers of the core module.
[ "Implementation", "of", "ConfigProvider", "which", "registers", "all", "providers", "of", "the", "core", "module", "." ]
[]
[ { "param": "ConfigProvider", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ConfigProvider", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69da9b6012487fe47fe934ce352ada474dd365b4
yeppog/tp
src/main/java/seedu/address/logic/commands/task/DoneTaskCommand.java
[ "MIT" ]
Java
DoneTaskCommand
/** * Completes an existing task in the task list. */
Completes an existing task in the task list.
[ "Completes", "an", "existing", "task", "in", "the", "task", "list", "." ]
public class DoneTaskCommand extends TaskCommand { public static final String COMMAND_WORD = "done"; public static final String FULL_COMMAND_WORD = TaskCommand.COMMAND_WORD + " " + COMMAND_WORD; public static final String MESSAGE_SUCCESS = "Task completed: %1$s"; public static final String MESSAGE_ALREADY_DONE = "Task has already been completed: %1$s"; public static final String MESSAGE_USAGE = FULL_COMMAND_WORD + ": Completes an existing task in the task list.\n" + "Parameters: INDEX (must be a positive integer) " + "Example: " + FULL_COMMAND_WORD + " 1"; private final Index index; public DoneTaskCommand(Index index) { this.index = index; } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); List<Task> taskList = model.getFilteredTaskList(); if (index.getZeroBased() >= taskList.size()) { throw new CommandException(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } Task task = taskList.get(index.getZeroBased()); if (task.getIsDone()) { throw new CommandException(String.format(MESSAGE_ALREADY_DONE, task)); } Task completedTask = new Task(task.getTitle(), task.getDescription(), task.getTimestamp(), task.getTags(), !task.getIsDone()); model.setTask(task, completedTask); return new CommandResult(String.format(MESSAGE_SUCCESS, completedTask)); } @Override public boolean equals(Object o) { return this == o || (o instanceof DoneTaskCommand && index.equals(((DoneTaskCommand) o).index)); } }
[ "public", "class", "DoneTaskCommand", "extends", "TaskCommand", "{", "public", "static", "final", "String", "COMMAND_WORD", "=", "\"", "done", "\"", ";", "public", "static", "final", "String", "FULL_COMMAND_WORD", "=", "TaskCommand", ".", "COMMAND_WORD", "+", "\"", " ", "\"", "+", "COMMAND_WORD", ";", "public", "static", "final", "String", "MESSAGE_SUCCESS", "=", "\"", "Task completed: %1$s", "\"", ";", "public", "static", "final", "String", "MESSAGE_ALREADY_DONE", "=", "\"", "Task has already been completed: %1$s", "\"", ";", "public", "static", "final", "String", "MESSAGE_USAGE", "=", "FULL_COMMAND_WORD", "+", "\"", ": Completes an existing task in the task list.", "\\n", "\"", "+", "\"", "Parameters: INDEX (must be a positive integer) ", "\"", "+", "\"", "Example: ", "\"", "+", "FULL_COMMAND_WORD", "+", "\"", " 1", "\"", ";", "private", "final", "Index", "index", ";", "public", "DoneTaskCommand", "(", "Index", "index", ")", "{", "this", ".", "index", "=", "index", ";", "}", "@", "Override", "public", "CommandResult", "execute", "(", "Model", "model", ")", "throws", "CommandException", "{", "requireNonNull", "(", "model", ")", ";", "List", "<", "Task", ">", "taskList", "=", "model", ".", "getFilteredTaskList", "(", ")", ";", "if", "(", "index", ".", "getZeroBased", "(", ")", ">=", "taskList", ".", "size", "(", ")", ")", "{", "throw", "new", "CommandException", "(", "Messages", ".", "MESSAGE_INVALID_TASK_DISPLAYED_INDEX", ")", ";", "}", "Task", "task", "=", "taskList", ".", "get", "(", "index", ".", "getZeroBased", "(", ")", ")", ";", "if", "(", "task", ".", "getIsDone", "(", ")", ")", "{", "throw", "new", "CommandException", "(", "String", ".", "format", "(", "MESSAGE_ALREADY_DONE", ",", "task", ")", ")", ";", "}", "Task", "completedTask", "=", "new", "Task", "(", "task", ".", "getTitle", "(", ")", ",", "task", ".", "getDescription", "(", ")", ",", "task", ".", "getTimestamp", "(", ")", ",", "task", ".", "getTags", "(", ")", ",", "!", "task", ".", "getIsDone", "(", ")", ")", ";", "model", ".", "setTask", "(", "task", ",", "completedTask", ")", ";", "return", "new", "CommandResult", "(", "String", ".", "format", "(", "MESSAGE_SUCCESS", ",", "completedTask", ")", ")", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "o", ")", "{", "return", "this", "==", "o", "||", "(", "o", "instanceof", "DoneTaskCommand", "&&", "index", ".", "equals", "(", "(", "(", "DoneTaskCommand", ")", "o", ")", ".", "index", ")", ")", ";", "}", "}" ]
Completes an existing task in the task list.
[ "Completes", "an", "existing", "task", "in", "the", "task", "list", "." ]
[]
[ { "param": "TaskCommand", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "TaskCommand", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69dad7f4826565690ce30e191cd904000977e112
mankeyl/elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/discovery/SnapshotDisruptionIT.java
[ "Apache-2.0" ]
Java
SnapshotDisruptionIT
/** * Tests snapshot operations during disruptions. */
Tests snapshot operations during disruptions.
[ "Tests", "snapshot", "operations", "during", "disruptions", "." ]
@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.TEST, numDataNodes = 0) public class SnapshotDisruptionIT extends AbstractSnapshotIntegTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Arrays.asList(MockTransportService.TestPlugin.class, MockRepository.Plugin.class); } @Override protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) { return Settings.builder() .put(super.nodeSettings(nodeOrdinal, otherSettings)) .put(AbstractDisruptionTestCase.DEFAULT_SETTINGS) .build(); } public void testDisruptionAfterFinalization() throws Exception { final String idxName = "test"; internalCluster().startMasterOnlyNodes(3); final String dataNode = internalCluster().startDataOnlyNode(); ensureStableCluster(4); createRandomIndex(idxName); final String repoName = "test-repo"; createRepository(repoName, "fs"); final String masterNode1 = internalCluster().getMasterName(); NetworkDisruption networkDisruption = isolateMasterDisruption(NetworkDisruption.UNRESPONSIVE); internalCluster().setDisruptionScheme(networkDisruption); ClusterService clusterService = internalCluster().clusterService(masterNode1); CountDownLatch disruptionStarted = new CountDownLatch(1); clusterService.addListener(new ClusterStateListener() { @Override public void clusterChanged(ClusterChangedEvent event) { SnapshotsInProgress snapshots = event.state().custom(SnapshotsInProgress.TYPE); if (snapshots != null && snapshots.isEmpty() == false) { final SnapshotsInProgress.Entry snapshotEntry = snapshots.forRepo(repoName).get(0); if (snapshotEntry.state() == SnapshotsInProgress.State.SUCCESS) { final RepositoriesMetadata repoMeta = event.state().metadata().custom(RepositoriesMetadata.TYPE); final RepositoryMetadata metadata = repoMeta.repository(repoName); if (metadata.pendingGeneration() > snapshotEntry.repositoryStateId()) { logger.info("--> starting disruption"); networkDisruption.startDisrupting(); clusterService.removeListener(this); disruptionStarted.countDown(); } } } } }); final String snapshot = "test-snap"; logger.info("--> starting snapshot"); ActionFuture<CreateSnapshotResponse> future = client(masterNode1).admin() .cluster() .prepareCreateSnapshot("test-repo", snapshot) .setWaitForCompletion(true) .setIndices(idxName) .execute(); logger.info("--> waiting for disruption to start"); assertTrue(disruptionStarted.await(1, TimeUnit.MINUTES)); awaitNoMoreRunningOperations(dataNode); logger.info("--> verify that snapshot was successful or no longer exist"); assertBusy(() -> { try { assertSnapshotExists("test-repo", snapshot); } catch (SnapshotMissingException exception) { logger.info("--> done verifying, snapshot doesn't exist"); } }, 1, TimeUnit.MINUTES); logger.info("--> stopping disrupting"); networkDisruption.stopDisrupting(); ensureStableCluster(4, masterNode1); logger.info("--> done"); try { future.get(); fail("Should have failed because the node disconnected from the cluster during snapshot finalization"); } catch (Exception ex) { final SnapshotException sne = (SnapshotException) ExceptionsHelper.unwrap(ex, SnapshotException.class); assertNotNull(sne); assertThat( sne.getMessage(), either(endsWith(" Failed to update cluster state during snapshot finalization")).or(endsWith(" no longer master")) ); assertThat(sne.getSnapshotName(), is(snapshot)); } awaitNoMoreRunningOperations(dataNode); } public void testDisruptionAfterShardFinalization() throws Exception { final String idxName = "test"; internalCluster().startMasterOnlyNodes(1); internalCluster().startDataOnlyNode(); ensureStableCluster(2); createIndex(idxName); index(idxName, JsonXContent.contentBuilder().startObject().field("foo", "bar").endObject()); final String repoName = "test-repo"; createRepository(repoName, "mock"); final String masterNode = internalCluster().getMasterName(); blockAllDataNodes(repoName); final String snapshot = "test-snap"; logger.info("--> starting snapshot"); ActionFuture<CreateSnapshotResponse> future = client(masterNode).admin() .cluster() .prepareCreateSnapshot(repoName, snapshot) .setWaitForCompletion(true) .execute(); waitForBlockOnAnyDataNode(repoName); NetworkDisruption networkDisruption = isolateMasterDisruption(NetworkDisruption.DISCONNECT); internalCluster().setDisruptionScheme(networkDisruption); networkDisruption.startDisrupting(); final CreateSnapshotResponse createSnapshotResponse = future.get(); final SnapshotInfo snapshotInfo = createSnapshotResponse.getSnapshotInfo(); assertThat(snapshotInfo.state(), is(SnapshotState.PARTIAL)); logger.info("--> stopping disrupting"); networkDisruption.stopDisrupting(); unblockAllDataNodes(repoName); ensureStableCluster(2, masterNode); logger.info("--> done"); logger.info("--> recreate the index with potentially different shard counts"); client().admin().indices().prepareDelete(idxName).get(); createIndex(idxName); index(idxName, JsonXContent.contentBuilder().startObject().field("foo", "bar").endObject()); logger.info("--> run a snapshot that fails to finalize but succeeds on the data node"); blockMasterFromFinalizingSnapshotOnIndexFile(repoName); final ActionFuture<CreateSnapshotResponse> snapshotFuture = client(masterNode).admin() .cluster() .prepareCreateSnapshot(repoName, "snapshot-2") .setWaitForCompletion(true) .execute(); waitForBlock(masterNode, repoName); unblockNode(repoName, masterNode); assertFutureThrows(snapshotFuture, SnapshotException.class); logger.info("--> create a snapshot expected to be successful"); final CreateSnapshotResponse successfulSnapshot = client(masterNode).admin() .cluster() .prepareCreateSnapshot(repoName, "snapshot-2") .setWaitForCompletion(true) .get(); final SnapshotInfo successfulSnapshotInfo = successfulSnapshot.getSnapshotInfo(); assertThat(successfulSnapshotInfo.state(), is(SnapshotState.SUCCESS)); logger.info("--> making sure snapshot delete works out cleanly"); assertAcked(client().admin().cluster().prepareDeleteSnapshot(repoName, "snapshot-2").get()); } public void testMasterFailOverDuringShardSnapshots() throws Exception { internalCluster().startMasterOnlyNodes(3); final String dataNode = internalCluster().startDataOnlyNode(); ensureStableCluster(4); final String repoName = "test-repo"; createRepository(repoName, "mock"); final String indexName = "index-one"; createIndex(indexName); client().prepareIndex(indexName).setSource("foo", "bar").get(); blockDataNode(repoName, dataNode); logger.info("--> create snapshot via master node client"); final ActionFuture<CreateSnapshotResponse> snapshotResponse = internalCluster().masterClient() .admin() .cluster() .prepareCreateSnapshot(repoName, "test-snap") .setWaitForCompletion(true) .execute(); waitForBlock(dataNode, repoName); final NetworkDisruption networkDisruption = isolateMasterDisruption(NetworkDisruption.DISCONNECT); internalCluster().setDisruptionScheme(networkDisruption); networkDisruption.startDisrupting(); ensureStableCluster(3, dataNode); unblockNode(repoName, dataNode); networkDisruption.stopDisrupting(); awaitNoMoreRunningOperations(dataNode); logger.info("--> make sure isolated master responds to snapshot request"); final SnapshotException sne = expectThrows( SnapshotException.class, () -> snapshotResponse.actionGet(TimeValue.timeValueSeconds(30L)) ); assertThat(sne.getMessage(), endsWith("no longer master")); } private void assertSnapshotExists(String repository, String snapshot) { GetSnapshotsResponse snapshotsStatusResponse = dataNodeClient().admin() .cluster() .prepareGetSnapshots(repository) .setSnapshots(snapshot) .get(); SnapshotInfo snapshotInfo = snapshotsStatusResponse.getSnapshots().get(0); assertEquals(SnapshotState.SUCCESS, snapshotInfo.state()); assertEquals(snapshotInfo.totalShards(), snapshotInfo.successfulShards()); assertEquals(0, snapshotInfo.failedShards()); logger.info("--> done verifying, snapshot exists"); } private void createRandomIndex(String idxName) throws InterruptedException { assertAcked(prepareCreate(idxName, 0, indexSettingsNoReplicas(between(1, 5)))); logger.info("--> indexing some data"); final int numdocs = randomIntBetween(10, 100); IndexRequestBuilder[] builders = new IndexRequestBuilder[numdocs]; for (int i = 0; i < builders.length; i++) { builders[i] = client().prepareIndex(idxName).setId(Integer.toString(i)).setSource("field1", "bar " + i); } indexRandom(true, builders); } }
[ "@", "ESIntegTestCase", ".", "ClusterScope", "(", "scope", "=", "ESIntegTestCase", ".", "Scope", ".", "TEST", ",", "numDataNodes", "=", "0", ")", "public", "class", "SnapshotDisruptionIT", "extends", "AbstractSnapshotIntegTestCase", "{", "@", "Override", "protected", "Collection", "<", "Class", "<", "?", "extends", "Plugin", ">", ">", "nodePlugins", "(", ")", "{", "return", "Arrays", ".", "asList", "(", "MockTransportService", ".", "TestPlugin", ".", "class", ",", "MockRepository", ".", "Plugin", ".", "class", ")", ";", "}", "@", "Override", "protected", "Settings", "nodeSettings", "(", "int", "nodeOrdinal", ",", "Settings", "otherSettings", ")", "{", "return", "Settings", ".", "builder", "(", ")", ".", "put", "(", "super", ".", "nodeSettings", "(", "nodeOrdinal", ",", "otherSettings", ")", ")", ".", "put", "(", "AbstractDisruptionTestCase", ".", "DEFAULT_SETTINGS", ")", ".", "build", "(", ")", ";", "}", "public", "void", "testDisruptionAfterFinalization", "(", ")", "throws", "Exception", "{", "final", "String", "idxName", "=", "\"", "test", "\"", ";", "internalCluster", "(", ")", ".", "startMasterOnlyNodes", "(", "3", ")", ";", "final", "String", "dataNode", "=", "internalCluster", "(", ")", ".", "startDataOnlyNode", "(", ")", ";", "ensureStableCluster", "(", "4", ")", ";", "createRandomIndex", "(", "idxName", ")", ";", "final", "String", "repoName", "=", "\"", "test-repo", "\"", ";", "createRepository", "(", "repoName", ",", "\"", "fs", "\"", ")", ";", "final", "String", "masterNode1", "=", "internalCluster", "(", ")", ".", "getMasterName", "(", ")", ";", "NetworkDisruption", "networkDisruption", "=", "isolateMasterDisruption", "(", "NetworkDisruption", ".", "UNRESPONSIVE", ")", ";", "internalCluster", "(", ")", ".", "setDisruptionScheme", "(", "networkDisruption", ")", ";", "ClusterService", "clusterService", "=", "internalCluster", "(", ")", ".", "clusterService", "(", "masterNode1", ")", ";", "CountDownLatch", "disruptionStarted", "=", "new", "CountDownLatch", "(", "1", ")", ";", "clusterService", ".", "addListener", "(", "new", "ClusterStateListener", "(", ")", "{", "@", "Override", "public", "void", "clusterChanged", "(", "ClusterChangedEvent", "event", ")", "{", "SnapshotsInProgress", "snapshots", "=", "event", ".", "state", "(", ")", ".", "custom", "(", "SnapshotsInProgress", ".", "TYPE", ")", ";", "if", "(", "snapshots", "!=", "null", "&&", "snapshots", ".", "isEmpty", "(", ")", "==", "false", ")", "{", "final", "SnapshotsInProgress", ".", "Entry", "snapshotEntry", "=", "snapshots", ".", "forRepo", "(", "repoName", ")", ".", "get", "(", "0", ")", ";", "if", "(", "snapshotEntry", ".", "state", "(", ")", "==", "SnapshotsInProgress", ".", "State", ".", "SUCCESS", ")", "{", "final", "RepositoriesMetadata", "repoMeta", "=", "event", ".", "state", "(", ")", ".", "metadata", "(", ")", ".", "custom", "(", "RepositoriesMetadata", ".", "TYPE", ")", ";", "final", "RepositoryMetadata", "metadata", "=", "repoMeta", ".", "repository", "(", "repoName", ")", ";", "if", "(", "metadata", ".", "pendingGeneration", "(", ")", ">", "snapshotEntry", ".", "repositoryStateId", "(", ")", ")", "{", "logger", ".", "info", "(", "\"", "--> starting disruption", "\"", ")", ";", "networkDisruption", ".", "startDisrupting", "(", ")", ";", "clusterService", ".", "removeListener", "(", "this", ")", ";", "disruptionStarted", ".", "countDown", "(", ")", ";", "}", "}", "}", "}", "}", ")", ";", "final", "String", "snapshot", "=", "\"", "test-snap", "\"", ";", "logger", ".", "info", "(", "\"", "--> starting snapshot", "\"", ")", ";", "ActionFuture", "<", "CreateSnapshotResponse", ">", "future", "=", "client", "(", "masterNode1", ")", ".", "admin", "(", ")", ".", "cluster", "(", ")", ".", "prepareCreateSnapshot", "(", "\"", "test-repo", "\"", ",", "snapshot", ")", ".", "setWaitForCompletion", "(", "true", ")", ".", "setIndices", "(", "idxName", ")", ".", "execute", "(", ")", ";", "logger", ".", "info", "(", "\"", "--> waiting for disruption to start", "\"", ")", ";", "assertTrue", "(", "disruptionStarted", ".", "await", "(", "1", ",", "TimeUnit", ".", "MINUTES", ")", ")", ";", "awaitNoMoreRunningOperations", "(", "dataNode", ")", ";", "logger", ".", "info", "(", "\"", "--> verify that snapshot was successful or no longer exist", "\"", ")", ";", "assertBusy", "(", "(", ")", "->", "{", "try", "{", "assertSnapshotExists", "(", "\"", "test-repo", "\"", ",", "snapshot", ")", ";", "}", "catch", "(", "SnapshotMissingException", "exception", ")", "{", "logger", ".", "info", "(", "\"", "--> done verifying, snapshot doesn't exist", "\"", ")", ";", "}", "}", ",", "1", ",", "TimeUnit", ".", "MINUTES", ")", ";", "logger", ".", "info", "(", "\"", "--> stopping disrupting", "\"", ")", ";", "networkDisruption", ".", "stopDisrupting", "(", ")", ";", "ensureStableCluster", "(", "4", ",", "masterNode1", ")", ";", "logger", ".", "info", "(", "\"", "--> done", "\"", ")", ";", "try", "{", "future", ".", "get", "(", ")", ";", "fail", "(", "\"", "Should have failed because the node disconnected from the cluster during snapshot finalization", "\"", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "final", "SnapshotException", "sne", "=", "(", "SnapshotException", ")", "ExceptionsHelper", ".", "unwrap", "(", "ex", ",", "SnapshotException", ".", "class", ")", ";", "assertNotNull", "(", "sne", ")", ";", "assertThat", "(", "sne", ".", "getMessage", "(", ")", ",", "either", "(", "endsWith", "(", "\"", " Failed to update cluster state during snapshot finalization", "\"", ")", ")", ".", "or", "(", "endsWith", "(", "\"", " no longer master", "\"", ")", ")", ")", ";", "assertThat", "(", "sne", ".", "getSnapshotName", "(", ")", ",", "is", "(", "snapshot", ")", ")", ";", "}", "awaitNoMoreRunningOperations", "(", "dataNode", ")", ";", "}", "public", "void", "testDisruptionAfterShardFinalization", "(", ")", "throws", "Exception", "{", "final", "String", "idxName", "=", "\"", "test", "\"", ";", "internalCluster", "(", ")", ".", "startMasterOnlyNodes", "(", "1", ")", ";", "internalCluster", "(", ")", ".", "startDataOnlyNode", "(", ")", ";", "ensureStableCluster", "(", "2", ")", ";", "createIndex", "(", "idxName", ")", ";", "index", "(", "idxName", ",", "JsonXContent", ".", "contentBuilder", "(", ")", ".", "startObject", "(", ")", ".", "field", "(", "\"", "foo", "\"", ",", "\"", "bar", "\"", ")", ".", "endObject", "(", ")", ")", ";", "final", "String", "repoName", "=", "\"", "test-repo", "\"", ";", "createRepository", "(", "repoName", ",", "\"", "mock", "\"", ")", ";", "final", "String", "masterNode", "=", "internalCluster", "(", ")", ".", "getMasterName", "(", ")", ";", "blockAllDataNodes", "(", "repoName", ")", ";", "final", "String", "snapshot", "=", "\"", "test-snap", "\"", ";", "logger", ".", "info", "(", "\"", "--> starting snapshot", "\"", ")", ";", "ActionFuture", "<", "CreateSnapshotResponse", ">", "future", "=", "client", "(", "masterNode", ")", ".", "admin", "(", ")", ".", "cluster", "(", ")", ".", "prepareCreateSnapshot", "(", "repoName", ",", "snapshot", ")", ".", "setWaitForCompletion", "(", "true", ")", ".", "execute", "(", ")", ";", "waitForBlockOnAnyDataNode", "(", "repoName", ")", ";", "NetworkDisruption", "networkDisruption", "=", "isolateMasterDisruption", "(", "NetworkDisruption", ".", "DISCONNECT", ")", ";", "internalCluster", "(", ")", ".", "setDisruptionScheme", "(", "networkDisruption", ")", ";", "networkDisruption", ".", "startDisrupting", "(", ")", ";", "final", "CreateSnapshotResponse", "createSnapshotResponse", "=", "future", ".", "get", "(", ")", ";", "final", "SnapshotInfo", "snapshotInfo", "=", "createSnapshotResponse", ".", "getSnapshotInfo", "(", ")", ";", "assertThat", "(", "snapshotInfo", ".", "state", "(", ")", ",", "is", "(", "SnapshotState", ".", "PARTIAL", ")", ")", ";", "logger", ".", "info", "(", "\"", "--> stopping disrupting", "\"", ")", ";", "networkDisruption", ".", "stopDisrupting", "(", ")", ";", "unblockAllDataNodes", "(", "repoName", ")", ";", "ensureStableCluster", "(", "2", ",", "masterNode", ")", ";", "logger", ".", "info", "(", "\"", "--> done", "\"", ")", ";", "logger", ".", "info", "(", "\"", "--> recreate the index with potentially different shard counts", "\"", ")", ";", "client", "(", ")", ".", "admin", "(", ")", ".", "indices", "(", ")", ".", "prepareDelete", "(", "idxName", ")", ".", "get", "(", ")", ";", "createIndex", "(", "idxName", ")", ";", "index", "(", "idxName", ",", "JsonXContent", ".", "contentBuilder", "(", ")", ".", "startObject", "(", ")", ".", "field", "(", "\"", "foo", "\"", ",", "\"", "bar", "\"", ")", ".", "endObject", "(", ")", ")", ";", "logger", ".", "info", "(", "\"", "--> run a snapshot that fails to finalize but succeeds on the data node", "\"", ")", ";", "blockMasterFromFinalizingSnapshotOnIndexFile", "(", "repoName", ")", ";", "final", "ActionFuture", "<", "CreateSnapshotResponse", ">", "snapshotFuture", "=", "client", "(", "masterNode", ")", ".", "admin", "(", ")", ".", "cluster", "(", ")", ".", "prepareCreateSnapshot", "(", "repoName", ",", "\"", "snapshot-2", "\"", ")", ".", "setWaitForCompletion", "(", "true", ")", ".", "execute", "(", ")", ";", "waitForBlock", "(", "masterNode", ",", "repoName", ")", ";", "unblockNode", "(", "repoName", ",", "masterNode", ")", ";", "assertFutureThrows", "(", "snapshotFuture", ",", "SnapshotException", ".", "class", ")", ";", "logger", ".", "info", "(", "\"", "--> create a snapshot expected to be successful", "\"", ")", ";", "final", "CreateSnapshotResponse", "successfulSnapshot", "=", "client", "(", "masterNode", ")", ".", "admin", "(", ")", ".", "cluster", "(", ")", ".", "prepareCreateSnapshot", "(", "repoName", ",", "\"", "snapshot-2", "\"", ")", ".", "setWaitForCompletion", "(", "true", ")", ".", "get", "(", ")", ";", "final", "SnapshotInfo", "successfulSnapshotInfo", "=", "successfulSnapshot", ".", "getSnapshotInfo", "(", ")", ";", "assertThat", "(", "successfulSnapshotInfo", ".", "state", "(", ")", ",", "is", "(", "SnapshotState", ".", "SUCCESS", ")", ")", ";", "logger", ".", "info", "(", "\"", "--> making sure snapshot delete works out cleanly", "\"", ")", ";", "assertAcked", "(", "client", "(", ")", ".", "admin", "(", ")", ".", "cluster", "(", ")", ".", "prepareDeleteSnapshot", "(", "repoName", ",", "\"", "snapshot-2", "\"", ")", ".", "get", "(", ")", ")", ";", "}", "public", "void", "testMasterFailOverDuringShardSnapshots", "(", ")", "throws", "Exception", "{", "internalCluster", "(", ")", ".", "startMasterOnlyNodes", "(", "3", ")", ";", "final", "String", "dataNode", "=", "internalCluster", "(", ")", ".", "startDataOnlyNode", "(", ")", ";", "ensureStableCluster", "(", "4", ")", ";", "final", "String", "repoName", "=", "\"", "test-repo", "\"", ";", "createRepository", "(", "repoName", ",", "\"", "mock", "\"", ")", ";", "final", "String", "indexName", "=", "\"", "index-one", "\"", ";", "createIndex", "(", "indexName", ")", ";", "client", "(", ")", ".", "prepareIndex", "(", "indexName", ")", ".", "setSource", "(", "\"", "foo", "\"", ",", "\"", "bar", "\"", ")", ".", "get", "(", ")", ";", "blockDataNode", "(", "repoName", ",", "dataNode", ")", ";", "logger", ".", "info", "(", "\"", "--> create snapshot via master node client", "\"", ")", ";", "final", "ActionFuture", "<", "CreateSnapshotResponse", ">", "snapshotResponse", "=", "internalCluster", "(", ")", ".", "masterClient", "(", ")", ".", "admin", "(", ")", ".", "cluster", "(", ")", ".", "prepareCreateSnapshot", "(", "repoName", ",", "\"", "test-snap", "\"", ")", ".", "setWaitForCompletion", "(", "true", ")", ".", "execute", "(", ")", ";", "waitForBlock", "(", "dataNode", ",", "repoName", ")", ";", "final", "NetworkDisruption", "networkDisruption", "=", "isolateMasterDisruption", "(", "NetworkDisruption", ".", "DISCONNECT", ")", ";", "internalCluster", "(", ")", ".", "setDisruptionScheme", "(", "networkDisruption", ")", ";", "networkDisruption", ".", "startDisrupting", "(", ")", ";", "ensureStableCluster", "(", "3", ",", "dataNode", ")", ";", "unblockNode", "(", "repoName", ",", "dataNode", ")", ";", "networkDisruption", ".", "stopDisrupting", "(", ")", ";", "awaitNoMoreRunningOperations", "(", "dataNode", ")", ";", "logger", ".", "info", "(", "\"", "--> make sure isolated master responds to snapshot request", "\"", ")", ";", "final", "SnapshotException", "sne", "=", "expectThrows", "(", "SnapshotException", ".", "class", ",", "(", ")", "->", "snapshotResponse", ".", "actionGet", "(", "TimeValue", ".", "timeValueSeconds", "(", "30L", ")", ")", ")", ";", "assertThat", "(", "sne", ".", "getMessage", "(", ")", ",", "endsWith", "(", "\"", "no longer master", "\"", ")", ")", ";", "}", "private", "void", "assertSnapshotExists", "(", "String", "repository", ",", "String", "snapshot", ")", "{", "GetSnapshotsResponse", "snapshotsStatusResponse", "=", "dataNodeClient", "(", ")", ".", "admin", "(", ")", ".", "cluster", "(", ")", ".", "prepareGetSnapshots", "(", "repository", ")", ".", "setSnapshots", "(", "snapshot", ")", ".", "get", "(", ")", ";", "SnapshotInfo", "snapshotInfo", "=", "snapshotsStatusResponse", ".", "getSnapshots", "(", ")", ".", "get", "(", "0", ")", ";", "assertEquals", "(", "SnapshotState", ".", "SUCCESS", ",", "snapshotInfo", ".", "state", "(", ")", ")", ";", "assertEquals", "(", "snapshotInfo", ".", "totalShards", "(", ")", ",", "snapshotInfo", ".", "successfulShards", "(", ")", ")", ";", "assertEquals", "(", "0", ",", "snapshotInfo", ".", "failedShards", "(", ")", ")", ";", "logger", ".", "info", "(", "\"", "--> done verifying, snapshot exists", "\"", ")", ";", "}", "private", "void", "createRandomIndex", "(", "String", "idxName", ")", "throws", "InterruptedException", "{", "assertAcked", "(", "prepareCreate", "(", "idxName", ",", "0", ",", "indexSettingsNoReplicas", "(", "between", "(", "1", ",", "5", ")", ")", ")", ")", ";", "logger", ".", "info", "(", "\"", "--> indexing some data", "\"", ")", ";", "final", "int", "numdocs", "=", "randomIntBetween", "(", "10", ",", "100", ")", ";", "IndexRequestBuilder", "[", "]", "builders", "=", "new", "IndexRequestBuilder", "[", "numdocs", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "builders", ".", "length", ";", "i", "++", ")", "{", "builders", "[", "i", "]", "=", "client", "(", ")", ".", "prepareIndex", "(", "idxName", ")", ".", "setId", "(", "Integer", ".", "toString", "(", "i", ")", ")", ".", "setSource", "(", "\"", "field1", "\"", ",", "\"", "bar ", "\"", "+", "i", ")", ";", "}", "indexRandom", "(", "true", ",", "builders", ")", ";", "}", "}" ]
Tests snapshot operations during disruptions.
[ "Tests", "snapshot", "operations", "during", "disruptions", "." ]
[]
[ { "param": "AbstractSnapshotIntegTestCase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractSnapshotIntegTestCase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69dd68869bec0b745bafcb799be20980a2a6a4df
watchful-sky/WatchfulSky
app/src/main/java/ca/mun/engi5895/watchfulsky/OrekitDataInstallation/MyApplication.java
[ "MIT" ]
Java
MyApplication
/** * Class representing the android application */
Class representing the android application
[ "Class", "representing", "the", "android", "application" ]
public class MyApplication extends Application { /** * Ran once, when the application starts up */ @Override public void onCreate() { super.onCreate(); Log.i("main", "onCreate fired"); } }
[ "public", "class", "MyApplication", "extends", "Application", "{", "/**\n * Ran once, when the application starts up\n */", "@", "Override", "public", "void", "onCreate", "(", ")", "{", "super", ".", "onCreate", "(", ")", ";", "Log", ".", "i", "(", "\"", "main", "\"", ",", "\"", "onCreate fired", "\"", ")", ";", "}", "}" ]
Class representing the android application
[ "Class", "representing", "the", "android", "application" ]
[]
[ { "param": "Application", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Application", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69ded2db61237c3886234a9fe5d95c1130fc999b
Omarkojak/chat-application
src/Misc/Message.java
[ "MIT" ]
Java
Message
/** * Created by mohamedelzarei on 11/22/16. * [email protected] */
Created by mohamedelzarei on 11/22/16.
[ "Created", "by", "mohamedelzarei", "on", "11", "/", "22", "/", "16", "." ]
public class Message implements Serializable{ public String from; public String to; public Object data; public MessageType type; public int TTL; public int loginClient; public Message(MessageType type, String from, String to, Object data) { this.type = type; this.from = from; this.to = to; this.data = data; this.TTL = 4; } public Message(MessageType type, Object data) { this.type = type; this.data = data; this.TTL = 4; } public boolean isAlive(){ return TTL > 0; } public void decreaseTTL() { TTL--; } }
[ "public", "class", "Message", "implements", "Serializable", "{", "public", "String", "from", ";", "public", "String", "to", ";", "public", "Object", "data", ";", "public", "MessageType", "type", ";", "public", "int", "TTL", ";", "public", "int", "loginClient", ";", "public", "Message", "(", "MessageType", "type", ",", "String", "from", ",", "String", "to", ",", "Object", "data", ")", "{", "this", ".", "type", "=", "type", ";", "this", ".", "from", "=", "from", ";", "this", ".", "to", "=", "to", ";", "this", ".", "data", "=", "data", ";", "this", ".", "TTL", "=", "4", ";", "}", "public", "Message", "(", "MessageType", "type", ",", "Object", "data", ")", "{", "this", ".", "type", "=", "type", ";", "this", ".", "data", "=", "data", ";", "this", ".", "TTL", "=", "4", ";", "}", "public", "boolean", "isAlive", "(", ")", "{", "return", "TTL", ">", "0", ";", "}", "public", "void", "decreaseTTL", "(", ")", "{", "TTL", "--", ";", "}", "}" ]
Created by mohamedelzarei on 11/22/16.
[ "Created", "by", "mohamedelzarei", "on", "11", "/", "22", "/", "16", "." ]
[]
[ { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69e1670cd05f4be59fe878b3865ad8af7f26a459
fjchica/hazelcast-monitor
hazelcast-monitor-agent/src/main/java/io/github/daniloarcidiacono/hazelcast/monitor/agent/dto/topic/DistributedObjectStatsTopic.java
[ "MIT" ]
Java
DistributedObjectStatsTopic
/** * Topic for a specific distributed object */
Topic for a specific distributed object
[ "Topic", "for", "a", "specific", "distributed", "object" ]
@TypescriptDTO public class DistributedObjectStatsTopic extends AbstractTopic { public static final String TOPIC_TYPE = DistributedObjectStatsTopicProducer.TOPIC_TYPE; private DistributedObjectType distributedObjectType; private String objectName; @JsonCreator public DistributedObjectStatsTopic(@JsonProperty("instanceName") final String instanceName, @JsonProperty("objectName") final String objectName) { super(TOPIC_TYPE, instanceName); this.objectName = objectName; } public String getObjectName() { return objectName; } public void setObjectName(String objectName) { this.objectName = objectName; } public DistributedObjectType getDistributedObjectType() { return distributedObjectType; } public void setDistributedObjectType(DistributedObjectType distributedObjectType) { this.distributedObjectType = distributedObjectType; } }
[ "@", "TypescriptDTO", "public", "class", "DistributedObjectStatsTopic", "extends", "AbstractTopic", "{", "public", "static", "final", "String", "TOPIC_TYPE", "=", "DistributedObjectStatsTopicProducer", ".", "TOPIC_TYPE", ";", "private", "DistributedObjectType", "distributedObjectType", ";", "private", "String", "objectName", ";", "@", "JsonCreator", "public", "DistributedObjectStatsTopic", "(", "@", "JsonProperty", "(", "\"", "instanceName", "\"", ")", "final", "String", "instanceName", ",", "@", "JsonProperty", "(", "\"", "objectName", "\"", ")", "final", "String", "objectName", ")", "{", "super", "(", "TOPIC_TYPE", ",", "instanceName", ")", ";", "this", ".", "objectName", "=", "objectName", ";", "}", "public", "String", "getObjectName", "(", ")", "{", "return", "objectName", ";", "}", "public", "void", "setObjectName", "(", "String", "objectName", ")", "{", "this", ".", "objectName", "=", "objectName", ";", "}", "public", "DistributedObjectType", "getDistributedObjectType", "(", ")", "{", "return", "distributedObjectType", ";", "}", "public", "void", "setDistributedObjectType", "(", "DistributedObjectType", "distributedObjectType", ")", "{", "this", ".", "distributedObjectType", "=", "distributedObjectType", ";", "}", "}" ]
Topic for a specific distributed object
[ "Topic", "for", "a", "specific", "distributed", "object" ]
[]
[ { "param": "AbstractTopic", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractTopic", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69e17d37f55e48d8d03d61bbdd37440bdacb3e99
zj-dreamly/my-program-learning
java/jvm/chapter01_bytecode/src/com/atguigu/java3/InterviewTest.java
[ "Apache-2.0" ]
Java
InterviewTest
/** * @author shkstart * @create 14:52 */
@author shkstart @create 14:52
[ "@author", "shkstart", "@create", "14", ":", "52" ]
public class InterviewTest { @Test public void test1(){ Integer x = 128; int y = 128; System.out.println(x == y);//true } }
[ "public", "class", "InterviewTest", "{", "@", "Test", "public", "void", "test1", "(", ")", "{", "Integer", "x", "=", "128", ";", "int", "y", "=", "128", ";", "System", ".", "out", ".", "println", "(", "x", "==", "y", ")", ";", "}", "}" ]
@author shkstart @create 14:52
[ "@author", "shkstart", "@create", "14", ":", "52" ]
[ "//true" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
69e590f766cfe440c499b33428d079166c466131
Kaisir/itpub
src/com/wisedu/emap/itpub/bean/soap/UserAppRequest.java
[ "Apache-2.0" ]
Java
UserAppRequest
/** * <p> * Java class for userAppRequest complex type. * * <p> * The following schema fragment specifies the expected content contained within * this class. * * <pre> * &lt;complexType name="userAppRequest"> * &lt;complexContent> * &lt;extension base="{http://app.ws.api.mdbservice.wisedu.com/}baseRequest"> * &lt;sequence> * &lt;element name="appId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="userId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */
Java class for userAppRequest complex type. The following schema fragment specifies the expected content contained within this class.
[ "Java", "class", "for", "userAppRequest", "complex", "type", ".", "The", "following", "schema", "fragment", "specifies", "the", "expected", "content", "contained", "within", "this", "class", "." ]
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "userAppRequest", propOrder = { "appId", "userId" }) public class UserAppRequest extends BaseRequest { protected String appId; protected String userId; /** * Gets the value of the appId property. * * @return possible object is {@link String } * */ public String getAppId() { return appId; } /** * Sets the value of the appId property. * * @param value * allowed object is {@link String } * */ public void setAppId(String value) { this.appId = value; } /** * Gets the value of the userId property. * * @return possible object is {@link String } * */ public String getUserId() { return userId; } /** * Sets the value of the userId property. * * @param value * allowed object is {@link String } * */ public void setUserId(String value) { this.userId = value; } }
[ "@", "XmlAccessorType", "(", "XmlAccessType", ".", "FIELD", ")", "@", "XmlType", "(", "name", "=", "\"", "userAppRequest", "\"", ",", "propOrder", "=", "{", "\"", "appId", "\"", ",", "\"", "userId", "\"", "}", ")", "public", "class", "UserAppRequest", "extends", "BaseRequest", "{", "protected", "String", "appId", ";", "protected", "String", "userId", ";", "/**\n\t * Gets the value of the appId property.\n\t * \n\t * @return possible object is {@link String }\n\t * \n\t */", "public", "String", "getAppId", "(", ")", "{", "return", "appId", ";", "}", "/**\n\t * Sets the value of the appId property.\n\t * \n\t * @param value\n\t * allowed object is {@link String }\n\t * \n\t */", "public", "void", "setAppId", "(", "String", "value", ")", "{", "this", ".", "appId", "=", "value", ";", "}", "/**\n\t * Gets the value of the userId property.\n\t * \n\t * @return possible object is {@link String }\n\t * \n\t */", "public", "String", "getUserId", "(", ")", "{", "return", "userId", ";", "}", "/**\n\t * Sets the value of the userId property.\n\t * \n\t * @param value\n\t * allowed object is {@link String }\n\t * \n\t */", "public", "void", "setUserId", "(", "String", "value", ")", "{", "this", ".", "userId", "=", "value", ";", "}", "}" ]
<p> Java class for userAppRequest complex type.
[ "<p", ">", "Java", "class", "for", "userAppRequest", "complex", "type", "." ]
[]
[ { "param": "BaseRequest", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseRequest", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69e88ada69133c4600f544d37a84d54e065d4c2e
elsudano/Facultad
02Segundo/Programacion_Diseno_Orientada_Objetos_PDOO/Napakalaki/src/napakalaki/Treasure.java
[ "MIT" ]
Java
Treasure
/** * Clase Tesoro, se encarga gestionar todos los datos que contienen los tesoros * que proporcionan las ventajas al jugador para poder enfrentarse a los * monstruos * * @author: Carlos de la Torre */
Clase Tesoro, se encarga gestionar todos los datos que contienen los tesoros que proporcionan las ventajas al jugador para poder enfrentarse a los monstruos @author: Carlos de la Torre
[ "Clase", "Tesoro", "se", "encarga", "gestionar", "todos", "los", "datos", "que", "contienen", "los", "tesoros", "que", "proporcionan", "las", "ventajas", "al", "jugador", "para", "poder", "enfrentarse", "a", "los", "monstruos", "@author", ":", "Carlos", "de", "la", "Torre" ]
public class Treasure implements Card { /** * Variable con el nombre del tesoro. */ private String name; /** * Variable con la cantidad de monedas de oro que tiene el tesoro. */ private int goldCoins; /** * Variable del valor minimo del bonus del tesoro. */ private int minBonus; /** * Variable del valor maximo del bonus del tesoro. */ private int maxBonus; /** * Variable con el tipo de Tesoroa que se almacena. */ private TreasureKind type; /** * Constructor con parametros, se encarga de inicializar el tesoro con todos * los datos * * @param n nombre del tesoro * @param g cantidad de monedas de oro que tiene el tesoro * @param min bonus minimo que tiene el tesoro * @param max bonus maximo que tiene el tesoro * @param t tipo de tesoro que tiene dentro */ public Treasure(String n, int g, int min, int max, TreasureKind t) { this.name = n; this.goldCoins = g; this.minBonus = min; this.maxBonus = max; this.type = t; } /** * Constructor de copia (en profundidad), que simplemente copia todos los * atributos del objeto en otro lugar de la memoria. * @param t El objeto de tipo Treasure que queremos copiar. */ public Treasure(Treasure t){ this.name = t.name; this.minBonus = t.minBonus; this.maxBonus = t.maxBonus; this.goldCoins = t.goldCoins; this.type = t.type; } /** * Consultor de la cantidad de monedas que tiene el tesoro. * * @return numero entero con la cantidad de monedas de oro. */ public int getGoldCoins() { return this.goldCoins; } /** * Consultor del tipo de tesoro que tiene dentro * * @return devuelve un objeto de tipo TreasureKind del tipo que corresponde */ public TreasureKind getType() { return this.type; } /** * Consultor del valor minimo de bonus que se consigue con el tesoro * * @return numero entero con el valor minimo que tiene el tesoro */ public int getMinBonus() { return this.minBonus; } /** * Consultor del valor maximo de bonus que se consigue con el tesoro * * @return numero entero con el valor maximo que tiene el tesoro */ public int getMaxBonus() { return this.maxBonus; } /** * Consultor del nombre del tesoro * * @return cadena de caracteres con el valor del nombre del tesoro */ @Override public String getName() { return this.name; } /** * Consultor del atributo de bonus minimo * @return devuelve un entero con el nivel minimo que proporciona el tesoro */ @Override public int getBasicValue() { return this.getMinBonus(); } /** * Consultor del atributo de bonus máximo * @return devuelve un entero con el nivel máximo que proporciona el tesoro */ @Override public int getSpecialValue() { return this.getMaxBonus(); } @Override public String toString() { return "Nombre tesoro: " + this.name + " (" + this.type.toString() + ") " + "\nBonus mínimo = " + this.minBonus + "\nBonus máximo = " + this.maxBonus + "\nPiezas de Oro = " + this.goldCoins; } }
[ "public", "class", "Treasure", "implements", "Card", "{", "/**\n * Variable con el nombre del tesoro.\n */", "private", "String", "name", ";", "/**\n * Variable con la cantidad de monedas de oro que tiene el tesoro.\n */", "private", "int", "goldCoins", ";", "/**\n * Variable del valor minimo del bonus del tesoro.\n */", "private", "int", "minBonus", ";", "/**\n * Variable del valor maximo del bonus del tesoro.\n */", "private", "int", "maxBonus", ";", "/**\n * Variable con el tipo de Tesoroa que se almacena.\n */", "private", "TreasureKind", "type", ";", "/**\n * Constructor con parametros, se encarga de inicializar el tesoro con todos\n * los datos\n *\n * @param n nombre del tesoro\n * @param g cantidad de monedas de oro que tiene el tesoro\n * @param min bonus minimo que tiene el tesoro\n * @param max bonus maximo que tiene el tesoro\n * @param t tipo de tesoro que tiene dentro\n */", "public", "Treasure", "(", "String", "n", ",", "int", "g", ",", "int", "min", ",", "int", "max", ",", "TreasureKind", "t", ")", "{", "this", ".", "name", "=", "n", ";", "this", ".", "goldCoins", "=", "g", ";", "this", ".", "minBonus", "=", "min", ";", "this", ".", "maxBonus", "=", "max", ";", "this", ".", "type", "=", "t", ";", "}", "/**\n * Constructor de copia (en profundidad), que simplemente copia todos los\n * atributos del objeto en otro lugar de la memoria.\n * @param t El objeto de tipo Treasure que queremos copiar.\n */", "public", "Treasure", "(", "Treasure", "t", ")", "{", "this", ".", "name", "=", "t", ".", "name", ";", "this", ".", "minBonus", "=", "t", ".", "minBonus", ";", "this", ".", "maxBonus", "=", "t", ".", "maxBonus", ";", "this", ".", "goldCoins", "=", "t", ".", "goldCoins", ";", "this", ".", "type", "=", "t", ".", "type", ";", "}", "/**\n * Consultor de la cantidad de monedas que tiene el tesoro.\n *\n * @return numero entero con la cantidad de monedas de oro.\n */", "public", "int", "getGoldCoins", "(", ")", "{", "return", "this", ".", "goldCoins", ";", "}", "/**\n * Consultor del tipo de tesoro que tiene dentro\n *\n * @return devuelve un objeto de tipo TreasureKind del tipo que corresponde\n */", "public", "TreasureKind", "getType", "(", ")", "{", "return", "this", ".", "type", ";", "}", "/**\n * Consultor del valor minimo de bonus que se consigue con el tesoro\n *\n * @return numero entero con el valor minimo que tiene el tesoro\n */", "public", "int", "getMinBonus", "(", ")", "{", "return", "this", ".", "minBonus", ";", "}", "/**\n * Consultor del valor maximo de bonus que se consigue con el tesoro\n *\n * @return numero entero con el valor maximo que tiene el tesoro\n */", "public", "int", "getMaxBonus", "(", ")", "{", "return", "this", ".", "maxBonus", ";", "}", "/**\n * Consultor del nombre del tesoro\n *\n * @return cadena de caracteres con el valor del nombre del tesoro\n */", "@", "Override", "public", "String", "getName", "(", ")", "{", "return", "this", ".", "name", ";", "}", "/**\n * Consultor del atributo de bonus minimo\n * @return devuelve un entero con el nivel minimo que proporciona el tesoro\n */", "@", "Override", "public", "int", "getBasicValue", "(", ")", "{", "return", "this", ".", "getMinBonus", "(", ")", ";", "}", "/**\n * Consultor del atributo de bonus máximo\n * @return devuelve un entero con el nivel máximo que proporciona el tesoro\n */", "@", "Override", "public", "int", "getSpecialValue", "(", ")", "{", "return", "this", ".", "getMaxBonus", "(", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "Nombre tesoro: ", "\"", "+", "this", ".", "name", "+", "\"", " (", "\"", "+", "this", ".", "type", ".", "toString", "(", ")", "+", "\"", ") ", "\"", "+", "\"", "\\n", "Bonus mínimo = \"", " ", " ", "his.", "m", "inBonus", "+", "\"", "\\n", "Bonus máximo = \"", " ", " ", "his.", "m", "axBonus", "+", "\"", "\\n", "Piezas de Oro = ", "\"", "+", "this", ".", "goldCoins", ";", "}", "}" ]
Clase Tesoro, se encarga gestionar todos los datos que contienen los tesoros que proporcionan las ventajas al jugador para poder enfrentarse a los monstruos
[ "Clase", "Tesoro", "se", "encarga", "gestionar", "todos", "los", "datos", "que", "contienen", "los", "tesoros", "que", "proporcionan", "las", "ventajas", "al", "jugador", "para", "poder", "enfrentarse", "a", "los", "monstruos" ]
[]
[ { "param": "Card", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Card", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
69edc757ce8a11165fa67f66aabeb139fc8a016e
Pixelated-Project/aosp-android-jar
android-31/src/android/net/util/SocketUtils.java
[ "MIT" ]
Java
SocketUtils
/** * Collection of utilities to interact with raw sockets. * @hide */
Collection of utilities to interact with raw sockets. @hide
[ "Collection", "of", "utilities", "to", "interact", "with", "raw", "sockets", ".", "@hide" ]
@SystemApi public final class SocketUtils { /** * Create a raw datagram socket that is bound to an interface. * * <p>Data sent through the socket will go directly to the underlying network, ignoring VPNs. */ public static void bindSocketToInterface(@NonNull FileDescriptor socket, @NonNull String iface) throws ErrnoException { // SO_BINDTODEVICE actually takes a string. This works because the first member // of struct ifreq is a NULL-terminated interface name. // TODO: add a setsockoptString() Os.setsockoptIfreq(socket, SOL_SOCKET, SO_BINDTODEVICE, iface); NetworkUtilsInternal.protectFromVpn(socket); } /** * Make a socket address to communicate with netlink. */ @NonNull public static SocketAddress makeNetlinkSocketAddress(int portId, int groupsMask) { return new NetlinkSocketAddress(portId, groupsMask); } /** * Make socket address that packet sockets can bind to. * * @param protocol the layer 2 protocol of the packets to receive. One of the {@code ETH_P_*} * constants in {@link android.system.OsConstants}. * @param ifIndex the interface index on which packets will be received. */ @NonNull public static SocketAddress makePacketSocketAddress(int protocol, int ifIndex) { return new PacketSocketAddress( protocol /* sll_protocol */, ifIndex /* sll_ifindex */, null /* sll_addr */); } /** * Make a socket address that packet socket can send packets to. * @deprecated Use {@link #makePacketSocketAddress(int, int, byte[])} instead. * * @param ifIndex the interface index on which packets will be sent. * @param hwAddr the hardware address to which packets will be sent. */ @Deprecated @NonNull public static SocketAddress makePacketSocketAddress(int ifIndex, @NonNull byte[] hwAddr) { return new PacketSocketAddress( 0 /* sll_protocol */, ifIndex /* sll_ifindex */, hwAddr /* sll_addr */); } /** * Make a socket address that a packet socket can send packets to. * * @param protocol the layer 2 protocol of the packets to send. One of the {@code ETH_P_*} * constants in {@link android.system.OsConstants}. * @param ifIndex the interface index on which packets will be sent. * @param hwAddr the hardware address to which packets will be sent. */ @NonNull public static SocketAddress makePacketSocketAddress(int protocol, int ifIndex, @NonNull byte[] hwAddr) { return new PacketSocketAddress( protocol /* sll_protocol */, ifIndex /* sll_ifindex */, hwAddr /* sll_addr */); } /** * @see IoBridge#closeAndSignalBlockedThreads(FileDescriptor) */ public static void closeSocket(@Nullable FileDescriptor fd) throws IOException { IoBridge.closeAndSignalBlockedThreads(fd); } private SocketUtils() {} }
[ "@", "SystemApi", "public", "final", "class", "SocketUtils", "{", "/**\n * Create a raw datagram socket that is bound to an interface.\n *\n * <p>Data sent through the socket will go directly to the underlying network, ignoring VPNs.\n */", "public", "static", "void", "bindSocketToInterface", "(", "@", "NonNull", "FileDescriptor", "socket", ",", "@", "NonNull", "String", "iface", ")", "throws", "ErrnoException", "{", "Os", ".", "setsockoptIfreq", "(", "socket", ",", "SOL_SOCKET", ",", "SO_BINDTODEVICE", ",", "iface", ")", ";", "NetworkUtilsInternal", ".", "protectFromVpn", "(", "socket", ")", ";", "}", "/**\n * Make a socket address to communicate with netlink.\n */", "@", "NonNull", "public", "static", "SocketAddress", "makeNetlinkSocketAddress", "(", "int", "portId", ",", "int", "groupsMask", ")", "{", "return", "new", "NetlinkSocketAddress", "(", "portId", ",", "groupsMask", ")", ";", "}", "/**\n * Make socket address that packet sockets can bind to.\n *\n * @param protocol the layer 2 protocol of the packets to receive. One of the {@code ETH_P_*}\n * constants in {@link android.system.OsConstants}.\n * @param ifIndex the interface index on which packets will be received.\n */", "@", "NonNull", "public", "static", "SocketAddress", "makePacketSocketAddress", "(", "int", "protocol", ",", "int", "ifIndex", ")", "{", "return", "new", "PacketSocketAddress", "(", "protocol", "/* sll_protocol */", ",", "ifIndex", "/* sll_ifindex */", ",", "null", "/* sll_addr */", ")", ";", "}", "/**\n * Make a socket address that packet socket can send packets to.\n * @deprecated Use {@link #makePacketSocketAddress(int, int, byte[])} instead.\n *\n * @param ifIndex the interface index on which packets will be sent.\n * @param hwAddr the hardware address to which packets will be sent.\n */", "@", "Deprecated", "@", "NonNull", "public", "static", "SocketAddress", "makePacketSocketAddress", "(", "int", "ifIndex", ",", "@", "NonNull", "byte", "[", "]", "hwAddr", ")", "{", "return", "new", "PacketSocketAddress", "(", "0", "/* sll_protocol */", ",", "ifIndex", "/* sll_ifindex */", ",", "hwAddr", "/* sll_addr */", ")", ";", "}", "/**\n * Make a socket address that a packet socket can send packets to.\n *\n * @param protocol the layer 2 protocol of the packets to send. One of the {@code ETH_P_*}\n * constants in {@link android.system.OsConstants}.\n * @param ifIndex the interface index on which packets will be sent.\n * @param hwAddr the hardware address to which packets will be sent.\n */", "@", "NonNull", "public", "static", "SocketAddress", "makePacketSocketAddress", "(", "int", "protocol", ",", "int", "ifIndex", ",", "@", "NonNull", "byte", "[", "]", "hwAddr", ")", "{", "return", "new", "PacketSocketAddress", "(", "protocol", "/* sll_protocol */", ",", "ifIndex", "/* sll_ifindex */", ",", "hwAddr", "/* sll_addr */", ")", ";", "}", "/**\n * @see IoBridge#closeAndSignalBlockedThreads(FileDescriptor)\n */", "public", "static", "void", "closeSocket", "(", "@", "Nullable", "FileDescriptor", "fd", ")", "throws", "IOException", "{", "IoBridge", ".", "closeAndSignalBlockedThreads", "(", "fd", ")", ";", "}", "private", "SocketUtils", "(", ")", "{", "}", "}" ]
Collection of utilities to interact with raw sockets.
[ "Collection", "of", "utilities", "to", "interact", "with", "raw", "sockets", "." ]
[ "// SO_BINDTODEVICE actually takes a string. This works because the first member", "// of struct ifreq is a NULL-terminated interface name.", "// TODO: add a setsockoptString()" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
69f36588f3e0e8ab3aef6e2d60b3487a20a74201
halfrost/2017_ele_hackathon_tank
game_engine/src/main/java/ele/me/hackathon/tank/MovableObject.java
[ "MIT" ]
Java
MovableObject
/** * Created by lanjiangang on 03/11/2017. */
Created by lanjiangang on 03/11/2017.
[ "Created", "by", "lanjiangang", "on", "03", "/", "11", "/", "2017", "." ]
public class MovableObject { private int id; private Position pos; private Direction dir; private int speed; private boolean destroyed = false; public MovableObject(int id, Position pos, Direction dir, int speed) { this.pos = pos; this.dir = dir; this.speed = speed; this.id = id; } public void turnTo(Direction dir) { this.dir = dir; } /** * Because the object itself doesn't know the Map, it does not know if the movement is validate. * So it can only evaluate the moveOneStep track and let the GameStateMachine to verify it . (0,0) - (0,1) - (0,2) | UP LEFT (1,0) - (1,1) - (1,2) RIGHT | DOWN (2,1) * @return */ public Position[] evaluateMoveTrack() { Position[] track = new Position[speed]; Position prePos = pos; for(int i = 0; i < speed; i++) { track[i] = prePos.moveOneStep(dir); prePos = track[i]; } return track; } public void moveOneStep() { this.pos = pos.moveOneStep(dir); } public void withdrawOneStep() { this.pos = pos.withDrawStep(dir); } /** * move the object to given position. * @param position */ public void moveTo(Position position) { this.pos = position; } public void destroyed() { this.destroyed = true; } public boolean isDestroyed() { return destroyed; } public Position getPos() { return pos; } public Direction getDir() { return dir; } public int getId() { return id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MovableObject that = (MovableObject) o; if (speed != that.speed) return false; if (destroyed != that.destroyed) return false; if (pos != null ? !pos.equals(that.pos) : that.pos != null) return false; return dir == that.dir; } @Override public int hashCode() { int result = pos != null ? pos.hashCode() : 0; result = 31 * result + (dir != null ? dir.hashCode() : 0); result = 31 * result + speed; result = 31 * result + (destroyed ? 1 : 0); return result; } protected void setSpeed(int speed) { this.speed = speed; } @Override public String toString() { return "MovableObject{" + "id=" + id + ", pos=" + pos + ", dir=" + dir + ", speed=" + speed + ", destroyed=" + destroyed + '}'; } }
[ "public", "class", "MovableObject", "{", "private", "int", "id", ";", "private", "Position", "pos", ";", "private", "Direction", "dir", ";", "private", "int", "speed", ";", "private", "boolean", "destroyed", "=", "false", ";", "public", "MovableObject", "(", "int", "id", ",", "Position", "pos", ",", "Direction", "dir", ",", "int", "speed", ")", "{", "this", ".", "pos", "=", "pos", ";", "this", ".", "dir", "=", "dir", ";", "this", ".", "speed", "=", "speed", ";", "this", ".", "id", "=", "id", ";", "}", "public", "void", "turnTo", "(", "Direction", "dir", ")", "{", "this", ".", "dir", "=", "dir", ";", "}", "/**\n * Because the object itself doesn't know the Map, it does not know if the movement is validate.\n * So it can only evaluate the moveOneStep track and let the GameStateMachine to verify it .\n (0,0) - (0,1) - (0,2)\n | UP\n LEFT (1,0) - (1,1) - (1,2) RIGHT\n | DOWN\n (2,1)\n * @return\n */", "public", "Position", "[", "]", "evaluateMoveTrack", "(", ")", "{", "Position", "[", "]", "track", "=", "new", "Position", "[", "speed", "]", ";", "Position", "prePos", "=", "pos", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "speed", ";", "i", "++", ")", "{", "track", "[", "i", "]", "=", "prePos", ".", "moveOneStep", "(", "dir", ")", ";", "prePos", "=", "track", "[", "i", "]", ";", "}", "return", "track", ";", "}", "public", "void", "moveOneStep", "(", ")", "{", "this", ".", "pos", "=", "pos", ".", "moveOneStep", "(", "dir", ")", ";", "}", "public", "void", "withdrawOneStep", "(", ")", "{", "this", ".", "pos", "=", "pos", ".", "withDrawStep", "(", "dir", ")", ";", "}", "/**\n * move the object to given position.\n * @param position\n */", "public", "void", "moveTo", "(", "Position", "position", ")", "{", "this", ".", "pos", "=", "position", ";", "}", "public", "void", "destroyed", "(", ")", "{", "this", ".", "destroyed", "=", "true", ";", "}", "public", "boolean", "isDestroyed", "(", ")", "{", "return", "destroyed", ";", "}", "public", "Position", "getPos", "(", ")", "{", "return", "pos", ";", "}", "public", "Direction", "getDir", "(", ")", "{", "return", "dir", ";", "}", "public", "int", "getId", "(", ")", "{", "return", "id", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "o", ")", "{", "if", "(", "this", "==", "o", ")", "return", "true", ";", "if", "(", "o", "==", "null", "||", "getClass", "(", ")", "!=", "o", ".", "getClass", "(", ")", ")", "return", "false", ";", "MovableObject", "that", "=", "(", "MovableObject", ")", "o", ";", "if", "(", "speed", "!=", "that", ".", "speed", ")", "return", "false", ";", "if", "(", "destroyed", "!=", "that", ".", "destroyed", ")", "return", "false", ";", "if", "(", "pos", "!=", "null", "?", "!", "pos", ".", "equals", "(", "that", ".", "pos", ")", ":", "that", ".", "pos", "!=", "null", ")", "return", "false", ";", "return", "dir", "==", "that", ".", "dir", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "int", "result", "=", "pos", "!=", "null", "?", "pos", ".", "hashCode", "(", ")", ":", "0", ";", "result", "=", "31", "*", "result", "+", "(", "dir", "!=", "null", "?", "dir", ".", "hashCode", "(", ")", ":", "0", ")", ";", "result", "=", "31", "*", "result", "+", "speed", ";", "result", "=", "31", "*", "result", "+", "(", "destroyed", "?", "1", ":", "0", ")", ";", "return", "result", ";", "}", "protected", "void", "setSpeed", "(", "int", "speed", ")", "{", "this", ".", "speed", "=", "speed", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "MovableObject{", "\"", "+", "\"", "id=", "\"", "+", "id", "+", "\"", ", pos=", "\"", "+", "pos", "+", "\"", ", dir=", "\"", "+", "dir", "+", "\"", ", speed=", "\"", "+", "speed", "+", "\"", ", destroyed=", "\"", "+", "destroyed", "+", "'}'", ";", "}", "}" ]
Created by lanjiangang on 03/11/2017.
[ "Created", "by", "lanjiangang", "on", "03", "/", "11", "/", "2017", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
69f63ff45ce9c485020f71fa6821035dc6ff25f0
HeinerKuecker/Array-Comparator-Java
ARRAY_COMPARATOR/test_util/de/heinerkuecker/iterator/EmptyIterable.java
[ "Unlicense" ]
Java
EmptyIterable
/** * {@link Iterable} over * {qlink EmptyIterator}. * * @author Heiner K&uuml;cker */
Iterable over {qlink EmptyIterator}. @author Heiner Kücker
[ "Iterable", "over", "{", "qlink", "EmptyIterator", "}", ".", "@author", "Heiner", "Kücker" ]
public class EmptyIterable<T> implements Iterable<T> { /** * @see java.lang.Iterable#iterator() */ @Override public Iterator<T> iterator() { return new EmptyIterator<>(); } }
[ "public", "class", "EmptyIterable", "<", "T", ">", "implements", "Iterable", "<", "T", ">", "{", "/**\r\n * @see java.lang.Iterable#iterator()\r\n */", "@", "Override", "public", "Iterator", "<", "T", ">", "iterator", "(", ")", "{", "return", "new", "EmptyIterator", "<", ">", "(", ")", ";", "}", "}" ]
{@link Iterable} over {qlink EmptyIterator}.
[ "{", "@link", "Iterable", "}", "over", "{", "qlink", "EmptyIterator", "}", "." ]
[]
[ { "param": "Iterable<T>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Iterable<T>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
46647680cf4322113327b6de39092e84526113bb
billwert/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/fluent/models/RoleAssignmentScheduleRequestInner.java
[ "MIT" ]
Java
RoleAssignmentScheduleRequestInner
/** Role Assignment schedule request. */
Role Assignment schedule request.
[ "Role", "Assignment", "schedule", "request", "." ]
@Fluent public final class RoleAssignmentScheduleRequestInner { /* * The role assignment schedule request ID. */ @JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY) private String id; /* * The role assignment schedule request name. */ @JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY) private String name; /* * The role assignment schedule request type. */ @JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY) private String type; /* * Role assignment schedule request properties. */ @JsonProperty(value = "properties") private RoleAssignmentScheduleRequestProperties innerProperties; /** * Get the id property: The role assignment schedule request ID. * * @return the id value. */ public String id() { return this.id; } /** * Get the name property: The role assignment schedule request name. * * @return the name value. */ public String name() { return this.name; } /** * Get the type property: The role assignment schedule request type. * * @return the type value. */ public String type() { return this.type; } /** * Get the innerProperties property: Role assignment schedule request properties. * * @return the innerProperties value. */ private RoleAssignmentScheduleRequestProperties innerProperties() { return this.innerProperties; } /** * Get the scope property: The role assignment schedule request scope. * * @return the scope value. */ public String scope() { return this.innerProperties() == null ? null : this.innerProperties().scope(); } /** * Get the roleDefinitionId property: The role definition ID. * * @return the roleDefinitionId value. */ public String roleDefinitionId() { return this.innerProperties() == null ? null : this.innerProperties().roleDefinitionId(); } /** * Set the roleDefinitionId property: The role definition ID. * * @param roleDefinitionId the roleDefinitionId value to set. * @return the RoleAssignmentScheduleRequestInner object itself. */ public RoleAssignmentScheduleRequestInner withRoleDefinitionId(String roleDefinitionId) { if (this.innerProperties() == null) { this.innerProperties = new RoleAssignmentScheduleRequestProperties(); } this.innerProperties().withRoleDefinitionId(roleDefinitionId); return this; } /** * Get the principalId property: The principal ID. * * @return the principalId value. */ public String principalId() { return this.innerProperties() == null ? null : this.innerProperties().principalId(); } /** * Set the principalId property: The principal ID. * * @param principalId the principalId value to set. * @return the RoleAssignmentScheduleRequestInner object itself. */ public RoleAssignmentScheduleRequestInner withPrincipalId(String principalId) { if (this.innerProperties() == null) { this.innerProperties = new RoleAssignmentScheduleRequestProperties(); } this.innerProperties().withPrincipalId(principalId); return this; } /** * Get the principalType property: The principal type of the assigned principal ID. * * @return the principalType value. */ public PrincipalType principalType() { return this.innerProperties() == null ? null : this.innerProperties().principalType(); } /** * Get the requestType property: The type of the role assignment schedule request. Eg: SelfActivate, AdminAssign * etc. * * @return the requestType value. */ public RequestType requestType() { return this.innerProperties() == null ? null : this.innerProperties().requestType(); } /** * Set the requestType property: The type of the role assignment schedule request. Eg: SelfActivate, AdminAssign * etc. * * @param requestType the requestType value to set. * @return the RoleAssignmentScheduleRequestInner object itself. */ public RoleAssignmentScheduleRequestInner withRequestType(RequestType requestType) { if (this.innerProperties() == null) { this.innerProperties = new RoleAssignmentScheduleRequestProperties(); } this.innerProperties().withRequestType(requestType); return this; } /** * Get the status property: The status of the role assignment schedule request. * * @return the status value. */ public Status status() { return this.innerProperties() == null ? null : this.innerProperties().status(); } /** * Get the approvalId property: The approvalId of the role assignment schedule request. * * @return the approvalId value. */ public String approvalId() { return this.innerProperties() == null ? null : this.innerProperties().approvalId(); } /** * Get the targetRoleAssignmentScheduleId property: The resultant role assignment schedule id or the role assignment * schedule id being updated. * * @return the targetRoleAssignmentScheduleId value. */ public String targetRoleAssignmentScheduleId() { return this.innerProperties() == null ? null : this.innerProperties().targetRoleAssignmentScheduleId(); } /** * Set the targetRoleAssignmentScheduleId property: The resultant role assignment schedule id or the role assignment * schedule id being updated. * * @param targetRoleAssignmentScheduleId the targetRoleAssignmentScheduleId value to set. * @return the RoleAssignmentScheduleRequestInner object itself. */ public RoleAssignmentScheduleRequestInner withTargetRoleAssignmentScheduleId( String targetRoleAssignmentScheduleId) { if (this.innerProperties() == null) { this.innerProperties = new RoleAssignmentScheduleRequestProperties(); } this.innerProperties().withTargetRoleAssignmentScheduleId(targetRoleAssignmentScheduleId); return this; } /** * Get the targetRoleAssignmentScheduleInstanceId property: The role assignment schedule instance id being updated. * * @return the targetRoleAssignmentScheduleInstanceId value. */ public String targetRoleAssignmentScheduleInstanceId() { return this.innerProperties() == null ? null : this.innerProperties().targetRoleAssignmentScheduleInstanceId(); } /** * Set the targetRoleAssignmentScheduleInstanceId property: The role assignment schedule instance id being updated. * * @param targetRoleAssignmentScheduleInstanceId the targetRoleAssignmentScheduleInstanceId value to set. * @return the RoleAssignmentScheduleRequestInner object itself. */ public RoleAssignmentScheduleRequestInner withTargetRoleAssignmentScheduleInstanceId( String targetRoleAssignmentScheduleInstanceId) { if (this.innerProperties() == null) { this.innerProperties = new RoleAssignmentScheduleRequestProperties(); } this.innerProperties().withTargetRoleAssignmentScheduleInstanceId(targetRoleAssignmentScheduleInstanceId); return this; } /** * Get the scheduleInfo property: Schedule info of the role assignment schedule. * * @return the scheduleInfo value. */ public RoleAssignmentScheduleRequestPropertiesScheduleInfo scheduleInfo() { return this.innerProperties() == null ? null : this.innerProperties().scheduleInfo(); } /** * Set the scheduleInfo property: Schedule info of the role assignment schedule. * * @param scheduleInfo the scheduleInfo value to set. * @return the RoleAssignmentScheduleRequestInner object itself. */ public RoleAssignmentScheduleRequestInner withScheduleInfo( RoleAssignmentScheduleRequestPropertiesScheduleInfo scheduleInfo) { if (this.innerProperties() == null) { this.innerProperties = new RoleAssignmentScheduleRequestProperties(); } this.innerProperties().withScheduleInfo(scheduleInfo); return this; } /** * Get the linkedRoleEligibilityScheduleId property: The linked role eligibility schedule id - to activate an * eligibility. * * @return the linkedRoleEligibilityScheduleId value. */ public String linkedRoleEligibilityScheduleId() { return this.innerProperties() == null ? null : this.innerProperties().linkedRoleEligibilityScheduleId(); } /** * Set the linkedRoleEligibilityScheduleId property: The linked role eligibility schedule id - to activate an * eligibility. * * @param linkedRoleEligibilityScheduleId the linkedRoleEligibilityScheduleId value to set. * @return the RoleAssignmentScheduleRequestInner object itself. */ public RoleAssignmentScheduleRequestInner withLinkedRoleEligibilityScheduleId( String linkedRoleEligibilityScheduleId) { if (this.innerProperties() == null) { this.innerProperties = new RoleAssignmentScheduleRequestProperties(); } this.innerProperties().withLinkedRoleEligibilityScheduleId(linkedRoleEligibilityScheduleId); return this; } /** * Get the justification property: Justification for the role assignment. * * @return the justification value. */ public String justification() { return this.innerProperties() == null ? null : this.innerProperties().justification(); } /** * Set the justification property: Justification for the role assignment. * * @param justification the justification value to set. * @return the RoleAssignmentScheduleRequestInner object itself. */ public RoleAssignmentScheduleRequestInner withJustification(String justification) { if (this.innerProperties() == null) { this.innerProperties = new RoleAssignmentScheduleRequestProperties(); } this.innerProperties().withJustification(justification); return this; } /** * Get the ticketInfo property: Ticket Info of the role assignment. * * @return the ticketInfo value. */ public RoleAssignmentScheduleRequestPropertiesTicketInfo ticketInfo() { return this.innerProperties() == null ? null : this.innerProperties().ticketInfo(); } /** * Set the ticketInfo property: Ticket Info of the role assignment. * * @param ticketInfo the ticketInfo value to set. * @return the RoleAssignmentScheduleRequestInner object itself. */ public RoleAssignmentScheduleRequestInner withTicketInfo( RoleAssignmentScheduleRequestPropertiesTicketInfo ticketInfo) { if (this.innerProperties() == null) { this.innerProperties = new RoleAssignmentScheduleRequestProperties(); } this.innerProperties().withTicketInfo(ticketInfo); return this; } /** * Get the condition property: The conditions on the role assignment. This limits the resources it can be assigned * to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] * StringEqualsIgnoreCase 'foo_storage_container'. * * @return the condition value. */ public String condition() { return this.innerProperties() == null ? null : this.innerProperties().condition(); } /** * Set the condition property: The conditions on the role assignment. This limits the resources it can be assigned * to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] * StringEqualsIgnoreCase 'foo_storage_container'. * * @param condition the condition value to set. * @return the RoleAssignmentScheduleRequestInner object itself. */ public RoleAssignmentScheduleRequestInner withCondition(String condition) { if (this.innerProperties() == null) { this.innerProperties = new RoleAssignmentScheduleRequestProperties(); } this.innerProperties().withCondition(condition); return this; } /** * Get the conditionVersion property: Version of the condition. Currently accepted value is '2.0'. * * @return the conditionVersion value. */ public String conditionVersion() { return this.innerProperties() == null ? null : this.innerProperties().conditionVersion(); } /** * Set the conditionVersion property: Version of the condition. Currently accepted value is '2.0'. * * @param conditionVersion the conditionVersion value to set. * @return the RoleAssignmentScheduleRequestInner object itself. */ public RoleAssignmentScheduleRequestInner withConditionVersion(String conditionVersion) { if (this.innerProperties() == null) { this.innerProperties = new RoleAssignmentScheduleRequestProperties(); } this.innerProperties().withConditionVersion(conditionVersion); return this; } /** * Get the createdOn property: DateTime when role assignment schedule request was created. * * @return the createdOn value. */ public OffsetDateTime createdOn() { return this.innerProperties() == null ? null : this.innerProperties().createdOn(); } /** * Get the requestorId property: Id of the user who created this request. * * @return the requestorId value. */ public String requestorId() { return this.innerProperties() == null ? null : this.innerProperties().requestorId(); } /** * Get the expandedProperties property: Additional properties of principal, scope and role definition. * * @return the expandedProperties value. */ public ExpandedProperties expandedProperties() { return this.innerProperties() == null ? null : this.innerProperties().expandedProperties(); } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (innerProperties() != null) { innerProperties().validate(); } } }
[ "@", "Fluent", "public", "final", "class", "RoleAssignmentScheduleRequestInner", "{", "/*\n * The role assignment schedule request ID.\n */", "@", "JsonProperty", "(", "value", "=", "\"", "id", "\"", ",", "access", "=", "JsonProperty", ".", "Access", ".", "WRITE_ONLY", ")", "private", "String", "id", ";", "/*\n * The role assignment schedule request name.\n */", "@", "JsonProperty", "(", "value", "=", "\"", "name", "\"", ",", "access", "=", "JsonProperty", ".", "Access", ".", "WRITE_ONLY", ")", "private", "String", "name", ";", "/*\n * The role assignment schedule request type.\n */", "@", "JsonProperty", "(", "value", "=", "\"", "type", "\"", ",", "access", "=", "JsonProperty", ".", "Access", ".", "WRITE_ONLY", ")", "private", "String", "type", ";", "/*\n * Role assignment schedule request properties.\n */", "@", "JsonProperty", "(", "value", "=", "\"", "properties", "\"", ")", "private", "RoleAssignmentScheduleRequestProperties", "innerProperties", ";", "/**\n * Get the id property: The role assignment schedule request ID.\n *\n * @return the id value.\n */", "public", "String", "id", "(", ")", "{", "return", "this", ".", "id", ";", "}", "/**\n * Get the name property: The role assignment schedule request name.\n *\n * @return the name value.\n */", "public", "String", "name", "(", ")", "{", "return", "this", ".", "name", ";", "}", "/**\n * Get the type property: The role assignment schedule request type.\n *\n * @return the type value.\n */", "public", "String", "type", "(", ")", "{", "return", "this", ".", "type", ";", "}", "/**\n * Get the innerProperties property: Role assignment schedule request properties.\n *\n * @return the innerProperties value.\n */", "private", "RoleAssignmentScheduleRequestProperties", "innerProperties", "(", ")", "{", "return", "this", ".", "innerProperties", ";", "}", "/**\n * Get the scope property: The role assignment schedule request scope.\n *\n * @return the scope value.\n */", "public", "String", "scope", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "scope", "(", ")", ";", "}", "/**\n * Get the roleDefinitionId property: The role definition ID.\n *\n * @return the roleDefinitionId value.\n */", "public", "String", "roleDefinitionId", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "roleDefinitionId", "(", ")", ";", "}", "/**\n * Set the roleDefinitionId property: The role definition ID.\n *\n * @param roleDefinitionId the roleDefinitionId value to set.\n * @return the RoleAssignmentScheduleRequestInner object itself.\n */", "public", "RoleAssignmentScheduleRequestInner", "withRoleDefinitionId", "(", "String", "roleDefinitionId", ")", "{", "if", "(", "this", ".", "innerProperties", "(", ")", "==", "null", ")", "{", "this", ".", "innerProperties", "=", "new", "RoleAssignmentScheduleRequestProperties", "(", ")", ";", "}", "this", ".", "innerProperties", "(", ")", ".", "withRoleDefinitionId", "(", "roleDefinitionId", ")", ";", "return", "this", ";", "}", "/**\n * Get the principalId property: The principal ID.\n *\n * @return the principalId value.\n */", "public", "String", "principalId", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "principalId", "(", ")", ";", "}", "/**\n * Set the principalId property: The principal ID.\n *\n * @param principalId the principalId value to set.\n * @return the RoleAssignmentScheduleRequestInner object itself.\n */", "public", "RoleAssignmentScheduleRequestInner", "withPrincipalId", "(", "String", "principalId", ")", "{", "if", "(", "this", ".", "innerProperties", "(", ")", "==", "null", ")", "{", "this", ".", "innerProperties", "=", "new", "RoleAssignmentScheduleRequestProperties", "(", ")", ";", "}", "this", ".", "innerProperties", "(", ")", ".", "withPrincipalId", "(", "principalId", ")", ";", "return", "this", ";", "}", "/**\n * Get the principalType property: The principal type of the assigned principal ID.\n *\n * @return the principalType value.\n */", "public", "PrincipalType", "principalType", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "principalType", "(", ")", ";", "}", "/**\n * Get the requestType property: The type of the role assignment schedule request. Eg: SelfActivate, AdminAssign\n * etc.\n *\n * @return the requestType value.\n */", "public", "RequestType", "requestType", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "requestType", "(", ")", ";", "}", "/**\n * Set the requestType property: The type of the role assignment schedule request. Eg: SelfActivate, AdminAssign\n * etc.\n *\n * @param requestType the requestType value to set.\n * @return the RoleAssignmentScheduleRequestInner object itself.\n */", "public", "RoleAssignmentScheduleRequestInner", "withRequestType", "(", "RequestType", "requestType", ")", "{", "if", "(", "this", ".", "innerProperties", "(", ")", "==", "null", ")", "{", "this", ".", "innerProperties", "=", "new", "RoleAssignmentScheduleRequestProperties", "(", ")", ";", "}", "this", ".", "innerProperties", "(", ")", ".", "withRequestType", "(", "requestType", ")", ";", "return", "this", ";", "}", "/**\n * Get the status property: The status of the role assignment schedule request.\n *\n * @return the status value.\n */", "public", "Status", "status", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "status", "(", ")", ";", "}", "/**\n * Get the approvalId property: The approvalId of the role assignment schedule request.\n *\n * @return the approvalId value.\n */", "public", "String", "approvalId", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "approvalId", "(", ")", ";", "}", "/**\n * Get the targetRoleAssignmentScheduleId property: The resultant role assignment schedule id or the role assignment\n * schedule id being updated.\n *\n * @return the targetRoleAssignmentScheduleId value.\n */", "public", "String", "targetRoleAssignmentScheduleId", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "targetRoleAssignmentScheduleId", "(", ")", ";", "}", "/**\n * Set the targetRoleAssignmentScheduleId property: The resultant role assignment schedule id or the role assignment\n * schedule id being updated.\n *\n * @param targetRoleAssignmentScheduleId the targetRoleAssignmentScheduleId value to set.\n * @return the RoleAssignmentScheduleRequestInner object itself.\n */", "public", "RoleAssignmentScheduleRequestInner", "withTargetRoleAssignmentScheduleId", "(", "String", "targetRoleAssignmentScheduleId", ")", "{", "if", "(", "this", ".", "innerProperties", "(", ")", "==", "null", ")", "{", "this", ".", "innerProperties", "=", "new", "RoleAssignmentScheduleRequestProperties", "(", ")", ";", "}", "this", ".", "innerProperties", "(", ")", ".", "withTargetRoleAssignmentScheduleId", "(", "targetRoleAssignmentScheduleId", ")", ";", "return", "this", ";", "}", "/**\n * Get the targetRoleAssignmentScheduleInstanceId property: The role assignment schedule instance id being updated.\n *\n * @return the targetRoleAssignmentScheduleInstanceId value.\n */", "public", "String", "targetRoleAssignmentScheduleInstanceId", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "targetRoleAssignmentScheduleInstanceId", "(", ")", ";", "}", "/**\n * Set the targetRoleAssignmentScheduleInstanceId property: The role assignment schedule instance id being updated.\n *\n * @param targetRoleAssignmentScheduleInstanceId the targetRoleAssignmentScheduleInstanceId value to set.\n * @return the RoleAssignmentScheduleRequestInner object itself.\n */", "public", "RoleAssignmentScheduleRequestInner", "withTargetRoleAssignmentScheduleInstanceId", "(", "String", "targetRoleAssignmentScheduleInstanceId", ")", "{", "if", "(", "this", ".", "innerProperties", "(", ")", "==", "null", ")", "{", "this", ".", "innerProperties", "=", "new", "RoleAssignmentScheduleRequestProperties", "(", ")", ";", "}", "this", ".", "innerProperties", "(", ")", ".", "withTargetRoleAssignmentScheduleInstanceId", "(", "targetRoleAssignmentScheduleInstanceId", ")", ";", "return", "this", ";", "}", "/**\n * Get the scheduleInfo property: Schedule info of the role assignment schedule.\n *\n * @return the scheduleInfo value.\n */", "public", "RoleAssignmentScheduleRequestPropertiesScheduleInfo", "scheduleInfo", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "scheduleInfo", "(", ")", ";", "}", "/**\n * Set the scheduleInfo property: Schedule info of the role assignment schedule.\n *\n * @param scheduleInfo the scheduleInfo value to set.\n * @return the RoleAssignmentScheduleRequestInner object itself.\n */", "public", "RoleAssignmentScheduleRequestInner", "withScheduleInfo", "(", "RoleAssignmentScheduleRequestPropertiesScheduleInfo", "scheduleInfo", ")", "{", "if", "(", "this", ".", "innerProperties", "(", ")", "==", "null", ")", "{", "this", ".", "innerProperties", "=", "new", "RoleAssignmentScheduleRequestProperties", "(", ")", ";", "}", "this", ".", "innerProperties", "(", ")", ".", "withScheduleInfo", "(", "scheduleInfo", ")", ";", "return", "this", ";", "}", "/**\n * Get the linkedRoleEligibilityScheduleId property: The linked role eligibility schedule id - to activate an\n * eligibility.\n *\n * @return the linkedRoleEligibilityScheduleId value.\n */", "public", "String", "linkedRoleEligibilityScheduleId", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "linkedRoleEligibilityScheduleId", "(", ")", ";", "}", "/**\n * Set the linkedRoleEligibilityScheduleId property: The linked role eligibility schedule id - to activate an\n * eligibility.\n *\n * @param linkedRoleEligibilityScheduleId the linkedRoleEligibilityScheduleId value to set.\n * @return the RoleAssignmentScheduleRequestInner object itself.\n */", "public", "RoleAssignmentScheduleRequestInner", "withLinkedRoleEligibilityScheduleId", "(", "String", "linkedRoleEligibilityScheduleId", ")", "{", "if", "(", "this", ".", "innerProperties", "(", ")", "==", "null", ")", "{", "this", ".", "innerProperties", "=", "new", "RoleAssignmentScheduleRequestProperties", "(", ")", ";", "}", "this", ".", "innerProperties", "(", ")", ".", "withLinkedRoleEligibilityScheduleId", "(", "linkedRoleEligibilityScheduleId", ")", ";", "return", "this", ";", "}", "/**\n * Get the justification property: Justification for the role assignment.\n *\n * @return the justification value.\n */", "public", "String", "justification", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "justification", "(", ")", ";", "}", "/**\n * Set the justification property: Justification for the role assignment.\n *\n * @param justification the justification value to set.\n * @return the RoleAssignmentScheduleRequestInner object itself.\n */", "public", "RoleAssignmentScheduleRequestInner", "withJustification", "(", "String", "justification", ")", "{", "if", "(", "this", ".", "innerProperties", "(", ")", "==", "null", ")", "{", "this", ".", "innerProperties", "=", "new", "RoleAssignmentScheduleRequestProperties", "(", ")", ";", "}", "this", ".", "innerProperties", "(", ")", ".", "withJustification", "(", "justification", ")", ";", "return", "this", ";", "}", "/**\n * Get the ticketInfo property: Ticket Info of the role assignment.\n *\n * @return the ticketInfo value.\n */", "public", "RoleAssignmentScheduleRequestPropertiesTicketInfo", "ticketInfo", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "ticketInfo", "(", ")", ";", "}", "/**\n * Set the ticketInfo property: Ticket Info of the role assignment.\n *\n * @param ticketInfo the ticketInfo value to set.\n * @return the RoleAssignmentScheduleRequestInner object itself.\n */", "public", "RoleAssignmentScheduleRequestInner", "withTicketInfo", "(", "RoleAssignmentScheduleRequestPropertiesTicketInfo", "ticketInfo", ")", "{", "if", "(", "this", ".", "innerProperties", "(", ")", "==", "null", ")", "{", "this", ".", "innerProperties", "=", "new", "RoleAssignmentScheduleRequestProperties", "(", ")", ";", "}", "this", ".", "innerProperties", "(", ")", ".", "withTicketInfo", "(", "ticketInfo", ")", ";", "return", "this", ";", "}", "/**\n * Get the condition property: The conditions on the role assignment. This limits the resources it can be assigned\n * to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName]\n * StringEqualsIgnoreCase 'foo_storage_container'.\n *\n * @return the condition value.\n */", "public", "String", "condition", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "condition", "(", ")", ";", "}", "/**\n * Set the condition property: The conditions on the role assignment. This limits the resources it can be assigned\n * to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName]\n * StringEqualsIgnoreCase 'foo_storage_container'.\n *\n * @param condition the condition value to set.\n * @return the RoleAssignmentScheduleRequestInner object itself.\n */", "public", "RoleAssignmentScheduleRequestInner", "withCondition", "(", "String", "condition", ")", "{", "if", "(", "this", ".", "innerProperties", "(", ")", "==", "null", ")", "{", "this", ".", "innerProperties", "=", "new", "RoleAssignmentScheduleRequestProperties", "(", ")", ";", "}", "this", ".", "innerProperties", "(", ")", ".", "withCondition", "(", "condition", ")", ";", "return", "this", ";", "}", "/**\n * Get the conditionVersion property: Version of the condition. Currently accepted value is '2.0'.\n *\n * @return the conditionVersion value.\n */", "public", "String", "conditionVersion", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "conditionVersion", "(", ")", ";", "}", "/**\n * Set the conditionVersion property: Version of the condition. Currently accepted value is '2.0'.\n *\n * @param conditionVersion the conditionVersion value to set.\n * @return the RoleAssignmentScheduleRequestInner object itself.\n */", "public", "RoleAssignmentScheduleRequestInner", "withConditionVersion", "(", "String", "conditionVersion", ")", "{", "if", "(", "this", ".", "innerProperties", "(", ")", "==", "null", ")", "{", "this", ".", "innerProperties", "=", "new", "RoleAssignmentScheduleRequestProperties", "(", ")", ";", "}", "this", ".", "innerProperties", "(", ")", ".", "withConditionVersion", "(", "conditionVersion", ")", ";", "return", "this", ";", "}", "/**\n * Get the createdOn property: DateTime when role assignment schedule request was created.\n *\n * @return the createdOn value.\n */", "public", "OffsetDateTime", "createdOn", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "createdOn", "(", ")", ";", "}", "/**\n * Get the requestorId property: Id of the user who created this request.\n *\n * @return the requestorId value.\n */", "public", "String", "requestorId", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "requestorId", "(", ")", ";", "}", "/**\n * Get the expandedProperties property: Additional properties of principal, scope and role definition.\n *\n * @return the expandedProperties value.\n */", "public", "ExpandedProperties", "expandedProperties", "(", ")", "{", "return", "this", ".", "innerProperties", "(", ")", "==", "null", "?", "null", ":", "this", ".", "innerProperties", "(", ")", ".", "expandedProperties", "(", ")", ";", "}", "/**\n * Validates the instance.\n *\n * @throws IllegalArgumentException thrown if the instance is not valid.\n */", "public", "void", "validate", "(", ")", "{", "if", "(", "innerProperties", "(", ")", "!=", "null", ")", "{", "innerProperties", "(", ")", ".", "validate", "(", ")", ";", "}", "}", "}" ]
Role Assignment schedule request.
[ "Role", "Assignment", "schedule", "request", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
466e17b31c290f3c2864b45a84a38a9b69817c5b
eamanu/HistorialClinica-LaRioja
back-end/hospital-api/src/main/java/net/pladema/security/authorization/InstitutionPermissionEvaluator.java
[ "Apache-2.0" ]
Java
InstitutionPermissionEvaluator
/** * Implementa hasPermission que se puede acceder desde las anotaciones * de seguridad del estilo @PreAuthorize("hasPermission(....)"). */
Implementa hasPermission que se puede acceder desde las anotaciones de seguridad del estilo @PreAuthorize("hasPermission(....)").
[ "Implementa", "hasPermission", "que", "se", "puede", "acceder", "desde", "las", "anotaciones", "de", "seguridad", "del", "estilo", "@PreAuthorize", "(", "\"", "hasPermission", "(", "....", ")", "\"", ")", "." ]
@Component public class InstitutionPermissionEvaluator implements PermissionEvaluator { @Override /** * targetDomainObject: id de la institución * permission: tiene que ser uno de los definidos en ERole */ public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) { if (permission instanceof String) { List<String> permissions = new ArrayList<>(Arrays.asList(((String)permission).split(","))); return hasPermission(auth, targetDomainObject, permissions); } return false; } private boolean hasPermission(Authentication auth, Object targetDomainObject, List<String> permission) { return permission.stream().anyMatch(p -> hasRoleInInstitution(auth, (Integer) targetDomainObject, ERole.valueOf(StringUtils.deleteWhitespace(p)))); } @Override /** * targetId: id de la institución * targetType: por ahora tiene que ser "Institution" * permission: tiene que ser uno de los definidos en ERole */ public boolean hasPermission(Authentication auth, Serializable targetId, String targetType, Object permission) { if (!targetType.equals("Institution")) return false; return hasRoleInInstitution(auth, (Integer) targetId, ERole.valueOf((String) permission)); } private boolean hasRoleInInstitution(Authentication auth, Integer targetId, ERole role) { List<InstitutionGrantedAuthority> authorities = (List<InstitutionGrantedAuthority>) auth.getAuthorities(); RoleAssignment requestedRole = new RoleAssignment(role, targetId); return authorities.contains(new InstitutionGrantedAuthority(requestedRole)); } }
[ "@", "Component", "public", "class", "InstitutionPermissionEvaluator", "implements", "PermissionEvaluator", "{", "@", "Override", "/**\n\t * targetDomainObject: id de la institución\n\t * permission: tiene que ser uno de los definidos en ERole\n\t */", "public", "boolean", "hasPermission", "(", "Authentication", "auth", ",", "Object", "targetDomainObject", ",", "Object", "permission", ")", "{", "if", "(", "permission", "instanceof", "String", ")", "{", "List", "<", "String", ">", "permissions", "=", "new", "ArrayList", "<", ">", "(", "Arrays", ".", "asList", "(", "(", "(", "String", ")", "permission", ")", ".", "split", "(", "\"", ",", "\"", ")", ")", ")", ";", "return", "hasPermission", "(", "auth", ",", "targetDomainObject", ",", "permissions", ")", ";", "}", "return", "false", ";", "}", "private", "boolean", "hasPermission", "(", "Authentication", "auth", ",", "Object", "targetDomainObject", ",", "List", "<", "String", ">", "permission", ")", "{", "return", "permission", ".", "stream", "(", ")", ".", "anyMatch", "(", "p", "->", "hasRoleInInstitution", "(", "auth", ",", "(", "Integer", ")", "targetDomainObject", ",", "ERole", ".", "valueOf", "(", "StringUtils", ".", "deleteWhitespace", "(", "p", ")", ")", ")", ")", ";", "}", "@", "Override", "/**\n * targetId: id de la institución\n * targetType: por ahora tiene que ser \"Institution\"\n * permission: tiene que ser uno de los definidos en ERole \n */", "public", "boolean", "hasPermission", "(", "Authentication", "auth", ",", "Serializable", "targetId", ",", "String", "targetType", ",", "Object", "permission", ")", "{", "if", "(", "!", "targetType", ".", "equals", "(", "\"", "Institution", "\"", ")", ")", "return", "false", ";", "return", "hasRoleInInstitution", "(", "auth", ",", "(", "Integer", ")", "targetId", ",", "ERole", ".", "valueOf", "(", "(", "String", ")", "permission", ")", ")", ";", "}", "private", "boolean", "hasRoleInInstitution", "(", "Authentication", "auth", ",", "Integer", "targetId", ",", "ERole", "role", ")", "{", "List", "<", "InstitutionGrantedAuthority", ">", "authorities", "=", "(", "List", "<", "InstitutionGrantedAuthority", ">", ")", "auth", ".", "getAuthorities", "(", ")", ";", "RoleAssignment", "requestedRole", "=", "new", "RoleAssignment", "(", "role", ",", "targetId", ")", ";", "return", "authorities", ".", "contains", "(", "new", "InstitutionGrantedAuthority", "(", "requestedRole", ")", ")", ";", "}", "}" ]
Implementa hasPermission que se puede acceder desde las anotaciones de seguridad del estilo @PreAuthorize("hasPermission(....)").
[ "Implementa", "hasPermission", "que", "se", "puede", "acceder", "desde", "las", "anotaciones", "de", "seguridad", "del", "estilo", "@PreAuthorize", "(", "\"", "hasPermission", "(", "....", ")", "\"", ")", "." ]
[]
[ { "param": "PermissionEvaluator", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PermissionEvaluator", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
467a14d80077a2fdecbb795a29cbf68d79257bef
Saljack/mapstruct
processor/src/test/java/org/mapstruct/ap/test/factories/qualified/QualifiedFactoryTestMapper.java
[ "Apache-2.0" ]
Java
QualifiedFactoryTestMapper
/** * @author Remo Meier */
@author Remo Meier
[ "@author", "Remo", "Meier" ]
@Mapper( uses = { Bar10Factory.class } ) public abstract class QualifiedFactoryTestMapper { public static final QualifiedFactoryTestMapper INSTANCE = Mappers.getMapper( QualifiedFactoryTestMapper.class ); public abstract Bar10 foo10ToBar10Lower(Foo10 foo10); @BeanMapping( qualifiedBy = TestQualifier.class ) public abstract Bar10 foo10ToBar10Upper(Foo10 foo10); @BeanMapping( qualifiedByName = "Bar10NamedQualifier" ) public abstract Bar10 foo10ToBar10Camel(Foo10 foo10); }
[ "@", "Mapper", "(", "uses", "=", "{", "Bar10Factory", ".", "class", "}", ")", "public", "abstract", "class", "QualifiedFactoryTestMapper", "{", "public", "static", "final", "QualifiedFactoryTestMapper", "INSTANCE", "=", "Mappers", ".", "getMapper", "(", "QualifiedFactoryTestMapper", ".", "class", ")", ";", "public", "abstract", "Bar10", "foo10ToBar10Lower", "(", "Foo10", "foo10", ")", ";", "@", "BeanMapping", "(", "qualifiedBy", "=", "TestQualifier", ".", "class", ")", "public", "abstract", "Bar10", "foo10ToBar10Upper", "(", "Foo10", "foo10", ")", ";", "@", "BeanMapping", "(", "qualifiedByName", "=", "\"", "Bar10NamedQualifier", "\"", ")", "public", "abstract", "Bar10", "foo10ToBar10Camel", "(", "Foo10", "foo10", ")", ";", "}" ]
@author Remo Meier
[ "@author", "Remo", "Meier" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
467b287266666a9dc2df859af5aace500479d74b
paganini2008/transporter
vortex-spring-boot-starter/src/main/java/io/atlantisframework/vortex/ServerInfo.java
[ "Apache-2.0" ]
Java
ServerInfo
/** * * ServerInfo * * @author Fred Feng * @since 2.0.1 */
@author Fred Feng @since 2.0.1
[ "@author", "Fred", "Feng", "@since", "2", ".", "0", ".", "1" ]
public final class ServerInfo { private Map<String, Object> attributes = new HashMap<String, Object>(); private String hostName; private int port; public ServerInfo() { } public ServerInfo(InetSocketAddress socketAddress) { this.hostName = socketAddress.getHostName(); this.port = socketAddress.getPort(); } public String getHostName() { return hostName; } public void setHostName(String hostName) { this.hostName = hostName; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public Map<String, Object> getAttributes() { return attributes; } public void setAttributes(Map<String, Object> attributes) { this.attributes = attributes; } public Object getAttribute(String name) { return attributes.get(name); } public void setAttribute(String name, Object attributeValue) { if (attributeValue != null) { attributes.put(name, attributeValue); } else { attributes.remove(name); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (hostName != null ? 0 : hostName.hashCode()); result = prime * result + Integer.hashCode(port); return result; } @Override public boolean equals(Object obj) { if (obj instanceof ServerInfo) { if (obj == this) { return true; } ServerInfo other = (ServerInfo) obj; return other.getHostName().equals(getHostName()) && other.getPort() == getPort(); } return false; } @Override public String toString() { return hostName + ":" + port; } }
[ "public", "final", "class", "ServerInfo", "{", "private", "Map", "<", "String", ",", "Object", ">", "attributes", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "private", "String", "hostName", ";", "private", "int", "port", ";", "public", "ServerInfo", "(", ")", "{", "}", "public", "ServerInfo", "(", "InetSocketAddress", "socketAddress", ")", "{", "this", ".", "hostName", "=", "socketAddress", ".", "getHostName", "(", ")", ";", "this", ".", "port", "=", "socketAddress", ".", "getPort", "(", ")", ";", "}", "public", "String", "getHostName", "(", ")", "{", "return", "hostName", ";", "}", "public", "void", "setHostName", "(", "String", "hostName", ")", "{", "this", ".", "hostName", "=", "hostName", ";", "}", "public", "int", "getPort", "(", ")", "{", "return", "port", ";", "}", "public", "void", "setPort", "(", "int", "port", ")", "{", "this", ".", "port", "=", "port", ";", "}", "public", "Map", "<", "String", ",", "Object", ">", "getAttributes", "(", ")", "{", "return", "attributes", ";", "}", "public", "void", "setAttributes", "(", "Map", "<", "String", ",", "Object", ">", "attributes", ")", "{", "this", ".", "attributes", "=", "attributes", ";", "}", "public", "Object", "getAttribute", "(", "String", "name", ")", "{", "return", "attributes", ".", "get", "(", "name", ")", ";", "}", "public", "void", "setAttribute", "(", "String", "name", ",", "Object", "attributeValue", ")", "{", "if", "(", "attributeValue", "!=", "null", ")", "{", "attributes", ".", "put", "(", "name", ",", "attributeValue", ")", ";", "}", "else", "{", "attributes", ".", "remove", "(", "name", ")", ";", "}", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "final", "int", "prime", "=", "31", ";", "int", "result", "=", "1", ";", "result", "=", "prime", "*", "result", "+", "(", "hostName", "!=", "null", "?", "0", ":", "hostName", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "Integer", ".", "hashCode", "(", "port", ")", ";", "return", "result", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "obj", "instanceof", "ServerInfo", ")", "{", "if", "(", "obj", "==", "this", ")", "{", "return", "true", ";", "}", "ServerInfo", "other", "=", "(", "ServerInfo", ")", "obj", ";", "return", "other", ".", "getHostName", "(", ")", ".", "equals", "(", "getHostName", "(", ")", ")", "&&", "other", ".", "getPort", "(", ")", "==", "getPort", "(", ")", ";", "}", "return", "false", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "hostName", "+", "\"", ":", "\"", "+", "port", ";", "}", "}" ]
ServerInfo
[ "ServerInfo" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
467bda1f51160843df52c48a65754cc6afb66e73
KalebKE/CAExplorer
cellularAutomata/lattice/view/listener/PositionListener.java
[ "Apache-2.0" ]
Java
PositionListener
/** * A mouse listener that gets the location of the cell under the cursor. * * @author David Bahr */
A mouse listener that gets the location of the cell under the cursor. @author David Bahr
[ "A", "mouse", "listener", "that", "gets", "the", "location", "of", "the", "cell", "under", "the", "cursor", ".", "@author", "David", "Bahr" ]
public class PositionListener extends LatticeMouseListener { // indicates if the mouse is inside the component private boolean insideComponent = true; // the status panel that displays info about the current simulation. private StatusPanel statusPanel = null; /** * Create a listener for the mouse that will get the row and column of the * cell under the cursor. * * @param graphics * A graphics panel with an update that can be called by this * listener. * @param statusPanel * The panel that displays info about the current simulation * (like running, stopped, lattice size, etcetera). */ public PositionListener(LatticeView graphics, StatusPanel statusPanel) { super(graphics); this.statusPanel = statusPanel; } /** * Handles the mouse event by getting the row and col of the cell under the * cursor.. * * @param event * The mouseMoved event that called this method. */ private void getPosition(MouseEvent event) { Coordinate rowColPosition = null; if(insideComponent) { int xPos = event.getX(); int yPos = event.getY(); rowColPosition = super.getRowCol(xPos, yPos); // Do this so all lattices behave the same outside their range. the // hexagonal and triangular lattices are null outside their // range, but the square lattices are not. if(rowColPosition != null) { if(rowColPosition.getRow() >= getNumRows() || rowColPosition.getColumn() >= getNumColumns()) { rowColPosition = null; } } } // set the label on the status panel statusPanel.setCurrentCursorPositionLabel(rowColPosition); } /** * Does nothing. */ public void mouseClicked(MouseEvent event) { } /** * Gets the position of the cursor. */ public void mouseDragged(MouseEvent event) { if(insideComponent) { getPosition(event); } } /** * Keep track of when inside the component's boundaries. */ public void mouseEntered(MouseEvent event) { insideComponent = true; } /** * Keep track of when inside the component's boundaries. */ public void mouseExited(MouseEvent event) { insideComponent = false; // so sets a value of null and displays no value getPosition(event); } /** * Gets the position of the cursor. */ public void mouseMoved(MouseEvent event) { if(insideComponent) { getPosition(event); } } /** * Does nothing */ public void mousePressed(MouseEvent event) { } /** * Does nothing. */ public void mouseReleased(MouseEvent event) { } }
[ "public", "class", "PositionListener", "extends", "LatticeMouseListener", "{", "private", "boolean", "insideComponent", "=", "true", ";", "private", "StatusPanel", "statusPanel", "=", "null", ";", "/**\r\n * Create a listener for the mouse that will get the row and column of the\r\n * cell under the cursor.\r\n * \r\n * @param graphics\r\n * A graphics panel with an update that can be called by this\r\n * listener.\r\n * @param statusPanel\r\n * The panel that displays info about the current simulation\r\n * (like running, stopped, lattice size, etcetera).\r\n */", "public", "PositionListener", "(", "LatticeView", "graphics", ",", "StatusPanel", "statusPanel", ")", "{", "super", "(", "graphics", ")", ";", "this", ".", "statusPanel", "=", "statusPanel", ";", "}", "/**\r\n * Handles the mouse event by getting the row and col of the cell under the\r\n * cursor..\r\n * \r\n * @param event\r\n * The mouseMoved event that called this method.\r\n */", "private", "void", "getPosition", "(", "MouseEvent", "event", ")", "{", "Coordinate", "rowColPosition", "=", "null", ";", "if", "(", "insideComponent", ")", "{", "int", "xPos", "=", "event", ".", "getX", "(", ")", ";", "int", "yPos", "=", "event", ".", "getY", "(", ")", ";", "rowColPosition", "=", "super", ".", "getRowCol", "(", "xPos", ",", "yPos", ")", ";", "if", "(", "rowColPosition", "!=", "null", ")", "{", "if", "(", "rowColPosition", ".", "getRow", "(", ")", ">=", "getNumRows", "(", ")", "||", "rowColPosition", ".", "getColumn", "(", ")", ">=", "getNumColumns", "(", ")", ")", "{", "rowColPosition", "=", "null", ";", "}", "}", "}", "statusPanel", ".", "setCurrentCursorPositionLabel", "(", "rowColPosition", ")", ";", "}", "/**\r\n * Does nothing.\r\n */", "public", "void", "mouseClicked", "(", "MouseEvent", "event", ")", "{", "}", "/**\r\n * Gets the position of the cursor.\r\n */", "public", "void", "mouseDragged", "(", "MouseEvent", "event", ")", "{", "if", "(", "insideComponent", ")", "{", "getPosition", "(", "event", ")", ";", "}", "}", "/**\r\n * Keep track of when inside the component's boundaries.\r\n */", "public", "void", "mouseEntered", "(", "MouseEvent", "event", ")", "{", "insideComponent", "=", "true", ";", "}", "/**\r\n * Keep track of when inside the component's boundaries.\r\n */", "public", "void", "mouseExited", "(", "MouseEvent", "event", ")", "{", "insideComponent", "=", "false", ";", "getPosition", "(", "event", ")", ";", "}", "/**\r\n * Gets the position of the cursor.\r\n */", "public", "void", "mouseMoved", "(", "MouseEvent", "event", ")", "{", "if", "(", "insideComponent", ")", "{", "getPosition", "(", "event", ")", ";", "}", "}", "/**\r\n * Does nothing\r\n */", "public", "void", "mousePressed", "(", "MouseEvent", "event", ")", "{", "}", "/**\r\n * Does nothing.\r\n */", "public", "void", "mouseReleased", "(", "MouseEvent", "event", ")", "{", "}", "}" ]
A mouse listener that gets the location of the cell under the cursor.
[ "A", "mouse", "listener", "that", "gets", "the", "location", "of", "the", "cell", "under", "the", "cursor", "." ]
[ "// indicates if the mouse is inside the component\r", "// the status panel that displays info about the current simulation.\r", "// Do this so all lattices behave the same outside their range. the\r", "// hexagonal and triangular lattices are null outside their\r", "// range, but the square lattices are not.\r", "// set the label on the status panel\r", "// so sets a value of null and displays no value\r" ]
[ { "param": "LatticeMouseListener", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "LatticeMouseListener", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4684daee700ec6ce1014c791e94c746faefbd5a2
lauracristinaes/aula-java
hibernate-release-5.3.7.Final/project/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/AuditAssociationQueryImpl.java
[ "Apache-2.0" ]
Java
AuditAssociationQueryImpl
/** * @author Felix Feisst (feisst dot felix at gmail dot com) */
@author Felix Feisst (feisst dot felix at gmail dot com)
[ "@author", "Felix", "Feisst", "(", "feisst", "dot", "felix", "at", "gmail", "dot", "com", ")" ]
@Incubating public class AuditAssociationQueryImpl<Q extends AuditQueryImplementor> implements AuditAssociationQuery<Q>, AuditQueryImplementor { private final EnversService enversService; private final AuditReaderImplementor auditReader; private final Q parent; private final QueryBuilder queryBuilder; private final JoinType joinType; private final String entityName; private final IdMapper ownerAssociationIdMapper; private final String ownerAlias; private final String alias; private final Map<String, String> aliasToEntityNameMap; private final List<AuditCriterion> criterions = new ArrayList<>(); private final Parameters parameters; private final List<AuditAssociationQueryImpl<?>> associationQueries = new ArrayList<>(); private final Map<String, AuditAssociationQueryImpl<AuditAssociationQueryImpl<Q>>> associationQueryMap = new HashMap<>(); public AuditAssociationQueryImpl( final EnversService enversService, final AuditReaderImplementor auditReader, final Q parent, final QueryBuilder queryBuilder, final String propertyName, final JoinType joinType, final Map<String, String> aliasToEntityNameMap, final String ownerAlias, final String userSuppliedAlias) { this.enversService = enversService; this.auditReader = auditReader; this.parent = parent; this.queryBuilder = queryBuilder; this.joinType = joinType; String ownerEntityName = aliasToEntityNameMap.get( ownerAlias ); final RelationDescription relationDescription = CriteriaTools.getRelatedEntity( enversService, ownerEntityName, propertyName ); if ( relationDescription == null ) { throw new IllegalArgumentException( "Property " + propertyName + " of entity " + ownerEntityName + " is not a valid association for queries" ); } this.entityName = relationDescription.getToEntityName(); this.ownerAssociationIdMapper = relationDescription.getIdMapper(); this.ownerAlias = ownerAlias; this.alias = userSuppliedAlias == null ? queryBuilder.generateAlias() : userSuppliedAlias; aliasToEntityNameMap.put( this.alias, entityName ); this.aliasToEntityNameMap = aliasToEntityNameMap; parameters = queryBuilder.addParameters( this.alias ); } @Override public String getAlias() { return alias; } @Override public List getResultList() throws AuditException { return parent.getResultList(); } @Override public Object getSingleResult() throws AuditException, NonUniqueResultException, NoResultException { return parent.getSingleResult(); } @Override public AuditAssociationQueryImpl<AuditAssociationQueryImpl<Q>> traverseRelation( String associationName, JoinType joinType) { return traverseRelation( associationName, joinType, null ); } @Override public AuditAssociationQueryImpl<AuditAssociationQueryImpl<Q>> traverseRelation( String associationName, JoinType joinType, String alias) { AuditAssociationQueryImpl<AuditAssociationQueryImpl<Q>> result = associationQueryMap.get( associationName ); if ( result == null ) { result = new AuditAssociationQueryImpl<>( enversService, auditReader, this, queryBuilder, associationName, joinType, aliasToEntityNameMap, this.alias, alias ); associationQueries.add( result ); associationQueryMap.put( associationName, result ); } return result; } @Override public AuditAssociationQueryImpl<Q> add(AuditCriterion criterion) { criterions.add( criterion ); return this; } @Override public AuditAssociationQueryImpl<Q> addProjection(AuditProjection projection) { AuditProjection.ProjectionData projectionData = projection.getData( enversService ); String projectionEntityAlias = projectionData.getAlias( alias ); String projectionEntityName = aliasToEntityNameMap.get( projectionEntityAlias ); String propertyName = CriteriaTools.determinePropertyName( enversService, auditReader, projectionEntityName, projectionData.getPropertyName() ); queryBuilder.addProjection( projectionData.getFunction(), projectionEntityAlias, propertyName, projectionData.isDistinct() ); registerProjection( projectionEntityName, projection ); return this; } @Override public AuditAssociationQueryImpl<Q> addOrder(AuditOrder order) { AuditOrder.OrderData orderData = order.getData( enversService ); String orderEntityAlias = orderData.getAlias( alias ); String orderEntityName = aliasToEntityNameMap.get( orderEntityAlias ); String propertyName = CriteriaTools.determinePropertyName( enversService, auditReader, orderEntityName, orderData.getPropertyName() ); queryBuilder.addOrder( orderEntityAlias, propertyName, orderData.isAscending() ); return this; } @Override public AuditAssociationQueryImpl<Q> setMaxResults(int maxResults) { parent.setMaxResults( maxResults ); return this; } @Override public AuditAssociationQueryImpl<Q> setFirstResult(int firstResult) { parent.setFirstResult( firstResult ); return this; } @Override public AuditAssociationQueryImpl<Q> setCacheable(boolean cacheable) { parent.setCacheable( cacheable ); return this; } @Override public AuditAssociationQueryImpl<Q> setCacheRegion(String cacheRegion) { parent.setCacheRegion( cacheRegion ); return this; } @Override public AuditAssociationQueryImpl<Q> setComment(String comment) { parent.setComment( comment ); return this; } @Override public AuditAssociationQueryImpl<Q> setFlushMode(FlushMode flushMode) { parent.setFlushMode( flushMode ); return this; } @Override public AuditAssociationQueryImpl<Q> setCacheMode(CacheMode cacheMode) { parent.setCacheMode( cacheMode ); return this; } @Override public AuditAssociationQueryImpl<Q> setTimeout(int timeout) { parent.setTimeout( timeout ); return this; } @Override public AuditAssociationQueryImpl<Q> setLockMode(LockMode lockMode) { parent.setLockMode( lockMode ); return this; } public Q up() { return parent; } protected void addCriterionsToQuery(AuditReaderImplementor versionsReader) { if ( enversService.getEntitiesConfigurations().isVersioned( entityName ) ) { String auditEntityName = enversService.getAuditEntitiesConfiguration().getAuditEntityName( entityName ); Parameters joinConditionParameters = queryBuilder.addJoin( joinType, auditEntityName, alias, false ); // owner.reference_id = target.originalId.id AuditEntitiesConfiguration verEntCfg = enversService.getAuditEntitiesConfiguration(); String originalIdPropertyName = verEntCfg.getOriginalIdPropName(); IdMapper idMapperTarget = enversService.getEntitiesConfigurations().get( entityName ).getIdMapper(); final String prefix = alias.concat( "." ).concat( originalIdPropertyName ); ownerAssociationIdMapper.addIdsEqualToQuery( joinConditionParameters, ownerAlias, idMapperTarget, prefix ); // filter revision of target entity Parameters parametersToUse = parameters; String revisionPropertyPath = verEntCfg.getRevisionNumberPath(); if (joinType == JoinType.LEFT) { parametersToUse = parameters.addSubParameters( Parameters.OR ); parametersToUse.addNullRestriction( revisionPropertyPath, true ); parametersToUse = parametersToUse.addSubParameters( Parameters.AND ); } MiddleIdData referencedIdData = new MiddleIdData( verEntCfg, enversService.getEntitiesConfigurations().get( entityName ).getIdMappingData(), null, entityName, enversService.getEntitiesConfigurations().isVersioned( entityName ) ); enversService.getAuditStrategy().addEntityAtRevisionRestriction( enversService.getGlobalConfiguration(), queryBuilder, parametersToUse, revisionPropertyPath, verEntCfg.getRevisionEndFieldName(), true, referencedIdData, revisionPropertyPath, originalIdPropertyName, alias, queryBuilder.generateAlias(), true ); } else { Parameters joinConditionParameters = queryBuilder.addJoin( joinType, entityName, alias, false ); // owner.reference_id = target.id final IdMapper idMapperTarget = enversService.getEntitiesConfigurations() .getNotVersionEntityConfiguration( entityName ) .getIdMapper(); ownerAssociationIdMapper.addIdsEqualToQuery( joinConditionParameters, ownerAlias, idMapperTarget, alias ); } for ( AuditCriterion criterion : criterions ) { criterion.addToQuery( enversService, versionsReader, aliasToEntityNameMap, alias, queryBuilder, parameters ); } for ( final AuditAssociationQueryImpl<?> sub : associationQueries ) { sub.addCriterionsToQuery( versionsReader ); } } @Override public void registerProjection(final String entityName, AuditProjection projection) { parent.registerProjection( entityName, projection ); } }
[ "@", "Incubating", "public", "class", "AuditAssociationQueryImpl", "<", "Q", "extends", "AuditQueryImplementor", ">", "implements", "AuditAssociationQuery", "<", "Q", ">", ",", "AuditQueryImplementor", "{", "private", "final", "EnversService", "enversService", ";", "private", "final", "AuditReaderImplementor", "auditReader", ";", "private", "final", "Q", "parent", ";", "private", "final", "QueryBuilder", "queryBuilder", ";", "private", "final", "JoinType", "joinType", ";", "private", "final", "String", "entityName", ";", "private", "final", "IdMapper", "ownerAssociationIdMapper", ";", "private", "final", "String", "ownerAlias", ";", "private", "final", "String", "alias", ";", "private", "final", "Map", "<", "String", ",", "String", ">", "aliasToEntityNameMap", ";", "private", "final", "List", "<", "AuditCriterion", ">", "criterions", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "private", "final", "Parameters", "parameters", ";", "private", "final", "List", "<", "AuditAssociationQueryImpl", "<", "?", ">", ">", "associationQueries", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "private", "final", "Map", "<", "String", ",", "AuditAssociationQueryImpl", "<", "AuditAssociationQueryImpl", "<", "Q", ">", ">", ">", "associationQueryMap", "=", "new", "HashMap", "<", ">", "(", ")", ";", "public", "AuditAssociationQueryImpl", "(", "final", "EnversService", "enversService", ",", "final", "AuditReaderImplementor", "auditReader", ",", "final", "Q", "parent", ",", "final", "QueryBuilder", "queryBuilder", ",", "final", "String", "propertyName", ",", "final", "JoinType", "joinType", ",", "final", "Map", "<", "String", ",", "String", ">", "aliasToEntityNameMap", ",", "final", "String", "ownerAlias", ",", "final", "String", "userSuppliedAlias", ")", "{", "this", ".", "enversService", "=", "enversService", ";", "this", ".", "auditReader", "=", "auditReader", ";", "this", ".", "parent", "=", "parent", ";", "this", ".", "queryBuilder", "=", "queryBuilder", ";", "this", ".", "joinType", "=", "joinType", ";", "String", "ownerEntityName", "=", "aliasToEntityNameMap", ".", "get", "(", "ownerAlias", ")", ";", "final", "RelationDescription", "relationDescription", "=", "CriteriaTools", ".", "getRelatedEntity", "(", "enversService", ",", "ownerEntityName", ",", "propertyName", ")", ";", "if", "(", "relationDescription", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Property ", "\"", "+", "propertyName", "+", "\"", " of entity ", "\"", "+", "ownerEntityName", "+", "\"", " is not a valid association for queries", "\"", ")", ";", "}", "this", ".", "entityName", "=", "relationDescription", ".", "getToEntityName", "(", ")", ";", "this", ".", "ownerAssociationIdMapper", "=", "relationDescription", ".", "getIdMapper", "(", ")", ";", "this", ".", "ownerAlias", "=", "ownerAlias", ";", "this", ".", "alias", "=", "userSuppliedAlias", "==", "null", "?", "queryBuilder", ".", "generateAlias", "(", ")", ":", "userSuppliedAlias", ";", "aliasToEntityNameMap", ".", "put", "(", "this", ".", "alias", ",", "entityName", ")", ";", "this", ".", "aliasToEntityNameMap", "=", "aliasToEntityNameMap", ";", "parameters", "=", "queryBuilder", ".", "addParameters", "(", "this", ".", "alias", ")", ";", "}", "@", "Override", "public", "String", "getAlias", "(", ")", "{", "return", "alias", ";", "}", "@", "Override", "public", "List", "getResultList", "(", ")", "throws", "AuditException", "{", "return", "parent", ".", "getResultList", "(", ")", ";", "}", "@", "Override", "public", "Object", "getSingleResult", "(", ")", "throws", "AuditException", ",", "NonUniqueResultException", ",", "NoResultException", "{", "return", "parent", ".", "getSingleResult", "(", ")", ";", "}", "@", "Override", "public", "AuditAssociationQueryImpl", "<", "AuditAssociationQueryImpl", "<", "Q", ">", ">", "traverseRelation", "(", "String", "associationName", ",", "JoinType", "joinType", ")", "{", "return", "traverseRelation", "(", "associationName", ",", "joinType", ",", "null", ")", ";", "}", "@", "Override", "public", "AuditAssociationQueryImpl", "<", "AuditAssociationQueryImpl", "<", "Q", ">", ">", "traverseRelation", "(", "String", "associationName", ",", "JoinType", "joinType", ",", "String", "alias", ")", "{", "AuditAssociationQueryImpl", "<", "AuditAssociationQueryImpl", "<", "Q", ">", ">", "result", "=", "associationQueryMap", ".", "get", "(", "associationName", ")", ";", "if", "(", "result", "==", "null", ")", "{", "result", "=", "new", "AuditAssociationQueryImpl", "<", ">", "(", "enversService", ",", "auditReader", ",", "this", ",", "queryBuilder", ",", "associationName", ",", "joinType", ",", "aliasToEntityNameMap", ",", "this", ".", "alias", ",", "alias", ")", ";", "associationQueries", ".", "add", "(", "result", ")", ";", "associationQueryMap", ".", "put", "(", "associationName", ",", "result", ")", ";", "}", "return", "result", ";", "}", "@", "Override", "public", "AuditAssociationQueryImpl", "<", "Q", ">", "add", "(", "AuditCriterion", "criterion", ")", "{", "criterions", ".", "add", "(", "criterion", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "AuditAssociationQueryImpl", "<", "Q", ">", "addProjection", "(", "AuditProjection", "projection", ")", "{", "AuditProjection", ".", "ProjectionData", "projectionData", "=", "projection", ".", "getData", "(", "enversService", ")", ";", "String", "projectionEntityAlias", "=", "projectionData", ".", "getAlias", "(", "alias", ")", ";", "String", "projectionEntityName", "=", "aliasToEntityNameMap", ".", "get", "(", "projectionEntityAlias", ")", ";", "String", "propertyName", "=", "CriteriaTools", ".", "determinePropertyName", "(", "enversService", ",", "auditReader", ",", "projectionEntityName", ",", "projectionData", ".", "getPropertyName", "(", ")", ")", ";", "queryBuilder", ".", "addProjection", "(", "projectionData", ".", "getFunction", "(", ")", ",", "projectionEntityAlias", ",", "propertyName", ",", "projectionData", ".", "isDistinct", "(", ")", ")", ";", "registerProjection", "(", "projectionEntityName", ",", "projection", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "AuditAssociationQueryImpl", "<", "Q", ">", "addOrder", "(", "AuditOrder", "order", ")", "{", "AuditOrder", ".", "OrderData", "orderData", "=", "order", ".", "getData", "(", "enversService", ")", ";", "String", "orderEntityAlias", "=", "orderData", ".", "getAlias", "(", "alias", ")", ";", "String", "orderEntityName", "=", "aliasToEntityNameMap", ".", "get", "(", "orderEntityAlias", ")", ";", "String", "propertyName", "=", "CriteriaTools", ".", "determinePropertyName", "(", "enversService", ",", "auditReader", ",", "orderEntityName", ",", "orderData", ".", "getPropertyName", "(", ")", ")", ";", "queryBuilder", ".", "addOrder", "(", "orderEntityAlias", ",", "propertyName", ",", "orderData", ".", "isAscending", "(", ")", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "AuditAssociationQueryImpl", "<", "Q", ">", "setMaxResults", "(", "int", "maxResults", ")", "{", "parent", ".", "setMaxResults", "(", "maxResults", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "AuditAssociationQueryImpl", "<", "Q", ">", "setFirstResult", "(", "int", "firstResult", ")", "{", "parent", ".", "setFirstResult", "(", "firstResult", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "AuditAssociationQueryImpl", "<", "Q", ">", "setCacheable", "(", "boolean", "cacheable", ")", "{", "parent", ".", "setCacheable", "(", "cacheable", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "AuditAssociationQueryImpl", "<", "Q", ">", "setCacheRegion", "(", "String", "cacheRegion", ")", "{", "parent", ".", "setCacheRegion", "(", "cacheRegion", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "AuditAssociationQueryImpl", "<", "Q", ">", "setComment", "(", "String", "comment", ")", "{", "parent", ".", "setComment", "(", "comment", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "AuditAssociationQueryImpl", "<", "Q", ">", "setFlushMode", "(", "FlushMode", "flushMode", ")", "{", "parent", ".", "setFlushMode", "(", "flushMode", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "AuditAssociationQueryImpl", "<", "Q", ">", "setCacheMode", "(", "CacheMode", "cacheMode", ")", "{", "parent", ".", "setCacheMode", "(", "cacheMode", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "AuditAssociationQueryImpl", "<", "Q", ">", "setTimeout", "(", "int", "timeout", ")", "{", "parent", ".", "setTimeout", "(", "timeout", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "AuditAssociationQueryImpl", "<", "Q", ">", "setLockMode", "(", "LockMode", "lockMode", ")", "{", "parent", ".", "setLockMode", "(", "lockMode", ")", ";", "return", "this", ";", "}", "public", "Q", "up", "(", ")", "{", "return", "parent", ";", "}", "protected", "void", "addCriterionsToQuery", "(", "AuditReaderImplementor", "versionsReader", ")", "{", "if", "(", "enversService", ".", "getEntitiesConfigurations", "(", ")", ".", "isVersioned", "(", "entityName", ")", ")", "{", "String", "auditEntityName", "=", "enversService", ".", "getAuditEntitiesConfiguration", "(", ")", ".", "getAuditEntityName", "(", "entityName", ")", ";", "Parameters", "joinConditionParameters", "=", "queryBuilder", ".", "addJoin", "(", "joinType", ",", "auditEntityName", ",", "alias", ",", "false", ")", ";", "AuditEntitiesConfiguration", "verEntCfg", "=", "enversService", ".", "getAuditEntitiesConfiguration", "(", ")", ";", "String", "originalIdPropertyName", "=", "verEntCfg", ".", "getOriginalIdPropName", "(", ")", ";", "IdMapper", "idMapperTarget", "=", "enversService", ".", "getEntitiesConfigurations", "(", ")", ".", "get", "(", "entityName", ")", ".", "getIdMapper", "(", ")", ";", "final", "String", "prefix", "=", "alias", ".", "concat", "(", "\"", ".", "\"", ")", ".", "concat", "(", "originalIdPropertyName", ")", ";", "ownerAssociationIdMapper", ".", "addIdsEqualToQuery", "(", "joinConditionParameters", ",", "ownerAlias", ",", "idMapperTarget", ",", "prefix", ")", ";", "Parameters", "parametersToUse", "=", "parameters", ";", "String", "revisionPropertyPath", "=", "verEntCfg", ".", "getRevisionNumberPath", "(", ")", ";", "if", "(", "joinType", "==", "JoinType", ".", "LEFT", ")", "{", "parametersToUse", "=", "parameters", ".", "addSubParameters", "(", "Parameters", ".", "OR", ")", ";", "parametersToUse", ".", "addNullRestriction", "(", "revisionPropertyPath", ",", "true", ")", ";", "parametersToUse", "=", "parametersToUse", ".", "addSubParameters", "(", "Parameters", ".", "AND", ")", ";", "}", "MiddleIdData", "referencedIdData", "=", "new", "MiddleIdData", "(", "verEntCfg", ",", "enversService", ".", "getEntitiesConfigurations", "(", ")", ".", "get", "(", "entityName", ")", ".", "getIdMappingData", "(", ")", ",", "null", ",", "entityName", ",", "enversService", ".", "getEntitiesConfigurations", "(", ")", ".", "isVersioned", "(", "entityName", ")", ")", ";", "enversService", ".", "getAuditStrategy", "(", ")", ".", "addEntityAtRevisionRestriction", "(", "enversService", ".", "getGlobalConfiguration", "(", ")", ",", "queryBuilder", ",", "parametersToUse", ",", "revisionPropertyPath", ",", "verEntCfg", ".", "getRevisionEndFieldName", "(", ")", ",", "true", ",", "referencedIdData", ",", "revisionPropertyPath", ",", "originalIdPropertyName", ",", "alias", ",", "queryBuilder", ".", "generateAlias", "(", ")", ",", "true", ")", ";", "}", "else", "{", "Parameters", "joinConditionParameters", "=", "queryBuilder", ".", "addJoin", "(", "joinType", ",", "entityName", ",", "alias", ",", "false", ")", ";", "final", "IdMapper", "idMapperTarget", "=", "enversService", ".", "getEntitiesConfigurations", "(", ")", ".", "getNotVersionEntityConfiguration", "(", "entityName", ")", ".", "getIdMapper", "(", ")", ";", "ownerAssociationIdMapper", ".", "addIdsEqualToQuery", "(", "joinConditionParameters", ",", "ownerAlias", ",", "idMapperTarget", ",", "alias", ")", ";", "}", "for", "(", "AuditCriterion", "criterion", ":", "criterions", ")", "{", "criterion", ".", "addToQuery", "(", "enversService", ",", "versionsReader", ",", "aliasToEntityNameMap", ",", "alias", ",", "queryBuilder", ",", "parameters", ")", ";", "}", "for", "(", "final", "AuditAssociationQueryImpl", "<", "?", ">", "sub", ":", "associationQueries", ")", "{", "sub", ".", "addCriterionsToQuery", "(", "versionsReader", ")", ";", "}", "}", "@", "Override", "public", "void", "registerProjection", "(", "final", "String", "entityName", ",", "AuditProjection", "projection", ")", "{", "parent", ".", "registerProjection", "(", "entityName", ",", "projection", ")", ";", "}", "}" ]
@author Felix Feisst (feisst dot felix at gmail dot com)
[ "@author", "Felix", "Feisst", "(", "feisst", "dot", "felix", "at", "gmail", "dot", "com", ")" ]
[ "// owner.reference_id = target.originalId.id", "// filter revision of target entity", "// owner.reference_id = target.id" ]
[ { "param": "AuditAssociationQuery<Q>, AuditQueryImplementor", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AuditAssociationQuery<Q>, AuditQueryImplementor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
46869f7e402cc9bd45e57c5a4a43c836f17086e0
mathgladiator/adama-lang
core/src/main/java/org/adamalang/translator/tree/definitions/DefineTest.java
[ "MIT" ]
Java
DefineTest
/** defines a test to run on an empty document, this helps validate flow */
defines a test to run on an empty document, this helps validate flow
[ "defines", "a", "test", "to", "run", "on", "an", "empty", "document", "this", "helps", "validate", "flow" ]
public class DefineTest extends Definition { public final Block code; public final String name; public final Token nameToken; public final Token testToken; public DefineTest(final Token testToken, final Token nameToken, final Block code) { this.testToken = testToken; this.nameToken = nameToken; name = nameToken.text; this.code = code; ingest(code); } @Override public void emit(final Consumer<Token> yielder) { yielder.accept(testToken); yielder.accept(nameToken); code.emit(yielder); } @Override public void typing(final Environment environment) { code.typing(environment.scopeAsUnitTest()); } }
[ "public", "class", "DefineTest", "extends", "Definition", "{", "public", "final", "Block", "code", ";", "public", "final", "String", "name", ";", "public", "final", "Token", "nameToken", ";", "public", "final", "Token", "testToken", ";", "public", "DefineTest", "(", "final", "Token", "testToken", ",", "final", "Token", "nameToken", ",", "final", "Block", "code", ")", "{", "this", ".", "testToken", "=", "testToken", ";", "this", ".", "nameToken", "=", "nameToken", ";", "name", "=", "nameToken", ".", "text", ";", "this", ".", "code", "=", "code", ";", "ingest", "(", "code", ")", ";", "}", "@", "Override", "public", "void", "emit", "(", "final", "Consumer", "<", "Token", ">", "yielder", ")", "{", "yielder", ".", "accept", "(", "testToken", ")", ";", "yielder", ".", "accept", "(", "nameToken", ")", ";", "code", ".", "emit", "(", "yielder", ")", ";", "}", "@", "Override", "public", "void", "typing", "(", "final", "Environment", "environment", ")", "{", "code", ".", "typing", "(", "environment", ".", "scopeAsUnitTest", "(", ")", ")", ";", "}", "}" ]
defines a test to run on an empty document, this helps validate flow
[ "defines", "a", "test", "to", "run", "on", "an", "empty", "document", "this", "helps", "validate", "flow" ]
[]
[ { "param": "Definition", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Definition", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4687ed6d4cd4ba9d88c03b3b55fe6b03a474cbfd
mP1/walkingkooka-spreadsheet
src/main/java/walkingkooka/spreadsheet/tool/TextStylePropertyNameConstantJavaScriptSourceTool.java
[ "Apache-2.0" ]
Java
TextStylePropertyNameConstantJavaScriptSourceTool
/** * When run prints out javascript constants for each of the {@link TextStylePropertyName} properties. */
When run prints out javascript constants for each of the TextStylePropertyName properties.
[ "When", "run", "prints", "out", "javascript", "constants", "for", "each", "of", "the", "TextStylePropertyName", "properties", "." ]
public final class TextStylePropertyNameConstantJavaScriptSourceTool { public static void main(final String[] args) { try (final IndentingPrinter printer = Printers.sysOut().indenting(Indentation.with(" "))) { for (final TextStylePropertyName<?> name : TextStylePropertyName.values()) { printer.println("static " + name.constantName() + " = \"" + name.value() + "\";"); } printer.flush(); } } }
[ "public", "final", "class", "TextStylePropertyNameConstantJavaScriptSourceTool", "{", "public", "static", "void", "main", "(", "final", "String", "[", "]", "args", ")", "{", "try", "(", "final", "IndentingPrinter", "printer", "=", "Printers", ".", "sysOut", "(", ")", ".", "indenting", "(", "Indentation", ".", "with", "(", "\"", " ", "\"", ")", ")", ")", "{", "for", "(", "final", "TextStylePropertyName", "<", "?", ">", "name", ":", "TextStylePropertyName", ".", "values", "(", ")", ")", "{", "printer", ".", "println", "(", "\"", "static ", "\"", "+", "name", ".", "constantName", "(", ")", "+", "\"", " = ", "\\\"", "\"", "+", "name", ".", "value", "(", ")", "+", "\"", "\\\"", ";", "\"", ")", ";", "}", "printer", ".", "flush", "(", ")", ";", "}", "}", "}" ]
When run prints out javascript constants for each of the {@link TextStylePropertyName} properties.
[ "When", "run", "prints", "out", "javascript", "constants", "for", "each", "of", "the", "{", "@link", "TextStylePropertyName", "}", "properties", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
468951c1630d7eb217d0fb1d986dfbed2eca9280
booleguo/Reactive-Design-Patterns
chapter14/src/main/java/chapter14/ResourceEncapsulation.java
[ "Apache-2.0" ]
Java
ResourceEncapsulation
/** * This is not a completely runnable example but only a fully compiled collection of code snippets * used in section 13.1. */
This is not a completely runnable example but only a fully compiled collection of code snippets used in section 13.1.
[ "This", "is", "not", "a", "completely", "runnable", "example", "but", "only", "a", "fully", "compiled", "collection", "of", "code", "snippets", "used", "in", "section", "13", ".", "1", "." ]
public class ResourceEncapsulation { // #snip_14-1 public Instance startInstance(final AWSCredentials credentials) { final AmazonEC2 amazonEC2Client = AmazonEC2ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .build(); final RunInstancesRequest runInstancesRequest = new RunInstancesRequest() .withImageId("") .withInstanceType("m1.small") .withMinCount(1) .withMaxCount(1); final RunInstancesResult runInstancesResult = amazonEC2Client.runInstances(runInstancesRequest); final Reservation reservation = runInstancesResult.getReservation(); final List<Instance> instances = reservation.getInstances(); // there will be exactly one INSTANCE in this list, otherwise // runInstances() would have thrown an exception return instances.get(0); } // #snip_14-1 // #snip_14-2 private ExecutionContext executionContext; // value from somewhere private CircuitBreaker circuitBreaker; // value from somewhere public Future<Instance> startInstanceAsync(AWSCredentials credentials) { final Future<Instance> f = circuitBreaker.callWithCircuitBreaker( () -> Futures.future(() -> startInstance(credentials), executionContext)); final PartialFunction<Throwable, Future<Instance>> recovery = new PFBuilder<Throwable, Future<Instance>>() .match( AmazonClientException.class, AmazonClientException::isRetryable, ex -> startInstanceAsync(credentials)) .build(); return f.recoverWith(recovery, executionContext); } // #snip_14-2 // #snip_14-3 public Future<RunInstancesResult> runInstancesAsync( final RunInstancesRequest request, final AmazonEC2Async client) { final Promise<RunInstancesResult> promise = Futures.promise(); client.runInstancesAsync( request, new AsyncHandler<RunInstancesRequest, RunInstancesResult>() { @Override public void onSuccess(RunInstancesRequest request, RunInstancesResult result) { promise.success(result); } @Override public void onError(Exception exception) { promise.failure(exception); } }); return promise.future(); } // #snip_14-3 // #snip_14-4 public Future<TerminateInstancesResult> terminateInstancesAsync( final AmazonEC2Client client, final Instance... instances) { final List<String> ids = Arrays.stream(instances).map(Instance::getInstanceId).collect(Collectors.toList()); final TerminateInstancesRequest request = new TerminateInstancesRequest(ids); final Future<TerminateInstancesResult> f = circuitBreaker.callWithCircuitBreaker( () -> Futures.future(() -> client.terminateInstances(request), executionContext)); final PartialFunction<Throwable, Future<TerminateInstancesResult>> recovery = new PFBuilder<Throwable, Future<TerminateInstancesResult>>() .match( AmazonClientException.class, AmazonClientException::isRetryable, ex -> terminateInstancesAsync(client, instances)) .build(); return f.recoverWith(recovery, executionContext); } // #snip_14-4 static interface WorkerNodeMessage { public long id(); public ActorRef replyTo(); } static class WorkerCommandFailed { public final String reason; public final long id; public WorkerCommandFailed(String reason, long id) { this.reason = reason; this.id = id; } } static class DoHealthCheck { public static final DoHealthCheck INSTANCE = new DoHealthCheck(); } static class Shutdown { public static Shutdown instance = new Shutdown(); } static class WorkerNodeReady { public static WorkerNodeReady instance = new WorkerNodeReady(); } // #snip_14-5 class WorkerNode extends AbstractActor { private final Cancellable checkTimer; public WorkerNode(final InetAddress address, final Duration checkInterval) { checkTimer = getContext() .getSystem() .getScheduler() .schedule( checkInterval, checkInterval, self(), DoHealthCheck.INSTANCE, getContext().dispatcher(), self()); } @Override public Receive createReceive() { final List<WorkerNodeMessage> msgs = new ArrayList<>(); return receiveBuilder() .match(WorkerNodeMessage.class, msgs::add) .match( DoHealthCheck.class, dhc -> { /* perform check */ }) .match( Shutdown.class, s -> { msgs.forEach( msg -> msg.replyTo() .tell(new WorkerCommandFailed("shutting down", msg.id()), self())); /* ask Resource Pool to shut down this INSTANCE */ }) .match( WorkerNodeReady.class, wnr -> { /* send msgs to the worker */ getContext().become(initialized()); }) .build(); } private Receive initialized() { /* forward commands and deal with responses from worker node */ // ... return null; } @Override public void postStop() { checkTimer.cancel(); } } // #snip_14-5 }
[ "public", "class", "ResourceEncapsulation", "{", "public", "Instance", "startInstance", "(", "final", "AWSCredentials", "credentials", ")", "{", "final", "AmazonEC2", "amazonEC2Client", "=", "AmazonEC2ClientBuilder", ".", "standard", "(", ")", ".", "withCredentials", "(", "new", "AWSStaticCredentialsProvider", "(", "credentials", ")", ")", ".", "build", "(", ")", ";", "final", "RunInstancesRequest", "runInstancesRequest", "=", "new", "RunInstancesRequest", "(", ")", ".", "withImageId", "(", "\"", "\"", ")", ".", "withInstanceType", "(", "\"", "m1.small", "\"", ")", ".", "withMinCount", "(", "1", ")", ".", "withMaxCount", "(", "1", ")", ";", "final", "RunInstancesResult", "runInstancesResult", "=", "amazonEC2Client", ".", "runInstances", "(", "runInstancesRequest", ")", ";", "final", "Reservation", "reservation", "=", "runInstancesResult", ".", "getReservation", "(", ")", ";", "final", "List", "<", "Instance", ">", "instances", "=", "reservation", ".", "getInstances", "(", ")", ";", "return", "instances", ".", "get", "(", "0", ")", ";", "}", "private", "ExecutionContext", "executionContext", ";", "private", "CircuitBreaker", "circuitBreaker", ";", "public", "Future", "<", "Instance", ">", "startInstanceAsync", "(", "AWSCredentials", "credentials", ")", "{", "final", "Future", "<", "Instance", ">", "f", "=", "circuitBreaker", ".", "callWithCircuitBreaker", "(", "(", ")", "->", "Futures", ".", "future", "(", "(", ")", "->", "startInstance", "(", "credentials", ")", ",", "executionContext", ")", ")", ";", "final", "PartialFunction", "<", "Throwable", ",", "Future", "<", "Instance", ">", ">", "recovery", "=", "new", "PFBuilder", "<", "Throwable", ",", "Future", "<", "Instance", ">", ">", "(", ")", ".", "match", "(", "AmazonClientException", ".", "class", ",", "AmazonClientException", "::", "isRetryable", ",", "ex", "->", "startInstanceAsync", "(", "credentials", ")", ")", ".", "build", "(", ")", ";", "return", "f", ".", "recoverWith", "(", "recovery", ",", "executionContext", ")", ";", "}", "public", "Future", "<", "RunInstancesResult", ">", "runInstancesAsync", "(", "final", "RunInstancesRequest", "request", ",", "final", "AmazonEC2Async", "client", ")", "{", "final", "Promise", "<", "RunInstancesResult", ">", "promise", "=", "Futures", ".", "promise", "(", ")", ";", "client", ".", "runInstancesAsync", "(", "request", ",", "new", "AsyncHandler", "<", "RunInstancesRequest", ",", "RunInstancesResult", ">", "(", ")", "{", "@", "Override", "public", "void", "onSuccess", "(", "RunInstancesRequest", "request", ",", "RunInstancesResult", "result", ")", "{", "promise", ".", "success", "(", "result", ")", ";", "}", "@", "Override", "public", "void", "onError", "(", "Exception", "exception", ")", "{", "promise", ".", "failure", "(", "exception", ")", ";", "}", "}", ")", ";", "return", "promise", ".", "future", "(", ")", ";", "}", "public", "Future", "<", "TerminateInstancesResult", ">", "terminateInstancesAsync", "(", "final", "AmazonEC2Client", "client", ",", "final", "Instance", "...", "instances", ")", "{", "final", "List", "<", "String", ">", "ids", "=", "Arrays", ".", "stream", "(", "instances", ")", ".", "map", "(", "Instance", "::", "getInstanceId", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "final", "TerminateInstancesRequest", "request", "=", "new", "TerminateInstancesRequest", "(", "ids", ")", ";", "final", "Future", "<", "TerminateInstancesResult", ">", "f", "=", "circuitBreaker", ".", "callWithCircuitBreaker", "(", "(", ")", "->", "Futures", ".", "future", "(", "(", ")", "->", "client", ".", "terminateInstances", "(", "request", ")", ",", "executionContext", ")", ")", ";", "final", "PartialFunction", "<", "Throwable", ",", "Future", "<", "TerminateInstancesResult", ">", ">", "recovery", "=", "new", "PFBuilder", "<", "Throwable", ",", "Future", "<", "TerminateInstancesResult", ">", ">", "(", ")", ".", "match", "(", "AmazonClientException", ".", "class", ",", "AmazonClientException", "::", "isRetryable", ",", "ex", "->", "terminateInstancesAsync", "(", "client", ",", "instances", ")", ")", ".", "build", "(", ")", ";", "return", "f", ".", "recoverWith", "(", "recovery", ",", "executionContext", ")", ";", "}", "static", "interface", "WorkerNodeMessage", "{", "public", "long", "id", "(", ")", ";", "public", "ActorRef", "replyTo", "(", ")", ";", "}", "static", "class", "WorkerCommandFailed", "{", "public", "final", "String", "reason", ";", "public", "final", "long", "id", ";", "public", "WorkerCommandFailed", "(", "String", "reason", ",", "long", "id", ")", "{", "this", ".", "reason", "=", "reason", ";", "this", ".", "id", "=", "id", ";", "}", "}", "static", "class", "DoHealthCheck", "{", "public", "static", "final", "DoHealthCheck", "INSTANCE", "=", "new", "DoHealthCheck", "(", ")", ";", "}", "static", "class", "Shutdown", "{", "public", "static", "Shutdown", "instance", "=", "new", "Shutdown", "(", ")", ";", "}", "static", "class", "WorkerNodeReady", "{", "public", "static", "WorkerNodeReady", "instance", "=", "new", "WorkerNodeReady", "(", ")", ";", "}", "class", "WorkerNode", "extends", "AbstractActor", "{", "private", "final", "Cancellable", "checkTimer", ";", "public", "WorkerNode", "(", "final", "InetAddress", "address", ",", "final", "Duration", "checkInterval", ")", "{", "checkTimer", "=", "getContext", "(", ")", ".", "getSystem", "(", ")", ".", "getScheduler", "(", ")", ".", "schedule", "(", "checkInterval", ",", "checkInterval", ",", "self", "(", ")", ",", "DoHealthCheck", ".", "INSTANCE", ",", "getContext", "(", ")", ".", "dispatcher", "(", ")", ",", "self", "(", ")", ")", ";", "}", "@", "Override", "public", "Receive", "createReceive", "(", ")", "{", "final", "List", "<", "WorkerNodeMessage", ">", "msgs", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "return", "receiveBuilder", "(", ")", ".", "match", "(", "WorkerNodeMessage", ".", "class", ",", "msgs", "::", "add", ")", ".", "match", "(", "DoHealthCheck", ".", "class", ",", "dhc", "->", "{", "/* perform check */", "}", ")", ".", "match", "(", "Shutdown", ".", "class", ",", "s", "->", "{", "msgs", ".", "forEach", "(", "msg", "->", "msg", ".", "replyTo", "(", ")", ".", "tell", "(", "new", "WorkerCommandFailed", "(", "\"", "shutting down", "\"", ",", "msg", ".", "id", "(", ")", ")", ",", "self", "(", ")", ")", ")", ";", "/* ask Resource Pool to shut down this INSTANCE */", "}", ")", ".", "match", "(", "WorkerNodeReady", ".", "class", ",", "wnr", "->", "{", "/* send msgs to the worker */", "getContext", "(", ")", ".", "become", "(", "initialized", "(", ")", ")", ";", "}", ")", ".", "build", "(", ")", ";", "}", "private", "Receive", "initialized", "(", ")", "{", "/* forward commands and deal with responses from worker node */", "return", "null", ";", "}", "@", "Override", "public", "void", "postStop", "(", ")", "{", "checkTimer", ".", "cancel", "(", ")", ";", "}", "}", "}" ]
This is not a completely runnable example but only a fully compiled collection of code snippets used in section 13.1.
[ "This", "is", "not", "a", "completely", "runnable", "example", "but", "only", "a", "fully", "compiled", "collection", "of", "code", "snippets", "used", "in", "section", "13", ".", "1", "." ]
[ "// #snip_14-1", "// there will be exactly one INSTANCE in this list, otherwise", "// runInstances() would have thrown an exception", "// #snip_14-1", "// #snip_14-2", "// value from somewhere", "// value from somewhere", "// #snip_14-2", "// #snip_14-3", "// #snip_14-3", "// #snip_14-4", "// #snip_14-4", "// #snip_14-5", "// ...", "// #snip_14-5" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
468c3a36f51938f6451767829a894dde806b509a
wavelength-ide/wavelength-ide
Wavelength/src/edu/kit/wavelength/client/view/execution/Executor.java
[ "BSD-3-Clause" ]
Java
Executor
/** * Concurrently reduces lambda terms. */
Concurrently reduces lambda terms.
[ "Concurrently", "reduces", "lambda", "terms", "." ]
public class Executor implements Serializable { private enum S { Running, Paused, Terminated } private static class State { S val; State(S v) { this.val = v; } State(State s) { this(s.val); } } private static int allowedReductionTimeMS = 100; private List<ExecutionObserver> executionObservers; private List<ControlObserver> controlObservers; private List<ReductionStepCountObserver> reductionStepCountObserver; private State state = new State(S.Terminated); private void setState(S v) { state.val = v; state = new State(state); } private ExecutionEngine engine; /** * Creates a new Executor. * * @param executionObservers * Observers to update with reduced lambda terms * @param controlObservers * Observers to notify when executor reaches certain states */ public Executor(List<ExecutionObserver> executionObservers, List<ControlObserver> controlObservers, List<ReductionStepCountObserver> reductionStepCountObserver) { this.executionObservers = executionObservers; this.controlObservers = controlObservers; this.reductionStepCountObserver = reductionStepCountObserver; } private void pushCount(int n) { reductionStepCountObserver.forEach(o -> o.update(n)); } private void pushEngineCount() { pushCount(engine.getStepNumber()); } private void pushTerm(LambdaTerm t) { executionObservers.forEach(o -> o.pushTerm(t)); } private void pushTerms(Iterable<LambdaTerm> ts) { ts.forEach(this::pushTerm); } private void pushError(String error) { executionObservers.forEach(o -> o.pushError(error)); } private void scheduleExecution() { final State state = this.state; Scheduler.get().scheduleIncremental(() -> { Date start = new Date(); switch (state.val) { case Terminated: return false; case Paused: return false; default: while (true) { if (engine.isFinished()) { setState(S.Paused); controlObservers.forEach(ControlObserver::finish); return false; } List<LambdaTerm> displayedTerms; try { displayedTerms = engine.stepForward(); } catch (ExecutionException e) { setState(S.Paused); pushError(e.getMessage()); controlObservers.forEach(ControlObserver::finish); return false; } pushEngineCount(); pushTerms(displayedTerms); Date end = new Date(); if (end.getTime() - start.getTime() > allowedReductionTimeMS) { return true; } } } }); } /** * Starts the automatic execution of the input, parsing the term and then * reducing it. * * @param input * code to parse and reduce * @param order * order with which to reduce * @param size * which terms to push to observers * @param libraries * libraries to consider when parsing * @throws ParseException * thrown when input cannot be parsed */ public void start(String input, ReductionOrder order, OutputSize size, List<Library> libraries) throws ParseException { if (!isTerminated()) { throw new IllegalStateException("trying to start execution while execution is not terminated"); } executionObservers.forEach(o -> o.clear()); engine = new ExecutionEngine(input, order, size, libraries); setState(S.Running); if (!engine.getDisplayed().isEmpty()) { pushTerm(engine.getDisplayed().get(0)); } pushEngineCount(); scheduleExecution(); } /** * Initiates the step by step execution, allowing the caller to choose the next * step. * * @param input * code to parse and execute * @param order * order with which to reduce * @param size * which terms to push to observers * @param libraries * libraries to consider when parsing * @throws ParseException * thrown when input cannot be parsed */ public void stepByStep(String input, ReductionOrder order, OutputSize size, List<Library> libraries) throws ParseException { if (!isTerminated()) { throw new IllegalStateException("trying to start execution while execution is not terminated"); } executionObservers.forEach(o -> o.clear()); engine = new ExecutionEngine(input, order, size, libraries); setState(S.Paused); if (!engine.getDisplayed().isEmpty()) { pushTerm(engine.getDisplayed().get(0)); } pushEngineCount(); } /** * Pauses the automatic execution, transitioning into the step by step mode. */ public void pause() { if (!isRunning()) { throw new IllegalStateException("trying to pause execution that isn't running"); } setState(S.Paused); if (!engine.isCurrentDisplayed()) { LambdaTerm current = engine.displayCurrent(); pushTerm(current); } pushEngineCount(); } /** * Unpauses the automatic execution, transitioning from step by step mode into * automatic execution. */ public void unpause() { if (!isPaused()) { throw new IllegalStateException("trying to unpause execution that isn't paused"); } setState(S.Running); scheduleExecution(); } /** * Terminates the step by step- and automatic execution. */ public void terminate() { if (isTerminated()) { throw new IllegalStateException("trying to terminate a terminated execution"); } setState(S.Terminated); pushCount(0); engine = null; } /** * Executes a single reduction of the current lambda term. */ public void stepForward() { if (!isPaused()) { throw new IllegalStateException("trying to step while execution isn't paused"); } List<LambdaTerm> displayedTerms; try { displayedTerms = engine.stepForward(); } catch (ExecutionException e) { setState(S.Paused); pushError(e.getMessage()); controlObservers.forEach(ControlObserver::finish); return; } pushTerms(displayedTerms); if (!engine.isCurrentDisplayed()) { LambdaTerm current = engine.displayCurrent(); pushTerm(current); } pushEngineCount(); } /** * Executes a single reduction of the supplied redex. * * @param redex * The redex to be evaluated. Must be a redex, otherwise an exception * is thrown */ public void stepForward(Application redex) { if (!isPaused()) { throw new IllegalStateException("trying to step while execution isn't paused"); } List<LambdaTerm> displayedTerms; try { displayedTerms = engine.stepForward(redex); } catch (ExecutionException e) { setState(S.Paused); pushError(e.getMessage()); controlObservers.forEach(ControlObserver::finish); return; } pushTerms(displayedTerms); pushEngineCount(); } /** * Reverts to the previously output lambda term. */ public void stepBackward() { if (!isPaused()) { throw new IllegalStateException("trying to step while execution isn't paused"); } engine.stepBackward(); pushEngineCount(); executionObservers.forEach(o -> o.removeLastTerm()); } /** * Checks whether stepBackward is possible. * * @return whether stepBackward is possible */ public boolean canStepBackward() { return isPaused() && engine.canStepBackward(); } /** * Checks whether stepForward is possible. * * @return whether stepForward is possible */ public boolean canStepForward() { return isPaused() && !engine.isFinished(); } /** * Checks whether the engine is paused. * * @return whether the engine is paused */ public boolean isPaused() { return state.val == S.Paused; } /** * Checks whether the engine is terminated. * * @return whether the engine is terminated */ public boolean isTerminated() { return state.val == S.Terminated; } /** * Checks whether the engine is running. * * @return whether the engine is running */ public boolean isRunning() { return state.val == S.Running; } /** * Returns the currently displayed lambda terms. * * @return lt */ public List<LambdaTerm> getDisplayed() { if (isTerminated()) { throw new IllegalStateException("trying to read data of execution while executor is terminated"); } return engine.getDisplayed(); } /** * Returns the libraries in use by the engine. * * @return libraries */ public List<Library> getLibraries() { if (isTerminated()) { throw new IllegalStateException("trying to read data of execution while executor is terminated"); } return engine.getLibraries(); } /** * Serializes the Executor by serializing its ExecutionEngine. * * @return The Executor serialized String representation */ public StringBuilder serialize() { if (engine == null) { return new StringBuilder(""); } else { return engine.serialize(); } } /** * Deserializes the Executor by deserializing its ExecutionEngine. Also loads * the correct content into OutputArea. * * @param serialization * serialized Executor */ public void deserialize(String serialization) { if (serialization == "") { // engine was null return; } else { setState(S.Paused); this.engine = new ExecutionEngine(serialization); this.pushTerms(engine.getDisplayed()); } } /** * Changes the active reduction order to the entered one. * * @param reduction * The new reduction order */ public void setReductionOrder(ReductionOrder reduction) { if (isTerminated()) { throw new IllegalStateException("trying to set option while execution is terminated"); } engine.setReductionOrder(reduction); executionObservers.forEach(o -> o.reloadTerm()); } /** * Causes the last displayed term to be reloaded if a new output format was * selected. */ public void updatedOutputFormat() { if (isTerminated()) { throw new IllegalStateException("trying to set option while execution is terminated"); } executionObservers.forEach(o -> o.reloadTerm()); } /** * Changes the active output size to the entered one. * * @param s * The new output size */ public void setOutputSize(OutputSize s) { if (isTerminated()) { throw new IllegalStateException("trying to set option while execution is terminated"); } engine.setOutputSize(s); } }
[ "public", "class", "Executor", "implements", "Serializable", "{", "private", "enum", "S", "{", "Running", ",", "Paused", ",", "Terminated", "}", "private", "static", "class", "State", "{", "S", "val", ";", "State", "(", "S", "v", ")", "{", "this", ".", "val", "=", "v", ";", "}", "State", "(", "State", "s", ")", "{", "this", "(", "s", ".", "val", ")", ";", "}", "}", "private", "static", "int", "allowedReductionTimeMS", "=", "100", ";", "private", "List", "<", "ExecutionObserver", ">", "executionObservers", ";", "private", "List", "<", "ControlObserver", ">", "controlObservers", ";", "private", "List", "<", "ReductionStepCountObserver", ">", "reductionStepCountObserver", ";", "private", "State", "state", "=", "new", "State", "(", "S", ".", "Terminated", ")", ";", "private", "void", "setState", "(", "S", "v", ")", "{", "state", ".", "val", "=", "v", ";", "state", "=", "new", "State", "(", "state", ")", ";", "}", "private", "ExecutionEngine", "engine", ";", "/**\n\t * Creates a new Executor.\n\t * \n\t * @param executionObservers\n\t * Observers to update with reduced lambda terms\n\t * @param controlObservers\n\t * Observers to notify when executor reaches certain states\n\t */", "public", "Executor", "(", "List", "<", "ExecutionObserver", ">", "executionObservers", ",", "List", "<", "ControlObserver", ">", "controlObservers", ",", "List", "<", "ReductionStepCountObserver", ">", "reductionStepCountObserver", ")", "{", "this", ".", "executionObservers", "=", "executionObservers", ";", "this", ".", "controlObservers", "=", "controlObservers", ";", "this", ".", "reductionStepCountObserver", "=", "reductionStepCountObserver", ";", "}", "private", "void", "pushCount", "(", "int", "n", ")", "{", "reductionStepCountObserver", ".", "forEach", "(", "o", "->", "o", ".", "update", "(", "n", ")", ")", ";", "}", "private", "void", "pushEngineCount", "(", ")", "{", "pushCount", "(", "engine", ".", "getStepNumber", "(", ")", ")", ";", "}", "private", "void", "pushTerm", "(", "LambdaTerm", "t", ")", "{", "executionObservers", ".", "forEach", "(", "o", "->", "o", ".", "pushTerm", "(", "t", ")", ")", ";", "}", "private", "void", "pushTerms", "(", "Iterable", "<", "LambdaTerm", ">", "ts", ")", "{", "ts", ".", "forEach", "(", "this", "::", "pushTerm", ")", ";", "}", "private", "void", "pushError", "(", "String", "error", ")", "{", "executionObservers", ".", "forEach", "(", "o", "->", "o", ".", "pushError", "(", "error", ")", ")", ";", "}", "private", "void", "scheduleExecution", "(", ")", "{", "final", "State", "state", "=", "this", ".", "state", ";", "Scheduler", ".", "get", "(", ")", ".", "scheduleIncremental", "(", "(", ")", "->", "{", "Date", "start", "=", "new", "Date", "(", ")", ";", "switch", "(", "state", ".", "val", ")", "{", "case", "Terminated", ":", "return", "false", ";", "case", "Paused", ":", "return", "false", ";", "default", ":", "while", "(", "true", ")", "{", "if", "(", "engine", ".", "isFinished", "(", ")", ")", "{", "setState", "(", "S", ".", "Paused", ")", ";", "controlObservers", ".", "forEach", "(", "ControlObserver", "::", "finish", ")", ";", "return", "false", ";", "}", "List", "<", "LambdaTerm", ">", "displayedTerms", ";", "try", "{", "displayedTerms", "=", "engine", ".", "stepForward", "(", ")", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "setState", "(", "S", ".", "Paused", ")", ";", "pushError", "(", "e", ".", "getMessage", "(", ")", ")", ";", "controlObservers", ".", "forEach", "(", "ControlObserver", "::", "finish", ")", ";", "return", "false", ";", "}", "pushEngineCount", "(", ")", ";", "pushTerms", "(", "displayedTerms", ")", ";", "Date", "end", "=", "new", "Date", "(", ")", ";", "if", "(", "end", ".", "getTime", "(", ")", "-", "start", ".", "getTime", "(", ")", ">", "allowedReductionTimeMS", ")", "{", "return", "true", ";", "}", "}", "}", "}", ")", ";", "}", "/**\n\t * Starts the automatic execution of the input, parsing the term and then\n\t * reducing it.\n\t * \n\t * @param input\n\t * code to parse and reduce\n\t * @param order\n\t * order with which to reduce\n\t * @param size\n\t * which terms to push to observers\n\t * @param libraries\n\t * libraries to consider when parsing\n\t * @throws ParseException\n\t * thrown when input cannot be parsed\n\t */", "public", "void", "start", "(", "String", "input", ",", "ReductionOrder", "order", ",", "OutputSize", "size", ",", "List", "<", "Library", ">", "libraries", ")", "throws", "ParseException", "{", "if", "(", "!", "isTerminated", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "trying to start execution while execution is not terminated", "\"", ")", ";", "}", "executionObservers", ".", "forEach", "(", "o", "->", "o", ".", "clear", "(", ")", ")", ";", "engine", "=", "new", "ExecutionEngine", "(", "input", ",", "order", ",", "size", ",", "libraries", ")", ";", "setState", "(", "S", ".", "Running", ")", ";", "if", "(", "!", "engine", ".", "getDisplayed", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "pushTerm", "(", "engine", ".", "getDisplayed", "(", ")", ".", "get", "(", "0", ")", ")", ";", "}", "pushEngineCount", "(", ")", ";", "scheduleExecution", "(", ")", ";", "}", "/**\n\t * Initiates the step by step execution, allowing the caller to choose the next\n\t * step.\n\t * \n\t * @param input\n\t * code to parse and execute\n\t * @param order\n\t * order with which to reduce\n\t * @param size\n\t * which terms to push to observers\n\t * @param libraries\n\t * libraries to consider when parsing\n\t * @throws ParseException\n\t * thrown when input cannot be parsed\n\t */", "public", "void", "stepByStep", "(", "String", "input", ",", "ReductionOrder", "order", ",", "OutputSize", "size", ",", "List", "<", "Library", ">", "libraries", ")", "throws", "ParseException", "{", "if", "(", "!", "isTerminated", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "trying to start execution while execution is not terminated", "\"", ")", ";", "}", "executionObservers", ".", "forEach", "(", "o", "->", "o", ".", "clear", "(", ")", ")", ";", "engine", "=", "new", "ExecutionEngine", "(", "input", ",", "order", ",", "size", ",", "libraries", ")", ";", "setState", "(", "S", ".", "Paused", ")", ";", "if", "(", "!", "engine", ".", "getDisplayed", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "pushTerm", "(", "engine", ".", "getDisplayed", "(", ")", ".", "get", "(", "0", ")", ")", ";", "}", "pushEngineCount", "(", ")", ";", "}", "/**\n\t * Pauses the automatic execution, transitioning into the step by step mode.\n\t */", "public", "void", "pause", "(", ")", "{", "if", "(", "!", "isRunning", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "trying to pause execution that isn't running", "\"", ")", ";", "}", "setState", "(", "S", ".", "Paused", ")", ";", "if", "(", "!", "engine", ".", "isCurrentDisplayed", "(", ")", ")", "{", "LambdaTerm", "current", "=", "engine", ".", "displayCurrent", "(", ")", ";", "pushTerm", "(", "current", ")", ";", "}", "pushEngineCount", "(", ")", ";", "}", "/**\n\t * Unpauses the automatic execution, transitioning from step by step mode into\n\t * automatic execution.\n\t */", "public", "void", "unpause", "(", ")", "{", "if", "(", "!", "isPaused", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "trying to unpause execution that isn't paused", "\"", ")", ";", "}", "setState", "(", "S", ".", "Running", ")", ";", "scheduleExecution", "(", ")", ";", "}", "/**\n\t * Terminates the step by step- and automatic execution.\n\t */", "public", "void", "terminate", "(", ")", "{", "if", "(", "isTerminated", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "trying to terminate a terminated execution", "\"", ")", ";", "}", "setState", "(", "S", ".", "Terminated", ")", ";", "pushCount", "(", "0", ")", ";", "engine", "=", "null", ";", "}", "/**\n\t * Executes a single reduction of the current lambda term.\n\t */", "public", "void", "stepForward", "(", ")", "{", "if", "(", "!", "isPaused", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "trying to step while execution isn't paused", "\"", ")", ";", "}", "List", "<", "LambdaTerm", ">", "displayedTerms", ";", "try", "{", "displayedTerms", "=", "engine", ".", "stepForward", "(", ")", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "setState", "(", "S", ".", "Paused", ")", ";", "pushError", "(", "e", ".", "getMessage", "(", ")", ")", ";", "controlObservers", ".", "forEach", "(", "ControlObserver", "::", "finish", ")", ";", "return", ";", "}", "pushTerms", "(", "displayedTerms", ")", ";", "if", "(", "!", "engine", ".", "isCurrentDisplayed", "(", ")", ")", "{", "LambdaTerm", "current", "=", "engine", ".", "displayCurrent", "(", ")", ";", "pushTerm", "(", "current", ")", ";", "}", "pushEngineCount", "(", ")", ";", "}", "/**\n\t * Executes a single reduction of the supplied redex.\n\t * \n\t * @param redex\n\t * The redex to be evaluated. Must be a redex, otherwise an exception\n\t * is thrown\n\t */", "public", "void", "stepForward", "(", "Application", "redex", ")", "{", "if", "(", "!", "isPaused", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "trying to step while execution isn't paused", "\"", ")", ";", "}", "List", "<", "LambdaTerm", ">", "displayedTerms", ";", "try", "{", "displayedTerms", "=", "engine", ".", "stepForward", "(", "redex", ")", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "setState", "(", "S", ".", "Paused", ")", ";", "pushError", "(", "e", ".", "getMessage", "(", ")", ")", ";", "controlObservers", ".", "forEach", "(", "ControlObserver", "::", "finish", ")", ";", "return", ";", "}", "pushTerms", "(", "displayedTerms", ")", ";", "pushEngineCount", "(", ")", ";", "}", "/**\n\t * Reverts to the previously output lambda term.\n\t */", "public", "void", "stepBackward", "(", ")", "{", "if", "(", "!", "isPaused", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "trying to step while execution isn't paused", "\"", ")", ";", "}", "engine", ".", "stepBackward", "(", ")", ";", "pushEngineCount", "(", ")", ";", "executionObservers", ".", "forEach", "(", "o", "->", "o", ".", "removeLastTerm", "(", ")", ")", ";", "}", "/**\n\t * Checks whether stepBackward is possible.\n\t * \n\t * @return whether stepBackward is possible\n\t */", "public", "boolean", "canStepBackward", "(", ")", "{", "return", "isPaused", "(", ")", "&&", "engine", ".", "canStepBackward", "(", ")", ";", "}", "/**\n\t * Checks whether stepForward is possible.\n\t * \n\t * @return whether stepForward is possible\n\t */", "public", "boolean", "canStepForward", "(", ")", "{", "return", "isPaused", "(", ")", "&&", "!", "engine", ".", "isFinished", "(", ")", ";", "}", "/**\n\t * Checks whether the engine is paused.\n\t * \n\t * @return whether the engine is paused\n\t */", "public", "boolean", "isPaused", "(", ")", "{", "return", "state", ".", "val", "==", "S", ".", "Paused", ";", "}", "/**\n\t * Checks whether the engine is terminated.\n\t * \n\t * @return whether the engine is terminated\n\t */", "public", "boolean", "isTerminated", "(", ")", "{", "return", "state", ".", "val", "==", "S", ".", "Terminated", ";", "}", "/**\n\t * Checks whether the engine is running.\n\t * \n\t * @return whether the engine is running\n\t */", "public", "boolean", "isRunning", "(", ")", "{", "return", "state", ".", "val", "==", "S", ".", "Running", ";", "}", "/**\n\t * Returns the currently displayed lambda terms.\n\t * \n\t * @return lt\n\t */", "public", "List", "<", "LambdaTerm", ">", "getDisplayed", "(", ")", "{", "if", "(", "isTerminated", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "trying to read data of execution while executor is terminated", "\"", ")", ";", "}", "return", "engine", ".", "getDisplayed", "(", ")", ";", "}", "/**\n\t * Returns the libraries in use by the engine.\n\t * \n\t * @return libraries\n\t */", "public", "List", "<", "Library", ">", "getLibraries", "(", ")", "{", "if", "(", "isTerminated", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "trying to read data of execution while executor is terminated", "\"", ")", ";", "}", "return", "engine", ".", "getLibraries", "(", ")", ";", "}", "/**\n\t * Serializes the Executor by serializing its ExecutionEngine.\n\t * \n\t * @return The Executor serialized String representation\n\t */", "public", "StringBuilder", "serialize", "(", ")", "{", "if", "(", "engine", "==", "null", ")", "{", "return", "new", "StringBuilder", "(", "\"", "\"", ")", ";", "}", "else", "{", "return", "engine", ".", "serialize", "(", ")", ";", "}", "}", "/**\n\t * Deserializes the Executor by deserializing its ExecutionEngine. Also loads\n\t * the correct content into OutputArea.\n\t * \n\t * @param serialization\n\t * serialized Executor\n\t */", "public", "void", "deserialize", "(", "String", "serialization", ")", "{", "if", "(", "serialization", "==", "\"", "\"", ")", "{", "return", ";", "}", "else", "{", "setState", "(", "S", ".", "Paused", ")", ";", "this", ".", "engine", "=", "new", "ExecutionEngine", "(", "serialization", ")", ";", "this", ".", "pushTerms", "(", "engine", ".", "getDisplayed", "(", ")", ")", ";", "}", "}", "/**\n\t * Changes the active reduction order to the entered one.\n\t * \n\t * @param reduction\n\t * The new reduction order\n\t */", "public", "void", "setReductionOrder", "(", "ReductionOrder", "reduction", ")", "{", "if", "(", "isTerminated", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "trying to set option while execution is terminated", "\"", ")", ";", "}", "engine", ".", "setReductionOrder", "(", "reduction", ")", ";", "executionObservers", ".", "forEach", "(", "o", "->", "o", ".", "reloadTerm", "(", ")", ")", ";", "}", "/**\n\t * Causes the last displayed term to be reloaded if a new output format was\n\t * selected.\n\t */", "public", "void", "updatedOutputFormat", "(", ")", "{", "if", "(", "isTerminated", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "trying to set option while execution is terminated", "\"", ")", ";", "}", "executionObservers", ".", "forEach", "(", "o", "->", "o", ".", "reloadTerm", "(", ")", ")", ";", "}", "/**\n\t * Changes the active output size to the entered one.\n\t * \n\t * @param s\n\t * The new output size\n\t */", "public", "void", "setOutputSize", "(", "OutputSize", "s", ")", "{", "if", "(", "isTerminated", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "trying to set option while execution is terminated", "\"", ")", ";", "}", "engine", ".", "setOutputSize", "(", "s", ")", ";", "}", "}" ]
Concurrently reduces lambda terms.
[ "Concurrently", "reduces", "lambda", "terms", "." ]
[ "// engine was null" ]
[ { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
468de3c0d08c4dca268dd1606855d2b74e0227db
woniu1983/LibPdfStamper
src/cn/woniu/lib/pdf/model/PDFString.java
[ "Apache-2.0" ]
Java
PDFString
/** * @ClassName: PDFString <br/> * @Description <br/> * * A <CODE>PDFString</CODE>-class is the PDF-equivalent of a * JAVA-<CODE>String</CODE>-object. * <P> * A string object consists of a series of bytes * - unsigned integer values in the range of 0 to 255 * - delimited by parenthesis * * String objects are not integer objects, but are stored in a more compact format. * String objects can be written in two ways. * - Literal String: (helloworld) * - Hex String : <901FA3> * If a string is too long to be conveniently placed on a single line, it may * be split across multiple lines by using the backslash character (\) at the * end of a line to indicate that the string continues on the following line. * Within a string, the backslash character is used as an escape to specify * unbalanced parenthesis, non-printing ASCII characters, and the backslash * character itself. Use of the \<I>ddd</I> escape sequence is the preferred * way to represent characters outside the printable ASCII character set.<BR> * * @version * @since JDK 1.6 */
A PDFString-class is the PDF-equivalent of a JAVA-String-object. A string object consists of a series of bytes - unsigned integer values in the range of 0 to 255 - delimited by parenthesis String objects are not integer objects, but are stored in a more compact format. String objects can be written in two ways. - Literal String: (helloworld) - Hex String : <901FA3> If a string is too long to be conveniently placed on a single line, it may be split across multiple lines by using the backslash character (\) at the end of a line to indicate that the string continues on the following line. Within a string, the backslash character is used as an escape to specify unbalanced parenthesis, non-printing ASCII characters, and the backslash character itself. Use of the \ddd escape sequence is the preferred way to represent characters outside the printable ASCII character set.
[ "A", "PDFString", "-", "class", "is", "the", "PDF", "-", "equivalent", "of", "a", "JAVA", "-", "String", "-", "object", ".", "A", "string", "object", "consists", "of", "a", "series", "of", "bytes", "-", "unsigned", "integer", "values", "in", "the", "range", "of", "0", "to", "255", "-", "delimited", "by", "parenthesis", "String", "objects", "are", "not", "integer", "objects", "but", "are", "stored", "in", "a", "more", "compact", "format", ".", "String", "objects", "can", "be", "written", "in", "two", "ways", ".", "-", "Literal", "String", ":", "(", "helloworld", ")", "-", "Hex", "String", ":", "<901FA3", ">", "If", "a", "string", "is", "too", "long", "to", "be", "conveniently", "placed", "on", "a", "single", "line", "it", "may", "be", "split", "across", "multiple", "lines", "by", "using", "the", "backslash", "character", "(", "\\", ")", "at", "the", "end", "of", "a", "line", "to", "indicate", "that", "the", "string", "continues", "on", "the", "following", "line", ".", "Within", "a", "string", "the", "backslash", "character", "is", "used", "as", "an", "escape", "to", "specify", "unbalanced", "parenthesis", "non", "-", "printing", "ASCII", "characters", "and", "the", "backslash", "character", "itself", ".", "Use", "of", "the", "\\", "ddd", "escape", "sequence", "is", "the", "preferred", "way", "to", "represent", "characters", "outside", "the", "printable", "ASCII", "character", "set", "." ]
public class PDFString extends PDFObj { private static final long serialVersionUID = -7104936244693143451L; /** The value of this object. */ protected String value = NOTHING; protected String originalValue = null; protected String encoding = TEXT_PDFDOCENCODING; protected int objNum = 0; protected int objGen = 0; protected boolean hexWriting = false; /** * Constructs an empty <CODE>PDFString</CODE>-object. */ public PDFString() { super(STRING); } /** * Constructs a <CODE>PDFString</CODE>-object containing a string in the * standard encoding <CODE>TEXT_PDFDOCENCODING</CODE>. * * @param value the content of the string */ public PDFString(String value) { super(STRING); this.value = value; } /** * Constructs a <CODE>PDFString</CODE>-object containing a string in the * specified encoding. * * @param value the content of the string * @param encoding an encoding */ public PDFString(String value, String encoding) { super(STRING); this.value = value; this.encoding = encoding; } /** * Constructs a <CODE>PDFString</CODE>-object. * * @param bytes an array of <CODE>byte</CODE> */ public PDFString(byte[] bytes) { super(STRING); value = PdfEncodings.convertToString(bytes, null); encoding = NOTHING; } /** * Returns the <CODE>String</CODE> value of this <CODE>PdfString</CODE>-object. * * @return A <CODE>String</CODE> */ public String toString() { return value; } public byte[] getBytes() { if (bytes == null) { if (encoding != null && encoding.equals(TEXT_UNICODE) && PdfEncodings.isPdfDocEncoding(value)) bytes = PdfEncodings.convertToBytes(value, TEXT_PDFDOCENCODING); else bytes = PdfEncodings.convertToBytes(value, encoding); } return bytes; } // other methods /** * Returns the Unicode <CODE>String</CODE> value of this * <CODE>PdfString</CODE>-object. * * @return A <CODE>String</CODE> */ public String toUnicodeString() { if (encoding != null && encoding.length() != 0) return value; getBytes(); if (bytes.length >= 2 && bytes[0] == (byte)254 && bytes[1] == (byte)255) { return PdfEncodings.convertToString(bytes, PDFObj.TEXT_UNICODE); } else { return PdfEncodings.convertToString(bytes, PDFObj.TEXT_PDFDOCENCODING); } } /** * Gets the encoding of this string. * * @return a <CODE>String</CODE> */ public String getEncoding() { return encoding; } public void setObjNum(int objNum, int objGen) { this.objNum = objNum; this.objGen = objGen; } public byte[] getOriginalBytes() { if (originalValue == null) return getBytes(); return PdfEncodings.convertToBytes(originalValue, null); } public PDFString setHexWriting(boolean hexWriting) { this.hexWriting = hexWriting; return this; } public boolean isHexWriting() { return hexWriting; } /** * Writes the PDF representation of this <CODE>PdfString</CODE> as an array * of <CODE>byte</CODE> to the specified <CODE>OutputStream</CODE>. * * @param writer for backwards compatibility * @param os The <CODE>OutputStream</CODE> to write the bytes to. */ @Override public void write(OutputStream os) throws IOException { byte b[] = getBytes(); if (hexWriting) { ByteBuffer buf = new ByteBuffer(); buf.append('<'); int len = b.length; for (int k = 0; k < len; ++k) buf.appendHex(b[k]); buf.append('>'); os.write(buf.toByteArray()); } else { os.write(StringUtils.escapeString(b)); } } // /** // * Decrypt an encrypted <CODE>PdfString</CODE> // */ // void decrypt(PdfReader reader) { // PdfEncryption decrypt = reader.getDecrypt(); // if (decrypt != null) { // originalValue = value; // decrypt.setHashKey(objNum, objGen); // bytes = PdfEncodings.convertToBytes(value, null); // bytes = decrypt.decryptByteArray(bytes); // value = PdfEncodings.convertToString(bytes, null); // } // } }
[ "public", "class", "PDFString", "extends", "PDFObj", "{", "private", "static", "final", "long", "serialVersionUID", "=", "-", "7104936244693143451L", ";", "/** The value of this object. */", "protected", "String", "value", "=", "NOTHING", ";", "protected", "String", "originalValue", "=", "null", ";", "protected", "String", "encoding", "=", "TEXT_PDFDOCENCODING", ";", "protected", "int", "objNum", "=", "0", ";", "protected", "int", "objGen", "=", "0", ";", "protected", "boolean", "hexWriting", "=", "false", ";", "/**\n * Constructs an empty <CODE>PDFString</CODE>-object.\n */", "public", "PDFString", "(", ")", "{", "super", "(", "STRING", ")", ";", "}", "/**\n * Constructs a <CODE>PDFString</CODE>-object containing a string in the\n * standard encoding <CODE>TEXT_PDFDOCENCODING</CODE>.\n *\n * @param value the content of the string\n */", "public", "PDFString", "(", "String", "value", ")", "{", "super", "(", "STRING", ")", ";", "this", ".", "value", "=", "value", ";", "}", "/**\n * Constructs a <CODE>PDFString</CODE>-object containing a string in the\n * specified encoding.\n *\n * @param value the content of the string\n * @param encoding an encoding\n */", "public", "PDFString", "(", "String", "value", ",", "String", "encoding", ")", "{", "super", "(", "STRING", ")", ";", "this", ".", "value", "=", "value", ";", "this", ".", "encoding", "=", "encoding", ";", "}", "/**\n * Constructs a <CODE>PDFString</CODE>-object.\n *\n * @param bytes an array of <CODE>byte</CODE>\n */", "public", "PDFString", "(", "byte", "[", "]", "bytes", ")", "{", "super", "(", "STRING", ")", ";", "value", "=", "PdfEncodings", ".", "convertToString", "(", "bytes", ",", "null", ")", ";", "encoding", "=", "NOTHING", ";", "}", "/**\n * Returns the <CODE>String</CODE> value of this <CODE>PdfString</CODE>-object.\n *\n * @return A <CODE>String</CODE>\n */", "public", "String", "toString", "(", ")", "{", "return", "value", ";", "}", "public", "byte", "[", "]", "getBytes", "(", ")", "{", "if", "(", "bytes", "==", "null", ")", "{", "if", "(", "encoding", "!=", "null", "&&", "encoding", ".", "equals", "(", "TEXT_UNICODE", ")", "&&", "PdfEncodings", ".", "isPdfDocEncoding", "(", "value", ")", ")", "bytes", "=", "PdfEncodings", ".", "convertToBytes", "(", "value", ",", "TEXT_PDFDOCENCODING", ")", ";", "else", "bytes", "=", "PdfEncodings", ".", "convertToBytes", "(", "value", ",", "encoding", ")", ";", "}", "return", "bytes", ";", "}", "/**\n * Returns the Unicode <CODE>String</CODE> value of this\n * <CODE>PdfString</CODE>-object.\n *\n * @return A <CODE>String</CODE>\n */", "public", "String", "toUnicodeString", "(", ")", "{", "if", "(", "encoding", "!=", "null", "&&", "encoding", ".", "length", "(", ")", "!=", "0", ")", "return", "value", ";", "getBytes", "(", ")", ";", "if", "(", "bytes", ".", "length", ">=", "2", "&&", "bytes", "[", "0", "]", "==", "(", "byte", ")", "254", "&&", "bytes", "[", "1", "]", "==", "(", "byte", ")", "255", ")", "{", "return", "PdfEncodings", ".", "convertToString", "(", "bytes", ",", "PDFObj", ".", "TEXT_UNICODE", ")", ";", "}", "else", "{", "return", "PdfEncodings", ".", "convertToString", "(", "bytes", ",", "PDFObj", ".", "TEXT_PDFDOCENCODING", ")", ";", "}", "}", "/**\n * Gets the encoding of this string.\n *\n * @return a <CODE>String</CODE>\n */", "public", "String", "getEncoding", "(", ")", "{", "return", "encoding", ";", "}", "public", "void", "setObjNum", "(", "int", "objNum", ",", "int", "objGen", ")", "{", "this", ".", "objNum", "=", "objNum", ";", "this", ".", "objGen", "=", "objGen", ";", "}", "public", "byte", "[", "]", "getOriginalBytes", "(", ")", "{", "if", "(", "originalValue", "==", "null", ")", "return", "getBytes", "(", ")", ";", "return", "PdfEncodings", ".", "convertToBytes", "(", "originalValue", ",", "null", ")", ";", "}", "public", "PDFString", "setHexWriting", "(", "boolean", "hexWriting", ")", "{", "this", ".", "hexWriting", "=", "hexWriting", ";", "return", "this", ";", "}", "public", "boolean", "isHexWriting", "(", ")", "{", "return", "hexWriting", ";", "}", "/**\n * Writes the PDF representation of this <CODE>PdfString</CODE> as an array\n * of <CODE>byte</CODE> to the specified <CODE>OutputStream</CODE>.\n * \n * @param writer for backwards compatibility\n * @param os The <CODE>OutputStream</CODE> to write the bytes to.\n */", "@", "Override", "public", "void", "write", "(", "OutputStream", "os", ")", "throws", "IOException", "{", "byte", "b", "[", "]", "=", "getBytes", "(", ")", ";", "if", "(", "hexWriting", ")", "{", "ByteBuffer", "buf", "=", "new", "ByteBuffer", "(", ")", ";", "buf", ".", "append", "(", "'<'", ")", ";", "int", "len", "=", "b", ".", "length", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "len", ";", "++", "k", ")", "buf", ".", "appendHex", "(", "b", "[", "k", "]", ")", ";", "buf", ".", "append", "(", "'>'", ")", ";", "os", ".", "write", "(", "buf", ".", "toByteArray", "(", ")", ")", ";", "}", "else", "{", "os", ".", "write", "(", "StringUtils", ".", "escapeString", "(", "b", ")", ")", ";", "}", "}", "}" ]
@ClassName: PDFString <br/> @Description <br/>
[ "@ClassName", ":", "PDFString", "<br", "/", ">", "@Description", "<br", "/", ">" ]
[ "// other methods", "// /**", "// * Decrypt an encrypted <CODE>PdfString</CODE>", "// */", "// void decrypt(PdfReader reader) {", "// PdfEncryption decrypt = reader.getDecrypt();", "// if (decrypt != null) {", "// originalValue = value;", "// decrypt.setHashKey(objNum, objGen);", "// bytes = PdfEncodings.convertToBytes(value, null);", "// bytes = decrypt.decryptByteArray(bytes);", "// value = PdfEncodings.convertToString(bytes, null);", "// }", "// }" ]
[ { "param": "PDFObj", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PDFObj", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
469136c492ee4c8114ebdfb0268c2c8f6a0a266a
jianghancn/data-prepper
data-prepper-core/src/main/java/com/amazon/dataprepper/pipeline/server/CloudWatchMeterRegistryProvider.java
[ "Apache-2.0" ]
Java
CloudWatchMeterRegistryProvider
/** * Provides {@link CloudWatchMeterRegistry} that enables publishing metrics to AWS Cloudwatch. Registry * uses the default aws credentials (i.e. credentials from .aws directory; * refer https://docs.aws.amazon.com/sdk-for-java/v2/developer-guide/credentials.html#credentials-file-format). * {@link CloudWatchMeterRegistryProvider} also has a constructor with {@link CloudWatchAsyncClient} that will be used * for communication with Cloudwatch. */
Provides CloudWatchMeterRegistry that enables publishing metrics to AWS Cloudwatch. Registry uses the default aws credentials . CloudWatchMeterRegistryProvider also has a constructor with CloudWatchAsyncClient that will be used for communication with Cloudwatch.
[ "Provides", "CloudWatchMeterRegistry", "that", "enables", "publishing", "metrics", "to", "AWS", "Cloudwatch", ".", "Registry", "uses", "the", "default", "aws", "credentials", ".", "CloudWatchMeterRegistryProvider", "also", "has", "a", "constructor", "with", "CloudWatchAsyncClient", "that", "will", "be", "used", "for", "communication", "with", "Cloudwatch", "." ]
public class CloudWatchMeterRegistryProvider { private static final String CLOUDWATCH_PROPERTIES = "cloudwatch.properties"; private static final Logger LOG = LoggerFactory.getLogger(CloudWatchMeterRegistryProvider.class); private final CloudWatchMeterRegistry cloudWatchMeterRegistry; public CloudWatchMeterRegistryProvider() { this(CLOUDWATCH_PROPERTIES, CloudWatchAsyncClient.create()); } public CloudWatchMeterRegistryProvider( final String cloudWatchPropertiesFilePath, final CloudWatchAsyncClient cloudWatchAsyncClient) { final CloudWatchConfig cloudWatchConfig = createCloudWatchConfig( requireNonNull(cloudWatchPropertiesFilePath, "cloudWatchPropertiesFilePath must not be null")); this.cloudWatchMeterRegistry = new CloudWatchMeterRegistry(cloudWatchConfig, Clock.SYSTEM, requireNonNull(cloudWatchAsyncClient, "cloudWatchAsyncClient must not be null")); } /** * Returns the CloudWatchMeterRegistry created using the default aws credentials */ public CloudWatchMeterRegistry getCloudWatchMeterRegistry() { return this.cloudWatchMeterRegistry; } /** * Returns CloudWatchConfig using the properties from {@link #CLOUDWATCH_PROPERTIES} */ private CloudWatchConfig createCloudWatchConfig(final String cloudWatchPropertiesFilePath) { CloudWatchConfig cloudWatchConfig = null; try (final InputStream inputStream = requireNonNull(getClass().getClassLoader() .getResourceAsStream(cloudWatchPropertiesFilePath))) { final Properties cloudwatchProperties = new Properties(); cloudwatchProperties.load(inputStream); cloudWatchConfig = new CloudWatchConfig() { @Override public String get(final String key) { return cloudwatchProperties.getProperty(key); } }; } catch (IOException ex) { LOG.error("Encountered exception in creating CloudWatchConfig for CloudWatchMeterRegistry, " + "Proceeding without metrics", ex); //If there is no registry attached, micrometer will make NoopMeters which are discarded. } return cloudWatchConfig; } }
[ "public", "class", "CloudWatchMeterRegistryProvider", "{", "private", "static", "final", "String", "CLOUDWATCH_PROPERTIES", "=", "\"", "cloudwatch.properties", "\"", ";", "private", "static", "final", "Logger", "LOG", "=", "LoggerFactory", ".", "getLogger", "(", "CloudWatchMeterRegistryProvider", ".", "class", ")", ";", "private", "final", "CloudWatchMeterRegistry", "cloudWatchMeterRegistry", ";", "public", "CloudWatchMeterRegistryProvider", "(", ")", "{", "this", "(", "CLOUDWATCH_PROPERTIES", ",", "CloudWatchAsyncClient", ".", "create", "(", ")", ")", ";", "}", "public", "CloudWatchMeterRegistryProvider", "(", "final", "String", "cloudWatchPropertiesFilePath", ",", "final", "CloudWatchAsyncClient", "cloudWatchAsyncClient", ")", "{", "final", "CloudWatchConfig", "cloudWatchConfig", "=", "createCloudWatchConfig", "(", "requireNonNull", "(", "cloudWatchPropertiesFilePath", ",", "\"", "cloudWatchPropertiesFilePath must not be null", "\"", ")", ")", ";", "this", ".", "cloudWatchMeterRegistry", "=", "new", "CloudWatchMeterRegistry", "(", "cloudWatchConfig", ",", "Clock", ".", "SYSTEM", ",", "requireNonNull", "(", "cloudWatchAsyncClient", ",", "\"", "cloudWatchAsyncClient must not be null", "\"", ")", ")", ";", "}", "/**\n * Returns the CloudWatchMeterRegistry created using the default aws credentials\n */", "public", "CloudWatchMeterRegistry", "getCloudWatchMeterRegistry", "(", ")", "{", "return", "this", ".", "cloudWatchMeterRegistry", ";", "}", "/**\n * Returns CloudWatchConfig using the properties from {@link #CLOUDWATCH_PROPERTIES}\n */", "private", "CloudWatchConfig", "createCloudWatchConfig", "(", "final", "String", "cloudWatchPropertiesFilePath", ")", "{", "CloudWatchConfig", "cloudWatchConfig", "=", "null", ";", "try", "(", "final", "InputStream", "inputStream", "=", "requireNonNull", "(", "getClass", "(", ")", ".", "getClassLoader", "(", ")", ".", "getResourceAsStream", "(", "cloudWatchPropertiesFilePath", ")", ")", ")", "{", "final", "Properties", "cloudwatchProperties", "=", "new", "Properties", "(", ")", ";", "cloudwatchProperties", ".", "load", "(", "inputStream", ")", ";", "cloudWatchConfig", "=", "new", "CloudWatchConfig", "(", ")", "{", "@", "Override", "public", "String", "get", "(", "final", "String", "key", ")", "{", "return", "cloudwatchProperties", ".", "getProperty", "(", "key", ")", ";", "}", "}", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "LOG", ".", "error", "(", "\"", "Encountered exception in creating CloudWatchConfig for CloudWatchMeterRegistry, ", "\"", "+", "\"", "Proceeding without metrics", "\"", ",", "ex", ")", ";", "}", "return", "cloudWatchConfig", ";", "}", "}" ]
Provides {@link CloudWatchMeterRegistry} that enables publishing metrics to AWS Cloudwatch.
[ "Provides", "{", "@link", "CloudWatchMeterRegistry", "}", "that", "enables", "publishing", "metrics", "to", "AWS", "Cloudwatch", "." ]
[ "//If there is no registry attached, micrometer will make NoopMeters which are discarded." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
4692196ff3f51b9976cd94a7235c560fdaf7a372
cquoss/jboss-4.2.3.GA-jdk8
tomcat/src/main/org/jboss/web/tomcat/security/HttpServletRequestValve.java
[ "Apache-2.0" ]
Java
HttpServletRequestValve
/** * A Tomcat Valve that obtains the client's HttpServletRequest and saves it in a * ThreadLocal variable. It allows the WebCallbackHandler to populate the * HttpServletRequestCallback. * * @author Ricardo Arguello ([email protected]) * @version $Revision: 57206 $ */
A Tomcat Valve that obtains the client's HttpServletRequest and saves it in a ThreadLocal variable. It allows the WebCallbackHandler to populate the HttpServletRequestCallback. @author Ricardo Arguello ([email protected]) @version $Revision: 57206 $
[ "A", "Tomcat", "Valve", "that", "obtains", "the", "client", "'", "s", "HttpServletRequest", "and", "saves", "it", "in", "a", "ThreadLocal", "variable", ".", "It", "allows", "the", "WebCallbackHandler", "to", "populate", "the", "HttpServletRequestCallback", ".", "@author", "Ricardo", "Arguello", "(", "ricardoarguello@users", ".", "sourceforge", ".", "net", ")", "@version", "$Revision", ":", "57206", "$" ]
public class HttpServletRequestValve extends ValveBase { /** ThreadLocal to save the HttpServletRequest. */ public static ThreadLocal httpRequest = new ThreadLocal(); /** * Default constructor. */ public HttpServletRequestValve() { } /** * @see org.apache.catalina.Valve#invoke(org.apache.catalina.connector.Request, * org.apache.catalina.connector.Response) */ public void invoke(Request request, Response response) throws IOException, ServletException { try { // Set the ThreadLocal httpRequest.set(request.getRequest()); // Perform the request getNext().invoke(request, response); } finally { // Unset the ThreadLocal httpRequest.set(null); } } }
[ "public", "class", "HttpServletRequestValve", "extends", "ValveBase", "{", "/** ThreadLocal to save the HttpServletRequest. */", "public", "static", "ThreadLocal", "httpRequest", "=", "new", "ThreadLocal", "(", ")", ";", "/**\n * Default constructor.\n */", "public", "HttpServletRequestValve", "(", ")", "{", "}", "/**\n * @see org.apache.catalina.Valve#invoke(org.apache.catalina.connector.Request,\n * org.apache.catalina.connector.Response)\n */", "public", "void", "invoke", "(", "Request", "request", ",", "Response", "response", ")", "throws", "IOException", ",", "ServletException", "{", "try", "{", "httpRequest", ".", "set", "(", "request", ".", "getRequest", "(", ")", ")", ";", "getNext", "(", ")", ".", "invoke", "(", "request", ",", "response", ")", ";", "}", "finally", "{", "httpRequest", ".", "set", "(", "null", ")", ";", "}", "}", "}" ]
A Tomcat Valve that obtains the client's HttpServletRequest and saves it in a ThreadLocal variable.
[ "A", "Tomcat", "Valve", "that", "obtains", "the", "client", "'", "s", "HttpServletRequest", "and", "saves", "it", "in", "a", "ThreadLocal", "variable", "." ]
[ "// Set the ThreadLocal", "// Perform the request", "// Unset the ThreadLocal" ]
[ { "param": "ValveBase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ValveBase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
46941999c0a425b3d99ee1bb5e498844abd2a9e8
isabella232/YetAnotherChatApp
android/solution/app/src/main/java/com/example/yetanotherchatapp/MainActivity.java
[ "Apache-2.0" ]
Java
ViewHolder
/** * Represents a view of each data item in our list. */
Represents a view of each data item in our list.
[ "Represents", "a", "view", "of", "each", "data", "item", "in", "our", "list", "." ]
static class ViewHolder extends RecyclerView.ViewHolder { private final TextView listItemTextView; ViewHolder(ViewGroup layout) { super(layout); listItemTextView = layout.findViewById(R.id.list_item_text_view); } void setTextContents(String text) { listItemTextView.setText(text); } }
[ "static", "class", "ViewHolder", "extends", "RecyclerView", ".", "ViewHolder", "{", "private", "final", "TextView", "listItemTextView", ";", "ViewHolder", "(", "ViewGroup", "layout", ")", "{", "super", "(", "layout", ")", ";", "listItemTextView", "=", "layout", ".", "findViewById", "(", "R", ".", "id", ".", "list_item_text_view", ")", ";", "}", "void", "setTextContents", "(", "String", "text", ")", "{", "listItemTextView", ".", "setText", "(", "text", ")", ";", "}", "}" ]
Represents a view of each data item in our list.
[ "Represents", "a", "view", "of", "each", "data", "item", "in", "our", "list", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
4695963a6e39209d84469a920e38dd5ccef76851
yoshi-code-bot/google-api-java-client-services
clients/google-api-services-civicinfo/v2/1.31.0/com/google/api/services/civicinfo/v2/model/Precinct.java
[ "Apache-2.0" ]
Java
Precinct
/** * Model definition for Precinct. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Google Civic Information API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */
Model definition for Precinct. This is the Java data model class that specifies how to parse/serialize into the JSON that is transmitted over HTTP when working with the Google Civic Information API. @author Google, Inc.
[ "Model", "definition", "for", "Precinct", ".", "This", "is", "the", "Java", "data", "model", "class", "that", "specifies", "how", "to", "parse", "/", "serialize", "into", "the", "JSON", "that", "is", "transmitted", "over", "HTTP", "when", "working", "with", "the", "Google", "Civic", "Information", "API", ".", "@author", "Google", "Inc", "." ]
@SuppressWarnings("javadoc") public final class Precinct extends com.google.api.client.json.GenericJson { /** * ID of the AdministrationRegion message for this precinct. Corresponds to LocalityId xml tag. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String administrationRegionId; /** * ID(s) of the Contest message(s) for this precinct. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> contestId; /** * Required. Dataset ID. What datasets our Precincts come from. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long datasetId; /** * ID(s) of the PollingLocation message(s) for this precinct. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> earlyVoteSiteId; /** * ID(s) of the ElectoralDistrict message(s) for this precinct. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> electoralDistrictId; /** * Required. A unique identifier for this precinct. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String id; /** * Specifies if the precinct runs mail-only elections. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean mailOnly; /** * Required. The name of the precinct. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * The number of the precinct. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String number; /** * Encouraged. The OCD ID of the precinct * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> ocdId; /** * ID(s) of the PollingLocation message(s) for this precinct. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> pollingLocationId; /** * ID(s) of the SpatialBoundary message(s) for this precinct. Used to specify a geometrical * boundary of the precinct. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> spatialBoundaryId; /** * If present, this proto corresponds to one portion of split precinct. Other portions of this * precinct are guaranteed to have the same `name`. If not present, this proto represents a full * precicnt. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String splitName; /** * Specifies the ward the precinct is contained within. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String ward; /** * ID of the AdministrationRegion message for this precinct. Corresponds to LocalityId xml tag. * @return value or {@code null} for none */ public java.lang.String getAdministrationRegionId() { return administrationRegionId; } /** * ID of the AdministrationRegion message for this precinct. Corresponds to LocalityId xml tag. * @param administrationRegionId administrationRegionId or {@code null} for none */ public Precinct setAdministrationRegionId(java.lang.String administrationRegionId) { this.administrationRegionId = administrationRegionId; return this; } /** * ID(s) of the Contest message(s) for this precinct. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getContestId() { return contestId; } /** * ID(s) of the Contest message(s) for this precinct. * @param contestId contestId or {@code null} for none */ public Precinct setContestId(java.util.List<java.lang.String> contestId) { this.contestId = contestId; return this; } /** * Required. Dataset ID. What datasets our Precincts come from. * @return value or {@code null} for none */ public java.lang.Long getDatasetId() { return datasetId; } /** * Required. Dataset ID. What datasets our Precincts come from. * @param datasetId datasetId or {@code null} for none */ public Precinct setDatasetId(java.lang.Long datasetId) { this.datasetId = datasetId; return this; } /** * ID(s) of the PollingLocation message(s) for this precinct. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getEarlyVoteSiteId() { return earlyVoteSiteId; } /** * ID(s) of the PollingLocation message(s) for this precinct. * @param earlyVoteSiteId earlyVoteSiteId or {@code null} for none */ public Precinct setEarlyVoteSiteId(java.util.List<java.lang.String> earlyVoteSiteId) { this.earlyVoteSiteId = earlyVoteSiteId; return this; } /** * ID(s) of the ElectoralDistrict message(s) for this precinct. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getElectoralDistrictId() { return electoralDistrictId; } /** * ID(s) of the ElectoralDistrict message(s) for this precinct. * @param electoralDistrictId electoralDistrictId or {@code null} for none */ public Precinct setElectoralDistrictId(java.util.List<java.lang.String> electoralDistrictId) { this.electoralDistrictId = electoralDistrictId; return this; } /** * Required. A unique identifier for this precinct. * @return value or {@code null} for none */ public java.lang.String getId() { return id; } /** * Required. A unique identifier for this precinct. * @param id id or {@code null} for none */ public Precinct setId(java.lang.String id) { this.id = id; return this; } /** * Specifies if the precinct runs mail-only elections. * @return value or {@code null} for none */ public java.lang.Boolean getMailOnly() { return mailOnly; } /** * Specifies if the precinct runs mail-only elections. * @param mailOnly mailOnly or {@code null} for none */ public Precinct setMailOnly(java.lang.Boolean mailOnly) { this.mailOnly = mailOnly; return this; } /** * Required. The name of the precinct. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Required. The name of the precinct. * @param name name or {@code null} for none */ public Precinct setName(java.lang.String name) { this.name = name; return this; } /** * The number of the precinct. * @return value or {@code null} for none */ public java.lang.String getNumber() { return number; } /** * The number of the precinct. * @param number number or {@code null} for none */ public Precinct setNumber(java.lang.String number) { this.number = number; return this; } /** * Encouraged. The OCD ID of the precinct * @return value or {@code null} for none */ public java.util.List<java.lang.String> getOcdId() { return ocdId; } /** * Encouraged. The OCD ID of the precinct * @param ocdId ocdId or {@code null} for none */ public Precinct setOcdId(java.util.List<java.lang.String> ocdId) { this.ocdId = ocdId; return this; } /** * ID(s) of the PollingLocation message(s) for this precinct. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPollingLocationId() { return pollingLocationId; } /** * ID(s) of the PollingLocation message(s) for this precinct. * @param pollingLocationId pollingLocationId or {@code null} for none */ public Precinct setPollingLocationId(java.util.List<java.lang.String> pollingLocationId) { this.pollingLocationId = pollingLocationId; return this; } /** * ID(s) of the SpatialBoundary message(s) for this precinct. Used to specify a geometrical * boundary of the precinct. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getSpatialBoundaryId() { return spatialBoundaryId; } /** * ID(s) of the SpatialBoundary message(s) for this precinct. Used to specify a geometrical * boundary of the precinct. * @param spatialBoundaryId spatialBoundaryId or {@code null} for none */ public Precinct setSpatialBoundaryId(java.util.List<java.lang.String> spatialBoundaryId) { this.spatialBoundaryId = spatialBoundaryId; return this; } /** * If present, this proto corresponds to one portion of split precinct. Other portions of this * precinct are guaranteed to have the same `name`. If not present, this proto represents a full * precicnt. * @return value or {@code null} for none */ public java.lang.String getSplitName() { return splitName; } /** * If present, this proto corresponds to one portion of split precinct. Other portions of this * precinct are guaranteed to have the same `name`. If not present, this proto represents a full * precicnt. * @param splitName splitName or {@code null} for none */ public Precinct setSplitName(java.lang.String splitName) { this.splitName = splitName; return this; } /** * Specifies the ward the precinct is contained within. * @return value or {@code null} for none */ public java.lang.String getWard() { return ward; } /** * Specifies the ward the precinct is contained within. * @param ward ward or {@code null} for none */ public Precinct setWard(java.lang.String ward) { this.ward = ward; return this; } @Override public Precinct set(String fieldName, Object value) { return (Precinct) super.set(fieldName, value); } @Override public Precinct clone() { return (Precinct) super.clone(); } }
[ "@", "SuppressWarnings", "(", "\"", "javadoc", "\"", ")", "public", "final", "class", "Precinct", "extends", "com", ".", "google", ".", "api", ".", "client", ".", "json", ".", "GenericJson", "{", "/**\n * ID of the AdministrationRegion message for this precinct. Corresponds to LocalityId xml tag.\n * The value may be {@code null}.\n */", "@", "com", ".", "google", ".", "api", ".", "client", ".", "util", ".", "Key", "private", "java", ".", "lang", ".", "String", "administrationRegionId", ";", "/**\n * ID(s) of the Contest message(s) for this precinct.\n * The value may be {@code null}.\n */", "@", "com", ".", "google", ".", "api", ".", "client", ".", "util", ".", "Key", "private", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "contestId", ";", "/**\n * Required. Dataset ID. What datasets our Precincts come from.\n * The value may be {@code null}.\n */", "@", "com", ".", "google", ".", "api", ".", "client", ".", "util", ".", "Key", "@", "com", ".", "google", ".", "api", ".", "client", ".", "json", ".", "JsonString", "private", "java", ".", "lang", ".", "Long", "datasetId", ";", "/**\n * ID(s) of the PollingLocation message(s) for this precinct.\n * The value may be {@code null}.\n */", "@", "com", ".", "google", ".", "api", ".", "client", ".", "util", ".", "Key", "private", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "earlyVoteSiteId", ";", "/**\n * ID(s) of the ElectoralDistrict message(s) for this precinct.\n * The value may be {@code null}.\n */", "@", "com", ".", "google", ".", "api", ".", "client", ".", "util", ".", "Key", "private", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "electoralDistrictId", ";", "/**\n * Required. A unique identifier for this precinct.\n * The value may be {@code null}.\n */", "@", "com", ".", "google", ".", "api", ".", "client", ".", "util", ".", "Key", "private", "java", ".", "lang", ".", "String", "id", ";", "/**\n * Specifies if the precinct runs mail-only elections.\n * The value may be {@code null}.\n */", "@", "com", ".", "google", ".", "api", ".", "client", ".", "util", ".", "Key", "private", "java", ".", "lang", ".", "Boolean", "mailOnly", ";", "/**\n * Required. The name of the precinct.\n * The value may be {@code null}.\n */", "@", "com", ".", "google", ".", "api", ".", "client", ".", "util", ".", "Key", "private", "java", ".", "lang", ".", "String", "name", ";", "/**\n * The number of the precinct.\n * The value may be {@code null}.\n */", "@", "com", ".", "google", ".", "api", ".", "client", ".", "util", ".", "Key", "private", "java", ".", "lang", ".", "String", "number", ";", "/**\n * Encouraged. The OCD ID of the precinct\n * The value may be {@code null}.\n */", "@", "com", ".", "google", ".", "api", ".", "client", ".", "util", ".", "Key", "private", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "ocdId", ";", "/**\n * ID(s) of the PollingLocation message(s) for this precinct.\n * The value may be {@code null}.\n */", "@", "com", ".", "google", ".", "api", ".", "client", ".", "util", ".", "Key", "private", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "pollingLocationId", ";", "/**\n * ID(s) of the SpatialBoundary message(s) for this precinct. Used to specify a geometrical\n * boundary of the precinct.\n * The value may be {@code null}.\n */", "@", "com", ".", "google", ".", "api", ".", "client", ".", "util", ".", "Key", "private", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "spatialBoundaryId", ";", "/**\n * If present, this proto corresponds to one portion of split precinct. Other portions of this\n * precinct are guaranteed to have the same `name`. If not present, this proto represents a full\n * precicnt.\n * The value may be {@code null}.\n */", "@", "com", ".", "google", ".", "api", ".", "client", ".", "util", ".", "Key", "private", "java", ".", "lang", ".", "String", "splitName", ";", "/**\n * Specifies the ward the precinct is contained within.\n * The value may be {@code null}.\n */", "@", "com", ".", "google", ".", "api", ".", "client", ".", "util", ".", "Key", "private", "java", ".", "lang", ".", "String", "ward", ";", "/**\n * ID of the AdministrationRegion message for this precinct. Corresponds to LocalityId xml tag.\n * @return value or {@code null} for none\n */", "public", "java", ".", "lang", ".", "String", "getAdministrationRegionId", "(", ")", "{", "return", "administrationRegionId", ";", "}", "/**\n * ID of the AdministrationRegion message for this precinct. Corresponds to LocalityId xml tag.\n * @param administrationRegionId administrationRegionId or {@code null} for none\n */", "public", "Precinct", "setAdministrationRegionId", "(", "java", ".", "lang", ".", "String", "administrationRegionId", ")", "{", "this", ".", "administrationRegionId", "=", "administrationRegionId", ";", "return", "this", ";", "}", "/**\n * ID(s) of the Contest message(s) for this precinct.\n * @return value or {@code null} for none\n */", "public", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "getContestId", "(", ")", "{", "return", "contestId", ";", "}", "/**\n * ID(s) of the Contest message(s) for this precinct.\n * @param contestId contestId or {@code null} for none\n */", "public", "Precinct", "setContestId", "(", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "contestId", ")", "{", "this", ".", "contestId", "=", "contestId", ";", "return", "this", ";", "}", "/**\n * Required. Dataset ID. What datasets our Precincts come from.\n * @return value or {@code null} for none\n */", "public", "java", ".", "lang", ".", "Long", "getDatasetId", "(", ")", "{", "return", "datasetId", ";", "}", "/**\n * Required. Dataset ID. What datasets our Precincts come from.\n * @param datasetId datasetId or {@code null} for none\n */", "public", "Precinct", "setDatasetId", "(", "java", ".", "lang", ".", "Long", "datasetId", ")", "{", "this", ".", "datasetId", "=", "datasetId", ";", "return", "this", ";", "}", "/**\n * ID(s) of the PollingLocation message(s) for this precinct.\n * @return value or {@code null} for none\n */", "public", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "getEarlyVoteSiteId", "(", ")", "{", "return", "earlyVoteSiteId", ";", "}", "/**\n * ID(s) of the PollingLocation message(s) for this precinct.\n * @param earlyVoteSiteId earlyVoteSiteId or {@code null} for none\n */", "public", "Precinct", "setEarlyVoteSiteId", "(", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "earlyVoteSiteId", ")", "{", "this", ".", "earlyVoteSiteId", "=", "earlyVoteSiteId", ";", "return", "this", ";", "}", "/**\n * ID(s) of the ElectoralDistrict message(s) for this precinct.\n * @return value or {@code null} for none\n */", "public", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "getElectoralDistrictId", "(", ")", "{", "return", "electoralDistrictId", ";", "}", "/**\n * ID(s) of the ElectoralDistrict message(s) for this precinct.\n * @param electoralDistrictId electoralDistrictId or {@code null} for none\n */", "public", "Precinct", "setElectoralDistrictId", "(", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "electoralDistrictId", ")", "{", "this", ".", "electoralDistrictId", "=", "electoralDistrictId", ";", "return", "this", ";", "}", "/**\n * Required. A unique identifier for this precinct.\n * @return value or {@code null} for none\n */", "public", "java", ".", "lang", ".", "String", "getId", "(", ")", "{", "return", "id", ";", "}", "/**\n * Required. A unique identifier for this precinct.\n * @param id id or {@code null} for none\n */", "public", "Precinct", "setId", "(", "java", ".", "lang", ".", "String", "id", ")", "{", "this", ".", "id", "=", "id", ";", "return", "this", ";", "}", "/**\n * Specifies if the precinct runs mail-only elections.\n * @return value or {@code null} for none\n */", "public", "java", ".", "lang", ".", "Boolean", "getMailOnly", "(", ")", "{", "return", "mailOnly", ";", "}", "/**\n * Specifies if the precinct runs mail-only elections.\n * @param mailOnly mailOnly or {@code null} for none\n */", "public", "Precinct", "setMailOnly", "(", "java", ".", "lang", ".", "Boolean", "mailOnly", ")", "{", "this", ".", "mailOnly", "=", "mailOnly", ";", "return", "this", ";", "}", "/**\n * Required. The name of the precinct.\n * @return value or {@code null} for none\n */", "public", "java", ".", "lang", ".", "String", "getName", "(", ")", "{", "return", "name", ";", "}", "/**\n * Required. The name of the precinct.\n * @param name name or {@code null} for none\n */", "public", "Precinct", "setName", "(", "java", ".", "lang", ".", "String", "name", ")", "{", "this", ".", "name", "=", "name", ";", "return", "this", ";", "}", "/**\n * The number of the precinct.\n * @return value or {@code null} for none\n */", "public", "java", ".", "lang", ".", "String", "getNumber", "(", ")", "{", "return", "number", ";", "}", "/**\n * The number of the precinct.\n * @param number number or {@code null} for none\n */", "public", "Precinct", "setNumber", "(", "java", ".", "lang", ".", "String", "number", ")", "{", "this", ".", "number", "=", "number", ";", "return", "this", ";", "}", "/**\n * Encouraged. The OCD ID of the precinct\n * @return value or {@code null} for none\n */", "public", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "getOcdId", "(", ")", "{", "return", "ocdId", ";", "}", "/**\n * Encouraged. The OCD ID of the precinct\n * @param ocdId ocdId or {@code null} for none\n */", "public", "Precinct", "setOcdId", "(", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "ocdId", ")", "{", "this", ".", "ocdId", "=", "ocdId", ";", "return", "this", ";", "}", "/**\n * ID(s) of the PollingLocation message(s) for this precinct.\n * @return value or {@code null} for none\n */", "public", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "getPollingLocationId", "(", ")", "{", "return", "pollingLocationId", ";", "}", "/**\n * ID(s) of the PollingLocation message(s) for this precinct.\n * @param pollingLocationId pollingLocationId or {@code null} for none\n */", "public", "Precinct", "setPollingLocationId", "(", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "pollingLocationId", ")", "{", "this", ".", "pollingLocationId", "=", "pollingLocationId", ";", "return", "this", ";", "}", "/**\n * ID(s) of the SpatialBoundary message(s) for this precinct. Used to specify a geometrical\n * boundary of the precinct.\n * @return value or {@code null} for none\n */", "public", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "getSpatialBoundaryId", "(", ")", "{", "return", "spatialBoundaryId", ";", "}", "/**\n * ID(s) of the SpatialBoundary message(s) for this precinct. Used to specify a geometrical\n * boundary of the precinct.\n * @param spatialBoundaryId spatialBoundaryId or {@code null} for none\n */", "public", "Precinct", "setSpatialBoundaryId", "(", "java", ".", "util", ".", "List", "<", "java", ".", "lang", ".", "String", ">", "spatialBoundaryId", ")", "{", "this", ".", "spatialBoundaryId", "=", "spatialBoundaryId", ";", "return", "this", ";", "}", "/**\n * If present, this proto corresponds to one portion of split precinct. Other portions of this\n * precinct are guaranteed to have the same `name`. If not present, this proto represents a full\n * precicnt.\n * @return value or {@code null} for none\n */", "public", "java", ".", "lang", ".", "String", "getSplitName", "(", ")", "{", "return", "splitName", ";", "}", "/**\n * If present, this proto corresponds to one portion of split precinct. Other portions of this\n * precinct are guaranteed to have the same `name`. If not present, this proto represents a full\n * precicnt.\n * @param splitName splitName or {@code null} for none\n */", "public", "Precinct", "setSplitName", "(", "java", ".", "lang", ".", "String", "splitName", ")", "{", "this", ".", "splitName", "=", "splitName", ";", "return", "this", ";", "}", "/**\n * Specifies the ward the precinct is contained within.\n * @return value or {@code null} for none\n */", "public", "java", ".", "lang", ".", "String", "getWard", "(", ")", "{", "return", "ward", ";", "}", "/**\n * Specifies the ward the precinct is contained within.\n * @param ward ward or {@code null} for none\n */", "public", "Precinct", "setWard", "(", "java", ".", "lang", ".", "String", "ward", ")", "{", "this", ".", "ward", "=", "ward", ";", "return", "this", ";", "}", "@", "Override", "public", "Precinct", "set", "(", "String", "fieldName", ",", "Object", "value", ")", "{", "return", "(", "Precinct", ")", "super", ".", "set", "(", "fieldName", ",", "value", ")", ";", "}", "@", "Override", "public", "Precinct", "clone", "(", ")", "{", "return", "(", "Precinct", ")", "super", ".", "clone", "(", ")", ";", "}", "}" ]
Model definition for Precinct.
[ "Model", "definition", "for", "Precinct", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
469602a9488eee582faf95652f6bbca1debcda78
dbdxnuliba/IHMC-
ihmc-robotics-toolkit/src/main/java/us/ihmc/robotics/geometry/FrameMatrix3D.java
[ "Apache-2.0" ]
Java
FrameMatrix3D
/** * One of the main goals of this class is to check, at runtime, that operations on matrices occur within the same Frame. * This method checks for one matrix argument. * */
One of the main goals of this class is to check, at runtime, that operations on matrices occur within the same Frame. This method checks for one matrix argument.
[ "One", "of", "the", "main", "goals", "of", "this", "class", "is", "to", "check", "at", "runtime", "that", "operations", "on", "matrices", "occur", "within", "the", "same", "Frame", ".", "This", "method", "checks", "for", "one", "matrix", "argument", "." ]
public class FrameMatrix3D extends FrameGeometryObject<FrameMatrix3D, Matrix3D> { private final Matrix3D matrix; public FrameMatrix3D() { this(ReferenceFrame.getWorldFrame()); } public FrameMatrix3D(ReferenceFrame referenceFrame) { super(referenceFrame, new Matrix3D()); this.matrix = this.getGeometryObject(); } public FrameMatrix3D(FrameMatrix3D frameMatrix3D) { this(); setIncludingFrame(frameMatrix3D); } public FrameMatrix3D(ReferenceFrame referenceFrame, Matrix3DReadOnly matrix) { this(); setIncludingFrame(referenceFrame, matrix); } public void set(Matrix3DReadOnly matrix) { this.matrix.set(matrix); } public void setM00(double m00) { this.matrix.setM00(m00); } public void setM01(double m01) { this.matrix.setM01(m01); } public void setM02(double m02) { this.matrix.setM02(m02); } public void setM10(double m10) { this.matrix.setM10(m10); } public void setM11(double m11) { this.matrix.setM11(m11); } public void setM12(double m12) { this.matrix.setM12(m12); } public void setM20(double m20) { this.matrix.setM20(m20); } public void setM21(double m21) { this.matrix.setM21(m21); } public void setM22(double m22) { this.matrix.setM22(m22); } public void setElement(int row, int column, double value) { this.matrix.setElement(row, column, value); } public void setRow(int row, double x, double y, double z) { this.matrix.setRow(row, x, y, z); } public void setColumn(int column, double x, double y, double z) { this.matrix.setColumn(column, x, y, z); } public void setIncludingFrame(ReferenceFrame referenceFrame, Matrix3DReadOnly matrix) { this.referenceFrame = referenceFrame; this.matrix.set(matrix); } public void setToIdentity() { matrix.setIdentity(); } public void setToIdentity(ReferenceFrame referenceFrame) { this.referenceFrame = referenceFrame; setToIdentity(); } public double getElement(int row, int column) { return matrix.getElement(row, column); } public void getMatrix(Matrix3DBasics matrixToPack) { matrixToPack.set(matrix); } public void getDenseMatrix(DenseMatrix64F matrixToPack) { getDenseMatrix(matrixToPack, 0, 0); } public void getDenseMatrix(DenseMatrix64F matrixToPack, int startRow, int startColumn) { matrix.get(startRow, startColumn, matrixToPack); } /** * Multiply this frameMatrix3D by the FrameTuple frameTupleToPack and place the result * back into the FrameTuple (frameTupleToPack = this * frameTupleToPack). * @param frameTupleToPack the frameTuple to be multiplied by this frameMatrix3D and then replaced * @throws ReferenceFrameMismatchException */ public void transform(FrameTuple3DBasics frameTupleToPack) { checkReferenceFrameMatch(frameTupleToPack); matrix.transform(frameTupleToPack); } /** * Multiply this frameMatrix3D by the FrameTuple frameTupleOriginal and and place the result * into the FrameTuple frameTupleToPack (frameTupleToPack = this * frameTupleOriginal). * @param frameTupleOriginal the FrameTuple to be multiplied by this frameMatrix3D * @param frameTupleToPack the FrameTuple into which the product is placed * @throws ReferenceFrameMismatchException */ public void transform(FrameTuple3DReadOnly frameTupleOriginal, FrameTuple3DBasics frameTupleToPack) { checkReferenceFrameMatch(frameTupleOriginal); frameTupleToPack.setIncludingFrame(frameTupleOriginal); matrix.transform(frameTupleToPack); } public void setMainDiagonal(double x, double y, double z) { setElement(0, 0, x); setElement(1, 1, y); setElement(2, 2, z); } }
[ "public", "class", "FrameMatrix3D", "extends", "FrameGeometryObject", "<", "FrameMatrix3D", ",", "Matrix3D", ">", "{", "private", "final", "Matrix3D", "matrix", ";", "public", "FrameMatrix3D", "(", ")", "{", "this", "(", "ReferenceFrame", ".", "getWorldFrame", "(", ")", ")", ";", "}", "public", "FrameMatrix3D", "(", "ReferenceFrame", "referenceFrame", ")", "{", "super", "(", "referenceFrame", ",", "new", "Matrix3D", "(", ")", ")", ";", "this", ".", "matrix", "=", "this", ".", "getGeometryObject", "(", ")", ";", "}", "public", "FrameMatrix3D", "(", "FrameMatrix3D", "frameMatrix3D", ")", "{", "this", "(", ")", ";", "setIncludingFrame", "(", "frameMatrix3D", ")", ";", "}", "public", "FrameMatrix3D", "(", "ReferenceFrame", "referenceFrame", ",", "Matrix3DReadOnly", "matrix", ")", "{", "this", "(", ")", ";", "setIncludingFrame", "(", "referenceFrame", ",", "matrix", ")", ";", "}", "public", "void", "set", "(", "Matrix3DReadOnly", "matrix", ")", "{", "this", ".", "matrix", ".", "set", "(", "matrix", ")", ";", "}", "public", "void", "setM00", "(", "double", "m00", ")", "{", "this", ".", "matrix", ".", "setM00", "(", "m00", ")", ";", "}", "public", "void", "setM01", "(", "double", "m01", ")", "{", "this", ".", "matrix", ".", "setM01", "(", "m01", ")", ";", "}", "public", "void", "setM02", "(", "double", "m02", ")", "{", "this", ".", "matrix", ".", "setM02", "(", "m02", ")", ";", "}", "public", "void", "setM10", "(", "double", "m10", ")", "{", "this", ".", "matrix", ".", "setM10", "(", "m10", ")", ";", "}", "public", "void", "setM11", "(", "double", "m11", ")", "{", "this", ".", "matrix", ".", "setM11", "(", "m11", ")", ";", "}", "public", "void", "setM12", "(", "double", "m12", ")", "{", "this", ".", "matrix", ".", "setM12", "(", "m12", ")", ";", "}", "public", "void", "setM20", "(", "double", "m20", ")", "{", "this", ".", "matrix", ".", "setM20", "(", "m20", ")", ";", "}", "public", "void", "setM21", "(", "double", "m21", ")", "{", "this", ".", "matrix", ".", "setM21", "(", "m21", ")", ";", "}", "public", "void", "setM22", "(", "double", "m22", ")", "{", "this", ".", "matrix", ".", "setM22", "(", "m22", ")", ";", "}", "public", "void", "setElement", "(", "int", "row", ",", "int", "column", ",", "double", "value", ")", "{", "this", ".", "matrix", ".", "setElement", "(", "row", ",", "column", ",", "value", ")", ";", "}", "public", "void", "setRow", "(", "int", "row", ",", "double", "x", ",", "double", "y", ",", "double", "z", ")", "{", "this", ".", "matrix", ".", "setRow", "(", "row", ",", "x", ",", "y", ",", "z", ")", ";", "}", "public", "void", "setColumn", "(", "int", "column", ",", "double", "x", ",", "double", "y", ",", "double", "z", ")", "{", "this", ".", "matrix", ".", "setColumn", "(", "column", ",", "x", ",", "y", ",", "z", ")", ";", "}", "public", "void", "setIncludingFrame", "(", "ReferenceFrame", "referenceFrame", ",", "Matrix3DReadOnly", "matrix", ")", "{", "this", ".", "referenceFrame", "=", "referenceFrame", ";", "this", ".", "matrix", ".", "set", "(", "matrix", ")", ";", "}", "public", "void", "setToIdentity", "(", ")", "{", "matrix", ".", "setIdentity", "(", ")", ";", "}", "public", "void", "setToIdentity", "(", "ReferenceFrame", "referenceFrame", ")", "{", "this", ".", "referenceFrame", "=", "referenceFrame", ";", "setToIdentity", "(", ")", ";", "}", "public", "double", "getElement", "(", "int", "row", ",", "int", "column", ")", "{", "return", "matrix", ".", "getElement", "(", "row", ",", "column", ")", ";", "}", "public", "void", "getMatrix", "(", "Matrix3DBasics", "matrixToPack", ")", "{", "matrixToPack", ".", "set", "(", "matrix", ")", ";", "}", "public", "void", "getDenseMatrix", "(", "DenseMatrix64F", "matrixToPack", ")", "{", "getDenseMatrix", "(", "matrixToPack", ",", "0", ",", "0", ")", ";", "}", "public", "void", "getDenseMatrix", "(", "DenseMatrix64F", "matrixToPack", ",", "int", "startRow", ",", "int", "startColumn", ")", "{", "matrix", ".", "get", "(", "startRow", ",", "startColumn", ",", "matrixToPack", ")", ";", "}", "/**\n * Multiply this frameMatrix3D by the FrameTuple frameTupleToPack and place the result\n * back into the FrameTuple (frameTupleToPack = this * frameTupleToPack).\n * @param frameTupleToPack the frameTuple to be multiplied by this frameMatrix3D and then replaced\n * @throws ReferenceFrameMismatchException\n */", "public", "void", "transform", "(", "FrameTuple3DBasics", "frameTupleToPack", ")", "{", "checkReferenceFrameMatch", "(", "frameTupleToPack", ")", ";", "matrix", ".", "transform", "(", "frameTupleToPack", ")", ";", "}", "/**\n * Multiply this frameMatrix3D by the FrameTuple frameTupleOriginal and and place the result\n * into the FrameTuple frameTupleToPack (frameTupleToPack = this * frameTupleOriginal).\n * @param frameTupleOriginal the FrameTuple to be multiplied by this frameMatrix3D\n * @param frameTupleToPack the FrameTuple into which the product is placed\n * @throws ReferenceFrameMismatchException\n */", "public", "void", "transform", "(", "FrameTuple3DReadOnly", "frameTupleOriginal", ",", "FrameTuple3DBasics", "frameTupleToPack", ")", "{", "checkReferenceFrameMatch", "(", "frameTupleOriginal", ")", ";", "frameTupleToPack", ".", "setIncludingFrame", "(", "frameTupleOriginal", ")", ";", "matrix", ".", "transform", "(", "frameTupleToPack", ")", ";", "}", "public", "void", "setMainDiagonal", "(", "double", "x", ",", "double", "y", ",", "double", "z", ")", "{", "setElement", "(", "0", ",", "0", ",", "x", ")", ";", "setElement", "(", "1", ",", "1", ",", "y", ")", ";", "setElement", "(", "2", ",", "2", ",", "z", ")", ";", "}", "}" ]
One of the main goals of this class is to check, at runtime, that operations on matrices occur within the same Frame.
[ "One", "of", "the", "main", "goals", "of", "this", "class", "is", "to", "check", "at", "runtime", "that", "operations", "on", "matrices", "occur", "within", "the", "same", "Frame", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
46a8023a9c1a7f9b3ea179f26b04ebac39243b67
qoders/easywallet
src/main/java/org/qoders/easywallet/domain/FileUpload.java
[ "Apache-2.0" ]
Java
FileUpload
/** * Domain object for file upload * @author Nhu Trinh * */
Domain object for file upload @author Nhu Trinh
[ "Domain", "object", "for", "file", "upload", "@author", "Nhu", "Trinh" ]
public class FileUpload implements Serializable { private static final long serialVersionUID = 5238513534350490116L; /** * File field in multipart file upload */ @NotNull(message="{Form.Upload.FileEmpty}") private MultipartFile file; /** * Path is a string which indicate which type of this upload, location of upload, * path = receipt then the file will be put in /media/receipts/<user_name>/<random-uuid>.jpg * ... */ @NotEmpty(message="{Form.Upload.FilePathEmpty}") private String path; public MultipartFile getFile() { return file; } public void setFile(MultipartFile file) { this.file = file; } public String getPath() { return path; } public void setPath(String type) { this.path = type; } }
[ "public", "class", "FileUpload", "implements", "Serializable", "{", "private", "static", "final", "long", "serialVersionUID", "=", "5238513534350490116L", ";", "/**\r\n\t * File field in multipart file upload\r\n\t */", "@", "NotNull", "(", "message", "=", "\"", "{Form.Upload.FileEmpty}", "\"", ")", "private", "MultipartFile", "file", ";", "/**\r\n\t * Path is a string which indicate which type of this upload, location of upload, \r\n\t * path = receipt then the file will be put in /media/receipts/<user_name>/<random-uuid>.jpg\r\n\t * ...\r\n\t */", "@", "NotEmpty", "(", "message", "=", "\"", "{Form.Upload.FilePathEmpty}", "\"", ")", "private", "String", "path", ";", "public", "MultipartFile", "getFile", "(", ")", "{", "return", "file", ";", "}", "public", "void", "setFile", "(", "MultipartFile", "file", ")", "{", "this", ".", "file", "=", "file", ";", "}", "public", "String", "getPath", "(", ")", "{", "return", "path", ";", "}", "public", "void", "setPath", "(", "String", "type", ")", "{", "this", ".", "path", "=", "type", ";", "}", "}" ]
Domain object for file upload @author Nhu Trinh
[ "Domain", "object", "for", "file", "upload", "@author", "Nhu", "Trinh" ]
[]
[ { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
46b2a3a22843e274385dc2ef754a183bfe02c1dd
kupl/starlab-benchmarks
Benchmarks_with_Functional_Bugs/Java/Bears-169/src/pinot-controller/src/main/java/com/linkedin/pinot/controller/helix/core/retention/RetentionManager.java
[ "MIT" ]
Java
RetentionManager
/** * RetentionManager is scheduled to run only on Leader controller. * It will first scan the table configs to get segment retention strategy then * do data retention.. * * */
RetentionManager is scheduled to run only on Leader controller. It will first scan the table configs to get segment retention strategy then do data retention
[ "RetentionManager", "is", "scheduled", "to", "run", "only", "on", "Leader", "controller", ".", "It", "will", "first", "scan", "the", "table", "configs", "to", "get", "segment", "retention", "strategy", "then", "do", "data", "retention" ]
public class RetentionManager { public static final Logger LOGGER = LoggerFactory.getLogger(RetentionManager.class); private final PinotHelixResourceManager _pinotHelixResourceManager; private final Map<String, RetentionStrategy> _tableDeletionStrategy = new HashMap<>(); private final Map<String, List<SegmentZKMetadata>> _segmentMetadataMap = new HashMap<>(); private final Object _lock = new Object(); private final ScheduledExecutorService _executorService; private final int _runFrequencyInSeconds; private final int _deletedSegmentsRetentionInDays; private static final int RETENTION_TIME_FOR_OLD_LLC_SEGMENTS_DAYS = 5; private static final int DEFAULT_RETENTION_FOR_DELETED_SEGMENTS_DAYS = 7; public RetentionManager(PinotHelixResourceManager pinotHelixResourceManager, int runFrequencyInSeconds, int deletedSegmentsRetentionInDays) { _pinotHelixResourceManager = pinotHelixResourceManager; _runFrequencyInSeconds = runFrequencyInSeconds; _deletedSegmentsRetentionInDays = deletedSegmentsRetentionInDays; _executorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(@Nonnull Runnable runnable) { Thread thread = new Thread(runnable); thread.setName("PinotRetentionManagerExecutorService"); return thread; } }); } public RetentionManager(PinotHelixResourceManager pinotHelixResourceManager, int runFrequencyInSeconds) { this(pinotHelixResourceManager, runFrequencyInSeconds, DEFAULT_RETENTION_FOR_DELETED_SEGMENTS_DAYS); } public static long getRetentionTimeForOldLLCSegmentsDays() { return RETENTION_TIME_FOR_OLD_LLC_SEGMENTS_DAYS; } public void start() { scheduleRetentionThreadWithFrequency(_runFrequencyInSeconds); LOGGER.info("RetentionManager is started!"); } private void scheduleRetentionThreadWithFrequency(int runFrequencyInSeconds) { _executorService.scheduleWithFixedDelay(new Runnable() { @Override public void run() { synchronized (getLock()) { execute(); } } }, Math.min(50, runFrequencyInSeconds), runFrequencyInSeconds, TimeUnit.SECONDS); } private Object getLock() { return _lock; } private void execute() { try { if (_pinotHelixResourceManager.isLeader()) { LOGGER.info("Trying to run retentionManager!"); updateDeletionStrategiesForEntireCluster(); LOGGER.info("Finished update deletion strategies for entire cluster!"); updateSegmentMetadataForEntireCluster(); LOGGER.info("Finished update segment metadata for entire cluster!"); scanSegmentMetadataAndPurge(); LOGGER.info("Finished segment purge for entire cluster!"); removeAgedDeletedSegments(); LOGGER.info("Finished remove aged deleted segments!"); } else { LOGGER.info("Not leader of the controller, sleep!"); } } catch (Exception e) { LOGGER.error("Caught exception while running retention", e); } } private void scanSegmentMetadataAndPurge() { for (String tableName : _segmentMetadataMap.keySet()) { List<SegmentZKMetadata> segmentZKMetadataList = _segmentMetadataMap.get(tableName); List<String> segmentsToDelete = new ArrayList<>(128); IdealState idealState = null; try { if (TableNameBuilder.getTableTypeFromTableName(tableName).equals(TableType.REALTIME)) { idealState = _pinotHelixResourceManager.getHelixAdmin().getResourceIdealState( _pinotHelixResourceManager.getHelixClusterName(), tableName); } } catch (Exception e) { LOGGER.warn("Could not get idealstate for {}", tableName, e); // Ignore, worst case we have some old inactive segments in place. } for (SegmentZKMetadata segmentZKMetadata : segmentZKMetadataList) { RetentionStrategy deletionStrategy; deletionStrategy = _tableDeletionStrategy.get(tableName); if (deletionStrategy == null) { LOGGER.info("No Retention strategy found for segment: {}", segmentZKMetadata.getSegmentName()); continue; } if (segmentZKMetadata instanceof RealtimeSegmentZKMetadata) { final RealtimeSegmentZKMetadata realtimeSegmentZKMetadata = (RealtimeSegmentZKMetadata)segmentZKMetadata; if (realtimeSegmentZKMetadata.getStatus() == Status.IN_PROGRESS) { final String segmentId = realtimeSegmentZKMetadata.getSegmentName(); if (SegmentName.isHighLevelConsumerSegmentName(segmentId)) { continue; } // This is an in-progress LLC segment. Delete any old ones hanging around. Do not delete // segments that are current since there may be a race with the ValidationManager trying to // auto-create LLC segments. if (shouldDeleteInProgressLLCSegment(segmentId, idealState, realtimeSegmentZKMetadata)) { segmentsToDelete.add(segmentId); } continue; } } if (deletionStrategy.isPurgeable(segmentZKMetadata)) { LOGGER.info("Marking segment to delete: {}", segmentZKMetadata.getSegmentName()); segmentsToDelete.add(segmentZKMetadata.getSegmentName()); } } if (segmentsToDelete.size() > 0) { LOGGER.info("Trying to delete {} segments for table {}", segmentsToDelete.size(), tableName); _pinotHelixResourceManager.deleteSegments(tableName, segmentsToDelete); } } } private void removeAgedDeletedSegments() { // Trigger clean-up for deleted segments from the deleted directory _pinotHelixResourceManager.getSegmentDeletionManager().removeAgedDeletedSegments(_deletedSegmentsRetentionInDays); } private boolean shouldDeleteInProgressLLCSegment(final String segmentId, final IdealState idealState, RealtimeSegmentZKMetadata segmentZKMetadata) { if (idealState == null) { return false; } Map<String, String> stateMap = idealState.getInstanceStateMap(segmentId); if (stateMap == null) { // segment is there in propertystore but not in idealstate. mark for deletion return true; } else { Set<String> states = new HashSet<>(stateMap.values()); if (states.size() == 1 && states .contains(CommonConstants.Helix.StateModel.SegmentOnlineOfflineStateModel.OFFLINE)) { // All replicas of this segment are offline, delete it if it is old enough final long now = System.currentTimeMillis(); if (now - segmentZKMetadata.getCreationTime() >= TimeUnit.DAYS.toMillis( RETENTION_TIME_FOR_OLD_LLC_SEGMENTS_DAYS)) { return true; } } } return false; } private void updateDeletionStrategiesForEntireCluster() { List<String> tableNames = _pinotHelixResourceManager.getAllTables(); for (String tableName : tableNames) { updateDeletionStrategyForTable(tableName); } } private void updateDeletionStrategyForTable(String tableName) { TableType tableType = TableNameBuilder.getTableTypeFromTableName(tableName); assert tableType != null; switch (tableType) { case OFFLINE: updateDeletionStrategyForOfflineTable(tableName); break; case REALTIME: updateDeletionStrategyForRealtimeTable(tableName); break; default: throw new IllegalArgumentException("No table type matches table name: " + tableName); } } /** * Update deletion strategy for offline table. * <ul> * <li>Keep the current deletion strategy when one of the followings happened: * <ul> * <li>Failed to fetch the retention config.</li> * <li>Push type is not valid (neither 'APPEND' nor 'REFRESH').</li> * </ul> * <li> * Remove the deletion strategy when one of the followings happened: * <ul> * <li>Push type is set to 'REFRESH'.</li> * <li>No valid retention time is set.</li> * </ul> * </li> * <li>Update the deletion strategy when push type is set to 'APPEND' and valid retention time is set.</li> * </ul> */ private void updateDeletionStrategyForOfflineTable(String offlineTableName) { // Fetch table config. TableConfig offlineTableConfig; try { offlineTableConfig = _pinotHelixResourceManager.getOfflineTableConfig(TableNameBuilder.extractRawTableName(offlineTableName)); if (offlineTableConfig == null) { LOGGER.error("Table config is null, skip updating deletion strategy for table: {}.", offlineTableName); return; } } catch (Exception e) { LOGGER.error("Caught exception while fetching table config, skip updating deletion strategy for table: {}.", offlineTableName, e); return; } // Fetch validation config. SegmentsValidationAndRetentionConfig validationConfig = offlineTableConfig.getValidationConfig(); if (validationConfig == null) { LOGGER.error("Validation config is null, skip updating deletion strategy for table: {}.", offlineTableName); return; } // Fetch push type. String segmentPushType = validationConfig.getSegmentPushType(); if ((segmentPushType == null) || (!segmentPushType.equalsIgnoreCase("APPEND") && !segmentPushType.equalsIgnoreCase("REFRESH"))) { LOGGER.error( "Segment push type: {} is not valid ('APPEND' or 'REFRESH'), skip updating deletion strategy for table: {}.", segmentPushType, offlineTableName); return; } if (segmentPushType.equalsIgnoreCase("REFRESH")) { LOGGER.info("Segment push type is set to 'REFRESH', remove deletion strategy for table: {}.", offlineTableName); _tableDeletionStrategy.remove(offlineTableName); return; } // Fetch retention time unit and value. String retentionTimeUnit = validationConfig.getRetentionTimeUnit(); String retentionTimeValue = validationConfig.getRetentionTimeValue(); if (((retentionTimeUnit == null) || retentionTimeUnit.isEmpty()) || ((retentionTimeValue == null) || retentionTimeValue.isEmpty())) { LOGGER.info("Retention time unit/value is not set, remove deletion strategy for table: {}.", offlineTableName); _tableDeletionStrategy.remove(offlineTableName); return; } // Update time retention strategy. try { TimeRetentionStrategy timeRetentionStrategy = new TimeRetentionStrategy(retentionTimeUnit, retentionTimeValue); _tableDeletionStrategy.put(offlineTableName, timeRetentionStrategy); LOGGER.info("Updated deletion strategy for table: {} using retention time: {} {}.", offlineTableName, retentionTimeValue, retentionTimeUnit); } catch (Exception e) { LOGGER.error( "Caught exception while building deletion strategy with retention time: {} {], remove deletion strategy for table: {}.", retentionTimeValue, retentionTimeUnit, offlineTableName); _tableDeletionStrategy.remove(offlineTableName); } } /** * Update deletion strategy for realtime table. * <ul> * <li>Keep the current deletion strategy when failed to get a valid retention time</li> * <li>Update the deletion strategy when valid retention time is set.</li> * </ul> * The reason for this is that we don't allow realtime table without deletion strategy. */ private void updateDeletionStrategyForRealtimeTable(String realtimeTableName) { try { TableConfig realtimeTableConfig = _pinotHelixResourceManager.getRealtimeTableConfig(TableNameBuilder.extractRawTableName(realtimeTableName)); assert realtimeTableConfig != null; SegmentsValidationAndRetentionConfig validationConfig = realtimeTableConfig.getValidationConfig(); TimeRetentionStrategy timeRetentionStrategy = new TimeRetentionStrategy(validationConfig.getRetentionTimeUnit(), validationConfig.getRetentionTimeValue()); _tableDeletionStrategy.put(realtimeTableName, timeRetentionStrategy); } catch (Exception e) { LOGGER.error("Caught exception while updating deletion strategy, skip updating deletion strategy for table: {}.", realtimeTableName, e); } } private void updateSegmentMetadataForEntireCluster() { // Gets table names with type. List<String> tableNames = _pinotHelixResourceManager.getAllTables(); for (String tableNameWithType : tableNames) { _segmentMetadataMap.put(tableNameWithType, retrieveSegmentMetadataForTable(tableNameWithType)); } } private List<SegmentZKMetadata> retrieveSegmentMetadataForTable(String tableNameWithType) { List<SegmentZKMetadata> segmentMetadataList = new ArrayList<>(); TableType tableType = TableNameBuilder.getTableTypeFromTableName(tableNameWithType); assert tableType != null; switch (tableType) { case OFFLINE: List<OfflineSegmentZKMetadata> offlineSegmentZKMetadatas = _pinotHelixResourceManager.getOfflineSegmentMetadata( tableNameWithType); for (OfflineSegmentZKMetadata offlineSegmentZKMetadata : offlineSegmentZKMetadatas) { segmentMetadataList.add(offlineSegmentZKMetadata); } break; case REALTIME: List<RealtimeSegmentZKMetadata> realtimeSegmentZKMetadatas = _pinotHelixResourceManager.getRealtimeSegmentMetadata( tableNameWithType); for (RealtimeSegmentZKMetadata realtimeSegmentZKMetadata : realtimeSegmentZKMetadatas) { segmentMetadataList.add(realtimeSegmentZKMetadata); } break; default: throw new IllegalArgumentException("No table type matches table name: " + tableNameWithType); } return segmentMetadataList; } public void stop() { _executorService.shutdown(); } }
[ "public", "class", "RetentionManager", "{", "public", "static", "final", "Logger", "LOGGER", "=", "LoggerFactory", ".", "getLogger", "(", "RetentionManager", ".", "class", ")", ";", "private", "final", "PinotHelixResourceManager", "_pinotHelixResourceManager", ";", "private", "final", "Map", "<", "String", ",", "RetentionStrategy", ">", "_tableDeletionStrategy", "=", "new", "HashMap", "<", ">", "(", ")", ";", "private", "final", "Map", "<", "String", ",", "List", "<", "SegmentZKMetadata", ">", ">", "_segmentMetadataMap", "=", "new", "HashMap", "<", ">", "(", ")", ";", "private", "final", "Object", "_lock", "=", "new", "Object", "(", ")", ";", "private", "final", "ScheduledExecutorService", "_executorService", ";", "private", "final", "int", "_runFrequencyInSeconds", ";", "private", "final", "int", "_deletedSegmentsRetentionInDays", ";", "private", "static", "final", "int", "RETENTION_TIME_FOR_OLD_LLC_SEGMENTS_DAYS", "=", "5", ";", "private", "static", "final", "int", "DEFAULT_RETENTION_FOR_DELETED_SEGMENTS_DAYS", "=", "7", ";", "public", "RetentionManager", "(", "PinotHelixResourceManager", "pinotHelixResourceManager", ",", "int", "runFrequencyInSeconds", ",", "int", "deletedSegmentsRetentionInDays", ")", "{", "_pinotHelixResourceManager", "=", "pinotHelixResourceManager", ";", "_runFrequencyInSeconds", "=", "runFrequencyInSeconds", ";", "_deletedSegmentsRetentionInDays", "=", "deletedSegmentsRetentionInDays", ";", "_executorService", "=", "Executors", ".", "newSingleThreadScheduledExecutor", "(", "new", "ThreadFactory", "(", ")", "{", "@", "Override", "public", "Thread", "newThread", "(", "@", "Nonnull", "Runnable", "runnable", ")", "{", "Thread", "thread", "=", "new", "Thread", "(", "runnable", ")", ";", "thread", ".", "setName", "(", "\"", "PinotRetentionManagerExecutorService", "\"", ")", ";", "return", "thread", ";", "}", "}", ")", ";", "}", "public", "RetentionManager", "(", "PinotHelixResourceManager", "pinotHelixResourceManager", ",", "int", "runFrequencyInSeconds", ")", "{", "this", "(", "pinotHelixResourceManager", ",", "runFrequencyInSeconds", ",", "DEFAULT_RETENTION_FOR_DELETED_SEGMENTS_DAYS", ")", ";", "}", "public", "static", "long", "getRetentionTimeForOldLLCSegmentsDays", "(", ")", "{", "return", "RETENTION_TIME_FOR_OLD_LLC_SEGMENTS_DAYS", ";", "}", "public", "void", "start", "(", ")", "{", "scheduleRetentionThreadWithFrequency", "(", "_runFrequencyInSeconds", ")", ";", "LOGGER", ".", "info", "(", "\"", "RetentionManager is started!", "\"", ")", ";", "}", "private", "void", "scheduleRetentionThreadWithFrequency", "(", "int", "runFrequencyInSeconds", ")", "{", "_executorService", ".", "scheduleWithFixedDelay", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "synchronized", "(", "getLock", "(", ")", ")", "{", "execute", "(", ")", ";", "}", "}", "}", ",", "Math", ".", "min", "(", "50", ",", "runFrequencyInSeconds", ")", ",", "runFrequencyInSeconds", ",", "TimeUnit", ".", "SECONDS", ")", ";", "}", "private", "Object", "getLock", "(", ")", "{", "return", "_lock", ";", "}", "private", "void", "execute", "(", ")", "{", "try", "{", "if", "(", "_pinotHelixResourceManager", ".", "isLeader", "(", ")", ")", "{", "LOGGER", ".", "info", "(", "\"", "Trying to run retentionManager!", "\"", ")", ";", "updateDeletionStrategiesForEntireCluster", "(", ")", ";", "LOGGER", ".", "info", "(", "\"", "Finished update deletion strategies for entire cluster!", "\"", ")", ";", "updateSegmentMetadataForEntireCluster", "(", ")", ";", "LOGGER", ".", "info", "(", "\"", "Finished update segment metadata for entire cluster!", "\"", ")", ";", "scanSegmentMetadataAndPurge", "(", ")", ";", "LOGGER", ".", "info", "(", "\"", "Finished segment purge for entire cluster!", "\"", ")", ";", "removeAgedDeletedSegments", "(", ")", ";", "LOGGER", ".", "info", "(", "\"", "Finished remove aged deleted segments!", "\"", ")", ";", "}", "else", "{", "LOGGER", ".", "info", "(", "\"", "Not leader of the controller, sleep!", "\"", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "LOGGER", ".", "error", "(", "\"", "Caught exception while running retention", "\"", ",", "e", ")", ";", "}", "}", "private", "void", "scanSegmentMetadataAndPurge", "(", ")", "{", "for", "(", "String", "tableName", ":", "_segmentMetadataMap", ".", "keySet", "(", ")", ")", "{", "List", "<", "SegmentZKMetadata", ">", "segmentZKMetadataList", "=", "_segmentMetadataMap", ".", "get", "(", "tableName", ")", ";", "List", "<", "String", ">", "segmentsToDelete", "=", "new", "ArrayList", "<", ">", "(", "128", ")", ";", "IdealState", "idealState", "=", "null", ";", "try", "{", "if", "(", "TableNameBuilder", ".", "getTableTypeFromTableName", "(", "tableName", ")", ".", "equals", "(", "TableType", ".", "REALTIME", ")", ")", "{", "idealState", "=", "_pinotHelixResourceManager", ".", "getHelixAdmin", "(", ")", ".", "getResourceIdealState", "(", "_pinotHelixResourceManager", ".", "getHelixClusterName", "(", ")", ",", "tableName", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "LOGGER", ".", "warn", "(", "\"", "Could not get idealstate for {}", "\"", ",", "tableName", ",", "e", ")", ";", "}", "for", "(", "SegmentZKMetadata", "segmentZKMetadata", ":", "segmentZKMetadataList", ")", "{", "RetentionStrategy", "deletionStrategy", ";", "deletionStrategy", "=", "_tableDeletionStrategy", ".", "get", "(", "tableName", ")", ";", "if", "(", "deletionStrategy", "==", "null", ")", "{", "LOGGER", ".", "info", "(", "\"", "No Retention strategy found for segment: {}", "\"", ",", "segmentZKMetadata", ".", "getSegmentName", "(", ")", ")", ";", "continue", ";", "}", "if", "(", "segmentZKMetadata", "instanceof", "RealtimeSegmentZKMetadata", ")", "{", "final", "RealtimeSegmentZKMetadata", "realtimeSegmentZKMetadata", "=", "(", "RealtimeSegmentZKMetadata", ")", "segmentZKMetadata", ";", "if", "(", "realtimeSegmentZKMetadata", ".", "getStatus", "(", ")", "==", "Status", ".", "IN_PROGRESS", ")", "{", "final", "String", "segmentId", "=", "realtimeSegmentZKMetadata", ".", "getSegmentName", "(", ")", ";", "if", "(", "SegmentName", ".", "isHighLevelConsumerSegmentName", "(", "segmentId", ")", ")", "{", "continue", ";", "}", "if", "(", "shouldDeleteInProgressLLCSegment", "(", "segmentId", ",", "idealState", ",", "realtimeSegmentZKMetadata", ")", ")", "{", "segmentsToDelete", ".", "add", "(", "segmentId", ")", ";", "}", "continue", ";", "}", "}", "if", "(", "deletionStrategy", ".", "isPurgeable", "(", "segmentZKMetadata", ")", ")", "{", "LOGGER", ".", "info", "(", "\"", "Marking segment to delete: {}", "\"", ",", "segmentZKMetadata", ".", "getSegmentName", "(", ")", ")", ";", "segmentsToDelete", ".", "add", "(", "segmentZKMetadata", ".", "getSegmentName", "(", ")", ")", ";", "}", "}", "if", "(", "segmentsToDelete", ".", "size", "(", ")", ">", "0", ")", "{", "LOGGER", ".", "info", "(", "\"", "Trying to delete {} segments for table {}", "\"", ",", "segmentsToDelete", ".", "size", "(", ")", ",", "tableName", ")", ";", "_pinotHelixResourceManager", ".", "deleteSegments", "(", "tableName", ",", "segmentsToDelete", ")", ";", "}", "}", "}", "private", "void", "removeAgedDeletedSegments", "(", ")", "{", "_pinotHelixResourceManager", ".", "getSegmentDeletionManager", "(", ")", ".", "removeAgedDeletedSegments", "(", "_deletedSegmentsRetentionInDays", ")", ";", "}", "private", "boolean", "shouldDeleteInProgressLLCSegment", "(", "final", "String", "segmentId", ",", "final", "IdealState", "idealState", ",", "RealtimeSegmentZKMetadata", "segmentZKMetadata", ")", "{", "if", "(", "idealState", "==", "null", ")", "{", "return", "false", ";", "}", "Map", "<", "String", ",", "String", ">", "stateMap", "=", "idealState", ".", "getInstanceStateMap", "(", "segmentId", ")", ";", "if", "(", "stateMap", "==", "null", ")", "{", "return", "true", ";", "}", "else", "{", "Set", "<", "String", ">", "states", "=", "new", "HashSet", "<", ">", "(", "stateMap", ".", "values", "(", ")", ")", ";", "if", "(", "states", ".", "size", "(", ")", "==", "1", "&&", "states", ".", "contains", "(", "CommonConstants", ".", "Helix", ".", "StateModel", ".", "SegmentOnlineOfflineStateModel", ".", "OFFLINE", ")", ")", "{", "final", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "now", "-", "segmentZKMetadata", ".", "getCreationTime", "(", ")", ">=", "TimeUnit", ".", "DAYS", ".", "toMillis", "(", "RETENTION_TIME_FOR_OLD_LLC_SEGMENTS_DAYS", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}", "private", "void", "updateDeletionStrategiesForEntireCluster", "(", ")", "{", "List", "<", "String", ">", "tableNames", "=", "_pinotHelixResourceManager", ".", "getAllTables", "(", ")", ";", "for", "(", "String", "tableName", ":", "tableNames", ")", "{", "updateDeletionStrategyForTable", "(", "tableName", ")", ";", "}", "}", "private", "void", "updateDeletionStrategyForTable", "(", "String", "tableName", ")", "{", "TableType", "tableType", "=", "TableNameBuilder", ".", "getTableTypeFromTableName", "(", "tableName", ")", ";", "assert", "tableType", "!=", "null", ";", "switch", "(", "tableType", ")", "{", "case", "OFFLINE", ":", "updateDeletionStrategyForOfflineTable", "(", "tableName", ")", ";", "break", ";", "case", "REALTIME", ":", "updateDeletionStrategyForRealtimeTable", "(", "tableName", ")", ";", "break", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"", "No table type matches table name: ", "\"", "+", "tableName", ")", ";", "}", "}", "/**\n * Update deletion strategy for offline table.\n * <ul>\n * <li>Keep the current deletion strategy when one of the followings happened:\n * <ul>\n * <li>Failed to fetch the retention config.</li>\n * <li>Push type is not valid (neither 'APPEND' nor 'REFRESH').</li>\n * </ul>\n * <li>\n * Remove the deletion strategy when one of the followings happened:\n * <ul>\n * <li>Push type is set to 'REFRESH'.</li>\n * <li>No valid retention time is set.</li>\n * </ul>\n * </li>\n * <li>Update the deletion strategy when push type is set to 'APPEND' and valid retention time is set.</li>\n * </ul>\n */", "private", "void", "updateDeletionStrategyForOfflineTable", "(", "String", "offlineTableName", ")", "{", "TableConfig", "offlineTableConfig", ";", "try", "{", "offlineTableConfig", "=", "_pinotHelixResourceManager", ".", "getOfflineTableConfig", "(", "TableNameBuilder", ".", "extractRawTableName", "(", "offlineTableName", ")", ")", ";", "if", "(", "offlineTableConfig", "==", "null", ")", "{", "LOGGER", ".", "error", "(", "\"", "Table config is null, skip updating deletion strategy for table: {}.", "\"", ",", "offlineTableName", ")", ";", "return", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "LOGGER", ".", "error", "(", "\"", "Caught exception while fetching table config, skip updating deletion strategy for table: {}.", "\"", ",", "offlineTableName", ",", "e", ")", ";", "return", ";", "}", "SegmentsValidationAndRetentionConfig", "validationConfig", "=", "offlineTableConfig", ".", "getValidationConfig", "(", ")", ";", "if", "(", "validationConfig", "==", "null", ")", "{", "LOGGER", ".", "error", "(", "\"", "Validation config is null, skip updating deletion strategy for table: {}.", "\"", ",", "offlineTableName", ")", ";", "return", ";", "}", "String", "segmentPushType", "=", "validationConfig", ".", "getSegmentPushType", "(", ")", ";", "if", "(", "(", "segmentPushType", "==", "null", ")", "||", "(", "!", "segmentPushType", ".", "equalsIgnoreCase", "(", "\"", "APPEND", "\"", ")", "&&", "!", "segmentPushType", ".", "equalsIgnoreCase", "(", "\"", "REFRESH", "\"", ")", ")", ")", "{", "LOGGER", ".", "error", "(", "\"", "Segment push type: {} is not valid ('APPEND' or 'REFRESH'), skip updating deletion strategy for table: {}.", "\"", ",", "segmentPushType", ",", "offlineTableName", ")", ";", "return", ";", "}", "if", "(", "segmentPushType", ".", "equalsIgnoreCase", "(", "\"", "REFRESH", "\"", ")", ")", "{", "LOGGER", ".", "info", "(", "\"", "Segment push type is set to 'REFRESH', remove deletion strategy for table: {}.", "\"", ",", "offlineTableName", ")", ";", "_tableDeletionStrategy", ".", "remove", "(", "offlineTableName", ")", ";", "return", ";", "}", "String", "retentionTimeUnit", "=", "validationConfig", ".", "getRetentionTimeUnit", "(", ")", ";", "String", "retentionTimeValue", "=", "validationConfig", ".", "getRetentionTimeValue", "(", ")", ";", "if", "(", "(", "(", "retentionTimeUnit", "==", "null", ")", "||", "retentionTimeUnit", ".", "isEmpty", "(", ")", ")", "||", "(", "(", "retentionTimeValue", "==", "null", ")", "||", "retentionTimeValue", ".", "isEmpty", "(", ")", ")", ")", "{", "LOGGER", ".", "info", "(", "\"", "Retention time unit/value is not set, remove deletion strategy for table: {}.", "\"", ",", "offlineTableName", ")", ";", "_tableDeletionStrategy", ".", "remove", "(", "offlineTableName", ")", ";", "return", ";", "}", "try", "{", "TimeRetentionStrategy", "timeRetentionStrategy", "=", "new", "TimeRetentionStrategy", "(", "retentionTimeUnit", ",", "retentionTimeValue", ")", ";", "_tableDeletionStrategy", ".", "put", "(", "offlineTableName", ",", "timeRetentionStrategy", ")", ";", "LOGGER", ".", "info", "(", "\"", "Updated deletion strategy for table: {} using retention time: {} {}.", "\"", ",", "offlineTableName", ",", "retentionTimeValue", ",", "retentionTimeUnit", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOGGER", ".", "error", "(", "\"", "Caught exception while building deletion strategy with retention time: {} {], remove deletion strategy for table: {}.", "\"", ",", "retentionTimeValue", ",", "retentionTimeUnit", ",", "offlineTableName", ")", ";", "_tableDeletionStrategy", ".", "remove", "(", "offlineTableName", ")", ";", "}", "}", "/**\n * Update deletion strategy for realtime table.\n * <ul>\n * <li>Keep the current deletion strategy when failed to get a valid retention time</li>\n * <li>Update the deletion strategy when valid retention time is set.</li>\n * </ul>\n * The reason for this is that we don't allow realtime table without deletion strategy.\n */", "private", "void", "updateDeletionStrategyForRealtimeTable", "(", "String", "realtimeTableName", ")", "{", "try", "{", "TableConfig", "realtimeTableConfig", "=", "_pinotHelixResourceManager", ".", "getRealtimeTableConfig", "(", "TableNameBuilder", ".", "extractRawTableName", "(", "realtimeTableName", ")", ")", ";", "assert", "realtimeTableConfig", "!=", "null", ";", "SegmentsValidationAndRetentionConfig", "validationConfig", "=", "realtimeTableConfig", ".", "getValidationConfig", "(", ")", ";", "TimeRetentionStrategy", "timeRetentionStrategy", "=", "new", "TimeRetentionStrategy", "(", "validationConfig", ".", "getRetentionTimeUnit", "(", ")", ",", "validationConfig", ".", "getRetentionTimeValue", "(", ")", ")", ";", "_tableDeletionStrategy", ".", "put", "(", "realtimeTableName", ",", "timeRetentionStrategy", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOGGER", ".", "error", "(", "\"", "Caught exception while updating deletion strategy, skip updating deletion strategy for table: {}.", "\"", ",", "realtimeTableName", ",", "e", ")", ";", "}", "}", "private", "void", "updateSegmentMetadataForEntireCluster", "(", ")", "{", "List", "<", "String", ">", "tableNames", "=", "_pinotHelixResourceManager", ".", "getAllTables", "(", ")", ";", "for", "(", "String", "tableNameWithType", ":", "tableNames", ")", "{", "_segmentMetadataMap", ".", "put", "(", "tableNameWithType", ",", "retrieveSegmentMetadataForTable", "(", "tableNameWithType", ")", ")", ";", "}", "}", "private", "List", "<", "SegmentZKMetadata", ">", "retrieveSegmentMetadataForTable", "(", "String", "tableNameWithType", ")", "{", "List", "<", "SegmentZKMetadata", ">", "segmentMetadataList", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "TableType", "tableType", "=", "TableNameBuilder", ".", "getTableTypeFromTableName", "(", "tableNameWithType", ")", ";", "assert", "tableType", "!=", "null", ";", "switch", "(", "tableType", ")", "{", "case", "OFFLINE", ":", "List", "<", "OfflineSegmentZKMetadata", ">", "offlineSegmentZKMetadatas", "=", "_pinotHelixResourceManager", ".", "getOfflineSegmentMetadata", "(", "tableNameWithType", ")", ";", "for", "(", "OfflineSegmentZKMetadata", "offlineSegmentZKMetadata", ":", "offlineSegmentZKMetadatas", ")", "{", "segmentMetadataList", ".", "add", "(", "offlineSegmentZKMetadata", ")", ";", "}", "break", ";", "case", "REALTIME", ":", "List", "<", "RealtimeSegmentZKMetadata", ">", "realtimeSegmentZKMetadatas", "=", "_pinotHelixResourceManager", ".", "getRealtimeSegmentMetadata", "(", "tableNameWithType", ")", ";", "for", "(", "RealtimeSegmentZKMetadata", "realtimeSegmentZKMetadata", ":", "realtimeSegmentZKMetadatas", ")", "{", "segmentMetadataList", ".", "add", "(", "realtimeSegmentZKMetadata", ")", ";", "}", "break", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"", "No table type matches table name: ", "\"", "+", "tableNameWithType", ")", ";", "}", "return", "segmentMetadataList", ";", "}", "public", "void", "stop", "(", ")", "{", "_executorService", ".", "shutdown", "(", ")", ";", "}", "}" ]
RetentionManager is scheduled to run only on Leader controller.
[ "RetentionManager", "is", "scheduled", "to", "run", "only", "on", "Leader", "controller", "." ]
[ "// Ignore, worst case we have some old inactive segments in place.", "// This is an in-progress LLC segment. Delete any old ones hanging around. Do not delete", "// segments that are current since there may be a race with the ValidationManager trying to", "// auto-create LLC segments.", "// Trigger clean-up for deleted segments from the deleted directory", "// segment is there in propertystore but not in idealstate. mark for deletion", "// All replicas of this segment are offline, delete it if it is old enough", "// Fetch table config.", "// Fetch validation config.", "// Fetch push type.", "// Fetch retention time unit and value.", "// Update time retention strategy.", "// Gets table names with type." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
46bb967614629c0095a72397ceab835d1b003d7f
PuddlesSmit/android-ponewheel
app/src/main/java/net/kwatts/powtools/events/DeviceBatteryRemainingEvent.java
[ "MIT" ]
Java
DeviceBatteryRemainingEvent
/** * Created by kwatts on 5/30/16. */
Created by kwatts on 5/30/16.
[ "Created", "by", "kwatts", "on", "5", "/", "30", "/", "16", "." ]
public class DeviceBatteryRemainingEvent { public final int percentage; public DeviceBatteryRemainingEvent(int percentage) { this.percentage = percentage; } }
[ "public", "class", "DeviceBatteryRemainingEvent", "{", "public", "final", "int", "percentage", ";", "public", "DeviceBatteryRemainingEvent", "(", "int", "percentage", ")", "{", "this", ".", "percentage", "=", "percentage", ";", "}", "}" ]
Created by kwatts on 5/30/16.
[ "Created", "by", "kwatts", "on", "5", "/", "30", "/", "16", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
46bc0883a0e077f1d8d55a178aae8b848ddc8f08
mort11/2016-Robot
src/org/mort11/commands/auton/LowBarLowGoal.java
[ "MIT" ]
Java
LowBarLowGoal
/** * Oh baby a triple * * @author Sahit Chintalapudi */
Oh baby a triple @author Sahit Chintalapudi
[ "Oh", "baby", "a", "triple", "@author", "Sahit", "Chintalapudi" ]
public class LowBarLowGoal extends CommandGroup { public LowBarLowGoal() { addParallel(new IntakeArmToAngle(80)); addSequential(new WaitCommand(3.5)); addSequential(new DriveStraight(256)); addSequential(new TurnDegrees(55)); addSequential(new DriveStraight(71)); addSequential(new DriveStraight(-61)); addSequential(new IntakeRollers(4, SubsystemStates.RollerState.EXHAUST)); } }
[ "public", "class", "LowBarLowGoal", "extends", "CommandGroup", "{", "public", "LowBarLowGoal", "(", ")", "{", "addParallel", "(", "new", "IntakeArmToAngle", "(", "80", ")", ")", ";", "addSequential", "(", "new", "WaitCommand", "(", "3.5", ")", ")", ";", "addSequential", "(", "new", "DriveStraight", "(", "256", ")", ")", ";", "addSequential", "(", "new", "TurnDegrees", "(", "55", ")", ")", ";", "addSequential", "(", "new", "DriveStraight", "(", "71", ")", ")", ";", "addSequential", "(", "new", "DriveStraight", "(", "-", "61", ")", ")", ";", "addSequential", "(", "new", "IntakeRollers", "(", "4", ",", "SubsystemStates", ".", "RollerState", ".", "EXHAUST", ")", ")", ";", "}", "}" ]
Oh baby a triple @author Sahit Chintalapudi
[ "Oh", "baby", "a", "triple", "@author", "Sahit", "Chintalapudi" ]
[]
[ { "param": "CommandGroup", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "CommandGroup", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
46be82283861500b972770a0e7c31fb46d85ec7e
zdrapela/kie-tools
packages/stunner-editors/errai-ioc/src/main/java/org/jboss/errai/ioc/client/test/FakeGWT.java
[ "Apache-2.0" ]
Java
FakeGWT
/** * This class is designed to create a randomized delay in the callback to simulate network latency. * * @author Mike Brock */
This class is designed to create a randomized delay in the callback to simulate network latency. @author Mike Brock
[ "This", "class", "is", "designed", "to", "create", "a", "randomized", "delay", "in", "the", "callback", "to", "simulate", "network", "latency", ".", "@author", "Mike", "Brock" ]
public class FakeGWT { public static Throwable trace; private static final Logger logger = LoggerFactory.getLogger(FakeGWT.class); public static void runAsync(final Class<?> fragmentName, final RunAsyncCallback callback) { // no use for the fragment name here. runAsync(callback); } public static void runAsync(final RunAsyncCallback callback) { final int delay = Random.nextInt(50) + 1; final Throwable _trace = new Throwable(); new Timer() { @Override public void run() { trace = _trace; callback.onSuccess(); } }.schedule(delay); logger.info("simulating async load with " + delay + "ms delay."); } }
[ "public", "class", "FakeGWT", "{", "public", "static", "Throwable", "trace", ";", "private", "static", "final", "Logger", "logger", "=", "LoggerFactory", ".", "getLogger", "(", "FakeGWT", ".", "class", ")", ";", "public", "static", "void", "runAsync", "(", "final", "Class", "<", "?", ">", "fragmentName", ",", "final", "RunAsyncCallback", "callback", ")", "{", "runAsync", "(", "callback", ")", ";", "}", "public", "static", "void", "runAsync", "(", "final", "RunAsyncCallback", "callback", ")", "{", "final", "int", "delay", "=", "Random", ".", "nextInt", "(", "50", ")", "+", "1", ";", "final", "Throwable", "_trace", "=", "new", "Throwable", "(", ")", ";", "new", "Timer", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "trace", "=", "_trace", ";", "callback", ".", "onSuccess", "(", ")", ";", "}", "}", ".", "schedule", "(", "delay", ")", ";", "logger", ".", "info", "(", "\"", "simulating async load with ", "\"", "+", "delay", "+", "\"", "ms delay.", "\"", ")", ";", "}", "}" ]
This class is designed to create a randomized delay in the callback to simulate network latency.
[ "This", "class", "is", "designed", "to", "create", "a", "randomized", "delay", "in", "the", "callback", "to", "simulate", "network", "latency", "." ]
[ "// no use for the fragment name here." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
46c2f42e00d402cb38776c361f06b02385cb04d6
pallamidessi/Courses
kv-3.5.2/src/oracle/kv/impl/rep/admin/RepNodeInfo.java
[ "MIT" ]
Java
RepNodeInfo
/** * Diagnostic and status information about a RepNode. */
Diagnostic and status information about a RepNode.
[ "Diagnostic", "and", "status", "information", "about", "a", "RepNode", "." ]
public class RepNodeInfo implements Serializable { /** * */ private static final long serialVersionUID = 1L; private final EnvironmentConfig envConfig; private final EnvironmentStats envStats; /* Since R2 patch 1 */ private final KVVersion version; RepNodeInfo(RepNode repNode) { version = KVVersion.CURRENT_VERSION; Environment env = repNode.getEnv(0L); if (env == null) { envConfig = null; envStats = null; return; } envConfig = env.getConfig(); envStats = env.getStats(null); } public EnvironmentConfig getEnvConfig() { return envConfig; } public EnvironmentStats getEnvStats() { return envStats; } /** * Gets the RepNode's software version. * * @return the RepNode's software version */ public KVVersion getSoftwareVersion() { /* * If the version field is not filled-in we will assume that the * node it came from is running the initial R2 release (2.0.23). */ return (version != null) ? version : KVVersion.R2_0_23; } @Override public String toString() { return "Environment Configuration:\n" + envConfig + "\n" + envStats; } }
[ "public", "class", "RepNodeInfo", "implements", "Serializable", "{", "/**\n * \n */", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "private", "final", "EnvironmentConfig", "envConfig", ";", "private", "final", "EnvironmentStats", "envStats", ";", "/* Since R2 patch 1 */", "private", "final", "KVVersion", "version", ";", "RepNodeInfo", "(", "RepNode", "repNode", ")", "{", "version", "=", "KVVersion", ".", "CURRENT_VERSION", ";", "Environment", "env", "=", "repNode", ".", "getEnv", "(", "0L", ")", ";", "if", "(", "env", "==", "null", ")", "{", "envConfig", "=", "null", ";", "envStats", "=", "null", ";", "return", ";", "}", "envConfig", "=", "env", ".", "getConfig", "(", ")", ";", "envStats", "=", "env", ".", "getStats", "(", "null", ")", ";", "}", "public", "EnvironmentConfig", "getEnvConfig", "(", ")", "{", "return", "envConfig", ";", "}", "public", "EnvironmentStats", "getEnvStats", "(", ")", "{", "return", "envStats", ";", "}", "/**\n * Gets the RepNode's software version.\n * \n * @return the RepNode's software version\n */", "public", "KVVersion", "getSoftwareVersion", "(", ")", "{", "/*\n * If the version field is not filled-in we will assume that the\n * node it came from is running the initial R2 release (2.0.23).\n */", "return", "(", "version", "!=", "null", ")", "?", "version", ":", "KVVersion", ".", "R2_0_23", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "Environment Configuration:", "\\n", "\"", "+", "envConfig", "+", "\"", "\\n", "\"", "+", "envStats", ";", "}", "}" ]
Diagnostic and status information about a RepNode.
[ "Diagnostic", "and", "status", "information", "about", "a", "RepNode", "." ]
[]
[ { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
46c5978df10829561678ac610189b0ddafd3bb34
orange-cloudfoundry/elpaaso-core
cloud-paas/cloud-paas-webapp/cloud-paas-webapp-war/src/main/java/com/francetelecom/clara/cloud/presentation/common/HeaderNavigation.java
[ "Apache-2.0" ]
Java
HeaderNavigation
/** * Created by IntelliJ IDEA. * User: Thomas Escalle - tawe8231 * Entity : FT/OLNC/RD/MAPS/MEP/MSE * Date: 10/05/11 */
Created by IntelliJ IDEA.
[ "Created", "by", "IntelliJ", "IDEA", "." ]
public class HeaderNavigation extends Panel { private static final long serialVersionUID = -8477698440112231631L; private static final Logger logger = LoggerFactory.getLogger(HeaderNavigation.class.getName()); public HeaderNavigation(String id) { super(id); logger.debug("create page navigation header"); } }
[ "public", "class", "HeaderNavigation", "extends", "Panel", "{", "private", "static", "final", "long", "serialVersionUID", "=", "-", "8477698440112231631L", ";", "private", "static", "final", "Logger", "logger", "=", "LoggerFactory", ".", "getLogger", "(", "HeaderNavigation", ".", "class", ".", "getName", "(", ")", ")", ";", "public", "HeaderNavigation", "(", "String", "id", ")", "{", "super", "(", "id", ")", ";", "logger", ".", "debug", "(", "\"", "create page navigation header", "\"", ")", ";", "}", "}" ]
Created by IntelliJ IDEA.
[ "Created", "by", "IntelliJ", "IDEA", "." ]
[]
[ { "param": "Panel", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Panel", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
46ca12259ea82f56648602d664feb01bc9e4bfc9
powerfuler/fw-spring-cloud
fw-cloud-securitys/fw-securitys-security/fw-security-oauth2-sso/fw-security-oauth2-sso-server/src/main/java/com/yisu/security/sso/properties/OAuth2Properties.java
[ "Apache-2.0" ]
Java
OAuth2Properties
/** * @author xuyisu * @description * @date 2020/04/11 */
@author xuyisu @description @date 2020/04/11
[ "@author", "xuyisu", "@description", "@date", "2020", "/", "04", "/", "11" ]
@Data public class OAuth2Properties { private String jwtSigningKey = "fw"; private OAuth2ClientProperties[] clients = {}; }
[ "@", "Data", "public", "class", "OAuth2Properties", "{", "private", "String", "jwtSigningKey", "=", "\"", "fw", "\"", ";", "private", "OAuth2ClientProperties", "[", "]", "clients", "=", "{", "}", ";", "}" ]
@author xuyisu @description @date 2020/04/11
[ "@author", "xuyisu", "@description", "@date", "2020", "/", "04", "/", "11" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
46cb98ef0e97e09b8f6ff12ece1730f28a49126a
oobujieshi/aliyun-openapi-java-sdk
aliyun-java-sdk-sgw/src/main/java/com/aliyuncs/sgw/model/v20180511/DescribeOssBucketInfoResponse.java
[ "Apache-2.0" ]
Java
DescribeOssBucketInfoResponse
/** * @author auto create * @version */
@author auto create @version
[ "@author", "auto", "create", "@version" ]
public class DescribeOssBucketInfoResponse extends AcsResponse { private String requestId; private Boolean success; private String code; private String message; private Boolean isArchive; private Boolean isBackToResource; private Integer pollingInterval; private Boolean isSupportServerSideEncryption; private Boolean isFresh; private Long storageSize; private Boolean isVersioning; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public Boolean getSuccess() { return this.success; } public void setSuccess(Boolean success) { this.success = success; } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public Boolean getIsArchive() { return this.isArchive; } public void setIsArchive(Boolean isArchive) { this.isArchive = isArchive; } public Boolean getIsBackToResource() { return this.isBackToResource; } public void setIsBackToResource(Boolean isBackToResource) { this.isBackToResource = isBackToResource; } public Integer getPollingInterval() { return this.pollingInterval; } public void setPollingInterval(Integer pollingInterval) { this.pollingInterval = pollingInterval; } public Boolean getIsSupportServerSideEncryption() { return this.isSupportServerSideEncryption; } public void setIsSupportServerSideEncryption(Boolean isSupportServerSideEncryption) { this.isSupportServerSideEncryption = isSupportServerSideEncryption; } public Boolean getIsFresh() { return this.isFresh; } public void setIsFresh(Boolean isFresh) { this.isFresh = isFresh; } public Long getStorageSize() { return this.storageSize; } public void setStorageSize(Long storageSize) { this.storageSize = storageSize; } public Boolean getIsVersioning() { return this.isVersioning; } public void setIsVersioning(Boolean isVersioning) { this.isVersioning = isVersioning; } @Override public DescribeOssBucketInfoResponse getInstance(UnmarshallerContext context) { return DescribeOssBucketInfoResponseUnmarshaller.unmarshall(this, context); } }
[ "public", "class", "DescribeOssBucketInfoResponse", "extends", "AcsResponse", "{", "private", "String", "requestId", ";", "private", "Boolean", "success", ";", "private", "String", "code", ";", "private", "String", "message", ";", "private", "Boolean", "isArchive", ";", "private", "Boolean", "isBackToResource", ";", "private", "Integer", "pollingInterval", ";", "private", "Boolean", "isSupportServerSideEncryption", ";", "private", "Boolean", "isFresh", ";", "private", "Long", "storageSize", ";", "private", "Boolean", "isVersioning", ";", "public", "String", "getRequestId", "(", ")", "{", "return", "this", ".", "requestId", ";", "}", "public", "void", "setRequestId", "(", "String", "requestId", ")", "{", "this", ".", "requestId", "=", "requestId", ";", "}", "public", "Boolean", "getSuccess", "(", ")", "{", "return", "this", ".", "success", ";", "}", "public", "void", "setSuccess", "(", "Boolean", "success", ")", "{", "this", ".", "success", "=", "success", ";", "}", "public", "String", "getCode", "(", ")", "{", "return", "this", ".", "code", ";", "}", "public", "void", "setCode", "(", "String", "code", ")", "{", "this", ".", "code", "=", "code", ";", "}", "public", "String", "getMessage", "(", ")", "{", "return", "this", ".", "message", ";", "}", "public", "void", "setMessage", "(", "String", "message", ")", "{", "this", ".", "message", "=", "message", ";", "}", "public", "Boolean", "getIsArchive", "(", ")", "{", "return", "this", ".", "isArchive", ";", "}", "public", "void", "setIsArchive", "(", "Boolean", "isArchive", ")", "{", "this", ".", "isArchive", "=", "isArchive", ";", "}", "public", "Boolean", "getIsBackToResource", "(", ")", "{", "return", "this", ".", "isBackToResource", ";", "}", "public", "void", "setIsBackToResource", "(", "Boolean", "isBackToResource", ")", "{", "this", ".", "isBackToResource", "=", "isBackToResource", ";", "}", "public", "Integer", "getPollingInterval", "(", ")", "{", "return", "this", ".", "pollingInterval", ";", "}", "public", "void", "setPollingInterval", "(", "Integer", "pollingInterval", ")", "{", "this", ".", "pollingInterval", "=", "pollingInterval", ";", "}", "public", "Boolean", "getIsSupportServerSideEncryption", "(", ")", "{", "return", "this", ".", "isSupportServerSideEncryption", ";", "}", "public", "void", "setIsSupportServerSideEncryption", "(", "Boolean", "isSupportServerSideEncryption", ")", "{", "this", ".", "isSupportServerSideEncryption", "=", "isSupportServerSideEncryption", ";", "}", "public", "Boolean", "getIsFresh", "(", ")", "{", "return", "this", ".", "isFresh", ";", "}", "public", "void", "setIsFresh", "(", "Boolean", "isFresh", ")", "{", "this", ".", "isFresh", "=", "isFresh", ";", "}", "public", "Long", "getStorageSize", "(", ")", "{", "return", "this", ".", "storageSize", ";", "}", "public", "void", "setStorageSize", "(", "Long", "storageSize", ")", "{", "this", ".", "storageSize", "=", "storageSize", ";", "}", "public", "Boolean", "getIsVersioning", "(", ")", "{", "return", "this", ".", "isVersioning", ";", "}", "public", "void", "setIsVersioning", "(", "Boolean", "isVersioning", ")", "{", "this", ".", "isVersioning", "=", "isVersioning", ";", "}", "@", "Override", "public", "DescribeOssBucketInfoResponse", "getInstance", "(", "UnmarshallerContext", "context", ")", "{", "return", "DescribeOssBucketInfoResponseUnmarshaller", ".", "unmarshall", "(", "this", ",", "context", ")", ";", "}", "}" ]
@author auto create @version
[ "@author", "auto", "create", "@version" ]
[]
[ { "param": "AcsResponse", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AcsResponse", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
46cc2b3fd484b46c7497130f47a838cf6b058c9c
dylPeters15/voogasalad_noplacelikehome
src/frontend/factory/wizard/strategies/wizard_pages/util/SelectableInputRow.java
[ "MIT" ]
Java
SelectableInputRow
/** * SelectableInputRow extends the BaseUIManager and is a UI structure used in * the creation of many wizard pages used to create objects, that allows the * user to select items with check boxes * * @author Andreas * */
SelectableInputRow extends the BaseUIManager and is a UI structure used in the creation of many wizard pages used to create objects, that allows the user to select items with check boxes @author Andreas
[ "SelectableInputRow", "extends", "the", "BaseUIManager", "and", "is", "a", "UI", "structure", "used", "in", "the", "creation", "of", "many", "wizard", "pages", "used", "to", "create", "objects", "that", "allows", "the", "user", "to", "select", "items", "with", "check", "boxes", "@author", "Andreas" ]
public class SelectableInputRow extends BaseUIManager<Region> { HBox hbox; CheckBox checkbox; ImageView icon; Label name; Label description; /** * Creates a new instance of SelectableInputRow with no image, name, or * description. */ public SelectableInputRow() { this(null, null, null); } /** * Creates a new instance of selectableInput with the given image, name, and * description. * * @param image * the image to use as the icon for the row. * @param name * the name/title of the row. * @param description * the description of the row. */ public SelectableInputRow(Image image, String name, String description) { super(null); hbox = new HBox(); checkbox = new CheckBox(); icon = new ImageView(); this.name = new Label(); this.description = new Label(); setImage(image); setName(name); setDescription(description); hbox.getChildren().addAll(checkbox, icon, this.name, this.description); } /** * Sets the image for the SelectableInputRow to use as an icon. * * @param image * a JavaFX image */ public void setImage(Image image) { icon.setImage(image); if (image != null) { icon.setFitWidth(Double.parseDouble(getResourceBundle().getString("ICON_SIZE"))); icon.setFitHeight(Double.parseDouble(getResourceBundle().getString("ICON_SIZE"))); } } /** * Returns the image displayed in the SelectableInputRow. * * @return the image displayed in the SelectableInputRow. */ public Image getImage() { return icon.getImage(); } /** * Sets the name/title of the SelectableInputRow. * * @param name * the name/title of the SelectableInputRow. */ public void setName(String name) { this.name.setText(name); } /** * Returns the name of the SelectableInputRow. This value will be displayed * to the user. * * @return the name of the SelectableInputRow. */ public String getName() { return name.getText(); } /** * Sets the description of the SelectableInputRow. This value will be * displayed to the user. * * @param description * the description of the SelectableInputRow */ public void setDescription(String description) { this.description.setText(description); } /** * Returns the description of the SelectableInputRow * * @return a string that is the description of the SelectableInputRow. */ public String getDescription() { return description.getText(); } @Override public Region getNode() { return hbox; } /** * Returns a BooleanProperty containing a boolean of whether the row is * selected. * * @return a BooleanProperty containing a boolean of whether the row is * selected. */ public BooleanProperty getSelectedProperty() { return checkbox.selectedProperty(); } /** * Returns a boolean of whether the row is selected. * * @return a boolean of whether the row is selected. */ public boolean getSelected() { return checkbox.isSelected(); } /** * Sets the row's selected property to the specified boolean. * * @param selected * the value to set the selected property to. */ public void setSelected(boolean selected) { checkbox.setSelected(selected); } }
[ "public", "class", "SelectableInputRow", "extends", "BaseUIManager", "<", "Region", ">", "{", "HBox", "hbox", ";", "CheckBox", "checkbox", ";", "ImageView", "icon", ";", "Label", "name", ";", "Label", "description", ";", "/**\n\t * Creates a new instance of SelectableInputRow with no image, name, or\n\t * description.\n\t */", "public", "SelectableInputRow", "(", ")", "{", "this", "(", "null", ",", "null", ",", "null", ")", ";", "}", "/**\n\t * Creates a new instance of selectableInput with the given image, name, and\n\t * description.\n\t * \n\t * @param image\n\t * the image to use as the icon for the row.\n\t * @param name\n\t * the name/title of the row.\n\t * @param description\n\t * the description of the row.\n\t */", "public", "SelectableInputRow", "(", "Image", "image", ",", "String", "name", ",", "String", "description", ")", "{", "super", "(", "null", ")", ";", "hbox", "=", "new", "HBox", "(", ")", ";", "checkbox", "=", "new", "CheckBox", "(", ")", ";", "icon", "=", "new", "ImageView", "(", ")", ";", "this", ".", "name", "=", "new", "Label", "(", ")", ";", "this", ".", "description", "=", "new", "Label", "(", ")", ";", "setImage", "(", "image", ")", ";", "setName", "(", "name", ")", ";", "setDescription", "(", "description", ")", ";", "hbox", ".", "getChildren", "(", ")", ".", "addAll", "(", "checkbox", ",", "icon", ",", "this", ".", "name", ",", "this", ".", "description", ")", ";", "}", "/**\n\t * Sets the image for the SelectableInputRow to use as an icon.\n\t * \n\t * @param image\n\t * a JavaFX image\n\t */", "public", "void", "setImage", "(", "Image", "image", ")", "{", "icon", ".", "setImage", "(", "image", ")", ";", "if", "(", "image", "!=", "null", ")", "{", "icon", ".", "setFitWidth", "(", "Double", ".", "parseDouble", "(", "getResourceBundle", "(", ")", ".", "getString", "(", "\"", "ICON_SIZE", "\"", ")", ")", ")", ";", "icon", ".", "setFitHeight", "(", "Double", ".", "parseDouble", "(", "getResourceBundle", "(", ")", ".", "getString", "(", "\"", "ICON_SIZE", "\"", ")", ")", ")", ";", "}", "}", "/**\n\t * Returns the image displayed in the SelectableInputRow.\n\t * \n\t * @return the image displayed in the SelectableInputRow.\n\t */", "public", "Image", "getImage", "(", ")", "{", "return", "icon", ".", "getImage", "(", ")", ";", "}", "/**\n\t * Sets the name/title of the SelectableInputRow.\n\t * \n\t * @param name\n\t * the name/title of the SelectableInputRow.\n\t */", "public", "void", "setName", "(", "String", "name", ")", "{", "this", ".", "name", ".", "setText", "(", "name", ")", ";", "}", "/**\n\t * Returns the name of the SelectableInputRow. This value will be displayed\n\t * to the user.\n\t * \n\t * @return the name of the SelectableInputRow.\n\t */", "public", "String", "getName", "(", ")", "{", "return", "name", ".", "getText", "(", ")", ";", "}", "/**\n\t * Sets the description of the SelectableInputRow. This value will be\n\t * displayed to the user.\n\t * \n\t * @param description\n\t * the description of the SelectableInputRow\n\t */", "public", "void", "setDescription", "(", "String", "description", ")", "{", "this", ".", "description", ".", "setText", "(", "description", ")", ";", "}", "/**\n\t * Returns the description of the SelectableInputRow\n\t * \n\t * @return a string that is the description of the SelectableInputRow.\n\t */", "public", "String", "getDescription", "(", ")", "{", "return", "description", ".", "getText", "(", ")", ";", "}", "@", "Override", "public", "Region", "getNode", "(", ")", "{", "return", "hbox", ";", "}", "/**\n\t * Returns a BooleanProperty containing a boolean of whether the row is\n\t * selected.\n\t * \n\t * @return a BooleanProperty containing a boolean of whether the row is\n\t * selected.\n\t */", "public", "BooleanProperty", "getSelectedProperty", "(", ")", "{", "return", "checkbox", ".", "selectedProperty", "(", ")", ";", "}", "/**\n\t * Returns a boolean of whether the row is selected.\n\t * \n\t * @return a boolean of whether the row is selected.\n\t */", "public", "boolean", "getSelected", "(", ")", "{", "return", "checkbox", ".", "isSelected", "(", ")", ";", "}", "/**\n\t * Sets the row's selected property to the specified boolean.\n\t * \n\t * @param selected\n\t * the value to set the selected property to.\n\t */", "public", "void", "setSelected", "(", "boolean", "selected", ")", "{", "checkbox", ".", "setSelected", "(", "selected", ")", ";", "}", "}" ]
SelectableInputRow extends the BaseUIManager and is a UI structure used in the creation of many wizard pages used to create objects, that allows the user to select items with check boxes
[ "SelectableInputRow", "extends", "the", "BaseUIManager", "and", "is", "a", "UI", "structure", "used", "in", "the", "creation", "of", "many", "wizard", "pages", "used", "to", "create", "objects", "that", "allows", "the", "user", "to", "select", "items", "with", "check", "boxes" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
46d875e74784075c67b1dabf1b3d3b77d4426125
takanori-ugai/smile
core/src/main/java/smile/feature/WinsorScaler.java
[ "Apache-2.0" ]
Java
WinsorScaler
/** * Scales all numeric variables into the range [0, 1]. * If the dataset has outliers, normalization will certainly scale * the "normal" data to a very small interval. In this case, the * Winsorization procedure should be applied: values greater than the * specified upper limit are replaced with the upper limit, and those * below the lower limit are replace with the lower limit. Often, the * specified range is indicate in terms of percentiles of the original * distribution (like the 5th and 95th percentile). * * @author Haifeng Li */
Scales all numeric variables into the range [0, 1]. If the dataset has outliers, normalization will certainly scale the "normal" data to a very small interval. In this case, the Winsorization procedure should be applied: values greater than the specified upper limit are replaced with the upper limit, and those below the lower limit are replace with the lower limit. Often, the specified range is indicate in terms of percentiles of the original distribution (like the 5th and 95th percentile). @author Haifeng Li
[ "Scales", "all", "numeric", "variables", "into", "the", "range", "[", "0", "1", "]", ".", "If", "the", "dataset", "has", "outliers", "normalization", "will", "certainly", "scale", "the", "\"", "normal", "\"", "data", "to", "a", "very", "small", "interval", ".", "In", "this", "case", "the", "Winsorization", "procedure", "should", "be", "applied", ":", "values", "greater", "than", "the", "specified", "upper", "limit", "are", "replaced", "with", "the", "upper", "limit", "and", "those", "below", "the", "lower", "limit", "are", "replace", "with", "the", "lower", "limit", ".", "Often", "the", "specified", "range", "is", "indicate", "in", "terms", "of", "percentiles", "of", "the", "original", "distribution", "(", "like", "the", "5th", "and", "95th", "percentile", ")", ".", "@author", "Haifeng", "Li" ]
public class WinsorScaler extends Scaler { private static final long serialVersionUID = 2L; /** * Constructor. * @param lo the lower bound. * @param hi the upper bound. */ public WinsorScaler(double[] lo, double[] hi) { super(lo, hi); } /** * Constructor. * @param schema the schema of data. * @param lo the lower bound. * @param hi the upper bound. */ public WinsorScaler(StructType schema, double[] lo, double[] hi) { super(schema, lo, hi); } /** * Fits the transformation parameters with 5% lower limit and 95% upper limit. * @param data The training data. * @return the model. */ public static WinsorScaler fit(DataFrame data) { return fit(data, 0.05, 0.95); } /** * Fits the transformation parameters. * @param data The training data. * @param lower the lower limit in terms of percentiles of the original * distribution (e.g. 5th percentile). * @param upper the upper limit in terms of percentiles of the original * distribution (e.g. 95th percentile). * @return the model. */ public static WinsorScaler fit(DataFrame data, double lower, double upper) { if (data.isEmpty()) { throw new IllegalArgumentException("Empty data frame"); } if (lower < 0.0 || lower > 0.5) { throw new IllegalArgumentException("Invalid lower limit: " + lower); } if (upper < 0.5 || upper > 1.0) { throw new IllegalArgumentException("Invalid upper limit: " + upper); } if (upper <= lower) { throw new IllegalArgumentException("Invalid lower and upper limit pair: " + lower + " >= " + upper); } StructType schema = data.schema(); int p = schema.length(); double[] lo = new double[p]; double[] hi = new double[p]; for (int i = 0; i < p; i++) { if (schema.field(i).isNumeric()) { IQAgent agent = new IQAgent(); double[] x = data.column(i).toDoubleArray(); for (double xi : x) { agent.add(xi); } lo[i] = agent.quantile(lower); hi[i] = agent.quantile(upper); } } return new WinsorScaler(schema, lo, hi); } /** * Fits the transformation parameters with 5% lower limit and 95% upper limit. * @param data The training data. * @return the model. */ public static WinsorScaler fit(double[][] data) { return fit(data, 0.05, 0.95); } /** * Fits the transformation parameters. * @param data The training data. * @param lower the lower limit in terms of percentiles of the original * distribution (say 5th percentile). * @param upper the upper limit in terms of percentiles of the original * distribution (say 95th percentile). * @return the model. */ public static WinsorScaler fit(double[][] data, double lower, double upper) { int p = data[0].length; double[] lo = new double[p]; double[] hi = new double[p]; IQAgent[] agents = new IQAgent[p]; for (int i = 0; i < p; i++) { agents[i] = new IQAgent(); } for (double[] x : data) { for (int i = 0; i < p; i++) { agents[i].add(x[i]); } } for (int i = 0; i < p; i++) { IQAgent agent = agents[i]; lo[i] = agent.quantile(lower); hi[i] = agent.quantile(upper); } return new WinsorScaler(lo, hi); } }
[ "public", "class", "WinsorScaler", "extends", "Scaler", "{", "private", "static", "final", "long", "serialVersionUID", "=", "2L", ";", "/**\n * Constructor.\n * @param lo the lower bound.\n * @param hi the upper bound.\n */", "public", "WinsorScaler", "(", "double", "[", "]", "lo", ",", "double", "[", "]", "hi", ")", "{", "super", "(", "lo", ",", "hi", ")", ";", "}", "/**\n * Constructor.\n * @param schema the schema of data.\n * @param lo the lower bound.\n * @param hi the upper bound.\n */", "public", "WinsorScaler", "(", "StructType", "schema", ",", "double", "[", "]", "lo", ",", "double", "[", "]", "hi", ")", "{", "super", "(", "schema", ",", "lo", ",", "hi", ")", ";", "}", "/**\n * Fits the transformation parameters with 5% lower limit and 95% upper limit.\n * @param data The training data.\n * @return the model.\n */", "public", "static", "WinsorScaler", "fit", "(", "DataFrame", "data", ")", "{", "return", "fit", "(", "data", ",", "0.05", ",", "0.95", ")", ";", "}", "/**\n * Fits the transformation parameters.\n * @param data The training data.\n * @param lower the lower limit in terms of percentiles of the original\n * distribution (e.g. 5th percentile).\n * @param upper the upper limit in terms of percentiles of the original\n * distribution (e.g. 95th percentile).\n * @return the model.\n */", "public", "static", "WinsorScaler", "fit", "(", "DataFrame", "data", ",", "double", "lower", ",", "double", "upper", ")", "{", "if", "(", "data", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Empty data frame", "\"", ")", ";", "}", "if", "(", "lower", "<", "0.0", "||", "lower", ">", "0.5", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Invalid lower limit: ", "\"", "+", "lower", ")", ";", "}", "if", "(", "upper", "<", "0.5", "||", "upper", ">", "1.0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Invalid upper limit: ", "\"", "+", "upper", ")", ";", "}", "if", "(", "upper", "<=", "lower", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Invalid lower and upper limit pair: ", "\"", "+", "lower", "+", "\"", " >= ", "\"", "+", "upper", ")", ";", "}", "StructType", "schema", "=", "data", ".", "schema", "(", ")", ";", "int", "p", "=", "schema", ".", "length", "(", ")", ";", "double", "[", "]", "lo", "=", "new", "double", "[", "p", "]", ";", "double", "[", "]", "hi", "=", "new", "double", "[", "p", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "p", ";", "i", "++", ")", "{", "if", "(", "schema", ".", "field", "(", "i", ")", ".", "isNumeric", "(", ")", ")", "{", "IQAgent", "agent", "=", "new", "IQAgent", "(", ")", ";", "double", "[", "]", "x", "=", "data", ".", "column", "(", "i", ")", ".", "toDoubleArray", "(", ")", ";", "for", "(", "double", "xi", ":", "x", ")", "{", "agent", ".", "add", "(", "xi", ")", ";", "}", "lo", "[", "i", "]", "=", "agent", ".", "quantile", "(", "lower", ")", ";", "hi", "[", "i", "]", "=", "agent", ".", "quantile", "(", "upper", ")", ";", "}", "}", "return", "new", "WinsorScaler", "(", "schema", ",", "lo", ",", "hi", ")", ";", "}", "/**\n * Fits the transformation parameters with 5% lower limit and 95% upper limit.\n * @param data The training data.\n * @return the model.\n */", "public", "static", "WinsorScaler", "fit", "(", "double", "[", "]", "[", "]", "data", ")", "{", "return", "fit", "(", "data", ",", "0.05", ",", "0.95", ")", ";", "}", "/**\n * Fits the transformation parameters.\n * @param data The training data.\n * @param lower the lower limit in terms of percentiles of the original\n * distribution (say 5th percentile).\n * @param upper the upper limit in terms of percentiles of the original\n * distribution (say 95th percentile).\n * @return the model.\n */", "public", "static", "WinsorScaler", "fit", "(", "double", "[", "]", "[", "]", "data", ",", "double", "lower", ",", "double", "upper", ")", "{", "int", "p", "=", "data", "[", "0", "]", ".", "length", ";", "double", "[", "]", "lo", "=", "new", "double", "[", "p", "]", ";", "double", "[", "]", "hi", "=", "new", "double", "[", "p", "]", ";", "IQAgent", "[", "]", "agents", "=", "new", "IQAgent", "[", "p", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "p", ";", "i", "++", ")", "{", "agents", "[", "i", "]", "=", "new", "IQAgent", "(", ")", ";", "}", "for", "(", "double", "[", "]", "x", ":", "data", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "p", ";", "i", "++", ")", "{", "agents", "[", "i", "]", ".", "add", "(", "x", "[", "i", "]", ")", ";", "}", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "p", ";", "i", "++", ")", "{", "IQAgent", "agent", "=", "agents", "[", "i", "]", ";", "lo", "[", "i", "]", "=", "agent", ".", "quantile", "(", "lower", ")", ";", "hi", "[", "i", "]", "=", "agent", ".", "quantile", "(", "upper", ")", ";", "}", "return", "new", "WinsorScaler", "(", "lo", ",", "hi", ")", ";", "}", "}" ]
Scales all numeric variables into the range [0, 1].
[ "Scales", "all", "numeric", "variables", "into", "the", "range", "[", "0", "1", "]", "." ]
[]
[ { "param": "Scaler", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Scaler", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
46dc72ef927ae1be3f8c24790b5d0e392604b46c
simon-greatrix/prng
core/src/main/java/prng/NoOpLogger.java
[ "MIT" ]
Java
NoOpLogger
/** * A logger with everything permanently turned off. * * @author Simon Greatrix on 25/10/2019. */
A logger with everything permanently turned off.
[ "A", "logger", "with", "everything", "permanently", "turned", "off", "." ]
public class NoOpLogger implements Logger { private final String name; public NoOpLogger(Class<?> type) { name = type.getName(); } @Override public void debug(String msg) { // do nothing } @Override public void debug(String format, Object arg) { // do nothing } @Override public void debug(String format, Object arg1, Object arg2) { // do nothing } @Override public void debug(String format, Object... arguments) { // do nothing } @Override public void debug(String msg, Throwable t) { // do nothing } @Override public void debug(Marker marker, String msg) { // do nothing } @Override public void debug(Marker marker, String format, Object arg) { // do nothing } @Override public void debug(Marker marker, String format, Object arg1, Object arg2) { // do nothing } @Override public void debug(Marker marker, String format, Object... arguments) { // do nothing } @Override public void debug(Marker marker, String msg, Throwable t) { // do nothing } @Override public void error(String msg) { // do nothing } @Override public void error(String format, Object arg) { // do nothing } @Override public void error(String format, Object arg1, Object arg2) { // do nothing } @Override public void error(String format, Object... arguments) { // do nothing } @Override public void error(String msg, Throwable t) { // do nothing } @Override public void error(Marker marker, String msg) { // do nothing } @Override public void error(Marker marker, String format, Object arg) { // do nothing } @Override public void error(Marker marker, String format, Object arg1, Object arg2) { // do nothing } @Override public void error(Marker marker, String format, Object... arguments) { // do nothing } @Override public void error(Marker marker, String msg, Throwable t) { // do nothing } @Override public String getName() { return name; } @Override public void info(String msg) { // do nothing } @Override public void info(String format, Object arg) { // do nothing } @Override public void info(String format, Object arg1, Object arg2) { // do nothing } @Override public void info(String format, Object... arguments) { // do nothing } @Override public void info(String msg, Throwable t) { // do nothing } @Override public void info(Marker marker, String msg) { // do nothing } @Override public void info(Marker marker, String format, Object arg) { // do nothing } @Override public void info(Marker marker, String format, Object arg1, Object arg2) { // do nothing } @Override public void info(Marker marker, String format, Object... arguments) { // do nothing } @Override public void info(Marker marker, String msg, Throwable t) { // do nothing } @Override public boolean isDebugEnabled() { return false; } @Override public boolean isDebugEnabled(Marker marker) { return false; } @Override public boolean isErrorEnabled() { return false; } @Override public boolean isErrorEnabled(Marker marker) { return false; } @Override public boolean isInfoEnabled() { return false; } @Override public boolean isInfoEnabled(Marker marker) { return false; } @Override public boolean isTraceEnabled() { return false; } @Override public boolean isTraceEnabled(Marker marker) { return false; } @Override public boolean isWarnEnabled() { return false; } @Override public boolean isWarnEnabled(Marker marker) { return false; } @Override public void trace(String msg) { // do nothing } @Override public void trace(String format, Object arg) { // do nothing } @Override public void trace(String format, Object arg1, Object arg2) { // do nothing } @Override public void trace(String format, Object... arguments) { // do nothing } @Override public void trace(String msg, Throwable t) { // do nothing } @Override public void trace(Marker marker, String msg) { // do nothing } @Override public void trace(Marker marker, String format, Object arg) { // do nothing } @Override public void trace(Marker marker, String format, Object arg1, Object arg2) { // do nothing } @Override public void trace(Marker marker, String format, Object... argArray) { // do nothing } @Override public void trace(Marker marker, String msg, Throwable t) { // do nothing } @Override public void warn(String msg) { // do nothing } @Override public void warn(String format, Object arg) { // do nothing } @Override public void warn(String format, Object... arguments) { // do nothing } @Override public void warn(String format, Object arg1, Object arg2) { // do nothing } @Override public void warn(String msg, Throwable t) { // do nothing } @Override public void warn(Marker marker, String msg) { // do nothing } @Override public void warn(Marker marker, String format, Object arg) { // do nothing } @Override public void warn(Marker marker, String format, Object arg1, Object arg2) { // do nothing } @Override public void warn(Marker marker, String format, Object... arguments) { // do nothing } @Override public void warn(Marker marker, String msg, Throwable t) { // do nothing } }
[ "public", "class", "NoOpLogger", "implements", "Logger", "{", "private", "final", "String", "name", ";", "public", "NoOpLogger", "(", "Class", "<", "?", ">", "type", ")", "{", "name", "=", "type", ".", "getName", "(", ")", ";", "}", "@", "Override", "public", "void", "debug", "(", "String", "msg", ")", "{", "}", "@", "Override", "public", "void", "debug", "(", "String", "format", ",", "Object", "arg", ")", "{", "}", "@", "Override", "public", "void", "debug", "(", "String", "format", ",", "Object", "arg1", ",", "Object", "arg2", ")", "{", "}", "@", "Override", "public", "void", "debug", "(", "String", "format", ",", "Object", "...", "arguments", ")", "{", "}", "@", "Override", "public", "void", "debug", "(", "String", "msg", ",", "Throwable", "t", ")", "{", "}", "@", "Override", "public", "void", "debug", "(", "Marker", "marker", ",", "String", "msg", ")", "{", "}", "@", "Override", "public", "void", "debug", "(", "Marker", "marker", ",", "String", "format", ",", "Object", "arg", ")", "{", "}", "@", "Override", "public", "void", "debug", "(", "Marker", "marker", ",", "String", "format", ",", "Object", "arg1", ",", "Object", "arg2", ")", "{", "}", "@", "Override", "public", "void", "debug", "(", "Marker", "marker", ",", "String", "format", ",", "Object", "...", "arguments", ")", "{", "}", "@", "Override", "public", "void", "debug", "(", "Marker", "marker", ",", "String", "msg", ",", "Throwable", "t", ")", "{", "}", "@", "Override", "public", "void", "error", "(", "String", "msg", ")", "{", "}", "@", "Override", "public", "void", "error", "(", "String", "format", ",", "Object", "arg", ")", "{", "}", "@", "Override", "public", "void", "error", "(", "String", "format", ",", "Object", "arg1", ",", "Object", "arg2", ")", "{", "}", "@", "Override", "public", "void", "error", "(", "String", "format", ",", "Object", "...", "arguments", ")", "{", "}", "@", "Override", "public", "void", "error", "(", "String", "msg", ",", "Throwable", "t", ")", "{", "}", "@", "Override", "public", "void", "error", "(", "Marker", "marker", ",", "String", "msg", ")", "{", "}", "@", "Override", "public", "void", "error", "(", "Marker", "marker", ",", "String", "format", ",", "Object", "arg", ")", "{", "}", "@", "Override", "public", "void", "error", "(", "Marker", "marker", ",", "String", "format", ",", "Object", "arg1", ",", "Object", "arg2", ")", "{", "}", "@", "Override", "public", "void", "error", "(", "Marker", "marker", ",", "String", "format", ",", "Object", "...", "arguments", ")", "{", "}", "@", "Override", "public", "void", "error", "(", "Marker", "marker", ",", "String", "msg", ",", "Throwable", "t", ")", "{", "}", "@", "Override", "public", "String", "getName", "(", ")", "{", "return", "name", ";", "}", "@", "Override", "public", "void", "info", "(", "String", "msg", ")", "{", "}", "@", "Override", "public", "void", "info", "(", "String", "format", ",", "Object", "arg", ")", "{", "}", "@", "Override", "public", "void", "info", "(", "String", "format", ",", "Object", "arg1", ",", "Object", "arg2", ")", "{", "}", "@", "Override", "public", "void", "info", "(", "String", "format", ",", "Object", "...", "arguments", ")", "{", "}", "@", "Override", "public", "void", "info", "(", "String", "msg", ",", "Throwable", "t", ")", "{", "}", "@", "Override", "public", "void", "info", "(", "Marker", "marker", ",", "String", "msg", ")", "{", "}", "@", "Override", "public", "void", "info", "(", "Marker", "marker", ",", "String", "format", ",", "Object", "arg", ")", "{", "}", "@", "Override", "public", "void", "info", "(", "Marker", "marker", ",", "String", "format", ",", "Object", "arg1", ",", "Object", "arg2", ")", "{", "}", "@", "Override", "public", "void", "info", "(", "Marker", "marker", ",", "String", "format", ",", "Object", "...", "arguments", ")", "{", "}", "@", "Override", "public", "void", "info", "(", "Marker", "marker", ",", "String", "msg", ",", "Throwable", "t", ")", "{", "}", "@", "Override", "public", "boolean", "isDebugEnabled", "(", ")", "{", "return", "false", ";", "}", "@", "Override", "public", "boolean", "isDebugEnabled", "(", "Marker", "marker", ")", "{", "return", "false", ";", "}", "@", "Override", "public", "boolean", "isErrorEnabled", "(", ")", "{", "return", "false", ";", "}", "@", "Override", "public", "boolean", "isErrorEnabled", "(", "Marker", "marker", ")", "{", "return", "false", ";", "}", "@", "Override", "public", "boolean", "isInfoEnabled", "(", ")", "{", "return", "false", ";", "}", "@", "Override", "public", "boolean", "isInfoEnabled", "(", "Marker", "marker", ")", "{", "return", "false", ";", "}", "@", "Override", "public", "boolean", "isTraceEnabled", "(", ")", "{", "return", "false", ";", "}", "@", "Override", "public", "boolean", "isTraceEnabled", "(", "Marker", "marker", ")", "{", "return", "false", ";", "}", "@", "Override", "public", "boolean", "isWarnEnabled", "(", ")", "{", "return", "false", ";", "}", "@", "Override", "public", "boolean", "isWarnEnabled", "(", "Marker", "marker", ")", "{", "return", "false", ";", "}", "@", "Override", "public", "void", "trace", "(", "String", "msg", ")", "{", "}", "@", "Override", "public", "void", "trace", "(", "String", "format", ",", "Object", "arg", ")", "{", "}", "@", "Override", "public", "void", "trace", "(", "String", "format", ",", "Object", "arg1", ",", "Object", "arg2", ")", "{", "}", "@", "Override", "public", "void", "trace", "(", "String", "format", ",", "Object", "...", "arguments", ")", "{", "}", "@", "Override", "public", "void", "trace", "(", "String", "msg", ",", "Throwable", "t", ")", "{", "}", "@", "Override", "public", "void", "trace", "(", "Marker", "marker", ",", "String", "msg", ")", "{", "}", "@", "Override", "public", "void", "trace", "(", "Marker", "marker", ",", "String", "format", ",", "Object", "arg", ")", "{", "}", "@", "Override", "public", "void", "trace", "(", "Marker", "marker", ",", "String", "format", ",", "Object", "arg1", ",", "Object", "arg2", ")", "{", "}", "@", "Override", "public", "void", "trace", "(", "Marker", "marker", ",", "String", "format", ",", "Object", "...", "argArray", ")", "{", "}", "@", "Override", "public", "void", "trace", "(", "Marker", "marker", ",", "String", "msg", ",", "Throwable", "t", ")", "{", "}", "@", "Override", "public", "void", "warn", "(", "String", "msg", ")", "{", "}", "@", "Override", "public", "void", "warn", "(", "String", "format", ",", "Object", "arg", ")", "{", "}", "@", "Override", "public", "void", "warn", "(", "String", "format", ",", "Object", "...", "arguments", ")", "{", "}", "@", "Override", "public", "void", "warn", "(", "String", "format", ",", "Object", "arg1", ",", "Object", "arg2", ")", "{", "}", "@", "Override", "public", "void", "warn", "(", "String", "msg", ",", "Throwable", "t", ")", "{", "}", "@", "Override", "public", "void", "warn", "(", "Marker", "marker", ",", "String", "msg", ")", "{", "}", "@", "Override", "public", "void", "warn", "(", "Marker", "marker", ",", "String", "format", ",", "Object", "arg", ")", "{", "}", "@", "Override", "public", "void", "warn", "(", "Marker", "marker", ",", "String", "format", ",", "Object", "arg1", ",", "Object", "arg2", ")", "{", "}", "@", "Override", "public", "void", "warn", "(", "Marker", "marker", ",", "String", "format", ",", "Object", "...", "arguments", ")", "{", "}", "@", "Override", "public", "void", "warn", "(", "Marker", "marker", ",", "String", "msg", ",", "Throwable", "t", ")", "{", "}", "}" ]
A logger with everything permanently turned off.
[ "A", "logger", "with", "everything", "permanently", "turned", "off", "." ]
[ "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing", "// do nothing" ]
[ { "param": "Logger", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Logger", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
46de480ec99368c346462db9ce7e7a4b238c72da
pkumar-singh/bookkeeper
stream/proto/src/main/java/org/apache/bookkeeper/stream/protocol/util/ProtoUtils.java
[ "Apache-2.0" ]
Java
ProtoUtils
/** * Protocol related utils. */
Protocol related utils.
[ "Protocol", "related", "utils", "." ]
public class ProtoUtils { /** * Check if two key ranges overlaps with each other. * * @param meta1 first key range * @param meta2 second key range * @return true if two key ranges overlaps */ public static boolean keyRangeOverlaps(RangeProperties meta1, RangeProperties meta2) { return keyRangeOverlaps( meta1.getStartHashKey(), meta1.getEndHashKey(), meta2.getStartHashKey(), meta2.getEndHashKey()); } public static boolean keyRangeOverlaps(Pair<Long, Long> range1, Pair<Long, Long> range2) { return keyRangeOverlaps(range1.getLeft(), range1.getRight(), range2.getLeft(), range2.getRight()); } public static boolean keyRangeOverlaps(RangeProperties range1, Pair<Long, Long> range2) { return keyRangeOverlaps(range1.getStartHashKey(), range1.getEndHashKey(), range2.getLeft(), range2.getRight()); } public static boolean keyRangeOverlaps(Pair<Long, Long> range1, RangeProperties range2) { return keyRangeOverlaps(range1.getLeft(), range1.getRight(), range2.getStartHashKey(), range2.getEndHashKey()); } static boolean keyRangeOverlaps(long startKey1, long endKey1, long startKey2, long endKey2) { return endKey2 > startKey1 && startKey2 < endKey1; } /** * Validate namespace name. * * @return true if it is a valid namespace name. otherwise false. */ public static boolean validateNamespaceName(String name) { return validateStreamName(name); } /** * Validate stream name. * * <p>follow the rules that dlog uses for validating stream name. * * @return true if it is a valid namespace name. otherwise false. */ public static boolean validateStreamName(String name) { if (Strings.isNullOrEmpty(name)) { return false; } for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (c == 0 || c == ' ' || c == '<' || c == '>' || c > '\u0000' && c < '\u001f' || c > '\u007f' && c < '\u009f' || c > '\ud800' && c < '\uf8ff' || c > '\ufff0' && c < '\uffff') { return false; } } return true; } public static List<RangeProperties> split(long streamId, int numInitialRanges, long nextRangeId, StorageContainerPlacementPolicy placementPolicy) { int numRanges = Math.max(2, numInitialRanges); if (numRanges % 2 != 0) { // round up to odd number numRanges = numRanges + 1; } long rangeSize = Long.MAX_VALUE / (numRanges / 2); long startKey = Long.MIN_VALUE; List<RangeProperties> ranges = Lists.newArrayListWithExpectedSize(numRanges); for (int idx = 0; idx < numRanges; ++idx) { long endKey = startKey + rangeSize; if (numRanges - 1 == idx) { endKey = Long.MAX_VALUE; } long rangeId = nextRangeId++; RangeProperties props = RangeProperties.newBuilder() .setStartHashKey(startKey) .setEndHashKey(endKey) .setStorageContainerId(placementPolicy.placeStreamRange(streamId, rangeId)) .setRangeId(rangeId) .build(); startKey = endKey; ranges.add(props); } return ranges; } /** * Check if the stream is created. * * @param state stream state * @return true if the stream is in created state. otherwise, false. */ public static boolean isStreamCreated(LifecycleState state) { checkArgument(state != LifecycleState.UNRECOGNIZED); return LifecycleState.UNINIT != state && LifecycleState.CREATING != state; } /** * Check if the stream is writable. * * @param state stream state * @return true if the stream is writable. otherwise, false. */ public static boolean isStreamWritable(ServingState state) { checkArgument(state != ServingState.UNRECOGNIZED); return ServingState.WRITABLE == state; } // // Location API // /** * Create a {@link GetStorageContainerEndpointRequest}. * * @param storageContainers list of storage containers * @return a get storage container endpoint request. */ public static GetStorageContainerEndpointRequest createGetStorageContainerEndpointRequest( List<Revisioned<Long>> storageContainers) { GetStorageContainerEndpointRequest.Builder builder = GetStorageContainerEndpointRequest.newBuilder(); for (Revisioned<Long> storageContainer : storageContainers) { builder.addRequests( OneStorageContainerEndpointRequest.newBuilder() .setStorageContainer(storageContainer.getValue()) .setRevision(storageContainer.getRevision())); } return builder.build(); } /** * Create a {@link GetStorageContainerEndpointResponse}. * * @param endpoints list of storage container endpoints * @return a get storage container endpoint response. */ public static GetStorageContainerEndpointResponse createGetStorageContainerEndpointResponse( List<StorageContainerEndpoint> endpoints) { GetStorageContainerEndpointResponse.Builder builder = GetStorageContainerEndpointResponse.newBuilder(); builder.setStatusCode(StatusCode.SUCCESS); for (StorageContainerEndpoint endpoint : endpoints) { builder.addResponses( OneStorageContainerEndpointResponse.newBuilder() .setStatusCode(StatusCode.SUCCESS) .setEndpoint(endpoint)); } return builder.build(); } // // Meta Range API // public static GetActiveRangesRequest createGetActiveRangesRequest(long streamId) { return GetActiveRangesRequest.newBuilder() .setStreamId(streamId) .build(); } public static GetActiveRangesRequest createGetActiveRangesRequest(StreamProperties streamProps) { return GetActiveRangesRequest.newBuilder() .setStreamId(streamProps.getStreamId()) .setStreamProps(streamProps) .build(); } // // Namespace API // /** * Create a {@link CreateNamespaceRequest}. * * @param nsName namespace name * @param nsConf namespace conf * @return a create namespace request. */ public static CreateNamespaceRequest createCreateNamespaceRequest(String nsName, NamespaceConfiguration nsConf) { return CreateNamespaceRequest.newBuilder() .setName(nsName) .setNsConf(nsConf) .build(); } /** * Create a {@link DeleteNamespaceRequest}. * * @param colName namespace name * @return a delete namespace request. */ public static DeleteNamespaceRequest createDeleteNamespaceRequest(String colName) { return DeleteNamespaceRequest.newBuilder() .setName(colName) .build(); } /** * Create a {@link GetNamespaceRequest}. * * @param colName namespace name * @return a get namespace request. */ public static GetNamespaceRequest createGetNamespaceRequest(String colName) { return GetNamespaceRequest.newBuilder() .setName(colName) .build(); } // // Stream API // /** * Create a {@link CreateStreamRequest}. * * @param nsName namespace name * @param streamName stream name * @param streamConf stream configuration * @return a create stream request. */ public static CreateStreamRequest createCreateStreamRequest(String nsName, String streamName, StreamConfiguration streamConf) { return CreateStreamRequest.newBuilder() .setNsName(nsName) .setName(streamName) .setStreamConf(streamConf) .build(); } /** * Create a {@link GetStreamRequest}. * * @param nsName namespace name * @param streamName stream name * @return a create stream request. */ public static GetStreamRequest createGetStreamRequest(String nsName, String streamName) { return GetStreamRequest.newBuilder() .setStreamName(StreamName.newBuilder() .setNamespaceName(nsName) .setStreamName(streamName)) .build(); } /** * Create a {@link GetStreamRequest}. * * @param streamId stream id * @return a create stream request. */ public static GetStreamRequest createGetStreamRequest(long streamId) { return GetStreamRequest.newBuilder() .setStreamId(streamId) .build(); } /** * Create a {@link DeleteStreamRequest}. * * @param nsName namespace name * @param streamName stream name * @return a create stream request. */ public static DeleteStreamRequest createDeleteStreamRequest(String nsName, String streamName) { return DeleteStreamRequest.newBuilder() .setName(streamName) .setNsName(nsName) .build(); } }
[ "public", "class", "ProtoUtils", "{", "/**\n * Check if two key ranges overlaps with each other.\n *\n * @param meta1 first key range\n * @param meta2 second key range\n * @return true if two key ranges overlaps\n */", "public", "static", "boolean", "keyRangeOverlaps", "(", "RangeProperties", "meta1", ",", "RangeProperties", "meta2", ")", "{", "return", "keyRangeOverlaps", "(", "meta1", ".", "getStartHashKey", "(", ")", ",", "meta1", ".", "getEndHashKey", "(", ")", ",", "meta2", ".", "getStartHashKey", "(", ")", ",", "meta2", ".", "getEndHashKey", "(", ")", ")", ";", "}", "public", "static", "boolean", "keyRangeOverlaps", "(", "Pair", "<", "Long", ",", "Long", ">", "range1", ",", "Pair", "<", "Long", ",", "Long", ">", "range2", ")", "{", "return", "keyRangeOverlaps", "(", "range1", ".", "getLeft", "(", ")", ",", "range1", ".", "getRight", "(", ")", ",", "range2", ".", "getLeft", "(", ")", ",", "range2", ".", "getRight", "(", ")", ")", ";", "}", "public", "static", "boolean", "keyRangeOverlaps", "(", "RangeProperties", "range1", ",", "Pair", "<", "Long", ",", "Long", ">", "range2", ")", "{", "return", "keyRangeOverlaps", "(", "range1", ".", "getStartHashKey", "(", ")", ",", "range1", ".", "getEndHashKey", "(", ")", ",", "range2", ".", "getLeft", "(", ")", ",", "range2", ".", "getRight", "(", ")", ")", ";", "}", "public", "static", "boolean", "keyRangeOverlaps", "(", "Pair", "<", "Long", ",", "Long", ">", "range1", ",", "RangeProperties", "range2", ")", "{", "return", "keyRangeOverlaps", "(", "range1", ".", "getLeft", "(", ")", ",", "range1", ".", "getRight", "(", ")", ",", "range2", ".", "getStartHashKey", "(", ")", ",", "range2", ".", "getEndHashKey", "(", ")", ")", ";", "}", "static", "boolean", "keyRangeOverlaps", "(", "long", "startKey1", ",", "long", "endKey1", ",", "long", "startKey2", ",", "long", "endKey2", ")", "{", "return", "endKey2", ">", "startKey1", "&&", "startKey2", "<", "endKey1", ";", "}", "/**\n * Validate namespace name.\n *\n * @return true if it is a valid namespace name. otherwise false.\n */", "public", "static", "boolean", "validateNamespaceName", "(", "String", "name", ")", "{", "return", "validateStreamName", "(", "name", ")", ";", "}", "/**\n * Validate stream name.\n *\n * <p>follow the rules that dlog uses for validating stream name.\n *\n * @return true if it is a valid namespace name. otherwise false.\n */", "public", "static", "boolean", "validateStreamName", "(", "String", "name", ")", "{", "if", "(", "Strings", ".", "isNullOrEmpty", "(", "name", ")", ")", "{", "return", "false", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "name", ".", "length", "(", ")", ";", "i", "++", ")", "{", "char", "c", "=", "name", ".", "charAt", "(", "i", ")", ";", "if", "(", "c", "==", "0", "||", "c", "==", "' '", "||", "c", "==", "'<'", "||", "c", "==", "'>'", "||", "c", ">", "'\\u0000'", "&&", "c", "<", "'\\u001f'", "||", "c", ">", "'\\u007f'", "&&", "c", "<", "'\\u009f'", "||", "c", ">", "'\\ud800'", "&&", "c", "<", "'\\uf8ff'", "||", "c", ">", "'\\ufff0'", "&&", "c", "<", "'\\uffff'", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "public", "static", "List", "<", "RangeProperties", ">", "split", "(", "long", "streamId", ",", "int", "numInitialRanges", ",", "long", "nextRangeId", ",", "StorageContainerPlacementPolicy", "placementPolicy", ")", "{", "int", "numRanges", "=", "Math", ".", "max", "(", "2", ",", "numInitialRanges", ")", ";", "if", "(", "numRanges", "%", "2", "!=", "0", ")", "{", "numRanges", "=", "numRanges", "+", "1", ";", "}", "long", "rangeSize", "=", "Long", ".", "MAX_VALUE", "/", "(", "numRanges", "/", "2", ")", ";", "long", "startKey", "=", "Long", ".", "MIN_VALUE", ";", "List", "<", "RangeProperties", ">", "ranges", "=", "Lists", ".", "newArrayListWithExpectedSize", "(", "numRanges", ")", ";", "for", "(", "int", "idx", "=", "0", ";", "idx", "<", "numRanges", ";", "++", "idx", ")", "{", "long", "endKey", "=", "startKey", "+", "rangeSize", ";", "if", "(", "numRanges", "-", "1", "==", "idx", ")", "{", "endKey", "=", "Long", ".", "MAX_VALUE", ";", "}", "long", "rangeId", "=", "nextRangeId", "++", ";", "RangeProperties", "props", "=", "RangeProperties", ".", "newBuilder", "(", ")", ".", "setStartHashKey", "(", "startKey", ")", ".", "setEndHashKey", "(", "endKey", ")", ".", "setStorageContainerId", "(", "placementPolicy", ".", "placeStreamRange", "(", "streamId", ",", "rangeId", ")", ")", ".", "setRangeId", "(", "rangeId", ")", ".", "build", "(", ")", ";", "startKey", "=", "endKey", ";", "ranges", ".", "add", "(", "props", ")", ";", "}", "return", "ranges", ";", "}", "/**\n * Check if the stream is created.\n *\n * @param state stream state\n * @return true if the stream is in created state. otherwise, false.\n */", "public", "static", "boolean", "isStreamCreated", "(", "LifecycleState", "state", ")", "{", "checkArgument", "(", "state", "!=", "LifecycleState", ".", "UNRECOGNIZED", ")", ";", "return", "LifecycleState", ".", "UNINIT", "!=", "state", "&&", "LifecycleState", ".", "CREATING", "!=", "state", ";", "}", "/**\n * Check if the stream is writable.\n *\n * @param state stream state\n * @return true if the stream is writable. otherwise, false.\n */", "public", "static", "boolean", "isStreamWritable", "(", "ServingState", "state", ")", "{", "checkArgument", "(", "state", "!=", "ServingState", ".", "UNRECOGNIZED", ")", ";", "return", "ServingState", ".", "WRITABLE", "==", "state", ";", "}", "/**\n * Create a {@link GetStorageContainerEndpointRequest}.\n *\n * @param storageContainers list of storage containers\n * @return a get storage container endpoint request.\n */", "public", "static", "GetStorageContainerEndpointRequest", "createGetStorageContainerEndpointRequest", "(", "List", "<", "Revisioned", "<", "Long", ">", ">", "storageContainers", ")", "{", "GetStorageContainerEndpointRequest", ".", "Builder", "builder", "=", "GetStorageContainerEndpointRequest", ".", "newBuilder", "(", ")", ";", "for", "(", "Revisioned", "<", "Long", ">", "storageContainer", ":", "storageContainers", ")", "{", "builder", ".", "addRequests", "(", "OneStorageContainerEndpointRequest", ".", "newBuilder", "(", ")", ".", "setStorageContainer", "(", "storageContainer", ".", "getValue", "(", ")", ")", ".", "setRevision", "(", "storageContainer", ".", "getRevision", "(", ")", ")", ")", ";", "}", "return", "builder", ".", "build", "(", ")", ";", "}", "/**\n * Create a {@link GetStorageContainerEndpointResponse}.\n *\n * @param endpoints list of storage container endpoints\n * @return a get storage container endpoint response.\n */", "public", "static", "GetStorageContainerEndpointResponse", "createGetStorageContainerEndpointResponse", "(", "List", "<", "StorageContainerEndpoint", ">", "endpoints", ")", "{", "GetStorageContainerEndpointResponse", ".", "Builder", "builder", "=", "GetStorageContainerEndpointResponse", ".", "newBuilder", "(", ")", ";", "builder", ".", "setStatusCode", "(", "StatusCode", ".", "SUCCESS", ")", ";", "for", "(", "StorageContainerEndpoint", "endpoint", ":", "endpoints", ")", "{", "builder", ".", "addResponses", "(", "OneStorageContainerEndpointResponse", ".", "newBuilder", "(", ")", ".", "setStatusCode", "(", "StatusCode", ".", "SUCCESS", ")", ".", "setEndpoint", "(", "endpoint", ")", ")", ";", "}", "return", "builder", ".", "build", "(", ")", ";", "}", "public", "static", "GetActiveRangesRequest", "createGetActiveRangesRequest", "(", "long", "streamId", ")", "{", "return", "GetActiveRangesRequest", ".", "newBuilder", "(", ")", ".", "setStreamId", "(", "streamId", ")", ".", "build", "(", ")", ";", "}", "public", "static", "GetActiveRangesRequest", "createGetActiveRangesRequest", "(", "StreamProperties", "streamProps", ")", "{", "return", "GetActiveRangesRequest", ".", "newBuilder", "(", ")", ".", "setStreamId", "(", "streamProps", ".", "getStreamId", "(", ")", ")", ".", "setStreamProps", "(", "streamProps", ")", ".", "build", "(", ")", ";", "}", "/**\n * Create a {@link CreateNamespaceRequest}.\n *\n * @param nsName namespace name\n * @param nsConf namespace conf\n * @return a create namespace request.\n */", "public", "static", "CreateNamespaceRequest", "createCreateNamespaceRequest", "(", "String", "nsName", ",", "NamespaceConfiguration", "nsConf", ")", "{", "return", "CreateNamespaceRequest", ".", "newBuilder", "(", ")", ".", "setName", "(", "nsName", ")", ".", "setNsConf", "(", "nsConf", ")", ".", "build", "(", ")", ";", "}", "/**\n * Create a {@link DeleteNamespaceRequest}.\n *\n * @param colName namespace name\n * @return a delete namespace request.\n */", "public", "static", "DeleteNamespaceRequest", "createDeleteNamespaceRequest", "(", "String", "colName", ")", "{", "return", "DeleteNamespaceRequest", ".", "newBuilder", "(", ")", ".", "setName", "(", "colName", ")", ".", "build", "(", ")", ";", "}", "/**\n * Create a {@link GetNamespaceRequest}.\n *\n * @param colName namespace name\n * @return a get namespace request.\n */", "public", "static", "GetNamespaceRequest", "createGetNamespaceRequest", "(", "String", "colName", ")", "{", "return", "GetNamespaceRequest", ".", "newBuilder", "(", ")", ".", "setName", "(", "colName", ")", ".", "build", "(", ")", ";", "}", "/**\n * Create a {@link CreateStreamRequest}.\n *\n * @param nsName namespace name\n * @param streamName stream name\n * @param streamConf stream configuration\n * @return a create stream request.\n */", "public", "static", "CreateStreamRequest", "createCreateStreamRequest", "(", "String", "nsName", ",", "String", "streamName", ",", "StreamConfiguration", "streamConf", ")", "{", "return", "CreateStreamRequest", ".", "newBuilder", "(", ")", ".", "setNsName", "(", "nsName", ")", ".", "setName", "(", "streamName", ")", ".", "setStreamConf", "(", "streamConf", ")", ".", "build", "(", ")", ";", "}", "/**\n * Create a {@link GetStreamRequest}.\n *\n * @param nsName namespace name\n * @param streamName stream name\n * @return a create stream request.\n */", "public", "static", "GetStreamRequest", "createGetStreamRequest", "(", "String", "nsName", ",", "String", "streamName", ")", "{", "return", "GetStreamRequest", ".", "newBuilder", "(", ")", ".", "setStreamName", "(", "StreamName", ".", "newBuilder", "(", ")", ".", "setNamespaceName", "(", "nsName", ")", ".", "setStreamName", "(", "streamName", ")", ")", ".", "build", "(", ")", ";", "}", "/**\n * Create a {@link GetStreamRequest}.\n *\n * @param streamId stream id\n * @return a create stream request.\n */", "public", "static", "GetStreamRequest", "createGetStreamRequest", "(", "long", "streamId", ")", "{", "return", "GetStreamRequest", ".", "newBuilder", "(", ")", ".", "setStreamId", "(", "streamId", ")", ".", "build", "(", ")", ";", "}", "/**\n * Create a {@link DeleteStreamRequest}.\n *\n * @param nsName namespace name\n * @param streamName stream name\n * @return a create stream request.\n */", "public", "static", "DeleteStreamRequest", "createDeleteStreamRequest", "(", "String", "nsName", ",", "String", "streamName", ")", "{", "return", "DeleteStreamRequest", ".", "newBuilder", "(", ")", ".", "setName", "(", "streamName", ")", ".", "setNsName", "(", "nsName", ")", ".", "build", "(", ")", ";", "}", "}" ]
Protocol related utils.
[ "Protocol", "related", "utils", "." ]
[ "// round up to odd number", "//", "// Location API", "//", "//", "// Meta Range API", "//", "//", "// Namespace API", "//", "//", "// Stream API", "//" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
46def84ae5d76041433e966f8f95a600cff0c3a5
kvovo/kvovo
jobscheduler/scheduler-component-shared/src/java/org/sakaiproject/component/app/scheduler/jobs/autoimport/GetArchivesJob.java
[ "ECL-2.0" ]
Java
GetArchivesJob
/** * Attempts to download a file that lists all the site archives to import automatically. */
Attempts to download a file that lists all the site archives to import automatically.
[ "Attempts", "to", "download", "a", "file", "that", "lists", "all", "the", "site", "archives", "to", "import", "automatically", "." ]
public class GetArchivesJob implements Job { private final Logger log = LoggerFactory.getLogger(GetArchivesJob.class); private final Pattern uuidRegex = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); private ServerConfigurationService serverConfigurationService; private SchedulerManager schedulerManager; @Inject public void setServerConfigurationService(ServerConfigurationService serverConfigurationService) { this.serverConfigurationService = serverConfigurationService; } @Inject public void setSchedulerManager(SchedulerManager schedulerManager) { this.schedulerManager = schedulerManager; } @Override public void execute(JobExecutionContext context) throws JobExecutionException { String source = serverConfigurationService.getString("archives.import.source", null); if (source == null) { return; } log.info("Attempting to import archives listed in: "+ source); try { URL url = new URL(source); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Sakai Content Importer"); connection.setConnectTimeout(30000); connection.setReadTimeout(30000); // Now make the connection. connection.connect(); try (InputStream inputStream = connection.getInputStream()) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { if (!line.isEmpty() && !line.startsWith("#")) { String file = downloadArchive(line); if (file != null) { String siteId = extractSiteId(line); scheduleImport(file, siteId); } } } } } catch (IOException ioe) { log.warn("Problem with "+ source + " "+ ioe.getMessage()); } } private String extractSiteId(String line) { Matcher matcher = uuidRegex.matcher(line); if (matcher.find()) { return matcher.group(); } return null; } private void scheduleImport(String file, String siteId) { JobDataMap jobData = new JobDataMap(); jobData.put("zip", file); if (siteId != null) { jobData.put("siteId", siteId); } JobDetail jobDetail = JobBuilder.newJob(ImportJob.class) .withIdentity("Import Job") .setJobData(jobData) .build(); Scheduler scheduler = schedulerManager.getScheduler(); try { scheduler.addJob(jobDetail, true, true); scheduler.triggerJob(jobDetail.getKey()); } catch (SchedulerException e) { log.warn("Problem adding job to scheduler to import "+ file, e); } } private String downloadArchive(String archiveUrl) { if (archiveUrl == null || archiveUrl.trim().length() == 0) { log.warn("Empty archive setting."); return null; } log.info("Attempting to import: "+ archiveUrl); try { URL url = new URL(archiveUrl); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Sakai Content Importer"); connection.setConnectTimeout(30000); connection.setReadTimeout(30000); // Now make the connection. connection.connect(); Path out = Files.createTempFile("archive", ".zip"); try (InputStream in = connection.getInputStream()) { Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING); } return out.toString(); } catch (IOException ioe) { log.warn("Problem with "+ archiveUrl+ " "+ ioe.getMessage()); } return null; } }
[ "public", "class", "GetArchivesJob", "implements", "Job", "{", "private", "final", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "GetArchivesJob", ".", "class", ")", ";", "private", "final", "Pattern", "uuidRegex", "=", "Pattern", ".", "compile", "(", "\"", "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", "\"", ")", ";", "private", "ServerConfigurationService", "serverConfigurationService", ";", "private", "SchedulerManager", "schedulerManager", ";", "@", "Inject", "public", "void", "setServerConfigurationService", "(", "ServerConfigurationService", "serverConfigurationService", ")", "{", "this", ".", "serverConfigurationService", "=", "serverConfigurationService", ";", "}", "@", "Inject", "public", "void", "setSchedulerManager", "(", "SchedulerManager", "schedulerManager", ")", "{", "this", ".", "schedulerManager", "=", "schedulerManager", ";", "}", "@", "Override", "public", "void", "execute", "(", "JobExecutionContext", "context", ")", "throws", "JobExecutionException", "{", "String", "source", "=", "serverConfigurationService", ".", "getString", "(", "\"", "archives.import.source", "\"", ",", "null", ")", ";", "if", "(", "source", "==", "null", ")", "{", "return", ";", "}", "log", ".", "info", "(", "\"", "Attempting to import archives listed in: ", "\"", "+", "source", ")", ";", "try", "{", "URL", "url", "=", "new", "URL", "(", "source", ")", ";", "URLConnection", "connection", "=", "url", ".", "openConnection", "(", ")", ";", "connection", ".", "setRequestProperty", "(", "\"", "User-Agent", "\"", ",", "\"", "Sakai Content Importer", "\"", ")", ";", "connection", ".", "setConnectTimeout", "(", "30000", ")", ";", "connection", ".", "setReadTimeout", "(", "30000", ")", ";", "connection", ".", "connect", "(", ")", ";", "try", "(", "InputStream", "inputStream", "=", "connection", ".", "getInputStream", "(", ")", ")", "{", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "inputStream", ")", ")", ";", "String", "line", ";", "while", "(", "(", "line", "=", "reader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "!", "line", ".", "isEmpty", "(", ")", "&&", "!", "line", ".", "startsWith", "(", "\"", "#", "\"", ")", ")", "{", "String", "file", "=", "downloadArchive", "(", "line", ")", ";", "if", "(", "file", "!=", "null", ")", "{", "String", "siteId", "=", "extractSiteId", "(", "line", ")", ";", "scheduleImport", "(", "file", ",", "siteId", ")", ";", "}", "}", "}", "}", "}", "catch", "(", "IOException", "ioe", ")", "{", "log", ".", "warn", "(", "\"", "Problem with ", "\"", "+", "source", "+", "\"", " ", "\"", "+", "ioe", ".", "getMessage", "(", ")", ")", ";", "}", "}", "private", "String", "extractSiteId", "(", "String", "line", ")", "{", "Matcher", "matcher", "=", "uuidRegex", ".", "matcher", "(", "line", ")", ";", "if", "(", "matcher", ".", "find", "(", ")", ")", "{", "return", "matcher", ".", "group", "(", ")", ";", "}", "return", "null", ";", "}", "private", "void", "scheduleImport", "(", "String", "file", ",", "String", "siteId", ")", "{", "JobDataMap", "jobData", "=", "new", "JobDataMap", "(", ")", ";", "jobData", ".", "put", "(", "\"", "zip", "\"", ",", "file", ")", ";", "if", "(", "siteId", "!=", "null", ")", "{", "jobData", ".", "put", "(", "\"", "siteId", "\"", ",", "siteId", ")", ";", "}", "JobDetail", "jobDetail", "=", "JobBuilder", ".", "newJob", "(", "ImportJob", ".", "class", ")", ".", "withIdentity", "(", "\"", "Import Job", "\"", ")", ".", "setJobData", "(", "jobData", ")", ".", "build", "(", ")", ";", "Scheduler", "scheduler", "=", "schedulerManager", ".", "getScheduler", "(", ")", ";", "try", "{", "scheduler", ".", "addJob", "(", "jobDetail", ",", "true", ",", "true", ")", ";", "scheduler", ".", "triggerJob", "(", "jobDetail", ".", "getKey", "(", ")", ")", ";", "}", "catch", "(", "SchedulerException", "e", ")", "{", "log", ".", "warn", "(", "\"", "Problem adding job to scheduler to import ", "\"", "+", "file", ",", "e", ")", ";", "}", "}", "private", "String", "downloadArchive", "(", "String", "archiveUrl", ")", "{", "if", "(", "archiveUrl", "==", "null", "||", "archiveUrl", ".", "trim", "(", ")", ".", "length", "(", ")", "==", "0", ")", "{", "log", ".", "warn", "(", "\"", "Empty archive setting.", "\"", ")", ";", "return", "null", ";", "}", "log", ".", "info", "(", "\"", "Attempting to import: ", "\"", "+", "archiveUrl", ")", ";", "try", "{", "URL", "url", "=", "new", "URL", "(", "archiveUrl", ")", ";", "URLConnection", "connection", "=", "url", ".", "openConnection", "(", ")", ";", "connection", ".", "setRequestProperty", "(", "\"", "User-Agent", "\"", ",", "\"", "Sakai Content Importer", "\"", ")", ";", "connection", ".", "setConnectTimeout", "(", "30000", ")", ";", "connection", ".", "setReadTimeout", "(", "30000", ")", ";", "connection", ".", "connect", "(", ")", ";", "Path", "out", "=", "Files", ".", "createTempFile", "(", "\"", "archive", "\"", ",", "\"", ".zip", "\"", ")", ";", "try", "(", "InputStream", "in", "=", "connection", ".", "getInputStream", "(", ")", ")", "{", "Files", ".", "copy", "(", "in", ",", "out", ",", "StandardCopyOption", ".", "REPLACE_EXISTING", ")", ";", "}", "return", "out", ".", "toString", "(", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "log", ".", "warn", "(", "\"", "Problem with ", "\"", "+", "archiveUrl", "+", "\"", " ", "\"", "+", "ioe", ".", "getMessage", "(", ")", ")", ";", "}", "return", "null", ";", "}", "}" ]
Attempts to download a file that lists all the site archives to import automatically.
[ "Attempts", "to", "download", "a", "file", "that", "lists", "all", "the", "site", "archives", "to", "import", "automatically", "." ]
[ "// Now make the connection.", "// Now make the connection." ]
[ { "param": "Job", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Job", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
46e1d08b3bb4d77184d7915350b6650778bd6626
ivy-rew/ivy-reporting-ide
ch.ivyteam.ivy.reporting.base/src/ch/ivyteam/ivy/reporting/internal/dataset/ProcessElementAttributeDataSetEventAdapter.java
[ "Apache-2.0" ]
Java
ProcessElementAttributeDataSetEventAdapter
// navigated using the process image. (At least for HTML)
navigated using the process image. (At least for HTML)
[ "navigated", "using", "the", "process", "image", ".", "(", "At", "least", "for", "HTML", ")" ]
public class ProcessElementAttributeDataSetEventAdapter extends ReportingDataSetEventAdapter { /** The map with the attributes */ private Iterator<Map.Entry<String, String>> attributeIterator; /** The next identifier */ private int nextIdentifier = 0; /** * @see org.eclipse.birt.report.engine.api.script.eventadapter.ScriptedDataSetEventAdapter#open(org.eclipse.birt.report.engine.api.script.instance.IDataSetInstance) */ @Override public void open(IDataSetInstance dataSet) { try { Integer processElementId; processElementId = (Integer) dataSet.getInputParameterValue("ProcessElementId"); for (ProcessReportDataEntry entry : reportDataCollector.getProcessReportData()) { if (((Integer)entry.getId()).equals(processElementId)) { /* Get Process Element Inscription mask details. */ DataWrapperNode<?> elementDW = (DataWrapperNode<?>) DataWrapperFactory.createDataWrapper(entry.getProcessElement(), entry.getProject().getIvyProject()); Map<String, String> attributes = new LinkedHashMap<String, String>(); elementDW.getCompleteInfo(attributes); attributeIterator = attributes.entrySet().iterator(); nextIdentifier = 0; return; } } for (RichDialogReportDataEntry entry : reportDataCollector.getRichDialogReportData()) { if (((Integer)entry.getProcessId()).equals(processElementId)) { /* Get Process Element Inscription mask details. */ DataWrapperNode<?> elementDW = (DataWrapperNode<?>) DataWrapperFactory.createDataWrapper(entry.getProcessElement(), entry.getProject().getIvyProject()); Map<String, String> attributes = new LinkedHashMap<String, String>(); elementDW.getCompleteInfo(attributes); attributeIterator = attributes.entrySet().iterator(); nextIdentifier = 0; return; } } } catch (ScriptException ex) { ex.printStackTrace(); } } /** * @see org.eclipse.birt.report.engine.api.script.eventadapter.ScriptedDataSetEventAdapter#fetch(org.eclipse.birt.report.engine.api.script.instance.IDataSetInstance, * org.eclipse.birt.report.engine.api.script.IUpdatableDataSetRow) */ @Override public boolean fetch(IDataSetInstance dataSet, IUpdatableDataSetRow row) { if ((attributeIterator == null)||(attributeIterator.hasNext()==false)) { return false; } Map.Entry<String, String> entry = attributeIterator.next(); try { row.setColumnValue("Id", nextIdentifier++); row.setColumnValue("Name", entry.getKey()); row.setColumnValue("Value", entry.getValue()); } catch (ScriptException ex) { ReportingManager.getLogger().error("Error filling Report Data.", ex); throw new RuntimeException("Error filling Report Data.", ex); } return true; } /** * @see org.eclipse.birt.report.engine.api.script.eventadapter.ScriptedDataSetEventAdapter#close(org.eclipse.birt.report.engine.api.script.instance.IDataSetInstance) */ @Override public void close(IDataSetInstance _dataSet) { attributeIterator = null; nextIdentifier = 0; } }
[ "public", "class", "ProcessElementAttributeDataSetEventAdapter", "extends", "ReportingDataSetEventAdapter", "{", "/** The map with the attributes */", "private", "Iterator", "<", "Map", ".", "Entry", "<", "String", ",", "String", ">", ">", "attributeIterator", ";", "/** The next identifier */", "private", "int", "nextIdentifier", "=", "0", ";", "/**\r\n * @see org.eclipse.birt.report.engine.api.script.eventadapter.ScriptedDataSetEventAdapter#open(org.eclipse.birt.report.engine.api.script.instance.IDataSetInstance)\r\n */", "@", "Override", "public", "void", "open", "(", "IDataSetInstance", "dataSet", ")", "{", "try", "{", "Integer", "processElementId", ";", "processElementId", "=", "(", "Integer", ")", "dataSet", ".", "getInputParameterValue", "(", "\"", "ProcessElementId", "\"", ")", ";", "for", "(", "ProcessReportDataEntry", "entry", ":", "reportDataCollector", ".", "getProcessReportData", "(", ")", ")", "{", "if", "(", "(", "(", "Integer", ")", "entry", ".", "getId", "(", ")", ")", ".", "equals", "(", "processElementId", ")", ")", "{", "/* Get Process Element Inscription mask details. */", "DataWrapperNode", "<", "?", ">", "elementDW", "=", "(", "DataWrapperNode", "<", "?", ">", ")", "DataWrapperFactory", ".", "createDataWrapper", "(", "entry", ".", "getProcessElement", "(", ")", ",", "entry", ".", "getProject", "(", ")", ".", "getIvyProject", "(", ")", ")", ";", "Map", "<", "String", ",", "String", ">", "attributes", "=", "new", "LinkedHashMap", "<", "String", ",", "String", ">", "(", ")", ";", "elementDW", ".", "getCompleteInfo", "(", "attributes", ")", ";", "attributeIterator", "=", "attributes", ".", "entrySet", "(", ")", ".", "iterator", "(", ")", ";", "nextIdentifier", "=", "0", ";", "return", ";", "}", "}", "for", "(", "RichDialogReportDataEntry", "entry", ":", "reportDataCollector", ".", "getRichDialogReportData", "(", ")", ")", "{", "if", "(", "(", "(", "Integer", ")", "entry", ".", "getProcessId", "(", ")", ")", ".", "equals", "(", "processElementId", ")", ")", "{", "/* Get Process Element Inscription mask details. */", "DataWrapperNode", "<", "?", ">", "elementDW", "=", "(", "DataWrapperNode", "<", "?", ">", ")", "DataWrapperFactory", ".", "createDataWrapper", "(", "entry", ".", "getProcessElement", "(", ")", ",", "entry", ".", "getProject", "(", ")", ".", "getIvyProject", "(", ")", ")", ";", "Map", "<", "String", ",", "String", ">", "attributes", "=", "new", "LinkedHashMap", "<", "String", ",", "String", ">", "(", ")", ";", "elementDW", ".", "getCompleteInfo", "(", "attributes", ")", ";", "attributeIterator", "=", "attributes", ".", "entrySet", "(", ")", ".", "iterator", "(", ")", ";", "nextIdentifier", "=", "0", ";", "return", ";", "}", "}", "}", "catch", "(", "ScriptException", "ex", ")", "{", "ex", ".", "printStackTrace", "(", ")", ";", "}", "}", "/**\r\n * @see org.eclipse.birt.report.engine.api.script.eventadapter.ScriptedDataSetEventAdapter#fetch(org.eclipse.birt.report.engine.api.script.instance.IDataSetInstance,\r\n * org.eclipse.birt.report.engine.api.script.IUpdatableDataSetRow)\r\n */", "@", "Override", "public", "boolean", "fetch", "(", "IDataSetInstance", "dataSet", ",", "IUpdatableDataSetRow", "row", ")", "{", "if", "(", "(", "attributeIterator", "==", "null", ")", "||", "(", "attributeIterator", ".", "hasNext", "(", ")", "==", "false", ")", ")", "{", "return", "false", ";", "}", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", "=", "attributeIterator", ".", "next", "(", ")", ";", "try", "{", "row", ".", "setColumnValue", "(", "\"", "Id", "\"", ",", "nextIdentifier", "++", ")", ";", "row", ".", "setColumnValue", "(", "\"", "Name", "\"", ",", "entry", ".", "getKey", "(", ")", ")", ";", "row", ".", "setColumnValue", "(", "\"", "Value", "\"", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "catch", "(", "ScriptException", "ex", ")", "{", "ReportingManager", ".", "getLogger", "(", ")", ".", "error", "(", "\"", "Error filling Report Data.", "\"", ",", "ex", ")", ";", "throw", "new", "RuntimeException", "(", "\"", "Error filling Report Data.", "\"", ",", "ex", ")", ";", "}", "return", "true", ";", "}", "/**\r\n * @see org.eclipse.birt.report.engine.api.script.eventadapter.ScriptedDataSetEventAdapter#close(org.eclipse.birt.report.engine.api.script.instance.IDataSetInstance)\r\n */", "@", "Override", "public", "void", "close", "(", "IDataSetInstance", "_dataSet", ")", "{", "attributeIterator", "=", "null", ";", "nextIdentifier", "=", "0", ";", "}", "}" ]
navigated using the process image.
[ "navigated", "using", "the", "process", "image", "." ]
[]
[ { "param": "ReportingDataSetEventAdapter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ReportingDataSetEventAdapter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
46ea43149e01e10d9cb8cd5ed1cc3c26c894a8c3
TU-Berlin/citolytics
src/main/java/org/wikipedia/citolytics/edits/operators/CoEditsReducer.java
[ "MIT" ]
Java
CoEditsReducer
/** * Take article-author-pairs and generate co-edit pairs. * (With article filter) */
Take article-author-pairs and generate co-edit pairs. (With article filter)
[ "Take", "article", "-", "author", "-", "pairs", "and", "generate", "co", "-", "edit", "pairs", ".", "(", "With", "article", "filter", ")" ]
public class CoEditsReducer implements GroupReduceFunction<ArticleAuthorPair, CoEditMap> { private Collection<String> articleFilter; public CoEditsReducer(Collection<String> articleFilter) { this.articleFilter = articleFilter; } @Override public void reduce(Iterable<ArticleAuthorPair> in, Collector<CoEditMap> out) throws Exception { Iterator<ArticleAuthorPair> iterator = in.iterator(); HashSet<String> articles = new HashSet<>(); ArticleAuthorPair pair; // Read all edited articles from this author while (iterator.hasNext()) { pair = iterator.next(); articles.add(pair.getArticle()); } // Only author with at least two articles are useful if (articles.size() > 1) { // System.out.println(pair.getAuthorId() + " // " + articles); // Loop over all articles twice (generate edit pairs) for(String article: articles) { // Skip if is not part of filter if(articleFilter != null && !articleFilter.contains(article)) continue; // Build co-edit maps Map<String, Integer> coArticles = new HashMap<>(); for(String coArticle: articles) { if(!coArticle.equals(article)) // No a-a pairs coArticles.put(coArticle, 1); } out.collect(new CoEditMap(article, coArticles)); } } } }
[ "public", "class", "CoEditsReducer", "implements", "GroupReduceFunction", "<", "ArticleAuthorPair", ",", "CoEditMap", ">", "{", "private", "Collection", "<", "String", ">", "articleFilter", ";", "public", "CoEditsReducer", "(", "Collection", "<", "String", ">", "articleFilter", ")", "{", "this", ".", "articleFilter", "=", "articleFilter", ";", "}", "@", "Override", "public", "void", "reduce", "(", "Iterable", "<", "ArticleAuthorPair", ">", "in", ",", "Collector", "<", "CoEditMap", ">", "out", ")", "throws", "Exception", "{", "Iterator", "<", "ArticleAuthorPair", ">", "iterator", "=", "in", ".", "iterator", "(", ")", ";", "HashSet", "<", "String", ">", "articles", "=", "new", "HashSet", "<", ">", "(", ")", ";", "ArticleAuthorPair", "pair", ";", "while", "(", "iterator", ".", "hasNext", "(", ")", ")", "{", "pair", "=", "iterator", ".", "next", "(", ")", ";", "articles", ".", "add", "(", "pair", ".", "getArticle", "(", ")", ")", ";", "}", "if", "(", "articles", ".", "size", "(", ")", ">", "1", ")", "{", "for", "(", "String", "article", ":", "articles", ")", "{", "if", "(", "articleFilter", "!=", "null", "&&", "!", "articleFilter", ".", "contains", "(", "article", ")", ")", "continue", ";", "Map", "<", "String", ",", "Integer", ">", "coArticles", "=", "new", "HashMap", "<", ">", "(", ")", ";", "for", "(", "String", "coArticle", ":", "articles", ")", "{", "if", "(", "!", "coArticle", ".", "equals", "(", "article", ")", ")", "coArticles", ".", "put", "(", "coArticle", ",", "1", ")", ";", "}", "out", ".", "collect", "(", "new", "CoEditMap", "(", "article", ",", "coArticles", ")", ")", ";", "}", "}", "}", "}" ]
Take article-author-pairs and generate co-edit pairs.
[ "Take", "article", "-", "author", "-", "pairs", "and", "generate", "co", "-", "edit", "pairs", "." ]
[ "// Read all edited articles from this author", "// Only author with at least two articles are useful", "// System.out.println(pair.getAuthorId() + \" // \" + articles);", "// Loop over all articles twice (generate edit pairs)", "// Skip if is not part of filter", "// Build co-edit maps", "// No a-a pairs" ]
[ { "param": "GroupReduceFunction<ArticleAuthorPair, CoEditMap>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "GroupReduceFunction<ArticleAuthorPair, CoEditMap>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
46ec0198749b146d09ef2a01b4108d8fe4cad33a
mockstar/data-prep
dataprep-backend-service/src/main/java/org/talend/dataprep/transformation/api/action/dynamic/GenericParameter.java
[ "Apache-2.0" ]
Java
GenericParameter
/** * Representation of a "Generic" Parameter. */
Representation of a "Generic" Parameter.
[ "Representation", "of", "a", "\"", "Generic", "\"", "Parameter", "." ]
public class GenericParameter { /** Parameter type (item, parameter, cluster, ...). */ final String type; /** Parameter details. this can be an array, a map, an object. */ final Object details; /** * Default constructor. * * @param type the parameter type. * @param details the parameter details. */ public GenericParameter(final String type, final Object details) { this.type = type; this.details = details; } /** * @return the parameter type. */ public String getType() { return type; } /** * @return the parameter details. */ public Object getDetails() { return details; } }
[ "public", "class", "GenericParameter", "{", "/** Parameter type (item, parameter, cluster, ...). */", "final", "String", "type", ";", "/** Parameter details. this can be an array, a map, an object. */", "final", "Object", "details", ";", "/**\n * Default constructor.\n *\n * @param type the parameter type.\n * @param details the parameter details.\n */", "public", "GenericParameter", "(", "final", "String", "type", ",", "final", "Object", "details", ")", "{", "this", ".", "type", "=", "type", ";", "this", ".", "details", "=", "details", ";", "}", "/**\n * @return the parameter type.\n */", "public", "String", "getType", "(", ")", "{", "return", "type", ";", "}", "/**\n * @return the parameter details.\n */", "public", "Object", "getDetails", "(", ")", "{", "return", "details", ";", "}", "}" ]
Representation of a "Generic" Parameter.
[ "Representation", "of", "a", "\"", "Generic", "\"", "Parameter", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }