idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
15,600
public ValidationSessionInfo createSession ( HttpServletRequest req , HttpServletResponse res ) { String key = this . getSessionKey ( ) ; ValidationSessionInfo sessionInfo = new ValidationSessionInfo ( req , key ) ; this . sessionMap . put ( key , sessionInfo ) ; res . addCookie ( new Cookie ( "AuthToken" , key ) ) ; return sessionInfo ; }
Create session validation session info .
15,601
public Object getSession ( HttpServletRequest req ) { if ( req . getCookies ( ) == null ) { return null ; } Cookie cookie = Arrays . stream ( req . getCookies ( ) ) . filter ( c -> c . getName ( ) . equalsIgnoreCase ( "ValidationSession" ) ) . findFirst ( ) . orElse ( null ) ; if ( cookie == null ) { return null ; } return this . sessionMap . get ( cookie . getValue ( ) ) ; }
Gets session .
15,602
private String response ( HttpURLConnection connection ) throws LightblueHttpClientException { try ( InputStream responseStream = connection . getInputStream ( ) ) { return readResponseStream ( responseStream , connection ) ; } catch ( IOException e ) { return readErrorStream ( connection , e ) ; } }
Parses response whether or not the request was successful if possible . Reads entire input stream and closes it so the socket knows it is finished and may be put back into a pool for reuse .
15,603
private String readResponseStream ( InputStream responseStream , HttpURLConnection connection ) throws IOException { LOGGER . debug ( "Reading response stream" ) ; InputStream decodedStream = responseStream ; if ( compression == Compression . LZF && "lzf" . equals ( connection . getHeaderField ( "Content-Encoding" ) ) ) { LOGGER . debug ( "Decoding lzf" ) ; decodedStream = new LZFInputStream ( responseStream ) ; } int contentLength = connection . getContentLength ( ) ; if ( contentLength == 0 ) { return "" ; } else { return new String ( ByteStreams . toByteArray ( decodedStream ) , UTF_8 ) ; } }
Tries to efficiently allocate the response string if the Content - Length header is set .
15,604
protected void openConnection ( ) throws SQLException { if ( connection == null ) { try { Class . forName ( configuration . getJdbcDriver ( ) ) ; } catch ( NullPointerException npe ) { throw new RuntimeException ( "error while lookup jdbc driver class. jdbc driver is not configured." , npe ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( "jdbc driver not found" , e ) ; } connection = DriverManager . getConnection ( configuration . getJdbcUrl ( ) , configuration . getJdbcUser ( ) , configuration . getJdbcPassword ( ) ) ; connection . setAutoCommit ( false ) ; } }
Establish a connection to the given database .
15,605
protected void closeConnection ( ) throws SQLException { if ( connection != null && ! connection . isClosed ( ) ) { connection . close ( ) ; connection = null ; } }
Close the connection to the database .
15,606
protected void executeScript ( final String filename , final Statement statement ) throws SQLException { LOG . info ( "Executing sql script: " + filename ) ; InputStream fileInputStream ; try { fileInputStream = ConfigurationLoader . loadResource ( filename ) ; } catch ( FileNotFoundException e ) { LOG . error ( "could not execute script" , e ) ; return ; } final BufferedReader reader = new BufferedReader ( new InputStreamReader ( fileInputStream ) ) ; executeScript ( reader , statement ) ; }
Execute the given sql script .
15,607
@ SuppressWarnings ( "unchecked" ) public < T > HandlerRegistration register ( Deserializer < T > deserializer ) { final HandlerRegistration reg = bindDeserializerToType ( deserializer , deserializer . handledType ( ) ) ; if ( deserializer instanceof HasImpl ) { Class [ ] impls = ( ( HasImpl ) deserializer ) . implTypes ( ) ; final HandlerRegistration [ ] regs = new HandlerRegistration [ impls . length + 1 ] ; regs [ 0 ] = reg ; for ( int i = 0 ; i < impls . length ; i ++ ) { Class impl = impls [ i ] ; regs [ i + 1 ] = bindDeserializerToType ( deserializer , impl ) ; } return new HandlerRegistration ( ) { public void removeHandler ( ) { for ( HandlerRegistration reg : regs ) { reg . removeHandler ( ) ; } } } ; } return reg ; }
Register a deserializer of the given type .
15,608
@ SuppressWarnings ( "unchecked" ) public < T > HandlerRegistration register ( Serializer < T > serializer ) { final HandlerRegistration reg = bindSerializerToType ( serializer , serializer . handledType ( ) ) ; if ( serializer instanceof HasImpl ) { Class [ ] impls = ( ( HasImpl ) serializer ) . implTypes ( ) ; final HandlerRegistration [ ] regs = new HandlerRegistration [ impls . length + 1 ] ; regs [ 0 ] = reg ; for ( int i = 0 ; i < impls . length ; i ++ ) { Class impl = impls [ i ] ; regs [ i + 1 ] = bindSerializerToType ( serializer , impl ) ; } return new HandlerRegistration ( ) { public void removeHandler ( ) { for ( HandlerRegistration reg : regs ) { reg . removeHandler ( ) ; } } } ; } return reg ; }
Register a serializer of the given type .
15,609
@ SuppressWarnings ( "unchecked" ) public < T > Deserializer < T > getDeserializer ( Class < T > type , String mediaType ) throws SerializationException { checkNotNull ( type , "Type (Class<T>) cannot be null." ) ; checkNotNull ( mediaType , "Media-Type cannot be null." ) ; final String typeName = getClassName ( type ) ; final Key key = new Key ( typeName , mediaType ) ; logger . log ( Level . FINE , "Querying for Deserializer of type '" + typeName + "' and " + "media-type '" + mediaType + "'." ) ; ArrayList < DeserializerHolder > holders = deserializers . get ( typeName ) ; if ( holders != null ) { for ( DeserializerHolder holder : holders ) { if ( holder . key . matches ( key ) ) { logger . log ( Level . FINE , "Deserializer for type '" + holder . deserializer . handledType ( ) + "' and " + "media-type '" + Arrays . toString ( holder . deserializer . mediaType ( ) ) + "' matched: " + holder . deserializer . getClass ( ) . getName ( ) ) ; return ( Deserializer < T > ) holder . deserializer ; } } } logger . log ( Level . WARNING , "There is no Deserializer registered for " + type . getName ( ) + " and media-type " + mediaType + ". If you're relying on auto-generated deserializers," + " please make sure you imported the correct GWT Module." ) ; return null ; }
Retrieve Deserializer from manager .
15,610
@ SuppressWarnings ( "unchecked" ) public < T > Serializer < T > getSerializer ( Class < T > type , String mediaType ) throws SerializationException { checkNotNull ( type , "Type (Class<T>) cannot be null." ) ; checkNotNull ( mediaType , "Media-Type cannot be null." ) ; final String typeName = getClassName ( type ) ; final Key key = new Key ( typeName , mediaType ) ; logger . log ( Level . FINE , "Querying for Serializer of type '" + typeName + "' and " + "media-type '" + mediaType + "'." ) ; ArrayList < SerializerHolder > holders = serializers . get ( typeName ) ; if ( holders != null ) { for ( SerializerHolder holder : holders ) { if ( holder . key . matches ( key ) ) { logger . log ( Level . FINE , "Serializer for type '" + holder . serializer . handledType ( ) + "' and " + "media-type '" + Arrays . toString ( holder . serializer . mediaType ( ) ) + "' matched: " + holder . serializer . getClass ( ) . getName ( ) ) ; return ( Serializer < T > ) holder . serializer ; } } } logger . log ( Level . WARNING , "There is no Serializer registered for type " + type . getName ( ) + " and media-type " + mediaType + ". If you're relying on auto-generated serializers," + " please make sure you imported the correct GWT Module." ) ; return null ; }
Retrieve Serializer from manager .
15,611
private RecordList loadData ( AbstractDataTable table , DataSchema schema ) { RecordListBuilder recordListBuilder = new RecordListBuilder ( RecordListBuilder . CompressionMode . CANONICAL , schema ) ; if ( schema . size ( ) != table . getNumberOfColumns ( ) ) { final IllegalArgumentException illegalArgumentException = new IllegalArgumentException ( "schema row definition do not match table supplied" ) ; logger . log ( SEVERE , "Warning:" , illegalArgumentException ) ; } int columnLength = table . getNumberOfColumns ( ) ; for ( int rowIndex = 0 ; rowIndex < table . getNumberOfRows ( ) ; rowIndex ++ ) { String [ ] fields = new String [ columnLength ] ; for ( int columnIndex = 0 ; columnIndex < columnLength ; columnIndex ++ ) { if ( table . getColumnType ( columnIndex ) == AbstractDataTable . ColumnType . DATE ) { Date valueDate = table . getValueDate ( rowIndex , columnIndex ) ; if ( valueDate == null ) { continue ; } String dateFormatted = DateTimeFormat . getFormat ( DateTimeFormat . PredefinedFormat . ISO_8601 ) . format ( valueDate ) ; fields [ columnIndex ] = dateFormatted ; } else { fields [ columnIndex ] = table . getFormattedValue ( rowIndex , columnIndex ) ; } } recordListBuilder . addRecord ( ( fields ) ) ; } String dataSourceHash = "" ; return recordListBuilder . createRecordList ( dataSourceHash ) ; }
Given a schema attempts to load table into internal structure
15,612
private static TrustManager createNaiveTrustManager ( ) { return new X509TrustManager ( ) { public void checkClientTrusted ( X509Certificate [ ] chain , String authType ) throws CertificateException { } public void checkServerTrusted ( X509Certificate [ ] chain , String authType ) throws CertificateException { } public X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } } ; }
Naive trust manager trusts all .
15,613
protected void onLoad ( ) { mainAbsolutePanel . setSize ( String . valueOf ( yuiSliderGwtWidget . getOffsetWidth ( ) ) , String . valueOf ( yuiSliderGwtWidget . getOffsetHeight ( ) ) ) ; setupMarkerLabels ( ) ; }
override onLoad to know when absolutePanel s size can be set
15,614
public void urlCheckAndSave ( BasicCheckInfo basicCheckInfo , ParamType paramType , ReqUrl reqUrl , Class < ? > type ) { if ( ! this . validationConfig . isFreshUrlSave ( ) || ! basicCheckInfo . isUrlMapping ( ) ) { return ; } List < ValidationData > datas = this . validationDataRepository . findByParamTypeAndMethodAndUrl ( paramType , reqUrl . getMethod ( ) , reqUrl . getUrl ( ) ) ; if ( datas . isEmpty ( ) ) { this . saveParameter ( basicCheckInfo . getDetailParam ( ) , paramType , reqUrl , null , type , 0 , this . validationConfig . getMaxDeepLevel ( ) ) ; this . validationDataRepository . flush ( ) ; this . validationStore . refresh ( ) ; } }
Url check and save .
15,615
public MapBuilder configureMapDimension ( Integer width , Integer height ) { this . mapHeight = height ; this . mapWidth = width ; return this ; }
Setup map display properties
15,616
protected void detectTypes ( ImportMatrix matrix ) { for ( int row = 0 ; row < matrix . getNumberOfRows ( ) ; row ++ ) { for ( int column = 0 ; column < matrix . getNumberOfColumns ( ) ; column ++ ) { ImportCell cell = matrix . getCell ( row , column ) ; if ( cell != null && cell . getInterpretation ( ) == null ) { cell . setInterpretation ( cellContentInterpreter . interpretString ( cell . getContent ( ) ) ) ; } } } }
Detect types of each cell of the matrix
15,617
protected PCMDirection detectDirection ( ImportMatrix matrix ) { double sumHomogeneityOfRow = 0 ; for ( int row = 0 ; row < matrix . getNumberOfRows ( ) ; row ++ ) { Map < String , Integer > types = new HashMap < > ( ) ; for ( int column = 0 ; column < matrix . getNumberOfColumns ( ) ; column ++ ) { countType ( matrix , row , column , types ) ; } if ( ! types . isEmpty ( ) ) { double homogeneityOfRow = Collections . max ( types . values ( ) ) / ( double ) matrix . getNumberOfColumns ( ) ; sumHomogeneityOfRow += homogeneityOfRow ; } } double homogeneityOfColumns = 0 ; for ( int column = 0 ; column < matrix . getNumberOfColumns ( ) ; column ++ ) { Map < String , Integer > types = new HashMap < > ( ) ; for ( int row = 0 ; row < matrix . getNumberOfRows ( ) ; row ++ ) { countType ( matrix , row , column , types ) ; } if ( ! types . isEmpty ( ) ) { double homogeneityOfColumn = Collections . max ( types . values ( ) ) / ( double ) matrix . getNumberOfRows ( ) ; homogeneityOfColumns += homogeneityOfColumn ; } } if ( sumHomogeneityOfRow / matrix . getNumberOfRows ( ) > homogeneityOfColumns / matrix . getNumberOfColumns ( ) ) { return PCMDirection . PRODUCTS_AS_COLUMNS ; } else { return PCMDirection . PRODUCTS_AS_LINES ; } }
Detect if products are represented by a line or a column
15,618
protected IONode < String > detectFeatures ( ImportMatrix matrix , PCMContainer pcmContainer ) { IONode < String > root = new IONode < > ( null ) ; List < IONode < String > > parents = new ArrayList < > ( ) ; for ( int column = 0 ; column < matrix . getNumberOfColumns ( ) ; column ++ ) { parents . add ( root ) ; } for ( int row = 0 ; row < matrix . getNumberOfRows ( ) ; row ++ ) { List < IONode < String > > nextParents = new ArrayList < > ( parents ) ; for ( int column = 0 ; column < matrix . getNumberOfColumns ( ) ; column ++ ) { IOCell currentCell = matrix . getCell ( row , column ) ; if ( currentCell == null ) { currentCell = new IOCell ( "" ) ; } IONode < String > parent = parents . get ( column ) ; boolean sameAsParent = currentCell . getContent ( ) . equals ( parent . getContent ( ) ) ; boolean sameAsPrevious = false ; boolean sameParentAsPrevious = true ; if ( column > 0 ) { IOCell previousCell = matrix . getCell ( row , column - 1 ) ; if ( previousCell == null ) { previousCell = new IOCell ( "" ) ; } sameAsPrevious = currentCell . getContent ( ) . equals ( previousCell . getContent ( ) ) ; if ( parent . getContent ( ) != null ) { sameParentAsPrevious = parent . getContent ( ) . equals ( parents . get ( column - 1 ) . getContent ( ) ) ; } } if ( ! sameAsParent && ( ! sameParentAsPrevious || ! sameAsPrevious ) ) { IONode < String > newNode = new IONode < > ( currentCell . getContent ( ) ) ; newNode . getPositions ( ) . add ( column ) ; parent . getChildren ( ) . add ( newNode ) ; nextParents . set ( column , newNode ) ; } else if ( column > 0 && sameParentAsPrevious && sameAsPrevious ) { IONode < String > previousNode = nextParents . get ( column - 1 ) ; previousNode . getPositions ( ) . add ( column ) ; nextParents . set ( column , previousNode ) ; } } parents = nextParents ; if ( root . getLeaves ( ) . size ( ) == matrix . getNumberOfColumns ( ) ) { break ; } } return root ; }
Detect features from the information contained in the matrix and the provided direction
15,619
protected void createProducts ( ImportMatrix matrix , PCMContainer pcmContainer , Map < Integer , Feature > positionToFeature ) { int featuresDepth = pcmContainer . getPcm ( ) . getFeaturesDepth ( ) ; for ( int row = featuresDepth ; row < matrix . getNumberOfRows ( ) ; row ++ ) { Product product = factory . createProduct ( ) ; for ( int column = 0 ; column < matrix . getNumberOfColumns ( ) ; column ++ ) { Cell cell = factory . createCell ( ) ; cell . setFeature ( positionToFeature . get ( column ) ) ; ImportCell ioCell = matrix . getCell ( row , column ) ; if ( ioCell == null ) { ioCell = new ImportCell ( "" ) ; } cell . setContent ( ioCell . getContent ( ) ) ; cell . setRawContent ( ioCell . getRawContent ( ) ) ; cell . setInterpretation ( ioCell . getInterpretation ( ) ) ; product . addCell ( cell ) ; } pcmContainer . getPcm ( ) . addProduct ( product ) ; pcmContainer . getMetadata ( ) . setProductPosition ( product , row ) ; } }
Detect and create products from the information contained in the matrix and the provided direction
15,620
public static String readBody ( HttpServletRequest request ) { BufferedReader input = null ; try { input = new BufferedReader ( new InputStreamReader ( request . getInputStream ( ) ) ) ; StringBuilder builder = new StringBuilder ( ) ; String buffer ; while ( ( buffer = input . readLine ( ) ) != null ) { if ( builder . length ( ) > 0 ) { builder . append ( "\n" ) ; } builder . append ( buffer ) ; } return builder . toString ( ) ; } catch ( IOException e ) { log . info ( "http io exception : " + e . getMessage ( ) ) ; } return null ; }
Read body string .
15,621
private RecordList convertDataTable ( AbstractDataTable table , DataSchema schema ) { return dataTableConversionUtility . convertDataTableToRecordList ( schema , table ) ; }
covert a gwtDatatable to an internal RecordList
15,622
private List < Integer > calculateRowsToFilter ( DataView dataView , FilterQuery filterQuery , DataSchema schema ) { JsArray < JavaScriptObject > propertiesJsArray = convertToColumnIndexAndValueArray ( filterQuery , schema ) ; JsArrayInteger jsArrayInteger = getFilteredRows ( dataView , propertiesJsArray ) ; return toTypedObjectArray ( jsArrayInteger ) ; }
Calculate the row indexes for rows that match all of the given filters . Parses the filterQuery
15,623
public static ObjectMapper getDefaultObjectMapper ( ) { ObjectMapper mapper = new ObjectMapper ( ) ; mapper . configure ( DeserializationFeature . FAIL_ON_UNKNOWN_PROPERTIES , false ) ; mapper . configure ( DeserializationFeature . READ_UNKNOWN_ENUM_VALUES_AS_NULL , true ) ; mapper . configure ( SerializationFeature . FAIL_ON_EMPTY_BEANS , false ) ; mapper . setSerializationInclusion ( JsonInclude . Include . NON_NULL ) ; return mapper ; }
Gets default object mapper .
15,624
public static boolean isNumberObj ( Object type ) { try { Double . valueOf ( type + "" ) ; } catch ( NumberFormatException e ) { return false ; } return true ; }
Is number obj boolean .
15,625
public static boolean isDoubleType ( Class < ? > type ) { return ( type . isPrimitive ( ) && type == float . class ) || ( type . isPrimitive ( ) && type == double . class ) || ( ! type . isPrimitive ( ) && type == Float . class ) || ( ! type . isPrimitive ( ) && type == Double . class ) ; }
Is double type boolean .
15,626
public static boolean isIntType ( Class < ? > type ) { return ( type . isPrimitive ( ) && type == int . class ) || ( type . isPrimitive ( ) && type == long . class ) || ( ! type . isPrimitive ( ) && type == Integer . class ) || ( ! type . isPrimitive ( ) && type == Long . class ) ; }
Is int type boolean .
15,627
public static Method getSetterMethodNotCheckParamType ( Class < ? > cType , String fieldName ) { String methodName = getMethodName ( fieldName , SET_METHOD_PREFIX ) ; Method [ ] methods = cType . getMethods ( ) ; for ( Method m : methods ) { if ( m . getName ( ) . equals ( methodName ) && m . getParameterCount ( ) == 1 ) { return m ; } } return null ; }
Gets setter method not check param type .
15,628
public static Method getSetterMethod ( Class < ? > cType , String fieldName , Class < ? > paramType ) { Class < ? > subType = getSubType ( paramType ) ; String methodName = getMethodName ( fieldName , SET_METHOD_PREFIX ) ; try { return cType . getMethod ( methodName , paramType ) ; } catch ( NoSuchMethodException e ) { try { return cType . getMethod ( methodName , subType ) ; } catch ( NoSuchMethodException e1 ) { return null ; } } }
Gets setter method .
15,629
public static String getMethodName ( String name , String prefix ) { return prefix + name . substring ( 0 , 1 ) . toUpperCase ( ) + name . substring ( 1 ) ; }
Gets method name .
15,630
public static String getFieldNameFromMethod ( Method m ) { String methodName = m . getName ( ) ; if ( methodName . startsWith ( GET_METHOD_PREFIX ) ) { methodName = methodName . replaceFirst ( GET_METHOD_PREFIX , "" ) ; } else if ( methodName . startsWith ( IS_METHOD_PREFIX ) ) { methodName = methodName . replaceFirst ( IS_METHOD_PREFIX , "" ) ; } else if ( methodName . startsWith ( SET_METHOD_PREFIX ) ) { methodName = methodName . replaceFirst ( SET_METHOD_PREFIX , "" ) ; } return methodName . substring ( 0 , 1 ) . toLowerCase ( ) + methodName . substring ( 1 ) ; }
Gets field name from method .
15,631
public static Method getGetterMethod ( Class < ? > c , String field ) { try { return c . getMethod ( getMethodName ( field , GET_METHOD_PREFIX ) , EMPTY_CLASS ) ; } catch ( NoSuchMethodException e ) { try { return c . getMethod ( getMethodName ( field , IS_METHOD_PREFIX ) , EMPTY_CLASS ) ; } catch ( NoSuchMethodException e1 ) { return null ; } } }
Gets getter method .
15,632
public static Object getValue ( Object obj , String field ) { Method getter = getGetterMethod ( obj . getClass ( ) , field ) ; try { return getter . invoke ( obj ) ; } catch ( IllegalAccessException | InvocationTargetException e ) { return null ; } }
Gets value .
15,633
public static Object objDeepCopy ( Object from , Object to , String ... copyFields ) { if ( from == null || to == null ) { log . error ( "object deep copy from or to is null " ) ; return to ; } for ( String field : copyFields ) { copyFromTo ( from , to , field ) ; } return to ; }
Obj deep copy object .
15,634
public static < T > T objectDeepCopyWithWhiteList ( Object from , Object to , String ... copyFields ) { return ( T ) to . getClass ( ) . cast ( objDeepCopy ( from , to , copyFields ) ) ; }
Object deep copy with white list t .
15,635
public static boolean isGetterMethod ( Method m ) { String methodName = m . getName ( ) ; if ( methodName . equals ( "getClass" ) ) { return false ; } if ( ! methodName . startsWith ( GET_METHOD_PREFIX ) && ! methodName . startsWith ( IS_METHOD_PREFIX ) ) { return false ; } if ( m . getParameterCount ( ) > 0 ) { return false ; } return true ; }
Is getter method boolean .
15,636
public static Double getObjectSize ( Object value ) { double v = 1 ; if ( value instanceof String ) { v = ( ( String ) value ) . length ( ) ; if ( v < 1 ) { return null ; } } else if ( value instanceof List ) { v = ( ( List ) value ) . size ( ) ; } else if ( ValidationObjUtil . isNumberObj ( value ) ) { v = Double . valueOf ( value + "" ) ; } return v ; }
Gets object size .
15,637
public static Class < ? > getListInnerClassFromGenericType ( Type genericType ) { ParameterizedType innerClass = ( ParameterizedType ) genericType ; return ( Class < ? > ) innerClass . getActualTypeArguments ( ) [ 0 ] ; }
Gets list inner class from generic type .
15,638
public MsgChecker replaceCallback ( BasicCheckRule type , ValidationInvalidCallback cb ) { this . callbackMap . put ( type . name ( ) , cb ) ; return this ; }
Replace callback msg checker .
15,639
public void checkPoint ( ValidationData param , ValidationRule rule , Object bodyObj , Object standardValue ) { Object value = param . getValue ( bodyObj ) ; BaseValidationCheck checker = this . validationRuleStore . getValidationChecker ( rule ) ; if ( ( value != null && standardValue != null ) || rule . getAssistType ( ) . isNullable ( ) ) { boolean valid = checker . check ( value , standardValue ) ; if ( ! valid ) { this . callExcpetion ( param , rule , value , standardValue ) ; } } Object replaceValue = checker . replace ( value , standardValue , param ) ; if ( replaceValue != null && replaceValue != value ) { param . replaceValue ( bodyObj , replaceValue ) ; } }
Check point .
15,640
public void checkPointListChild ( ValidationData param , ValidationRule rule , Object bodyObj , Object standardValue ) { ValidationData listParent = param . findListParent ( ) ; List list = ( List ) listParent . getValue ( bodyObj ) ; if ( list == null || list . isEmpty ( ) ) { return ; } list . stream ( ) . forEach ( item -> { this . checkPoint ( param , rule , item , standardValue ) ; } ) ; }
Check point list child .
15,641
public void checkDataInnerRules ( ValidationData data , Object bodyObj ) { data . getValidationRules ( ) . stream ( ) . filter ( vr -> vr . isUse ( ) ) . forEach ( rule -> { if ( data . isListChild ( ) ) { this . checkPointListChild ( data , rule , bodyObj , rule . getStandardValue ( ) ) ; } else { this . checkPoint ( data , rule , bodyObj , rule . getStandardValue ( ) ) ; } } ) ; }
Check data inner rules .
15,642
public void checkRequest ( BasicCheckInfo basicCheckInfo , Object bodyObj ) { String key = basicCheckInfo . getUniqueKey ( ) ; List < ValidationData > checkData = this . validationStore . getValidationDatas ( basicCheckInfo . getParamType ( ) , key ) ; if ( checkData == null || checkData . isEmpty ( ) ) { return ; } checkData . stream ( ) . forEach ( data -> { this . checkDataInnerRules ( data , bodyObj ) ; } ) ; }
Check request .
15,643
private void applyDefaultValues ( Map < String , Object > parameterValues ) { for ( Parameter < ? > parameter : allParameters ) { parameterValues . put ( parameter . getName ( ) , getParameterDefaultValue ( parameter ) ) ; } }
Apply default values for all parameters .
15,644
private < T > T getParameterDefaultValue ( Parameter < T > parameter ) { String defaultOsgiConfigProperty = parameter . getDefaultOsgiConfigProperty ( ) ; if ( StringUtils . isNotBlank ( defaultOsgiConfigProperty ) ) { String [ ] parts = StringUtils . split ( defaultOsgiConfigProperty , ":" ) ; String className = parts [ 0 ] ; String propertyName = parts [ 1 ] ; ServiceReference ref = bundleContext . getServiceReference ( className ) ; if ( ref != null ) { Object value = ref . getProperty ( propertyName ) ; return TypeConversion . osgiPropertyToObject ( value , parameter . getType ( ) , parameter . getDefaultValue ( ) ) ; } } return parameter . getDefaultValue ( ) ; }
Get default value for parameter - from OSGi configuration property or parameter definition itself .
15,645
private void applyOverrideSystemDefault ( Map < String , Object > parameterValues ) { for ( Parameter < ? > parameter : allParameters ) { Object overrideValue = parameterOverride . getOverrideSystemDefault ( parameter ) ; if ( overrideValue != null ) { parameterValues . put ( parameter . getName ( ) , overrideValue ) ; } } }
Apply system - wide overrides for default values .
15,646
private Map < String , Object > ensureValidValueTypes ( Map < String , Object > parameterValues ) { Map < String , Object > transformedParameterValues = new HashMap < > ( ) ; for ( Map . Entry < String , Object > entry : parameterValues . entrySet ( ) ) { if ( entry . getKey ( ) == null || entry . getValue ( ) == null ) { continue ; } else { Parameter < ? > parameter = allParametersMap . get ( entry . getKey ( ) ) ; if ( parameter == null ) { continue ; } else { Object transformedValue = PersistenceTypeConversion . fromPersistenceType ( entry . getValue ( ) , parameter . getType ( ) ) ; if ( ! parameter . getType ( ) . isAssignableFrom ( transformedValue . getClass ( ) ) ) { continue ; } transformedParameterValues . put ( entry . getKey ( ) , transformedValue ) ; } } } return transformedParameterValues ; }
Make sure value types match with declared parameter types . Values which types do not match or for which no parameter definition exists are removed . Types are converted from persistence format if required .
15,647
private SortedSet < String > applyOverrideForce ( String configurationId , Map < String , Object > parameterValues , SortedSet < String > ancestorLockedParameterNames ) { for ( Parameter < ? > parameter : allParameters ) { Object overrideValue = parameterOverride . getOverrideForce ( configurationId , parameter ) ; if ( overrideValue != null ) { parameterValues . put ( parameter . getName ( ) , overrideValue ) ; } } Set < String > overrideLockedParameterNames = parameterOverride . getLockedParameterNames ( configurationId ) ; return mergeSets ( ancestorLockedParameterNames , overrideLockedParameterNames ) ; }
Apply forced overrides for a configurationId .
15,648
private void validateParameterProviders ( ) { Set < String > parameterNames = new HashSet < > ( ) ; for ( ParameterProvider provider : this . parameterProviders ) { Set < String > applicationIdsOfThisProvider = new HashSet < > ( ) ; for ( Parameter < ? > parameter : provider . getParameters ( ) ) { if ( StringUtils . isNotEmpty ( parameter . getApplicationId ( ) ) ) { applicationIdsOfThisProvider . add ( parameter . getApplicationId ( ) ) ; } if ( parameterNames . contains ( parameter . getName ( ) ) ) { log . warn ( "Parameter name is not unique: {} (application: {})" , parameter . getName ( ) , parameter . getApplicationId ( ) ) ; } else { parameterNames . add ( parameter . getName ( ) ) ; } } if ( applicationIdsOfThisProvider . size ( ) > 1 ) { log . warn ( "Parameter provider {} defines parameters with multiple application Ids: {}" , provider , applicationIdsOfThisProvider . toArray ( new String [ applicationIdsOfThisProvider . size ( ) ] ) ) ; } } }
Validate that application ids and configuration names are unique over all providers .
15,649
private SortedSet < String > mergeSets ( SortedSet < String > primary , Set < String > secondary ) { SortedSet < String > result = primary ; if ( ! secondary . isEmpty ( ) ) { result = new TreeSet < > ( ) ; result . addAll ( primary ) ; result . addAll ( secondary ) ; } return result ; }
Merge two sets . If secondary set is empty return primary .
15,650
public boolean equalUrl ( ReqUrl url ) { return url . getMethod ( ) . equalsIgnoreCase ( this . method ) && url . getUrl ( ) . equalsIgnoreCase ( this . url ) ; }
Equal url boolean .
15,651
public void replaceValue ( Object bodyObj , Object replaceValue ) { Object parentObj = bodyObj ; if ( this . listChild ) { ValidationData rootListParent = this . findListParent ( ) ; if ( this . deepLevel - rootListParent . deepLevel > 1 ) { parentObj = this . parent . getValue ( bodyObj ) ; } } else { if ( this . parentId != null ) { parentObj = this . parent . getValue ( bodyObj ) ; } } this . setter ( this , parentObj , replaceValue ) ; }
Replace value .
15,652
public ValidationData updateKey ( DetailParam detailParam ) { if ( detailParam == null ) { return this ; } this . methodKey = detailParam . getMethodKey ( ) ; this . parameterKey = this . paramType . getUniqueKey ( this . methodKey ) ; this . urlMapping = detailParam . isUrlMapping ( ) ; return this ; }
Update key validation data .
15,653
public boolean diffKey ( DetailParam detailParam ) { if ( detailParam == null ) { return false ; } if ( ! detailParam . getMethodKey ( ) . equals ( this . methodKey ) ) { return true ; } return detailParam . isUrlMapping ( ) != this . isUrlMapping ( ) ; }
Diff key boolean .
15,654
public void updateField ( Field field ) { this . name = field . getName ( ) ; this . obj = TypeCheckUtil . isObjClass ( field ) ; this . list = TypeCheckUtil . isListClass ( field ) ; this . number = TypeCheckUtil . isNumberClass ( field ) ; this . enumType = field . getType ( ) . isEnum ( ) ; this . typeClass = field . getType ( ) ; this . type = field . getType ( ) . getSimpleName ( ) ; if ( this . list ) { this . innerClass = ValidationObjUtil . getListInnerClassFromGenericType ( field . getGenericType ( ) ) ; this . type += "<" + this . innerClass . getSimpleName ( ) + ">" ; } }
Update field .
15,655
public ValidationData minimalize ( ) { this . setValidationRules ( this . validationRules . stream ( ) . filter ( vr -> vr . isUse ( ) ) . collect ( Collectors . toList ( ) ) ) ; return this ; }
Minimalize validation data .
15,656
public ValidationData ruleSync ( List < ValidationRule > rules ) { List < ValidationRule > ruleList = new ArrayList < > ( ) ; rules . forEach ( rule -> { ValidationRule existRule = this . getExistRule ( rule ) ; ruleList . add ( existRule != null ? existRule : rule ) ; } ) ; this . validationRules . removeAll ( ruleList ) ; this . tempRules . addAll ( this . validationRules ) ; this . validationRules = ruleList ; this . validationRules . sort ( new RuleSorter ( ) ) ; return this ; }
Rule sync validation data .
15,657
public ValidationData findListParent ( ) { if ( ! this . listChild ) { return null ; } ValidationData parent = this . parent ; while ( parent != null && ! parent . isList ( ) ) { parent = parent . parent ; } return parent ; }
Find list parent validation data .
15,658
public RecordList getUniqueRecordsBy ( String fieldName ) { Set < String > uniqueKeys = new HashSet < String > ( ) ; final RecordListBuilder uniqueRecordListBuilder = new RecordListBuilder ( schema ) ; for ( int rowIndex = 0 ; rowIndex < this . size ( ) ; rowIndex ++ ) { final Record currentRecord = this . records . get ( rowIndex ) ; String uniqueKeyField = currentRecord . getValueByFieldName ( fieldName ) ; if ( ! uniqueKeys . contains ( uniqueKeyField ) ) { uniqueRecordListBuilder . add ( currentRecord ) ; } uniqueKeys . add ( uniqueKeyField ) ; } return uniqueRecordListBuilder . createRecordList ( dataSourceHash ) ; }
Picks the first available record by given fieldName
15,659
public static void main ( String [ ] args ) throws IOException { inputpath = "off_output/pcms/test_paget/input" ; outputpath = "off_output/pcms/test_paget/output" ; try { Stream < Path > paths = Files . walk ( Paths . get ( inputpath ) ) ; paths . forEach ( filePath -> { if ( Files . isRegularFile ( filePath ) && filePath . toString ( ) . endsWith ( ".pcm" ) ) { System . out . println ( "> PCM read from " + filePath ) ; PCMContainer pcmC = null ; try { pcmC = JSONtoPCM . JSONFormatToPCM ( JSONReader . importJSON ( filePath . toString ( ) ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } PCMInfoContainerMuted pcmic = null ; try { System . out . println ( pcmic . toString ( ) ) ; pcmic = new PCMInfoContainerMuted ( pcmC ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } if ( pcmic != null ) { if ( pcmic . isSameSizePcm ( ) ) { System . out . println ( "> PCM muted is the same" ) ; } else { pcmC . setPcm ( pcmic . getMutedPcm ( ) . getPcm ( ) ) ; KMFJSONExporter pcmExporter = new KMFJSONExporter ( ) ; String pcmString = pcmExporter . export ( pcmC ) ; Path p = Paths . get ( outputpath + "muted_" ) ; try { Files . write ( p , pcmString . getBytes ( ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } System . out . println ( "> PCM exported to " + p ) ; } } else { System . out . println ( "> PCM corrompu" ) ; } } } ) ; paths . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
give path with argv
15,660
public void writeFile ( String fn , HttpServletResponse res ) { ValidationFileUtil . initFileSendHeader ( res , ValidationFileUtil . getEncodingFileName ( fn + ".xls" ) , null ) ; try { this . workBook . write ( res . getOutputStream ( ) ) ; } catch ( IOException e ) { throw new ValidationLibException ( "workbook write error : " + e . getMessage ( ) , HttpStatus . INTERNAL_SERVER_ERROR , e ) ; } }
Write file .
15,661
public void onSelectFilter ( SelectFilterEvent selectFilterEvent ) { for ( FacetWidget facetWidget : filterList ) { if ( facetWidget . getFacetField ( ) . equals ( selectFilterEvent . getFilterName ( ) ) ) { for ( FacetWidgetItem facetWidgetItem : facetWidget . getFacetWidgetItems ( ) ) { if ( facetWidgetItem . getValue ( ) . equals ( selectFilterEvent . getFilterValue ( ) ) ) { facetWidget . selectItems ( Arrays . asList ( facetWidgetItem ) ) ; } } } } }
When a SelectFilterEvent is triggered this method will look for the filter and value and will select it .
15,662
public < T > GenericMarker < T > createMarker ( T markerContext , GenericMapWidget mapWidget ) { this . map = mapWidget ; validateRequiredParameters ( ) ; if ( map instanceof GoogleV3MapWidget ) { return new GoogleV3Marker < T > ( this , markerContext ) ; } if ( map instanceof OfflineMapWidget ) { return new OfflineMapMarker < T > ( this , markerContext ) ; } throw new UnsupportedOperationException ( ) ; }
Final build method of the builder called once all parameters are setup for the Generic Marker
15,663
public static Resource getResource ( Object adaptable ) { if ( adaptable instanceof Resource ) { return ( Resource ) adaptable ; } else if ( adaptable instanceof SlingHttpServletRequest ) { SlingHttpServletRequest request = ( SlingHttpServletRequest ) adaptable ; return request . getResource ( ) ; } return null ; }
Tries to get the resource associated with the adaptable .
15,664
public void readState ( DataInputStream stream ) throws IOException { int len = mt . length ; for ( int x = 0 ; x < len ; x ++ ) mt [ x ] = stream . readInt ( ) ; len = mag01 . length ; for ( int x = 0 ; x < len ; x ++ ) mag01 [ x ] = stream . readInt ( ) ; mti = stream . readInt ( ) ; __nextNextGaussian = stream . readDouble ( ) ; __haveNextNextGaussian = stream . readBoolean ( ) ; }
Reads the entire state of the MersenneTwister RNG from the stream
15,665
public void writeState ( DataOutputStream stream ) throws IOException { int len = mt . length ; for ( int x = 0 ; x < len ; x ++ ) stream . writeInt ( mt [ x ] ) ; len = mag01 . length ; for ( int x = 0 ; x < len ; x ++ ) stream . writeInt ( mag01 [ x ] ) ; stream . writeInt ( mti ) ; stream . writeDouble ( __nextNextGaussian ) ; stream . writeBoolean ( __haveNextNextGaussian ) ; }
Writes the entire state of the MersenneTwister RNG to the stream
15,666
synchronized public void setSeed ( final int [ ] array ) { if ( array . length == 0 ) throw new IllegalArgumentException ( "Array length must be greater than zero" ) ; int i , j , k ; setSeed ( 19650218 ) ; i = 1 ; j = 0 ; k = ( N > array . length ? N : array . length ) ; for ( ; k != 0 ; k -- ) { mt [ i ] = ( mt [ i ] ^ ( ( mt [ i - 1 ] ^ ( mt [ i - 1 ] >>> 30 ) ) * 1664525 ) ) + array [ j ] + j ; mt [ i ] &= 0xffffffff ; i ++ ; j ++ ; if ( i >= N ) { mt [ 0 ] = mt [ N - 1 ] ; i = 1 ; } if ( j >= array . length ) j = 0 ; } for ( k = N - 1 ; k != 0 ; k -- ) { mt [ i ] = ( mt [ i ] ^ ( ( mt [ i - 1 ] ^ ( mt [ i - 1 ] >>> 30 ) ) * 1566083941 ) ) - i ; mt [ i ] &= 0xffffffff ; i ++ ; if ( i >= N ) { mt [ 0 ] = mt [ N - 1 ] ; i = 1 ; } } mt [ 0 ] = 0x80000000 ; }
Sets the seed of the MersenneTwister using an array of integers . Your array must have a non - zero length . Only the first 624 integers in the array are used ; if the array is shorter than this then integers are repeatedly used in a wrap - around fashion .
15,667
public void lire ( ) { try { String adressedufichier = System . getProperty ( "user.dir" ) + "\\monfichier.txt" ; FileReader fr = new FileReader ( adressedufichier ) ; BufferedReader br = new BufferedReader ( fr ) ; String texte = "" ; int a = 0 ; while ( a < 2 ) { texte = texte + br . readLine ( ) + "\n" ; a ++ ; } br . close ( ) ; System . out . println ( texte ) ; } catch ( IOException ioe ) { System . out . println ( "erreur : " + ioe ) ; } }
je vais moins commenter cette partie c est presque la meme chose
15,668
public < T > T deserialize ( Class < T > clazz , String stringContainingSerialisedInput ) { T instance ; try { instance = storageSerializer . deserialize ( clazz , stringContainingSerialisedInput ) ; } catch ( SerializationException e ) { throw new IllegalStateException ( "unable to serialise" , e ) ; } return instance ; }
Returns an object from a serialised string
15,669
private BitSet parseQuery ( FilterQuery filterQuery , DataSchema schema ) { BitSet queryBitSet = new BitSet ( ) ; if ( filterQuery instanceof MatchAllQuery || filterQuery . getFilterQueries ( ) . size ( ) < 1 ) return queryBitSet ; for ( String filterField : filterQuery . getFilterQueries ( ) . keySet ( ) ) { final int columnIndex = schema . getColumnIndex ( filterField ) ; final Map < String , BitSet > map = fieldInvertedIndex . get ( columnIndex ) ; final FilterQuery . FilterQueryElement filterQueryElement = filterQuery . getFilterQueries ( ) . get ( filterField ) ; DataType type = schema . getType ( columnIndex ) ; switch ( type ) { case CoordinateLat : case CoordinateLon : case String : case Boolean : case Integer : if ( filterQueryElement instanceof FilterQuery . FilterFieldRange ) { queryBitSet = processRangeQueryIntegerTypes ( queryBitSet , map , filterQueryElement , type ) ; } else if ( filterQueryElement instanceof FilterQuery . FilterFieldGreaterThanInteger ) { queryBitSet = processIntegerGreaterThanDefaultTypes ( queryBitSet , map , filterQueryElement , type ) ; } else { queryBitSet = processMultiValueQueryDefaultTypes ( queryBitSet , map , filterQueryElement , type ) ; } break ; case Date : if ( filterQueryElement instanceof FilterQuery . FilterFieldRangeDate ) { queryBitSet = processRangeQueryISODateTypes ( queryBitSet , map , filterQueryElement , type ) ; } else { queryBitSet = processRangeQueryMultiValueQueryDateYear ( queryBitSet , map , filterQueryElement , type ) ; } break ; case DateYear : if ( filterQueryElement instanceof FilterQuery . FilterFieldRange ) { queryBitSet = processRangeQueryDateYearType ( queryBitSet , map , filterQueryElement , type ) ; } else { queryBitSet = processRangeQueryMultiValueQueryDateYear ( queryBitSet , map , filterQueryElement , type ) ; } break ; } } return queryBitSet ; }
Calculates which documents are available given the current FilterQuery selection
15,670
public ResultMetadata [ ] getResultMetadata ( ) throws LightblueParseException { JsonNode node = getJson ( ) . get ( "resultMetadata" ) ; if ( node instanceof ArrayNode ) { try { return getMapper ( ) . readValue ( node . traverse ( ) , ResultMetadata [ ] . class ) ; } catch ( IOException e ) { throw new LightblueParseException ( "Error parsing lightblue response:" + getText ( ) + "\n" , e ) ; } } else { return null ; } }
Returns a result metadata array where each element corresponds to the metadata for the result at the same index in processed array .
15,671
private Map < Feature , Feature > diffFeatures ( List < Feature > pcm1Features , List < Feature > pcm2Features , PCMElementComparator comparator , DiffResult result ) { List < Feature > commonFeatures = new ArrayList < Feature > ( ) ; List < Feature > featuresOnlyInPCM1 = new ArrayList < Feature > ( ) ; List < Feature > featuresOnlyInPCM2 = new ArrayList < Feature > ( pcm2Features ) ; Map < Feature , Feature > equivalentFeatures = new HashMap < Feature , Feature > ( ) ; for ( Feature f1 : pcm1Features ) { boolean similarFeature = false ; for ( Feature f2 : pcm2Features ) { similarFeature = comparator . similarFeature ( f1 , f2 ) ; if ( similarFeature ) { commonFeatures . add ( f1 ) ; featuresOnlyInPCM2 . remove ( f2 ) ; equivalentFeatures . put ( f1 , f2 ) ; break ; } } if ( ! similarFeature ) { featuresOnlyInPCM1 . add ( f1 ) ; } } result . setCommonFeatures ( commonFeatures ) ; result . setFeaturesOnlyInPCM1 ( featuresOnlyInPCM1 ) ; result . setFeaturesOnlyInPCM2 ( featuresOnlyInPCM2 ) ; return equivalentFeatures ; }
Compare the features of two PCMs
15,672
private Map < Product , Product > diffProducts ( List < Product > pcm1Products , List < Product > pcm2Products , PCMElementComparator comparator , DiffResult result ) { List < Product > commonProducts = new ArrayList < Product > ( ) ; List < Product > productsOnlyInPCM1 = new ArrayList < Product > ( ) ; List < Product > productsOnlyInPCM2 = new ArrayList < Product > ( pcm2Products ) ; Map < Product , Product > equivalentProducts = new HashMap < Product , Product > ( ) ; for ( Product p1 : pcm1Products ) { boolean similarProduct = false ; for ( Product p2 : pcm2Products ) { similarProduct = comparator . similarProduct ( p1 , p2 ) ; if ( similarProduct ) { commonProducts . add ( p1 ) ; productsOnlyInPCM2 . remove ( p2 ) ; equivalentProducts . put ( p1 , p2 ) ; break ; } } if ( ! similarProduct ) { productsOnlyInPCM1 . add ( p1 ) ; } } result . setCommonProducts ( commonProducts ) ; result . setProductsOnlyInPCM1 ( productsOnlyInPCM1 ) ; result . setProductsOnlyInPCM2 ( productsOnlyInPCM2 ) ; return equivalentProducts ; }
Compare the products of two PCMs
15,673
public static Object toPersistenceType ( Object value , Class < ? > parameterType ) { if ( ! isTypeConversionRequired ( parameterType ) ) { return value ; } if ( Map . class . isAssignableFrom ( parameterType ) && ( value instanceof Map ) ) { Map < ? , ? > map = ( Map < ? , ? > ) value ; Map . Entry < ? , ? > [ ] entries = Iterators . toArray ( map . entrySet ( ) . iterator ( ) , Map . Entry . class ) ; String [ ] stringArray = new String [ entries . length ] ; for ( int i = 0 ; i < entries . length ; i ++ ) { Map . Entry < ? , ? > entry = entries [ i ] ; String entryKey = Objects . toString ( entry . getKey ( ) , "" ) ; String entryValue = Objects . toString ( entry . getValue ( ) , "" ) ; stringArray [ i ] = ConversionStringUtils . encodeString ( entryKey ) + KEY_VALUE_DELIMITER + ConversionStringUtils . encodeString ( entryValue ) ; } return stringArray ; } throw new IllegalArgumentException ( "Type conversion not supported: " + parameterType . getName ( ) ) ; }
Convert object to be persisted .
15,674
public static Object fromPersistenceType ( Object value , Class < ? > parameterType ) { if ( ! isTypeConversionRequired ( parameterType ) ) { return value ; } if ( Map . class . isAssignableFrom ( parameterType ) && ( value instanceof String [ ] ) ) { String [ ] rows = ( String [ ] ) value ; Map < String , String > map = new LinkedHashMap < > ( ) ; for ( int i = 0 ; i < rows . length ; i ++ ) { String [ ] keyValue = ConversionStringUtils . splitPreserveAllTokens ( rows [ i ] , KEY_VALUE_DELIMITER . charAt ( 0 ) ) ; if ( keyValue . length == 2 && StringUtils . isNotEmpty ( keyValue [ 0 ] ) ) { String entryKey = keyValue [ 0 ] ; String entryValue = StringUtils . isEmpty ( keyValue [ 1 ] ) ? null : keyValue [ 1 ] ; map . put ( ConversionStringUtils . decodeString ( entryKey ) , ConversionStringUtils . decodeString ( entryValue ) ) ; } } return map ; } throw new IllegalArgumentException ( "Type conversion not supported: " + parameterType . getName ( ) ) ; }
Convert object from persistence to be used in configuration .
15,675
public void addFilter ( String field , String valueToFilter ) { if ( StringUtils . isEmpty ( field ) || StringUtils . isEmpty ( valueToFilter ) ) { throw new IllegalArgumentException ( "Expected all attributes to be non empty" ) ; } Set < String > valuesToFilter = new HashSet < String > ( ) ; valuesToFilter . add ( valueToFilter ) ; filterQueries . put ( field , new FilterFieldValue ( field , valuesToFilter ) ) ; }
add a filter to the to build FilterQuery instance
15,676
public void addMultipleValuesFilter ( String field , Set < String > valueToFilter ) { if ( ! valueToFilter . isEmpty ( ) ) { filterQueries . put ( field , new FilterFieldValue ( field , valueToFilter ) ) ; } }
add a filter with multiple values to build FilterQuery instance
15,677
public long nextLong ( final long n ) { if ( n <= 0 ) throw new IllegalArgumentException ( "n must be > 0" ) ; long bits , val ; do { bits = ( nextLong ( ) >>> 1 ) ; val = bits % n ; } while ( bits - val + ( n - 1 ) < 0 ) ; return val ; }
This method is for completness sake . Returns a long drawn uniformly from 0 to n - 1 . Suffice it to say n must be > 0 or an IllegalArgumentException is raised .
15,678
public void addDocument ( String ... fields ) { for ( int i = 0 ; i < fields . length ; i ++ ) { final DataType type = schema . getType ( i ) ; String field = fields [ i ] ; final Map < String , Set < Integer > > stringSetMap = this . fields . get ( i ) ; if ( type == DataType . DateYear ) { field = field . split ( "-" ) [ 0 ] ; } Set < Integer > integers = stringSetMap . get ( field ) ; if ( integers == null ) { integers = new TreeSet < > ( ) ; } integers . add ( docPosition ) ; stringSetMap . put ( field , integers ) ; } docPosition ++ ; }
add fields on index
15,679
public void print ( PCM pcm ) { System . out . println ( "--- Products ---" ) ; for ( Product product : pcm . getProducts ( ) ) { System . out . println ( product . getKeyContent ( ) ) ; } pcm . accept ( this ) ; }
Print some information contained in a PCM
15,680
public void visit ( PCM pcm ) { for ( Product product : pcm . getProducts ( ) ) { product . accept ( this ) ; } }
Methods for the visitor
15,681
public String getSheetName ( int idx ) { String name = method + "|" + url . replace ( "/" , "|" ) ; if ( name . length ( ) > 30 ) { return name . substring ( 0 , 29 ) + idx ; } return name ; }
Gets sheet name .
15,682
private void setupIndexMonitor ( final DataSchema dataSchema , final GenericDataSource dataSource ) { logger . log ( FINE , "LuceneSearchServiceImpl::setupIndexMonitor Attempting to setup Index monitor..." ) ; try { if ( GoogleAppEngineUtil . isGaeEnv ( ) ) { return ; } if ( dataSource . getDataSourceType ( ) != GenericDataSource . DataSourceType . ServletRelativeDataSource || dataSource . getLocation ( ) == null ) { return ; } else { } fileChangeMonitor = FileChangeMonitor . getInstance ( ) ; fileChangeMonitor . addObserver ( new Observer ( ) { public void update ( Observable o , Object arg ) { JSONWithMetaData jsonContent ; try { logger . log ( FINE , "LuceneSearchServiceImpl::setupIndexMonitor" , "Index monitor change noted." ) ; jsonContent = getJsonArrayFrom ( dataSource ) ; } catch ( SearchException e ) { throw new IllegalStateException ( e ) ; } setupIndex ( dataSource , dataSchema , jsonContent ) ; } } ) ; } catch ( Exception e ) { logger . log ( SEVERE , "LuceneSearchServiceImpl::setupIndexMonitor Failed to setup monitor for indexed file changes" , e ) ; } }
setup a monitor to watch for changes in datasource
15,683
public static List < ReqUrl > getUrlListFromValidationDatas ( List < ValidationData > datas ) { Map < String , ReqUrl > urlMap = new HashMap < > ( ) ; datas . stream ( ) . forEach ( data -> { ReqUrl url = new ReqUrl ( data ) ; urlMap . put ( url . getUniqueKey ( ) , url ) ; } ) ; return urlMap . entrySet ( ) . stream ( ) . map ( entry -> entry . getValue ( ) ) . collect ( Collectors . toList ( ) ) ; }
Gets url list from validation datas .
15,684
private void appendLiteral ( int word ) { if ( lastWordIndex == 0 && word == ConciseSetUtils . ALL_ZEROS_LITERAL && words [ 0 ] == 0x01FFFFFF ) { return ; } if ( lastWordIndex < 0 ) { words [ lastWordIndex = 0 ] = word ; return ; } final int lastWord = words [ lastWordIndex ] ; if ( word == ConciseSetUtils . ALL_ZEROS_LITERAL ) { if ( lastWord == ConciseSetUtils . ALL_ZEROS_LITERAL ) { words [ lastWordIndex ] = 1 ; } else if ( isZeroSequence ( lastWord ) ) { words [ lastWordIndex ] ++ ; } else if ( ! simulateWAH && containsOnlyOneBit ( getLiteralBits ( lastWord ) ) ) { words [ lastWordIndex ] = 1 | ( ( 1 + Integer . numberOfTrailingZeros ( lastWord ) ) << 25 ) ; } else { words [ ++ lastWordIndex ] = word ; } } else if ( word == ConciseSetUtils . ALL_ONES_LITERAL ) { if ( lastWord == ConciseSetUtils . ALL_ONES_LITERAL ) { words [ lastWordIndex ] = ConciseSetUtils . SEQUENCE_BIT | 1 ; } else if ( isOneSequence ( lastWord ) ) { words [ lastWordIndex ] ++ ; } else if ( ! simulateWAH && containsOnlyOneBit ( ~ lastWord ) ) { words [ lastWordIndex ] = ConciseSetUtils . SEQUENCE_BIT | 1 | ( ( 1 + Integer . numberOfTrailingZeros ( ~ lastWord ) ) << 25 ) ; } else { words [ ++ lastWordIndex ] = word ; } } else { words [ ++ lastWordIndex ] = word ; } }
Append a literal word after the last word
15,685
public static void addIndexData ( ValidationData data , ValidationDataIndex index ) { String key = index . getKey ( data ) ; List < ValidationData > datas = index . get ( key ) ; if ( datas == null ) { datas = new ArrayList < > ( ) ; } datas . add ( data ) ; index . getMap ( ) . put ( key , datas ) ; }
Add index data .
15,686
public static void removeIndexData ( ValidationData data , ValidationDataIndex index ) { String key = index . getKey ( data ) ; List < ValidationData > datas = index . get ( key ) ; if ( ! datas . isEmpty ( ) ) { datas = datas . stream ( ) . filter ( d -> ! d . getId ( ) . equals ( data . getId ( ) ) ) . collect ( Collectors . toList ( ) ) ; } if ( datas . isEmpty ( ) ) { index . getMap ( ) . remove ( key ) ; } else { index . getMap ( ) . put ( key , datas ) ; } }
Remove index data .
15,687
public static String makeKey ( String ... keys ) { StringBuffer keyBuffer = new StringBuffer ( ) ; for ( String s : keys ) { keyBuffer . append ( s ) ; keyBuffer . append ( ":" ) ; } return keyBuffer . toString ( ) ; }
Make key string .
15,688
public static Method findMethod ( Class < ? > c , String methodName ) { for ( Method m : c . getMethods ( ) ) { if ( ! m . getName ( ) . equalsIgnoreCase ( methodName ) ) { continue ; } if ( m . getParameterCount ( ) != 1 ) { continue ; } return m ; } return null ; }
Find method method .
15,689
@ SuppressWarnings ( "PMD.LooseCoupling" ) public static Object castValue ( Method m , Class < ? > castType , String value ) { try { if ( castType . isEnum ( ) ) { Method valueOf ; try { valueOf = castType . getMethod ( "valueOf" , String . class ) ; return valueOf . invoke ( null , value ) ; } catch ( Exception e ) { log . info ( "enum value of excute error : (" + castType . getName ( ) + ") | " + value ) ; return null ; } } else if ( castType == Integer . class || castType == int . class ) { return Integer . parseInt ( value ) ; } else if ( castType == Long . class || castType == long . class ) { return Long . parseLong ( value ) ; } else if ( castType == Double . class || castType == double . class ) { return Double . parseDouble ( value ) ; } else if ( castType == Boolean . class || castType == boolean . class ) { return Boolean . parseBoolean ( value ) ; } else if ( castType == Float . class || castType == float . class ) { return Float . parseFloat ( value ) ; } else if ( castType == String . class ) { return value ; } else if ( castType == ArrayList . class || castType == List . class ) { ParameterizedType paramType = ( ParameterizedType ) m . getGenericParameterTypes ( ) [ 0 ] ; Class < ? > paramClass = ( Class < ? > ) paramType . getActualTypeArguments ( ) [ 0 ] ; List < Object > castList = new ArrayList < > ( ) ; String [ ] values = value . split ( "," ) ; for ( String v : values ) { castList . add ( castValue ( m , paramClass , v ) ) ; } return castList ; } else { log . info ( "invalid castType : " + castType ) ; return null ; } } catch ( NumberFormatException e ) { log . info ( "value : " + value + " is invalid value, setter parameter type is : " + castType ) ; return null ; } }
Cast value object .
15,690
public static Object mapToObject ( Map < String , String > map , Class < ? > c ) { Method m = null ; Object obj = null ; try { obj = c . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { log . info ( "instance create fail : " + c . getName ( ) ) ; return null ; } for ( Map . Entry < String , String > entry : map . entrySet ( ) ) { if ( entry . getValue ( ) == null || entry . getValue ( ) . trim ( ) . isEmpty ( ) ) { continue ; } if ( entry . getValue ( ) . equalsIgnoreCase ( "undefined" ) ) { continue ; } try { m = findMethod ( c , getSetMethodName ( entry . getKey ( ) ) ) ; if ( m == null ) { log . info ( "not found mapping method : " + entry . getKey ( ) ) ; continue ; } try { m . invoke ( obj , castValue ( m , m . getParameterTypes ( ) [ 0 ] , entry . getValue ( ) ) ) ; } catch ( IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { log . info ( "method invoke error : " + m . getName ( ) ) ; } } catch ( SecurityException e ) { log . info ( "security exception : " + e . getMessage ( ) ) ; } } return obj ; }
Map to object object .
15,691
public List < ValidationData > findByIds ( List < Long > ids ) { return this . datas . stream ( ) . filter ( d -> ids . contains ( d . getId ( ) ) ) . collect ( Collectors . toList ( ) ) ; }
Find by ids list .
15,692
public List < ValidationData > findAll ( boolean referenceCache ) { if ( referenceCache && this . datas != null ) { return this . datas ; } List < ValidationData > list = null ; File repositroyFile = new File ( this . validationConfig . getRepositoryPath ( ) ) ; try { String jsonStr = ValidationFileUtil . readFileToString ( repositroyFile , Charset . forName ( "UTF-8" ) ) ; list = objectMapper . readValue ( jsonStr , objectMapper . getTypeFactory ( ) . constructCollectionType ( List . class , ValidationData . class ) ) ; } catch ( IOException e ) { log . error ( "repository json file read error : " + repositroyFile . getAbsolutePath ( ) ) ; list = new ArrayList < > ( ) ; } this . parentObjInit ( list ) ; if ( referenceCache ) { this . datas = list ; } return list ; }
Find all list .
15,693
public List < ValidationData > findByParamTypeAndMethodAndUrl ( ParamType paramType , String method , String url ) { return this . findByMethodAndUrl ( method , url ) . stream ( ) . filter ( d -> d . getParamType ( ) . equals ( paramType ) ) . collect ( Collectors . toList ( ) ) ; }
Find by param type and method and url list .
15,694
public List < ValidationData > findByParamTypeAndMethodAndUrlAndName ( ParamType paramType , String method , String url , String name ) { return this . findByMethodAndUrlAndName ( method , url , name ) . stream ( ) . filter ( vd -> vd . getParamType ( ) . equals ( paramType ) ) . collect ( Collectors . toList ( ) ) ; }
Find by param type and method and url and name list .
15,695
public ValidationData findByParamTypeAndMethodAndUrlAndNameAndParentId ( ParamType paramType , String method , String url , String name , Long parentId ) { if ( parentId == null ) { return this . findByParamTypeAndMethodAndUrlAndName ( paramType , method , url , name ) . stream ( ) . filter ( d -> d . getParentId ( ) == null ) . findAny ( ) . orElse ( null ) ; } return this . findByParamTypeAndMethodAndUrlAndName ( paramType , method , url , name ) . stream ( ) . filter ( d -> d . getParentId ( ) != null && d . getParentId ( ) . equals ( parentId ) ) . findAny ( ) . orElse ( null ) ; }
Find by param type and method and url and name and parent id validation data .
15,696
public List < ValidationData > findByMethodAndUrlAndName ( String method , String url , String name ) { return this . findByMethodAndUrl ( method , url ) . stream ( ) . filter ( d -> d . getName ( ) . equalsIgnoreCase ( name ) ) . collect ( Collectors . toList ( ) ) ; }
Find by method and url and name list .
15,697
public List < ValidationData > findByParentId ( Long id ) { return this . datas . stream ( ) . filter ( d -> d . getParentId ( ) != null && d . getParentId ( ) . equals ( id ) ) . collect ( Collectors . toList ( ) ) ; }
Find by parent id list .
15,698
public ValidationData findByMethodAndUrlAndNameAndParentId ( String method , String url , String name , Long parentId ) { if ( parentId == null ) { return this . findByMethodAndUrlAndName ( method , url , name ) . stream ( ) . filter ( d -> d . getParentId ( ) == null ) . findAny ( ) . orElse ( null ) ; } return this . findByMethodAndUrlAndName ( method , url , name ) . stream ( ) . filter ( d -> d . getParentId ( ) != null && d . getParentId ( ) . equals ( parentId ) ) . findAny ( ) . orElse ( null ) ; }
Find by method and url and name and parent id validation data .
15,699
public List < ValidationData > saveAll ( List < ValidationData > pDatas ) { pDatas . forEach ( this :: save ) ; return pDatas ; }
Save all list .