idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
16,000
public Traverson startWith ( final HalRepresentation resource ) { this . startWith = null ; this . lastResult = singletonList ( requireNonNull ( resource ) ) ; Optional < Link > self = resource . getLinks ( ) . getLinkBy ( "self" ) ; if ( self . isPresent ( ) ) { this . contextUrl = linkToUrl ( self . get ( ) ) ; } els...
Start traversal at the given HAL resource .
16,001
private static Link resolve ( final URL contextUrl , final Link link ) { if ( link != null && link . isTemplated ( ) ) { final String msg = "Link must not be templated" ; LOG . error ( msg ) ; throw new IllegalStateException ( msg ) ; } if ( link == null ) { return self ( contextUrl . toString ( ) ) ; } else { return c...
Resolved a link using the URL of the current resource and returns it as an absolute Link .
16,002
private void checkState ( ) { if ( startWith == null && lastResult == null ) { final String msg = "Please call startWith(uri) first." ; LOG . error ( msg ) ; throw new IllegalStateException ( msg ) ; } }
Checks the current state of the Traverson .
16,003
public Client build ( final ZipkinClientConfiguration configuration ) { final Client client = new JerseyClientBuilder ( environment ) . using ( configuration ) . build ( configuration . getServiceName ( ) ) ; return build ( client ) ; }
Build a new Jersey Client that is instrumented for Zipkin
16,004
public Client build ( final Client client ) { client . register ( TracingClientFilter . create ( tracing ) ) ; return client ; }
Instrument an existing Jersey client
16,005
public CreateResponse create ( ) throws IOException , PlivoRestException { validate ( ) ; Response < CreateResponse > response = obtainCall ( ) . execute ( ) ; handleResponse ( response ) ; return response . body ( ) ; }
Actually create an instance of the resource .
16,006
private static void getAccountInfo ( ) { try { Account response = Account . getter ( ) . get ( ) ; System . out . println ( response ) ; } catch ( PlivoRestException | IOException e ) { e . printStackTrace ( ) ; } }
trying to get account info without setting the client
16,007
private static void getAccountInfoBySettingClient ( ) { try { Account response = Account . getter ( ) . client ( client ) . get ( ) ; System . out . println ( response ) ; } catch ( PlivoRestException | IOException e ) { e . printStackTrace ( ) ; } }
trying to get account info by setting the client
16,008
private static void modifyAccountBySettingClient ( ) { try { AccountUpdateResponse response = Account . updater ( ) . city ( "Test city" ) . client ( client ) . update ( ) ; System . out . println ( response ) ; } catch ( PlivoRestException | IOException e ) { e . printStackTrace ( ) ; } }
update account with different client settings
16,009
private static void createSubAccountBySettingClient ( ) { try { SubaccountCreateResponse subaccount = Subaccount . creator ( "Test 2" ) . enabled ( true ) . client ( client ) . create ( ) ; System . out . println ( subaccount ) ; } catch ( PlivoRestException | IOException e ) { e . printStackTrace ( ) ; } }
create subaccount with different client settings
16,010
public void delete ( ) throws IOException , PlivoRestException { validate ( ) ; Response < ResponseBody > response = obtainCall ( ) . execute ( ) ; handleResponse ( response ) ; }
Actually delete the resource .
16,011
public T update ( ) throws IOException , PlivoRestException { validate ( ) ; Response < T > response = obtainCall ( ) . execute ( ) ; handleResponse ( response ) ; return response . body ( ) ; }
Actually update the resource .
16,012
public ListResponse < T > list ( ) throws IOException , PlivoRestException { validate ( ) ; Response < ListResponse < T > > response = obtainCall ( ) . execute ( ) ; handleResponse ( response ) ; return response . body ( ) ; }
Actually list instances of the resource .
16,013
protected Result check ( ) throws Exception { final ClusterHealthStatus status = client . admin ( ) . cluster ( ) . prepareHealth ( ) . get ( ) . getStatus ( ) ; if ( status == ClusterHealthStatus . RED || ( failOnYellow && status == ClusterHealthStatus . YELLOW ) ) { return Result . unhealthy ( "Last status: %s" , sta...
Perform a check of the Elasticsearch cluster health .
16,014
public static void i ( String s , Throwable t ) { log ( Level . INFO , s , t ) ; }
Log an INFO message and the exception
16,015
public static void w ( String s , Throwable t ) { log ( Level . WARNING , s , t ) ; }
Log a WARNING message and the exception
16,016
public static byte [ ] fromHex ( String hex ) { char [ ] c = hex . toCharArray ( ) ; byte [ ] b = new byte [ c . length / 2 ] ; for ( int i = 0 ; i < b . length ; i ++ ) { b [ i ] = ( byte ) ( HEX_DECODE_CHAR [ c [ i * 2 ] & 0xFF ] * 16 + HEX_DECODE_CHAR [ c [ i * 2 + 1 ] & 0xFF ] ) ; } return b ; }
Decode from hexadecimal
16,017
public static String toHexUpper ( byte [ ] b , int off , int len ) { return toHex ( b , off , len , HEX_UPPER_CHAR ) ; }
Encode to uppercase hexadecimal
16,018
public static String toHexLower ( byte [ ] b , int off , int len ) { return toHex ( b , off , len , HEX_LOWER_CHAR ) ; }
Encode to lowercase hexadecimal
16,019
public static byte [ ] add ( byte [ ] b1 , int off1 , int len1 , byte [ ] b2 , int off2 , int len2 ) { byte [ ] b = new byte [ len1 + len2 ] ; System . arraycopy ( b1 , off1 , b , 0 , len1 ) ; System . arraycopy ( b2 , off2 , b , len1 , len2 ) ; return b ; }
Concatenate 2 byte arrays
16,020
public static byte [ ] sub ( byte [ ] b , int off , int len ) { byte [ ] result = new byte [ len ] ; System . arraycopy ( b , off , result , 0 , len ) ; return result ; }
Truncate and keep middle part of a byte array
16,021
public static synchronized void chdir ( String path ) { if ( path != null ) { rootDir = new File ( getAbsolutePath ( path ) ) . getAbsolutePath ( ) ; } }
Change the current folder
16,022
public static void closeLogger ( Logger logger ) { for ( Handler handler : logger . getHandlers ( ) ) { logger . removeHandler ( handler ) ; handler . close ( ) ; } }
Close a logger
16,023
public static List < String > getClasses ( String ... packageNames ) { List < String > classes = new ArrayList < > ( ) ; for ( String packageName : packageNames ) { String packagePath = packageName . replace ( '.' , '/' ) ; URL url = Conf . class . getResource ( "/" + packagePath ) ; if ( url == null ) { return classes...
Traverse all classes under given packages
16,024
public Entry borrow ( ) throws E { long now = System . currentTimeMillis ( ) ; if ( timeout > 0 ) { long accessed_ = accessed . get ( ) ; if ( now > accessed_ + Time . SECOND && accessed . compareAndSet ( accessed_ , now ) ) { Entry entry ; while ( ( entry = deque . pollLast ( ) ) != null ) { if ( now < entry . borrowe...
Borrow an object from the pool or create a new object if no valid objects in the pool
16,025
public void await ( ) { if ( interrupted . get ( ) ) { return ; } try { mainLatch . await ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } }
Wait until a proper shutdown command is received then return .
16,026
public T get ( ) throws E { T result = object ; if ( object == null ) { synchronized ( this ) { result = object ; if ( object == null ) { object = result = initializer . get ( ) ; } } } return result ; }
Create or get the instance .
16,027
public void close ( ) { synchronized ( this ) { if ( object != null ) { T object_ = object ; object = null ; try { finalizer . accept ( object_ ) ; } catch ( Exception e ) { } } } }
Close the lazy factory and destroy the instance if created .
16,028
public ByteArrayQueue add ( byte [ ] b , int off , int len ) { int newLength = addLength ( len ) ; System . arraycopy ( b , off , array , offset + length , len ) ; length = newLength ; return this ; }
Adds a sequence of bytes into the tail of the queue .
16,029
public ByteArrayQueue add ( int b ) { int newLength = addLength ( 1 ) ; array [ offset + length ] = ( byte ) b ; length = newLength ; return this ; }
Adds one byte into the tail of the queue .
16,030
public ByteArrayQueue remove ( byte [ ] b , int off , int len ) { System . arraycopy ( array , offset , b , off , len ) ; return remove ( len ) ; }
Retrieves a sequence of bytes from the head of the queue .
16,031
public ByteArrayQueue remove ( int len ) { offset += len ; length -= len ; if ( length == 0 && array . length > 1024 ) { array = new byte [ 32 ] ; offset = 0 ; shared = false ; } return this ; }
Removes a sequence of bytes from the head of the queue .
16,032
public List < String > escapePiecesForUri ( final List < String > pieces ) { final List < String > escapedPieces = new ArrayList < > ( pieces . size ( ) ) ; for ( final String piece : pieces ) { final String escaped = escapeForUri ( piece ) ; escapedPieces . add ( escaped ) ; } return escapedPieces ; }
Do a poor man s URI escaping . We aren t terribly interested in precision here or in introducing a library that would do it better .
16,033
public void addIds ( Collection < String > ids ) { if ( this . ids == null ) { this . ids = new ArrayList < > ( ids ) ; } else { this . ids . retainAll ( ids ) ; if ( this . ids . isEmpty ( ) ) { LOGGER . warn ( "No ids remain after addIds. All elements will be filtered out." ) ; } } }
When called the first time all ids are added to the filter . When called two or more times the provided id s are and ed with the those provided in the previous lists .
16,034
private static void forceInit ( Class < ? > cls ) { try { Class . forName ( cls . getName ( ) , true , cls . getClassLoader ( ) ) ; } catch ( ClassNotFoundException e ) { throw new IllegalArgumentException ( "Can't initialize class " + cls , e ) ; } }
Force initialization of the static members . As of Java 5 referencing a class doesn t force it to initialize . Since this class requires that the classes be initialized to declare their comparators we force that initialization to happen .
16,035
public static int readInt ( byte [ ] bytes , int start ) { return ( ( ( bytes [ start ] & 0xff ) << 24 ) + ( ( bytes [ start + 1 ] & 0xff ) << 16 ) + ( ( bytes [ start + 2 ] & 0xff ) << 8 ) + ( ( bytes [ start + 3 ] & 0xff ) ) ) ; }
Parse an integer from a byte array .
16,036
public static long readLong ( byte [ ] bytes , int start ) { return ( ( long ) ( readInt ( bytes , start ) ) << 32 ) + ( readInt ( bytes , start + 4 ) & 0xFFFFFFFFL ) ; }
Parse a long from a byte array .
16,037
public static long readVLong ( byte [ ] bytes , int start ) throws IOException { int len = bytes [ start ] ; if ( len >= - 112 ) { return len ; } boolean isNegative = ( len < - 120 ) ; len = isNegative ? - ( len + 120 ) : - ( len + 112 ) ; if ( start + 1 + len > bytes . length ) { throw new IOException ( "Not enough nu...
Reads a zero - compressed encoded long from a byte array and returns it .
16,038
public static String getVertexId ( Value value ) { byte [ ] buffer = value . get ( ) ; int offset = 0 ; int strLen = readInt ( buffer , offset ) ; offset += 4 ; if ( strLen > 0 ) { offset += strLen ; } strLen = readInt ( buffer , offset ) ; return readString ( buffer , offset , strLen ) ; }
fast access method to avoid creating a new instance of an EdgeInfo
16,039
public static < T > boolean intersectsAll ( T [ ] a1 , T [ ] a2 ) { for ( T anA1 : a1 ) { if ( ! contains ( a2 , anA1 ) ) { return false ; } } for ( T anA2 : a2 ) { if ( ! contains ( a1 , anA2 ) ) { return false ; } } return true ; }
Determines if all values in a1 appear in a2 and that all values in a2 appear in a2 .
16,040
public static byte [ ] decode ( String chars ) { if ( chars == null || chars . length ( ) == 0 ) { throw new IllegalArgumentException ( "You must provide a non-zero length input" ) ; } BigDecimal decodedLength = BigDecimal . valueOf ( chars . length ( ) ) . multiply ( BigDecimal . valueOf ( 4 ) ) . divide ( BigDecimal ...
This is a very simple base85 decoder . It respects the z optimization for empty chunks and strips whitespace between characters to respect line limits .
16,041
public int compareTo ( ByteSequence obs ) { if ( isBackedByArray ( ) && obs . isBackedByArray ( ) ) { return WritableComparator . compareBytes ( getBackingArray ( ) , offset ( ) , length ( ) , obs . getBackingArray ( ) , obs . offset ( ) , obs . length ( ) ) ; } return compareBytes ( this , obs ) ; }
Compares this byte sequence to another .
16,042
public static GeoPoint calculateCenter ( List < GeoPoint > geoPoints ) { checkNotNull ( geoPoints , "geoPoints cannot be null" ) ; checkArgument ( geoPoints . size ( ) > 0 , "must have at least 1 geoPoints" ) ; if ( geoPoints . size ( ) == 1 ) { return geoPoints . get ( 0 ) ; } double x = 0.0 ; double y = 0.0 ; double ...
For large distances center point calculation has rounding errors
16,043
public static byte [ ] escape ( byte [ ] auth , boolean quote ) { int escapeCount = 0 ; for ( int i = 0 ; i < auth . length ; i ++ ) { if ( auth [ i ] == '"' || auth [ i ] == '\\' ) { escapeCount ++ ; } } if ( escapeCount > 0 || quote ) { byte [ ] escapedAuth = new byte [ auth . length + escapeCount + ( quote ? 2 : 0 )...
Properly escapes an authorization string . The string can be quoted if desired .
16,044
public static byte [ ] quote ( byte [ ] term ) { boolean needsQuote = false ; for ( int i = 0 ; i < term . length ; i ++ ) { if ( ! Authorizations . isValidAuthChar ( term [ i ] ) ) { needsQuote = true ; break ; } } if ( ! needsQuote ) { return term ; } return VisibilityEvaluator . escape ( term , true ) ; }
Properly quotes terms in a column visibility expression . If no quoting is needed then nothing is done .
16,045
public static int hash32 ( byte [ ] data , int length , int seed ) { int hash = seed ; final int nblocks = length >> 2 ; for ( int i = 0 ; i < nblocks ; i ++ ) { int i_4 = i << 2 ; int k = ( data [ i_4 ] & 0xff ) | ( ( data [ i_4 + 1 ] & 0xff ) << 8 ) | ( ( data [ i_4 + 2 ] & 0xff ) << 16 ) | ( ( data [ i_4 + 3 ] & 0xf...
Murmur3 32 - bit variant .
16,046
public static long hash64 ( byte [ ] data , int offset , int length , int seed ) { long hash = seed ; final int nblocks = length >> 3 ; for ( int i = 0 ; i < nblocks ; i ++ ) { final int i8 = i << 3 ; long k = ( ( long ) data [ offset + i8 ] & 0xff ) | ( ( ( long ) data [ offset + i8 + 1 ] & 0xff ) << 8 ) | ( ( ( long ...
Murmur3 64 - bit variant . This is essentially MSB 8 bytes of Murmur3 128 - bit variant .
16,047
protected boolean hasValidFile ( Artifact artifact ) { boolean hasValidFile = artifact != null && artifact . getFile ( ) != null && artifact . getFile ( ) . exists ( ) ; hasValidFile = hasValidFile && ! artifact . getFile ( ) . getPath ( ) . equals ( project . getFile ( ) . getPath ( ) ) ; hasValidFile = hasValidFile &...
Decide whether the artifact file should be processed .
16,048
private Map < String , Map < String , String > > readSummaryFile ( File outputFile ) throws ExecutionException { List < String > algorithms = new ArrayList < String > ( ) ; Map < String , Map < String , String > > filesHashcodes = new HashMap < String , Map < String , String > > ( ) ; BufferedReader reader = null ; try...
Read the summary file
16,049
private void sync ( final DirContext ctx , final AlpineQueryManager qm , final LdapConnectionWrapper ldap , LdapUser user ) throws NamingException { LOGGER . debug ( "Syncing: " + user . getUsername ( ) ) ; final SearchResult result = ldap . searchForSingleUsername ( ctx , user . getUsername ( ) ) ; if ( result != null...
Performs the actual sync of the specified user .
16,050
public static int determineNumberOfWorkerThreads ( ) { final int threads = Config . getInstance ( ) . getPropertyAsInt ( Config . AlpineKey . WORKER_THREADS ) ; if ( threads > 0 ) { return threads ; } else if ( threads == 0 ) { final int cores = SystemUtil . getCpuCores ( ) ; final int multiplier = Config . getInstance...
Calculates the number of worker threads to use . Minimum return value is 1 .
16,051
protected final List < ValidationError > contOnValidationError ( final Set < ConstraintViolation < Object > > ... violationsArray ) { final List < ValidationError > errors = new ArrayList < > ( ) ; for ( final Set < ConstraintViolation < Object > > violations : violationsArray ) { for ( final ConstraintViolation violat...
Accepts the result from one of the many validation methods available and returns a List of ValidationErrors . If the size of the List is 0 no errors were encounter during validation .
16,052
protected final List < ValidationException > contOnValidationError ( final ValidationTask ... validationTasks ) { final List < ValidationException > errors = new ArrayList < > ( ) ; for ( final ValidationTask validationTask : validationTasks ) { if ( ! validationTask . isRequired ( ) && validationTask . getInput ( ) ==...
Given one or mote ValidationTasks this method will return a List of ValidationErrors . If the size of the List is 0 no errors were encountered during validation .
16,053
private void initialize ( ) { final MultivaluedMap < String , String > queryParams = uriInfo . getQueryParameters ( ) ; final String offset = multiParam ( queryParams , "offset" ) ; final String page = multiParam ( queryParams , "page" , "pageNumber" ) ; final String size = multiParam ( queryParams , "size" , "pageSize...
Initializes this resource instance by populating some of the features of this class
16,054
protected Principal getPrincipal ( ) { final Object principal = requestContext . getProperty ( "Principal" ) ; if ( principal != null ) { return ( Principal ) principal ; } else { return null ; } }
Returns the principal for who initiated the request .
16,055
protected boolean hasPermission ( final String permission ) { if ( getPrincipal ( ) == null ) { return false ; } try ( AlpineQueryManager qm = new AlpineQueryManager ( ) ) { boolean hasPermission = false ; if ( getPrincipal ( ) instanceof ApiKey ) { hasPermission = qm . hasPermission ( ( ApiKey ) getPrincipal ( ) , per...
Convenience method that returns true if the principal has the specified permission or false if not .
16,056
public static boolean matches ( final char [ ] assertedPassword , final ManagedUser user ) { final char [ ] prehash = createSha512Hash ( assertedPassword ) ; return BCrypt . checkpw ( new String ( prehash ) , user . getPassword ( ) ) ; }
Checks the validity of the asserted password against a ManagedUsers actual hashed password .
16,057
private static char [ ] createSha512Hash ( final char [ ] password ) { try { final MessageDigest digest = MessageDigest . getInstance ( "SHA-512" ) ; digest . update ( ByteUtil . toBytes ( password ) ) ; final byte [ ] byteData = digest . digest ( ) ; final StringBuilder sb = new StringBuilder ( ) ; for ( final byte da...
Creates a SHA - 512 hash of the specified password and returns a HEX representation of the hash . This method should NOT be used solely for password hashing but in conjunction with password - specific hashing functions .
16,058
public void init ( final FilterConfig filterConfig ) { final String host = filterConfig . getInitParameter ( "host" ) ; if ( StringUtils . isNotBlank ( host ) ) { this . host = host ; } }
Initialize host parameter from web . xml .
16,059
private void startDbServer ( ) { final String mode = Config . getInstance ( ) . getProperty ( Config . AlpineKey . DATABASE_MODE ) ; final int port = Config . getInstance ( ) . getPropertyAsInt ( Config . AlpineKey . DATABASE_PORT ) ; if ( StringUtils . isEmpty ( mode ) || ! ( "server" . equals ( mode ) || "embedded" ....
Starts the H2 database engine if the database mode is set to server
16,060
private void init ( ) { if ( properties != null ) { return ; } LOGGER . info ( "Initializing Configuration" ) ; properties = new Properties ( ) ; final String alpineAppProp = PathUtil . resolve ( System . getProperty ( ALPINE_APP_PROP ) ) ; if ( StringUtils . isNotBlank ( alpineAppProp ) ) { LOGGER . info ( "Loading ap...
Initialize the Config object . This method should only be called once .
16,061
private String getPropertyFromEnvironment ( Key key ) { final String envVariable = key . getPropertyName ( ) . toUpperCase ( ) . replace ( "." , "_" ) ; try { return StringUtils . trimToNull ( System . getenv ( envVariable ) ) ; } catch ( SecurityException e ) { LOGGER . warn ( "A security exception prevented access to...
Attempts to retrieve the key via environment variable . Property names are always upper case with periods replaced with underscores .
16,062
public boolean hasUpgradeRan ( final Class < ? extends UpgradeItem > upgradeClass ) throws SQLException { PreparedStatement statement = null ; ResultSet results = null ; try { statement = connection . prepareStatement ( "SELECT \"UPGRADECLASS\" FROM \"INSTALLEDUPGRADES\" WHERE \"UPGRADECLASS\" = ?" ) ; statement . setS...
Determines if the specified upgrade already has a record of being executed previously or not .
16,063
public void installUpgrade ( final Class < ? extends UpgradeItem > upgradeClass , final long startTime , final long endTime ) throws SQLException { PreparedStatement statement = null ; try { statement = connection . prepareStatement ( "INSERT INTO \"INSTALLEDUPGRADES\" (\"UPGRADECLASS\", \"STARTTIME\", \"ENDTIME\") VAL...
Documents a record in the database for the specified class indicating it has been executed .
16,064
public VersionComparator getSchemaVersion ( ) { PreparedStatement statement = null ; ResultSet results = null ; try { statement = connection . prepareStatement ( "SELECT \"VERSION\" FROM \"SCHEMAVERSION\"" ) ; results = statement . executeQuery ( ) ; if ( results . next ( ) ) { return new VersionComparator ( results . ...
Retrieves the current schema version documented in the database .
16,065
public void updateSchemaVersion ( VersionComparator version ) throws SQLException { PreparedStatement statement = null ; PreparedStatement updateStatement = null ; ResultSet results = null ; try { statement = connection . prepareStatement ( "SELECT \"VERSION\" FROM \"SCHEMAVERSION\"" ) ; results = statement . executeQu...
Updates the schema version in the database .
16,066
private String getValue ( FilterConfig filterConfig , String initParam , String variable ) { final String value = filterConfig . getInitParameter ( initParam ) ; if ( StringUtils . isNotBlank ( value ) ) { return value ; } else { return variable ; } }
Returns the value of the initParam .
16,067
private String formatHeader ( ) { final StringBuilder sb = new StringBuilder ( ) ; getStringFromValue ( sb , "default-src" , defaultSrc ) ; getStringFromValue ( sb , "script-src" , scriptSrc ) ; getStringFromValue ( sb , "style-src" , styleSrc ) ; getStringFromValue ( sb , "img-src" , imgSrc ) ; getStringFromValue ( sb...
Formats a CSP header
16,068
private void getStringFromValue ( final StringBuilder builder , final String directive , final String value ) { if ( value != null ) { builder . append ( directive ) . append ( " " ) . append ( value ) . append ( ";" ) ; } }
Assists in the formatting of a single CSP directive .
16,069
public Principal authenticate ( ) throws AlpineAuthenticationException { LOGGER . debug ( "Attempting to authenticate user: " + username ) ; final ManagedUserAuthenticationService userService = new ManagedUserAuthenticationService ( username , password ) ; try { final Principal principal = userService . authenticate ( ...
Attempts to authenticate the credentials internally first and if not successful checks to see if LDAP is enabled or not . If enabled a second attempt to authenticate the credentials will be made but this time against the directory service .
16,070
private static void init ( ) { if ( hasInitialized ) { return ; } final String osName = System . getProperty ( "os.name" ) ; if ( osName != null ) { final String osNameLower = osName . toLowerCase ( ) ; isWindows = osNameLower . contains ( "windows" ) ; isMac = osNameLower . contains ( "mac os x" ) || osNameLower . con...
Initialize static variables .
16,071
public void advancePagination ( ) { if ( pagination . isPaginated ( ) ) { pagination = new Pagination ( pagination . getStrategy ( ) , pagination . getOffset ( ) + pagination . getLimit ( ) , pagination . getLimit ( ) ) ; } }
Advances the pagination based on the previous pagination settings . This is purely a convenience method as the method by itself is not aware of the query being executed the result count etc .
16,072
public Query decorate ( final Query query ) { query . setResult ( null ) ; if ( pagination != null && pagination . isPaginated ( ) ) { final long begin = pagination . getOffset ( ) ; final long end = begin + pagination . getLimit ( ) ; query . setRange ( begin , end ) ; } if ( orderBy != null && RegexSequence . Pattern...
Given a query this method will decorate that query with pagination ordering and sorting direction . Specific checks are performed to ensure the execution of the query is capable of being paged and that ordering can be securely performed .
16,073
@ SuppressWarnings ( "unchecked" ) public < T > T persist ( T object ) { pm . currentTransaction ( ) . begin ( ) ; pm . makePersistent ( object ) ; pm . currentTransaction ( ) . commit ( ) ; pm . getFetchPlan ( ) . setDetachmentOptions ( FetchPlan . DETACH_LOAD_FIELDS ) ; pm . refresh ( object ) ; return object ; }
Persists the specified PersistenceCapable object .
16,074
@ SuppressWarnings ( "unchecked" ) public < T > T [ ] persist ( T ... pcs ) { pm . currentTransaction ( ) . begin ( ) ; pm . makePersistentAll ( pcs ) ; pm . currentTransaction ( ) . commit ( ) ; pm . getFetchPlan ( ) . setDetachmentOptions ( FetchPlan . DETACH_LOAD_FIELDS ) ; pm . refreshAll ( pcs ) ; return pcs ; }
Persists the specified PersistenceCapable objects .
16,075
public < T > T detach ( Class < T > clazz , Object id ) { pm . getFetchPlan ( ) . setDetachmentOptions ( FetchPlan . DETACH_LOAD_FIELDS ) ; return pm . detachCopy ( pm . getObjectById ( clazz , id ) ) ; }
Refreshes and detaches an object by its ID .
16,076
public < T > T getObjectById ( Class < T > clazz , Object id ) { return pm . getObjectById ( clazz , id ) ; }
Retrieves an object by its ID .
16,077
public void init ( final FilterConfig filterConfig ) { final String allowParam = filterConfig . getInitParameter ( "allowUrls" ) ; if ( StringUtils . isNotBlank ( allowParam ) ) { this . allowUrls = allowParam . split ( "," ) ; } }
Initialize allowUrls parameter from web . xml .
16,078
public void doFilter ( final ServletRequest request , final ServletResponse response , final FilterChain chain ) throws IOException , ServletException { final HttpServletRequest req = ( HttpServletRequest ) request ; final HttpServletResponse res = ( HttpServletResponse ) response ; final String requestUri = req . getR...
Check for allowed URLs being requested .
16,079
@ Produces ( MediaType . TEXT_PLAIN ) @ ApiOperation ( value = "Assert login credentials" , notes = "Upon a successful login, a JWT will be returned in the response. This functionality requires authentication to be enabled." , response = String . class ) @ ApiResponses ( value = { @ ApiResponse ( code = 200 , message =...
Processes login requests .
16,080
public static byte [ ] toBytes ( char [ ] chars ) { final CharBuffer charBuffer = CharBuffer . wrap ( chars ) ; final ByteBuffer byteBuffer = Charset . forName ( "UTF-8" ) . encode ( charBuffer ) ; final byte [ ] bytes = Arrays . copyOfRange ( byteBuffer . array ( ) , byteBuffer . position ( ) , byteBuffer . limit ( ) ...
Converts a char array to a byte array without the use of Strings .
16,081
public void init ( final FilterConfig filterConfig ) { final String denyParam = filterConfig . getInitParameter ( "denyUrls" ) ; if ( StringUtils . isNotBlank ( denyParam ) ) { this . denyUrls = denyParam . split ( "," ) ; } final String ignoreParam = filterConfig . getInitParameter ( "ignoreUrls" ) ; if ( StringUtils ...
Initialize deny parameter from web . xml .
16,082
public void doFilter ( final ServletRequest request , final ServletResponse response , final FilterChain chain ) throws IOException , ServletException { final HttpServletRequest req = ( HttpServletRequest ) request ; final HttpServletResponse res = ( HttpServletResponse ) response ; final String requestUri = req . getR...
Check for denied or ignored URLs being requested .
16,083
protected void scheduleEvent ( final Event event , final long delay , final long period ) { final Timer timer = new Timer ( ) ; timer . schedule ( new ScheduleEvent ( ) . event ( event ) , delay , period ) ; timers . add ( timer ) ; }
Schedules a repeating Event .
16,084
private void calculateStrategy ( final Strategy strategy , final int o1 , final int o2 ) { if ( Strategy . OFFSET == strategy ) { this . offset = o1 ; this . limit = o2 ; } else if ( Strategy . PAGES == strategy ) { this . offset = ( o1 * o2 ) - o2 ; this . limit = o2 ; } }
Determines the offset and limit based on pagination strategy .
16,085
private Integer parseIntegerFromParam ( final String value , final int defaultValue ) { try { return Integer . valueOf ( value ) ; } catch ( NumberFormatException | NullPointerException e ) { return defaultValue ; } }
Parses a parameter to an Integer defaulting to 0 upon any errors encountered .
16,086
public static String generate ( final int chars ) { final SecureRandom secureRandom = new SecureRandom ( ) ; final char [ ] buff = new char [ chars ] ; for ( int i = 0 ; i < chars ; ++ i ) { if ( i % 10 == 0 ) { secureRandom . setSeed ( secureRandom . nextLong ( ) ) ; } buff [ i ] = VALID_CHARACTERS [ secureRandom . ne...
Generates a cryptographically secure API key of the specified length .
16,087
private int [ ] parse ( String version ) { final Matcher m = Pattern . compile ( "(\\d+)\\.(\\d+)\\.(\\d+)-?(SNAPSHOT)?\\.?(\\d*)?" ) . matcher ( version ) ; if ( ! m . matches ( ) ) { throw new IllegalArgumentException ( "Malformed version string: " + version ) ; } return new int [ ] { Integer . parseInt ( m . group (...
Parses the version .
16,088
public boolean isNewerThan ( VersionComparator comparator ) { if ( this . major > comparator . getMajor ( ) ) { return true ; } else if ( this . major == comparator . getMajor ( ) && this . minor > comparator . getMinor ( ) ) { return true ; } else if ( this . major == comparator . getMajor ( ) && this . minor == compa...
Determines if the specified VersionComparator is newer than this instance .
16,089
private void initialize ( ) { createKeysIfNotExist ( ) ; if ( keyPair == null ) { try { loadKeyPair ( ) ; } catch ( IOException | NoSuchAlgorithmException | InvalidKeySpecException e ) { LOGGER . error ( "An error occurred loading key pair" ) ; LOGGER . error ( e . getMessage ( ) ) ; } } if ( secretKey == null ) { try ...
Initializes the KeyManager
16,090
private void createKeysIfNotExist ( ) { if ( ! keyPairExists ( ) ) { try { final KeyPair keyPair = generateKeyPair ( ) ; save ( keyPair ) ; } catch ( NoSuchAlgorithmException e ) { LOGGER . error ( "An error occurred generating new keypair" ) ; LOGGER . error ( e . getMessage ( ) ) ; } catch ( IOException e ) { LOGGER ...
Checks if the keys exists . If not they will be created .
16,091
public KeyPair generateKeyPair ( ) throws NoSuchAlgorithmException { LOGGER . info ( "Generating new key pair" ) ; final KeyPairGenerator keyGen = KeyPairGenerator . getInstance ( "RSA" ) ; final SecureRandom random = SecureRandom . getInstance ( "SHA1PRNG" ) ; keyGen . initialize ( 4096 , random ) ; return this . keyP...
Generates a key pair .
16,092
private File getKeyPath ( final KeyType keyType ) { return new File ( Config . getInstance ( ) . getDataDirectorty ( ) + File . separator + "keys" + File . separator + keyType . name ( ) . toLowerCase ( ) + ".key" ) ; }
Retrieves the path where the keys should be stored .
16,093
private File getKeyPath ( final Key key ) { KeyType keyType = null ; if ( key instanceof PrivateKey ) { keyType = KeyType . PRIVATE ; } else if ( key instanceof PublicKey ) { keyType = KeyType . PUBLIC ; } else if ( key instanceof SecretKey ) { keyType = KeyType . SECRET ; } return getKeyPath ( keyType ) ; }
Given the type of key this method will return the File path to that key .
16,094
public void save ( final KeyPair keyPair ) throws IOException { LOGGER . info ( "Saving key pair" ) ; final PrivateKey privateKey = keyPair . getPrivate ( ) ; final PublicKey publicKey = keyPair . getPublic ( ) ; final File publicKeyFile = getKeyPath ( publicKey ) ; publicKeyFile . getParentFile ( ) . mkdirs ( ) ; fina...
Saves a key pair .
16,095
public void save ( final SecretKey key ) throws IOException { final File keyFile = getKeyPath ( key ) ; keyFile . getParentFile ( ) . mkdirs ( ) ; try ( OutputStream fos = Files . newOutputStream ( keyFile . toPath ( ) ) ; ObjectOutputStream oout = new ObjectOutputStream ( fos ) ) { oout . writeObject ( key ) ; } }
Saves a secret key .
16,096
private KeyPair loadKeyPair ( ) throws IOException , NoSuchAlgorithmException , InvalidKeySpecException { final File filePrivateKey = getKeyPath ( KeyType . PRIVATE ) ; final File filePublicKey = getKeyPath ( KeyType . PUBLIC ) ; byte [ ] encodedPrivateKey ; byte [ ] encodedPublicKey ; try ( InputStream pvtfis = Files ...
Loads a key pair .
16,097
private SecretKey loadSecretKey ( ) throws IOException , ClassNotFoundException { final File file = getKeyPath ( KeyType . SECRET ) ; SecretKey key ; try ( InputStream fis = Files . newInputStream ( file . toPath ( ) ) ; ObjectInputStream ois = new ObjectInputStream ( fis ) ) { key = ( SecretKey ) ois . readObject ( ) ...
Loads the secret key .
16,098
public static boolean valueOf ( String value ) { return ( value != null ) && ( value . trim ( ) . equalsIgnoreCase ( "true" ) || value . trim ( ) . equals ( "1" ) ) ; }
Determines if the specified string contains true or 1
16,099
public static byte [ ] encryptAsBytes ( final SecretKey secretKey , final String plainText ) throws Exception { final byte [ ] clean = plainText . getBytes ( ) ; int ivSize = 16 ; final byte [ ] iv = new byte [ ivSize ] ; final SecureRandom random = new SecureRandom ( ) ; random . nextBytes ( iv ) ; final IvParameterSp...
Encrypts the specified plainText using AES - 256 .