idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
35,100
static void generateConfigFile ( String configFilePath ) throws ConfigurationException { String fileExtention = FilenameUtils . getExtension ( configFilePath ) ; ConfigProvider < Configuration > provider = getProviderByFileExtention ( fileExtention ) ; if ( ! AuditUtil . isFileExists ( configFilePath ) ) { provider . generateConfig ( Configuration . DEFAULT , configFilePath ) ; } }
Generate config file .
35,101
private static ConfigProvider < Configuration > getProviderByFileExtention ( String extention ) throws ConfigurationException { ConfigProvider < Configuration > provider ; if ( XML_EXTENTION . equals ( extention ) ) { provider = new XMLConfigProvider < > ( Configuration . class ) ; } else if ( YML_EXTENTION . equals ( extention ) || YAML_EXTENTION . equals ( extention ) ) { provider = new YAMLConfigProvider < > ( Configuration . class ) ; } else { throw new ConfigurationException ( "Given file type is not supported." , CONFIG_EXTENTION_NOT_SUPPORTED_EXCEPTION_ID ) ; } return provider ; }
Gets the provider by file extention .
35,102
static Path getEnvironemtVariableConfigFilePath ( ) { final String value = System . getenv ( ENVIRONMENT_CONFIG_VARIABLE_NAME ) ; return Paths . get ( value ) ; }
Gets the environemt variable config file path .
35,103
static boolean hasEnvironmentVariable ( String variable ) { final String value = System . getenv ( variable ) ; if ( value != null ) { return true ; } return false ; }
Checks for environment variable .
35,104
static Path getSystemPropertyConfigFilePath ( ) { final String path = System . getProperty ( SYSTEM_PROPERTY_CONFIG_VARIABLE_NAME ) ; return Paths . get ( path ) ; }
Gets the system property config file path .
35,105
static boolean hasSystemPropertyVariable ( String variable ) { final String path = System . getProperty ( variable ) ; if ( path != null ) { return true ; } return false ; }
Checks for system property variable .
35,106
static InputStream getFileAsStream ( File resourceFile ) throws ConfigurationException { try { return new FileInputStream ( resourceFile ) ; } catch ( FileNotFoundException e ) { Log . error ( "File Resource could not be resolved. Given Resource:" + resourceFile , e ) ; throw new ConfigurationException ( "File Resource could not be resolve" , FILE_NOT_FOUND_EXCEPTION_ID , e ) ; } }
Gets the file as stream .
35,107
static boolean hasDiskAccess ( final String path ) { try { AccessController . checkPermission ( new FilePermission ( path , "read,write" ) ) ; return true ; } catch ( AccessControlException e ) { return false ; } }
Checks for disk access .
35,108
public static ClassLoader getClassLoader ( final Class < ? > clazz ) { final ClassLoader contextClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( contextClassLoader != null ) { return contextClassLoader ; } if ( clazz != null ) { final ClassLoader clazzClassLoader = clazz . getClassLoader ( ) ; if ( clazzClassLoader != null ) { return clazzClassLoader ; } } return ClassLoader . getSystemClassLoader ( ) ; }
Gets the class loader .
35,109
public List < E > getBuffered ( ) { List < E > temp = new ArrayList < > ( buff ) ; clear ( ) ; return temp ; }
Gets the buffered .
35,110
public void setRepository ( String repository ) { if ( meta == null ) { meta = new EventMeta ( ) ; } meta . setRepository ( repository ) ; }
Sets the repository .
35,111
public void setClient ( String client ) { if ( meta == null ) { meta = new EventMeta ( ) ; } meta . setClient ( client ) ; }
Sets the client .
35,112
public static String encodeLines ( final byte [ ] input , final int iOff , final int iLen , final int lineLen , final String lineSeparator ) { final int blockLen = ( lineLen * CONSTANT_3 ) / CONSTANT_4 ; if ( blockLen <= 0 ) { throw new IllegalArgumentException ( ) ; } final int lines = ( iLen + blockLen - 1 ) / blockLen ; final int bufLen = ( ( iLen + 2 ) / CONSTANT_3 ) * CONSTANT_4 + lines * lineSeparator . length ( ) ; final StringBuilder buf = new StringBuilder ( bufLen ) ; int ipValue = 0 ; while ( ipValue < iLen ) { final int length = Math . min ( iLen - ipValue , blockLen ) ; buf . append ( encode ( input , iOff + ipValue , length ) ) ; buf . append ( lineSeparator ) ; ipValue += length ; } return buf . toString ( ) ; }
Encode lines .
35,113
public static byte [ ] decodeLines ( final String text ) { char [ ] buf = new char [ text . length ( ) ] ; int pValue = 0 ; for ( int ip = 0 ; ip < text . length ( ) ; ip ++ ) { final char cValue = text . charAt ( ip ) ; if ( cValue != ' ' && cValue != '\r' && cValue != '\n' && cValue != '\t' ) { buf [ pValue ++ ] = cValue ; } } return decode ( buf , 0 , pValue ) ; }
Decode lines .
35,114
public final static String toJson ( Object object , DeIdentify deidentify ) { if ( isPrimitive ( object ) ) { Object deidentifiedObj = deidentifyObject ( object , deidentify ) ; String primitiveValue = String . valueOf ( deidentifiedObj ) ; if ( object instanceof String || object instanceof Character || ! object . equals ( deidentifiedObj ) ) { primitiveValue = '"' + primitiveValue + '"' ; } return primitiveValue ; } return JSON . toJSONString ( object , JsonFilter . INSTANCE ) ; }
Converts an object to json .
35,115
public static String deidentifyLeft ( String str , int size ) { int repeat ; if ( size > str . length ( ) ) { repeat = str . length ( ) ; } else { repeat = size ; } return StringUtils . overlay ( str , StringUtils . repeat ( '*' , repeat ) , 0 , size ) ; }
Deidentify left .
35,116
public static String deidentifyRight ( String str , int size ) { int end = str . length ( ) ; int repeat ; if ( size > str . length ( ) ) { repeat = str . length ( ) ; } else { repeat = size ; } return StringUtils . overlay ( str , StringUtils . repeat ( '*' , repeat ) , end - size , end ) ; }
Deidentify right .
35,117
public static String deidentifyMiddle ( String str , int start , int end ) { int repeat ; if ( end - start > str . length ( ) ) { repeat = str . length ( ) ; } else { repeat = ( str . length ( ) - end ) - start ; } return StringUtils . overlay ( str , StringUtils . repeat ( '*' , repeat ) , start , str . length ( ) - end ) ; }
Deidentify middle .
35,118
public static String deidentifyEdge ( String str , int start , int end ) { return deidentifyLeft ( deidentifyRight ( str , end ) , start ) ; }
Deidentify edge .
35,119
final static void stop ( ) { if ( lifeCycle . getStatus ( ) . equals ( RunStatus . RUNNING ) || lifeCycle . getStatus ( ) . equals ( RunStatus . DISABLED ) ) { lifeCycle . setStatus ( RunStatus . STOPPED ) ; Log . info ( "Preparing to shutdown Audit4j..." ) ; Log . info ( "Closing Streams..." ) ; auditStream . close ( ) ; Log . info ( "Shutdown handlers..." ) ; for ( Handler handler : configContext . getHandlers ( ) ) { handler . stop ( ) ; Log . info ( handler . getClass ( ) . getName ( ) + " shutdown." ) ; } Log . info ( "Disposing configurations..." ) ; configContext = null ; conf = null ; Log . info ( "Audit4j shutdown completed." ) ; } else { Log . info ( "No active Audit4j instance. Cancelling shutdown request." ) ; } }
The Audit4j context shutdown method . This will release the all allocated resources by the Audit4j Context initialization .
35,120
final static void enable ( ) { if ( lifeCycle . getStatus ( ) . equals ( RunStatus . READY ) || lifeCycle . getStatus ( ) . equals ( RunStatus . STOPPED ) ) { init ( ) ; } else if ( lifeCycle . getStatus ( ) . equals ( RunStatus . DISABLED ) ) { lifeCycle . setStatus ( RunStatus . RUNNING ) ; } }
Enable Audit4j core services .
35,121
private final static void checkEnvironment ( ) { boolean javaSupport = EnvUtil . isJDK7OrHigher ( ) ; if ( ! javaSupport ) { Log . error ( "Your Java version (" , EnvUtil . getJavaersion ( ) , ") is not supported for Audit4j. " , ErrorGuide . getGuide ( ErrorGuide . JAVA_VERSION_ERROR ) ) ; throw new InitializationException ( "Java version is not supported." ) ; } }
Check environment .
35,122
private final static void loadConfig ( ) { try { conf = Configurations . loadConfig ( configFilePath ) ; } catch ( ConfigurationException e ) { terminate ( ) ; throw new InitializationException ( INIT_FAILED , e ) ; } }
Load configuration items .
35,123
private static void loadRegistry ( ) { for ( AuditEventFilter filter : PreConfigurationContext . getPrefilters ( ) ) { configContext . addFilter ( filter ) ; } for ( AuditAnnotationFilter annotationFilter : PreConfigurationContext . getPreannotationfilters ( ) ) { configContext . addAnnotationFilter ( annotationFilter ) ; } }
Load initial configurations from Registry .
35,124
private static void initHandlers ( ) { Log . info ( "Initializing Handlers..." ) ; for ( Handler handler : conf . getHandlers ( ) ) { try { if ( ! configContext . getHandlers ( ) . contains ( handler ) ) { Map < String , String > handlerproperties = new HashMap < > ( ) ; handlerproperties . putAll ( configContext . getProperties ( ) ) ; handler . setProperties ( handlerproperties ) ; handler . init ( ) ; configContext . addHandler ( handler ) ; } Log . info ( handler . getClass ( ) . getName ( ) + " Initialized." ) ; } catch ( InitializationException e ) { Log . error ( "There is a problem in the hander: " , handler . getClass ( ) . getName ( ) , ErrorGuide . getGuide ( ErrorGuide . HANDLER_ERROR ) ) ; terminate ( ) ; throw new InitializationException ( INIT_FAILED , e ) ; } } }
Initialize handlers .
35,125
private static void initStreams ( ) { Log . info ( "Initializing Streams..." ) ; MetadataCommand command = ( MetadataCommand ) PreConfigurationContext . getCommandByName ( "-metadata" ) ; BatchCommand batchCommand = ( BatchCommand ) PreConfigurationContext . getCommandByName ( "-batchSize" ) ; AsyncAnnotationAuditOutputStream asyncAnnotationStream = new AsyncAnnotationAuditOutputStream ( new AuditProcessOutputStream ( Context . getConfigContext ( ) ) , annotationTransformer ) ; AuditProcessOutputStream processStream = new AuditProcessOutputStream ( Context . getConfigContext ( ) ) ; if ( command . isAsync ( ) ) { MetadataLookupStream metadataStream ; if ( batchCommand . getBatchSize ( ) > 0 ) { BatchProcessStream batchStream = new BatchProcessStream ( processStream , batchCommand . getBatchSize ( ) ) ; metadataStream = new MetadataLookupStream ( batchStream ) ; } else { metadataStream = new MetadataLookupStream ( processStream ) ; } AsyncAuditOutputStream asyncStream = new AsyncAuditOutputStream ( metadataStream , asyncAnnotationStream ) ; auditStream = new AuditEventOutputStream ( asyncStream , configContext ) ; } else { AsyncAuditOutputStream asyncStream ; if ( batchCommand . getBatchSize ( ) > 0 ) { BatchProcessStream batchStream = new BatchProcessStream ( processStream , batchCommand . getBatchSize ( ) ) ; asyncStream = new AsyncAuditOutputStream ( batchStream , asyncAnnotationStream ) ; } else { asyncStream = new AsyncAuditOutputStream ( processStream , asyncAnnotationStream ) ; } MetadataLookupStream metadataStream = new MetadataLookupStream ( asyncStream ) ; auditStream = new AuditEventOutputStream ( metadataStream , configContext ) ; } Log . info ( "Audit Streams Initialized." ) ; }
Initialize streams .
35,126
private static AnnotationTransformer < AuditEvent > getDefaultAnnotationTransformer ( ) { DefaultAnnotationTransformer defaultAnnotationTransformer = new DefaultAnnotationTransformer ( ) ; ObjectSerializerCommand serializerCommand = ( ObjectSerializerCommand ) PreConfigurationContext . getCommandByName ( "-objectSerializer" ) ; if ( serializerCommand . getSerializer ( ) == null ) { defaultAnnotationTransformer . setSerializer ( new ObjectToFieldsSerializer ( ) ) ; } else { defaultAnnotationTransformer . setSerializer ( serializerCommand . getSerializer ( ) ) ; } return defaultAnnotationTransformer ; }
Initializes and returns the default annotation transformer .
35,127
static void validateConfigurations ( Configuration conf ) throws ValidationException { if ( null == conf . getHandlers ( ) ) { Log . error ( "Handler should not be null, One or more handler implementation shuld be configured in the configuration" , ErrorGuide . getGuide ( ErrorGuide . EMPTY_HANDLERS ) ) ; throw new ValidationException ( "Configuration error" , ValidationException . VALIDATION_LEVEL_INVALID ) ; } if ( null == conf . getLayout ( ) ) { Log . error ( "Layout should not be null, A layout implementation shuld be configured in the configuration" , ErrorGuide . getGuide ( ErrorGuide . EMPTY_LAYOUT ) ) ; throw new ValidationException ( "Configuration error" , ValidationException . VALIDATION_LEVEL_INVALID ) ; } }
Validate configurations .
35,128
static boolean isSerializable ( Object object ) { final boolean retVal ; if ( implementsInterface ( object ) ) { retVal = attemptToSerialize ( object ) ; } else { retVal = false ; } return retVal ; }
Checks if is serializable .
35,129
private static boolean implementsInterface ( final Object o ) { final boolean retVal ; retVal = ( o instanceof Serializable ) || ( o instanceof Externalizable ) ; return retVal ; }
Implements interface .
35,130
private static boolean attemptToSerialize ( final Object o ) { final OutputStream sink ; ObjectOutputStream stream ; stream = null ; try { sink = new ByteArrayOutputStream ( ) ; stream = new ObjectOutputStream ( sink ) ; stream . writeObject ( o ) ; } catch ( final IOException ex ) { return false ; } finally { if ( stream != null ) { try { stream . close ( ) ; } catch ( final IOException ex ) { } } } return true ; }
Attempt to serialize .
35,131
protected List < String > getOptionsByCommand ( String command ) { String rawOption = commands . get ( command ) ; String [ ] options = rawOption . split ( CoreConstants . COMMA ) ; return Arrays . asList ( options ) ; }
Gets the options by command .
35,132
public void scanClass ( InputStream bits ) throws IOException { DataInputStream dstream = new DataInputStream ( new BufferedInputStream ( bits ) ) ; ClassFile cf = null ; try { cf = new ClassFile ( dstream ) ; classIndex . put ( cf . getName ( ) , new HashSet < String > ( ) ) ; if ( scanClassAnnotations ) scanClass ( cf ) ; if ( scanMethodAnnotations || scanParameterAnnotations ) scanMethods ( cf ) ; if ( scanFieldAnnotations ) scanFields ( cf ) ; if ( cf . getInterfaces ( ) != null ) { Set < String > intfs = new HashSet < String > ( ) ; for ( String intf : cf . getInterfaces ( ) ) intfs . add ( intf ) ; implementsIndex . put ( cf . getName ( ) , intfs ) ; } } finally { dstream . close ( ) ; bits . close ( ) ; } }
Parse a . class file for annotations
35,133
protected void scanMethods ( ClassFile cf ) { List < ClassFile > methods = cf . getMethods ( ) ; if ( methods == null ) return ; for ( Object obj : methods ) { MethodInfo method = ( MethodInfo ) obj ; if ( scanMethodAnnotations ) { AnnotationsAttribute visible = ( AnnotationsAttribute ) method . getAttribute ( AnnotationsAttribute . visibleTag ) ; AnnotationsAttribute invisible = ( AnnotationsAttribute ) method . getAttribute ( AnnotationsAttribute . invisibleTag ) ; if ( visible != null ) populate ( visible . getAnnotations ( ) , cf . getName ( ) ) ; if ( invisible != null ) populate ( invisible . getAnnotations ( ) , cf . getName ( ) ) ; } if ( scanParameterAnnotations ) { ParameterAnnotationsAttribute paramsVisible = ( ParameterAnnotationsAttribute ) method . getAttribute ( ParameterAnnotationsAttribute . visibleTag ) ; ParameterAnnotationsAttribute paramsInvisible = ( ParameterAnnotationsAttribute ) method . getAttribute ( ParameterAnnotationsAttribute . invisibleTag ) ; if ( paramsVisible != null && paramsVisible . getAnnotations ( ) != null ) { for ( Annotation [ ] anns : paramsVisible . getAnnotations ( ) ) { populate ( anns , cf . getName ( ) ) ; } } if ( paramsInvisible != null && paramsInvisible . getAnnotations ( ) != null ) { for ( Annotation [ ] anns : paramsInvisible . getAnnotations ( ) ) { populate ( anns , cf . getName ( ) ) ; } } } } }
Scanns both the method and its parameters for annotations .
35,134
public void outputAnnotationIndex ( PrintWriter writer ) { for ( String ann : annotationIndex . keySet ( ) ) { writer . print ( ann ) ; writer . print ( ": " ) ; Set < String > classes = annotationIndex . get ( ann ) ; Iterator < String > it = classes . iterator ( ) ; while ( it . hasNext ( ) ) { writer . print ( it . next ( ) ) ; if ( it . hasNext ( ) ) writer . print ( ", " ) ; } writer . println ( ) ; } }
Prints out annotationIndex
35,135
boolean canSearchConfigFile ( ServletContext servletContext ) { String searchConfigFile = servletContext . getInitParameter ( "searchConfigFile" ) ; if ( searchConfigFile == null || searchConfigFile . equals ( "" ) ) { return false ; } else if ( "true" . equals ( searchConfigFile ) ) { return true ; } return false ; }
Can search config file .
35,136
boolean hasHandlers ( ServletContext servletContext ) { String handlers = servletContext . getInitParameter ( "handlers" ) ; return ! ( handlers == null || handlers . equals ( "" ) ) ; }
Checks for handlers .
35,137
private void setNumberHits ( BitSet bits , String value , int min , int max ) { String [ ] fields = StringUtils . delimitedListToStringArray ( value , "," ) ; for ( String field : fields ) { if ( ! field . contains ( "/" ) ) { int [ ] range = getRange ( field , min , max ) ; bits . set ( range [ 0 ] , range [ 1 ] + 1 ) ; } else { String [ ] split = StringUtils . delimitedListToStringArray ( field , "/" ) ; if ( split . length > 2 ) { throw new IllegalArgumentException ( "Incrementer has more than two fields: '" + field + "' in expression \"" + this . expression + "\"" ) ; } int [ ] range = getRange ( split [ 0 ] , min , max ) ; if ( ! split [ 0 ] . contains ( "-" ) ) { range [ 1 ] = max - 1 ; } int delta = Integer . valueOf ( split [ 1 ] ) ; for ( int i = range [ 0 ] ; i <= range [ 1 ] ; i += delta ) { bits . set ( i ) ; } } } }
Sets the number hits .
35,138
private int [ ] getRange ( String field , int min , int max ) { int [ ] result = new int [ 2 ] ; if ( field . contains ( "*" ) ) { result [ 0 ] = min ; result [ 1 ] = max - 1 ; return result ; } if ( ! field . contains ( "-" ) ) { result [ 0 ] = result [ 1 ] = Integer . valueOf ( field ) ; } else { String [ ] split = StringUtils . delimitedListToStringArray ( field , "-" ) ; if ( split . length > 2 ) { throw new IllegalArgumentException ( "Range has more than two fields: '" + field + "' in expression \"" + this . expression + "\"" ) ; } result [ 0 ] = Integer . valueOf ( split [ 0 ] ) ; result [ 1 ] = Integer . valueOf ( split [ 1 ] ) ; } if ( result [ 0 ] >= max || result [ 1 ] >= max ) { throw new IllegalArgumentException ( "Range exceeds maximum (" + max + "): '" + field + "' in expression \"" + this . expression + "\"" ) ; } if ( result [ 0 ] < min || result [ 1 ] < min ) { throw new IllegalArgumentException ( "Range less than minimum (" + min + "): '" + field + "' in expression \"" + this . expression + "\"" ) ; } return result ; }
Gets the range .
35,139
public void execute ( Runnable task ) { try { this . concurrentExecutor . execute ( task ) ; } catch ( RejectedExecutionException ex ) { throw new TaskRejectedException ( "Executor [" + this . concurrentExecutor + "] did not accept task: " + task , ex ) ; } }
Delegates to the specified JDK concurrent executor .
35,140
private void executeArchive ( ) { for ( AbstractArchiveJob archiveJob : jobs ) { archiveJob . setArchiveDateDiff ( extractArchiveDateCount ( archiveEnv . getDatePattern ( ) ) ) ; archiveJob . setPath ( archiveEnv . getDirPath ( ) ) ; archiveJob . setCompressionExtention ( archiveEnv . getCompression ( ) . getExtention ( ) ) ; archiveJob . archive ( ) ; } }
Execute archive .
35,141
public Integer extractArchiveDateCount ( String datePattern ) { int dateCount = 0 ; String [ ] splits = datePattern . split ( "d|M|y" ) ; if ( splits . length > 0 ) { dateCount = dateCount + Integer . valueOf ( splits [ 0 ] ) ; } if ( splits . length > 1 ) { dateCount = dateCount + ( Integer . valueOf ( splits [ 1 ] ) * 30 ) ; } if ( splits . length > 2 ) { dateCount = dateCount + ( Integer . valueOf ( splits [ 2 ] ) * 365 ) ; } return dateCount ; }
Extract archive date count .
35,142
private static boolean isJDK_N_OrHigher ( int n ) { List < String > versionList = new ArrayList < String > ( ) ; for ( int i = 0 ; i < 5 ; i ++ ) { if ( n + i < 10 ) versionList . add ( "1." + ( n + i ) ) ; else versionList . add ( ( n + i ) + "." ) ; } String javaVersion = System . getProperty ( "java.version" ) ; if ( javaVersion == null ) { return false ; } for ( String v : versionList ) { if ( javaVersion . startsWith ( v ) ) return true ; } return false ; }
Checks if is jD k_ n_ or higher .
35,143
static public boolean isJaninoAvailable ( ) { ClassLoader classLoader = EnvUtil . class . getClassLoader ( ) ; try { Class < ? > bindingClass = classLoader . loadClass ( "org.codehaus.janino.ScriptEvaluator" ) ; return bindingClass != null ; } catch ( ClassNotFoundException e ) { return false ; } }
Checks if is janino available .
35,144
public static boolean hasConfigFileExists ( String dirPath ) { String filePath = dirPath + File . separator + Configurations . CONFIG_FILE_NAME + "." ; if ( AuditUtil . isFileExists ( filePath + Configurations . YML_EXTENTION ) || AuditUtil . isFileExists ( filePath + Configurations . YAML_EXTENTION ) || AuditUtil . isFileExists ( filePath + Configurations . XML_EXTENTION ) ) { return true ; } return false ; }
Checks whether config file exists in directory .
35,145
public static URL findClassBase ( Class clazz ) { String resource = clazz . getName ( ) . replace ( '.' , '/' ) + ".class" ; return findResourceBase ( resource , clazz . getClassLoader ( ) ) ; }
Find the classpath for the particular class
35,146
private Cipher getCipher ( int mode ) throws InvalidKeyException , InvalidAlgorithmParameterException , UnsupportedEncodingException , NoSuchAlgorithmException , NoSuchPaddingException { Cipher c = Cipher . getInstance ( ALGORYITHM ) ; byte [ ] iv = CoreConstants . IV . getBytes ( CoreConstants . ENCODE_UTF8 ) ; c . init ( mode , cryptKey , new IvParameterSpec ( iv ) ) ; return c ; }
Gets the cipher .
35,147
public static EncryptionUtil getInstance ( String key , String salt ) throws NoSuchAlgorithmException , UnsupportedEncodingException , InvalidKeySpecException { if ( instance == null ) { synchronized ( EncryptionUtil . class ) { if ( instance == null ) { instance = new EncryptionUtil ( ) ; generateKeyIfNotAvailable ( key , salt ) ; } } } return instance ; }
Gets the Encryptor .
35,148
public static String getGuide ( String code ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( " see " ) . append ( code ) . append ( " for further details." ) ; return builder . toString ( ) ; }
Gets the guide .
35,149
public List < Field > getAllFields ( final Method method , final Object [ ] arg1 ) { final Annotation [ ] [ ] parameterAnnotations = method . getParameterAnnotations ( ) ; List < Field > actionItems = new ArrayList < Field > ( ) ; int i = 0 ; String paramName = null ; String paramValue = null ; Class < ? > paramType ; for ( final Annotation [ ] annotations : parameterAnnotations ) { final Object object = arg1 [ i ++ ] ; paramType = object . getClass ( ) ; for ( final Annotation annotation : annotations ) { if ( annotation instanceof AuditField ) { final AuditField field = ( AuditField ) annotation ; paramName = field . field ( ) ; } else if ( annotation instanceof DeIdentify ) { final DeIdentify deidentify = ( DeIdentify ) annotation ; paramValue = DeIdentifyUtil . deidentify ( paramValue , deidentify . left ( ) , deidentify . right ( ) , deidentify . fromLeft ( ) , deidentify . fromRight ( ) ) ; } } if ( null == paramName ) { paramName = "arg" + ( i - 1 ) ; } Field field = new Field ( ) ; field . setName ( paramName ) ; field . setValue ( paramValue ) ; field . setType ( paramType . getName ( ) ) ; actionItems . add ( field ) ; paramName = null ; paramValue = null ; } return actionItems ; }
Gets the all params .
35,150
public static Object quoteIfString ( Object obj ) { return obj instanceof String ? quote ( ( String ) obj ) : obj ; }
Turn the given Object into a String with single quotes if it is a String ; keeping the Object as - is else .
35,151
public AuditEvent transformToEvent ( AnnotationAuditEvent annotationEvent ) { AuditEvent event = null ; if ( annotationEvent . getClazz ( ) . isAnnotationPresent ( Audit . class ) && ! annotationEvent . getMethod ( ) . isAnnotationPresent ( IgnoreAudit . class ) ) { event = new AuditEvent ( ) ; Audit audit = annotationEvent . getClazz ( ) . getAnnotation ( Audit . class ) ; event . setFields ( getFields ( annotationEvent . getMethod ( ) , annotationEvent . getArgs ( ) ) ) ; String annotationAction = audit . action ( ) ; if ( ACTION . equals ( annotationAction ) ) { event . setAction ( annotationEvent . getMethod ( ) . getName ( ) ) ; } else { event . setAction ( annotationAction ) ; } event . setRepository ( audit . repository ( ) ) ; event . setActor ( annotationEvent . getActor ( ) ) ; event . setOrigin ( annotationEvent . getOrigin ( ) ) ; } else if ( ! annotationEvent . getClazz ( ) . isAnnotationPresent ( Audit . class ) && annotationEvent . getMethod ( ) . isAnnotationPresent ( Audit . class ) ) { event = new AuditEvent ( ) ; Audit audit = annotationEvent . getMethod ( ) . getAnnotation ( Audit . class ) ; event . setFields ( getFields ( annotationEvent . getMethod ( ) , annotationEvent . getArgs ( ) ) ) ; String annotationAction = audit . action ( ) ; if ( ACTION . equals ( annotationAction ) ) { event . setAction ( annotationEvent . getMethod ( ) . getName ( ) ) ; } else { event . setAction ( annotationAction ) ; } event . setRepository ( audit . repository ( ) ) ; event . setActor ( annotationEvent . getActor ( ) ) ; event . setOrigin ( annotationEvent . getOrigin ( ) ) ; } return event ; }
Transform annotation informations to Audit Event object .
35,152
private List < Field > getFields ( final Method method , final Object [ ] params ) { final Annotation [ ] [ ] parameterAnnotations = method . getParameterAnnotations ( ) ; final List < Field > fields = new ArrayList < Field > ( ) ; int i = 0 ; String paramName = null ; for ( final Annotation [ ] annotations : parameterAnnotations ) { final Object object = params [ i ++ ] ; boolean ignoreFlag = false ; DeIdentify deidentify = null ; for ( final Annotation annotation : annotations ) { if ( annotation instanceof IgnoreAudit ) { ignoreFlag = true ; break ; } if ( annotation instanceof AuditField ) { final AuditField field = ( AuditField ) annotation ; paramName = field . field ( ) ; } if ( annotation instanceof DeIdentify ) { deidentify = ( DeIdentify ) annotation ; } } if ( ignoreFlag ) { } else { if ( null == paramName ) { paramName = "arg" + i ; } serializer . serialize ( fields , object , paramName , deidentify ) ; } paramName = null ; } return fields ; }
Extract fields based on annotations .
35,153
private Runnable errorHandlingTask ( Runnable task , boolean isRepeatingTask ) { return TaskUtils . decorateTaskWithErrorHandler ( task , this . errorHandler , isRepeatingTask ) ; }
Error handling task .
35,154
public static Map < String , String > transformMap ( final Map < String , Object > paramMap ) { final Map < String , String > paramStrMap = new LinkedHashMap < String , String > ( ) ; for ( final Map . Entry < String , Object > entry : paramMap . entrySet ( ) ) { paramStrMap . put ( entry . getKey ( ) , entry . getValue ( ) . toString ( ) ) ; } return paramStrMap ; }
Transform map .
35,155
public static String dateToString ( final Date date , final String format ) { if ( date == null ) { return null ; } final DateFormat dateFormat = new SimpleDateFormat ( format , Locale . US ) ; return dateFormat . format ( date ) ; }
Date to string .
35,156
public static Date stringTodate ( String dateString , String format ) throws ParseException { final DateFormat dateFormat = new SimpleDateFormat ( format , Locale . US ) ; return dateFormat . parse ( dateString ) ; }
Convert string to date .
35,157
public static String timeStampToString ( final Timestamp timestamp , final String format ) { return dateToString ( new Date ( timestamp . getTime ( ) ) , format ) ; }
Time stamp to string .
35,158
public static boolean isFileExists ( String filePathString ) { File file = new File ( filePathString ) ; if ( file . exists ( ) && ! file . isDirectory ( ) ) return true ; return false ; }
Checks if is file exists .
35,159
public Timestamp parseTimestamp ( String strValue ) throws IllegalArgumentException { if ( fmt != null ) { Optional < Timestamp > parsed = tryParseWithFormat ( strValue ) ; if ( parsed . isPresent ( ) ) { return parsed . get ( ) ; } } return Timestamp . valueOf ( strValue ) ; }
Parse the input string and return a timestamp value
35,160
public Object deserialize ( Writable blob ) throws SerDeException { Text t = ( Text ) blob ; JsonParser p ; List < Object > r = new ArrayList < Object > ( Collections . nCopies ( columnNames . size ( ) , null ) ) ; try { p = jsonFactory . createJsonParser ( new ByteArrayInputStream ( ( t . getBytes ( ) ) ) ) ; if ( p . nextToken ( ) != JsonToken . START_OBJECT ) { throw new IOException ( "Start token not found where expected" ) ; } JsonToken token ; while ( ( ( token = p . nextToken ( ) ) != JsonToken . END_OBJECT ) && ( token != null ) ) { populateRecord ( r , token , p , schema ) ; } } catch ( JsonParseException e ) { LOG . warn ( "Error [{}] parsing json text [{}]." , e , t ) ; LOG . debug ( null , e ) ; throw new SerDeException ( e ) ; } catch ( IOException e ) { LOG . warn ( "Error [{}] parsing json text [{}]." , e , t ) ; LOG . debug ( null , e ) ; throw new SerDeException ( e ) ; } return new DefaultHCatRecord ( r ) ; }
Takes JSON string in Text form and has to return an object representation above it that s readable by the corresponding object inspector .
35,161
public Writable serialize ( Object obj , ObjectInspector objInspector ) throws SerDeException { StringBuilder sb = new StringBuilder ( ) ; try { StructObjectInspector soi = ( StructObjectInspector ) objInspector ; List < ? extends StructField > structFields = soi . getAllStructFieldRefs ( ) ; assert ( columnNames . size ( ) == structFields . size ( ) ) ; if ( obj == null ) { sb . append ( "null" ) ; } else { sb . append ( SerDeUtils . LBRACE ) ; for ( int i = 0 ; i < structFields . size ( ) ; i ++ ) { if ( i > 0 ) { sb . append ( SerDeUtils . COMMA ) ; } appendWithQuotes ( sb , columnNames . get ( i ) ) ; sb . append ( SerDeUtils . COLON ) ; buildJSONString ( sb , soi . getStructFieldData ( obj , structFields . get ( i ) ) , structFields . get ( i ) . getFieldObjectInspector ( ) ) ; } sb . append ( SerDeUtils . RBRACE ) ; } } catch ( IOException e ) { LOG . warn ( "Error generating json text from object." , e ) ; throw new SerDeException ( e ) ; } return new Text ( sb . toString ( ) ) ; }
Given an object and object inspector pair traverse the object and generate a Text representation of the object .
35,162
private void setupCompositeInspector ( ) { ForgePropertyStyleConfig forgePropertyStyleConfig = new ForgePropertyStyleConfig ( ) ; forgePropertyStyleConfig . setProject ( this . project ) ; ForgeInspectorConfig forgeInspectorConfig = new ForgeInspectorConfig ( ) ; forgeInspectorConfig . setProject ( this . project ) ; forgeInspectorConfig . setPropertyStyle ( new ForgePropertyStyle ( forgePropertyStyleConfig ) ) ; PropertyTypeInspector propertyTypeInspector = new PropertyTypeInspector ( forgeInspectorConfig ) ; ForgeInspector forgeInspector = new ForgeInspector ( forgeInspectorConfig ) ; JpaInspectorConfig jpaInspectorConfig = new JpaInspectorConfig ( ) ; jpaInspectorConfig . setHideIds ( true ) ; jpaInspectorConfig . setHideVersions ( true ) ; jpaInspectorConfig . setHideTransients ( true ) ; jpaInspectorConfig . setPropertyStyle ( new ForgePropertyStyle ( forgePropertyStyleConfig ) ) ; JpaInspector jpaInspector = new JpaInspector ( jpaInspectorConfig ) ; BeanValidationInspector beanValidationInspector = new BeanValidationInspector ( forgeInspectorConfig ) ; CompositeInspectorConfig compositeInspectorConfig = new CompositeInspectorConfig ( ) ; compositeInspectorConfig . setInspectors ( propertyTypeInspector , forgeInspector , jpaInspector , beanValidationInspector ) ; compositeInspector = new CompositeInspector ( compositeInspectorConfig ) ; }
Setup the composite inspector . This is not done at construction time since Metawidget inspectors cache trait lookups and hence report incorrect values when underlying Java classes change in projects . Therefore the composite inspector setup and configuration is perform explicitly upon every inspection .
35,163
public ValueAndDeclaredType traverse ( final Object toTraverse , final String type , final boolean onlyToParent , final String ... names ) { if ( ( names == null ) || ( names . length == 0 ) ) { if ( onlyToParent ) { return new ValueAndDeclaredType ( null , null ) ; } return new ValueAndDeclaredType ( null , type ) ; } String traverseDeclaredType = type ; for ( int loop = 0 , length = names . length ; loop < length ; loop ++ ) { if ( onlyToParent && ( loop >= ( length - 1 ) ) ) { return new ValueAndDeclaredType ( null , traverseDeclaredType ) ; } String name = names [ loop ] ; Property property = getProperties ( traverseDeclaredType ) . get ( name ) ; if ( ( property == null ) || ! property . isReadable ( ) ) { return new ValueAndDeclaredType ( null , null ) ; } traverseDeclaredType = property . getType ( ) ; } return new ValueAndDeclaredType ( null , traverseDeclaredType ) ; }
Traverses the given Class heirarchy using properties of the given names .
35,164
private void inspectClassProperties ( final String type , Map < String , Property > properties ) { JavaSource < ? > clazz = sourceForName ( this . project , type ) ; if ( clazz instanceof MethodHolder < ? > ) { lookupGetters ( properties , ( MethodHolder < ? > ) clazz ) ; lookupSetters ( properties , ( MethodHolder < ? > ) clazz ) ; if ( clazz instanceof JavaClass ) { JavaClassSource source = Roaster . parse ( JavaClassSource . class , clazz . toString ( ) ) ; if ( ! source . getSuperType ( ) . equals ( "java.lang.Object" ) ) { inspectClassProperties ( source . getSuperType ( ) , properties ) ; } } } }
Recursive lookup for properties from superclass in order to support inheritance
35,165
protected String isGetter ( final Method < ? , ? > method ) { String methodName = method . getName ( ) ; String propertyName ; if ( methodName . startsWith ( ClassUtils . JAVABEAN_GET_PREFIX ) ) { propertyName = methodName . substring ( ClassUtils . JAVABEAN_GET_PREFIX . length ( ) ) ; } else if ( methodName . startsWith ( ClassUtils . JAVABEAN_IS_PREFIX ) && method . getReturnType ( ) != null && boolean . class . equals ( method . getReturnType ( ) . getQualifiedName ( ) ) ) { propertyName = methodName . substring ( ClassUtils . JAVABEAN_IS_PREFIX . length ( ) ) ; } else { return null ; } return StringUtils . decapitalize ( propertyName ) ; }
Returns whether the given method is a getter method .
35,166
protected String isSetter ( final Method < ? , ? > method ) { String methodName = method . getName ( ) ; if ( ! methodName . startsWith ( ClassUtils . JAVABEAN_SET_PREFIX ) ) { return null ; } String propertyName = methodName . substring ( ClassUtils . JAVABEAN_SET_PREFIX . length ( ) ) ; return StringUtils . decapitalize ( propertyName ) ; }
Returns whether the given method is a setter method .
35,167
public void newOneToOneRelationship ( Project project , final JavaResource resource , final String fieldName , final String fieldType , final String inverseFieldName , final FetchType fetchType , final boolean required , final Iterable < CascadeType > cascadeTypes ) throws FileNotFoundException { JavaSourceFacet java = project . getFacet ( JavaSourceFacet . class ) ; JavaClassSource entityClass = getJavaClassFrom ( resource ) ; JavaClassSource fieldEntityClass ; if ( areTypesSame ( fieldType , entityClass . getCanonicalName ( ) ) ) { fieldEntityClass = entityClass ; } else { fieldEntityClass = findEntity ( project , fieldType ) ; entityClass . addImport ( fieldEntityClass ) ; } FieldSource < JavaClassSource > localField = addFieldTo ( entityClass , fieldEntityClass . getName ( ) , fieldName , OneToOne . class . getName ( ) ) ; AnnotationSource < JavaClassSource > annotation = localField . getAnnotation ( OneToOne . class ) ; if ( ( inverseFieldName != null ) && ! inverseFieldName . isEmpty ( ) ) { FieldSource < JavaClassSource > inverseField = addFieldTo ( fieldEntityClass , entityClass . getName ( ) , inverseFieldName , OneToOne . class . getName ( ) ) ; inverseField . getAnnotation ( OneToOne . class ) . setStringValue ( "mappedBy" , localField . getName ( ) ) ; java . saveJavaSource ( fieldEntityClass ) ; } if ( fetchType != null && fetchType != FetchType . EAGER ) { annotation . setEnumValue ( "fetch" , fetchType ) ; } if ( required ) { annotation . setLiteralValue ( "optional" , "false" ) ; } addCascade ( cascadeTypes , annotation ) ; java . saveJavaSource ( entityClass ) ; }
Creates a One - to - One relationship
35,168
public void newManyToOneRelationship ( final Project project , final JavaResource resource , final String fieldName , final String fieldType , final String inverseFieldName , final FetchType fetchType , final boolean required , final Iterable < CascadeType > cascadeTypes ) throws FileNotFoundException { JavaSourceFacet java = project . getFacet ( JavaSourceFacet . class ) ; JavaClassSource many = getJavaClassFrom ( resource ) ; JavaClassSource one ; if ( areTypesSame ( fieldType , many . getCanonicalName ( ) ) ) { one = many ; } else { one = findEntity ( project , fieldType ) ; many . addImport ( one ) ; } if ( many . hasField ( fieldName ) ) { throw new IllegalStateException ( "Entity [" + many . getCanonicalName ( ) + "] already has a field named [" + fieldName + "]" ) ; } if ( ! Strings . isNullOrEmpty ( inverseFieldName ) && one . hasField ( inverseFieldName ) ) { throw new IllegalStateException ( "Entity [" + one . getCanonicalName ( ) + "] already has a field named [" + inverseFieldName + "]" ) ; } FieldSource < JavaClassSource > manyField = many . addField ( "private " + one . getName ( ) + " " + fieldName + ";" ) ; AnnotationSource < JavaClassSource > manyAnnotation = manyField . addAnnotation ( ManyToOne . class ) ; Refactory . createGetterAndSetter ( many , manyField ) ; if ( ! Strings . isNullOrEmpty ( inverseFieldName ) ) { one . addImport ( Set . class ) ; one . addImport ( HashSet . class ) ; if ( ! one . getCanonicalName ( ) . equals ( many . getCanonicalName ( ) ) ) { one . addImport ( many . getQualifiedName ( ) ) ; } FieldSource < JavaClassSource > oneField = one . addField ( "private Set<" + many . getName ( ) + "> " + inverseFieldName + "= new HashSet<" + many . getName ( ) + ">();" ) ; AnnotationSource < JavaClassSource > oneAnnotation = oneField . addAnnotation ( OneToMany . class ) . setStringValue ( "mappedBy" , fieldName ) ; oneAnnotation . setLiteralValue ( "cascade" , "CascadeType.ALL" ) ; oneAnnotation . getOrigin ( ) . addImport ( CascadeType . class ) ; Refactory . createGetterAndSetter ( one , oneField ) ; java . saveJavaSource ( one ) ; } if ( fetchType != null && fetchType != FetchType . EAGER ) { manyAnnotation . setEnumValue ( "fetch" , fetchType ) ; } if ( required ) { manyAnnotation . setLiteralValue ( "optional" , "false" ) ; } addCascade ( cascadeTypes , manyAnnotation ) ; java . saveJavaSource ( many ) ; }
Creates a Many - To - One relationship
35,169
public void newEmbeddedRelationship ( final Project project , final JavaResource resource , final String fieldName , final String fieldType ) throws FileNotFoundException { JavaSourceFacet java = project . getFacet ( JavaSourceFacet . class ) ; JavaClassSource entityClass = getJavaClassFrom ( resource ) ; JavaClassSource fieldEntityClass ; if ( areTypesSame ( fieldType , entityClass . getCanonicalName ( ) ) ) { fieldEntityClass = entityClass ; } else { fieldEntityClass = findEntity ( project , fieldType ) ; entityClass . addImport ( fieldEntityClass ) ; } addFieldTo ( entityClass , fieldEntityClass . getName ( ) , fieldName , Embedded . class . getName ( ) ) ; java . saveJavaSource ( entityClass ) ; }
Creates an Embedded relationship
35,170
private boolean areTypesSame ( String from , String to ) { String fromCompare = from . endsWith ( ".java" ) ? from . substring ( 0 , from . length ( ) - 5 ) : from ; String toCompare = to . endsWith ( ".java" ) ? to . substring ( 0 , to . length ( ) - 5 ) : to ; return fromCompare . equals ( toCompare ) ; }
Checks if the types are the same removing the . java in the end of the string in case it exists
35,171
public Collection < JavaClassSource > allResources ( ) { Set < JavaClassSource > result = new HashSet < > ( ) ; for ( DTOPair pair : dtos . values ( ) ) { if ( pair . rootDTO != null ) { result . add ( pair . rootDTO ) ; } if ( pair . nestedDTO != null ) { result . add ( pair . nestedDTO ) ; } } return result ; }
Retrieves all the DTOs present in this instance .
35,172
public void addRootDTO ( JavaClass < ? > entity , JavaClassSource rootDTO ) { DTOPair dtoPair = dtos . containsKey ( entity ) ? dtos . get ( entity ) : new DTOPair ( ) ; dtoPair . rootDTO = rootDTO ; dtos . put ( entity , dtoPair ) ; }
Registers the root DTO created for a JPA entity
35,173
public void addNestedDTO ( JavaClass < ? > entity , JavaClassSource nestedDTO ) { DTOPair dtoPair = dtos . containsKey ( entity ) ? dtos . get ( entity ) : new DTOPair ( ) ; dtoPair . nestedDTO = nestedDTO ; dtos . put ( entity , dtoPair ) ; }
Registers the nested DTO created for a JPA entity
35,174
public boolean containsDTOFor ( JavaClass < ? > entity , boolean root ) { if ( dtos . get ( entity ) == null ) { return false ; } return ( root ? ( dtos . get ( entity ) . rootDTO != null ) : ( dtos . get ( entity ) . nestedDTO != null ) ) ; }
Indicates whether a DTO is found in the underlying collection or not .
35,175
public JavaClassSource getDTOFor ( JavaClass < ? > entity , boolean root ) { if ( dtos . get ( entity ) == null ) { return null ; } return root ? ( dtos . get ( entity ) . rootDTO ) : ( dtos . get ( entity ) . nestedDTO ) ; }
Retrieves the DTO created for the JPA entity depending on whether a top level or nested DTO was requested as the return value .
35,176
public boolean promptRequiredMissingValues ( ShellImpl shell ) throws InterruptedException { Map < String , InputComponent < ? , ? > > inputs = getController ( ) . getInputs ( ) ; if ( hasMissingRequiredInputValues ( inputs . values ( ) ) ) { UIOutput output = shell . getOutput ( ) ; if ( ! getContext ( ) . isInteractive ( ) ) { output . error ( output . out ( ) , NON_INTERACTIVE_MODE_MESSAGE ) ; return false ; } output . info ( output . out ( ) , INTERACTIVE_MODE_MESSAGE ) ; promptRequiredMissingValues ( shell , inputs . values ( ) ) ; } return true ; }
Prompts for required missing values
35,177
protected < T extends ProjectFacet > boolean filterValueChoicesFromStack ( Project project , UISelectOne < T > select ) { boolean result = true ; Optional < Stack > stackOptional = project . getStack ( ) ; if ( stackOptional . isPresent ( ) ) { Stack stack = stackOptional . get ( ) ; Iterable < T > valueChoices = select . getValueChoices ( ) ; Set < T > filter = stack . filter ( select . getValueType ( ) , valueChoices ) ; select . setValueChoices ( filter ) ; if ( filter . size ( ) == 1 ) { select . setDefaultValue ( filter . iterator ( ) . next ( ) ) ; result = false ; } else if ( filter . size ( ) == 0 ) { result = false ; } } return result ; }
Filters the given value choices according the current enabled stack
35,178
@ SuppressWarnings ( "unchecked" ) private < F extends FACETTYPE > F safeGetFacet ( Class < F > type ) { for ( FACETTYPE facet : facets ) { if ( type . isInstance ( facet ) ) { return ( F ) facet ; } } return null ; }
Returns the installed facet that is an instance of the provided type argument null otherwise .
35,179
@ SuppressWarnings ( "unchecked" ) public Object convert ( Object source ) { Object value = source ; for ( Converter < Object , Object > converter : converters ) { if ( converter != null ) { value = converter . convert ( value ) ; } } return value ; }
This method always returns the last object converted from the list
35,180
private String buildFacesViewId ( final String servletMapping , final String resourcePath ) { for ( String suffix : getFacesSuffixes ( ) ) { if ( resourcePath . endsWith ( suffix ) ) { StringBuffer result = new StringBuffer ( ) ; Map < Pattern , String > patterns = new HashMap < > ( ) ; Pattern pathMapping = Pattern . compile ( "^(/.*)/\\*$" ) ; Pattern extensionMapping = Pattern . compile ( "^\\*(\\..*)$" ) ; Pattern defaultMapping = Pattern . compile ( "^/\\*$" ) ; patterns . put ( pathMapping , "$1" + resourcePath ) ; patterns . put ( extensionMapping , resourcePath . replaceAll ( "^(.*)(\\.\\w+)$" , "$1" ) + "$1" ) ; patterns . put ( defaultMapping , resourcePath ) ; boolean matched = false ; Iterator < Pattern > iterator = patterns . keySet ( ) . iterator ( ) ; while ( ( matched == false ) && iterator . hasNext ( ) ) { Pattern p = iterator . next ( ) ; Matcher m = p . matcher ( servletMapping ) ; if ( m . matches ( ) ) { String replacement = patterns . get ( p ) ; m . appendReplacement ( result , replacement ) ; matched = true ; } } if ( matched == false ) { return null ; } return result . toString ( ) ; } } return resourcePath ; }
Build a Faces view ID for the given resource path return null if not mapped by Faces Servlet
35,181
protected String encodePassword ( String password ) { StringBuilder result = new StringBuilder ( ) ; if ( password != null ) { for ( int i = 0 ; i < password . length ( ) ; i ++ ) { int c = password . charAt ( i ) ; c ^= 0xdfaa ; result . append ( Integer . toHexString ( c ) ) ; } } return result . toString ( ) ; }
Copied from com . intellij . openapi . util . PasswordUtil . java
35,182
public void registerMapping ( String prefix , String namespaceURI ) { prefix2Ns . put ( prefix , namespaceURI ) ; ns2Prefix . put ( namespaceURI , prefix ) ; }
Registers prefix - namespace URI mapping
35,183
public static CharSequence prettyPrint ( DependencyNode root ) { StringBuilder sb = new StringBuilder ( ) ; prettyPrint ( root , new Predicate < DependencyNode > ( ) { public boolean accept ( DependencyNode node ) { return true ; } } , sb , 0 ) ; return sb ; }
Prints a tree - like structure for this object
35,184
protected void initializeEnablementUI ( UIBuilder builder ) { enabled . setEnabled ( hasEnablement ( ) ) ; if ( getSelectedProject ( builder ) . hasFacet ( CDIFacet_1_1 . class ) ) { priority . setEnabled ( hasEnablement ( ) ) ; builder . add ( priority ) ; } else { priority . setEnabled ( false ) ; } builder . add ( enabled ) ; }
Note that enablement should be initialized last
35,185
public static String colorizeResource ( FileResource < ? > resource ) { String name = resource . getName ( ) ; if ( resource . isDirectory ( ) ) { name = new TerminalString ( name , new TerminalColor ( Color . BLUE , Color . DEFAULT ) ) . toString ( ) ; } else if ( resource . isExecutable ( ) ) { name = new TerminalString ( name , new TerminalColor ( Color . GREEN , Color . DEFAULT ) ) . toString ( ) ; } return name ; }
Applies ANSI colors in a specific resource
35,186
protected void addColumnComponents ( HtmlDataTable dataTable , Map < String , String > attributes , NodeList elements , StaticXmlMetawidget metawidget ) { super . addColumnComponents ( dataTable , attributes , elements , metawidget ) ; if ( dataTable . getChildren ( ) . isEmpty ( ) ) { return ; } if ( ! attributes . containsKey ( N_TO_MANY ) || metawidget . isReadOnly ( ) ) { return ; } HtmlCommandLink removeLink = new HtmlCommandLink ( ) ; removeLink . putAttribute ( "styleClass" , "remove-button" ) ; String removeExpression = COLLECTION_VAR + ".remove(" + dataTable . getAttribute ( "var" ) + ")" ; removeLink . putAttribute ( "action" , StaticFacesUtils . wrapExpression ( removeExpression ) ) ; HtmlColumn column = new HtmlColumn ( ) ; column . putAttribute ( "headerClass" , "remove-column" ) ; column . putAttribute ( "footerClass" , "remove-column" ) ; column . getChildren ( ) . add ( removeLink ) ; dataTable . getChildren ( ) . add ( column ) ; String inverseRelationship = attributes . get ( INVERSE_RELATIONSHIP ) ; if ( inverseRelationship != null ) { String componentType = WidgetBuilderUtils . getComponentType ( attributes ) ; if ( componentType != null ) { String controllerName = StringUtils . decapitalize ( ClassUtils . getSimpleName ( componentType ) ) ; HtmlCommandLink addLink = new HtmlCommandLink ( ) ; addLink . putAttribute ( "styleClass" , "add-button" ) ; String addExpression = COLLECTION_VAR + ".add(" + controllerName + "Bean.added)" ; addLink . putAttribute ( "action" , StaticFacesUtils . wrapExpression ( addExpression ) ) ; SetPropertyActionListener setPropertyActionListener = new SetPropertyActionListener ( ) ; setPropertyActionListener . putAttribute ( "target" , StaticFacesUtils . wrapExpression ( controllerName + "Bean.add." + inverseRelationship ) ) ; StandardBindingProcessor bindingProcessor = metawidget . getWidgetProcessor ( StandardBindingProcessor . class ) ; if ( bindingProcessor != null ) { bindingProcessor . processWidget ( setPropertyActionListener , ENTITY , attributes , ( StaticUIMetawidget ) metawidget ) ; } addLink . getChildren ( ) . add ( setPropertyActionListener ) ; String id = StaticFacesUtils . unwrapExpression ( setPropertyActionListener . getValue ( ) ) + StringUtils . SEPARATOR_DOT_CHAR + attributes . get ( NAME ) + StringUtils . SEPARATOR_DOT_CHAR + "Add" ; addLink . putAttribute ( "id" , StringUtils . camelCase ( id , StringUtils . SEPARATOR_DOT_CHAR ) ) ; Facet footerFacet = new Facet ( ) ; footerFacet . putAttribute ( "name" , "footer" ) ; footerFacet . getChildren ( ) . add ( addLink ) ; column . getChildren ( ) . add ( footerFacet ) ; } } }
Overridden to add a remove column .
35,187
protected Resource < ? > generateNavigation ( final String targetDir ) throws IOException { WebResourcesFacet web = this . project . getFacet ( WebResourcesFacet . class ) ; HtmlTag unorderedList = new HtmlTag ( "ul" ) ; ResourceFilter filter = new ResourceFilter ( ) { public boolean accept ( Resource < ? > resource ) { FileResource < ? > file = ( FileResource < ? > ) resource ; if ( ! file . isDirectory ( ) || file . getName ( ) . equals ( "resources" ) || file . getName ( ) . equals ( "WEB-INF" ) || file . getName ( ) . equals ( "META-INF" ) ) { return false ; } return true ; } } ; for ( Resource < ? > resource : web . getWebResource ( targetDir + "/" ) . listResources ( filter ) ) { HtmlOutcomeTargetLink outcomeTargetLink = new HtmlOutcomeTargetLink ( ) ; String outcome = targetDir . isEmpty ( ) || targetDir . startsWith ( "/" ) ? targetDir : "/" + targetDir ; outcomeTargetLink . putAttribute ( "outcome" , outcome + "/" + resource . getName ( ) + "/search" ) ; outcomeTargetLink . setValue ( StringUtils . uncamelCase ( resource . getName ( ) ) ) ; HtmlTag listItem = new HtmlTag ( "li" ) ; listItem . getChildren ( ) . add ( outcomeTargetLink ) ; unorderedList . getChildren ( ) . add ( listItem ) ; } Writer writer = new IndentedWriter ( new StringWriter ( ) , this . navigationTemplateIndent ) ; unorderedList . write ( writer ) ; Map < Object , Object > context = CollectionUtils . newHashMap ( ) ; context . put ( "appName" , StringUtils . uncamelCase ( this . project . getRoot ( ) . getName ( ) ) ) ; context . put ( "navigation" , writer . toString ( ) . trim ( ) ) ; context . put ( "targetDir" , targetDir ) ; if ( this . navigationTemplate == null ) { loadTemplates ( ) ; } try { return ScaffoldUtil . createOrOverwrite ( ( FileResource < ? > ) getTemplateStrategy ( ) . getDefaultTemplate ( ) , FreemarkerTemplateProcessor . processTemplate ( context , navigationTemplate ) ) ; } finally { writer . close ( ) ; } }
Generates the navigation menu based on scaffolded entities .
35,188
protected Map < String , String > parseNamespaces ( final String template ) { Map < String , String > namespaces = CollectionUtils . newHashMap ( ) ; Document document = XmlUtils . documentFromString ( template ) ; Element element = document . getDocumentElement ( ) ; NamedNodeMap attributes = element . getAttributes ( ) ; for ( int loop = 0 , length = attributes . getLength ( ) ; loop < length ; loop ++ ) { org . w3c . dom . Node node = attributes . item ( loop ) ; String nodeName = node . getNodeName ( ) ; int indexOf = nodeName . indexOf ( XMLNS_PREFIX ) ; if ( indexOf == - 1 ) { continue ; } namespaces . put ( nodeName . substring ( indexOf + XMLNS_PREFIX . length ( ) ) , node . getNodeValue ( ) ) ; } return namespaces ; }
Parses the given XML and determines what namespaces it already declares . These are later removed from the list of namespaces that Metawidget introduces .
35,189
protected int parseIndent ( final String template , final String indentOf ) { int indent = 0 ; int indexOf = template . indexOf ( indentOf ) ; while ( ( indexOf >= 0 ) && ( template . charAt ( indexOf ) != '\n' ) ) { if ( template . charAt ( indexOf ) == '\t' ) { indent ++ ; } indexOf -- ; } return indent ; }
Parses the given XML and determines the indent of the given String namespaces that Metawidget introduces .
35,190
protected void writeEntityMetawidget ( final Map < Object , Object > context , final int entityMetawidgetIndent , final Map < String , String > existingNamespaces ) { StringWriter stringWriter = new StringWriter ( ) ; this . entityMetawidget . write ( stringWriter , entityMetawidgetIndent ) ; context . put ( "metawidget" , stringWriter . toString ( ) . trim ( ) ) ; Map < String , String > namespaces = this . entityMetawidget . getNamespaces ( ) ; namespaces . keySet ( ) . removeAll ( existingNamespaces . keySet ( ) ) ; context . put ( "metawidgetNamespaces" , namespacesToString ( namespaces ) ) ; }
Writes the entity Metawidget and its namespaces into the given context .
35,191
protected void writeSearchAndBeanMetawidget ( final Map < Object , Object > context , final int searchMetawidgetIndent , final int beanMetawidgetIndent , final Map < String , String > existingNamespaces ) { StringWriter stringWriter = new StringWriter ( ) ; this . searchMetawidget . write ( stringWriter , searchMetawidgetIndent ) ; context . put ( "searchMetawidget" , stringWriter . toString ( ) . trim ( ) ) ; stringWriter = new StringWriter ( ) ; this . beanMetawidget . write ( stringWriter , beanMetawidgetIndent ) ; context . put ( "beanMetawidget" , stringWriter . toString ( ) . trim ( ) ) ; Map < String , String > namespaces = this . searchMetawidget . getNamespaces ( ) ; namespaces . putAll ( this . beanMetawidget . getNamespaces ( ) ) ; namespaces . keySet ( ) . removeAll ( existingNamespaces . keySet ( ) ) ; context . put ( "metawidgetNamespaces" , namespacesToString ( namespaces ) ) ; }
Writes the search Metawidget the bean Metawidget and their namespaces into the given context .
35,192
private boolean areTypesAssignable ( Class < ? > source , Class < ? > target ) { if ( target . isAssignableFrom ( source ) ) { return true ; } else if ( ! source . isPrimitive ( ) && ! target . isPrimitive ( ) ) { return false ; } else if ( source . isPrimitive ( ) ) { return primitiveToWrapperMap . get ( source ) == target ; } else { return source == primitiveToWrapperMap . get ( target ) ; } }
Check if the parameters are primitive and if they can be assignable
35,193
@ SuppressWarnings ( "unchecked" ) protected Element findAndReplaceProperties ( Counter counter , Element parent , String name , Map props ) { boolean shouldExist = ( props != null ) && ! props . isEmpty ( ) ; Element element = updateElement ( counter , parent , name , shouldExist ) ; if ( shouldExist ) { Iterator it = props . keySet ( ) . iterator ( ) ; Counter innerCounter = new Counter ( counter . getDepth ( ) + 1 ) ; while ( it . hasNext ( ) ) { String key = ( String ) it . next ( ) ; findAndReplaceSimpleElement ( innerCounter , element , key , ( String ) props . get ( key ) , null ) ; } List < String > lst = new ArrayList < String > ( props . keySet ( ) ) ; it = element . getChildren ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Element elem = ( Element ) it . next ( ) ; String key = elem . getName ( ) ; if ( ! lst . contains ( key ) ) { it . remove ( ) ; } } } return element ; }
Method findAndReplaceProperties .
35,194
protected Element findAndReplaceSimpleElement ( Counter counter , Element parent , String name , String text , String defaultValue ) { if ( ( defaultValue != null ) && ( text != null ) && defaultValue . equals ( text ) ) { Element element = parent . getChild ( name , parent . getNamespace ( ) ) ; if ( ( ( element != null ) && defaultValue . equals ( element . getText ( ) ) ) || ( element == null ) ) { return element ; } } boolean shouldExist = ( text != null ) && ( text . trim ( ) . length ( ) > 0 ) ; Element element = updateElement ( counter , parent , name , shouldExist ) ; if ( shouldExist ) { element . setText ( text ) ; } return element ; }
Method findAndReplaceSimpleElement .
35,195
protected Element findAndReplaceSimpleLists ( Counter counter , Element parent , java . util . Collection list , String parentName , String childName ) { boolean shouldExist = ( list != null ) && ( list . size ( ) > 0 ) ; Element element = updateElement ( counter , parent , parentName , shouldExist ) ; if ( shouldExist ) { Iterator it = list . iterator ( ) ; Iterator elIt = element . getChildren ( childName , element . getNamespace ( ) ) . iterator ( ) ; if ( ! elIt . hasNext ( ) ) { elIt = null ; } Counter innerCount = new Counter ( counter . getDepth ( ) + 1 ) ; while ( it . hasNext ( ) ) { String value = ( String ) it . next ( ) ; Element el ; if ( ( elIt != null ) && elIt . hasNext ( ) ) { el = ( Element ) elIt . next ( ) ; if ( ! elIt . hasNext ( ) ) { elIt = null ; } } else { el = factory . element ( childName , element . getNamespace ( ) ) ; insertAtPreferredLocation ( element , el , innerCount ) ; } el . setText ( value ) ; innerCount . increaseCount ( ) ; } if ( elIt != null ) { while ( elIt . hasNext ( ) ) { elIt . next ( ) ; elIt . remove ( ) ; } } } return element ; }
Method findAndReplaceSimpleLists .
35,196
protected Element findAndReplaceXpp3DOM ( Counter counter , Element parent , String name , Xpp3Dom dom ) { boolean shouldExist = ( dom != null ) && ( ( dom . getChildCount ( ) > 0 ) || ( dom . getValue ( ) != null ) ) ; Element element = updateElement ( counter , parent , name , shouldExist ) ; if ( shouldExist ) { replaceXpp3DOM ( element , dom , new Counter ( counter . getDepth ( ) + 1 ) ) ; } return element ; }
Method findAndReplaceXpp3DOM .
35,197
protected void insertAtPreferredLocation ( Element parent , Element child , Counter counter ) { int contentIndex = 0 ; int elementCounter = 0 ; Iterator it = parent . getContent ( ) . iterator ( ) ; Text lastText = null ; int offset = 0 ; while ( it . hasNext ( ) && ( elementCounter <= counter . getCurrentIndex ( ) ) ) { Object next = it . next ( ) ; offset = offset + 1 ; if ( next instanceof Element ) { elementCounter = elementCounter + 1 ; contentIndex = contentIndex + offset ; offset = 0 ; } if ( ( next instanceof Text ) && it . hasNext ( ) ) { lastText = ( Text ) next ; } } if ( ( lastText != null ) && ( lastText . getTextTrim ( ) . length ( ) == 0 ) ) { lastText = ( Text ) lastText . clone ( ) ; } else { StringBuilder starter = new StringBuilder ( lineSeparator ) ; for ( int i = 0 ; i < counter . getDepth ( ) ; i ++ ) { starter . append ( " " ) ; } lastText = factory . text ( starter . toString ( ) ) ; } if ( parent . getContentSize ( ) == 0 ) { Text finalText = ( Text ) lastText . clone ( ) ; finalText . setText ( finalText . getText ( ) . substring ( 0 , finalText . getText ( ) . length ( ) - " " . length ( ) ) ) ; parent . addContent ( contentIndex , finalText ) ; } parent . addContent ( contentIndex , child ) ; parent . addContent ( contentIndex , lastText ) ; }
Method insertAtPreferredLocation .
35,198
protected void iterateContributor ( Counter counter , Element parent , java . util . Collection list , java . lang . String parentTag , java . lang . String childTag ) { boolean shouldExist = ( list != null ) && ( list . size ( ) > 0 ) ; Element element = updateElement ( counter , parent , parentTag , shouldExist ) ; if ( shouldExist ) { Iterator it = list . iterator ( ) ; Iterator elIt = element . getChildren ( childTag , element . getNamespace ( ) ) . iterator ( ) ; if ( ! elIt . hasNext ( ) ) { elIt = null ; } Counter innerCount = new Counter ( counter . getDepth ( ) + 1 ) ; while ( it . hasNext ( ) ) { Contributor value = ( Contributor ) it . next ( ) ; Element el ; if ( ( elIt != null ) && elIt . hasNext ( ) ) { el = ( Element ) elIt . next ( ) ; if ( ! elIt . hasNext ( ) ) { elIt = null ; } } else { el = factory . element ( childTag , element . getNamespace ( ) ) ; insertAtPreferredLocation ( element , el , innerCount ) ; } updateContributor ( value , childTag , innerCount , el ) ; innerCount . increaseCount ( ) ; } if ( elIt != null ) { while ( elIt . hasNext ( ) ) { elIt . next ( ) ; elIt . remove ( ) ; } } } }
Method iterateContributor .
35,199
@ SuppressWarnings ( "unchecked" ) protected void replaceXpp3DOM ( final Element parent , final Xpp3Dom parentDom , final Counter counter ) { if ( parentDom . getChildCount ( ) > 0 ) { Xpp3Dom [ ] childs = parentDom . getChildren ( ) ; Collection < Xpp3Dom > domChilds = new ArrayList < > ( ) ; for ( int i = 0 ; i < childs . length ; i ++ ) { domChilds . add ( childs [ i ] ) ; } ListIterator < Element > it = parent . getChildren ( ) . listIterator ( ) ; while ( it . hasNext ( ) ) { Element elem = it . next ( ) ; Iterator < Xpp3Dom > it2 = domChilds . iterator ( ) ; Xpp3Dom corrDom = null ; while ( it2 . hasNext ( ) ) { Xpp3Dom dm = it2 . next ( ) ; if ( dm . getName ( ) . equals ( elem . getName ( ) ) ) { corrDom = dm ; break ; } } if ( corrDom != null ) { domChilds . remove ( corrDom ) ; replaceXpp3DOM ( elem , corrDom , new Counter ( counter . getDepth ( ) + 1 ) ) ; counter . increaseCount ( ) ; } else { it . remove ( ) ; } } Iterator < Xpp3Dom > it2 = domChilds . iterator ( ) ; while ( it2 . hasNext ( ) ) { Xpp3Dom dm = it2 . next ( ) ; Element elem = factory . element ( dm . getName ( ) , parent . getNamespace ( ) ) ; for ( String attName : dm . getAttributeNames ( ) ) { elem . setAttribute ( attName , dm . getAttribute ( attName ) ) ; } insertAtPreferredLocation ( parent , elem , counter ) ; counter . increaseCount ( ) ; replaceXpp3DOM ( elem , dm , new Counter ( counter . getDepth ( ) + 1 ) ) ; } } else if ( parentDom . getValue ( ) != null ) { parent . setText ( parentDom . getValue ( ) ) ; } }
Method replaceXpp3DOM .