idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
4,900
public JSONObject getRoomDetails ( String company , String roomId , HashMap < String , String > params ) throws JSONException { return oClient . get ( "/messages/v3/" + company + "/rooms/" + roomId , params ) ; }
Get a specific room information
4,901
public JSONObject getRoomByOffer ( String company , String offerId , HashMap < String , String > params ) throws JSONException { return oClient . get ( "/messages/v3/" + company + "/rooms/offers/" + offerId , params ) ; }
Get a specific room by offer ID
4,902
public JSONObject getRoomByApplication ( String company , String applicationId , HashMap < String , String > params ) throws JSONException { return oClient . get ( "/messages/v3/" + company + "/rooms/appications/" + applicationId , params ) ; }
Get a specific room by application ID
4,903
public JSONObject getRoomByContract ( String company , String contractId , HashMap < String , String > params ) throws JSONException { return oClient . get ( "/messages/v3/" + company + "/rooms/contracts/" + contractId , params ) ; }
Get a specific room by contract ID
4,904
public JSONObject createRoom ( String company , HashMap < String , String > params ) throws JSONException { return oClient . post ( "/messages/v3/" + company + "/rooms" , params ) ; }
Create a new room
4,905
public JSONObject sendMessageToRoom ( String company , String roomId , HashMap < String , String > params ) throws JSONException { return oClient . post ( "/messages/v3/" + company + "/rooms/" + roomId + "/stories" , params ) ; }
Send a message to a room
4,906
public JSONObject updateRoomSettings ( String company , String roomId , String username , HashMap < String , String > params ) throws JSONException { return oClient . put ( "/messages/v3/" + company + "/rooms/" + roomId + "/users/" + username , params ) ; }
Update a room settings
4,907
public JSONObject updateRoomMetadata ( String company , String roomId , HashMap < String , String > params ) throws JSONException { return oClient . put ( "/messages/v3/" + company + "/rooms/" + roomId , params ) ; }
Update the metadata of a room
4,908
public final HandlerRegistration addOpenHandler ( final OpenEvent . Handler handler ) { return _eventBus . addHandler ( OpenEvent . getType ( ) , handler ) ; }
Add listener for open events .
4,909
public final HandlerRegistration addCloseHandler ( final CloseEvent . Handler handler ) { return _eventBus . addHandler ( CloseEvent . getType ( ) , handler ) ; }
Add listener for close events .
4,910
public final HandlerRegistration addMessageHandler ( final MessageEvent . Handler handler ) { return _eventBus . addHandler ( MessageEvent . getType ( ) , handler ) ; }
Add listener for message events .
4,911
public static String extractClassName ( Description description ) { final String displayName = description . getDisplayName ( ) ; final String regex = "^" + "[^\\(\\)]+" + "\\((" + "[^\\\\(\\\\)]+" + ")\\)" + "$" ; final Pattern parens = Pattern . compile ( regex ) ; final Matcher m = parens . matcher ( displayName ) ; if ( ! m . find ( ) ) { return displayName ; } return m . group ( 1 ) ; }
Extract the class name from a given junit test description
4,912
public static String extractSimpleClassName ( Description description ) { String simpleClassName = null ; final String className = extractClassName ( description ) ; final String [ ] splitClassName = className . split ( "\\." ) ; if ( splitClassName . length > 0 ) { simpleClassName = splitClassName [ splitClassName . length - 1 ] ; } return simpleClassName ; }
Extract the simple class name from a given junit test description
4,913
public static String extractMethodName ( Description description ) { String methodName = null ; final String [ ] splitDisplayName = description . getDisplayName ( ) . split ( "\\(" ) ; if ( splitDisplayName . length > 0 ) { methodName = splitDisplayName [ 0 ] ; } return methodName ; }
Get the tested method name
4,914
public static String getLine ( JUnitTestData testMethod ) { String line = "~" ; Throwable testException = testMethod . getFailException ( ) ; if ( testException != null ) { StringBuilder lookFor = new StringBuilder ( ) ; lookFor . append ( extractClassName ( testMethod . getDescription ( ) ) ) ; lookFor . append ( '.' ) ; lookFor . append ( extractMethodName ( testMethod . getDescription ( ) ) ) ; lookFor . append ( '(' ) ; lookFor . append ( extractSimpleClassName ( testMethod . getDescription ( ) ) ) ; lookFor . append ( ".java:" ) ; StackTraceElement [ ] els = testException . getStackTrace ( ) ; for ( int i = 0 ; i < els . length ; i ++ ) { StackTraceElement el = els [ i ] ; line = getLineNumberFromExceptionTraceLine ( el . toString ( ) , lookFor . toString ( ) ) ; if ( line . equals ( "" ) == Boolean . FALSE ) { break ; } } } return line ; }
Get the line of the error in the exception info
4,915
public static String getLineNumberFromExceptionTraceLine ( String exceptionTraceLine , String substrToSearch ) { String lineNumber = "" ; int index = exceptionTraceLine . indexOf ( substrToSearch ) ; if ( index >= 0 ) { int length = substrToSearch . length ( ) + index ; if ( exceptionTraceLine . lastIndexOf ( ')' ) > length ) { lineNumber = exceptionTraceLine . substring ( length , exceptionTraceLine . lastIndexOf ( ')' ) ) ; } } return lineNumber ; }
Get the error line number from the exception stack trace
4,916
public static String getError ( JUnitTestData testMethod ) { String error = "~" ; Throwable t = testMethod . getFailException ( ) ; if ( t != null ) { error = t . getMessage ( ) ; } return error ; }
Get the error message from a given failed JUnit test result
4,917
public static String getSeverity ( JUnitTestData testMethod ) { String severity = "~" ; if ( testMethod . getFailException ( ) != null ) { severity = "High" ; } return severity ; }
Get the severity of the test
4,918
public static String getDatetime ( ) { long currentTimeMillis = System . currentTimeMillis ( ) ; final Date date = new Date ( currentTimeMillis ) ; return new SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ss" ) . format ( date ) ; }
Get a date time string
4,919
public static String getBacktrace ( JUnitTestData testMethod ) { StringBuilder stackTrace = new StringBuilder ( ) ; Throwable throwable = testMethod . getFailException ( ) ; if ( throwable != null ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; throwable . printStackTrace ( pw ) ; String stackTraceString = sw . toString ( ) ; stackTraceString = stackTraceString . trim ( ) . replaceAll ( "\\r\\n" , "\n" ) ; StringTokenizer st = new StringTokenizer ( stackTraceString , LINE_SEPARATOR ) ; while ( st . hasMoreTokens ( ) ) { String stackTraceLine = st . nextToken ( ) ; stackTrace . append ( stackTraceLine ) ; stackTrace . append ( LINE_SEPARATOR ) ; } } else { stackTrace . append ( '~' ) ; } return stackTrace . toString ( ) ; }
Get the backtrace from a given failed JUnit test result
4,920
private void pushState ( int indentation ) { states . push ( state ) ; state = new StreamStatus ( ) ; state . setIndentationLevel ( indentation ) ; }
Saves the current state in the stack .
4,921
private void onFinish ( ) { if ( planRequired && state . getTestSet ( ) . getPlan ( ) == null ) { throw new ParserException ( "Missing TAP Plan." ) ; } parseDiagnostics ( ) ; while ( ! states . isEmpty ( ) && state . getIndentationLevel ( ) > baseIndentation ) { state = states . pop ( ) ; } }
Called after the rest of the stream has been processed .
4,922
public static WebSocket newWebSocketIfSupported ( ) { if ( null == g_factory && GWT . isClient ( ) && getSupportDetector ( ) . isSupported ( ) ) { register ( getSupportDetector ( ) . newFactory ( ) ) ; return g_factory . newWebSocket ( ) ; } return ( null != g_factory ) ? g_factory . newWebSocket ( ) : null ; }
Create a WebSocket if supported by the platform .
4,923
public static boolean deregister ( final Factory factory ) { if ( g_factory != factory ) { return false ; } else { g_factory = null ; return true ; } }
Deregister factory if the specified factory is the registered factory .
4,924
public final void setListener ( final WebSocketListener listener ) { _listener = null == listener ? NullWebSocketListener . LISTENER : listener ; }
Set the listener to receive messages from the WebSocket .
4,925
protected final void onClose ( final boolean wasClean , final int code , final String reason ) { getListener ( ) . onClose ( this , wasClean , code , reason ) ; }
Fire a Close event .
4,926
private void markMergeRequestAsWIP ( ) { if ( ! this . api . getShouldSetWIP ( ) ) { return ; } final String currentTitle = mergeRequest . getTitle ( ) ; final String startTitle = "WIP: (VIOLATIONS) " ; if ( currentTitle . startsWith ( startTitle ) ) { return ; } final Integer projectId = this . project . getId ( ) ; final Integer mergeRequestIid = this . mergeRequest . getIid ( ) ; final String targetBranch = null ; final Integer assigneeId = null ; final String title = startTitle + currentTitle ; final String description = null ; final Constants . StateEvent stateEvent = null ; final String labels = null ; final Integer milestoneId = null ; final Boolean removeSourceBranch = null ; final Boolean squash = null ; final Boolean discussionLocked = null ; final Boolean allowCollaboration = null ; try { mergeRequest . setTitle ( title ) ; gitLabApi . getMergeRequestApi ( ) . updateMergeRequest ( projectId , mergeRequestIid , targetBranch , title , assigneeId , description , stateEvent , labels , milestoneId , removeSourceBranch , squash , discussionLocked , allowCollaboration ) ; } catch ( final Throwable e ) { violationsLogger . log ( SEVERE , e . getMessage ( ) , e ) ; } }
Set the merge request as Work in Progress if configured to do so by the shouldSetWIP flag .
4,927
public static TapProducer makeTap13YamlProducer ( ) { DumperOptions options = new DumperOptions ( ) ; options . setPrintDiagnostics ( true ) ; return new TapProducer ( new Tap13Representer ( options ) ) ; }
Create a TAP 13 producer with YAMLish .
4,928
public static Text createTextElement ( String tapLine ) { Matcher m = Patterns . TEXT_PATTERN . matcher ( tapLine ) ; if ( m . matches ( ) ) { Text result = new Text ( tapLine ) ; result . setIndentationString ( m . group ( 1 ) ) ; result . indentation = m . group ( 1 ) . length ( ) ; return result ; } return null ; }
Create a text element . This element is created when none of the other elements have matched the TAP stream line .
4,929
protected void generateTapPerMethod ( Result result ) { for ( final JUnitTestData testMethod : testMethodsList ) { final TestResult tapTestResult = TapJUnitUtil . generateTAPTestResult ( testMethod , 1 , isYaml ( ) ) ; final TestSet testSet = new TestSet ( ) ; testSet . setPlan ( new Plan ( 1 ) ) ; testSet . addTestResult ( tapTestResult ) ; final String className = TapJUnitUtil . extractClassName ( testMethod . getDescription ( ) ) ; final String methodName = TapJUnitUtil . extractMethodName ( testMethod . getDescription ( ) ) ; final File output = new File ( System . getProperty ( "tap.junit.results" , "target/" ) , className + ":" + methodName + ".tap" ) ; tapProducer . dump ( testSet , output ) ; } }
Generate tap file for each method
4,930
protected void generateTapPerClass ( Result result ) { Map < String , List < JUnitTestData > > testsByClass = new HashMap < > ( ) ; for ( JUnitTestData testMethod : testMethodsList ) { String className = TapJUnitUtil . extractClassName ( testMethod . getDescription ( ) ) ; testsByClass . computeIfAbsent ( className , k -> new ArrayList < > ( ) ) . add ( testMethod ) ; } testsByClass . forEach ( ( className , testMethods ) -> { final TestSet testSet = new TestSet ( ) ; testSet . setPlan ( new Plan ( testMethods . size ( ) ) ) ; testMethods . forEach ( testMethod -> { TestResult tapTestResult = TapJUnitUtil . generateTAPTestResult ( testMethod , 1 , isYaml ( ) ) ; testSet . addTestResult ( tapTestResult ) ; } ) ; File output = new File ( System . getProperty ( "tap.junit.results" , "target/" ) , className + ".tap" ) ; tapProducer . dump ( testSet , output ) ; } ) ; }
Generate tap file for a class
4,931
@ SuppressWarnings ( "unchecked" ) public E get ( ) { if ( getPreferences ( ) . contains ( getKey ( ) ) ) { return ( E ) enumValues [ getPreferences ( ) . getInt ( getKey ( ) , 0 ) ] ; } else { return getDefaultValue ( ) ; } }
Get the value the preference
4,932
public TestSet parseFile ( File file , boolean generateTapFile ) { TestSet testSet = new TestSet ( ) ; final Header header = new Header ( TAP_VERSION ) ; testSet . setHeader ( header ) ; List < AbstractSample > sampleResultList = getResultList ( file ) ; Plan plan = new Plan ( INITIAL_TEST_STEP , sampleResultList . size ( ) ) ; testSet . setPlan ( plan ) ; for ( AbstractSample httpSample : sampleResultList ) { List < AssertionResult > assetionResultList = httpSample . getAssertionResult ( ) ; boolean resultError = false ; String failitureMessage = "" ; String severity = "" ; for ( AssertionResult assertionResult : assetionResultList ) { resultError = ( assertionResult . isFailure ( ) || assertionResult . isError ( ) ) ; if ( resultError ) { failitureMessage += FAILURE_MESSAGE + assertionResult . getFailureMessage ( ) ; if ( assertionResult . isFailure ( ) ) { severity = FAIL_ASSERT ; } if ( assertionResult . isError ( ) ) { severity += ERROR ; } } } TestResult testResult = new TestResult ( ) ; testResult . setDescription ( httpSample . getLb ( ) ) ; StatusValues status = StatusValues . OK ; if ( resultError ) { final Map < String , Object > yamlish = testResult . getDiagnostic ( ) ; createYAMLishMessage ( yamlish , httpSample , failitureMessage ) ; createYAMLishSeverity ( yamlish , severity ) ; createYAMLishDump ( yamlish , httpSample ) ; status = StatusValues . NOT_OK ; } testResult . setStatus ( status ) ; testSet . addTestResult ( testResult ) ; } if ( generateTapFile ) { generateTapFile ( file , testSet ) ; } return testSet ; }
Parses jMeter result file into TestSet and optionally generates a Tap file with the same name of the parsed file
4,933
protected void printDiagnostic ( PrintWriter pw , TapElement tapElement ) { if ( this . yaml != null ) { Map < String , Object > diagnostic = tapElement . getDiagnostic ( ) ; if ( diagnostic != null && ! diagnostic . isEmpty ( ) ) { String diagnosticText = yaml . dump ( diagnostic ) ; diagnosticText = diagnosticText . replaceAll ( "((?m)^)" , " " ) ; pw . append ( LINE_SEPARATOR ) ; printFiller ( pw ) ; pw . append ( diagnosticText ) ; } } }
Prints diagnostic of the TAP Element into the Print Writer .
4,934
protected void printFiller ( PrintWriter pw ) { if ( this . options . getIndent ( ) > 0 ) { for ( int i = 0 ; i < options . getIndent ( ) ; i ++ ) { pw . append ( ' ' ) ; } } }
Print filler .
4,935
private void processEventsFromQueue ( int timeoutValue , TimeUnit timeoutUnit ) throws InterruptedException { TeamEvent event = memberQueue . getVal ( timeoutValue , timeoutUnit ) ; while ( null != event ) { if ( TeamEvent . Type . NEW == event . type ) { getServerDolphin ( ) . presentationModel ( null , TYPE_TEAM_MEMBER , event . dto ) ; } if ( TeamEvent . Type . CHANGE == event . type ) { silent = true ; List < ServerAttribute > attributes = getServerDolphin ( ) . findAllAttributesByQualifier ( event . qualifier ) ; for ( ServerAttribute attribute : attributes ) { PresentationModel pm = attribute . getPresentationModel ( ) ; if ( TYPE_TEAM_MEMBER . equals ( pm . getPresentationModelType ( ) ) ) { attribute . setValue ( event . value ) ; } } silent = false ; } if ( TeamEvent . Type . REBASE == event . type ) { List < ServerAttribute > attributes = getServerDolphin ( ) . findAllAttributesByQualifier ( event . qualifier ) ; for ( ServerAttribute attribute : attributes ) { attribute . rebase ( ) ; } } if ( TeamEvent . Type . REMOVE == event . type ) { List < ServerAttribute > attributes = getServerDolphin ( ) . findAllAttributesByQualifier ( event . qualifier ) ; Set < ServerPresentationModel > toDelete = new HashSet < ServerPresentationModel > ( ) ; for ( ServerAttribute attribute : attributes ) { ServerPresentationModel pm = attribute . getPresentationModel ( ) ; if ( TYPE_TEAM_MEMBER . equals ( pm . getPresentationModelType ( ) ) ) { toDelete . add ( pm ) ; } } for ( ServerPresentationModel pm : toDelete ) { getServerDolphin ( ) . remove ( pm ) ; } } event = memberQueue . getVal ( 20 , TimeUnit . MILLISECONDS ) ; } }
with user interactions and is thus safe to process in a more efficient manner .
4,936
public Set < Class < ? > > findClassesToParse ( ) { Reflections reflections = new Reflections ( new ConfigurationBuilder ( ) . setUrls ( buildClassLoaderUrls ( ) ) . setScanners ( new SubTypesScanner ( false ) ) . filterInputsBy ( buildPackagePredicates ( ) ) ) ; return reflections . getSubTypesOf ( Object . class ) ; }
Scans the classpath to find all classes that are in the configured model packages . It ignores excluded classes .
4,937
static boolean isExpression ( final String string ) { if ( string == null ) { return false ; } return string . startsWith ( "${" ) && string . endsWith ( "}" ) ; }
Whether the string is a valid expression .
4,938
static String getExpressValue ( final String key ) { if ( isExpression ( key ) ) { String keyValue = getSystemProperty ( key . substring ( 2 , key . length ( ) - 1 ) ) ; return keyValue == null ? key : keyValue ; } else { return key ; } }
Gets the express value by the key .
4,939
public void endpointActivation ( MessageEndpointFactory endpointFactory , ActivationSpec spec ) throws ResourceException { VertxActivation activation = new VertxActivation ( this , endpointFactory , ( VertxActivationSpec ) spec ) ; activations . put ( ( VertxActivationSpec ) spec , activation ) ; activation . start ( ) ; log . finest ( "endpointActivation()" ) ; }
This is called during the activation of a message endpoint .
4,940
public void endpointDeactivation ( MessageEndpointFactory endpointFactory , ActivationSpec spec ) { VertxActivation activation = activations . remove ( spec ) ; if ( activation != null ) activation . stop ( ) ; log . finest ( "endpointDeactivation()" ) ; }
This is called when a message endpoint is deactivated .
4,941
protected Filter createFilter ( final T configuration ) { ShiroConfiguration shiroConfig = narrow ( configuration ) ; final IniWebEnvironment shiroEnv = new IniWebEnvironment ( ) ; shiroEnv . setConfigLocations ( shiroConfig . iniConfigs ( ) ) ; shiroEnv . init ( ) ; AbstractShiroFilter shiroFilter = new AbstractShiroFilter ( ) { public void init ( ) throws Exception { Collection < Realm > realms = createRealms ( configuration ) ; WebSecurityManager securityManager = realms . isEmpty ( ) ? shiroEnv . getWebSecurityManager ( ) : new DefaultWebSecurityManager ( realms ) ; setSecurityManager ( securityManager ) ; setFilterChainResolver ( shiroEnv . getFilterChainResolver ( ) ) ; } } ; return shiroFilter ; }
Create the Shiro filter . Overriding this method allows for complete customization of how Shiro is initialized .
4,942
public static List < Container > getRegisteredContainers ( ) { CONTAINERS_LOCK . lock ( ) ; try { return ImmutableList . copyOf ( CONTAINERS . values ( ) ) ; } finally { CONTAINERS_LOCK . unlock ( ) ; } }
Returns a list of registered containers .
4,943
public static Container start ( final DockerConfig config , final boolean stopOthers ) throws Exception { Preconditions . checkArgument ( config != null , "config must be non-null" ) ; if ( stopOthers ) { getRegisteredContainers ( ) . stream ( ) . filter ( container -> { return container . isStarted ( ) && container . getRefCount ( ) == 0 && ! StringUtils . equals ( config . getName ( ) , container . getConfig ( ) . getName ( ) ) ; } ) . forEach ( container -> container . stop ( ) ) ; } final Container container = register ( config ) ; container . start ( ) ; return container ; }
Starts a docker container with the given configuration .
4,944
ClassConstraints extractValidationRules ( ) { final ClassConstraints classConstraints = new ClassConstraints ( ) ; Set < Field > allFields = ReflectionUtils . getAllFields ( clazz , buildAnnotationsPredicate ( ) ) ; for ( Field field : allFields ) { if ( isNotExcluded ( field ) ) { FieldConstraints fieldValidationRules = new AnnotatedField ( field , relevantAnnotationClasses ) . extractValidationRules ( ) ; if ( fieldValidationRules . size ( ) > 0 ) { classConstraints . put ( field . getName ( ) , fieldValidationRules ) ; } } } return classConstraints ; }
Parses all fields and builds validation rules for those with relevant annotations .
4,945
FieldConstraints extractValidationRules ( ) { Annotation [ ] annotations = field . getAnnotations ( ) ; FieldConstraints fieldConstraints = new FieldConstraints ( ) ; for ( Annotation annotation : annotations ) { if ( Iterables . contains ( relevantAnnotationClasses , annotation . annotationType ( ) ) ) { ConstraintAttributes constraintAttributes = new ConstraintAttributes ( annotation ) ; BuiltInConstraint supportedValidator = BuiltInConstraint . valueOfAnnotationClassOrNull ( annotation . annotationType ( ) ) ; if ( supportedValidator == null ) { fieldConstraints . put ( annotation . annotationType ( ) . getName ( ) , constraintAttributes ) ; } else { fieldConstraints . put ( supportedValidator . toString ( ) , supportedValidator . createDecoratorFor ( constraintAttributes ) ) ; } } } return fieldConstraints ; }
Parses all annotations and builds validation rules for the relevant ones .
4,946
@ SuppressWarnings ( "unchecked" ) private void initSession ( SMTPClientSession session ) { Iterator < SMTPDeliveryEnvelope > transactionList = ( ( Iterator < SMTPDeliveryEnvelope > ) session . getAttribute ( SMTP_TRANSACTIONS_KEY ) ) ; SMTPDeliveryEnvelope transaction = transactionList . next ( ) ; session . setAttribute ( CURRENT_SMTP_TRANSACTION_KEY , transaction ) ; session . setAttribute ( RECIPIENTS_KEY , transaction . getRecipients ( ) . iterator ( ) ) ; session . setAttribute ( DELIVERY_STATUS_KEY , new ArrayList < DeliveryRecipientStatus > ( ) ) ; session . setAttribute ( CURRENT_RCPT_KEY , null ) ; }
Init the SMTPClienSesion by adding all needed data to the attributes
4,947
public synchronized void getOrCreateVertx ( final VertxPlatformConfiguration config , final VertxListener listener ) { Vertx vertx = vertxPlatforms . get ( config . getVertxPlatformIdentifier ( ) ) ; if ( vertx != null ) { listener . whenReady ( vertx ) ; return ; } VertxOptions options = new VertxOptions ( ) ; options . setClustered ( config . isClustered ( ) ) ; options . setClusterHost ( config . getClusterHost ( ) ) ; options . setClusterPort ( config . getClusterPort ( ) ) ; CountDownLatch latch = new CountDownLatch ( 1 ) ; Vertx . clusteredVertx ( options , ar -> { try { if ( ar . succeeded ( ) ) { log . log ( Level . INFO , "Acquired Vert.x platform." ) ; listener . whenReady ( ar . result ( ) ) ; vertxPlatforms . put ( config . getVertxPlatformIdentifier ( ) , ar . result ( ) ) ; } else { throw new RuntimeException ( "Could not acquire Vert.x platform." , ar . cause ( ) ) ; } } finally { latch . countDown ( ) ; } } ) ; try { if ( ! latch . await ( config . getTimeout ( ) , TimeUnit . MILLISECONDS ) ) { log . log ( Level . SEVERE , "Could not acquire Vert.x platform in interval." ) ; throw new RuntimeException ( "Could not acquire Vert.x platform in interval" ) ; } } catch ( Exception ignore ) { } }
Creates a Vertx if one is not started yet .
4,948
public void addVertxHolder ( VertxHolder holder ) { if ( vertxPlatforms . containsValue ( holder . getVertx ( ) ) ) { if ( ! this . vertxHolders . contains ( holder ) ) { log . log ( Level . INFO , "Adding Vertx Holder: " + holder ) ; this . vertxHolders . add ( holder ) ; } else { log . log ( Level . WARNING , "Vertx Holder: " + holder + " has been added already." ) ; } } else { log . log ( Level . SEVERE , "Vertx Holder: " + holder + " is out of management." ) ; } }
Adds VertxHolder to be recorded .
4,949
public void removeVertxHolder ( VertxHolder holder ) { if ( this . vertxHolders . contains ( holder ) ) { log . log ( Level . INFO , "Removing Vertx Holder: " + holder ) ; this . vertxHolders . remove ( holder ) ; } else { log . log ( Level . SEVERE , "Vertx Holder: " + holder + " is out of management." ) ; } }
Removes the VertxHolder from recorded .
4,950
public void stopPlatformManager ( VertxPlatformConfiguration config ) { Vertx vertx = this . vertxPlatforms . get ( config . getVertxPlatformIdentifier ( ) ) ; if ( vertx != null && isVertxHolded ( vertx ) ) { log . log ( Level . INFO , "Stopping Vert.x: " + config . getVertxPlatformIdentifier ( ) ) ; vertxPlatforms . remove ( config . getVertxPlatformIdentifier ( ) ) ; stopVertx ( vertx ) ; } }
Stops the Vert . x Platform Manager and removes it from cache .
4,951
public void closeAllPlatforms ( ) { log . log ( Level . FINEST , "Closing all Vert.x instances" ) ; try { for ( Map . Entry < String , Vertx > entry : this . vertxPlatforms . entrySet ( ) ) { stopVertx ( entry . getValue ( ) ) ; } vertxPlatforms . clear ( ) ; vertxHolders . clear ( ) ; } catch ( Exception e ) { log . log ( Level . SEVERE , "Error closing Vert.x instance" , e . getCause ( ) ) ; } }
Stops all started Vert . x platforms .
4,952
public String parse ( ) { Map < String , ClassConstraints > classNameToValidationRulesMap = new HashMap < > ( ) ; for ( Class clazz : classpathScanner . findClassesToParse ( ) ) { if ( clazz != null ) { ClassConstraints classValidationRules = new AnnotatedClass ( clazz , options . getExcludedFields ( ) , allRelevantAnnotationClasses ) . extractValidationRules ( ) ; if ( classValidationRules . size ( ) > 0 ) { String name = options . getOutputFullTypeName ( ) ? clazz . getName ( ) : clazz . getSimpleName ( ) ; classNameToValidationRulesMap . put ( name , classValidationRules ) ; } } } return toJson ( classNameToValidationRulesMap ) ; }
Based on the configuration passed to the constructor model classes are parsed for constraints .
4,953
public boolean add ( ClientPresentationModel model ) { boolean success = super . add ( model ) ; if ( success ) { List < ClientAttribute > attributes = model . getAttributes ( ) ; for ( ClientAttribute attribute : attributes ) { attribute . addPropertyChangeListener ( attributeChangeListener ) ; } if ( ! model . isClientSideOnly ( ) ) { getClientConnector ( ) . send ( CreatePresentationModelCommand . makeFrom ( model ) ) ; } } return success ; }
ModelStoreListener ADDED will be fired before server is notified .
4,954
public void deleteAllPresentationModelsOfType ( String presentationModelType ) { getClientConnector ( ) . send ( new DeletedAllPresentationModelsOfTypeNotification ( presentationModelType ) ) ; List < ClientPresentationModel > models = new LinkedList < ClientPresentationModel > ( findAllPresentationModelsByType ( presentationModelType ) ) ; for ( ClientPresentationModel model : models ) { delete ( model , false ) ; } }
ModelStoreListener REMOVE will be fired after the server is notified .
4,955
public void start ( ) throws ResourceException { if ( ! deliveryActive . get ( ) ) { VertxPlatformFactory . instance ( ) . getOrCreateVertx ( config , this ) ; VertxPlatformFactory . instance ( ) . addVertxHolder ( this ) ; } setup ( ) ; }
Start the activation
4,956
public void send ( String channel , String message ) { Pair < Boolean , String > sendValidation = isSendValid ( channel , message , null , null ) ; if ( sendValidation != null && sendValidation . first ) { try { String messageId = Strings . randomString ( 8 ) ; ArrayList < Pair < String , String > > messagesToSend = multiPartMessage ( message , messageId ) ; for ( Pair < String , String > messageToSend : messagesToSend ) { send ( channel , messageToSend . second , messageToSend . first , sendValidation . second ) ; } } catch ( IOException e ) { raiseOrtcEvent ( EventEnum . OnException , this , e ) ; } } }
Sends a message to the specified channel .
4,957
public void subscribeWithFilter ( String channel , boolean subscribeOnReconnect , String filter , OnMessageWithFilter onMessageWithFilter ) { ChannelSubscription subscribedChannel = subscribedChannels . get ( channel ) ; Pair < Boolean , String > subscribeValidation = isSubscribeValid ( channel , subscribedChannel ) ; if ( subscribeValidation != null && subscribeValidation . first ) { subscribedChannel = new ChannelSubscription ( subscribeOnReconnect , onMessageWithFilter ) ; subscribedChannel . setFilter ( filter ) ; subscribedChannel . setWithFilter ( true ) ; subscribedChannel . setSubscribing ( true ) ; subscribedChannels . put ( channel , subscribedChannel ) ; subscribe ( channel , subscribeValidation . second , true , filter ) ; } }
subscribeWithFilter the specified channel with a given filter in order to receive filtered messages in that channel
4,958
public Boolean isSubscribed ( String channel ) { Boolean result = null ; if ( ! isConnected ) { raiseOrtcEvent ( EventEnum . OnException , this , new OrtcNotConnectedException ( ) ) ; } else if ( Strings . isNullOrEmpty ( channel ) ) { raiseOrtcEvent ( EventEnum . OnException , this , new OrtcEmptyFieldException ( "Channel" ) ) ; } else if ( ! Strings . ortcIsValidInput ( channel ) ) { raiseOrtcEvent ( EventEnum . OnException , this , new OrtcInvalidCharactersException ( "Channel" ) ) ; } else { ChannelSubscription subscribedChannel = subscribedChannels . get ( channel ) ; result = subscribedChannel != null && subscribedChannel . isSubscribed ( ) ; } return result ; }
Indicates if the channel is subscribed
4,959
public void setProxy ( String host , int port , String user , String pwd ) { this . proxy = new Proxy ( host , port , user , pwd ) ; }
sets proxy optionally using basic authentication
4,960
public OrtcFactory loadOrtcFactory ( String ortcType ) throws InstantiationException , IllegalAccessException , ClassNotFoundException { OrtcFactory result = null ; Class < ? > factoryClass = this . getClass ( ) . getClassLoader ( ) . loadClass ( String . format ( "ibt.ortc.plugins.%s.%sFactory" , ortcType , ortcType ) ) ; if ( factoryClass != null ) { result = OrtcFactory . class . cast ( factoryClass . newInstance ( ) ) ; } return result ; }
Creates an instance of a factory of the specified Ortc plugin type
4,961
@ SuppressWarnings ( "AssignmentToForLoopParameter" ) public static String encode ( final byte [ ] data ) { final int len = data . length ; final StringBuilder result = new StringBuilder ( ( len / 3 + 1 ) * 4 ) ; int bte ; int index ; for ( int i = 0 ; i < len ; i ++ ) { bte = data [ i ] ; index = bte >> 2 & MASK_6 ; result . append ( CHAR_TABLE . charAt ( index ) ) ; index = bte << 4 & MASK_6 ; if ( ++ i < len ) { bte = data [ i ] ; index |= bte >> 4 & MASK_4 ; } result . append ( CHAR_TABLE . charAt ( index ) ) ; if ( i < len ) { index = bte << 2 & MASK_6 ; if ( ++ i < len ) { bte = data [ i ] ; index |= bte >> 6 & MASK_2 ; } result . append ( CHAR_TABLE . charAt ( index ) ) ; } else { i ++ ; result . append ( CHAR_TABLE . charAt ( 64 ) ) ; } if ( i < len ) { index = bte & MASK_6 ; result . append ( CHAR_TABLE . charAt ( index ) ) ; } else { result . append ( CHAR_TABLE . charAt ( 64 ) ) ; } } return result . toString ( ) ; }
Encodes the given data to a base64 string .
4,962
protected List < Command > decodeInput ( Codec codec , String input ) { return codec . decode ( input ) ; }
Decodes the given input .
4,963
protected List < Command > handleCommands ( ServerConnector serverConnector , List < Command > commands ) { List < Command > results = new ArrayList < Command > ( ) ; for ( Command command : commands ) { if ( LOG . isLoggable ( Level . FINEST ) ) { LOG . finest ( "processing " + command ) ; } results . addAll ( serverConnector . receive ( command ) ) ; } return results ; }
Processes incoming commands and creates outgoing commands .
4,964
protected String encodeOutput ( Codec codec , List < Command > results ) { return codec . encode ( results ) ; }
Encodes the given output .
4,965
public int getValue ( String attributeName , int defaultValue ) { A attribute = getAt ( attributeName ) ; Object attributeValue = ( attribute == null ) ? null : attribute . getValue ( ) ; return ( attributeValue == null ) ? defaultValue : Integer . parseInt ( attributeValue . toString ( ) ) ; }
Convenience method to get the value of an attribute if it exists or a default value otherwise .
4,966
public void syncWith ( PresentationModel sourcePresentationModel ) { for ( A targetAttribute : attributes ) { Attribute sourceAttribute = sourcePresentationModel . getAt ( targetAttribute . getPropertyName ( ) , targetAttribute . getTag ( ) ) ; if ( sourceAttribute != null ) targetAttribute . syncWith ( sourceAttribute ) ; } }
Synchronizes all attributes of the source with all matching attributes of this presentation model
4,967
public static boolean isSocketAlive ( final SocketAddress socketAddress , final int timeoutMsecs ) { final Socket socket = new Socket ( ) ; try { socket . connect ( socketAddress , timeoutMsecs ) ; socket . close ( ) ; return true ; } catch ( final SocketTimeoutException exception ) { return false ; } catch ( final IOException exception ) { return false ; } }
Returns true if a connection can be established to the given socket address within the timeout provided .
4,968
public final Binding getPortBinding ( final String portName ) throws IllegalStateException , IllegalArgumentException { assertStarted ( ) ; final Map < String , List < PortBinding > > ports = info . networkSettings ( ) . ports ( ) ; final List < PortBinding > portBindings = ports . get ( portName ) ; if ( portBindings == null || portBindings . isEmpty ( ) ) { throw new IllegalArgumentException ( "Unknown port binding: " + portName ) ; } final PortBinding portBinding = portBindings . get ( 0 ) ; return ImmutableBinding . builder ( ) . host ( portBinding . hostIp ( ) ) . port ( Integer . parseInt ( portBinding . hostPort ( ) ) ) . build ( ) ; }
Returns the host and port information for the given Docker port name .
4,969
public void stop ( ) { synchronized ( this . startStopMonitor ) { doStop ( ) ; if ( this . shutdownHook != null ) { try { Runtime . getRuntime ( ) . removeShutdownHook ( this . shutdownHook ) ; } catch ( final IllegalStateException ex ) { } } } }
Instructs Docker to stop the container
4,970
public final void waitForLog ( final int timeout , final TimeUnit unit , final String ... messages ) throws DockerException , InterruptedException { final long startTime = System . currentTimeMillis ( ) ; final long timeoutTimeMillis = startTime + TimeUnit . MILLISECONDS . convert ( timeout , unit ) ; int n = 0 ; LOGGER . info ( "Tailing logs for \"{}\"" , messages [ n ] ) ; final LogStream logs = client . logs ( containerId , follow ( ) , stdout ( ) , stderr ( ) ) ; while ( logs . hasNext ( ) ) { if ( Thread . interrupted ( ) ) { throw new InterruptedException ( ) ; } final String message = messages [ n ] ; final String log = StandardCharsets . UTF_8 . decode ( logs . next ( ) . content ( ) ) . toString ( ) ; if ( log . contains ( message ) ) { LOGGER . info ( "Successfully received \"{}\" after {}ms" , message , System . currentTimeMillis ( ) - startTime ) ; if ( ++ n >= messages . length ) { return ; } } if ( startTime > timeoutTimeMillis ) { throw new IllegalStateException ( "Timeout waiting for log \"" + message + "\"" ) ; } } }
Wait for nth occurrence of message to appear in docker logs within the specified timeframe .
4,971
public final void waitForPort ( final String portName ) { final Binding binding = getPortBinding ( portName ) ; waitForPort ( binding . getHost ( ) , binding . getPort ( ) ) ; }
Wait for the specified port to accept socket connection .
4,972
private void startContainer ( ) throws DockerException { final long startTime = System . currentTimeMillis ( ) ; try { LOGGER . info ( "Starting container {} with id {}" , containerConfig . image ( ) , containerId ) ; client . startContainer ( containerId ) ; } catch ( DockerException | InterruptedException e ) { throw new DockerException ( "Unable to start container " + containerConfig . image ( ) + " with id " + containerId , e ) ; } finally { final long elapsedMillis = System . currentTimeMillis ( ) - startTime ; LOGGER . info ( "Container {} started in {}ms" , containerConfig . image ( ) , elapsedMillis ) ; } }
Instructs Docker to start the container
4,973
public VertxEventBus vertxEventBus ( ) throws ResourceException { log . finest ( "getConnection()" ) ; if ( this . mc != null ) { return this . mc . getVertxEventBus ( ) ; } throw new ResourceException ( "Vertx Managed Connection has been closed." ) ; }
Get connection from factory
4,974
public static String randomString ( int length ) { if ( length < 1 ) { throw new IllegalArgumentException ( String . format ( "length < 1: %s" , length ) ) ; } char [ ] buf = new char [ length ] ; return nextString ( buf ) ; }
Generates a random alphanumeric string
4,975
public static Object checkValue ( Object value ) { if ( null == value ) return null ; if ( value instanceof Tag ) return ( ( Tag ) value ) . getName ( ) ; Object result = value ; if ( result instanceof GString ) result = value . toString ( ) ; if ( result instanceof BaseAttribute ) { if ( log . isLoggable ( Level . WARNING ) ) log . warning ( "An Attribute may not itself contain an attribute as a value. Assuming you forgot to call getValue()." ) ; result = checkValue ( ( ( ( BaseAttribute ) value ) . getValue ( ) ) ) ; } boolean ok = false ; for ( Class type : SUPPORTED_VALUE_TYPES ) { if ( type . isAssignableFrom ( result . getClass ( ) ) ) { ok = true ; break ; } } if ( ! ok ) { throw new IllegalArgumentException ( "Attribute values of this type are not allowed: " + result . getClass ( ) . getSimpleName ( ) ) ; } return result ; }
Check whether value is of allowed type and convert to an allowed type if possible .
4,976
private void releaseHttpRequest ( HttpServletRequestEvent hreqEvent ) { if ( tracer . isFinestEnabled ( ) ) { tracer . finest ( "releaseHttpRequest() enter" ) ; } final Object lock = requestLock . removeLock ( hreqEvent ) ; if ( lock != null ) { synchronized ( lock ) { lock . notify ( ) ; } } if ( tracer . isFineEnabled ( ) ) { tracer . fine ( "released lock for http request " + hreqEvent . getId ( ) ) ; } }
Allows control to be returned back to the servlet conainer which delivered the http request . The container will mandatory close the response stream .
4,977
public void onStartServiceEvent ( javax . slee . serviceactivity . ServiceStartedEvent event , ActivityContextInterface aci ) { tracer . info ( "Retreiving www.telestax.com..." ) ; try { HttpClientNIORequestActivity activity = httpClientRA . execute ( new HttpGet ( "http://www.telestax.com" ) , null , System . currentTimeMillis ( ) ) ; httpClientACIF . getActivityContextInterface ( activity ) . attach ( sbbContext . getSbbLocalObject ( ) ) ; } catch ( Exception e ) { tracer . severe ( "failed to retrieve webpage" , e ) ; } }
Event handler methods
4,978
public Date parse ( String dateString ) throws ParseException { Date result = null ; ParseException lastException = null ; for ( DateFormat format : inputFormats ) { try { result = ( ( DateFormat ) format . clone ( ) ) . parse ( dateString ) ; lastException = null ; break ; } catch ( ParseException e ) { if ( lastException == null ) { lastException = e ; } } } if ( lastException != null ) { throw lastException ; } return result ; }
Attempts to parse the given string into a java . util . Date using the provided input formats .
4,979
private HttpAsyncClient buildHttpAsyncClient ( ) throws IOReactorException { IOReactorConfig ioReactorConfig = IOReactorConfig . custom ( ) . setConnectTimeout ( connectTimeout ) . setSoTimeout ( socketTimeout ) . build ( ) ; ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor ( ioReactorConfig ) ; PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager ( ioReactor ) ; connManager . setMaxTotal ( maxTotal ) ; connManager . setDefaultMaxPerRoute ( defaultMaxPerRoute ) ; return httpAsyncClient = HttpAsyncClients . custom ( ) . useSystemProperties ( ) . setConnectionManager ( connManager ) . build ( ) ; }
Creates an instance of async http client .
4,980
private void doIncrementHash ( String key , String hashKey , long amount , String bookkeepingKey ) { long newValue = hashOperations . increment ( key , hashKey , amount ) ; if ( newValue == amount ) { setOperations . add ( bookkeepingKey , key ) ; } }
Internally increments the given hash key keeping track of created hash for a given counter so they can be cleaned up when needed .
4,981
@ RequestMapping ( value = "/{name}" , method = RequestMethod . GET ) public AggregateCounterResource display ( @ PathVariable ( "name" ) String name ) { AggregateCounter counter = repository . findOne ( name ) ; if ( counter == null ) { throw new NoSuchMetricException ( name ) ; } return deepAssembler . toResource ( counter ) ; }
Retrieve information about a specific aggregate counter .
4,982
@ RequestMapping ( value = "/{name}" , method = RequestMethod . GET , produces = MediaType . APPLICATION_JSON_VALUE ) public AggregateCounterResource display ( @ PathVariable ( "name" ) String name , @ RequestParam ( value = "from" , required = false ) @ DateTimeFormat ( iso = DateTimeFormat . ISO . DATE_TIME ) DateTime from , @ RequestParam ( value = "to" , required = false ) @ DateTimeFormat ( iso = DateTimeFormat . ISO . DATE_TIME ) DateTime to , @ RequestParam ( value = "resolution" , defaultValue = "hour" ) AggregateCounterResolution resolution ) { to = providedOrDefaultToValue ( to ) ; from = providedOrDefaultFromValue ( from , to , resolution ) ; AggregateCounter aggregate = repository . getCounts ( name , new Interval ( from , to ) , resolution ) ; return deepAssembler . toResource ( aggregate ) ; }
Retrieve counts for a given time interval using some precision .
4,983
private DateTime providedOrDefaultFromValue ( DateTime from , DateTime to , AggregateCounterResolution resolution ) { if ( from != null ) { return from ; } switch ( resolution ) { case minute : return to . minusMinutes ( 59 ) ; case hour : return to . minusHours ( 23 ) ; case day : return to . minusDays ( 6 ) ; case month : return to . minusMonths ( 11 ) ; case year : return to . minusYears ( 4 ) ; default : throw new IllegalStateException ( "Shouldn't happen. Unhandled resolution: " + resolution ) ; } }
Return a default value for the interval start if none has been provided .
4,984
protected XStream createXStream ( HierarchicalStreamDriver driver , NaaccrPatientConverter patientConverter ) { XStream xstream = new XStream ( driver ) { protected void setupConverters ( ) { registerConverter ( new NullConverter ( ) , PRIORITY_VERY_HIGH ) ; registerConverter ( new IntConverter ( ) , PRIORITY_NORMAL ) ; registerConverter ( new FloatConverter ( ) , PRIORITY_NORMAL ) ; registerConverter ( new DoubleConverter ( ) , PRIORITY_NORMAL ) ; registerConverter ( new LongConverter ( ) , PRIORITY_NORMAL ) ; registerConverter ( new ShortConverter ( ) , PRIORITY_NORMAL ) ; registerConverter ( new BooleanConverter ( ) , PRIORITY_NORMAL ) ; registerConverter ( new ByteConverter ( ) , PRIORITY_NORMAL ) ; registerConverter ( new StringConverter ( ) , PRIORITY_NORMAL ) ; registerConverter ( new DateConverter ( ) , PRIORITY_NORMAL ) ; registerConverter ( new CollectionConverter ( getMapper ( ) ) , PRIORITY_NORMAL ) ; registerConverter ( new ReflectionConverter ( getMapper ( ) , getReflectionProvider ( ) ) , PRIORITY_VERY_LOW ) ; } } ; xstream . addPermission ( NoTypePermission . NONE ) ; xstream . addPermission ( new WildcardTypePermission ( new String [ ] { "com.imsweb.naaccrxml.**" } ) ) ; xstream . alias ( NaaccrXmlUtils . NAACCR_XML_TAG_ROOT , NaaccrData . class ) ; xstream . alias ( NaaccrXmlUtils . NAACCR_XML_TAG_ITEM , Item . class ) ; xstream . alias ( NaaccrXmlUtils . NAACCR_XML_TAG_PATIENT , Patient . class ) ; xstream . aliasAttribute ( NaaccrData . class , "_baseDictionaryUri" , NaaccrXmlUtils . NAACCR_XML_ROOT_ATT_BASE_DICT ) ; xstream . aliasAttribute ( NaaccrData . class , "_userDictionaryUri" , NaaccrXmlUtils . NAACCR_XML_ROOT_ATT_USER_DICT ) ; xstream . aliasAttribute ( NaaccrData . class , "_recordType" , NaaccrXmlUtils . NAACCR_XML_ROOT_ATT_REC_TYPE ) ; xstream . aliasAttribute ( NaaccrData . class , "_timeGenerated" , NaaccrXmlUtils . NAACCR_XML_ROOT_ATT_TIME_GENERATED ) ; xstream . aliasAttribute ( NaaccrData . class , "_specificationVersion" , NaaccrXmlUtils . NAACCR_XML_ROOT_ATT_SPEC_VERSION ) ; xstream . addImplicitCollection ( NaaccrData . class , "_items" , Item . class ) ; xstream . addImplicitCollection ( NaaccrData . class , "_patients" , Patient . class ) ; xstream . registerConverter ( patientConverter ) ; return xstream ; }
Creates the instance of XStream to us for all reading and writing operations
4,985
public void registerNamespace ( String namespacePrefix , String namespaceUri ) { if ( _namespaces . containsKey ( namespacePrefix ) ) throw new RuntimeException ( "Namespace prefix '" + namespacePrefix + "' has already been registered" ) ; _namespaces . put ( namespacePrefix , namespaceUri ) ; }
Registers a namespace for a given namespace prefix . This method must be called before registering any tags or attributes for that namespace . Note that extensions require namespaces to work properly .
4,986
public void registerTag ( String namespacePrefix , String tagName , Class < ? > clazz ) { if ( ! _namespaces . containsKey ( namespacePrefix ) ) throw new RuntimeException ( "Namespace prefix '" + namespacePrefix + "' has not been registered yet" ) ; _xstream . alias ( namespacePrefix + ":" + tagName , clazz ) ; _xstream . addPermission ( new WildcardTypePermission ( new String [ ] { clazz . getName ( ) } ) ) ; _tags . computeIfAbsent ( namespacePrefix , k -> new HashSet < > ( ) ) . add ( tagName ) ; }
Registers a tag corresponding to a specific class in the given namespace .
4,987
public void registerTag ( String namespacePrefix , String tagName , Class < ? > clazz , String fieldName , Class < ? > fieldClass ) { if ( ! _namespaces . containsKey ( namespacePrefix ) ) throw new RuntimeException ( "Namespace prefix '" + namespacePrefix + "' has not been registered yet" ) ; _xstream . alias ( namespacePrefix + ":" + tagName , fieldClass ) ; _xstream . aliasField ( namespacePrefix + ":" + tagName , clazz , fieldName ) ; _tags . computeIfAbsent ( namespacePrefix , k -> new HashSet < > ( ) ) . add ( tagName ) ; }
Registers a tag corresponding to a specific field of a specific class in a the given namespace .
4,988
public void registerAttribute ( String namespacePrefix , String attributeName , Class < ? > clazz , String fieldName , Class < ? > fieldClass ) { if ( ! _namespaces . containsKey ( namespacePrefix ) ) throw new RuntimeException ( "Namespace prefix '" + namespacePrefix + "' has not been registered yet" ) ; _xstream . aliasAttribute ( clazz , fieldName , namespacePrefix + ":" + attributeName ) ; _xstream . useAttributeFor ( fieldName , fieldClass ) ; }
Registers an attribute corresponding to a specific field of a specific class in a given namespace .
4,989
public static String getValidationError ( String code , Object ... msgValues ) { if ( ! _MESSAGES . containsKey ( code ) ) throw new RuntimeException ( "Unknown code: " + code ) ; return fillMessage ( _MESSAGES . get ( code ) , msgValues ) ; }
Returns the error message for the given error code
4,990
public static BufferedReader createReader ( File file ) throws IOException { InputStream is = new FileInputStream ( file ) ; if ( file . getName ( ) . toLowerCase ( ) . endsWith ( ".gz" ) ) is = new GZIPInputStream ( is ) ; return new BufferedReader ( new InputStreamReader ( is , StandardCharsets . UTF_8 ) ) ; }
Creates a reader from the given file . Support GZIP compressed files .
4,991
public static BufferedWriter createWriter ( File file ) throws IOException { OutputStream os = new FileOutputStream ( file ) ; if ( file . getName ( ) . toLowerCase ( ) . endsWith ( ".gz" ) ) os = new GZIPOutputStream ( os ) ; return new BufferedWriter ( new OutputStreamWriter ( os , StandardCharsets . UTF_8 ) ) ; }
Creates a writer from the given file . Supports GZIP compressed files .
4,992
public static List < SasFieldInfo > getFields ( String version , String recordType , File dictionary ) { return getFields ( recordType , Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( "naaccr-xml-items-" + version + ".csv" ) , dictionary ) ; }
Returns the fields information for the given parameters .
4,993
@ RequestMapping ( value = "/{name}" , method = RequestMethod . GET ) public CounterResource display ( @ PathVariable ( "name" ) String name ) { Metric < Double > c = findCounter ( name ) ; return counterResourceAssembler . toResource ( c ) ; }
Retrieve information about a specific counter .
4,994
private Metric < Double > findCounter ( @ PathVariable ( "name" ) String name ) { @ SuppressWarnings ( "unchecked" ) Metric < Double > c = ( Metric < Double > ) metricRepository . findOne ( COUNTER_PREFIX + name ) ; if ( c == null ) { throw new NoSuchMetricException ( name ) ; } return c ; }
Find a given counter taking care of name conversion between the Spring Boot domain and our domain .
4,995
@ SuppressWarnings ( "unchecked" ) private < T extends Number > List < Metric < T > > filterCounters ( Iterable < Metric < ? > > input ) { List < Metric < T > > result = new ArrayList < > ( ) ; for ( Metric < ? > metric : input ) { if ( metric . getName ( ) . startsWith ( COUNTER_PREFIX ) ) { result . add ( ( Metric < T > ) metric ) ; } } return result ; }
Filter the list of Boot metrics to only return those that are counters .
4,996
public static SeerClickableLabelAction createBrowseToUrlAction ( final String url ) { return ( ) -> { Desktop desktop = Desktop . isDesktopSupported ( ) ? Desktop . getDesktop ( ) : null ; if ( desktop != null && desktop . isSupported ( Desktop . Action . BROWSE ) ) { try { desktop . browse ( URI . create ( url ) ) ; } catch ( IOException | RuntimeException e ) { } } } ; }
Utility method to create an action that browse to a given internet address .
4,997
public static boolean isSpecificationSupported ( String spec ) { return SPEC_1_0 . equals ( spec ) || SPEC_1_1 . equals ( spec ) || SPEC_1_2 . equals ( spec ) || SPEC_1_3 . equals ( spec ) ; }
Returns true if the provided spec is supported by this library false otherwise .
4,998
public static int compareSpecifications ( String spec1 , String spec2 ) { String [ ] parts1 = StringUtils . split ( spec1 , '.' ) ; Integer major1 = Integer . valueOf ( parts1 [ 0 ] ) ; Integer minor1 = Integer . valueOf ( parts1 [ 1 ] ) ; String [ ] parts2 = StringUtils . split ( spec2 , '.' ) ; Integer major2 = Integer . valueOf ( parts2 [ 0 ] ) ; Integer minor2 = Integer . valueOf ( parts2 [ 1 ] ) ; if ( major1 . equals ( major2 ) ) return minor1 . compareTo ( minor2 ) ; return major1 . compareTo ( major2 ) ; }
Compare the two provided specifications . Result is undefined if any of them is not supported .
4,999
public List < String > getContainedItemId ( ) { if ( StringUtils . isBlank ( _contains ) ) return Collections . emptyList ( ) ; return Arrays . asList ( StringUtils . split ( _contains , ',' ) ) ; }
Returns the NAACCR ID of the items contained in this grouped item .