idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
10,600
public String serialize ( Object object ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Serializing object to Json" ) ; } XStream xstream = new XStream ( new JettisonMappedXmlDriver ( ) ) ; String json = xstream . toXML ( object ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Object serialized well" ) ; } return json ; }
Serializes an object to Json .
10,601
public Object deserialize ( String jsonObject ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Deserializing Json object" ) ; } XStream xstream = new XStream ( new JettisonMappedXmlDriver ( ) ) ; Object obj = xstream . fromXML ( jsonObject ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Object deserialized" ) ; } return obj ; }
Deserializes a Json string representation to an object .
10,602
private Iterator < String > filterOutEmptyStrings ( final Iterator < String > splitted ) { return new Iterator < String > ( ) { String next = getNext ( ) ; public boolean hasNext ( ) { return next != null ; } public String next ( ) { if ( ! hasNext ( ) ) throw new NoSuchElementException ( ) ; String result = next ; next = getNext ( ) ; return result ; } public String getNext ( ) { while ( splitted . hasNext ( ) ) { String value = splitted . next ( ) ; if ( value != null && ! value . isEmpty ( ) ) { return value ; } } return null ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }
Its easier to understand if the logic for omit empty sequences is a filtering iterator
10,603
public static Envelope toJts ( Bbox bbox ) throws JtsConversionException { if ( bbox == null ) { throw new JtsConversionException ( "Cannot convert null argument" ) ; } return new Envelope ( bbox . getX ( ) , bbox . getMaxX ( ) , bbox . getY ( ) , bbox . getMaxY ( ) ) ; }
Convert a Geomajas bounding box to a JTS envelope .
10,604
public static com . vividsolutions . jts . geom . Coordinate toJts ( org . geomajas . geometry . Coordinate coordinate ) throws JtsConversionException { if ( coordinate == null ) { throw new JtsConversionException ( "Cannot convert null argument" ) ; } return new com . vividsolutions . jts . geom . Coordinate ( coordinate . getX ( ) , coordinate . getY ( ) ) ; }
Convert a Geomajas coordinate to a JTS coordinate .
10,605
public static Geometry fromJts ( com . vividsolutions . jts . geom . Geometry geometry ) throws JtsConversionException { if ( geometry == null ) { throw new JtsConversionException ( "Cannot convert null argument" ) ; } int srid = geometry . getSRID ( ) ; int precision = - 1 ; PrecisionModel precisionmodel = geometry . getPrecisionModel ( ) ; if ( ! precisionmodel . isFloating ( ) ) { precision = ( int ) Math . log10 ( precisionmodel . getScale ( ) ) ; } String geometryType = getGeometryType ( geometry ) ; Geometry dto = new Geometry ( geometryType , srid , precision ) ; if ( geometry . isEmpty ( ) ) { } else if ( geometry instanceof Point ) { dto . setCoordinates ( convertCoordinates ( geometry ) ) ; } else if ( geometry instanceof LinearRing ) { dto . setCoordinates ( convertCoordinates ( geometry ) ) ; } else if ( geometry instanceof LineString ) { dto . setCoordinates ( convertCoordinates ( geometry ) ) ; } else if ( geometry instanceof Polygon ) { Polygon polygon = ( Polygon ) geometry ; Geometry [ ] geometries = new Geometry [ polygon . getNumInteriorRing ( ) + 1 ] ; for ( int i = 0 ; i < geometries . length ; i ++ ) { if ( i == 0 ) { geometries [ i ] = fromJts ( polygon . getExteriorRing ( ) ) ; } else { geometries [ i ] = fromJts ( polygon . getInteriorRingN ( i - 1 ) ) ; } } dto . setGeometries ( geometries ) ; } else if ( geometry instanceof MultiPoint ) { dto . setGeometries ( convertGeometries ( geometry ) ) ; } else if ( geometry instanceof MultiLineString ) { dto . setGeometries ( convertGeometries ( geometry ) ) ; } else if ( geometry instanceof MultiPolygon ) { dto . setGeometries ( convertGeometries ( geometry ) ) ; } else { throw new JtsConversionException ( "Cannot convert geometry: Unsupported type." ) ; } return dto ; }
Convert a JTS geometry to a Geomajas geometry .
10,606
public static Bbox fromJts ( Envelope envelope ) throws JtsConversionException { if ( envelope == null ) { throw new JtsConversionException ( "Cannot convert null argument" ) ; } return new Bbox ( envelope . getMinX ( ) , envelope . getMinY ( ) , envelope . getWidth ( ) , envelope . getHeight ( ) ) ; }
Convert a JTS envelope to a Geomajas bounding box .
10,607
public static Coordinate fromJts ( com . vividsolutions . jts . geom . Coordinate coordinate ) throws JtsConversionException { if ( coordinate == null ) { throw new JtsConversionException ( "Cannot convert null argument" ) ; } return new Coordinate ( coordinate . x , coordinate . y ) ; }
Convert a GTS coordinate to a Geomajas coordinate .
10,608
public long writeTo ( File fileOrDirectory ) throws IOException { long written = 0 ; OutputStream fileOut = null ; try { if ( fileName != null ) { File file ; if ( fileOrDirectory . isDirectory ( ) ) { file = new File ( fileOrDirectory , fileName ) ; } else { file = fileOrDirectory ; } if ( policy != null ) { file = policy . rename ( file ) ; fileName = file . getName ( ) ; } fileOut = new BufferedOutputStream ( new FileOutputStream ( file ) ) ; written = write ( fileOut ) ; } } finally { if ( fileOut != null ) fileOut . close ( ) ; } return written ; }
Write this file part to a file or directory . If the user supplied a file we write it to that file and if they supplied a directory we write it to that directory with the filename that accompanied it . If this part doesn t contain a file this method does nothing .
10,609
public long writeTo ( OutputStream out ) throws IOException { long size = 0 ; if ( fileName != null ) { size = write ( out ) ; } return size ; }
Write this file part to the given output stream . If this part doesn t contain a file this method does nothing .
10,610
long write ( OutputStream out ) throws IOException { if ( contentType . equals ( "application/x-macbinary" ) ) { out = new MacBinaryDecoderOutputStream ( out ) ; } long size = 0 ; int read ; byte [ ] buf = new byte [ 8 * 1024 ] ; while ( ( read = partInput . read ( buf ) ) != - 1 ) { out . write ( buf , 0 , read ) ; size += read ; } return size ; }
Internal method to write this file part ; doesn t check to see if it has contents first .
10,611
public static Xml readAllFromResource ( String resourceName ) { InputStream is = XmlReader . class . getResourceAsStream ( resourceName ) ; XmlReader reader = new XmlReader ( is ) ; Xml xml = reader . read ( "node()" ) ; reader . close ( ) ; return xml ; }
Read all XML content from a resource location
10,612
private void init ( InputStream inputStream ) { this . inputStream = inputStream ; currentPath = new LinkedList < Node > ( ) ; nodeQueue = new LinkedList < XmlNode > ( ) ; XMLInputFactory factory = XMLInputFactory . newInstance ( ) ; factory . setProperty ( "javax.xml.stream.isCoalescing" , true ) ; factory . setProperty ( "javax.xml.stream.isReplacingEntityReferences" , true ) ; try { reader = factory . createXMLStreamReader ( inputStream ) ; } catch ( XMLStreamException e ) { throw new XmlReaderException ( e ) ; } }
Initialize XML reader for processing
10,613
public boolean find ( String xmlPathQuery ) { XmlPath xmlPath = XmlPathParser . parse ( xmlPathQuery ) ; XmlNode node ; while ( ( node = pullXmlNode ( ) ) != null ) { if ( node instanceof XmlStartElement ) { XmlStartElement startElement = ( XmlStartElement ) node ; Element element = new Element ( startElement . getLocalName ( ) ) ; element . addAttributes ( startElement . getAttributes ( ) ) ; currentPath . addLast ( element ) ; if ( xmlPath . matches ( currentPath ) ) { nodeQueue . push ( node ) ; currentPath . removeLast ( ) ; return true ; } } else if ( node instanceof XmlEndElement ) { if ( currentPath . getLast ( ) instanceof Content ) { currentPath . removeLast ( ) ; } currentPath . removeLast ( ) ; } else if ( node instanceof XmlContent ) { XmlContent content = ( XmlContent ) node ; if ( currentPath . getLast ( ) instanceof Content ) { currentPath . removeLast ( ) ; } currentPath . addLast ( new Content ( content . getText ( ) ) ) ; } else { throw new XmlReaderException ( "Unknown XmlNode type: " + node ) ; } } return false ; }
Find position in input stream that matches XML path query
10,614
private XmlNode pullXmlNode ( ) { if ( ! nodeQueue . isEmpty ( ) ) { return nodeQueue . poll ( ) ; } try { while ( reader . hasNext ( ) ) { int event = reader . next ( ) ; switch ( event ) { case XMLStreamConstants . START_ELEMENT : return new XmlStartElement ( reader . getLocalName ( ) , getAttributes ( reader ) ) ; case XMLStreamConstants . CHARACTERS : String text = filterWhitespace ( reader . getText ( ) ) ; if ( text . length ( ) > 0 ) { return new XmlContent ( text ) ; } break ; case XMLStreamConstants . END_ELEMENT : return new XmlEndElement ( reader . getLocalName ( ) ) ; default : } } } catch ( XMLStreamException e ) { throw new XmlReaderException ( e ) ; } return null ; }
Pull an XML node object from the input stream
10,615
private String filterWhitespace ( String text ) { text = text . replace ( "\n" , " " ) ; text = text . replaceAll ( " {2,}" , " " ) ; text = XmlEscape . escape ( text ) ; return text . trim ( ) ; }
This method filters out white space characters
10,616
private List < Attribute > getAttributes ( XMLStreamReader reader ) { List < Attribute > list = new ArrayList < Attribute > ( ) ; for ( int i = 0 ; i < reader . getAttributeCount ( ) ; i ++ ) { list . add ( new Attribute ( reader . getAttributeLocalName ( i ) , reader . getAttributeValue ( i ) ) ) ; } return list ; }
Extract XML element attributes form XML input stream
10,617
private static boolean isOverridable ( Method method , Class < ? > targetClass ) { if ( Modifier . isPrivate ( method . getModifiers ( ) ) ) { return false ; } if ( Modifier . isPublic ( method . getModifiers ( ) ) || Modifier . isProtected ( method . getModifiers ( ) ) ) { return true ; } return ( targetClass == null || getPackageName ( method . getDeclaringClass ( ) ) . equals ( getPackageName ( targetClass ) ) ) ; }
Determine whether the given method is overridable in the given target class .
10,618
< I > void register ( Method disposeMethod , I injectee ) { disposables . add ( new Disposable ( disposeMethod , injectee ) ) ; }
Register an injectee and its related method to release resources .
10,619
public void dispatch ( ParameterResolveFactory parameterResolveFactory , ActionParam param , Route route , Object [ ] args ) { if ( ! route . isRegex ( ) ) return ; Matcher matcher = route . getMatcher ( ) ; String [ ] pathParameters = new String [ matcher . groupCount ( ) ] ; for ( int i = 1 , len = matcher . groupCount ( ) ; i <= len ; i ++ ) { pathParameters [ i - 1 ] = matcher . group ( i ) ; } Map < String , String > path = new HashMap < > ( ) ; route . getRegexRoute ( ) . getNames ( ) . forEach ( name -> CollectionKit . MapAdd ( path , name , matcher . group ( name ) ) ) ; param . getRequest ( ) . setPathNamedParameters ( path ) ; param . getRequest ( ) . setPathParameters ( pathParameters ) ; }
prepare to resolve path parameters
10,620
public File createDir ( File dir ) throws DataUtilException { if ( dir == null ) { throw new DataUtilException ( "Dir parameter can not be a null value" ) ; } if ( dir . exists ( ) ) { throw new DataUtilException ( "Directory already exists: " + dir . getAbsolutePath ( ) ) ; } if ( ! dir . mkdir ( ) ) { throw new DataUtilException ( "The result of File.mkDir() was false. Failed to create directory. : " + dir . getAbsolutePath ( ) ) ; } trackedFiles . add ( dir ) ; return dir ; }
Create and add a new directory
10,621
public void deleteAll ( ) { if ( trackedFiles . size ( ) == 0 ) { return ; } ArrayList < File > files = new ArrayList < File > ( trackedFiles ) ; Collections . sort ( files , filePathComparator ) ; for ( File file : files ) { if ( file . exists ( ) ) { if ( ! file . delete ( ) ) { throw new DataUtilException ( "Couldn't delete a tracked " + ( file . isFile ( ) ? "file" : "directory" + ": " ) + file . getAbsolutePath ( ) ) ; } } } trackedFiles . clear ( ) ; }
Delete all tracked files
10,622
public void removeTombstone ( final String path ) throws FedoraException { final HttpDelete delete = httpHelper . createDeleteMethod ( path + "/fcr:tombstone" ) ; try { final HttpResponse response = httpHelper . execute ( delete ) ; final StatusLine status = response . getStatusLine ( ) ; final String uri = delete . getURI ( ) . toString ( ) ; if ( status . getStatusCode ( ) == SC_NO_CONTENT ) { LOGGER . debug ( "triples updated successfully for resource {}" , uri ) ; } else if ( status . getStatusCode ( ) == SC_NOT_FOUND ) { LOGGER . error ( "resource {} does not exist, cannot update" , uri ) ; throw new NotFoundException ( "resource " + uri + " does not exist, cannot update" ) ; } else { LOGGER . error ( "error updating resource {}: {} {}" , uri , status . getStatusCode ( ) , status . getReasonPhrase ( ) ) ; throw new FedoraException ( "error updating resource " + uri + ": " + status . getStatusCode ( ) + " " + status . getReasonPhrase ( ) ) ; } } catch ( final FedoraException e ) { throw e ; } catch ( final Exception e ) { LOGGER . error ( "Error executing request" , e ) ; throw new FedoraException ( e ) ; } finally { delete . releaseConnection ( ) ; } }
Remove tombstone located at given path
10,623
protected Collection < String > getPropertyValues ( final Property property ) { final ExtendedIterator < Triple > iterator = graph . find ( Node . ANY , property . asNode ( ) , Node . ANY ) ; final Set < String > set = new HashSet < > ( ) ; while ( iterator . hasNext ( ) ) { final Node object = iterator . next ( ) . getObject ( ) ; if ( object . isLiteral ( ) ) { set . add ( object . getLiteralValue ( ) . toString ( ) ) ; } else if ( object . isURI ( ) ) { set . add ( object . getURI ( ) . toString ( ) ) ; } else { set . add ( object . toString ( ) ) ; } } return set ; }
Return all the values of a property
10,624
public static String generateRequestId ( ) { final SecureRandom sr = new SecureRandom ( ) ; final byte [ ] bytes = new byte [ 32 ] ; sr . nextBytes ( bytes ) ; return hexEncode ( bytes ) ; }
Generate a request ID suitable for passing to SAMLClient . createAuthnRequest .
10,625
public final boolean isAssignableTo ( MimeType mimeType ) { if ( mimeType . getPrimaryType ( ) . equals ( "*" ) ) { return true ; } if ( ! mimeType . getPrimaryType ( ) . equalsIgnoreCase ( getPrimaryType ( ) ) ) { return false ; } String mtSec = mimeType . getSecondaryType ( ) ; return mtSec . equals ( "*" ) || mtSec . equalsIgnoreCase ( getSecondaryType ( ) ) ; }
Checks if this MIME type is a subtype of the provided MIME type .
10,626
@ SuppressWarnings ( "rawtypes" ) public List < ServletDefinition > initJawrSpringServlets ( ServletContext servletContext ) throws ServletException { List < ServletDefinition > jawrServletDefinitions = new ArrayList < ServletDefinition > ( ) ; ContextLoader contextLoader = new ContextLoader ( ) ; WebApplicationContext applicationCtx = contextLoader . initWebApplicationContext ( servletContext ) ; Map < ? , ? > jawrControllersMap = applicationCtx . getBeansOfType ( JawrSpringController . class ) ; Iterator < ? > entrySetIterator = jawrControllersMap . entrySet ( ) . iterator ( ) ; while ( entrySetIterator . hasNext ( ) ) { JawrSpringController jawrController = ( JawrSpringController ) ( ( Map . Entry ) entrySetIterator . next ( ) ) . getValue ( ) ; Map < String , Object > initParams = new HashMap < String , Object > ( ) ; initParams . putAll ( jawrController . getInitParams ( ) ) ; ServletConfig servletConfig = new MockServletConfig ( SPRING_DISPATCHER_SERVLET , servletContext , initParams ) ; MockJawrSpringServlet servlet = new MockJawrSpringServlet ( jawrController , servletConfig ) ; ServletDefinition servletDefinition = new ServletDefinition ( servlet , servletConfig ) ; jawrServletDefinitions . add ( servletDefinition ) ; } contextLoader . closeWebApplicationContext ( servletContext ) ; return jawrServletDefinitions ; }
Initialize the servlets which will handle the request to the JawrSpringController
10,627
public static Graph filterTriples ( final Iterator < Triple > triples , final Node ... properties ) { final Graph filteredGraph = new RandomOrderGraph ( RandomOrderGraph . createDefaultGraph ( ) ) ; final Sink < Triple > graphOutput = new SinkTriplesToGraph ( true , filteredGraph ) ; final RDFSinkFilter rdfFilter = new RDFSinkFilter ( graphOutput , properties ) ; rdfFilter . start ( ) ; while ( triples . hasNext ( ) ) { final Triple triple = triples . next ( ) ; rdfFilter . triple ( triple ) ; } rdfFilter . finish ( ) ; return filteredGraph ; }
Filter the triples
10,628
public List < ? extends TypeMirror > directSupertypes ( TypeMirror t ) { switch ( t . getKind ( ) ) { case DECLARED : DeclaredType dt = ( DeclaredType ) t ; TypeElement te = ( TypeElement ) dt . asElement ( ) ; List < TypeMirror > list = new ArrayList < > ( ) ; TypeElement superclass = ( TypeElement ) asElement ( te . getSuperclass ( ) ) ; if ( superclass != null ) { list . add ( 0 , superclass . asType ( ) ) ; } list . addAll ( te . getInterfaces ( ) ) ; return list ; case EXECUTABLE : case PACKAGE : throw new IllegalArgumentException ( t . getKind ( ) . name ( ) ) ; default : throw new UnsupportedOperationException ( t . getKind ( ) . name ( ) + " not supported yet" ) ; } }
The direct superclass is the class from whose implementation the implementation of the current class is derived .
10,629
protected Provider < ObjectMapper > getJacksonProvider ( ) { return new Provider < ObjectMapper > ( ) { public ObjectMapper get ( ) { final ObjectMapper mapper = new ObjectMapper ( ) ; mapper . registerModule ( new JodaModule ( ) ) ; mapper . disable ( SerializationFeature . WRITE_DATES_AS_TIMESTAMPS ) ; return mapper ; } } ; }
Override this method to provide your own Jackson provider .
10,630
public Injector injector ( final ServletContextEvent event ) { return ( Injector ) event . getServletContext ( ) . getAttribute ( Injector . class . getName ( ) ) ; }
This method can be called by classes extending SetupServer to retrieve the actual injector . This requires some inside knowledge on where it is stored but the actual key is not visible outside the guice packages .
10,631
private void writeParent ( Account account , XmlStreamWriter writer ) throws Exception { writer . writeStartElement ( "RDF:Seq" ) ; writer . writeAttribute ( "RDF:about" , account . getId ( ) ) ; for ( Account child : account . getChildren ( ) ) { logger . fine ( " Write-RDF:li: " + child . getId ( ) ) ; writer . writeStartElement ( "RDF:li" ) ; writer . writeAttribute ( "RDF:resource" , child . getId ( ) ) ; writer . writeEndElement ( ) ; } writer . writeEndElement ( ) ; writeDescription ( account , writer ) ; for ( Account child : account . getChildren ( ) ) { logger . fine ( "Write-RDF:Desc: " + child . getName ( ) ) ; writeDescription ( child , writer ) ; } for ( Account child : account . getChildren ( ) ) { if ( child . getChildren ( ) . size ( ) > 0 ) { writeParent ( child , writer ) ; } } }
Writes a parent node to the stream recursing into any children .
10,632
private void writeFFGlobalSettings ( Database db , XmlStreamWriter writer ) throws Exception { writer . writeStartElement ( "RDF:Description" ) ; writer . writeAttribute ( "RDF:about" , RDFDatabaseReader . FF_GLOBAL_SETTINGS_URI ) ; for ( String key : db . getGlobalSettings ( ) . keySet ( ) ) { writer . writeAttribute ( key , db . getGlobalSettings ( ) . get ( key ) ) ; } writer . writeEndElement ( ) ; }
Writes the firefox settings back .
10,633
public static boolean intersectsLineSegment ( Coordinate a , Coordinate b , Coordinate c , Coordinate d ) { if ( ( a . getX ( ) == b . getX ( ) && a . getY ( ) == b . getY ( ) ) || ( c . getX ( ) == d . getX ( ) && c . getY ( ) == d . getY ( ) ) ) { return false ; } double c1 = cross ( a , c , a , b ) ; double c2 = cross ( a , b , c , d ) ; if ( c1 == 0 && c2 == 0 ) { double xmin = Math . min ( a . getX ( ) , b . getX ( ) ) ; double ymin = Math . min ( a . getY ( ) , b . getY ( ) ) ; double xmax = Math . max ( a . getX ( ) , b . getX ( ) ) ; double ymax = Math . max ( a . getY ( ) , b . getY ( ) ) ; if ( c . getX ( ) > xmin && c . getX ( ) < xmax && c . getY ( ) > ymin && c . getY ( ) < ymax ) { return true ; } else if ( d . getX ( ) > xmin && d . getX ( ) < xmax && d . getY ( ) > ymin && d . getY ( ) < ymax ) { return true ; } else { return c . getX ( ) >= xmin && c . getX ( ) <= xmax && c . getY ( ) >= ymin && c . getY ( ) <= ymax & d . getX ( ) >= xmin && d . getX ( ) <= xmax && d . getY ( ) >= ymin && d . getY ( ) <= ymax ; } } if ( c2 == 0 ) { return false ; } double u = c1 / c2 ; double t = cross ( a , c , c , d ) / c2 ; return ( t > 0 ) && ( t < 1 ) && ( u > 0 ) && ( u < 1 ) ; }
Calculates whether or not 2 line - segments intersect . The definition we use is that line segments intersect if they either cross or overlap . If they touch in 1 end point they do not intersect . This definition is most useful for checking polygon validity as touching rings in 1 point are allowed but crossing or overlapping not .
10,634
private static double cross ( Coordinate a1 , Coordinate a2 , Coordinate b1 , Coordinate b2 ) { return ( a2 . getX ( ) - a1 . getX ( ) ) * ( b2 . getY ( ) - b1 . getY ( ) ) - ( a2 . getY ( ) - a1 . getY ( ) ) * ( b2 . getX ( ) - b1 . getX ( ) ) ; }
cross - product of 2 vectors
10,635
public static double distance ( Coordinate c1 , Coordinate c2 ) { double a = c1 . getX ( ) - c2 . getX ( ) ; double b = c1 . getY ( ) - c2 . getY ( ) ; return Math . sqrt ( a * a + b * b ) ; }
Distance between 2 points .
10,636
public static double distance ( Coordinate c1 , Coordinate c2 , Coordinate c ) { return distance ( nearest ( c1 , c2 , c ) , c ) ; }
Distance between a point and a line segment . This method looks at the line segment c1 - c2 it does not regard it as a line . This means that the distance to c is calculated to a point between c1 and c2 .
10,637
public static Coordinate nearest ( Coordinate c1 , Coordinate c2 , Coordinate c ) { double len = distance ( c1 , c2 ) ; double u = ( c . getX ( ) - c1 . getX ( ) ) * ( c2 . getX ( ) - c1 . getX ( ) ) + ( c . getY ( ) - c1 . getY ( ) ) * ( c2 . getY ( ) - c1 . getY ( ) ) ; u = u / ( len * len ) ; if ( u < 0.00001 || u > 1 ) { double len1 = distance ( c , c1 ) ; double len2 = distance ( c , c2 ) ; if ( len1 < len2 ) { return c1 ; } return c2 ; } else { double x1 = c1 . getX ( ) + u * ( c2 . getX ( ) - c1 . getX ( ) ) ; double y1 = c1 . getY ( ) + u * ( c2 . getY ( ) - c1 . getY ( ) ) ; return new Coordinate ( x1 , y1 ) ; } }
Calculate which point on a line segment is nearest to the given coordinate . Will be perpendicular or one of the end - points .
10,638
public static boolean isXForwardedAllowed ( String remoteAddr ) { return isXForwardedAllowed ( ) && ( S . eq ( "all" , xForwardedAllowed ) || xForwardedAllowed . contains ( remoteAddr ) ) ; }
Does the remote address is allowed for x - forwarded header
10,639
public static String createId ( Account acc ) throws Exception { return Account . createId ( acc . getName ( ) + acc . getDesc ( ) + ( new Random ( ) ) . nextLong ( ) + Runtime . getRuntime ( ) . freeMemory ( ) ) ; }
Creates and _returns_ an ID from data in an account .
10,640
public Account getChild ( int index ) throws IndexOutOfBoundsException { if ( index < 0 || index >= children . size ( ) ) throw new IndexOutOfBoundsException ( "Illegal child index, " + index ) ; return children . get ( index ) ; }
Gets a specifically indexed child .
10,641
public boolean hasChild ( Account account ) { for ( Account child : children ) { if ( child . equals ( account ) ) return true ; } return false ; }
Tests if an account is a direct child of this account .
10,642
public int compareTo ( Account o ) { if ( this . isFolder ( ) && ! o . isFolder ( ) ) return - 1 ; else if ( ! this . isFolder ( ) && o . isFolder ( ) ) return 1 ; int result = name . compareToIgnoreCase ( o . name ) ; if ( result == 0 ) return name . compareTo ( o . name ) ; else return result ; }
Implements the Comparable&lt ; Account&gt ; interface this is based first on if the account is a folder or not . This is so that during sorting all folders are first in the list . Finally it is based on the name .
10,643
@ SuppressWarnings ( "UnusedDeclaration" ) public void setPatterns ( Iterable < AccountPatternData > patterns ) { this . patterns . clear ( ) ; for ( AccountPatternData data : patterns ) { this . patterns . add ( new AccountPatternData ( data ) ) ; } }
This will make a deep clone of the passed in Iterable . This will also replace any patterns already set .
10,644
public void close ( ) throws DiffException { try { if ( writer != null ) { writer . flush ( ) ; writer . close ( ) ; } } catch ( IOException e ) { throw new DiffException ( "Failed to close report file" , e ) ; } }
Close the file report instance and it s underlying writer
10,645
public void swapAccounts ( Database other ) { Account otherRoot = other . rootAccount ; other . rootAccount = rootAccount ; rootAccount = otherRoot ; boolean otherDirty = other . dirty ; other . dirty = dirty ; dirty = otherDirty ; HashMap < String , String > otherGlobalSettings = other . globalSettings ; other . globalSettings = globalSettings ; globalSettings = otherGlobalSettings ; }
Is is so that the after an database is loaded we can reuse this object This does not swap listeners .
10,646
public void addAccount ( Account parent , Account child ) throws Exception { for ( Account dup : parent . getChildren ( ) ) { if ( dup == child ) { logger . warning ( "Duplicate RDF:li=" + child . getId ( ) + " detected. Dropping duplicate" ) ; return ; } } int iterationCount = 0 ; final int maxIteration = 0x100000 ; while ( findAccountById ( child . getId ( ) ) != null && ( iterationCount ++ < maxIteration ) ) { logger . warning ( "ID collision detected on '" + child . getId ( ) + "', attempting to regenerate ID. iteration=" + iterationCount ) ; child . setId ( Account . createId ( child ) ) ; } if ( iterationCount >= maxIteration ) { throw new Exception ( "Could not genererate a unique ID in " + iterationCount + " iterations, this is really rare. I know it's lame, but change the description and try again." ) ; } parent . getChildren ( ) . add ( child ) ; sendAccountAdded ( parent , child ) ; setDirty ( true ) ; }
Adds an account to a parent . This will first check to see if the account already has a parent and if so remove it from that parent before adding it to the new parent .
10,647
public void removeAccount ( Account accountToDelete ) { if ( accountToDelete . getId ( ) . equals ( rootAccount . getId ( ) ) ) return ; Account parent = findParent ( accountToDelete ) ; if ( parent != null ) { removeAccount ( parent , accountToDelete ) ; setDirty ( true ) ; } }
Removes an account from a parent account .
10,648
private void removeAccount ( Account parent , Account child ) { parent . getChildren ( ) . remove ( child ) ; sendAccountRemoved ( parent , child ) ; }
Internal routine to remove a child from a parent . Notifies the listeners of the removal
10,649
public void setGlobalSetting ( String name , String value ) { String oldValue ; if ( globalSettings . containsKey ( name ) ) { oldValue = globalSettings . get ( name ) ; if ( value . compareTo ( oldValue ) == 0 ) return ; } globalSettings . put ( name , value ) ; setDirty ( true ) ; }
Sets a firefox global setting . This allows any name and should be avoided . It is used by the RDF reader .
10,650
public String getGlobalSetting ( GlobalSettingKey key ) { if ( globalSettings . containsKey ( key . toString ( ) ) ) return globalSettings . get ( key . toString ( ) ) ; return key . getDefault ( ) ; }
The preferred way of getting a global setting value .
10,651
private void printDatabase ( Account acc , int level , PrintStream stream ) { String buf = "" ; for ( int i = 0 ; i < level ; i ++ ) buf += " " ; buf += "+" ; buf += acc . getName ( ) + "[" + acc . getUrl ( ) + "] (" + acc . getPatterns ( ) . size ( ) + " patterns)" ; stream . println ( buf ) ; for ( Account account : acc . getChildren ( ) ) printDatabase ( account , level + 2 , stream ) ; }
Gooey recursiveness .
10,652
private static int checkResult ( int result ) { if ( exceptionsEnabled && result != curandStatus . CURAND_STATUS_SUCCESS ) { throw new CudaException ( curandStatus . stringFor ( result ) ) ; } return result ; }
If the given result is not curandStatus . CURAND_STATUS_SUCCESS and exceptions have been enabled this method will throw a CudaException with an error message that corresponds to the given result code . Otherwise the given result is simply returned .
10,653
public final void nameArgument ( String name , int index ) { VariableElement lv = getLocalVariable ( index ) ; if ( lv instanceof UpdateableElement ) { UpdateableElement ue = ( UpdateableElement ) lv ; ue . setSimpleName ( El . getName ( name ) ) ; } else { throw new IllegalArgumentException ( "local variable at index " + index + " cannot be named" ) ; } }
Names an argument
10,654
public VariableElement getLocalVariable ( int index ) { int idx = 0 ; for ( VariableElement lv : localVariables ) { if ( idx == index ) { return lv ; } if ( Typ . isCategory2 ( lv . asType ( ) ) ) { idx += 2 ; } else { idx ++ ; } } throw new IllegalArgumentException ( "local variable at index " + index + " not found" ) ; }
Returns local variable at index . Note! long and double take two positions .
10,655
public String getLocalName ( int index ) { VariableElement lv = getLocalVariable ( index ) ; return lv . getSimpleName ( ) . toString ( ) ; }
Returns the name of local variable at index
10,656
public TypeMirror getLocalType ( String name ) { VariableElement lv = getLocalVariable ( name ) ; return lv . asType ( ) ; }
returns the type of local variable named name .
10,657
public String getLocalDescription ( int index ) { StringWriter sw = new StringWriter ( ) ; El . printElements ( sw , getLocalVariable ( index ) ) ; return sw . toString ( ) ; }
return a descriptive text about local variable named name .
10,658
public void loadDefault ( TypeMirror type ) throws IOException { if ( type . getKind ( ) != TypeKind . VOID ) { if ( Typ . isPrimitive ( type ) ) { tconst ( type , 0 ) ; } else { aconst_null ( ) ; } } }
Load default value to stack depending on type
10,659
public void startSubroutine ( String target ) throws IOException { if ( subroutine != null ) { throw new IllegalStateException ( "subroutine " + subroutine + " not ended when " + target + "started" ) ; } subroutine = target ; if ( ! hasLocalVariable ( SUBROUTINERETURNADDRESSNAME ) ) { addVariable ( SUBROUTINERETURNADDRESSNAME , Typ . ReturnAddress ) ; } fixAddress ( target ) ; tstore ( SUBROUTINERETURNADDRESSNAME ) ; }
Compiles the subroutine start . Use endSubroutine to end that subroutine .
10,660
public TypeMirror typeForCount ( int count ) { if ( count <= Byte . MAX_VALUE ) { return Typ . Byte ; } if ( count <= Short . MAX_VALUE ) { return Typ . Short ; } if ( count <= Integer . MAX_VALUE ) { return Typ . Int ; } return Typ . Long ; }
Return a integral class able to support count values
10,661
public void fixAddress ( String name ) throws IOException { super . fixAddress ( name ) ; if ( debugMethod != null ) { int position = position ( ) ; tload ( "this" ) ; ldc ( position ) ; ldc ( name ) ; invokevirtual ( debugMethod ) ; } }
Labels a current position
10,662
public Route matchRoute ( String url ) { if ( hashRoute . containsKey ( url ) ) { return new Route ( hashRoute . get ( url ) . get ( 0 ) , null ) ; } for ( RegexRoute route : regexRoute ) { Matcher matcher = route . getPattern ( ) . matcher ( url ) ; if ( matcher . matches ( ) ) { return new Route ( route , matcher ) ; } } return null ; }
simple match route
10,663
public void addAttributes ( List < Attribute > attributes ) { for ( Attribute attribute : attributes ) { addAttribute ( attribute . getName ( ) , attribute . getValue ( ) ) ; } }
Add element attributes
10,664
public void addAttribute ( String attributeName , String attributeValue ) throws XmlModelException { String name = attributeName . trim ( ) ; String value = attributeValue . trim ( ) ; if ( attributesMap . containsKey ( name ) ) { throw new XmlModelException ( "Duplicate attribute: " + name ) ; } attributeNames . add ( name ) ; attributesMap . put ( name , new Attribute ( name , value ) ) ; }
Add a new element attribute
10,665
private static void tc ( Map < M , Set < M > > index ) { final Map < String , Object [ ] > warnings = new HashMap < > ( ) ; for ( Entry < M , Set < M > > entry : index . entrySet ( ) ) { final M src = entry . getKey ( ) ; final Set < M > dependents = entry . getValue ( ) ; final Queue < M > queue = new LinkedList < M > ( dependents ) ; while ( ! queue . isEmpty ( ) ) { final M key = queue . poll ( ) ; if ( ! index . containsKey ( key ) ) { continue ; } for ( M addition : index . get ( key ) ) { if ( ! dependents . contains ( addition ) ) { dependents . add ( addition ) ; queue . add ( addition ) ; warnings . put ( src + "|" + addition + "|" + key , new Object [ ] { src , addition , key } ) ; } } } } for ( final Object [ ] args : warnings . values ( ) ) { StructuredLog . ImpliedTransitiveDependency . warn ( log , args ) ; } }
Compute the transitive closure of the dependencies
10,666
private < I > void hear ( Class < ? super I > type , TypeEncounter < I > encounter ) { if ( type == null || type . getPackage ( ) . getName ( ) . startsWith ( JAVA_PACKAGE ) ) { return ; } for ( Method method : type . getDeclaredMethods ( ) ) { if ( method . isAnnotationPresent ( annotationType ) ) { if ( method . getParameterTypes ( ) . length != 0 ) { encounter . addError ( "Annotated methods with @%s must not accept any argument, found %s" , annotationType . getName ( ) , method ) ; } hear ( method , encounter ) ; } } hear ( type . getSuperclass ( ) , encounter ) ; }
Allows traverse the input type hierarchy .
10,667
public ResultSetStreamer require ( String column , Assertion assertion ) { if ( _requires == Collections . EMPTY_MAP ) _requires = new HashMap < String , Assertion > ( ) ; _requires . put ( column , assertion ) ; return this ; }
Requires a data column to satisfy an assertion .
10,668
public ResultSetStreamer exclude ( String column , Assertion assertion ) { if ( _excludes == Collections . EMPTY_MAP ) _excludes = new HashMap < String , Assertion > ( ) ; _excludes . put ( column , assertion ) ; return this ; }
Excludes rows whose data columns satisfy an assertion .
10,669
public static < T extends Executable > Predicate < T > executableIsSynthetic ( ) { return candidate -> candidate != null && candidate . isSynthetic ( ) ; }
Checks if a candidate executable is synthetic .
10,670
public static < T extends Executable > Predicate < T > executableBelongsToClass ( Class < ? > reference ) { return candidate -> candidate != null && reference . equals ( candidate . getDeclaringClass ( ) ) ; }
Checks if a candidate executable does belong to the specified class .
10,671
public static < T extends Executable > Predicate < T > executableBelongsToClassAssignableTo ( Class < ? > reference ) { return candidate -> candidate != null && reference . isAssignableFrom ( candidate . getDeclaringClass ( ) ) ; }
Checks if a candidate executable does belong to a class assignable as the specified class .
10,672
public static < T extends Executable > Predicate < T > executableIsEquivalentTo ( T reference ) { Predicate < T > predicate = candidate -> candidate != null && candidate . getName ( ) . equals ( reference . getName ( ) ) && executableHasSameParameterTypesAs ( reference ) . test ( candidate ) ; if ( reference instanceof Method ) { predicate . and ( candidate -> candidate instanceof Method && ( ( Method ) candidate ) . getReturnType ( ) . equals ( ( ( Method ) reference ) . getReturnType ( ) ) ) ; } return predicate ; }
Checks if a candidate executable is equivalent to the specified reference executable .
10,673
public static < T extends Executable > Predicate < T > executableHasSameParameterTypesAs ( T reference ) { return candidate -> { if ( candidate == null ) { return false ; } Class < ? > [ ] candidateParameterTypes = candidate . getParameterTypes ( ) ; Class < ? > [ ] referenceParameterTypes = reference . getParameterTypes ( ) ; if ( candidateParameterTypes . length != referenceParameterTypes . length ) { return false ; } for ( int i = 0 ; i < candidateParameterTypes . length ; i ++ ) { if ( ! candidateParameterTypes [ i ] . equals ( referenceParameterTypes [ i ] ) ) { return false ; } } return true ; } ; }
Checks if a candidate executable has the same parameter type as the specified reference executable .
10,674
public void run ( ) { try { try { turnsControl . waitTurns ( 1 , "Robot starting" ) ; } catch ( BankInterruptedException exc ) { log . trace ( "[run] Interrupted before starting" ) ; } assert getData ( ) . isEnabled ( ) : "Robot is disabled" ; mainLoop ( ) ; log . debug ( "[run] Robot terminated gracefully" ) ; } catch ( Exception | Error all ) { log . error ( "[run] Problem running robot " + this , all ) ; die ( "Execution Error -- " + all ) ; } }
The main loop of the robot
10,675
public void die ( String reason ) { log . info ( "[die] Robot {} died with reason: {}" , serialNumber , reason ) ; if ( alive ) { alive = false ; interrupted = true ; world . remove ( Robot . this ) ; } }
Kills the robot and removes it from the board
10,676
protected List < FileStatus > listStatus ( JobContext job ) throws IOException { List < FileStatus > result = new ArrayList < FileStatus > ( ) ; Path [ ] dirs = getInputPaths ( job ) ; if ( dirs . length == 0 ) { throw new IOException ( "No input paths specified in job" ) ; } TokenCache . obtainTokensForNamenodes ( job . getCredentials ( ) , dirs , job . getConfiguration ( ) ) ; List < IOException > errors = new ArrayList < IOException > ( ) ; for ( Path p : dirs ) { FileSystem fs = p . getFileSystem ( job . getConfiguration ( ) ) ; final SmilePathFilter filter = new SmilePathFilter ( ) ; FileStatus [ ] matches = fs . globStatus ( p , filter ) ; if ( matches == null ) { errors . add ( new IOException ( "Input path does not exist: " + p ) ) ; } else if ( matches . length == 0 ) { errors . add ( new IOException ( "Input Pattern " + p + " matches 0 files" ) ) ; } else { for ( FileStatus globStat : matches ) { if ( globStat . isDir ( ) ) { Collections . addAll ( result , fs . listStatus ( globStat . getPath ( ) , filter ) ) ; } else { result . add ( globStat ) ; } } } } if ( ! errors . isEmpty ( ) ) { throw new InvalidInputException ( errors ) ; } return result ; }
List input directories .
10,677
protected void checkInputClass ( final Object domainObject ) { final Class < ? > actualInputType = domainObject . getClass ( ) ; if ( ! ( expectedInputType . isAssignableFrom ( actualInputType ) ) ) { throw new IllegalArgumentException ( "The input document is required to be of type: " + expectedInputType . getName ( ) ) ; } }
Optional hook ; default implementation checks that the input type is of the correct type .
10,678
public void setTimeout ( long timeout , TimeUnit unit ) { this . timeout = TimeUnit . MILLISECONDS . convert ( timeout , unit ) ; }
Change the idle timeout .
10,679
public final void sendObjectToSocket ( Object o ) { Session sess = this . getSession ( ) ; if ( sess != null ) { String json ; try { json = this . mapper . writeValueAsString ( o ) ; } catch ( JsonProcessingException e ) { ClientSocketAdapter . LOGGER . error ( "Failed to serialize object" , e ) ; return ; } sess . getRemote ( ) . sendString ( json , new WriteCallback ( ) { public void writeSuccess ( ) { ClientSocketAdapter . LOGGER . info ( "Send data to socket" ) ; } public void writeFailed ( Throwable x ) { ClientSocketAdapter . LOGGER . error ( "Error sending message to socket" , x ) ; } } ) ; } }
send the given object to the server using JSON serialization
10,680
protected final < T > T readMessage ( String message , Class < T > clazz ) { if ( ( message == null ) || message . isEmpty ( ) ) { ClientSocketAdapter . LOGGER . info ( "Got empty session data" ) ; return null ; } try { return this . mapper . readValue ( message , clazz ) ; } catch ( IOException e1 ) { ClientSocketAdapter . LOGGER . info ( "Got invalid session data" , e1 ) ; return null ; } }
reads the received string into the given class by parsing JSON
10,681
public ByteBuffer makeByteBuffer ( InputStream in ) throws IOException { int limit = in . available ( ) ; if ( limit < 1024 ) limit = 1024 ; ByteBuffer result = byteBufferCache . get ( limit ) ; int position = 0 ; while ( in . available ( ) != 0 ) { if ( position >= limit ) result = ByteBuffer . allocate ( limit <<= 1 ) . put ( ( ByteBuffer ) result . flip ( ) ) ; int count = in . read ( result . array ( ) , position , limit - position ) ; if ( count < 0 ) break ; result . position ( position += count ) ; } return ( ByteBuffer ) result . flip ( ) ; }
Make a byte buffer from an input stream .
10,682
public void add ( Collection < BrowserApplication > browserApplications ) { for ( BrowserApplication browserApplication : browserApplications ) this . browserApplications . put ( browserApplication . getId ( ) , browserApplication ) ; }
Adds the browser application list to the browser applications for the account .
10,683
public static Object getProperty ( Object object , String name ) throws NoSuchFieldException { try { Matcher matcher = ARRAY_INDEX . matcher ( name ) ; if ( matcher . matches ( ) ) { object = getProperty ( object , matcher . group ( 1 ) ) ; if ( object . getClass ( ) . isArray ( ) ) { return Array . get ( object , Integer . parseInt ( matcher . group ( 2 ) ) ) ; } else { return ( ( List ) object ) . get ( Integer . parseInt ( matcher . group ( 2 ) ) ) ; } } else { int dot = name . lastIndexOf ( '.' ) ; if ( dot > 0 ) { object = getProperty ( object , name . substring ( 0 , dot ) ) ; name = name . substring ( dot + 1 ) ; } return Beans . getKnownField ( object . getClass ( ) , name ) . get ( object ) ; } } catch ( NoSuchFieldException x ) { throw x ; } catch ( Exception x ) { throw new IllegalArgumentException ( x . getMessage ( ) + ": " + name , x ) ; } }
Reports a property .
10,684
@ SuppressWarnings ( "unchecked" ) public static void setProperty ( Object object , String name , String text ) throws NoSuchFieldException { try { int length = name . lastIndexOf ( '.' ) ; if ( length > 0 ) { object = getProperty ( object , name . substring ( 0 , length ) ) ; name = name . substring ( length + 1 ) ; } length = name . length ( ) ; Matcher matcher = ARRAY_INDEX . matcher ( name ) ; for ( Matcher m = matcher ; m . matches ( ) ; m = ARRAY_INDEX . matcher ( name ) ) { name = m . group ( 1 ) ; } Field field = Beans . getKnownField ( object . getClass ( ) , name ) ; if ( name . length ( ) != length ) { int index = Integer . parseInt ( matcher . group ( 2 ) ) ; object = getProperty ( object , matcher . group ( 1 ) ) ; if ( object . getClass ( ) . isArray ( ) ) { Array . set ( object , index , new ValueOf ( object . getClass ( ) . getComponentType ( ) , field . getAnnotation ( typeinfo . class ) ) . invoke ( text ) ) ; } else { ( ( List ) object ) . set ( index , new ValueOf ( field . getAnnotation ( typeinfo . class ) . value ( ) [ 0 ] ) . invoke ( text ) ) ; } } else { field . set ( object , new ValueOf ( field . getType ( ) , field . getAnnotation ( typeinfo . class ) ) . invoke ( text ) ) ; } } catch ( NoSuchFieldException x ) { throw x ; } catch ( Exception x ) { throw new IllegalArgumentException ( x . getMessage ( ) + ": " + name , x ) ; } }
Updates a property .
10,685
public static < T > T [ ] concat ( T [ ] first , T [ ] ... rest ) { int length = first . length ; for ( T [ ] array : rest ) { length += array . length ; } T [ ] result = Arrays . copyOf ( first , length ) ; int offset = first . length ; for ( T [ ] array : rest ) { System . arraycopy ( array , 0 , result , offset , array . length ) ; offset += array . length ; } return result ; }
Concatenates several reference arrays .
10,686
public Iterable < Di18n > queryByBaseBundle ( java . lang . String baseBundle ) { return queryByField ( null , Di18nMapper . Field . BASEBUNDLE . getFieldName ( ) , baseBundle ) ; }
query - by method for field baseBundle
10,687
public Iterable < Di18n > queryByKey ( java . lang . String key ) { return queryByField ( null , Di18nMapper . Field . KEY . getFieldName ( ) , key ) ; }
query - by method for field key
10,688
public Iterable < Di18n > queryByLocale ( java . lang . String locale ) { return queryByField ( null , Di18nMapper . Field . LOCALE . getFieldName ( ) , locale ) ; }
query - by method for field locale
10,689
public Iterable < Di18n > queryByLocalizedMessage ( java . lang . String localizedMessage ) { return queryByField ( null , Di18nMapper . Field . LOCALIZEDMESSAGE . getFieldName ( ) , localizedMessage ) ; }
query - by method for field localizedMessage
10,690
public static String maskExcept ( final String s , final int unmaskedLength , final char maskChar ) { if ( s == null ) { return null ; } final boolean maskLeading = unmaskedLength > 0 ; final int length = s . length ( ) ; final int maskedLength = Math . max ( 0 , length - Math . abs ( unmaskedLength ) ) ; if ( maskedLength > 0 ) { final String mask = StringUtils . repeat ( maskChar , maskedLength ) ; if ( maskLeading ) { return StringUtils . overlay ( s , mask , 0 , maskedLength ) ; } return StringUtils . overlay ( s , mask , length - maskedLength , length ) ; } return s ; }
Returns a masked string leaving only the given number of characters unmasked .
10,691
public static String replaceNonPrintableControlCharacters ( final String value ) { if ( value == null || value . length ( ) == 0 ) { return value ; } boolean changing = false ; for ( int i = 0 , length = value . length ( ) ; i < length ; i ++ ) { final char ch = value . charAt ( i ) ; if ( ch < 32 && ch != '\n' && ch != '\r' && ch != '\t' ) { changing = true ; break ; } } if ( ! changing ) { return value ; } final StringBuilder buf = new StringBuilder ( value ) ; for ( int i = 0 , length = buf . length ( ) ; i < length ; i ++ ) { final char ch = buf . charAt ( i ) ; if ( ch < 32 && ch != '\n' && ch != '\r' && ch != '\t' ) { buf . setCharAt ( i , ' ' ) ; } } return buf . toString ( ) ; }
Returns a string where non - printable control characters are replaced by whitespace .
10,692
public static String shortUuid ( ) { final byte [ ] randomBytes = new byte [ 16 ] ; UUID_GENERATOR . nextBytes ( randomBytes ) ; randomBytes [ 6 ] = ( byte ) ( randomBytes [ 6 ] & 0x0f ) ; randomBytes [ 6 ] = ( byte ) ( randomBytes [ 6 ] | 0x40 ) ; randomBytes [ 8 ] = ( byte ) ( randomBytes [ 8 ] & 0x3f ) ; randomBytes [ 8 ] = ( byte ) ( randomBytes [ 8 ] | 0x80 ) ; return BaseEncoding . base64Url ( ) . omitPadding ( ) . encode ( randomBytes ) ; }
Returns a short UUID which is encoding use base 64 characters instead of hexadecimal . This saves 10 bytes per UUID .
10,693
public static List < String > splitToList ( final String value ) { if ( ! StringUtils . isEmpty ( value ) ) { return COMMA_SPLITTER . splitToList ( value ) ; } return Collections . < String > emptyList ( ) ; }
Parses a comma - separated string and returns a list of String values .
10,694
public static String trimWhitespace ( final String s ) { if ( s == null || s . length ( ) == 0 ) { return s ; } final int length = s . length ( ) ; int end = length ; int start = 0 ; while ( start < end && Character . isWhitespace ( s . charAt ( start ) ) ) { start ++ ; } while ( start < end && Character . isWhitespace ( s . charAt ( end - 1 ) ) ) { end -- ; } return start > 0 || end < length ? s . substring ( start , end ) : s ; }
Strip leading and trailing whitespace from a String .
10,695
public static String trimWhitespaceToNull ( final String s ) { final String result = trimWhitespace ( s ) ; return StringUtils . isEmpty ( result ) ? null : s ; }
Strip leading and trailing whitespace from a String . If the resulting string is empty this method returns null .
10,696
public List < ServiceReference > getReferences ( String resourceType ) { List < ServiceReference > references = new ArrayList < ServiceReference > ( ) ; if ( containsKey ( resourceType ) ) { references . addAll ( get ( resourceType ) ) ; Collections . sort ( references , new Comparator < ServiceReference > ( ) { public int compare ( ServiceReference r0 , ServiceReference r1 ) { Integer p0 = OsgiUtil . toInteger ( r0 . getProperty ( ComponentBindingsProvider . PRIORITY ) , 0 ) ; Integer p1 = OsgiUtil . toInteger ( r1 . getProperty ( ComponentBindingsProvider . PRIORITY ) , 0 ) ; return - 1 * p0 . compareTo ( p1 ) ; } } ) ; } return references ; }
Gets the ComponentBindingProvider references for the specified resource type .
10,697
public void registerComponentBindingsProvider ( ServiceReference reference ) { log . info ( "registerComponentBindingsProvider" ) ; log . info ( "Registering Component Bindings Provider {} - {}" , new Object [ ] { reference . getProperty ( Constants . SERVICE_ID ) , reference . getProperty ( Constants . SERVICE_PID ) } ) ; String [ ] resourceTypes = OsgiUtil . toStringArray ( reference . getProperty ( ComponentBindingsProvider . RESOURCE_TYPE_PROP ) , new String [ 0 ] ) ; for ( String resourceType : resourceTypes ) { if ( ! this . containsKey ( resourceType ) ) { put ( resourceType , new HashSet < ServiceReference > ( ) ) ; } log . debug ( "Adding to resource type {}" , resourceType ) ; get ( resourceType ) . add ( reference ) ; } }
Registers the ComponentBindingsProvider specified by the ServiceReference .
10,698
public void unregisterComponentBindingsProvider ( ServiceReference reference ) { log . info ( "unregisterComponentBindingsProvider" ) ; String [ ] resourceTypes = OsgiUtil . toStringArray ( reference . getProperty ( ComponentBindingsProvider . RESOURCE_TYPE_PROP ) , new String [ 0 ] ) ; for ( String resourceType : resourceTypes ) { if ( ! this . containsKey ( resourceType ) ) { continue ; } get ( resourceType ) . remove ( reference ) ; } }
UnRegisters the ComponentBindingsProvider specified by the ServiceReference .
10,699
public ComponentFactory < T , E > toCreate ( BiFunction < Constructor , Object [ ] , Object > createFunction ) { return new ComponentFactory < > ( this . annotationType , this . classElement , this . contextConsumer , createFunction ) ; }
Sets the function used to create the objects .