idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
22,400 | public LinkedMultiValueMap < K , V > deepCopy ( ) { LinkedMultiValueMap < K , V > copy = new LinkedMultiValueMap < > ( this . size ( ) ) ; this . forEach ( ( key , value ) -> copy . put ( key , new LinkedList < > ( value ) ) ) ; return copy ; } | Create a deep copy of this Map . |
22,401 | protected void executeAdvice ( Executable action ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Action " + action ) ; } try { action . execute ( this ) ; } catch ( Exception e ) { setRaisedException ( e ) ; throw new ActionExecutionException ( "Failed to execute advice action " + action , e ) ; } } | Executes advice action . |
22,402 | @ SuppressWarnings ( "unchecked" ) public < T > T getAspectAdviceBean ( String aspectId ) { return ( aspectAdviceResult != null ? ( T ) aspectAdviceResult . getAspectAdviceBean ( aspectId ) : null ) ; } | Gets the aspect advice bean . |
22,403 | protected void putAspectAdviceBean ( String aspectId , Object adviceBean ) { if ( aspectAdviceResult == null ) { aspectAdviceResult = new AspectAdviceResult ( ) ; } aspectAdviceResult . putAspectAdviceBean ( aspectId , adviceBean ) ; } | Puts the aspect advice bean . |
22,404 | @ SuppressWarnings ( "unchecked" ) public < T > T getBeforeAdviceResult ( String aspectId ) { return ( aspectAdviceResult != null ? ( T ) aspectAdviceResult . getBeforeAdviceResult ( aspectId ) : null ) ; } | Gets the before advice result . |
22,405 | @ SuppressWarnings ( "unchecked" ) public < T > T getAfterAdviceResult ( String aspectId ) { return ( aspectAdviceResult != null ? ( T ) aspectAdviceResult . getAfterAdviceResult ( aspectId ) : null ) ; } | Gets the after advice result . |
22,406 | @ SuppressWarnings ( "unchecked" ) public < T > T getAroundAdviceResult ( String aspectId ) { return ( aspectAdviceResult != null ? ( T ) aspectAdviceResult . getAroundAdviceResult ( aspectId ) : null ) ; } | Gets the around advice result . |
22,407 | @ SuppressWarnings ( "unchecked" ) public < T > T getFinallyAdviceResult ( String aspectId ) { return ( aspectAdviceResult != null ? ( T ) aspectAdviceResult . getFinallyAdviceResult ( aspectId ) : null ) ; } | Gets the finally advice result . |
22,408 | protected void putAdviceResult ( AspectAdviceRule aspectAdviceRule , Object adviceActionResult ) { if ( aspectAdviceResult == null ) { aspectAdviceResult = new AspectAdviceResult ( ) ; } aspectAdviceResult . putAdviceResult ( aspectAdviceRule , adviceActionResult ) ; } | Puts the result of the advice . |
22,409 | private ActionList touchActionList ( ) { if ( contentList != null ) { if ( contentList . isExplicit ( ) || contentList . size ( ) != 1 ) { contentList = null ; } else { ActionList actionList = contentList . get ( 0 ) ; if ( actionList . isExplicit ( ) ) { contentList = null ; } } } ActionList actionList ; if ( contentList == null ) { contentList = new ContentList ( false ) ; actionList = new ActionList ( false ) ; contentList . add ( actionList ) ; } else { actionList = contentList . get ( 0 ) ; } return actionList ; } | Returns the action list . If not yet instantiated then create a new one . |
22,410 | public static void setStatus ( HttpStatus httpStatus , Translet translet ) { translet . getResponseAdapter ( ) . setStatus ( httpStatus . value ( ) ) ; } | Sets the status code . |
22,411 | private void outputString ( String s ) throws SAXException { handler . characters ( s . toCharArray ( ) , 0 , s . length ( ) ) ; } | Outputs a string . |
22,412 | protected InputStream getTemplateAsStream ( URL url ) throws IOException { URLConnection conn = url . openConnection ( ) ; return conn . getInputStream ( ) ; } | Gets the template as stream . |
22,413 | public static int search ( String str , String keyw ) { int strLen = str . length ( ) ; int keywLen = keyw . length ( ) ; int pos = 0 ; int cnt = 0 ; if ( keywLen == 0 ) { return 0 ; } while ( ( pos = str . indexOf ( keyw , pos ) ) != - 1 ) { pos += keywLen ; cnt ++ ; if ( pos >= strLen ) { break ; } } return cnt ; } | Returns the number of times the specified string was found in the target string or 0 if there is no specified string . |
22,414 | public static int searchIgnoreCase ( String str , String keyw ) { return search ( str . toLowerCase ( ) , keyw . toLowerCase ( ) ) ; } | Returns the number of times the specified string was found in the target string or 0 if there is no specified string . When searching for the specified string it is not case - sensitive . |
22,415 | public static int search ( CharSequence chars , char c ) { int count = 0 ; for ( int i = 0 ; i < chars . length ( ) ; i ++ ) { if ( chars . charAt ( i ) == c ) { count ++ ; } } return count ; } | Returns the number of times the specified character was found in the target string or 0 if there is no specified character . |
22,416 | public static int searchIgnoreCase ( CharSequence chars , char c ) { int count = 0 ; char cl = Character . toLowerCase ( c ) ; for ( int i = 0 ; i < chars . length ( ) ; i ++ ) { if ( Character . toLowerCase ( chars . charAt ( i ) ) == cl ) { count ++ ; } } return count ; } | Returns the number of times the specified character was found in the target string or 0 if there is no specified character . When searching for the specified character it is not case - sensitive . |
22,417 | public static String toLanguageTag ( Locale locale ) { return locale . getLanguage ( ) + ( hasText ( locale . getCountry ( ) ) ? "-" + locale . getCountry ( ) : EMPTY ) ; } | Determine the RFC 3066 compliant language tag as used for the HTTP Accept - Language header . |
22,418 | public static String convertToHumanFriendlyByteSize ( long size ) { if ( size < 1024 ) { return size + " B" ; } int z = ( 63 - Long . numberOfLeadingZeros ( size ) ) / 10 ; double d = ( double ) size / ( 1L << ( z * 10 ) ) ; String format = ( d % 1.0 == 0 ) ? "%.0f %sB" : "%.1f %sB" ; return String . format ( format , d , " KMGTPE" . charAt ( z ) ) ; } | Convert byte size into human friendly format . |
22,419 | @ SuppressWarnings ( "fallthrough" ) public static long convertToMachineFriendlyByteSize ( String size ) { double d ; try { d = Double . parseDouble ( size . replaceAll ( "[GMK]?[B]?$" , "" ) ) ; } catch ( NumberFormatException e ) { String msg = "Size must be specified as bytes (B), " + "kilobytes (KB), megabytes (MB), gigabytes (GB). " + "E.g. 1024, 1KB, 10M, 10MB, 100G, 100GB" ; throw new NumberFormatException ( msg + " " + e . getMessage ( ) ) ; } long l = Math . round ( d * 1024 * 1024 * 1024L ) ; int index = Math . max ( 0 , size . length ( ) - ( size . endsWith ( "B" ) ? 2 : 1 ) ) ; switch ( size . charAt ( index ) ) { default : l /= 1024 ; case 'K' : l /= 1024 ; case 'M' : l /= 1024 ; case 'G' : return l ; } } | Convert byte size into machine friendly format . |
22,420 | private void scan ( final String targetPath , final String basePackageName , final String relativePackageName , final WildcardMatcher matcher , final SaveHandler saveHandler ) { final File target = new File ( targetPath ) ; if ( ! target . exists ( ) ) { return ; } target . listFiles ( file -> { String fileName = file . getName ( ) ; if ( file . isDirectory ( ) ) { String relativePackageName2 ; if ( relativePackageName == null ) { relativePackageName2 = fileName + ResourceUtils . REGULAR_FILE_SEPARATOR ; } else { relativePackageName2 = relativePackageName + fileName + ResourceUtils . REGULAR_FILE_SEPARATOR ; } String basePath2 = targetPath + fileName + ResourceUtils . REGULAR_FILE_SEPARATOR ; scan ( basePath2 , basePackageName , relativePackageName2 , matcher , saveHandler ) ; } else if ( fileName . endsWith ( ClassUtils . CLASS_FILE_SUFFIX ) ) { String className ; if ( relativePackageName != null ) { className = basePackageName + relativePackageName + fileName . substring ( 0 , fileName . length ( ) - ClassUtils . CLASS_FILE_SUFFIX . length ( ) ) ; } else { className = basePackageName + fileName . substring ( 0 , fileName . length ( ) - ClassUtils . CLASS_FILE_SUFFIX . length ( ) ) ; } String relativePath = className . substring ( basePackageName . length ( ) ) ; if ( matcher . matches ( relativePath ) ) { String resourceName = targetPath + fileName ; Class < ? > targetClass = loadClass ( className ) ; saveHandler . save ( resourceName , targetClass ) ; } } return false ; } ) ; } | Recursive method used to find all classes in a given directory and sub dirs . |
22,421 | public static boolean isAssignableValue ( Class < ? > type , Object value ) { if ( value == null ) { return ! type . isPrimitive ( ) ; } Class < ? > valueType = value . getClass ( ) ; if ( type . isArray ( ) || valueType . isArray ( ) ) { if ( ( type . isArray ( ) && valueType . isArray ( ) ) ) { int len = Array . getLength ( value ) ; if ( len == 0 ) { return true ; } else { Object first = Array . get ( value , 0 ) ; return isAssignableValue ( type . getComponentType ( ) , first ) ; } } } else { if ( type . isInstance ( value ) ) { return true ; } if ( valueType . isPrimitive ( ) && ! type . isPrimitive ( ) && type . equals ( getPrimitiveWrapper ( valueType ) ) ) { return true ; } if ( type . isPrimitive ( ) && ! valueType . isPrimitive ( ) && valueType . equals ( getPrimitiveWrapper ( type ) ) ) { return true ; } } return false ; } | Determine if the given type is assignable from the given value assuming setting by reflection . Considers primitive wrapper classes as assignable to the corresponding primitive types . |
22,422 | public static Object toComponentTypeArray ( Object val , Class < ? > componentType ) { if ( val != null ) { int len = Array . getLength ( val ) ; Object arr = Array . newInstance ( componentType , len ) ; for ( int i = 0 ; i < len ; i ++ ) { Array . set ( arr , i , Array . get ( val , i ) ) ; } return arr ; } else { return null ; } } | Converts an array of objects to an array of the specified component type . |
22,423 | public void addActionResult ( ActionResult actionResult ) { ActionResult existActionResult = getActionResult ( actionResult . getActionId ( ) ) ; if ( existActionResult != null && existActionResult . getResultValue ( ) instanceof ResultValueMap && actionResult . getResultValue ( ) instanceof ResultValueMap ) { ResultValueMap resultValueMap = ( ResultValueMap ) existActionResult . getResultValue ( ) ; resultValueMap . putAll ( ( ResultValueMap ) actionResult . getResultValue ( ) ) ; } else { add ( actionResult ) ; } } | Adds the action result . |
22,424 | private void readParameters ( ) { ItemRuleMap parameterItemRuleMap = getRequestRule ( ) . getParameterItemRuleMap ( ) ; if ( parameterItemRuleMap != null && ! parameterItemRuleMap . isEmpty ( ) ) { ItemRuleList parameterItemRuleList = new ItemRuleList ( parameterItemRuleMap . values ( ) ) ; determineSimpleMode ( parameterItemRuleList ) ; if ( procedural ) { console . setStyle ( "GREEN" ) ; console . writeLine ( "Required parameters:" ) ; console . styleOff ( ) ; if ( ! simpleInputMode ) { for ( ItemRule itemRule : parameterItemRuleList ) { Token [ ] tokens = itemRule . getAllTokens ( ) ; if ( tokens == null ) { Token t = new Token ( TokenType . PARAMETER , itemRule . getName ( ) ) ; t . setDefaultValue ( itemRule . getDefaultValue ( ) ) ; tokens = new Token [ ] { t } ; } String mandatoryMarker = itemRule . isMandatory ( ) ? " * " : " " ; console . setStyle ( "YELLOW" ) ; console . write ( mandatoryMarker ) ; console . styleOff ( ) ; console . setStyle ( "bold" ) ; console . write ( itemRule . getName ( ) ) ; console . styleOff ( ) ; console . write ( ": " ) ; writeToken ( tokens ) ; console . writeLine ( ) ; } } } readRequiredParameters ( parameterItemRuleList ) ; } } | Read required input parameters . |
22,425 | private void readAttributes ( ) { ItemRuleMap attributeItemRuleMap = getRequestRule ( ) . getAttributeItemRuleMap ( ) ; if ( attributeItemRuleMap != null && ! attributeItemRuleMap . isEmpty ( ) ) { ItemRuleList attributeItemRuleList = new ItemRuleList ( attributeItemRuleMap . values ( ) ) ; determineSimpleMode ( attributeItemRuleList ) ; if ( procedural ) { console . setStyle ( "GREEN" ) ; console . writeLine ( "Required attributes:" ) ; console . styleOff ( ) ; if ( ! simpleInputMode ) { for ( ItemRule itemRule : attributeItemRuleList ) { Token [ ] tokens = itemRule . getAllTokens ( ) ; if ( tokens == null ) { Token t = new Token ( TokenType . PARAMETER , itemRule . getName ( ) ) ; t . setDefaultValue ( itemRule . getDefaultValue ( ) ) ; tokens = new Token [ ] { t } ; } String mandatoryMarker = itemRule . isMandatory ( ) ? " * " : " " ; console . setStyle ( "YELLOW" ) ; console . write ( mandatoryMarker ) ; console . styleOff ( ) ; console . setStyle ( "bold" ) ; console . write ( itemRule . getName ( ) ) ; console . styleOff ( ) ; console . write ( ": " ) ; writeToken ( tokens ) ; console . writeLine ( ) ; } } } readRequiredAttributes ( attributeItemRuleList ) ; } } | Read required input attributes . |
22,426 | private void destroySingletons ( ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Destroying singletons in " + this ) ; } int failedDestroyes = 0 ; for ( BeanRule beanRule : beanRuleRegistry . getIdBasedBeanRules ( ) ) { failedDestroyes += doDestroySingleton ( beanRule ) ; } for ( Set < BeanRule > beanRuleSet : beanRuleRegistry . getTypeBasedBeanRules ( ) ) { for ( BeanRule beanRule : beanRuleSet ) { failedDestroyes += doDestroySingleton ( beanRule ) ; } } for ( BeanRule beanRule : beanRuleRegistry . getConfigurableBeanRules ( ) ) { failedDestroyes += doDestroySingleton ( beanRule ) ; } if ( failedDestroyes > 0 ) { log . warn ( "Singletons has not been destroyed cleanly (Failure Count: " + failedDestroyes + ")" ) ; } else { log . debug ( "Destroyed all cached singletons in " + this ) ; } } | Destroy all cached singletons . |
22,427 | public static Response createTransformResponse ( TransformRule transformRule ) { TransformType transformType = transformRule . getTransformType ( ) ; Response transformResponse ; if ( transformType == TransformType . XSL ) { transformResponse = new XslTransformResponse ( transformRule ) ; } else if ( transformType == TransformType . XML ) { if ( transformRule . getContentType ( ) == null ) { transformRule . setContentType ( ContentType . TEXT_XML . toString ( ) ) ; } transformResponse = new XmlTransformResponse ( transformRule ) ; } else if ( transformType == TransformType . TEXT ) { transformResponse = new TextTransformResponse ( transformRule ) ; } else if ( transformType == TransformType . JSON ) { if ( transformRule . getContentType ( ) == null ) { transformRule . setContentType ( ContentType . TEXT_PLAIN . toString ( ) ) ; } transformResponse = new JsonTransformResponse ( transformRule ) ; } else if ( transformType == TransformType . APON ) { if ( transformRule . getContentType ( ) == null ) { transformRule . setContentType ( ContentType . TEXT_PLAIN . toString ( ) ) ; } transformResponse = new AponTransformResponse ( transformRule ) ; } else { transformResponse = new NoneTransformResponse ( transformRule ) ; } return transformResponse ; } | Creates a new Transform object with specified TransformRule . |
22,428 | private void mem ( boolean gc , Console console ) { long total = Runtime . getRuntime ( ) . totalMemory ( ) ; long before = Runtime . getRuntime ( ) . freeMemory ( ) ; console . writeLine ( "%-24s %12s" , "Total memory" , StringUtils . convertToHumanFriendlyByteSize ( total ) ) ; console . writeLine ( "%-24s %12s" , "Used memory" , StringUtils . convertToHumanFriendlyByteSize ( total - before ) ) ; if ( gc ) { System . gc ( ) ; System . gc ( ) ; System . runFinalization ( ) ; try { Thread . sleep ( 100 ) ; } catch ( InterruptedException e ) { } long after = Runtime . getRuntime ( ) . freeMemory ( ) ; console . writeLine ( "%-24s %12s" , "Free memory before GC" , StringUtils . convertToHumanFriendlyByteSize ( before ) ) ; console . writeLine ( "%-24s %12s" , "Free memory after GC" , StringUtils . convertToHumanFriendlyByteSize ( after ) ) ; console . writeLine ( "%-24s %12s" , "Memory gained with GC" , StringUtils . convertToHumanFriendlyByteSize ( after - before ) ) ; } else { console . writeLine ( "%-24s %12s" , "Free memory" , StringUtils . convertToHumanFriendlyByteSize ( before ) ) ; } } | Displays memory usage . |
22,429 | private void initMessageSource ( ) { if ( contextBeanRegistry . containsBean ( MESSAGE_SOURCE_BEAN_ID ) ) { messageSource = contextBeanRegistry . getBean ( MESSAGE_SOURCE_BEAN_ID , MessageSource . class ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Using MessageSource [" + messageSource + "]" ) ; } } else { messageSource = new DelegatingMessageSource ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_ID + "': using default [" + messageSource + "]" ) ; } } } | Initialize the MessageSource . Use parent s if none defined in this context . |
22,430 | protected Locale resolveDefaultLocale ( Translet translet ) { Locale defaultLocale = getDefaultLocale ( ) ; if ( defaultLocale != null ) { translet . getRequestAdapter ( ) . setLocale ( defaultLocale ) ; return defaultLocale ; } else { return translet . getRequestAdapter ( ) . getLocale ( ) ; } } | Resolve the default locale for the given translet Called if can not find specified Locale . |
22,431 | protected TimeZone resolveDefaultTimeZone ( Translet translet ) { TimeZone defaultTimeZone = getDefaultTimeZone ( ) ; if ( defaultTimeZone != null ) { translet . getRequestAdapter ( ) . setTimeZone ( defaultTimeZone ) ; return defaultTimeZone ; } else { return translet . getRequestAdapter ( ) . getTimeZone ( ) ; } } | Resolve the default time zone for the given translet Called if can not find specified TimeZone . |
22,432 | public static Parameters parse ( String text ) throws AponParseException { Parameters parameters = new VariableParameters ( ) ; return parse ( text , parameters ) ; } | Converts an APON formatted string into a Parameters object . |
22,433 | public static < T extends Parameters > T parse ( String text , T parameters ) throws AponParseException { if ( text == null ) { throw new IllegalArgumentException ( "text must not be null" ) ; } if ( parameters == null ) { throw new IllegalArgumentException ( "parameters must not be null" ) ; } try { AponReader aponReader = new AponReader ( text ) ; aponReader . read ( parameters ) ; aponReader . close ( ) ; return parameters ; } catch ( AponParseException e ) { throw e ; } catch ( Exception e ) { throw new AponParseException ( "Failed to parse string with APON format" , e ) ; } } | Converts an APON formatted string into a given Parameters object . |
22,434 | public static Parameters parse ( File file , String encoding ) throws AponParseException { if ( file == null ) { throw new IllegalArgumentException ( "file must not be null" ) ; } Parameters parameters = new VariableParameters ( ) ; return parse ( file , encoding , parameters ) ; } | Converts to a Parameters object from a file . |
22,435 | public static Parameters parse ( Reader reader ) throws AponParseException { if ( reader == null ) { throw new IllegalArgumentException ( "reader must not be null" ) ; } AponReader aponReader = new AponReader ( reader ) ; return aponReader . read ( ) ; } | Converts to a Parameters object from a character - input stream . |
22,436 | 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 . |
22,437 | 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 . |
22,438 | 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 . |
22,439 | 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 . |
22,440 | 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 . |
22,441 | public static String encrypt ( String inputString , String encryptionPassword ) { return getEncryptor ( encryptionPassword ) . encrypt ( inputString ) ; } | Encrypts the inputString using the encryption password . |
22,442 | public static String decrypt ( String inputString , String encryptionPassword ) { checkPassword ( encryptionPassword ) ; return getEncryptor ( encryptionPassword ) . decrypt ( inputString ) ; } | Decrypts the inputString using the encryption password . |
22,443 | 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 . |
22,444 | 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 . |
22,445 | 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 . |
22,446 | private Method [ ] getAllMethods ( Class < ? > beanClass ) { Map < String , Method > uniqueMethods = new HashMap < > ( ) ; Class < ? > currentClass = beanClass ; while ( currentClass != null && currentClass != Object . class ) { addUniqueMethods ( uniqueMethods , currentClass . getDeclaredMethods ( ) ) ; 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 . |
22,447 | 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 . |
22,448 | 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 . |
22,449 | 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 . |
22,450 | 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 . |
22,451 | 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 . |
22,452 | 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 . |
22,453 | 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 . |
22,454 | 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 ) { } fileChannel = null ; } return false ; } else { return true ; } } } | Try to lock the file and return true if the locking succeeds . |
22,455 | 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 ) { } fileChannel = null ; } if ( lockFile != null ) { if ( lockFile . exists ( ) ) { lockFile . delete ( ) ; } lockFile = null ; } } } } | Releases the lock . |
22,456 | @ 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 . |
22,457 | 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 . |
22,458 | 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 |
22,459 | 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 . |
22,460 | 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 . |
22,461 | 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 |
22,462 | 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 . |
22,463 | public void setFidelity ( String key , boolean decision ) throws UnsupportedOption { if ( key . equals ( FEATURE_STRICT ) ) { if ( decision ) { 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 { options . remove ( key ) ; isStrict = false ; } } else if ( key . equals ( FEATURE_LEXICAL_VALUE ) ) { if ( decision ) { options . add ( key ) ; isLexicalValue = true ; } else { 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 ; } 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 { 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 . |
22,464 | 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 . |
22,465 | 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 . |
22,466 | public static < T extends OtlType > LogMetadata logOtl ( T otl ) { return new LogMetadata ( Collections . emptyMap ( ) ) . andInline ( otl ) ; } | Add an OTL object to the log message |
22,467 | public LogMetadata and ( String key , Object value ) { metadata . put ( key , value ) ; return this ; } | Extend a metadata marker with another key - value pair . |
22,468 | 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 . |
22,469 | 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 . |
22,470 | protected static HttpClient httpClient ( ) throws Exception { return HttpClients . custom ( ) . setHostnameVerifier ( new AllowAllHostnameVerifier ( ) ) . setSslcontext ( SSLContexts . custom ( ) . loadTrustMaterial ( null , new TrustStrategy ( ) { public boolean isTrusted ( X509Certificate [ ] x509Certificates , String s ) throws CertificateException { return true ; } } ) . build ( ) ) . build ( ) ; } | Sets the Commons HttpComponents to accept all SSL Certificates . |
22,471 | private void addCurrentDirFiles ( List < File > theFiles , List < File > theDirs , File currentDir ) { File dirs [ ] = currentDir . listFiles ( new FileFilter ( ) { public boolean accept ( File file ) { return file . isDirectory ( ) && ! file . getName ( ) . startsWith ( "." ) && ! file . getName ( ) . equals ( "META-INF" ) ; } } ) ; File htmlFiles [ ] = currentDir . listFiles ( new FileFilter ( ) { 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 . |
22,472 | 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 . |
22,473 | 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 . |
22,474 | public List < String > listUsers ( ) { List < String > users = new ArrayList < String > ( this . users . keySet ( ) ) ; Collections . sort ( users ) ; return users ; } | Lists all existing user accounts . |
22,475 | 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 . |
22,476 | 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 . |
22,477 | public static void enableProtoStuffSerialization ( Configuration conf ) { String ser = conf . get ( "io.serializations" ) . trim ( ) ; if ( ser . length ( ) != 0 ) { ser += "," ; } ser += ProtoStuffSerialization . class . getName ( ) ; conf . set ( "io.serializations" , ser ) ; } | Enables ProtoStuff Serialization support in Hadoop . |
22,478 | 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 . |
22,479 | 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 . |
22,480 | 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 . |
22,481 | 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 . |
22,482 | 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 |
22,483 | 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 . |
22,484 | public void write ( BitEncoderChannel headerChannel , EXIFactory f ) throws EXIException { try { EncodingOptions headerOptions = f . getEncodingOptions ( ) ; CodingMode codingMode = f . getCodingMode ( ) ; if ( headerOptions . isOptionEnabled ( EncodingOptions . INCLUDE_COOKIE ) ) { headerChannel . encode ( '$' ) ; headerChannel . encode ( 'E' ) ; headerChannel . encode ( 'X' ) ; headerChannel . encode ( 'I' ) ; } headerChannel . encodeNBitUnsignedInteger ( 2 , 2 ) ; boolean includeOptions = headerOptions . isOptionEnabled ( EncodingOptions . INCLUDE_OPTIONS ) ; headerChannel . encodeBoolean ( includeOptions ) ; headerChannel . encodeBoolean ( false ) ; headerChannel . encodeNBitUnsignedInteger ( 0 , 4 ) ; if ( includeOptions ) { writeEXIOptions ( f , headerChannel ) ; } 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 .. |
22,485 | 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 . |
22,486 | public < B > Message < B > toCadmiumMessage ( org . jgroups . Message jgMessage ) throws JsonProcessingException , IOException { JsonParser parser = factory . createJsonParser ( jgMessage . getBuffer ( ) ) ; parser . nextToken ( ) ; parser . nextToken ( ) ; parser . nextToken ( ) ; Header header = parser . readValueAs ( Header . class ) ; Class < ? > bodyClass = lookupBodyClass ( header ) ; parser . nextToken ( ) ; Object body = null ; if ( bodyClass == Void . class ) { body = null ; } else { parser . nextToken ( ) ; 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 ( ) ; } parser . nextToken ( ) ; 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 . |
22,487 | 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 . |
22,488 | 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 . |
22,489 | 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 ; 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 ; } 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 . |
22,490 | 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 |
22,491 | 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 . |
22,492 | @ 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 . |
22,493 | 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 . |
22,494 | @ SuppressWarnings ( "rawtypes" ) 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 . |
22,495 | @ SuppressWarnings ( "rawtypes" ) public EntityManagerFactory createContainerEntityManagerFactory ( PersistenceUnitInfo info , Map properties ) { EntityManagerFactory factory = wrappedPersistenceProvider . createContainerEntityManagerFactory ( info , properties ) ; return factory ; } | This just delegates to the HibernatePersistence method . |
22,496 | 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 . |
22,497 | @ 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 . |
22,498 | @ 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 . |
22,499 | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.