idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
12,000
public Listener < T > add ( Consumer < T > listener ) { Assert . notNull ( listener , "listener" ) ; ListenerHolder holder = new ListenerHolder ( listener , ThreadContext . currentContext ( ) ) ; listeners . add ( holder ) ; return holder ; }
Adds a listener to the set of listeners .
12,001
public CompletableFuture < Void > accept ( T event ) { List < CompletableFuture < Void > > futures = new ArrayList < > ( listeners . size ( ) ) ; for ( ListenerHolder listener : listeners ) { if ( listener . context != null ) { futures . add ( listener . context . execute ( ( ) -> listener . listener . accept ( event ) ) ) ; } else { listener . listener . accept ( event ) ; } } return CompletableFuture . allOf ( futures . toArray ( new CompletableFuture [ futures . size ( ) ] ) ) ; }
Applies an event to all listeners .
12,002
private ThreadContext getOrCreateContext ( Channel channel ) { ThreadContext context = ThreadContext . currentContext ( ) ; if ( context != null ) { return context ; } return new SingleThreadContext ( Thread . currentThread ( ) , channel . eventLoop ( ) , this . context . serializer ( ) . clone ( ) ) ; }
Returns the current execution context or creates one .
12,003
private void handleResponse ( ByteBuf response , ChannelHandlerContext context ) { NettyConnection connection = getConnection ( context . channel ( ) ) ; if ( connection != null ) { connection . handleResponse ( response ) ; } }
Handles a response .
12,004
private int calculateTypeId ( Class < ? > type ) { if ( type == null ) throw new NullPointerException ( "type cannot be null" ) ; return hasher . hash32 ( type . getName ( ) ) ; }
Returns the type ID for the given class .
12,005
public SerializerRegistry registerDefault ( Class < ? > baseType , Class < ? extends TypeSerializer > serializer ) { return registerDefault ( baseType , new DefaultTypeSerializerFactory ( serializer ) ) ; }
Registers the given class as a default serializer for the given base type .
12,006
public synchronized SerializerRegistry registerDefault ( Class < ? > baseType , TypeSerializerFactory factory ) { defaultFactories . put ( baseType , factory ) ; return this ; }
Registers the given factory as a default serializer factory for the given base type .
12,007
private Class < ? > findBaseType ( Class < ? > type , Map < Class < ? > , TypeSerializerFactory > factories ) { if ( factories . containsKey ( type ) ) return type ; List < Map . Entry < Class < ? > , TypeSerializerFactory > > orderedFactories = new ArrayList < > ( factories . entrySet ( ) ) ; Collections . reverse ( orderedFactories ) ; Optional < Map . Entry < Class < ? > , TypeSerializerFactory > > optional = orderedFactories . stream ( ) . filter ( e -> e . getKey ( ) . isAssignableFrom ( type ) ) . findFirst ( ) ; return optional . isPresent ( ) ? optional . get ( ) . getKey ( ) : null ; }
Finds a serializable base type for the given type in the given factories map .
12,008
synchronized int id ( Class < ? > type ) { Integer id = ids . get ( type ) ; if ( id != null ) return id ; Class < ? > baseType = findBaseType ( type , abstractFactories ) ; if ( baseType != null ) { id = ids . get ( baseType ) ; if ( id != null ) { return id ; } } return 0 ; }
Looks up the serializable type ID for the given type .
12,009
@ SuppressWarnings ( "unchecked" ) private T readReference ( Class < T > type , BufferInput < ? > buffer , Serializer serializer ) { ReferencePool < ? > pool = pools . get ( type ) ; if ( pool == null ) { Constructor < ? > constructor = constructorMap . get ( type ) ; if ( constructor == null ) { try { constructor = type . getDeclaredConstructor ( ReferenceManager . class ) ; constructor . setAccessible ( true ) ; constructorMap . put ( type , constructor ) ; } catch ( NoSuchMethodException e ) { throw new SerializationException ( "failed to instantiate reference: must provide a single argument constructor" , e ) ; } } pool = new ReferencePool < > ( createFactory ( constructor ) ) ; pools . put ( type , pool ) ; } T object = ( T ) pool . acquire ( ) ; object . readObject ( buffer , serializer ) ; return object ; }
Reads an object reference .
12,010
private ReferenceFactory < ? > createFactory ( final Constructor < ? > constructor ) { return manager -> { try { return ( ReferenceCounted < ? > ) constructor . newInstance ( manager ) ; } catch ( InstantiationException | IllegalAccessException | InvocationTargetException e ) { throw new SerializationException ( "failed to instantiate reference" , e ) ; } } ; }
Dynamically created a reference factory for a pooled type .
12,011
@ SuppressWarnings ( "unchecked" ) private T readObject ( Class < T > type , BufferInput < ? > buffer , Serializer serializer ) { try { Constructor < ? > constructor = constructorMap . get ( type ) ; if ( constructor == null ) { try { constructor = type . getDeclaredConstructor ( ) ; constructor . setAccessible ( true ) ; constructorMap . put ( type , constructor ) ; } catch ( NoSuchMethodException e ) { throw new SerializationException ( "failed to instantiate reference: must provide a single argument constructor" , e ) ; } } T object = ( T ) constructor . newInstance ( ) ; object . readObject ( buffer , serializer ) ; return object ; } catch ( InstantiationException | IllegalAccessException | InvocationTargetException e ) { throw new SerializationException ( "failed to instantiate object: must provide a no argument constructor" , e ) ; } }
Reads an object .
12,012
private static File [ ] loadXmlFiles ( final File directory ) { return directory . listFiles ( new FileFilter ( ) { public boolean accept ( File file ) { return file . getName ( ) . endsWith ( ".xml" ) ; } } ) ; }
load all XML files listed in the directory specified
12,013
private static void generateJavaFiles ( final StatusUpdateTemplate template , final String workingPath ) throws FileNotFoundException { final String javaPath = WORKING_DIR + template . getName ( ) + ".java" ; final File javaFile = new File ( javaPath ) ; final String [ ] optionsAndSources = { "-classpath" , workingPath , "-proc:none" , "-source" , "1.7" , "-target" , "1.7" , javaPath } ; final PrintWriter writer = new PrintWriter ( javaFile ) ; writer . write ( template . getJavaCode ( ) ) ; writer . flush ( ) ; writer . close ( ) ; final File classFile = new File ( WORKING_DIR + template . getName ( ) + ".class" ) ; classFile . delete ( ) ; final JavaCompiler compiler = ToolProvider . getSystemJavaCompiler ( ) ; compiler . run ( System . in , System . out , System . err , optionsAndSources ) ; javaFile . delete ( ) ; }
generate a java class file for the template specified
12,014
private static void storeStatusUpdateTemplate ( final AbstractGraphDatabase graphDatabase , final StatusUpdateTemplate template , final Node previousTemplateNode ) { final Transaction transaction = graphDatabase . beginTx ( ) ; try { final Node templateNode = StatusUpdateTemplate . createTemplateNode ( graphDatabase , template ) ; if ( previousTemplateNode != null ) { templateNode . createRelationshipTo ( previousTemplateNode , SocialGraphRelationshipType . Templates . PREVIOUS ) ; } NeoUtils . storeStatusUpdateTemplateNode ( graphDatabase , template . getName ( ) , templateNode , previousTemplateNode ) ; transaction . success ( ) ; } finally { transaction . finish ( ) ; } }
store the status update template linking to the latest previous version
12,015
public static void loadStatusUpdateTemplates ( final String rootDir , final Configuration config , final AbstractGraphDatabase graphDatabase ) throws ParserConfigurationException , SAXException , IOException { final String workingPath = rootDir + "classes/" ; final String targetPackage = StatusUpdate . class . getPackage ( ) . getName ( ) + ".templates." ; WORKING_DIR = workingPath + targetPackage . replace ( "." , "/" ) ; final File dirWorking = new File ( WORKING_DIR ) ; if ( ! dirWorking . exists ( ) ) { dirWorking . mkdir ( ) ; } System . out . println ( "WORKING_DIR:" + WORKING_DIR ) ; final ClassLoader classLoader = StatusUpdate . class . getClassLoader ( ) ; final URLClassLoader loader = new URLClassLoader ( new URL [ ] { new File ( workingPath ) . toURI ( ) . toURL ( ) } , classLoader ) ; StatusUpdateTemplate template , previousTemplate ; final File templatesDir = new File ( config . getTemplatesPath ( ) ) ; if ( ! templatesDir . exists ( ) ) { templatesDir . mkdir ( ) ; } File [ ] xmlFiles = loadXmlFiles ( templatesDir ) ; if ( xmlFiles . length == 0 ) { final File plainTemplate = new File ( config . getTemplatesPath ( ) + "Plain.xml" ) ; final PrintWriter writer = new PrintWriter ( plainTemplate ) ; writer . println ( "<class name=\"Plain\" version=\"1.0\">" ) ; writer . println ( "<param name=\"message\" type=\"String\" />" ) ; writer . println ( "</class>" ) ; writer . flush ( ) ; writer . close ( ) ; xmlFiles = loadXmlFiles ( new File ( config . getTemplatesPath ( ) ) ) ; } System . out . println ( "TEMPLATES:" + xmlFiles . length ) ; for ( File xmlFile : xmlFiles ) { template = new StatusUpdateTemplate ( xmlFile ) ; final Node previousTemplateNode = NeoUtils . getStatusUpdateTemplateByIdentifier ( template . getName ( ) ) ; if ( previousTemplateNode != null ) { previousTemplate = new StatusUpdateTemplate ( previousTemplateNode ) ; } else { previousTemplate = null ; } if ( previousTemplate != null ) { if ( ! template . getVersion ( ) . equals ( previousTemplate . getVersion ( ) ) ) { } } storeStatusUpdateTemplate ( graphDatabase , template , previousTemplateNode ) ; generateJavaFiles ( template , workingPath ) ; try { template . setInstantiationClass ( loader . loadClass ( targetPackage + template . getName ( ) ) ) ; STATUS_UPDATE_TYPES . put ( template . getName ( ) , template ) ; } catch ( final ClassNotFoundException e ) { e . printStackTrace ( ) ; } } loader . close ( ) ; }
load the status update allowed
12,016
public static StatusUpdate instantiateStatusUpdate ( final String typeIdentifier , final FormItemList values ) throws StatusUpdateInstantiationFailedException { final StatusUpdateTemplate template = getStatusUpdateTemplate ( typeIdentifier ) ; final Class < ? > templateInstantiationClass = template . getInstantiationClass ( ) ; try { final StatusUpdate statusUpdate = ( StatusUpdate ) templateInstantiationClass . newInstance ( ) ; String value ; try { for ( String fieldName : template . getFields ( ) . keySet ( ) ) { try { value = values . getField ( fieldName ) ; } catch ( final IllegalArgumentException e ) { throw new StatusUpdateInstantiationFailedException ( e . getMessage ( ) ) ; } templateInstantiationClass . getField ( fieldName ) . set ( statusUpdate , value ) ; } for ( String fileName : template . getFiles ( ) . keySet ( ) ) { try { value = values . getFile ( fileName ) . getAbsoluteFilePath ( ) ; } catch ( final IllegalArgumentException e ) { throw new StatusUpdateInstantiationFailedException ( e . getMessage ( ) ) ; } templateInstantiationClass . getField ( fileName ) . set ( statusUpdate , value ) ; } } catch ( final IllegalArgumentException e ) { throw new StatusUpdateInstantiationFailedException ( "The types of the parameters passed do not match the status update template." ) ; } return statusUpdate ; } catch ( final SecurityException e ) { throw new IllegalArgumentException ( "failed to load the status update type specified, SecurityException occurred!" ) ; } catch ( final InstantiationException e ) { throw new IllegalArgumentException ( "failed to load the status update type specified, InstantiationException occurred!" ) ; } catch ( final IllegalAccessException e ) { throw new IllegalArgumentException ( "failed to load the status update type specified, IllegalAccessException occurred!" ) ; } catch ( final NoSuchFieldException e ) { throw new IllegalArgumentException ( "failed to load the status update type specified, NoSuchFieldException occurred!" ) ; } }
instantiate a status update
12,017
public static DeleteUserRequest checkRequest ( final HttpServletRequest request , final DeleteRequest deleteRequest , final DeleteUserResponse deleteUserResponse ) { final Node user = checkUserIdentifier ( request , deleteUserResponse ) ; if ( user != null ) { return new DeleteUserRequest ( deleteRequest . getType ( ) , user ) ; } return null ; }
check a delete user request for validity concerning NSSP
12,018
public void addFriendById ( String userId , String name , FriendGroup friendGroup ) { if ( name == null && getRiotApi ( ) != null ) { try { name = getRiotApi ( ) . getName ( userId ) ; } catch ( final IOException e ) { e . printStackTrace ( ) ; } } try { connection . getRoster ( ) . createEntry ( StringUtils . parseBareAddress ( userId ) , name , new String [ ] { friendGroup == null ? getDefaultFriendGroup ( ) . getName ( ) : friendGroup . getName ( ) } ) ; } catch ( NotLoggedInException | NoResponseException | XMPPErrorException | NotConnectedException e ) { e . printStackTrace ( ) ; } }
Sends an friend request to an other user .
12,019
public boolean addFriendByName ( String name , FriendGroup friendGroup ) { if ( getRiotApi ( ) != null ) { try { final StringBuilder buf = new StringBuilder ( ) ; buf . append ( "sum" ) ; buf . append ( getRiotApi ( ) . getSummonerId ( name ) ) ; buf . append ( "@pvp.net" ) ; addFriendById ( buf . toString ( ) , name , friendGroup ) ; return true ; } catch ( IOException | URISyntaxException e ) { e . printStackTrace ( ) ; return false ; } } return false ; }
Sends an friend request to an other user . An Riot API key is required for this .
12,020
public FriendGroup addFriendGroup ( String name ) { final RosterGroup g = connection . getRoster ( ) . createGroup ( name ) ; if ( g != null ) { return new FriendGroup ( this , connection , g ) ; } return null ; }
Creates a new FriendGroup . If this FriendGroup contains no Friends when you logout it will be erased from the server .
12,021
public void disconnect ( ) { connection . getRoster ( ) . removeRosterListener ( leagueRosterListener ) ; try { connection . disconnect ( ) ; } catch ( final NotConnectedException e ) { e . printStackTrace ( ) ; } stop = true ; }
Disconnects from chatserver and releases all resources .
12,022
public Friend getFriend ( Filter < Friend > filter ) { for ( final RosterEntry e : connection . getRoster ( ) . getEntries ( ) ) { final Friend f = new Friend ( this , connection , e ) ; if ( filter . accept ( f ) ) { return f ; } } return null ; }
Gets a friend based on a given filter .
12,023
public Friend getFriendById ( String xmppAddress ) { final RosterEntry entry = connection . getRoster ( ) . getEntry ( StringUtils . parseBareAddress ( xmppAddress ) ) ; if ( entry != null ) { return new Friend ( this , connection , entry ) ; } return null ; }
Gets a friend based on his XMPPAddress .
12,024
public FriendGroup getFriendGroupByName ( String name ) { final RosterGroup g = connection . getRoster ( ) . getGroup ( name ) ; if ( g != null ) { return new FriendGroup ( this , connection , g ) ; } return addFriendGroup ( name ) ; }
Gets a FriendGroup by name for example Duo Partners . The name is case sensitive! The FriendGroup will be created if it didn t exist yet .
12,025
public List < FriendGroup > getFriendGroups ( ) { final ArrayList < FriendGroup > groups = new ArrayList < > ( ) ; for ( final RosterGroup g : connection . getRoster ( ) . getGroups ( ) ) { groups . add ( new FriendGroup ( this , connection , g ) ) ; } return groups ; }
Get a list of all your FriendGroups .
12,026
public List < Friend > getFriends ( ) { return getFriends ( new Filter < Friend > ( ) { public boolean accept ( Friend e ) { return true ; } } ) ; }
Get all your friends both online and offline .
12,027
public List < Friend > getFriends ( Filter < Friend > filter ) { final ArrayList < Friend > friends = new ArrayList < > ( ) ; for ( final RosterEntry e : connection . getRoster ( ) . getEntries ( ) ) { final Friend f = new Friend ( this , connection , e ) ; if ( filter . accept ( f ) ) { friends . add ( f ) ; } } return friends ; }
Gets a list of your friends based on a given filter .
12,028
public String getName ( boolean forcedUpdate ) { if ( ( name == null || forcedUpdate ) && getRiotApi ( ) != null ) { try { name = getRiotApi ( ) . getName ( connection . getUser ( ) ) ; } catch ( final IOException e ) { e . printStackTrace ( ) ; } } return name ; }
Gets the name of the user that is logged in . An Riot API key has to be provided .
12,029
public List < Friend > getOfflineFriends ( ) { return getFriends ( new Filter < Friend > ( ) { public boolean accept ( Friend friend ) { return ! friend . isOnline ( ) ; } } ) ; }
Get all your friends who are offline .
12,030
public List < Friend > getOnlineFriends ( ) { return getFriends ( new Filter < Friend > ( ) { public boolean accept ( Friend friend ) { return friend . isOnline ( ) ; } } ) ; }
Get all your friends who are online .
12,031
public List < Friend > getPendingFriendRequests ( ) { return getFriends ( new Filter < Friend > ( ) { public boolean accept ( Friend friend ) { return friend . getFriendStatus ( ) == FriendStatus . ADD_REQUEST_PENDING ; } } ) ; }
Gets a list of user that you ve sent friend requests but haven t answered yet .
12,032
public int threads ( ) { int threads = reader . getInteger ( THREADS , DEFAULT_THREADS ) ; if ( threads == - 1 ) { return Runtime . getRuntime ( ) . availableProcessors ( ) ; } return threads ; }
The number of event loop threads .
12,033
public SslProtocol sslProtocol ( ) { String protocol = reader . getString ( SSL_PROTOCOL , DEFAULT_SSL_PROTOCOL ) . replace ( "." , "_" ) ; try { return SslProtocol . valueOf ( protocol ) ; } catch ( IllegalArgumentException e ) { throw new ConfigurationException ( "unknown SSL protocol: " + protocol , e ) ; } }
The SSL Protocol .
12,034
private void listen ( Address address , Consumer < Connection > listener , ThreadContext context ) { channelGroup = new DefaultChannelGroup ( "catalyst-acceptor-channels" , GlobalEventExecutor . INSTANCE ) ; handler = new ServerHandler ( connections , listener , context , transport . properties ( ) ) ; final ServerBootstrap bootstrap = new ServerBootstrap ( ) ; bootstrap . group ( transport . eventLoopGroup ( ) ) . channel ( NioServerSocketChannel . class ) . handler ( new LoggingHandler ( LogLevel . DEBUG ) ) . childHandler ( new ChannelInitializer < SocketChannel > ( ) { public void initChannel ( SocketChannel channel ) throws Exception { ChannelPipeline pipeline = channel . pipeline ( ) ; if ( transport . properties ( ) . sslEnabled ( ) ) { pipeline . addFirst ( new SslHandler ( new NettyTls ( transport . properties ( ) ) . initSslEngine ( false ) ) ) ; } pipeline . addLast ( FIELD_PREPENDER ) ; pipeline . addLast ( new LengthFieldBasedFrameDecoder ( transport . properties ( ) . maxFrameSize ( ) , 0 , 4 , 0 , 4 ) ) ; pipeline . addLast ( handler ) ; } } ) . option ( ChannelOption . SO_BACKLOG , transport . properties ( ) . acceptBacklog ( ) ) . option ( ChannelOption . TCP_NODELAY , transport . properties ( ) . tcpNoDelay ( ) ) . option ( ChannelOption . SO_REUSEADDR , transport . properties ( ) . reuseAddress ( ) ) . childOption ( ChannelOption . ALLOCATOR , ALLOCATOR ) . childOption ( ChannelOption . SO_KEEPALIVE , transport . properties ( ) . tcpKeepAlive ( ) ) ; if ( transport . properties ( ) . sendBufferSize ( ) != - 1 ) { bootstrap . childOption ( ChannelOption . SO_SNDBUF , transport . properties ( ) . sendBufferSize ( ) ) ; } if ( transport . properties ( ) . receiveBufferSize ( ) != - 1 ) { bootstrap . childOption ( ChannelOption . SO_RCVBUF , transport . properties ( ) . receiveBufferSize ( ) ) ; } LOGGER . info ( "Binding to {}" , address ) ; ChannelFuture bindFuture = bootstrap . bind ( address . socketAddress ( ) ) ; bindFuture . addListener ( ( ChannelFutureListener ) channelFuture -> { if ( channelFuture . isSuccess ( ) ) { listening = true ; context . executor ( ) . execute ( ( ) -> { LOGGER . info ( "Listening at {}" , bindFuture . channel ( ) . localAddress ( ) ) ; listenFuture . complete ( null ) ; } ) ; } else { context . execute ( ( ) -> listenFuture . completeExceptionally ( channelFuture . cause ( ) ) ) ; } } ) ; channelGroup . add ( bindFuture . channel ( ) ) ; }
Starts listening for the given member .
12,035
static Runnable logFailure ( final Runnable runnable , Logger logger ) { return ( ) -> { try { runnable . run ( ) ; } catch ( Throwable t ) { if ( ! ( t instanceof RejectedExecutionException ) ) { logger . error ( "An uncaught exception occurred" , t ) ; } throw t ; } } ; }
Returns a wrapped runnable that logs and rethrows uncaught exceptions .
12,036
public boolean delete ( ) { try { con . getRoster ( ) . removeEntry ( get ( ) ) ; return true ; } catch ( XMPPException | NotLoggedInException | NoResponseException | NotConnectedException e ) { e . printStackTrace ( ) ; } return false ; }
Deletes this friend .
12,037
public FriendStatus getFriendStatus ( ) { for ( final FriendStatus status : FriendStatus . values ( ) ) { if ( status . status == get ( ) . getStatus ( ) ) { return status ; } } return null ; }
Gets the relation between you and this friend .
12,038
public FriendGroup getGroup ( ) { final Collection < RosterGroup > groups = get ( ) . getGroups ( ) ; if ( groups . size ( ) > 0 ) { return new FriendGroup ( api , con , get ( ) . getGroups ( ) . iterator ( ) . next ( ) ) ; } return null ; }
Gets the FriendGroup that contains this friend .
12,039
public String getName ( boolean forcedUpdate ) { String name = get ( ) . getName ( ) ; if ( ( name == null || forcedUpdate ) && api . getRiotApi ( ) != null ) { try { name = api . getRiotApi ( ) . getName ( getUserId ( ) ) ; setName ( name ) ; } catch ( final IOException e ) { e . printStackTrace ( ) ; } } return name ; }
Gets the name of this friend . If the name was null then we try to fetch the name with your Riot API Key if provided . Enable forcedUpdate to always fetch the latest name of this Friend even when the name is not null .
12,040
public void sendMessage ( String message ) { try { getChat ( ) . sendMessage ( message ) ; } catch ( XMPPException | NotConnectedException e ) { e . printStackTrace ( ) ; } }
Sends a message to this friend
12,041
@ SuppressWarnings ( "unchecked" ) protected void addStatusMessage ( final String statusMessage , final String solution ) { this . json . put ( ProtocolConstants . SOLUTION , solution ) ; this . json . put ( ProtocolConstants . STATUS_MESSAGE , statusMessage ) ; }
add a status message to the response
12,042
public void error ( final int errorCode , final String message ) { try { this . response . sendError ( errorCode , message ) ; } catch ( final IOException e ) { e . printStackTrace ( ) ; } }
abort the response with an error
12,043
protected AbstractBuffer reset ( long offset , long capacity , long maxCapacity ) { this . offset = offset ; this . capacity = 0 ; this . initialCapacity = capacity ; this . maxCapacity = maxCapacity ; capacity ( initialCapacity ) ; references . set ( 0 ) ; rewind ( ) ; return this ; }
Resets the buffer s internal offset and capacity .
12,044
protected void checkOffset ( long offset ) { if ( offset ( offset ) < this . offset ) { throw new IndexOutOfBoundsException ( ) ; } else if ( limit == - 1 ) { if ( offset > maxCapacity ) throw new IndexOutOfBoundsException ( ) ; } else { if ( offset > limit ) throw new IndexOutOfBoundsException ( ) ; } }
Checks that the offset is within the bounds of the buffer .
12,045
protected long checkSlice ( long offset , long length ) { checkOffset ( offset ) ; if ( limit == - 1 ) { if ( offset + length > capacity ) { if ( capacity < maxCapacity ) { capacity ( calculateCapacity ( offset + length ) ) ; } else { throw new BufferUnderflowException ( ) ; } } } else { if ( offset + length > limit ) throw new BufferUnderflowException ( ) ; } return offset ( offset ) ; }
Checks bounds for a slice .
12,046
public static ReadRequest checkRequest ( final HttpServletRequest request , final ReadResponse readResponse ) { final Node user = checkUserIdentifier ( request , readResponse ) ; if ( user != null ) { final Node poster = checkPosterIdentifier ( request , readResponse ) ; if ( poster != null ) { final int numItems = checkNumItems ( request , readResponse ) ; if ( numItems != 0 ) { final Boolean ownUpdates = checkOwnUpdates ( request , readResponse ) ; if ( ownUpdates != null ) { return new ReadRequest ( user , poster , numItems , ownUpdates ) ; } } } } return null ; }
check a read request for validity concerning NSSP
12,047
private static Node checkPosterIdentifier ( final HttpServletRequest request , final ReadResponse response ) { final String posterId = request . getParameter ( ProtocolConstants . Parameters . Read . POSTER_IDENTIFIER ) ; if ( posterId != null ) { final Node user = NeoUtils . getUserByIdentifier ( posterId ) ; if ( user != null ) { return user ; } response . posterIdentifierInvalid ( posterId ) ; } else { response . posterIdentifierMissing ( ) ; } return null ; }
check if the request contains a valid poster identifier
12,048
private static int checkNumItems ( final HttpServletRequest request , final ReadResponse response ) { final String sNumItems = request . getParameter ( ProtocolConstants . Parameters . Read . NUM_ITEMS ) ; if ( sNumItems != null ) { int numItems ; try { numItems = Integer . valueOf ( sNumItems ) ; if ( numItems > 0 ) { return numItems ; } response . numItemsInvalid ( "Please provide a number greater than zero." ) ; } catch ( final NumberFormatException e ) { response . numItemsInvalid ( "\"" + sNumItems + "\" is not a number. Please provide a number such as \"15\" to retrieve that number of items." ) ; } } else { response . numItemsMissing ( ) ; } return 0 ; }
check if the request contains a valid number of items to retrieve
12,049
private static Boolean checkOwnUpdates ( final HttpServletRequest request , final ReadResponse response ) { final String sOwnUpdates = request . getParameter ( ProtocolConstants . Parameters . Read . OWN_UPDATES ) ; if ( sOwnUpdates != null ) { try { final int iOwnUpdates = Integer . valueOf ( sOwnUpdates ) ; return ( iOwnUpdates != 0 ) ; } catch ( final NumberFormatException e ) { response . ownUpdatesInvalid ( sOwnUpdates ) ; } } else { response . ownUpdatesMissing ( ) ; } return null ; }
check if the request contains a valid retrieval flag
12,050
public SSLEngine initSslEngine ( boolean client ) throws Exception { KeyStore keyStore = loadKeystore ( properties . sslKeyStorePath ( ) , properties . sslKeyStorePassword ( ) ) ; KeyManagerFactory keyManagerFactory = KeyManagerFactory . getInstance ( KeyManagerFactory . getDefaultAlgorithm ( ) ) ; keyManagerFactory . init ( keyStore , keyStoreKeyPass ( properties ) ) ; KeyStore trustStore ; if ( properties . sslTrustStorePath ( ) != null ) { LOGGER . debug ( "Using separate trust store" ) ; trustStore = loadKeystore ( properties . sslTrustStorePath ( ) , properties . sslTrustStorePassword ( ) ) ; } else { trustStore = keyStore ; LOGGER . debug ( "Using key store as trust store" ) ; } TrustManagerFactory trustManagerFactory = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; trustManagerFactory . init ( trustStore ) ; KeyManager [ ] keyManagers = keyManagerFactory . getKeyManagers ( ) ; TrustManager [ ] trustManagers = trustManagerFactory . getTrustManagers ( ) ; SSLContext sslContext = SSLContext . getInstance ( "TLS" ) ; sslContext . init ( keyManagers , trustManagers , null ) ; SSLEngine sslEngine = sslContext . createSSLEngine ( ) ; sslEngine . setUseClientMode ( client ) ; sslEngine . setWantClientAuth ( true ) ; sslEngine . setEnabledProtocols ( sslEngine . getSupportedProtocols ( ) ) ; sslEngine . setEnabledCipherSuites ( sslEngine . getSupportedCipherSuites ( ) ) ; sslEngine . setEnableSessionCreation ( true ) ; return sslEngine ; }
Initializes an SSL engine .
12,051
private void initialize ( ) throws IllegalArgumentException , IllegalAccessException { Field [ ] fields = this . getClass ( ) . getFields ( ) ; for ( Field f : fields ) { if ( this . getProperty ( f . getName ( ) ) == null ) { System . err . print ( "Property '" + f . getName ( ) + "' not defined in config file" ) ; } if ( f . getType ( ) . equals ( String . class ) ) { f . set ( this , this . getProperty ( f . getName ( ) ) ) ; } else if ( f . getType ( ) . equals ( long . class ) ) { f . setLong ( this , Long . valueOf ( this . getProperty ( f . getName ( ) ) ) ) ; } else if ( f . getType ( ) . equals ( int . class ) ) { f . setInt ( this , Integer . valueOf ( this . getProperty ( f . getName ( ) ) ) ) ; } else if ( f . getType ( ) . equals ( boolean . class ) ) { f . setBoolean ( this , Boolean . valueOf ( this . getProperty ( f . getName ( ) ) ) ) ; } else if ( f . getType ( ) . equals ( String [ ] . class ) ) { f . set ( this , this . getProperty ( f . getName ( ) ) . split ( ";" ) ) ; } else if ( f . getType ( ) . equals ( int [ ] . class ) ) { String [ ] tmp = this . getProperty ( f . getName ( ) ) . split ( ";" ) ; int [ ] ints = new int [ tmp . length ] ; for ( int i = 0 ; i < tmp . length ; i ++ ) { ints [ i ] = Integer . parseInt ( tmp [ i ] ) ; } f . set ( this , ints ) ; } else if ( f . getType ( ) . equals ( long [ ] . class ) ) { String [ ] tmp = this . getProperty ( f . getName ( ) ) . split ( ";" ) ; long [ ] longs = new long [ tmp . length ] ; for ( int i = 0 ; i < tmp . length ; i ++ ) { longs [ i ] = Long . parseLong ( tmp [ i ] ) ; } f . set ( this , longs ) ; } } }
Fills all fields with the data defined in the config file .
12,052
public int weightOf ( String suggestion ) { Node n = getNode ( suggestion ) ; return ( n != null ) ? n . weight : - 1 ; }
Returns the weight of the specified suggestion in this tree or - 1 if the tree does not contain the suggestion .
12,053
public void put ( String suggestion , int weight , String key ) { if ( suggestion . isEmpty ( ) || weight < 0 ) throw new IllegalArgumentException ( ) ; if ( root == null ) { root = new Node ( suggestion , weight , key , 0 , null ) ; size ++ ; return ; } int i = 0 ; Node n = root ; while ( true ) { if ( suggestion . charAt ( i ) < n . firstChar ) { if ( n . left != null ) n = n . left ; else { n . left = new Node ( suggestion , weight , key , i , n ) ; insertIntoLists ( n . left ) ; size ++ ; return ; } } else if ( suggestion . charAt ( i ) > n . firstChar ) { if ( n . right != null ) n = n . right ; else { n . right = new Node ( suggestion , weight , key , i , n ) ; insertIntoLists ( n . right ) ; size ++ ; return ; } } else { for ( i ++ ; i < n . charEnd ; i ++ ) { if ( i == suggestion . length ( ) || suggestion . charAt ( i ) != n . suggestion . charAt ( i ) ) { n = splitNode ( n , i ) ; break ; } } if ( i < suggestion . length ( ) ) { if ( n . mid != null ) n = n . mid ; else { n . mid = new Node ( suggestion , weight , key , i , n ) ; insertIntoLists ( n . mid ) ; size ++ ; return ; } } else if ( n . weight == - 1 ) { n . suggestion = suggestion ; n . weight = weight ; insertIntoLists ( n ) ; size ++ ; return ; } else if ( weight > n . weight ) { n . weight = weight ; updateListsIncreasedWeight ( n ) ; return ; } else if ( weight < n . weight ) { n . weight = weight ; updateListsDecreasedWeight ( n ) ; return ; } else return ; } } }
Inserts the specified suggestion with the specified weight into this tree or assigns the specified new weight to the suggestion if it is already present .
12,054
public void remove ( String suggestion ) { Node n = getNode ( suggestion ) ; if ( n == null ) return ; n . weight = - 1 ; size -- ; Node m = n ; if ( n . mid == null ) { Node replacement = removeNode ( n ) ; if ( replacement != null ) replacement . parent = n . parent ; if ( n == root ) root = replacement ; else if ( n == n . parent . mid ) n . parent . mid = replacement ; else { if ( n == n . parent . left ) n . parent . left = replacement ; else n . parent . right = replacement ; while ( n != root && n != n . parent . mid ) n = n . parent ; } n = n . parent ; if ( n == null ) return ; } if ( n . weight == - 1 && n . mid . left == null && n . mid . right == null ) { n = mergeWithChild ( n ) ; while ( n != root && n != n . parent . mid ) n = n . parent ; n = n . parent ; if ( n == null ) return ; } removeFromLists ( m , n ) ; }
Removes the specified suggestion from this tree if present .
12,055
private void updateEgoNetwork ( final Node user ) { Node followedReplica , followingUser , lastPosterReplica ; Node prevReplica , nextReplica ; for ( Relationship relationship : user . getRelationships ( SocialGraphRelationshipType . REPLICA , Direction . INCOMING ) ) { followedReplica = relationship . getStartNode ( ) ; followingUser = NeoUtils . getPrevSingleNode ( followedReplica , SocialGraphRelationshipType . FOLLOW ) ; prevReplica = NeoUtils . getPrevSingleNode ( followedReplica , SocialGraphRelationshipType . GRAPHITY ) ; if ( ! prevReplica . equals ( followingUser ) ) { followedReplica . getSingleRelationship ( SocialGraphRelationshipType . GRAPHITY , Direction . INCOMING ) . delete ( ) ; nextReplica = NeoUtils . getNextSingleNode ( followedReplica , SocialGraphRelationshipType . GRAPHITY ) ; if ( nextReplica != null ) { followedReplica . getSingleRelationship ( SocialGraphRelationshipType . GRAPHITY , Direction . OUTGOING ) . delete ( ) ; prevReplica . createRelationshipTo ( nextReplica , SocialGraphRelationshipType . GRAPHITY ) ; } } lastPosterReplica = NeoUtils . getNextSingleNode ( followingUser , SocialGraphRelationshipType . GRAPHITY ) ; if ( ! lastPosterReplica . equals ( followedReplica ) ) { followingUser . getSingleRelationship ( SocialGraphRelationshipType . GRAPHITY , Direction . OUTGOING ) . delete ( ) ; followingUser . createRelationshipTo ( followedReplica , SocialGraphRelationshipType . GRAPHITY ) ; followedReplica . createRelationshipTo ( lastPosterReplica , SocialGraphRelationshipType . GRAPHITY ) ; } } }
update the ego network of a user
12,056
private void removeFromReplicaLayer ( final Node followedReplica ) { final Node prev = NeoUtils . getPrevSingleNode ( followedReplica , SocialGraphRelationshipType . GRAPHITY ) ; final Node next = NeoUtils . getNextSingleNode ( followedReplica , SocialGraphRelationshipType . GRAPHITY ) ; prev . getSingleRelationship ( SocialGraphRelationshipType . GRAPHITY , Direction . OUTGOING ) . delete ( ) ; if ( next != null ) { next . getSingleRelationship ( SocialGraphRelationshipType . GRAPHITY , Direction . INCOMING ) . delete ( ) ; prev . createRelationshipTo ( next , SocialGraphRelationshipType . GRAPHITY ) ; } followedReplica . getSingleRelationship ( SocialGraphRelationshipType . FOLLOW , Direction . INCOMING ) . delete ( ) ; followedReplica . getSingleRelationship ( SocialGraphRelationshipType . REPLICA , Direction . OUTGOING ) . delete ( ) ; followedReplica . delete ( ) ; }
remove a followed user from the replica layer
12,057
private void updateReplicaLayerStatusUpdateDeletion ( final Node user , final Node statusUpdate ) { final Node lastUpdate = NeoUtils . getNextSingleNode ( user , SocialGraphRelationshipType . UPDATE ) ; if ( statusUpdate . equals ( lastUpdate ) ) { long newTimestamp = 0 ; final Node nextStatusUpdate = NeoUtils . getNextSingleNode ( statusUpdate , SocialGraphRelationshipType . UPDATE ) ; if ( nextStatusUpdate != null ) { newTimestamp = ( long ) nextStatusUpdate . getProperty ( Properties . StatusUpdate . TIMESTAMP ) ; } Node replicaNode , following ; for ( Relationship replicated : user . getRelationships ( SocialGraphRelationshipType . REPLICA , Direction . INCOMING ) ) { replicaNode = replicated . getEndNode ( ) ; following = NeoUtils . getPrevSingleNode ( replicaNode , SocialGraphRelationshipType . FOLLOW ) ; long crrTimestamp ; Node prevReplica = following ; Node nextReplica = null ; while ( true ) { nextReplica = NeoUtils . getNextSingleNode ( prevReplica , SocialGraphRelationshipType . GRAPHITY ) ; if ( nextReplica != null ) { if ( nextReplica . equals ( replicaNode ) ) { prevReplica = nextReplica ; continue ; } crrTimestamp = getLastUpdateByReplica ( nextReplica ) ; if ( crrTimestamp > newTimestamp ) { prevReplica = nextReplica ; continue ; } } break ; } if ( nextReplica != null ) { final Node oldPrevReplica = NeoUtils . getNextSingleNode ( replicaNode , SocialGraphRelationshipType . GRAPHITY ) ; final Node oldNextReplica = NeoUtils . getNextSingleNode ( replicaNode , SocialGraphRelationshipType . GRAPHITY ) ; replicaNode . getSingleRelationship ( SocialGraphRelationshipType . GRAPHITY , Direction . INCOMING ) . delete ( ) ; if ( oldNextReplica != null ) { oldNextReplica . getSingleRelationship ( SocialGraphRelationshipType . GRAPHITY , Direction . INCOMING ) . delete ( ) ; oldPrevReplica . createRelationshipTo ( oldNextReplica , SocialGraphRelationshipType . GRAPHITY ) ; } if ( nextReplica != null ) { replicaNode . createRelationshipTo ( nextReplica , SocialGraphRelationshipType . GRAPHITY ) ; prevReplica . getSingleRelationship ( SocialGraphRelationshipType . GRAPHITY , Direction . OUTGOING ) ; } prevReplica . createRelationshipTo ( replicaNode , SocialGraphRelationshipType . GRAPHITY ) ; } } } }
update the replica layer for status update deletion
12,058
private static long getLastUpdateByReplica ( final Node userReplica ) { final Node user = NeoUtils . getNextSingleNode ( userReplica , SocialGraphRelationshipType . REPLICA ) ; if ( user . hasProperty ( Properties . User . LAST_UPDATE ) ) { return ( long ) user . getProperty ( Properties . User . LAST_UPDATE ) ; } return 0 ; }
get a user s last recent status update s time stamp
12,059
public static CreateFollowRequest checkRequest ( final FormItemList formItemList , final CreateRequest createRequest , final CreateFollowResponse createFollowResponse ) { final Node user = checkUserIdentifier ( formItemList , createFollowResponse ) ; if ( user != null ) { final Node followed = checkFollowedIdentifier ( formItemList , createFollowResponse ) ; if ( followed != null ) { return new CreateFollowRequest ( createRequest . getType ( ) , user , followed ) ; } } return null ; }
check a create follow edge request for validity concerning NSSP
12,060
public boolean removeFooterView ( View v ) { if ( mFooterViewInfos . size ( ) > 0 ) { boolean result = false ; ListAdapter adapter = getAdapter ( ) ; if ( adapter != null && ( ( HeaderFooterViewGridAdapter ) adapter ) . removeFooter ( v ) ) { result = true ; } removeFixedViewInfo ( v , mFooterViewInfos ) ; return result ; } return false ; }
Removes a previously - added footer view .
12,061
public Messages reserve ( int numberOfMessages , int timeout , int wait ) throws IOException { if ( numberOfMessages < 1 || numberOfMessages > 100 ) { throw new IllegalArgumentException ( "numberOfMessages has to be within 1..100" ) ; } MessagesReservationModel payload = new MessagesReservationModel ( numberOfMessages , timeout , wait ) ; String url = "queues/" + name + "/reservations" ; IronReader reader = client . post ( url , gson . toJson ( payload ) ) ; Messages messages = gson . fromJson ( reader . reader , Messages . class ) ; reader . close ( ) ; return messages ; }
Retrieves Messages from the queue and reserves it . If there are no items on the queue an EmptyQueueException is thrown .
12,062
public Message peek ( ) throws IOException { Messages msgs = peek ( 1 ) ; Message msg ; try { msg = msgs . getMessage ( 0 ) ; } catch ( IndexOutOfBoundsException e ) { throw new EmptyQueueException ( ) ; } return msg ; }
Peeking at a queue returns the next messages on the queue but it does not reserve them . If there are no items on the queue an EmptyQueueException is thrown .
12,063
public Messages peek ( int numberOfMessages ) throws IOException { if ( numberOfMessages < 1 || numberOfMessages > 100 ) { throw new IllegalArgumentException ( "numberOfMessages has to be within 1..100" ) ; } IronReader reader = client . get ( "queues/" + name + "/messages?n=" + numberOfMessages ) ; try { return gson . fromJson ( reader . reader , Messages . class ) ; } finally { reader . close ( ) ; } }
Peeking at a queue returns the next messages on the queue but it does not reserve them .
12,064
public MessageOptions touchMessage ( String id , String reservationId , int timeout ) throws IOException { return touchMessage ( id , reservationId , ( long ) timeout ) ; }
Touching a reserved message extends its timeout to the specified duration .
12,065
public String push ( String msg , long delay ) throws IOException { Message message = new Message ( ) ; message . setBody ( msg ) ; message . setDelay ( delay ) ; Messages msgs = new Messages ( message ) ; IronReader reader = client . post ( "queues/" + name + "/messages" , msgs ) ; Ids ids = gson . fromJson ( reader . reader , Ids . class ) ; reader . close ( ) ; return ids . getId ( 0 ) ; }
Pushes a message onto the queue .
12,066
public Ids pushMessages ( String [ ] msg , long delay ) throws IOException { ArrayList < Message > messages = new ArrayList < Message > ( ) ; for ( String messageName : msg ) { Message message = new Message ( ) ; message . setBody ( messageName ) ; message . setDelay ( delay ) ; messages . add ( message ) ; } MessagesArrayList msgs = new MessagesArrayList ( messages ) ; IronReader reader = client . post ( "queues/" + name + "/messages" , msgs ) ; Ids ids = gson . fromJson ( reader . reader , Ids . class ) ; reader . close ( ) ; return ids ; }
Pushes a messages onto the queue .
12,067
public QueueModel getInfoAboutQueue ( ) throws IOException { IronReader reader = client . get ( "queues/" + name ) ; QueueContainer queueContainer = gson . fromJson ( reader . reader , QueueContainer . class ) ; reader . close ( ) ; return queueContainer . getQueue ( ) ; }
Retrieves Info about queue . If there is no queue an EmptyQueueException is thrown .
12,068
public Message getMessageById ( String id ) throws IOException { String url = "queues/" + name + "/messages/" + id ; IronReader reader = client . get ( url ) ; MessageContainer container = gson . fromJson ( reader . reader , MessageContainer . class ) ; reader . close ( ) ; return container . getMessage ( ) ; }
Retrieves Message from the queue by message id . If there are no items on the queue an EmptyQueueException is thrown .
12,069
public void addSubscribers ( Subscribers subscribers ) throws IOException { String payload = gson . toJson ( subscribers ) ; IronReader reader = client . post ( "queues/" + name + "/subscribers" , payload ) ; reader . close ( ) ; }
Add subscribers to Queue . If there is no queue an EmptyQueueException is thrown .
12,070
public void replaceSubscribers ( Subscribers subscribers ) throws IOException { String payload = gson . toJson ( subscribers ) ; IronReader reader = client . put ( "queues/" + name + "/subscribers" , payload ) ; reader . close ( ) ; }
Sets list of subscribers to a queue . Older subscribers will be removed . If there is no queue an EmptyQueueException is thrown .
12,071
public void removeSubscribers ( Subscribers subscribers ) throws IOException { String url = "queues/" + name + "/subscribers" ; String jsonMessages = gson . toJson ( subscribers ) ; IronReader reader = client . delete ( url , jsonMessages ) ; reader . close ( ) ; }
Remove subscribers from Queue . If there is no queue an EmptyQueueException is thrown .
12,072
public SubscribersInfo getPushStatusForMessage ( String messageId ) throws IOException { String url = "queues/" + name + "/messages/" + messageId + "/subscribers" ; IronReader reader = client . get ( url ) ; SubscribersInfo subscribersInfo = gson . fromJson ( reader . reader , SubscribersInfo . class ) ; reader . close ( ) ; return subscribersInfo ; }
Get push info of message by message id . If there is no message an EmptyQueueException is thrown .
12,073
public void deletePushMessageForSubscriber ( String messageId , String reservationId , String subscriberName ) throws IOException { deleteMessage ( messageId , reservationId , subscriberName ) ; }
Delete push message for subscriber by subscriber ID and message ID . If there is no message or subscriber an EmptyQueueException is thrown .
12,074
public QueueModel updateAlerts ( ArrayList < Alert > alerts ) throws IOException { QueueModel payload = new QueueModel ( alerts ) ; return this . update ( payload ) ; }
Replace current queue alerts with a given list of alerts . If there is no queue an EmptyQueueException is thrown .
12,075
public void deleteAlertsFromQueue ( ArrayList < Alert > alert_ids ) throws IOException { String url = "queues/" + name + "/alerts" ; Alerts alert = new Alerts ( alert_ids ) ; String jsonMessages = gson . toJson ( alert ) ; IronReader reader = client . delete ( url , jsonMessages ) ; reader . close ( ) ; }
Delete alerts from a queue . If there is no queue an EmptyQueueException is thrown .
12,076
public void deleteAlertFromQueueById ( String alert_id ) throws IOException { String url = "queues/" + name + "/alerts/" + alert_id ; IronReader reader = client . delete ( url ) ; reader . close ( ) ; }
Delete alert from a queue by alert id . If there is no queue an EmptyQueueException is thrown .
12,077
public boolean isExpired ( int seconds ) { long diff = localIssuedAt . getTime ( ) - issuedAt . getTime ( ) ; long localExpiresAtTime = expiresAt . getTime ( ) + diff ; return ( new Date ( ) . getTime ( ) - seconds * 1000 ) >= localExpiresAtTime ; }
Indicated if token will expire after N seconds .
12,078
private void scheduleAcknowledgment ( final String topic ) { if ( ! acknowledgeScheduled . has ( topic ) ) { acknowledgeScheduled . set ( topic , true ) ; Platform . scheduler ( ) . scheduleDelay ( acknowledgeDelayMillis , new Handler < Void > ( ) { public void handle ( Void event ) { if ( acknowledgeScheduled . has ( topic ) ) { acknowledgeScheduled . remove ( topic ) ; double knownHeadSequence = knownHeadSequences . getNumber ( topic ) ; double currentSequence = currentSequences . getNumber ( topic ) ; if ( knownHeadSequence > currentSequence && ( ! acknowledgeNumbers . has ( topic ) || knownHeadSequence > acknowledgeNumbers . getNumber ( topic ) ) ) { acknowledgeNumbers . set ( topic , knownHeadSequence ) ; log . log ( Level . CONFIG , "Catching up to " + knownHeadSequence ) ; catchup ( topic , currentSequence ) ; } else { log . log ( Level . FINE , "No need to catchup" ) ; } } } } ) ; } }
Acknowledgment Number is the next sequence number that the receiver is expecting
12,079
public FutureResultImpl < T > setFailure ( Throwable throwable ) { this . throwable = throwable ; failed = true ; checkCallHandler ( ) ; return this ; }
Set the failure . Any handler will be called if there is one
12,080
public FutureResultImpl < T > setHandler ( Handler < AsyncResult < T > > handler ) { this . handler = handler ; checkCallHandler ( ) ; return this ; }
Set a handler for the result . It will get called when it s complete
12,081
public FutureResultImpl < T > setResult ( T result ) { this . result = result ; succeeded = true ; checkCallHandler ( ) ; return this ; }
Set the result . Any handler will be called if there is one
12,082
public BackOffParameters next ( ) { int ret = Math . min ( nextBackOffTime , maxBackOff ) ; nextBackOffTime += backOffTime ; if ( nextBackOffTime <= 0 ) { nextBackOffTime = Integer . MAX_VALUE ; } backOffTime = ret ; int randomizeTime = ( int ) ( backOffTime * ( 1.0 + ( Math . random ( ) * randomizationFactor ) ) ) ; int minAllowedTime = ( int ) Math . round ( randomizeTime - backOffTime * randomizationFactor ) ; return new BackOffParameters ( randomizeTime , minAllowedTime ) ; }
Gets the next back off time . Until maxBackOff is reached .
12,083
public Object getItem ( ELContext context , int i ) { if ( originalListObject == null ) { originalListObject = orig . getValue ( context ) ; if ( originalListObject instanceof Collection ) { type = TypesEnum . ACollection ; } else if ( originalListObject instanceof Iterator ) { type = TypesEnum . AnIterator ; } else if ( originalListObject instanceof Enumeration ) { type = TypesEnum . AnEnumeration ; } else if ( originalListObject instanceof Map ) { type = TypesEnum . AMap ; } else if ( originalListObject instanceof String ) { type = TypesEnum . AString ; } else { throw new RuntimeException ( "IteratedExpression.getItem: Object not of correct type." ) ; } currentListObject = returnNewIterator ( originalListObject , type ) ; } Object currentObject = null ; if ( i < currentIndex ) { currentListObject = returnNewIterator ( originalListObject , type ) ; currentIndex = 0 ; } for ( ; currentIndex <= i ; currentIndex ++ ) { if ( currentListObject . hasNext ( ) ) { currentObject = currentListObject . next ( ) ; } else { throw new RuntimeException ( "IteratedExpression.getItem: Index out of Bounds" ) ; } } return currentObject ; }
Iterates the original expression and returns the value at the index .
12,084
public int doEndTag ( ) throws JspException { Object xmlText = this . xml ; if ( xmlText == null ) { if ( bodyContent != null && bodyContent . getString ( ) != null ) { xmlText = bodyContent . getString ( ) . trim ( ) ; } else { xmlText = "" ; } } if ( xmlText instanceof String ) { xmlText = new StringReader ( ( String ) xmlText ) ; } if ( ! ( xmlText instanceof Reader ) ) { throw new JspTagException ( Resources . getMessage ( "PARSE_INVALID_SOURCE" ) ) ; } InputSource source = XmlUtil . newInputSource ( ( ( Reader ) xmlText ) , systemId ) ; Document d ; if ( filter != null ) { d = parseInputSourceWithFilter ( source , filter ) ; } else { d = parseInputSource ( source ) ; } if ( var != null ) { pageContext . setAttribute ( var , d , scope ) ; } if ( varDom != null ) { pageContext . setAttribute ( varDom , d , scopeDom ) ; } return EVAL_PAGE ; }
parse source or body storing result in var
12,085
private Document parseInputSourceWithFilter ( InputSource s , XMLFilter f ) throws JspException { try { XMLReader xr = XmlUtil . newXMLReader ( entityResolver ) ; f . setParent ( xr ) ; TransformerHandler th = XmlUtil . newTransformerHandler ( ) ; Document o = XmlUtil . newEmptyDocument ( ) ; th . setResult ( new DOMResult ( o ) ) ; f . setContentHandler ( th ) ; f . parse ( s ) ; return o ; } catch ( IOException e ) { throw new JspException ( e ) ; } catch ( SAXException e ) { throw new JspException ( e ) ; } catch ( TransformerConfigurationException e ) { throw new JspException ( e ) ; } catch ( ParserConfigurationException e ) { throw new JspException ( e ) ; } }
Parses the given InputSource after applying the given XMLFilter .
12,086
private Document parseInputSource ( InputSource s ) throws JspException { try { DocumentBuilder db = XmlUtil . newDocumentBuilder ( ) ; db . setEntityResolver ( entityResolver ) ; return db . parse ( s ) ; } catch ( SAXException e ) { throw new JspException ( e ) ; } catch ( IOException e ) { throw new JspException ( e ) ; } }
Parses the given InputSource into a Document .
12,087
public void setScope ( String scope ) { if ( scope . equalsIgnoreCase ( "page" ) ) { this . scope = PageContext . PAGE_SCOPE ; } else if ( scope . equalsIgnoreCase ( "request" ) ) { this . scope = PageContext . REQUEST_SCOPE ; } else if ( scope . equalsIgnoreCase ( "session" ) ) { this . scope = PageContext . SESSION_SCOPE ; } else if ( scope . equalsIgnoreCase ( "application" ) ) { this . scope = PageContext . APPLICATION_SCOPE ; } }
Sets the scope attribute .
12,088
public static String getContentTypeAttribute ( String input , String name ) { int begin ; int end ; int index = input . toUpperCase ( ) . indexOf ( name . toUpperCase ( ) ) ; if ( index == - 1 ) { return null ; } index = index + name . length ( ) ; index = input . indexOf ( '=' , index ) ; if ( index == - 1 ) { return null ; } index += 1 ; input = input . substring ( index ) . trim ( ) ; if ( input . charAt ( 0 ) == '"' ) { begin = 1 ; end = input . indexOf ( '"' , begin ) ; if ( end == - 1 ) { return null ; } } else { begin = 0 ; end = input . indexOf ( ';' ) ; if ( end == - 1 ) { end = input . indexOf ( ' ' ) ; } if ( end == - 1 ) { end = input . length ( ) ; } } return input . substring ( begin , end ) . trim ( ) ; }
Get the value associated with a content - type attribute . Syntax defined in RFC 2045 section 5 . 1 .
12,089
public Map getAsMap ( ) { if ( mMap != null ) { return mMap ; } else { Map m = convertToMap ( ) ; if ( ! isMutable ( ) ) { mMap = m ; } return m ; } }
Converts the MapSource to a Map . If the map is not mutable this is cached
12,090
Map convertToMap ( ) { Map ret = new HashMap ( ) ; for ( Enumeration e = enumerateKeys ( ) ; e . hasMoreElements ( ) ; ) { Object key = e . nextElement ( ) ; Object value = getValue ( key ) ; ret . put ( key , value ) ; } return ret ; }
Converts to a Map
12,091
public int doEndTag ( ) throws JspException { Tag t = findAncestorWithClass ( this , ParamParent . class ) ; if ( t == null ) { throw new JspTagException ( Resources . getMessage ( "PARAM_OUTSIDE_PARENT" ) ) ; } if ( name == null || name . equals ( "" ) ) { return EVAL_PAGE ; } ParamParent parent = ( ParamParent ) t ; String value = this . value ; if ( value == null ) { if ( bodyContent == null || bodyContent . getString ( ) == null ) { value = "" ; } else { value = bodyContent . getString ( ) . trim ( ) ; } } if ( encode ) { String enc = pageContext . getResponse ( ) . getCharacterEncoding ( ) ; try { parent . addParameter ( URLEncoder . encode ( name , enc ) , URLEncoder . encode ( value , enc ) ) ; } catch ( UnsupportedEncodingException e ) { throw new JspTagException ( e ) ; } } else { parent . addParameter ( name , value ) ; } return EVAL_PAGE ; }
simply send our name and value to our appropriate ancestor
12,092
public static String [ ] union ( String [ ] arr1 , String [ ] arr2 ) { Set < String > set = new HashSet < String > ( ) ; for ( String str : arr1 ) { set . add ( str ) ; } for ( String str : arr2 ) { set . add ( str ) ; } String [ ] result = { } ; return set . toArray ( result ) ; }
Arr1 union Arr2
12,093
public static String [ ] intersect ( String [ ] arr1 , String [ ] arr2 ) { Map < String , Boolean > map = new HashMap < String , Boolean > ( ) ; LinkedList < String > list = new LinkedList < String > ( ) ; for ( String str : arr1 ) { if ( ! map . containsKey ( str ) ) { map . put ( str , Boolean . FALSE ) ; } } for ( String str : arr2 ) { if ( map . containsKey ( str ) ) { map . put ( str , Boolean . TRUE ) ; } } for ( Entry < String , Boolean > e : map . entrySet ( ) ) { if ( e . getValue ( ) . equals ( Boolean . TRUE ) ) { list . add ( e . getKey ( ) ) ; } } String [ ] result = { } ; return list . toArray ( result ) ; }
Arr1 intersect Arr2
12,094
public static String [ ] minus ( String [ ] arr1 , String [ ] arr2 ) { LinkedList < String > list = new LinkedList < String > ( ) ; LinkedList < String > history = new LinkedList < String > ( ) ; String [ ] longerArr = arr1 ; String [ ] shorterArr = arr2 ; if ( arr1 . length > arr2 . length ) { longerArr = arr2 ; shorterArr = arr1 ; } for ( String str : longerArr ) { if ( ! list . contains ( str ) ) { list . add ( str ) ; } } for ( String str : shorterArr ) { if ( list . contains ( str ) ) { history . add ( str ) ; list . remove ( str ) ; } else { if ( ! history . contains ( str ) ) { list . add ( str ) ; } } } String [ ] result = { } ; return list . toArray ( result ) ; }
Arr1 minus Arr2
12,095
public int doEndTag ( ) throws JspException { try { conn . commit ( ) ; } catch ( SQLException e ) { throw new JspTagException ( Resources . getMessage ( "TRANSACTION_COMMIT_ERROR" , e . toString ( ) ) , e ) ; } return EVAL_PAGE ; }
Commits the transaction .
12,096
public void doCatch ( Throwable t ) throws Throwable { if ( conn != null ) { try { conn . rollback ( ) ; } catch ( SQLException e ) { } } throw t ; }
Rollbacks the transaction and rethrows the Throwable .
12,097
public void setIsolation ( String iso ) throws JspTagException { if ( TRANSACTION_READ_COMMITTED . equals ( iso ) ) { isolation = Connection . TRANSACTION_READ_COMMITTED ; } else if ( TRANSACTION_READ_UNCOMMITTED . equals ( iso ) ) { isolation = Connection . TRANSACTION_READ_UNCOMMITTED ; } else if ( TRANSACTION_REPEATABLE_READ . equals ( iso ) ) { isolation = Connection . TRANSACTION_REPEATABLE_READ ; } else if ( TRANSACTION_SERIALIZABLE . equals ( iso ) ) { isolation = Connection . TRANSACTION_SERIALIZABLE ; } else { throw new JspTagException ( Resources . getMessage ( "TRANSACTION_INVALID_ISOLATION" ) ) ; } }
Setter method for the transaction isolation level .
12,098
public static BeanInfoManager getBeanInfoManager ( Class pClass ) { BeanInfoManager ret = ( BeanInfoManager ) mBeanInfoManagerByClass . get ( pClass ) ; if ( ret == null ) { ret = createBeanInfoManager ( pClass ) ; } return ret ; }
Returns the BeanInfoManager for the specified class
12,099
public static BeanInfoProperty getBeanInfoProperty ( Class pClass , String pPropertyName , Logger pLogger ) throws ELException { return getBeanInfoManager ( pClass ) . getProperty ( pPropertyName , pLogger ) ; }
Returns the BeanInfoProperty for the specified property in the given class or null if not found .