idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
24,300 | private Style getStyle ( ) { SharedPreferences sharedPreferences = PreferenceManager . getDefaultSharedPreferences ( getActivity ( ) ) ; String key = getString ( R . string . bottom_sheet_style_preference_key ) ; String defaultValue = getString ( R . string . bottom_sheet_style_preference_default_value ) ; String style = sharedPreferences . getString ( key , defaultValue ) ; switch ( style ) { case "list" : return Style . LIST ; case "list_columns" : return Style . LIST_COLUMNS ; default : return Style . GRID ; } } | Returns the style which should be used to create bottom sheets depending on the app s settings . |
24,301 | private boolean shouldTitleBeShown ( ) { SharedPreferences sharedPreferences = PreferenceManager . getDefaultSharedPreferences ( getActivity ( ) ) ; String key = getString ( R . string . show_bottom_sheet_title_preference_key ) ; boolean defaultValue = getResources ( ) . getBoolean ( R . bool . show_bottom_sheet_title_preference_default_value ) ; return sharedPreferences . getBoolean ( key , defaultValue ) ; } | Returns whether the title of bottom sheets should be shown depending on the app s settings or not . |
24,302 | private String getBottomSheetTitle ( ) { SharedPreferences sharedPreferences = PreferenceManager . getDefaultSharedPreferences ( getActivity ( ) ) ; String key = getString ( R . string . bottom_sheet_title_preference_key ) ; String defaultValue = getString ( R . string . bottom_sheet_title_preference_default_value ) ; return sharedPreferences . getString ( key , defaultValue ) ; } | Returns the title of bottom sheets depending on the app s settings . |
24,303 | private boolean shouldIconBeShown ( ) { SharedPreferences sharedPreferences = PreferenceManager . getDefaultSharedPreferences ( getActivity ( ) ) ; String key = getString ( R . string . show_bottom_sheet_icon_preference_key ) ; boolean defaultValue = getResources ( ) . getBoolean ( R . bool . show_bottom_sheet_icon_preference_default_value ) ; return sharedPreferences . getBoolean ( key , defaultValue ) ; } | Returns whether the icon of bottom sheets should be shown depending on the app s settings or not . |
24,304 | private int getDividerCount ( ) { SharedPreferences sharedPreferences = PreferenceManager . getDefaultSharedPreferences ( getActivity ( ) ) ; String key = getString ( R . string . divider_count_preference_key ) ; String defaultValue = getString ( R . string . divider_count_preference_default_value ) ; return Integer . valueOf ( sharedPreferences . getString ( key , defaultValue ) ) ; } | Returns the number of dividers which should be shown depending on the app s settings . |
24,305 | private boolean shouldDividerTitleBeShown ( ) { SharedPreferences sharedPreferences = PreferenceManager . getDefaultSharedPreferences ( getActivity ( ) ) ; String key = getString ( R . string . show_divider_title_preference_key ) ; boolean defaultValue = getResources ( ) . getBoolean ( R . bool . show_divider_title_preference_default_value ) ; return sharedPreferences . getBoolean ( key , defaultValue ) ; } | Returns whether the title of dividers should be shown depending on the app s settings or not . |
24,306 | private int getItemCount ( ) { SharedPreferences sharedPreferences = PreferenceManager . getDefaultSharedPreferences ( getActivity ( ) ) ; String key = getString ( R . string . item_count_preference_key ) ; String defaultValue = getString ( R . string . item_count_preference_default_value ) ; return Integer . valueOf ( sharedPreferences . getString ( key , defaultValue ) ) ; } | Returns the number of items which should be shown per divider depending on the app s settings . |
24,307 | private boolean shouldItemIconsBeShown ( ) { SharedPreferences sharedPreferences = PreferenceManager . getDefaultSharedPreferences ( getActivity ( ) ) ; String key = getString ( R . string . show_item_icons_preference_key ) ; boolean defaultValue = getResources ( ) . getBoolean ( R . bool . show_item_icons_preference_default_value ) ; return sharedPreferences . getBoolean ( key , defaultValue ) ; } | Returns whether icons should be shown next to items depending on the app s settings or not . |
24,308 | private boolean shouldItemsBeDisabled ( ) { SharedPreferences sharedPreferences = PreferenceManager . getDefaultSharedPreferences ( getActivity ( ) ) ; String key = getString ( R . string . disable_items_preference_key ) ; boolean defaultValue = getResources ( ) . getBoolean ( R . bool . disable_items_preference_default_value ) ; return sharedPreferences . getBoolean ( key , defaultValue ) ; } | Returns whether items should be disabled depending on the app s settings or not . |
24,309 | private boolean isDarkThemeSet ( ) { SharedPreferences sharedPreferences = PreferenceManager . getDefaultSharedPreferences ( getActivity ( ) ) ; String key = getString ( R . string . theme_preference_key ) ; String defaultValue = getString ( R . string . theme_preference_default_value ) ; return Integer . valueOf ( sharedPreferences . getString ( key , defaultValue ) ) != 0 ; } | Returns whether the app uses the dark theme or not . |
24,310 | public Map < String , String > detectVariableValues ( TokenList tokenList ) { Map < String , String > variables = new HashMap < String , String > ( ) ; boolean thisContainsVariables = containsVariables ( ) ; boolean thatContainsVariables = tokenList . containsVariables ( ) ; if ( thisContainsVariables && thatContainsVariables ) { throw new VariableValueDetectionException ( "Cannot detect variable values if both token lists contain variables." ) ; } if ( ! thisContainsVariables && ! thatContainsVariables ) { return variables ; } ListIterator < Token > iteratorWithVariables = ( thisContainsVariables ? this : tokenList ) . listIterator ( ) ; ListIterator < Token > iteratorWithoutVariables = ( thisContainsVariables ? tokenList : this ) . listIterator ( ) ; while ( iteratorWithVariables . hasNext ( ) && iteratorWithoutVariables . hasNext ( ) ) { Token possibleVariableToken = iteratorWithVariables . next ( ) ; Token literalToken = iteratorWithoutVariables . next ( ) ; if ( possibleVariableToken instanceof VariableToken ) { variables . put ( possibleVariableToken . getText ( ) , literalToken . getText ( ) ) ; } } return variables ; } | Detects variable values using another token list . |
24,311 | private boolean tokenTypesMatch ( Token token1 , Token token2 , Class < ? extends Token > tokenType ) { return tokenType . isAssignableFrom ( token1 . getClass ( ) ) && tokenType . isAssignableFrom ( token2 . getClass ( ) ) ; } | Checks whether both tokens have the specified type . |
24,312 | private boolean tokenTextsDoNotMatch ( Token token1 , Token token2 ) { return ! token1 . getText ( ) . equals ( token2 . getText ( ) ) ; } | Checks whether both tokens have the same texts . |
24,313 | @ SuppressWarnings ( "WeakerAccess" ) public static void setStatementResolver ( StatementResolver statementResolver ) { if ( statementResolver == null ) { throw new NullPointerException ( "The statement resolver must not be null." ) ; } StatementResolverHolder . STATEMENT_RESOLVER . set ( statementResolver ) ; } | Sets the statement resolver for the current thread . |
24,314 | public static WebElement findElementOrFail ( WebDriver webDriver , By element ) { try { return webDriver . findElement ( element ) ; } catch ( NoSuchElementException e ) { fail ( String . format ( "Element %s should exist but it does not." , element . toString ( ) ) , e ) ; } return null ; } | Tries to find a specific element and fails if the element could not be found . |
24,315 | public void go ( ) { logger . info ( "Typing \"{}\"..." , ( Object ) keys ) ; new Actions ( getWebDriver ( ) ) . sendKeys ( Keys . ENTER ) ; } | Types the keys . |
24,316 | protected void failOnInvalidContext ( ExecutionContext executionContext ) { for ( Fact fact : executionContext . getFacts ( ) ) { failOnInvalidFact ( fact ) ; } for ( Step step : executionContext . getSteps ( ) ) { failOnInvalidStep ( step ) ; } for ( Result result : executionContext . getResults ( ) ) { failOnInvalidResult ( result ) ; } } | This method validates the execution context . |
24,317 | public void expect ( ) { try { webResult . setWebDriver ( getWebDriver ( ) ) ; webResult . expect ( ) ; fail ( "Result should fail but it did not." ) ; } catch ( Exception e ) { logger . debug ( "Negated failure:" , e ) ; } catch ( AssertionError e ) { logger . debug ( "Negated failure:" , e ) ; } } | Expects that the specified web result fails . |
24,318 | private void findTokens ( ) { mergedTokens = new TokenList ( ) ; variable = null ; state = TokenizerState . START ; index = - 1 ; while ( index < rawTokens . length ) { switch ( state ) { case START : next ( TokenizerState . OUTSIDE_VARIABLE_CONTEXT ) ; break ; case OUTSIDE_VARIABLE_CONTEXT : handleTokenOutsideOfVariableContext ( ) ; break ; case INSIDE_VARIABLE_CONTEXT : handleTokenInsideOfVariableContext ( ) ; break ; default : break ; } } } | Finds tokens within the split statement name . |
24,319 | public void go ( ) { logger . info ( "Waiting {} seconds..." , sleepTime ) ; try { Thread . sleep ( sleepTime ) ; } catch ( InterruptedException e ) { throw new ExecutionException ( "Thread could not sleep." , e ) ; } } | Waits for the specified sleep time . |
24,320 | public void go ( ) { logger . info ( "Typing \"{}\" into {}..." , keys , element ) ; findElementOrFail ( getWebDriver ( ) , element ) . sendKeys ( keys ) ; } | Types into the element . |
24,321 | public void go ( ) { logger . info ( "Waiting {} seconds for {}..." , timeout , element ) ; WebDriverWait waiting = new WebDriverWait ( getWebDriver ( ) , timeout ) ; try { waiting . until ( ExpectedConditions . presenceOfElementLocated ( element ) ) ; } catch ( NullPointerException e ) { fail ( String . format ( "Element %s did not appear within %d seconds." , element , timeout ) , e ) ; } } | Waits for the element . |
24,322 | public void expect ( ) { assertTrue ( String . format ( "Page should contain \"%s\" but it does not." , text ) , getWebDriver ( ) . getPageSource ( ) . contains ( text ) ) ; } | Expects that the specified text is present . |
24,323 | public SelectStep value ( String value ) { return new SelectStep ( element , value , SelectStep . OptionSelectorType . VALUE ) ; } | Selects an option by its value . |
24,324 | public SelectStep text ( String text ) { return new SelectStep ( element , text , SelectStep . OptionSelectorType . TEXT ) ; } | Selects an option by its text . |
24,325 | @ SuppressWarnings ( { "resource" } ) @ RequestMapping ( value = { "/api.js" , "/api-debug.js" , "/api-debug-doc.js" } , method = RequestMethod . GET ) public void api ( @ RequestParam ( value = "apiNs" , required = false ) String apiNs , @ RequestParam ( value = "actionNs" , required = false ) String actionNs , @ RequestParam ( value = "remotingApiVar" , required = false ) String remotingApiVar , @ RequestParam ( value = "pollingUrlsVar" , required = false ) String pollingUrlsVar , @ RequestParam ( value = "group" , required = false ) String group , @ RequestParam ( value = "fullRouterUrl" , required = false ) Boolean fullRouterUrl , @ RequestParam ( value = "format" , required = false ) String format , @ RequestParam ( value = "baseRouterUrl" , required = false ) String baseRouterUrl , HttpServletRequest request , HttpServletResponse response ) throws IOException { if ( format == null ) { response . setContentType ( this . configurationService . getConfiguration ( ) . getJsContentType ( ) ) ; response . setCharacterEncoding ( ExtDirectSpringUtil . UTF8_CHARSET . name ( ) ) ; String apiString = buildAndCacheApiString ( apiNs , actionNs , remotingApiVar , pollingUrlsVar , group , fullRouterUrl , baseRouterUrl , request ) ; byte [ ] outputBytes = apiString . getBytes ( ExtDirectSpringUtil . UTF8_CHARSET ) ; response . setContentLength ( outputBytes . length ) ; ServletOutputStream outputStream = response . getOutputStream ( ) ; outputStream . write ( outputBytes ) ; outputStream . flush ( ) ; } else { response . setContentType ( RouterController . APPLICATION_JSON . toString ( ) ) ; response . setCharacterEncoding ( RouterController . APPLICATION_JSON . getCharset ( ) . name ( ) ) ; String requestUrlString = request . getRequestURL ( ) . toString ( ) ; boolean debug = requestUrlString . contains ( "api-debug.js" ) ; String routerUrl = requestUrlString . replaceFirst ( "api[^/]*?\\.js" , "router" ) ; String apiString = buildApiJson ( apiNs , actionNs , remotingApiVar , routerUrl , group , debug ) ; byte [ ] outputBytes = apiString . getBytes ( ExtDirectSpringUtil . UTF8_CHARSET ) ; response . setContentLength ( outputBytes . length ) ; ServletOutputStream outputStream = response . getOutputStream ( ) ; outputStream . write ( outputBytes ) ; outputStream . flush ( ) ; } } | Method that handles api . js and api - debug . js calls . Generates a javascript with the necessary code for Ext Direct . |
24,326 | public void addError ( String field , String error ) { Assert . notNull ( field , "field must not be null" ) ; Assert . notNull ( error , "field must not be null" ) ; addErrors ( field , Collections . singletonList ( error ) ) ; addResultProperty ( SUCCESS_PROPERTY , Boolean . FALSE ) ; } | Adds one error message to a specific field . Does not overwrite already existing errors . |
24,327 | @ SuppressWarnings ( "unchecked" ) public void addErrors ( String field , List < String > errors ) { Assert . notNull ( field , "field must not be null" ) ; Assert . notNull ( errors , "field must not be null" ) ; Map < String , List < String > > errorMap = ( Map < String , List < String > > ) this . result . get ( ERRORS_PROPERTY ) ; if ( errorMap == null ) { errorMap = new HashMap < > ( ) ; addResultProperty ( ERRORS_PROPERTY , errorMap ) ; } List < String > fieldErrors = errorMap . get ( field ) ; if ( fieldErrors == null ) { fieldErrors = new ArrayList < > ( ) ; errorMap . put ( field , fieldErrors ) ; } fieldErrors . addAll ( errors ) ; addResultProperty ( SUCCESS_PROPERTY , Boolean . FALSE ) ; } | Adds multiple error messages to a specific field . Does not overwrite already existing errors . |
24,328 | @ SuppressWarnings ( "unchecked" ) public < T extends Filter > T getFirstFilterForField ( String field ) { for ( Filter filter : this . filters ) { if ( filter . getField ( ) . equals ( field ) ) { return ( T ) filter ; } } return null ; } | Returns the first filter for the field . |
24,329 | public List < Filter > getAllFiltersForField ( String field ) { List < Filter > foundFilters = new ArrayList < > ( ) ; for ( Filter filter : this . filters ) { if ( filter . getField ( ) . equals ( field ) ) { foundFilters . add ( filter ) ; } } return Collections . unmodifiableList ( foundFilters ) ; } | Returns all filters for a field |
24,330 | public ExtDirectResponseBuilder addResultProperty ( String key , Object value ) { this . result . put ( key , value ) ; return this ; } | Add additional property to the response . |
24,331 | public static boolean isMultipart ( HttpServletRequest request ) { if ( ! "post" . equals ( request . getMethod ( ) . toLowerCase ( ) ) ) { return false ; } String contentType = request . getContentType ( ) ; return contentType != null && contentType . toLowerCase ( ) . startsWith ( "multipart/" ) ; } | Checks if the request is a multipart request |
24,332 | public static Object invoke ( ApplicationContext context , String beanName , MethodInfo methodInfo , final Object [ ] params ) throws IllegalArgumentException , IllegalAccessException , InvocationTargetException { Object bean = context . getBean ( beanName ) ; Method handlerMethod = methodInfo . getMethod ( ) ; ReflectionUtils . makeAccessible ( handlerMethod ) ; Object result = handlerMethod . invoke ( bean , params ) ; if ( result != null && result instanceof Optional ) { return ( ( Optional < ? > ) result ) . orElse ( null ) ; } return result ; } | Invokes a method on a Spring managed bean . |
24,333 | public static void addCacheHeaders ( HttpServletResponse response , String etag , Integer month ) { Assert . notNull ( etag , "ETag must not be null" ) ; long seconds ; if ( month != null ) { seconds = month * secondsInAMonth ; } else { seconds = 6L * secondsInAMonth ; } response . setDateHeader ( "Expires" , System . currentTimeMillis ( ) + seconds * 1000L ) ; response . setHeader ( "ETag" , etag ) ; response . setHeader ( "Cache-Control" , "public, max-age=" + seconds ) ; } | Adds Expires ETag and Cache - Control response headers . |
24,334 | public static String generateApiString ( ApplicationContext ctx , String remotingVarName , String pollingApiVarName ) throws JsonProcessingException { RemotingApi remotingApi = new RemotingApi ( ctx . getBean ( ConfigurationService . class ) . getConfiguration ( ) . getProviderType ( ) , "router" , null ) ; for ( Map . Entry < MethodInfoCache . Key , MethodInfo > entry : ctx . getBean ( MethodInfoCache . class ) ) { MethodInfo methodInfo = entry . getValue ( ) ; if ( methodInfo . getAction ( ) != null ) { remotingApi . addAction ( entry . getKey ( ) . getBeanName ( ) , methodInfo . getAction ( ) ) ; } else if ( methodInfo . getPollingProvider ( ) != null ) { remotingApi . addPollingProvider ( methodInfo . getPollingProvider ( ) ) ; } } remotingApi . sort ( ) ; StringBuilder extDirectConfig = new StringBuilder ( 100 ) ; extDirectConfig . append ( "var " ) . append ( remotingVarName ) . append ( " = " ) ; extDirectConfig . append ( new ObjectMapper ( ) . writer ( ) . withDefaultPrettyPrinter ( ) . writeValueAsString ( remotingApi ) ) ; extDirectConfig . append ( ";" ) ; List < PollingProvider > pollingProviders = remotingApi . getPollingProviders ( ) ; if ( ! pollingProviders . isEmpty ( ) ) { extDirectConfig . append ( "\n\nvar " ) . append ( pollingApiVarName ) . append ( " = {\n" ) ; for ( int i = 0 ; i < pollingProviders . size ( ) ; i ++ ) { extDirectConfig . append ( " \"" ) ; extDirectConfig . append ( pollingProviders . get ( i ) . getEvent ( ) ) ; extDirectConfig . append ( "\" : \"poll/" ) ; extDirectConfig . append ( pollingProviders . get ( i ) . getBeanName ( ) ) ; extDirectConfig . append ( "/" ) ; extDirectConfig . append ( pollingProviders . get ( i ) . getMethod ( ) ) ; extDirectConfig . append ( "/" ) ; extDirectConfig . append ( pollingProviders . get ( i ) . getEvent ( ) ) ; extDirectConfig . append ( "\"" ) ; if ( i < pollingProviders . size ( ) - 1 ) { extDirectConfig . append ( ",\n" ) ; } } extDirectConfig . append ( "\n};" ) ; } return extDirectConfig . toString ( ) ; } | Returns the api configuration as a String |
24,335 | public String writeValueAsString ( Object obj , boolean indent ) { try { if ( indent ) { return this . mapper . writer ( ) . withDefaultPrettyPrinter ( ) . writeValueAsString ( obj ) ; } return this . mapper . writeValueAsString ( obj ) ; } catch ( Exception e ) { LogFactory . getLog ( JsonHandler . class ) . info ( "serialize object to json" , e ) ; return null ; } } | Converts an object into a JSON string . In case of an exceptions returns null and logs the exception . |
24,336 | public Object readValue ( InputStream is , Class < Object > clazz ) { try { return this . mapper . readValue ( is , clazz ) ; } catch ( Exception e ) { LogFactory . getLog ( JsonHandler . class ) . info ( "deserialize json to object" , e ) ; return null ; } } | Converts a JSON string into an object . The input is read from an InputStream . In case of an exception returns null and logs the exception . |
24,337 | public static Method findMethodWithAnnotation ( Method method , Class < ? extends Annotation > annotation ) { if ( method . isAnnotationPresent ( annotation ) ) { return method ; } Class < ? > cl = method . getDeclaringClass ( ) ; while ( cl != null && cl != Object . class ) { try { Method equivalentMethod = cl . getDeclaredMethod ( method . getName ( ) , method . getParameterTypes ( ) ) ; if ( equivalentMethod . isAnnotationPresent ( annotation ) ) { return equivalentMethod ; } } catch ( NoSuchMethodException e ) { } cl = cl . getSuperclass ( ) ; } return null ; } | Find a method that is annotated with a specific annotation . Starts with the method and goes up to the superclasses of the class . |
24,338 | public void put ( String beanName , Class < ? > clazz , Method method , ApplicationContext context ) { MethodInfo info = new MethodInfo ( clazz , context , beanName , method ) ; this . cache . put ( new Key ( beanName , method . getName ( ) ) , info ) ; } | Put a method into the MethodCache . |
24,339 | public MethodInfo get ( String beanName , String methodName ) { return this . cache . get ( new Key ( beanName , methodName ) ) ; } | Get a method from the MethodCache . |
24,340 | public String getMessage ( Throwable exception ) { String message ; if ( getExceptionToMessage ( ) != null ) { message = getExceptionToMessage ( ) . get ( exception . getClass ( ) ) ; if ( StringUtils . hasText ( message ) ) { return message ; } if ( getExceptionToMessage ( ) . containsKey ( exception . getClass ( ) ) ) { return exception . getMessage ( ) ; } } if ( isSendExceptionMessage ( ) ) { return exception . getMessage ( ) ; } return getDefaultExceptionMessage ( ) ; } | Returns an error message for the supplied exception and based on this configuration . |
24,341 | public Configuration copy ( ) { Configuration copy = new Configuration ( ) ; copy . apiUrl = apiUrl ; copy . domain = domain ; copy . apiKey = apiKey ; copy . mailRequestCallbackFactory = mailRequestCallbackFactory ; copy . mailSendFilter = mailSendFilter ; copy . defaultParameters = new MultivaluedHashMap < String , String > ( defaultParameters ) ; copy . converters . addAll ( converters ) ; return copy ; } | Creates a copy of this configuration . |
24,342 | public MailBuilder from ( String name , String email ) { return param ( "from" , email ( name , email ) ) ; } | Sets the address of the sender . |
24,343 | public MailBuilder to ( String name , String email ) { return param ( "to" , email ( name , email ) ) ; } | Adds a destination recipient s address . |
24,344 | public MailBuilder cc ( String name , String email ) { return param ( "cc" , email ( name , email ) ) ; } | Adds a CC recipient s address . |
24,345 | public MailBuilder bcc ( String name , String email ) { return param ( "bcc" , email ( name , email ) ) ; } | Adds a BCC recipient s address . |
24,346 | public void sendAsync ( ) { if ( ! configuration . mailSendFilter ( ) . filter ( this ) ) return ; MailRequestCallbackFactory factory = configuration . mailRequestCallbackFactory ( ) ; if ( factory == null ) { prepareSend ( ) ; request ( ) . async ( ) . post ( entity ( ) ) ; } else sendAsync ( factory . create ( this ) ) ; } | Sends the email asynchronously . It uses the configuration provided default callback if available ignoring the outcome otherwise . |
24,347 | public MultipartBuilder attachment ( InputStream is , String filename ) { return bodyPart ( new StreamDataBodyPart ( ATTACHMENT_NAME , is , filename ) ) ; } | Adds a named attachment . |
24,348 | public MultipartBuilder attachment ( String content , String filename ) { ByteArrayInputStream is = new ByteArrayInputStream ( content . getBytes ( ) ) ; return bodyPart ( new StreamDataBodyPart ( ATTACHMENT_NAME , is , filename ) ) ; } | Adds an attachment directly by content . |
24,349 | public MultipartBuilder inline ( InputStream is , String cidName ) { return bodyPart ( new StreamDataBodyPart ( "inline" , is , cidName ) ) ; } | Adds a named inline attachment . |
24,350 | public MailContent row ( String firstCell , String secondCell , String thirdCell ) { return tag ( "tr" ) . cell ( firstCell ) . cell ( secondCell ) . cell ( thirdCell ) . end ( ) ; } | Adds a new row with three columns . |
24,351 | public MailBuilder mail ( ) { if ( mailBuilder != null ) return mailBuilder . content ( build ( ) ) ; else return MailBuilder . using ( configuration ) . content ( build ( ) ) ; } | Convenience method for chaining the creation of the content body with the creation of the mail envelope . |
24,352 | public Builder end ( ) { if ( ends . isEmpty ( ) ) throw new IllegalStateException ( "No pending tag/section to close." ) ; String tag = ends . pop ( ) ; html . a ( tag ) ; if ( newLineAfterTheseTags . contains ( tag . toLowerCase ( ) ) ) { html . nl ( ) ; text . nl ( ) ; } return this ; } | Closes the last opened tag or section . |
24,353 | public < T > Builder row ( T firstCell , T secondCell ) { return tag ( "tr" ) . cell ( firstCell , false ) . cell ( secondCell ) . end ( ) ; } | Adds a new row with two columns . |
24,354 | public < T > Builder rowh ( String label , T data ) { return tag ( "tr" ) . cellHeader ( label , false ) . cell ( data ) . end ( ) ; } | Adds a new row with two columns the first one being a header cell . |
24,355 | public static Object flatten ( Object array ) { Preconditions . checkArgument ( array . getClass ( ) . isArray ( ) , "array" ) ; Class < ? > type = getType ( array ) ; int [ ] dimensions = getDimensions ( array ) ; int length = length ( dimensions ) ; Object flattened = Array . newInstance ( type , length ) ; flatten ( array , flattened , dimensions , 0 ) ; return flattened ; } | Flatten a multi - dimensional array into a one - dimensional array . |
24,356 | public static Object unflatten ( Object array , int [ ] dimensions ) { Class < ? > type = getType ( array ) ; return unflatten ( type , array , dimensions , 0 ) ; } | Un - flatten a one - dimensional array into an multi - dimensional array based on the provided dimensions . |
24,357 | public static byte [ ] sha1 ( byte [ ] input ) { MessageDigest messageDigest = sha1Digest . get ( ) ; if ( messageDigest == null ) { try { messageDigest = MessageDigest . getInstance ( "SHA1" ) ; sha1Digest . set ( messageDigest ) ; } catch ( NoSuchAlgorithmException e ) { throw new UaRuntimeException ( StatusCodes . Bad_InternalError , e ) ; } } return messageDigest . digest ( input ) ; } | Compute the SHA1 digest for a given input . |
24,358 | private static ByteBuf encode ( MessageType messageType , Consumer < ByteBuf > messageEncoder , ByteBuf buffer ) throws UaException { buffer . writeMedium ( MessageType . toMediumInt ( messageType ) ) ; buffer . writeByte ( 'F' ) ; int lengthIndex = buffer . writerIndex ( ) ; buffer . writeInt ( 0 ) ; int indexBefore = buffer . writerIndex ( ) ; messageEncoder . accept ( buffer ) ; int indexAfter = buffer . writerIndex ( ) ; int bytesWritten = indexAfter - indexBefore ; buffer . writerIndex ( lengthIndex ) ; buffer . writeInt ( 8 + bytesWritten ) ; buffer . writerIndex ( indexAfter ) ; return buffer ; } | Encode a simple UA TCP message . |
24,359 | public static void validateHostnameOrIpAddress ( X509Certificate certificate , String hostname ) throws UaException { boolean dnsNameMatches = validateSubjectAltNameField ( certificate , SUBJECT_ALT_NAME_DNS_NAME , hostname :: equals ) ; boolean ipAddressMatches = validateSubjectAltNameField ( certificate , SUBJECT_ALT_NAME_IP_ADDRESS , hostname :: equals ) ; if ( ! ( dnsNameMatches || ipAddressMatches ) ) { throw new UaException ( StatusCodes . Bad_CertificateHostNameInvalid ) ; } } | Validate that the hostname used in the endpoint URL matches either the SubjectAltName DNSName or IPAddress in the given certificate . |
24,360 | public static void validateApplicationUri ( X509Certificate certificate , String applicationUri ) throws UaException { if ( ! validateSubjectAltNameField ( certificate , SUBJECT_ALT_NAME_URI , applicationUri :: equals ) ) { throw new UaException ( StatusCodes . Bad_CertificateUriInvalid ) ; } } | Validate that the application URI matches the SubjectAltName URI in the given certificate . |
24,361 | public static byte [ ] hmac ( SecurityAlgorithm securityAlgorithm , byte [ ] secretKey , ByteBuffer ... buffers ) throws UaException { String transformation = securityAlgorithm . getTransformation ( ) ; try { Mac mac = Mac . getInstance ( transformation ) ; mac . init ( new SecretKeySpec ( secretKey , transformation ) ) ; for ( ByteBuffer buffer : buffers ) { mac . update ( buffer ) ; } return mac . doFinal ( ) ; } catch ( GeneralSecurityException e ) { throw new UaException ( StatusCodes . Bad_SecurityChecksFailed , e ) ; } } | Compute the HMAC of the provided buffers . |
24,362 | public static Optional < String [ ] > lookup ( long code ) { String [ ] desc = DESCRIPTIONS . get ( code & 0xFFFF0000 ) ; return Optional . ofNullable ( desc ) ; } | Lookup information about a StatusCode . |
24,363 | public static CompletableFuture < EndpointDescription [ ] > getEndpoints ( String endpointUrl ) { UaTcpStackClientConfig config = UaTcpStackClientConfig . builder ( ) . setEndpointUrl ( endpointUrl ) . build ( ) ; UaTcpStackClient client = new UaTcpStackClient ( config ) ; GetEndpointsRequest request = new GetEndpointsRequest ( new RequestHeader ( null , DateTime . now ( ) , uint ( 1 ) , uint ( 0 ) , null , uint ( 5000 ) , null ) , endpointUrl , null , new String [ ] { Stack . UA_TCP_BINARY_TRANSPORT_URI } ) ; return client . < GetEndpointsResponse > sendRequest ( request ) . whenComplete ( ( r , ex ) -> client . disconnect ( ) ) . thenApply ( GetEndpointsResponse :: getEndpoints ) ; } | Query the GetEndpoints service at the given endpoint URL . |
24,364 | protected void skipLinesAlreadyRead ( Iterator it ) { long linesRead = getItemsRead ( ) ; if ( linesRead > 0 ) { for ( long i = 0 ; i < linesRead ; i ++ ) { if ( it . hasNext ( ) ) { it . next ( ) ; } } } } | Skips the iterator ahead to the items read value stored in the execution context |
24,365 | protected void addToLong ( String key , long value ) { synchronized ( this . stepExecution ) { long currentValue = getLongValue ( key ) ; getExecutionContext ( ) . putLong ( key , currentValue + value ) ; } } | Adds the specified value to the existing key . |
24,366 | public void reload ( ) { try { if ( file . exists ( ) ) { try ( FileReader fileReader = new FileReader ( file ) ) { props . load ( fileReader ) ; } } } catch ( IOException e ) { FOKLogger . log ( Prefs . class . getName ( ) , Level . SEVERE , FOKLogger . DEFAULT_ERROR_TEXT , e ) ; } } | Reloads this preference file from the hard disk |
24,367 | public void setPreference ( String prefKey , String prefValue ) { props . setProperty ( prefKey , prefValue ) ; savePreferences ( ) ; } | Sets the value of the specified preference in the properties file |
24,368 | public String getPreference ( String prefKey , String defaultValue ) { return props . getProperty ( prefKey , defaultValue ) ; } | Returns the value of the specified preference . |
24,369 | protected Supplier < Set < Image > > overrideImageSupplier ( Injector injector , Supplier < Set < Image > > originalSupplier ) { return originalSupplier ; } | Allows jclouds submodules to override the image supplier |
24,370 | protected Supplier < Set < Location > > overrideLocationSupplier ( Injector injector , Supplier < Set < Location > > originalSupplier ) { return originalSupplier ; } | Allows jclouds submodules to override the location supplier |
24,371 | protected Supplier < Set < HardwareFlavor > > overrideHardwareFlavorSupplier ( Injector injector , Supplier < Set < HardwareFlavor > > originalSupplier ) { return originalSupplier ; } | Allows jclouds submodules to override the hardware supplier |
24,372 | protected Supplier < Set < VirtualMachine > > overrideVirtualMachineSupplier ( Injector injector , Supplier < Set < VirtualMachine > > originalSupplier ) { return originalSupplier ; } | Allows jclouds submodules to override the VirtualMachine supplier |
24,373 | public TemplateOptionsBuilder addOption ( Object field , Object value ) { additionalOptions . put ( field , value ) ; return this ; } | Adds a generic option to the template |
24,374 | public Location build ( ) { return new LocationImpl ( id , providerId , name , parent , isAssignable , locationScope , geoLocation , tags ) ; } | Builds the location . |
24,375 | public static String fromFile ( File file ) throws IOException { BufferedReader br = new BufferedReader ( new FileReader ( file ) ) ; StringBuilder sb = new StringBuilder ( ) ; String line = br . readLine ( ) ; while ( line != null ) { sb . append ( line ) ; line = br . readLine ( ) ; if ( line != null ) sb . append ( System . lineSeparator ( ) ) ; } br . close ( ) ; return sb . toString ( ) ; } | Reads the text from a text file |
24,376 | private static String getRequiredSpaces ( String reference , String message ) { StringBuilder res = new StringBuilder ( ) ; int requiredSpaces = reference . length ( ) - message . length ( ) - 4 ; for ( int i = 0 ; i < requiredSpaces ; i ++ ) { res . append ( " " ) ; } return res . toString ( ) ; } | Formats a message to be printed on the console |
24,377 | private void readRemoteConfig ( URL remoteConfig , URL fallbackConfig , boolean cacheRemoteConfig , String cacheFileName ) throws IOException { checkForOfflineCacheOrLoadFallback ( fallbackConfig , cacheFileName ) ; if ( ! isOfflineMode ( ) ) getRemoteConfig ( remoteConfig , cacheRemoteConfig , cacheFileName ) ; } | Reads the config from the remote url synchronously . If this fails for any reason and a cached config is available the cached config is used instead . If the remote config can t be read and no cached version is available the fallbackConfig is used . |
24,378 | public boolean contains ( String key ) { return onlineProps . getProperty ( key ) != null || offlineProps . getProperty ( key ) != null ; } | Checks if the specified key is defined in this Config file . |
24,379 | public void removeSnapshots ( ) { VersionList versionToRemove = new VersionList ( ) ; for ( Version ver : this ) { if ( ver . isSnapshot ( ) ) { versionToRemove . add ( ver ) ; } } this . removeAll ( versionToRemove ) ; } | Removes all snapshots from this list |
24,380 | public void markAsRead ( ) throws IOException , ClassNotFoundException { if ( ! this . isMarkedAsRead ( ) ) { FileOutputStream fileOut = getMotdFileOutputStreamProvider ( ) . createFileOutputStream ( getNextSerializationFileName ( ) ) ; ObjectOutputStream out = new ObjectOutputStream ( fileOut ) ; out . writeObject ( entry ) ; out . close ( ) ; fileOut . close ( ) ; } } | Marks this message of the day as read . |
24,381 | public boolean isValid ( ) { if ( name == null ) { return false ; } if ( type == null || ! type . isValid ( ) ) { return false ; } else if ( type == Type . Link ) { if ( url == null ) { return false ; } } if ( this . getActions ( ) != null ) { for ( DesktopAction a : this . getActions ( ) ) { if ( ! a . isValid ( ) ) { return false ; } } } return true ; } | Checks if this link is valid to be saved |
24,382 | public List < Classification > list ( String classificationName ) { assertArgumentNotNull ( "classificationName" , classificationName ) ; final String delimiter = GROUP_DELIMITER ; final String pureName ; final String groupName ; if ( classificationName . contains ( delimiter ) ) { pureName = Srl . substringFirstFront ( classificationName , delimiter ) ; groupName = Srl . substringFirstRear ( classificationName , delimiter ) ; } else { pureName = classificationName ; groupName = null ; } final ClassificationMeta meta = findClassificationMeta ( pureName , ( ) -> { return "list('" + classificationName + "')" ; } ) ; if ( groupName != null ) { final List < Classification > groupOfList = meta . groupOf ( groupName ) ; if ( groupOfList . isEmpty ( ) ) { throw new TemplateProcessingException ( "Not found the classification group: " + groupName + " of " + pureName ) ; } return groupOfList ; } else { return meta . listAll ( ) ; } } | Get list of specified classification . |
24,383 | public List < Classification > listAll ( String classificationName ) { assertArgumentNotNull ( "classificationName" , classificationName ) ; return findClassificationMeta ( classificationName , ( ) -> { return "listAll('" + classificationName + "')" ; } ) . listAll ( ) ; } | Get list of all classification . |
24,384 | public String alias ( Object cls , String defaultValue ) { assertArgumentNotNull ( "defaultValue" , defaultValue ) ; if ( cls != null ) { return alias ( cls ) ; } else { return defaultValue ; } } | Get classification alias or default value if the classification is null . |
24,385 | public Classification codeOf ( String classificationName , String code ) { assertArgumentNotNull ( "elementName" , classificationName ) ; assertArgumentNotNull ( "code" , code ) ; return findClassificationMeta ( classificationName , ( ) -> { return "codeOf('" + classificationName + "', '" + code + "')" ; } ) . codeOf ( code ) ; } | Get classification by code . |
24,386 | public Classification nameOf ( String classificationName , String name ) { return findClassificationMeta ( ( String ) classificationName , ( ) -> { return "nameOf('" + classificationName + "', '" + name + "')" ; } ) . nameOf ( name ) ; } | Get classification by name . |
24,387 | public T get ( String s ) { checkNotNull ( s ) ; checkArgument ( ! s . isEmpty ( ) ) ; for ( T t : supplier . get ( ) ) { if ( t . id ( ) . equals ( s ) ) { return t ; } } return null ; } | Searches for the given id in the supplier . |
24,388 | public static UpdateInfo isUpdateAvailable ( URL repoBaseURL , String mavenGroupID , String mavenArtifactID , String mavenClassifier ) { return isUpdateAvailable ( repoBaseURL , mavenGroupID , mavenArtifactID , mavenClassifier , "jar" ) ; } | Checks if a new release has been published on the website . This does not compare the current app version to the release version on the website just checks if something happened on the website . This ensures that updates that were ignored by the user do not show up again . Assumes that the artifact has a jar - packaging . |
24,389 | @ SuppressWarnings ( "Duplicates" ) public static UpdateInfo isUpdateAvailable ( URL repoBaseURL , String mavenGroupID , String mavenArtifactID , String mavenClassifier , @ SuppressWarnings ( "SameParameterValue" ) String packaging ) { String savedSetting = updatePrefs . getPreference ( latestSeenVersionPrefKey , "" ) ; UpdateInfo res = null ; try { FOKLogger . info ( UpdateChecker . class . getName ( ) , "Checking for updates..." ) ; res = getLatestUpdateInfo ( repoBaseURL , mavenGroupID , mavenArtifactID , mavenClassifier , packaging ) ; Version currentVersion ; try { currentVersion = new Version ( Common . getInstance ( ) . getAppVersion ( ) ) ; } catch ( IllegalArgumentException e ) { FOKLogger . log ( UpdateChecker . class . getName ( ) , Level . SEVERE , FOKLogger . DEFAULT_ERROR_TEXT , e ) ; res . showAlert = false ; return res ; } Version savedVersion ; try { savedVersion = new Version ( savedSetting ) ; } catch ( IllegalArgumentException e ) { savedVersion = currentVersion ; } if ( res . toVersion . compareTo ( savedVersion ) > 0 ) { FOKLogger . info ( UpdateChecker . class . getName ( ) , "Update available!" ) ; FOKLogger . info ( UpdateChecker . class . getName ( ) , "Version after update: " + res . toVersion . toString ( ) ) ; FOKLogger . info ( UpdateChecker . class . getName ( ) , "Filesize: " + res . fileSizeInMB + "MB" ) ; res . showAlert = true ; } else if ( res . toVersion . compareTo ( currentVersion ) > 0 ) { FOKLogger . info ( UpdateChecker . class . getName ( ) , "Update available (Update was ignored by the user)!" ) ; FOKLogger . info ( UpdateChecker . class . getName ( ) , "Version after update: " + res . toVersion . toString ( ) ) ; FOKLogger . info ( UpdateChecker . class . getName ( ) , "Filesize: " + res . fileSizeInMB + "MB" ) ; } else { FOKLogger . info ( UpdateChecker . class . getName ( ) , "No update found." ) ; } } catch ( JDOMException | IOException e ) { FOKLogger . log ( UpdateChecker . class . getName ( ) , Level . SEVERE , FOKLogger . DEFAULT_ERROR_TEXT , e ) ; } return res ; } | Checks if a new release has been published on the website . This does not compare the current app version to the release version on the website just checks if something happened on the website . This ensures that updates that were ignored by the user do not show up again . |
24,390 | public static UpdateInfo isUpdateAvailableCompareAppVersion ( URL repoBaseURL , String mavenGroupID , String mavenArtifactID , String mavenClassifier ) { return isUpdateAvailableCompareAppVersion ( repoBaseURL , mavenGroupID , mavenArtifactID , mavenClassifier , "jar" ) ; } | Checks if a new release has been published on the website . This compares the current appVersion to the version available on the website and thus does not take into account if the user ignored that update . Assumes that the artifact has a jar - packaging . |
24,391 | protected void checkRegisteredDataUsingReservedWord ( ActionRuntime runtime , WebContext context , String varKey ) { if ( isSuppressRegisteredDataUsingReservedWordCheck ( ) ) { return ; } if ( context . getVariableNames ( ) . contains ( varKey ) ) { throwThymeleafRegisteredDataUsingReservedWordException ( runtime , context , varKey ) ; } } | Thymeleaf s reserved words are already checked in Thymeleaf process so no check them here |
24,392 | @ ApiModelProperty ( required = true , value = "Primary account number that uniquely identifies this card." ) @ JsonProperty ( "pan" ) @ Pattern ( regexp = "[0-9]{1,19}" ) public String getPan ( ) { return pan ; } | Primary account number that uniquely identifies this card . |
24,393 | @ Path ( "{snapshotId}/complete" ) @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( MediaType . APPLICATION_JSON ) public Response complete ( @ PathParam ( "snapshotId" ) String snapshotId , CompleteSnapshotBridgeParameters params ) { try { Snapshot snapshot = this . snapshotRepo . findByName ( snapshotId ) ; List < String > alternateIds = params . getAlternateIds ( ) ; String altIds = "[]" ; if ( alternateIds != null && ! alternateIds . isEmpty ( ) ) { snapshot = this . snapshotManager . addAlternateSnapshotIds ( snapshot , alternateIds ) ; StringBuilder history = new StringBuilder ( ) ; history . append ( "[" ) ; boolean first = true ; for ( String id : alternateIds ) { if ( ! first ) { history . append ( "," ) ; } history . append ( "'" + id + "'" ) ; first = false ; } history . append ( "]" ) ; altIds = history . toString ( ) ; } String history = "[{'" + SNAPSHOT_ACTION_TITLE + "':'" + SNAPSHOT_ACTION_COMPLETED + "'}," + "{'" + SNAPSHOT_ID_TITLE + "':'" + snapshotId + "'}," + "{'" + SNAPSHOT_ALT_IDS_TITLE + "':" + altIds + "}]" ; snapshotManager . updateHistory ( snapshot , history ) ; snapshot = this . snapshotManager . transferToStorageComplete ( snapshotId ) ; log . info ( "successfully processed snapshot complete notification: {}" , snapshot ) ; return Response . ok ( null ) . entity ( new CompleteSnapshotBridgeResult ( snapshot . getStatus ( ) , snapshot . getStatusText ( ) ) ) . build ( ) ; } catch ( AlternateIdAlreadyExistsException ex ) { log . warn ( ex . getMessage ( ) ) ; return Response . status ( HttpStatus . SC_BAD_REQUEST ) . entity ( new ResponseDetails ( ex . getMessage ( ) ) ) . build ( ) ; } catch ( Exception ex ) { log . error ( ex . getMessage ( ) , ex ) ; return Response . serverError ( ) . entity ( new ResponseDetails ( ex . getMessage ( ) ) ) . build ( ) ; } } | Notifies the bridge that the snapshot transfer from the bridge storage to the preservation storage is complete . Also sets a snapshot s alternate id s if they are passed in . |
24,394 | @ Path ( "{snapshotId}/error" ) @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( MediaType . APPLICATION_JSON ) public Response error ( @ PathParam ( "snapshotId" ) String snapshotId , SnapshotErrorBridgeParameters params ) { try { Snapshot snapshot = snapshotManager . transferError ( snapshotId , params . getError ( ) ) ; log . info ( "Processed snapshot error notification: {}" , snapshot ) ; return Response . ok ( new SnapshotErrorBridgeResult ( snapshot . getStatus ( ) , snapshot . getStatusText ( ) ) ) . build ( ) ; } catch ( Exception ex ) { log . error ( ex . getMessage ( ) , ex ) ; return Response . serverError ( ) . entity ( new ResponseDetails ( ex . getMessage ( ) ) ) . build ( ) ; } } | Notifies the bridge that the snapshot process is not able to continue due to an error which cannot be resolved by the system processing the snapshot data . |
24,395 | @ Path ( "{snapshotId}/history" ) @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( MediaType . APPLICATION_JSON ) public Response updateHistory ( @ PathParam ( "snapshotId" ) String snapshotId , UpdateSnapshotHistoryBridgeParameters params ) { try { if ( params . getAlternate ( ) == null ) { return Response . serverError ( ) . entity ( new ResponseDetails ( "Incorrect parameters submitted!" ) ) . build ( ) ; } Snapshot snapshot = ( params . getAlternate ( ) ? this . snapshotRepo . findBySnapshotAlternateIds ( snapshotId ) : this . snapshotRepo . findByName ( snapshotId ) ) ; if ( snapshot != null ) { if ( params . getHistory ( ) != null && params . getHistory ( ) . length ( ) > 0 ) { snapshot = this . snapshotManager . updateHistory ( snapshot , params . getHistory ( ) ) ; log . info ( "successfully processed snapshot " + "history update: {}" , snapshot ) ; } else { log . info ( "did not process empty or null snapshot " + "history update: {}" , snapshot ) ; } SnapshotSummary snapSummary = createSnapshotSummary ( snapshot ) ; List < SnapshotHistory > snapMeta = snapshot . getSnapshotHistory ( ) ; String history = ( ( snapMeta != null && snapMeta . size ( ) > 0 ) ? snapMeta . get ( snapMeta . size ( ) - 1 ) . getHistory ( ) : "" ) ; UpdateSnapshotHistoryBridgeResult result = new UpdateSnapshotHistoryBridgeResult ( snapSummary , history ) ; log . debug ( "Returning results of update snapshot history: {}" , result ) ; return Response . ok ( null ) . entity ( result ) . build ( ) ; } else { String error = "Snapshot with " + ( params . getAlternate ( ) ? "alternate " : "" ) + "id [" + snapshotId + "] not found!" ; return Response . serverError ( ) . entity ( new ResponseDetails ( error ) ) . build ( ) ; } } catch ( Exception ex ) { log . error ( ex . getMessage ( ) , ex ) ; return Response . serverError ( ) . entity ( new ResponseDetails ( ex . getMessage ( ) ) ) . build ( ) ; } } | Updates a snapshot s history |
24,396 | public void onWriteError ( Exception e , List < ? extends ContentItem > items ) { StringBuilder sb = new StringBuilder ( ) ; for ( ContentItem item : items ) { sb . append ( item . getContentId ( ) + ", " ) ; } String message = "Error writing item(s): " + e . getMessage ( ) + ": items=" + sb . toString ( ) ; this . errors . add ( message ) ; log . error ( message , e ) ; } | Method defined in ItemWriteListener interface |
24,397 | private Date changeRestoreStatus ( Restoration restoration , RestoreStatus status , String msg , Date currentDate ) { log . info ( "Changing restore status to: " + status + " with message: " + msg ) ; restoration . setStatus ( status ) ; restoration . setStatusText ( msg ) ; Date expirationDate = getExpirationDate ( currentDate , daysToExpire ) ; if ( status . equals ( RestoreStatus . RESTORATION_COMPLETE ) ) { restoration . setEndDate ( currentDate ) ; restoration . setExpirationDate ( expirationDate ) ; } restoreRepo . save ( restoration ) ; eventLog . logRestoreUpdate ( restoration ) ; return expirationDate ; } | Updates the restore details in the database |
24,398 | protected Date getExpirationDate ( Date endDate , int daysToExpire ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( endDate ) ; calendar . add ( Calendar . DATE , daysToExpire ) ; return calendar . getTime ( ) ; } | Calculates the restore expiration date based on the restoration end date and the number of days before retirement |
24,399 | private SnapshotTaskClient getSnapshotTaskClient ( DuracloudEndPointConfig source ) { return this . snapshotTaskClientHelper . create ( source , bridgeConfig . getDuracloudUsername ( ) , bridgeConfig . getDuracloudPassword ( ) ) ; } | Build the snapshot task client - for communicating with the DuraCloud snapshot provider to perform tasks . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.