idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
12,400
public final ServiceStatusType getServiceStatus ( ) { ServiceStatusType serviceStatus = ServiceStatusType . UNKNOWN ; if ( "true" . equals ( status ) ) { serviceStatus = ServiceStatusType . RUNNING ; } else if ( "false" . equals ( status ) ) { serviceStatus = ServiceStatusType . STOPPED ; } return serviceStatus ; }
Get the service status .
12,401
public void ofsToIdx ( Code context , int ofs , Object [ ] argValues ) { int i ; IntArrayList branchesW ; switch ( encoding ) { case TS : i = ( ( Integer ) argValues [ 0 ] ) . intValue ( ) ; argValues [ 0 ] = new Integer ( context . findIdx ( ofs + i ) ) ; branchesW = ( IntArrayList ) argValues [ 3 ] ; for ( i = 0 ; i < branchesW . size ( ) ; i ++ ) { branchesW . set ( i , context . findIdx ( ofs + branchesW . get ( i ) ) ) ; } break ; case LS : i = ( ( Integer ) argValues [ 0 ] ) . intValue ( ) ; argValues [ 0 ] = new Integer ( context . findIdx ( ofs + i ) ) ; branchesW = ( IntArrayList ) argValues [ 2 ] ; for ( i = 0 ; i < branchesW . size ( ) ; i ++ ) { branchesW . set ( i , context . findIdx ( ofs + branchesW . get ( i ) ) ) ; } break ; case BRANCH : case VBRANCH : i = ( ( Integer ) argValues [ 0 ] ) . intValue ( ) ; argValues [ 0 ] = new Integer ( context . findIdx ( ofs + i ) ) ; break ; default : break ; } }
Fixup . Turn ofs into idx .
12,402
private boolean fillLast ( ) throws IOException { int count ; if ( lastFilled == pageSize ) { throw new IllegalStateException ( ) ; } count = src . read ( pages [ lastNo ] , lastFilled , pageSize - lastFilled ) ; if ( count <= 0 ) { if ( count == 0 ) { throw new IllegalStateException ( ) ; } return false ; } lastFilled += count ; return true ; }
Reads bytes to fill the last page .
12,403
private void grow ( ) { char [ ] [ ] newPages ; if ( lastFilled != pageSize ) { throw new IllegalStateException ( ) ; } lastNo ++ ; if ( lastNo >= pages . length ) { newPages = new char [ lastNo * 5 / 2 ] [ ] ; System . arraycopy ( pages , 0 , newPages , 0 , lastNo ) ; pages = newPages ; } if ( pages [ lastNo ] == null ) { pages [ lastNo ] = new char [ pageSize ] ; } lastFilled = 0 ; }
Adds a page at the end
12,404
public void shrink ( int count ) { char [ ] keepAllocated ; if ( count == 0 ) { throw new IllegalArgumentException ( ) ; } if ( count > lastNo ) { throw new IllegalArgumentException ( count + " vs " + lastNo ) ; } lastNo -= count ; keepAllocated = pages [ 0 ] ; System . arraycopy ( pages , count , pages , 0 , lastNo + 1 ) ; pages [ lastNo + 1 ] = keepAllocated ; for ( int i = lastNo + 2 ; i < pages . length ; i ++ ) { pages [ i ] = null ; } }
Remove count pages from the beginning
12,405
public static FABuilder run ( Rule [ ] rules , IntBitSet terminals , StringArrayList symbolTable , PrintWriter verbose ) throws ActionException { FA alt ; int i ; Expander expander ; FABuilder builder ; Label label ; RegExpr expanded ; Minimizer minimizer ; expander = new Expander ( rules , symbolTable ) ; builder = new FABuilder ( symbolTable ) ; builder . fa = ( FA ) new Choice ( ) . visit ( builder ) ; if ( verbose != null ) { verbose . println ( "building NFA" ) ; } for ( i = 0 ; i < rules . length ; i ++ ) { if ( terminals . contains ( rules [ i ] . getLeft ( ) ) ) { expanded = ( RegExpr ) rules [ i ] . getRight ( ) . visit ( expander ) ; alt = ( FA ) expanded . visit ( builder ) ; label = new Label ( rules [ i ] . getLeft ( ) ) ; alt . setEndLabels ( label ) ; builder . fa . alternate ( alt ) ; } } if ( verbose != null ) { verbose . println ( "building DFA" ) ; } builder . fa = DFA . create ( builder . fa ) ; if ( verbose != null ) { verbose . println ( "complete DFA" ) ; } builder . errorSi = builder . fa . add ( null ) ; builder . fa = CompleteFA . create ( builder . fa , builder . errorSi ) ; if ( verbose != null ) { verbose . println ( "minimized DFA" ) ; } minimizer = new Minimizer ( builder . fa ) ; builder . fa = minimizer . run ( ) ; builder . errorSi = minimizer . getNewSi ( builder . errorSi ) ; builder . inlines = expander . getUsed ( ) ; if ( builder . fa . isEnd ( builder . fa . getStart ( ) ) ) { label = ( Label ) builder . fa . get ( builder . fa . getStart ( ) ) . getLabel ( ) ; throw new ActionException ( "Scanner accepts the empty word for symbol " + symbolTable . get ( label . getSymbol ( ) ) + ".\nThis is illegal because it might cause infinite loops when scanning." ) ; } return builder ; }
Translates only those rules where the left - hand . side is contained in the specified terminals set . The remaining rules are used for inlining .
12,406
public synchronized Logger getLogger ( ) { if ( m_Logger == null ) { m_Logger = Logger . getLogger ( getClass ( ) . getName ( ) ) ; m_Logger . setLevel ( LoggingHelper . getLevel ( getClass ( ) ) ) ; } return m_Logger ; }
Returns the logger in use .
12,407
public boolean remove ( String classname ) { String pkgname ; HashSet < String > names ; classname = ClassPathTraversal . cleanUp ( classname ) ; pkgname = ClassPathTraversal . extractPackage ( classname ) ; names = m_NameCache . get ( pkgname ) ; if ( names != null ) return names . remove ( classname ) ; else return false ; }
Removes the classname from the cache .
12,408
public HashSet < String > getClassnames ( String pkgname ) { if ( m_NameCache . containsKey ( pkgname ) ) return m_NameCache . get ( pkgname ) ; else return new HashSet < > ( ) ; }
Returns all the classes for the given package .
12,409
protected void initialize ( ClassTraversal traversal ) { Listener listener ; listener = new Listener ( ) ; traversal . traverse ( listener ) ; m_NameCache = listener . getNameCache ( ) ; }
Initializes the cache .
12,410
public void contributeRequestHandler ( OrderedConfiguration < RequestFilter > configuration , URLRewriter urlRewriter ) { if ( urlRewriter . hasRequestRules ( ) ) { URLRewriterRequestFilter urlRewriterRequestFilter = new URLRewriterRequestFilter ( urlRewriter ) ; configuration . add ( "URLRewriter" , urlRewriterRequestFilter , "before:StaticFiles" ) ; } }
Contributes the URL rewriter request filter if there are URL rewriter rules .
12,411
public static void main ( String [ ] args ) throws IOException { Properties props = new Properties ( System . getProperties ( ) ) ; props . load ( JobServerMain . class . getResourceAsStream ( "system.properties" ) ) ; System . setProperties ( props ) ; javax . swing . SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { startServer ( ) ; } } ) ; }
Runs the JDCP server application .
12,412
private static void startServer ( ) { try { JdcpUtil . initialize ( ) ; Class . forName ( "org.apache.derby.jdbc.EmbeddedDriver" ) ; EmbeddedDataSource ds = new EmbeddedDataSource ( ) ; ds . setConnectionAttributes ( "create=true" ) ; ds . setDatabaseName ( "classes" ) ; System . err . print ( "Initializing progress monitor..." ) ; ProgressPanel panel = new ProgressPanel ( ) ; panel . setPreferredSize ( new Dimension ( 500 , 350 ) ) ; System . err . println ( "OK" ) ; System . err . print ( "Initializing folders..." ) ; Preferences pref = Preferences . userNodeForPackage ( JobServer . class ) ; String path = pref . get ( "rootDirectory" , "./server" ) ; File rootDirectory = new File ( path ) ; File jobsDirectory = new File ( rootDirectory , "jobs" ) ; rootDirectory . mkdir ( ) ; jobsDirectory . mkdir ( ) ; System . err . println ( "OK" ) ; System . err . print ( "Initializing service..." ) ; DbClassManager classManager = new DbClassManager ( ds ) ; classManager . prepareDataSource ( ) ; TaskScheduler scheduler = new PrioritySerialTaskScheduler ( ) ; Executor executor = Executors . newCachedThreadPool ( ) ; JobServer jobServer = new JobServer ( jobsDirectory , panel , scheduler , classManager , executor ) ; AuthenticationServer authServer = new AuthenticationServer ( jobServer , JdcpUtil . DEFAULT_PORT ) ; System . err . println ( "OK" ) ; System . err . print ( "Exporting service stubs..." ) ; System . err . println ( "OK" ) ; System . err . print ( "Binding service..." ) ; final Registry registry = LocateRegistry . createRegistry ( JdcpUtil . DEFAULT_PORT ) ; registry . bind ( "AuthenticationService" , authServer ) ; System . err . println ( "OK" ) ; System . err . println ( "Server ready" ) ; JFrame frame = new JFrame ( "JDCP Server" ) ; frame . setDefaultCloseOperation ( JFrame . DISPOSE_ON_CLOSE ) ; frame . getContentPane ( ) . add ( panel ) ; frame . pack ( ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosed ( WindowEvent event ) { System . err . print ( "Shutting down..." ) ; try { registry . unbind ( "AuthenticationService" ) ; System . err . println ( "OK" ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } System . exit ( 0 ) ; } } ) ; frame . setVisible ( true ) ; } catch ( Exception e ) { System . err . println ( "Server exception:" ) ; e . printStackTrace ( ) ; } }
Starts the JDCP server .
12,413
public void addValue ( double val ) { numItems ++ ; double valMinusMean = val - mean ; sumsq += valMinusMean * valMinusMean * ( numItems - 1 ) / numItems ; mean += valMinusMean / numItems ; }
Update the variance with a new value .
12,414
protected < T extends DavidBoxResponse > T execute ( DavidBoxOperation operation , Class < T > responseTargetClass ) throws TheDavidBoxClientException { LinkedHashMap < String , String > operationArguments = operation . buildHttpArguments ( ) ; String urlGet = remoteHttpService . buildGetRequest ( remoteHost , operation . getOperationType ( ) , operationArguments ) ; T responseObject = sendAndParse ( urlGet , responseTargetClass ) ; return responseObject ; }
It executes a davidbox operation . Builds the http get request sends receive and fit the response in the response target object
12,415
private < T extends DavidBoxResponse > T sendAndParse ( String urlGet , Class < T > responseTargetClass ) throws TheDavidBoxClientException { logger . debug ( "urlGet: " + urlGet ) ; notifyRequest ( urlGet ) ; String xmlResponse = "" ; try { xmlResponse = getRemoteHttpService ( ) . sendGetRequest ( urlGet ) ; } catch ( TheDavidBoxClientException e1 ) { throw new TheDavidBoxClientException ( e1 , urlGet , xmlResponse ) ; } notifyResponse ( xmlResponse ) ; T responseObject = null ; try { responseObject = getDavidBoxPaser ( ) . parse ( responseTargetClass , xmlResponse ) ; } catch ( TheDavidBoxClientException e2 ) { throw new TheDavidBoxClientException ( e2 , urlGet , xmlResponse ) ; } return responseObject ; }
It sends the url get to the service and parse the response in the desired response target class .
12,416
protected Provider < String > getPUNameProvider ( ) { final String puName = settings . getDatabaseSettings ( ) . getPersistenceUnit ( ) ; return Providers . < String > of ( puName == null ? "croquet" : puName ) ; }
Provides the name of the persistence unit .
12,417
protected List < ManagedModule > createAndStartModules ( ) { final List < ManagedModule > managedModuleInstances = new ArrayList < > ( ) ; for ( final Class < ? extends ManagedModule > module : managedModules ) { final ManagedModule mm = injector . getInstance ( module ) ; managedModuleInstances . add ( mm ) ; mm . start ( ) ; } return managedModuleInstances ; }
Creates and starts all the managed modules .
12,418
@ SuppressFBWarnings ( "DM_EXIT" ) public void run ( ) { status = CroquetStatus . STARTING ; createInjector ( ) ; jettyServer = configureJetty ( settings . getPort ( ) ) ; jettyServer . addLifeCycleListener ( new AbstractLifeCycleListener ( ) { public void lifeCycleStarted ( final LifeCycle event ) { final String pidFile = settings . getPidFile ( ) ; if ( pidFile != null ) { LOG . info ( "Dropping PID file: {}" , pidFile ) ; new PidManager ( pidFile ) . dropPidOrDie ( ) ; } else { LOG . warn ( "No PID file specified, so not file will be dropped. " + "Set a file via code or in the config file to drop a pid file." ) ; } } } ) ; try { jettyServer . start ( ) ; } catch ( final Exception e ) { LOG . error ( "Error starting Jetty: {}" , e . getMessage ( ) , e ) ; System . err . println ( "Error starting Jetty: " + e . getMessage ( ) ) ; System . exit ( - 1 ) ; throw new RuntimeException ( e ) ; } final List < ManagedModule > managedModuleInstances = createAndStartModules ( ) ; Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { public void run ( ) { status = CroquetStatus . STOPPING ; try { jettyServer . stop ( ) ; } catch ( final Exception e ) { LOG . error ( "Error stopping Jetty: {}" , e . getMessage ( ) , e ) ; } for ( final ManagedModule module : managedModuleInstances ) { module . stop ( ) ; } status = CroquetStatus . STOPPED ; LOG . info ( "Croquet has stopped" ) ; } } ) ; status = CroquetStatus . RUNNING ; LOG . info ( "Croquet is running on port {}" , settings . getPort ( ) ) ; }
Starts the Croquet framework .
12,419
public String getFormattedDate ( String format ) { SimpleDateFormat dateFormat = new SimpleDateFormat ( format ) ; return dateFormat . format ( date ) ; }
Formats the date of the event with the given format
12,420
public static String getPathOr ( String var , String def ) { String path = AcePathfinder . INSTANCE . getPath ( var ) ; if ( path == null ) { path = def ; } return path ; }
Get a valid path from the pathfiner or if not found a user - specified path .
12,421
public OrderContainer add ( String property , OrderType orderType ) { if ( property == null || property . trim ( ) . length ( ) == 0 ) return this ; if ( orderType == null ) return this ; orders . put ( property . trim ( ) , orderType ) ; return this ; }
Methode d ajout d un ordre de tri
12,422
public void traverse ( String classname , TraversalState state ) { classname = cleanUp ( classname ) ; state . getListener ( ) . traversing ( classname , state . getURL ( ) ) ; }
Traverses the class calls the listener available through the state .
12,423
protected void traverseManifest ( Manifest manifest , TraversalState state ) { Attributes atts ; String cp ; String [ ] parts ; if ( manifest == null ) return ; atts = manifest . getMainAttributes ( ) ; cp = atts . getValue ( "Class-Path" ) ; if ( cp == null ) return ; parts = cp . split ( " " ) ; for ( String part : parts ) { if ( part . trim ( ) . length ( ) == 0 ) return ; if ( part . toLowerCase ( ) . endsWith ( ".jar" ) || ! part . equals ( "." ) ) traverseClasspathPart ( part , state ) ; } }
Analyzes the MANIFEST . MF file of a jar whether additional jars are listed in the Class - Path key .
12,424
protected void traverseJar ( File file , TraversalState state ) { JarFile jar ; JarEntry entry ; Enumeration enm ; if ( isLoggingEnabled ( ) ) getLogger ( ) . log ( Level . INFO , "Analyzing jar: " + file ) ; if ( ! file . exists ( ) ) { getLogger ( ) . log ( Level . WARNING , "Jar does not exist: " + file ) ; return ; } try { jar = new JarFile ( file ) ; enm = jar . entries ( ) ; while ( enm . hasMoreElements ( ) ) { entry = ( JarEntry ) enm . nextElement ( ) ; if ( entry . getName ( ) . endsWith ( ".class" ) ) traverse ( entry . getName ( ) , state ) ; } traverseManifest ( jar . getManifest ( ) , state ) ; } catch ( Exception e ) { getLogger ( ) . log ( Level . SEVERE , "Failed to inspect: " + file , e ) ; } }
Fills the class cache with classes from the specified jar .
12,425
protected void traverseClasspathPart ( String part , TraversalState state ) { File file ; file = null ; if ( part . startsWith ( "file:" ) ) { part = part . replace ( " " , "%20" ) ; try { file = new File ( new java . net . URI ( part ) ) ; } catch ( URISyntaxException e ) { getLogger ( ) . log ( Level . SEVERE , "Failed to generate URI: " + part , e ) ; } } else { file = new File ( part ) ; } if ( file == null ) { if ( isLoggingEnabled ( ) ) getLogger ( ) . log ( Level . INFO , "Skipping: " + part ) ; return ; } if ( file . isDirectory ( ) ) traverseDir ( file , state ) ; else if ( file . exists ( ) ) traverseJar ( file , state ) ; }
Analyzes a part of the classpath .
12,426
public static boolean contains ( Object [ ] arr , Object obj ) { if ( arr != null ) { for ( int i = 0 ; i < arr . length ; i ++ ) { Object arri = arr [ i ] ; if ( arri == obj || ( arri != null && arri . equals ( obj ) ) ) { return true ; } } } return false ; }
Returns where an object is in a given array .
12,427
public static < E > void addAll ( Collection < E > collection , E [ ] ... arr ) { if ( collection == null ) { throw new IllegalArgumentException ( "collection cannot be null" ) ; } for ( E [ ] oarr : arr ) { for ( E o : oarr ) { collection . add ( o ) ; } } }
Adds the contents of one or more arrays to a collection .
12,428
public static < E > List < E > asList ( E [ ] ... arrs ) { int size = 0 ; for ( E [ ] arr : arrs ) { if ( arr == null ) { throw new IllegalArgumentException ( "Null arrays not allowed" ) ; } size += arr . length ; } List < E > result = new ArrayList < > ( size ) ; addAll ( result , arrs ) ; return result ; }
Returns a newly created random access list with the contents of the provided arrays .
12,429
private void moveClass ( File fromDirectory , String name , File toDirectory ) { String baseName = getBaseFileName ( name ) ; File fromClassFile = new File ( fromDirectory , baseName + CLASS_EXTENSION ) ; File toClassFile = new File ( toDirectory , baseName + CLASS_EXTENSION ) ; File fromDigestFile = new File ( fromDirectory , baseName + DIGEST_EXTENSION ) ; File toDigestFile = new File ( toDirectory , baseName + DIGEST_EXTENSION ) ; File toClassDirectory = toClassFile . getParentFile ( ) ; toClassDirectory . mkdirs ( ) ; fromClassFile . renameTo ( toClassFile ) ; fromDigestFile . renameTo ( toDigestFile ) ; }
Moves a class definition from the specified directory tree to another specified directory tree .
12,430
private boolean classExists ( File directory , String name ) { String baseName = getBaseFileName ( name ) ; File classFile = new File ( directory , baseName + CLASS_EXTENSION ) ; File digestFile = new File ( directory , baseName + DIGEST_EXTENSION ) ; return classFile . isFile ( ) && digestFile . isFile ( ) ; }
Determines if the specified class exists in the specified directory tree .
12,431
private byte [ ] getFileContents ( File file ) { if ( file . exists ( ) ) { try { return FileUtil . getFileContents ( file ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } return null ; }
Gets the contents of the specified file or null if the file does not exist .
12,432
private byte [ ] getClassDigest ( File directory , String name ) { String baseName = getBaseFileName ( name ) ; File digestFile = new File ( directory , baseName + DIGEST_EXTENSION ) ; return getFileContents ( digestFile ) ; }
Gets the MD5 digest of a class definition .
12,433
private ByteBuffer getClassDefinition ( File directory , String name ) { String baseName = getBaseFileName ( name ) ; File digestFile = new File ( directory , baseName + CLASS_EXTENSION ) ; return ByteBuffer . wrap ( getFileContents ( digestFile ) ) ; }
Gets the definition of a class .
12,434
private byte [ ] computeClassDigest ( ByteBuffer def ) { try { MessageDigest alg = MessageDigest . getInstance ( DIGEST_ALGORITHM ) ; def . mark ( ) ; alg . update ( def ) ; def . reset ( ) ; return alg . digest ( ) ; } catch ( NoSuchAlgorithmException e ) { throw new UnexpectedException ( e ) ; } }
Computes the MD5 digest of the given class definition .
12,435
public Connection getOrCreate ( ) throws SQLException { Connection con ; if ( this . user == null && this . password == null ) { con = this . dataSource . getConnection ( ) ; } else { con = this . dataSource . getConnection ( this . user , this . password ) ; } con . setAutoCommit ( isAutoCommitEnabled ( ) ) ; return con ; }
Creates a database connection or gets an existing connection with the JNDI name username and password specified in the constructor .
12,436
public static JobService connect ( String host , String username , String password ) throws RemoteException , NotBoundException , LoginException , ProtocolVersionException { Registry registry = LocateRegistry . getRegistry ( host , DEFAULT_PORT ) ; AuthenticationService auth = ( AuthenticationService ) registry . lookup ( "AuthenticationService" ) ; return auth . authenticate ( username , password , PROTOCOL_VERSION_ID ) ; }
Connects to a JDCP server .
12,437
public static UUID submitJob ( ParallelizableJob job , String description , String host , String username , String password ) throws SecurityException , RemoteException , ClassNotFoundException , JobExecutionException , LoginException , NotBoundException , ProtocolVersionException { Serialized < ParallelizableJob > payload = new Serialized < ParallelizableJob > ( job ) ; JobService service = connect ( host , username , password ) ; return service . submitJob ( payload , description ) ; }
Submits a job to a server for processing .
12,438
public static void registerTaskService ( String name , TaskService taskService , String host , String username , String password ) throws SecurityException , RemoteException , ClassNotFoundException , JobExecutionException , LoginException , NotBoundException , ProtocolVersionException { JobService service = connect ( host , username , password ) ; service . registerTaskService ( name , taskService ) ; }
Connects to a job server and provides a source of tasks to be processed .
12,439
public static void initialize ( ) { String homeDirName = System . getProperty ( "jdcp.home" ) ; File homeDir ; if ( homeDirName != null ) { homeDir = new File ( homeDirName ) ; } else { homeDir = FileUtil . getApplicationDataDirectory ( "jdcp" ) ; System . setProperty ( "jdcp.home" , homeDir . getPath ( ) ) ; } homeDir . mkdir ( ) ; if ( System . getProperty ( "derby.system.home" ) == null ) { System . setProperty ( "derby.system.home" , homeDir . getPath ( ) ) ; } }
Performs initialization for the currently running JDCP application .
12,440
public List < String > findPackages ( ) { List < String > result ; Iterator < String > packages ; result = new ArrayList < > ( ) ; packages = m_Cache . packages ( ) ; while ( packages . hasNext ( ) ) result . add ( packages . next ( ) ) ; Collections . sort ( result , new StringCompare ( ) ) ; return result ; }
Lists all packages it can find in the classpath .
12,441
protected void initCache ( ClassTraversal traversal ) { if ( m_CacheNames == null ) m_CacheNames = new HashMap < > ( ) ; if ( m_CacheClasses == null ) m_CacheClasses = new HashMap < > ( ) ; if ( m_BlackListed == null ) m_BlackListed = new HashSet < > ( ) ; if ( m_Cache == null ) m_Cache = newClassCache ( traversal ) ; }
initializes the cache for the classnames .
12,442
protected void addCache ( Class cls , String pkgname , List < String > classnames , List < Class > classes ) { m_CacheNames . put ( cls . getName ( ) + "-" + pkgname , classnames ) ; m_CacheClasses . put ( cls . getName ( ) + "-" + pkgname , classes ) ; }
adds the list of classnames to the cache .
12,443
protected List < String > getNameCache ( Class cls , String pkgname ) { return m_CacheNames . get ( cls . getName ( ) + "-" + pkgname ) ; }
returns the list of classnames associated with this class and package if available otherwise null .
12,444
protected List < Class > getClassCache ( Class cls , String pkgname ) { return m_CacheClasses . get ( cls . getName ( ) + "-" + pkgname ) ; }
returns the list of classes associated with this class and package if available otherwise null .
12,445
public boolean matches ( Class < ? > [ ] args ) { int i ; Class < ? > [ ] paras ; paras = getParameterTypes ( ) ; if ( args . length != paras . length ) { return false ; } for ( i = 0 ; i < args . length ; i ++ ) { if ( ! paras [ i ] . isAssignableFrom ( args [ i ] ) ) { return false ; } } return true ; }
Tests if the functions can be called with arguments of the specified types .
12,446
protected Query buildQuery ( Object target ) { if ( expressionModel == null ) return null ; Query query = this . entityManager . createQuery ( expressionModel . getComputedExpression ( ) ) ; Map < String , String > parameters = expressionModel . getParameters ( ) ; if ( parameters != null && parameters . size ( ) > 0 ) { Set < String > keys = parameters . keySet ( ) ; for ( String key : keys ) { query . setParameter ( key , DAOValidatorHelper . evaluateValueExpression ( parameters . get ( key ) , target ) ) ; } } return query ; }
Methode de construction de la requete
12,447
protected boolean isProcessable ( ) { boolean correctMode = DAOValidatorHelper . arraryContains ( getAnnotationMode ( ) , this . systemDAOMode ) ; boolean correctTime = DAOValidatorHelper . arraryContains ( getAnnotationEvaluationTime ( ) , this . systemEvaluationTime ) ; return correctMode && correctTime ; }
methode permettant de tester si l annotation doit - etre executee
12,448
static public String encode ( byte [ ] bytes , String indentation ) { StringBuilder result = new StringBuilder ( ) ; int length = bytes . length ; if ( length == 0 ) return "" ; if ( indentation != null ) result . append ( indentation ) ; encodeBytes ( bytes [ 0 ] , bytes [ 0 ] , 0 , result ) ; for ( int i = 1 ; i < length ; i ++ ) { if ( i % 50 == 0 ) { result . append ( "\n" ) ; if ( indentation != null ) result . append ( indentation ) ; } encodeBytes ( bytes [ i - 1 ] , bytes [ i ] , i , result ) ; } encodeLastByte ( bytes [ length - 1 ] , length - 1 , result ) ; return result . toString ( ) ; }
This function encodes a byte array using base 32 with a specific indentation of new lines .
12,449
static public byte [ ] decode ( String base32 ) { String string = base32 . replaceAll ( "\\s" , "" ) ; int length = string . length ( ) ; byte [ ] bytes = new byte [ ( int ) ( length * 5.0 / 8.0 ) ] ; for ( int i = 0 ; i < length - 1 ; i ++ ) { char character = string . charAt ( i ) ; byte chunk = ( byte ) lookupTable . indexOf ( ( int ) character ) ; if ( chunk < 0 ) throw new NumberFormatException ( "Attempted to decode a string that is not base 32: " + string ) ; decodeCharacter ( chunk , i , bytes , 0 ) ; } if ( length > 0 ) { char character = string . charAt ( length - 1 ) ; byte chunk = ( byte ) lookupTable . indexOf ( ( int ) character ) ; if ( chunk < 0 ) throw new NumberFormatException ( "Attempted to decode a string that is not base 32: " + string ) ; decodeLastCharacter ( chunk , length - 1 , bytes , 0 ) ; } return bytes ; }
This function decodes a base 32 string into its corresponding byte array .
12,450
public static < S > Feature < S , Boolean > not ( Feature < ? super S , Boolean > feature ) { return FeatureExpressions . not ( feature ) ; }
Decorate a boolean feature to yield its logical negation .
12,451
public static < V > boolean the ( Sampler < V > variable , Matcher < ? super V > criteria ) { variable . takeSample ( ) ; return criteria . matches ( variable . sampledValue ( ) ) ; }
Report whether a sample of the variable satisfies the criteria .
12,452
public static < S > boolean the ( S subject , Matcher < ? super S > criteria ) { return criteria . matches ( subject ) ; }
Report whether the subject satisfies the criteria .
12,453
public static < S , V > boolean the ( S subject , Feature < ? super S , V > feature , Matcher < ? super V > criteria ) { return criteria . matches ( feature . of ( subject ) ) ; }
Report whether a sample of the feature satisfies the criteria .
12,454
public static Function fillParas ( Function func , int ofs , Object [ ] paras ) { int i ; if ( func == null ) { throw new NullPointerException ( ) ; } for ( i = 0 ; i < paras . length ; i ++ ) { func = Composition . create ( func , ofs , new Constant ( paras [ i ] . getClass ( ) , "arg" + i , paras [ i ] ) ) ; if ( func == null ) { throw new RuntimeException ( ) ; } } return func ; }
Replaces arguments to Functions by Constant Functions . Results in Functions with fewer arguments .
12,455
public void unbind ( DataSource dataSource ) throws NamingException { if ( dataSource == null ) { throw new IllegalArgumentException ( "dataSource cannot be null" ) ; } String jndiUrl = this . dataSourceBindings . get ( dataSource ) ; if ( jndiUrl == null ) { throw new NamingException ( "No such binding" ) ; } this . initialContext . unbind ( jndiUrl ) ; this . dataSourceBindings . remove ( dataSource ) ; }
Unbinds a data source .
12,456
public static String prepareExtendedIdentifier ( Document doc ) throws MarshalException { Transformer tf = null ; String res = null ; try { tf = TRANSFORMER_FACTORY . newTransformer ( ) ; } catch ( TransformerConfigurationException e ) { IfmapJLog . error ( "Oh oh.... [" + e . getMessage ( ) + "]" ) ; throw new MarshalException ( e . getMessage ( ) ) ; } fixupNamespace ( doc ) ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; DOMSource domSource = new DOMSource ( doc . getFirstChild ( ) ) ; Result result = new StreamResult ( baos ) ; tf . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , "yes" ) ; tf . setOutputProperty ( OutputKeys . INDENT , "no" ) ; tf . setOutputProperty ( OutputKeys . METHOD , "xml" ) ; try { tf . transform ( domSource , result ) ; } catch ( TransformerException e ) { IfmapJLog . error ( "Oh oh.... [" + e . getMessage ( ) + "]" ) ; throw new MarshalException ( e . getMessage ( ) ) ; } ByteArrayInputStream bais = new ByteArrayInputStream ( baos . toByteArray ( ) ) ; InputSource inputSource = new InputSource ( bais ) ; CanonicalXML cxml = new CanonicalXML ( ) ; XMLReader reader = null ; try { reader = XMLReaderFactory . createXMLReader ( ) ; } catch ( SAXException e ) { IfmapJLog . error ( "Oh oh.... [" + e . getMessage ( ) + "]" ) ; throw new MarshalException ( e . getMessage ( ) ) ; } try { res = cxml . toCanonicalXml2 ( reader , inputSource , true ) ; } catch ( Exception e ) { IfmapJLog . error ( "Oh oh.... [" + e . getMessage ( ) + "]" ) ; throw new MarshalException ( e . getMessage ( ) ) ; } return escapeXml ( res ) ; }
Prepare an extended identifier for publish by removing namespace added by XSL transformation and encoding all relevant XML entities .
12,457
private static void removePrefixFromChildren ( Element el , String prefix ) throws MarshalException { NodeList nl = el . getChildNodes ( ) ; String localPrefix = null ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node n = nl . item ( i ) ; if ( n . getNodeType ( ) != Node . ELEMENT_NODE ) { continue ; } localPrefix = n . getPrefix ( ) ; if ( localPrefix != null && localPrefix . length ( ) > 0 ) { if ( ! localPrefix . equals ( prefix ) ) { IfmapJLog . warn ( "Extended Identifier: Multiple namespaces in extended identifer used." + "IfmapJ thinks this is not a wise idea. Sorry!" ) ; throw new MarshalException ( "Extended Identifier: Multiple namespaces in extended identifer used." + "IfmapJ thinks this is not a wise idea. Sorry!" ) ; } n . setPrefix ( null ) ; } removePrefixFromChildren ( ( Element ) n , prefix ) ; dropNamespaceDecls ( ( Element ) n ) ; } }
If any child of el has prefix as prefix remove it . drop all namespace decls on the way . If we find an element with a different prefix go crazy .
12,458
public static boolean compare ( Document d1 , Document d2 ) throws MarshalException { d1 . normalize ( ) ; d2 . normalize ( ) ; return d1 . isEqualNode ( d2 ) ; }
Compare two DOM documents
12,459
Set < Class < ? extends TrailWriter > > findTrailWriters ( ) { Set < Class < ? extends TrailWriter > > trailWriters = auditConfig . getWriters ( ) ; if ( trailWriters . isEmpty ( ) ) { LOGGER . info ( "No TrailWriter specified" ) ; } return trailWriters ; }
Finds the trail writers as configured in the props .
12,460
@ SuppressWarnings ( { "unchecked" } ) Set < Class < ? extends TrailExceptionHandler < ? > > > findTrailExceptionHandlers ( ) { Set < Class < ? extends TrailExceptionHandler < ? > > > trailExceptionHandlers = auditConfig . getExceptionHandlers ( ) ; if ( trailExceptionHandlers . isEmpty ( ) ) { Collection < Class < ? > > scannedTrailExceptionHandlers = auditClasses . get ( TrailExceptionHandler . class ) ; LOGGER . info ( "No audit TrailExceptionHandler specified, using every handler found" ) ; Set < Class < ? extends TrailExceptionHandler < ? > > > foundExceptionHandlers = new HashSet < > ( ) ; for ( Class < ? > scannedTrailExceptionHandler : scannedTrailExceptionHandlers ) { foundExceptionHandlers . add ( ( Class < ? extends TrailExceptionHandler < ? > > ) scannedTrailExceptionHandler ) ; LOGGER . info ( "Registered audit exception handler {}" , scannedTrailExceptionHandler ) ; } return foundExceptionHandlers ; } else { return trailExceptionHandlers ; } }
Finds the exception handlers as configured in the props .
12,461
public File outputDir ( File src , File explicitOutputDir , String mapperName ) throws IOException { File outputDir ; int prev ; int idx ; File subDir ; if ( explicitOutputDir == null ) { outputDir = src . getParentFile ( ) ; } else { outputDir = explicitOutputDir ; idx = mapperName . indexOf ( '.' ) ; prev = 0 ; while ( idx != - 1 ) { subDir = new File ( outputDir , mapperName . substring ( prev , idx ) ) ; if ( ! subDir . isDirectory ( ) ) { if ( ! subDir . mkdir ( ) ) { throw new IOException ( "cannot create directory: " + subDir ) ; } } prev = idx + 1 ; idx = mapperName . indexOf ( '.' , prev ) ; outputDir = subDir ; } } return outputDir ; }
creates new directory if necessary .
12,462
private void run ( Class < ? > type , Object val , int limit ) { int initial ; initial = dest . getSize ( ) ; if ( val == null ) { if ( type . isPrimitive ( ) ) { throw new IllegalArgumentException ( "primitive null" ) ; } dest . emit ( LDC , ( String ) null ) ; } else if ( val instanceof String ) { dest . emit ( LDC , ( String ) val ) ; } else if ( type . isPrimitive ( ) ) { primitive ( ClassRef . findComponent ( type ) . id , val ) ; } else if ( type . isArray ( ) ) { array ( type , val , limit ) ; } else { object ( type , val , limit ) ; } if ( dest . getSize ( ) - initial > limit ) { throw new IllegalStateException ( "limit:" + limit + " used:" + ( dest . getSize ( ) - initial ) + " val:" + val ) ; } }
type is the static type . If type is primitive the primitive object wrapped by val is compiled .
12,463
private void primitive ( int typeCode , Object obj ) { switch ( typeCode ) { case T_BOOLEAN : dest . emit ( LDC , ( ( Boolean ) obj ) . booleanValue ( ) ? 1 : 0 ) ; break ; case T_CHAR : dest . emit ( LDC , ( ( Character ) obj ) . charValue ( ) ) ; break ; case T_BYTE : case T_SHORT : dest . emit ( LDC , ( ( Number ) obj ) . intValue ( ) ) ; break ; case T_INT : case T_FLOAT : case T_LONG : case T_DOUBLE : dest . emitGeneric ( LDC , new Object [ ] { obj } ) ; break ; default : throw new IllegalArgumentException ( "not supported: " + typeCode ) ; } }
generates exactly 1 instruction .
12,464
private void charArray ( char [ ] vals , int limit ) { int len ; char c ; int left , right ; String str ; int instrsPerChunk = 6 ; int maxLen ; int used ; left = 0 ; len = vals . length ; maxLen = 3 + ( len / CHUNK + 1 ) * instrsPerChunk + 1 ; if ( limit < maxLen ) { pushMethod ( char . class ) ; if ( limit < maxLen ) { throw new IllegalStateException ( "array size ..." ) ; } charArray ( vals , MAX_INSTRUCTIONS ) ; popMethod ( ) ; return ; } dest . emit ( LDC , len ) ; ClassRef . CHAR . emitArrayNew ( dest ) ; dest . emit ( ASTORE , buffer ) ; while ( left < len ) { c = vals [ left ] ; if ( c != 0 ) { right = Math . min ( len , left + CHUNK ) ; used = right - left ; while ( used > 0 && vals [ left + used - 1 ] == 0 ) { used -- ; } if ( used > 0 ) { str = String . copyValueOf ( vals , left , used ) ; dest . emit ( LDC , str ) ; dest . emit ( LDC , 0 ) ; dest . emit ( LDC , used ) ; dest . emit ( ALOAD , buffer ) ; dest . emit ( LDC , left ) ; dest . emit ( INVOKEVIRTUAL , GET_CHARS ) ; left = right ; } else { } } else { left ++ ; } } dest . emit ( ALOAD , buffer ) ; }
reference on the operand stack
12,465
public void managed_send_and_receive_is_working ( ) throws JMSException { testSender1 . send ( "MANAGED" ) ; try { managed . await ( 1 , TimeUnit . SECONDS ) ; Assertions . assertThat ( textManaged ) . isEqualTo ( "MANAGED" ) ; } catch ( InterruptedException e ) { fail ( "Thread interrupted" ) ; } }
TestSender1 and TestMessageListener1 .
12,466
public void unmanaged_send_and_receive_is_working ( ) throws JMSException { testSender2 . send ( "UNMANAGED" ) ; try { unmanaged . await ( 1 , TimeUnit . SECONDS ) ; Assertions . assertThat ( textUnmanaged ) . isEqualTo ( "UNMANAGED" ) ; } catch ( InterruptedException e ) { fail ( "Thread interrupted" ) ; } }
TestSender2 and TestMessageListener2 .
12,467
public < T > T datastoreToJava ( Entity entity ) { try { if ( entity == null ) { return null ; } T result = ( T ) persistentClass . newInstance ( ) ; populate ( entity , result ) ; return result ; } catch ( InstantiationException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } }
Convert a value from Google representation to a Java value
12,468
public void populate ( Entity from , Object to ) { for ( Entry < String , Object > property : from . getProperties ( ) . entrySet ( ) ) { PropertyMetadata metadata = properties . get ( property . getKey ( ) ) ; if ( metadata != null ) { Object value = metadata . getConverter ( ) . datastoreToJava ( property . getValue ( ) ) ; metadata . setValue ( to , value ) ; } else { if ( log . isDebugEnabled ( ) ) { log . debug ( "Unmapped attribute found in DataStore entry. Ignoring: " + from . getKind ( ) + "." + property . getKey ( ) ) ; } } } keyProperty . setValue ( to , from . getKey ( ) ) ; }
Copy all properties from the datastore entity into the persistent class instance passed as an attribute .
12,469
public void validateConstraints ( Entity entity ) { for ( String propertyName : requiredProperties ) { Object value = entity . getProperty ( propertyName ) ; if ( value == null || ( value instanceof String && ( ( String ) value ) . length ( ) == 0 ) ) { throw new RequiredFieldException ( "Required property '" + this . persistentClass . getSimpleName ( ) + "." + propertyName + "' is not set" ) ; } } }
Validate the schema constraints on the provided Entity instance
12,470
public void validateParentKey ( Key parentKey ) { if ( parents . isEmpty ( ) ) { if ( parentKey != null ) { throw new IllegalArgumentException ( "Specified parent key " + parentKey + ", but entity " + this . persistentClass . getSimpleName ( ) + " is configured as a root class (missing @Id(parent)?)" ) ; } } else { if ( parentKey == null ) { throw new IllegalArgumentException ( "Missing parent key for entity " + this . persistentClass . getSimpleName ( ) + ". Expected: " + Joiner . on ( ", " ) . join ( parents ) ) ; } if ( ! parents . contains ( parentKey . getKind ( ) ) ) { throw new IllegalArgumentException ( "Specified parent key " + parentKey + ", but entity " + this . persistentClass . getSimpleName ( ) + " expects parents with type " + Joiner . on ( ", " ) . join ( parents ) ) ; } } }
Validates the parent key when inserting
12,471
public static < K , V > void putSetAll ( Map < K , Set < V > > map , Map < K , Set < V > > other ) { for ( Map . Entry < K , Set < V > > me : other . entrySet ( ) ) { putSetMult ( map , me . getKey ( ) , me . getValue ( ) ) ; } }
Copies all of the mappings from the second map to the first . The value for each key is the union of the first and second maps values for that key .
12,472
public static < K > boolean containsAny ( Set < K > aSet , K [ ] arr ) { for ( K obj : arr ) { if ( aSet . contains ( obj ) ) { return true ; } } return false ; }
Checks whether any of an array s elements are also in the provided set .
12,473
public HalResource read ( final Reader reader ) { final ContentRepresentation readableRepresentation = representationFactory . readRepresentation ( RepresentationFactory . HAL_JSON , reader ) ; return new HalResource ( objectMapper , readableRepresentation ) ; }
Read and return HalResource
12,474
public Set < Method > subscriptionsOn ( Object subscriber ) { SubscriptionMethodFilter filter = new SubscriptionMethodFilter ( ) ; Class < ? > subscriberClass = subscriber . getClass ( ) ; List < Method > methods = Arrays . asList ( subscriberClass . getMethods ( ) ) ; Set < Method > subscriptions = new HashSet < Method > ( ) ; for ( Method method : methods ) { if ( filter . accepts ( method ) ) { subscriptions . add ( method ) ; } } return subscriptions ; }
Report the subscription methods declared on the subscriber .
12,475
private static IdentifierHandler < ? extends Identifier > getExtendedIdentifierHandlerFor ( Element element ) { if ( ! checkExtendedIdentityElement ( element ) ) { return null ; } String name = element . getAttribute ( IfmapStrings . IDENTITY_ATTR_NAME ) ; Document extendedDocument ; try { extendedDocument = DomHelpers . parseEscapedXmlString ( name ) ; } catch ( UnmarshalException e ) { return null ; } Element extendedElement = extendedDocument . getDocumentElement ( ) ; String nodeName = extendedElement . getLocalName ( ) ; for ( Entry < Class < ? extends Identifier > , IdentifierHandler < ? extends Identifier > > entry : sIdentifierHandlers . entrySet ( ) ) { String simpleClassName = entry . getKey ( ) . getSimpleName ( ) ; if ( simpleClassName . equalsIgnoreCase ( nodeName ) ) { return entry . getValue ( ) ; } } return null ; }
If the element argument is an extended identity Identifier then try to find the most specific handler for this element . Used the Element - LocalName to find the right handler .
12,476
public static AccessRequest createArRandomUuid ( String admDom ) { return new AccessRequest ( java . util . UUID . randomUUID ( ) . toString ( ) , admDom ) ; }
Create an access - request identifier with an random UUID as name and administrative - domain as given .
12,477
public static Identity createOtherIdentity ( String name , String admDom , String otherTypeDef ) { return createIdentity ( IdentityType . other , name , admDom , otherTypeDef ) ; }
Create an other identity identifier .
12,478
public static IpAddress createIp4 ( String value , String admDom ) { return createIp ( IpAddressType . IPv4 , value , admDom ) ; }
Create an ip - address identifier for IPv4 with the given value and the given administrative - domain .
12,479
public static IpAddress createIp6 ( String value , String admDom ) { return createIp ( IpAddressType . IPv6 , value , admDom ) ; }
Create an ip - address identifier for IPv6 with the given parameters .
12,480
public static IpAddress createIp ( IpAddressType type , String value , String admDom ) { return new IpAddress ( type , value , admDom ) ; }
Create an ip - address identifier with the given parameters .
12,481
@ SuppressWarnings ( "unchecked" ) public < T > List < T > getAll ( Class < T > entityCls ) { if ( entityCls == null ) { throw new IllegalArgumentException ( "entityCls cannot be null" ) ; } EntityManager entityManager = this . entityManagerProvider . get ( ) ; CriteriaBuilder builder = entityManager . getCriteriaBuilder ( ) ; CriteriaQuery < T > criteriaQuery = builder . createQuery ( entityCls ) ; criteriaQuery . from ( entityCls ) ; TypedQuery < T > typedQuery = entityManager . createQuery ( criteriaQuery ) ; List < T > results = typedQuery . getResultList ( ) ; return results ; }
Gets every instance of the specified entity in the database .
12,482
public < T extends HistoricalEntity < ? > > List < T > getCurrent ( Class < T > historicalEntityCls ) { EntityManager entityManager = this . entityManagerProvider . get ( ) ; CriteriaBuilder builder = entityManager . getCriteriaBuilder ( ) ; CriteriaQuery < T > criteriaQuery = builder . createQuery ( historicalEntityCls ) ; Root < T > root = criteriaQuery . from ( historicalEntityCls ) ; criteriaQuery . where ( expiredAt ( root , builder ) ) ; TypedQuery < T > typedQuery = entityManager . createQuery ( criteriaQuery ) ; return typedQuery . getResultList ( ) ; }
Gets every instance of the specified historical entity in the database .
12,483
public < T extends HistoricalEntity < ? > , Y > T getCurrentUniqueByAttribute ( Class < T > historicalEntityCls , SingularAttribute < T , Y > attribute , Y value ) { EntityManager entityManager = this . entityManagerProvider . get ( ) ; CriteriaBuilder builder = entityManager . getCriteriaBuilder ( ) ; CriteriaQuery < T > criteriaQuery = builder . createQuery ( historicalEntityCls ) ; Root < T > root = criteriaQuery . from ( historicalEntityCls ) ; Predicate whereClause = builder . and ( builder . equal ( root . get ( attribute ) , value ) , expiredAt ( root , builder ) ) ; criteriaQuery . where ( whereClause ) ; TypedQuery < T > query = entityManager . createQuery ( criteriaQuery ) ; T result = null ; try { result = query . getSingleResult ( ) ; } catch ( NonUniqueResultException nure ) { LOGGER . warn ( "Result not unique for {}: {} = {}" , historicalEntityCls . getName ( ) , attribute . getName ( ) , value ) ; result = query . getResultList ( ) . get ( 0 ) ; } catch ( NoResultException nre ) { LOGGER . debug ( "Result not existant for {}: {} = {}" , historicalEntityCls . getName ( ) , attribute . getName ( ) , value ) ; } return result ; }
Gets the instance of the specified historical entity in the database that has the given value of the given attribute .
12,484
public < T extends HistoricalEntity < ? > , Y > List < T > getCurrentListByAttribute ( Class < T > historicalEntityCls , SingularAttribute < T , Y > attribute , Y value ) { EntityManager entityManager = this . entityManagerProvider . get ( ) ; CriteriaBuilder builder = entityManager . getCriteriaBuilder ( ) ; CriteriaQuery < T > criteriaQuery = builder . createQuery ( historicalEntityCls ) ; Root < T > root = criteriaQuery . from ( historicalEntityCls ) ; Predicate whereClause = builder . and ( builder . equal ( root . get ( attribute ) , value ) , expiredAt ( root , builder ) ) ; criteriaQuery . where ( whereClause ) ; TypedQuery < T > typedQuery = entityManager . createQuery ( criteriaQuery ) ; return typedQuery . getResultList ( ) ; }
Gets every instance of the specified historical entity in the database that has the given value of the given attribute .
12,485
public < T , Y > T getUniqueByAttribute ( Class < T > entityCls , String attributeName , Y value ) { if ( entityCls == null ) { throw new IllegalArgumentException ( "entityCls cannot be null" ) ; } if ( attributeName == null ) { throw new IllegalArgumentException ( "attributeName cannot be null" ) ; } TypedQuery < T > query = createTypedQuery ( entityCls , attributeName , value ) ; T result = null ; try { result = query . getSingleResult ( ) ; } catch ( NonUniqueResultException nure ) { LOGGER . warn ( "Result not unique for {}: {} = {}" , entityCls . getName ( ) , attributeName , value ) ; result = query . getResultList ( ) . get ( 0 ) ; } catch ( NoResultException nre ) { LOGGER . debug ( "Result not existant for {}: {} = {}" , entityCls . getName ( ) , attributeName , value ) ; } return result ; }
Executes a query for the entity with the given attribute value . This method assumes that at most one instance of the given entity will be a match . This typically is used with attributes with a uniqueness constraint .
12,486
public < T , Y > List < T > getListByAttribute ( Class < T > entityCls , SingularAttribute < T , Y > attribute , Y value ) { if ( entityCls == null ) { throw new IllegalArgumentException ( "entityCls cannot be null" ) ; } if ( attribute == null ) { throw new IllegalArgumentException ( "attribute cannot be null" ) ; } TypedQuery < T > query = createTypedQuery ( entityCls , attribute , value ) ; return query . getResultList ( ) ; }
Executes a query for the entities that have the specified value of the given attribute .
12,487
public < T , Y > List < T > getListByAttributeIn ( Class < T > entityCls , SingularAttribute < T , Y > attribute , List < Y > values ) { if ( entityCls == null ) { throw new IllegalArgumentException ( "entityCls cannot be null" ) ; } if ( attribute == null ) { throw new IllegalArgumentException ( "attribute cannot be null" ) ; } TypedQuery < T > query = createTypedQueryIn ( entityCls , attribute , values ) ; return query . getResultList ( ) ; }
Executes a query for entities that have any of the given attribute values .
12,488
private < T , Y > TypedQuery < T > createTypedQueryIn ( Class < T > entityCls , SingularAttribute < T , Y > attribute , List < Y > values ) { EntityManager entityManager = this . entityManagerProvider . get ( ) ; CriteriaBuilder builder = entityManager . getCriteriaBuilder ( ) ; CriteriaQuery < T > criteriaQuery = builder . createQuery ( entityCls ) ; Root < T > root = criteriaQuery . from ( entityCls ) ; Path < Y > path = root . get ( attribute ) ; CriteriaBuilder . In < Y > in = builder . in ( path ) ; if ( values != null ) { for ( Y val : values ) { in . value ( val ) ; } } return entityManager . createQuery ( criteriaQuery . where ( in ) ) ; }
Creates a typed query for entities that match any of the specified values of the given attribute .
12,489
private < T , Y > TypedQuery < T > createTypedQuery ( Class < T > entityCls , SingularAttribute < T , Y > attribute , Y value ) { EntityManager entityManager = this . entityManagerProvider . get ( ) ; CriteriaBuilder builder = entityManager . getCriteriaBuilder ( ) ; CriteriaQuery < T > criteriaQuery = builder . createQuery ( entityCls ) ; Root < T > root = criteriaQuery . from ( entityCls ) ; Path < Y > path = root . get ( attribute ) ; return entityManager . createQuery ( criteriaQuery . where ( builder . equal ( path , value ) ) ) ; }
Creates a typed query for entities that have the given attribute value .
12,490
private < T , Y extends Number > TypedQuery < T > createTypedQuery ( Class < T > entityCls , SingularAttribute < T , Y > attribute , SqlComparator comparator , Y value ) { EntityManager entityManager = this . entityManagerProvider . get ( ) ; CriteriaBuilder builder = entityManager . getCriteriaBuilder ( ) ; CriteriaQuery < T > criteriaQuery = builder . createQuery ( entityCls ) ; Root < T > root = criteriaQuery . from ( entityCls ) ; Path < Y > path = root . get ( attribute ) ; Predicate pred ; switch ( comparator ) { case LESS_THAN : pred = builder . lt ( path , value ) ; break ; case LESS_THAN_OR_EQUAL_TO : pred = builder . le ( path , value ) ; break ; case EQUAL_TO : pred = builder . equal ( path , value ) ; break ; case NOT_EQUAL_TO : pred = builder . notEqual ( path , value ) ; break ; case GREATER_THAN_OR_EQUAL_TO : pred = builder . ge ( path , value ) ; break ; case GREATER_THAN : pred = builder . gt ( path , value ) ; break ; default : throw new AssertionError ( "Invalid SQLComparator: " + comparator ) ; } return entityManager . createQuery ( criteriaQuery . where ( pred ) ) ; }
Creates a typed query for entities with the given numerical attribute value .
12,491
protected Response get ( ) { RequestBuilder getRequest = RequestBuilder . get ( ) . setUri ( url ) ; return executeHttpRequest ( getRequest ) ; }
execute a get request from the Request object configuration
12,492
protected Response post ( ) { RequestBuilder builder = RequestBuilder . post ( ) . setUri ( url ) ; return getResponseAfterDetectingType ( builder ) ; }
execute a post request for this Request object
12,493
public Request setHeader ( String name , String value ) { this . headers . put ( name , value ) ; return this ; }
seat a header and return modified request
12,494
public Request accept ( String headerValue ) { final String accept = RequestHeaderFields . ACCEPT . getName ( ) ; String acceptValue = headers . get ( accept ) ; if ( acceptValue == null ) { acceptValue = headerValue ; } else { acceptValue = acceptValue + ", " + headerValue ; } return this . setHeader ( accept , acceptValue ) ; }
sets the accept header for the request if exists then appends
12,495
public Request acceptEncoding ( String encoding ) { final String acceptEncoding = RequestHeaderFields . ACCEPT_ENCODING . getName ( ) ; String encodingValue = headers . get ( acceptEncoding ) ; if ( encodingValue == null ) { encodingValue = encoding ; } else { encodingValue = encodingValue + ", " + encoding ; } return this . setHeader ( acceptEncoding , encodingValue ) ; }
sets the accept encoding header for the request if exists then appends
12,496
public Request acceptLanguage ( String language ) { final String acceptLanguage = RequestHeaderFields . ACCEPT_LANGUAGE . getName ( ) ; String languageValue = headers . get ( acceptLanguage ) ; if ( languageValue == null ) { languageValue = language ; } else { languageValue = languageValue + ", " + language ; } return this . setHeader ( acceptLanguage , languageValue ) ; }
sets the accept language header for the request if exists then appends
12,497
public Request userAgent ( String userAgentValue ) { final String userAgent = RequestHeaderFields . USER_AGENT . getName ( ) ; String agent = headers . get ( userAgent ) ; if ( agent == null ) { agent = userAgentValue ; } else { agent = agent + " " + userAgentValue ; } return this . setHeader ( userAgent , agent ) ; }
sets the user agent header for the request if exists then appends
12,498
public Request referer ( String refererValue ) { final String referer = RequestHeaderFields . REFERER . getName ( ) ; return this . setHeader ( referer , refererValue ) ; }
sets the Referer header for the request
12,499
public Request authorization ( String authorizationValue ) { final String authorization = RequestHeaderFields . AUTHORIZATION . getName ( ) ; return this . setHeader ( authorization , authorizationValue ) ; }
sets the Authorization header for the request