Input: Get a value editor for a given target type . [CODESPLIT] public static PropertyEditor getEditor ( final Class < ? > type ) { PropertyEditor editor = findEditor ( type ) ; if ( editor == null ) { throw new RuntimeException ( "No property editor for type: " + type ) ; } return editor ; }


Input: Get a value editor for a given target type . [CODESPLIT] public static PropertyEditor getEditor ( final String typeName ) throws ClassNotFoundException { PropertyEditor editor = findEditor ( typeName ) ; if ( editor == null ) { throw new RuntimeException ( "No property editor for type: " + typeName ) ; } return editor ; }


Input: Register an editor class to be used to editor values of a given target class . [CODESPLIT] public static void registerEditor ( final String typeName , final String editorTypeName ) throws ClassNotFoundException { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; Class < ? > type = loader . loadClass ( typeName ) ; Class < ? > editorType = loader . loadClass ( editorTypeName ) ; PropertyEditorManager . registerEditor ( type , editorType ) ; }


Input: Convert a string value into the true value for typeName using the PropertyEditor associated with typeName . [CODESPLIT] public static Object convertValue ( String text , String typeName ) throws ClassNotFoundException , IntrospectionException { // see if it is a primitive type first Class < ? > typeClass = Classes . getPrimitiveTypeForName ( typeName ) ; if ( typeClass == null ) { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; typeClass = loader . loadClass ( typeName ) ; } PropertyEditor editor = PropertyEditorManager . findEditor ( typeClass ) ; if ( editor == null ) { throw new IntrospectionException ( "No property editor for type=" + typeClass ) ; } editor . setAsText ( text ) ; return editor . getValue ( ) ; }


Input: This method takes the properties found in the given beanProps to the bean using the property editor registered for the property . Any property in beanProps that does not have an associated java bean property will result in an IntrospectionException . The string property values are converted to the true java bean property type using the java bean PropertyEditor framework . If a property in beanProps does not have a PropertyEditor registered it will be ignored . [CODESPLIT] public static void mapJavaBeanProperties ( Object bean , Properties beanProps ) throws IntrospectionException { mapJavaBeanProperties ( bean , beanProps , true ) ; }


Input:
This method takes the properties found in the given beanProps to the bean using the property editor registered for the property . Any property in beanProps that does not have an associated java bean property will result in an IntrospectionException . The string property values are converted to the true java bean property type using the java bean PropertyEditor framework . If a property in beanProps does not have a PropertyEditor registered it will be ignored . [CODESPLIT] public static void mapJavaBeanProperties ( Object bean , Properties beanProps , boolean isStrict ) throws IntrospectionException { HashMap < String , PropertyDescriptor > propertyMap = new HashMap < String , PropertyDescriptor > ( ) ; BeanInfo beanInfo = Introspector . getBeanInfo ( bean . getClass ( ) ) ; PropertyDescriptor [ ] props = beanInfo . getPropertyDescriptors ( ) ; for ( int p = 0 ; p < props . length ; p ++ ) { String fieldName = props [ p ] . getName ( ) ; propertyMap . put ( fieldName , props [ p ] ) ; } boolean trace = log . isTraceEnabled ( ) ; Iterator keys = beanProps . keySet ( ) . iterator ( ) ; if ( trace ) log . trace ( "Mapping properties for bean: " + bean ) ; while ( keys . hasNext ( ) ) { String name = ( String ) keys . next ( ) ; String text = beanProps . getProperty ( name ) ; PropertyDescriptor pd = propertyMap . get ( name ) ; if ( pd == null ) { /* Try the property name with the first char uppercased to handle
            a property name like dLQMaxResent whose expected introspected
            property name would be DLQMaxResent since the JavaBean
            Introspector would view setDLQMaxResent as the setter for a
            DLQMaxResent property whose Introspector.decapitalize() method
            would also return "DLQMaxResent".
            */ if ( name . length ( ) > 1 ) { char first = name . charAt ( 0 ) ; String exName = Character . toUpperCase ( first ) + name . substring ( 1 ) ; pd = propertyMap . get ( exName ) ; // Be lenient and check the other way around, e.g. ServerName -> serverName if ( pd == null ) { exName = Character . toLowerCase ( first ) + name . substring ( 1 ) ; pd = propertyMap . get ( exName ) ; } } if ( pd == null ) { if ( isStrict ) { String msg = "No property found for: " + name + " on JavaBean: " + bean ; throw new IntrospectionException ( msg ) ; } else { // since is not strict, ignore that this property was not found continue ; } } } Method setter = pd . getWriteMethod ( ) ; if ( trace ) log . trace ( "Property editor found for: " + name + ", editor: " + pd + ", setter: " + setter ) ; if ( setter != null ) { Class < ? > ptype = pd . getPropertyType ( ) ; PropertyEditor editor = PropertyEditorManager . findEditor ( ptype ) ; if ( editor == null ) { if ( trace ) log . trace ( "Failed to find property editor for: " + name ) ; } try { editor . setAsText ( text ) ; Object args [ ] = { editor . getValue ( ) } ; setter . invoke ( bean , args ) ; } catch ( Exception e ) { if ( trace ) log . trace ( "Failed to write property" , e ) ; } } } }


Input: Create a server socket on the specified port ( port 0 indicates an anonymous port ) . [CODESPLIT] public ServerSocket createServerSocket ( int port ) throws IOException { ServerSocket activeSocket = new TimeoutServerSocket ( port , backlog , bindAddress ) ; return activeSocket ; }


Input: Retrieve the context classloader for the given thread [CODESPLIT] public ClassLoader getContextClassLoader ( final Thread thread ) { return ( ClassLoader ) AccessController . doPrivileged ( new PrivilegedAction ( ) { public Object run ( ) { return thread . getContextClassLoader ( ) ; } } ) ; }


Input: Detects exception contains is or a ApplicationDeadlockException . [CODESPLIT] public static ApplicationDeadlockException isADE ( Throwable t ) { while ( t != null ) { if ( t instanceof ApplicationDeadlockException ) { return ( ApplicationDeadlockException ) t ; } else { t = t . getCause ( ) ; } } return null ; }


Input: Schedules a new timeout . [CODESPLIT] public Timeout schedule ( long time , TimeoutTarget target ) { if ( cancelled . get ( ) ) throw new IllegalStateException ( "TimeoutFactory has been cancelled" ) ; if ( time < 0 ) throw new IllegalArgumentException ( "Negative time" ) ; if ( target == null ) throw new IllegalArgumentException ( "Null timeout target" ) ; return queue . offer ( time , target ) ; }


Input: Timeout worker method . [CODESPLIT] private void doWork ( ) { while ( cancelled . get ( ) == false ) { TimeoutExt work = queue . take ( ) ; // Do work, if any if ( work != null ) { // Wrap the TimeoutExt with a runnable that invokes the target callback TimeoutWorker worker = new TimeoutWorker ( work ) ; try { threadPool . run ( worker ) ; } catch ( Throwable t ) { // protect the worker thread from pool enqueue errors ThrowableHandler . add ( ThrowableHandler . Type . ERROR , t ) ; } synchronized ( work ) { work . done ( ) ; } } } // TimeoutFactory was cancelled queue . cancel ( ) ; }


Input: Create a subcontext including any intermediate contexts . [CODESPLIT] public static Context createSubcontext ( Context ctx , String name ) throws NamingException { Name n = ctx . getNameParser ( "" ) . parse ( name ) ; return createSubcontext ( ctx , n ) ; }


Input: Unbinds a name from ctx and removes parents if they are empty [CODESPLIT] public static void unbind ( Context ctx , Name name ) throws NamingException { ctx . unbind ( name ) ; //unbind the end node in the name int sz = name . size ( ) ; // walk the tree backwards, stopping at the domain while ( -- sz > 0 ) { Name pname = name . getPrefix ( sz ) ; try { ctx . destroySubcontext ( pname ) ; } catch ( NamingException e ) { log . trace ( "Unable to remove context " + pname , e ) ; break ; } } }


Input: Lookup an object in the default initial context [CODESPLIT] public static Object lookup ( String name , Class < ? > clazz ) throws Exception { InitialContext ctx = new InitialContext ( ) ; try { return lookup ( ctx , name , clazz ) ; } finally { ctx . close ( ) ; } }


Input: Lookup an object in the given context [CODESPLIT] public static Object lookup ( Context context , String name , Class clazz ) throws Exception { Object result = context . lookup ( name ) ; checkObject ( context , name , result , clazz ) ; return result ; }


Input: Lookup an object in the given context [CODESPLIT] public static Object lookup ( Context context , Name name , Class clazz ) throws Exception { Object result = context . lookup ( name ) ; checkObject ( context , name . toString ( ) , result , clazz ) ; return result ; }


Input: Create a link [CODESPLIT] public static void createLinkRef ( String fromName , String toName ) throws NamingException { InitialContext ctx = new InitialContext ( ) ; createLinkRef ( ctx , fromName , toName ) ; }


Input: Create a link [CODESPLIT] public static void createLinkRef ( Context ctx , String fromName , String toName ) throws NamingException { LinkRef link = new LinkRef ( toName ) ; Context fromCtx = ctx ; Name name = ctx . getNameParser ( "" ) . parse ( fromName ) ; String atom = name . get ( name . size ( ) - 1 ) ; for ( int n = 0 ; n < name . size ( ) - 1 ; n ++ ) { String comp = name . get ( n ) ; try { fromCtx = ( Context ) fromCtx . lookup ( comp ) ; } catch ( NameNotFoundException e ) { fromCtx = fromCtx . createSubcontext ( comp ) ; } } log . debug ( "atom: " + atom ) ; log . debug ( "link: " + link ) ; fromCtx . rebind ( atom , link ) ; log . debug ( "Bound link " + fromName + " to " + toName ) ; }


Input: Remove the link ref [CODESPLIT] public static void removeLinkRef ( String name ) throws NamingException { InitialContext ctx = new InitialContext ( ) ; removeLinkRef ( ctx , name ) ; }


Input: Remove the link ref [CODESPLIT] public static void removeLinkRef ( Context ctx , String name ) throws NamingException { log . debug ( "Unbinding link " + name ) ; ctx . unbind ( name ) ; }


Input: Checks an object implements the given class [CODESPLIT] protected static void checkObject ( Context context , String name , Object object , Class clazz ) throws Exception { Class objectClass = object . getClass ( ) ; if ( clazz . isAssignableFrom ( objectClass ) == false ) { StringBuffer buffer = new StringBuffer ( 100 ) ; buffer . append ( "Object at '" ) . append ( name ) ; buffer . append ( "' in context " ) . append ( context . getEnvironment ( ) ) ; buffer . append ( " is not an instance of " ) ; appendClassInfo ( buffer , clazz ) ; buffer . append ( " object class is " ) ; appendClassInfo ( buffer , object . getClass ( ) ) ; throw new ClassCastException ( buffer . toString ( ) ) ; } }


Input: Append Class Info [CODESPLIT] protected static void appendClassInfo ( StringBuffer buffer , Class clazz ) { buffer . append ( "[class=" ) . append ( clazz . getName ( ) ) ; buffer . append ( " classloader=" ) . append ( clazz . getClassLoader ( ) ) ; buffer . append ( " interfaces={" ) ; Class [ ] interfaces = clazz . getInterfaces ( ) ; for ( int i = 0 ; i < interfaces . length ; ++ i ) { if ( i > 0 ) buffer . append ( ", " ) ; buffer . append ( "interface=" ) . append ( interfaces [ i ] . getName ( ) ) ; buffer . append ( " classloader=" ) . append ( interfaces [ i ] . getClassLoader ( ) ) ; } buffer . append ( "}]" ) ; }


Input: Lookup an allowed transition given its name . [CODESPLIT] public Transition getTransition ( String name ) { Transition t = ( Transition ) allowedTransitions . get ( name ) ; return t ; }


Input: Load the properties from the propertyFile and build the resources from it . [CODESPLIT] private synchronized void readProperties ( ) { try { propertyFileURI = CatalogManager . class . getResource ( "/" + propertyFile ) ; InputStream in = CatalogManager . class . getResourceAsStream ( "/" + propertyFile ) ; if ( in == null ) { if ( ! ignoreMissingProperties ) { System . err . println ( "Cannot find " + propertyFile ) ; // there's no reason to give this warning more than once ignoreMissingProperties = true ; } return ; } resources = new PropertyResourceBundle ( in ) ; } catch ( MissingResourceException mre ) { if ( ! ignoreMissingProperties ) { System . err . println ( "Cannot read " + propertyFile ) ; } } catch ( java . io . IOException e ) { if ( ! ignoreMissingProperties ) { System . err . println ( "Failure trying to read " + propertyFile ) ; } } // This is a bit of a hack. After we've successfully read the properties, // use them to set the default debug level, if the user hasn't already set // the default debug level. if ( verbosity == null ) { try { String verbStr = resources . getString ( "verbosity" ) ; int verb = Integer . parseInt ( verbStr . trim ( ) ) ; debug . setDebug ( verb ) ; verbosity = new Integer ( verb ) ; } catch ( Exception e ) { // nop } } }


Input: Obtain the verbosity setting from the properties . [CODESPLIT] private int queryVerbosity ( ) { String verbStr = System . getProperty ( pVerbosity ) ; if ( verbStr == null ) { if ( resources == null ) readProperties ( ) ; if ( resources == null ) return defaultVerbosity ; try { verbStr = resources . getString ( "verbosity" ) ; } catch ( MissingResourceException e ) { return defaultVerbosity ; } } try { int verb = Integer . parseInt ( verbStr . trim ( ) ) ; return verb ; } catch ( Exception e ) { System . err . println ( "Cannot parse verbosity: \"" + verbStr + "\"" ) ; return defaultVerbosity ; } }


Input: Obtain the relativeCatalogs setting from the properties . [CODESPLIT] private boolean queryRelativeCatalogs ( ) { if ( resources == null ) readProperties ( ) ; if ( resources == null ) return defaultRelativeCatalogs ; try { String allow = resources . getString ( "relative-catalogs" ) ; return ( allow . equalsIgnoreCase ( "true" ) || allow . equalsIgnoreCase ( "yes" ) || allow . equalsIgnoreCase ( "1" ) ) ; } catch ( MissingResourceException e ) { return defaultRelativeCatalogs ; } }


Input: Obtain the list of catalog files from the properties . [CODESPLIT] private String queryCatalogFiles ( ) { String catalogList = System . getProperty ( pFiles ) ; fromPropertiesFile = false ; if ( catalogList == null ) { if ( resources == null ) readProperties ( ) ; if ( resources != null ) { try { catalogList = resources . getString ( "catalogs" ) ; fromPropertiesFile = true ; } catch ( MissingResourceException e ) { System . err . println ( propertyFile + ": catalogs not found." ) ; catalogList = null ; } } } if ( catalogList == null ) { catalogList = defaultCatalogFiles ; } return catalogList ; }


Input: Return the current list of catalog files . [CODESPLIT] public Vector getCatalogFiles ( ) { if ( catalogFiles == null ) { catalogFiles = queryCatalogFiles ( ) ; } StringTokenizer files = new StringTokenizer ( catalogFiles , ";" ) ; Vector catalogs = new Vector ( ) ; while ( files . hasMoreTokens ( ) ) { String catalogFile = files . nextToken ( ) ; URL absURI = null ; if ( fromPropertiesFile && ! relativeCatalogs ( ) ) { try { absURI = new URL ( propertyFileURI , catalogFile ) ; catalogFile = absURI . toString ( ) ; } catch ( MalformedURLException mue ) { absURI = null ; } } catalogs . add ( catalogFile ) ; } return catalogs ; }


Input: Obtain the preferPublic setting from the properties . [CODESPLIT] private boolean queryPreferPublic ( ) { String prefer = System . getProperty ( pPrefer ) ; if ( prefer == null ) { if ( resources == null ) readProperties ( ) ; if ( resources == null ) return defaultPreferPublic ; try { prefer = resources . getString ( "prefer" ) ; } catch ( MissingResourceException e ) { return defaultPreferPublic ; } } if ( prefer == null ) { return defaultPreferPublic ; } return ( prefer . equalsIgnoreCase ( "public" ) ) ; }


Input: Obtain the static - catalog setting from the properties . [CODESPLIT] private boolean queryUseStaticCatalog ( ) { String staticCatalog = System . getProperty ( pStatic ) ; if ( useStaticCatalog == null ) { if ( resources == null ) readProperties ( ) ; if ( resources == null ) return defaultUseStaticCatalog ; try { staticCatalog = resources . getString ( "static-catalog" ) ; } catch ( MissingResourceException e ) { return defaultUseStaticCatalog ; } } if ( staticCatalog == null ) { return defaultUseStaticCatalog ; } return ( staticCatalog . equalsIgnoreCase ( "true" ) || staticCatalog . equalsIgnoreCase ( "yes" ) || staticCatalog . equalsIgnoreCase ( "1" ) ) ; }


Input: @return a new catalog instance . [CODESPLIT] public Catalog getPrivateCatalog ( ) { Catalog catalog = staticCatalog ; if ( useStaticCatalog == null ) { useStaticCatalog = new Boolean ( getUseStaticCatalog ( ) ) ; } if ( catalog == null || ! useStaticCatalog . booleanValue ( ) ) { try { String catalogClassName = getCatalogClassName ( ) ; if ( catalogClassName == null ) { catalog = new Catalog ( ) ; } else { try { catalog = ( Catalog ) Class . forName ( catalogClassName ) . newInstance ( ) ; } catch ( ClassNotFoundException cnfe ) { debug . message ( 1 , "Catalog class named '" + catalogClassName + "' could not be found. Using default." ) ; catalog = new Catalog ( ) ; } catch ( ClassCastException cnfe ) { debug . message ( 1 , "Class named '" + catalogClassName + "' is not a Catalog. Using default." ) ; catalog = new Catalog ( ) ; } } catalog . setCatalogManager ( this ) ; catalog . setupReaders ( ) ; catalog . loadSystemCatalogs ( ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } if ( useStaticCatalog . booleanValue ( ) ) { staticCatalog = catalog ; } } return catalog ; }


Input: @return a catalog instance . [CODESPLIT] public Catalog getCatalog ( ) { Catalog catalog = staticCatalog ; if ( useStaticCatalog == null ) { useStaticCatalog = new Boolean ( getUseStaticCatalog ( ) ) ; } if ( catalog == null || ! useStaticCatalog . booleanValue ( ) ) { catalog = getPrivateCatalog ( ) ; if ( useStaticCatalog . booleanValue ( ) ) { staticCatalog = catalog ; } } return catalog ; }


Input: <p > Obtain the oasisXMLCatalogPI setting from the properties . < / p > [CODESPLIT] public boolean queryAllowOasisXMLCatalogPI ( ) { String allow = System . getProperty ( pAllowPI ) ; if ( allow == null ) { if ( resources == null ) readProperties ( ) ; if ( resources == null ) return defaultOasisXMLCatalogPI ; try { allow = resources . getString ( "allow-oasis-xml-catalog-pi" ) ; } catch ( MissingResourceException e ) { return defaultOasisXMLCatalogPI ; } } if ( allow == null ) { return defaultOasisXMLCatalogPI ; } return ( allow . equalsIgnoreCase ( "true" ) || allow . equalsIgnoreCase ( "yes" ) || allow . equalsIgnoreCase ( "1" ) ) ; }


Input: Obtain the Catalog class name setting from the properties . @return the name [CODESPLIT] public String queryCatalogClassName ( ) { String className = System . getProperty ( pClassname ) ; if ( className == null ) { if ( resources == null ) readProperties ( ) ; if ( resources == null ) return null ; try { return resources . getString ( "catalog-class-name" ) ; } catch ( MissingResourceException e ) { return null ; } } return className ; }


Input: SAX resolveEntity API . [CODESPLIT] public InputSource resolveEntity ( String publicId , String systemId ) { String resolved = null ; if ( systemId != null && systemMap . containsKey ( systemId ) ) { resolved = ( String ) systemMap . get ( systemId ) ; } else if ( publicId != null && publicMap . containsKey ( publicId ) ) { resolved = ( String ) publicMap . get ( publicId ) ; } if ( resolved != null ) { try { InputSource iSource = new InputSource ( resolved ) ; iSource . setPublicId ( publicId ) ; // Ideally this method would not attempt to open the // InputStream, but there is a bug (in Xerces, at least) // that causes the parser to mistakenly open the wrong // system identifier if the returned InputSource does // not have a byteStream. // // It could be argued that we still shouldn't do this here, // but since the purpose of calling the entityResolver is // almost certainly to open the input stream, it seems to // do little harm. // URL url = new URL ( resolved ) ; InputStream iStream = url . openStream ( ) ; iSource . setByteStream ( iStream ) ; return iSource ; } catch ( Exception e ) { // FIXME: silently fail? return null ; } } return null ; }


Input: Transformer resolve API . [CODESPLIT] public Source resolve ( String href , String base ) throws TransformerException { String uri = href ; int hashPos = href . indexOf ( "#" ) ; if ( hashPos >= 0 ) { uri = href . substring ( 0 , hashPos ) ; } String result = null ; if ( href != null && uriMap . containsKey ( href ) ) { result = ( String ) uriMap . get ( href ) ; } if ( result == null ) { try { URL url = null ; if ( base == null ) { url = new URL ( uri ) ; result = url . toString ( ) ; } else { URL baseURL = new URL ( base ) ; url = ( href . length ( ) == 0 ? baseURL : new URL ( baseURL , uri ) ) ; result = url . toString ( ) ; } } catch ( java . net . MalformedURLException mue ) { // try to make an absolute URI from the current base String absBase = makeAbsolute ( base ) ; if ( ! absBase . equals ( base ) ) { // don't bother if the absBase isn't different! return resolve ( href , absBase ) ; } else { throw new TransformerException ( "Malformed URL " + href + "(base " + base + ")" , mue ) ; } } } SAXSource source = new SAXSource ( ) ; source . setInputSource ( new InputSource ( result ) ) ; return source ; }


Input: Attempt to construct an absolute URI [CODESPLIT] private String makeAbsolute ( String uri ) { if ( uri == null ) { uri = "" ; } try { URL url = new URL ( uri ) ; return url . toString ( ) ; } catch ( MalformedURLException mue ) { String dir = System . getProperty ( "user.dir" ) ; String file = "" ; if ( dir . endsWith ( "/" ) ) { file = "file://" + dir + uri ; } else { file = "file://" + dir + "/" + uri ; } try { URL fileURL = new URL ( file ) ; return fileURL . toString ( ) ; } catch ( MalformedURLException mue2 ) { // bail return uri ; } } }


Input: Use the thread context class loader to resolve the class [CODESPLIT] protected Class < ? > resolveClass ( ObjectStreamClass v ) throws IOException , ClassNotFoundException { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; String className = v . getName ( ) ; try { // JDK 6, by default, only supports array types (ex. [[B)  using Class.forName() return Class . forName ( className , false , loader ) ; } catch ( ClassNotFoundException cnfe ) { Class cl = primClasses . get ( className ) ; if ( cl == null ) throw cnfe ; else return cl ; } }


Input: Get the <tt > PropertyDescriptor< / tt > for the given bean property name . [CODESPLIT] private PropertyDescriptor getPropertyDescriptor ( final String beanPropertyName ) throws IntrospectionException { Class < ? > instanceType = instance . getClass ( ) ; BeanInfo beanInfo = Introspector . getBeanInfo ( instanceType ) ; PropertyDescriptor descriptors [ ] = beanInfo . getPropertyDescriptors ( ) ; PropertyDescriptor descriptor = null ; for ( int i = 0 ; i < descriptors . length ; i ++ ) { if ( descriptors [ i ] . getName ( ) . equals ( beanPropertyName ) ) { descriptor = descriptors [ i ] ; break ; } } return descriptor ; }


Input: Coerce and invoke the property setter method on the instance . [CODESPLIT] protected void invokeSetter ( String value ) { try { // coerce value to field type Class < ? > type = descriptor . getPropertyType ( ) ; PropertyEditor editor = PropertyEditors . findEditor ( type ) ; editor . setAsText ( value ) ; Object coerced = editor . getValue ( ) ; // System.out.println("type: " + type); // System.out.println("coerced: " + coerced); // invoke the setter method setter . invoke ( instance , new Object [ ] { coerced } ) ; } catch ( InvocationTargetException e ) { Throwable target = e . getTargetException ( ) ; if ( target instanceof PropertyException ) { throw ( PropertyException ) target ; } else { throw new PropertyException ( target ) ; } } catch ( Exception e ) { throw new PropertyException ( e ) ; } }


Input: Notifies that this listener was bound to a property . [CODESPLIT] public void propertyBound ( final PropertyMap map ) { // only set the field if the map contains the property already if ( map . containsProperty ( propertyName ) ) { invokeSetter ( map . getProperty ( propertyName ) ) ; } }


Input: Returns the prefix part of a QName or the empty string ( not null ) if the name has no prefix . [CODESPLIT] public static String getPrefix ( Element element ) { String name = element . getTagName ( ) ; String prefix = "" ; if ( name . indexOf ( ' ' ) > 0 ) { prefix = name . substring ( 0 , name . indexOf ( ' ' ) ) ; } return prefix ; }


Input: Returns the localname part of a QName which is the whole name if it has no prefix . [CODESPLIT] public static String getLocalName ( Element element ) { String name = element . getTagName ( ) ; if ( name . indexOf ( ' ' ) > 0 ) { name = name . substring ( name . indexOf ( ' ' ) + 1 ) ; } return name ; }


Input: Returns the namespace URI for the specified prefix at the specified context node . [CODESPLIT] public static String getNamespaceURI ( Node node , String prefix ) { if ( node == null || node . getNodeType ( ) != Node . ELEMENT_NODE ) { return null ; } if ( prefix . equals ( "" ) ) { if ( ( ( Element ) node ) . hasAttribute ( "xmlns" ) ) { return ( ( Element ) node ) . getAttribute ( "xmlns" ) ; } } else { String nsattr = "xmlns:" + prefix ; if ( ( ( Element ) node ) . hasAttribute ( nsattr ) ) { return ( ( Element ) node ) . getAttribute ( nsattr ) ; } } return getNamespaceURI ( node . getParentNode ( ) , prefix ) ; }


Input: Returns the namespace URI for the namespace to which the element belongs . [CODESPLIT] public static String getNamespaceURI ( Element element ) { String prefix = getPrefix ( element ) ; return getNamespaceURI ( element , prefix ) ; }


Input: Map the argument text into and Integer using Integer . valueOf . [CODESPLIT] public void setAsText ( final String text ) { if ( PropertyEditors . isNull ( text ) ) { setValue ( null ) ; return ; } Object newValue = Long . valueOf ( text ) ; setValue ( newValue ) ; }


Input: Create a list from an enumeration [CODESPLIT] public static List list ( Enumeration e ) { ArrayList result = new ArrayList ( ) ; while ( e . hasMoreElements ( ) ) result . add ( e . nextElement ( ) ) ; return result ; }


Input: Get an input stream for the given filename . [CODESPLIT] protected InputStream getInputStream ( String filename ) throws IOException { File file = new File ( filename ) ; return new FileInputStream ( file ) ; }


Input: Load properties from a file into a properties map . [CODESPLIT] protected void loadProperties ( Properties props , String filename ) throws IOException { if ( filename == null ) throw new NullArgumentException ( "filename" ) ; if ( filename . equals ( "" ) ) throw new IllegalArgumentException ( "filename" ) ; InputStream in = new BufferedInputStream ( getInputStream ( filename ) ) ; props . load ( in ) ; in . close ( ) ; }


Input: Read properties from each specified filename [CODESPLIT] public Map readProperties ( ) throws PropertyException , IOException { Properties props = new Properties ( ) ; // load each specified property file for ( int i = 0 ; i < filenames . length ; i ++ ) { loadProperties ( props , filenames [ i ] ) ; } return props ; }


Input: Add an edge to the vertex . If edge . from is this vertex its an outgoing edge . If edge . to is this vertex its an incoming edge . If neither from or to is this vertex the edge is not added . [CODESPLIT] public boolean addEdge ( Edge < T > e ) { if ( e . getFrom ( ) == this ) outgoingEdges . add ( e ) ; else if ( e . getTo ( ) == this ) incomingEdges . add ( e ) ; else return false ; return true ; }


Input: Add an outgoing edge ending at to . [CODESPLIT] public void addOutgoingEdge ( Vertex < T > to , int cost ) { Edge < T > out = new Edge < T > ( this , to , cost ) ; outgoingEdges . add ( out ) ; }


Input: Add an incoming edge starting at from [CODESPLIT] public void addIncomingEdge ( Vertex < T > from , int cost ) { Edge < T > out = new Edge < T > ( this , from , cost ) ; incomingEdges . add ( out ) ; }


Input: Check the vertex for either an incoming or outgoing edge mathcing e . [CODESPLIT] public boolean hasEdge ( Edge < T > e ) { if ( e . getFrom ( ) == this ) return outgoingEdges . contains ( e ) ; else if ( e . getTo ( ) == this ) return incomingEdges . contains ( e ) ; else return false ; }


Input: Remove an edge from this vertex [CODESPLIT] public boolean remove ( Edge < T > e ) { if ( e . getFrom ( ) == this ) outgoingEdges . remove ( e ) ; else if ( e . getTo ( ) == this ) incomingEdges . remove ( e ) ; else return false ; return true ; }


Input: Search the outgoing edges looking for an edge whose s edge . to == dest . [CODESPLIT] public Edge < T > findEdge ( Vertex < T > dest ) { for ( Edge < T > e : outgoingEdges ) { if ( e . getTo ( ) == dest ) return e ; } return null ; }


Input: Search the outgoing edges for a match to e . [CODESPLIT] public Edge < T > findEdge ( Edge < T > e ) { if ( outgoingEdges . contains ( e ) ) return e ; else return null ; }


Input: What is the cost from this vertext to the dest vertex . [CODESPLIT] public int cost ( Vertex < T > dest ) { if ( dest == this ) return 0 ; Edge < T > e = findEdge ( dest ) ; int cost = Integer . MAX_VALUE ; if ( e != null ) cost = e . getCost ( ) ; return cost ; }


Input: <P > This function will create a Jar archive containing the src file / directory . The archive will be written to the specified OutputStream . < / P > [CODESPLIT] public static void jar ( OutputStream out , File src ) throws IOException { jar ( out , new File [ ] { src } , null , null , null ) ; }


Input: <P > This function will create a Jar archive containing the src file / directory . The archive will be written to the specified OutputStream . Directories are processed recursively applying the specified filter if it exists . [CODESPLIT] public static void jar ( OutputStream out , File [ ] src , FileFilter filter ) throws IOException { jar ( out , src , filter , null , null ) ; }


Input: <P > This function will create a Jar archive containing the src file / directory . The archive will be written to the specified OutputStream . Directories are processed recursively applying the specified filter if it exists . [CODESPLIT] public static void jar ( OutputStream out , File [ ] src , FileFilter filter , String prefix , Manifest man ) throws IOException { for ( int i = 0 ; i < src . length ; i ++ ) { if ( ! src [ i ] . exists ( ) ) { throw new FileNotFoundException ( src . toString ( ) ) ; } } JarOutputStream jout ; if ( man == null ) { jout = new JarOutputStream ( out ) ; } else { jout = new JarOutputStream ( out , man ) ; } if ( prefix != null && prefix . length ( ) > 0 && ! prefix . equals ( "/" ) ) { // strip leading '/' if ( prefix . charAt ( 0 ) == ' ' ) { prefix = prefix . substring ( 1 ) ; } // ensure trailing '/' if ( prefix . charAt ( prefix . length ( ) - 1 ) != ' ' ) { prefix = prefix + "/" ; } } else { prefix = "" ; } JarInfo info = new JarInfo ( jout , filter ) ; for ( int i = 0 ; i < src . length ; i ++ ) { jar ( src [ i ] , prefix , info ) ; } jout . close ( ) ; }


Input: This recursive method writes all matching files and directories to the jar output stream . [CODESPLIT] private static void jar ( File src , String prefix , JarInfo info ) throws IOException { JarOutputStream jout = info . out ; if ( src . isDirectory ( ) ) { // create / init the zip entry prefix = prefix + src . getName ( ) + "/" ; ZipEntry entry = new ZipEntry ( prefix ) ; entry . setTime ( src . lastModified ( ) ) ; entry . setMethod ( JarOutputStream . STORED ) ; entry . setSize ( 0L ) ; entry . setCrc ( 0L ) ; jout . putNextEntry ( entry ) ; jout . closeEntry ( ) ; // process the sub-directories File [ ] files = src . listFiles ( info . filter ) ; for ( int i = 0 ; i < files . length ; i ++ ) { jar ( files [ i ] , prefix , info ) ; } } else if ( src . isFile ( ) ) { // get the required info objects byte [ ] buffer = info . buffer ; // create / init the zip entry ZipEntry entry = new ZipEntry ( prefix + src . getName ( ) ) ; entry . setTime ( src . lastModified ( ) ) ; jout . putNextEntry ( entry ) ; // dump the file FileInputStream in = new FileInputStream ( src ) ; int len ; while ( ( len = in . read ( buffer , 0 , buffer . length ) ) != - 1 ) { jout . write ( buffer , 0 , len ) ; } in . close ( ) ; jout . closeEntry ( ) ; } }


Input: Given a URL check if its a jar url ( jar : <url > ! / archive ) and if it is extract the archive entry into the given dest directory and return a file URL to its location . If jarURL is not a jar url then it is simply returned as the URL for the jar . [CODESPLIT] public static URL extractNestedJar ( URL jarURL , File dest ) throws IOException { // This may not be a jar URL so validate the protocol  if ( jarURL . getProtocol ( ) . equals ( "jar" ) == false ) return jarURL ; String destPath = dest . getAbsolutePath ( ) ; URLConnection urlConn = jarURL . openConnection ( ) ; JarURLConnection jarConn = ( JarURLConnection ) urlConn ; // Extract the archive to dest/jarName-contents/archive String parentArchiveName = jarConn . getJarFile ( ) . getName ( ) ; // Find the longest common prefix between destPath and parentArchiveName int length = Math . min ( destPath . length ( ) , parentArchiveName . length ( ) ) ; int n = 0 ; while ( n < length ) { char a = destPath . charAt ( n ) ; char b = parentArchiveName . charAt ( n ) ; if ( a != b ) break ; n ++ ; } // Remove any common prefix from parentArchiveName parentArchiveName = parentArchiveName . substring ( n ) ; File archiveDir = new File ( dest , parentArchiveName + "-contents" ) ; if ( archiveDir . exists ( ) == false && archiveDir . mkdirs ( ) == false ) throw new IOException ( "Failed to create contents directory for archive, path=" + archiveDir . getAbsolutePath ( ) ) ; String archiveName = jarConn . getEntryName ( ) ; File archiveFile = new File ( archiveDir , archiveName ) ; File archiveParentDir = archiveFile . getParentFile ( ) ; if ( archiveParentDir . exists ( ) == false && archiveParentDir . mkdirs ( ) == false ) throw new IOException ( "Failed to create parent directory for archive, path=" + archiveParentDir . getAbsolutePath ( ) ) ; InputStream archiveIS = jarConn . getInputStream ( ) ; FileOutputStream fos = new FileOutputStream ( archiveFile ) ; BufferedOutputStream bos = new BufferedOutputStream ( fos ) ; byte [ ] buffer = new byte [ 4096 ] ; int read ; while ( ( read = archiveIS . read ( buffer ) ) > 0 ) { bos . write ( buffer , 0 , read ) ; } archiveIS . close ( ) ; bos . close ( ) ; // Return the file url to the extracted jar return archiveFile . toURL ( ) ; }


Input: Check if there are more elements . [CODESPLIT] public boolean hasNext ( ) { for ( ; index < iters . length ; index ++ ) { if ( iters [ index ] != null && iters [ index ] . hasNext ( ) ) { return true ; } } return false ; }


Input: Forwards an event into state machine . State machine will deliver the event to a handler methods responsible for its processing . If there is no handler method found then event gets silently ignored and this call has no effect . [CODESPLIT] public void fireEvent ( Object event ) { if ( event == null ) { throw new IllegalArgumentException ( "Event must not be null." ) ; } mTaskQueue . offer ( Task . obtainTask ( Task . CODE_FIRE_EVENT , event , - 1 ) ) ; if ( ! mQueueProcessed ) processTaskQueue ( ) ; }


Input: Moves state machine in a new given state . If state machine is already in that state then this method has no effect . Otherwise if exists <code > Type . OnExit< / code > event handler for the current state is called first and then <code > Type . OnEntry< / code > event handler for new state is called . [CODESPLIT] public void transitionTo ( int state ) { mTaskQueue . offer ( Task . obtainTask ( Task . CODE_TRANSITION , null , state ) ) ; if ( ! mQueueProcessed ) processTaskQueue ( ) ; }


Input: Enables traces and sets tag to be used for <code > Log . d () < / code > output . <code > TinyMachine< / code > will trace all processed events and state transitions including events for which handlers in current state are missed . [CODESPLIT] public TinyMachine setTraceTag ( String tag ) { mTraceTag = tag ; if ( mTraceTag != null ) { log ( "current state" , null ) ; } return this ; }


Input: -- implementation [CODESPLIT] private void processTaskQueue ( ) { mQueueProcessed = true ; try { Task task ; while ( ( task = mTaskQueue . poll ( ) ) != null ) { switch ( task . code ) { case Task . CODE_FIRE_EVENT : { Object event = task . event ; final Class < ? extends Object > clazz = event . getClass ( ) ; fire ( clazz , event , StateHandler . STATE_ANY ) ; fire ( clazz , event , mCurrentState ) ; break ; } case Task . CODE_TRANSITION : { int state = task . state ; if ( mCurrentState != state ) { fire ( OnExit . class , null , StateHandler . STATE_ANY ) ; fire ( OnExit . class , null , mCurrentState ) ; mCurrentState = state ; if ( mTraceTag != null ) { log ( "new state" , null ) ; } fire ( OnEntry . class , null , StateHandler . STATE_ANY ) ; fire ( OnEntry . class , null , mCurrentState ) ; } break ; } default : throw new IllegalStateException ( "wrong code: " + task . code ) ; } task . recycle ( ) ; } } finally { mQueueProcessed = false ; } }


Input: Installs the complete JvmTypeProvider including index access into the { @link ResourceSet } . The lookup classpath is enhanced with the given tmp directory . [CODESPLIT] @ Deprecated protected void installJvmTypeProvider ( XtextResourceSet resourceSet , File tmpClassDirectory ) { internalInstallJvmTypeProvider ( resourceSet , tmpClassDirectory , false ) ; }


Input: Installs the JvmTypeProvider optionally including index access into the { [CODESPLIT] protected void installJvmTypeProvider ( XtextResourceSet resourceSet , File tmpClassDirectory , boolean skipIndexLookup ) { if ( skipIndexLookup ) { internalInstallJvmTypeProvider ( resourceSet , tmpClassDirectory , skipIndexLookup ) ; } else { // delegate to the deprecated signature in case it was overridden by // clients installJvmTypeProvider ( resourceSet , tmpClassDirectory ) ; } }


Input: Performs the actual installation of the JvmTypeProvider . [CODESPLIT] private void internalInstallJvmTypeProvider ( XtextResourceSet resourceSet , File tmpClassDirectory , boolean skipIndexLookup ) { Iterable < String > classPathEntries = concat ( getClassPathEntries ( ) , getSourcePathDirectories ( ) , asList ( tmpClassDirectory . toString ( ) ) ) ; classPathEntries = filter ( classPathEntries , new Predicate < String > ( ) { public boolean apply ( String input ) { return ! Strings . isEmpty ( input . trim ( ) ) ; } } ) ; Function < String , URL > toUrl = new Function < String , URL > ( ) { public URL apply ( String from ) { try { return new File ( from ) . toURI ( ) . toURL ( ) ; } catch ( MalformedURLException e ) { throw new RuntimeException ( e ) ; } } } ; Iterable < URL > classPathUrls = Iterables . transform ( classPathEntries , toUrl ) ; log . debug ( "classpath used for Struct compilation : " + classPathUrls ) ; ClassLoader parentClassLoader ; if ( useCurrentClassLoaderAsParent ) { parentClassLoader = currentClassLoader ; } else { if ( isEmpty ( bootClassPath ) ) { parentClassLoader = ClassLoader . getSystemClassLoader ( ) . getParent ( ) ; } else { Iterable < URL > bootClassPathUrls = Iterables . transform ( getBootClassPathEntries ( ) , toUrl ) ; parentClassLoader = new BootClassLoader ( toArray ( bootClassPathUrls , URL . class ) ) ; } } ClassLoader urlClassLoader = new URLClassLoader ( toArray ( classPathUrls , URL . class ) , parentClassLoader ) ; new ClasspathTypeProvider ( urlClassLoader , resourceSet , skipIndexLookup ? null : indexedJvmTypeAccess ) ; resourceSet . setClasspathURIContext ( urlClassLoader ) ; // for annotation processing we need to have the compiler's classpath as // a parent. URLClassLoader urlClassLoaderForAnnotationProcessing = new URLClassLoader ( toArray ( classPathUrls , URL . class ) , currentClassLoader ) ; resourceSet . eAdapters ( ) . add ( new ProcessorClassloaderAdapter ( urlClassLoaderForAnnotationProcessing ) ) ; }


Input: version 2 . 2 . x [CODESPLIT] protected static boolean cleanFolder ( File parentFolder , FileFilter filter , boolean continueOnError , boolean deleteParentFolder ) { if ( ! parentFolder . exists ( ) ) { return true ; } if ( filter == null ) filter = ACCEPT_ALL_FILTER ; log . debug ( "Cleaning folder " + parentFolder . toString ( ) ) ; final File [ ] contents = parentFolder . listFiles ( filter ) ; for ( int j = 0 ; j < contents . length ; j ++ ) { final File file = contents [ j ] ; if ( file . isDirectory ( ) ) { if ( ! cleanFolder ( file , filter , continueOnError , true ) && ! continueOnError ) return false ; } else { if ( ! file . delete ( ) ) { log . warn ( "Couldn't delete " + file . getAbsolutePath ( ) ) ; if ( ! continueOnError ) return false ; } } } if ( deleteParentFolder ) { if ( parentFolder . list ( ) . length == 0 && ! parentFolder . delete ( ) ) { log . warn ( "Couldn't delete " + parentFolder . getAbsolutePath ( ) ) ; return false ; } } return true ; }


Input: Dispatch the given action . Dispatching is always done on the JavaFX application thread even if this method is called from another thread . [CODESPLIT] public void dispatchOnFxThread ( Action action ) { if ( Platform . isFxApplicationThread ( ) ) { actionStream . push ( action ) ; } else { Platform . runLater ( ( ) -> actionStream . push ( action ) ) ; } }


Input: A filtered event - stream of actions of the given type . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) < T extends Action > EventStream < T > getActionStream ( Class < T > actionType ) { return Dispatcher . getInstance ( ) . getActionStream ( ) . filter ( action -> action . getClass ( ) . equals ( actionType ) ) . map ( action -> ( T ) action ) ; }


Input: Taken from mvvmFX [CODESPLIT] private static String createFxmlPath ( Class < ? > viewType ) { final StringBuilder pathBuilder = new StringBuilder ( ) ; pathBuilder . append ( "/" ) ; if ( viewType . getPackage ( ) != null ) { pathBuilder . append ( viewType . getPackage ( ) . getName ( ) . replaceAll ( "\\." , "/" ) ) ; pathBuilder . append ( "/" ) ; } pathBuilder . append ( viewType . getSimpleName ( ) ) ; pathBuilder . append ( ".fxml" ) ; return pathBuilder . toString ( ) ; }


Input: Update all views by invoking the update function ( { [CODESPLIT] public void updateViews ( ) { cache . entrySet ( ) . forEach ( entry -> updateFunction . accept ( entry . getKey ( ) , entry . getValue ( ) . getController ( ) ) ) ; }


Input: Update all views that match the given predicate by invoking the update function ( { [CODESPLIT] public void updateViews ( Predicate < T > predicate ) { cache . entrySet ( ) . stream ( ) . filter ( entry -> predicate . test ( entry . getKey ( ) ) ) . forEach ( entry -> updateFunction . accept ( entry . getKey ( ) , entry . getValue ( ) . getController ( ) ) ) ; }


Input: This method can be used to subscribe to actions of a given type . The subscription is managed by the { @link Dispatcher } . [CODESPLIT] protected < T extends Action > void subscribe ( Class < T > actionType , Consumer < T > actionConsumer ) { Dispatcher . getInstance ( ) . getActionStream ( actionType ) . subscribe ( actionConsumer ) ; }


Input: Return an appropriate { [CODESPLIT] public Logger getLogger ( String name ) { String tag = name == null ? ANONYMOUS_TAG : name ; Logger logger = loggerMap . get ( tag ) ; if ( logger == null ) { Logger newInstance = new TimberAndroidLoggerAdapter ( tag ) ; Logger oldInstance = loggerMap . putIfAbsent ( tag , newInstance ) ; logger = oldInstance == null ? newInstance : oldInstance ; } return logger ; }


Input: Log a message at level VERBOSE according to the specified format and argument . <p > <p > This form avoids superfluous object creation when the logger is disabled for level VERBOSE . < / p > [CODESPLIT] public void trace ( String format , Object arg ) { formatAndLog ( Log . VERBOSE , format , arg ) ; }


Input: Log a message at level VERBOSE according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the VERBOSE level . < / p > [CODESPLIT] public void trace ( String format , Object arg1 , Object arg2 ) { formatAndLog ( Log . VERBOSE , format , arg1 , arg2 ) ; }


Input: Log a message at level VERBOSE according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the VERBOSE level . < / p > [CODESPLIT] public void trace ( String format , Object ... argArray ) { formatAndLog ( Log . VERBOSE , format , argArray ) ; }


Input: Log an exception ( throwable ) at level VERBOSE with an accompanying message . [CODESPLIT] public void trace ( String msg , Throwable t ) { log ( Log . VERBOSE , msg , t ) ; }


Input: Log a message at level DEBUG according to the specified format and argument . <p > <p > This form avoids superfluous object creation when the logger is disabled for level DEBUG . < / p > [CODESPLIT] public void debug ( String format , Object arg ) { formatAndLog ( Log . DEBUG , format , arg ) ; }


Input: Log a message at level DEBUG according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the DEBUG level . < / p > [CODESPLIT] public void debug ( String format , Object arg1 , Object arg2 ) { formatAndLog ( Log . DEBUG , format , arg1 , arg2 ) ; }


Input: Log a message at level DEBUG according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the DEBUG level . < / p > [CODESPLIT] public void debug ( String format , Object ... argArray ) { formatAndLog ( Log . DEBUG , format , argArray ) ; }


Input: Log an exception ( throwable ) at level DEBUG with an accompanying message . [CODESPLIT] public void debug ( String msg , Throwable t ) { log ( Log . DEBUG , msg , t ) ; }


Input: Log a message at level INFO according to the specified format and argument . <p > <p > This form avoids superfluous object creation when the logger is disabled for the INFO level . < / p > [CODESPLIT] public void info ( String format , Object arg ) { formatAndLog ( Log . INFO , format , arg ) ; }


Input: Log a message at the INFO level according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the INFO level . < / p > [CODESPLIT] public void info ( String format , Object arg1 , Object arg2 ) { formatAndLog ( Log . INFO , format , arg1 , arg2 ) ; }


Input: Log a message at level INFO according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the INFO level . < / p > [CODESPLIT] public void info ( String format , Object ... argArray ) { formatAndLog ( Log . INFO , format , argArray ) ; }


Input: Log an exception ( throwable ) at the INFO level with an accompanying message . [CODESPLIT] public void info ( String msg , Throwable t ) { log ( Log . INFO , msg , t ) ; }


Input: Log a message at the WARN level according to the specified format and argument . <p > <p > This form avoids superfluous object creation when the logger is disabled for the WARN level . < / p > [CODESPLIT] public void warn ( String format , Object arg ) { formatAndLog ( Log . WARN , format , arg ) ; }


Input: Log a message at the WARN level according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the WARN level . < / p > [CODESPLIT] public void warn ( String format , Object arg1 , Object arg2 ) { formatAndLog ( Log . WARN , format , arg1 , arg2 ) ; }


Input: Log a message at level WARN according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the WARN level . < / p > [CODESPLIT] public void warn ( String format , Object ... argArray ) { formatAndLog ( Log . WARN , format , argArray ) ; }


Input: Log an exception ( throwable ) at the WARN level with an accompanying message . [CODESPLIT] public void warn ( String msg , Throwable t ) { log ( Log . WARN , msg , t ) ; }


Input: Log a message at the ERROR level according to the specified format and argument . <p > <p > This form avoids superfluous object creation when the logger is disabled for the ERROR level . < / p > [CODESPLIT] public void error ( String format , Object arg ) { formatAndLog ( Log . ERROR , format , arg ) ; }


Input: Log a message at the ERROR level according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the ERROR level . < / p > [CODESPLIT] public void error ( String format , Object arg1 , Object arg2 ) { formatAndLog ( Log . ERROR , format , arg1 , arg2 ) ; }


Input: Log a message at level ERROR according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the ERROR level . < / p > [CODESPLIT] public void error ( String format , Object ... argArray ) { formatAndLog ( Log . ERROR , format , argArray ) ; }


Input: Log an exception ( throwable ) at the ERROR level with an accompanying message . [CODESPLIT] public void error ( String msg , Throwable t ) { log ( Log . ERROR , msg , t ) ; }


Input: One to many [CODESPLIT] public Stream < Record > oneToMany ( Collection < ? extends Record > rights , ListKey < Record > manyKey ) { return oneToMany ( rights . stream ( ) , manyKey ) ; }


Input: Strict one to many [CODESPLIT] public Stream < Record > strictOneToMany ( Collection < ? extends Record > rights , ListKey < Record > manyKey ) { return strictOneToMany ( rights . stream ( ) , manyKey ) ; }


Input: Many to one [CODESPLIT] public Stream < T2 < L , R > > manyToOne ( Collection < ? extends R > rights ) { return manyToOne ( rights . stream ( ) ) ; }


Input: Strict many to one [CODESPLIT] public Stream < T2 < L , R > > strictManyToOne ( Collection < ? extends R > rights ) { return strictManyToOne ( rights . stream ( ) ) ; }


Input: Strict one to many [CODESPLIT] public Stream < T2 < L , Set < R > > > strictOneToMany ( Collection < ? extends R > rights ) { return strictOneToMany ( rights . stream ( ) ) ; }


Input: Strict one to one [CODESPLIT] public Stream < T2 < L , R > > strictOneToOne ( Collection < ? extends R > rights ) { return strictOneToOne ( rights . stream ( ) ) ; }


Input: Bootstrap the SLF4J root logger with a configured { @link com . getsentry . raven . logback . SentryAppender } . [CODESPLIT] public static void bootstrap ( final String dsn , Optional < String > tags , boolean cleanRootLogger ) { bootstrap ( dsn , tags , Optional . empty ( ) , Optional . empty ( ) , cleanRootLogger ) ; }


Input: Bootstrap the SLF4J root logger with a configured { @link com . getsentry . raven . logback . SentryAppender } . [CODESPLIT] public static void bootstrap ( final String dsn , Optional < String > tags , Optional < String > environment , Optional < String > release , boolean cleanRootLogger ) { bootstrap ( dsn , tags , environment , release , Optional . empty ( ) , cleanRootLogger ) ; }


Input: Bootstrap the SLF4J root logger with a configured { @link com . getsentry . raven . logback . SentryAppender } . [CODESPLIT] public static void bootstrap ( final String dsn , Optional < String > tags , Optional < String > environment , Optional < String > release , Optional < String > serverName , boolean cleanRootLogger ) { final RavenAppenderFactory raven = new RavenAppenderFactory ( ) ; raven . setThreshold ( Level . ERROR ) ; raven . setDsn ( dsn ) ; raven . setTags ( tags ) ; raven . setEnvironment ( environment ) ; raven . setRelease ( release ) ; raven . setServerName ( serverName ) ; registerAppender ( dsn , cleanRootLogger , raven ) ; }


Input: The last modified time of a page is the most recent of : <ol > <li > { [CODESPLIT] @ Override public ReadableInstant getLastModified ( ServletContext servletContext , HttpServletRequest request , HttpServletResponse response , Page page ) throws ServletException , IOException { return AoArrays . maxNonNull ( page . getDateCreated ( ) , page . getDatePublished ( ) , page . getDateModified ( ) ) ; }


Input: Uses the page settings . [CODESPLIT] @ Override public boolean getAllowRobots ( ServletContext servletContext , HttpServletRequest request , HttpServletResponse response , Page page ) throws ServletException , IOException { return PageUtils . findAllowRobots ( servletContext , request , response , page ) ; }


Input: Assert that the generated command matches the specified command . [CODESPLIT] @ Then ( "^the instruction generated should be \"([^\"]*)\"$" ) public void the_instruction_generated_should_be ( String command ) throws Throwable { verify ( context . getDrinkMaker ( ) ) . executeCommand ( eq ( command ) ) ; }


Input: Attempt to retrieve the parameter ( <code > [CODESPLIT] private DocletTag findParamDocByNameOrIndex ( String name , int paramIndex , List < DocletTag > tags ) { for ( DocletTag tag : tags ) { if ( name . equals ( tag . getParameters ( ) . get ( 0 ) ) ) { return tag ; } } if ( paramIndex < tags . size ( ) ) { return tags . get ( paramIndex ) ; } return null ; }


Input: 尝试合并 sogou（去除了没有词性的） 与 rmmseg 的词库。 [CODESPLIT] public static void main ( String [ ] args ) throws IOException { FileInputStream fis = new FileInputStream ( new File ( "dic/word-with-attr.dic" ) ) ; final Set < String > words = new TreeSet < String > ( ) ; final int [ ] num = { 0 } ; FileLoading fl = new FileLoading ( ) { public void row ( String line , int n ) { words . add ( line . trim ( ) ) ; num [ 0 ] ++ ; } } ; Dictionary . load ( fis , fl ) ; fis = new FileInputStream ( new File ( "dic/words-rmmseg.dic" ) ) ; Dictionary . load ( fis , fl ) ; WriterRow wr = new WriterRow ( new File ( "dic/words-marge-sogou-no-attr-and-rmmseg.dic" ) ) ; for ( String word : words ) { wr . writerRow ( word ) ; } wr . close ( ) ; System . out . println ( "rows=" + num [ 0 ] + ", size=" + words . size ( ) + ", same=" + ( num [ 0 ] - words . size ( ) ) ) ; }


Input: - Dmode = simple default is complex [CODESPLIT] public static void main ( String [ ] args ) throws Exception { int n = 1 ; if ( args . length < 1 ) { usage ( ) ; return ; } Properties analyzers = new Properties ( ) ; analyzers . load ( new FileInputStream ( new File ( "analyzer.properties" ) ) ) ; String mode = System . getProperty ( "mode" , "complex" ) ; String a = System . getProperty ( "analyzer" , "mmseg4j" ) ; Analyzer analyzer = null ; String an = ( String ) analyzers . get ( a ) ; if ( an != null ) { analyzer = ( Analyzer ) Class . forName ( an ) . newInstance ( ) ; mode = a ; } else { usage ( ) ; return ; } if ( args . length > 1 ) { try { n = Integer . parseInt ( args [ 1 ] ) ; } catch ( NumberFormatException e ) { } } File path = new File ( args [ 0 ] ) ; System . out . println ( "analyzer=" + analyzer . getClass ( ) . getName ( ) ) ; Effect ef = new Effect ( path , analyzer ) ; ef . run ( mode , n ) ; }


Input: 只要 wordsXXX . dic的文件 [CODESPLIT] protected File [ ] listWordsFiles ( ) { return dicPath . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . startsWith ( "words" ) && name . endsWith ( ".dic" ) ; } } ) ; }


Input: 加载词文件的模板 [CODESPLIT] public static int load ( InputStream fin , FileLoading loading ) throws IOException { BufferedReader br = new BufferedReader ( new InputStreamReader ( new BufferedInputStream ( fin ) , "UTF-8" ) ) ; String line = null ; int n = 0 ; while ( ( line = br . readLine ( ) ) != null ) { if ( line == null || line . startsWith ( "#" ) ) { continue ; } n ++ ; loading . row ( line , n ) ; } return n ; }


Input: 取得 str 除去第一个char的部分 [CODESPLIT] private static char [ ] tail ( String str ) { char [ ] cs = new char [ str . length ( ) - 1 ] ; str . getChars ( 1 , str . length ( ) , cs , 0 ) ; return cs ; }


Input: 把 wordsFile 文件的最后更新时间加记录下来 . [CODESPLIT] private synchronized void addLastTime ( File wordsFile ) { if ( wordsFile != null ) { wordsLastTime . put ( wordsFile , wordsFile . lastModified ( ) ) ; } }


Input:
词典文件是否有修改过 [CODESPLIT] public synchronized boolean wordsFileIsChange ( ) { //检查是否有修改文件,包括删除的
 for ( Entry < File , Long > flt : wordsLastTime . entrySet ( ) ) { File words = flt . getKey ( ) ; if ( ! words . canRead ( ) ) { //可能是删除了
 return true ; } if ( words . lastModified ( ) > flt . getValue ( ) ) { //更新了文件
 return true ; } } //检查是否有新文件
 File [ ] words = listWordsFiles ( ) ; if ( words != null ) { for ( File wordsFile : words ) { if ( ! wordsLastTime . containsKey ( wordsFile ) ) { //有新词典文件
 return true ; } } } return false ; }


Input:
全新加载词库，没有成功加载会回滚。<P / > 注意：重新加载时，务必有两倍的词库树结构的内存，默认词库是 50M / 个 左右。否则抛出 OOM。 [CODESPLIT] public synchronized boolean reload ( ) { Map < File , Long > oldWordsLastTime = new HashMap < File , Long > ( wordsLastTime ) ; Map < Character , CharNode > oldDict = dict ; Map < Character , Object > oldUnit = unit ; try { wordsLastTime . clear ( ) ; dict = loadDic ( dicPath ) ; unit = loadUnit ( dicPath ) ; lastLoadTime = System . currentTimeMillis ( ) ; } catch ( IOException e ) { //rollback
 wordsLastTime . putAll ( oldWordsLastTime ) ; dict = oldDict ; unit = oldUnit ; if ( log . isLoggable ( Level . WARNING ) ) { log . log ( Level . WARNING , "reload dic error! dic=" + dicPath + ", and rollbacked." , e ) ; } return false ; } return true ; }


Input: word 能否在词库里找到 [CODESPLIT] public boolean match ( String word ) { if ( word == null || word . length ( ) < 2 ) { return false ; } CharNode cn = dict . get ( word . charAt ( 0 ) ) ; return search ( cn , word . toCharArray ( ) , 0 , word . length ( ) - 1 ) >= 0 ; }


Input: sen [ offset ] 后 tailLen 长的词是否存在 . [CODESPLIT] public int search ( CharNode node , char [ ] sen , int offset , int tailLen ) { if ( node != null ) { return node . indexOf ( sen , offset , tailLen ) ; } return - 1 ; }


Input: 当 words . dic 是从 jar 里加载时 可能 defalut 不存在 [CODESPLIT] public static File getDefalutPath ( ) { if ( defalutPath == null ) { String defPath = System . getProperty ( "mmseg.dic.path" ) ; log . info ( "look up in mmseg.dic.path=" + defPath ) ; if ( defPath == null ) { URL url = Dictionary . class . getClassLoader ( ) . getResource ( "data" ) ; if ( url != null ) { defPath = url . getFile ( ) ; log . info ( "look up in classpath=" + defPath ) ; } else { defPath = System . getProperty ( "user.dir" ) + "/data" ; log . info ( "look up in user.dir=" + defPath ) ; } } defalutPath = new File ( defPath ) ; if ( ! defalutPath . exists ( ) ) { log . warning ( "defalut dic path=" + defalutPath + " not exist" ) ; } } return defalutPath ; }


Input:
读取下一串指定类型的字符放到 bufSentence 中 . [CODESPLIT] private int readChars ( StringBuilder bufSentence , ReadChar readChar ) throws IOException { int num = 0 ; int data = - 1 ; while ( ( data = readNext ( ) ) != - 1 ) { int d = readChar . transform ( data ) ; if ( readChar . isRead ( d ) ) { bufSentence . appendCodePoint ( d ) ; num ++ ; } else { //不是数字回压,要下一步操作
 pushBack ( data ) ; break ; } } return num ; }


Input: 从 StringBuilder 里复制出 char [] [CODESPLIT] private static char [ ] toChars ( StringBuilder bufSentence ) { char [ ] chs = new char [ bufSentence . length ( ) ] ; bufSentence . getChars ( 0 , bufSentence . length ( ) , chs , 0 ) ; return chs ; }


Input:
双角转单角 [CODESPLIT] private static int toAscii ( int codePoint ) { if ( ( codePoint >= 65296 && codePoint <= 65305 ) //０-９
 || ( codePoint >= 65313 && codePoint <= 65338 ) //Ａ-Ｚ
 || ( codePoint >= 65345 && codePoint <= 65370 ) //ａ-ｚ
 ) { codePoint -= 65248 ; } return codePoint ; }


Input: - Dmode = simple default is complex - Dfile . encode = utf - 8 or other [CODESPLIT] public static void main ( String [ ] args ) throws IOException { if ( args . length < 1 ) { System . out . println ( "Usage:" ) ; System . out . println ( "\t-Dmode=simple, defalut is complex" ) ; System . out . println ( "\tPerformance <txt path> - is a directory that contain *.txt" ) ; return ; } String mode = System . getProperty ( "mode" , "complex" ) ; Seg seg = null ; Dictionary dic = Dictionary . getInstance ( ) ; if ( "simple" . equals ( mode ) ) { seg = new SimpleSeg ( dic ) ; } else { seg = new ComplexSeg ( dic ) ; } File path = new File ( args [ 0 ] ) ; File [ ] txts = path . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . endsWith ( ".txt" ) ; } } ) ; long time = 0 ; for ( File txt : txts ) { MMSeg mmSeg = new MMSeg ( new InputStreamReader ( new FileInputStream ( txt ) ) , seg ) ; Word word = null ; OutputStreamWriter osw = new OutputStreamWriter ( new FileOutputStream ( new File ( txt . getAbsoluteFile ( ) + "." + mode + ".word" ) ) ) ; BufferedWriter bw = new BufferedWriter ( osw ) ; long start = System . currentTimeMillis ( ) ; while ( ( word = mmSeg . next ( ) ) != null ) { bw . append ( new String ( word . getString ( ) ) ) . append ( "\r\n" ) ; } time += System . currentTimeMillis ( ) - start ; bw . close ( ) ; } System . out . println ( "use " + time + "ms" ) ; }


Input: Word Length [CODESPLIT] public int getLen ( ) { if ( len < 0 ) { len = 0 ; count = 0 ; for ( Word word : words ) { if ( word != null ) { len += word . getLength ( ) ; count ++ ; } } } return len ; }


Input: 有多少个词，最多3个。 [CODESPLIT] public int getCount ( ) { if ( count < 0 ) { count = 0 ; for ( Word word : words ) { if ( word != null ) { count ++ ; } } } return count ; }


Input: Variance of Word Lengths 就是 标准差的平方 [CODESPLIT] public double getVariance ( ) { if ( variance < 0 ) { double sum = 0 ; for ( Word word : words ) { if ( word != null ) { sum += Math . pow ( word . getLength ( ) - getAvgLen ( ) , 2 ) ; } } variance = sum / getCount ( ) ; } return variance ; }


Input: Sum of Degree of Morphemic Freedom of One - Character [CODESPLIT] public int getSumDegree ( ) { if ( sumDegree < 0 ) { int sum = 0 ; for ( Word word : words ) { if ( word != null && word . getDegree ( ) > - 1 ) { sum += word . getDegree ( ) ; } } sumDegree = sum ; } return sumDegree ; }


Input: 输出 chunks 调试用 . [CODESPLIT] protected void printChunk ( List < Chunk > chunks ) { for ( Chunk ck : chunks ) { System . out . println ( ck + " -> " + ck . toFactorString ( ) ) ; } }


Input: 查找chs [ offset ] 后面的 tailLen个char是否为词 . [CODESPLIT] protected int search ( char [ ] chs , int offset , int tailLen ) { if ( tailLen == 0 ) { return - 1 ; } CharNode cn = dic . head ( chs [ offset ] ) ; return search ( cn , chs , offset , tailLen ) ; }


Input: 没有数组的复制 . [CODESPLIT] protected int search ( CharNode cn , char [ ] chs , int offset , int tailLen ) { if ( tailLen == 0 || cn == null ) { return - 1 ; } return dic . search ( cn , chs , offset , tailLen ) ; }


Input: 最大匹配<br / > 从 chs [ offset ] 开始匹配 同时把 chs [ offset ] 的字符结点保存在 cns [ cnIdx ] [CODESPLIT] protected int maxMatch ( CharNode [ ] cns , int cnIdx , char [ ] chs , int offset ) { CharNode cn = null ; if ( offset < chs . length ) { cn = dic . head ( chs [ offset ] ) ; } cns [ cnIdx ] = cn ; return dic . maxMatch ( cn , chs , offset ) ; }


Input: 匹配 同时找出长度 . <br / > 从 chs [ offset ] 开始找所有匹配的词 找到的放到 tailLens [ tailLensIdx ] 中 . <br / > 同时把 chs [ offset ] 的字符结点保存在 cns [ cnIdx ] . [CODESPLIT] protected void maxMatch ( CharNode [ ] cns , int cnIdx , char [ ] chs , int offset , ArrayList < Integer > [ ] tailLens , int tailLensIdx ) { CharNode cn = null ; if ( offset < chs . length ) { cn = dic . head ( chs [ offset ] ) ; } cns [ cnIdx ] = cn ; dic . maxMatch ( cn , tailLens [ tailLensIdx ] , chs , offset ) ; }


Input:
词库转换 [CODESPLIT] public static void main ( String [ ] args ) throws IOException { String words = "sogou/SogouLabDic.dic" ; String charset = "GBK" ; if ( args . length > 0 ) { words = args [ 0 ] ; } File file = new File ( words ) ; //File path = file.getParentFile();
 //File dist = new File("dic/words.dic");
 File dist = new File ( "dic/word-with-attr.dic" ) ; DicTransform dt = new DicTransform ( ) ; //只要词,不频率
 //dt.transform(file, charset, dist, new DeFreq());
 //只要两或三个字的词.
 //dt.transform(file, charset, dist, new TwoOrThreeChar());
 dt . transform ( file , charset , dist , new NoAttr ( ) ) ; }


Input: You can take this and extend for your setup if you need more . [CODESPLIT] @ NotNull public static Mode minimal ( @ NotNull String apiKey , @ NotNull Host host , @ NotNull RestPortUrlFactory portUrlFactory ) { return Mode . create ( ) . with ( RestKeys . REST_PORT_URL_FACTORY , portUrlFactory ) //                .with(ExceptionTranslationExtension.TRANSLATOR, new CombinedExceptionTranslator(new DefaultClientExceptionTranslator(), new SoapFaultExceptionTranslator())) . with ( Keys . HOST , host ) . with ( NameApiKeys . API_KEY , apiKey ) ; }


Input: Overloaded method that uses for host : { [CODESPLIT] @ NotNull public static Mode minimal ( @ NotNull String apiKey ) { return minimal ( apiKey , DEFAULT_HOST , DEFAULT_PORT_FACTORY ) ; }


Input: You can take this and extend for your setup if you need more . [CODESPLIT] @ NotNull public static Mode withContext ( @ NotNull String apiKey , @ NotNull Context context , @ NotNull Host host , @ NotNull RestPortUrlFactory portUrlFactory ) { return minimal ( apiKey , host , portUrlFactory ) . with ( NameApiKeys . CONTEXT , context ) ; }


Input: Overloaded method that uses for host : { [CODESPLIT] @ NotNull public static Mode withContext ( @ NotNull String apiKey , @ NotNull Context context ) { return withContext ( apiKey , context , DEFAULT_HOST , DEFAULT_PORT_FACTORY ) ; }


Input: Returns a map which contains only those arguments that the superclass understands . [CODESPLIT] private static Map < String , String > superclassArgs ( Map < String , String > args ) { Map < String , String > result = new HashMap <> ( ) ; // resource loading does not take place if no file has been configured. if ( ! result . containsKey ( "dictionary" ) ) { result . put ( "dictionary" , JdbcResourceLoader . DATABASE ) ; } for ( String arg : ImmutableList . of ( "dictionary" , "ignoreCase" ) ) { String value = args . get ( arg ) ; if ( value != null ) { result . put ( arg , value ) ; } } return result ; }


Input: Load words from jdbc [CODESPLIT] @ Override public void inform ( ResourceLoader loader ) throws IOException { super . inform ( new JdbcResourceLoader ( loader , reader , StandardCharsets . UTF_8 ) ) ; }


Input: Check if the datasource is able to provide connections . [CODESPLIT] protected final void checkDatasource ( ) { // Check database connection information of data source if ( dataSource != null ) { //noinspection unused,EmptyTryBlock try ( Connection connection = dataSource . getConnection ( ) ) { // Just get the connection to check if data source parameters are configured correctly. } catch ( SQLException e ) { dataSource = null ; logger . error ( "Failed to connect to database of data source: {}." , e . getMessage ( ) ) ; if ( ! ignore ) { throw new IllegalArgumentException ( "Failed to connect to the database." , e ) ; } } } }


Input: { [CODESPLIT] @ Override public Reader getReader ( ) { if ( dataSource == null ) { if ( ignore ) { return new StringReader ( "" ) ; } throw new IllegalArgumentException ( "Missing data source." ) ; } QueryRunner runner = new QueryRunner ( dataSource ) ; try { logger . info ( "Querying for data using {}" , sql ) ; List < String > content = runner . query ( sql , SINGLE_LINE_RESULT_SET_HANDLER ) ; logger . info ( "Loaded {} lines" , content . size ( ) ) ; // return joined return new StringReader ( Joiner . on ( ' ' ) . join ( content ) ) ; } catch ( SQLException e ) { throw new IllegalArgumentException ( "Failed to load data from the database" , e ) ; } }


Input: { [CODESPLIT] @ Override public QueryRunner getJdbcRunner ( ) { if ( dataSource == null ) { if ( ignore ) { logger . warn ( "Could not load Jdbc Datasource!" ) ; return null ; } throw new IllegalArgumentException ( "Missing data source." ) ; } return new QueryRunner ( dataSource ) ; }


Input: Inform { @link SearcherAware } about a new searcher . [CODESPLIT] private void inform ( String type , String name , Object o , SolrIndexSearcher searcher ) { if ( o instanceof SearcherAware ) { logger . info ( "Informing searcher aware {} ({}) of field type {} about a new searcher." , type , o . getClass ( ) . getName ( ) , name ) ; try { ( ( SearcherAware ) o ) . inform ( searcher ) ; } catch ( IOException e ) { logger . error ( "Failed to inform {} ({}) of field type {} about a new searcher." , type , o . getClass ( ) . getName ( ) , name , e ) ; throw new IllegalArgumentException ( "Failed to inform about a new searcher." , e ) ; } } }


Input: Inform { @link SearcherAware } filter factories in a { @link TokenizerChain } about a new searcher . [CODESPLIT] private void inform ( String name , TokenizerChain tokenizers , SolrIndexSearcher searcher ) { for ( TokenFilterFactory factory : tokenizers . getTokenFilterFactories ( ) ) { inform ( "token filter factory" , name , factory , searcher ) ; } }


Input: Lookup data source . [CODESPLIT] public static DataSource getDataSource ( Map < ? , ? > config ) { String ignoreString = ( String ) config . remove ( JdbcReaderFactoryParams . IGNORE ) ; boolean ignore = ! "false" . equals ( ignoreString ) ; String dataSourceName = ( String ) config . remove ( JdbcReaderFactoryParams . DATASOURCE ) ; DataSource dataSource = null ; if ( dataSourceName != null ) { dataSource = jndiDataSource ( fixJndiName ( dataSourceName ) ) ; if ( dataSource == null ) { log . error ( "Data source {} not found.",   ataSourceName) ;  if ( ! ignore ) { throw new IllegalArgumentException ( "No data source found." ) ; } } } else { log . error ( "No data source configured." ) ; if ( ! ignore ) { throw new IllegalArgumentException ( "No data source configured." ) ; } } return dataSource ; }


Input: Initializes the database and lookups a { @linkplain DataSource } in JNDI . [CODESPLIT] private static DataSource jndiDataSource ( String jndiName ) { try { Context ctx = new InitialContext ( ) ; log . info ( "Looking up data source {} in JNDI." , jndiName ) ; DataSource dataSource = ( DataSource ) ctx . lookup ( jndiName ) ; ctx . close ( ) ; return dataSource ; } catch ( NameNotFoundException e ) { return null ; } catch ( NamingException e ) { log . error ( "JNDI error: {}." , e . getMessage ( ) ) ; throw new IllegalArgumentException ( "JNDI error." , e ) ; } catch ( ClassCastException e ) { log . error ( "The JNDI resource {} is no data source: {}." , jndiName , e . getMessage ( ) ) ; throw new IllegalArgumentException ( "The JNDI resource is no data source." , e ) ; } }


Input: Create the { @link JdbcReader } from configuration . [CODESPLIT] public static JdbcReader createFromSolrParams ( Map < String , String > config , String originalParamName ) { Preconditions . checkNotNull ( config ) ; // Set a fixed synonyms "file". // This "file" will be loaded from the database by the JdbcResourceLoader. if ( originalParamName != null ) { config . put ( originalParamName , JdbcResourceLoader . DATABASE ) ; } DataSource dataSource = JdbcDataSourceFactory . getDataSource ( config ) ; String sql = config . remove ( JdbcReaderFactoryParams . SQL ) ; String ignoreString = config . remove ( JdbcReaderFactoryParams . IGNORE ) ; boolean ignore = ! "false" . equals ( ignoreString ) ; return new SimpleJdbcReader ( dataSource , sql , ignore ) ; }


Input: ITERABLES - complete [CODESPLIT] @ NonNull public static < T > Iterable < T > iterableOf ( final InstanceOf < T > type ) { return PrivateGenerate . FIXTURE . createMany ( type ) ; }


Input: ARRAYS - complete [CODESPLIT] @ NonNull public static < T > T [ ] arrayOf ( final Class < T > clazz ) { assertIsNotParameterized ( clazz , ErrorMessages . msg ( "arrayOf" ) ) ; return PrivateGenerate . manyAsArrayOf ( TypeToken . of ( clazz ) ) ; }


Input: LISTS - complete [CODESPLIT] @ NonNull public static < T > List < T > listOf ( final Class < T > clazz ) { assertIsNotParameterized ( clazz , ErrorMessages . msg ( "listOf" ) ) ; return PrivateGenerate . manyAsListOf ( TypeToken . of ( clazz ) ) ; }


Input: COLLECTIONS - complete [CODESPLIT] @ NonNull public static < T > Collection < T > collectionOf ( final InstanceOf < T > typeToken , final InlineConstrainedGenerator < T > omittedValues ) { return PrivateGenerate . manyAsListOf ( typeToken , omittedValues ) ; }


Input: TODO variations [CODESPLIT] @ NonNull public static < T > Set < T > setOf ( final Class < T > clazz ) { assertIsNotParameterized ( clazz , ErrorMessages . msg ( "setOf" ) ) ; return PrivateGenerate . manyAsSetOf ( TypeToken . of ( clazz ) ) ; }


Input: TODO UT [CODESPLIT] @ NonNull public static < T > Set < T > setOf ( final Class < T > type , final InlineConstrainedGenerator < T > omittedValues ) { assertIsNotParameterized ( type , ErrorMessages . msgInline ( "setOf" ) ) ; return PrivateGenerate . manyAsSetOf ( TypeToken . of ( type ) , omittedValues ) ; }


Input: queues : incomplete [CODESPLIT] @ NonNull public static < T > Queue < T > queueOf ( final Class < T > clazz ) { assertIsNotParameterized ( clazz , ErrorMessages . msg ( "queueOf" ) ) ; return PrivateGenerate . manyAsQueueOf ( TypeToken . of ( clazz ) ) ; }


Input: TODO UT [CODESPLIT] @ NonNull public static < T > Queue < T > queueOf ( final Class < T > type , final InlineConstrainedGenerator < T > omittedValues ) { assertIsNotParameterized ( type , ErrorMessages . msgInline ( "queueOf" ) ) ; return PrivateGenerate . manyAsQueueOf ( TypeToken . of ( type ) , omittedValues ) ; }


Input: Deques : incomplete [CODESPLIT] @ NonNull public static < T > Deque < T > dequeOf ( final Class < T > clazz ) { assertIsNotParameterized ( clazz , ErrorMessages . msg ( "dequeOf" ) ) ; return PrivateGenerate . manyAsDequeOf ( TypeToken . of ( clazz ) ) ; }


Input: TODO UT [CODESPLIT] @ NonNull public static < T > Deque < T > dequeOf ( final Class < T > type , final InlineConstrainedGenerator < T > omittedValues ) { assertIsNotParameterized ( type , ErrorMessages . msgInline ( "dequeOf" ) ) ; return PrivateGenerate . manyAsDequeOf ( TypeToken . of ( type ) , omittedValues ) ; }


Input: sorted sets : incomplete [CODESPLIT] @ NonNull public static < T > SortedSet < T > sortedSetOf ( final Class < T > clazz ) { assertIsNotParameterized ( clazz , ErrorMessages . msg ( "sortedSetOf" ) ) ; return PrivateGenerate . manyAsSortedSetOf ( TypeToken . of ( clazz ) ) ; }


Input: TODO UT [CODESPLIT] @ NonNull public static < T > SortedSet < T > sortedSetOf ( final Class < T > type , final InlineConstrainedGenerator < T > omittedValues ) { assertIsNotParameterized ( type , ErrorMessages . msgInline ( "sortedSetOf" ) ) ; return PrivateGenerate . manyAsSortedSetOf ( TypeToken . of ( type ) , omittedValues ) ; }


Input: TODO variations and UT [CODESPLIT] @ NonNull public static < T , V > SortedMap < T , V > sortedMapBetween ( final Class < T > keyClass , final Class < V > valueClass ) { assertIsNotParameterized ( keyClass , "generic key types are not allowed for this method." ) ; assertIsNotParameterized ( valueClass , "generic value types are not allowed for this method." ) ; return PrivateGenerate . manyAsSortedMapBetween ( TypeToken . of ( keyClass ) , TypeToken . of ( valueClass ) ) ; }


Input: TODO variations [CODESPLIT] @ NonNull public static < T , V > Map < T , V > mapBetween ( final Class < T > keyClass , final Class < V > valueClass ) { assertIsNotParameterized ( keyClass , "generic key types are not allowed for this method." ) ; assertIsNotParameterized ( valueClass , "generic value types are not allowed for this method." ) ; return PrivateGenerate . manyAsMapBetween ( TypeToken . of ( keyClass ) , TypeToken . of ( valueClass ) ) ; }


Input: / optionals [CODESPLIT] @ NonNull public static < T > Optional < T > optional ( Class < T > type ) { return Optional . of ( Any . anonymous ( type ) ) ; }


Input: TODO rethink putting this into the Fixture class [CODESPLIT] static < T > List < T > manyAsListOf ( final TypeToken < T > typeToken , final InlineConstrainedGenerator < T > generator ) { final List < T > result = CollectionFactory . createList ( ) ; result . add ( any ( typeToken , generator ) ) ; result . add ( any ( typeToken , generator ) ) ; result . add ( any ( typeToken , generator ) ) ; return result ; }


Input: TODO check case when new X<Integer > () . GetValue () and new X<String > () . GetValue () afterwards - does this work? [CODESPLIT] private Object generateFreshValueFor ( final Object proxy , final Method method , final TypeToken < ? > returnType ) { final Optional < Object > freshReturnValue = createReturnValue ( fixture , returnType ) ; if ( freshReturnValue . isPresent ( ) ) { methodsInvocationResultCache . setFor ( proxy , method , freshReturnValue . get ( ) ) ; } return freshReturnValue . orNull ( ) ; }


Input: todo add generics checks [CODESPLIT] @ NonNull public static < T > List < T > listOf ( Class < T > clazz ) { assertIsNotParameterized ( clazz , msg ( "listOf" ) ) ; return io . vavr . collection . List . ofAll ( Any . listOf ( clazz ) ) ; }


Input: ///////////// arrays [CODESPLIT] @ NonNull public static < T > Array < T > arrayOf ( Class < T > clazz ) { assertIsNotParameterized ( clazz , msg ( "arrayOf" ) ) ; return Array . ofAll ( Any . listOf ( clazz ) ) ; }


Input: ///////////// hashsets [CODESPLIT] @ NonNull public static < T > HashSet < T > hashSetOf ( Class < T > clazz ) { assertIsNotParameterized ( clazz , msg ( "hashSetOf" ) ) ; return HashSet . ofAll ( Any . listOf ( clazz ) ) ; }


Input: ////// tree sets [CODESPLIT] @ NonNull public static < T > TreeSet < T > treeSetOf ( Class < T > clazz ) { assertIsNotParameterized ( clazz , msg ( "treeSetOf" ) ) ; return TreeSet . ofAll ( ( Iterable ) Any . iterableOf ( clazz ) ) ; }


Input: ////// sets [CODESPLIT] @ NonNull public static < T > Set < T > setOf ( Class < T > clazz ) { assertIsNotParameterized ( clazz , msg ( "setOf" ) ) ; return hashSetOf ( clazz ) ; }


Input: ///// sorted sets [CODESPLIT] @ NonNull public static < T > SortedSet < T > sortedSetOf ( Class < T > clazz ) { assertIsNotParameterized ( clazz , msg ( "sortedSetOf" ) ) ; return treeSetOf ( clazz ) ; }


Input: ///////////////////////////// hash maps [CODESPLIT] @ NonNull public static < T , V > HashMap < T , V > hashMapBetween ( final Class < T > keyClass , final Class < V > valueClass ) { assertIsNotParameterized ( keyClass , "generic key types are not allowed for this method." ) ; assertIsNotParameterized ( valueClass , "generic value types are not allowed for this method." ) ; return HashMap . ofAll ( Any . mapBetween ( keyClass , valueClass ) ) ; }


Input: ///////////////////////////// maps [CODESPLIT] @ NonNull public static < T , V > Map < T , V > mapBetween ( final Class < T > keyClass , final Class < V > valueClass ) { assertIsNotParameterized ( keyClass , "generic key types are not allowed for this method." ) ; assertIsNotParameterized ( valueClass , "generic value types are not allowed for this method." ) ; return hashMapBetween ( keyClass , valueClass ) ; }


Input: ////////////////// queues [CODESPLIT] @ NonNull public static < T > Queue < T > queueOf ( Class < T > clazz ) { assertIsNotParameterized ( clazz , msg ( "queueOf" ) ) ; return Queue . ofAll ( Any . queueOf ( clazz ) ) ; }


Input: options [CODESPLIT] @ NonNull public static < T > Option < T > option ( final Class < T > type ) { assertIsNotParameterized ( type , msgInline ( "option" ) ) ; return Option . of ( Any . instanceOf ( type ) ) ; }


Input: eithers - left [CODESPLIT] @ NonNull public static < T , U > Either < T , U > left ( final Class < T > leftType ) { assertIsNotParameterized ( leftType , msgInline ( "left" ) ) ; return Either . left ( Any . instanceOf ( leftType ) ) ; }


Input: eithers - right [CODESPLIT] @ NonNull public static < T , U > Either < T , U > right ( final Class < U > rightType ) { assertIsNotParameterized ( rightType , msgInline ( "right" ) ) ; return Either . right ( Any . instanceOf ( rightType ) ) ; }


Input: validations - failures [CODESPLIT] @ NonNull public static < T , U > Validation < T , U > validationFailed ( final Class < T > type ) { assertIsNotParameterized ( type , msgInline ( "validationFailed" ) ) ; return Validation . invalid ( Any . instanceOf ( type ) ) ; }


Input: validations - successful [CODESPLIT] @ NonNull public static < T , U > Validation < T , U > validationSuccess ( final Class < U > type ) { assertIsNotParameterized ( type , msgInline ( "validationSuccess" ) ) ; return Validation . valid ( Any . instanceOf ( type ) ) ; }


Input: try - successful [CODESPLIT] @ NonNull public static < T > Try < T > trySuccess ( final Class < T > type ) { assertIsNotParameterized ( type , msgInline ( "trySuccess" ) ) ; return Try . success ( Any . instanceOf ( type ) ) ; }


Input: Registers a database to further execute SQL commands [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public boolean connectJdbcOnWithUrlAndDriverAndUsernameAndPassword ( String dataBaseId , String url , String driverClassName , String username , String password ) throws ReflectiveOperationException { SimpleDriverDataSource dataSource = new SimpleDriverDataSource ( ) ; dataSource . setUrl ( url ) ; dataSource . setDriverClass ( ( Class < Driver > ) Class . forName ( driverClassName ) ) ; dataSource . setUsername ( username ) ; dataSource . setPassword ( password ) ; this . templateMap . put ( dataBaseId , new JdbcTemplate ( dataSource ) ) ; return true ; }


Input: Simply runs a SQL command used for udpates inserts which the result doesn t matter . [CODESPLIT] public boolean runInTheSql ( String database , final String sql ) { getDatabaseJdbcTemplate ( database ) . update ( sql ) ; return true ; }


Input: Used generally when the result is assigned to a variable [CODESPLIT] public String queryInWithSql ( String database , String sql ) { JdbcTemplate template = getDatabaseJdbcTemplate ( database ) ; if ( sql != null && ! sql . trim ( ) . toUpperCase ( ) . startsWith ( JdbcFixture . SELECT_COMMAND_PREFIX ) ) { return Objects . toString ( template . update ( sql ) ) ; } List < String > results = template . queryForList ( sql , String . class ) ; if ( results == null || results . isEmpty ( ) ) { return null ; } return results . get ( 0 ) ; }


Input: Interprets a strongly - typed number array to array of booleans . If a value found in the array is greater than 0 return true false otherwise . [CODESPLIT] public boolean [ ] asBoolArray ( ) { boolean [ ] retval ; UBArray array = asArray ( ) ; switch ( array . getStrongType ( ) ) { case Int8 : { byte [ ] data = ( ( UBInt8Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } case Int16 : { short [ ] data = ( ( UBInt16Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } case Int32 : { int [ ] data = ( ( UBInt32Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } case Int64 : { long [ ] data = ( ( UBInt64Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } case Float32 : { float [ ] data = ( ( UBFloat32Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } case Float64 : { double [ ] data = ( ( UBFloat64Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } default : throw new RuntimeException ( "not an int32[] type" ) ; } return retval ; }


Input: Executes a query which returns all rows in the entity table that match the fields of the example object having values other than the defaults . [CODESPLIT] public Query < T > byExample ( T obj ) { if ( obj != null ) { return dao . getTableHelper ( ) . buildFilter ( this , obj ) ; } return this ; }


Input: / * Convenience methods for comparing equality of each wrapper type [CODESPLIT] public Query < T > eq ( Column colName , Boolean param ) { Integer sqlValue = BooleanConverter . GET . toSql ( param ) ; where . append ( " AND " + colName + "=?" ) ; params . add ( BooleanConverter . GET . toString ( sqlValue ) ) ; return this ; }


Input: Upgrades the table that represents the associated entity . This will typically be an ALTER TABLE statement . [CODESPLIT] protected void onUpgrade ( final SQLiteDatabase db , final int oldVersion , final int newVersion ) { db . execSQL ( upgradeSql ( oldVersion , newVersion ) ) ; }


Input: Backs up the current table to a CSV file . [CODESPLIT] public boolean backup ( SQLiteDatabase db , Context ctx , String suffix ) { try { new CsvTableWriter ( this ) . dumpToCsv ( ctx , db , suffix ) ; } catch ( SQLException e ) { if ( e . getMessage ( ) . contains ( "no such table" ) ) { Log . w ( TAG , "Table " + this . getTableName ( ) + " doesn't exist. This is expected if the table is new in this db version." ) ; } } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; return false ; } return true ; }


Input: Restores a table from a text file . [CODESPLIT] public void restore ( SQLiteDatabase db , Context ctx , String suffix ) { new CsvTableReader ( this ) . importFromCsv ( ctx , db , suffix ) ; }


Input: / * Cursor wrapper methods which bind to primitive type columns and return the corresponding wrapper type which may be null [CODESPLIT] protected byte [ ] getBlobOrNull ( Cursor c , int col ) { return c . isNull ( col ) ? null : c . getBlob ( col ) ; }


Input: The default content for this Activity has a TextView that is shown when the list is empty . If you would like to change the text call this method to supply the text it should use . [CODESPLIT] public void setEmptyText ( CharSequence emptyText ) { if ( mListView != null ) { View emptyView = mListView . getEmptyView ( ) ; if ( emptyText instanceof TextView ) { ( ( TextView ) emptyView ) . setText ( emptyText ) ; } } }


Input: Dumps a database table to a CSV file in the default location . Returns the number of rows written to the file . [CODESPLIT] public int dumpToCsv ( Context ctx , SQLiteDatabase db , String suffix ) throws FileNotFoundException { int numRowsWritten = 0 ; Cursor c ; String filename = getCsvFilename ( db . getPath ( ) , db . getVersion ( ) , suffix ) ; c = db . query ( th . getTableName ( ) , null , null , null , null , null , null ) ; FileOutputStream fos ; fos = ctx . openFileOutput ( filename , 0 ) ; PrintWriter printWriter = new PrintWriter ( fos ) ; String headerRow = buildHeaderRow ( ) ; printWriter . println ( headerRow ) ; for ( boolean hasItem = c . moveToFirst ( ) ; hasItem ; hasItem = c . moveToNext ( ) ) { String csv = buildCsvRow ( c ) ; printWriter . println ( csv ) ; numRowsWritten ++ ; } printWriter . flush ( ) ; printWriter . close ( ) ; return numRowsWritten ; }


Input: Adds an expression to this Select Clause with support for Constructor Expressions . [CODESPLIT] public < T > QueryBuilder add ( final Class < T > constructorClass , final String expression ) { return add ( ( String ) null , constructorClass , expression ) ; }


Input: Adds an expression to this Select Clause with support for Constructor Expressions . [CODESPLIT] public < T > QueryBuilder add ( final String lhsStatement , final Class < T > constructorClass , final String expression ) { StringBuilder itemBuilder = new StringBuilder ( ) ; if ( lhsStatement != null ) { itemBuilder . append ( lhsStatement ) ; itemBuilder . append ( " " ) ; } itemBuilder . append ( "NEW " ) ; itemBuilder . append ( constructorClass . getName ( ) ) ; itemBuilder . append ( "(" ) ; itemBuilder . append ( expression ) ; itemBuilder . append ( ")" ) ; items . add ( itemBuilder . toString ( ) ) ; return builder ; }


Input: Adds expressions to this Select Clause with support for Constructor Expressions . [CODESPLIT] public < T > QueryBuilder add ( final Class < T > constructorClass , final String ... expressions ) { return add ( ( String ) null , constructorClass , expressions ) ; }


Input: Adds expressions to this Select Clause with support for Constructor Expressions . [CODESPLIT] public < T > QueryBuilder add ( final String lhsStatement , final Class < T > constructorClass , final String ... expressions ) { return add ( lhsStatement , constructorClass , StringUtils . join ( expressions ) ) ; }


Input: Returns a { @link String } for a CSV column enclosed in double quotes if required . [CODESPLIT] public static String escapeCsv ( String str ) { if ( str == null ) return "" ; if ( containsNone ( str , CSV_SEARCH_CHARS ) ) return str ; StringWriter out = new StringWriter ( ) ; out . write ( QUOTE ) ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { char c = str . charAt ( i ) ; if ( c == QUOTE ) out . write ( QUOTE ) ; out . write ( c ) ; } out . write ( QUOTE ) ; return out . toString ( ) ; }


Input: Removes enclosing quotes and unescapes double quotes [CODESPLIT] public static String unescapeCsv ( String str ) { if ( str == null ) return null ; if ( ! ( str . charAt ( 0 ) == QUOTE && str . charAt ( str . length ( ) - 1 ) == QUOTE ) ) return str ; String quoteless = str . substring ( 1 , str . length ( ) - 1 ) ; return quoteless . replace ( QUOTE_STR + QUOTE_STR , QUOTE_STR ) ; }


Input: Returns values from a CSV String . [CODESPLIT] public static List < String > getValues ( String csvRow ) { List < String > values = new ArrayList < String > ( ) ; StringReader in = new StringReader ( csvRow ) ; String value ; try { value = nextValue ( in ) ; while ( true ) { values . add ( value ) ; value = nextValue ( in ) ; } } catch ( IOException e ) { // TODO handle case of final null value better? if ( csvRow . lastIndexOf ( ' ' ) == csvRow . length ( ) - 1 ) values . add ( null ) ; return values ; } }


Input: Obtains the next value from a { @link StringReader } . [CODESPLIT] public static String nextValue ( StringReader in ) throws IOException { StringWriter w = new StringWriter ( ) ; boolean inQuotedValue = false ; boolean openQuote = false ; int c = in . read ( ) ; if ( c == QUOTE ) inQuotedValue = true ; else if ( c == DELIMITER ) { return null ; } else if ( c >= 0 ) { w . write ( c ) ; } else { throw new IOException ( "End of line reached" ) ; } c = in . read ( ) ; while ( c >= 0 ) { if ( c == QUOTE ) { if ( inQuotedValue ) { if ( openQuote ) { openQuote = false ; w . write ( QUOTE ) ; } else { openQuote = true ; } } else // invalid return w . toString ( ) ; } else if ( c == DELIMITER ) { if ( openQuote ) return w . toString ( ) ; else if ( inQuotedValue ) w . write ( c ) ; else // invalid return w . toString ( ) ; } else w . write ( c ) ; c = in . read ( ) ; } return w . toString ( ) ; }


Input: Parses a CSV row containing name = value pairs . [CODESPLIT] public static Map < String , String > getAsMap ( String csvPairs ) { Map < String , String > map = new HashMap < String , String > ( ) ; String [ ] pairs = csvPairs . split ( "," ) ; for ( String pair : pairs ) { String [ ] split = pair . split ( "=" ) ; map . put ( split [ 0 ] , split [ 1 ] ) ; } return map ; }


Input: Returns a String containing a comma - separated list of name = value pairs from a map . [CODESPLIT] public static String mapToCsv ( Map < String , String > map ) { StringBuilder sb = new StringBuilder ( ) ; for ( String key : map . keySet ( ) ) { sb . append ( "," ) ; String val = map . get ( key ) ; sb . append ( key + "=" + val ) ; } return sb . toString ( ) . substring ( 1 ) ; }


Input: Joins items of a text list separating items by comma . [CODESPLIT] public static String join ( final List < String > list ) { // zero, empty or one element if ( list == null ) { return null ; } else if ( list . size ( ) == 0 ) { return "" ; } else if ( list . size ( ) == 1 ) { return list . get ( 0 ) ; } // two or more elements final StringBuilder builder = new StringBuilder ( ) ; for ( String item : list ) { if ( builder . length ( ) > 0 ) { builder . append ( ", " ) ; } builder . append ( item ) ; } return builder . toString ( ) ; }


Input: Joins items of a text array separating items by comma . [CODESPLIT] public static String join ( final String [ ] list ) { // zero, empty or one element if ( list == null ) { return null ; } else if ( list . length == 0 ) { return "" ; } else if ( list . length == 1 ) { return list [ 0 ] ; } // two or more elements final StringBuilder builder = new StringBuilder ( ) ; for ( String item : list ) { if ( builder . length ( ) > 0 ) { builder . append ( ", " ) ; } builder . append ( item ) ; } return builder . toString ( ) ; }


Input: Renders this object as { @literal JPQL } fragment . [CODESPLIT] public String render ( ) { StringBuilder builder = new StringBuilder ( column ) ; if ( order != null ) { builder . append ( " " ) . append ( getOrder ( ) . name ( ) ) ; } return builder . toString ( ) ; }


Input: Populate the model of a database and its associated tables from a file in support of incremental compilation . [CODESPLIT] public static DatabaseModel readFromIndex ( BufferedReader reader , ProcessorLogger logger ) throws IOException { String dbInfo = reader . readLine ( ) ; logger . info ( dbInfo ) ; Map < String , String > props = CsvUtils . getAsMap ( dbInfo ) ; String dbName = props . get ( "dbName" ) ; int dbVersion = Integer . parseInt ( props . get ( "dbVersion" ) ) ; String helperClass = props . get ( "helperClass" ) ; DatabaseModel dbModel = new DatabaseModel ( dbName , dbVersion , helperClass ) ; // read TableHelpers List < String > tables = new ArrayList < String > ( ) ; String th = reader . readLine ( ) ; while ( th != null && ! th . equals ( StormEnvironment . END_DATABASE ) ) { tables . add ( th ) ; th = reader . readLine ( ) ; } dbModel . tableHelpers = tables ; return dbModel ; }


Input: Write the database info and associated tables to a file in support of incremental compilation . [CODESPLIT] public void writeToIndex ( PrintWriter out ) { out . println ( StormEnvironment . BEGIN_DATABASE ) ; Map < String , String > dbMap = new HashMap < String , String > ( ) ; dbMap . put ( "dbName" , this . getDbName ( ) ) ; dbMap . put ( "dbVersion" , String . valueOf ( this . getDbVersion ( ) ) ) ; dbMap . put ( "helperClass" , this . getQualifiedClassName ( ) ) ; String dbInfo = CsvUtils . mapToCsv ( dbMap ) ; out . println ( dbInfo ) ; // write TableHelpers for ( String th : this . tableHelpers ) { out . println ( th ) ; } out . println ( StormEnvironment . END_DATABASE ) ; }


Input: Verifies that the entity has exactly one id field of type long . [CODESPLIT] private void inspectId ( ) { if ( entityModel . getIdField ( ) == null ) { // Default to field named "id" List < FieldModel > fields = entityModel . getFields ( ) ; for ( FieldModel f : fields ) { if ( EntityModel . DEFAULT_ID_FIELD . equals ( f . getFieldName ( ) ) ) { entityModel . setIdField ( f ) ; } } } FieldModel idField = entityModel . getIdField ( ) ; if ( idField != null && "long" . equals ( idField . getJavaType ( ) ) ) { return ; } else { abort ( "Entity must contain a field named id or annotated with @Id of type long" ) ; } }


Input: Trying to get Class<? > from an annotation raises an exception see http : // stackoverflow . com / questions / 7687829 / java - 6 - annotation - processing - getting - a - class - from - an - annotation [CODESPLIT] private static TypeMirror getBaseDaoTypeMirror ( Entity entity ) { if ( entity != null ) { try { entity . baseDaoClass ( ) ; } catch ( MirroredTypeException mte ) { return mte . getTypeMirror ( ) ; } } return null ; }


Input: Builds a BaseDaoModel from the class passed as attribute baseDaoClass of the annotation Entity [CODESPLIT] private static BaseDaoModel getBaseDaoClass ( Entity entity ) { String qualifiedName = SQLiteDao . class . getName ( ) ; TypeMirror typeMirror = getBaseDaoTypeMirror ( entity ) ; if ( typeMirror != null ) qualifiedName = typeMirror . toString ( ) ; return new BaseDaoModel ( qualifiedName ) ; }


Input: Morph bind type like INT == > Int so it can be used in a Cursor getXxx method name . Never called at runtime . [CODESPLIT] public String getBindType ( ) { String bindType = getConverter ( ) . getBindType ( ) . name ( ) ; return bindType . charAt ( 0 ) + bindType . toLowerCase ( ) . substring ( 1 ) ; }


Input: Capitalizes the first letter to create a valid getter / setter name . [CODESPLIT] private String capFirst ( String anyName ) { // obscure Java convention: // if second letter capitalized, leave it alone if ( anyName . length ( ) > 1 ) if ( anyName . charAt ( 1 ) >= ' ' && anyName . charAt ( 1 ) <= ' ' ) return anyName ; String capFirstLetter = anyName . substring ( 0 , 1 ) . toUpperCase ( ) ; return capFirstLetter + anyName . substring ( 1 ) ; }


Input: Attempts to import a database table from a CSV file in the default location . [CODESPLIT] public int importFromCsv ( Context ctx , SQLiteDatabase db , String suffix ) { String filename = getCsvFilename ( db . getPath ( ) , db . getVersion ( ) , suffix ) ; FileInputStream fileInputStream ; try { fileInputStream = ctx . openFileInput ( filename ) ; return importFromCsv ( db , fileInputStream ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; return - 1 ; } }


Input: Attempts to import a database table from an { @link InputStream } formatted as a CSV file . Does all inserts in a single transaction for efficiency and so that all inserts will succeed or fail together . [CODESPLIT] public int importFromCsv ( SQLiteDatabase db , InputStream is ) { int numInserts = 0 ; db . beginTransaction ( ) ; insertHelper = new DatabaseUtils . InsertHelper ( db , th . getTableName ( ) ) ; try { InputStreamReader isr = new InputStreamReader ( is ) ; BufferedReader reader = new BufferedReader ( isr ) ; String headerRow = reader . readLine ( ) ; String csvRow = reader . readLine ( ) ; while ( csvRow != null ) { long rowId = parseAndInsertRow ( csvRow ) ; if ( rowId == - 1L ) { throw new RuntimeException ( "Error after row " + numInserts ) ; } numInserts ++ ; csvRow = reader . readLine ( ) ; } db . setTransactionSuccessful ( ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { db . endTransaction ( ) ; } return numInserts ; }


Input: Parse the values in a CSV row map them to the table column order and insert . Uses { @link InsertHelper } so it may be called repeatedly within a transaction for max performance . [CODESPLIT] private long parseAndInsertRow ( String csvRow ) { List < String > textValues = CsvUtils . getValues ( csvRow ) ; insertHelper . prepareForInsert ( ) ; String [ ] rowValues = textValues . toArray ( new String [ textValues . size ( ) ] ) ; th . bindRowValues ( insertHelper , rowValues ) ; return insertHelper . execute ( ) ; }


Input: Calls { @link TableHelper#onCreate ( SQLiteDatabase ) } for each TableHelper . [CODESPLIT] @ Override public void onCreate ( SQLiteDatabase db ) { for ( TableHelper th : getTableHelpers ( ) ) { th . onCreate ( db ) ; } }