idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
14,700
public Sight getSight ( long sightId , Integer level ) throws SmartsheetException { String path = "sights/" + sightId ; HashMap < String , Object > parameters = new HashMap < String , Object > ( ) ; if ( level != null ) { parameters . put ( "level" , level ) ; } path += QueryUtil . generateUrl ( null , parameters ) ; return this . getResource ( path , Sight . class ) ; }
Get a specified Sight .
14,701
public Sight updateSight ( Sight sight ) throws SmartsheetException { Util . throwIfNull ( sight ) ; return this . updateResource ( "sights/" + sight . getId ( ) , Sight . class , sight ) ; }
Update a specified Sight .
14,702
public SightPublish setPublishStatus ( long sightId , SightPublish sightPublish ) throws SmartsheetException { Util . throwIfNull ( sightPublish ) ; return this . updateResource ( "sights/" + sightId + "/publish" , SightPublish . class , sightPublish ) ; }
Sets the publish status of a Sight and returns the new status including the URLs of any enabled publishing .
14,703
public PagedResult < Template > listUserCreatedTemplates ( PaginationParameters parameters ) throws SmartsheetException { String path = "templates" ; if ( parameters != null ) { path += parameters . toQueryString ( ) ; } return this . listResourcesWithWrapper ( path , Template . class ) ; }
List user - created templates .
14,704
public Folder getFolder ( long folderId , EnumSet < SourceInclusion > includes ) throws SmartsheetException { String path = "folders/" + folderId ; HashMap < String , Object > parameters = new HashMap < String , Object > ( ) ; parameters . put ( "include" , QueryUtil . generateCommaSeparatedList ( includes ) ) ; path += QueryUtil . generateUrl ( null , parameters ) ; return this . getResource ( path , Folder . class ) ; }
Get a folder .
14,705
public Folder updateFolder ( Folder folder ) throws SmartsheetException { return this . updateResource ( "folders/" + folder . getId ( ) , Folder . class , folder ) ; }
Update a folder .
14,706
public PagedResult < Folder > listFolders ( long parentFolderId , PaginationParameters parameters ) throws SmartsheetException { String path = "folders/" + parentFolderId + "/folders" ; if ( parameters != null ) { path += parameters . toQueryString ( ) ; } return this . listResourcesWithWrapper ( path , Folder . class ) ; }
List child folders of a given folder .
14,707
public Folder createFolder ( long parentFolderId , Folder folder ) throws SmartsheetException { return this . createResource ( "folders/" + parentFolderId + "/folders" , Folder . class , folder ) ; }
Create a folder .
14,708
public Folder moveFolder ( long folderId , ContainerDestination containerDestination ) throws SmartsheetException { String path = "folders/" + folderId + "/move" ; return this . createResource ( path , Folder . class , containerDestination ) ; }
Moves the specified Folder to another location .
14,709
public SearchResult searchSheet ( long sheetId , String query ) throws SmartsheetException { Util . throwIfNull ( query ) ; Util . throwIfEmpty ( query ) ; try { return this . getResource ( "search/sheets/" + sheetId + "?query=" + URLEncoder . encode ( query , "utf-8" ) , SearchResult . class ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Performs a search within a sheet .
14,710
public Attachment attachUrl ( long sheetId , Attachment attachment ) throws SmartsheetException { return this . createResource ( "sheets/" + sheetId + "/attachments" , Attachment . class , attachment ) ; }
Attach a URL to a sheet .
14,711
public PagedResult < Attachment > listAttachments ( long sheetId , PaginationParameters parameters ) throws SmartsheetException { String path = "sheets/" + sheetId + "/attachments" ; if ( parameters != null ) { path += parameters . toQueryString ( ) ; } return this . listResourcesWithWrapper ( path , Attachment . class ) ; }
Gets a list of all Attachments that are on the Sheet including Sheet Row and Discussion level Attachments .
14,712
public OAuthFlow build ( ) { if ( httpClient == null ) { httpClient = new DefaultHttpClient ( ) ; } if ( tokenURL == null ) { tokenURL = DEFAULT_TOKEN_URL ; } if ( authorizationURL == null ) { authorizationURL = DEFAULT_AUTHORIZATION_URL ; } if ( jsonSerializer == null ) { jsonSerializer = new JacksonJsonSerializer ( ) ; } if ( clientId == null || clientSecret == null || redirectURL == null ) { throw new IllegalStateException ( ) ; } return new OAuthFlowImpl ( clientId , clientSecret , redirectURL , authorizationURL , tokenURL , httpClient , jsonSerializer ) ; }
Build the OAuthFlow instance .
14,713
public Folder createFolder ( long workspaceId , Folder folder ) throws SmartsheetException { return this . createResource ( "workspaces/" + workspaceId + "/folders" , Folder . class , folder ) ; }
Create a folder in the workspace .
14,714
public List < Favorite > addFavorites ( List < Favorite > favorites ) throws SmartsheetException { return this . postAndReceiveList ( "favorites/" , favorites , Favorite . class ) ; }
Adds one or more items to the user s list of Favorite items .
14,715
public PagedResult < Favorite > listFavorites ( PaginationParameters parameters ) throws SmartsheetException { String path = "favorites" ; if ( parameters != null ) { path += parameters . toQueryString ( ) ; } return this . listResourcesWithWrapper ( path , Favorite . class ) ; }
Gets a list of all of the user s Favorite items .
14,716
public static < T > String generateCommaSeparatedList ( Collection < T > list ) { if ( list == null || list . size ( ) == 0 ) { return "" ; } StringBuilder result = new StringBuilder ( ) ; for ( Object obj : list ) { result . append ( ',' ) . append ( obj . toString ( ) ) ; } return result . length ( ) == 0 ? "" : result . substring ( 1 ) ; }
Returns a comma seperated list of items as a string
14,717
protected static String generateQueryString ( Map < String , Object > parameters ) { if ( parameters == null || parameters . size ( ) == 0 ) { return "" ; } StringBuilder result = new StringBuilder ( ) ; try { for ( Map . Entry < String , Object > entry : parameters . entrySet ( ) ) { if ( entry . getKey ( ) != null && ( entry . getValue ( ) != null && ! entry . getValue ( ) . toString ( ) . equals ( "" ) ) ) { result . append ( '&' ) . append ( URLEncoder . encode ( entry . getKey ( ) , "utf-8" ) ) . append ( "=" ) . append ( URLEncoder . encode ( entry . getValue ( ) . toString ( ) , "utf-8" ) ) ; } } } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } return result . length ( ) == 0 ? "" : "?" + result . substring ( 1 ) ; }
Returns a query string .
14,718
public static Message errorMessage ( String detailMessage ) { Message message = new Message ( ) ; message . setDetailMessage ( detailMessage ) ; message . setSeverity ( "ERROR" ) ; message . setType ( "" ) ; return message ; }
Returns a Message with Severity set to ERROR and the detailMessage set to what is passed in .
14,719
public void handleJsonArrayToJavaString ( String name , Object value ) { try { PropertyUtils . setProperty ( this , name , this . convertListToString ( value ) ) ; } catch ( IllegalAccessException e ) { log . debug ( "Error setting field " + name + " with value " + value + " on entity " + this . getClass ( ) . getSimpleName ( ) ) ; this . additionalProperties . put ( name , value ) ; } catch ( InvocationTargetException e ) { log . debug ( "Error setting field " + name + " with value " + value + " on entity " + this . getClass ( ) . getSimpleName ( ) ) ; this . additionalProperties . put ( name , value ) ; } catch ( NoSuchMethodException e ) { log . debug ( "Error setting field " + name + " with value " + value + " on entity " + this . getClass ( ) . getSimpleName ( ) ) ; this . additionalProperties . put ( name , value ) ; } }
Unknown properties are handled here . One main purpose of this method is to handle String values that are sent as json arrays if configured as multi - values in bh .
14,720
public String convertListToString ( Object listOrString ) { if ( listOrString == null ) { return null ; } if ( listOrString instanceof Collection ) { List < String > list = ( List < String > ) listOrString ; return StringUtils . join ( list , "," ) ; } return listOrString . toString ( ) ; }
Handles the fact that bh rest api sends Strings as json arrays if they are setup as multipickers in the fieldmaps .
14,721
private ObjectMapper createObjectMapper ( ) { ObjectMapper mapper = new ObjectMapper ( ) ; mapper . registerModule ( new JodaModule ( ) ) ; mapper . configure ( SerializationFeature . INDENT_OUTPUT , true ) ; return mapper ; }
Create the ObjectMapper that deserializes entity to json String .
14,722
public < T > T jsonToEntityUnwrapRoot ( String jsonString , Class < T > type ) { return jsonToEntity ( jsonString , type , this . objectMapperWrapped ) ; }
Converts a jsonString to an object of type T . Unwraps from root most often this means that the data tag is ignored and that the entity is created from within that data tag .
14,723
public < T extends BullhornEntity > String convertEntityToJsonString ( T entity ) { String jsonString = "" ; try { jsonString = objectMapperStandard . writeValueAsString ( entity ) ; } catch ( JsonProcessingException e ) { log . error ( "Error deserializing entity of type" + entity . getClass ( ) + " to jsonString." , e ) ; } return jsonString ; }
Takes a BullhornEntity and converts it to a String in json format .
14,724
public Map < String , String > getUriVariablesForEntity ( BullhornEntityInfo entityInfo , Integer id , Set < String > fieldSet , EntityParams params ) { if ( params == null ) { params = ParamFactory . entityParams ( ) ; } Map < String , String > uriVariables = params . getParameterMap ( ) ; this . addCommonUriVariables ( fieldSet , entityInfo , uriVariables ) ; uriVariables . put ( ID , id == null ? "" : id . toString ( ) ) ; return uriVariables ; }
Returns the uri variables needed for an entity GET
14,725
public Map < String , String > getUriVariablesForEntityDelete ( BullhornEntityInfo entityInfo , Integer id ) { Map < String , String > uriVariables = new LinkedHashMap < String , String > ( ) ; addModifyingUriVariables ( uriVariables , entityInfo ) ; uriVariables . put ( ID , id . toString ( ) ) ; return uriVariables ; }
Returns the uri variables needed for an entity DELETE
14,726
public Map < String , String > getUriVariablesForEntityInsert ( BullhornEntityInfo entityInfo ) { Map < String , String > uriVariables = new LinkedHashMap < String , String > ( ) ; addModifyingUriVariables ( uriVariables , entityInfo ) ; return uriVariables ; }
Returns the uri variables needed for the entity PUT request .
14,727
public Map < String , String > getUriVariablesForQueryWithPost ( BullhornEntityInfo entityInfo , Set < String > fieldSet , QueryParams params ) { Map < String , String > uriVariables = params . getParameterMap ( ) ; this . addCommonUriVariables ( fieldSet , entityInfo , uriVariables ) ; return uriVariables ; }
Returns the uri variables needed for a query request minus where since that will be in the body
14,728
public Map < String , String > getUriVariablesForQuery ( BullhornEntityInfo entityInfo , String where , Set < String > fieldSet , QueryParams params ) { Map < String , String > uriVariables = params . getParameterMap ( ) ; this . addCommonUriVariables ( fieldSet , entityInfo , uriVariables ) ; uriVariables . put ( WHERE , where ) ; return uriVariables ; }
Returns the uri variables needed for a query request
14,729
public Map < String , String > getUriVariablesForSearchWithPost ( BullhornEntityInfo entityInfo , Set < String > fieldSet , SearchParams params ) { Map < String , String > uriVariables = params . getParameterMap ( ) ; this . addCommonUriVariables ( fieldSet , entityInfo , uriVariables ) ; return uriVariables ; }
Returns the uri variables needed for a search request minus query
14,730
public Map < String , String > getUriVariablesForSearch ( BullhornEntityInfo entityInfo , String query , Set < String > fieldSet , SearchParams params ) { Map < String , String > uriVariables = params . getParameterMap ( ) ; this . addCommonUriVariables ( fieldSet , entityInfo , uriVariables ) ; uriVariables . put ( QUERY , query ) ; return uriVariables ; }
Returns the uri variables needed for a search request
14,731
public Map < String , String > getUriVariablesForIdSearch ( BullhornEntityInfo entityInfo , String query , SearchParams params ) { Map < String , String > uriVariables = params . getParameterMap ( ) ; uriVariables . put ( BH_REST_TOKEN , bullhornApiRest . getBhRestToken ( ) ) ; uriVariables . put ( ENTITY_TYPE , entityInfo . getName ( ) ) ; uriVariables . put ( QUERY , query ) ; return uriVariables ; }
Returns the uri variables needed for a id search request
14,732
public Map < String , String > getUriVariablesForResumeFileParse ( ResumeFileParseParams params , MultipartFile resume ) { if ( params == null ) { params = ParamFactory . resumeFileParseParams ( ) ; } Map < String , String > uriVariables = params . getParameterMap ( ) ; String bhRestToken = bullhornApiRest . getBhRestToken ( ) ; uriVariables . put ( BH_REST_TOKEN , bhRestToken ) ; uriVariables . put ( FORMAT , restFileManager . getFileParam ( resume ) ) ; return uriVariables ; }
Returns the uri variables needed for a resume file request
14,733
public Map < String , String > getUriVariablesForResumeTextParse ( ResumeTextParseParams params ) { if ( params == null ) { params = ParamFactory . resumeTextParseParams ( ) ; } Map < String , String > uriVariables = params . getParameterMap ( ) ; String bhRestToken = bullhornApiRest . getBhRestToken ( ) ; uriVariables . put ( BH_REST_TOKEN , bhRestToken ) ; return uriVariables ; }
Returns the uri variables needed for a resume text request
14,734
public Map < String , String > getUriVariablesForGetFile ( BullhornEntityInfo entityInfo , Integer entityId , Integer fileId ) { Map < String , String > uriVariables = new LinkedHashMap < String , String > ( ) ; String bhRestToken = bullhornApiRest . getBhRestToken ( ) ; uriVariables . put ( BH_REST_TOKEN , bhRestToken ) ; uriVariables . put ( ENTITY_TYPE , entityInfo . getName ( ) ) ; uriVariables . put ( ENTITY_ID , entityId . toString ( ) ) ; uriVariables . put ( FILE_ID , fileId . toString ( ) ) ; return uriVariables ; }
Returns the uri variables needed for a get file request
14,735
public Map < String , String > getUriVariablesForCorpNotes ( Integer clientCorporationID , Set < String > fieldSet , CorpNotesParams params ) { if ( params == null ) { params = ParamFactory . corpNotesParams ( ) ; } Map < String , String > uriVariables = params . getParameterMap ( ) ; String bhRestToken = bullhornApiRest . getBhRestToken ( ) ; uriVariables . put ( BH_REST_TOKEN , bhRestToken ) ; String fields = this . convertFieldSetToString ( fieldSet ) ; uriVariables . put ( FIELDS , fields ) ; uriVariables . put ( CLIENT_CORP_ID , clientCorporationID . toString ( ) ) ; return uriVariables ; }
Returns the uri variables needed for a get corp notes call
14,736
private void addModifyingUriVariables ( Map < String , String > uriVariables , BullhornEntityInfo entityInfo ) { String bhRestToken = bullhornApiRest . getBhRestToken ( ) ; uriVariables . put ( BH_REST_TOKEN , bhRestToken ) ; uriVariables . put ( ENTITY_TYPE , entityInfo . getName ( ) ) ; uriVariables . put ( EXECUTE_FORM_TRIGGERS , bullhornApiRest . getExecuteFormTriggers ( ) ? "true" : "false" ) ; }
Adds common URI Variables for calls that are creating updating or deleting data .
14,737
public Map < String , String > getUriVariablesForFastFind ( String query , FastFindParams params ) { Map < String , String > uriVariables = params . getParameterMap ( ) ; uriVariables . put ( BH_REST_TOKEN , bullhornApiRest . getBhRestToken ( ) ) ; uriVariables . put ( QUERY , query ) ; return uriVariables ; }
Returns the uri variables needed for a fastFind request
14,738
protected < C extends CrudResponse , T extends UpdateEntity > List < C > handleMultipleUpdates ( List < T > entityList ) { if ( entityList == null || entityList . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < EntityUpdateWorker < C > > taskList = new ArrayList < EntityUpdateWorker < C > > ( ) ; for ( T entity : entityList ) { taskList . add ( new EntityUpdateWorker < C > ( this , entity ) ) ; } return concurrencyService . spinThreadsAndWaitForResult ( taskList ) ; }
Spins off threads that will call handleUpdateEntity for each entity .
14,739
protected < P extends ParsedResume > P handleParseResumeText ( String resume , ResumeTextParseParams params ) { Map < String , String > uriVariables = restUriVariablesFactory . getUriVariablesForResumeTextParse ( params ) ; String url = restUrlFactory . assembleParseResumeTextUrl ( params ) ; JSONObject resumeInfoToPost = new JSONObject ( ) ; try { resumeInfoToPost . put ( "resume" , resume ) ; } catch ( JSONException e ) { log . error ( "Error creating JsonObject with resume text." , e ) ; } String jsonEncodedResume = resumeInfoToPost . toString ( ) ; ParsedResume response = this . parseResume ( url , jsonEncodedResume , uriVariables ) ; return ( P ) response ; }
Handles the parsing of a resume text . Contains retry logic .
14,740
protected ParsedResume parseResume ( String url , Object requestPayLoad , Map < String , String > uriVariables ) { ParsedResume response = null ; for ( int tryNumber = 1 ; tryNumber <= RESUME_PARSE_RETRY ; tryNumber ++ ) { try { response = this . performPostResumeRequest ( url , requestPayLoad , uriVariables ) ; break ; } catch ( HttpStatusCodeException error ) { response = handleResumeParseError ( tryNumber , error ) ; } catch ( Exception e ) { log . error ( "error" , e ) ; } } return response ; }
Makes the call to the resume parser . If parse fails this method will retry RESUME_PARSE_RETRY number of times .
14,741
protected List < FileWrapper > handleGetAllFileContentWithMetaData ( Class < ? extends FileEntity > type , Integer entityId ) { List < FileMeta > metaDataList = this . handleGetEntityMetaFiles ( type , entityId ) ; ExecutorService executor = Executors . newFixedThreadPool ( Runtime . getRuntime ( ) . availableProcessors ( ) ) ; List < Future < FileContent > > futureList = new ArrayList < Future < FileContent > > ( ) ; for ( FileMeta metaData : metaDataList ) { FileWorker fileWorker = new FileWorker ( entityId , metaData . getId ( ) , type , this ) ; Future < FileContent > fileContent = executor . submit ( fileWorker ) ; futureList . add ( fileContent ) ; } Map < Integer , FileContent > fileContentMap = new HashMap < Integer , FileContent > ( ) ; for ( Future < FileContent > future : futureList ) { try { fileContentMap . put ( future . get ( ) . getId ( ) , future . get ( ) ) ; } catch ( InterruptedException e ) { log . error ( "Error in bullhornapirest.getAllFileContentWithMetaData" , e ) ; } catch ( ExecutionException e ) { log . error ( "Error in bullhornapirest.getAllFileContentWithMetaData" , e ) ; } } executor . shutdown ( ) ; while ( ! executor . isTerminated ( ) ) { } executor = null ; List < FileWrapper > fileWrapperList = new ArrayList < FileWrapper > ( ) ; for ( FileMeta metaData : metaDataList ) { FileContent fileContent = fileContentMap . get ( metaData . getId ( ) ) ; FileWrapper fileWrapper = new StandardFileWrapper ( fileContent , metaData ) ; fileWrapperList . add ( fileWrapper ) ; } return fileWrapperList ; }
This method will get all the meta data and then handle the fetching of FileContent in a multi - threaded fashion .
14,742
protected FileWrapper handleGetFileContentWithMetaData ( Class < ? extends FileEntity > type , Integer entityId , Integer fileId ) { FileWrapper fileWrapper = null ; try { FileContent fileContent = this . handleGetFileContent ( type , entityId , fileId ) ; List < FileMeta > metaDataList = this . handleGetEntityMetaFiles ( type , entityId ) ; FileMeta correctMetaData = null ; for ( FileMeta metaData : metaDataList ) { if ( fileId . equals ( metaData . getId ( ) ) ) { correctMetaData = metaData ; break ; } } fileWrapper = new StandardFileWrapper ( fileContent , correctMetaData ) ; } catch ( Exception e ) { log . error ( "Error getting file with id: " + fileId + " for " + type . getSimpleName ( ) + " with id:" + entityId ) ; } return fileWrapper ; }
Makes the api call to get both the file content and filemeta data and combines those two to a FileWrapper
14,743
protected List < FileMeta > handleGetEntityMetaFiles ( Class < ? extends FileEntity > type , Integer entityId ) { Map < String , String > uriVariables = restUriVariablesFactory . getUriVariablesForGetEntityMetaFiles ( BullhornEntityInfo . getTypesRestEntityName ( type ) , entityId ) ; String url = restUrlFactory . assembleGetEntityMetaFilesUrl ( ) ; String jsonString = this . performGetRequest ( url , String . class , uriVariables ) ; EntityMetaFiles < ? extends FileMeta > entityMetaFiles = restJsonConverter . jsonToEntityDoNotUnwrapRoot ( jsonString , StandardEntityMetaFiles . class ) ; if ( entityMetaFiles == null || entityMetaFiles . getFileMetas ( ) == null ) { return Collections . emptyList ( ) ; } return ( List < FileMeta > ) entityMetaFiles . getFileMetas ( ) ; }
Makes the api call to get the FileMeta data for an entity
14,744
protected FileContent handleGetFileContent ( Class < ? extends FileEntity > type , Integer entityId , Integer fileId ) { Map < String , String > uriVariables = restUriVariablesFactory . getUriVariablesForGetFile ( BullhornEntityInfo . getTypesRestEntityName ( type ) , entityId , fileId ) ; String url = restUrlFactory . assembleGetFileUrl ( ) ; String jsonString = this . performGetRequest ( url , String . class , uriVariables ) ; FileContent fileContent = restJsonConverter . jsonToEntityUnwrapRoot ( jsonString , StandardFileContent . class ) ; fileContent . setId ( fileId ) ; return fileContent ; }
Makes the api call to get the file content
14,745
protected FileWrapper handleAddFileWithMultipartFile ( Class < ? extends FileEntity > type , Integer entityId , MultipartFile multipartFile , String externalId , FileParams params , boolean deleteFile ) { MultiValueMap < String , Object > multiValueMap = null ; try { multiValueMap = restFileManager . addFileToMultiValueMap ( multipartFile ) ; } catch ( IOException e ) { log . error ( "Error creating temp file" , e ) ; } Map < String , String > uriVariables = restUriVariablesFactory . getUriVariablesForAddFile ( BullhornEntityInfo . getTypesRestEntityName ( type ) , entityId , externalId , params ) ; String url = restUrlFactory . assembleAddFileUrl ( params ) ; return this . handleAddFile ( type , entityId , multiValueMap , url , uriVariables , multipartFile . getOriginalFilename ( ) , deleteFile ) ; }
Makes the api call to add files to an entity . Takes a MultipartFile .
14,746
protected FileWrapper handleAddFileAndUpdateCandidateDescription ( Integer candidateId , File file , String candidateDescription , String externalId , FileParams params , boolean deleteFile ) { FileWrapper fileWrapper = this . handleAddFileWithFile ( Candidate . class , candidateId , file , externalId , params , deleteFile ) ; try { Candidate candidateToUpdate = new Candidate ( ) ; candidateToUpdate . setId ( candidateId ) ; if ( ! StringUtils . isBlank ( candidateDescription ) ) { candidateToUpdate . setDescription ( candidateDescription ) ; this . updateEntity ( candidateToUpdate ) ; } } catch ( Exception e ) { log . error ( "Error reading file to resume text" , e ) ; } return fileWrapper ; }
Handles logic to add the file to the candidate entity AND updating the candidate . description with the resume text .
14,747
protected < P extends ParsedResume > P addFileThenHandleParseResume ( Class < ? extends FileEntity > type , Integer entityId , MultipartFile multipartFile , String externalId , FileParams fileParams , ResumeFileParseParams params ) { FileWrapper fileWrapper = handleAddFileWithMultipartFile ( type , entityId , multipartFile , externalId , fileParams , true ) ; P parsedResume = this . handleParseResumeFile ( multipartFile , params ) ; if ( ! parsedResume . isError ( ) ) { parsedResume . setFileWrapper ( fileWrapper ) ; } return parsedResume ; }
Makes the api call to both parse the resume and then attach the file . File is only attached if the resume parse was successful .
14,748
protected FileApiResponse handleDeleteFile ( Class < ? extends FileEntity > type , Integer entityId , Integer fileId ) { Map < String , String > uriVariables = restUriVariablesFactory . getUriVariablesDeleteFile ( BullhornEntityInfo . getTypesRestEntityName ( type ) , entityId , fileId ) ; String url = restUrlFactory . assembleDeleteFileUrl ( ) ; StandardFileApiResponse fileApiResponse = this . performCustomRequest ( url , null , StandardFileApiResponse . class , uriVariables , HttpMethod . DELETE , null ) ; return fileApiResponse ; }
Makes the api call to delete a file attached to an entity .
14,749
protected < C extends CrudResponse , T extends AssociationEntity > C handleAssociateWithEntity ( Class < T > type , Integer entityId , AssociationField < T , ? extends BullhornEntity > associationName , Set < Integer > associationIds ) { Map < String , String > uriVariables = restUriVariablesFactory . getUriVariablesForAssociateWithEntity ( BullhornEntityInfo . getTypesRestEntityName ( type ) , entityId , associationName , associationIds ) ; String url = restUrlFactory . assembleEntityUrlForAssociateWithEntity ( ) ; CrudResponse response = null ; try { response = this . performCustomRequest ( url , null , CreateResponse . class , uriVariables , HttpMethod . PUT , null ) ; } catch ( HttpStatusCodeException error ) { response = restErrorHandler . handleHttpFourAndFiveHundredErrors ( new CreateResponse ( ) , error , entityId ) ; } return ( C ) response ; }
Makes the api call to create associations .
14,750
public < T extends BullhornEntity > CrudResponse handleHttpFourAndFiveHundredErrors ( CrudResponse response , HttpStatusCodeException error , Integer id ) { response . setChangedEntityId ( id ) ; Message message = new Message ( ) ; message . setDetailMessage ( error . getResponseBodyAsString ( ) ) ; message . setSeverity ( "ERROR" ) ; message . setType ( error . getStatusCode ( ) . toString ( ) ) ; response . addOneMessage ( message ) ; response . setErrorCode ( error . getStatusCode ( ) . toString ( ) ) ; response . setErrorMessage ( error . getResponseBodyAsString ( ) ) ; return response ; }
Updates the passed in CrudResponse with the HttpStatusCodeException thrown by the RestTemplate .
14,751
private void displayMBeans ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { Iterator mbeans ; try { mbeans = getDomainData ( ) ; } catch ( Exception e ) { throw new ServletException ( "Failed to get MBeans" , e ) ; } request . setAttribute ( "mbeans" , mbeans ) ; RequestDispatcher rd = this . getServletContext ( ) . getRequestDispatcher ( "/displaymbeans.jsp" ) ; rd . forward ( request , response ) ; }
Display all MBeans
14,752
private void inspectMBean ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { String name = request . getParameter ( "name" ) ; if ( trace ) log . trace ( "inspectMBean, name=" + name ) ; try { MBeanData data = getMBeanData ( name ) ; request . setAttribute ( "mbeanData" , data ) ; RequestDispatcher rd = this . getServletContext ( ) . getRequestDispatcher ( "/inspectmbean.jsp" ) ; rd . forward ( request , response ) ; } catch ( Exception e ) { throw new ServletException ( "Failed to get MBean data" , e ) ; } }
Display a MBeans attributes and operations
14,753
private void updateAttributes ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { String name = request . getParameter ( "name" ) ; if ( trace ) log . trace ( "updateAttributes, name=" + name ) ; Enumeration paramNames = request . getParameterNames ( ) ; HashMap < String , String > attributes = new HashMap < String , String > ( ) ; while ( paramNames . hasMoreElements ( ) ) { String param = ( String ) paramNames . nextElement ( ) ; if ( param . equals ( "name" ) || param . equals ( "action" ) ) continue ; String value = request . getParameter ( param ) ; if ( trace ) log . trace ( "name=" + param + ", value='" + value + "'" ) ; if ( value == null || value . length ( ) == 0 ) continue ; attributes . put ( param , value ) ; } try { AttributeList newAttributes = setAttributes ( name , attributes ) ; MBeanData data = getMBeanData ( name ) ; request . setAttribute ( "mbeanData" , data ) ; RequestDispatcher rd = this . getServletContext ( ) . getRequestDispatcher ( "/inspectmbean.jsp" ) ; rd . forward ( request , response ) ; } catch ( Exception e ) { throw new ServletException ( "Failed to update attributes" , e ) ; } }
Update the writable attributes of a MBean
14,754
private void invokeOpByName ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { String name = request . getParameter ( "name" ) ; if ( trace ) log . trace ( "invokeOpByName, name=" + name ) ; String [ ] argTypes = request . getParameterValues ( "argType" ) ; String [ ] args = getArgs ( request ) ; String methodName = request . getParameter ( "methodName" ) ; if ( methodName == null ) throw new ServletException ( "No methodName given in invokeOpByName form" ) ; try { OpResultInfo opResult = invokeOpByName ( name , methodName , argTypes , args ) ; request . setAttribute ( "opResultInfo" , opResult ) ; RequestDispatcher rd = this . getServletContext ( ) . getRequestDispatcher ( "/displayopresult.jsp" ) ; rd . forward ( request , response ) ; } catch ( Exception e ) { throw new ServletException ( "Failed to invoke operation" , e ) ; } }
Invoke a MBean operation given the method name and its signature .
14,755
private MBeanData getMBeanData ( final String name ) throws PrivilegedActionException { return AccessController . doPrivileged ( new PrivilegedExceptionAction < MBeanData > ( ) { public MBeanData run ( ) throws Exception { return Server . getMBeanData ( name ) ; } } ) ; }
Get the MBean data for a bean
14,756
@ SuppressWarnings ( { "unchecked" } ) private AttributeList setAttributes ( final String name , final HashMap attributes ) throws PrivilegedActionException { return AccessController . doPrivileged ( new PrivilegedExceptionAction < AttributeList > ( ) { public AttributeList run ( ) throws Exception { return Server . setAttributes ( name , attributes ) ; } } ) ; }
Set attributes on a MBean
14,757
private void writeTransaction ( Definition def , Writer out , int indent ) throws IOException { writeWithIndent ( out , indent , "/**\n" ) ; writeWithIndent ( out , indent , " * Returns an <code>javax.resource.spi.LocalTransaction</code> instance.\n" ) ; writeWithIndent ( out , indent , " *\n" ) ; writeWithIndent ( out , indent , " * @return LocalTransaction instance\n" ) ; writeWithIndent ( out , indent , " * @throws ResourceException generic exception if operation fails\n" ) ; writeWithIndent ( out , indent , " */\n" ) ; writeWithIndent ( out , indent , "public LocalTransaction getLocalTransaction() throws ResourceException" ) ; writeLeftCurlyBracket ( out , indent ) ; if ( def . getSupportTransaction ( ) . equals ( "NoTransaction" ) ) { writeWithIndent ( out , indent + 1 , "throw new NotSupportedException(\"getLocalTransaction() not supported\");" ) ; } else { writeLogging ( def , out , indent + 1 , "trace" , "getLocalTransaction" ) ; writeWithIndent ( out , indent + 1 , "return null;" ) ; } writeRightCurlyBracket ( out , indent ) ; writeEol ( out ) ; writeWithIndent ( out , indent , "/**\n" ) ; writeWithIndent ( out , indent , " * Returns an <code>javax.transaction.xa.XAresource</code> instance. \n" ) ; writeWithIndent ( out , indent , " *\n" ) ; writeWithIndent ( out , indent , " * @return XAResource instance\n" ) ; writeWithIndent ( out , indent , " * @throws ResourceException generic exception if operation fails\n" ) ; writeWithIndent ( out , indent , " */\n" ) ; writeWithIndent ( out , indent , "public XAResource getXAResource() throws ResourceException" ) ; writeLeftCurlyBracket ( out , indent ) ; if ( def . getSupportTransaction ( ) . equals ( "NoTransaction" ) ) { writeWithIndent ( out , indent + 1 , "throw new NotSupportedException(\"getXAResource() not supported\");" ) ; } else { writeLogging ( def , out , indent + 1 , "trace" , "getXAResource" ) ; writeWithIndent ( out , indent + 1 , "return null;" ) ; } writeRightCurlyBracket ( out , indent ) ; writeEol ( out ) ; }
Output Transaction method
14,758
private static Class < ? > [ ] getFields ( Class < ? > clz ) { List < Class < ? > > result = new ArrayList < Class < ? > > ( ) ; Class < ? > c = clz ; while ( ! c . equals ( Object . class ) ) { try { Field [ ] fields = SecurityActions . getDeclaredFields ( c ) ; if ( fields . length > 0 ) { for ( Field f : fields ) { Class < ? > defClz = f . getType ( ) ; String defClzName = defClz . getName ( ) ; if ( ! defClz . isPrimitive ( ) && ! defClz . isArray ( ) && ! defClzName . startsWith ( "java" ) && ! defClzName . startsWith ( "javax" ) && ! result . contains ( defClz ) ) { if ( trace ) log . tracef ( "Adding field: %s" , defClzName ) ; result . add ( defClz ) ; } } } } catch ( Throwable t ) { } c = c . getSuperclass ( ) ; } return result . toArray ( new Class < ? > [ result . size ( ) ] ) ; }
Get the classes for all the fields
14,759
public void execute ( Runnable job ) { try { executor . execute ( job ) ; } catch ( RejectedExecutionException e ) { log . warnf ( e , "Job rejected: %s" , job ) ; } }
Execute a job
14,760
public int getIdleThreads ( ) { if ( executor instanceof ThreadPoolExecutor ) { final ThreadPoolExecutor tpe = ( ThreadPoolExecutor ) executor ; return tpe . getPoolSize ( ) - tpe . getActiveCount ( ) ; } return - 1 ; }
Get the number of idle threads
14,761
public boolean isLowOnThreads ( ) { if ( executor instanceof ThreadPoolExecutor ) { final ThreadPoolExecutor tpe = ( ThreadPoolExecutor ) executor ; return tpe . getActiveCount ( ) >= tpe . getMaximumPoolSize ( ) ; } return false ; }
Is the pool low on threads ?
14,762
public static Pool createPool ( String type , ConnectionManager cm , PoolConfiguration pc ) { if ( type == null || type . equals ( "" ) ) return new DefaultPool ( cm , pc ) ; type = type . toLowerCase ( Locale . US ) ; switch ( type ) { case "default" : return new DefaultPool ( cm , pc ) ; case "stable" : return new StablePool ( cm , pc ) ; default : { Class < ? extends Pool > clz = customPoolTypes . get ( type ) ; if ( clz == null ) throw new RuntimeException ( type + " can not be found" ) ; try { Constructor constructor = clz . getConstructor ( ConnectionManager . class , PoolConfiguration . class ) ; return ( Pool ) constructor . newInstance ( cm , pc ) ; } catch ( Exception e ) { throw new RuntimeException ( type + " can not be created" , e ) ; } } } }
Create a pool
14,763
static Set < PasswordCredential > getPasswordCredentials ( final Subject subject ) { if ( System . getSecurityManager ( ) == null ) return subject . getPrivateCredentials ( PasswordCredential . class ) ; return AccessController . doPrivileged ( new PrivilegedAction < Set < PasswordCredential > > ( ) { public Set < PasswordCredential > run ( ) { return subject . getPrivateCredentials ( PasswordCredential . class ) ; } } ) ; }
Get the PasswordCredential from the Subject
14,764
static StackTraceElement [ ] getStackTrace ( final Thread t ) { if ( System . getSecurityManager ( ) == null ) return t . getStackTrace ( ) ; return AccessController . doPrivileged ( new PrivilegedAction < StackTraceElement [ ] > ( ) { public StackTraceElement [ ] run ( ) { return t . getStackTrace ( ) ; } } ) ; }
Get stack trace
14,765
public static void main ( String [ ] args ) { boolean quiet = false ; String outputDir = "." ; int arg = 0 ; String [ ] classpath = null ; if ( args . length > 0 ) { while ( args . length > arg + 1 ) { if ( args [ arg ] . startsWith ( "-" ) ) { if ( args [ arg ] . endsWith ( "quiet" ) ) { quiet = true ; } else if ( args [ arg ] . endsWith ( "output" ) ) { arg ++ ; if ( arg + 1 >= args . length ) { usage ( ) ; System . exit ( OTHER ) ; } outputDir = args [ arg ] ; } else if ( args [ arg ] . endsWith ( "classpath" ) ) { arg ++ ; classpath = args [ arg ] . split ( System . getProperty ( "path.separator" ) ) ; } } else { usage ( ) ; System . exit ( OTHER ) ; } arg ++ ; } try { int systemExitCode = Validation . validate ( new File ( args [ arg ] ) . toURI ( ) . toURL ( ) , outputDir , classpath ) ; if ( ! quiet ) { if ( systemExitCode == SUCCESS ) { System . out . println ( "Validation sucessful" ) ; } else if ( systemExitCode == FAIL ) { System . out . println ( "Validation errors" ) ; } else if ( systemExitCode == OTHER ) { System . out . println ( "Validation unknown" ) ; } } System . exit ( systemExitCode ) ; } catch ( ArrayIndexOutOfBoundsException oe ) { usage ( ) ; System . exit ( OTHER ) ; } catch ( MalformedURLException e ) { e . printStackTrace ( ) ; } } else { usage ( ) ; } System . exit ( SUCCESS ) ; }
Validator standalone tool
14,766
protected LocalXAResource getLocalXAResource ( ManagedConnection mc ) throws ResourceException { TransactionalConnectionManager txCM = ( TransactionalConnectionManager ) cm ; LocalXAResource xaResource = null ; String eisProductName = null ; String eisProductVersion = null ; String jndiName = cm . getConnectionManagerConfiguration ( ) . getJndiName ( ) ; try { if ( mc . getMetaData ( ) != null ) { eisProductName = mc . getMetaData ( ) . getEISProductName ( ) ; eisProductVersion = mc . getMetaData ( ) . getEISProductVersion ( ) ; } } catch ( ResourceException re ) { } if ( eisProductName == null ) eisProductName = jndiName ; if ( eisProductVersion == null ) eisProductVersion = jndiName ; if ( cm . getConnectionManagerConfiguration ( ) . isConnectable ( ) ) { if ( mc instanceof org . ironjacamar . core . spi . transaction . ConnectableResource ) { ConnectableResource cr = ( ConnectableResource ) mc ; xaResource = txCM . getTransactionIntegration ( ) . createConnectableLocalXAResource ( cm , eisProductName , eisProductVersion , jndiName , cr , statistics ) ; } else if ( txCM . getTransactionIntegration ( ) . isConnectableResource ( mc ) ) { xaResource = txCM . getTransactionIntegration ( ) . createConnectableLocalXAResource ( cm , eisProductName , eisProductVersion , jndiName , mc , statistics ) ; } } if ( xaResource == null ) xaResource = txCM . getTransactionIntegration ( ) . createLocalXAResource ( cm , eisProductName , eisProductVersion , jndiName , statistics ) ; return xaResource ; }
Get a LocalXAResource instance
14,767
protected XAResource getXAResource ( ManagedConnection mc ) throws ResourceException { TransactionalConnectionManager txCM = ( TransactionalConnectionManager ) cm ; XAResource xaResource = null ; if ( cm . getConnectionManagerConfiguration ( ) . isWrapXAResource ( ) ) { String eisProductName = null ; String eisProductVersion = null ; String jndiName = cm . getConnectionManagerConfiguration ( ) . getJndiName ( ) ; boolean padXid = cm . getConnectionManagerConfiguration ( ) . isPadXid ( ) ; Boolean isSameRMOverride = cm . getConnectionManagerConfiguration ( ) . isIsSameRMOverride ( ) ; try { if ( mc . getMetaData ( ) != null ) { eisProductName = mc . getMetaData ( ) . getEISProductName ( ) ; eisProductVersion = mc . getMetaData ( ) . getEISProductVersion ( ) ; } } catch ( ResourceException re ) { } if ( eisProductName == null ) eisProductName = jndiName ; if ( eisProductVersion == null ) eisProductVersion = jndiName ; if ( cm . getConnectionManagerConfiguration ( ) . isConnectable ( ) ) { if ( mc instanceof org . ironjacamar . core . spi . transaction . ConnectableResource ) { ConnectableResource cr = ( ConnectableResource ) mc ; xaResource = txCM . getTransactionIntegration ( ) . createConnectableXAResourceWrapper ( mc . getXAResource ( ) , padXid , isSameRMOverride , eisProductName , eisProductVersion , jndiName , cr , statistics ) ; } else if ( txCM . getTransactionIntegration ( ) . isConnectableResource ( mc ) ) { xaResource = txCM . getTransactionIntegration ( ) . createConnectableXAResourceWrapper ( mc . getXAResource ( ) , padXid , isSameRMOverride , eisProductName , eisProductVersion , jndiName , mc , statistics ) ; } } if ( xaResource == null ) { XAResource xar = mc . getXAResource ( ) ; if ( ! ( xar instanceof org . ironjacamar . core . spi . transaction . xa . XAResourceWrapper ) ) { boolean firstResource = txCM . getTransactionIntegration ( ) . isFirstResource ( mc ) ; xaResource = txCM . getTransactionIntegration ( ) . createXAResourceWrapper ( xar , padXid , isSameRMOverride , eisProductName , eisProductVersion , jndiName , firstResource , statistics ) ; } else { xaResource = xar ; } } } else { xaResource = mc . getXAResource ( ) ; } return xaResource ; }
Get a XAResource instance
14,768
public void prefill ( ) { if ( isShutdown ( ) ) return ; if ( poolConfiguration . isPrefill ( ) ) { ManagedConnectionPool mcp = pools . get ( getPrefillCredential ( ) ) ; if ( mcp == null ) { getManagedConnectionPool ( getPrefillCredential ( ) ) ; } else { mcp . prefill ( ) ; } } }
Prefill the connection pool
14,769
public Credential getPrefillCredential ( ) { if ( this . prefillCredential == null ) { if ( cm . getSubjectFactory ( ) == null || cm . getConnectionManagerConfiguration ( ) . getSecurityDomain ( ) == null ) { prefillCredential = new Credential ( null , null ) ; } else { prefillCredential = new Credential ( SecurityActions . createSubject ( cm . getSubjectFactory ( ) , cm . getConnectionManagerConfiguration ( ) . getSecurityDomain ( ) , cm . getManagedConnectionFactory ( ) ) , null ) ; } } return this . prefillCredential ; }
Get prefill credential
14,770
protected boolean isRarArchive ( URL url ) { if ( url == null ) return false ; return isRarFile ( url ) || isRarDirectory ( url ) ; }
Does the URL represent a . rar archive
14,771
protected boolean isRarFile ( URL url ) { if ( url != null && url . toExternalForm ( ) . endsWith ( ".rar" ) && ! url . toExternalForm ( ) . startsWith ( "jar" ) ) return true ; return false ; }
Does the URL represent a . rar file
14,772
public Object getAnnotation ( ) { try { if ( isOnField ( ) ) { Class < ? > clazz = cl . loadClass ( className ) ; while ( ! clazz . equals ( Object . class ) ) { try { Field field = SecurityActions . getDeclaredField ( clazz , memberName ) ; return field . getAnnotation ( annotationClass ) ; } catch ( Throwable t ) { clazz = clazz . getSuperclass ( ) ; } } } else if ( isOnMethod ( ) ) { Class < ? > clazz = cl . loadClass ( className ) ; Class < ? > [ ] params = new Class < ? > [ parameterTypes . size ( ) ] ; int i = 0 ; for ( String paramClazz : parameterTypes ) { params [ i ] = cl . loadClass ( paramClazz ) ; i ++ ; } while ( ! clazz . equals ( Object . class ) ) { try { Method method = SecurityActions . getDeclaredMethod ( clazz , memberName , params ) ; return method . getAnnotation ( annotationClass ) ; } catch ( Throwable t ) { clazz = clazz . getSuperclass ( ) ; } } } else { Class < ? > clazz = cl . loadClass ( className ) ; return clazz . getAnnotation ( annotationClass ) ; } } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; } return null ; }
Get the annotation .
14,773
public DataSources parse ( XMLStreamReader reader ) throws Exception { DataSources dataSources = null ; int iterate ; try { iterate = reader . nextTag ( ) ; } catch ( XMLStreamException e ) { iterate = reader . nextTag ( ) ; } switch ( iterate ) { case END_ELEMENT : { break ; } case START_ELEMENT : { switch ( reader . getLocalName ( ) ) { case XML . ELEMENT_DATASOURCES : { dataSources = parseDataSources ( reader ) ; break ; } default : throw new ParserException ( bundle . unexpectedElement ( reader . getLocalName ( ) ) ) ; } break ; } default : throw new IllegalStateException ( ) ; } return dataSources ; }
Parse a - ds . xml file
14,774
public void store ( DataSources metadata , XMLStreamWriter writer ) throws Exception { if ( metadata != null && writer != null ) { writer . writeStartElement ( XML . ELEMENT_DATASOURCES ) ; if ( metadata . getDataSource ( ) != null && ! metadata . getDataSource ( ) . isEmpty ( ) ) { for ( DataSource ds : metadata . getDataSource ( ) ) { storeDataSource ( ds , writer ) ; } } if ( metadata . getXaDataSource ( ) != null && ! metadata . getXaDataSource ( ) . isEmpty ( ) ) { for ( XaDataSource xads : metadata . getXaDataSource ( ) ) { storeXaDataSource ( xads , writer ) ; } } if ( metadata . getDrivers ( ) != null && ! metadata . getDrivers ( ) . isEmpty ( ) ) { writer . writeStartElement ( XML . ELEMENT_DRIVERS ) ; for ( Driver drv : metadata . getDrivers ( ) ) { storeDriver ( drv , writer ) ; } writer . writeEndElement ( ) ; } writer . writeEndElement ( ) ; } }
Store a - ds . xml file
14,775
protected void storeDriver ( Driver drv , XMLStreamWriter writer ) throws Exception { writer . writeStartElement ( XML . ELEMENT_DRIVER ) ; if ( drv . getName ( ) != null ) writer . writeAttribute ( XML . ATTRIBUTE_NAME , drv . getValue ( XML . ATTRIBUTE_NAME , drv . getName ( ) ) ) ; if ( drv . getModule ( ) != null ) writer . writeAttribute ( XML . ATTRIBUTE_MODULE , drv . getValue ( XML . ATTRIBUTE_MODULE , drv . getModule ( ) ) ) ; if ( drv . getMajorVersion ( ) != null ) writer . writeAttribute ( XML . ATTRIBUTE_MAJOR_VERSION , drv . getValue ( XML . ATTRIBUTE_MAJOR_VERSION , drv . getMajorVersion ( ) . toString ( ) ) ) ; if ( drv . getMinorVersion ( ) != null ) writer . writeAttribute ( XML . ATTRIBUTE_MINOR_VERSION , drv . getValue ( XML . ATTRIBUTE_MINOR_VERSION , drv . getMinorVersion ( ) . toString ( ) ) ) ; if ( drv . getDriverClass ( ) != null ) { writer . writeStartElement ( XML . ELEMENT_DRIVER_CLASS ) ; writer . writeCharacters ( drv . getValue ( XML . ELEMENT_DRIVER_CLASS , drv . getDriverClass ( ) ) ) ; writer . writeEndElement ( ) ; } if ( drv . getDataSourceClass ( ) != null ) { writer . writeStartElement ( XML . ELEMENT_DATASOURCE_CLASS ) ; writer . writeCharacters ( drv . getValue ( XML . ELEMENT_DATASOURCE_CLASS , drv . getDataSourceClass ( ) ) ) ; writer . writeEndElement ( ) ; } if ( drv . getXaDataSourceClass ( ) != null ) { writer . writeStartElement ( XML . ELEMENT_XA_DATASOURCE_CLASS ) ; writer . writeCharacters ( drv . getValue ( XML . ELEMENT_XA_DATASOURCE_CLASS , drv . getXaDataSourceClass ( ) ) ) ; writer . writeEndElement ( ) ; } writer . writeEndElement ( ) ; }
Store a driver
14,776
public static ClassDefinition createClassDefinition ( Serializable s , Class < ? > clz ) { if ( s == null || clz == null ) return null ; String name = clz . getName ( ) ; long serialVersionUID = 0L ; byte [ ] data = null ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; InputStream is = null ; try { try { Field svuf = getSerialVersionUID ( clz ) ; if ( svuf != null ) serialVersionUID = ( long ) svuf . get ( s ) ; } catch ( Throwable t ) { } String clzName = name . replace ( '.' , '/' ) + ".class" ; is = SecurityActions . getClassLoader ( s . getClass ( ) ) . getResourceAsStream ( clzName ) ; int i = is . read ( ) ; while ( i != - 1 ) { baos . write ( i ) ; i = is . read ( ) ; } data = baos . toByteArray ( ) ; return new ClassDefinition ( name , serialVersionUID , data ) ; } catch ( Throwable t ) { } finally { if ( is != null ) { try { is . close ( ) ; } catch ( IOException ioe ) { } } } return null ; }
Create a class definition
14,777
private static Field getSerialVersionUID ( Class < ? > clz ) { Class < ? > c = clz ; while ( c != null ) { try { Field svuf = SecurityActions . getDeclaredField ( clz , "serialVersionUID" ) ; SecurityActions . setAccessible ( svuf ) ; return svuf ; } catch ( Throwable t ) { } c = c . getSuperclass ( ) ; } return null ; }
Find the serialVersionUID field
14,778
protected WorkManager parseWorkManager ( XMLStreamReader reader ) throws XMLStreamException , ParserException , ValidateException { WorkManagerSecurity security = null ; while ( reader . hasNext ( ) ) { switch ( reader . nextTag ( ) ) { case END_ELEMENT : { if ( CommonXML . ELEMENT_WORKMANAGER . equals ( reader . getLocalName ( ) ) ) { return new WorkManagerImpl ( security ) ; } else { switch ( reader . getLocalName ( ) ) { case CommonXML . ELEMENT_SECURITY : break ; default : throw new ParserException ( bundle . unexpectedEndTag ( reader . getLocalName ( ) ) ) ; } } break ; } case START_ELEMENT : { switch ( reader . getLocalName ( ) ) { case CommonXML . ELEMENT_SECURITY : { security = parseWorkManagerSecurity ( reader ) ; break ; } default : throw new ParserException ( bundle . unexpectedElement ( reader . getLocalName ( ) ) ) ; } break ; } } } throw new ParserException ( bundle . unexpectedEndOfDocument ( ) ) ; }
Parse workmanager element
14,779
protected void storeAdminObject ( AdminObject ao , XMLStreamWriter writer ) throws Exception { writer . writeStartElement ( CommonXML . ELEMENT_ADMIN_OBJECT ) ; if ( ao . getClassName ( ) != null ) writer . writeAttribute ( CommonXML . ATTRIBUTE_CLASS_NAME , ao . getValue ( CommonXML . ATTRIBUTE_CLASS_NAME , ao . getClassName ( ) ) ) ; if ( ao . getJndiName ( ) != null ) writer . writeAttribute ( CommonXML . ATTRIBUTE_JNDI_NAME , ao . getValue ( CommonXML . ATTRIBUTE_JNDI_NAME , ao . getJndiName ( ) ) ) ; if ( ao . isEnabled ( ) != null && ( ao . hasExpression ( CommonXML . ATTRIBUTE_ENABLED ) || ! Defaults . ENABLED . equals ( ao . isEnabled ( ) ) ) ) writer . writeAttribute ( CommonXML . ATTRIBUTE_ENABLED , ao . getValue ( CommonXML . ATTRIBUTE_ENABLED , ao . isEnabled ( ) . toString ( ) ) ) ; if ( ao . getId ( ) != null ) writer . writeAttribute ( CommonXML . ATTRIBUTE_ID , ao . getValue ( CommonXML . ATTRIBUTE_ID , ao . getId ( ) ) ) ; if ( ao . getConfigProperties ( ) != null && ! ao . getConfigProperties ( ) . isEmpty ( ) ) { Iterator < Map . Entry < String , String > > it = ao . getConfigProperties ( ) . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Map . Entry < String , String > entry = it . next ( ) ; writer . writeStartElement ( CommonXML . ELEMENT_CONFIG_PROPERTY ) ; writer . writeAttribute ( CommonXML . ATTRIBUTE_NAME , entry . getKey ( ) ) ; writer . writeCharacters ( ao . getValue ( CommonXML . ELEMENT_CONFIG_PROPERTY , entry . getKey ( ) , entry . getValue ( ) ) ) ; writer . writeEndElement ( ) ; } } writer . writeEndElement ( ) ; }
Store admin object
14,780
public static AnnotationScanner getAnnotationScanner ( ) { if ( active != null ) return active ; if ( defaultImplementation == null ) throw new IllegalStateException ( bundle . noAnnotationScanner ( ) ) ; return defaultImplementation ; }
Get the annotation scanner
14,781
void writeConfigPropsDeclare ( Definition def , Writer out , int indent ) throws IOException { if ( getConfigProps ( def ) == null ) return ; for ( int i = 0 ; i < getConfigProps ( def ) . size ( ) ; i ++ ) { writeWithIndent ( out , indent , "/** " + getConfigProps ( def ) . get ( i ) . getName ( ) + " */\n" ) ; if ( def . isUseAnnotation ( ) ) { writeIndent ( out , indent ) ; out . write ( "@ConfigProperty(defaultValue = \"" + getConfigProps ( def ) . get ( i ) . getValue ( ) + "\")" ) ; if ( getConfigProps ( def ) . get ( i ) . isRequired ( ) ) { out . write ( " @NotNull" ) ; } writeEol ( out ) ; } writeWithIndent ( out , indent , "private " + getConfigProps ( def ) . get ( i ) . getType ( ) + " " + getConfigProps ( def ) . get ( i ) . getName ( ) + ";\n\n" ) ; } }
Output Configuration Properties Declare
14,782
void writeConfigProps ( Definition def , Writer out , int indent ) throws IOException { if ( getConfigProps ( def ) == null ) return ; for ( int i = 0 ; i < getConfigProps ( def ) . size ( ) ; i ++ ) { String name = getConfigProps ( def ) . get ( i ) . getName ( ) ; String upcaseName = upcaseFirst ( name ) ; writeWithIndent ( out , indent , "/** \n" ) ; writeWithIndent ( out , indent , " * Set " + name ) ; writeEol ( out ) ; writeWithIndent ( out , indent , " * @param " + name + " The value\n" ) ; writeWithIndent ( out , indent , " */\n" ) ; writeWithIndent ( out , indent , "public void set" + upcaseName + "(" + getConfigProps ( def ) . get ( i ) . getType ( ) + " " + name + ")" ) ; writeLeftCurlyBracket ( out , indent ) ; writeWithIndent ( out , indent + 1 , "this." + name + " = " + name + ";" ) ; writeRightCurlyBracket ( out , indent ) ; writeEol ( out ) ; writeWithIndent ( out , indent , "/** \n" ) ; writeWithIndent ( out , indent , " * Get " + name ) ; writeEol ( out ) ; writeWithIndent ( out , indent , " * @return The value\n" ) ; writeWithIndent ( out , indent , " */\n" ) ; writeWithIndent ( out , indent , "public " + getConfigProps ( def ) . get ( i ) . getType ( ) + " get" + upcaseName + "()" ) ; writeLeftCurlyBracket ( out , indent ) ; writeWithIndent ( out , indent + 1 , "return " + name + ";" ) ; writeRightCurlyBracket ( out , indent ) ; writeEol ( out ) ; } }
Output Configuration Properties
14,783
public synchronized Object verifyConnectionListener ( ConnectionListener cl ) throws ResourceException { for ( Map . Entry < Object , Map < ManagedConnectionPool , ConnectionListener > > entry : transactionMap . entrySet ( ) ) { if ( entry . getValue ( ) . values ( ) . contains ( cl ) ) { try { TransactionalConnectionManager txCM = ( TransactionalConnectionManager ) cm ; Transaction tx = txCM . getTransactionIntegration ( ) . getTransactionManager ( ) . getTransaction ( ) ; Object id = txCM . getTransactionIntegration ( ) . getTransactionSynchronizationRegistry ( ) . getTransactionKey ( ) ; if ( ! id . equals ( entry . getKey ( ) ) ) return entry . getKey ( ) ; } catch ( Exception e ) { throw new ResourceException ( e ) ; } } } return null ; }
Verify if a connection listener is already in use
14,784
public static List < Failure > validateConfigPropertiesType ( ValidateClass vo , String section , String failMsg ) { List < Failure > failures = new ArrayList < Failure > ( 1 ) ; for ( ConfigProperty cpmd : vo . getConfigProperties ( ) ) { try { containGetOrIsMethod ( vo , "get" , cpmd , section , failMsg , failures ) ; } catch ( Throwable t ) { try { containGetOrIsMethod ( vo , "is" , cpmd , section , failMsg , failures ) ; } catch ( Throwable it ) { } } } if ( failures . isEmpty ( ) ) return null ; return failures ; }
validate ConfigProperties type
14,785
private static void containGetOrIsMethod ( ValidateClass vo , String getOrIs , ConfigProperty cpmd , String section , String failMsg , List < Failure > failures ) throws NoSuchMethodException { String methodName = getOrIs + cpmd . getConfigPropertyName ( ) . getValue ( ) . substring ( 0 , 1 ) . toUpperCase ( Locale . US ) ; if ( cpmd . getConfigPropertyName ( ) . getValue ( ) . length ( ) > 1 ) { methodName += cpmd . getConfigPropertyName ( ) . getValue ( ) . substring ( 1 ) ; } Method method = SecurityActions . getMethod ( vo . getClazz ( ) , methodName , ( Class [ ] ) null ) ; if ( ! VALID_TYPES . contains ( method . getReturnType ( ) ) ) { StringBuilder sb = new StringBuilder ( "Class: " + vo . getClazz ( ) . getName ( ) ) ; sb = sb . append ( " Property: " + cpmd . getConfigPropertyName ( ) . getValue ( ) ) ; sb = sb . append ( " Type: " + method . getReturnType ( ) . getName ( ) ) ; Failure failure ; if ( WARNING_TYPES . contains ( method . getReturnType ( ) ) ) { failure = new Failure ( Severity . WARNING , section , failMsg , sb . toString ( ) ) ; } else { failure = new Failure ( Severity . ERROR , section , failMsg , sb . toString ( ) ) ; } failures . add ( failure ) ; } }
validated object contain get or is Method
14,786
protected org . ironjacamar . core . connectionmanager . listener . ConnectionListener getConnectionListener ( Credential credential ) throws ResourceException { org . ironjacamar . core . connectionmanager . listener . ConnectionListener result = null ; Exception failure = null ; boolean isInterrupted = Thread . interrupted ( ) ; boolean innerIsInterrupted = false ; try { result = pool . getConnectionListener ( credential ) ; if ( supportsLazyAssociation == null ) { supportsLazyAssociation = ( result . getManagedConnection ( ) instanceof DissociatableManagedConnection ) ? Boolean . TRUE : Boolean . FALSE ; } return result ; } catch ( ResourceException e ) { failure = e ; if ( cmConfiguration . getAllocationRetry ( ) != 0 || e instanceof RetryableException ) { int to = cmConfiguration . getAllocationRetry ( ) ; long sleep = cmConfiguration . getAllocationRetryWaitMillis ( ) ; if ( to == 0 && e instanceof RetryableException ) to = 1 ; for ( int i = 0 ; i < to ; i ++ ) { if ( shutdown . get ( ) ) { throw new ResourceException ( ) ; } if ( Thread . currentThread ( ) . isInterrupted ( ) ) { Thread . interrupted ( ) ; innerIsInterrupted = true ; } try { if ( sleep > 0 ) Thread . sleep ( sleep ) ; return pool . getConnectionListener ( credential ) ; } catch ( ResourceException re ) { failure = re ; } catch ( InterruptedException ie ) { failure = ie ; innerIsInterrupted = true ; } } } } catch ( Exception e ) { failure = e ; } finally { if ( isInterrupted || innerIsInterrupted ) { Thread . currentThread ( ) . interrupt ( ) ; if ( innerIsInterrupted ) throw new ResourceException ( failure ) ; } } if ( cmConfiguration . isSharable ( ) && Boolean . TRUE . equals ( supportsLazyAssociation ) ) return associateConnectionListener ( credential , null ) ; throw new ResourceException ( failure ) ; }
Get a connection listener
14,787
private org . ironjacamar . core . connectionmanager . listener . ConnectionListener associateConnectionListener ( Credential credential , Object connection ) throws ResourceException { log . tracef ( "associateConnectionListener(%s, %s)" , credential , connection ) ; if ( isShutdown ( ) ) { throw new ResourceException ( ) ; } if ( ! cmConfiguration . isSharable ( ) ) throw new ResourceException ( ) ; org . ironjacamar . core . connectionmanager . listener . ConnectionListener cl = pool . getActiveConnectionListener ( credential ) ; if ( cl == null ) { if ( ! pool . isFull ( ) ) { try { cl = pool . getConnectionListener ( credential ) ; } catch ( ResourceException re ) { } } if ( cl == null ) { org . ironjacamar . core . connectionmanager . listener . ConnectionListener removeCl = pool . removeConnectionListener ( null ) ; if ( removeCl != null ) { try { if ( ccm != null ) { for ( Object c : removeCl . getConnections ( ) ) { ccm . unregisterConnection ( this , removeCl , c ) ; } } returnConnectionListener ( removeCl , true ) ; cl = pool . getConnectionListener ( credential ) ; } catch ( ResourceException ire ) { } } else { if ( getTransactionSupport ( ) == TransactionSupportLevel . NoTransaction ) { org . ironjacamar . core . connectionmanager . listener . ConnectionListener targetCl = pool . removeConnectionListener ( credential ) ; if ( targetCl != null ) { if ( targetCl . getManagedConnection ( ) instanceof DissociatableManagedConnection ) { DissociatableManagedConnection dmc = ( DissociatableManagedConnection ) targetCl . getManagedConnection ( ) ; if ( ccm != null ) { for ( Object c : targetCl . getConnections ( ) ) { ccm . unregisterConnection ( this , targetCl , c ) ; } } dmc . dissociateConnections ( ) ; targetCl . clearConnections ( ) ; cl = targetCl ; } else { try { if ( ccm != null ) { for ( Object c : targetCl . getConnections ( ) ) { ccm . unregisterConnection ( this , targetCl , c ) ; } } returnConnectionListener ( targetCl , true ) ; cl = pool . getConnectionListener ( credential ) ; } catch ( ResourceException ire ) { } } } } } } } if ( cl == null ) throw new ResourceException ( ) ; if ( connection != null ) { cl . getManagedConnection ( ) . associateConnection ( connection ) ; cl . addConnection ( connection ) ; if ( ccm != null ) { ccm . registerConnection ( this , cl , connection ) ; } } return cl ; }
Associate a ConnectionListener
14,788
private boolean shouldEnlist ( ConnectionListener cl ) { if ( cmConfiguration . isEnlistment ( ) && cl . getManagedConnection ( ) instanceof LazyEnlistableManagedConnection ) return false ; return true ; }
Should enlist the ConnectionListener
14,789
static WARClassLoader createWARClassLoader ( final Kernel kernel , final ClassLoader parent ) { return AccessController . doPrivileged ( new PrivilegedAction < WARClassLoader > ( ) { public WARClassLoader run ( ) { return new WARClassLoader ( kernel , parent ) ; } } ) ; }
Create a WARClassLoader
14,790
static WebAppClassLoader createWebAppClassLoader ( final ClassLoader cl , final WebAppContext wac ) { return AccessController . doPrivileged ( new PrivilegedAction < WebAppClassLoader > ( ) { public WebAppClassLoader run ( ) { try { return new WebAppClassLoader ( cl , wac ) ; } catch ( IOException ioe ) { return null ; } } } ) ; }
Create a WebClassLoader
14,791
void generateRaCode ( Definition def ) { if ( def . isUseRa ( ) ) { generateClassCode ( def , "Ra" ) ; generateClassCode ( def , "RaMeta" ) ; } if ( def . isGenAdminObject ( ) ) { for ( int i = 0 ; i < def . getAdminObjects ( ) . size ( ) ; i ++ ) { generateMultiAdminObjectClassCode ( def , "AoImpl" , i ) ; generateMultiAdminObjectClassCode ( def , "AoInterface" , i ) ; } } }
generate resource adapter code
14,792
void generateOutboundCode ( Definition def ) { if ( def . isSupportOutbound ( ) ) { if ( def . getMcfDefs ( ) == null ) throw new IllegalStateException ( "Should define at least one mcf class" ) ; for ( int num = 0 ; num < def . getMcfDefs ( ) . size ( ) ; num ++ ) { generateMultiMcfClassCode ( def , "Mcf" , num ) ; generateMultiMcfClassCode ( def , "Mc" , num ) ; generateMultiMcfClassCode ( def , "McMeta" , num ) ; if ( ! def . getMcfDefs ( ) . get ( num ) . isUseCciConnection ( ) ) { generateMultiMcfClassCode ( def , "CfInterface" , num ) ; generateMultiMcfClassCode ( def , "Cf" , num ) ; generateMultiMcfClassCode ( def , "ConnInterface" , num ) ; generateMultiMcfClassCode ( def , "ConnImpl" , num ) ; } else { generateMultiMcfClassCode ( def , "CciConn" , num ) ; generateMultiMcfClassCode ( def , "CciConnFactory" , num ) ; generateMultiMcfClassCode ( def , "ConnMeta" , num ) ; generateMultiMcfClassCode ( def , "ConnSpec" , num ) ; } } } }
generate outbound code
14,793
void generateInboundCode ( Definition def ) { if ( def . isSupportInbound ( ) ) { if ( def . isDefaultPackageInbound ( ) ) generateClassCode ( def , "Ml" , "inflow" ) ; generateClassCode ( def , "As" , "inflow" ) ; generateClassCode ( def , "Activation" , "inflow" ) ; generatePackageInfo ( def , "main" , "inflow" ) ; } }
generate inbound code
14,794
void generateMBeanCode ( Definition def ) { if ( def . isSupportOutbound ( ) ) { generateClassCode ( def , "MbeanInterface" , "mbean" ) ; generateClassCode ( def , "MbeanImpl" , "mbean" ) ; generatePackageInfo ( def , "main" , "mbean" ) ; } }
generate MBean code
14,795
void generateClassCode ( Definition def , String className , String subDir ) { if ( className == null || className . equals ( "" ) ) return ; try { String clazzName = this . getClass ( ) . getPackage ( ) . getName ( ) + ".code." + className + "CodeGen" ; String javaFile = Definition . class . getMethod ( "get" + className + "Class" ) . invoke ( def , ( Object [ ] ) null ) + ".java" ; FileWriter fw ; if ( subDir == null ) fw = Utils . createSrcFile ( javaFile , def . getRaPackage ( ) , def . getOutputDir ( ) ) ; else fw = Utils . createSrcFile ( javaFile , def . getRaPackage ( ) + "." + subDir , def . getOutputDir ( ) ) ; Class < ? > clazz = Class . forName ( clazzName , true , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; AbstractCodeGen codeGen = ( AbstractCodeGen ) clazz . newInstance ( ) ; codeGen . generate ( def , fw ) ; fw . flush ( ) ; fw . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
generate class code
14,796
void generateMultiMcfClassCode ( Definition def , String className , int num ) { if ( className == null || className . equals ( "" ) ) return ; if ( num < 0 || num + 1 > def . getMcfDefs ( ) . size ( ) ) return ; try { String clazzName = this . getClass ( ) . getPackage ( ) . getName ( ) + ".code." + className + "CodeGen" ; String javaFile = McfDef . class . getMethod ( "get" + className + "Class" ) . invoke ( def . getMcfDefs ( ) . get ( num ) , ( Object [ ] ) null ) + ".java" ; FileWriter fw ; fw = Utils . createSrcFile ( javaFile , def . getRaPackage ( ) , def . getOutputDir ( ) ) ; Class < ? > clazz = Class . forName ( clazzName , true , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; AbstractCodeGen codeGen = ( AbstractCodeGen ) clazz . newInstance ( ) ; codeGen . setNumOfMcf ( num ) ; codeGen . generate ( def , fw ) ; fw . flush ( ) ; fw . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
generate multi mcf class code
14,797
void generateMultiAdminObjectClassCode ( Definition def , String className , int num ) { if ( className == null || className . equals ( "" ) ) return ; try { String clazzName = this . getClass ( ) . getPackage ( ) . getName ( ) + ".code." + className + "CodeGen" ; Class < ? > clazz = Class . forName ( clazzName , true , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; AbstractCodeGen codeGen = ( AbstractCodeGen ) clazz . newInstance ( ) ; String javaFile = "" ; if ( codeGen instanceof AoImplCodeGen ) { ( ( AoImplCodeGen ) codeGen ) . setNumOfAo ( num ) ; javaFile = def . getAdminObjects ( ) . get ( num ) . getAdminObjectClass ( ) + ".java" ; } else if ( codeGen instanceof AoInterfaceCodeGen ) { ( ( AoInterfaceCodeGen ) codeGen ) . setNumOfAo ( num ) ; javaFile = def . getAdminObjects ( ) . get ( num ) . getAdminObjectInterface ( ) + ".java" ; } FileWriter fw = Utils . createSrcFile ( javaFile , def . getRaPackage ( ) , def . getOutputDir ( ) ) ; codeGen . generate ( def , fw ) ; fw . flush ( ) ; fw . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
generate multi admin object class code
14,798
void generateAntIvyXml ( Definition def , String outputDir ) { try { FileWriter antfw = Utils . createFile ( "build.xml" , outputDir ) ; BuildIvyXmlGen bxGen = new BuildIvyXmlGen ( ) ; bxGen . generate ( def , antfw ) ; antfw . close ( ) ; FileWriter ivyfw = Utils . createFile ( "ivy.xml" , outputDir ) ; IvyXmlGen ixGen = new IvyXmlGen ( ) ; ixGen . generate ( def , ivyfw ) ; ivyfw . close ( ) ; FileWriter ivySettingsfw = Utils . createFile ( "ivy.settings.xml" , outputDir ) ; IvySettingsXmlGen isxGen = new IvySettingsXmlGen ( ) ; isxGen . generate ( def , ivySettingsfw ) ; ivySettingsfw . close ( ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; } }
generate ant + ivy build . xml and ivy files
14,799
void generateGradle ( Definition def , String outputDir ) { try { FileWriter bgfw = Utils . createFile ( "build.gradle" , outputDir ) ; BuildGradleGen bgGen = new BuildGradleGen ( ) ; bgGen . generate ( def , bgfw ) ; bgfw . close ( ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; } }
generate gradle build . gradle