idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
39,800 | public Set < WebSocketChannel > getChannels ( String uri ) { Objects . requireNonNull ( uri , Required . URI . toString ( ) ) ; final Set < WebSocketChannel > channels = this . cache . get ( Default . WSS_CACHE_PREFIX . toString ( ) + uri ) ; return ( channels == null ) ? new HashSet < > ( ) : channels ; } | Retrieves all channels under a given URL |
39,801 | public < T > Future < T > submit ( Runnable runnable , T result ) { return this . executorService . submit ( runnable , result ) ; } | Submits a Runnable task for execution and returns a Future representing that task . The Future s get method will return the given result upon successful completion . |
39,802 | public void reload ( Locale locale ) { this . bundle = ResourceBundle . getBundle ( Default . BUNDLE_NAME . toString ( ) , locale ) ; } | Refreshes the resource bundle by reloading the bundle with the default locale |
39,803 | public static Response withRedirect ( String redirectTo ) { Objects . requireNonNull ( redirectTo , Required . REDIRECT_TO . toString ( ) ) ; return new Response ( redirectTo ) ; } | Creates a response object with a given url to redirect to |
39,804 | public Response andTemplate ( String template ) { Objects . requireNonNull ( template , Required . TEMPLATE . toString ( ) ) ; this . template = template ; return this ; } | Sets a specific template to use for the response |
39,805 | public Response andCharset ( String charset ) { Objects . requireNonNull ( charset , Required . CHARSET . toString ( ) ) ; this . charset = charset ; return this ; } | Sets a specific charset to the response |
39,806 | public Response andCookie ( Cookie cookie ) { Objects . requireNonNull ( cookie , Required . COOKIE . toString ( ) ) ; this . cookies . add ( cookie ) ; return this ; } | Adds an additional Cookie to the response which is passed to the client |
39,807 | @ SuppressFBWarnings ( justification = "null check of file on entry point of method" , value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE" ) public Response andBinaryFile ( Path file ) { Objects . requireNonNull ( file , Required . FILE . toString ( ) ) ; try ( InputStream inputStream = Files . newInputStream ( file ) ) { this . binaryFileName = file . getFileName ( ) . toString ( ) ; this . binaryContent = IOUtils . toByteArray ( inputStream ) ; this . binary = true ; this . rendered = false ; } catch ( final IOException e ) { LOG . error ( "Failed to handle binary file" , e ) ; } return this ; } | Sends a binary file to the client skipping rendering |
39,808 | public Response andBinaryContent ( byte [ ] content ) { Objects . requireNonNull ( content , Required . CONTENT . toString ( ) ) ; this . binaryContent = content . clone ( ) ; this . binary = true ; this . rendered = false ; return this ; } | Sends binary content to the client skipping rendering |
39,809 | public Response andHeader ( HttpString key , String value ) { Objects . requireNonNull ( key , Required . KEY . toString ( ) ) ; this . headers . put ( key , value ) ; return this ; } | Adds an additional header to the request response . If an header key already exists it will we overwritten with the latest value . |
39,810 | public Response andContent ( Map < String , Object > content ) { Objects . requireNonNull ( content , Required . CONTENT . toString ( ) ) ; this . content . putAll ( content ) ; return this ; } | Adds an additional content map to the content rendered in the template . Already existing values with the same key are overwritten . |
39,811 | public Response andHeaders ( Map < HttpString , String > headers ) { Objects . requireNonNull ( headers , Required . HEADERS . toString ( ) ) ; this . headers . putAll ( headers ) ; return this ; } | Adds an additional header map to the response . Already existing values with the same key are overwritten . |
39,812 | public RequestRoute respondeWith ( String method ) { Objects . requireNonNull ( method , Required . CONTROLLER_METHOD . toString ( ) ) ; this . controllerMethod = method ; return this ; } | Sets the controller method to response on request |
39,813 | public void withControllerClass ( Class < ? > clazz ) { Objects . requireNonNull ( clazz , Required . CONTROLLER_CLASS . toString ( ) ) ; this . controllerClass = clazz ; } | Sets the controller class of this request |
39,814 | public void withHttpMethod ( Http method ) { Objects . requireNonNull ( method , Required . METHOD . toString ( ) ) ; this . method = method ; } | Sets the HTTP method of this request |
39,815 | public String getHeader ( HttpString headerName ) { return ( this . httpServerExchange . getRequestHeaders ( ) . get ( headerName ) == null ) ? null : this . httpServerExchange . getRequestHeaders ( ) . get ( headerName ) . element ( ) ; } | Retrieves a specific header value by its name |
39,816 | public void addAttribute ( String key , Object value ) { Objects . requireNonNull ( key , Required . KEY . toString ( ) ) ; this . attributes . put ( key , value ) ; } | Adds an attribute to the internal attributes map |
39,817 | public Object getAttribute ( String key ) { Objects . requireNonNull ( key , Required . KEY . toString ( ) ) ; return this . attributes . get ( key ) ; } | Returns an object attribute from a given key |
39,818 | public void addConnection ( ServerSentEventConnection connection ) { Objects . requireNonNull ( connection , Required . CONNECTION . toString ( ) ) ; final String url = RequestUtils . getServerSentEventURL ( connection ) ; Set < ServerSentEventConnection > uriConnections = getConnections ( url ) ; if ( uriConnections == null ) { uriConnections = new HashSet < > ( ) ; uriConnections . add ( connection ) ; } else { uriConnections . add ( connection ) ; } setConnections ( url , uriConnections ) ; } | Adds a new connection to the manager |
39,819 | public void send ( String uri , String data ) { Objects . requireNonNull ( uri , Required . URI . toString ( ) ) ; final Set < ServerSentEventConnection > uriConnections = getConnections ( uri ) ; if ( uriConnections != null ) { uriConnections . stream ( ) . filter ( ServerSentEventConnection :: isOpen ) . forEach ( ( ServerSentEventConnection connection ) -> connection . send ( data ) ) ; } } | Sends data to all connections for a given URI resource |
39,820 | public Set < ServerSentEventConnection > getConnections ( String uri ) { Objects . requireNonNull ( uri , Required . URI . toString ( ) ) ; final Set < ServerSentEventConnection > uriConnections = this . cache . get ( Default . SSE_CACHE_PREFIX . toString ( ) + uri ) ; return ( uriConnections == null ) ? new HashSet < > ( ) : uriConnections ; } | Retrieves all connection resources under a given URL |
39,821 | public void put ( String key , String value ) { if ( validCharacters ( key ) && validCharacters ( value ) ) { this . values . put ( key , value ) ; } } | Adds a value with a specific key to the flash overwriting an existing value |
39,822 | private boolean validCharacters ( String value ) { if ( INVALID_CHARACTERS . contains ( value ) ) { LOG . error ( "Flash key or value can not contain the following characters: spaces, |, & or :" ) ; return false ; } return true ; } | Checks if the given value contains characters that are not allowed in the key or value of a flash cookie |
39,823 | public static String getVersion ( ) { String version = Default . VERSION_UNKNOW . toString ( ) ; try ( InputStream inputStream = Resources . getResource ( Default . VERSION_PROPERTIES . toString ( ) ) . openStream ( ) ) { final Properties properties = new Properties ( ) ; properties . load ( inputStream ) ; version = String . valueOf ( properties . get ( "version" ) ) ; } catch ( final IOException e ) { LOG . error ( "Failed to get application version" , e ) ; } return version ; } | Retrieves the current version of the framework from the version . properties file |
39,824 | public static Map < String , String > copyMap ( Map < String , String > originalMap ) { Objects . requireNonNull ( originalMap , Required . MAP . toString ( ) ) ; return new HashMap < > ( originalMap ) ; } | Copies a given map to a new map instance |
39,825 | public static String randomString ( int length ) { Preconditions . checkArgument ( length > MIN_PASSWORD_LENGTH , "random string length must be at least 1 character" ) ; Preconditions . checkArgument ( length <= MAX_PASSWORD_LENGTH , "random string length must be at most 256 character" ) ; return RandomStringUtils . random ( length , 0 , CHARACTERS . length - 1 , false , false , CHARACTERS , new SecureRandom ( ) ) ; } | Generates a random string with the given length . |
39,826 | public static String readableFileSize ( long size ) { if ( size <= 0 ) { return "0" ; } int index = ( int ) ( Math . log10 ( size ) / Math . log10 ( CONVERTION ) ) ; return new DecimalFormat ( "#,##0.#" ) . format ( size / Math . pow ( CONVERTION , index ) ) + " " + UNITS [ index ] ; } | Converts a given file size into a readable file size including unit |
39,827 | public static boolean resourceExists ( String name ) { Objects . requireNonNull ( name , Required . NAME . toString ( ) ) ; URL resource = null ; try { resource = Resources . getResource ( name ) ; } catch ( IllegalArgumentException e ) { } return resource != null ; } | Checks if a resource exists in the classpath |
39,828 | public static void minify ( String absolutePath ) { if ( absolutePath == null || absolutePath . contains ( MIN ) ) { return ; } if ( config == null ) { System . setProperty ( Key . APPLICATION_CONFIG . toString ( ) , basePath + Default . CONFIG_PATH . toString ( ) ) ; config = new Config ( Mode . DEV . toString ( ) ) ; } if ( config . isApplicationMinifyCSS ( ) && absolutePath . endsWith ( JS ) ) { minifyJS ( new File ( absolutePath ) ) ; } else if ( config . isApplicationMinifyJS ( ) && absolutePath . endsWith ( CSS ) ) { minifyCSS ( new File ( absolutePath ) ) ; } } | Minifies a JS or CSS file to a corresponding JS or CSS file |
39,829 | public static void preprocess ( String absolutePath ) { if ( absolutePath == null ) { return ; } if ( config == null ) { System . setProperty ( Key . APPLICATION_CONFIG . toString ( ) , basePath + Default . CONFIG_PATH . toString ( ) ) ; config = new Config ( ) ; } if ( config . isApplicationPreprocessLess ( ) && absolutePath . endsWith ( LESS ) ) { lessify ( new File ( absolutePath ) ) ; } else if ( config . isApplicationPreprocessSass ( ) && absolutePath . endsWith ( SASS ) ) { sassify ( new File ( absolutePath ) ) ; } } | Compiles a LESS or SASS file to a corresponding CSS file |
39,830 | @ SuppressFBWarnings ( justification = "SourcePath should intentionally come from user file path" , value = "PATH_TRAVERSAL_IN" ) private List < Source > getSources ( int errorLine , String sourcePath ) throws IOException { Objects . requireNonNull ( sourcePath , Required . SOURCE_PATH . toString ( ) ) ; StringBuilder buffer = new StringBuilder ( ) ; buffer . append ( System . getProperty ( "user.dir" ) ) . append ( File . separator ) . append ( "src" ) . append ( File . separator ) . append ( "main" ) . append ( File . separator ) . append ( "java" ) ; List < Source > sources = new ArrayList < > ( ) ; Path templateFile = Paths . get ( buffer . toString ( ) ) . resolve ( sourcePath ) ; if ( Files . exists ( templateFile ) ) { List < String > lines = Files . readAllLines ( templateFile ) ; int index = 0 ; for ( String line : lines ) { if ( ( index + MAX_LINES > errorLine ) && ( index - MIN_LINES < errorLine ) ) { sources . add ( new Source ( ( index + 1 ) == errorLine , index + 1 , line ) ) ; } index ++ ; } } return sources ; } | Retrieves the lines of code where an exception occurred |
39,831 | private String getSourceCodePath ( StackTraceElement stackTraceElement ) { Objects . requireNonNull ( stackTraceElement , Required . STACK_TRACE_ELEMENT . toString ( ) ) ; String packageName = stackTraceElement . getClassName ( ) ; int position = packageName . lastIndexOf ( '.' ) ; if ( position > 0 ) { packageName = packageName . substring ( 0 , position ) ; return StringUtils . replace ( packageName , "." , File . separator ) + File . separator + stackTraceElement . getFileName ( ) ; } return stackTraceElement . getFileName ( ) ; } | Retrieves the source code file name from an StrackTraceElement |
39,832 | private String getCacheKey ( HttpServerExchange exchange ) { String host = null ; HeaderMap headerMap = exchange . getRequestHeaders ( ) ; if ( headerMap != null ) { HeaderValues headerValues = headerMap . get ( Header . X_FORWARDED_FOR . toHttpString ( ) ) ; if ( headerValues != null ) { host = headerValues . element ( ) ; } } if ( StringUtils . isBlank ( host ) ) { InetSocketAddress inetSocketAddress = exchange . getSourceAddress ( ) ; if ( inetSocketAddress != null ) { host = inetSocketAddress . getHostString ( ) ; } } if ( StringUtils . isNotBlank ( host ) ) { host = host . toLowerCase ( Locale . ENGLISH ) ; } String url = exchange . getRequestURL ( ) ; if ( StringUtils . isNotBlank ( url ) ) { url = url . toLowerCase ( Locale . ENGLISH ) ; } return url + host ; } | Creates a key for used for limit an request containing the requested url and the source host |
39,833 | protected void nextHandler ( HttpServerExchange exchange ) throws Exception { if ( this . attachment . hasBasicAuthentication ( ) ) { HttpHandler httpHandler = RequestUtils . wrapBasicAuthentication ( Application . getInstance ( LocaleHandler . class ) , this . attachment . getUsername ( ) , getPassword ( ) ) ; httpHandler . handleRequest ( exchange ) ; } else { Application . getInstance ( LocaleHandler . class ) . handleRequest ( exchange ) ; } } | Handles the next request in the handler chain |
39,834 | public static String getQRCode ( String name , String issuer , String secret , HmacShaAlgorithm algorithm , String digits , String period ) { Objects . requireNonNull ( name , Required . ACCOUNT_NAME . toString ( ) ) ; Objects . requireNonNull ( secret , Required . SECRET . toString ( ) ) ; Objects . requireNonNull ( issuer , Required . ISSUER . toString ( ) ) ; Objects . requireNonNull ( algorithm , Required . ALGORITHM . toString ( ) ) ; Objects . requireNonNull ( digits , Required . DIGITS . toString ( ) ) ; Objects . requireNonNull ( period , Required . PERIOD . toString ( ) ) ; var buffer = new StringBuilder ( ) ; buffer . append ( "https://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=200x200&chld=M|0&cht=qr&chl=" ) . append ( getOtpauthURL ( name , issuer , secret , algorithm , digits , period ) ) ; return buffer . toString ( ) ; } | Generates a QR code to share a secret with a user |
39,835 | public static String getOtpauthURL ( String name , String issuer , String secret , HmacShaAlgorithm algorithm , String digits , String period ) { Objects . requireNonNull ( name , Required . ACCOUNT_NAME . toString ( ) ) ; Objects . requireNonNull ( secret , Required . SECRET . toString ( ) ) ; Objects . requireNonNull ( issuer , Required . ISSUER . toString ( ) ) ; Objects . requireNonNull ( algorithm , Required . ALGORITHM . toString ( ) ) ; Objects . requireNonNull ( digits , Required . DIGITS . toString ( ) ) ; Objects . requireNonNull ( period , Required . PERIOD . toString ( ) ) ; var buffer = new StringBuilder ( ) ; buffer . append ( "otpauth://totp/" ) . append ( name ) . append ( "?secret=" ) . append ( RegExUtils . replaceAll ( base32 . encodeAsString ( secret . getBytes ( StandardCharsets . UTF_8 ) ) , "=" , "" ) ) . append ( "&algorithm=" ) . append ( algorithm . getAlgorithm ( ) ) . append ( "&issuer=" ) . append ( issuer ) . append ( "&digits=" ) . append ( digits ) . append ( "&period=" ) . append ( period ) ; String url = "" ; try { url = URLEncoder . encode ( buffer . toString ( ) , StandardCharsets . UTF_8 . name ( ) ) ; } catch ( UnsupportedEncodingException e ) { LOG . error ( "Failed to encode otpauth url" , e ) ; } return url ; } | Generates a otpauth code to share a secret with a user |
39,836 | @ SuppressWarnings ( "unchecked" ) protected Session getSessionCookie ( HttpServerExchange exchange ) { Session session = Session . create ( ) . withContent ( new HashMap < > ( ) ) . withAuthenticity ( MangooUtils . randomString ( STRING_LENGTH ) ) ; if ( this . config . getSessionCookieExpires ( ) > 0 ) { session . withExpires ( LocalDateTime . now ( ) . plusSeconds ( this . config . getSessionCookieExpires ( ) ) ) ; } String cookieValue = getCookieValue ( exchange , this . config . getSessionCookieName ( ) ) ; if ( StringUtils . isNotBlank ( cookieValue ) ) { try { String decryptedValue = Application . getInstance ( Crypto . class ) . decrypt ( cookieValue , this . config . getSessionCookieEncryptionKey ( ) ) ; JwtConsumer jwtConsumer = new JwtConsumerBuilder ( ) . setVerificationKey ( new HmacKey ( this . config . getSessionCookieSignKey ( ) . getBytes ( StandardCharsets . UTF_8 ) ) ) . setJwsAlgorithmConstraints ( new AlgorithmConstraints ( ConstraintType . WHITELIST , AlgorithmIdentifiers . HMAC_SHA512 ) ) . build ( ) ; JwtClaims jwtClaims = jwtConsumer . processToClaims ( decryptedValue ) ; String expiresClaim = jwtClaims . getClaimValue ( ClaimKey . EXPIRES . toString ( ) , String . class ) ; if ( ( "-1" ) . equals ( expiresClaim ) ) { session = Session . create ( ) . withContent ( MangooUtils . copyMap ( jwtClaims . getClaimValue ( ClaimKey . DATA . toString ( ) , Map . class ) ) ) . withAuthenticity ( jwtClaims . getClaimValue ( ClaimKey . AUTHENTICITY . toString ( ) , String . class ) ) ; } else if ( LocalDateTime . parse ( jwtClaims . getClaimValue ( ClaimKey . EXPIRES . toString ( ) , String . class ) , DateUtils . formatter ) . isAfter ( LocalDateTime . now ( ) ) ) { session = Session . create ( ) . withContent ( MangooUtils . copyMap ( jwtClaims . getClaimValue ( ClaimKey . DATA . toString ( ) , Map . class ) ) ) . withAuthenticity ( jwtClaims . getClaimValue ( ClaimKey . AUTHENTICITY . toString ( ) , String . class ) ) . withExpires ( LocalDateTime . parse ( jwtClaims . getClaimValue ( ClaimKey . EXPIRES . toString ( ) , String . class ) , DateUtils . formatter ) ) ; } else { } } catch ( MalformedClaimException | InvalidJwtException e ) { LOG . error ( "Failed to parse session cookie" , e ) ; session . invalidate ( ) ; } } return session ; } | Retrieves the current session from the HttpServerExchange |
39,837 | protected Authentication getAuthenticationCookie ( HttpServerExchange exchange ) { Authentication authentication = Authentication . create ( ) . withSubject ( null ) ; String cookieValue = getCookieValue ( exchange , this . config . getAuthenticationCookieName ( ) ) ; if ( StringUtils . isNotBlank ( cookieValue ) ) { try { String decryptedValue = Application . getInstance ( Crypto . class ) . decrypt ( cookieValue , this . config . getAuthenticationCookieEncryptionKey ( ) ) ; JwtConsumer jwtConsumer = new JwtConsumerBuilder ( ) . setRequireSubject ( ) . setVerificationKey ( new HmacKey ( this . config . getAuthenticationCookieSignKey ( ) . getBytes ( StandardCharsets . UTF_8 ) ) ) . setJwsAlgorithmConstraints ( new AlgorithmConstraints ( ConstraintType . WHITELIST , AlgorithmIdentifiers . HMAC_SHA512 ) ) . build ( ) ; JwtClaims jwtClaims = jwtConsumer . processToClaims ( decryptedValue ) ; String expiresClaim = jwtClaims . getClaimValue ( ClaimKey . EXPIRES . toString ( ) , String . class ) ; if ( ( "-1" ) . equals ( expiresClaim ) ) { authentication = Authentication . create ( ) . withSubject ( jwtClaims . getSubject ( ) ) . twoFactorAuthentication ( jwtClaims . getClaimValue ( ClaimKey . TWO_FACTOR . toString ( ) , Boolean . class ) ) ; } else if ( LocalDateTime . parse ( jwtClaims . getClaimValue ( ClaimKey . EXPIRES . toString ( ) , String . class ) , DateUtils . formatter ) . isAfter ( LocalDateTime . now ( ) ) ) { authentication = Authentication . create ( ) . withExpires ( LocalDateTime . parse ( jwtClaims . getClaimValue ( ClaimKey . EXPIRES . toString ( ) , String . class ) , DateUtils . formatter ) ) . withSubject ( jwtClaims . getSubject ( ) ) . twoFactorAuthentication ( jwtClaims . getClaimValue ( ClaimKey . TWO_FACTOR . toString ( ) , Boolean . class ) ) ; } else { } } catch ( MalformedClaimException | InvalidJwtException e ) { LOG . error ( "Failed to parse authentication cookie" , e ) ; authentication . invalidate ( ) ; } } return authentication ; } | Retrieves the current authentication from the HttpServerExchange |
39,838 | @ SuppressWarnings ( "unchecked" ) protected Flash getFlashCookie ( HttpServerExchange exchange ) { Flash flash = Flash . create ( ) ; final String cookieValue = getCookieValue ( exchange , this . config . getFlashCookieName ( ) ) ; if ( StringUtils . isNotBlank ( cookieValue ) ) { try { String decryptedValue = Application . getInstance ( Crypto . class ) . decrypt ( cookieValue , this . config . getFlashCookieEncryptionKey ( ) ) ; JwtConsumer jwtConsumer = new JwtConsumerBuilder ( ) . setVerificationKey ( new HmacKey ( this . config . getFlashCookieSignKey ( ) . getBytes ( StandardCharsets . UTF_8 ) ) ) . setJwsAlgorithmConstraints ( new AlgorithmConstraints ( ConstraintType . WHITELIST , AlgorithmIdentifiers . HMAC_SHA512 ) ) . build ( ) ; JwtClaims jwtClaims = jwtConsumer . processToClaims ( decryptedValue ) ; LocalDateTime expires = LocalDateTime . parse ( jwtClaims . getClaimValue ( ClaimKey . EXPIRES . toString ( ) , String . class ) , DateUtils . formatter ) ; if ( expires . isAfter ( LocalDateTime . now ( ) ) ) { if ( jwtClaims . hasClaim ( ClaimKey . FORM . toString ( ) ) ) { this . form = CodecUtils . deserializeFromBase64 ( jwtClaims . getClaimValue ( ClaimKey . FORM . toString ( ) , String . class ) ) ; } flash = Flash . create ( ) . withContent ( MangooUtils . copyMap ( jwtClaims . getClaimValue ( ClaimKey . DATA . toString ( ) , Map . class ) ) ) . setDiscard ( true ) ; } } catch ( MalformedClaimException | InvalidJwtException e ) { LOG . error ( "Failed to parse flash cookie" , e ) ; flash . invalidate ( ) ; } } return flash ; } | Retrieves the flash cookie from the current |
39,839 | private String getCookieValue ( HttpServerExchange exchange , String cookieName ) { String value = null ; Map < String , Cookie > requestCookies = exchange . getRequestCookies ( ) ; if ( requestCookies != null ) { Cookie cookie = exchange . getRequestCookies ( ) . get ( cookieName ) ; if ( cookie != null ) { value = cookie . getValue ( ) ; } } return value ; } | Retrieves the value of a cookie with a given name from a HttpServerExchange |
39,840 | private void parse ( String propKey , String propValue ) { if ( ARG_TAG . equals ( propValue ) ) { String value = System . getProperty ( propKey ) ; if ( StringUtils . isNotBlank ( value ) && value . startsWith ( CRYPTEX_TAG ) ) { value = decrypt ( value ) ; } if ( StringUtils . isNotBlank ( value ) ) { this . props . setValue ( propKey , value , Application . getMode ( ) . toString ( ) ) ; } } if ( propValue . startsWith ( CRYPTEX_TAG ) ) { this . props . setValue ( propKey , decrypt ( propValue ) , Application . getMode ( ) . toString ( ) ) ; } } | Parses a given property key and value and checks if the value comes from a system property and maybe decrypts the value |
39,841 | private String decrypt ( String value ) { Crypto crypto = new Crypto ( this ) ; String keyFile = System . getProperty ( Key . APPLICATION_PRIVATEKEY . toString ( ) ) ; if ( StringUtils . isNotBlank ( keyFile ) ) { try ( Stream < String > lines = Files . lines ( Paths . get ( keyFile ) ) ) { String key = lines . findFirst ( ) . orElse ( null ) ; if ( StringUtils . isNotBlank ( key ) ) { PrivateKey privateKey = crypto . getPrivateKeyFromString ( key ) ; String cryptex = StringUtils . substringBetween ( value , CRYPTEX_TAG , "}" ) ; if ( privateKey != null && StringUtils . isNotBlank ( cryptex ) ) { return crypto . decrypt ( cryptex , privateKey ) ; } else { LOG . error ( "Failed to decrypt an encrypted config value" ) ; this . decrypted = false ; } } } catch ( IOException | SecurityException | MangooEncryptionException e ) { LOG . error ( "Failed to decrypt an encrypted config value" , e ) ; this . decrypted = false ; } } else { LOG . error ( "Found an encrypted value in config file but private key for decryption is missing" ) ; this . decrypted = false ; } return "" ; } | Decrypts a given property key and rewrites it to props |
39,842 | public static void header ( Header header , String value ) { Objects . requireNonNull ( header , Required . HEADER . toString ( ) ) ; Map < Header , String > newHeaders = new EnumMap < > ( headers ) ; newHeaders . put ( header , value ) ; headers = newHeaders ; } | Sets a custom header that is used globally on server responses |
39,843 | public Mail withBuilder ( Email email ) { Objects . requireNonNull ( email , Required . EMAIL . toString ( ) ) ; this . email = email ; return this ; } | Sets the org . Jodd . Email instance that the email is based on |
39,844 | public Mail templateMessage ( String template , Map < String , Object > content ) throws MangooTemplateEngineException { Objects . requireNonNull ( template , Required . TEMPLATE . toString ( ) ) ; Objects . requireNonNull ( content , Required . CONTENT . toString ( ) ) ; if ( template . charAt ( 0 ) == '/' || template . startsWith ( "\\" ) ) { template = template . substring ( 1 , template . length ( ) ) ; } this . email . htmlMessage ( Application . getInstance ( TemplateEngine . class ) . renderTemplate ( new TemplateContext ( content ) . withTemplatePath ( template ) ) , Default . ENCODING . toString ( ) ) ; return this ; } | Sets a template to be rendered for the email . Using a template will make it a HTML Email by default . |
39,845 | public static Date localDateTimeToDate ( LocalDateTime localDateTime ) { Objects . requireNonNull ( localDateTime , Required . LOCAL_DATE_TIME . toString ( ) ) ; Instant instant = localDateTime . atZone ( ZoneId . systemDefault ( ) ) . toInstant ( ) ; return Date . from ( instant ) ; } | Converts a LocalDateTime to Date |
39,846 | public static Date localDateToDate ( LocalDate localDate ) { Objects . requireNonNull ( localDate , Required . LOCAL_DATE . toString ( ) ) ; Instant instant = localDate . atStartOfDay ( ) . atZone ( ZoneId . systemDefault ( ) ) . toInstant ( ) ; return Date . from ( instant ) ; } | Converts a localDate to Date |
39,847 | protected Request getRequest ( HttpServerExchange exchange ) { final String authenticity = Optional . ofNullable ( this . attachment . getRequestParameter ( ) . get ( Default . AUTHENTICITY . toString ( ) ) ) . orElse ( this . attachment . getForm ( ) . get ( Default . AUTHENTICITY . toString ( ) ) ) ; return new Request ( exchange ) . withSession ( this . attachment . getSession ( ) ) . withAuthenticity ( authenticity ) . withAuthentication ( this . attachment . getAuthentication ( ) ) . withParameter ( this . attachment . getRequestParameter ( ) ) . withBody ( this . attachment . getBody ( ) ) ; } | Creates a new request object containing the current request data |
39,848 | protected Response invokeController ( HttpServerExchange exchange , Response response ) throws IllegalAccessException , InvocationTargetException , MangooTemplateEngineException , IOException { Response invokedResponse ; if ( this . attachment . getMethodParameters ( ) . isEmpty ( ) ) { invokedResponse = ( Response ) this . attachment . getMethod ( ) . invoke ( this . attachment . getControllerInstance ( ) ) ; } else { final Object [ ] convertedParameters = getConvertedParameters ( exchange ) ; invokedResponse = ( Response ) this . attachment . getMethod ( ) . invoke ( this . attachment . getControllerInstance ( ) , convertedParameters ) ; } invokedResponse . andContent ( response . getContent ( ) ) ; invokedResponse . andHeaders ( response . getHeaders ( ) ) ; if ( invokedResponse . isRendered ( ) ) { TemplateContext templateContext = new TemplateContext ( invokedResponse . getContent ( ) ) . withFlash ( this . attachment . getFlash ( ) ) . withSession ( this . attachment . getSession ( ) ) . withForm ( this . attachment . getForm ( ) ) . withMessages ( this . attachment . getMessages ( ) ) . withController ( this . attachment . getControllerAndMethod ( ) ) . withPrettyTime ( this . attachment . getLocale ( ) ) . withAuthenticity ( this . attachment . getSession ( ) ) . withAuthenticityForm ( this . attachment . getSession ( ) ) . withTemplatePath ( getTemplatePath ( invokedResponse ) ) ; invokedResponse . andBody ( this . attachment . getTemplateEngine ( ) . renderTemplate ( templateContext ) ) ; } else if ( invokedResponse . isUnrendered ( ) ) { Cache cache = Application . getInstance ( CacheProvider . class ) . getCache ( CacheName . RESPONSE ) ; String path = "templates/" + this . attachment . getControllerClassName ( ) + '/' + this . attachment . getControllerMethodName ( ) + ".body" ; String body = "" ; if ( cache . get ( path ) == null ) { body = Resources . toString ( Resources . getResource ( path ) , StandardCharsets . UTF_8 ) ; cache . put ( path , body ) ; } else { body = cache . get ( path ) ; } invokedResponse . andBody ( body ) ; } else { } return invokedResponse ; } | Invokes the controller methods and retrieves the response which is later send to the client |
39,849 | protected String getTemplatePath ( Response response ) { return StringUtils . isBlank ( response . getTemplate ( ) ) ? ( this . attachment . getControllerClassName ( ) + "/" + this . attachment . getTemplateEngine ( ) . getTemplateName ( this . attachment . getControllerMethodName ( ) ) ) : response . getTemplate ( ) ; } | Returns the complete path to the template based on the controller and method name |
39,850 | protected Response executeFilter ( List < Annotation > annotations , Response response ) throws NoSuchMethodException , IllegalAccessException , InvocationTargetException { for ( final Annotation annotation : annotations ) { final FilterWith filterWith = ( FilterWith ) annotation ; for ( final Class < ? > clazz : filterWith . value ( ) ) { if ( response . isEndResponse ( ) ) { return response ; } else { final Method classMethod = clazz . getMethod ( Default . FILTER_METHOD . toString ( ) , Request . class , Response . class ) ; response = ( Response ) classMethod . invoke ( Application . getInstance ( clazz ) , this . attachment . getRequest ( ) , response ) ; } } } return response ; } | Executes all filters on controller and method level |
39,851 | protected String getRequestBody ( HttpServerExchange exchange ) throws IOException { String body = "" ; if ( RequestUtils . isPostPutPatch ( exchange ) ) { exchange . startBlocking ( ) ; body = IOUtils . toString ( exchange . getInputStream ( ) , Default . ENCODING . toString ( ) ) ; } return body ; } | Retrieves the complete request body from the request |
39,852 | public boolean isStarted ( ) throws MangooSchedulerException { boolean started ; try { started = this . quartzScheduler != null && this . quartzScheduler . isStarted ( ) ; } catch ( SchedulerException e ) { throw new MangooSchedulerException ( e ) ; } return started ; } | Checks if the scheduler is initialized and started |
39,853 | public void schedule ( JobDetail jobDetail , Trigger trigger ) throws MangooSchedulerException { Objects . requireNonNull ( jobDetail , Required . JOB_DETAIL . toString ( ) ) ; Objects . requireNonNull ( trigger , Required . TRIGGER . toString ( ) ) ; Objects . requireNonNull ( this . quartzScheduler , Required . SCHEDULER . toString ( ) ) ; try { this . quartzScheduler . scheduleJob ( jobDetail , trigger ) ; } catch ( final SchedulerException e ) { throw new MangooSchedulerException ( e ) ; } } | Adds a new job with a given JobDetail and Trigger to the scheduler |
39,854 | @ SuppressWarnings ( "unchecked" ) public List < io . mangoo . models . Job > getAllJobs ( ) throws MangooSchedulerException { Objects . requireNonNull ( this . quartzScheduler , Required . SCHEDULER . toString ( ) ) ; List < io . mangoo . models . Job > jobs = new ArrayList < > ( ) ; try { for ( JobKey jobKey : getAllJobKeys ( ) ) { List < Trigger > triggers = ( List < Trigger > ) this . quartzScheduler . getTriggersOfJob ( jobKey ) ; Trigger trigger = triggers . get ( 0 ) ; TriggerState triggerState = quartzScheduler . getTriggerState ( trigger . getKey ( ) ) ; boolean active = ( TriggerState . NORMAL == triggerState ) ? true : false ; jobs . add ( new io . mangoo . models . Job ( active , jobKey . getName ( ) , trigger . getDescription ( ) , trigger . getNextFireTime ( ) , trigger . getPreviousFireTime ( ) ) ) ; } } catch ( SchedulerException e ) { throw new MangooSchedulerException ( e ) ; } return jobs ; } | Retrieves a list of all jobs and their current status |
39,855 | public JobKey getJobKey ( String name ) throws MangooSchedulerException { Objects . requireNonNull ( name , Required . NAME . toString ( ) ) ; return getAllJobKeys ( ) . stream ( ) . filter ( jobKey -> jobKey . getName ( ) . equalsIgnoreCase ( name ) ) . findFirst ( ) . orElse ( null ) ; } | Retrieves a JobKey by it given name |
39,856 | public void executeJob ( String jobName ) throws MangooSchedulerException { Objects . requireNonNull ( this . quartzScheduler , Required . SCHEDULER . toString ( ) ) ; Objects . requireNonNull ( jobName , Required . JOB_NAME . toString ( ) ) ; try { for ( JobKey jobKey : getAllJobKeys ( ) ) { if ( jobKey . getName ( ) . equalsIgnoreCase ( jobName ) ) { this . quartzScheduler . triggerJob ( jobKey ) ; } } } catch ( SchedulerException | MangooSchedulerException e ) { throw new MangooSchedulerException ( e ) ; } } | Executes a single Quartz Scheduler job right away only once |
39,857 | public List < JobKey > getAllJobKeys ( ) throws MangooSchedulerException { Objects . requireNonNull ( this . quartzScheduler , Required . SCHEDULER . toString ( ) ) ; List < JobKey > jobKeys = new ArrayList < > ( ) ; try { for ( String groupName : this . quartzScheduler . getJobGroupNames ( ) ) { jobKeys . addAll ( this . quartzScheduler . getJobKeys ( GroupMatcher . jobGroupEquals ( groupName ) ) ) ; } } catch ( SchedulerException e ) { throw new MangooSchedulerException ( e ) ; } return jobKeys ; } | Retrieves a list of all JobKeys from the Quartz Scheduler |
39,858 | public void changeState ( String jobName ) throws MangooSchedulerException { Objects . requireNonNull ( this . quartzScheduler , Required . SCHEDULER . toString ( ) ) ; try { for ( JobKey jobKey : getAllJobKeys ( ) ) { if ( jobKey . getName ( ) . equalsIgnoreCase ( jobName ) ) { TriggerState triggerState = getTriggerState ( jobKey ) ; if ( TriggerState . NORMAL == triggerState ) { this . quartzScheduler . pauseJob ( jobKey ) ; } else { this . quartzScheduler . resumeJob ( jobKey ) ; } } } } catch ( SchedulerException | MangooSchedulerException e ) { throw new MangooSchedulerException ( e ) ; } } | Changes the state of a normally running job from pause to resume or resume to pause |
39,859 | private void endRequest ( HttpServerExchange exchange , String redirect ) { exchange . setStatusCode ( StatusCodes . FOUND ) ; Server . headers ( ) . entrySet ( ) . stream ( ) . filter ( entry -> StringUtils . isNotBlank ( entry . getValue ( ) ) ) . forEach ( entry -> exchange . getResponseHeaders ( ) . add ( entry . getKey ( ) . toHttpString ( ) , entry . getValue ( ) ) ) ; exchange . getResponseHeaders ( ) . put ( Header . LOCATION . toHttpString ( ) , redirect ) ; exchange . endExchange ( ) ; } | Ends the current request by sending a HTTP 302 status code and a direct to the given URL |
39,860 | private void endRequest ( HttpServerExchange exchange ) { exchange . setStatusCode ( StatusCodes . FORBIDDEN ) ; Server . headers ( ) . entrySet ( ) . stream ( ) . filter ( entry -> StringUtils . isNotBlank ( entry . getValue ( ) ) ) . forEach ( entry -> exchange . getResponseHeaders ( ) . add ( entry . getKey ( ) . toHttpString ( ) , entry . getValue ( ) ) ) ; exchange . getResponseSender ( ) . send ( Template . DEFAULT . forbidden ( ) ) ; } | Ends the current request by sending a HTTP 403 status code and the default forbidden template |
39,861 | public static Map < String , String > getRequestParameters ( HttpServerExchange exchange ) { Objects . requireNonNull ( exchange , Required . HTTP_SERVER_EXCHANGE . toString ( ) ) ; final Map < String , String > requestParamater = new HashMap < > ( ) ; final Map < String , Deque < String > > queryParameters = exchange . getQueryParameters ( ) ; queryParameters . putAll ( exchange . getPathParameters ( ) ) ; queryParameters . entrySet ( ) . forEach ( entry -> requestParamater . put ( entry . getKey ( ) , entry . getValue ( ) . element ( ) ) ) ; return requestParamater ; } | Converts request and query parameter into a single map |
39,862 | public static boolean isPostPutPatch ( HttpServerExchange exchange ) { Objects . requireNonNull ( exchange , Required . HTTP_SERVER_EXCHANGE . toString ( ) ) ; return ( Methods . POST ) . equals ( exchange . getRequestMethod ( ) ) || ( Methods . PUT ) . equals ( exchange . getRequestMethod ( ) ) || ( Methods . PATCH ) . equals ( exchange . getRequestMethod ( ) ) ; } | Checks if the request is a POST PUT or PATCH request |
39,863 | public static boolean hasValidAuthentication ( String cookie ) { boolean valid = false ; if ( StringUtils . isNotBlank ( cookie ) ) { Config config = Application . getInstance ( Config . class ) ; String value = null ; String [ ] contents = cookie . split ( ";" ) ; for ( String content : contents ) { if ( StringUtils . isNotBlank ( content ) && content . startsWith ( config . getAuthenticationCookieName ( ) ) ) { value = StringUtils . substringAfter ( content , config . getAuthenticationCookieName ( ) + "=" ) ; value = PATTERN . matcher ( value ) . replaceAll ( "" ) ; } } if ( StringUtils . isNotBlank ( value ) ) { String jwt = Application . getInstance ( Crypto . class ) . decrypt ( value , config . getAuthenticationCookieEncryptionKey ( ) ) ; JwtConsumer jwtConsumer = new JwtConsumerBuilder ( ) . setRequireExpirationTime ( ) . setRequireSubject ( ) . setVerificationKey ( new HmacKey ( config . getAuthenticationCookieSignKey ( ) . getBytes ( StandardCharsets . UTF_8 ) ) ) . setJwsAlgorithmConstraints ( new AlgorithmConstraints ( ConstraintType . WHITELIST , AlgorithmIdentifiers . HMAC_SHA512 ) ) . build ( ) ; try { jwtConsumer . processToClaims ( jwt ) ; valid = true ; } catch ( InvalidJwtException e ) { LOG . error ( "Failed to parse authentication cookie" , e ) ; } } } return valid ; } | Checks if the given header contains a valid authentication |
39,864 | public static HttpHandler wrapBasicAuthentication ( HttpHandler httpHandler , String username , String password ) { Objects . requireNonNull ( httpHandler , Required . HTTP_HANDLER . toString ( ) ) ; Objects . requireNonNull ( username , Required . USERNAME . toString ( ) ) ; Objects . requireNonNull ( password , Required . PASSWORD . toString ( ) ) ; HttpHandler wrap = new AuthenticationCallHandler ( httpHandler ) ; wrap = new AuthenticationConstraintHandler ( wrap ) ; wrap = new AuthenticationMechanismsHandler ( wrap , Collections . < AuthenticationMechanism > singletonList ( new BasicAuthenticationMechanism ( "Authentication required" ) ) ) ; return new SecurityInitialHandler ( AuthenticationMode . PRO_ACTIVE , new Identity ( username , password ) , wrap ) ; } | Adds a Wrapper to the handler when the request requires authentication |
39,865 | public static String getOperation ( HttpString method ) { String operation = "" ; if ( Methods . POST . equals ( method ) ) { operation = WRITE ; } else if ( Methods . PUT . equals ( method ) ) { operation = WRITE ; } else if ( Methods . DELETE . equals ( method ) ) { operation = WRITE ; } else if ( Methods . GET . equals ( method ) ) { operation = READ ; } else if ( Methods . PATCH . equals ( method ) ) { operation = WRITE ; } else if ( Methods . OPTIONS . equals ( method ) ) { operation = READ ; } else if ( Methods . HEAD . equals ( method ) ) { operation = READ ; } else { } return operation ; } | Return if a given HTTP method results in a read or write request to a resource |
39,866 | public String decrypt ( String encrytedText , String key ) { Objects . requireNonNull ( encrytedText , Required . ENCRYPTED_TEXT . toString ( ) ) ; Objects . requireNonNull ( key , Required . KEY . toString ( ) ) ; CipherParameters cipherParameters = new ParametersWithRandom ( new KeyParameter ( getSizedSecret ( key ) . getBytes ( StandardCharsets . UTF_8 ) ) ) ; this . paddedBufferedBlockCipher . init ( false , cipherParameters ) ; return new String ( cipherData ( base64Decoder . decode ( encrytedText ) ) , StandardCharsets . UTF_8 ) ; } | Decrypts an given encrypted text using the given key |
39,867 | public String encrypt ( final String plainText , final String key ) { Objects . requireNonNull ( plainText , Required . PLAIN_TEXT . toString ( ) ) ; Objects . requireNonNull ( key , Required . KEY . toString ( ) ) ; CipherParameters cipherParameters = new ParametersWithRandom ( new KeyParameter ( getSizedSecret ( key ) . getBytes ( StandardCharsets . UTF_8 ) ) ) ; this . paddedBufferedBlockCipher . init ( true , cipherParameters ) ; return new String ( base64Encoder . encode ( cipherData ( plainText . getBytes ( StandardCharsets . UTF_8 ) ) ) , StandardCharsets . UTF_8 ) ; } | Encrypts a given plain text using the given key |
39,868 | private byte [ ] cipherData ( final byte [ ] data ) { byte [ ] result = null ; try { final byte [ ] buffer = new byte [ this . paddedBufferedBlockCipher . getOutputSize ( data . length ) ] ; final int processedBytes = this . paddedBufferedBlockCipher . processBytes ( data , 0 , data . length , buffer , 0 ) ; final int finalBytes = this . paddedBufferedBlockCipher . doFinal ( buffer , processedBytes ) ; result = new byte [ processedBytes + finalBytes ] ; System . arraycopy ( buffer , 0 , result , 0 , result . length ) ; } catch ( final CryptoException e ) { LOG . error ( "Failed to encrypt/decrypt data array" , e ) ; } return result ; } | Encrypts or decrypts a given byte array of data |
39,869 | public KeyPair generateKeyPair ( ) { KeyPair keyPair = null ; try { KeyPairGenerator keyPairGenerator = KeyPairGenerator . getInstance ( ALGORITHM ) ; keyPairGenerator . initialize ( KEYLENGTH ) ; keyPair = keyPairGenerator . generateKeyPair ( ) ; } catch ( NoSuchAlgorithmException e ) { LOG . error ( "Failed to create publi/private key pair" , e ) ; } return keyPair ; } | Generate key which contains a pair of private and public key using 4096 bytes |
39,870 | public byte [ ] encrypt ( byte [ ] text , PublicKey key ) throws MangooEncryptionException { Objects . requireNonNull ( text , Required . PLAIN_TEXT . toString ( ) ) ; Objects . requireNonNull ( text , Required . PUBLIC_KEY . toString ( ) ) ; byte [ ] encrypt = null ; try { Cipher cipher = Cipher . getInstance ( ENCRYPTION ) ; cipher . init ( Cipher . ENCRYPT_MODE , key ) ; encrypt = cipher . doFinal ( text ) ; } catch ( NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException e ) { throw new MangooEncryptionException ( "Failed to encrypt clear text with public key" , e ) ; } return encrypt ; } | Encrypt a text using public key |
39,871 | public String encrypt ( String text , PublicKey key ) throws MangooEncryptionException { Objects . requireNonNull ( text , Required . PLAIN_TEXT . toString ( ) ) ; Objects . requireNonNull ( text , Required . PUBLIC_KEY . toString ( ) ) ; String encrypt = null ; try { byte [ ] cipherText = encrypt ( text . getBytes ( StandardCharsets . UTF_8 ) , key ) ; encrypt = encodeBase64 ( cipherText ) ; } catch ( MangooEncryptionException e ) { throw new MangooEncryptionException ( "Failed to encrypt clear text with public key" , e ) ; } return encrypt ; } | Encrypt a text using public key . The result is encoded to Base64 . |
39,872 | public byte [ ] decrypt ( byte [ ] text , PrivateKey key ) throws MangooEncryptionException { Objects . requireNonNull ( text , Required . ENCRYPTED_TEXT . toString ( ) ) ; Objects . requireNonNull ( text , Required . PRIVATE_KEY . toString ( ) ) ; byte [ ] decrypt = null ; try { Cipher cipher = Cipher . getInstance ( ENCRYPTION ) ; cipher . init ( Cipher . DECRYPT_MODE , key ) ; decrypt = cipher . doFinal ( text ) ; } catch ( InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e ) { throw new MangooEncryptionException ( "Failed to decrypt encrypted text with private key" , e ) ; } return decrypt ; } | Decrypt text using private key |
39,873 | public String decrypt ( String text , PrivateKey key ) throws MangooEncryptionException { Objects . requireNonNull ( text , Required . ENCRYPTED_TEXT . toString ( ) ) ; Objects . requireNonNull ( text , Required . PRIVATE_KEY . toString ( ) ) ; String decrypt = null ; try { byte [ ] dectyptedText = decrypt ( decodeBase64 ( text ) , key ) ; decrypt = new String ( dectyptedText , StandardCharsets . UTF_8 ) ; } catch ( MangooEncryptionException e ) { throw new MangooEncryptionException ( "Failed to decrypt encrypted text with private key" , e ) ; } return decrypt ; } | Decrypt Base64 encoded text using private key |
39,874 | public String getKeyAsString ( Key key ) { Objects . requireNonNull ( key , Required . KEY . toString ( ) ) ; return encodeBase64 ( key . getEncoded ( ) ) ; } | Convert a Key to string encoded as Base64 |
39,875 | public PrivateKey getPrivateKeyFromString ( String key ) throws MangooEncryptionException { Objects . requireNonNull ( key , Required . KEY . toString ( ) ) ; try { return KeyFactory . getInstance ( ALGORITHM ) . generatePrivate ( new PKCS8EncodedKeySpec ( decodeBase64 ( key ) ) ) ; } catch ( InvalidKeySpecException | NoSuchAlgorithmException e ) { throw new MangooEncryptionException ( "Failed to get private key from string" , e ) ; } } | Generates Private Key from Base64 encoded string |
39,876 | public PublicKey getPublicKeyFromString ( String key ) throws MangooEncryptionException { Objects . requireNonNull ( key , Required . KEY . toString ( ) ) ; try { return KeyFactory . getInstance ( ALGORITHM ) . generatePublic ( new X509EncodedKeySpec ( decodeBase64 ( key ) ) ) ; } catch ( InvalidKeySpecException | NoSuchAlgorithmException e ) { throw new MangooEncryptionException ( "Failed to get pulbic key from string" , e ) ; } } | Generates Public Key from Base64 encoded string |
39,877 | private String encodeBase64 ( byte [ ] bytes ) { Objects . requireNonNull ( bytes , Required . BYTES . toString ( ) ) ; return org . apache . commons . codec . binary . Base64 . encodeBase64String ( bytes ) ; } | Encode bytes array to Base64 string |
39,878 | private byte [ ] decodeBase64 ( String text ) { Objects . requireNonNull ( text , Required . PLAIN_TEXT . toString ( ) ) ; return org . apache . commons . codec . binary . Base64 . decodeBase64 ( text ) ; } | Decode Base64 encoded string to bytes array |
39,879 | public static String hexJBcrypt ( String data ) { Objects . requireNonNull ( data , Required . DATA . toString ( ) ) ; return BCrypt . hashpw ( data , BCrypt . gensalt ( Default . JBCRYPT_ROUNDS . toInt ( ) ) ) ; } | Hashes a given cleartext data with JBCrypt |
39,880 | public static String hexSHA512 ( String data ) { Objects . requireNonNull ( data , Required . DATA . toString ( ) ) ; return DigestUtils . sha512Hex ( data ) ; } | Hashes a given cleartext data with SHA512 |
39,881 | public static String hexSHA512 ( String data , String salt ) { Objects . requireNonNull ( data , Required . DATA . toString ( ) ) ; Objects . requireNonNull ( salt , Required . SALT . toString ( ) ) ; return DigestUtils . sha512Hex ( data + salt ) ; } | Hashes a given cleartext data with SHA512 and an appended salt |
39,882 | public static boolean checkJBCrypt ( String data , String hash ) { Objects . requireNonNull ( data , Required . DATA . toString ( ) ) ; Objects . requireNonNull ( hash , Required . HASH . toString ( ) ) ; return BCrypt . checkpw ( data , hash ) ; } | Checks a given data against a JBCrypted hash |
39,883 | public static String serializeToBase64 ( Serializable object ) { Objects . requireNonNull ( object , Required . OBJECT . toString ( ) ) ; byte [ ] serialize = SerializationUtils . serialize ( object ) ; return base64Encoder . encodeToString ( serialize ) ; } | Serializes an object into an Base64 encoded data string |
39,884 | public static < T > T deserializeFromBase64 ( String data ) { Objects . requireNonNull ( data , Required . DATA . toString ( ) ) ; byte [ ] bytes = base64Decoder . decode ( data ) ; return SerializationUtils . deserialize ( bytes ) ; } | Deserialize a given Base64 encoded data string into an object |
39,885 | public Optional < String > getString ( String key ) { Objects . requireNonNull ( key , Required . KEY . toString ( ) ) ; String value = this . values . get ( key ) ; if ( StringUtils . isNotBlank ( value ) ) { return Optional . of ( value ) ; } return Optional . empty ( ) ; } | Retrieves an optional string value corresponding to the name of the form element |
39,886 | public Optional < Boolean > getBoolean ( String key ) { Objects . requireNonNull ( key , Required . KEY . toString ( ) ) ; String value = this . values . get ( key ) ; if ( StringUtils . isNotBlank ( value ) ) { if ( ( "1" ) . equals ( value ) ) { return Optional . of ( Boolean . TRUE ) ; } else if ( ( "true" ) . equals ( value ) ) { return Optional . of ( Boolean . TRUE ) ; } else if ( ( "false" ) . equals ( value ) ) { return Optional . of ( Boolean . FALSE ) ; } else if ( ( "0" ) . equals ( value ) ) { return Optional . of ( Boolean . FALSE ) ; } else { } } return Optional . empty ( ) ; } | Retrieves an optional boolean value corresponding to the name of the form element |
39,887 | public Optional < Integer > getInteger ( String key ) { Objects . requireNonNull ( key , Required . KEY . toString ( ) ) ; String value = this . values . get ( key ) ; if ( StringUtils . isNotBlank ( value ) && NumberUtils . isCreatable ( value ) ) { return Optional . of ( Integer . valueOf ( value ) ) ; } return Optional . empty ( ) ; } | Retrieves an optional integer value corresponding to the name of the form element |
39,888 | public Optional < InputStream > getFile ( ) { if ( ! this . files . isEmpty ( ) ) { return Optional . of ( this . files . get ( 0 ) ) ; } return Optional . empty ( ) ; } | Retrieves a single file of the form . If the the form has multiple files the first will be returned |
39,889 | public void addValueList ( String key , String value ) { Objects . requireNonNull ( key , Required . KEY . toString ( ) ) ; if ( ! valueMap . containsKey ( key ) ) { List < String > values = new ArrayList < > ( ) ; values . add ( value ) ; valueMap . put ( key , values ) ; } else { List < String > values = valueMap . get ( key ) ; values . add ( value ) ; valueMap . put ( key , values ) ; } } | Adds an additional item to the value list |
39,890 | public List < String > getValueList ( String key ) { Objects . requireNonNull ( key , Required . KEY . toString ( ) ) ; return this . valueMap . get ( key ) ; } | Retrieves the value list for a given key |
39,891 | public void register ( Object eventListener ) { Objects . requireNonNull ( eventListener , Required . EVENT_LISTENER . toString ( ) ) ; this . eventBus . register ( eventListener ) ; this . listeners . getAndIncrement ( ) ; } | Registers an event listener to the event bus |
39,892 | public void unregister ( Object eventListener ) throws MangooEventBusException { Objects . requireNonNull ( eventListener , Required . EVENT_LISTENER . toString ( ) ) ; try { this . eventBus . unregister ( eventListener ) ; } catch ( IllegalArgumentException e ) { throw new MangooEventBusException ( e ) ; } if ( this . listeners . get ( ) > 0 ) { this . listeners . getAndDecrement ( ) ; } } | Unregisters an event listener to the event bus |
39,893 | public void publish ( Object event ) { Objects . requireNonNull ( event , Required . EVENT . toString ( ) ) ; this . eventBus . post ( event ) ; this . events . getAndIncrement ( ) ; } | Publishes an event to the event bus |
39,894 | @ SuppressWarnings ( "rawtypes" ) protected Form getForm ( HttpServerExchange exchange ) throws IOException { final Form form = Application . getInstance ( Form . class ) ; if ( RequestUtils . isPostPutPatch ( exchange ) ) { final Builder builder = FormParserFactory . builder ( ) ; builder . setDefaultCharset ( StandardCharsets . UTF_8 . name ( ) ) ; try ( final FormDataParser formDataParser = builder . build ( ) . createParser ( exchange ) ) { if ( formDataParser != null ) { exchange . startBlocking ( ) ; final FormData formData = formDataParser . parseBlocking ( ) ; for ( String data : formData ) { Deque < FormValue > deque = formData . get ( data ) ; if ( deque != null ) { FormValue formValue = deque . element ( ) ; if ( formValue != null ) { if ( formValue . isFileItem ( ) && formValue . getFileItem ( ) . getFile ( ) != null ) { form . addFile ( Files . newInputStream ( formValue . getFileItem ( ) . getFile ( ) ) ) ; } else { if ( data . contains ( "[]" ) ) { String key = StringUtils . replace ( data , "[]" , "" ) ; for ( Iterator iterator = deque . iterator ( ) ; iterator . hasNext ( ) ; ) { form . addValueList ( new HttpString ( key ) . toString ( ) , ( ( FormValue ) iterator . next ( ) ) . getValue ( ) ) ; } } else { form . addValue ( new HttpString ( data ) . toString ( ) , formValue . getValue ( ) ) ; } } } } } } } form . setSubmitted ( true ) ; } return form ; } | Retrieves the form parameter from a request |
39,895 | public void put ( String key , String value ) { if ( INVALID_CHRACTERTS . contains ( key ) || INVALID_CHRACTERTS . contains ( value ) ) { LOG . error ( "Session key or value can not contain the following characters: spaces, |, & or :" ) ; } else { this . changed = true ; this . values . put ( key , value ) ; } } | Adds a value to the session overwriting an existing value |
39,896 | private Map < String , Class < ? > > getMethodParameters ( ) { final Map < String , Class < ? > > parameters = new LinkedHashMap < > ( ) ; for ( final Method declaredMethod : this . controllerClass . getDeclaredMethods ( ) ) { if ( declaredMethod . getName ( ) . equals ( this . controllerMethodName ) && declaredMethod . getParameterCount ( ) > 0 ) { Arrays . asList ( declaredMethod . getParameters ( ) ) . forEach ( parameter -> parameters . put ( parameter . getName ( ) , parameter . getType ( ) ) ) ; break ; } } return parameters ; } | Converts the method parameter of a mapped controller method to a map |
39,897 | public WebSocketRoute onController ( Class < ? > clazz ) { Objects . requireNonNull ( clazz , Required . URL . toString ( ) ) ; this . controllerClass = clazz ; return this ; } | Sets the controller class for this WebSocket route |
39,898 | public static String toJson ( Object object ) { Objects . requireNonNull ( object , Required . OBJECT . toString ( ) ) ; String json = null ; try { json = mapper . writeValueAsString ( object ) ; } catch ( JsonProcessingException e ) { LOG . error ( "Failed to convert object to json" , e ) ; } return json ; } | Converts a given object to a Json string |
39,899 | public static ReadContext fromJson ( String json ) { Objects . requireNonNull ( json , Required . JSON . toString ( ) ) ; return JsonPath . parse ( json ) ; } | Converts a given Json string to an JSONPath ReadContext |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.