idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
35,300 | public static SubsystemSuspensionLevels findBySubsystem ( EntityManager em , SubSystem subSystem ) { SystemAssert . requireArgument ( em != null , "Entity manager can not be null." ) ; SystemAssert . requireArgument ( subSystem != null , "Subsystem cannot be null." ) ; TypedQuery < SubsystemSuspensionLevels > query = em . createNamedQuery ( "SubsystemSuspensionLevels.findBySubsystem" , SubsystemSuspensionLevels . class ) ; try { query . setParameter ( "subSystem" , subSystem ) ; return query . getSingleResult ( ) ; } catch ( NoResultException ex ) { Map < Integer , Long > levels = new HashMap < > ( ) ; levels . put ( 1 , 60 * 60 * 1000L ) ; levels . put ( 2 , 10 * 60 * 60 * 1000L ) ; levels . put ( 3 , 24 * 60 * 60 * 1000L ) ; levels . put ( 4 , 3 * 24 * 60 * 60 * 1000L ) ; levels . put ( 5 , 10 * 24 * 60 * 60 * 1000L ) ; SubsystemSuspensionLevels suspensionLevels = new SubsystemSuspensionLevels ( null , subSystem , levels ) ; return em . merge ( suspensionLevels ) ; } } | Retrieves the SubsystemSuspensionLevels object for the given subsystem . |
35,301 | public static Map < Integer , Long > getSuspensionLevelsBySubsystem ( EntityManager em , SubSystem subSystem ) { return findBySubsystem ( em , subSystem ) . getLevels ( ) ; } | Retrieves the suspension levels for the given subsystem . |
35,302 | public void setLevels ( Map < Integer , Long > levels ) { SystemAssert . requireArgument ( levels != null , "Levels cannot be null" ) ; this . levels . clear ( ) ; this . levels . putAll ( levels ) ; } | Sets the suspension time in milliseconds for the corresponding infraction count . |
35,303 | public static SystemMain getInstance ( Properties config ) { return Guice . createInjector ( new SystemInitializer ( config ) ) . getInstance ( SystemMain . class ) ; } | Returns an instance of the system . Configuration is read from the supplied properties file . |
35,304 | protected void doStart ( ) { try { String build = _configuration . getValue ( SystemConfiguration . Property . BUILD ) ; String version = _configuration . getValue ( SystemConfiguration . Property . VERSION ) ; String year = new SimpleDateFormat ( "yyyy" ) . format ( new Date ( ) ) ; _log . info ( "Argus version {} build {}." , version , build ) ; _log . info ( "Copyright Salesforce.com, {}." , year ) ; _log . info ( "{} started." , getName ( ) ) ; _persistService . start ( ) ; _serviceFactory . getUserService ( ) . findAdminUser ( ) ; _serviceFactory . getUserService ( ) . findDefaultUser ( ) ; } catch ( Throwable ex ) { _log . error ( getName ( ) + " startup aborted." , ex ) ; } finally { _mergeServiceConfiguration ( ) ; _mergeNotifierConfiguration ( ) ; _log . info ( _configuration . toString ( ) ) ; } } | Starts the system . |
35,305 | protected void doStop ( ) { try { _dispose ( _serviceFactory . getWardenService ( ) ) ; _dispose ( _serviceFactory . getMonitorService ( ) ) ; _dispose ( _serviceFactory . getSchedulingService ( ) ) ; _dispose ( _serviceFactory . getGlobalInterlockService ( ) ) ; _dispose ( _serviceFactory . getMQService ( ) ) ; _dispose ( _serviceFactory . getSchemaService ( ) ) ; _dispose ( _serviceFactory . getTSDBService ( ) ) ; _dispose ( _serviceFactory . getCacheService ( ) ) ; _dispose ( _serviceFactory . getHistoryService ( ) ) ; _persistService . stop ( ) ; _log . info ( "{} stopped." , getName ( ) ) ; } catch ( Exception ex ) { _log . error ( getName ( ) + " shutdown aborted." , ex ) ; } } | Stops the system . |
35,306 | public static MetricDto transformToDto ( Metric metric ) { if ( metric == null ) { throw new WebApplicationException ( "Null entity object cannot be converted to Dto object." , Status . INTERNAL_SERVER_ERROR ) ; } MetricDto result = createDtoObject ( MetricDto . class , metric ) ; return result ; } | Converts a metric entity to a DTO . |
35,307 | public static long _9sComplement ( long creationTime ) { String time = String . valueOf ( creationTime ) ; char [ ] timeArr = time . toCharArray ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( char c : timeArr ) { sb . append ( 9 - Character . getNumericValue ( c ) ) ; } return Long . parseLong ( sb . toString ( ) ) ; } | Return a 9 s complement of the given timestamp . Since AsyncHBase doesn t allow a reverse scan and we want to scan data in descending order of creation time . |
35,308 | public Dashboard getDashboard ( BigInteger dashboardId ) throws IOException , TokenExpiredException { String requestUrl = RESOURCE + "/" + dashboardId . toString ( ) ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . GET , requestUrl , null ) ; assertValidResponse ( response , requestUrl ) ; return fromJson ( response . getResult ( ) , Dashboard . class ) ; } | Returns the batch for the given ID . |
35,309 | public static String internalReducer ( Metric metric , String reducerType ) { Map < Long , Double > sortedDatapoints = new TreeMap < > ( ) ; List < Double > operands = new ArrayList < Double > ( ) ; if ( ! reducerType . equals ( InternalReducerType . NAME . getName ( ) ) ) { if ( metric . getDatapoints ( ) != null && metric . getDatapoints ( ) . size ( ) > 0 ) { sortedDatapoints . putAll ( metric . getDatapoints ( ) ) ; for ( Double value : sortedDatapoints . values ( ) ) { if ( value == null ) { operands . add ( 0.0 ) ; } else { operands . add ( value ) ; } } } else { return null ; } } InternalReducerType type = InternalReducerType . fromString ( reducerType ) ; switch ( type ) { case AVG : return String . valueOf ( ( new Mean ( ) ) . evaluate ( Doubles . toArray ( operands ) ) ) ; case MIN : return String . valueOf ( Collections . min ( operands ) ) ; case MAX : return String . valueOf ( Collections . max ( operands ) ) ; case RECENT : return String . valueOf ( operands . get ( operands . size ( ) - 1 ) ) ; case MAXIMA : return String . valueOf ( Collections . max ( operands ) ) ; case MINIMA : return String . valueOf ( Collections . min ( operands ) ) ; case NAME : return metric . getMetric ( ) ; case DEVIATION : return String . valueOf ( ( new StandardDeviation ( ) ) . evaluate ( Doubles . toArray ( operands ) ) ) ; default : throw new UnsupportedOperationException ( reducerType ) ; } } | Reduces the give metric to a single value based on the specified reducer . |
35,310 | public static Map < Metric , String > sortByValue ( Map < Metric , String > map , final String reducerType ) { List < Map . Entry < Metric , String > > list = new LinkedList < > ( map . entrySet ( ) ) ; Collections . sort ( list , new Comparator < Map . Entry < Metric , String > > ( ) { public int compare ( Map . Entry < Metric , String > o1 , Map . Entry < Metric , String > o2 ) { if ( reducerType . equals ( "name" ) ) { return o1 . getValue ( ) . compareTo ( o2 . getValue ( ) ) ; } Double d1 = Double . parseDouble ( o1 . getValue ( ) ) ; Double d2 = Double . parseDouble ( o2 . getValue ( ) ) ; return ( d1 . compareTo ( d2 ) ) ; } } ) ; Map < Metric , String > result = new LinkedHashMap < > ( ) ; for ( Map . Entry < Metric , String > entry : list ) { result . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } return result ; } | Sorts a metric . |
35,311 | public static NotificationDto transformToDto ( Notification notification ) { if ( notification == null ) { throw new WebApplicationException ( "Null entity object cannot be converted to Dto object." , Status . INTERNAL_SERVER_ERROR ) ; } NotificationDto result = createDtoObject ( NotificationDto . class , notification ) ; result . setAlertId ( notification . getAlert ( ) . getId ( ) ) ; for ( Trigger trigger : notification . getTriggers ( ) ) { result . addTriggersIds ( trigger ) ; } return result ; } | Converts notification entity object to notificationDto object . |
35,312 | public static List < NotificationDto > transformToDto ( List < Notification > notifications ) { if ( notifications == null ) { throw new WebApplicationException ( "Null entity object cannot be converted to Dto object." , Status . INTERNAL_SERVER_ERROR ) ; } List < NotificationDto > result = new ArrayList < NotificationDto > ( ) ; for ( Notification notification : notifications ) { result . add ( transformToDto ( notification ) ) ; } return result ; } | Converts list of notification entity objects to list of notificationDto objects . |
35,313 | public static boolean isSignatureValid ( String payload , String signature , String appSecret ) { try { final Mac mac = Mac . getInstance ( HMAC_SHA1 ) ; mac . init ( new SecretKeySpec ( appSecret . getBytes ( ) , HMAC_SHA1 ) ) ; final byte [ ] rawHmac = mac . doFinal ( payload . getBytes ( ) ) ; final String expected = signature . substring ( 5 ) ; final String actual = bytesToHexString ( rawHmac ) ; return expected . equals ( actual ) ; } catch ( NoSuchAlgorithmException | InvalidKeyException e ) { throw new RuntimeException ( e ) ; } } | Verifies the provided signature of the payload . |
35,314 | public ProxyDataSourceBuilder autoRetrieveGeneratedKeys ( boolean autoClose , ResultSetProxyLogicFactory factory ) { this . autoRetrieveGeneratedKeys = true ; this . autoCloseGeneratedKeys = autoClose ; this . generatedKeysProxyLogicFactory = factory ; return this ; } | Enable auto retrieval of generated keys with proxy created by specified factory . |
35,315 | protected SortedMap < String , String > getParametersToDisplay ( List < ParameterSetOperation > params ) { SortedMap < String , String > paramMap = new TreeMap < String , String > ( new StringAsIntegerComparator ( ) ) ; for ( ParameterSetOperation param : params ) { String key = getParameterKeyToDisplay ( param ) ; String value = getParameterValueToDisplay ( param ) ; paramMap . put ( key , value ) ; } return paramMap ; } | populate param map with sorted by key . |
35,316 | public static QueryType getQueryType ( String query ) { final String trimmedQuery = removeCommentAndWhiteSpace ( query ) ; if ( trimmedQuery == null || trimmedQuery . length ( ) < 1 ) { return QueryType . OTHER ; } final char firstChar = trimmedQuery . charAt ( 0 ) ; final QueryType type ; switch ( firstChar ) { case 'S' : case 's' : type = QueryType . SELECT ; break ; case 'I' : case 'i' : type = QueryType . INSERT ; break ; case 'U' : case 'u' : type = QueryType . UPDATE ; break ; case 'D' : case 'd' : type = QueryType . DELETE ; break ; default : type = QueryType . OTHER ; } return type ; } | Returns type of query from given query string . |
35,317 | protected void writeConnectionIdEntry ( StringBuilder sb , ExecutionInfo execInfo , List < QueryInfo > queryInfoList ) { sb . append ( "Connection:" ) ; sb . append ( execInfo . getConnectionId ( ) ) ; sb . append ( ", " ) ; } | Write connection ID when enabled . |
35,318 | protected void writeTimeEntry ( StringBuilder sb , ExecutionInfo execInfo , List < QueryInfo > queryInfoList ) { sb . append ( "Time:" ) ; sb . append ( execInfo . getElapsedTime ( ) ) ; sb . append ( ", " ) ; } | Write elapsed time . |
35,319 | protected void writeResultEntry ( StringBuilder sb , ExecutionInfo execInfo , List < QueryInfo > queryInfoList ) { sb . append ( "Success:" ) ; sb . append ( execInfo . isSuccess ( ) ? "True" : "False" ) ; sb . append ( ", " ) ; } | Write query result whether successful or not . |
35,320 | protected void writeTypeEntry ( StringBuilder sb , ExecutionInfo execInfo , List < QueryInfo > queryInfoList ) { sb . append ( "Type:" ) ; sb . append ( getStatementType ( execInfo . getStatementType ( ) ) ) ; sb . append ( ", " ) ; } | Write statement type . |
35,321 | protected void writeParamsEntry ( StringBuilder sb , ExecutionInfo execInfo , List < QueryInfo > queryInfoList ) { boolean isPrepared = execInfo . getStatementType ( ) == StatementType . PREPARED ; sb . append ( "Params:[" ) ; for ( QueryInfo queryInfo : queryInfoList ) { for ( List < ParameterSetOperation > parameters : queryInfo . getParametersList ( ) ) { SortedMap < String , String > paramMap = getParametersToDisplay ( parameters ) ; if ( isPrepared ) { writeParamsForSinglePreparedEntry ( sb , paramMap , execInfo , queryInfoList ) ; } else { writeParamsForSingleCallableEntry ( sb , paramMap , execInfo , queryInfoList ) ; } } } chompIfEndWith ( sb , ',' ) ; sb . append ( "]" ) ; } | Write query parameters . |
35,322 | protected void writeParamsForSinglePreparedEntry ( StringBuilder sb , SortedMap < String , String > paramMap , ExecutionInfo execInfo , List < QueryInfo > queryInfoList ) { sb . append ( "(" ) ; for ( Map . Entry < String , String > paramEntry : paramMap . entrySet ( ) ) { sb . append ( paramEntry . getValue ( ) ) ; sb . append ( "," ) ; } chompIfEndWith ( sb , ',' ) ; sb . append ( ")," ) ; } | Write query parameters for PreparedStatement . |
35,323 | protected String getArguments ( Object [ ] args ) { if ( args == null || args . length == 0 ) { return "" ; } StringBuilder sb = new StringBuilder ( ) ; if ( args . length == 1 ) { Object arg = args [ 0 ] ; String param = getSingleArgParameterAsString ( arg ) ; String displayParam = getSingleArgDisplayParameter ( param ) ; if ( arg instanceof String ) { sb . append ( "\"" ) ; sb . append ( displayParam ) ; sb . append ( "\"" ) ; } else { sb . append ( displayParam ) ; } } else { for ( int i = 0 ; i < args . length ; i ++ ) { Object arg = args [ i ] ; boolean lastArg = i == args . length - 1 ; String param = getParameterAsString ( arg ) ; String displayParam = getDisplayParameter ( param ) ; if ( arg instanceof String ) { sb . append ( "\"" ) ; sb . append ( displayParam ) ; sb . append ( "\"" ) ; } else { sb . append ( displayParam ) ; } if ( ! lastArg ) { sb . append ( "," ) ; } } } return sb . toString ( ) ; } | Convert method parameters to a string . |
35,324 | protected String getDisplayParameter ( String parameter ) { if ( parameter . length ( ) <= this . parameterDisplayLength ) { return parameter ; } return parameter . substring ( 0 , this . parameterDisplayLength - 3 ) + "..." ; } | Construct parameter value to display . |
35,325 | protected String constructMessage ( long seq , Throwable thrown , long execTime , String connectionId , Class < ? > targetClass , Method method , String args ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "[" ) ; sb . append ( seq ) ; sb . append ( "]" ) ; sb . append ( "[" ) ; sb . append ( thrown == null ? "success" : "fail" ) ; sb . append ( "]" ) ; sb . append ( "[" ) ; sb . append ( execTime ) ; sb . append ( "ms]" ) ; sb . append ( "[conn=" ) ; sb . append ( connectionId ) ; sb . append ( "]" ) ; if ( thrown != null ) { sb . append ( "[error=" ) ; sb . append ( thrown . getMessage ( ) ) ; sb . append ( "]" ) ; } sb . append ( " " ) ; sb . append ( targetClass . getSimpleName ( ) ) ; sb . append ( "#" ) ; sb . append ( method . getName ( ) ) ; sb . append ( "(" ) ; sb . append ( args ) ; sb . append ( ")" ) ; return sb . toString ( ) ; } | Construct a message to log . |
35,326 | public void setRowId ( String parameterName , RowId x ) { recordByName ( parameterName , getDeclaredMethod ( CallableStatement . class , "setRowId" , String . class , RowId . class ) , parameterName , x ) ; } | since 1 . 6 |
35,327 | protected void writeDataSourceNameEntry ( StringBuilder sb , ExecutionInfo execInfo , List < QueryInfo > queryInfoList ) { String name = execInfo . getDataSourceName ( ) ; sb . append ( "\"name\":\"" ) ; sb . append ( name == null ? "" : escapeSpecialCharacter ( name ) ) ; sb . append ( "\", " ) ; } | Write datasource name when enabled as json . |
35,328 | protected void writeBatchEntry ( StringBuilder sb , ExecutionInfo execInfo , List < QueryInfo > queryInfoList ) { sb . append ( "\"batch\":" ) ; sb . append ( execInfo . isBatch ( ) ? "true" : "false" ) ; sb . append ( ", " ) ; } | Write whether batch execution or not as json . |
35,329 | protected void writeQuerySizeEntry ( StringBuilder sb , ExecutionInfo execInfo , List < QueryInfo > queryInfoList ) { sb . append ( "\"querySize\":" ) ; sb . append ( queryInfoList . size ( ) ) ; sb . append ( ", " ) ; } | Write query size as json . |
35,330 | protected void writeBatchSizeEntry ( StringBuilder sb , ExecutionInfo execInfo , List < QueryInfo > queryInfoList ) { sb . append ( "\"batchSize\":" ) ; sb . append ( execInfo . getBatchSize ( ) ) ; sb . append ( ", " ) ; } | Write batch size as json . |
35,331 | protected void writeQueriesEntry ( StringBuilder sb , ExecutionInfo execInfo , List < QueryInfo > queryInfoList ) { sb . append ( "\"query\":[" ) ; for ( QueryInfo queryInfo : queryInfoList ) { sb . append ( "\"" ) ; sb . append ( escapeSpecialCharacter ( queryInfo . getQuery ( ) ) ) ; sb . append ( "\"," ) ; } chompIfEndWith ( sb , ',' ) ; sb . append ( "], " ) ; } | Write queries as json . |
35,332 | protected void writeParamsForSinglePreparedEntry ( StringBuilder sb , SortedMap < String , String > paramMap , ExecutionInfo execInfo , List < QueryInfo > queryInfoList ) { sb . append ( "[" ) ; for ( Map . Entry < String , String > paramEntry : paramMap . entrySet ( ) ) { Object value = paramEntry . getValue ( ) ; if ( value == null ) { sb . append ( "null" ) ; } else { sb . append ( "\"" ) ; sb . append ( escapeSpecialCharacter ( value . toString ( ) ) ) ; sb . append ( "\"" ) ; } sb . append ( "," ) ; } chompIfEndWith ( sb , ',' ) ; sb . append ( "]," ) ; } | Write parameters for single execution as json . |
35,333 | public QueryBuilder populateFilterBuilder ( Expression condtionalExp , EntityMetadata m ) { log . info ( "Populating filter for expression: " + condtionalExp ) ; QueryBuilder filter = null ; if ( condtionalExp instanceof SubExpression ) { filter = populateFilterBuilder ( ( ( SubExpression ) condtionalExp ) . getExpression ( ) , m ) ; } else if ( condtionalExp instanceof ComparisonExpression ) { filter = getFilter ( populateFilterClause ( ( ComparisonExpression ) condtionalExp ) , m ) ; } else if ( condtionalExp instanceof BetweenExpression ) { filter = populateBetweenFilter ( ( BetweenExpression ) condtionalExp , m ) ; } else if ( condtionalExp instanceof LogicalExpression ) { filter = populateLogicalFilterBuilder ( condtionalExp , m ) ; } else if ( condtionalExp instanceof LikeExpression ) { filter = populateLikeQuery ( ( LikeExpression ) condtionalExp , m ) ; } else if ( condtionalExp instanceof InExpression ) { filter = populateInQuery ( ( InExpression ) condtionalExp , m ) ; } else { log . error ( condtionalExp . toParsedText ( ) + "found in where clause. Not supported in elasticsearch." ) ; throw new KunderaException ( condtionalExp . toParsedText ( ) + " not supported in ElasticSearch" ) ; } log . debug ( "Following is the populated filter for required query: " + filter ) ; return filter ; } | Populate filter builder . |
35,334 | private QueryBuilder populateLikeQuery ( LikeExpression likeExpression , EntityMetadata metadata ) { Expression patternValue = likeExpression . getPatternValue ( ) ; String field = likeExpression . getStringExpression ( ) . toString ( ) ; String likePattern = ( patternValue instanceof InputParameter ) ? kunderaQuery . getParametersMap ( ) . get ( ( patternValue ) . toParsedText ( ) ) . toString ( ) : patternValue . toParsedText ( ) . toString ( ) ; String jpaField = getField ( field ) ; log . debug ( "Pattern value for field " + field + " is: " + patternValue ) ; QueryBuilder filterBuilder = getQueryBuilder ( kunderaQuery . new FilterClause ( jpaField , Expression . LIKE , likePattern , field ) , metadata ) ; return filterBuilder ; } | Populate like query . |
35,335 | private QueryBuilder populateInQuery ( InExpression inExpression , EntityMetadata metadata ) { String property = getField ( inExpression . getExpression ( ) . toParsedText ( ) ) ; Expression inItemsParameter = inExpression . getInItems ( ) ; log . debug ( "IN query parameters for field " + property + " is: " + inItemsParameter ) ; Iterable inItemsIterable = getInValuesCollection ( inItemsParameter ) ; return getFilter ( kunderaQuery . new FilterClause ( property , Expression . IN , inItemsIterable , property ) , metadata ) ; } | Populate IN query filter . |
35,336 | private Collection getInValuesCollection ( Expression inClauseValues ) { Collection inParameterCollection = new ArrayList < > ( ) ; if ( inClauseValues instanceof NullExpression ) { log . debug ( "No items passed in IN clause values, returning blank IN values list" ) ; return inParameterCollection ; } if ( inClauseValues instanceof InputParameter ) { Object inValues = kunderaQuery . getParametersMap ( ) . get ( inClauseValues . toParsedText ( ) ) ; log . debug ( inClauseValues . toParsedText ( ) + "named parameter found in query, Replacing parameter with " + inValues ) ; inParameterCollection = inValues . getClass ( ) . isArray ( ) ? Arrays . asList ( ( Object [ ] ) inValues ) : ( Collection ) kunderaQuery . getParametersMap ( ) . get ( inClauseValues . toParsedText ( ) ) ; return inParameterCollection ; } if ( inClauseValues instanceof CollectionExpression ) { Iterator inValueIterator = ( ( CollectionExpression ) inClauseValues ) . children ( ) . iterator ( ) ; log . debug ( "Collection object found for IN clause values" ) ; while ( inValueIterator . hasNext ( ) ) { Expression value = ( Expression ) inValueIterator . next ( ) ; inParameterCollection . add ( value . toParsedText ( ) ) ; } return inParameterCollection ; } throw new KunderaException ( inClauseValues . toParsedText ( ) + " not supported for IN clause" ) ; } | Returns the collection of IN clause values . |
35,337 | private QueryBuilder populateBetweenFilter ( BetweenExpression betweenExpression , EntityMetadata m ) { String lowerBoundExpression = getBetweenBoundaryValues ( betweenExpression . getLowerBoundExpression ( ) ) ; String upperBoundExpression = getBetweenBoundaryValues ( betweenExpression . getUpperBoundExpression ( ) ) ; String field = getField ( betweenExpression . getExpression ( ) . toParsedText ( ) ) ; log . debug ( "Between clause for field " + field + "with lower bound " + lowerBoundExpression + "and upper bound " + upperBoundExpression ) ; return new AndQueryBuilder ( getFilter ( kunderaQuery . new FilterClause ( field , Expression . GREATER_THAN_OR_EQUAL , lowerBoundExpression , field ) , m ) , getFilter ( kunderaQuery . new FilterClause ( field , Expression . LOWER_THAN_OR_EQUAL , upperBoundExpression , field ) , m ) ) ; } | Populate between filter . |
35,338 | private String getBetweenBoundaryValues ( Expression boundExpression ) { if ( boundExpression instanceof IdentificationVariable || boundExpression instanceof NumericLiteral || boundExpression instanceof InputParameter ) { Object value = ( boundExpression instanceof InputParameter ) ? kunderaQuery . getParametersMap ( ) . get ( ( boundExpression ) . toParsedText ( ) ) : boundExpression . toParsedText ( ) ; return value . toString ( ) ; } else if ( boundExpression instanceof AdditionExpression ) { String leftValue = checkInputParameter ( ( ( AdditionExpression ) boundExpression ) . getLeftExpression ( ) ) ; String rightValue = checkInputParameter ( ( ( AdditionExpression ) boundExpression ) . getRightExpression ( ) ) ; return new Integer ( Integer . parseInt ( leftValue ) + Integer . parseInt ( rightValue ) ) . toString ( ) ; } else if ( boundExpression instanceof SubtractionExpression ) { String leftValue = checkInputParameter ( ( ( SubtractionExpression ) boundExpression ) . getLeftExpression ( ) ) ; String rightValue = checkInputParameter ( ( ( SubtractionExpression ) boundExpression ) . getRightExpression ( ) ) ; return new Integer ( Integer . parseInt ( leftValue ) - Integer . parseInt ( rightValue ) ) . toString ( ) ; } else if ( boundExpression instanceof MultiplicationExpression ) { String leftValue = checkInputParameter ( ( ( MultiplicationExpression ) boundExpression ) . getLeftExpression ( ) ) ; String rightValue = checkInputParameter ( ( ( MultiplicationExpression ) boundExpression ) . getRightExpression ( ) ) ; return new Integer ( Integer . parseInt ( leftValue ) * Integer . parseInt ( rightValue ) ) . toString ( ) ; } else if ( boundExpression instanceof DivisionExpression ) { String leftValue = checkInputParameter ( ( ( DivisionExpression ) boundExpression ) . getLeftExpression ( ) ) ; String rightValue = checkInputParameter ( ( ( DivisionExpression ) boundExpression ) . getRightExpression ( ) ) ; return new Integer ( Integer . parseInt ( leftValue ) / Integer . parseInt ( rightValue ) ) . toString ( ) ; } return null ; } | Gets the between boundary values . |
35,339 | private String checkInputParameter ( Expression expression ) { return ( expression instanceof InputParameter ) ? kunderaQuery . getParametersMap ( ) . get ( ( expression ) . toParsedText ( ) ) . toString ( ) : expression . toParsedText ( ) . toString ( ) ; } | Check input parameter . |
35,340 | private QueryBuilder populateLogicalFilterBuilder ( Expression logicalExp , EntityMetadata m ) { String identifier = ( ( LogicalExpression ) logicalExp ) . getIdentifier ( ) ; return ( identifier . equalsIgnoreCase ( LogicalExpression . AND ) ) ? getAndFilterBuilder ( logicalExp , m ) : ( identifier . equalsIgnoreCase ( LogicalExpression . OR ) ) ? getOrFilterBuilder ( logicalExp , m ) : null ; } | Populate logical filter builder . |
35,341 | private AndQueryBuilder getAndFilterBuilder ( Expression logicalExp , EntityMetadata m ) { AndExpression andExp = ( AndExpression ) logicalExp ; Expression leftExpression = andExp . getLeftExpression ( ) ; Expression rightExpression = andExp . getRightExpression ( ) ; return new AndQueryBuilder ( populateFilterBuilder ( leftExpression , m ) , populateFilterBuilder ( rightExpression , m ) ) ; } | Gets the and filter builder . |
35,342 | private OrQueryBuilder getOrFilterBuilder ( Expression logicalExp , EntityMetadata m ) { OrExpression orExp = ( OrExpression ) logicalExp ; Expression leftExpression = orExp . getLeftExpression ( ) ; Expression rightExpression = orExp . getRightExpression ( ) ; return new OrQueryBuilder ( populateFilterBuilder ( leftExpression , m ) , populateFilterBuilder ( rightExpression , m ) ) ; } | Gets the or filter builder . |
35,343 | private FilterClause populateFilterClause ( ComparisonExpression conditionalExpression ) { String property = ( ( StateFieldPathExpression ) conditionalExpression . getLeftExpression ( ) ) . getPath ( 1 ) ; String condition = conditionalExpression . getComparisonOperator ( ) ; Expression rightExpression = conditionalExpression . getRightExpression ( ) ; Object value = ( rightExpression instanceof InputParameter ) ? kunderaQuery . getParametersMap ( ) . get ( ( rightExpression ) . toParsedText ( ) ) : rightExpression . toParsedText ( ) ; return ( condition != null && property != null ) ? kunderaQuery . new FilterClause ( property , condition , value , property ) : null ; } | Populate filter clause . |
35,344 | public final void validate ( final Class < ? > clazz ) { if ( classes . contains ( clazz ) ) { return ; } if ( log . isDebugEnabled ( ) ) log . debug ( "Validating " + clazz . getName ( ) ) ; if ( ! clazz . isAnnotationPresent ( Entity . class ) ) { throw new InvalidEntityDefinitionException ( clazz . getName ( ) + " is not annotated with @Entity." ) ; } try { clazz . getConstructor ( ) ; } catch ( NoSuchMethodException nsme ) { throw new InvalidEntityDefinitionException ( clazz . getName ( ) + " must have a default no-argument constructor." ) ; } List < Field > keys = new ArrayList < Field > ( ) ; for ( Field field : clazz . getDeclaredFields ( ) ) { if ( field . isAnnotationPresent ( Id . class ) && field . isAnnotationPresent ( EmbeddedId . class ) ) { throw new InvalidEntityDefinitionException ( clazz . getName ( ) + " must have either @Id field or @EmbeddedId field" ) ; } if ( field . isAnnotationPresent ( Id . class ) ) { keys . add ( field ) ; if ( field . isAnnotationPresent ( GeneratedValue . class ) ) { validateGeneratedValueAnnotation ( clazz , field ) ; } } else if ( field . isAnnotationPresent ( EmbeddedId . class ) ) { keys . add ( field ) ; } } if ( keys . size ( ) < 0 ) { throw new InvalidEntityDefinitionException ( clazz . getName ( ) + " must have an @Id field." ) ; } else if ( keys . size ( ) > 1 ) { throw new InvalidEntityDefinitionException ( clazz . getName ( ) + " can only have 1 @Id field." ) ; } classes . add ( clazz ) ; } | Checks the validity of a class for Cassandra entity . |
35,345 | private URL [ ] findResourcesInUrls ( String classRelativePath , URL [ ] urls ) { List < URL > list = new ArrayList < URL > ( ) ; for ( URL url : urls ) { if ( AllowedProtocol . isValidProtocol ( url . getProtocol ( ) . toUpperCase ( ) ) && url . getPath ( ) . endsWith ( ".jar" ) ) { try { JarFile jarFile = new JarFile ( URLDecoder . decode ( url . getFile ( ) , Constants . CHARSET_UTF8 ) ) ; Manifest manifest = jarFile . getManifest ( ) ; if ( manifest != null ) { String classPath = manifest . getMainAttributes ( ) . getValue ( "Class-Path" ) ; if ( ! StringUtils . isEmpty ( classPath ) ) { List < URL > subList = new ArrayList < URL > ( ) ; for ( String cpEntry : classPath . split ( " " ) ) { try { subList . add ( new URL ( cpEntry ) ) ; } catch ( MalformedURLException e ) { URL subResources = ClasspathReader . class . getClassLoader ( ) . getResource ( cpEntry ) ; if ( subResources != null ) { subList . add ( subResources ) ; } } } list . addAll ( Arrays . asList ( findResourcesInUrls ( classRelativePath , subList . toArray ( new URL [ subList . size ( ) ] ) ) ) ) ; } } JarEntry present = jarFile . getJarEntry ( classRelativePath + ".class" ) ; if ( present != null ) { list . add ( url ) ; } } catch ( IOException e ) { logger . warn ( "Error during loading from context , Caused by:" + e . getMessage ( ) ) ; } } else if ( url . getPath ( ) . endsWith ( "/" ) ) { File file = new File ( url . getPath ( ) + classRelativePath + ".class" ) ; if ( file . exists ( ) ) { try { list . add ( file . toURL ( ) ) ; } catch ( MalformedURLException e ) { throw new ResourceReadingException ( e ) ; } } } } return list . toArray ( new URL [ list . size ( ) ] ) ; } | Scan class resource in the provided urls with the additional Class - Path of each jar checking |
35,346 | private final URL [ ] findResourcesByContextLoader ( ) { List < URL > list = new ArrayList < URL > ( ) ; ClassLoader classLoader = this . getClass ( ) . getClassLoader ( ) ; assert classLoader != null ; URL [ ] urls = ( ( URLClassLoader ) classLoader ) . getURLs ( ) ; for ( String fullyQualifiedClassName : classesToScan ) { String classRelativePath = fullyQualifiedClassName . replace ( "." , "/" ) ; list . addAll ( Arrays . asList ( findResourcesInUrls ( classRelativePath , urls ) ) ) ; } return list . toArray ( new URL [ list . size ( ) ] ) ; } | Scan class resources into a basePackagetoScan path . |
35,347 | public static InputStream toInputStream ( String s ) { InputStream is = new ByteArrayInputStream ( s . getBytes ( ) ) ; return is ; } | Converts String to Input Stream |
35,348 | private MongoClient onSetMongoServerProperties ( String contactNode , String defaultPort , String poolSize , List < ServerAddress > addrs , List < MongoCredential > credentials ) { MongoClientOptions mo ; MongoDBSchemaMetadata metadata = MongoDBPropertyReader . msmd ; ClientProperties cp = metadata != null ? metadata . getClientProperties ( ) : null ; Properties propsFromCp = null ; if ( cp != null ) { DataStore dataStore = metadata != null ? metadata . getDataStore ( ) : null ; List < Server > servers = dataStore != null && dataStore . getConnection ( ) != null ? dataStore . getConnection ( ) . getServers ( ) : null ; if ( servers != null && ! servers . isEmpty ( ) ) { for ( Server server : servers ) { addrs . add ( new ServerAddress ( server . getHost ( ) . trim ( ) , Integer . parseInt ( server . getPort ( ) . trim ( ) ) ) ) ; } } propsFromCp = dataStore != null && dataStore . getConnection ( ) != null ? dataStore . getConnection ( ) . getProperties ( ) : null ; } else { for ( String node : contactNode . split ( Constants . COMMA ) ) { if ( StringUtils . countMatches ( node , Constants . COLON ) == 1 ) { String host = node . split ( ":" ) [ 0 ] ; int port = Integer . parseInt ( node . split ( Constants . COLON ) [ 1 ] ) ; addrs . add ( new ServerAddress ( host . trim ( ) , port ) ) ; } else { addrs . add ( new ServerAddress ( node . trim ( ) , Integer . parseInt ( defaultPort . trim ( ) ) ) ) ; } } } MongoClientOptions . Builder b = new PopulateMongoOptions ( propsFromCp , externalProperties ) . prepareBuilder ( ) ; mo = b . build ( ) ; if ( mo . getConnectionsPerHost ( ) <= 0 && ! StringUtils . isEmpty ( poolSize ) ) { mo = b . connectionsPerHost ( Integer . parseInt ( poolSize ) ) . build ( ) ; } return new MongoClient ( addrs , credentials , mo ) ; } | On set mongo server properties . |
35,349 | private void buildHosts ( Map externalProperties , List < Server > servers , String persistenceUnit , final KunderaMetadata kunderaMetadata ) { persistenceUnitMetadata = kunderaMetadata . getApplicationMetadata ( ) . getPersistenceUnitMetadata ( persistenceUnit ) ; Properties props = persistenceUnitMetadata . getProperties ( ) ; this . externalProperties = externalProperties ; String hosts = null ; String portAsString = null ; if ( externalProperties != null ) { hosts = ( String ) externalProperties . get ( PersistenceProperties . KUNDERA_NODES ) ; portAsString = ( String ) externalProperties . get ( PersistenceProperties . KUNDERA_PORT ) ; } if ( hosts == null ) { hosts = ( String ) props . get ( PersistenceProperties . KUNDERA_NODES ) ; } if ( portAsString == null ) { portAsString = ( String ) props . get ( PersistenceProperties . KUNDERA_PORT ) ; } if ( hosts != null && portAsString != null ) { buildHosts ( hosts , portAsString , this . hostsList ) ; } else if ( servers != null && servers . size ( ) >= 1 ) { buildHosts ( servers , this . hostsList ) ; } } | Build host array . |
35,350 | private void onCheckRelation ( ) { try { results = populateEntities ( entityMetadata , client ) ; if ( entityMetadata . isRelationViaJoinTable ( ) || ( entityMetadata . getRelationNames ( ) != null && ! ( entityMetadata . getRelationNames ( ) . isEmpty ( ) ) ) ) { query . setRelationalEntities ( results , client , entityMetadata ) ; } } catch ( Exception e ) { throw new PersistenceException ( "Error while scrolling over results, Caused by :." , e ) ; } } | on check relation event invokes populate entities and set relational entities in case relations are present . |
35,351 | private String appendWhereClauseWithScroll ( String parsedQuery ) { String queryWithoutLimit = parsedQuery . replaceAll ( parsedQuery . substring ( parsedQuery . lastIndexOf ( CQLTranslator . LIMIT ) , parsedQuery . length ( ) ) , "" ) ; CQLTranslator translator = new CQLTranslator ( ) ; final String tokenCondition = prepareNext ( translator , queryWithoutLimit ) ; StringBuilder builder = new StringBuilder ( queryWithoutLimit ) ; if ( tokenCondition != null ) { if ( query . getKunderaQuery ( ) . getFilterClauseQueue ( ) . isEmpty ( ) ) { builder . append ( CQLTranslator . ADD_WHERE_CLAUSE ) ; } else { builder . append ( CQLTranslator . AND_CLAUSE ) ; } builder . append ( tokenCondition ) ; } String replaceQuery = replaceAndAppendLimit ( builder . toString ( ) ) ; builder . replace ( 0 , builder . toString ( ) . length ( ) , replaceQuery ) ; translator . buildFilteringClause ( builder ) ; return checkOnEmptyResult ( ) && tokenCondition == null ? null : builder . toString ( ) ; } | Appends where claues and prepare for next fetch . Method to be called in case cql3 enabled . |
35,352 | private String replaceAndAppendLimit ( String parsedQuery ) { StringBuilder builder = new StringBuilder ( parsedQuery ) ; onLimit ( builder ) ; parsedQuery = builder . toString ( ) ; return parsedQuery ; } | Replace and append limit . |
35,353 | private void onLimit ( StringBuilder builder ) { builder . append ( CQLTranslator . LIMIT ) ; builder . append ( this . maxResult ) ; } | Append limit to sql3 query . |
35,354 | private Map < Boolean , String > getConditionOnIdColumn ( String idColumn ) { Map < Boolean , String > filterIdResult = new HashMap < Boolean , String > ( ) ; MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( entityMetadata . getPersistenceUnit ( ) ) ; EmbeddableType keyObj = null ; if ( metaModel . isEmbeddable ( entityMetadata . getIdAttribute ( ) . getBindableJavaType ( ) ) ) { keyObj = metaModel . embeddable ( entityMetadata . getIdAttribute ( ) . getBindableJavaType ( ) ) ; } for ( Object o : query . getKunderaQuery ( ) . getFilterClauseQueue ( ) ) { if ( o instanceof FilterClause ) { FilterClause clause = ( ( FilterClause ) o ) ; String fieldName = clause . getProperty ( ) ; String condition = clause . getCondition ( ) ; if ( keyObj != null && fieldName . equals ( idColumn ) || ( keyObj != null && StringUtils . contains ( fieldName , '.' ) ) || ( idColumn . equals ( fieldName ) ) ) { filterIdResult . put ( true , condition ) ; break ; } } } return filterIdResult ; } | Gets the condition on id column . |
35,355 | private byte [ ] idValueInByteArr ( ) { Object entity = results . get ( results . size ( ) - 1 ) ; Object id = PropertyAccessorHelper . getId ( entity , entityMetadata ) ; String idName = ( ( AbstractAttribute ) entityMetadata . getIdAttribute ( ) ) . getJPAColumnName ( ) ; Class idClazz = ( ( AbstractAttribute ) entityMetadata . getIdAttribute ( ) ) . getBindableJavaType ( ) ; MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( entityMetadata . getPersistenceUnit ( ) ) ; EmbeddableType keyObj = null ; ByteBuffer bytes = null ; if ( metaModel . isEmbeddable ( entityMetadata . getIdAttribute ( ) . getBindableJavaType ( ) ) ) { keyObj = metaModel . embeddable ( entityMetadata . getIdAttribute ( ) . getBindableJavaType ( ) ) ; Field embeddedField = getPartitionKeyField ( ) ; Attribute partitionKey = keyObj . getAttribute ( embeddedField . getName ( ) ) ; Object partitionKeyValue = PropertyAccessorHelper . getObject ( id , ( Field ) partitionKey . getJavaMember ( ) ) ; bytes = CassandraUtilities . toBytes ( partitionKeyValue , ( Field ) partitionKey . getJavaMember ( ) ) ; } else { bytes = query . getBytesValue ( idName , entityMetadata , id ) ; } return bytes . array ( ) ; } | Id value in byte arr . |
35,356 | private Field getPartitionKeyField ( ) { Field [ ] embeddedFields = entityMetadata . getIdAttribute ( ) . getBindableJavaType ( ) . getDeclaredFields ( ) ; Field field = null ; for ( Field embeddedField : embeddedFields ) { if ( ! ReflectUtils . isTransientOrStatic ( embeddedField ) ) { field = embeddedField ; break ; } } return field ; } | Will return partition key part of composite id . |
35,357 | private E getEntity ( Object entity ) { return ( E ) ( entity . getClass ( ) . isAssignableFrom ( EnhanceEntity . class ) ? ( ( EnhanceEntity ) entity ) . getEntity ( ) : entity ) ; } | Extract wrapped entity object from enhanced entity . |
35,358 | private String replaceAppliedToken ( String query ) { final String tokenRegex = "\\btoken\\(" ; final String pattern = "#TOKENKUNDERA#" ; query = query . replaceAll ( tokenRegex , pattern ) ; if ( query . indexOf ( pattern ) > - 1 ) { CQLTranslator translator = new CQLTranslator ( ) ; int closingIndex = query . indexOf ( CQLTranslator . CLOSE_BRACKET , query . lastIndexOf ( pattern ) ) ; String object = query . substring ( query . lastIndexOf ( pattern ) + pattern . length ( ) , closingIndex ) ; Object entity = results . get ( results . size ( ) - 1 ) ; Class idClazz = ( ( AbstractAttribute ) entityMetadata . getIdAttribute ( ) ) . getBindableJavaType ( ) ; Object id = PropertyAccessorHelper . getId ( entity , entityMetadata ) ; StringBuilder builder = new StringBuilder ( ) ; translator . appendValue ( builder , idClazz , id , false , false ) ; query = query . replaceAll ( pattern + object , pattern + builder . toString ( ) ) ; query = query . replaceAll ( pattern , CQLTranslator . TOKEN ) ; } return query ; } | Replace applied token . |
35,359 | public Node getParentNode ( String parentNodeId ) { NodeLink link = new NodeLink ( parentNodeId , getNodeId ( ) ) ; if ( this . parents == null ) { return null ; } else { return this . parents . get ( link ) ; } } | Retrieves parent node of this node for a given parent node ID |
35,360 | public Node getChildNode ( String childNodeId ) { NodeLink link = new NodeLink ( getNodeId ( ) , childNodeId ) ; if ( this . children == null ) { return null ; } else { return this . children . get ( link ) ; } } | Retrieves child node of this node for a given child node ID |
35,361 | public Map < String , EntityMetadata > getEntityMetadataMap ( ) { if ( entityMetadataMap == null ) { entityMetadataMap = new HashMap < String , EntityMetadata > ( ) ; } return entityMetadataMap ; } | Gets the entity metadata map . |
35,362 | public Map < String , Class < ? > > getEntityNameToClassMap ( ) { if ( entityNameToClassMap == null ) { entityNameToClassMap = new HashMap < String , Class < ? > > ( ) ; } return entityNameToClassMap ; } | Gets the entity name to class map . |
35,363 | public void assignManagedTypes ( Map < Class < ? > , EntityType < ? > > managedTypes ) { if ( this . entityTypes == null ) { this . entityTypes = managedTypes ; } else { this . entityTypes . putAll ( managedTypes ) ; } } | Assign to managedTypes . |
35,364 | public void assignEmbeddables ( Map < Class < ? > , ManagedType < ? > > embeddables ) { if ( this . embeddables == null ) { this . embeddables = embeddables ; } else { this . embeddables . putAll ( embeddables ) ; } } | Assign embeddables to embeddables collection . |
35,365 | public void assignMappedSuperClass ( Map < Class < ? > , ManagedType < ? > > mappedSuperClass ) { if ( this . mappedSuperClassTypes == null ) { this . mappedSuperClassTypes = mappedSuperClass ; } else { this . mappedSuperClassTypes . putAll ( mappedSuperClassTypes ) ; } } | Adds mapped super class to mapped super class collection . |
35,366 | public boolean isEmbeddable ( Class embeddableClazz ) { return embeddables != null ? embeddables . containsKey ( embeddableClazz ) && embeddables . get ( embeddableClazz ) . getPersistenceType ( ) . equals ( PersistenceType . EMBEDDABLE ) : false ; } | Returns true if attribute is embeddable . |
35,367 | public Attribute getEntityAttribute ( Class clazz , String fieldName ) { if ( entityTypes != null && entityTypes . containsKey ( clazz ) ) { EntityType entityType = entityTypes . get ( clazz ) ; return entityType . getAttribute ( fieldName ) ; } throw new IllegalArgumentException ( "No entity found: " + clazz ) ; } | Returns entity attribute for given managed entity class . |
35,368 | public Map < String , EmbeddableType > getEmbeddables ( Class clazz ) { Map < String , EmbeddableType > embeddableAttibutes = new HashMap < String , EmbeddableType > ( ) ; if ( entityTypes != null ) { EntityType entity = entityTypes . get ( clazz ) ; Iterator < Attribute > iter = entity . getAttributes ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Attribute attribute = iter . next ( ) ; if ( isEmbeddable ( ( ( AbstractAttribute ) attribute ) . getBindableJavaType ( ) ) ) { embeddableAttibutes . put ( attribute . getName ( ) , embeddable ( ( ( AbstractAttribute ) attribute ) . getBindableJavaType ( ) ) ) ; } } } return embeddableAttibutes ; } | Custom implementation to offer map of embeddables available for given entityType . |
35,369 | private String prepareCompositeIndexName ( String indexedColumns , final EntityType entityType , EntityMetadata metadata ) { StringTokenizer tokenizer = new StringTokenizer ( indexedColumns , "," ) ; StringBuilder builder = new StringBuilder ( ) ; while ( tokenizer . hasMoreTokens ( ) ) { String fieldName = ( String ) tokenizer . nextElement ( ) ; StringTokenizer stringTokenizer = new StringTokenizer ( fieldName , "." ) ; if ( stringTokenizer . countTokens ( ) > 1 ) { fieldName = stringTokenizer . nextToken ( ) ; String embeddedFieldName = stringTokenizer . nextToken ( ) ; Attribute embeddable = entityType . getAttribute ( fieldName ) ; EmbeddableType embeddedEntity = ( EmbeddableType ) kunderaMetadata . getApplicationMetadata ( ) . getMetaModelBuilder ( metadata . getPersistenceUnit ( ) ) . getEmbeddables ( ) . get ( ( ( AbstractAttribute ) embeddable ) . getBindableJavaType ( ) ) ; Attribute embeddedAttribute = embeddedEntity . getAttribute ( embeddedFieldName ) ; builder . append ( ( ( AbstractAttribute ) embeddedAttribute ) . getJPAColumnName ( ) ) ; } else { builder . append ( ( ( AbstractAttribute ) entityType . getAttribute ( fieldName ) ) . getJPAColumnName ( ) ) ; } builder . append ( "," ) ; } builder . deleteCharAt ( builder . length ( ) - 1 ) ; return builder . toString ( ) ; } | prepare composite index . |
35,370 | public LoadState isLoadedWithoutReference ( Object paramObject , String paramString ) { return PersistenceUtilHelper . isLoadedWithoutReference ( paramObject , paramString , provider . getCache ( ) ) ; } | If the provider determines that the entity has been provided by itself and that the state of the specified attribute has been loaded this method returns LoadState . LOADED . If the provider determines that the entity has been provided by itself and that either entity attributes with FetchType EAGER have not been loaded or that the state of the specified attribute has not been loaded this methods returns LoadState . NOT_LOADED . If a provider cannot determine the load state this method returns LoadState . UNKNOWN . The provider s implementation of this method must not obtain a reference to an attribute value as this could trigger the loading of entity state if the entity has been provided by a different provider . |
35,371 | private int toInt ( byte [ ] data ) { if ( data == null || data . length != 4 ) return 0x0 ; return ( int ) ( ( 0xff & data [ 0 ] ) << 24 | ( 0xff & data [ 1 ] ) << 16 | ( 0xff & data [ 2 ] ) << 8 | ( 0xff & data [ 3 ] ) << 0 ) ; } | To int . |
35,372 | public void download ( ) { DataKeeperService service = DataKeeperUtils . getService ( ) ; setDocumentId ( Integer . parseInt ( FacesUtils . getRequest ( ) . getParameter ( "documentId" ) ) ) ; DocumentInfo document = service . findDocumentByDocumentId ( getDocumentId ( ) ) ; final HttpServletResponse response = ( HttpServletResponse ) FacesContext . getCurrentInstance ( ) . getExternalContext ( ) . getResponse ( ) ; ServletOutputStream out = null ; try { out = response . getOutputStream ( ) ; out . write ( document . getData ( ) , 0 , 4096 ) ; } catch ( IOException e ) { } finally { if ( out != null ) { try { out . flush ( ) ; out . close ( ) ; } catch ( IOException e ) { } } } FacesContext . getCurrentInstance ( ) . responseComplete ( ) ; } | Download file used for downloading photo . |
35,373 | public DataFrame getDataFrame ( String query , EntityMetadata m , KunderaQuery kunderaQuery ) { PersistenceUnitMetadata puMetadata = kunderaMetadata . getApplicationMetadata ( ) . getPersistenceUnitMetadata ( persistenceUnit ) ; String clientName = puMetadata . getProperty ( DATA_CLIENT ) . toLowerCase ( ) ; SparkDataClient dataClient = SparkDataClientFactory . getDataClient ( clientName ) ; if ( registeredTables . get ( m . getTableName ( ) ) == null || ! registeredTables . get ( m . getTableName ( ) ) ) { dataClient . registerTable ( m , this ) ; registeredTables . put ( m . getTableName ( ) , true ) ; } DataFrame dataFrame = sqlContext . sql ( query ) ; return dataFrame ; } | Gets the data frame . |
35,374 | private void onIdAttribute ( final MetaModelBuilder builder , EntityMetadata entityMetadata , final Class clazz , Field f ) { EntityType entity = ( EntityType ) builder . getManagedTypes ( ) . get ( clazz ) ; Attribute attrib = entity . getAttribute ( f . getName ( ) ) ; if ( ! attrib . isCollection ( ) && ( ( SingularAttribute ) attrib ) . isId ( ) ) { entityMetadata . setIdAttribute ( ( SingularAttribute ) attrib ) ; populateIdAccessorMethods ( entityMetadata , clazz , f ) ; } } | On id attribute . |
35,375 | private void onFamilyType ( EntityMetadata entityMetadata , final Class clazz , Field f ) { if ( entityMetadata . getType ( ) == null || ! entityMetadata . getType ( ) . equals ( Type . SUPER_COLUMN_FAMILY ) ) { if ( ( f . isAnnotationPresent ( Embedded . class ) && f . getType ( ) . getAnnotation ( Embeddable . class ) != null ) ) { entityMetadata . setType ( Type . SUPER_COLUMN_FAMILY ) ; } else if ( f . isAnnotationPresent ( ElementCollection . class ) && ! MetadataUtils . isBasicElementCollectionField ( f ) ) { entityMetadata . setType ( Type . SUPER_COLUMN_FAMILY ) ; } else { entityMetadata . setType ( Type . COLUMN_FAMILY ) ; } } } | On family type . |
35,376 | public String encriptPassword ( String password ) { String newpassword = null ; byte [ ] defaultBytes = password . getBytes ( ) ; try { MessageDigest algorithm = MessageDigest . getInstance ( "MD5" ) ; algorithm . reset ( ) ; algorithm . update ( defaultBytes ) ; byte messageDigest [ ] = algorithm . digest ( ) ; StringBuffer hexString = new StringBuffer ( ) ; for ( int i = 0 ; i < messageDigest . length ; i ++ ) { hexString . append ( Integer . toHexString ( 0xFF & messageDigest [ i ] ) ) ; } newpassword = hexString . toString ( ) ; } catch ( NoSuchAlgorithmException e ) { log . error ( "Error while encripting password {}, caused by : ." , password , e ) ; throw new PersistenceException ( e ) ; } return newpassword ; } | encriptPassword method used for encrypting password . |
35,377 | protected EnhanceEntity findById ( Object primaryKey , EntityMetadata m , Client client ) { try { Object o = client . find ( m . getEntityClazz ( ) , primaryKey ) ; if ( o == null ) { return null ; } else { return o instanceof EnhanceEntity ? ( EnhanceEntity ) o : new EnhanceEntity ( o , getId ( o , m ) , null ) ; } } catch ( Exception e ) { throw new EntityReaderException ( e ) ; } } | Retrieves an entity from ID |
35,378 | private void onRelation ( final Object entity , final Map < String , Object > relationsMap , final EntityMetadata m , final PersistenceDelegator pd , Relation relation , ForeignKey relationType , boolean lazilyloaded , Map < Object , Object > relationStack ) { FetchType fetchType = relation . getFetchType ( ) ; if ( ! lazilyloaded && fetchType . equals ( FetchType . LAZY ) ) { final Object entityId = PropertyAccessorHelper . getId ( entity , m ) ; getAssociationBuilder ( ) . setProxyRelationObject ( entity , relationsMap , m , pd , entityId , relation ) ; } else { if ( relation . getType ( ) . equals ( ForeignKey . MANY_TO_MANY ) ) { Field f = relation . getProperty ( ) ; Object object = PropertyAccessorHelper . getObject ( entity , f ) ; final Object entityId = PropertyAccessorHelper . getId ( entity , m ) ; PersistenceCacheManager . addEntityToPersistenceCache ( entity , pd , entityId ) ; getAssociationBuilder ( ) . populateRelationForM2M ( entity , m , pd , relation , object , relationsMap ) ; } else { onRelation ( entity , relationsMap , relation , m , pd , lazilyloaded , relationStack ) ; } } } | Parse over each relation of fetched entity . |
35,379 | private void onRelation ( Object entity , Map < String , Object > relationsMap , final Relation relation , final EntityMetadata metadata , final PersistenceDelegator pd , boolean lazilyloaded , Map < Object , Object > relationStack ) { final Object entityId = PropertyAccessorHelper . getId ( entity , metadata ) ; Object relationValue = relationsMap != null ? relationsMap . get ( relation . getJoinColumnName ( kunderaMetadata ) ) : null ; EntityMetadata targetEntityMetadata = KunderaMetadataManager . getEntityMetadata ( kunderaMetadata , relation . getTargetEntity ( ) ) ; List relationalEntities = fetchRelations ( relation , metadata , pd , entityId , relationValue , targetEntityMetadata ) ; if ( relationalEntities != null ) { for ( Object relationEntity : relationalEntities ) { if ( relationEntity != null ) { addToRelationStack ( relationStack , relationEntity , targetEntityMetadata ) ; } } for ( Object relationEntity : relationalEntities ) { if ( relationEntity != null ) { onParseRelation ( entity , pd , targetEntityMetadata , relationEntity , relation , lazilyloaded , relationStack ) ; PersistenceCacheManager . addEntityToPersistenceCache ( getEntity ( relationEntity ) , pd , PropertyAccessorHelper . getId ( relationEntity , targetEntityMetadata ) ) ; } } } } | Method to handle one to one association relation events . |
35,380 | private void onParseRelation ( Object entity , final PersistenceDelegator pd , EntityMetadata targetEntityMetadata , Object relationEntity , Relation relation , boolean lazilyloaded , Map < Object , Object > relationStack ) { parseRelations ( entity , getEntity ( relationEntity ) , getPersistedRelations ( relationEntity ) , pd , targetEntityMetadata , lazilyloaded , relationStack ) ; setRelationToEntity ( entity , relationEntity , relation ) ; } | Invokes parseRelations for relation entity and set relational entity within entity |
35,381 | private void setRelationToEntity ( Object entity , Object relationEntity , Relation relation ) { if ( relation . getTargetEntity ( ) . isAssignableFrom ( getEntity ( relationEntity ) . getClass ( ) ) ) { if ( relation . isUnary ( ) ) { PropertyAccessorHelper . set ( entity , relation . getProperty ( ) , getEntity ( relationEntity ) ) ; } else { Object associationObject = PropertyAccessorHelper . getObject ( entity , relation . getProperty ( ) ) ; if ( associationObject == null || ProxyHelper . isProxyOrCollection ( associationObject ) ) { associationObject = PropertyAccessorHelper . getCollectionInstance ( relation . getProperty ( ) ) ; PropertyAccessorHelper . set ( entity , relation . getProperty ( ) , associationObject ) ; } ( ( Collection ) associationObject ) . add ( getEntity ( relationEntity ) ) ; } } } | After successfully parsing set relational entity object within entity object . |
35,382 | private void parseRelations ( final Object originalEntity , final Object relationEntity , final Map < String , Object > relationsMap , final PersistenceDelegator pd , final EntityMetadata metadata , boolean lazilyloaded , Map < Object , Object > relationStack ) { for ( Relation relation : metadata . getRelations ( ) ) { if ( relation != null ) { FetchType fetchType = relation . getFetchType ( ) ; if ( ! lazilyloaded && fetchType . equals ( FetchType . LAZY ) ) { final Object entityId = PropertyAccessorHelper . getId ( relationEntity , metadata ) ; getAssociationBuilder ( ) . setProxyRelationObject ( relationEntity , relationsMap , metadata , pd , entityId , relation ) ; } else { if ( relation . isUnary ( ) && relation . getTargetEntity ( ) . isAssignableFrom ( originalEntity . getClass ( ) ) ) { Object associationObject = PropertyAccessorHelper . getObject ( relationEntity , relation . getProperty ( ) ) ; if ( relation . getType ( ) . equals ( ForeignKey . ONE_TO_ONE ) ) { if ( ( associationObject == null || ProxyHelper . isProxyOrCollection ( associationObject ) ) ) { PropertyAccessorHelper . set ( relationEntity , relation . getProperty ( ) , originalEntity ) ; } } else if ( relationsMap != null && relationsMap . containsKey ( relation . getJoinColumnName ( kunderaMetadata ) ) ) { PropertyAccessorHelper . set ( relationEntity , relation . getProperty ( ) , originalEntity ) ; } } else { final Object entityId = PropertyAccessorHelper . getId ( relationEntity , metadata ) ; Object relationValue = relationsMap != null ? relationsMap . get ( relation . getJoinColumnName ( kunderaMetadata ) ) : null ; final EntityMetadata targetEntityMetadata = KunderaMetadataManager . getEntityMetadata ( kunderaMetadata , relation . getTargetEntity ( ) ) ; List immediateRelations = fetchRelations ( relation , metadata , pd , entityId , relationValue , targetEntityMetadata ) ; if ( immediateRelations != null && ! immediateRelations . isEmpty ( ) ) { for ( Object immediateRelation : immediateRelations ) { if ( immediateRelation != null ) { if ( existsInRelationStack ( relationStack , immediateRelation , targetEntityMetadata ) ) { setRelationToEntity ( relationEntity , fetchFromRelationStack ( relationStack , immediateRelation , targetEntityMetadata ) , relation ) ; } else { addToRelationStack ( relationStack , immediateRelation , targetEntityMetadata ) ; onParseRelation ( relationEntity , pd , targetEntityMetadata , immediateRelation , relation , lazilyloaded , relationStack ) ; } PersistenceCacheManager . addEntityToPersistenceCache ( getEntity ( relationEntity ) , pd , PropertyAccessorHelper . getId ( relationEntity , metadata ) ) ; } } } } } } } } | Parse relations of provided relationEntity . |
35,383 | private Map < String , Object > getPersistedRelations ( Object relationEntity ) { return relationEntity != null && relationEntity . getClass ( ) . isAssignableFrom ( EnhanceEntity . class ) ? ( ( EnhanceEntity ) relationEntity ) . getRelations ( ) : null ; } | Returns wrapped relations . |
35,384 | private Object getEntity ( Object relationEntity ) { return relationEntity != null && relationEntity . getClass ( ) . isAssignableFrom ( EnhanceEntity . class ) ? ( ( EnhanceEntity ) relationEntity ) . getEntity ( ) : relationEntity ; } | Returns wrapped entity . |
35,385 | protected List < EnhanceEntity > onAssociationUsingLucene ( EntityMetadata m , Client client , List < EnhanceEntity > ls ) { Set < String > rSet = fetchDataFromLucene ( m . getEntityClazz ( ) , client ) ; List resultList = client . findAll ( m . getEntityClazz ( ) , null , rSet . toArray ( new String [ ] { } ) ) ; return m . getRelationNames ( ) != null && ! m . getRelationNames ( ) . isEmpty ( ) ? resultList : transform ( m , ls , resultList ) ; } | On association using lucene . |
35,386 | protected Set < String > fetchDataFromLucene ( Class < ? > clazz , Client client ) { String luceneQueryFromJPAQuery = KunderaCoreUtils . getLuceneQueryFromJPAQuery ( kunderaQuery , kunderaMetadata ) ; Map < String , Object > results = client . getIndexManager ( ) . search ( clazz , luceneQueryFromJPAQuery ) ; Set rSet = new HashSet ( results . values ( ) ) ; return rSet ; } | Fetch data from lucene . |
35,387 | private boolean compareTo ( Object relationalEntity , Object originalEntity ) { if ( relationalEntity != null && originalEntity != null && relationalEntity . getClass ( ) . isAssignableFrom ( originalEntity . getClass ( ) ) ) { EntityMetadata metadata = KunderaMetadataManager . getEntityMetadata ( kunderaMetadata , originalEntity . getClass ( ) ) ; Object relationalEntityId = PropertyAccessorHelper . getId ( relationalEntity , metadata ) ; Object originalEntityId = PropertyAccessorHelper . getId ( originalEntity , metadata ) ; return relationalEntityId . equals ( originalEntityId ) ; } return false ; } | Compares original with relational entity . |
35,388 | private void createOrUpdateSchema ( Boolean isUpdate ) { createNamespace ( isUpdate ) ; readExternalProperties ( ) ; Map < Class < ? > , EntityType < ? > > entityMap = kunderaMetadata . getApplicationMetadata ( ) . getMetaModelBuilder ( puMetadata . getPersistenceUnitName ( ) ) . getManagedTypes ( ) ; for ( Class < ? > clazz : entityMap . keySet ( ) ) { EntityMetadata m = KunderaMetadataManager . getEntityMetadata ( kunderaMetadata , clazz ) ; if ( m != null ) { String tablename = m . getTableName ( ) ; HTableDescriptor hTableDescriptor = getTableDescriptor ( clazz , entityMap . get ( clazz ) , tablename ) ; String hTableName = HBaseUtils . getHTableName ( databaseName , tablename ) ; createOrUpdateTable ( hTableName , hTableDescriptor ) ; } } } | Creates the or update schema . |
35,389 | private HTableDescriptor getTableDescriptor ( Class < ? > clazz , EntityType < ? > entityType , String tableName ) { try { AbstractManagedType < ? > ent = ( AbstractManagedType < ? > ) entityType ; HTableDescriptor tableDescriptor = null ; String hTableName = HBaseUtils . getHTableName ( databaseName , tableName ) ; tableDescriptor = ! admin . tableExists ( TableName . valueOf ( hTableName ) ) ? new HTableDescriptor ( TableName . valueOf ( hTableName ) ) : admin . getTableDescriptor ( TableName . valueOf ( hTableName ) ) ; addColumnFamilyAndSetProperties ( tableDescriptor , tableName ) ; List < String > secondaryTables = ( ( DefaultEntityAnnotationProcessor ) ent . getEntityAnnotation ( ) ) . getSecondaryTablesName ( ) ; for ( String secTable : secondaryTables ) { addColumnFamilyAndSetProperties ( tableDescriptor , secTable ) ; } List < Relation > relations = KunderaMetadataManager . getEntityMetadata ( kunderaMetadata , clazz ) . getRelations ( ) ; addJoinTable ( relations ) ; return tableDescriptor ; } catch ( IOException ex ) { logger . error ( "Either table isn't in enabled state or some network problem, Caused by: " , ex ) ; throw new SchemaGenerationException ( ex , "Hbase" ) ; } } | Gets the table descriptor . |
35,390 | private void addJoinTable ( List < Relation > relations ) { for ( Relation relation : relations ) { if ( relation . getType ( ) . equals ( ForeignKey . MANY_TO_MANY ) && relation . isRelatedViaJoinTable ( ) ) { String joinTableName = relation . getJoinTableMetadata ( ) . getJoinTableName ( ) ; String hTableName = HBaseUtils . getHTableName ( databaseName , joinTableName ) ; HTableDescriptor tableDescriptor = new HTableDescriptor ( TableName . valueOf ( hTableName ) ) ; tableDescriptor . addFamily ( new HColumnDescriptor ( joinTableName ) ) ; createOrUpdateTable ( hTableName , tableDescriptor ) ; } } } | Adds the join table . |
35,391 | private void addColumnFamilyAndSetProperties ( HTableDescriptor tableDescriptor , String colFamilyName ) { if ( ! tableDescriptor . hasFamily ( colFamilyName . getBytes ( ) ) ) { HColumnDescriptor hColumnDescriptor = getColumnDescriptor ( colFamilyName ) ; tableDescriptor . addFamily ( hColumnDescriptor ) ; setExternalProperties ( tableDescriptor . getNameAsString ( ) , hColumnDescriptor ) ; } } | Adds the column family and set properties . |
35,392 | private void setExternalProperties ( String name , HColumnDescriptor hColumnDescriptor ) { Properties properties = externalProperties != null ? externalProperties . get ( name ) : null ; if ( properties != null && ! properties . isEmpty ( ) ) { for ( Object obj : properties . keySet ( ) ) { hColumnDescriptor . setValue ( Bytes . toBytes ( obj . toString ( ) ) , Bytes . toBytes ( properties . get ( obj ) . toString ( ) ) ) ; } } } | Sets the external properties . |
35,393 | private void createNamespace ( boolean isUpdate ) { boolean isNameSpaceAvailable = isNamespaceAvailable ( databaseName ) ; if ( isNameSpaceAvailable && ! isUpdate ) { drop ( ) ; } if ( ! ( isNameSpaceAvailable && isUpdate ) ) { try { NamespaceDescriptor descriptor = NamespaceDescriptor . create ( databaseName ) . build ( ) ; admin . createNamespace ( descriptor ) ; } catch ( IOException ioex ) { logger . error ( "Either table isn't in enabled state or some network problem, Caused by: " , ioex ) ; throw new SchemaGenerationException ( ioex , "Hbase" ) ; } } } | Creates the namespace . |
35,394 | private boolean isNamespaceAvailable ( String databaseName ) { try { for ( NamespaceDescriptor ns : admin . listNamespaceDescriptors ( ) ) { if ( ns . getName ( ) . equals ( databaseName ) ) { return true ; } } return false ; } catch ( IOException ioex ) { logger . error ( "Either table isn't in enabled state or some network problem, Caused by: " , ioex ) ; throw new SchemaGenerationException ( ioex , "Either table isn't in enabled state or some network problem." ) ; } } | Checks if is namespace available . |
35,395 | private void createOrUpdateTable ( String tablename , HTableDescriptor hTableDescriptor ) { try { if ( admin . isTableAvailable ( tablename ) ) { admin . modifyTable ( tablename , hTableDescriptor ) ; } else { admin . createTable ( hTableDescriptor ) ; } } catch ( IOException ioex ) { logger . error ( "Either table isn't in enabled state or some network problem, Caused by: " , ioex ) ; throw new SchemaGenerationException ( ioex , "Either table isn't in enabled state or some network problem." ) ; } } | Creates the or update table . |
35,396 | private void vaildateHostPort ( String host , String port ) { if ( host == null || ! StringUtils . isNumeric ( port ) || port . isEmpty ( ) ) { logger . error ( "Host or port should not be null / port should be numeric" ) ; throw new IllegalArgumentException ( "Host or port should not be null / port should be numeric" ) ; } } | Vaildate host port . |
35,397 | private void readExternalProperties ( ) { schemas = HBasePropertyReader . hsmd . getDataStore ( ) != null ? HBasePropertyReader . hsmd . getDataStore ( ) . getSchemas ( ) : null ; List < Table > tables = null ; if ( schemas != null && ! schemas . isEmpty ( ) ) { for ( Schema s : schemas ) { if ( s . getName ( ) != null && s . getName ( ) . equalsIgnoreCase ( databaseName ) ) { tables = s . getTables ( ) ; } } } if ( tables != null && ! tables . isEmpty ( ) ) { for ( Table table : tables ) { externalProperties . put ( HBaseUtils . getHTableName ( databaseName , table . getName ( ) ) , table . getProperties ( ) ) ; } } } | Read external properties . |
35,398 | public static void closeContent ( HttpResponse response ) { if ( response != null ) { try { InputStream content = response . getEntity ( ) . getContent ( ) ; content . close ( ) ; } catch ( Exception e ) { throw new KunderaException ( e ) ; } } } | Close content . |
35,399 | static Object appendQuotes ( Object value ) { if ( value instanceof String || value instanceof Character ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "\"" ) ; builder . append ( value ) ; builder . append ( "\"" ) ; return builder . toString ( ) ; } return value ; } | Append quotes . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.