idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
142,900 | private void key ( final byte key [ ] ) { int i ; final int koffp [ ] = { 0 } ; final int lr [ ] = { 0 , 0 } ; final int plen = P . length , slen = S . length ; for ( i = 0 ; i < plen ; i ++ ) { P [ i ] = P [ i ] ^ streamtoword ( key , koffp ) ; } for ( i = 0 ; i < plen ; i += 2 ) { encipher ( lr , 0 ) ; P [ i ] = lr [ 0 ] ; P [ i + 1 ] = lr [ 1 ] ; } for ( i = 0 ; i < slen ; i += 2 ) { encipher ( lr , 0 ) ; S [ i ] = lr [ 0 ] ; S [ i + 1 ] = lr [ 1 ] ; } } | Key the Blowfish cipher | 194 | 5 |
142,901 | public final static int createLocalId ( ) { Storage storage = Storage . getLocalStorageIfSupported ( ) ; if ( storage == null ) return 0 ; int increment = 0 ; String incrementString = storage . getItem ( LOCAL_CURRENT_ID_INCREMENT ) ; try { increment = Integer . parseInt ( incrementString ) ; } catch ( Exception e ) { } increment += 1 ; storage . setItem ( LOCAL_CURRENT_ID_INCREMENT , increment + "" ) ; return - increment ; } | Create a negative ID . | 111 | 5 |
142,902 | public < T > void RegisterClazz ( Clazz < T > clazz ) { _ensureMap ( ) ; if ( clazzz . containsKey ( clazz . getReflectedClass ( ) ) ) return ; clazzz . put ( clazz . getReflectedClass ( ) , clazz ) ; } | Register a runtime type information provider | 68 | 6 |
142,903 | public void init ( String baseUrl , XRPCBatchRequestSender callback ) { this . url = baseUrl + "&locale=" + LocaleInfo . getCurrentLocale ( ) . getLocaleName ( ) ; this . callback = callback ; } | initialize with url and other needed information | 57 | 8 |
142,904 | private void checkCallService ( RequestCallInfo info ) { String service = info . request . service ; String interfaceChecksum = info . request . interfaceChecksum ; String key = getServiceKey ( info ) ; if ( usedServices . containsKey ( key ) ) return ; ServiceInfo serviceInfo = new ServiceInfo ( service , interfaceChecksum ) ; serviceInfo . id = usedServices . size ( ) ; usedServices . put ( key , serviceInfo ) ; } | necessary to be sure that call s service is referenced | 100 | 10 |
142,905 | public boolean send ( ) { assert sentRequests == null ; sentRequests = new ArrayList < RequestCallInfo > ( ) ; // add prepended requests, addPrependedRequests ( sentRequests ) ; // add requests to send while ( ! requestsToSend . isEmpty ( ) ) sentRequests . add ( requestsToSend . remove ( 0 ) ) ; // add appended requests addAppendedRequests ( sentRequests ) ; // prepare payload JSONArray payload = createPayload ( ) ; RequestBuilder builderPost = buildMultipart ( "payload" , payload . toString ( ) ) ; nbSentBytes += builderPost . getRequestData ( ) . length ( ) ; try { sentRequest = builderPost . send ( ) ; } catch ( RequestException e ) { callback . error ( RPCErrorCodes . ERROR_REQUEST_SEND , e , this ) ; return false ; } callback . sent ( this ) ; return true ; } | when response arrives it will be given back to each request callback | 207 | 12 |
142,906 | private RequestBuilder buildMultipart ( String name , String value ) { String boundary = "AJAX------" + Math . random ( ) + "" + new Date ( ) . getTime ( ) ; RequestBuilder builderPost = new RequestBuilder ( RequestBuilder . POST , url ) ; builderPost . setHeader ( "Content-Type" , "multipart/form-data; charset=utf-8; boundary=" + boundary ) ; builderPost . setCallback ( requestCallback ) ; String CRLF = "\r\n" ; String data = "--" + boundary + CRLF ; data += "--" + boundary + CRLF ; data += "Content-Disposition: form-data; " ; data += "name=\"" + name + "\"" + CRLF + CRLF ; data += value + CRLF ; data += "--" + boundary + "--" + CRLF ; builderPost . setRequestData ( data ) ; return builderPost ; } | prepare a multipart form http request | 214 | 8 |
142,907 | public FormCreator field ( Widget widget ) { return field ( widget , totalWidth - currentlyUsedWidth - ( fFirstItem ? 0 : spacing ) ) ; } | automatically fills the line to the end | 35 | 9 |
142,908 | public void copy ( ConnectionContext source ) { this . connection = source . connection ; this . session = source . session ; this . destination = source . destination ; } | Sets this context object with the same data found in the source context . | 34 | 15 |
142,909 | public static Set < Annotation > getAllAnnotations ( Method m ) { Set < Annotation > annotationSet = new LinkedHashSet < Annotation > ( ) ; Annotation [ ] annotations = m . getAnnotations ( ) ; List < Class < ? > > annotationTypes = new ArrayList < Class < ? > > ( ) ; // Iterate through all annotations of the current class for ( Annotation a : annotations ) { // Add the current annotation to the result and to the annotation types that needed to be examained for stereotype annotations annotationSet . add ( a ) ; annotationTypes . add ( a . annotationType ( ) ) ; } if ( stereotypeAnnotationClass != null ) { while ( ! annotationTypes . isEmpty ( ) ) { Class < ? > annotationType = annotationTypes . remove ( annotationTypes . size ( ) - 1 ) ; if ( annotationType . isAnnotationPresent ( stereotypeAnnotationClass ) ) { // If the stereotype annotation is present examine the 'inherited' annotations for ( Annotation annotation : annotationType . getAnnotations ( ) ) { // add the 'inherited' annotations to be examined for further stereotype annotations annotationTypes . add ( annotation . annotationType ( ) ) ; if ( ! annotation . annotationType ( ) . equals ( stereotypeAnnotationClass ) ) { // add the stereotyped annotations to the set annotationSet . add ( annotation ) ; } } } } } return annotationSet ; } | Returns all annotations of a class also the annotations of the super classes implemented interfaces and the annotations that are present in stereotype annotations . The stereotype annotation will not be included in the annotation set . | 302 | 37 |
142,910 | public static < T extends Annotation > T findAnnotation ( Method m , Class < T > annotationClazz ) { T annotation = m . getAnnotation ( annotationClazz ) ; if ( annotation != null ) { return annotation ; } if ( stereotypeAnnotationClass != null ) { List < Class < ? > > annotations = new ArrayList <> ( ) ; for ( Annotation a : m . getAnnotations ( ) ) { annotations . add ( a . annotationType ( ) ) ; } return findAnnotation ( annotations , annotationClazz ) ; } return null ; } | Returns the annotation object for the specified annotation class of the method if it can be found otherwise null . The annotation is searched in the method which and if a stereotype annotation is found the annotations present on an annotation are also examined . If the annotation can not be found null is returned . | 122 | 56 |
142,911 | public static < T extends Annotation > T findAnnotation ( Class < ? > clazz , Class < T > annotationClazz ) { T annotation = clazz . getAnnotation ( annotationClazz ) ; if ( annotation != null ) { return annotation ; } Set < Class < ? > > superTypes = ReflectionUtils . getSuperTypes ( clazz ) ; for ( Class < ? > type : superTypes ) { annotation = type . getAnnotation ( annotationClazz ) ; if ( annotation != null ) { return annotation ; } } if ( stereotypeAnnotationClass != null ) { List < Class < ? > > annotations = new ArrayList <> ( ) ; for ( Class < ? > type : superTypes ) { for ( Annotation a : type . getAnnotations ( ) ) { annotations . add ( a . annotationType ( ) ) ; } } return findAnnotation ( annotations , annotationClazz ) ; } return null ; } | Returns the annotation object for the specified annotation class of the given class object . All super types of the given class are examined to find the annotation . If a stereotype annotation is found the annotations present on an annotation are also examined . | 200 | 45 |
142,912 | public < T extends BasicMessage > void listen ( ConsumerConnectionContext context , AbstractBasicMessageListener < T > listener ) throws JMSException { if ( context == null ) { throw new NullPointerException ( "context must not be null" ) ; } if ( listener == null ) { throw new NullPointerException ( "listener must not be null" ) ; } MessageConsumer consumer = context . getMessageConsumer ( ) ; if ( consumer == null ) { throw new NullPointerException ( "context had a null consumer" ) ; } listener . setConsumerConnectionContext ( context ) ; consumer . setMessageListener ( listener ) ; } | Listens for messages . | 134 | 5 |
142,913 | public MessageId send ( ProducerConnectionContext context , BasicMessage basicMessage , Map < String , String > headers ) throws JMSException { if ( context == null ) { throw new IllegalArgumentException ( "context must not be null" ) ; } if ( basicMessage == null ) { throw new IllegalArgumentException ( "message must not be null" ) ; } // create the JMS message to be sent Message msg = createMessage ( context , basicMessage , headers ) ; // if the message is correlated with another, put the correlation ID in the Message to be sent if ( basicMessage . getCorrelationId ( ) != null ) { msg . setJMSCorrelationID ( basicMessage . getCorrelationId ( ) . toString ( ) ) ; } if ( basicMessage . getMessageId ( ) != null ) { log . debugf ( "Non-null message ID [%s] will be ignored and a new one generated" , basicMessage . getMessageId ( ) ) ; basicMessage . setMessageId ( null ) ; } // now send the message to the broker MessageProducer producer = context . getMessageProducer ( ) ; if ( producer == null ) { throw new IllegalStateException ( "context had a null producer" ) ; } producer . send ( msg ) ; // put message ID into the message in case the caller wants to correlate it with another record MessageId messageId = new MessageId ( msg . getJMSMessageID ( ) ) ; basicMessage . setMessageId ( messageId ) ; return messageId ; } | Send the given message to its destinations across the message bus . Once sent the message will get assigned a generated message ID . That message ID will also be returned by this method . | 326 | 35 |
142,914 | public < T extends BasicMessage > RPCConnectionContext sendAndListen ( ProducerConnectionContext context , BasicMessage basicMessage , BasicMessageListener < T > responseListener , Map < String , String > headers ) throws JMSException { if ( context == null ) { throw new IllegalArgumentException ( "context must not be null" ) ; } if ( basicMessage == null ) { throw new IllegalArgumentException ( "message must not be null" ) ; } if ( responseListener == null ) { throw new IllegalArgumentException ( "response listener must not be null" ) ; } // create the JMS message to be sent Message msg = createMessage ( context , basicMessage , headers ) ; // if the message is correlated with another, put the correlation ID in the Message to be sent if ( basicMessage . getCorrelationId ( ) != null ) { msg . setJMSCorrelationID ( basicMessage . getCorrelationId ( ) . toString ( ) ) ; } if ( basicMessage . getMessageId ( ) != null ) { log . debugf ( "Non-null message ID [%s] will be ignored and a new one generated" , basicMessage . getMessageId ( ) ) ; basicMessage . setMessageId ( null ) ; } MessageProducer producer = context . getMessageProducer ( ) ; if ( producer == null ) { throw new NullPointerException ( "Cannot send request-response message - the producer is null" ) ; } // prepare for the response prior to sending the request Session session = context . getSession ( ) ; if ( session == null ) { throw new NullPointerException ( "Cannot send request-response message - the session is null" ) ; } TemporaryQueue responseQueue = session . createTemporaryQueue ( ) ; MessageConsumer responseConsumer = session . createConsumer ( responseQueue ) ; RPCConnectionContext rpcContext = new RPCConnectionContext ( ) ; rpcContext . copy ( context ) ; rpcContext . setDestination ( responseQueue ) ; rpcContext . setMessageConsumer ( responseConsumer ) ; rpcContext . setRequestMessage ( msg ) ; rpcContext . setResponseListener ( responseListener ) ; responseListener . setConsumerConnectionContext ( rpcContext ) ; responseConsumer . setMessageListener ( responseListener ) ; msg . setJMSReplyTo ( responseQueue ) ; // now send the message to the broker producer . send ( msg ) ; // put message ID into the message in case the caller wants to correlate it with another record MessageId messageId = new MessageId ( msg . getJMSMessageID ( ) ) ; basicMessage . setMessageId ( messageId ) ; return rpcContext ; } | Send the given message to its destinations across the message bus and any response sent back will be passed to the given listener . Use this for request - response messages where you expect to get a non - void response back . | 564 | 43 |
142,915 | public void sendBasicMessageAsync ( Session session , BasicMessage msg ) { String text = ApiDeserializer . toHawkularFormat ( msg ) ; sendTextAsync ( session , text ) ; } | Converts the given message to JSON and sends that JSON text to clients asynchronously . | 43 | 18 |
142,916 | public void sendBinaryAsync ( Session session , InputStream inputStream , ExecutorService threadPool ) { if ( session == null ) { return ; } if ( inputStream == null ) { throw new IllegalArgumentException ( "inputStream must not be null" ) ; } log . debugf ( "Attempting to send async binary data to client [%s]" , session . getId ( ) ) ; if ( session . isOpen ( ) ) { if ( this . asyncTimeout != null ) { // TODO: what to do with timeout? } CopyStreamRunnable runnable = new CopyStreamRunnable ( session , inputStream ) ; threadPool . execute ( runnable ) ; } return ; } | Sends binary data to a client asynchronously . | 153 | 11 |
142,917 | public void sendBinarySync ( Session session , InputStream inputStream ) throws IOException { if ( session == null ) { return ; } if ( inputStream == null ) { throw new IllegalArgumentException ( "inputStream must not be null" ) ; } log . debugf ( "Attempting to send binary data to client [%s]" , session . getId ( ) ) ; if ( session . isOpen ( ) ) { long size = new CopyStreamRunnable ( session , inputStream ) . copyInputToOutput ( ) ; log . debugf ( "Finished sending binary data to client [%s]: size=[%s]" , session . getId ( ) , size ) ; } return ; } | Sends binary data to a client synchronously . | 152 | 10 |
142,918 | @ OnOpen public void uiClientSessionOpen ( Session session ) { log . infoWsSessionOpened ( session . getId ( ) , endpoint ) ; wsEndpoints . getUiClientSessions ( ) . addSession ( session . getId ( ) , session ) ; WelcomeResponse welcomeResponse = new WelcomeResponse ( ) ; // FIXME we should not send the true sessionIds to clients to prevent spoofing. welcomeResponse . setSessionId ( session . getId ( ) ) ; try { new WebSocketHelper ( ) . sendBasicMessageSync ( session , welcomeResponse ) ; } catch ( IOException e ) { log . warnf ( e , "Could not send [%s] to UI client session [%s]." , WelcomeResponse . class . getName ( ) , session . getId ( ) ) ; } } | When a UI client connects this method is called . This will immediately send a welcome message to the UI client . | 177 | 22 |
142,919 | private void doStart ( ) throws LifecycleException { tomcat . getServer ( ) . addLifecycleListener ( new TomcatLifecycleListener ( ) ) ; logger . info ( "Deploying application to [" + getConfig ( ) . getDeployUrl ( ) + "]" ) ; tomcat . start ( ) ; // Let's set the port that was used to actually start the application if necessary if ( getConfig ( ) . getPort ( ) == EmbedVaadinConfig . DEFAULT_PORT ) { getConfig ( ) . setPort ( getTomcat ( ) . getConnector ( ) . getLocalPort ( ) ) ; } logger . info ( "Application has been deployed to [" + getConfig ( ) . getDeployUrl ( ) + "]" ) ; if ( config . shouldOpenBrowser ( ) ) { BrowserUtils . openBrowser ( getConfig ( ) . getOpenBrowserUrl ( ) ) ; } if ( isWaiting ( ) ) { tomcat . getServer ( ) . await ( ) ; } } | Fires the embedded tomcat that is assumed to be fully configured . | 218 | 14 |
142,920 | private void doStop ( ) throws LifecycleException { logger . info ( "Stopping tomcat." ) ; long startTime = System . currentTimeMillis ( ) ; tomcat . stop ( ) ; long duration = System . currentTimeMillis ( ) - startTime ; logger . info ( "Tomcat shutdown finished in " + duration + " ms." ) ; } | Stops the embedded tomcat . | 78 | 7 |
142,921 | public LogTarget addDelegate ( Log log ) { LogProxyTarget logProxyTarget = new LogProxyTarget ( log ) ; this . addTarget ( logProxyTarget ) ; return logProxyTarget ; } | Adds a ProxyTarget for an other Logger | 42 | 9 |
142,922 | public Object addingService ( ServiceReference reference ) { HttpService httpService = ( HttpService ) context . getService ( reference ) ; String alias = this . getAlias ( ) ; String name = this . getProperty ( RESOURCE_NAME ) ; if ( name == null ) name = alias ; try { httpService . registerResources ( alias , name , httpContext ) ; } catch ( NamespaceException e ) { e . printStackTrace ( ) ; } return httpService ; } | Http Service is up add my resource . | 103 | 8 |
142,923 | public final void setTypeName ( final String typeName ) { if ( typeName == null ) { type = LOOKING_AT ; } else if ( typeName . equalsIgnoreCase ( TYPES [ 0 ] ) ) { type = MATCHES ; } else if ( typeName . equalsIgnoreCase ( TYPES [ 1 ] ) ) { type = LOOKING_AT ; } else if ( typeName . equalsIgnoreCase ( TYPES [ 2 ] ) ) { type = FIND ; } } | Sets the type name of the matching . | 111 | 9 |
142,924 | public static Reflect onObject ( Object object ) { if ( object == null ) { return new Reflect ( null , null ) ; } return new Reflect ( object , object . getClass ( ) ) ; } | Creates an instance of Reflect associated with an object | 42 | 10 |
142,925 | public static Reflect onClass ( String clazz ) throws Exception { return new Reflect ( null , ReflectionUtils . getClassForName ( clazz ) ) ; } | Creates an instance of Reflect associated with a class | 35 | 10 |
142,926 | public boolean containsField ( String name ) { if ( StringUtils . isNullOrBlank ( name ) ) { return false ; } return ClassDescriptorCache . getInstance ( ) . getClassDescriptor ( clazz ) . getFields ( accessAll ) . stream ( ) . anyMatch ( f -> f . getName ( ) . equals ( name ) ) ; } | Determines if a field with the given name is associated with the class | 82 | 15 |
142,927 | public Reflect create ( ) throws ReflectionException { try { return on ( clazz . getConstructor ( ) , accessAll ) ; } catch ( NoSuchMethodException e ) { if ( accessAll ) { try { return on ( clazz . getDeclaredConstructor ( ) , accessAll ) ; } catch ( NoSuchMethodException e2 ) { throw new ReflectionException ( e2 ) ; } } throw new ReflectionException ( e ) ; } } | Creates an instance of the class being reflected using the no - argument constructor . | 98 | 16 |
142,928 | public Reflect create ( Object ... args ) throws ReflectionException { return create ( ReflectionUtils . getTypes ( args ) , args ) ; } | Creates an instance of the class being reflected using the most specific constructor available . | 31 | 16 |
142,929 | public Reflect create ( Class [ ] types , Object ... args ) throws ReflectionException { try { return on ( clazz . getConstructor ( types ) , accessAll , args ) ; } catch ( NoSuchMethodException e ) { for ( Constructor constructor : getConstructors ( ) ) { if ( ReflectionUtils . typesMatch ( constructor . getParameterTypes ( ) , types ) ) { return on ( constructor , accessAll , args ) ; } } throw new ReflectionException ( e ) ; } } | Create reflect . | 108 | 3 |
142,930 | public Method getMethod ( final String name ) { if ( StringUtils . isNullOrBlank ( name ) ) { return null ; } return getMethods ( ) . stream ( ) . filter ( method -> method . getName ( ) . equals ( name ) ) . findFirst ( ) . orElse ( null ) ; } | Gets method . | 69 | 4 |
142,931 | public boolean containsMethod ( final String name ) { if ( StringUtils . isNullOrBlank ( name ) ) { return false ; } return ClassDescriptorCache . getInstance ( ) . getClassDescriptor ( clazz ) . getMethods ( accessAll ) . stream ( ) . anyMatch ( f -> f . getName ( ) . equals ( name ) ) ; } | Contains method . | 82 | 4 |
142,932 | public Reflect invoke ( String methodName , Object ... args ) throws ReflectionException { Class [ ] types = ReflectionUtils . getTypes ( args ) ; try { return on ( clazz . getMethod ( methodName , types ) , object , accessAll , args ) ; } catch ( NoSuchMethodException e ) { Method method = ReflectionUtils . bestMatchingMethod ( getMethods ( ) , methodName , types ) ; if ( method != null ) { return on ( method , object , accessAll , args ) ; } throw new ReflectionException ( e ) ; } } | Invokes a method with a given name and arguments with the most specific method possible | 124 | 16 |
142,933 | public Reflect set ( String fieldName , Object value ) throws ReflectionException { Field field = null ; boolean isAccessible = false ; try { if ( hasField ( fieldName ) ) { field = getField ( fieldName ) ; isAccessible = field . isAccessible ( ) ; field . setAccessible ( accessAll ) ; } else { throw new NoSuchElementException ( ) ; } value = convertValueType ( value , field . getType ( ) ) ; field . set ( object , value ) ; return this ; } catch ( IllegalAccessException e ) { throw new ReflectionException ( e ) ; } finally { if ( field != null ) { field . setAccessible ( isAccessible ) ; } } } | Sets the value of a field . Will perform conversion on the value if needed . | 154 | 17 |
142,934 | public TypedQuery < Long > count ( Filter filter ) { CriteriaQuery < Long > query = cb . createQuery ( Long . class ) ; Root < T > from = query . from ( getEntityClass ( ) ) ; if ( filter != null ) { Predicate where = new CriteriaMapper ( from , cb ) . create ( filter ) ; query . where ( where ) ; } return getEntityManager ( ) . createQuery ( query . select ( cb . count ( from ) ) ) ; } | Creates a new TypedQuery that queries the amount of entities of the entity class of this QueryFactory that a query for the given Filter would return . | 110 | 31 |
142,935 | public static String generateMD5 ( final String input ) { try { return generateMD5 ( input . getBytes ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { LOG . debug ( "An error occurred generating the MD5 Hash of the input string" , e ) ; return null ; } } | Generates a MD5 Hash for a specific string | 70 | 10 |
142,936 | public static Properties loadClasspath ( String path ) throws IOException { InputStream input = PropUtils . class . getClassLoader ( ) . getResourceAsStream ( path ) ; Properties prop = null ; try { prop = load ( input ) ; } finally { IOUtils . close ( input ) ; } return prop ; } | Loads properties from a file in the classpath . | 70 | 11 |
142,937 | public Tuple shiftLeft ( ) { if ( degree ( ) < 2 ) { return Tuple0 . INSTANCE ; } Object [ ] copy = new Object [ degree ( ) - 1 ] ; System . arraycopy ( array ( ) , 1 , copy , 0 , copy . length ) ; return NTuple . of ( copy ) ; } | Shifts the first element of the tuple resulting in a tuple of degree - 1 . | 71 | 17 |
142,938 | public Tuple slice ( int start , int end ) { Preconditions . checkArgument ( start >= 0 , "Start index must be >= 0" ) ; Preconditions . checkArgument ( start < end , "Start index must be < end index" ) ; if ( start >= degree ( ) ) { return Tuple0 . INSTANCE ; } return new NTuple ( Arrays . copyOfRange ( array ( ) , start , Math . min ( end , degree ( ) ) ) ) ; } | Takes a slice of the tuple from an inclusive start to an exclusive end index . | 107 | 17 |
142,939 | public < T > Tuple appendLeft ( T object ) { if ( degree ( ) == 0 ) { return Tuple1 . of ( object ) ; } Object [ ] copy = new Object [ degree ( ) + 1 ] ; System . arraycopy ( array ( ) , 0 , copy , 1 , degree ( ) ) ; copy [ 0 ] = object ; return NTuple . of ( copy ) ; } | Appends an item the beginning of the tuple resulting in a new tuple of degree + 1 | 85 | 18 |
142,940 | private boolean isIncluded ( String className ) { if ( includes == null || includes . size ( ) == 0 ) { // generate nothing if no include defined - it makes no sense to generate for all classes from classpath return false ; } return includes . stream ( ) . filter ( pattern -> SelectorUtils . matchPath ( pattern , className , "." , true ) ) . count ( ) > 0 ; } | Check is class is included . | 88 | 6 |
142,941 | private boolean isExcluded ( String className ) { if ( excludes == null || excludes . size ( ) == 0 ) { return false ; } return excludes . stream ( ) . filter ( pattern -> SelectorUtils . matchPath ( pattern , className , "." , true ) ) . count ( ) == 0 ; } | Check if class is excluded | 68 | 5 |
142,942 | private void generateSchema ( Class clazz ) { try { File targetFile = new File ( getGeneratedResourcesDirectory ( ) , clazz . getName ( ) + ".json" ) ; getLog ( ) . info ( "Generate JSON schema: " + targetFile . getName ( ) ) ; SchemaFactoryWrapper schemaFactory = new SchemaFactoryWrapper ( ) ; OBJECT_MAPPER . acceptJsonFormatVisitor ( OBJECT_MAPPER . constructType ( clazz ) , schemaFactory ) ; JsonSchema jsonSchema = schemaFactory . finalSchema ( ) ; OBJECT_MAPPER . writerWithDefaultPrettyPrinter ( ) . writeValue ( targetFile , jsonSchema ) ; } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; } } | Generate JSON schema for given POJO | 173 | 8 |
142,943 | @ Override protected Class < ? > loadClass ( String name , boolean resolve ) throws ClassNotFoundException { synchronized ( LaunchedURLClassLoader . LOCK_PROVIDER . getLock ( this , name ) ) { Class < ? > loadedClass = findLoadedClass ( name ) ; if ( loadedClass == null ) { Handler . setUseFastConnectionExceptions ( true ) ; try { loadedClass = doLoadClass ( name ) ; } finally { Handler . setUseFastConnectionExceptions ( false ) ; } } if ( resolve ) { resolveClass ( loadedClass ) ; } return loadedClass ; } } | Attempt to load classes from the URLs before delegating to the parent loader . | 129 | 15 |
142,944 | @ SuppressWarnings ( "unchecked" ) public static int compare ( Object o1 , Object o2 ) { if ( o1 == null && o2 == null ) { return 0 ; } else if ( o1 == null ) { return 1 ; } else if ( o2 == null ) { return - 1 ; } return Cast . < Comparable > as ( o1 ) . compareTo ( o2 ) ; } | Compare int . | 91 | 3 |
142,945 | public static < T > SerializableComparator < T > hashCodeComparator ( ) { return ( o1 , o2 ) -> { if ( o1 == o2 ) { return 0 ; } else if ( o1 == null ) { return 1 ; } else if ( o2 == null ) { return - 1 ; } return Integer . compare ( o1 . hashCode ( ) , o2 . hashCode ( ) ) ; } ; } | Compares two objects based on their hashcode . | 94 | 10 |
142,946 | public final void addFolder ( @ NotNull final Folder folder ) { Contract . requireArgNotNull ( "folder" , folder ) ; if ( folders == null ) { folders = new ArrayList <> ( ) ; } folders . add ( folder ) ; } | Adds a folder to the list . If the list does not exist it s created . | 54 | 17 |
142,947 | public Iterator < int [ ] > fastPassByReferenceIterator ( ) { final int [ ] assignments = new int [ dimensions . length ] ; if ( dimensions . length > 0 ) assignments [ 0 ] = - 1 ; return new Iterator < int [ ] > ( ) { @ Override public boolean hasNext ( ) { for ( int i = 0 ; i < assignments . length ; i ++ ) { if ( assignments [ i ] < dimensions [ i ] - 1 ) return true ; } return false ; } @ Override public int [ ] next ( ) { // Add one to the first position assignments [ 0 ] ++ ; // Carry any resulting overflow all the way to the end. for ( int i = 0 ; i < assignments . length ; i ++ ) { if ( assignments [ i ] >= dimensions [ i ] ) { assignments [ i ] = 0 ; if ( i < assignments . length - 1 ) { assignments [ i + 1 ] ++ ; } } else { break ; } } return assignments ; } } ; } | This is its own function because people will inevitably attempt this optimization of not cloning the array we hand to the iterator to save on GC and it should not be default behavior . If you know what you re doing then this may be the iterator for you . | 214 | 50 |
142,948 | private int getTableAccessOffset ( int [ ] assignment ) { assert ( assignment . length == dimensions . length ) ; int offset = 0 ; for ( int i = 0 ; i < assignment . length ; i ++ ) { assert ( assignment [ i ] < dimensions [ i ] ) ; offset = ( offset * dimensions [ i ] ) + assignment [ i ] ; } return offset ; } | Compute the distance into the one dimensional factorTable array that corresponds to a setting of all the neighbors of the factor . | 80 | 24 |
142,949 | public static String center ( String s , int length ) { if ( s == null ) { return null ; } int start = ( int ) Math . floor ( Math . max ( 0 , ( length - s . length ( ) ) / 2d ) ) ; return padEnd ( repeat ( ' ' , start ) + s , length , ' ' ) ; } | Center string . | 75 | 3 |
142,950 | public static int compare ( String s1 , String s2 , boolean ignoreCase ) { if ( s1 == null && s2 == null ) { return 0 ; } else if ( s1 == null ) { return - 1 ; } else if ( s2 == null ) { return 1 ; } return ignoreCase ? s1 . compareToIgnoreCase ( s2 ) : s1 . compareTo ( s2 ) ; } | Null safe comparison of strings | 90 | 5 |
142,951 | public static String firstNonNullOrBlank ( String ... strings ) { if ( strings == null || strings . length == 0 ) { return null ; } for ( String s : strings ) { if ( isNotNullOrBlank ( s ) ) { return s ; } } return null ; } | First non null or blank string . | 62 | 7 |
142,952 | public static String leftTrim ( CharSequence input ) { if ( input == null ) { return null ; } return StringFunctions . LEFT_TRIM . apply ( input . toString ( ) ) ; } | Left trim . | 46 | 3 |
142,953 | public static String removeDiacritics ( CharSequence input ) { if ( input == null ) { return null ; } return StringFunctions . DIACRITICS_NORMALIZATION . apply ( input . toString ( ) ) ; } | Normalizes a string by removing the diacritics . | 53 | 12 |
142,954 | public static String rightTrim ( CharSequence input ) { if ( input == null ) { return null ; } return StringFunctions . RIGHT_TRIM . apply ( input . toString ( ) ) ; } | Right trim . | 45 | 3 |
142,955 | public static boolean safeEquals ( String s1 , String s2 , boolean caseSensitive ) { if ( s1 == s2 ) { return true ; } else if ( s1 == null || s2 == null ) { return false ; } else if ( caseSensitive ) { return s1 . equals ( s2 ) ; } return s1 . equalsIgnoreCase ( s2 ) ; } | Safe equals . | 85 | 3 |
142,956 | @ SneakyThrows public static List < String > split ( CharSequence input , char separator ) { if ( input == null ) { return new ArrayList <> ( ) ; } Preconditions . checkArgument ( separator != ' ' , "Separator cannot be a quote" ) ; try ( CSVReader reader = CSV . builder ( ) . delimiter ( separator ) . reader ( new StringReader ( input . toString ( ) ) ) ) { List < String > all = new ArrayList <> ( ) ; List < String > row ; while ( ( row = reader . nextRow ( ) ) != null ) { all . addAll ( row ) ; } return all ; } } | Properly splits a delimited separated string . | 150 | 10 |
142,957 | public static String toCanonicalForm ( CharSequence input ) { if ( input == null ) { return null ; } return StringFunctions . CANONICAL_NORMALIZATION . apply ( input . toString ( ) ) ; } | Normalize to canonical form . | 51 | 6 |
142,958 | public static String toTitleCase ( CharSequence input ) { if ( input == null ) { return null ; } return StringFunctions . TITLE_CASE . apply ( input . toString ( ) ) ; } | Converts an input string to title case | 46 | 8 |
142,959 | public static String trim ( CharSequence input ) { if ( input == null ) { return null ; } return StringFunctions . TRIM . apply ( input . toString ( ) ) ; } | Trims a string of unicode whitespace and invisible characters | 41 | 12 |
142,960 | public static String unescape ( String input , char escapeCharacter ) { if ( input == null ) { return null ; } StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < input . length ( ) ; ) { if ( input . charAt ( i ) == escapeCharacter ) { builder . append ( input . charAt ( i + 1 ) ) ; i = i + 2 ; } else { builder . append ( input . charAt ( i ) ) ; i ++ ; } } return builder . toString ( ) ; } | Unescape string . | 117 | 5 |
142,961 | public static void validateAddress ( String address ) { // Check for improperly formatted addresses Matcher matcher = ADDRESS_PATTERN . matcher ( address ) ; if ( ! matcher . matches ( ) ) { String message = "The address must have the format X.X.X.X" ; throw new IllegalArgumentException ( message ) ; } // Check for out of range address components for ( int i = 1 ; i <= 4 ; i ++ ) { int component = Integer . parseInt ( matcher . group ( i ) ) ; if ( component < 0 || component > 255 ) { String message = "All address components must be in the range [0, 255]" ; throw new IllegalArgumentException ( message ) ; } } } | Verifies that the given address is valid | 158 | 8 |
142,962 | public static void validatePeriod ( Duration period ) { if ( period . equals ( Duration . ZERO ) ) { String message = "The period must be nonzero" ; throw new IllegalArgumentException ( message ) ; } } | Verifies that the given period is valid | 48 | 8 |
142,963 | public static void validateTimeout ( Duration timeout ) { if ( timeout . equals ( Duration . ZERO ) ) { String message = "The timeout must be nonzero" ; throw new IllegalArgumentException ( message ) ; } } | Verifies that the given timeout is valid | 47 | 8 |
142,964 | @ Override public boolean setProperties ( Dictionary < String , String > properties ) { this . properties = properties ; if ( this . properties != null ) { if ( properties . get ( "debug" ) != null ) debug = Integer . parseInt ( properties . get ( "debug" ) ) ; if ( properties . get ( "input" ) != null ) input = Integer . parseInt ( properties . get ( "input" ) ) ; if ( properties . get ( "output" ) != null ) output = Integer . parseInt ( properties . get ( "output" ) ) ; listings = Boolean . parseBoolean ( properties . get ( "listings" ) ) ; if ( properties . get ( "readonly" ) != null ) readOnly = Boolean . parseBoolean ( properties . get ( "readonly" ) ) ; if ( properties . get ( "sendfileSize" ) != null ) sendfileSize = Integer . parseInt ( properties . get ( "sendfileSize" ) ) * 1024 ; fileEncoding = properties . get ( "fileEncoding" ) ; globalXsltFile = properties . get ( "globalXsltFile" ) ; contextXsltFile = properties . get ( "contextXsltFile" ) ; localXsltFile = properties . get ( "localXsltFile" ) ; readmeFile = properties . get ( "readmeFile" ) ; if ( properties . get ( "useAcceptRanges" ) != null ) useAcceptRanges = Boolean . parseBoolean ( properties . get ( "useAcceptRanges" ) ) ; // Sanity check on the specified buffer sizes if ( input < 256 ) input = 256 ; if ( output < 256 ) output = 256 ; if ( debug > 0 ) { log ( "DefaultServlet.init: input buffer size=" + input + ", output buffer size=" + output ) ; } return this . setDocBase ( this . properties . get ( BASE_PATH ) ) ; } else { return this . setDocBase ( null ) ; } } | Set servlet the properties . | 437 | 6 |
142,965 | @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public boolean setDocBase ( String basePath ) { proxyDirContext = null ; if ( basePath == null ) return false ; Hashtable env = new Hashtable ( ) ; File file = new File ( basePath ) ; if ( ! file . exists ( ) ) return false ; if ( ! file . isDirectory ( ) ) return false ; env . put ( ProxyDirContext . CONTEXT , file . getPath ( ) ) ; FileDirContext fileContext = new FileDirContext ( env ) ; fileContext . setDocBase ( file . getPath ( ) ) ; proxyDirContext = new ProxyDirContext ( env , fileContext ) ; /* Can't figure this one out InitialContext cx = null; try { cx.rebind(RESOURCES_JNDI_NAME, obj); } catch (NamingException e) { e.printStackTrace(); } */ // Load the proxy dir context. return true ; } | Set the local file path to serve files from . | 216 | 10 |
142,966 | public static Properties loadProperties ( final Class < ? > clasz , final String filename ) { checkNotNull ( "clasz" , clasz ) ; checkNotNull ( "filename" , filename ) ; final String path = getPackagePath ( clasz ) ; final String resPath = path + "/" + filename ; return loadProperties ( clasz . getClassLoader ( ) , resPath ) ; } | Load properties from classpath . | 92 | 6 |
142,967 | public static Properties loadProperties ( final ClassLoader loader , final String resource ) { checkNotNull ( "loader" , loader ) ; checkNotNull ( "resource" , resource ) ; final Properties props = new Properties ( ) ; try ( final InputStream inStream = loader . getResourceAsStream ( resource ) ) { if ( inStream == null ) { throw new IllegalArgumentException ( "Resource '" + resource + "' not found!" ) ; } props . load ( inStream ) ; } catch ( final IOException ex ) { throw new RuntimeException ( ex ) ; } return props ; } | Loads a resource from the classpath as properties . | 126 | 11 |
142,968 | public static Properties loadProperties ( final URL baseUrl , final String filename ) { return loadProperties ( createUrl ( baseUrl , "" , filename ) ) ; } | Load a file from an directory . | 35 | 7 |
142,969 | public static Properties loadProperties ( final URL fileURL ) { checkNotNull ( "fileURL" , fileURL ) ; final Properties props = new Properties ( ) ; try ( final InputStream inStream = fileURL . openStream ( ) ) { props . load ( inStream ) ; } catch ( final IOException ex ) { throw new RuntimeException ( ex ) ; } return props ; } | Load a file from an URL . | 82 | 7 |
142,970 | private ScenarioManager createScenarioManager ( Class < ? extends Scenario > scenarioClass , String scenarioID , String initialState , Properties properties ) throws ShanksException { // throws UnsupportedNetworkElementFieldException, // TooManyConnectionException, UnsupportedScenarioStatusException, // DuplicatedIDException, SecurityException, NoSuchMethodException, // IllegalArgumentException, InstantiationException, // IllegalAccessException, InvocationTargetException, // DuplicatedPortrayalIDException, ScenarioNotFoundException { Constructor < ? extends Scenario > c ; Scenario s = null ; try { c = scenarioClass . getConstructor ( new Class [ ] { String . class , String . class , Properties . class , Logger . class } ) ; s = c . newInstance ( scenarioID , initialState , properties , this . getLogger ( ) ) ; } catch ( SecurityException e ) { throw new ShanksException ( e ) ; } catch ( NoSuchMethodException e ) { throw new ShanksException ( e ) ; } catch ( IllegalArgumentException e ) { throw new ShanksException ( e ) ; } catch ( InstantiationException e ) { throw new ShanksException ( e ) ; } catch ( IllegalAccessException e ) { throw new ShanksException ( e ) ; } catch ( InvocationTargetException e ) { throw new ShanksException ( e ) ; } logger . fine ( "Scenario created" ) ; ScenarioPortrayal sp = s . createScenarioPortrayal ( ) ; if ( sp == null && ! properties . get ( Scenario . SIMULATION_GUI ) . equals ( Scenario . NO_GUI ) ) { logger . severe ( "ScenarioPortrayals is null" ) ; logger . severe ( "Impossible to follow with the execution..." ) ; throw new ShanksException ( "ScenarioPortrayals is null. Impossible to continue with the simulation..." ) ; } ScenarioManager sm = new ScenarioManager ( s , sp , logger ) ; return sm ; } | This method will set all required information about Scenario | 429 | 10 |
142,971 | public void startSimulation ( ) throws ShanksException { schedule . scheduleRepeating ( Schedule . EPOCH , 0 , this . scenarioManager , 2 ) ; schedule . scheduleRepeating ( Schedule . EPOCH , 1 , this . notificationManager , 1 ) ; this . addAgents ( ) ; this . addSteppables ( ) ; } | The initial configuration of the scenario | 74 | 6 |
142,972 | private void addAgents ( ) throws ShanksException { for ( Entry < String , ShanksAgent > agentEntry : this . agents . entrySet ( ) ) { stoppables . put ( agentEntry . getKey ( ) , schedule . scheduleRepeating ( Schedule . EPOCH , 2 , agentEntry . getValue ( ) , 1 ) ) ; } } | Add ShanksAgent s to the simulation using registerShanksAgent method | 76 | 14 |
142,973 | public void registerShanksAgent ( ShanksAgent agent ) throws ShanksException { if ( ! this . agents . containsKey ( agent . getID ( ) ) ) { this . agents . put ( agent . getID ( ) , agent ) ; } else { throw new DuplicatedAgentIDException ( agent . getID ( ) ) ; } } | This method adds and registers the ShanksAgent | 73 | 9 |
142,974 | public void unregisterShanksAgent ( String agentID ) { if ( this . agents . containsKey ( agentID ) ) { // this.agents.get(agentID).stop(); if ( stoppables . containsKey ( agentID ) ) { this . agents . remove ( agentID ) ; this . stoppables . remove ( agentID ) . stop ( ) ; } else { //No stoppable, stops the agent logger . warning ( "No stoppable found while trying to stop the agent. Attempting direct stop..." ) ; this . agents . remove ( agentID ) . stop ( ) ; } } } | Unregisters an agent . | 128 | 6 |
142,975 | public boolean containsStartTag ( @ NotNull @ FileExists @ IsFile final File file , @ NotNull final String tagName ) { Contract . requireArgNotNull ( "file" , file ) ; FileExistsValidator . requireArgValid ( "file" , file ) ; IsFileValidator . requireArgValid ( "file" , file ) ; Contract . requireArgNotNull ( "tagName" , tagName ) ; final String xml = readFirstPartOfFile ( file ) ; return xml . indexOf ( "<" + tagName ) > - 1 ; } | Checks if the given file contains a start tag within the first 1024 bytes . | 122 | 16 |
142,976 | @ SuppressWarnings ( "unchecked" ) @ NotNull public < TYPE > TYPE create ( @ NotNull final Reader reader , @ NotNull final JAXBContext jaxbContext ) throws UnmarshalObjectException { Contract . requireArgNotNull ( "reader" , reader ) ; Contract . requireArgNotNull ( "jaxbContext" , jaxbContext ) ; try { final Unmarshaller unmarshaller = jaxbContext . createUnmarshaller ( ) ; final TYPE obj = ( TYPE ) unmarshaller . unmarshal ( reader ) ; return obj ; } catch ( final JAXBException ex ) { throw new UnmarshalObjectException ( "Unable to parse XML from reader" , ex ) ; } } | Creates an instance by reading the XML from a reader . | 169 | 12 |
142,977 | @ SuppressWarnings ( "unchecked" ) @ NotNull public < TYPE > TYPE create ( @ NotNull @ FileExists @ IsFile final File file , @ NotNull final JAXBContext jaxbContext ) throws UnmarshalObjectException { Contract . requireArgNotNull ( "file" , file ) ; FileExistsValidator . requireArgValid ( "file" , file ) ; IsFileValidator . requireArgValid ( "file" , file ) ; Contract . requireArgNotNull ( "jaxbContext" , jaxbContext ) ; try { final FileReader fr = new FileReader ( file ) ; try { return ( TYPE ) create ( fr , jaxbContext ) ; } finally { fr . close ( ) ; } } catch ( final IOException ex ) { throw new UnmarshalObjectException ( "Unable to parse XML from file: " + file , ex ) ; } } | Creates an instance by reading the XML from a file . | 201 | 12 |
142,978 | @ SuppressWarnings ( "unchecked" ) @ NotNull public < TYPE > TYPE create ( @ NotNull final String xml , @ NotNull final JAXBContext jaxbContext ) throws UnmarshalObjectException { Contract . requireArgNotNull ( "xml" , xml ) ; Contract . requireArgNotNull ( "jaxbContext" , jaxbContext ) ; return ( TYPE ) create ( new StringReader ( xml ) , jaxbContext ) ; } | Creates an instance by from a given XML . | 105 | 10 |
142,979 | public < TYPE > void write ( @ NotNull final TYPE obj , @ NotNull final File file , @ NotNull final JAXBContext jaxbContext ) throws MarshalObjectException { Contract . requireArgNotNull ( "obj" , obj ) ; Contract . requireArgNotNull ( "file" , file ) ; Contract . requireArgNotNull ( "jaxbContext" , jaxbContext ) ; try { final FileWriter fw = new FileWriter ( file ) ; try { write ( obj , fw , jaxbContext ) ; } finally { fw . close ( ) ; } } catch ( final IOException ex ) { throw new MarshalObjectException ( "Unable to write XML to file: " + file , ex ) ; } } | Marshals the object as XML to a file . | 162 | 10 |
142,980 | public < TYPE > String write ( @ NotNull final TYPE obj , @ NotNull final JAXBContext jaxbContext ) throws MarshalObjectException { Contract . requireArgNotNull ( "obj" , obj ) ; Contract . requireArgNotNull ( "jaxbContext" , jaxbContext ) ; final StringWriter writer = new StringWriter ( ) ; write ( obj , writer , jaxbContext ) ; return writer . toString ( ) ; } | Marshals the object as XML to a string . | 99 | 10 |
142,981 | public < TYPE > void write ( @ NotNull final TYPE obj , @ NotNull final Writer writer , @ NotNull final JAXBContext jaxbContext ) throws MarshalObjectException { Contract . requireArgNotNull ( "obj" , obj ) ; Contract . requireArgNotNull ( "writer" , writer ) ; Contract . requireArgNotNull ( "jaxbContext" , jaxbContext ) ; try { final Marshaller marshaller = jaxbContext . createMarshaller ( ) ; marshaller . setProperty ( Marshaller . JAXB_FORMATTED_OUTPUT , formattedOutput ) ; marshaller . marshal ( obj , writer ) ; } catch ( final JAXBException ex ) { throw new MarshalObjectException ( "Unable to write XML to writer" , ex ) ; } } | Marshals the object as XML to a writer . | 179 | 10 |
142,982 | public boolean shouldConfigureVirtualenv ( ) { if ( this . configureVirtualenv == ConfigureVirtualenv . NO ) { return false ; } else if ( this . configureVirtualenv == ConfigureVirtualenv . YES ) { return true ; } else { final Optional < File > whichVirtualenv = this . which ( "virtualenv" ) ; return whichVirtualenv . isPresent ( ) ; } } | Determines if a virtualenv should be created for Galaxy . | 84 | 13 |
142,983 | public boolean isPre20141006Release ( File galaxyRoot ) { if ( galaxyRoot == null ) { throw new IllegalArgumentException ( "galaxyRoot is null" ) ; } else if ( ! galaxyRoot . exists ( ) ) { throw new IllegalArgumentException ( "galaxyRoot=" + galaxyRoot . getAbsolutePath ( ) + " does not exist" ) ; } File configDirectory = new File ( galaxyRoot , CONFIG_DIR_NAME ) ; return ! ( new File ( configDirectory , "galaxy.ini.sample" ) ) . exists ( ) ; } | Determines if this is a pre - 2014 . 10 . 06 release of Galaxy . | 124 | 18 |
142,984 | private File getConfigSampleIni ( File galaxyRoot ) { if ( isPre20141006Release ( galaxyRoot ) ) { return new File ( galaxyRoot , "universe_wsgi.ini.sample" ) ; } else { File configDirectory = new File ( galaxyRoot , CONFIG_DIR_NAME ) ; return new File ( configDirectory , "galaxy.ini.sample" ) ; } } | Gets the sample config ini for this Galaxy installation . | 86 | 12 |
142,985 | private File getConfigIni ( File galaxyRoot ) { if ( isPre20141006Release ( galaxyRoot ) ) { return new File ( galaxyRoot , "universe_wsgi.ini" ) ; } else { File configDirectory = new File ( galaxyRoot , CONFIG_DIR_NAME ) ; return new File ( configDirectory , "galaxy.ini" ) ; } } | Gets the config ini for this Galaxy installation . | 81 | 11 |
142,986 | @ SuppressWarnings ( "unchecked" ) public void init ( ServletConfig config ) throws ServletException { super . init ( config ) ; // Move init params to my properties Enumeration < String > paramNames = this . getInitParameterNames ( ) ; while ( paramNames . hasMoreElements ( ) ) { String paramName = paramNames . nextElement ( ) ; this . setProperty ( paramName , this . getInitParameter ( paramName ) ) ; } if ( Boolean . TRUE . toString ( ) . equalsIgnoreCase ( this . getInitParameter ( LOG_PARAM ) ) ) logger = Logger . getLogger ( PROPERTY_PREFIX ) ; } | web servlet init method . | 151 | 6 |
142,987 | public String getRequestParam ( HttpServletRequest request , String param , String defaultValue ) { String value = request . getParameter ( servicePid + ' ' + param ) ; if ( ( value == null ) && ( properties != null ) ) value = properties . get ( servicePid + ' ' + param ) ; if ( value == null ) value = request . getParameter ( param ) ; if ( ( value == null ) && ( properties != null ) ) value = properties . get ( param ) ; if ( value == null ) value = defaultValue ; return value ; } | Get this param from the request or from the servlet s properties . | 123 | 14 |
142,988 | private static Map < String , Object > readMap ( StreamingInput input ) throws IOException { boolean readEnd = false ; if ( input . peek ( ) == Token . OBJECT_START ) { // Check if the object is wrapped readEnd = true ; input . next ( ) ; } Token t ; Map < String , Object > result = new HashMap < String , Object > ( ) ; while ( ( t = input . peek ( ) ) != Token . OBJECT_END && t != null ) { // Read the key input . next ( Token . KEY ) ; String key = input . getString ( ) ; // Read the value Object value = readDynamic ( input ) ; result . put ( key , value ) ; } if ( readEnd ) { input . next ( Token . OBJECT_END ) ; } return result ; } | Read a single map from the input optionally while reading object start and end tokens . | 176 | 16 |
142,989 | private static List < Object > readList ( StreamingInput input ) throws IOException { input . next ( Token . LIST_START ) ; List < Object > result = new ArrayList < Object > ( ) ; while ( input . peek ( ) != Token . LIST_END ) { // Read the value Object value = readDynamic ( input ) ; result . add ( value ) ; } input . next ( Token . LIST_END ) ; return result ; } | Read a list from the input . | 95 | 7 |
142,990 | private static Object readDynamic ( StreamingInput input ) throws IOException { switch ( input . peek ( ) ) { case VALUE : input . next ( ) ; return input . getValue ( ) ; case NULL : input . next ( ) ; return input . getValue ( ) ; case LIST_START : return readList ( input ) ; case OBJECT_START : return readMap ( input ) ; } throw new SerializationException ( "Unable to read file, unknown start of value: " + input . peek ( ) ) ; } | Depending on the next token read either a value a list or a map . | 114 | 15 |
142,991 | public void execute ( ) throws MojoExecutionException { try { repositoryPath = findRepoPath ( this . ceylonRepository ) ; ArtifactRepositoryLayout layout = new CeylonRepoLayout ( ) ; getLog ( ) . debug ( "Layout: " + layout . getClass ( ) ) ; localRepository = new DefaultArtifactRepository ( ceylonRepository , repositoryPath . toURI ( ) . toURL ( ) . toString ( ) , layout ) ; getLog ( ) . debug ( "Repository: " + localRepository ) ; } catch ( MalformedURLException e ) { throw new MojoExecutionException ( "MalformedURLException: " + e . getMessage ( ) , e ) ; } if ( project . getFile ( ) != null ) { readModel ( project . getFile ( ) ) ; } if ( skip ) { getLog ( ) . info ( "Skipping artifact installation" ) ; return ; } if ( ! installAtEnd ) { installProject ( project ) ; } else { MavenProject lastProject = reactorProjects . get ( reactorProjects . size ( ) - 1 ) ; if ( lastProject . equals ( project ) ) { for ( MavenProject reactorProject : reactorProjects ) { installProject ( reactorProject ) ; } } else { getLog ( ) . info ( "Installing " + project . getGroupId ( ) + ":" + project . getArtifactId ( ) + ":" + project . getVersion ( ) + " at end" ) ; } } } | MoJo execute . | 335 | 4 |
142,992 | private void installProject ( final MavenProject mavenProject ) throws MojoExecutionException { Artifact artifact = mavenProject . getArtifact ( ) ; String packaging = mavenProject . getPackaging ( ) ; boolean isPomArtifact = "pom" . equals ( packaging ) ; try { // skip copying pom to Ceylon repository if ( ! isPomArtifact ) { File file = artifact . getFile ( ) ; if ( file != null && file . isFile ( ) ) { install ( file , artifact , localRepository ) ; File artifactFile = new File ( localRepository . getBasedir ( ) , localRepository . pathOf ( artifact ) ) ; installAdditional ( artifactFile , ".sha1" , CeylonUtil . calculateChecksum ( artifactFile ) , false ) ; String deps = calculateDependencies ( mavenProject ) ; if ( ! "" . equals ( deps ) ) { installAdditional ( artifactFile , "module.properties" , deps , false ) ; installAdditional ( artifactFile , ".module" , deps , true ) ; } } else { throw new MojoExecutionException ( "The packaging for this project did not assign a file to the build artifact" ) ; } } } catch ( Exception e ) { throw new MojoExecutionException ( e . getMessage ( ) , e ) ; } } | Does the actual installation of the project s main artifact . | 294 | 11 |
142,993 | void install ( final File file , final Artifact artifact , final ArtifactRepository repo ) throws MojoExecutionException { File destFile = new File ( repo . getBasedir ( ) + File . separator + repo . getLayout ( ) . pathOf ( artifact ) ) ; destFile . getParentFile ( ) . mkdirs ( ) ; try { FileUtils . copyFile ( file , destFile ) ; } catch ( IOException e ) { throw new MojoExecutionException ( e . getMessage ( ) , e ) ; } } | The actual copy . | 116 | 4 |
142,994 | String calculateDependencies ( final MavenProject proj ) throws MojoExecutionException { Module module = new Module ( new ModuleIdentifier ( CeylonUtil . ceylonModuleBaseName ( proj . getGroupId ( ) , proj . getArtifactId ( ) ) , proj . getVersion ( ) , false , false ) ) ; for ( Dependency dep : proj . getDependencies ( ) ) { if ( dep . getVersion ( ) != null && ! "" . equals ( dep . getVersion ( ) ) ) { if ( ! "test" . equals ( dep . getScope ( ) ) && dep . getSystemPath ( ) == null ) { module . addDependency ( new ModuleIdentifier ( CeylonUtil . ceylonModuleBaseName ( dep . getGroupId ( ) , dep . getArtifactId ( ) ) , dep . getVersion ( ) , dep . isOptional ( ) , false ) ) ; } } else { throw new MojoExecutionException ( "Dependency version for " + dep + " in project " + proj + "could not be determined from the POM. Aborting." ) ; } } StringBuilder builder = new StringBuilder ( CeylonUtil . STRING_BUILDER_SIZE ) ; for ( ModuleIdentifier depMod : module . getDependencies ( ) ) { builder . append ( depMod . getName ( ) ) ; if ( depMod . isOptional ( ) ) { builder . append ( "?" ) ; } builder . append ( "=" ) . append ( depMod . getVersion ( ) ) ; builder . append ( System . lineSeparator ( ) ) ; } return builder . toString ( ) ; } | Determines dependencies from the Maven project model . | 369 | 11 |
142,995 | File findRepoPath ( final String repoAlias ) { if ( "user" . equals ( repoAlias ) ) { return new File ( System . getProperty ( "user.home" ) + CeylonUtil . PATH_SEPARATOR + ".ceylon/repo" ) ; } else if ( "cache" . equals ( repoAlias ) ) { return new File ( System . getProperty ( "user.home" ) + CeylonUtil . PATH_SEPARATOR + ".ceylon/cache" ) ; } else if ( "system" . equals ( repoAlias ) ) { throw new IllegalArgumentException ( "Ceylon Repository 'system' should not be written to" ) ; } else if ( "remote" . equals ( repoAlias ) ) { throw new IllegalArgumentException ( "Ceylon Repository 'remote' should use the ceylon:deploy Maven goal" ) ; } else if ( "local" . equals ( repoAlias ) ) { return new File ( project . getBasedir ( ) , "modules" ) ; } else { throw new IllegalArgumentException ( "Property ceylonRepository must one of 'user', 'cache' or 'local'. Defaults to 'user'" ) ; } } | Find the Ceylon repository path from the alias . | 266 | 10 |
142,996 | void installAdditional ( final File installedFile , final String fileExt , final String payload , final boolean chop ) throws MojoExecutionException { File additionalFile = null ; if ( chop ) { String path = installedFile . getAbsolutePath ( ) ; additionalFile = new File ( path . substring ( 0 , path . lastIndexOf ( ' ' ) ) + fileExt ) ; } else { if ( fileExt . indexOf ( ' ' ) > 0 ) { additionalFile = new File ( installedFile . getParentFile ( ) , fileExt ) ; } else { additionalFile = new File ( installedFile . getAbsolutePath ( ) + fileExt ) ; } } getLog ( ) . debug ( "Installing additional file to " + additionalFile ) ; try { additionalFile . getParentFile ( ) . mkdirs ( ) ; FileUtils . fileWrite ( additionalFile . getAbsolutePath ( ) , "UTF-8" , payload ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "Failed to install additional file to " + additionalFile , e ) ; } } | Installs additional files into the same repo directory as the artifact . | 239 | 13 |
142,997 | public boolean complete ( Number value ) { return root . complete ( new Tree ( ( Tree ) null , null , value ) ) ; } | If not already completed sets the value to the given numeric value . | 28 | 13 |
142,998 | public boolean complete ( String value ) { return root . complete ( new Tree ( ( Tree ) null , null , value ) ) ; } | If not already completed sets the value to the given text . | 28 | 12 |
142,999 | public boolean complete ( Date value ) { return root . complete ( new Tree ( ( Tree ) null , null , value ) ) ; } | If not already completed sets the value to the given date . | 28 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.