idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
22,400 | public static < T extends Parameters > T parse ( Reader reader , T parameters ) throws AponParseException { AponReader aponReader = new AponReader ( reader ) ; aponReader . read ( parameters ) ; return parameters ; } | Converts into a given Parameters object from a character - input stream . | 51 | 14 |
22,401 | public void putExceptionThrownRule ( ExceptionThrownRule exceptionThrownRule ) { exceptionThrownRuleList . add ( exceptionThrownRule ) ; String [ ] exceptionTypes = exceptionThrownRule . getExceptionTypes ( ) ; if ( exceptionTypes != null ) { for ( String exceptionType : exceptionTypes ) { if ( exceptionType != null ) { if ( ! exceptionThrownRuleMap . containsKey ( exceptionType ) ) { exceptionThrownRuleMap . put ( exceptionType , exceptionThrownRule ) ; } } } } else { defaultExceptionThrownRule = exceptionThrownRule ; } } | Puts the exception thrown rule . | 128 | 7 |
22,402 | public ExceptionThrownRule getExceptionThrownRule ( Throwable ex ) { ExceptionThrownRule exceptionThrownRule = null ; int deepest = Integer . MAX_VALUE ; for ( Map . Entry < String , ExceptionThrownRule > entry : exceptionThrownRuleMap . entrySet ( ) ) { int depth = getMatchedDepth ( entry . getKey ( ) , ex ) ; if ( depth >= 0 && depth < deepest ) { deepest = depth ; exceptionThrownRule = entry . getValue ( ) ; } } return ( exceptionThrownRule != null ? exceptionThrownRule : defaultExceptionThrownRule ) ; } | Gets the exception thrown rule as specified exception . | 132 | 10 |
22,403 | private void lookupDefaultServletName ( ServletContext servletContext ) { if ( servletContext . getNamedDispatcher ( COMMON_DEFAULT_SERVLET_NAME ) != null ) { defaultServletName = COMMON_DEFAULT_SERVLET_NAME ; } else if ( servletContext . getNamedDispatcher ( RESIN_DEFAULT_SERVLET_NAME ) != null ) { defaultServletName = RESIN_DEFAULT_SERVLET_NAME ; } else if ( servletContext . getNamedDispatcher ( WEBLOGIC_DEFAULT_SERVLET_NAME ) != null ) { defaultServletName = WEBLOGIC_DEFAULT_SERVLET_NAME ; } else if ( servletContext . getNamedDispatcher ( WEBSPHERE_DEFAULT_SERVLET_NAME ) != null ) { defaultServletName = WEBSPHERE_DEFAULT_SERVLET_NAME ; } else if ( servletContext . getNamedDispatcher ( GAE_DEFAULT_SERVLET_NAME ) != null ) { defaultServletName = GAE_DEFAULT_SERVLET_NAME ; } else if ( servletContext . getNamedDispatcher ( JEUS_DEFAULT_SERVLET_NAME ) != null ) { defaultServletName = JEUS_DEFAULT_SERVLET_NAME ; } else { if ( log . isDebugEnabled ( ) ) { log . debug ( "Unable to locate the default servlet for serving static content. " + "Please set the 'web.defaultServletName'." ) ; } } } | Lookup default servlet name . | 365 | 7 |
22,404 | public boolean handle ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { if ( defaultServletName != null ) { RequestDispatcher rd = servletContext . getNamedDispatcher ( defaultServletName ) ; if ( rd == null ) { throw new IllegalStateException ( "A RequestDispatcher could not be located for the default servlet '" + defaultServletName + "'" ) ; } rd . forward ( request , response ) ; return true ; } else { return false ; } } | Process the actual dispatching . | 123 | 6 |
22,405 | public static String encrypt ( String inputString , String encryptionPassword ) { return getEncryptor ( encryptionPassword ) . encrypt ( inputString ) ; } | Encrypts the inputString using the encryption password . | 31 | 11 |
22,406 | public static String decrypt ( String inputString , String encryptionPassword ) { checkPassword ( encryptionPassword ) ; return getEncryptor ( encryptionPassword ) . decrypt ( inputString ) ; } | Decrypts the inputString using the encryption password . | 38 | 11 |
22,407 | private void newHttpSessionScope ( ) { SessionScopeAdvisor advisor = SessionScopeAdvisor . create ( context ) ; this . sessionScope = new HttpSessionScope ( advisor ) ; setAttribute ( SESSION_SCOPE_ATTRIBUTE_NAME , this . sessionScope ) ; } | Creates a new HTTP session scope . | 62 | 8 |
22,408 | private void handleUnknownToken ( String token ) throws OptionParserException { if ( token . startsWith ( "-" ) && token . length ( ) > 1 && ! skipParsingAtNonOption ) { throw new UnrecognizedOptionException ( "Unrecognized option: " + token , token ) ; } parsedOptions . addArg ( token ) ; } | Handles an unknown token . If the token starts with a dash an UnrecognizedOptionException is thrown . Otherwise the token is added to the arguments of the command line . If the skipParsingAtNonOption flag is set this stops the parsing and the remaining tokens are added as - is in the arguments of the command line . | 75 | 68 |
22,409 | private List < String > getMatchingLongOptions ( String token ) { if ( allowPartialMatching ) { return options . getMatchingOptions ( token ) ; } else { List < String > matches = new ArrayList <> ( 1 ) ; if ( options . hasLongOption ( token ) ) { Option option = options . getOption ( token ) ; matches . add ( option . getLongName ( ) ) ; } return matches ; } } | Returns a list of matching option strings for the given token depending on the selected partial matching policy . | 95 | 19 |
22,410 | private Method [ ] getAllMethods ( Class < ? > beanClass ) { Map < String , Method > uniqueMethods = new HashMap <> ( ) ; Class < ? > currentClass = beanClass ; while ( currentClass != null && currentClass != Object . class ) { addUniqueMethods ( uniqueMethods , currentClass . getDeclaredMethods ( ) ) ; // we also need to look for interface methods - // because the class may be abstract Class < ? > [ ] interfaces = currentClass . getInterfaces ( ) ; for ( Class < ? > anInterface : interfaces ) { addUniqueMethods ( uniqueMethods , anInterface . getMethods ( ) ) ; } currentClass = currentClass . getSuperclass ( ) ; } Collection < Method > methods = uniqueMethods . values ( ) ; return methods . toArray ( new Method [ 0 ] ) ; } | This method returns an array containing all methods exposed in this class and any superclass . In the future Java is not pleased to have access to private or protected methods . | 179 | 33 |
22,411 | public Method getGetter ( String name ) throws NoSuchMethodException { Method method = getterMethods . get ( name ) ; if ( method == null ) { throw new NoSuchMethodException ( "There is no READABLE property named '" + name + "' in class '" + className + "'" ) ; } return method ; } | Gets the getter for a property as a Method object . | 72 | 13 |
22,412 | public Method getSetter ( String name ) throws NoSuchMethodException { Method method = setterMethods . get ( name ) ; if ( method == null ) { throw new NoSuchMethodException ( "There is no WRITABLE property named '" + name + "' in class '" + className + "'" ) ; } return method ; } | Gets the setter for a property as a Method object . | 73 | 13 |
22,413 | public Class < ? > getGetterType ( String name ) throws NoSuchMethodException { Class < ? > type = getterTypes . get ( name ) ; if ( type == null ) { throw new NoSuchMethodException ( "There is no READABLE property named '" + name + "' in class '" + className + "'" ) ; } return type ; } | Gets the type for a property getter . | 79 | 10 |
22,414 | public Class < ? > getSetterType ( String name ) throws NoSuchMethodException { Class < ? > type = setterTypes . get ( name ) ; if ( type == null ) { throw new NoSuchMethodException ( "There is no WRITABLE property named '" + name + "' in class '" + className + "'" ) ; } return type ; } | Gets the type for a property setter . | 80 | 10 |
22,415 | public static BeanDescriptor getInstance ( Class < ? > type ) { BeanDescriptor bd = cache . get ( type ) ; if ( bd == null ) { bd = new BeanDescriptor ( type ) ; BeanDescriptor existing = cache . putIfAbsent ( type , bd ) ; if ( existing != null ) { bd = existing ; } } return bd ; } | Gets an instance of ClassDescriptor for the specified class . | 88 | 14 |
22,416 | private Option resolveOption ( String name ) { name = OptionUtils . stripLeadingHyphens ( name ) ; for ( Option option : options ) { if ( name . equals ( option . getName ( ) ) ) { return option ; } if ( name . equals ( option . getLongName ( ) ) ) { return option ; } } return null ; } | Retrieves the option object given the long or short option as a String . | 76 | 16 |
22,417 | public static IncludeActionRule newInstance ( String id , String transletName , String method , Boolean hidden ) throws IllegalRuleException { if ( transletName == null ) { throw new IllegalRuleException ( "The 'include' element requires a 'translet' attribute" ) ; } MethodType methodType = MethodType . resolve ( method ) ; if ( method != null && methodType == null ) { throw new IllegalRuleException ( "No request method type for '" + method + "'" ) ; } IncludeActionRule includeActionRule = new IncludeActionRule ( ) ; includeActionRule . setActionId ( id ) ; includeActionRule . setTransletName ( transletName ) ; includeActionRule . setMethodType ( methodType ) ; includeActionRule . setHidden ( hidden ) ; return includeActionRule ; } | Returns a new instance of IncludeActionRule . | 173 | 9 |
22,418 | public boolean lock ( ) throws Exception { synchronized ( this ) { if ( fileLock != null ) { throw new Exception ( "The lock is already held" ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Acquiring lock on " + lockFile . getAbsolutePath ( ) ) ; } try { fileChannel = new RandomAccessFile ( lockFile , "rw" ) . getChannel ( ) ; fileLock = fileChannel . tryLock ( ) ; } catch ( OverlappingFileLockException | IOException e ) { throw new Exception ( "Exception occurred while trying to get a lock on file: " + lockFile . getAbsolutePath ( ) , e ) ; } if ( fileLock == null ) { if ( fileChannel != null ) { try { fileChannel . close ( ) ; } catch ( IOException ie ) { // ignore } fileChannel = null ; } return false ; } else { return true ; } } } | Try to lock the file and return true if the locking succeeds . | 205 | 13 |
22,419 | public void release ( ) throws Exception { synchronized ( this ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Releasing lock on " + lockFile . getAbsolutePath ( ) ) ; } if ( fileLock != null ) { try { fileLock . release ( ) ; fileLock = null ; } catch ( Exception e ) { throw new Exception ( "Unable to release locked file: " + lockFile . getAbsolutePath ( ) , e ) ; } if ( fileChannel != null ) { try { fileChannel . close ( ) ; } catch ( IOException e ) { // ignore } fileChannel = null ; } if ( lockFile != null ) { if ( lockFile . exists ( ) ) { lockFile . delete ( ) ; } lockFile = null ; } } } } | Releases the lock . | 173 | 5 |
22,420 | @ GET @ Produces ( MediaType . APPLICATION_JSON ) public String [ ] get ( @ HeaderParam ( "Authorization" ) @ DefaultValue ( "no token" ) String auth ) throws Exception { if ( ! this . isAuth ( auth ) ) { throw new Exception ( "Unauthorized!" ) ; } return controller . getDisabled ( ) ; } | Retrieves a list of already disabled endpoints . | 79 | 11 |
22,421 | private void sendJGroupsMessage ( UpdateOpteration operation , String path , String auth ) throws Exception { if ( ! this . isAuth ( auth ) ) { throw new Exception ( "Unauthorized!" ) ; } log . trace ( "Sending jGroups message with operation {} and path {}" , operation , path ) ; ApiEndpointAccessRequest messageBody = new ApiEndpointAccessRequest ( ) ; messageBody . setEndpoint ( path ) ; messageBody . setOperation ( operation ) ; Message < ApiEndpointAccessRequest > msg = new Message < ApiEndpointAccessRequest > ( ProtocolMessage . API_ENDPOINT_ACCESS , messageBody ) ; log . trace ( "Sending jgroups message: " + msg ) ; sender . sendMessage ( msg , null ) ; } | Sends jgroups message to make sure that this operation is executed on all nodes in the cluster . | 176 | 20 |
22,422 | public Schema getIntermediateSchema ( String schemaName ) { Integer id = getSchemaIdByName ( schemaName ) ; return ( id == null ) ? null : schemas . get ( id ) ; } | Returns a defined intermediate schema with the specified name | 46 | 9 |
22,423 | public List < String > calculateRollupBaseFields ( ) { if ( rollupFrom == null ) { return getGroupByFields ( ) ; } List < String > result = new ArrayList < String > ( ) ; for ( SortElement element : commonCriteria . getElements ( ) ) { result . add ( element . getName ( ) ) ; if ( element . getName ( ) . equals ( rollupFrom ) ) { break ; } } return result ; } | Returns the fields that are a subset from the groupBy fields and will be used when rollup is needed . | 102 | 22 |
22,424 | public static Set < String > set ( TupleMRConfig mrConfig , Configuration conf ) throws TupleMRException { conf . set ( CONF_PANGOOL_CONF , mrConfig . toString ( ) ) ; return serializeComparators ( mrConfig , conf ) ; } | Returns the instance files generated . | 66 | 6 |
22,425 | static Set < String > serializeComparators ( Criteria criteria , Configuration conf , List < String > comparatorRefs , List < String > comparatorInstanceFiles , String prefix ) throws TupleMRException { Set < String > instanceFiles = new HashSet < String > ( ) ; if ( criteria == null ) { return instanceFiles ; } for ( SortElement element : criteria . getElements ( ) ) { if ( element . getCustomComparator ( ) != null ) { RawComparator < ? > comparator = element . getCustomComparator ( ) ; if ( ! ( comparator instanceof Serializable ) ) { throw new TupleMRException ( "The class '" + comparator . getClass ( ) . getName ( ) + "' is not Serializable." + " The customs comparators must implement Serializable." ) ; } String ref = prefix + "|" + element . getName ( ) ; String uniqueName = UUID . randomUUID ( ) . toString ( ) + ' ' + "comparator.dat" ; try { InstancesDistributor . distribute ( comparator , uniqueName , conf ) ; instanceFiles . add ( uniqueName ) ; } catch ( Exception e ) { throw new TupleMRException ( "The class " + comparator . getClass ( ) . getName ( ) + " can't be serialized" , e ) ; } comparatorRefs . add ( ref ) ; comparatorInstanceFiles . add ( uniqueName ) ; } } return instanceFiles ; } | Returns the instance files created | 329 | 5 |
22,426 | public static TupleMRConfig parse ( String s ) throws IOException { return parse ( FACTORY . createJsonParser ( new StringReader ( s ) ) ) ; } | Parse a schema from the provided string . If named the schema is added to the names known to this parser . | 37 | 23 |
22,427 | public void setFidelity ( String key , boolean decision ) throws UnsupportedOption { if ( key . equals ( FEATURE_STRICT ) ) { if ( decision ) { // no other features allowed // (LEXICAL_VALUE is an exception) boolean prevContainedLexVal = options . contains ( FEATURE_LEXICAL_VALUE ) ; options . clear ( ) ; isComment = false ; isPI = false ; isDTD = false ; isPrefix = false ; isLexicalValue = false ; isSC = false ; if ( prevContainedLexVal ) { options . add ( FEATURE_LEXICAL_VALUE ) ; isLexicalValue = true ; } options . add ( FEATURE_STRICT ) ; isStrict = true ; } else { // remove strict (if present) options . remove ( key ) ; isStrict = false ; } } else if ( key . equals ( FEATURE_LEXICAL_VALUE ) ) { // LEXICAL_VALUE is special --> does affect grammars if ( decision ) { options . add ( key ) ; isLexicalValue = true ; } else { // remove option (if present) options . remove ( key ) ; isLexicalValue = false ; } } else if ( key . equals ( FEATURE_COMMENT ) || key . equals ( FEATURE_PI ) || key . equals ( FEATURE_DTD ) || key . equals ( FEATURE_PREFIX ) || key . equals ( FEATURE_SC ) ) { if ( decision ) { if ( isStrict ( ) ) { options . remove ( FEATURE_STRICT ) ; this . isStrict = false ; // TODO inform user that STRICT mode is de-activated // throw new UnsupportedOption( // "StrictMode is exclusive and does not allow any other option."); } options . add ( key ) ; if ( key . equals ( FEATURE_COMMENT ) ) { isComment = true ; } if ( key . equals ( FEATURE_PI ) ) { isPI = true ; } if ( key . equals ( FEATURE_DTD ) ) { isDTD = true ; } if ( key . equals ( FEATURE_PREFIX ) ) { isPrefix = true ; } if ( key . equals ( FEATURE_SC ) ) { isSC = true ; } } else { // remove option (if present) options . remove ( key ) ; if ( key . equals ( FEATURE_COMMENT ) ) { isComment = false ; } if ( key . equals ( FEATURE_PI ) ) { isPI = false ; } if ( key . equals ( FEATURE_DTD ) ) { isDTD = false ; } if ( key . equals ( FEATURE_PREFIX ) ) { isPrefix = false ; } if ( key . equals ( FEATURE_SC ) ) { isSC = false ; } } } else { throw new UnsupportedOption ( "FidelityOption '" + key + "' is unknown!" ) ; } } | Enables or disables the specified fidelity feature . | 644 | 10 |
22,428 | public static void setDeflateLevel ( Job job , int level ) { FileOutputFormat . setCompressOutput ( job , true ) ; job . getConfiguration ( ) . setInt ( DEFLATE_LEVEL_KEY , level ) ; } | Enable output compression using the deflate codec and specify its level . | 52 | 13 |
22,429 | public static LogMetadata of ( String key , Object value ) { Map < String , Object > map = new HashMap <> ( ) ; map . put ( key , value ) ; return new LogMetadata ( map ) ; } | Create a new metadata marker with a single key - value pair . | 49 | 13 |
22,430 | public static < T extends OtlType > LogMetadata logOtl ( T otl ) { return new LogMetadata ( Collections . emptyMap ( ) ) . andInline ( otl ) ; } | Add an OTL object to the log message | 44 | 9 |
22,431 | public LogMetadata and ( String key , Object value ) { metadata . put ( key , value ) ; return this ; } | Extend a metadata marker with another key - value pair . | 26 | 12 |
22,432 | private static Pattern compilePattern ( String regex , Logger logger ) { try { return Pattern . compile ( regex ) ; } catch ( PatternSyntaxException pse ) { logger . error ( "Could not compile regex " + regex , pse ) ; } return null ; } | Compiles the given regex . Returns null if the pattern could not be compiled and logs an error message to the specified logger . | 55 | 25 |
22,433 | protected String getSecureBaseUrl ( String siteUrl ) { if ( ! siteUrl . startsWith ( "http://" ) && ! siteUrl . startsWith ( "https://" ) ) { siteUrl = "http://" + siteUrl ; } Matcher urlMatcher = URL_PATTERN . matcher ( siteUrl ) ; if ( urlMatcher . matches ( ) ) { logger . debug ( "Url matches [{}]" , siteUrl ) ; boolean local = false ; try { logger . debug ( "Checking if host [{}] is local" , urlMatcher . group ( 1 ) ) ; InetAddress hostAddr = InetAddress . getByName ( urlMatcher . group ( 1 ) ) ; local = hostAddr . isLoopbackAddress ( ) || hostAddr . isSiteLocalAddress ( ) ; logger . debug ( "IpAddress [{}] local: {}" , hostAddr . getHostAddress ( ) , local ) ; } catch ( UnknownHostException e ) { logger . warn ( "Hostname not found [" + siteUrl + "]" , e ) ; } if ( ! local ) { return siteUrl . replaceFirst ( "http://" , "https://" ) ; } } return siteUrl ; } | Converts the passed in siteUrl to be https if not already or not local . | 273 | 17 |
22,434 | protected static HttpClient httpClient ( ) throws Exception { return HttpClients . custom ( ) . setHostnameVerifier ( new AllowAllHostnameVerifier ( ) ) . setSslcontext ( SSLContexts . custom ( ) . loadTrustMaterial ( null , new TrustStrategy ( ) { @ Override public boolean isTrusted ( X509Certificate [ ] x509Certificates , String s ) throws CertificateException { return true ; } } ) . build ( ) ) . build ( ) ; } | Sets the Commons HttpComponents to accept all SSL Certificates . | 110 | 16 |
22,435 | private void addCurrentDirFiles ( List < File > theFiles , List < File > theDirs , File currentDir ) { File dirs [ ] = currentDir . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( File file ) { return file . isDirectory ( ) && ! file . getName ( ) . startsWith ( "." ) && ! file . getName ( ) . equals ( "META-INF" ) ; } } ) ; File htmlFiles [ ] = currentDir . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( File file ) { return ! file . isDirectory ( ) && file . isFile ( ) && file . canRead ( ) && ! file . getName ( ) . startsWith ( "." ) && ( file . getName ( ) . endsWith ( ".html" ) || file . getName ( ) . endsWith ( ".htm" ) ) ; } } ) ; if ( dirs != null && dirs . length > 0 ) { theDirs . addAll ( Arrays . asList ( dirs ) ) ; } if ( htmlFiles != null && htmlFiles . length > 0 ) { theFiles . addAll ( Arrays . asList ( htmlFiles ) ) ; } } | Adds all html files to the list passed in . | 273 | 10 |
22,436 | public void setDefaultNamedOutput ( OutputFormat outputFormat , Class keyClass , Class valueClass ) throws TupleMRException { setDefaultNamedOutput ( outputFormat , keyClass , valueClass , null ) ; } | Sets the default named output specs . By using this method one can use an arbitrary number of named outputs without pre - defining them beforehand . | 48 | 28 |
22,437 | public Properties getProperties ( ) { Properties props = new Properties ( ) ; for ( String name : this . users . keySet ( ) ) { SimpleAccount acct = this . users . get ( name ) ; props . setProperty ( USERNAME_PREFIX + name , acct . getCredentials ( ) . toString ( ) ) ; } return props ; } | Dump properties file backed with this Realms Users and roles . | 81 | 12 |
22,438 | public List < String > listUsers ( ) { List < String > users = new ArrayList < String > ( this . users . keySet ( ) ) ; Collections . sort ( users ) ; return users ; } | Lists all existing user accounts . | 44 | 7 |
22,439 | public static List < ILoggingEvent > capture ( Logger logger ) { CaptureAppender capture = new CaptureAppender ( ) ; ( ( ch . qos . logback . classic . Logger ) logger ) . addAppender ( capture ) ; capture . start ( ) ; return capture . captured ; } | Capture a Logger . | 65 | 5 |
22,440 | public boolean add ( Object o ) { boolean result = false ; if ( o == null ) { throw new IllegalArgumentException ( "Address sets do not support null." ) ; } else if ( o instanceof String ) { result = super . add ( convertAddress ( ( String ) o ) ) ; } else if ( o instanceof InternetAddress ) { result = super . add ( o ) ; } else { throw new IllegalArgumentException ( "Address sets cannot take objects of type '" + o . getClass ( ) . getName ( ) + "'." ) ; } return result ; } | Adds a specified address to this set . If o is an instance of String then a new InternetAddress is created and that object is added to the set . If o is an instance of InternetAddress then it is added to the set . All other values of o including null throw an IllegalArgumentException . | 125 | 61 |
22,441 | public static void enableProtoStuffSerialization ( Configuration conf ) { String ser = conf . get ( "io.serializations" ) . trim ( ) ; if ( ser . length ( ) != 0 ) { ser += "," ; } // Adding the ProtoStuff serialization ser += ProtoStuffSerialization . class . getName ( ) ; conf . set ( "io.serializations" , ser ) ; } | Enables ProtoStuff Serialization support in Hadoop . | 89 | 13 |
22,442 | public void execute ( ) throws Exception { String site1 = getSecureBaseUrl ( sites . get ( 0 ) ) ; String site2 = getSecureBaseUrl ( sites . get ( 1 ) ) ; if ( site1 . equalsIgnoreCase ( site2 ) ) { System . err . println ( "Cannot clone a site into itself." ) ; System . exit ( 1 ) ; } try { System . out . println ( "Getting status of [" + site1 + "]" ) ; Status site1Status = StatusCommand . getSiteStatus ( site1 , token ) ; System . out . println ( "Getting status of [" + site2 + "]" ) ; Status site2Status = StatusCommand . getSiteStatus ( site2 , token ) ; if ( site1Status != null && site2Status != null ) { String repo = site1Status . getRepo ( ) ; String revision = site1Status . getRevision ( ) ; String branch = site1Status . getBranch ( ) ; if ( site2Status . getRepo ( ) . equals ( repo ) && site2Status . getBranch ( ) . equals ( branch ) && site2Status . getRevision ( ) . equals ( revision ) ) { System . err . println ( "Source [" + site1 + "] is on the same content repo, branch, and revision as the target [" + site2 + "]." ) ; checkSendUpdateConfigMessage ( site1 , site2 , site1Status , site2Status ) ; System . exit ( 1 ) ; } System . out . println ( "Sending update message to [" + site2 + "]" ) ; UpdateCommand . sendUpdateMessage ( site2 , repo , branch , revision , "Cloned from [" + site1 + "]: " + comment , token ) ; checkSendUpdateConfigMessage ( site1 , site2 , site1Status , site2Status ) ; } else { System . err . println ( "Failed to get status from source and/or target." ) ; System . exit ( 1 ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; System . err . println ( "Failed to clone [" + site1 + "] to [" + site2 + "]: " + e . getMessage ( ) ) ; } } | Called to execute this command . | 489 | 7 |
22,443 | private void checkSendUpdateConfigMessage ( String site1 , String site2 , Status site1Status , Status site2Status ) throws Exception { String repo ; String revision ; String branch ; if ( includeConfig ) { repo = site1Status . getConfigRepo ( ) ; revision = site1Status . getConfigRevision ( ) ; branch = site1Status . getConfigBranch ( ) ; if ( ! StringUtils . isEmptyOrNull ( repo ) && ! StringUtils . isEmptyOrNull ( revision ) && ! StringUtils . isEmptyOrNull ( branch ) ) { if ( ! repo . equals ( site2Status . getConfigRepo ( ) ) || ! revision . equals ( site2Status . getConfigRevision ( ) ) || ! branch . equals ( site2Status . getConfigBranch ( ) ) ) { System . out . println ( "Sending update/config message to [" + site2 + "]" ) ; UpdateCommand . sendUpdateMessage ( site2 , repo , branch , revision , "Cloned config from [" + site1 + "]: " + comment , token , UpdateConfigCommand . UPDATE_CONFIG_ENDPOINT , UpdateRequest . CONFIG_BRANCH_PREFIX ) ; } else { System . out . println ( "Source [" + site1 + "] is on the same configuration repo, branch, and revision as the target [" + site2 + "]." ) ; } } else { System . out . println ( "Configuration status not available from source site [" + site1 + "]" ) ; } } } | Checks if a config update message is necessary and sends it if it is . | 335 | 16 |
22,444 | public static GitService cloneSiteRepo ( Status status ) throws Exception { File tmpDir = File . createTempFile ( "site" , "git" ) ; GitService git = null ; if ( tmpDir . delete ( ) ) { try { git = GitService . cloneRepo ( status . getRepo ( ) , tmpDir . getAbsolutePath ( ) ) ; if ( status . getBranch ( ) != null && ! git . getBranchName ( ) . equals ( status . getBranch ( ) ) ) { git . switchBranch ( status . getBranch ( ) ) ; } if ( status . getRevision ( ) != null && ! git . getCurrentRevision ( ) . equals ( status . getRevision ( ) ) ) { git . resetToRev ( status . getRevision ( ) ) ; } } catch ( Exception e ) { System . err . println ( "Failed to clone repo " + status . getRepo ( ) + " branch " + status . getBranch ( ) + "[" + tmpDir + "]" ) ; e . printStackTrace ( ) ; if ( git != null ) { git . close ( ) ; git = null ; } } } return git ; } | Clones a repository locally from a status response from a Cadmium site . | 264 | 16 |
22,445 | public static void setEnvironment ( String otEnv , String otEnvType , String otEnvLocation , String otEnvFlavor ) { OT_ENV = otEnv ; OT_ENV_TYPE = otEnvType ; OT_ENV_LOCATION = otEnvLocation ; OT_ENV_FLAVOR = otEnvFlavor ; } | Mock out the environment . You probably don t want to do this . | 81 | 15 |
22,446 | public static String getServiceType ( ) { if ( UNSET . equals ( serviceType ) && WARNED_UNSET . compareAndSet ( false , true ) ) { LoggerFactory . getLogger ( ApplicationLogEvent . class ) . error ( "The application name was not set! Sending 'UNSET' instead :(" ) ; } return serviceType ; } | Get the service type | 77 | 4 |
22,447 | private static boolean isEmptyOrNull ( GitLocation location ) { return location == null || ( StringUtils . isEmptyOrNull ( location . getRepository ( ) ) && StringUtils . isEmptyOrNull ( location . getBranch ( ) ) && StringUtils . isEmptyOrNull ( location . getRevision ( ) ) ) ; } | Returns true if a git location object is null or all of its values are empty or null . | 75 | 19 |
22,448 | public void write ( BitEncoderChannel headerChannel , EXIFactory f ) throws EXIException { try { EncodingOptions headerOptions = f . getEncodingOptions ( ) ; CodingMode codingMode = f . getCodingMode ( ) ; // EXI Cookie if ( headerOptions . isOptionEnabled ( EncodingOptions . INCLUDE_COOKIE ) ) { // four byte field consists of four characters " $ " , " E ", // " X " and " I " in that order headerChannel . encode ( ' ' ) ; headerChannel . encode ( ' ' ) ; headerChannel . encode ( ' ' ) ; headerChannel . encode ( ' ' ) ; } // Distinguishing Bits 10 headerChannel . encodeNBitUnsignedInteger ( 2 , 2 ) ; // Presence Bit for EXI Options 0 boolean includeOptions = headerOptions . isOptionEnabled ( EncodingOptions . INCLUDE_OPTIONS ) ; headerChannel . encodeBoolean ( includeOptions ) ; // EXI Format Version 0-0000 headerChannel . encodeBoolean ( false ) ; // preview headerChannel . encodeNBitUnsignedInteger ( 0 , 4 ) ; // EXI Header options and so forth if ( includeOptions ) { writeEXIOptions ( f , headerChannel ) ; } // other than bit-packed requires [Padding Bits] if ( codingMode != CodingMode . BIT_PACKED ) { headerChannel . align ( ) ; headerChannel . flush ( ) ; } } catch ( IOException e ) { throw new EXIException ( e ) ; } } | Writes the EXI header according to the header options with optional cookie EXI options .. | 332 | 18 |
22,449 | public org . jgroups . Message toJGroupsMessage ( Message < ? > cMessage ) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; JsonGenerator generator = factory . createJsonGenerator ( out ) ; generator . writeStartObject ( ) ; generator . writeObjectField ( "header" , cMessage . getHeader ( ) ) ; if ( cMessage . getBody ( ) != null ) { generator . writeObjectField ( "body" , cMessage . getBody ( ) ) ; } generator . writeEndObject ( ) ; generator . close ( ) ; org . jgroups . Message jgMessage = new org . jgroups . Message ( ) ; jgMessage . setBuffer ( out . toByteArray ( ) ) ; return jgMessage ; } | Serialized the cadmium message object into JSON and returns it as a JGroups message . | 171 | 20 |
22,450 | public < B > Message < B > toCadmiumMessage ( org . jgroups . Message jgMessage ) throws JsonProcessingException , IOException { JsonParser parser = factory . createJsonParser ( jgMessage . getBuffer ( ) ) ; parser . nextToken ( ) ; // parse the start token for the document. parser . nextToken ( ) ; // parse the field name parser . nextToken ( ) ; // parse the start token for header. Header header = parser . readValueAs ( Header . class ) ; Class < ? > bodyClass = lookupBodyClass ( header ) ; parser . nextToken ( ) ; // parse the end token for header. Object body = null ; if ( bodyClass == Void . class ) { body = null ; } else { parser . nextToken ( ) ; // parse the start token for body. try { body = parser . readValueAs ( bodyClass ) ; } catch ( JsonProcessingException e ) { log . error ( "Failed to parse body class as " + bodyClass + " for message " + header , e ) ; throw e ; } catch ( IOException e ) { log . error ( "Failed to parse body class as " + bodyClass + " for message " + header , e ) ; throw e ; } parser . nextToken ( ) ; // the end token for body. } parser . nextToken ( ) ; // the end token for the document. parser . close ( ) ; @ SuppressWarnings ( "unchecked" ) Message < B > cMessage = new Message < B > ( header , ( B ) body ) ; return cMessage ; } | Deserializes the JSON content of a JGroups message into a cadmium message . | 348 | 19 |
22,451 | private Class < ? > lookupBodyClass ( Header header ) throws IOException { if ( header == null ) throw new IOException ( "Could not deserialize message body: no header." ) ; if ( header . getCommand ( ) == null ) throw new IOException ( "Could not deserialize message body: no command declared." ) ; Class < ? > commandBodyClass = commandToBodyMapping . get ( header . getCommand ( ) ) ; if ( commandBodyClass == null ) throw new IOException ( "Could not deserialize message body: no body class defined for " + header . getCommand ( ) + "." ) ; return commandBodyClass ; } | Looks up the body type for a message based on the command in the specified header object . | 142 | 18 |
22,452 | public static boolean isValidBranchName ( String branch , String prefix ) throws Exception { if ( StringUtils . isNotBlank ( prefix ) && StringUtils . isNotBlank ( branch ) ) { if ( StringUtils . startsWithIgnoreCase ( branch , prefix + "-" ) ) { return true ; } else { System . err . println ( "Branch name must start with prefix \"" + prefix + "-\"." ) ; } } else { return true ; } return false ; } | Validates the branch name that will be sent to the given prefix . | 108 | 14 |
22,453 | public void configurationUpdated ( Object emailConfig ) { EmailConfiguration config = ( EmailConfiguration ) emailConfig ; if ( config != null && ( this . config == null || ! config . equals ( this . config ) ) ) { log . info ( "Updating configuration for email." ) ; this . config = config ; //Set the captcha validator up. if ( ! StringUtils . isEmptyOrNull ( config . getCaptchaPrivateKey ( ) ) ) { log . info ( "Setting up captcha validation: " + config . getCaptchaPrivateKey ( ) ) ; captchaValidator = new CaptchaValidator ( config . getCaptchaPrivateKey ( ) ) ; } else { log . info ( "Unsetting captcha validation." ) ; captchaValidator = null ; } // Need to get the Session Strategy and Transform class names out of the // Dictionary, and then use reflection to use them Dictionary < String , Object > props = new Hashtable < String , Object > ( ) ; if ( ! StringUtils . isEmptyOrNull ( config . getJndiName ( ) ) ) { props . put ( "com.meltmedia.email.jndi" , config . getJndiName ( ) ) ; log . debug ( "Using jndiName: " + config . getJndiName ( ) ) ; } log . debug ( "Using {} as the default from address." , config . getDefaultFromAddress ( ) ) ; if ( StringUtils . isEmptyOrNull ( config . getSessionStrategy ( ) ) ) { config . setSessionStrategy ( null ) ; } log . debug ( "Using mail session strategy: " + config . getSessionStrategy ( ) ) ; if ( StringUtils . isEmptyOrNull ( config . getMessageTransformer ( ) ) ) { config . setMessageTransformer ( DEFAULT_MESSAGE_TRANSFORMER ) ; } log . debug ( "Using message transformer: " + config . getMessageTransformer ( ) ) ; EmailSetup newSetup = new EmailSetup ( ) ; SessionStrategy strategy = null ; MessageTransformer transformer = null ; try { if ( config . getSessionStrategy ( ) != null ) { strategy = setSessionStrategy ( config , props , newSetup ) ; } } catch ( Exception e ) { log . error ( "Error Registering Mail Session Strategy " + config . getSessionStrategy ( ) , e ) ; config . setSessionStrategy ( null ) ; } try { transformer = setMessageTransformer ( config , newSetup ) ; } catch ( Exception e ) { log . error ( "Error Registering Mail Session Strategy " + config . getSessionStrategy ( ) , e ) ; config . setMessageTransformer ( DEFAULT_MESSAGE_TRANSFORMER ) ; try { transformer = setMessageTransformer ( config , newSetup ) ; } catch ( Exception e1 ) { log . error ( "Failed to fall back to default message transformer." , e1 ) ; } } this . setup = newSetup ; log . debug ( "Using new config jndi {}, strategy {}, transformer {}" , new Object [ ] { config . getJndiName ( ) , strategy , transformer } ) ; } } | Updates the Email Service component configuration . | 691 | 8 |
22,454 | public void send ( Email email ) throws EmailException { synchronized ( this ) { EmailConnection connection = openConnection ( ) ; connection . connect ( ) ; connection . send ( email ) ; connection . close ( ) ; } } | Opens a connection sends the email then closes the connection | 46 | 11 |
22,455 | public static WarInfo getDeployedWarInfo ( String url , String warName , String token ) throws Exception { HttpClient client = httpClient ( ) ; HttpGet get = new HttpGet ( url + "/system/deployment/details/" + warName ) ; addAuthHeader ( token , get ) ; HttpResponse resp = client . execute ( get ) ; if ( resp . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { WarInfo info = new Gson ( ) . fromJson ( EntityUtils . toString ( resp . getEntity ( ) ) , WarInfo . class ) ; return info ; } return null ; } | Retrieves information about a deployed cadmium war . | 148 | 12 |
22,456 | @ SuppressWarnings ( "unchecked" ) private void mergeConfigs ( Map < String , Map < String , ? > > configurationMap , Object parsed ) { if ( parsed instanceof Map ) { Map < ? , ? > parsedMap = ( Map < ? , ? > ) parsed ; for ( Object key : parsedMap . keySet ( ) ) { if ( key instanceof String ) { Map < String , Object > existingValue = ( Map < String , Object > ) configurationMap . get ( ( String ) key ) ; if ( ! configurationMap . containsKey ( ( String ) key ) ) { existingValue = new HashMap < String , Object > ( ) ; configurationMap . put ( ( String ) key , existingValue ) ; } Object parsedValue = parsedMap . get ( key ) ; if ( parsedValue instanceof Map ) { Map < ? , ? > parsedValueMap = ( Map < ? , ? > ) parsedValue ; for ( Object parsedKey : parsedValueMap . keySet ( ) ) { if ( parsedKey instanceof String ) { existingValue . put ( ( String ) parsedKey , parsedValueMap . get ( parsedKey ) ) ; } } } } } } } | Merges configurations from an Object into an existing Map . | 254 | 11 |
22,457 | private < T > T getEnvConfig ( Map < String , ? > configs , String key , Class < T > type ) { if ( configs . containsKey ( key ) ) { Object config = configs . get ( key ) ; if ( type . isAssignableFrom ( config . getClass ( ) ) ) { return type . cast ( config ) ; } } return null ; } | Helper method used to retrieve the value from a given map if it matches the type specified . | 85 | 18 |
22,458 | @ SuppressWarnings ( "rawtypes" ) @ Override public EntityManagerFactory createEntityManagerFactory ( String emName , Map properties ) { PersistenceUnitInfo pUnit = new CadmiumPersistenceUnitInfo ( ) ; return createContainerEntityManagerFactory ( pUnit , properties ) ; } | Uses Hibernate s Reflections and the properties map to override defaults to create a EntityManagerFactory without the need of any persistence . xml file . | 64 | 32 |
22,459 | @ SuppressWarnings ( "rawtypes" ) @ Override public EntityManagerFactory createContainerEntityManagerFactory ( PersistenceUnitInfo info , Map properties ) { EntityManagerFactory factory = wrappedPersistenceProvider . createContainerEntityManagerFactory ( info , properties ) ; return factory ; } | This just delegates to the HibernatePersistence method . | 60 | 13 |
22,460 | @ GET public Response getConfigurableUsers ( @ HeaderParam ( "Authorization" ) @ DefaultValue ( "no token" ) String auth ) throws Exception { if ( ! this . isAuth ( auth ) ) { throw new Exception ( "Unauthorized!" ) ; } if ( realm != null ) { List < String > usernames = new ArrayList < String > ( ) ; usernames = realm . listUsers ( ) ; return Response . ok ( new Gson ( ) . toJson ( usernames ) , MediaType . APPLICATION_JSON ) . build ( ) ; } return Response . status ( Status . NOT_FOUND ) . build ( ) ; } | Returns a list of users specific to this site only . | 145 | 11 |
22,461 | @ PUT @ Path ( "{user}" ) @ Consumes ( MediaType . TEXT_PLAIN ) public Response addUser ( @ PathParam ( "user" ) String username , @ HeaderParam ( "Authorization" ) @ DefaultValue ( "no token" ) String auth , String message ) throws Exception { if ( ! this . isAuth ( auth ) ) { throw new Exception ( "Unauthorized!" ) ; } if ( realm != null ) { AuthenticationManagerRequest req = new AuthenticationManagerRequest ( ) ; req . setAccountName ( username ) ; req . setPassword ( message ) ; req . setRequestType ( RequestType . ADD ) ; sendMessage ( req ) ; return Response . created ( new URI ( "" ) ) . build ( ) ; } return Response . status ( Status . NOT_FOUND ) . build ( ) ; } | Adds user credentials for access to this site only . | 179 | 10 |
22,462 | @ DELETE @ Path ( "{user}" ) public Response deleteUser ( @ PathParam ( "user" ) String username , @ HeaderParam ( "Authorization" ) @ DefaultValue ( "no token" ) String auth ) throws Exception { if ( ! this . isAuth ( auth ) ) { throw new Exception ( "Unauthorized!" ) ; } if ( realm != null ) { AuthenticationManagerRequest req = new AuthenticationManagerRequest ( ) ; req . setAccountName ( username ) ; req . setRequestType ( RequestType . REMOVE ) ; sendMessage ( req ) ; return Response . status ( Status . GONE ) . build ( ) ; } return Response . status ( Status . NOT_FOUND ) . build ( ) ; } | Deletes an user from the user acounts specific to this site only . | 158 | 16 |
22,463 | private void sendMessage ( AuthenticationManagerRequest req ) { Message < AuthenticationManagerRequest > msg = new Message < AuthenticationManagerRequest > ( AuthenticationManagerCommandAction . COMMAND_NAME , req ) ; try { sender . sendMessage ( msg , null ) ; } catch ( Exception e ) { log . error ( "Failed to update authentication." , e ) ; } } | Generically send a JGroups message to the cluster . | 76 | 12 |
22,464 | @ GET @ Path ( "teams" ) public Response authorizedTeams ( @ HeaderParam ( "Authorization" ) @ DefaultValue ( "no token" ) String auth ) throws Exception { if ( ! this . isAuth ( auth ) ) { return Response . status ( Status . FORBIDDEN ) . build ( ) ; } Integer teams [ ] = getAuthorizedTeams ( ) ; return Response . ok ( new Gson ( ) . toJson ( teams ) , MediaType . APPLICATION_JSON ) . build ( ) ; } | Get the list of github team ids that are allowed to access this instance . | 115 | 16 |
22,465 | private void sendRequest ( HttpUriRequest request , int expectedStatus ) throws Exception { addAuthHeader ( request ) ; HttpClient client = httpClient ( ) ; HttpResponse response = client . execute ( request ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_NOT_FOUND ) { EntityUtils . consume ( response . getEntity ( ) ) ; System . err . println ( "Authentication has been disabled for " + args . get ( 1 ) + "." ) ; } else if ( response . getStatusLine ( ) . getStatusCode ( ) == expectedStatus ) { if ( expectedStatus == HttpStatus . SC_OK ) { String responseStr = EntityUtils . toString ( response . getEntity ( ) ) ; List < String > usernames = new Gson ( ) . fromJson ( responseStr , new TypeToken < List < String > > ( ) { } . getType ( ) ) ; if ( usernames == null || usernames . isEmpty ( ) ) { System . out . println ( "There have been no site specific users created." ) ; } else { System . out . println ( usernames . size ( ) + " Users:" ) ; for ( String user : usernames ) { System . out . println ( user ) ; } } } } else { System . err . println ( EntityUtils . toString ( response . getEntity ( ) ) ) ; System . err . println ( "Unexpected status code returned. " + response . getStatusLine ( ) . getStatusCode ( ) ) ; } } | Sends a request to the rest endpoint . | 349 | 9 |
22,466 | private String hashPasswordForShiro ( ) { //Hash password HashFormatFactory HASH_FORMAT_FACTORY = new DefaultHashFormatFactory ( ) ; SecureRandomNumberGenerator generator = new SecureRandomNumberGenerator ( ) ; int byteSize = 128 / 8 ; ByteSource salt = generator . nextBytes ( byteSize ) ; SimpleHash hash = new SimpleHash ( "SHA-256" , password , salt , 10 ) ; HashFormat format = HASH_FORMAT_FACTORY . getInstance ( "shiro1" ) ; return format . format ( hash ) ; } | Hashes a password the shiro way . | 125 | 9 |
22,467 | public static Field createTupleField ( String name , Schema schema ) { return Field . createTupleField ( name , schema ) ; } | Creates a field containing a Pangool Tuple . | 30 | 12 |
22,468 | @ Override protected void configure ( ) { try { InternalLoggerFactory . setDefaultFactory ( new Slf4JLoggerFactory ( ) ) ; File appRoot = new File ( System . getProperty ( CadmiumListener . BASE_PATH_ENV ) , "maven" ) ; FileUtils . forceMkdir ( appRoot ) ; String remoteMavenRepo = System . getProperty ( MAVEN_REPOSITORY ) ; ArtifactResolver resolver = new ArtifactResolver ( remoteMavenRepo , appRoot . getAbsolutePath ( ) ) ; bind ( ArtifactResolver . class ) . toInstance ( resolver ) ; bind ( JBossAdminApi . class ) ; Multibinder < ConfigurationListener > listenerBinder = Multibinder . newSetBinder ( binder ( ) , ConfigurationListener . class ) ; listenerBinder . addBinding ( ) . to ( JBossAdminApi . class ) ; bind ( IJBossUtil . class ) . to ( JBossDelegator . class ) ; } catch ( Exception e ) { logger . error ( "Failed to initialize maven artifact resolver." , e ) ; } } | Called to do all bindings for this module . | 254 | 10 |
22,469 | public static Response internalError ( Throwable throwable , UriInfo uriInfo ) { GenericError error = new GenericError ( ExceptionUtils . getRootCauseMessage ( throwable ) , ErrorCode . INTERNAL . getCode ( ) , uriInfo . getAbsolutePath ( ) . toString ( ) ) ; if ( ! isProduction ( ) ) { error . setStack ( ExceptionUtils . getStackTrace ( throwable ) ) ; } return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . type ( MediaType . APPLICATION_JSON_TYPE ) . entity ( error ) . build ( ) ; } | Creates Jersey response corresponding to internal error | 139 | 8 |
22,470 | public static GitService initializeConfigDirectory ( String uri , String branch , String root , String warName , HistoryManager historyManager , ConfigManager configManager ) throws Exception { initializeBaseDirectoryStructure ( root , warName ) ; String warDir = FileSystemManager . getChildDirectoryIfExists ( root , warName ) ; Properties configProperties = configManager . getDefaultProperties ( ) ; GitLocation gitLocation = new GitLocation ( uri , branch , configProperties . getProperty ( "config.git.ref.sha" ) ) ; GitService cloned = initializeRepo ( gitLocation , warDir , "git-config-checkout" ) ; try { String renderedContentDir = initializeSnapshotDirectory ( warDir , configProperties , "com.meltmedia.cadmium.config.lastUpdated" , "git-config-checkout" , "config" ) ; boolean hasExisting = configProperties . containsKey ( "com.meltmedia.cadmium.config.lastUpdated" ) && renderedContentDir != null && renderedContentDir . equals ( configProperties . getProperty ( "com.meltmedia.cadmium.config.lastUpdated" ) ) ; if ( renderedContentDir != null ) { configProperties . setProperty ( "com.meltmedia.cadmium.config.lastUpdated" , renderedContentDir ) ; } configProperties . setProperty ( "config.branch" , cloned . getBranchName ( ) ) ; configProperties . setProperty ( "config.git.ref.sha" , cloned . getCurrentRevision ( ) ) ; configProperties . setProperty ( "config.repo" , cloned . getRemoteRepository ( ) ) ; configManager . persistDefaultProperties ( ) ; ExecutorService pool = null ; if ( historyManager == null ) { pool = Executors . newSingleThreadExecutor ( ) ; historyManager = new HistoryManager ( warDir , pool ) ; } try { if ( historyManager != null && ! hasExisting ) { historyManager . logEvent ( EntryType . CONFIG , // NOTE: We should integrate the git pointer into this class. new GitLocation ( cloned . getRemoteRepository ( ) , cloned . getBranchName ( ) , cloned . getCurrentRevision ( ) ) , "AUTO" , renderedContentDir , "" , "Initial config pull." , true , true ) ; } } finally { if ( pool != null ) { pool . shutdownNow ( ) ; } } return cloned ; } catch ( Throwable e ) { cloned . close ( ) ; throw new Exception ( e ) ; } } | Initializes war configuration directory for a Cadmium war . | 577 | 12 |
22,471 | public String checkinNewContent ( String sourceDirectory , String message ) throws Exception { RmCommand remove = git . rm ( ) ; boolean hasFiles = false ; for ( String filename : new File ( getBaseDirectory ( ) ) . list ( ) ) { if ( ! filename . equals ( ".git" ) ) { remove . addFilepattern ( filename ) ; hasFiles = true ; } } if ( hasFiles ) { log . info ( "Removing old content." ) ; remove . call ( ) ; } log . info ( "Copying in new content." ) ; FileSystemManager . copyAllContent ( sourceDirectory , getBaseDirectory ( ) , true ) ; log . info ( "Adding new content." ) ; AddCommand add = git . add ( ) ; for ( String filename : new File ( getBaseDirectory ( ) ) . list ( ) ) { if ( ! filename . equals ( ".git" ) ) { add . addFilepattern ( filename ) ; } } add . call ( ) ; log . info ( "Committing new content." ) ; git . commit ( ) . setMessage ( message ) . call ( ) ; return getCurrentRevision ( ) ; } | Checks in content from a source directory into the current git repository . | 249 | 14 |
22,472 | public ObjectNode convertToObjectNode ( ILoggingEvent event ) { final ObjectNode logLine = mapper . valueToTree ( event instanceof OtlType ? event : new ApplicationLogEvent ( event ) ) ; final Marker marker = event . getMarker ( ) ; if ( marker instanceof LogMetadata ) { ObjectNode metadataNode = mapper . valueToTree ( ( ( LogMetadata ) marker ) . getMetadata ( ) ) ; logLine . setAll ( metadataNode ) ; for ( Object o : ( ( LogMetadata ) marker ) . getInlines ( ) ) { metadataNode = mapper . valueToTree ( o ) ; logLine . setAll ( metadataNode ) ; } } if ( marker instanceof OtlMarker ) { ObjectNode metadataNode = mapper . valueToTree ( ( ( OtlMarker ) marker ) . getOtl ( ) ) ; logLine . setAll ( metadataNode ) ; } for ( Entry < String , String > e : event . getMDCPropertyMap ( ) . entrySet ( ) ) { if ( ! logLine . has ( e . getKey ( ) ) ) { logLine . put ( e . getKey ( ) , e . getValue ( ) ) ; } } logLine . put ( "sequencenumber" , LOG_SEQUENCE_NUMBER . incrementAndGet ( ) ) ; return logLine ; } | Prepare a log event but don t append it return it as an ObjectNode instead . | 302 | 18 |
22,473 | protected byte [ ] getLogMessage ( final ObjectNode event ) { try ( ByteArrayBuilder buf = new ByteArrayBuilder ( ) ) { mapper . writeValue ( buf , event ) ; buf . append ( ' ' ) ; return buf . toByteArray ( ) ; } catch ( IOException e ) { addError ( "while serializing log event" , e ) ; return NADA ; } } | Convert the JSON object to a byte array to log | 85 | 11 |
22,474 | public void execute ( ) throws Exception { String content = null ; String siteUrl = null ; if ( params . size ( ) == 2 ) { content = params . get ( 0 ) ; siteUrl = getSecureBaseUrl ( params . get ( 1 ) ) ; } else if ( params . size ( ) == 0 ) { System . err . println ( "The content directory and site must be specifed." ) ; System . exit ( 1 ) ; } else { System . err . println ( "Too many parameters were specified." ) ; System . exit ( 1 ) ; } GitService git = null ; try { System . out . println ( "Getting status of [" + siteUrl + "]" ) ; Status status = StatusCommand . getSiteStatus ( siteUrl , token ) ; if ( repo != null ) { status . setRepo ( repo ) ; } status . setRevision ( null ) ; System . out . println ( "Cloning repository that [" + siteUrl + "] is serving" ) ; git = CloneCommand . cloneSiteRepo ( status ) ; String revision = status . getRevision ( ) ; String branch = status . getBranch ( ) ; if ( ! UpdateCommand . isValidBranchName ( branch , UpdateRequest . CONTENT_BRANCH_PREFIX ) ) { throw new Exception ( "Cannot commit to a branch without the prefix of " + UpdateRequest . CONTENT_BRANCH_PREFIX + "." ) ; } if ( git . isTag ( branch ) ) { throw new Exception ( "Cannot commit to a tag!" ) ; } System . out . println ( "Cloning content from [" + content + "] to [" + siteUrl + ":" + branch + "]" ) ; revision = CloneCommand . cloneContent ( content , git , comment ) ; System . out . println ( "Switching content on [" + siteUrl + "]" ) ; if ( ! UpdateCommand . sendUpdateMessage ( siteUrl , null , branch , revision , comment , token ) ) { System . err . println ( "Failed to update [" + siteUrl + "]" ) ; System . exit ( 1 ) ; } } catch ( Exception e ) { System . err . println ( "Failed to commit changes to [" + siteUrl + "]: " + e . getMessage ( ) ) ; System . exit ( 1 ) ; } finally { if ( git != null ) { String dir = git . getBaseDirectory ( ) ; git . close ( ) ; FileUtils . forceDelete ( new File ( dir ) ) ; } } } | Does the work for this command . | 548 | 7 |
22,475 | public static void enableSerialization ( Configuration conf ) { String serClass = TupleSerialization . class . getName ( ) ; Collection < String > currentSers = conf . getStringCollection ( "io.serializations" ) ; if ( currentSers . size ( ) == 0 ) { conf . set ( "io.serializations" , serClass ) ; return ; } // Check if it is already present if ( ! currentSers . contains ( serClass ) ) { currentSers . add ( serClass ) ; conf . setStrings ( "io.serializations" , currentSers . toArray ( new String [ ] { } ) ) ; } } | Use this method to enable this serialization in Hadoop | 142 | 12 |
22,476 | public static void disableSerialization ( Configuration conf ) { String ser = conf . get ( "io.serializations" ) . trim ( ) ; String stToSearch = Pattern . quote ( "," + TupleSerialization . class . getName ( ) ) ; ser = ser . replaceAll ( stToSearch , "" ) ; conf . set ( "io.serializations" , ser ) ; } | Use this method to disable this serialization in Hadoop | 84 | 12 |
22,477 | public static int compare ( String ns1 , String ln1 , String ns2 , String ln2 ) { if ( ns1 == null ) { ns1 = Constants . XML_NULL_NS_URI ; } if ( ns2 == null ) { ns2 = Constants . XML_NULL_NS_URI ; } int cLocalPart = ln1 . compareTo ( ln2 ) ; return ( cLocalPart == 0 ? ns1 . compareTo ( ns2 ) : cLocalPart ) ; } | Sort lexicographically by qname local - name then by qname uri | 111 | 16 |
22,478 | public static void postConstructQuietly ( Object obj , Logger log ) { try { postConstruct ( obj , log ) ; } catch ( Throwable t ) { log . warn ( "Could not @PostConstruct object" , t ) ; } } | Calls postConstruct with the same arguments logging any exceptions that are thrown at the level warn . | 53 | 19 |
22,479 | public static void preDestroyQuietly ( Object obj , Logger log ) { try { preDestroy ( obj , log ) ; } catch ( Throwable t ) { log . warn ( "Could not @PreDestroy object" , t ) ; } } | Calls preDestroy with the same arguments logging any exceptions that are thrown at the level warn . | 53 | 19 |
22,480 | private static List < Method > getAnnotatedMethodsFromChildToParent ( Class < ? > clazz , Class < ? extends Annotation > annotation , Logger log ) { List < Method > methodsToRun = new ArrayList < Method > ( ) ; while ( clazz != null ) { List < Method > newMethods = getMethodsWithAnnotation ( clazz , annotation , log ) ; for ( Method newMethod : newMethods ) { if ( containsMethod ( newMethod , methodsToRun ) ) { removeMethodByName ( newMethod , methodsToRun ) ; } else { methodsToRun . add ( newMethod ) ; } } clazz = clazz . getSuperclass ( ) ; if ( clazz != null && clazz . equals ( Object . class ) ) { clazz = null ; } } return methodsToRun ; } | Locates all annotated methods on the type passed in sorted as declared from the type to its super class . | 178 | 22 |
22,481 | private static boolean containsMethod ( Method method , List < Method > methods ) { if ( methods != null ) { for ( Method aMethod : methods ) { if ( method . getName ( ) . equals ( aMethod . getName ( ) ) ) { return true ; } } } return false ; } | Checks if the passed in method already exists in the list of methods . Checks for equality by the name of the method . | 63 | 25 |
22,482 | private static void removeMethodByName ( Method method , List < Method > methods ) { if ( methods != null ) { Iterator < Method > itr = methods . iterator ( ) ; Method aMethod = null ; while ( itr . hasNext ( ) ) { aMethod = itr . next ( ) ; if ( aMethod . getName ( ) . equals ( method . getName ( ) ) ) { itr . remove ( ) ; break ; } } if ( aMethod != null ) { methods . add ( aMethod ) ; } } } | Removes a method from the given list and adds it to the end of the list . | 117 | 18 |
22,483 | private static List < Method > getMethodsWithAnnotation ( Class < ? > clazz , Class < ? extends Annotation > annotation , Logger log ) { List < Method > annotatedMethods = new ArrayList < Method > ( ) ; Method classMethods [ ] = clazz . getDeclaredMethods ( ) ; for ( Method classMethod : classMethods ) { if ( classMethod . isAnnotationPresent ( annotation ) && classMethod . getParameterTypes ( ) . length == 0 ) { if ( ! containsMethod ( classMethod , annotatedMethods ) ) { annotatedMethods . add ( classMethod ) ; } } } Collections . sort ( annotatedMethods , new Comparator < Method > ( ) { @ Override public int compare ( Method method1 , Method method2 ) { return method1 . getName ( ) . compareTo ( method2 . getName ( ) ) ; } } ) ; return annotatedMethods ; } | Locates all methods annotated with a given annotation that are declared directly in the class passed in alphabetical order . | 195 | 23 |
22,484 | public static Jsr250Executor createJsr250Executor ( Injector injector , final Logger log , Scope ... scopes ) { final Set < Object > instances = findInstancesInScopes ( injector , scopes ) ; final List < Object > reverseInstances = new ArrayList < Object > ( instances ) ; Collections . reverse ( reverseInstances ) ; return new Jsr250Executor ( ) { @ Override public Set < Object > getInstances ( ) { return instances ; } @ Override public void postConstruct ( ) { for ( Object instance : instances ) { postConstructQuietly ( instance , log ) ; } } @ Override public void preDestroy ( ) { for ( Object instance : reverseInstances ) { preDestroyQuietly ( instance , log ) ; } } } ; } | Creates a Jsr250Executor for the specified scopes . | 175 | 14 |
22,485 | public static Set < Object > findInstancesInScopes ( Injector injector , Class < ? extends Annotation > ... scopeAnnotations ) { Set < Object > objects = new TreeSet < Object > ( new Comparator < Object > ( ) { @ Override public int compare ( Object o0 , Object o1 ) { return o0 . getClass ( ) . getName ( ) . compareTo ( o1 . getClass ( ) . getName ( ) ) ; } } ) ; for ( Map . Entry < Key < ? > , Binding < ? > > entry : findBindingsInScope ( injector , scopeAnnotations ) . entrySet ( ) ) { Object object = injector . getInstance ( entry . getKey ( ) ) ; objects . add ( object ) ; } return objects ; } | Finds all of the instances in the specified scopes . | 172 | 12 |
22,486 | public static Map < Key < ? > , Binding < ? > > findBindingsInScope ( Injector injector , Class < ? extends Annotation > ... scopeAnnotations ) { Map < Key < ? > , Binding < ? > > bindings = new LinkedHashMap < Key < ? > , Binding < ? > > ( ) ; ALL_BINDINGS : for ( Map . Entry < Key < ? > , Binding < ? > > entry : injector . getAllBindings ( ) . entrySet ( ) ) { for ( Class < ? extends Annotation > scopeAnnotation : scopeAnnotations ) { if ( inScope ( injector , entry . getValue ( ) , scopeAnnotation ) ) { bindings . put ( entry . getKey ( ) , entry . getValue ( ) ) ; continue ALL_BINDINGS ; } } } return bindings ; } | Finds all of the unique providers in the injector in the specified scopes . | 184 | 17 |
22,487 | public static Map < Key < ? > , Binding < ? > > findBindingsInScope ( Injector injector , Scope ... scopes ) { Map < Key < ? > , Binding < ? > > bindings = new LinkedHashMap < Key < ? > , Binding < ? > > ( ) ; ALL_BINDINGS : for ( Map . Entry < Key < ? > , Binding < ? > > entry : injector . getAllBindings ( ) . entrySet ( ) ) { for ( Scope scope : scopes ) { if ( inScope ( injector , entry . getValue ( ) , scope ) ) { bindings . put ( entry . getKey ( ) , entry . getValue ( ) ) ; continue ALL_BINDINGS ; } } } return bindings ; } | Returns the bindings in the specified scope . | 166 | 8 |
22,488 | public static boolean inScope ( final Injector injector , final Binding < ? > binding , final Class < ? extends Annotation > scope ) { return binding . acceptScopingVisitor ( new BindingScopingVisitor < Boolean > ( ) { @ Override public Boolean visitEagerSingleton ( ) { return scope == Singleton . class || scope == javax . inject . Singleton . class ; } @ Override public Boolean visitNoScoping ( ) { return false ; } @ Override public Boolean visitScope ( Scope guiceScope ) { return injector . getScopeBindings ( ) . get ( scope ) == guiceScope ; } @ Override public Boolean visitScopeAnnotation ( Class < ? extends Annotation > scopeAnnotation ) { return scopeAnnotation == scope ; } } ) ; } | Returns true if the binding is in the specified scope false otherwise . | 172 | 13 |
22,489 | private void init ( Class < ? > type ) { if ( method . isAnnotationPresent ( CoordinatorOnly . class ) || type . isAnnotationPresent ( CoordinatorOnly . class ) ) { coordinatorOnly = true ; } if ( method . isAnnotationPresent ( Scheduled . class ) ) { annotation = method . getAnnotation ( Scheduled . class ) ; } else if ( type . isAnnotationPresent ( Scheduled . class ) ) { annotation = type . getAnnotation ( Scheduled . class ) ; } } | Sets all values needed for the scheduling of this Runnable . | 110 | 14 |
22,490 | private void checkRunnable ( Class < ? > type ) { if ( Runnable . class . isAssignableFrom ( type ) ) { try { this . method = type . getMethod ( "run" ) ; } catch ( Exception e ) { throw new RuntimeException ( "Cannot get run method of runnable class." , e ) ; } } } | Checks if the type is a Runnable and gets the run method . | 79 | 16 |
22,491 | public static String [ ] sendRequest ( String token , String site , OPERATION op , String path ) throws Exception { HttpClient client = httpClient ( ) ; HttpUriRequest message = null ; if ( op == OPERATION . DISABLE ) { message = new HttpPut ( site + ENDPOINT + path ) ; } else if ( op == OPERATION . ENABLE ) { message = new HttpDelete ( site + ENDPOINT + path ) ; } else { message = new HttpGet ( site + ENDPOINT ) ; } addAuthHeader ( token , message ) ; HttpResponse resp = client . execute ( message ) ; if ( resp . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { String results = EntityUtils . toString ( resp . getEntity ( ) ) ; return new Gson ( ) . fromJson ( results , String [ ] . class ) ; } return null ; } | Sends acl request to cadmium . | 210 | 10 |
22,492 | public void shallowCopy ( ITuple tupleDest ) { for ( Field field : this . getSchema ( ) . getFields ( ) ) { tupleDest . set ( field . getName ( ) , this . get ( field . getName ( ) ) ) ; } } | Simple shallow copy of this Tuple to another Tuple . | 58 | 12 |
22,493 | public static final String getQualifiedName ( String localName , String pfx ) { pfx = pfx == null ? "" : pfx ; return pfx . length ( ) == 0 ? localName : ( pfx + Constants . COLON + localName ) ; } | Returns qualified name as String | 59 | 5 |
22,494 | public void setOption ( String key , Object value ) throws UnsupportedOption { if ( key . equals ( INCLUDE_COOKIE ) ) { options . put ( key , null ) ; } else if ( key . equals ( INCLUDE_OPTIONS ) ) { options . put ( key , null ) ; } else if ( key . equals ( INCLUDE_SCHEMA_ID ) ) { options . put ( key , null ) ; } else if ( key . equals ( RETAIN_ENTITY_REFERENCE ) ) { options . put ( key , null ) ; } else if ( key . equals ( INCLUDE_XSI_SCHEMALOCATION ) ) { options . put ( key , null ) ; } else if ( key . equals ( INCLUDE_INSIGNIFICANT_XSI_NIL ) ) { options . put ( key , null ) ; } else if ( key . equals ( INCLUDE_PROFILE_VALUES ) ) { options . put ( key , null ) ; } else if ( key . equals ( CANONICAL_EXI ) ) { options . put ( key , null ) ; // by default the Canonical EXI Option "omitOptionsDocument" is // false // --> include options this . setOption ( INCLUDE_OPTIONS ) ; } else if ( key . equals ( UTC_TIME ) ) { options . put ( key , null ) ; } else if ( key . equals ( DEFLATE_COMPRESSION_VALUE ) ) { if ( value != null && value instanceof Integer ) { options . put ( key , value ) ; } else { throw new UnsupportedOption ( "EncodingOption '" + key + "' requires value of type Integer" ) ; } } else { throw new UnsupportedOption ( "EncodingOption '" + key + "' is unknown!" ) ; } } | Enables given option with value . | 410 | 7 |
22,495 | public boolean unsetOption ( String key ) { // we do have null values --> check for key boolean b = options . containsKey ( key ) ; options . remove ( key ) ; return b ; } | Disables given option . | 42 | 5 |
22,496 | private static void checkNamedOutputName ( JobContext job , String namedOutput , boolean alreadyDefined ) { validateOutputName ( namedOutput ) ; List < String > definedChannels = getNamedOutputsList ( job ) ; if ( alreadyDefined && definedChannels . contains ( namedOutput ) ) { throw new IllegalArgumentException ( "Named output '" + namedOutput + "' already alreadyDefined" ) ; } else if ( ! alreadyDefined && ! definedChannels . contains ( namedOutput ) ) { throw new IllegalArgumentException ( "Named output '" + namedOutput + "' not defined" ) ; } } | Checks if a named output name is valid . | 137 | 10 |
22,497 | private static String getDefaultNamedOutputFormatInstanceFile ( JobContext job ) { return job . getConfiguration ( ) . get ( DEFAULT_MO_PREFIX + FORMAT_INSTANCE_FILE , null ) ; } | Returns the DEFAULT named output OutputFormat . | 48 | 9 |
22,498 | private static Class < ? > getDefaultNamedOutputKeyClass ( JobContext job ) { return job . getConfiguration ( ) . getClass ( DEFAULT_MO_PREFIX + KEY , null , Object . class ) ; } | Returns the DEFAULT key class for a named output . | 49 | 11 |
22,499 | private static Class < ? > getDefaultNamedOutputValueClass ( JobContext job ) { return job . getConfiguration ( ) . getClass ( DEFAULT_MO_PREFIX + VALUE , null , Object . class ) ; } | Returns the DEFAULT value class for a named output . | 50 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.