idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
18,800 | public static String getProjectUrl ( final String group ) { if ( group == null ) { return PLUGIN_ID ; } else { return PLUGIN_ID + ParserRegistry . getUrl ( group ) ; } } | Returns the URL of the warning project for the specified parser . |
18,801 | public Object getDynamic ( final String link , final StaplerRequest request , final StaplerResponse response ) { if ( "configureDefaults" . equals ( link ) ) { Ancestor ancestor = request . findAncestor ( AbstractProject . class ) ; if ( ancestor . getObject ( ) instanceof AbstractProject ) { AbstractProject < ? , ? > project = ( AbstractProject < ? , ? > ) ancestor . getObject ( ) ; return new DefaultGraphConfigurationView ( new GraphConfiguration ( WarningsProjectAction . getAllGraphs ( ) ) , project , "warnings" , new NullBuildHistory ( ) , project . getAbsoluteUrl ( ) + "/descriptorByName/WarningsPublisher/configureDefaults/" ) ; } } return null ; } | Returns the graph configuration screen . |
18,802 | protected MessageFormat resolveCodeInternal ( String code , Locale locale ) { String result ; lastQuery = System . currentTimeMillis ( ) ; try { result = ( String ) jdbcTemplate . queryForObject ( sqlStatement , new Object [ ] { code , locale . toString ( ) } , String . class ) ; } catch ( IncorrectResultSizeDataAccessException e ) { if ( locale != null ) { try { result = ( String ) jdbcTemplate . queryForObject ( sqlStatement , new Object [ ] { code , null } , String . class ) ; } catch ( IncorrectResultSizeDataAccessException ex ) { return null ; } } else { return null ; } } return new MessageFormat ( result , locale ) ; } | Check in base the message associated with the given code and locale |
18,803 | public String generateMarkov ( int length , int context , String seed ) { String str = seed ; while ( str . length ( ) < length ) { String prefix = str . substring ( Math . max ( str . length ( ) - context , 0 ) , str . length ( ) ) ; TrieNode node = inner . matchPredictor ( prefix ) ; long cursorCount = node . getCursorCount ( ) ; long fate = CompressionUtil . random . nextLong ( ) % cursorCount ; String next = null ; Stream < TrieNode > stream = node . getChildren ( ) . map ( x -> x ) ; List < TrieNode > children = stream . collect ( Collectors . toList ( ) ) ; for ( TrieNode child : children ) { fate -= child . getCursorCount ( ) ; if ( fate <= 0 ) { if ( child . getChar ( ) != NodewalkerCodec . END_OF_STRING ) { next = child . getToken ( ) ; } break ; } } if ( null != next ) { str += next ; } else { break ; } } return str ; } | Generate markov string . |
18,804 | protected boolean alreadyResettingRule ( final RuleContext rc ) { if ( m_resettingRules . contains ( rc ) ) { return true ; } m_resettingRules . add ( rc ) ; return false ; } | Method alreadyResettingRule . Sometimes a rule attempts to reset twice and gets into a loop This checks for that situation . Rules only need to be reset once . |
18,805 | public void blockUtilConnected ( ) { if ( getStatus ( ) . isConnected ( ) ) { return ; } int to = getConnectTimeOut ( ) ; final Object o = new Object ( ) ; long now = System . currentTimeMillis ( ) ; synchronized ( o ) { ServiceDirectoryListener listener = new ServiceDirectoryListener ( ) { public void notify ( ServiceDirectoryEvent event ) { synchronized ( o ) { o . notifyAll ( ) ; } } } ; registerClientChangeListener ( listener ) ; try { while ( to > 0 ) { if ( getStatus ( ) . isConnected ( ) ) { return ; } try { o . wait ( to ) ; } catch ( InterruptedException e ) { LOGGER . warn ( "Block Util Connected interrupted." ) ; } to -= ( System . currentTimeMillis ( ) - now ) ; } } finally { unregisterClientChangeListener ( listener ) ; } } } | Block util the connect complete . |
18,806 | public void start ( ) { setStatus ( ConnectionStatus . NOT_CONNECTED ) ; InetSocketAddress address = directoryServer ; clientSocket . connect ( address ) ; eventThread . start ( ) ; connectionThread = new Thread ( new ConnectTask ( ) ) ; connectionThread . setDaemon ( true ) ; connectionThread . setName ( ServiceDirectoryThread . getThreadName ( "Client_Connect_Thread" ) ) ; connectionThread . start ( ) ; } | Start the DirectoryConnection . |
18,807 | public synchronized void close ( ) throws IOException { if ( getStatus ( ) . equals ( ConnectionStatus . CLOSED ) ) { return ; } if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Closing client for session: 0x" + getSessionId ( ) ) ; } connectRun . set ( false ) ; try { clientSocket . cleanup ( ) ; } catch ( Exception e ) { LOGGER . warn ( "Close the WSDirectorySocket get error." , e ) ; } try { setStatus ( ConnectionStatus . CLOSED ) ; sendCloseSession ( ) ; closeSession ( ) ; eventThread . queueEventOfDeath ( ) ; } catch ( ServiceException e ) { LOGGER . warn ( "Execute the CloseSession Protocol failed when close" , e ) ; } } | Close the Directory Connection . |
18,808 | public Response submitRequest ( ProtocolHeader h , Protocol request , WatcherRegistration wr ) { Packet packet = queuePacket ( h , request , null , null , null , wr ) ; synchronized ( packet ) { while ( ! packet . finished ) { try { packet . wait ( ) ; } catch ( InterruptedException e ) { ServiceDirectoryError sde = new ServiceDirectoryError ( ErrorCode . REQUEST_INTERUPTED ) ; throw new ServiceException ( sde , e ) ; } } } if ( ! packet . respHeader . getErr ( ) . equals ( ErrorCode . OK ) ) { ServiceDirectoryError sde = new ServiceDirectoryError ( packet . respHeader . getErr ( ) ) ; throw new ServiceException ( sde ) ; } return packet . response ; } | Submit a Request . |
18,809 | public void submitCallbackRequest ( ProtocolHeader h , Protocol request , ProtocolCallback callBack , Object context ) { queuePacket ( h , request , callBack , context , null , null ) ; } | Submit a Request with Callback . |
18,810 | public ServiceDirectoryFuture submitAsyncRequest ( ProtocolHeader h , Protocol request , WatcherRegistration wr ) { ServiceDirectoryFuture future = new ServiceDirectoryFuture ( ) ; queuePacket ( h , request , null , null , future , wr ) ; return future ; } | Submit a Request in asynchronizing it return a Future for the Request Response . |
18,811 | private Packet queuePacket ( ProtocolHeader header , Protocol protocol , ProtocolCallback cb , Object context , ServiceDirectoryFuture future , WatcherRegistration wr ) { Packet packet = new Packet ( header , protocol , wr ) ; PacketLatency . initPacket ( packet ) ; header . createTime = packet . createTime ; packet . cb = cb ; packet . context = context ; packet . future = future ; if ( ! clientSocket . isConnected ( ) || closing ) { onLossPacket ( packet ) ; } else { synchronized ( pendingQueue ) { if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . trace ( "Add the packet in queuePacket, type=" + header . getType ( ) ) ; } header . setXid ( xid . incrementAndGet ( ) ) ; try { PacketLatency . queuePacket ( packet ) ; clientSocket . sendPacket ( header , protocol ) ; pendingQueue . add ( packet ) ; PacketLatency . sendPacket ( packet ) ; } catch ( IOException e ) { LOGGER . error ( "ClientSocket send packet failed." ) ; if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . trace ( "ClientSocket send packet failed." , e ) ; } if ( packet != null ) { onLossPacket ( packet ) ; } } } } return packet ; } | Queue the Packet to Connection . |
18,812 | public void setDirectoryUser ( String userName , String password ) { this . authData = generateDirectoryAuthData ( userName , password ) ; if ( getStatus ( ) . isConnected ( ) ) { ErrorCode ec = sendConnectProtocol ( this . getConnectTimeOut ( ) ) ; if ( ErrorCode . SESSION_EXPIRED . equals ( ec ) ) { LOGGER . info ( "Session Expired, cleanup the client session." ) ; closeSession ( ) ; } else if ( ! ErrorCode . OK . equals ( ec ) ) { reopenSession ( ) ; } } } | Change the Directory Authentication . |
18,813 | private void setStatus ( ConnectionStatus status ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Set status to - " + status ) ; } if ( ! this . status . equals ( status ) ) { ConnectionStatus pre = this . status ; this . status = status ; eventThread . queueClientEvent ( new ClientStatusEvent ( pre , status ) ) ; } } | Set the DirectoryConnection ConenctionStatus . |
18,814 | public void onConnected ( int serverSessionTimeout , String sessionId , byte [ ] sessionPassword , int serverId ) { if ( serverSessionTimeout <= 0 ) { closeSession ( ) ; LOGGER . error ( "Unable to reconnect to Directory Server, session 0x" + sessionId + " has expired" ) ; return ; } boolean reopen = session . id == null || session . id . equals ( "" ) ? false : true ; session . timeOut = serverSessionTimeout ; session . id = sessionId ; session . password = sessionPassword ; session . serverId = serverId ; if ( getStatus ( ) . isAlive ( ) ) { setStatus ( ConnectionStatus . CONNECTED ) ; } if ( reopen ) { eventThread . queueClientEvent ( new ClientSessionEvent ( SessionEvent . REOPEN ) ) ; } else { eventThread . queueClientEvent ( new ClientSessionEvent ( SessionEvent . CREATED ) ) ; } LOGGER . info ( "Session establishment complete on server " + this . clientSocket . getRemoteSocketAddress ( ) + ", sessionid = 0x" + sessionId + ", session timeout = " + session . timeOut + ", serverId=" + session . serverId ) ; } | On the DirectoryConnection setup connection to DirectoryServer . |
18,815 | private void sendCloseSession ( ) throws IOException { ProtocolHeader h = new ProtocolHeader ( ) ; h . setType ( ProtocolType . CloseSession ) ; sendAdminPacket ( h , null ) ; } | Send the CloseSession packet . |
18,816 | private void doConnect ( ) throws SessionTimeOutException { long to = getConnectTimeOut ( ) ; if ( clientSocket . isConnected ( ) ) { ErrorCode ec = sendConnectProtocol ( to ) ; if ( ErrorCode . SESSION_EXPIRED . equals ( ec ) || ErrorCode . CONNECTION_LOSS . equals ( equals ( ec ) ) ) { LOGGER . info ( "Session Expired, cleanup the client session." ) ; cleanupSession ( ) ; } } } | Connect to the remote DirectoryServer . |
18,817 | private ErrorCode sendConnectProtocol ( long to ) { String sessId = session . id ; ErrorCode ec = ErrorCode . OK ; ConnectProtocol conReq = new ConnectProtocol ( 0 , lastDxid , session . timeOut , sessId , session . password , authData . userName , authData . secret , authData . obfuscated ) ; ServiceDirectoryFuture future = submitAsyncRequest ( new ProtocolHeader ( 0 , ProtocolType . CreateSession ) , conReq , null ) ; try { ConnectResponse resp = null ; if ( future . isDone ( ) ) { resp = ( ConnectResponse ) future . get ( ) ; } else { resp = ( ConnectResponse ) future . get ( to , TimeUnit . MILLISECONDS ) ; } onConnected ( resp . getTimeOut ( ) , resp . getSessionId ( ) , resp . getPasswd ( ) , resp . getServerId ( ) ) ; return ec ; } catch ( ExecutionException e ) { ServiceException se = ( ServiceException ) e . getCause ( ) ; ec = se . getServiceDirectoryError ( ) . getExceptionCode ( ) ; } catch ( Exception e ) { ec = ErrorCode . GENERAL_ERROR ; } future . cancel ( false ) ; return ec ; } | Send the Connect Protocol to the remote Directory Server . |
18,818 | private void sendAdminPacket ( ProtocolHeader header , Protocol protocol ) throws IOException { clientSocket . sendPacket ( header , protocol ) ; } | Send the packet to Directory Server directory . |
18,819 | private void finishPacket ( Packet p ) { if ( p . watcherRegistration != null ) { if ( ErrorCode . OK . equals ( p . respHeader . getErr ( ) ) ) { this . watcherManager . register ( p . watcherRegistration ) ; } } synchronized ( p ) { p . finished = true ; PacketLatency . finishPacket ( p ) ; if ( p . cb == null && p . future == null ) { p . notifyAll ( ) ; } } eventThread . queuePacket ( p ) ; } | The Packet finished . |
18,820 | private void onLossPacket ( Packet p ) { if ( p . respHeader == null ) { p . respHeader = new ResponseHeader ( - 1 , - 1 , ErrorCode . OK ) ; } switch ( getStatus ( ) ) { case AUTH_FAILED : p . respHeader . setErr ( ErrorCode . AUTHENT_FAILED ) ; break ; case CLOSED : p . respHeader . setErr ( ErrorCode . CLIENT_CLOSED ) ; break ; default : p . respHeader . setErr ( ErrorCode . CONNECTION_LOSS ) ; } finishPacket ( p ) ; } | On the Packet lost in the DirectoryConnection . |
18,821 | private void onSessionClose ( ) { synchronized ( pendingQueue ) { while ( ! pendingQueue . isEmpty ( ) ) { Packet p = pendingQueue . remove ( ) ; onLossPacket ( p ) ; } } } | On the session close . |
18,822 | private void closeSession ( ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Close the session, sessionId=" + session . id + ", timeOut=" + session . timeOut ) ; } if ( ! closing && getStatus ( ) . isConnected ( ) ) { closing = true ; if ( getStatus ( ) . isAlive ( ) ) { setStatus ( ConnectionStatus . NOT_CONNECTED ) ; } cleanupSession ( ) ; closing = false ; } } | It cleans the session including the sessionId sessionPassword . |
18,823 | private void cleanupSession ( ) { eventThread . queueClientEvent ( new ClientSessionEvent ( SessionEvent . CLOSED ) ) ; watcherManager . cleanup ( ) ; session . id = "" ; session . password = null ; session . serverId = - 1 ; onSessionClose ( ) ; } | Cleanup the session in the DirectoryConnection . |
18,824 | private void reopenSession ( ) { if ( ! closing && getStatus ( ) . isConnected ( ) ) { closing = true ; if ( getStatus ( ) . isAlive ( ) ) { setStatus ( ConnectionStatus . NOT_CONNECTED ) ; } closing = false ; } } | When connect has exception and the session still not out of time . Reopen the session to server . |
18,825 | private ErrorCode sendPing ( ) throws IOException { if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . trace ( "......................send Ping" ) ; } lastPingSentNs = System . currentTimeMillis ( ) ; ProtocolHeader h = new ProtocolHeader ( - 2 , ProtocolType . Ping ) ; sendAdminPacket ( h , null ) ; int waitTime = session . pingWaitTimeOut ; synchronized ( pingResponse ) { while ( waitTime > 0 ) { try { pingResponse . wait ( waitTime ) ; } catch ( InterruptedException e ) { } ResponseHeader header = pingResponse . get ( ) ; if ( header != null ) { pingResponse . set ( null ) ; return header . getErr ( ) ; } waitTime -= ( System . currentTimeMillis ( ) - lastPingSentNs ) ; } } return ErrorCode . PING_TIMEOUT ; } | Send the Ping Request . |
18,826 | private AuthData generateDirectoryAuthData ( String userName , String password ) { if ( password != null && ! password . isEmpty ( ) ) { byte [ ] secret = ObfuscatUtil . base64Encode ( password . getBytes ( ) ) ; return new AuthData ( AuthScheme . DIRECTORY , userName , secret , true ) ; } else { return new AuthData ( AuthScheme . DIRECTORY , userName , null , false ) ; } } | Generate the obfuscated auth data . |
18,827 | public RuleProxyField backChain ( ) { ObjectMetadata objectMetadata = m_proxyField . getObjectMetadata ( ) ; for ( RuleContext rc : getOutputRules ( ) ) { for ( FieldReference fr : rc . getRule ( ) . listeners ( ) ) { RuleProxyField rpf = m_ruleSession . getRuleProxyField ( objectMetadata . getProxyField ( fr . getFieldName ( ) ) ) ; if ( rpf . askFor ( ) ) { RuleProxyField rpf1 = rpf . backChain ( ) ; if ( rpf1 == null ) { return rpf ; } else { return rpf1 ; } } } } return null ; } | Find the first unfilled field needed to supply this field and return it . |
18,828 | public static byte [ ] fromBinaryCollection ( Collection < Binary > binaryList ) throws IOException { try ( ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; BigEndianBinaryWriter writer = new BigEndianBinaryWriter ( baos ) ) { writer . writeInt ( binaryList . size ( ) ) ; for ( Binary binary : binaryList ) { writer . writeInt ( binary . length ( ) ) ; writer . writeBinary ( binary ) ; } return baos . toByteArray ( ) ; } } | Method to convert a Collection of Binary to a byte array . |
18,829 | public static Collection < Binary > toBinaryCollection ( byte [ ] bytes ) throws IOException { try ( ByteArrayInputStream bais = new ByteArrayInputStream ( bytes ) ; BigEndianBinaryReader reader = new BigEndianBinaryReader ( bais ) ) { final int size = reader . expectInt ( ) ; Collection < Binary > result = new ArrayList < > ( ) ; for ( int i = 0 ; i < size ; i ++ ) { int length = reader . expectInt ( ) ; result . add ( reader . expectBinary ( length ) ) ; } return result ; } } | Method to convert a byte array to a Collection of Binary . |
18,830 | public static Properties format ( Config config ) { Properties properties = new Properties ( ) ; writeConfig ( "" , config , properties ) ; return properties ; } | Format a config into a properties instance . |
18,831 | static public String getString ( String msg ) { if ( bundle == null ) return msg ; try { return bundle . getString ( msg ) ; } catch ( MissingResourceException e ) { return "Missing message: " + msg ; } } | Retrieves a message which has no arguments . |
18,832 | static public String getString ( String msg , int arg ) { return getString ( msg , new Object [ ] { Integer . toString ( arg ) } ) ; } | Retrieves a message which takes 1 integer argument . |
18,833 | static public String getString ( String msg , char arg ) { return getString ( msg , new Object [ ] { String . valueOf ( arg ) } ) ; } | Retrieves a message which takes 1 character argument . |
18,834 | static public String getString ( String msg , Object arg1 , Object arg2 ) { return getString ( msg , new Object [ ] { arg1 , arg2 } ) ; } | Retrieves a message which takes 2 arguments . |
18,835 | static public String getString ( String msg , Object [ ] args ) { String format = msg ; if ( bundle != null ) { try { format = bundle . getString ( msg ) ; } catch ( MissingResourceException e ) { } } return format ( format , args ) ; } | Retrieves a message which takes several arguments . |
18,836 | public void invokeListeners ( final ValidationObject object , final String fieldName , final Object newValue , final Object currentValue ) { m_validationEngine . invokeListeners ( object , fieldName , newValue , currentValue , this ) ; } | This is called after a successful setter call on one of the fields . If any listeners are attached to the field they are invoked from here . |
18,837 | public void addListener ( ValidationObject object , String name , SetterListener listener ) { m_validationEngine . addListener ( object , name , this , listener ) ; } | Add a setter listener to a field . |
18,838 | public void clean ( final ValidationObject object ) { if ( m_enabled ) { m_validationEngine . clean ( object ) ; for ( ProxyField proxyField : m_history ) { proxyField . expire ( ) ; } } } | The clean method ensures that the object and its attached objects are up to date ie that any mapping is updated . This means the getters on the object are safe to use |
18,839 | public ObjectMetadata getMetadata ( final ValidationObject object ) { if ( m_enabled ) { m_validationEngine . clean ( object ) ; } return object . getMetadata ( ) ; } | Locate the metadata for the given object The object is cleaned first and then a wrapper for the metadata is returned |
18,840 | protected void removedFrom ( final ListeningArray < ? > array , final ValidationObject o ) { if ( m_enabled ) { m_validationEngine . removedFrom ( array , o , this ) ; } } | Remove an object from an array |
18,841 | static void generateVisitors ( Set < String > elementNames , List < XsdAttribute > attributes , String apiName ) { generateVisitorInterface ( elementNames , filterAttributes ( attributes ) , apiName ) ; } | Generates both the abstract visitor class with methods for each element from the list . |
18,842 | private static void generateVisitorInterface ( Set < String > elementNames , List < XsdAttribute > attributes , String apiName ) { ClassWriter classWriter = generateClass ( ELEMENT_VISITOR , JAVA_OBJECT , null , null , ACC_PUBLIC + ACC_ABSTRACT + ACC_SUPER , apiName ) ; MethodVisitor mVisitor = classWriter . visitMethod ( ACC_PUBLIC , CONSTRUCTOR , "()V" , null , null ) ; mVisitor . visitCode ( ) ; mVisitor . visitVarInsn ( ALOAD , 0 ) ; mVisitor . visitMethodInsn ( INVOKESPECIAL , JAVA_OBJECT , CONSTRUCTOR , "()V" , false ) ; mVisitor . visitInsn ( RETURN ) ; mVisitor . visitMaxs ( 1 , 1 ) ; mVisitor . visitEnd ( ) ; mVisitor = classWriter . visitMethod ( ACC_PUBLIC + ACC_ABSTRACT , VISIT_ELEMENT_NAME , "(" + elementTypeDesc + ")V" , null , null ) ; mVisitor . visitEnd ( ) ; mVisitor = classWriter . visitMethod ( ACC_PUBLIC + ACC_ABSTRACT , VISIT_ATTRIBUTE_NAME , "(" + JAVA_STRING_DESC + JAVA_STRING_DESC + ")V" , null , null ) ; mVisitor . visitEnd ( ) ; mVisitor = classWriter . visitMethod ( ACC_PUBLIC + ACC_ABSTRACT , VISIT_PARENT_NAME , "(" + elementTypeDesc + ")V" , null , null ) ; mVisitor . visitEnd ( ) ; mVisitor = classWriter . visitMethod ( ACC_PUBLIC + ACC_ABSTRACT , "visitText" , "(" + textTypeDesc + ")V" , "<R:" + JAVA_OBJECT_DESC + ">(L" + textType + "<+" + elementTypeDesc + "TR;>;)V" , null ) ; mVisitor . visitEnd ( ) ; mVisitor = classWriter . visitMethod ( ACC_PUBLIC + ACC_ABSTRACT , "visitComment" , "(" + textTypeDesc + ")V" , "<R:" + JAVA_OBJECT_DESC + ">(L" + textType + "<+" + elementTypeDesc + "TR;>;)V" , null ) ; mVisitor . visitEnd ( ) ; mVisitor = classWriter . visitMethod ( ACC_PUBLIC , "visitOpenDynamic" , "()V" , null , null ) ; mVisitor . visitCode ( ) ; mVisitor . visitInsn ( RETURN ) ; mVisitor . visitMaxs ( 0 , 1 ) ; mVisitor . visitEnd ( ) ; mVisitor = classWriter . visitMethod ( ACC_PUBLIC , "visitCloseDynamic" , "()V" , null , null ) ; mVisitor . visitCode ( ) ; mVisitor . visitInsn ( RETURN ) ; mVisitor . visitMaxs ( 0 , 1 ) ; mVisitor . visitEnd ( ) ; elementNames . forEach ( elementName -> addVisitorParentMethod ( classWriter , elementName , apiName ) ) ; elementNames . forEach ( elementName -> addVisitorElementMethod ( classWriter , elementName , apiName ) ) ; attributes . forEach ( attribute -> addVisitorAttributeMethod ( classWriter , attribute ) ) ; writeClassToFile ( ELEMENT_VISITOR , classWriter , apiName ) ; } | Generates the visitor class for this fluent interface with methods for all elements in the element list . |
18,843 | private static List < XsdAttribute > filterAttributes ( List < XsdAttribute > attributes ) { List < String > attributeNames = attributes . stream ( ) . map ( XsdNamedElements :: getName ) . distinct ( ) . collect ( Collectors . toList ( ) ) ; List < XsdAttribute > filteredAttributes = new ArrayList < > ( ) ; attributeNames . forEach ( attributeName -> { for ( XsdAttribute attribute : attributes ) { if ( attribute . getName ( ) . equals ( attributeName ) ) { filteredAttributes . add ( attribute ) ; break ; } } } ) ; return filteredAttributes ; } | Removes duplicate attribute names . |
18,844 | public InetSocketAddress getNextDirectoryServer ( ) { index = index + 1 ; if ( index == servers . size ( ) ) { index = 0 ; } InetSocketAddress unresolved = servers . get ( index ) ; return new InetSocketAddress ( unresolved . getHostName ( ) , unresolved . getPort ( ) ) ; } | Get the next directory server . |
18,845 | private void parseServers ( List < String > servers ) { if ( servers != null && servers . size ( ) > 0 ) { this . servers = new ArrayList < InetSocketAddress > ( ) ; for ( String server : servers ) { String [ ] ss = server . split ( ":" ) ; if ( ss . length == 2 ) { String host = ss [ 0 ] ; int port = 0 ; try { port = Integer . valueOf ( ss [ 1 ] ) ; } catch ( NumberFormatException e ) { } if ( validateServer ( host , port ) ) { this . servers . add ( InetSocketAddress . createUnresolved ( host , port ) ) ; } } } } } | Parser the server list . |
18,846 | private boolean validateServer ( String host , int port ) { if ( host == null || host . isEmpty ( ) ) { return false ; } if ( port <= 0 || port > 65535 ) { return false ; } return true ; } | Validate the host and port . |
18,847 | public void recycle ( ) { size = 0 ; position = 0 ; fill ( buffer , 0 , buffer . length , ( byte ) 0 ) ; synchronized ( pool ) { if ( pool . size ( ) == kMaxPoolSize ) { pool . poll ( ) ; } pool . offer ( this ) ; } } | Put a Parcel object back into the pool . |
18,848 | public static ParserConfiguration [ ] filterExisting ( final List < ? extends ParserConfiguration > parsers ) { List < ParserConfiguration > existing = Lists . newArrayList ( ) ; for ( ParserConfiguration parser : parsers ) { if ( ParserRegistry . exists ( parser . getParserName ( ) ) ) { existing . add ( parser ) ; } } return existing . toArray ( new ParserConfiguration [ existing . size ( ) ] ) ; } | Removes non - existing parsers from the specified collection of parsers . |
18,849 | private void analyseAdditionalStepImplementations ( final Class < ? > loadedClass , final Syntax syntax , final Class < ? > [ ] additionalStepImplementationClasses ) { for ( final Class < ? > stepImplClass : additionalStepImplementationClasses ) { analyseClass ( stepImplClass , syntax ) ; } } | Analyses all deferred step implementation classes of the loading class |
18,850 | private NodeList getNodeList ( final String xmlString , final String tagName ) throws ParserConfigurationException , SAXException , IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; dbf . setValidating ( false ) ; dbf . setFeature ( "http://xml.org/sax/features/namespaces" , false ) ; dbf . setFeature ( "http://xml.org/sax/features/validation" , false ) ; dbf . setFeature ( "http://apache.org/xml/features/nonvalidating/load-dtd-grammar" , false ) ; dbf . setFeature ( "http://apache.org/xml/features/nonvalidating/load-external-dtd" , false ) ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; InputSource is = new InputSource ( ) ; is . setCharacterStream ( new StringReader ( xmlString ) ) ; Document doc = db . parse ( is ) ; LOG . info ( "Getting tagName: " + tagName ) ; NodeList nodes = doc . getElementsByTagName ( tagName ) ; return nodes ; } | Gets the nodes list for a given tag name . |
18,851 | public static ApiKey [ ] loadApiKeys ( File file ) throws FileNotFoundException { ArrayList < ApiKey > keys = new ArrayList < > ( ) ; Scanner scanner = null ; try { scanner = new Scanner ( new BufferedInputStream ( new FileInputStream ( file ) ) ) ; while ( scanner . hasNextLine ( ) ) { String line = scanner . nextLine ( ) ; if ( "" . equals ( line . trim ( ) ) ) { continue ; } else if ( line . startsWith ( "#" ) ) { continue ; } String key = line . trim ( ) ; String keyDetails = scanner . nextLine ( ) . trim ( ) ; RateRule [ ] rules = null ; if ( DEVELOPMENT . equals ( keyDetails ) ) { rules = RateRule . getDevelopmentRates ( ) ; } else if ( PRODUCTION . equals ( keyDetails ) ) { rules = RateRule . getProductionRates ( ) ; } else { rules = parseRules ( keyDetails , scanner ) ; } keys . add ( new ApiKey ( key , rules ) ) ; } } finally { if ( scanner != null ) { scanner . close ( ) ; } } return keys . toArray ( new ApiKey [ keys . size ( ) ] ) ; } | Read API keys in the given file . This method exists as a convenience for developers to load keys without command line or checking in API keys to source control |
18,852 | public static boolean hasProperty ( Object obj , String name ) { if ( obj == null || name == null ) return false ; String [ ] names = name . split ( "\\." ) ; if ( names == null || names . length == 0 ) return false ; return performHasProperty ( obj , names , 0 ) ; } | Checks recursively if object or its subobjects has a property with specified name . |
18,853 | public static Object getProperty ( Object obj , String name ) { if ( obj == null || name == null ) return null ; String [ ] names = name . split ( "\\." ) ; if ( names == null || names . length == 0 ) return null ; return performGetProperty ( obj , names , 0 ) ; } | Recursively gets value of object or its subobjects property specified by its name . |
18,854 | public static List < String > getPropertyNames ( Object obj ) { List < String > propertyNames = new ArrayList < String > ( ) ; if ( obj == null ) { return propertyNames ; } else { List < Object > cycleDetect = new ArrayList < Object > ( ) ; performGetPropertyNames ( obj , null , propertyNames , cycleDetect ) ; return propertyNames ; } } | Recursively gets names of all properties implemented in specified object and its subobjects . |
18,855 | public static Map < String , Object > getProperties ( Object obj ) { Map < String , Object > properties = new HashMap < String , Object > ( ) ; if ( obj == null ) { return properties ; } else { List < Object > cycleDetect = new ArrayList < Object > ( ) ; performGetProperties ( obj , null , properties , cycleDetect ) ; return properties ; } } | Get values of all properties in specified object and its subobjects and returns them as a map . |
18,856 | public byte [ ] transform ( ClassLoader loader , String className , Class < ? > redefinedClass , ProtectionDomain protectionDomain , byte [ ] bytecode ) { if ( blacklistManager . isIgnored ( className ) ) { DebugUtils . info ( "agent" , "ignoring " + className ) ; return null ; } try { this . loader = loader ; ContractAnalyzer contracts = analyze ( className ) ; if ( contracts == null ) { if ( className . endsWith ( JavaUtils . HELPER_CLASS_SUFFIX ) ) { DebugUtils . info ( "agent" , "adding source info to " + className ) ; return instrumentWithDebug ( bytecode ) ; } else { return null ; } } else { DebugUtils . info ( "agent" , "adding contracts to " + className ) ; return instrumentWithContracts ( bytecode , contracts ) ; } } catch ( Throwable e ) { DebugUtils . err ( "agent" , "while instrumenting " + className , e ) ; throw new RuntimeException ( e ) ; } } | Instruments the specified class if necessary . |
18,857 | @ Requires ( { "bytecode != null" , "contractBytecode != null" } ) @ Ensures ( "result != null" ) public byte [ ] transformWithContracts ( byte [ ] bytecode , byte [ ] contractBytecode ) throws IllegalClassFormatException { try { ContractAnalyzer contracts = extractContracts ( new ClassReader ( contractBytecode ) ) ; return instrumentWithContracts ( bytecode , contracts ) ; } catch ( Throwable t ) { IllegalClassFormatException e = new IllegalClassFormatException ( ) ; e . initCause ( t ) ; throw e ; } } | Instruments the specified class with contracts . |
18,858 | @ Requires ( "bytecode != null" ) @ Ensures ( "result != null" ) public byte [ ] transformWithDebug ( byte [ ] bytecode ) throws IllegalClassFormatException { try { return instrumentWithDebug ( bytecode ) ; } catch ( Throwable t ) { IllegalClassFormatException e = new IllegalClassFormatException ( ) ; e . initCause ( t ) ; throw e ; } } | Instruments the specified class with debug information . |
18,859 | @ Requires ( "ClassName.isBinaryName(className)" ) protected ContractAnalyzer analyze ( String className ) throws IOException { if ( className . endsWith ( JavaUtils . HELPER_CLASS_SUFFIX ) ) { return null ; } String helperFileName = className + JavaUtils . HELPER_CLASS_SUFFIX + Kind . CLASS . extension ; if ( JavaUtils . resourceExists ( loader , helperFileName ) ) { return null ; } InputStream contractStream = JavaUtils . getContractClassInputStream ( loader , className ) ; if ( contractStream == null ) { return null ; } return extractContracts ( new ClassReader ( contractStream ) ) ; } | Extracts contract methods for the specified class if necessary . |
18,860 | @ Requires ( "reader != null" ) protected ContractAnalyzer extractContracts ( ClassReader reader ) { ContractAnalyzer contractAnalyzer = new ContractAnalyzer ( ) ; reader . accept ( contractAnalyzer , ClassReader . EXPAND_FRAMES ) ; return contractAnalyzer ; } | Processes the specified reader and returns extracted contracts . |
18,861 | @ Requires ( "bytecode != null" ) @ Ensures ( "result != null" ) private byte [ ] instrumentWithDebug ( byte [ ] bytecode ) { ClassReader reader = new ClassReader ( bytecode ) ; ClassWriter writer = new NonLoadingClassWriter ( reader , 0 ) ; reader . accept ( new HelperClassAdapter ( writer ) , ClassReader . EXPAND_FRAMES ) ; return writer . toByteArray ( ) ; } | Instruments the passed class file so that it contains debug information extraction from annotations . |
18,862 | private void calculateLR0KernelItemSets ( ) { for ( int stateId = 0 ; stateId < lr0ItemSetCollection . getStateNumber ( ) ; stateId ++ ) { LR0ItemSet lr0ItemSet = lr0ItemSetCollection . getItemSet ( stateId ) ; Set < LR1Item > lr1Items = new LinkedHashSet < LR1Item > ( ) ; for ( LR0Item lr0Item : lr0ItemSet . getKernelItems ( ) ) { LR1Item lr1Item = new LR1Item ( lr0Item . getProduction ( ) , lr0Item . getPosition ( ) , DUMMY_TERMINAL ) ; lr1Items . add ( lr1Item ) ; } itemSetCollection . add ( new LR1ItemSet ( lr1Items ) ) ; } } | This method takes all item sets from LR0StateTransitionGraph and makes them to a LR1ItemSet containing only kernel items . |
18,863 | public static synchronized byte [ ] addressHash ( byte [ ] pubkeyBytes ) { try { byte [ ] sha256 = MessageDigest . getInstance ( SHA256 ) . digest ( pubkeyBytes ) ; byte [ ] out = new byte [ 20 ] ; ripeMD160 . update ( sha256 , 0 , sha256 . length ) ; ripeMD160 . doFinal ( out , 0 ) ; return out ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( e ) ; } } | Calculate the RipeMd160 value of the SHA - 256 of an array of bytes . This is how a Bitcoin address is derived from public key bytes . |
18,864 | private void initFirstMapForGrammarProductions ( ) { for ( Production production : grammar . getProductions ( ) . getList ( ) ) { if ( ! firstGrammar . containsKey ( production . getName ( ) ) ) { firstGrammar . put ( production . getName ( ) , new LinkedHashSet < Terminal > ( ) ) ; } } } | Initializes the first map for data input . |
18,865 | public Set < Terminal > get ( Construction construction ) { if ( construction . isTerminal ( ) ) { Set < Terminal > result = new LinkedHashSet < Terminal > ( ) ; result . add ( ( Terminal ) construction ) ; return result ; } return firstGrammar . get ( construction . getName ( ) ) ; } | This method returns the first set for a specified construction . |
18,866 | static MemoEntry success ( int deltaPosition , int deltaLine , ParseTreeNode tree ) { return new MemoEntry ( deltaPosition , deltaLine , tree ) ; } | Creates a simple successs memo entry . |
18,867 | public static HadoopObject primitive2Hadoop ( Object object ) { if ( object == null ) { return new HadoopObject ( NULL , NullWritable . get ( ) ) ; } if ( object instanceof Byte ) { return new HadoopObject ( BYTE , new ByteWritable ( ( Byte ) object ) ) ; } else if ( object instanceof Integer ) { return new HadoopObject ( INTEGER , new IntWritable ( ( Integer ) object ) ) ; } else if ( object instanceof Long ) { return new HadoopObject ( LONG , new LongWritable ( ( Long ) object ) ) ; } else if ( object instanceof Double ) { return new HadoopObject ( DOUBLE , new DoubleWritable ( ( Double ) object ) ) ; } else if ( object instanceof Float ) { return new HadoopObject ( FLOAT , new FloatWritable ( ( Float ) object ) ) ; } else if ( object instanceof Boolean ) { return new HadoopObject ( BOOLEAN , new BooleanWritable ( ( Boolean ) object ) ) ; } else if ( object instanceof String ) { return new HadoopObject ( STRING , new Text ( ( String ) object ) ) ; } else if ( object . getClass ( ) . isArray ( ) ) { return arrayPrimitive2Hadoop ( object ) ; } else if ( object instanceof Collection < ? > ) { Collection < ? > collection = ( Collection < ? > ) object ; return arrayPrimitive2Hadoop ( collection . toArray ( ) ) ; } else if ( object instanceof Map < ? , ? > ) { Map < ? , ? > map = ( Map < ? , ? > ) object ; if ( map . size ( ) == 0 ) { throw new ClassCastException ( "object not found" ) ; } MapWritable mapWritable = new MapWritable ( ) ; for ( Entry < ? , ? > entry : map . entrySet ( ) ) { mapWritable . put ( primitive2Hadoop ( entry . getKey ( ) ) . getObject ( ) , primitive2Hadoop ( entry . getValue ( ) ) . getObject ( ) ) ; } return new HadoopObject ( MAP , mapWritable ) ; } throw new ClassCastException ( "cast object not found" ) ; } | Convert the HadoopObject from Java primitive . |
18,868 | public static int typeCompareTo ( Writable one , Writable other ) { PrimitiveObject noOne = hadoop2Primitive ( one ) ; PrimitiveObject noOther = hadoop2Primitive ( other ) ; if ( noOne . getType ( ) != noOther . getType ( ) ) { return - 1 ; } return 0 ; } | Compare the type Writable . |
18,869 | public Lexicon create ( ) throws Exception { Lexicon lexicon = new TrieLexicon ( caseSensitive , probabilistic , tagAttribute ) ; if ( resource != null ) { String base = resource . baseName ( ) . replaceFirst ( "\\.[^\\.]*$" , "" ) ; try ( CSVReader reader = CSV . builder ( ) . removeEmptyCells ( ) . reader ( resource ) ) { reader . forEach ( row -> { if ( row . size ( ) > 0 ) { String lemma = row . get ( 0 ) ; double probability = 1d ; Tag tag = null ; SerializablePredicate < HString > constraint = null ; int nc = 1 ; if ( tagAttribute != null && this . tag != null ) { tag = Cast . as ( this . tag ) ; } else if ( row . size ( ) > nc && tagAttribute != null && ! useResourceNameAsTag ) { tag = tagAttribute . getValueType ( ) . decode ( row . get ( nc ) ) ; if ( tag == null ) { log . warn ( "{0} is an invalid {1}, skipping entry {2}." , row . get ( nc ) , tagAttribute . name ( ) , row ) ; return ; } nc ++ ; } else if ( tagAttribute != null ) { tag = tagAttribute . getValueType ( ) . decode ( base ) ; Preconditions . checkNotNull ( tag , base + " is an invalid tag." ) ; } if ( probabilistic && row . size ( ) > nc && Doubles . tryParse ( row . get ( nc ) ) != null ) { probability = Double . parseDouble ( row . get ( nc ) ) ; nc ++ ; } if ( hasConstraints && row . size ( ) > nc ) { try { constraint = QueryToPredicate . parse ( row . get ( nc ) ) ; } catch ( ParseException e ) { if ( tag == null ) { log . warn ( "Error parsing constraint {0}, skipping entry {1}." , row . get ( nc ) , row ) ; return ; } } } lexicon . add ( new LexiconEntry ( lemma , probability , constraint , tag ) ) ; } } ) ; } } return lexicon ; } | Create lexicon . |
18,870 | protected Future < ActivityData > submit ( ActivityCallable callable ) { try { if ( getEjb ( ) == null ) { logger . info ( "locating AsynchronousBean EJB through service locator" ) ; setEjb ( ServiceLocator . getService ( asynchBeanName , AsynchronousBean . class ) ) ; } else { logger . info ( "asynchronousBean EJB correctly initialized through dependency injection" ) ; } return getEjb ( ) . submit ( callable ) ; } catch ( Exception e ) { logger . error ( "error in the AsynchronousBean service locator lookup" , e ) ; } return null ; } | Assigns the given activity to a worker thread in the JavaEE application server returning the task s Future object . |
18,871 | private static Runnable rejectionPropagatingRunnable ( final AbstractFuture < ? > outputFuture , final Runnable delegateTask , final Executor delegateExecutor ) { return new Runnable ( ) { public void run ( ) { final AtomicBoolean thrownFromDelegate = new AtomicBoolean ( true ) ; try { delegateExecutor . execute ( new Runnable ( ) { public void run ( ) { thrownFromDelegate . set ( false ) ; delegateTask . run ( ) ; } } ) ; } catch ( RejectedExecutionException e ) { if ( thrownFromDelegate . get ( ) ) { outputFuture . setException ( e ) ; } } } } ; } | Returns a Runnable that will invoke the delegate Runnable on the delegate executor but if the task is rejected it will propagate that rejection to the output future . |
18,872 | private static < I , O > AsyncFunction < I , O > asAsyncFunction ( final Function < ? super I , ? extends O > function ) { return new AsyncFunction < I , O > ( ) { public ListenableFuture < O > apply ( I input ) { O output = function . apply ( input ) ; return immediateFuture ( output ) ; } } ; } | Wraps the given function as an AsyncFunction . |
18,873 | public static < T > InterfaceDescriptor < T > findInterfaceDescriptor ( final Class < T > cls ) { if ( ! cls . isInterface ( ) ) { throw new IllegalArgumentException ( "Interface required, got " + cls ) ; } Field field ; try { field = cls . getField ( "DESCRIPTOR" ) ; } catch ( NoSuchFieldException e ) { throw new IllegalArgumentException ( "No DESCRIPTOR field in " + cls ) ; } if ( ! InterfaceDescriptor . class . isAssignableFrom ( field . getType ( ) ) ) { throw new IllegalArgumentException ( "Not an InterfaceDescriptor field, " + field ) ; } try { @ SuppressWarnings ( "unchecked" ) InterfaceDescriptor < T > descriptor = ( InterfaceDescriptor < T > ) field . get ( null ) ; return descriptor ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } } | Returns an interface descriptor or throws an IllegalArgumentException . |
18,874 | public static Version min ( Version ... versions ) { if ( versions . length == 0 ) { throw new IllegalArgumentException ( "At least one version needs to be provided for minimum calculation." ) ; } Version minimum = versions [ 0 ] ; for ( int index = 1 ; index < versions . length ; ++ index ) { Version version = versions [ index ] ; if ( minimum . compareTo ( version ) > 0 ) { minimum = version ; } } return minimum ; } | This class returns the minimum version of the provided versions within the array . |
18,875 | public static Version max ( Version ... versions ) { if ( versions . length == 0 ) { throw new IllegalArgumentException ( "At least one version needs to be provided for maximum calculation." ) ; } Version maximum = versions [ 0 ] ; for ( int index = 1 ; index < versions . length ; ++ index ) { Version version = versions [ index ] ; if ( maximum . compareTo ( version ) < 0 ) { maximum = version ; } } return maximum ; } | This class returns the maximum version of the provided versions within the array . |
18,876 | protected < T > T getFieldValue ( Object object , Field field , Class < T > clazz ) throws VisitorException { boolean reprotect = false ; if ( object == null ) { return null ; } try { if ( ! field . isAccessible ( ) ) { field . setAccessible ( true ) ; reprotect = true ; } Object value = field . get ( object ) ; if ( value != null ) { logger . trace ( "field '{}' has value '{}'" , field . getName ( ) , value ) ; return clazz . cast ( value ) ; } } catch ( IllegalArgumentException e ) { logger . error ( "trying to access field '{}' on invalid object of class '{}'" , field . getName ( ) , object . getClass ( ) . getSimpleName ( ) ) ; throw new VisitorException ( "Trying to access field on invalid object" , e ) ; } catch ( IllegalAccessException e ) { logger . error ( "illegal access to class '{}'" , object . getClass ( ) . getSimpleName ( ) ) ; throw new VisitorException ( "Illegal access to class" , e ) ; } finally { if ( reprotect ) { field . setAccessible ( false ) ; } } return null ; } | Attempts to retrieve the object stored in this node s object field ; the result will be cast to the appropriate class as per the user s input . |
18,877 | protected void cleanEntityForSave ( final RESTBaseElementV1 < ? > entity ) throws InvocationTargetException , IllegalAccessException { if ( entity == null ) return ; for ( final Method method : entity . getClass ( ) . getMethods ( ) ) { if ( ! method . getName ( ) . startsWith ( "get" ) || method . getReturnType ( ) . equals ( Void . TYPE ) ) continue ; if ( isCollectionClass ( method . getReturnType ( ) ) ) { cleanCollectionForSave ( ( RESTBaseEntityCollectionV1 < ? , ? , ? > ) method . invoke ( entity ) , true ) ; } else if ( isEntityClass ( method . getReturnType ( ) ) ) { cleanEntityForSave ( ( RESTBaseElementWithConfiguredParametersV1 ) method . invoke ( entity ) ) ; } } } | Cleans the entity and it s collections to remove any data that doesn t need to be sent to the server . |
18,878 | private boolean isCollectionClass ( Class < ? > clazz ) { if ( clazz == RESTBaseEntityUpdateCollectionV1 . class || clazz == RESTBaseEntityCollectionV1 . class ) { return true ; } else if ( clazz . getSuperclass ( ) != null ) { return isCollectionClass ( clazz . getSuperclass ( ) ) ; } else { return false ; } } | Checks if a class is or extends the REST Base Collection class . |
18,879 | private boolean isEntityClass ( Class < ? > clazz ) { if ( clazz == RESTBaseAuditedEntityV1 . class ) { return true ; } else if ( clazz . getSuperclass ( ) != null ) { return isEntityClass ( clazz . getSuperclass ( ) ) ; } else { return false ; } } | Checks if a class is or extends the REST Base Entity class . |
18,880 | protected void cleanCollectionForSave ( final RESTBaseEntityCollectionV1 < ? , ? , ? > collection , boolean cleanTopLevel ) throws InvocationTargetException , IllegalAccessException { if ( collection == null ) return ; if ( cleanTopLevel ) { collection . removeInvalidChangeItemRequests ( ) ; } for ( final RESTBaseEntityV1 < ? > item : collection . returnItems ( ) ) { cleanEntityForSave ( item ) ; } } | Cleans a collection and it s entities to remove any items in the collection that don t need to be sent to the server . |
18,881 | protected List < ExpandDataTrunk > getExpansionBranches ( final Collection < String > expansionNames ) { if ( expansionNames != null ) { final List < ExpandDataTrunk > expandDataTrunks = new ArrayList < ExpandDataTrunk > ( ) ; for ( final String subExpansionName : expansionNames ) { expandDataTrunks . add ( new ExpandDataTrunk ( new ExpandDataDetails ( subExpansionName ) ) ) ; } return expandDataTrunks ; } return null ; } | Get a list of expansion branches created from a list of names . |
18,882 | protected ExpandDataTrunk getExpansion ( final String expansionName , final Map < String , Collection < String > > subExpansionNames ) { final ExpandDataTrunk expandData = new ExpandDataTrunk ( new ExpandDataDetails ( expansionName ) ) ; expandData . setBranches ( getExpansionBranches ( subExpansionNames ) ) ; return expandData ; } | Create an expansion with sub expansions . |
18,883 | public void add ( final RESTBaseEntityCollectionV1 < ? , ? , ? > value , final boolean isRevisions ) { if ( value != null && value . getItems ( ) != null ) { for ( final RESTBaseEntityCollectionItemV1 < ? , ? , ? > item : value . getItems ( ) ) { if ( item . getItem ( ) != null ) { add ( item . getItem ( ) , isRevisions ) ; } } } } | Add a collection of entities to the cache . |
18,884 | public void add ( final RESTBaseEntityV1 < ? > value , final Number revision ) { add ( value , value . getId ( ) , revision ) ; } | Add a Entity to the cache where the id should be extracted from the entity . |
18,885 | protected String buildKey ( final Class < ? > clazz , final String id , final Number revision ) { if ( revision != null ) { return clazz . getSimpleName ( ) + "-" + id + "-" + revision ; } else { return clazz . getSimpleName ( ) + "-" + id ; } } | Build the unique key to be used for caching entities . |
18,886 | public static boolean closeClientSocket ( final Socket clientSocket ) { boolean closed = true ; try { close ( clientSocket ) ; } catch ( final IOException e ) { LOGGER . error ( "IOException occured by trying to close the client socket." , e ) ; closed = false ; } finally { try { close ( clientSocket ) ; } catch ( final IOException e ) { LOGGER . error ( "IOException occured by trying to close the client socket." , e ) ; closed = false ; } } return closed ; } | Closes the given client socket . |
18,887 | public static boolean closeServerSocket ( ServerSocket serverSocket ) { boolean closed = true ; try { if ( serverSocket != null && ! serverSocket . isClosed ( ) ) { serverSocket . close ( ) ; serverSocket = null ; } } catch ( final IOException e ) { LOGGER . error ( "IOException occured by trying to close the server socket." , e ) ; closed = false ; } finally { try { if ( serverSocket != null && ! serverSocket . isClosed ( ) ) { serverSocket . close ( ) ; } } catch ( final IOException e ) { LOGGER . error ( "IOException occured by trying to close the server socket." , e ) ; closed = false ; } } return closed ; } | Closes the given ServerSocket . |
18,888 | public static Object readObject ( final int port ) throws IOException , ClassNotFoundException { ServerSocket serverSocket = null ; Socket clientSocket = null ; Object objectToReturn = null ; try { serverSocket = new ServerSocket ( port ) ; clientSocket = serverSocket . accept ( ) ; objectToReturn = readObject ( clientSocket ) ; } catch ( final IOException e ) { throw e ; } catch ( final ClassNotFoundException e ) { throw e ; } finally { closeServerSocket ( serverSocket ) ; } return objectToReturn ; } | Reads an object from the given port . |
18,889 | public static Object readObject ( final Socket clientSocket ) throws IOException , ClassNotFoundException { ObjectInputStream in = null ; Object objectToReturn = null ; try { in = new ObjectInputStream ( new BufferedInputStream ( clientSocket . getInputStream ( ) ) ) ; while ( true ) { objectToReturn = in . readObject ( ) ; if ( objectToReturn != null ) { break ; } } in . close ( ) ; clientSocket . close ( ) ; } catch ( final IOException e ) { LOGGER . error ( "IOException occured by trying to read the object." , e ) ; throw e ; } catch ( final ClassNotFoundException e ) { LOGGER . error ( "ClassNotFoundException occured by trying to read the object from the socket." , e ) ; throw e ; } finally { try { if ( in != null ) { in . close ( ) ; } close ( clientSocket ) ; } catch ( final IOException e ) { LOGGER . error ( "IOException occured by trying to close the socket." , e ) ; throw e ; } } return objectToReturn ; } | Reads an object from the given socket object . |
18,890 | public static void writeObject ( final InetAddress inetAddress , final int port , final Object objectToSend ) throws IOException { Socket socketToClient = null ; ObjectOutputStream oos = null ; try { socketToClient = new Socket ( inetAddress , port ) ; oos = new ObjectOutputStream ( new BufferedOutputStream ( socketToClient . getOutputStream ( ) ) ) ; oos . writeObject ( objectToSend ) ; oos . close ( ) ; socketToClient . close ( ) ; } catch ( final IOException e ) { LOGGER . error ( "IOException occured by trying to write the object." , e ) ; throw e ; } finally { try { if ( oos != null ) { oos . close ( ) ; } close ( socketToClient ) ; } catch ( final IOException e ) { LOGGER . error ( "IOException occured by trying to close the socket." , e ) ; throw e ; } } } | Writes the given Object to the given InetAddress who listen to the given port . |
18,891 | public static void writeObject ( final Socket socket , final int port , final Object objectToSend ) throws IOException { writeObject ( socket . getInetAddress ( ) , port , objectToSend ) ; } | Writes the given Object to the given Socket who listen to the given port . |
18,892 | public static void writeObject ( final String serverName , final int port , final Object objectToSend ) throws IOException { final InetAddress inetAddress = InetAddress . getByName ( serverName ) ; writeObject ( inetAddress , port , objectToSend ) ; } | Writes the given Object . |
18,893 | private Object toMBean ( Object object ) throws IllegalArgumentException , NotCompliantMBeanException { JmxBean jmxBean = AnnotationUtils . getAnnotation ( object . getClass ( ) , JmxBean . class ) ; if ( DynamicMBean . class . isAssignableFrom ( object . getClass ( ) ) ) { return object ; } ClassIntrospector classIntrospector = new ClassIntrospectorImpl ( object . getClass ( ) ) ; Class < ? > mBeanInterface = classIntrospector . getInterface ( new ClassFilterBuilder ( ) . name ( object . getClass ( ) . getName ( ) . replace ( "." , "\\." ) + "MBean" ) . build ( ) ) ; if ( mBeanInterface != null ) { return new AnnotatedStandardMBean ( object , mBeanInterface ) ; } Class < ? > mxBeanInterface = classIntrospector . getInterface ( new ClassFilterBuilder ( ) . name ( ".*MXBean" ) . or ( ) . annotated ( MXBean . class ) . build ( ) ) ; if ( mxBeanInterface != null ) { return new AnnotatedStandardMBean ( object , mxBeanInterface , true ) ; } if ( ! jmxBean . managedInterface ( ) . equals ( EmptyInterface . class ) ) { if ( implementsInterface ( object , jmxBean . managedInterface ( ) ) ) { return new AnnotatedStandardMBean ( object , jmxBean . managedInterface ( ) ) ; } else { throw new IllegalArgumentException ( JmxBean . class + " attribute managedInterface is set to " + jmxBean . managedInterface ( ) + " but " + object . getClass ( ) + " does not implement that interface" ) ; } } Class < ? > annotatedInterface = classIntrospector . getInterface ( new ClassFilterBuilder ( ) . annotated ( JmxInterface . class ) . build ( ) ) ; if ( annotatedInterface != null ) { return new AnnotatedStandardMBean ( object , jmxBean . managedInterface ( ) ) ; } return dynamicBeanFactory . getMBeanFor ( object ) ; } | Returns either a AnnotatedStandardMBean or a DynamicMBean implementation . |
18,894 | protected Tree < FeatureStructure > populateTree ( JCas jcas ) { Tree < FeatureStructure > tree = new Tree < FeatureStructure > ( jcas . getDocumentAnnotationFs ( ) ) ; for ( TOP a : JCasUtil . select ( jcas , annotationTypes . get ( 0 ) ) ) { tree . add ( populateTree ( jcas , a , 1 ) ) ; } return tree ; } | This is the entry point for Tree construction . The root is the document node . |
18,895 | @ SuppressWarnings ( "unchecked" ) protected Tree < FeatureStructure > populateTree ( JCas jcas , TOP anno , int typeIndex ) { Tree < FeatureStructure > tree = new Tree < FeatureStructure > ( anno ) ; if ( annotationTypes . size ( ) > typeIndex ) if ( anno instanceof Annotation ) { Class < ? extends Annotation > rAnno = ( Class < ? extends Annotation > ) annotationTypes . get ( typeIndex ) ; for ( TOP a : JCasUtil . selectCovered ( ( Class < ? extends Annotation > ) rAnno , ( Annotation ) anno ) ) { tree . add ( populateTree ( jcas , a , typeIndex + 1 ) ) ; } } else { for ( TOP a : JCasUtil . select ( jcas , annotationTypes . get ( typeIndex ) ) ) { tree . add ( populateTree ( jcas , a , typeIndex + 1 ) ) ; } } return tree ; } | This function recursively constructs a tree containing the feature structures that are covering each other . Longer annotations should be on higher levels of the tree . |
18,896 | @ SuppressWarnings ( "unchecked" ) public T add ( YamlNode value ) { if ( value == this ) { throw new IllegalArgumentException ( "recursive structures are currently not supported" ) ; } value ( ) . add ( YamlNodes . nullToNode ( value ) ) ; return ( T ) this ; } | Adds the specified value to this sequence . |
18,897 | @ SuppressWarnings ( "unchecked" ) public T addAll ( YamlNode ... values ) { for ( YamlNode value : values ) { add ( value ) ; } return ( T ) this ; } | Adds all specified values to this sequence . |
18,898 | public static void saveModel ( final File file , final DajlabModel dajlabModel ) { Platform . runLater ( new Runnable ( ) { public void run ( ) { Gson fxGson = FxGson . fullBuilder ( ) . setPrettyPrinting ( ) . create ( ) ; JsonElement el = fxGson . toJsonTree ( dajlabModel ) ; try { JsonWriter w = new JsonWriter ( new FileWriter ( file ) ) ; w . setIndent ( "\t" ) ; fxGson . toJson ( el , w ) ; w . close ( ) ; } catch ( Exception e ) { logger . error ( "Unable to export model to file [{}]" , file . getName ( ) ) ; ExceptionFactory . throwDaJLabRuntimeException ( DaJLabConstants . ERR_SAVE_MODEL ) ; } } } ) ; } | Save to the file the model . |
18,899 | public static < T extends DajlabModelInterface > DajlabModel loadModel ( final File file ) { Gson fxGson = FxGson . fullBuilder ( ) . create ( ) ; DajlabModel model = new DajlabModel ( ) ; try { JsonParser jsonParser = new JsonParser ( ) ; JsonReader jsonReader = new JsonReader ( new FileReader ( file ) ) ; jsonReader . beginObject ( ) ; if ( jsonReader . hasNext ( ) ) { jsonReader . nextName ( ) ; JsonObject ob = jsonParser . parse ( jsonReader ) . getAsJsonObject ( ) ; Set < Entry < String , JsonElement > > set = ob . entrySet ( ) ; for ( Entry < String , JsonElement > entry : set ) { String className = entry . getKey ( ) ; JsonElement el = entry . getValue ( ) ; try { T obj = ( T ) fxGson . fromJson ( el , Class . forName ( className ) ) ; model . put ( obj ) ; } catch ( ClassNotFoundException e ) { logger . warn ( "Unable to load model for [{}]" , className ) ; } } } } catch ( Exception e ) { logger . debug ( e . getMessage ( ) ) ; logger . error ( "Unable to load model from file [{}]" , file . getName ( ) ) ; ExceptionFactory . throwDaJLabRuntimeException ( DaJLabConstants . ERR_LOAD_MODEL ) ; } return model ; } | Load a model from a file . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.