idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
7,000 | public void registerServlet ( @ Nonnull final Class < ? extends Servlet > aServletClass , @ Nonnull @ Nonempty final String sServletPath , @ Nonnull @ Nonempty final String sServletName , @ Nullable final Map < String , String > aServletInitParams ) { ValueEnforcer . notNull ( aServletClass , "ServletClass" ) ; ValueEnforcer . notEmpty ( sServletPath , "ServletPath" ) ; for ( final ServletItem aItem : m_aServlets ) { // Check path uniqueness if ( aItem . getServletPath ( ) . equals ( sServletPath ) ) throw new IllegalArgumentException ( "Another servlet with the path '" + sServletPath + "' is already registered: " + aItem ) ; // Check name uniqueness if ( aItem . getServletName ( ) . equals ( sServletName ) ) throw new IllegalArgumentException ( "Another servlet with the name '" + sServletName + "' is already registered: " + aItem ) ; } // Instantiate servlet final Servlet aServlet = GenericReflection . newInstance ( aServletClass ) ; if ( aServlet == null ) throw new IllegalArgumentException ( "Failed to instantiate servlet class " + aServletClass ) ; final ServletConfig aServletConfig = m_aSC . createServletConfig ( sServletName , aServletInitParams ) ; try { aServlet . init ( aServletConfig ) ; } catch ( final ServletException ex ) { throw new IllegalStateException ( "Failed to init servlet " + aServlet + " with configuration " + aServletConfig + " for path '" + sServletPath + "'" ) ; } m_aServlets . add ( new ServletItem ( aServlet , sServletPath ) ) ; } | Register a new servlet | 418 | 5 |
7,001 | @ Nullable public Servlet getServletOfPath ( @ Nullable final String sPath ) { final ICommonsList < ServletItem > aMatchingItems = new CommonsArrayList <> ( ) ; if ( StringHelper . hasText ( sPath ) ) m_aServlets . findAll ( aItem -> aItem . matchesPath ( sPath ) , aMatchingItems :: add ) ; final int nMatchingItems = aMatchingItems . size ( ) ; if ( nMatchingItems == 0 ) return null ; if ( nMatchingItems > 1 ) if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "Found more than 1 servlet matching path '" + sPath + "' - using first one: " + aMatchingItems ) ; return aMatchingItems . getFirst ( ) . getServlet ( ) ; } | Find the servlet matching the specified path . | 188 | 9 |
7,002 | public void invalidate ( ) { if ( m_bInvalidated ) throw new IllegalArgumentException ( "Servlet pool already invalidated!" ) ; m_bInvalidated = true ; // Destroy all servlets for ( final ServletItem aServletItem : m_aServlets ) try { aServletItem . getServlet ( ) . destroy ( ) ; } catch ( final Exception ex ) { if ( LOGGER . isErrorEnabled ( ) ) LOGGER . error ( "Failed to destroy servlet " + aServletItem , ex ) ; } m_aServlets . clear ( ) ; } | Invalidate the servlet pool by destroying all contained servlets . Also the list of registered servlets is cleared . | 132 | 23 |
7,003 | ReadIteratorResource < Read , ReadGroupSet , Reference > queryNextInterval ( ) { Stopwatch w = Stopwatch . createStarted ( ) ; if ( ! isAtEnd ( ) ) { intervalIndex ++ ; } if ( isAtEnd ( ) ) { return null ; } ReadIteratorResource < Read , ReadGroupSet , Reference > result = queryForInterval ( currentInterval ( ) ) ; LOG . info ( "Interval query took: " + w ) ; startTiming ( ) ; return result ; } | Re - queries the API for the next interval | 111 | 9 |
7,004 | ReadIteratorResource < Read , ReadGroupSet , Reference > queryForInterval ( GA4GHQueryInterval interval ) { try { return dataSource . getReads ( readSetId , interval . getSequence ( ) , interval . getStart ( ) , interval . getEnd ( ) ) ; } catch ( Exception ex ) { LOG . warning ( "Error getting data for interval " + ex . toString ( ) ) ; } return null ; } | Queries the API for an interval and returns the iterator resource or null if failed | 95 | 16 |
7,005 | void seekMatchingRead ( ) { while ( ! isAtEnd ( ) ) { if ( iterator == null || ! iterator . hasNext ( ) ) { LOG . info ( "Getting " + ( iterator == null ? "first" : "next" ) + " interval from the API" ) ; // We have hit an end (or this is first time) so we need to go fish // to the API. ReadIteratorResource < Read , ReadGroupSet , Reference > resource = queryNextInterval ( ) ; if ( resource != null ) { LOG . info ( "Got next interval from the API" ) ; header = resource . getSAMFileHeader ( ) ; iterator = resource . getSAMRecordIterable ( ) . iterator ( ) ; } else { LOG . info ( "Failed to get next interval from the API" ) ; header = null ; iterator = null ; } } else { nextRead = iterator . next ( ) ; if ( currentInterval ( ) . matches ( nextRead ) ) { return ; // Happy case, otherwise we keep spinning in the loop. } else { LOG . info ( "Skipping non matching read" ) ; } } } } | Ensures next returned read will match the currently requested interval . Since the API always returns overlapping reads we might need to skip some reads if the interval asks for included or starts at types . Also deals with the case of iterator being at an end and needing to query for the next interval . | 247 | 58 |
7,006 | @ Nonnull public CacheControlBuilder setMaxAge ( @ Nonnull final TimeUnit eTimeUnit , final long nDuration ) { return setMaxAgeSeconds ( eTimeUnit . toSeconds ( nDuration ) ) ; } | Set the maximum age relative to the request time | 48 | 9 |
7,007 | public boolean hasGroup ( String groupName ) { boolean result = false ; for ( Group item : getGroupsList ( ) ) { if ( item . getName ( ) . equals ( groupName ) ) { result = true ; } } return result ; } | Check if a group with the given groupName exists in the list or not . The check will be done case - sensitive . | 54 | 25 |
7,008 | public Group getGroup ( String groupName ) { Group result = null ; for ( Group item : getGroupsList ( ) ) { if ( item . getName ( ) . equals ( groupName ) ) { result = item ; } } return result ; } | Get the Group instance from the list by name . | 54 | 10 |
7,009 | protected void processDigits ( List < Span > contextTokens , char compare , HashMap rule , int matchBegin , int currentPosition , LinkedHashMap < String , ConTextSpan > matches ) { mt = pdigit . matcher ( contextTokens . get ( currentPosition ) . text ) ; if ( mt . find ( ) ) { double thisDigit ; // prevent length over limit if ( mt . group ( 1 ) . length ( ) < 4 ) { String a = mt . group ( 1 ) ; thisDigit = Double . parseDouble ( mt . group ( 1 ) ) ; } else { thisDigit = 1000 ; } Set < String > numbers = rule . keySet ( ) ; for ( String num : numbers ) { double ruleDigit = Double . parseDouble ( num ) ; if ( ( compare == ' ' && thisDigit > ruleDigit ) || ( compare == ' ' && thisDigit < ruleDigit ) ) { if ( mt . group ( 2 ) == null ) { // if this token is a number processRules ( contextTokens , ( HashMap ) rule . get ( num ) , matchBegin , currentPosition + 1 , matches ) ; } else { // thisToken is like "30-days" HashMap ruletmp = ( HashMap ) rule . get ( ruleDigit + "" ) ; String subtoken = mt . group ( 2 ) . substring ( 1 ) ; if ( ruletmp . containsKey ( subtoken ) ) { processRules ( contextTokens , ( HashMap ) ruletmp . get ( subtoken ) , matchBegin , currentPosition + 1 , matches ) ; } } } } } } | Because the digit regular expressions are revised into the format like > ; 13 days the rulesMap need to be handled differently to the token matching rulesMap | 351 | 30 |
7,010 | public boolean matches ( SAMRecord record ) { int myEnd = end == 0 ? Integer . MAX_VALUE : end ; switch ( readPositionConstraint ) { case OVERLAPPING : return CoordMath . overlaps ( start , myEnd , record . getAlignmentStart ( ) , record . getAlignmentEnd ( ) ) ; case CONTAINED : return CoordMath . encloses ( start , myEnd , record . getAlignmentStart ( ) , record . getAlignmentEnd ( ) ) ; case START_AT : return start == record . getAlignmentStart ( ) ; } return false ; } | Returns true iff the read specified by the record matches the interval given the interval s constraints and the read position . | 129 | 23 |
7,011 | public static void clearContextPath ( ) { if ( s_sServletContextPath != null ) { if ( LOGGER . isInfoEnabled ( ) && ! isSilentMode ( ) ) LOGGER . info ( "The servlet context path '" + s_sServletContextPath + "' was cleared!" ) ; s_sServletContextPath = null ; } if ( s_sCustomContextPath != null ) { if ( LOGGER . isInfoEnabled ( ) && ! isSilentMode ( ) ) LOGGER . info ( "The custom servlet context path '" + s_sCustomContextPath + "' was cleared!" ) ; s_sCustomContextPath = null ; } } | Clears both servlet context and custom context path . | 150 | 11 |
7,012 | public final void setDataSource ( DataSource dataSource ) { if ( this . jdbcTemplate == null || dataSource != this . jdbcTemplate . getDataSource ( ) ) { this . jdbcTemplate = createJdbcTemplate ( dataSource ) ; initTemplateConfig ( ) ; } } | Set the JDBC DataSource to be used by this DAO . | 66 | 14 |
7,013 | @ Nullable public static DigestAuthClientCredentials getDigestAuthClientCredentials ( @ Nullable final String sAuthHeader ) { final ICommonsOrderedMap < String , String > aParams = getDigestAuthParams ( sAuthHeader ) ; if ( aParams == null ) return null ; final String sUserName = aParams . remove ( "username" ) ; if ( sUserName == null ) { LOGGER . error ( "Digest Auth does not container 'username'" ) ; return null ; } final String sRealm = aParams . remove ( "realm" ) ; if ( sRealm == null ) { LOGGER . error ( "Digest Auth does not container 'realm'" ) ; return null ; } final String sNonce = aParams . remove ( "nonce" ) ; if ( sNonce == null ) { LOGGER . error ( "Digest Auth does not container 'nonce'" ) ; return null ; } final String sDigestURI = aParams . remove ( "uri" ) ; if ( sDigestURI == null ) { LOGGER . error ( "Digest Auth does not container 'uri'" ) ; return null ; } final String sResponse = aParams . remove ( "response" ) ; if ( sResponse == null ) { LOGGER . error ( "Digest Auth does not container 'response'" ) ; return null ; } final String sAlgorithm = aParams . remove ( "algorithm" ) ; final String sCNonce = aParams . remove ( "cnonce" ) ; final String sOpaque = aParams . remove ( "opaque" ) ; final String sMessageQOP = aParams . remove ( "qop" ) ; final String sNonceCount = aParams . remove ( "nc" ) ; if ( aParams . isNotEmpty ( ) ) if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "Digest Auth contains unhandled parameters: " + aParams . toString ( ) ) ; return new DigestAuthClientCredentials ( sUserName , sRealm , sNonce , sDigestURI , sResponse , sAlgorithm , sCNonce , sOpaque , sMessageQOP , sNonceCount ) ; } | Get the Digest authentication credentials from the passed HTTP header value . | 507 | 12 |
7,014 | @ Nonnull public static DigestAuthClientCredentials createDigestAuthClientCredentials ( @ Nonnull final EHttpMethod eMethod , @ Nonnull @ Nonempty final String sDigestURI , @ Nonnull @ Nonempty final String sUserName , @ Nonnull final String sPassword , @ Nonnull @ Nonempty final String sRealm , @ Nonnull @ Nonempty final String sServerNonce , @ Nullable final String sAlgorithm , @ Nullable final String sClientNonce , @ Nullable final String sOpaque , @ Nullable final String sMessageQOP , @ CheckForSigned final int nNonceCount ) { ValueEnforcer . notNull ( eMethod , "Method" ) ; ValueEnforcer . notEmpty ( sDigestURI , "DigestURI" ) ; ValueEnforcer . notEmpty ( sUserName , "UserName" ) ; ValueEnforcer . notNull ( sPassword , "Password" ) ; ValueEnforcer . notEmpty ( sRealm , "Realm" ) ; ValueEnforcer . notEmpty ( sServerNonce , "ServerNonce" ) ; if ( sMessageQOP != null && StringHelper . hasNoText ( sClientNonce ) ) throw new IllegalArgumentException ( "If a QOP is defined, client nonce must be set!" ) ; if ( sMessageQOP != null && nNonceCount <= 0 ) throw new IllegalArgumentException ( "If a QOP is defined, nonce count must be positive!" ) ; final String sRealAlgorithm = sAlgorithm == null ? DEFAULT_ALGORITHM : sAlgorithm ; if ( ! sRealAlgorithm . equals ( ALGORITHM_MD5 ) && ! sRealAlgorithm . equals ( ALGORITHM_MD5_SESS ) ) throw new IllegalArgumentException ( "Currently only '" + ALGORITHM_MD5 + "' and '" + ALGORITHM_MD5_SESS + "' algorithms are supported!" ) ; if ( sMessageQOP != null && ! sMessageQOP . equals ( QOP_AUTH ) ) throw new IllegalArgumentException ( "Currently only '" + QOP_AUTH + "' QOP is supported!" ) ; // Nonce must always by 8 chars long final String sNonceCount = getNonceCountString ( nNonceCount ) ; // Create HA1 String sHA1 = _md5 ( sUserName + SEPARATOR + sRealm + SEPARATOR + sPassword ) ; if ( sRealAlgorithm . equals ( ALGORITHM_MD5_SESS ) ) { if ( StringHelper . hasNoText ( sClientNonce ) ) throw new IllegalArgumentException ( "Algorithm requires client nonce!" ) ; sHA1 = _md5 ( sHA1 + SEPARATOR + sServerNonce + SEPARATOR + sClientNonce ) ; } // Create HA2 // Method name must be upper-case! final String sHA2 = _md5 ( eMethod . getName ( ) + SEPARATOR + sDigestURI ) ; // Create the request digest - result must be all lowercase hex chars! String sRequestDigest ; if ( sMessageQOP == null ) { // RFC 2069 backwards compatibility sRequestDigest = _md5 ( sHA1 + SEPARATOR + sServerNonce + SEPARATOR + sHA2 ) ; } else { sRequestDigest = _md5 ( sHA1 + SEPARATOR + sServerNonce + SEPARATOR + sNonceCount + SEPARATOR + sClientNonce + SEPARATOR + sMessageQOP + SEPARATOR + sHA2 ) ; } return new DigestAuthClientCredentials ( sUserName , sRealm , sServerNonce , sDigestURI , sRequestDigest , sAlgorithm , sClientNonce , sOpaque , sMessageQOP , sNonceCount ) ; } | Create HTTP Digest auth credentials for a client | 869 | 8 |
7,015 | @ SuppressWarnings ( "unchecked" ) public < U extends Uniform > U get ( String name ) { final Uniform uniform = uniforms . get ( name ) ; if ( uniform == null ) { return null ; } return ( U ) uniform ; } | Returns the uniform with the provided name or null if non can be found . | 54 | 15 |
7,016 | @ Nullable private static String _getFilename ( @ Nullable final String sContentDisposition ) { String sFilename = null ; if ( sContentDisposition != null ) { final String sContentDispositionLC = sContentDisposition . toLowerCase ( Locale . US ) ; if ( sContentDispositionLC . startsWith ( RequestHelper . FORM_DATA ) || sContentDispositionLC . startsWith ( RequestHelper . ATTACHMENT ) ) { // Parameter parser can handle null input final ICommonsMap < String , String > aParams = new ParameterParser ( ) . setLowerCaseNames ( true ) . parse ( sContentDisposition , ' ' ) ; if ( aParams . containsKey ( "filename" ) ) { sFilename = aParams . get ( "filename" ) ; if ( sFilename != null ) { sFilename = sFilename . trim ( ) ; } else { // Even if there is no value, the parameter is present, // so we return an empty file name rather than no file // name. sFilename = "" ; } } } } return sFilename ; } | Returns the given content - disposition headers file name . | 237 | 10 |
7,017 | @ Nullable private static String _getFieldName ( @ Nullable final String sContentDisposition ) { String sFieldName = null ; if ( sContentDisposition != null && sContentDisposition . toLowerCase ( Locale . US ) . startsWith ( RequestHelper . FORM_DATA ) ) { // Parameter parser can handle null input final ICommonsMap < String , String > aParams = new ParameterParser ( ) . setLowerCaseNames ( true ) . parse ( sContentDisposition , ' ' ) ; sFieldName = aParams . get ( "name" ) ; if ( sFieldName != null ) sFieldName = sFieldName . trim ( ) ; } return sFieldName ; } | Returns the field name which is given by the content - disposition header . | 155 | 14 |
7,018 | public static boolean isForbiddenParamValueChar ( final char c ) { // INVALID_VALUE_CHAR_XML10 + 0x7f return ( c >= 0x0 && c <= 0x8 ) || ( c >= 0xb && c <= 0xc ) || ( c >= 0xe && c <= 0x1f ) || ( c == 0x7f ) || ( c >= 0xd800 && c <= 0xdfff ) || ( c >= 0xfffe && c <= 0xffff ) ; } | Check if the provided char is forbidden in a request value or not . | 111 | 14 |
7,019 | @ Nullable public static String getWithoutForbiddenChars ( @ Nullable final String s ) { if ( s == null ) return null ; final StringBuilder aCleanValue = new StringBuilder ( s . length ( ) ) ; int nForbidden = 0 ; for ( final char c : s . toCharArray ( ) ) if ( isForbiddenParamValueChar ( c ) ) nForbidden ++ ; else aCleanValue . append ( c ) ; if ( nForbidden == 0 ) { // Return "as-is" return s ; } if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "Removed " + nForbidden + " forbidden character(s) from a request parameter value!" ) ; return aCleanValue . toString ( ) ; } | Remove all chars from the input that cannot be serialized as XML . | 166 | 14 |
7,020 | public void setString ( String string ) { rawString = string ; colorIndices . clear ( ) ; // Search for color codes final StringBuilder stringBuilder = new StringBuilder ( string ) ; final Matcher matcher = COLOR_PATTERN . matcher ( string ) ; int removedCount = 0 ; while ( matcher . find ( ) ) { final int index = matcher . start ( ) - removedCount ; // Ignore escaped color codes if ( index > 0 && stringBuilder . charAt ( index - 1 ) == ' ' ) { // Remove the escape character stringBuilder . deleteCharAt ( index - 1 ) ; removedCount ++ ; continue ; } // Add the color for the index and delete it from the string final String colorCode = matcher . group ( ) ; colorIndices . put ( index , CausticUtil . fromPackedARGB ( Long . decode ( colorCode ) . intValue ( ) ) ) ; final int length = colorCode . length ( ) ; stringBuilder . delete ( index , index + length ) ; removedCount += length ; } // Color code free string this . string = stringBuilder . toString ( ) ; } | Sets the string to render . | 246 | 7 |
7,021 | public static PrivateKey readPrivateKey ( final File root , final String directory , final String fileName ) throws NoSuchAlgorithmException , InvalidKeySpecException , NoSuchProviderException , IOException { final File privatekeyDir = new File ( root , directory ) ; final File privatekeyFile = new File ( privatekeyDir , fileName ) ; final PrivateKey privateKey = PrivateKeyReader . readPrivateKey ( privatekeyFile ) ; return privateKey ; } | Constructs from the given root parent directory and file name the file and reads the private key . | 96 | 19 |
7,022 | protected String newAlgorithm ( ) { if ( getModel ( ) . getAlgorithm ( ) == null ) { return SunJCEAlgorithm . PBEWithMD5AndDES . getAlgorithm ( ) ; } return getModel ( ) . getAlgorithm ( ) . getAlgorithm ( ) ; } | Factory method for creating a new algorithm that will be used with the cipher object . Overwrite this method to provide a specific algorithm . | 65 | 26 |
7,023 | @ Override public final void init ( @ Nonnull final ServletConfig aSC ) throws ServletException { super . init ( aSC ) ; m_aStatusMgr . onServletInit ( getClass ( ) ) ; try { // Build init parameter map final ICommonsMap < String , String > aInitParams = new CommonsHashMap <> ( ) ; final Enumeration < String > aEnum = aSC . getInitParameterNames ( ) ; while ( aEnum . hasMoreElements ( ) ) { final String sName = aEnum . nextElement ( ) ; aInitParams . put ( sName , aSC . getInitParameter ( sName ) ) ; } // Invoke each handler for potential initialization m_aHandlerRegistry . forEachHandlerThrowing ( x -> x . onServletInit ( aInitParams ) ) ; } catch ( final ServletException ex ) { m_aStatusMgr . onServletInitFailed ( ex , getClass ( ) ) ; throw ex ; } } | A final overload of init . Overload init instead . | 226 | 11 |
7,024 | @ Override public final void service ( @ Nonnull final ServletRequest req , @ Nonnull final ServletResponse res ) throws ServletException , IOException { super . service ( req , res ) ; } | Avoid overloading in sub classes | 44 | 6 |
7,025 | public static void beforeRequest ( @ Nonnull final HttpUriRequest aRequest , @ Nullable final HttpContext aHttpContext ) { if ( isEnabled ( ) ) if ( LOGGER . isInfoEnabled ( ) ) LOGGER . info ( "Before HTTP call: " + aRequest . getMethod ( ) + " " + aRequest . getURI ( ) + ( aHttpContext != null ? " (with special HTTP context)" : "" ) ) ; } | Call before an invocation | 98 | 4 |
7,026 | public static void afterRequest ( @ Nonnull final HttpUriRequest aRequest , @ Nullable final Object aResponse , @ Nullable final Throwable aCaughtException ) { if ( isEnabled ( ) ) if ( LOGGER . isInfoEnabled ( ) ) { final HttpResponseException aHex = aCaughtException instanceof HttpResponseException ? ( HttpResponseException ) aCaughtException : null ; LOGGER . info ( "After HTTP call: " + aRequest . getMethod ( ) + ( aResponse != null ? ". Response: " + aResponse : "" ) + ( aHex != null ? ". Status " + aHex . getStatusCode ( ) : "" ) , aHex != null ? null : aCaughtException ) ; } } | Call after an invocation . | 166 | 5 |
7,027 | private void transform ( JSONArray root ) { for ( int i = 0 , size = root . size ( ) ; i < size ; i ++ ) { Object target = root . get ( i ) ; if ( target instanceof JSONObject ) this . transform ( ( JSONObject ) target ) ; } } | Apply transform to each json object in the json array | 63 | 10 |
7,028 | public String hashAndHexPassword ( final String password , final String salt ) throws NoSuchAlgorithmException , InvalidKeyException , UnsupportedEncodingException , NoSuchPaddingException , IllegalBlockSizeException , BadPaddingException , InvalidKeySpecException , InvalidAlgorithmParameterException { return hashAndHexPassword ( password , salt , DEFAULT_ALGORITHM , DEFAULT_CHARSET ) ; } | Hash and hex password with the given salt . | 89 | 9 |
7,029 | public String hashAndHexPassword ( final String password , final String salt , final HashAlgorithm hashAlgorithm , final Charset charset ) throws NoSuchAlgorithmException , InvalidKeyException , UnsupportedEncodingException , NoSuchPaddingException , IllegalBlockSizeException , BadPaddingException , InvalidKeySpecException , InvalidAlgorithmParameterException { final String hashedPassword = Hasher . hashAndHex ( password , salt , hashAlgorithm , charset ) ; return hashedPassword ; } | Hash and hex the given password with the given salt hash algorithm and charset . | 107 | 16 |
7,030 | public String hashPassword ( final String password , final String salt , final HashAlgorithm hashAlgorithm , final Charset charset ) throws NoSuchAlgorithmException { final String hashedPassword = HashExtensions . hash ( password , salt , hashAlgorithm , charset ) ; return hashedPassword ; } | Hashes the given password with the given salt hash algorithm and charset . | 65 | 15 |
7,031 | @ Nonnull public static final < T extends AbstractGlobalWebSingleton > T getGlobalSingleton ( @ Nonnull final Class < T > aClass ) { return getSingleton ( _getStaticScope ( true ) , aClass ) ; } | Get the singleton object in the current global web scope using the passed class . If the singleton is not yet instantiated a new instance is created . | 51 | 31 |
7,032 | public static void setDNSCacheTime ( final int nSeconds ) { final String sValue = Integer . toString ( nSeconds ) ; Security . setProperty ( "networkaddress.cache.ttl" , sValue ) ; Security . setProperty ( "networkaddress.cache.negative.ttl" , sValue ) ; SystemProperties . setPropertyValue ( "disableWSAddressCaching" , nSeconds == 0 ) ; } | Set special DNS client properties that have influence on the DNS client behavior . This method should be called as soon as possible on startup . In most cases it may be beneficiary if the respective system properties are provided as system properties on the commandline! | 97 | 48 |
7,033 | @ Nonnull public QValue getQValueOfCharset ( @ Nonnull final String sCharset ) { ValueEnforcer . notNull ( sCharset , "Charset" ) ; // Find charset direct QValue aQuality = m_aMap . get ( _unify ( sCharset ) ) ; if ( aQuality == null ) { // If not explicitly given, check for "*" aQuality = m_aMap . get ( AcceptCharsetHandler . ANY_CHARSET ) ; if ( aQuality == null ) { // Neither charset nor "*" is present return sCharset . equals ( AcceptCharsetHandler . DEFAULT_CHARSET ) ? QValue . MAX_QVALUE : QValue . MIN_QVALUE ; } } return aQuality ; } | Return the associated quality of the given charset . | 177 | 10 |
7,034 | public static void checkForGLError ( ) { if ( CausticUtil . isDebugEnabled ( ) ) { final int errorValue = GL11 . glGetError ( ) ; if ( errorValue != GL11 . GL_NO_ERROR ) { throw new GLException ( "GL ERROR: " + GLU . gluErrorString ( errorValue ) ) ; } } } | Throws an exception if OpenGL reports an error . | 85 | 10 |
7,035 | public static PemObject getPemObject ( final File file ) throws IOException { PemObject pemObject ; try ( PemReader pemReader = new PemReader ( new InputStreamReader ( new FileInputStream ( file ) ) ) ) { pemObject = pemReader . readPemObject ( ) ; } return pemObject ; } | Gets the pem object . | 77 | 7 |
7,036 | public void clearAttributes ( ) { for ( final Map . Entry < String , Object > entry : m_aAttributes . entrySet ( ) ) { final String sName = entry . getKey ( ) ; final Object aValue = entry . getValue ( ) ; if ( aValue instanceof HttpSessionBindingListener ) ( ( HttpSessionBindingListener ) aValue ) . valueUnbound ( new HttpSessionBindingEvent ( this , sName , aValue ) ) ; } m_aAttributes . clear ( ) ; } | Clear all of this session s attributes . | 114 | 8 |
7,037 | @ Nonnull public Serializable serializeState ( ) { final ICommonsMap < String , Object > aState = new CommonsHashMap <> ( ) ; for ( final Map . Entry < String , Object > entry : m_aAttributes . entrySet ( ) ) { final String sName = entry . getKey ( ) ; final Object aValue = entry . getValue ( ) ; if ( aValue instanceof Serializable ) { aState . put ( sName , aValue ) ; } else { // Not serializable... Servlet containers usually automatically // unbind the attribute in this case. if ( aValue instanceof HttpSessionBindingListener ) { ( ( HttpSessionBindingListener ) aValue ) . valueUnbound ( new HttpSessionBindingEvent ( this , sName , aValue ) ) ; } } } m_aAttributes . clear ( ) ; return aState ; } | Serialize the attributes of this session into an object that can be turned into a byte array with standard Java serialization . | 192 | 24 |
7,038 | @ Nonnull public static EChange setAll ( final boolean bResponseCompressionEnabled , final boolean bResponseGzipEnabled , final boolean bResponseDeflateEnabled ) { return s_aRWLock . writeLocked ( ( ) -> { EChange eChange = EChange . UNCHANGED ; if ( s_bResponseCompressionEnabled != bResponseCompressionEnabled ) { s_bResponseCompressionEnabled = bResponseCompressionEnabled ; eChange = EChange . CHANGED ; LOGGER . info ( "ResponseHelper responseCompressEnabled=" + bResponseCompressionEnabled ) ; } if ( s_bResponseGzipEnabled != bResponseGzipEnabled ) { s_bResponseGzipEnabled = bResponseGzipEnabled ; eChange = EChange . CHANGED ; LOGGER . info ( "ResponseHelper responseGzipEnabled=" + bResponseGzipEnabled ) ; } if ( s_bResponseDeflateEnabled != bResponseDeflateEnabled ) { s_bResponseDeflateEnabled = bResponseDeflateEnabled ; eChange = EChange . CHANGED ; LOGGER . info ( "ResponseHelper responseDeflateEnabled=" + bResponseDeflateEnabled ) ; } return eChange ; } ) ; } | Set all parameters at once as an atomic transaction | 260 | 9 |
7,039 | @ Nonnull public static EChange setExpirationSeconds ( final int nExpirationSeconds ) { return s_aRWLock . writeLocked ( ( ) -> { if ( s_nExpirationSeconds == nExpirationSeconds ) return EChange . UNCHANGED ; s_nExpirationSeconds = nExpirationSeconds ; LOGGER . info ( "ResponseHelper expirationSeconds=" + nExpirationSeconds ) ; return EChange . CHANGED ; } ) ; } | Set the default expiration settings to be used for objects that should use HTTP caching | 108 | 15 |
7,040 | @ Nonnull public InputStream openStream ( ) throws IOException { if ( m_aIS instanceof ICloseable && ( ( ICloseable ) m_aIS ) . isClosed ( ) ) throw new MultipartItemSkippedException ( ) ; return m_aIS ; } | Returns an input stream which may be used to read the items contents . | 63 | 14 |
7,041 | public @ Nonnull String text ( ) { return new NodeListSpliterator ( node . getChildNodes ( ) ) . stream ( ) . filter ( it -> it instanceof Text ) . map ( it -> ( ( Text ) it ) . getNodeValue ( ) ) . collect ( joining ( ) ) ; } | Returns the text content of this node . | 66 | 8 |
7,042 | public @ Nonnull Map < String , String > attr ( ) { synchronized ( this ) { if ( attrMap . get ( ) == null ) { attrMap . set ( Optional . ofNullable ( node . getAttributes ( ) ) . map ( XQuery :: attributesToMap ) . map ( Collections :: unmodifiableMap ) . orElseGet ( Collections :: emptyMap ) ) ; } } return attrMap . get ( ) ; } | Returns a map of attributes . | 96 | 6 |
7,043 | private @ Nonnull NodeList evaluate ( String xpath ) { try { XPathExpression expr = xpf . newXPath ( ) . compile ( xpath ) ; return ( NodeList ) expr . evaluate ( node , XPathConstants . NODESET ) ; } catch ( XPathExpressionException ex ) { throw new IllegalArgumentException ( "Invalid XPath '" + xpath + "'" , ex ) ; } } | Evaluates the XPath expression and returns a list of nodes . | 94 | 14 |
7,044 | private @ Nonnull Optional < XQuery > findElement ( Function < Node , Node > iterator ) { Node it = node ; do { it = iterator . apply ( it ) ; } while ( it != null && ! ( it instanceof Element ) ) ; return Optional . ofNullable ( it ) . map ( XQuery :: new ) ; } | Finds an Element node by applying the iterator function until another Element was found . | 72 | 16 |
7,045 | @ Nonnull public DigestAuthServerBuilder setOpaque ( @ Nonnull final String sOpaque ) { if ( ! HttpStringHelper . isQuotedTextContent ( sOpaque ) ) throw new IllegalArgumentException ( "opaque is invalid: " + sOpaque ) ; m_sOpaque = sOpaque ; return this ; } | A string of data specified by the server which should be returned by the client unchanged in the Authorization header of subsequent requests with URIs in the same protection space . It is recommended that this string be base64 or hexadecimal data . | 81 | 48 |
7,046 | @ Nonnull public static String getRequestPathInfo ( @ Nullable final HttpServletRequest aRequest ) { String ret = null ; if ( aRequest != null ) try { // They may return null! if ( aRequest . isAsyncSupported ( ) && aRequest . isAsyncStarted ( ) ) ret = ( String ) aRequest . getAttribute ( AsyncContext . ASYNC_PATH_INFO ) ; else ret = aRequest . getPathInfo ( ) ; } catch ( final UnsupportedOperationException ex ) { // Offline request - fall through } catch ( final Exception ex ) { // fall through if ( isLogExceptions ( ) ) if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "[ServletHelper] Failed to determine path info of HTTP request" , ex ) ; } return ret == null ? "" : ret ; } | Get the path info of an request supporting sync and async requests . | 184 | 13 |
7,047 | @ Nonnull public static String getRequestRequestURI ( @ Nullable final HttpServletRequest aRequest ) { String ret = "" ; if ( aRequest != null ) try { if ( aRequest . isAsyncSupported ( ) && aRequest . isAsyncStarted ( ) ) ret = ( String ) aRequest . getAttribute ( AsyncContext . ASYNC_REQUEST_URI ) ; else ret = aRequest . getRequestURI ( ) ; } catch ( final Exception ex ) { // fall through if ( isLogExceptions ( ) ) if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "[ServletHelper] Failed to determine request URI of HTTP request" , ex ) ; } return ret ; } | Get the request URI of an request supporting sync and async requests . | 156 | 13 |
7,048 | @ Nonnull public static StringBuffer getRequestRequestURL ( @ Nullable final HttpServletRequest aRequest ) { StringBuffer ret = null ; if ( aRequest != null ) try { ret = aRequest . getRequestURL ( ) ; } catch ( final Exception ex ) { // fall through if ( isLogExceptions ( ) ) if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "[ServletHelper] Failed to determine request URL of HTTP request" , ex ) ; } return ret != null ? ret : new StringBuffer ( ) ; } | Get the request URL of an request supporting sync and async requests . | 121 | 13 |
7,049 | @ Nonnull public static String getRequestServletPath ( @ Nullable final HttpServletRequest aRequest ) { String ret = "" ; if ( aRequest != null ) try { if ( aRequest . isAsyncSupported ( ) && aRequest . isAsyncStarted ( ) ) ret = ( String ) aRequest . getAttribute ( AsyncContext . ASYNC_SERVLET_PATH ) ; else ret = aRequest . getServletPath ( ) ; } catch ( final UnsupportedOperationException ex ) { // Offline request - fall through } catch ( final Exception ex ) { // fall through if ( isLogExceptions ( ) ) if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "[ServletHelper] Failed to determine servlet path of HTTP request" , ex ) ; } return ret ; } | Get the servlet path of an request supporting sync and async requests . | 177 | 14 |
7,050 | @ Nonnull public BasicAuthServerBuilder setRealm ( @ Nonnull final String sRealm ) { ValueEnforcer . isTrue ( HttpStringHelper . isQuotedTextContent ( sRealm ) , ( ) -> "Realm is invalid: " + sRealm ) ; m_sRealm = sRealm ; return this ; } | Set the realm to be used . | 75 | 7 |
7,051 | public boolean contains ( String path ) { boolean result = false ; FileName fn = new FileName ( path ) ; if ( fn . getPath ( ) . startsWith ( getPath ( ) ) ) { result = true ; } return result ; } | This will check if the given path is part of the path which is represented by this instance . | 52 | 19 |
7,052 | public String getCurrentAttempt ( ) { if ( currentIndex < words . size ( ) ) { final String currentAttempt = words . get ( currentIndex ) ; return currentAttempt ; } return null ; } | Gets the current attempt . | 42 | 6 |
7,053 | public boolean process ( ) { boolean continueIterate = true ; boolean found = false ; String attempt = getCurrentAttempt ( ) ; while ( continueIterate ) { if ( attempt . equals ( toCheckAgainst ) ) { found = true ; break ; } attempt = getCurrentAttempt ( ) ; continueIterate = increment ( ) ; } return found ; } | Processes the word list . | 74 | 6 |
7,054 | @ Nullable public FailedMailData remove ( @ Nullable final String sID ) { if ( StringHelper . hasNoText ( sID ) ) return null ; return m_aRWLock . writeLocked ( ( ) -> internalRemove ( sID ) ) ; } | Remove the failed mail at the given index . | 57 | 9 |
7,055 | @ Nullable public static BasicAuthClientCredentials getBasicAuthClientCredentials ( @ Nullable final String sAuthHeader ) { final String sRealHeader = StringHelper . trim ( sAuthHeader ) ; if ( StringHelper . hasNoText ( sRealHeader ) ) return null ; final String [ ] aElements = RegExHelper . getSplitToArray ( sRealHeader , "\\s+" , 2 ) ; if ( aElements . length != 2 ) { if ( LOGGER . isErrorEnabled ( ) ) LOGGER . error ( "String is not Basic Auth: " + sRealHeader ) ; return null ; } if ( ! aElements [ 0 ] . equals ( HEADER_VALUE_PREFIX_BASIC ) ) { if ( LOGGER . isErrorEnabled ( ) ) LOGGER . error ( "String does not start with 'Basic': " + sRealHeader ) ; return null ; } // Apply Base64 decoding final String sEncodedCredentials = aElements [ 1 ] ; final String sUsernamePassword = Base64 . safeDecodeAsString ( sEncodedCredentials , CHARSET ) ; if ( sUsernamePassword == null ) { if ( LOGGER . isErrorEnabled ( ) ) LOGGER . error ( "Illegal Base64 encoded value '" + sEncodedCredentials + "'" ) ; return null ; } // Do we have a username/password separator? final int nIndex = sUsernamePassword . indexOf ( USERNAME_PASSWORD_SEPARATOR ) ; if ( nIndex >= 0 ) return new BasicAuthClientCredentials ( sUsernamePassword . substring ( 0 , nIndex ) , sUsernamePassword . substring ( nIndex + 1 ) ) ; return new BasicAuthClientCredentials ( sUsernamePassword ) ; } | Get the Basic authentication credentials from the passed HTTP header value . | 398 | 12 |
7,056 | public void onServletInit ( @ Nonnull final Class < ? extends GenericServlet > aServletClass ) { if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "onServletInit: " + aServletClass ) ; _updateStatus ( aServletClass , EServletStatus . INITED ) ; } | Invoked at the beginning of the servlet initialization . | 74 | 11 |
7,057 | public void onServletInvocation ( @ Nonnull final Class < ? extends GenericServlet > aServletClass ) { m_aRWLock . writeLocked ( ( ) -> _getOrCreateServletStatus ( aServletClass ) . internalIncrementInvocationCount ( ) ) ; } | Invoked at the beginning of a servlet invocation | 64 | 10 |
7,058 | @ Nonnull public static ENetworkPortStatus checkPortOpen ( @ Nonnull @ Nonempty final String sHostName , @ Nonnegative final int nPort , @ Nonnegative final int nTimeoutMillisecs ) { ValueEnforcer . notEmpty ( sHostName , "Hostname" ) ; ValueEnforcer . isGE0 ( nPort , "Port" ) ; ValueEnforcer . isGE0 ( nTimeoutMillisecs , "TimeoutMillisecs" ) ; LOGGER . info ( "Checking TCP port status for " + sHostName + ":" + nPort + " with timeouf of " + nTimeoutMillisecs + " ms" ) ; try ( final Socket aSocket = new Socket ( ) ) { aSocket . setReuseAddress ( true ) ; final SocketAddress aSocketAddr = new InetSocketAddress ( sHostName , nPort ) ; aSocket . connect ( aSocketAddr , nTimeoutMillisecs ) ; return ENetworkPortStatus . PORT_IS_OPEN ; } catch ( final IOException ex ) { // Can also be: // Connection refused: connect if ( ex . getMessage ( ) . startsWith ( "Connection refused" ) ) return ENetworkPortStatus . PORT_IS_CLOSED ; if ( ex instanceof java . net . UnknownHostException ) return ENetworkPortStatus . HOST_NOT_EXISTING ; if ( ex instanceof java . net . SocketTimeoutException ) return ENetworkPortStatus . CONNECTION_TIMEOUT ; if ( ex instanceof java . net . ConnectException ) { // E.g. for port 0 return ENetworkPortStatus . GENERIC_IO_ERROR ; } LOGGER . error ( "Other error checking TCP port status" , ex ) ; return ENetworkPortStatus . GENERIC_IO_ERROR ; } } | Check the status of a remote port . | 393 | 8 |
7,059 | @ Nonnull private static UserAgentElementList _decryptUserAgent ( @ Nonnull final String sUserAgent ) { final UserAgentElementList ret = new UserAgentElementList ( ) ; final StringScanner aSS = new StringScanner ( sUserAgent . trim ( ) ) ; while ( true ) { aSS . skipWhitespaces ( ) ; final int nIndex = aSS . findFirstIndex ( ' ' , ' ' , ' ' , ' ' ) ; if ( nIndex == - 1 ) break ; switch ( aSS . getCharAtIndex ( nIndex ) ) { case ' ' : { // e.g. "a/b" final String sKey = aSS . getUntilIndex ( nIndex ) ; final String sValue = aSS . skip ( 1 ) . getUntilWhiteSpace ( ) ; final String sFullValue = sKey + "/" + sValue ; // Special handling of URLs :) if ( URLProtocolRegistry . getInstance ( ) . hasKnownProtocol ( sFullValue ) ) ret . add ( sFullValue ) ; else ret . add ( Pair . create ( sKey , sValue ) ) ; break ; } case ' ' : { // e.g. "Opera 6.03" // e.g. "HTC_P3700 Opera/9.50 (Windows NT 5.1; U; de)" final String sText = aSS . getUntilIndex ( nIndex ) . trim ( ) ; final Matcher aMatcher = RegExHelper . getMatcher ( "([^\\s]+)\\s+([0-9]+\\.[0-9]+)" , sText ) ; if ( aMatcher . matches ( ) ) ret . add ( Pair . create ( aMatcher . group ( 1 ) , aMatcher . group ( 2 ) ) ) ; else ret . add ( sText ) ; break ; } case ' ' : { // e.g. "[en]" aSS . setIndex ( nIndex ) . skip ( 1 ) ; // skip incl. "[" ret . add ( aSS . getUntil ( ' ' ) ) ; aSS . skip ( 1 ) ; break ; } case ' ' : { // e.g. "(compatible; MSIE 5.0; Windows 2000)" aSS . setIndex ( nIndex ) . skip ( 1 ) ; // skip incl. "(" final String sParams = aSS . getUntilBalanced ( 1 , ' ' , ' ' ) ; // convert to ";" separated list final ICommonsList < String > aParams = StringHelper . getExploded ( ' ' , sParams ) ; ret . add ( aParams . getAllMapped ( String :: trim ) ) ; break ; } default : throw new IllegalStateException ( "Invalid character: " + aSS . getCharAtIndex ( nIndex ) ) ; } } // add all remaining parts as is final String sRest = aSS . getRest ( ) . trim ( ) ; if ( sRest . length ( ) > 0 ) ret . add ( sRest ) ; return ret ; } | Parse the passed user agent . | 665 | 7 |
7,060 | @ Nonnull public static IUserAgent decryptUserAgentString ( @ Nonnull final String sUserAgent ) { ValueEnforcer . notNull ( sUserAgent , "UserAgent" ) ; String sRealUserAgent = sUserAgent ; // Check if surrounded with '"' or ''' if ( sRealUserAgent . length ( ) >= 2 ) { final char cFirst = sRealUserAgent . charAt ( 0 ) ; if ( ( cFirst == ' ' || cFirst == ' ' ) && StringHelper . getLastChar ( sRealUserAgent ) == cFirst ) sRealUserAgent = sRealUserAgent . substring ( 1 , sRealUserAgent . length ( ) - 1 ) ; } // Skip a certain prefix that is known to occur frequently if ( sRealUserAgent . startsWith ( SKIP_PREFIX ) ) sRealUserAgent = sRealUserAgent . substring ( SKIP_PREFIX . length ( ) ) ; return new UserAgent ( sRealUserAgent , _decryptUserAgent ( sRealUserAgent ) ) ; } | Decrypt the passed user agent string . | 228 | 8 |
7,061 | @ Nullable public static PasswordAuthentication requestProxyPasswordAuthentication ( @ Nullable final String sHostName , @ Nullable final int nPort , @ Nullable final String sProtocol ) { return requestPasswordAuthentication ( sHostName , ( InetAddress ) null , nPort , sProtocol , ( String ) null , ( String ) null , ( URL ) null , RequestorType . PROXY ) ; } | Shortcut method for requesting proxy password authentication . This method can also be used if this class is NOT the default Authenticator . | 89 | 25 |
7,062 | public static < T > T get ( final Class < T > pageClass , final String ... params ) { cryIfNotAnnotated ( pageClass ) ; try { final String pageUrl = pageClass . getAnnotation ( Page . class ) . value ( ) ; return loadPage ( pageUrl , pageClass , Arrays . asList ( params ) ) ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } } | Loads content from url from the Page annotation on pageClass onto an instance of pageClass . | 94 | 19 |
7,063 | @ Nullable private ICommonsOrderedMap < String , RequestParamMapItem > _getChildMapExceptLast ( @ Nonnull @ Nonempty final String ... aPath ) { ValueEnforcer . notEmpty ( aPath , "Path" ) ; ICommonsOrderedMap < String , RequestParamMapItem > aMap = m_aMap ; // Until the second last object for ( int i = 0 ; i < aPath . length - 1 ; ++ i ) { aMap = _getChildMap ( aMap , aPath [ i ] ) ; if ( aMap == null ) return null ; } return aMap ; } | Iterate the root map down to the map specified by the passed path except for the last element . | 135 | 20 |
7,064 | @ Nonnull @ Nonempty @ Deprecated public static String getFieldName ( @ Nonnull @ Nonempty final String sBaseName ) { ValueEnforcer . notEmpty ( sBaseName , "BaseName" ) ; return sBaseName ; } | This method doesn t make sense but it should stay so that it s easy to spot usage of this invalid method . | 52 | 23 |
7,065 | public static void setSeparators ( final char cOpen , final char cClose ) { ValueEnforcer . isFalse ( cOpen == cClose , "Open and closing element may not be identical!" ) ; s_sOpen = Character . toString ( cOpen ) ; s_sClose = Character . toString ( cClose ) ; } | Set the separator chars to use . | 73 | 8 |
7,066 | public static void setSeparators ( @ Nonnull @ Nonempty final String sOpen , @ Nonnull @ Nonempty final String sClose ) { ValueEnforcer . notEmpty ( sOpen , "Open" ) ; ValueEnforcer . notEmpty ( sClose , "Close" ) ; ValueEnforcer . isFalse ( sOpen . contains ( sClose ) , "open may not contain close" ) ; ValueEnforcer . isFalse ( sClose . contains ( sOpen ) , "close may not contain open" ) ; s_sOpen = sOpen ; s_sClose = sClose ; } | Set the separators to use . | 128 | 7 |
7,067 | @ Nonnull public static SimpleURL getWithoutSessionID ( @ Nonnull final ISimpleURL aURL ) { ValueEnforcer . notNull ( aURL , "URL" ) ; // Strip the parameter from the path, but keep parameters and anchor intact! // Note: using URLData avoid parsing, since the data was already parsed! return new SimpleURL ( new URLData ( getWithoutSessionID ( aURL . getPath ( ) ) , aURL . params ( ) , aURL . getAnchor ( ) ) ) ; } | Get the passed string without an eventually contained session ID like in test . html ; JSESSIONID = 1234?param = value . | 113 | 27 |
7,068 | @ Nonnull public static String getPathWithinServletContext ( @ Nonnull final HttpServletRequest aHttpRequest ) { ValueEnforcer . notNull ( aHttpRequest , "HttpRequest" ) ; final String sRequestURI = getRequestURI ( aHttpRequest ) ; if ( StringHelper . hasNoText ( sRequestURI ) ) { // Can e.g. happen for "Request(GET //localhost:90/)" if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Having empty request URI '" + sRequestURI + "' from request " + aHttpRequest ) ; return "/" ; } // Always use the context path final String sContextPath = ServletContextPathHolder . getContextPath ( ) ; if ( StringHelper . hasNoText ( sContextPath ) || ! sRequestURI . startsWith ( sContextPath ) ) return sRequestURI ; // Normal case: URI contains context path. final String sPath = sRequestURI . substring ( sContextPath . length ( ) ) ; return sPath . length ( ) > 0 ? sPath : "/" ; } | Return the URI of the request within the servlet context . | 239 | 12 |
7,069 | @ Nullable public static EHttpVersion getHttpVersion ( @ Nonnull final HttpServletRequest aHttpRequest ) { ValueEnforcer . notNull ( aHttpRequest , "HttpRequest" ) ; final String sProtocol = aHttpRequest . getProtocol ( ) ; return EHttpVersion . getFromNameOrNull ( sProtocol ) ; } | Get the HTTP version associated with the given HTTP request | 76 | 10 |
7,070 | @ Nullable public static EHttpMethod getHttpMethod ( @ Nonnull final HttpServletRequest aHttpRequest ) { ValueEnforcer . notNull ( aHttpRequest , "HttpRequest" ) ; final String sMethod = aHttpRequest . getMethod ( ) ; return EHttpMethod . getFromNameOrNull ( sMethod ) ; } | Get the HTTP method associated with the given HTTP request | 73 | 10 |
7,071 | @ Nonnull @ ReturnsMutableCopy public static HttpHeaderMap getRequestHeaderMap ( @ Nonnull final HttpServletRequest aHttpRequest ) { ValueEnforcer . notNull ( aHttpRequest , "HttpRequest" ) ; final HttpHeaderMap ret = new HttpHeaderMap ( ) ; final Enumeration < String > aHeaders = aHttpRequest . getHeaderNames ( ) ; while ( aHeaders . hasMoreElements ( ) ) { final String sName = aHeaders . nextElement ( ) ; final Enumeration < String > eHeaderValues = aHttpRequest . getHeaders ( sName ) ; while ( eHeaderValues . hasMoreElements ( ) ) { final String sValue = eHeaderValues . nextElement ( ) ; ret . addHeader ( sName , sValue ) ; } } return ret ; } | Get a complete request header map as a copy . | 183 | 10 |
7,072 | @ Nullable public static X509Certificate [ ] getRequestClientCertificates ( @ Nonnull final HttpServletRequest aHttpRequest ) { return _getRequestAttr ( aHttpRequest , SERVLET_ATTR_CLIENT_CERTIFICATE , X509Certificate [ ] . class ) ; } | Get the client certificates provided by a HTTP servlet request . | 68 | 12 |
7,073 | @ Nullable public static String getHttpUserAgentStringFromRequest ( @ Nonnull final HttpServletRequest aHttpRequest ) { // Use non-standard headers first String sUserAgent = aHttpRequest . getHeader ( CHttpHeader . UA ) ; if ( sUserAgent == null ) { sUserAgent = aHttpRequest . getHeader ( CHttpHeader . X_DEVICE_USER_AGENT ) ; if ( sUserAgent == null ) sUserAgent = aHttpRequest . getHeader ( CHttpHeader . USER_AGENT ) ; } return sUserAgent ; } | Get the user agent from the given request . | 126 | 9 |
7,074 | @ Nonnull @ Nonempty public static String getCheckBoxHiddenFieldName ( @ Nonnull @ Nonempty final String sFieldName ) { ValueEnforcer . notEmpty ( sFieldName , "FieldName" ) ; return DEFAULT_CHECKBOX_HIDDEN_FIELD_PREFIX + sFieldName ; } | Get the name of the automatic hidden field associated with a check - box . | 68 | 15 |
7,075 | @ Nonnull public static Cookie createCookie ( @ Nonnull final String sName , @ Nullable final String sValue , final String sPath , final boolean bExpireWhenBrowserIsClosed ) { final Cookie aCookie = new Cookie ( sName , sValue ) ; aCookie . setPath ( sPath ) ; if ( bExpireWhenBrowserIsClosed ) aCookie . setMaxAge ( - 1 ) ; else aCookie . setMaxAge ( DEFAULT_MAX_AGE_SECONDS ) ; return aCookie ; } | Create a cookie that is bound on a certain path within the local web server . | 120 | 16 |
7,076 | public static void removeCookie ( @ Nonnull final HttpServletResponse aHttpResponse , @ Nonnull final Cookie aCookie ) { ValueEnforcer . notNull ( aHttpResponse , "HttpResponse" ) ; ValueEnforcer . notNull ( aCookie , "aCookie" ) ; // expire the cookie! aCookie . setMaxAge ( 0 ) ; aHttpResponse . addCookie ( aCookie ) ; } | Remove a cookie by setting the max age to 0 . | 95 | 11 |
7,077 | public static PrivateKey readPasswordProtectedPrivateKey ( final byte [ ] encryptedPrivateKeyBytes , final String password , final String algorithm ) throws IOException , NoSuchAlgorithmException , NoSuchPaddingException , InvalidKeySpecException , InvalidKeyException , InvalidAlgorithmParameterException { final EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo ( encryptedPrivateKeyBytes ) ; final String algName = encryptedPrivateKeyInfo . getAlgName ( ) ; final Cipher cipher = CipherFactory . newCipher ( algName ) ; final KeySpec pbeKeySpec = KeySpecFactory . newPBEKeySpec ( password ) ; final SecretKeyFactory secretKeyFactory = SecretKeyFactoryExtensions . newSecretKeyFactory ( algName ) ; final Key pbeKey = secretKeyFactory . generateSecret ( pbeKeySpec ) ; final AlgorithmParameters algParameters = encryptedPrivateKeyInfo . getAlgParameters ( ) ; cipher . init ( Cipher . DECRYPT_MODE , pbeKey , algParameters ) ; final KeySpec pkcs8KeySpec = encryptedPrivateKeyInfo . getKeySpec ( cipher ) ; final KeyFactory keyFactory = KeyFactory . getInstance ( algorithm ) ; return keyFactory . generatePrivate ( pkcs8KeySpec ) ; } | Reads the given byte array that contains a password protected private key . | 275 | 14 |
7,078 | @ Nonnull public static ServletAsyncSpec createAsync ( @ CheckForSigned final long nTimeoutMillis , @ Nullable final Iterable < ? extends AsyncListener > aAsyncListeners ) { return new ServletAsyncSpec ( true , nTimeoutMillis , aAsyncListeners ) ; } | Create an async spec . | 64 | 5 |
7,079 | protected OutputStream initOutput ( final File file ) throws MojoExecutionException { // stream to return final OutputStream stream ; // plenty of things can go wrong... try { // directory? if ( file . isDirectory ( ) ) { throw new MojoExecutionException ( "File " + file . getAbsolutePath ( ) + " is directory!" ) ; } // already exists && can't remove it? if ( file . exists ( ) && ! file . delete ( ) ) { throw new MojoExecutionException ( "Could not remove file: " + file . getAbsolutePath ( ) ) ; } // get directory above file file final File fileDirectory = file . getParentFile ( ) ; // does not exist && create it? if ( ! fileDirectory . exists ( ) && ! fileDirectory . mkdirs ( ) ) { throw new MojoExecutionException ( "Could not create directory: " + fileDirectory . getAbsolutePath ( ) ) ; } // moar wtf: parent directory is no directory? if ( ! fileDirectory . isDirectory ( ) ) { throw new MojoExecutionException ( "Not a directory: " + fileDirectory . getAbsolutePath ( ) ) ; } // file file is for any reason not creatable? if ( ! file . createNewFile ( ) ) { throw new MojoExecutionException ( "Could not create file: " + file . getAbsolutePath ( ) ) ; } // finally create some file stream = new FileOutputStream ( file ) ; } catch ( FileNotFoundException e ) { throw new MojoExecutionException ( "Could not find file: " + file . getAbsolutePath ( ) , e ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "Could not write to file: " + file . getAbsolutePath ( ) , e ) ; } // return return stream ; } | Opens an OutputStream based on the supplied file | 403 | 10 |
7,080 | protected InputStream initInput ( final File file ) throws MojoExecutionException { InputStream stream = null ; try { if ( file . isDirectory ( ) ) { throw new MojoExecutionException ( "File " + file . getAbsolutePath ( ) + " is directory!" ) ; } if ( ! file . exists ( ) ) { throw new MojoExecutionException ( "File " + file . getAbsolutePath ( ) + " does not exist!" ) ; } stream = new FileInputStream ( file ) ; //append to outfile here } catch ( FileNotFoundException e ) { throw new MojoExecutionException ( "Could not find file: " + file . getAbsolutePath ( ) , e ) ; } return stream ; } | Opens an InputStream based on the supplied file | 161 | 10 |
7,081 | protected void appendStream ( final InputStream input , final OutputStream output ) throws MojoExecutionException { // prebuffer int character ; try { // get line seperator, based on system final String newLine = System . getProperty ( "line.separator" ) ; // read & write while ( ( character = input . read ( ) ) != - 1 ) { output . write ( character ) ; } // append newline output . write ( newLine . getBytes ( ) ) ; // flush output . flush ( ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "Error in buffering/writing " + e . getMessage ( ) , e ) ; } } | Appends inputstream to outputstream | 148 | 7 |
7,082 | @ Override protected void onThresholdReached ( ) throws IOException { FileOutputStream aFOS = null ; try { aFOS = new FileOutputStream ( m_aOutputFile ) ; m_aMemoryOS . writeTo ( aFOS ) ; m_aCurrentOS = aFOS ; // Explicitly close the stream (even though this is a no-op) StreamHelper . close ( m_aMemoryOS ) ; m_aMemoryOS = null ; } catch ( final IOException ex ) { StreamHelper . close ( aFOS ) ; throw ex ; } } | Switches the underlying output stream from a memory based stream to one that is backed by disk . This is the point at which we realise that too much data is being written to keep in memory so we elect to switch to disk - based storage . | 127 | 49 |
7,083 | public void writeTo ( @ Nonnull @ WillNotClose final OutputStream aOS ) throws IOException { // we may only need to check if this is closed if we are working with a file // but we should force the habit of closing whether we are working with // a file or memory. if ( ! m_bClosed ) throw new IOException ( "This stream is not closed" ) ; if ( isInMemory ( ) ) { m_aMemoryOS . writeTo ( aOS ) ; } else { final InputStream aIS = FileHelper . getInputStream ( m_aOutputFile ) ; StreamHelper . copyInputStreamToOutputStream ( aIS , aOS ) ; } } | Writes the data from this output stream to the specified output stream after it has been closed . | 147 | 19 |
7,084 | public static VertexData generatePlane ( Vector2f size ) { final VertexData destination = new VertexData ( ) ; final VertexAttribute positionsAttribute = new VertexAttribute ( "positions" , DataType . FLOAT , 3 ) ; destination . addAttribute ( 0 , positionsAttribute ) ; final TFloatList positions = new TFloatArrayList ( ) ; final VertexAttribute normalsAttribute = new VertexAttribute ( "normals" , DataType . FLOAT , 3 ) ; destination . addAttribute ( 1 , normalsAttribute ) ; final TFloatList normals = new TFloatArrayList ( ) ; final VertexAttribute textureCoordsAttribute = new VertexAttribute ( "textureCoords" , DataType . FLOAT , 2 ) ; destination . addAttribute ( 2 , textureCoordsAttribute ) ; final TFloatList textureCoords = new TFloatArrayList ( ) ; final TIntList indices = destination . getIndices ( ) ; // Generate the mesh generatePlane ( positions , normals , textureCoords , indices , size ) ; // Put the mesh in the vertex data positionsAttribute . setData ( positions ) ; normalsAttribute . setData ( normals ) ; textureCoordsAttribute . setData ( textureCoords ) ; return destination ; } | Generates a plane on xy . The center is at the middle of the plane . | 282 | 18 |
7,085 | public static void generatePlane ( TFloatList positions , TFloatList normals , TFloatList textureCoords , TIntList indices , Vector2f size ) { /* * 2-----3 * | | * | | * 0-----1 */ // Corner positions final Vector2f p = size . div ( 2 ) ; final Vector3f p3 = new Vector3f ( p . getX ( ) , p . getY ( ) , 0 ) ; final Vector3f p2 = new Vector3f ( - p . getX ( ) , p . getY ( ) , 0 ) ; final Vector3f p1 = new Vector3f ( p . getX ( ) , - p . getY ( ) , 0 ) ; final Vector3f p0 = new Vector3f ( - p . getX ( ) , - p . getY ( ) , 0 ) ; // Normal final Vector3f n = new Vector3f ( 0 , 0 , 1 ) ; // Face addVector ( positions , p0 ) ; addVector ( normals , n ) ; addAll ( textureCoords , 0 , 0 ) ; addVector ( positions , p1 ) ; addVector ( normals , n ) ; addAll ( textureCoords , 1 , 0 ) ; addVector ( positions , p2 ) ; addVector ( normals , n ) ; addAll ( textureCoords , 0 , 1 ) ; addVector ( positions , p3 ) ; addVector ( normals , n ) ; addAll ( textureCoords , 1 , 1 ) ; addAll ( indices , 0 , 3 , 2 , 0 , 1 , 3 ) ; } | Generates a textured plane on xy . The center is at the middle of the plane . | 352 | 20 |
7,086 | public static void generateCylinder ( TFloatList positions , TFloatList normals , TIntList indices , float radius , float height ) { // 0,0,0 will be halfway up the cylinder in the middle final float halfHeight = height / 2 ; // The positions at the rims of the cylinders final List < Vector3f > rims = new ArrayList <> ( ) ; for ( int angle = 0 ; angle < 360 ; angle += 15 ) { final double angleRads = Math . toRadians ( angle ) ; rims . add ( new Vector3f ( radius * TrigMath . cos ( angleRads ) , halfHeight , radius * - TrigMath . sin ( angleRads ) ) ) ; } // The normals for the triangles of the top and bottom faces final Vector3f topNormal = new Vector3f ( 0 , 1 , 0 ) ; final Vector3f bottomNormal = new Vector3f ( 0 , - 1 , 0 ) ; // Add the top and bottom face center vertices addVector ( positions , new Vector3f ( 0 , halfHeight , 0 ) ) ; // 0 addVector ( normals , topNormal ) ; addVector ( positions , new Vector3f ( 0 , - halfHeight , 0 ) ) ; // 1 addVector ( normals , bottomNormal ) ; // Add all the faces section by section, turning around the y axis final int rimsSize = rims . size ( ) ; for ( int i = 0 ; i < rimsSize ; i ++ ) { // Get the top and bottom vertex positions and the side normal final Vector3f t = rims . get ( i ) ; final Vector3f b = new Vector3f ( t . getX ( ) , - t . getY ( ) , t . getZ ( ) ) ; final Vector3f n = new Vector3f ( t . getX ( ) , 0 , t . getZ ( ) ) . normalize ( ) ; // Top face vertex addVector ( positions , t ) ; // index addVector ( normals , topNormal ) ; // Bottom face vertex addVector ( positions , b ) ; // index + 1 addVector ( normals , bottomNormal ) ; // Side top vertex addVector ( positions , t ) ; // index + 2 addVector ( normals , n ) ; // Side bottom vertex addVector ( positions , b ) ; // index + 3 addVector ( normals , n ) ; // Get the current index for our vertices final int currentIndex = i * 4 + 2 ; // Get the index for the next iteration, wrapping around at the end final int nextIndex = ( i == rimsSize - 1 ? 0 : i + 1 ) * 4 + 2 ; // Add the 4 triangles (1 top, 1 bottom, 2 for the side) addAll ( indices , 0 , currentIndex , nextIndex ) ; addAll ( indices , 1 , nextIndex + 1 , currentIndex + 1 ) ; addAll ( indices , currentIndex + 2 , currentIndex + 3 , nextIndex + 2 ) ; addAll ( indices , currentIndex + 3 , nextIndex + 3 , nextIndex + 2 ) ; } } | Generates a cylindrical solid mesh . The center is at middle of the of the cylinder . | 673 | 20 |
7,087 | @ Nonnull public EChange setFrom ( @ Nonnull final MockEventListenerList aList ) { ValueEnforcer . notNull ( aList , "List" ) ; // Assigning this to this? if ( this == aList ) return EChange . UNCHANGED ; // Get all listeners to assign final ICommonsList < EventListener > aOtherListeners = aList . getAllListeners ( ) ; return m_aRWLock . writeLocked ( ( ) -> { if ( m_aListener . isEmpty ( ) && aOtherListeners . isEmpty ( ) ) return EChange . UNCHANGED ; m_aListener . setAll ( aOtherListeners ) ; return EChange . CHANGED ; } ) ; } | Set all listeners from the passed list to this list | 161 | 10 |
7,088 | @ Nonnull public EChange addListener ( @ Nonnull final EventListener aListener ) { ValueEnforcer . notNull ( aListener , "Listener" ) ; // Small consistency check if ( ! ( aListener instanceof ServletContextListener ) && ! ( aListener instanceof HttpSessionListener ) && ! ( aListener instanceof ServletRequestListener ) ) { LOGGER . warn ( "Passed mock listener is none of ServletContextListener, HttpSessionListener or ServletRequestListener and therefore has no effect. The listener class is: " + aListener . getClass ( ) ) ; } return m_aRWLock . writeLocked ( ( ) -> EChange . valueOf ( m_aListener . add ( aListener ) ) ) ; } | Add a new listener . | 161 | 5 |
7,089 | public static void forEachURLSet ( @ Nonnull final Consumer < ? super XMLSitemapURLSet > aConsumer ) { ValueEnforcer . notNull ( aConsumer , "Consumer" ) ; for ( final IXMLSitemapProviderSPI aSPI : s_aProviders ) { final XMLSitemapURLSet aURLSet = aSPI . createURLSet ( ) ; aConsumer . accept ( aURLSet ) ; } } | Create URL sets from every provider and invoke the provided consumer with it . | 103 | 14 |
7,090 | public Matrix4f getViewMatrix ( ) { if ( updateViewMatrix ) { rotationMatrixInverse = Matrix4f . createRotation ( rotation ) ; final Matrix4f rotationMatrix = Matrix4f . createRotation ( rotation . invert ( ) ) ; final Matrix4f positionMatrix = Matrix4f . createTranslation ( position . negate ( ) ) ; viewMatrix = rotationMatrix . mul ( positionMatrix ) ; updateViewMatrix = false ; } return viewMatrix ; } | Returns the view matrix which is the transformation matrix for the position and rotation . | 101 | 15 |
7,091 | public static Camera createPerspective ( float fieldOfView , int windowWidth , int windowHeight , float near , float far ) { return new Camera ( Matrix4f . createPerspective ( fieldOfView , ( float ) windowWidth / windowHeight , near , far ) ) ; } | Creates a new camera with a standard perspective projection matrix . | 61 | 12 |
7,092 | public static X509Certificate readPemCertificate ( final File file ) throws IOException , CertificateException { final String privateKeyAsString = readPemFileAsBase64 ( file ) ; final byte [ ] decoded = new Base64 ( ) . decode ( privateKeyAsString ) ; return readCertificate ( decoded ) ; } | Read pem certificate . | 72 | 5 |
7,093 | @ OverrideOnDemand protected boolean isLogRequest ( @ Nonnull final HttpServletRequest aHttpRequest , @ Nonnull final HttpServletResponse aHttpResponse ) { boolean bLog = isGloballyEnabled ( ) && m_aLogger . isInfoEnabled ( ) ; if ( bLog ) { // Check for excluded path final String sRequestURI = ServletHelper . getRequestRequestURI ( aHttpRequest ) ; for ( final String sExcludedPath : m_aExcludedPaths ) if ( sRequestURI . startsWith ( sExcludedPath ) ) { bLog = false ; break ; } } return bLog ; } | Check if this request should be logged or not . | 140 | 10 |
7,094 | @ Nonnull public CloseableHttpResponse execute ( @ Nonnull final HttpUriRequest aRequest ) throws IOException { return execute ( aRequest , ( HttpContext ) null ) ; } | Execute the provided request without any special context . Caller is responsible for consuming the response correctly! | 41 | 19 |
7,095 | @ Nonnull public CloseableHttpResponse execute ( @ Nonnull final HttpUriRequest aRequest , @ Nullable final HttpContext aHttpContext ) throws IOException { checkIfClosed ( ) ; HttpDebugger . beforeRequest ( aRequest , aHttpContext ) ; CloseableHttpResponse ret = null ; Throwable aCaughtException = null ; try { ret = m_aHttpClient . execute ( aRequest , aHttpContext ) ; return ret ; } catch ( final IOException ex ) { aCaughtException = ex ; throw ex ; } finally { HttpDebugger . afterRequest ( aRequest , ret , aCaughtException ) ; } } | Execute the provided request with an optional special context . Caller is responsible for consuming the response correctly! | 143 | 20 |
7,096 | @ Nullable public < T > T execute ( @ Nonnull final HttpUriRequest aRequest , @ Nonnull final ResponseHandler < T > aResponseHandler ) throws IOException { return execute ( aRequest , ( HttpContext ) null , aResponseHandler ) ; } | Execute the provided request without any special context . The response handler is invoked as a callback . This method automatically cleans up all used resources and as such is preferred over the execute methods returning the CloseableHttpResponse . | 58 | 43 |
7,097 | @ Nonnull public static EChange setMailQueueSize ( @ Nonnegative final int nMaxMailQueueLen , @ Nonnegative final int nMaxMailSendCount ) { ValueEnforcer . isGT0 ( nMaxMailQueueLen , "MaxMailQueueLen" ) ; ValueEnforcer . isGT0 ( nMaxMailSendCount , "MaxMailSendCount" ) ; ValueEnforcer . isTrue ( nMaxMailQueueLen >= nMaxMailSendCount , ( ) -> "MaxMailQueueLen (" + nMaxMailQueueLen + ") must be >= than MaxMailSendCount (" + nMaxMailSendCount + ")" ) ; return s_aRWLock . writeLocked ( ( ) -> { if ( nMaxMailQueueLen == s_nMaxMailQueueLen && nMaxMailSendCount == s_nMaxMailSendCount ) return EChange . UNCHANGED ; s_nMaxMailQueueLen = nMaxMailQueueLen ; s_nMaxMailSendCount = nMaxMailSendCount ; return EChange . CHANGED ; } ) ; } | Set mail queue settings . Changing these settings has no effect on existing mail queues! | 230 | 16 |
7,098 | @ Nonnull public static EChange setUseSSL ( final boolean bUseSSL ) { return s_aRWLock . writeLocked ( ( ) -> { if ( s_bUseSSL == bUseSSL ) return EChange . UNCHANGED ; s_bUseSSL = bUseSSL ; return EChange . CHANGED ; } ) ; } | Use SSL by default? | 76 | 5 |
7,099 | @ Nonnull public static EChange setUseSTARTTLS ( final boolean bUseSTARTTLS ) { return s_aRWLock . writeLocked ( ( ) -> { if ( s_bUseSTARTTLS == bUseSTARTTLS ) return EChange . UNCHANGED ; s_bUseSTARTTLS = bUseSTARTTLS ; return EChange . CHANGED ; } ) ; } | Use STARTTLS by default? | 94 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.