idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
35,000
public static CharSequence truncate ( CharSequence s , int len ) { if ( s . length ( ) == len ) return ( s ) ; if ( s . length ( ) > len ) return ( s . subSequence ( 0 , len ) ) ; StringBuilder result = new StringBuilder ( s ) ; while ( result . length ( ) < len ) result . append ( ' ' ) ; return ( result ) ; }
Returns a string of the given length fills with spaces if necessary
35,001
public static String capitalize ( String s ) { StringBuilder result = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( i == 0 || i > 0 && ! Character . isLetterOrDigit ( s . charAt ( i - 1 ) ) ) c = Character . toUpperCase ( c ) ; else c = Character . toLowerCase ( c ) ; result . append ( c ) ; } return ( result . toString ( ) ) ; }
Capitalizes words and lowercases the rest
35,002
public static boolean endsWith ( CharSequence s , String end ) { return ( s . length ( ) >= end . length ( ) && s . subSequence ( s . length ( ) - end . length ( ) , s . length ( ) ) . equals ( end ) ) ; }
TRUE if the Charsequence ends with the string
35,003
public static StructrOAuthClient getServer ( final String name ) { String configuredOauthServers = Settings . OAuthServers . getValue ( ) ; String [ ] authServers = configuredOauthServers . split ( " " ) ; for ( String authServer : authServers ) { if ( authServer . equals ( name ) ) { String authLocation = Settings . getOrCreateStringSetting ( "oauth" , authServer , "authorization_location" ) . getValue ( "" ) ; String tokenLocation = Settings . getOrCreateStringSetting ( "oauth" , authServer , "token_location" ) . getValue ( "" ) ; String clientId = Settings . getOrCreateStringSetting ( "oauth" , authServer , "client_id" ) . getValue ( "" ) ; String clientSecret = Settings . getOrCreateStringSetting ( "oauth" , authServer , "client_secret" ) . getValue ( "" ) ; String redirectUri = Settings . getOrCreateStringSetting ( "oauth" , authServer , "redirect_uri" ) . getValue ( "" ) ; if ( clientId != null && clientSecret != null && redirectUri != null ) { Class serverClass = getServerClassForName ( name ) ; Class tokenResponseClass = getTokenResponseClassForName ( name ) ; if ( serverClass != null ) { StructrOAuthClient oauthServer ; try { oauthServer = ( StructrOAuthClient ) serverClass . newInstance ( ) ; oauthServer . init ( authLocation , tokenLocation , clientId , clientSecret , redirectUri , tokenResponseClass ) ; logger . info ( "Using OAuth server {}" , oauthServer ) ; return oauthServer ; } catch ( Throwable t ) { logger . error ( "Could not instantiate auth server" , t ) ; } } else { logger . warn ( "No OAuth provider found for name {}, ignoring." , name ) ; } } } } return null ; }
Build an OAuth2 server from the configured values for the given name .
35,004
public static < T extends File > T transformFile ( final SecurityContext securityContext , final String uuid , final Class < T > fileType ) throws FrameworkException , IOException { AbstractFile existingFile = getFileByUuid ( securityContext , uuid ) ; if ( existingFile != null ) { existingFile . unlockSystemPropertiesOnce ( ) ; existingFile . setProperties ( securityContext , new PropertyMap ( AbstractNode . type , fileType == null ? File . class . getSimpleName ( ) : fileType . getSimpleName ( ) ) ) ; existingFile = getFileByUuid ( securityContext , uuid ) ; return ( T ) ( fileType != null ? fileType . cast ( existingFile ) : ( File ) existingFile ) ; } return null ; }
Transform an existing file into the target class .
35,005
public static < T extends File > T createFileBase64 ( final SecurityContext securityContext , final String rawData , final Class < T > t ) throws FrameworkException , IOException { Base64URIData uriData = new Base64URIData ( rawData ) ; return createFile ( securityContext , uriData . getBinaryData ( ) , uriData . getContentType ( ) , t ) ; }
Create a new image node from image data encoded in base64 format .
35,006
public static < T extends File > T createFile ( final SecurityContext securityContext , final InputStream fileStream , final String contentType , final Class < T > fileType , final String name ) throws FrameworkException , IOException { return createFile ( securityContext , fileStream , contentType , fileType , name , null ) ; }
Create a new file node from the given input stream
35,007
public static void decodeAndSetFileData ( final File file , final String rawData ) throws FrameworkException , IOException { Base64URIData uriData = new Base64URIData ( rawData ) ; setFileData ( file , uriData . getBinaryData ( ) , uriData . getContentType ( ) , true ) ; }
Decodes base64 - encoded raw data into binary data and writes it to the given file .
35,008
public static void setFileData ( final File file , final InputStream fileStream , final String contentType ) throws FrameworkException , IOException { FileHelper . writeToFile ( file , fileStream ) ; setFileProperties ( file , contentType ) ; }
Write image data from the given InputStream to the given file node and set checksum and size .
35,009
public static void setFileProperties ( final File file , final String contentType ) throws IOException , FrameworkException { final java . io . File fileOnDisk = file . getFileOnDisk ( false ) ; final PropertyMap map = new PropertyMap ( ) ; map . put ( StructrApp . key ( File . class , "contentType" ) , contentType != null ? contentType : FileHelper . getContentMimeType ( fileOnDisk , file . getProperty ( File . name ) ) ) ; map . put ( StructrApp . key ( File . class , "size" ) , FileHelper . getSize ( fileOnDisk ) ) ; map . put ( StructrApp . key ( File . class , "version" ) , 1 ) ; map . putAll ( getChecksums ( file , fileOnDisk ) ) ; file . setProperties ( file . getSecurityContext ( ) , map ) ; }
Set the contentType checksum size and version properties of the given fileNode
35,010
public static void setFileProperties ( File fileNode ) throws FrameworkException { final PropertyMap properties = new PropertyMap ( ) ; String id = fileNode . getProperty ( GraphObject . id ) ; if ( id == null ) { final String newUuid = UUID . randomUUID ( ) . toString ( ) . replaceAll ( "[\\-]+" , "" ) ; id = newUuid ; fileNode . unlockSystemPropertiesOnce ( ) ; properties . put ( GraphObject . id , newUuid ) ; } fileNode . unlockSystemPropertiesOnce ( ) ; fileNode . setProperties ( fileNode . getSecurityContext ( ) , properties ) ; }
Set the uuid and the path of a newly created fileNode
35,011
private static PropertyMap getChecksums ( final File file , final java . io . File fileOnDisk ) throws IOException { final PropertyMap propertiesWithChecksums = new PropertyMap ( ) ; Folder parentFolder = file . getParent ( ) ; String checksums = null ; while ( parentFolder != null && checksums == null ) { checksums = parentFolder . getEnabledChecksums ( ) ; parentFolder = parentFolder . getParent ( ) ; } if ( checksums == null ) { checksums = Settings . DefaultChecksums . getValue ( ) ; } propertiesWithChecksums . put ( StructrApp . key ( File . class , "checksum" ) , FileHelper . getChecksum ( fileOnDisk ) ) ; if ( StringUtils . contains ( checksums , "crc32" ) ) { propertiesWithChecksums . put ( StructrApp . key ( File . class , "crc32" ) , FileHelper . getCRC32Checksum ( fileOnDisk ) ) ; } if ( StringUtils . contains ( checksums , "md5" ) ) { propertiesWithChecksums . put ( StructrApp . key ( File . class , "md5" ) , FileHelper . getMD5Checksum ( file ) ) ; } if ( StringUtils . contains ( checksums , "sha1" ) ) { propertiesWithChecksums . put ( StructrApp . key ( File . class , "sha1" ) , FileHelper . getSHA1Checksum ( file ) ) ; } if ( StringUtils . contains ( checksums , "sha512" ) ) { propertiesWithChecksums . put ( StructrApp . key ( File . class , "sha512" ) , FileHelper . getSHA512Checksum ( file ) ) ; } return propertiesWithChecksums ; }
Calculate checksums that are configured in settings of parent folder .
35,012
public static void updateMetadata ( final File file , final PropertyMap map ) throws FrameworkException { updateMetadata ( file , map , false ) ; }
Update checksums content type size and additional properties of the given file
35,013
public static void writeToFile ( final File fileNode , final InputStream data ) throws FrameworkException , IOException { setFileProperties ( fileNode ) ; try ( final FileOutputStream out = new FileOutputStream ( fileNode . getFileOnDisk ( ) ) ) { IOUtils . copy ( data , out ) ; } }
Write binary data from FileInputStream to a file and reference the file on disk at the given file node
35,014
public static AbstractFile getFileByAbsolutePath ( final SecurityContext securityContext , final String absolutePath ) { try { return StructrApp . getInstance ( securityContext ) . nodeQuery ( AbstractFile . class ) . and ( StructrApp . key ( AbstractFile . class , "path" ) , absolutePath ) . getFirst ( ) ; } catch ( FrameworkException ex ) { ex . printStackTrace ( ) ; logger . warn ( "File not found: {}" , absolutePath ) ; } return null ; }
Find a file by its absolute ancestor path .
35,015
public static Folder createFolderPath ( final SecurityContext securityContext , final String path ) throws FrameworkException { final App app = StructrApp . getInstance ( securityContext ) ; if ( path == null ) { return null ; } Folder folder = ( Folder ) FileHelper . getFileByAbsolutePath ( securityContext , path ) ; if ( folder != null ) { return folder ; } String [ ] parts = PathHelper . getParts ( path ) ; String partialPath = "" ; for ( String part : parts ) { if ( ".." . equals ( part ) || "." . equals ( part ) ) { continue ; } Folder parent = folder ; partialPath += PathHelper . PATH_SEP + part ; folder = ( Folder ) FileHelper . getFileByAbsolutePath ( securityContext , partialPath ) ; if ( folder == null ) { folder = app . create ( Folder . class , part ) ; } if ( parent != null ) { folder . setParent ( parent ) ; } } return folder ; }
Create one folder per path item and return the last folder .
35,016
public static boolean noLatin ( String s ) { return ( s . indexOf ( 'h' ) > 0 || s . indexOf ( 'j' ) > 0 || s . indexOf ( 'k' ) > 0 || s . indexOf ( 'w' ) > 0 || s . indexOf ( 'y' ) > 0 || s . indexOf ( 'z' ) > 0 || s . indexOf ( "ou" ) > 0 || s . indexOf ( "sh" ) > 0 || s . indexOf ( "ch" ) > 0 || s . endsWith ( "aus" ) ) ; }
Returns true if a word is probably not Latin
35,017
public void updateChangeLog ( final Principal user , final Verb verb , final PropertyKey key , final Object previousValue , final Object newValue ) { if ( ( Settings . ChangelogEnabled . getValue ( ) || Settings . UserChangelogEnabled . getValue ( ) ) && key != null ) { final String name = key . jsonName ( ) ; if ( ! hiddenPropertiesInAuditLog . contains ( name ) && ! ( key . isUnvalidated ( ) || key . isReadOnly ( ) ) ) { final JsonObject obj = new JsonObject ( ) ; obj . add ( "time" , toElement ( System . currentTimeMillis ( ) ) ) ; obj . add ( "userId" , toElement ( user . getUuid ( ) ) ) ; obj . add ( "userName" , toElement ( user . getName ( ) ) ) ; obj . add ( "verb" , toElement ( verb ) ) ; obj . add ( "key" , toElement ( key . jsonName ( ) ) ) ; obj . add ( "prev" , toElement ( previousValue ) ) ; obj . add ( "val" , toElement ( newValue ) ) ; if ( Settings . ChangelogEnabled . getValue ( ) ) { changeLog . append ( obj . toString ( ) ) ; changeLog . append ( "\n" ) ; } if ( Settings . UserChangelogEnabled . getValue ( ) ) { obj . remove ( "userId" ) ; obj . remove ( "userName" ) ; obj . add ( "target" , toElement ( getUuid ( ) ) ) ; appendUserChangelog ( user . getUuid ( ) , obj . toString ( ) ) ; } } } }
Update changelog for Verb . change
35,018
public void updateChangeLog ( final Principal user , final Verb verb , final String object ) { if ( ( Settings . ChangelogEnabled . getValue ( ) || Settings . UserChangelogEnabled . getValue ( ) ) ) { final JsonObject obj = new JsonObject ( ) ; obj . add ( "time" , toElement ( System . currentTimeMillis ( ) ) ) ; if ( user != null ) { obj . add ( "userId" , toElement ( user . getUuid ( ) ) ) ; obj . add ( "userName" , toElement ( user . getName ( ) ) ) ; } else { obj . add ( "userId" , JsonNull . INSTANCE ) ; obj . add ( "userName" , JsonNull . INSTANCE ) ; } obj . add ( "verb" , toElement ( verb ) ) ; obj . add ( "target" , toElement ( object ) ) ; if ( Settings . ChangelogEnabled . getValue ( ) ) { if ( changeLog . length ( ) > 0 && verb . equals ( Verb . create ) ) { changeLog . insert ( 0 , "\n" ) ; changeLog . insert ( 0 , obj . toString ( ) ) ; } else { changeLog . append ( obj . toString ( ) ) ; changeLog . append ( "\n" ) ; } } if ( Settings . UserChangelogEnabled . getValue ( ) && user != null ) { obj . remove ( "userId" ) ; obj . remove ( "userName" ) ; appendUserChangelog ( user . getUuid ( ) , obj . toString ( ) ) ; } } }
Update changelog for Verb . create and Verb . delete
35,019
public Comparable convertForSorting ( S source ) throws FrameworkException { if ( source != null ) { if ( source instanceof Comparable ) { return ( Comparable ) source ; } return source . toString ( ) ; } return null ; }
Convert from source type to Comparable to allow a more fine - grained control over the sorted results . Override this method to modify sorting behaviour of entities .
35,020
public ClassLoader getClassLoader ( final Location location ) { return new SecureClassLoader ( ) { protected Class < ? > findClass ( String name ) throws ClassNotFoundException { final JavaClassObject obj = objects . get ( name ) ; if ( obj != null ) { byte [ ] b = obj . getBytes ( ) ; return super . defineClass ( name , obj . getBytes ( ) , 0 , b . length ) ; } throw new ClassNotFoundException ( name ) ; } } ; }
Will be used by us to get the class loader for our compiled class . It creates an anonymous class extending the SecureClassLoader which uses the byte code created by the compiler and stored in the JavaClassObject and returns the Class for it
35,021
public JavaFileObject getJavaFileForOutput ( final Location location , final String className , final Kind kind , final FileObject sibling ) throws IOException { JavaClassObject obj = new JavaClassObject ( className , kind ) ; objects . put ( className , obj ) ; return obj ; }
Gives the compiler an instance of the JavaClassObject so that the compiler can write the byte code into it .
35,022
public boolean startJob ( final Long jobId ) { final ScheduledJob job = removeFromQueueInternal ( jobId ) ; if ( job != null ) { activeJobs . put ( jobId , job ) ; job . startJob ( ) ; return true ; } else { return false ; } }
Starts an import job if it exists . Returns true if it is started .
35,023
private List < Class < ? extends RelationshipInterface > > getRelationClassCandidatesForRelType ( final String relType ) { List < Class < ? extends RelationshipInterface > > candidates = new ArrayList ( ) ; for ( final Class < ? extends RelationshipInterface > candidate : getRelationshipEntities ( ) . values ( ) ) { Relation rel = instantiate ( candidate ) ; if ( rel == null ) { continue ; } if ( rel . name ( ) . equals ( relType ) ) { candidates . add ( candidate ) ; } } return candidates ; }
Return a list of all relation entity classes filtered by relationship type .
35,024
private Class findNearestMatchingRelationClass ( final String sourceTypeName , final String relType , final String targetTypeName ) { final Class sourceType = getNodeEntityClass ( sourceTypeName ) ; final Class targetType = getNodeEntityClass ( targetTypeName ) ; final Map < Integer , Class > candidates = new TreeMap < > ( ) ; for ( final Class candidate : getRelationClassCandidatesForRelType ( relType ) ) { final Relation rel = instantiate ( candidate ) ; final int distance = getDistance ( rel . getSourceType ( ) , sourceType , - 1 ) + getDistance ( rel . getTargetType ( ) , targetType , - 1 ) ; if ( distance >= 2000 ) { candidates . put ( distance - 2000 , candidate ) ; } } if ( candidates . isEmpty ( ) ) { return null ; } else { final Entry < Integer , Class > candidateEntry = candidates . entrySet ( ) . iterator ( ) . next ( ) ; final Class c = candidateEntry . getValue ( ) ; combinedTypeRelationClassCache . put ( getCombinedType ( sourceTypeName , relType , targetTypeName ) , c ) ; return c ; } }
Find the most specialized relation class matching the given parameters .
35,025
public void registerEntityCreationTransformation ( Class type , Transformation < GraphObject > transformation ) { final Set < Transformation < GraphObject > > transformations = getEntityCreationTransformationsForType ( type ) ; if ( ! transformations . contains ( transformation ) ) { transformations . add ( transformation ) ; } }
Register a transformation that will be applied to every newly created entity of a given type .
35,026
public void registerPropertyGroup ( Class type , PropertyKey key , PropertyGroup propertyGroup ) { getPropertyGroupMapForType ( type ) . put ( key . dbName ( ) , propertyGroup ) ; }
Registers a property group for the given key of the given entity type . A property group can be used to combine a set of properties into an object .
35,027
private Set < String > getResourcesToScan ( ) { final String classPath = System . getProperty ( "java.class.path" ) ; final Set < String > modules = new TreeSet < > ( ) ; final Pattern pattern = Pattern . compile ( ".*(structr).*(war|jar)" ) ; final Matcher matcher = pattern . matcher ( "" ) ; for ( final String jarPath : classPath . split ( "[" . concat ( pathSep ) . concat ( "]+" ) ) ) { final String lowerPath = jarPath . toLowerCase ( ) ; if ( lowerPath . endsWith ( classesDir ) || lowerPath . endsWith ( testClassesDir ) ) { modules . add ( jarPath ) ; } else { final String moduleName = lowerPath . substring ( lowerPath . lastIndexOf ( pathSep ) + 1 ) ; matcher . reset ( moduleName ) ; if ( matcher . matches ( ) ) { modules . add ( jarPath ) ; } } } for ( final String resource : Services . getInstance ( ) . getResources ( ) ) { final String lowerResource = resource . toLowerCase ( ) ; if ( lowerResource . endsWith ( ".jar" ) || lowerResource . endsWith ( ".war" ) ) { modules . add ( resource ) ; } } return modules ; }
Scans the class path and returns a Set containing all structr modules .
35,028
private void unzip ( final File file , final String outputDir ) throws IOException { try ( final ZipFile zipFile = new ZipFile ( file ) ) { final Enumeration < ? extends ZipEntry > entries = zipFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { final ZipEntry entry = entries . nextElement ( ) ; final File targetFile = new File ( outputDir , entry . getName ( ) ) ; if ( entry . isDirectory ( ) ) { targetFile . mkdirs ( ) ; } else { targetFile . getParentFile ( ) . mkdirs ( ) ; InputStream in = zipFile . getInputStream ( entry ) ; try ( OutputStream out = new FileOutputStream ( targetFile ) ) { IOUtils . copy ( in , out ) ; IOUtils . closeQuietly ( in ) ; } } } } }
Unzip given file to given output directory .
35,029
public static List < Resource > parsePath ( final SecurityContext securityContext , final HttpServletRequest request , final Map < Pattern , Class < ? extends Resource > > resourceMap , final Value < String > propertyView ) throws FrameworkException { final String path = request . getPathInfo ( ) ; if ( StringUtils . isBlank ( path ) ) { throw new NoResultsException ( "No content" ) ; } final String [ ] pathParts = path . split ( "[/]+" ) ; final Set < String > propertyViews = Services . getInstance ( ) . getConfigurationProvider ( ) . getPropertyViews ( ) ; final List < Resource > resourceChain = new ArrayList < > ( pathParts . length ) ; for ( int i = 0 ; i < pathParts . length ; i ++ ) { final String part = pathParts [ i ] . trim ( ) ; if ( part . length ( ) > 0 ) { boolean found = false ; if ( propertyViews . contains ( part ) ) { Resource resource = new ViewFilterResource ( ) ; resource . checkAndConfigure ( part , securityContext , request ) ; resource . configurePropertyView ( propertyView ) ; resourceChain . add ( resource ) ; found = true ; } else { for ( Map . Entry < Pattern , Class < ? extends Resource > > entry : resourceMap . entrySet ( ) ) { Pattern pattern = entry . getKey ( ) ; Matcher matcher = pattern . matcher ( pathParts [ i ] ) ; if ( matcher . matches ( ) ) { Class < ? extends Resource > type = entry . getValue ( ) ; Resource resource = null ; try { resource = type . newInstance ( ) ; } catch ( Throwable t ) { logger . warn ( "Error instantiating resource class" , t ) ; } if ( resource != null ) { resource . setSecurityContext ( securityContext ) ; if ( resource . checkAndConfigure ( part , securityContext , request ) ) { logger . debug ( "{} matched, adding resource of type {} for part {}" , new Object [ ] { matcher . pattern ( ) , type . getName ( ) , part } ) ; resource . configurePropertyView ( propertyView ) ; resourceChain . add ( resource ) ; found = true ; break ; } } } } } if ( ! found ) { throw new NotFoundException ( "Cannot resolve URL path" ) ; } } } return resourceChain ; }
Parse the request path and match with possible resource patterns
35,030
public static Resource optimizeNestedResourceChain ( final SecurityContext securityContext , final HttpServletRequest request , final Map < Pattern , Class < ? extends Resource > > resourceMap , final Value < String > propertyView ) throws FrameworkException { final List < Resource > resourceChain = ResourceHelper . parsePath ( securityContext , request , resourceMap , propertyView ) ; ViewFilterResource view = null ; int num = resourceChain . size ( ) ; boolean found = false ; do { for ( Iterator < Resource > it = resourceChain . iterator ( ) ; it . hasNext ( ) ; ) { Resource constr = it . next ( ) ; if ( constr instanceof ViewFilterResource ) { view = ( ViewFilterResource ) constr ; it . remove ( ) ; } } found = false ; try { for ( int i = 0 ; i < num ; i ++ ) { Resource firstElement = resourceChain . get ( i ) ; Resource secondElement = resourceChain . get ( i + 1 ) ; Resource combinedConstraint = firstElement . tryCombineWith ( secondElement ) ; if ( combinedConstraint != null ) { resourceChain . remove ( firstElement ) ; resourceChain . remove ( secondElement ) ; resourceChain . add ( i , combinedConstraint ) ; found = true ; } } } catch ( Throwable t ) { final boolean test = false ; } } while ( found ) ; if ( resourceChain . size ( ) == 1 ) { Resource finalResource = resourceChain . get ( 0 ) ; if ( view != null ) { finalResource = finalResource . tryCombineWith ( view ) ; } if ( finalResource == null ) { finalResource = resourceChain . get ( 0 ) ; } return finalResource ; } else { logger . warn ( "Resource chain evaluation for path {} resulted in {} entries, returning status code 400." , new Object [ ] { request . getPathInfo ( ) , resourceChain . size ( ) } ) ; } throw new IllegalPathException ( "Cannot resolve URL path" ) ; }
Optimize the resource chain by trying to combine two resources to a new one
35,031
protected void logException ( final Object caller , final Throwable t , final Object [ ] parameters ) { logException ( t , "{}: Exception in '{}' for parameters: {}" , new Object [ ] { getReplacement ( ) , caller , getParametersAsString ( parameters ) } ) ; }
Logging of an Exception in a function with a simple message outputting the name and call parameters of the function
35,032
protected void logException ( final Throwable t , final String msg , final Object [ ] messageParams ) { logger . error ( msg , messageParams , t ) ; }
Logging of an Exception in a function with custom message and message parameters .
35,033
protected void assertArrayHasLengthAndAllElementsNotNull ( final Object [ ] array , final Integer length ) throws ArgumentCountException , ArgumentNullException { if ( array . length != length ) { throw ArgumentCountException . notEqual ( array . length , length ) ; } for ( final Object element : array ) { if ( element == null ) { throw new ArgumentNullException ( ) ; } } }
Test if the given object array has exact the given length and all its elements are not null .
35,034
public static Location createLocation ( final GeoCodingResult coords ) throws FrameworkException { final PropertyMap props = new PropertyMap ( ) ; double latitude = coords . getLatitude ( ) ; double longitude = coords . getLongitude ( ) ; String type = Location . class . getSimpleName ( ) ; props . put ( AbstractNode . type , type ) ; props . put ( StructrApp . key ( Location . class , "latitude" ) , latitude ) ; props . put ( StructrApp . key ( Location . class , "longitude" ) , longitude ) ; return StructrApp . getInstance ( ) . create ( Location . class , props ) ; }
Creates a Location entity for the given geocoding result and returns it .
35,035
public static GeoCodingResult geocode ( final String street , final String house , String postalCode , final String city , final String state , final String country ) throws FrameworkException { final String language = Settings . GeocodingLanguage . getValue ( ) ; final String cacheKey = cacheKey ( street , house , postalCode , city , state , country , language ) ; GeoCodingResult result = geoCache . get ( cacheKey ) ; if ( result == null ) { GeoCodingProvider provider = getGeoCodingProvider ( ) ; if ( provider != null ) { try { result = provider . geocode ( street , house , postalCode , city , state , country , language ) ; if ( result != null ) { geoCache . put ( cacheKey , result ) ; } } catch ( IOException ioex ) { logger . warn ( "Unable to obtain geocoding result using provider {}: {}" , new Object [ ] { provider . getClass ( ) . getName ( ) , ioex . getMessage ( ) } ) ; } } } return result ; }
Tries do find a geo location for the given address using the GeoCodingProvider specified in the configuration file .
35,036
public static boolean isConfirmationKeyValid ( final String confirmationKey , final Integer validityPeriod ) { final String [ ] parts = confirmationKey . split ( "!" ) ; if ( parts . length == 2 ) { final long confirmationKeyCreated = Long . parseLong ( parts [ 1 ] ) ; final long maxValidity = confirmationKeyCreated + validityPeriod * 60 * 1000 ; return ( maxValidity >= new Date ( ) . getTime ( ) ) ; } return Settings . ConfirmationKeyValidWithoutTimestamp . getValue ( ) ; }
Determines if the key is valid or not . If the key has no timestamp the configuration setting for keys without timestamp is used
35,037
public static void writeCsv ( final ResultStream < GraphObject > result , final Writer out , final String propertyView ) throws IOException { final StringBuilder row = new StringBuilder ( ) ; boolean headerWritten = false ; for ( final GraphObject obj : result ) { if ( ! headerWritten ) { row . setLength ( 0 ) ; for ( PropertyKey key : obj . getPropertyKeys ( propertyView ) ) { row . append ( "\"" ) . append ( key . dbName ( ) ) . append ( "\"" ) . append ( DEFAULT_FIELD_SEPARATOR ) ; } int pos = row . lastIndexOf ( "" + DEFAULT_FIELD_SEPARATOR ) ; if ( pos >= 0 ) { row . deleteCharAt ( pos ) ; } out . append ( row ) . append ( "\r\n" ) ; out . flush ( ) ; headerWritten = true ; } row . setLength ( 0 ) ; for ( PropertyKey key : obj . getPropertyKeys ( propertyView ) ) { Object value = obj . getProperty ( key ) ; row . append ( "\"" ) . append ( ( value != null ? escapeForCsv ( value ) : "" ) ) . append ( "\"" ) . append ( DEFAULT_FIELD_SEPARATOR ) ; } row . deleteCharAt ( row . lastIndexOf ( "" + DEFAULT_FIELD_SEPARATOR ) ) ; out . append ( row ) . append ( "\r\n" ) ; out . flush ( ) ; } }
Write list of objects to output
35,038
public void init ( SecurityContext securityContext , Node dbNode , Class type , final long transactionId ) { throw new UnsupportedOperationException ( "Not supported by this container." ) ; }
dummy implementation of NodeInterface
35,039
private File extractFileAttachment ( final Mailbox mb , final Part p ) { File file = null ; try { final Class fileClass = p . getContentType ( ) . toLowerCase ( ) . startsWith ( "image/" ) ? Image . class : File . class ; final App app = StructrApp . getInstance ( ) ; try ( final Tx tx = app . tx ( ) ) { org . structr . web . entity . Folder fileFolder = FileHelper . createFolderPath ( SecurityContext . getSuperUserInstance ( ) , getStoragePath ( mb . getUuid ( ) ) ) ; try { String fileName = decodeText ( p . getFileName ( ) ) ; if ( fileName == null ) { fileName = NodeServiceCommand . getNextUuid ( ) ; } file = FileHelper . createFile ( SecurityContext . getSuperUserInstance ( ) , p . getInputStream ( ) , p . getContentType ( ) , fileClass , fileName , fileFolder ) ; } catch ( FrameworkException ex ) { logger . warn ( "EMail in mailbox[" + mb . getUuid ( ) + "] attachment has invalid name. Using random UUID as fallback." ) ; file = FileHelper . createFile ( SecurityContext . getSuperUserInstance ( ) , p . getInputStream ( ) , p . getContentType ( ) , fileClass , NodeServiceCommand . getNextUuid ( ) , fileFolder ) ; } tx . success ( ) ; } catch ( IOException | FrameworkException ex ) { logger . error ( "Exception while extracting file attachment: " , ex ) ; } } catch ( MessagingException ex ) { logger . error ( "Exception while extracting file attachment: " , ex ) ; } return file ; }
Returns attachment UUID to append to the mail to be created
35,040
public void setSecurityContext ( final SecurityContext sc ) { if ( securityContext == null ) { if ( sc . isSuperUserSecurityContext ( ) == Boolean . FALSE ) { securityContext = sc ; } } }
Allow setting the securityContext if it was null . Important for Login transactions .
35,041
private long findInterval ( final String dateFormat ) { final long max = TimeUnit . DAYS . toMillis ( 365 ) ; final long step = TimeUnit . SECONDS . toMillis ( 60 ) ; try { final SimpleDateFormat format = new SimpleDateFormat ( dateFormat ) ; final long initial = format . parse ( format . format ( 3600 ) ) . getTime ( ) ; for ( long i = initial ; i < max ; i += step ) { final long current = format . parse ( format . format ( i ) ) . getTime ( ) ; if ( initial != current ) { return i - initial ; } } return max ; } catch ( ParseException pex ) { logger . warn ( "" , pex ) ; } return max ; }
This method takes a date format and finds the time interval that it represents .
35,042
public Locale getEffectiveLocale ( ) { Locale locale = Locale . getDefault ( ) ; boolean userHasLocaleString = false ; if ( cachedUser != null ) { final String userLocaleString = cachedUser . getLocale ( ) ; if ( userLocaleString != null ) { userHasLocaleString = true ; try { locale = LocaleUtils . toLocale ( userLocaleString ) ; } catch ( IllegalArgumentException e ) { locale = Locale . forLanguageTag ( userLocaleString ) ; } } } if ( request != null ) { if ( ! userHasLocaleString ) { locale = request . getLocale ( ) ; final Cookie [ ] cookies = request . getCookies ( ) ; if ( cookies != null ) { for ( Cookie c : cookies ) { if ( c . getName ( ) . equals ( LOCALE_KEY ) ) { final String cookieLocaleString = c . getValue ( ) ; try { locale = LocaleUtils . toLocale ( cookieLocaleString ) ; } catch ( IllegalArgumentException e ) { locale = Locale . forLanguageTag ( cookieLocaleString ) ; } } } } } String requestedLocaleString = request . getParameter ( LOCALE_KEY ) ; if ( StringUtils . isNotBlank ( requestedLocaleString ) ) { try { locale = LocaleUtils . toLocale ( requestedLocaleString ) ; } catch ( IllegalArgumentException e ) { locale = Locale . forLanguageTag ( requestedLocaleString ) ; } } } return locale ; }
Determine the effective locale for this request .
35,043
public final void setArgument ( final String key , final Object value ) { if ( key != null && value != null ) { this . arguments . put ( key , value ) ; } }
Sets an argument for this command .
35,044
public static String getHash ( final String password , final String salt ) { if ( StringUtils . isEmpty ( salt ) ) { return getSimpleHash ( password ) ; } return DigestUtils . sha512Hex ( DigestUtils . sha512Hex ( password ) . concat ( salt ) ) ; }
Calculate a SHA - 512 hash of the given password string .
35,045
private Page notFound ( final HttpServletResponse response , final SecurityContext securityContext ) throws IOException , FrameworkException { final List < Page > errorPages = StructrApp . getInstance ( securityContext ) . nodeQuery ( Page . class ) . and ( StructrApp . key ( Page . class , "showOnErrorCodes" ) , "404" , false ) . getAsList ( ) ; for ( final Page errorPage : errorPages ) { if ( isVisibleForSite ( securityContext . getRequest ( ) , errorPage ) ) { response . setStatus ( HttpServletResponse . SC_NOT_FOUND ) ; return errorPage ; } } response . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; return null ; }
Handle 404 Not Found
35,046
private AbstractNode findFirstNodeByName ( final SecurityContext securityContext , final HttpServletRequest request , final String path ) throws FrameworkException { final String name = PathHelper . getName ( path ) ; if ( ! name . isEmpty ( ) ) { logger . debug ( "Requested name: {}" , name ) ; final Query query = StructrApp . getInstance ( securityContext ) . nodeQuery ( ) ; final ConfigurationProvider config = StructrApp . getConfiguration ( ) ; if ( ! possiblePropertyNamesForEntityResolving . isEmpty ( ) ) { query . and ( ) ; resolvePossiblePropertyNamesForObjectResolution ( config , query , name ) ; query . parent ( ) ; } final List < AbstractNode > results = Iterables . toList ( query . getResultStream ( ) ) ; logger . debug ( "{} results" , results . size ( ) ) ; request . setAttribute ( POSSIBLE_ENTRY_POINTS_KEY , results ) ; return ( results . size ( ) > 0 ? ( AbstractNode ) results . get ( 0 ) : null ) ; } return null ; }
Find first node whose name matches the last part of the given path
35,047
private AbstractNode findNodeByUuid ( final SecurityContext securityContext , final String uuid ) throws FrameworkException { if ( ! uuid . isEmpty ( ) ) { logger . debug ( "Requested id: {}" , uuid ) ; return ( AbstractNode ) StructrApp . getInstance ( securityContext ) . getNodeById ( uuid ) ; } return null ; }
Find node by uuid
35,048
private File findFile ( final SecurityContext securityContext , final HttpServletRequest request , final String path ) throws FrameworkException { List < Linkable > entryPoints = findPossibleEntryPoints ( securityContext , request , path ) ; if ( entryPoints . isEmpty ( ) ) { entryPoints = findPossibleEntryPoints ( securityContext , request , PathHelper . replaceWhitespaceByPlus ( path ) ) ; } if ( entryPoints . isEmpty ( ) ) { entryPoints = findPossibleEntryPoints ( securityContext , request , PathHelper . replaceWhitespaceByPercentTwenty ( path ) ) ; } for ( Linkable node : entryPoints ) { if ( node instanceof File && ( path . equals ( node . getPath ( ) ) || node . getUuid ( ) . equals ( PathHelper . getName ( path ) ) ) ) { return ( File ) node ; } } return null ; }
Find a file with its name matching last path part
35,049
private Page findPage ( final SecurityContext securityContext , List < Page > pages , final String path , final EditMode edit ) throws FrameworkException { if ( pages == null ) { pages = StructrApp . getInstance ( securityContext ) . nodeQuery ( Page . class ) . getAsList ( ) ; Collections . sort ( pages , new GraphObjectComparator ( StructrApp . key ( Page . class , "position" ) , GraphObjectComparator . ASCENDING ) ) ; } for ( final Page page : pages ) { final String pagePath = page . getPath ( ) ; if ( pagePath != null && pagePath . equals ( path ) && ( EditMode . CONTENT . equals ( edit ) || isVisibleForSite ( securityContext . getRequest ( ) , page ) ) ) { return page ; } } final String name = PathHelper . getName ( path ) ; for ( final Page page : pages ) { final String pageName = page . getName ( ) ; if ( pageName != null && pageName . equals ( name ) && ( EditMode . CONTENT . equals ( edit ) || isVisibleForSite ( securityContext . getRequest ( ) , page ) ) ) { return page ; } } for ( final Page page : pages ) { final String pageUuid = page . getUuid ( ) ; if ( pageUuid != null && pageUuid . equals ( name ) && ( EditMode . CONTENT . equals ( edit ) || isVisibleForSite ( securityContext . getRequest ( ) , page ) ) ) { return page ; } } return null ; }
Find a page with matching path .
35,050
private Page findIndexPage ( final SecurityContext securityContext , List < Page > pages , final EditMode edit ) throws FrameworkException { final PropertyKey < Integer > positionKey = StructrApp . key ( Page . class , "position" ) ; if ( pages == null ) { pages = StructrApp . getInstance ( securityContext ) . nodeQuery ( Page . class ) . getAsList ( ) ; Collections . sort ( pages , new GraphObjectComparator ( positionKey , GraphObjectComparator . ASCENDING ) ) ; } for ( Page page : pages ) { if ( securityContext . isVisible ( page ) && page . getProperty ( positionKey ) != null && ( ( EditMode . CONTENT . equals ( edit ) || isVisibleForSite ( securityContext . getRequest ( ) , page ) ) || ( page . getEnableBasicAuth ( ) && page . isVisibleToAuthenticatedUsers ( ) ) ) ) { return page ; } } return null ; }
Find the page with the lowest non - empty position value which is visible in the current security context and for the given site .
35,051
private boolean checkRegistration ( final Authenticator auth , final HttpServletRequest request , final HttpServletResponse response , final String path ) throws FrameworkException , IOException { logger . debug ( "Checking registration ..." ) ; final String key = request . getParameter ( CONFIRM_KEY_KEY ) ; if ( StringUtils . isEmpty ( key ) ) { return false ; } final PropertyKey < String > confirmationKeyKey = StructrApp . key ( User . class , "confirmationKey" ) ; final String targetPage = filterMaliciousRedirects ( request . getParameter ( TARGET_PAGE_KEY ) ) ; final String errorPage = filterMaliciousRedirects ( request . getParameter ( ERROR_PAGE_KEY ) ) ; if ( CONFIRM_REGISTRATION_PAGE . equals ( path ) ) { final App app = StructrApp . getInstance ( ) ; List < Principal > results ; try ( final Tx tx = app . tx ( ) ) { results = app . nodeQuery ( Principal . class ) . and ( confirmationKeyKey , key ) . getAsList ( ) ; tx . success ( ) ; } if ( ! results . isEmpty ( ) ) { final Principal user = results . get ( 0 ) ; try ( final Tx tx = app . tx ( ) ) { user . setProperty ( confirmationKeyKey , null ) ; if ( AuthHelper . isConfirmationKeyValid ( key , Settings . ConfirmationKeyRegistrationValidityPeriod . getValue ( ) ) ) { if ( Settings . RestUserAutologin . getValue ( ) ) { AuthHelper . doLogin ( request , user ) ; } else { logger . warn ( "Refusing login because {} is disabled" , Settings . RestUserAutologin . getKey ( ) ) ; } } else { logger . warn ( "Confirmation key for user {} is not valid anymore - refusing login." , user . getName ( ) ) ; } tx . success ( ) ; } if ( StringUtils . isNotBlank ( targetPage ) ) { response . sendRedirect ( "/" + targetPage ) ; } return true ; } else { if ( StringUtils . isNotBlank ( errorPage ) ) { response . sendRedirect ( "/" + errorPage ) ; } return true ; } } return false ; }
This method checks if the current request is a user registration confirmation usually triggered by a user clicking on a confirmation link in an e - mail .
35,052
private boolean isVisibleForSite ( final HttpServletRequest request , final Page page ) { final Site site = page . getSite ( ) ; if ( site == null ) { return true ; } final String serverName = request . getServerName ( ) ; final int serverPort = request . getServerPort ( ) ; if ( StringUtils . isNotBlank ( serverName ) && ! serverName . equals ( site . getHostname ( ) ) ) { return false ; } final Integer sitePort = site . getPort ( ) ; if ( sitePort != null && serverPort != sitePort ) { return false ; } return true ; }
Check if the given page is visible for the requested site defined by a hostname and a port .
35,053
public static void clearSession ( final String sessionId ) { if ( StringUtils . isBlank ( sessionId ) ) { return ; } final App app = StructrApp . getInstance ( ) ; final PropertyKey < String [ ] > sessionIdKey = StructrApp . key ( Principal . class , "sessionIds" ) ; final Query < Principal > query = app . nodeQuery ( Principal . class ) . and ( sessionIdKey , new String [ ] { sessionId } ) . disableSorting ( ) ; try { for ( final Principal p : query . getAsList ( ) ) { p . removeSessionId ( sessionId ) ; } } catch ( Exception fex ) { logger . warn ( "Error while removing sessionId " + sessionId + " from all principals" , fex ) ; } }
Make sure the given sessionId is not set for any user .
35,054
public static void clearInvalidSessions ( final Principal user ) { logger . info ( "Clearing invalid sessions for user {} ({})" , user . getName ( ) , user . getUuid ( ) ) ; final PropertyKey < String [ ] > sessionIdKey = StructrApp . key ( Principal . class , "sessionIds" ) ; final String [ ] sessionIds = user . getProperty ( sessionIdKey ) ; if ( sessionIds != null && sessionIds . length > 0 ) { final SessionCache sessionCache = Services . getInstance ( ) . getService ( HttpService . class ) . getSessionCache ( ) ; for ( final String sessionId : sessionIds ) { HttpSession session = null ; try { session = sessionCache . get ( sessionId ) ; } catch ( Exception ex ) { logger . warn ( "Unable to retrieve session " + sessionId + " from session cache:" , ex ) ; } if ( session == null || SessionHelper . isSessionTimedOut ( session ) ) { SessionHelper . clearSession ( sessionId ) ; } } } }
Remove old sessionIds of the given user
35,055
public boolean evaluateCustomQuery ( final String customQuery , final Map < String , Object > parameters ) { final SessionTransaction tx = db . getCurrentTransaction ( ) ; boolean result = false ; try { result = tx . getBoolean ( customQuery , parameters ) ; } catch ( Exception ignore ) { } return result ; }
Evaluate a custom query and return result as a boolean value
35,056
private void ensureCorrectChildPositions ( ) throws FrameworkException { final List < Relation < T , T , OneStartpoint < T > , ManyEndpoint < T > > > childRels = treeGetChildRelationships ( ) ; int position = 0 ; for ( Relation < T , T , OneStartpoint < T > , ManyEndpoint < T > > childRel : childRels ) { childRel . setProperty ( getPositionProperty ( ) , position ++ ) ; } }
Ensures that the position attributes of the AbstractChildren of this node are correct . Please note that this method needs to run in the same transaction as any modifiying operation that changes the order of child nodes and therefore this method does _not_ create its own transaction . However it will not raise a NotInTransactionException when called outside of modifying operations because each setProperty call creates its own transaction .
35,057
public Set < T > getAllChildNodes ( ) { Set < T > allChildNodes = new HashSet ( ) ; List < T > childNodes = treeGetChildren ( ) ; for ( final T child : childNodes ) { allChildNodes . add ( child ) ; if ( child instanceof LinkedTreeNode ) { final LinkedTreeNode treeNode = ( LinkedTreeNode ) child ; allChildNodes . addAll ( treeNode . getAllChildNodes ( ) ) ; } } return allChildNodes ; }
Return a set containing all child nodes of this node .
35,058
protected PropertyMap getNotionProperties ( final SecurityContext securityContext , final Class type , final String storageKey ) { final Map < String , PropertyMap > notionPropertyMap = ( Map < String , PropertyMap > ) securityContext . getAttribute ( "notionProperties" ) ; if ( notionPropertyMap != null ) { final Set < PropertyKey > keySet = Services . getInstance ( ) . getConfigurationProvider ( ) . getPropertySet ( type , PropertyView . Public ) ; final PropertyMap notionProperties = notionPropertyMap . get ( storageKey ) ; if ( notionProperties != null ) { for ( final Iterator < PropertyKey > it = notionProperties . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { final PropertyKey key = it . next ( ) ; if ( ! keySet . contains ( key ) ) { it . remove ( ) ; } } return notionProperties ; } } return null ; }
Loads a PropertyMap from the current security context that was previously stored there by one of the Notions that was executed before this relationship creation .
35,059
protected List < NodeInterface > getNodesAt ( final NodeInterface locationNode ) { final List < NodeInterface > nodes = new LinkedList < > ( ) ; for ( RelationshipInterface rel : locationNode . getIncomingRelationships ( NodeHasLocation . class ) ) { NodeInterface startNode = rel . getSourceNode ( ) ; nodes . add ( startNode ) ; nodes . addAll ( getNodesAt ( startNode ) ) ; } return nodes ; }
Return all nodes which are connected by an incoming IS_AT relationships
35,060
private File fileExists ( final String path , final long checksum ) throws FrameworkException { final PropertyKey < Long > checksumKey = StructrApp . key ( File . class , "checksum" ) ; final PropertyKey < String > pathKey = StructrApp . key ( File . class , "path" ) ; return app . nodeQuery ( File . class ) . and ( pathKey , path ) . and ( checksumKey , checksum ) . getFirst ( ) ; }
Check whether a file with given path and checksum already exists
35,061
public static < T > List < T > subList ( final List < T > list , int pageSize , int page ) { if ( pageSize <= 0 || page == 0 ) { return Collections . EMPTY_LIST ; } int size = list . size ( ) ; int fromIndex = page > 0 ? ( page - 1 ) * pageSize : size + ( page * pageSize ) ; int toIndex = fromIndex + pageSize ; int finalFromIndex = Math . max ( 0 , fromIndex ) ; int finalToIndex = Math . min ( size , Math . max ( 0 , toIndex ) ) ; if ( finalFromIndex > finalToIndex ) { finalFromIndex = finalToIndex ; } try { return list . subList ( finalFromIndex , finalToIndex ) ; } catch ( Throwable t ) { logger . warn ( "Invalid range for sublist in paging, pageSize {}, page {}: {}" , new Object [ ] { pageSize , page , t . getMessage ( ) } ) ; } return Collections . EMPTY_LIST ; }
Return a single page of the list with the given paging parameters .
35,062
public static String getRelativeNodePath ( String basePath , String targetPath ) { if ( basePath . equals ( targetPath ) ) { return "." ; } if ( basePath . equals ( PATH_SEP ) && ( targetPath . length ( ) > 1 ) ) { return targetPath . substring ( 1 ) ; } String [ ] baseAncestors = FilenameUtils . normalizeNoEndSeparator ( basePath ) . split ( PATH_SEP ) ; String [ ] targetAncestors = FilenameUtils . normalizeNoEndSeparator ( targetPath ) . split ( PATH_SEP ) ; int length = ( baseAncestors . length < targetAncestors . length ) ? baseAncestors . length : targetAncestors . length ; int lastCommonRoot = - 1 ; int i ; for ( i = 0 ; i < length ; i ++ ) { if ( baseAncestors [ i ] . equals ( targetAncestors [ i ] ) ) { lastCommonRoot = i ; } else { break ; } } if ( lastCommonRoot != - 1 ) { StringBuilder newRelativePath = new StringBuilder ( ) ; for ( i = lastCommonRoot + 1 ; i < baseAncestors . length ; i ++ ) { if ( baseAncestors [ i ] . length ( ) > 0 ) { newRelativePath . append ( ".." + PATH_SEP ) ; } } for ( i = lastCommonRoot + 1 ; i < targetAncestors . length ; i ++ ) { newRelativePath . append ( targetAncestors [ i ] ) . append ( PATH_SEP ) ; } String result = newRelativePath . toString ( ) ; if ( result . endsWith ( PATH_SEP ) ) { result = result . substring ( 0 , result . length ( ) - 1 ) ; } return result ; } return targetPath ; }
Assemble a relative path for the given absolute paths
35,063
public static String getName ( final String path ) { String cleanedPath = clean ( path ) ; if ( cleanedPath != null && cleanedPath . contains ( PATH_SEP ) ) { return StringUtils . substringAfterLast ( cleanedPath , PATH_SEP ) ; } else { return cleanedPath ; } }
Return last part of the given path after separator or the path if no path separator was found .
35,064
public static String [ ] getParts ( final String path ) { String cleanedPath = clean ( path ) ; return StringUtils . splitByWholeSeparator ( cleanedPath , PATH_SEP ) ; }
Return array of path parts .
35,065
public void finish ( ) { try { FileChannel channel = getChannel ( false ) ; if ( channel != null && channel . isOpen ( ) ) { channel . force ( true ) ; channel . close ( ) ; this . privateFileChannel = null ; file . notifyUploadCompletion ( ) ; } } catch ( IOException e ) { logger . warn ( "Unable to finish file upload" , e ) ; } }
Called when the WebSocket connection is closed
35,066
public int indexOf ( T x ) { int r = Arrays . binarySearch ( data , x ) ; return ( r >= 0 ? r : - 1 ) ; }
Returns the position in the array or - 1
35,067
public static boolean endsWithUuid ( final String name ) { if ( name . length ( ) > 32 ) { return pattern . matcher ( name . substring ( name . length ( ) - 32 ) ) . matches ( ) ; } else { return false ; } }
Checks if the given string ends with a uuid
35,068
public int contentHashCode ( Set < PropertyKey > comparableKeys , boolean includeSystemProperties ) { Map < PropertyKey , Object > sortedMap = new TreeMap < > ( new PropertyKeyComparator ( ) ) ; int hashCode = 42 ; sortedMap . putAll ( properties ) ; if ( comparableKeys == null ) { for ( Entry < PropertyKey , Object > entry : sortedMap . entrySet ( ) ) { if ( includeSystemProperties || ! entry . getKey ( ) . isUnvalidated ( ) ) { hashCode ^= entry . hashCode ( ) ; } } } else { for ( Entry < PropertyKey , Object > entry : sortedMap . entrySet ( ) ) { PropertyKey key = entry . getKey ( ) ; if ( comparableKeys . contains ( key ) ) { if ( includeSystemProperties || ! key . isUnvalidated ( ) ) { hashCode ^= entry . hashCode ( ) ; } } } } return hashCode ; }
Calculates a hash code for the contents of this PropertyMap .
35,069
public List < RelationshipInterface > execute ( NodeInterface sourceNode , RelationshipType relType , Direction dir ) throws FrameworkException { RelationshipFactory factory = new RelationshipFactory ( securityContext ) ; List < RelationshipInterface > result = new LinkedList < > ( ) ; Node node = sourceNode . getNode ( ) ; Iterable < Relationship > rels ; if ( node == null ) { return Collections . EMPTY_LIST ; } if ( relType != null ) { rels = node . getRelationships ( dir , relType ) ; } else { rels = node . getRelationships ( dir ) ; } try { for ( Relationship r : rels ) { result . add ( factory . instantiate ( r ) ) ; } } catch ( RuntimeException e ) { logger . warn ( "Exception occured: " , e . getMessage ( ) ) ; } return result ; }
Fetch relationships for the given source node .
35,070
public static Date parse ( String source , final String pattern ) { if ( StringUtils . isBlank ( pattern ) ) { return parseISO8601DateString ( source ) ; } else { try { if ( StringUtils . contains ( source , "Z" ) ) { source = StringUtils . replace ( source , "Z" , "+0000" ) ; } return new SimpleDateFormat ( pattern ) . parse ( source ) ; } catch ( ParseException ignore ) { } return parseISO8601DateString ( source ) ; } }
Static method to catch parse exception
35,071
public static Date parseISO8601DateString ( String source ) { final String [ ] supportedFormats = new String [ ] { "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" , "yyyy-MM-dd'T'HH:mm:ssXXX" , "yyyy-MM-dd'T'HH:mm:ssZ" , "yyyy-MM-dd'T'HH:mm:ss.SSSZ" } ; if ( StringUtils . contains ( source , "Z" ) ) { source = StringUtils . replace ( source , "Z" , "+0000" ) ; } Date parsedDate = null ; for ( final String format : supportedFormats ) { try { parsedDate = new SimpleDateFormat ( format ) . parse ( source ) ; } catch ( ParseException pe ) { } if ( parsedDate != null ) { return parsedDate ; } } return null ; }
Try to parse source string as a ISO8601 date .
35,072
public static String format ( final Date date , String format ) { if ( date != null ) { if ( StringUtils . isBlank ( format ) ) { format = DateProperty . getDefaultFormat ( ) ; } return new SimpleDateFormat ( format ) . format ( date ) ; } return null ; }
Central method to format a date into a string .
35,073
public GraphObject getGraphObject ( final String id , final String nodeId ) { if ( isValidUuid ( id ) ) { final AbstractNode node = getNode ( id ) ; if ( node != null ) { return node ; } else { if ( nodeId == null ) { logger . warn ( "Relationship access by UUID is deprecated and not supported by Neo4j, this can take a very long time." ) ; } final AbstractRelationship rel = getRelationship ( id , nodeId ) ; if ( rel != null ) { return rel ; } } } else { logger . warn ( "Invalid UUID used for getGraphObject: {} is not a valid UUID." , id ) ; } return null ; }
Returns the graph object with the given id .
35,074
public AbstractNode getNode ( final String id ) { final SecurityContext securityContext = getWebSocket ( ) . getSecurityContext ( ) ; final App app = StructrApp . getInstance ( securityContext ) ; try ( final Tx tx = app . tx ( ) ) { final AbstractNode node = ( AbstractNode ) app . getNodeById ( id ) ; tx . success ( ) ; return node ; } catch ( FrameworkException fex ) { logger . warn ( "Unable to get node" , fex ) ; } return null ; }
Returns the node with the given id .
35,075
public AbstractRelationship getRelationship ( final String id , final String nodeId ) { if ( id == null ) { return null ; } if ( nodeId == null ) { return getRelationship ( id ) ; } final SecurityContext securityContext = getWebSocket ( ) . getSecurityContext ( ) ; final App app = StructrApp . getInstance ( securityContext ) ; try ( final Tx tx = app . tx ( ) ) { final AbstractNode node = ( AbstractNode ) app . getNodeById ( nodeId ) ; for ( final AbstractRelationship rel : node . getRelationships ( ) ) { if ( rel . getUuid ( ) . equals ( id ) ) { return rel ; } } tx . success ( ) ; } catch ( FrameworkException fex ) { logger . warn ( "Unable to get relationship" , fex ) ; } return null ; }
Returns the relationship with the given id by looking up a node with the given nodeId and filtering the relationships .
35,076
public AbstractRelationship getRelationship ( final String id ) { if ( id == null ) { return null ; } final SecurityContext securityContext = getWebSocket ( ) . getSecurityContext ( ) ; final App app = StructrApp . getInstance ( securityContext ) ; try ( final Tx tx = app . tx ( ) ) { final AbstractRelationship rel = ( AbstractRelationship ) app . getRelationshipById ( id ) ; tx . success ( ) ; return rel ; } catch ( FrameworkException fex ) { logger . warn ( "Unable to get relationship" , fex ) ; } return null ; }
Returns the relationship to which the uuid parameter of this command refers to .
35,077
protected void moveChildNodes ( final DOMNode sourceNode , final DOMNode targetNode ) { DOMNode child = ( DOMNode ) sourceNode . getFirstChild ( ) ; while ( child != null ) { DOMNode next = ( DOMNode ) child . getNextSibling ( ) ; targetNode . appendChild ( child ) ; child = next ; } }
Make child nodes of the source nodes child nodes of the target node .
35,078
private void fixDocumentElements ( final Page page ) { final NodeList heads = page . getElementsByTagName ( "head" ) ; if ( heads . getLength ( ) > 1 ) { final Node head1 = heads . item ( 0 ) ; final Node head2 = heads . item ( 1 ) ; final Node parent = head1 . getParentNode ( ) ; final boolean h1 = head1 . hasChildNodes ( ) ; final boolean h2 = head2 . hasChildNodes ( ) ; if ( h1 && h2 ) { for ( Node child = head2 . getFirstChild ( ) ; child != null ; child = child . getNextSibling ( ) ) { head2 . removeChild ( child ) ; head1 . appendChild ( child ) ; } parent . removeChild ( head2 ) ; } else if ( h1 && ! h2 ) { parent . removeChild ( head2 ) ; } else if ( ! h1 && h2 ) { parent . removeChild ( head1 ) ; } else { parent . removeChild ( head1 ) ; } } }
Remove duplicate Head element from import process .
35,079
public CMISInfo getCMISInfo ( final Class < ? extends GraphObject > type ) { try { return type . newInstance ( ) . getCMISInfo ( ) ; } catch ( Throwable t ) { } return null ; }
Returns the CMIS info that is defined in the given Structr type or null .
35,080
public BaseTypeId getBaseTypeId ( final Class < ? extends GraphObject > type ) { final CMISInfo info = getCMISInfo ( type ) ; if ( info != null ) { return info . getBaseTypeId ( ) ; } return null ; }
Returns the baseTypeId that is defined in the given Structr type or null .
35,081
public BaseTypeId getBaseTypeId ( final String typeId ) { try { return BaseTypeId . fromValue ( typeId ) ; } catch ( IllegalArgumentException iex ) { } return null ; }
Returns the enum value for the given typeId or null if no such value exists .
35,082
public Class typeFromObjectTypeId ( final String objectTypeId , final BaseTypeId defaultType , final Class defaultClass ) { if ( defaultType . value ( ) . equals ( objectTypeId ) ) { return defaultClass ; } return StructrApp . getConfiguration ( ) . getNodeEntityClass ( objectTypeId ) ; }
Returns the Structr type for the given objectTypeId or the defaultClass of the objectTypeId matches the given baseTypeId .
35,083
public void registerServiceClass ( Class serviceClass ) { registeredServiceClasses . put ( serviceClass . getSimpleName ( ) , serviceClass ) ; Settings . Services . addAvailableOption ( serviceClass . getSimpleName ( ) ) ; }
Registers a service enabling the service layer to automatically start autorun servies .
35,084
public boolean isReady ( final Class serviceClass ) { Service service = serviceCache . get ( serviceClass ) ; return ( service != null && service . isRunning ( ) ) ; }
Return true if the given service is ready to be used means initialized and running .
35,085
public static String replacePlaceHoldersInTemplate ( final String template , final Map < String , String > replacementMap ) { List < String > toReplace = new ArrayList < > ( ) ; List < String > replaceBy = new ArrayList < > ( ) ; for ( Entry < String , String > property : replacementMap . entrySet ( ) ) { toReplace . add ( property . getKey ( ) ) ; replaceBy . add ( property . getValue ( ) ) ; } return StringUtils . replaceEachRepeatedly ( template , toReplace . toArray ( new String [ toReplace . size ( ) ] ) , replaceBy . toArray ( new String [ replaceBy . size ( ) ] ) ) ; }
Parse the template and replace any of the keys in the replacement map by the given values
35,086
public void indexSourceTree ( final Folder rootFolder ) { logger . info ( "Starting indexing of source tree " + rootFolder . getPath ( ) ) ; final SecurityContext securityContext = rootFolder . getSecurityContext ( ) ; app = StructrApp . getInstance ( securityContext ) ; structrTypeSolver . parseRoot ( rootFolder ) ; final CombinedTypeSolver typeSolver = new CombinedTypeSolver ( ) ; typeSolver . add ( new ReflectionTypeSolver ( ) ) ; typeSolver . add ( structrTypeSolver ) ; facade = JavaParserFacade . get ( typeSolver ) ; logger . info ( "Done with indexing of source tree " + rootFolder . getPath ( ) ) ; }
Create an index containing all compilation units of Java files from the source tree under the given root folder .
35,087
public Iterable < T > bulkInstantiate ( final Iterable < S > input ) throws FrameworkException { return Iterables . map ( this , input ) ; }
Create structr nodes from all given underlying database nodes No paging but security check
35,088
public static void exportToFile ( final DatabaseService graphDb , final String fileName , final String query , final boolean includeFiles ) throws FrameworkException { final App app = StructrApp . getInstance ( ) ; try ( final Tx tx = app . tx ( ) ) { final NodeFactory nodeFactory = new NodeFactory ( SecurityContext . getSuperUserInstance ( ) ) ; final RelationshipFactory relFactory = new RelationshipFactory ( SecurityContext . getSuperUserInstance ( ) ) ; final Set < AbstractNode > nodes = new HashSet < > ( ) ; final Set < AbstractRelationship > rels = new HashSet < > ( ) ; boolean conditionalIncludeFiles = includeFiles ; if ( query != null ) { logger . info ( "Using Cypher query {} to determine export set, disabling export of files" , query ) ; conditionalIncludeFiles = false ; for ( final GraphObject obj : StructrApp . getInstance ( ) . query ( query , null ) ) { if ( obj . isNode ( ) ) { nodes . add ( ( AbstractNode ) obj . getSyncNode ( ) ) ; } else { rels . add ( ( AbstractRelationship ) obj . getSyncRelationship ( ) ) ; } } logger . info ( "Query returned {} nodes and {} relationships." , new Object [ ] { nodes . size ( ) , rels . size ( ) } ) ; } else { Iterables . addAll ( nodes , nodeFactory . bulkInstantiate ( graphDb . getAllNodes ( ) ) ) ; Iterables . addAll ( rels , relFactory . bulkInstantiate ( graphDb . getAllRelationships ( ) ) ) ; } try ( final FileOutputStream fos = new FileOutputStream ( fileName ) ) { exportToStream ( fos , nodes , rels , null , conditionalIncludeFiles ) ; } tx . success ( ) ; } catch ( Throwable t ) { logger . warn ( "" , t ) ; throw new FrameworkException ( 500 , t . getMessage ( ) ) ; } }
Exports the whole structr database to a file with the given name .
35,089
public static void exportToFile ( final String fileName , final Iterable < ? extends NodeInterface > nodes , final Iterable < ? extends RelationshipInterface > relationships , final Iterable < String > filePaths , final boolean includeFiles ) throws FrameworkException { try ( final Tx tx = StructrApp . getInstance ( ) . tx ( ) ) { try ( final FileOutputStream fos = new FileOutputStream ( fileName ) ) { exportToStream ( fos , nodes , relationships , filePaths , includeFiles ) ; } tx . success ( ) ; } catch ( Throwable t ) { throw new FrameworkException ( 500 , t . getMessage ( ) ) ; } }
Exports the given part of the structr database to a file with the given name .
35,090
public static void exportToStream ( final OutputStream outputStream , final Iterable < ? extends NodeInterface > nodes , final Iterable < ? extends RelationshipInterface > relationships , final Iterable < String > filePaths , final boolean includeFiles ) throws FrameworkException { try ( final ZipOutputStream zos = new ZipOutputStream ( outputStream ) ) { final Set < String > filesToInclude = new LinkedHashSet < > ( ) ; if ( filePaths != null ) { for ( String file : filePaths ) { filesToInclude . add ( file ) ; } } zos . setLevel ( 6 ) ; if ( includeFiles ) { logger . info ( "Exporting files.." ) ; exportDirectory ( zos , new File ( "files" ) , "" , filesToInclude . isEmpty ( ) ? null : filesToInclude ) ; } exportDatabase ( zos , new BufferedOutputStream ( zos ) , nodes , relationships ) ; zos . finish ( ) ; zos . flush ( ) ; zos . close ( ) ; } catch ( Throwable t ) { logger . warn ( "" , t ) ; throw new FrameworkException ( 500 , t . getMessage ( ) ) ; } }
Exports the given part of the structr database to the given output stream .
35,091
public static void serializeData ( DataOutputStream outputStream , byte [ ] data ) throws IOException { outputStream . writeInt ( data . length ) ; outputStream . write ( data ) ; outputStream . flush ( ) ; }
Serializes the given object into the given writer . The following format will be used to serialize objects . The first two characters are the type index see typeMap above . After that a single digit that indicates the length of the following length field follows . After that the length field is serialized followed by the string value of the given object and a space character for human readability .
35,092
private String getFirstPartOfString ( final String source ) { final int pos = source . indexOf ( "." ) ; if ( pos > - 1 ) { return source . substring ( 0 , pos ) ; } return source ; }
Returns the first part of the given source string when it contains a .
35,093
public SecurityContext initializeAndExamineRequest ( final HttpServletRequest request , final HttpServletResponse response ) throws FrameworkException { logger . warn ( "KAI: RestAuthenticator.initializeAndExamineRequest" ) ; SecurityContext securityContext ; Principal user = SessionHelper . checkSessionAuthentication ( request ) ; if ( user == null ) { user = getUser ( request , true ) ; } if ( user == null ) { securityContext = SecurityContext . getInstance ( user , request , AccessMode . Frontend ) ; } else { if ( user instanceof SuperUser ) { securityContext = SecurityContext . getSuperUserInstance ( request ) ; } else { securityContext = SecurityContext . getInstance ( user , request , AccessMode . Backend ) ; SessionHelper . clearInvalidSessions ( user ) ; } } securityContext . setAuthenticator ( this ) ; final String origin = request . getHeader ( "Origin" ) ; if ( ! StringUtils . isBlank ( origin ) ) { final Services services = Services . getInstance ( ) ; response . setHeader ( "Access-Control-Allow-Origin" , origin ) ; final String maxAge = Settings . AccessControlMaxAge . getValue ( ) ; if ( StringUtils . isNotBlank ( maxAge ) ) { response . setHeader ( "Access-Control-Max-Age" , maxAge ) ; } final String allowMethods = Settings . AccessControlAllowMethods . getValue ( ) ; if ( StringUtils . isNotBlank ( allowMethods ) ) { response . setHeader ( "Access-Control-Allow-Methods" , allowMethods ) ; } final String allowHeaders = Settings . AccessControlAllowHeaders . getValue ( ) ; if ( StringUtils . isNotBlank ( allowHeaders ) ) { response . setHeader ( "Access-Control-Allow-Headers" , allowHeaders ) ; } final String allowCredentials = Settings . AccessControlAllowCredentials . getValue ( ) ; if ( StringUtils . isNotBlank ( allowCredentials ) ) { response . setHeader ( "Access-Control-Allow-Credentials" , allowCredentials ) ; } final String exposeHeaders = Settings . AccessControlExposeHeaders . getValue ( ) ; if ( StringUtils . isNotBlank ( exposeHeaders ) ) { response . setHeader ( "Access-Control-Expose-Headers" , exposeHeaders ) ; } } examined = true ; return securityContext ; }
Examine request and try to find a user .
35,094
private int calculateSexCode ( Person . Sex sex ) { return SEX_FIELDS [ baseProducer . randomInt ( SEX_FIELDS . length - 1 ) ] + ( sex == Person . Sex . MALE ? 1 : 0 ) ; }
This should be tested
35,095
public static String getRandomNumStr ( BaseProducer baseProducer , int max , int paddingSize ) { int rndNum = baseProducer . randomBetween ( 1 , max ) ; String numStr = "" + rndNum ; while ( numStr . length ( ) < paddingSize ) { numStr = "0" + numStr ; } return numStr ; }
Get random number from 1 to max in 0 leading string format .
35,096
public static Fairy create ( Locale locale , String dataFilePrefix ) { return builder ( ) . withLocale ( locale ) . withFilePrefix ( dataFilePrefix ) . build ( ) ; }
Use this factory method to create your own dataset overriding bundled one
35,097
private static FairyModule getFairyModuleForLocale ( DataMaster dataMaster , Locale locale , RandomGenerator randomGenerator ) { LanguageCode code ; try { code = LanguageCode . valueOf ( locale . getLanguage ( ) . toUpperCase ( ) ) ; } catch ( IllegalArgumentException e ) { LOG . warn ( "Uknown locale " + locale ) ; code = LanguageCode . EN ; } switch ( code ) { case PL : return new PlFairyModule ( dataMaster , randomGenerator ) ; case EN : return new EnFairyModule ( dataMaster , randomGenerator ) ; case ES : return new EsFairyModule ( dataMaster , randomGenerator ) ; case FR : return new EsFairyModule ( dataMaster , randomGenerator ) ; case SV : return new SvFairyModule ( dataMaster , randomGenerator ) ; case ZH : return new ZhFairyModule ( dataMaster , randomGenerator ) ; case DE : return new DeFairyModule ( dataMaster , randomGenerator ) ; case KA : return new KaFairyModule ( dataMaster , randomGenerator ) ; default : LOG . info ( "No data for your language - using EN" ) ; return new EnFairyModule ( dataMaster , randomGenerator ) ; } }
Support customized language config
35,098
public void readResources ( String path ) throws IOException { Enumeration < URL > resources = getClass ( ) . getClassLoader ( ) . getResources ( path ) ; if ( ! resources . hasMoreElements ( ) ) { throw new IllegalArgumentException ( String . format ( "File %s was not found on classpath" , path ) ) ; } Yaml yaml = new Yaml ( ) ; while ( resources . hasMoreElements ( ) ) { appendData ( yaml . loadAs ( resources . nextElement ( ) . openStream ( ) , Data . class ) ) ; } }
fixme - should be package - private
35,099
public < T > T randomElement ( List < T > elements ) { return elements . get ( randomBetween ( 0 , elements . size ( ) - 1 ) ) ; }
Returns random element from passed List