idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
14,400
public JsonResponse deleteBlast ( Integer blastId ) throws IOException { Blast blast = new Blast ( ) ; blast . setBlastId ( blastId ) ; return apiDelete ( blast ) ; }
Delete existing blast
43
3
14,401
public JsonResponse cancelBlast ( Integer blastId ) throws IOException { Blast blast = new Blast ( ) ; Date d = null ; blast . setBlastId ( blastId ) . setScheduleTime ( d ) ; return apiPost ( blast ) ; }
Cancel a scheduled Blast
56
5
14,402
public JsonResponse getTemplate ( String template ) throws IOException { Map < String , Object > data = new HashMap < String , Object > ( ) ; data . put ( Template . PARAM_TEMPLATE , template ) ; return apiGet ( ApiAction . template , data ) ; }
Get template information
64
3
14,403
public JsonResponse deleteTemplate ( String template ) throws IOException { Map < String , Object > data = new HashMap < String , Object > ( ) ; data . put ( Template . PARAM_TEMPLATE , template ) ; return apiDelete ( ApiAction . template , data ) ; }
Delete existing template
64
3
14,404
public JsonResponse getAlert ( String email ) throws IOException { Map < String , Object > data = new HashMap < String , Object > ( ) ; data . put ( Alert . PARAM_EMAIL , email ) ; return apiGet ( ApiAction . alert , data ) ; }
Retrieve a user s alert settings
62
7
14,405
public JsonResponse deleteAlert ( String email , String alertId ) throws IOException { Map < String , Object > data = new HashMap < String , Object > ( ) ; data . put ( Alert . PARAM_EMAIL , email ) ; data . put ( Alert . PARAM_ALERT_ID , alertId ) ; return apiDelete ( ApiAction . alert , data ) ; }
Delete existing user alert
84
4
14,406
public Map < String , Object > listStats ( ListStat stat ) throws IOException { return ( Map < String , Object > ) this . stats ( stat ) ; }
get list stats information
35
4
14,407
public Map < String , Object > blastStats ( BlastStat stat ) throws IOException { return ( Map < String , Object > ) this . stats ( stat ) ; }
get blast stats information
35
4
14,408
public JsonResponse getJobStatus ( String jobId ) throws IOException { Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( Job . JOB_ID , jobId ) ; return apiGet ( ApiAction . job , params ) ; }
Get status of a job
64
5
14,409
public OSchemaHelper linkedClass ( String className ) { checkOProperty ( ) ; OClass linkedToClass = schema . getClass ( className ) ; if ( linkedToClass == null ) throw new IllegalArgumentException ( "Target OClass '" + className + "' to link to not found" ) ; if ( ! Objects . equal ( linkedToClass , lastProperty . getLinkedClass ( ) ) ) { lastProperty . setLinkedClass ( linkedToClass ) ; } return this ; }
Set linked class to a current property
109
7
14,410
public OSchemaHelper linkedType ( OType linkedType ) { checkOProperty ( ) ; if ( ! Objects . equal ( linkedType , lastProperty . getLinkedType ( ) ) ) { lastProperty . setLinkedType ( linkedType ) ; } return this ; }
Set linked type to a current property
59
7
14,411
public OSchemaHelper field ( String field , Object value ) { checkODocument ( ) ; lastDocument . field ( field , value ) ; return this ; }
Sets a field value for a current document
34
9
14,412
public static < R > R sudo ( Function < ODatabaseDocument , R > func ) { return new DBClosure < R > ( ) { @ Override protected R execute ( ODatabaseDocument db ) { return func . apply ( db ) ; } } . execute ( ) ; }
Simplified function to execute under admin
58
8
14,413
public static void sudoConsumer ( Consumer < ODatabaseDocument > consumer ) { new DBClosure < Void > ( ) { @ Override protected Void execute ( ODatabaseDocument db ) { consumer . accept ( db ) ; return null ; } } . execute ( ) ; }
Simplified consumer to execute under admin
55
8
14,414
public static void sudoSave ( final ODocument ... docs ) { if ( docs == null || docs . length == 0 ) return ; new DBClosure < Boolean > ( ) { @ Override protected Boolean execute ( ODatabaseDocument db ) { db . begin ( ) ; for ( ODocument doc : docs ) { db . save ( doc ) ; } db . commit ( ) ; return true ; } } . execute ( ) ; }
Allow to save set of document under admin
89
8
14,415
public static void sudoSave ( final ODocumentWrapper ... dws ) { if ( dws == null || dws . length == 0 ) return ; new DBClosure < Boolean > ( ) { @ Override protected Boolean execute ( ODatabaseDocument db ) { db . begin ( ) ; for ( ODocumentWrapper dw : dws ) { dw . save ( ) ; } db . commit ( ) ; return true ; } } . execute ( ) ; }
Allow to save set of document wrappers under admin
96
10
14,416
public static String buitify ( String string ) { char [ ] chars = string . toCharArray ( ) ; StringBuilder sb = new StringBuilder ( ) ; int lastApplied = 0 ; for ( int i = 0 ; i < chars . length ; i ++ ) { char pCh = i > 0 ? chars [ i - 1 ] : 0 ; char ch = chars [ i ] ; if ( ch == ' ' || ch == ' ' || Character . isWhitespace ( ch ) ) { sb . append ( chars , lastApplied , i - lastApplied ) ; lastApplied = i + 1 ; } else if ( i == 0 && Character . isLowerCase ( ch ) ) { sb . append ( Character . toUpperCase ( ch ) ) ; lastApplied = i + 1 ; } else if ( i > 0 && Character . isUpperCase ( ch ) && ! ( Character . isWhitespace ( pCh ) || pCh == ' ' || pCh == ' ' ) && ! Character . isUpperCase ( pCh ) ) { sb . append ( chars , lastApplied , i - lastApplied ) . append ( ' ' ) . append ( ch ) ; lastApplied = i + 1 ; } else if ( i > 0 && Character . isLowerCase ( ch ) && ( Character . isWhitespace ( pCh ) || pCh == ' ' || pCh == ' ' ) ) { sb . append ( chars , lastApplied , i - lastApplied ) ; if ( sb . length ( ) > 0 ) sb . append ( ' ' ) ; sb . append ( Character . toUpperCase ( ch ) ) ; lastApplied = i + 1 ; } } sb . append ( chars , lastApplied , chars . length - lastApplied ) ; return sb . toString ( ) ; }
Utility method to make source string more human readable
406
10
14,417
protected Object getDefaultValue ( String propName , Class < ? > returnType ) { Object ret = null ; if ( returnType . isPrimitive ( ) ) { if ( returnType . equals ( boolean . class ) ) { return false ; } else if ( returnType . equals ( char . class ) ) { return ' ' ; } else { try { Class < ? > wrapperClass = Primitives . wrap ( returnType ) ; return wrapperClass . getMethod ( "valueOf" , String . class ) . invoke ( null , "0" ) ; } catch ( Throwable e ) { throw new WicketRuntimeException ( "Can't create default value for '" + propName + "' which should have type '" + returnType . getName ( ) + "'" ) ; } } } return ret ; }
Method for obtaining default value of required property
172
8
14,418
public static boolean isAllowed ( ORule . ResourceGeneric resource , String specific , OrientPermission ... permissions ) { return OrientDbWebSession . get ( ) . getEffectiveUser ( ) . checkIfAllowed ( resource , specific , OrientPermission . combinedPermission ( permissions ) ) != null ; }
Check that all required permissions present for specified resource and specific
64
11
14,419
public static String getResourceSpecific ( String name ) { ORule . ResourceGeneric generic = getResourceGeneric ( name ) ; String specific = generic != null ? Strings . afterFirst ( name , ' ' ) : name ; return Strings . isEmpty ( specific ) ? null : specific ; }
Extract specific from resource string
61
6
14,420
public String resolveOrientDBRestApiUrl ( ) { OrientDbWebApplication app = OrientDbWebApplication . get ( ) ; OServer server = app . getServer ( ) ; if ( server != null ) { OServerNetworkListener http = server . getListenerByProtocol ( ONetworkProtocolHttpAbstract . class ) ; if ( http != null ) { return "http://" + http . getListeningAddress ( true ) ; } } return null ; }
Resolve OrientDB REST API URL to be used for OrientDb REST bridge
100
15
14,421
public boolean isInProgress ( RequestCycle cycle ) { Boolean inProgress = cycle . getMetaData ( IN_PROGRESS_KEY ) ; return inProgress != null ? inProgress : false ; }
Is current transaction in progress?
43
6
14,422
public OClass probeOClass ( int probeLimit ) { Iterator < ODocument > it = iterator ( 0 , probeLimit , null ) ; return OSchemaUtils . probeOClass ( it , probeLimit ) ; }
Probe the dataset and returns upper OClass for sample
48
11
14,423
public long size ( ) { if ( size == null ) { ODatabaseDocument db = OrientDbWebSession . get ( ) . getDatabase ( ) ; OSQLSynchQuery < ODocument > query = new OSQLSynchQuery < ODocument > ( queryManager . getCountSql ( ) ) ; List < ODocument > ret = db . query ( enhanceContextByVariables ( query ) , prepareParams ( ) ) ; if ( ret != null && ret . size ( ) > 0 ) { Number sizeNumber = ret . get ( 0 ) . field ( "count" ) ; size = sizeNumber != null ? sizeNumber . longValue ( ) : 0 ; } else { size = 0L ; } } return size ; }
Get the size of the data
158
6
14,424
public OQueryModel < K > setSort ( String sortableParameter , SortOrder order ) { setSortableParameter ( sortableParameter ) ; setAscending ( SortOrder . ASCENDING . equals ( order ) ) ; return this ; }
Set sorting configration
52
4
14,425
public static String md5 ( String data ) { try { return DigestUtils . md5Hex ( data . toString ( ) . getBytes ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { return DigestUtils . md5Hex ( data . toString ( ) ) ; } }
generates MD5 Hash
71
5
14,426
public static String arrayListToCSV ( List < String > list ) { StringBuilder csv = new StringBuilder ( ) ; for ( String str : list ) { csv . append ( str ) ; csv . append ( "," ) ; } int lastIndex = csv . length ( ) - 1 ; char last = csv . charAt ( lastIndex ) ; if ( last == ' ' ) { return csv . substring ( 0 , lastIndex ) ; } return csv . toString ( ) ; }
Converts String ArrayList to CSV string
111
8
14,427
protected Scheme getScheme ( ) { String scheme ; try { URI uri = new URI ( this . apiUrl ) ; scheme = uri . getScheme ( ) ; } catch ( URISyntaxException e ) { scheme = "http" ; } if ( scheme . equals ( "https" ) ) { return new Scheme ( scheme , DEFAULT_HTTPS_PORT , SSLSocketFactory . getSocketFactory ( ) ) ; } else { return new Scheme ( scheme , DEFAULT_HTTP_PORT , PlainSocketFactory . getSocketFactory ( ) ) ; } }
Get Scheme Object
122
3
14,428
protected Object httpRequest ( ApiAction action , HttpRequestMethod method , Map < String , Object > data ) throws IOException { String url = this . apiUrl + "/" + action . toString ( ) . toLowerCase ( ) ; Type type = new TypeToken < Map < String , Object > > ( ) { } . getType ( ) ; String json = GSON . toJson ( data , type ) ; Map < String , String > params = buildPayload ( json ) ; Object response = httpClient . executeHttpRequest ( url , method , params , handler , customHeaders ) ; recordRateLimitInfo ( action , method , response ) ; return response ; }
Make Http request to Sailthru API for given resource with given method and data
145
17
14,429
protected Object httpRequest ( HttpRequestMethod method , ApiParams apiParams ) throws IOException { ApiAction action = apiParams . getApiCall ( ) ; String url = apiUrl + "/" + action . toString ( ) . toLowerCase ( ) ; String json = GSON . toJson ( apiParams , apiParams . getType ( ) ) ; Map < String , String > params = buildPayload ( json ) ; Object response = httpClient . executeHttpRequest ( url , method , params , handler , customHeaders ) ; recordRateLimitInfo ( action , method , response ) ; return response ; }
Make HTTP Request to Sailthru API but with Api Params rather than generalized Map this is recommended way to make request if data structure is complex
139
30
14,430
private Map < String , String > buildPayload ( String jsonPayload ) { Map < String , String > params = new HashMap < String , String > ( ) ; params . put ( "api_key" , apiKey ) ; params . put ( "format" , handler . getSailthruResponseHandler ( ) . getFormat ( ) ) ; params . put ( "json" , jsonPayload ) ; params . put ( "sig" , getSignatureHash ( params ) ) ; return params ; }
Build HTTP Request Payload
111
5
14,431
protected String getSignatureHash ( Map < String , String > parameters ) { List < String > values = new ArrayList < String > ( ) ; StringBuilder data = new StringBuilder ( ) ; data . append ( this . apiSecret ) ; for ( Entry < String , String > entry : parameters . entrySet ( ) ) { values . add ( entry . getValue ( ) ) ; } Collections . sort ( values ) ; for ( String value : values ) { data . append ( value ) ; } return SailthruUtil . md5 ( data . toString ( ) ) ; }
Get Signature Hash from given Map
124
6
14,432
public JsonResponse apiGet ( ApiAction action , Map < String , Object > data ) throws IOException { return httpRequestJson ( action , HttpRequestMethod . GET , data ) ; }
HTTP GET Request with Map
43
5
14,433
public JsonResponse apiPost ( ApiAction action , Map < String , Object > data ) throws IOException { return httpRequestJson ( action , HttpRequestMethod . POST , data ) ; }
HTTP POST Request with Map
43
5
14,434
public JsonResponse apiPost ( ApiParams data , ApiFileParams fileParams ) throws IOException { return httpRequestJson ( HttpRequestMethod . POST , data , fileParams ) ; }
HTTP POST Request with Interface implementation of ApiParams and ApiFileParams
47
17
14,435
public JsonResponse apiDelete ( ApiAction action , Map < String , Object > data ) throws IOException { return httpRequestJson ( action , HttpRequestMethod . DELETE , data ) ; }
HTTP DELETE Request
45
5
14,436
static public int obtainNextIncrementInteger ( Connection connection , ColumnData autoIncrementIntegerColumn ) throws Exception { try { String sqlQuery = "SELECT nextval(?);" ; // Create SQL command PreparedStatement pstmt = null ; { pstmt = connection . prepareStatement ( sqlQuery ) ; // Populate prepared statement pstmt . setString ( 1 , autoIncrementIntegerColumn . getAutoIncrementSequence ( ) ) ; } if ( pstmt . execute ( ) ) { ResultSet rs = pstmt . getResultSet ( ) ; if ( rs . next ( ) ) { int nextValue = rs . getInt ( 1 ) ; return nextValue ; } else { throw new Exception ( "Empty result returned by SQL: " + sqlQuery ) ; } } else { throw new Exception ( "No result returned by SQL: " + sqlQuery ) ; } } catch ( Exception e ) { throw new Exception ( "Error while attempting to get a auto increment integer value for: " + autoIncrementIntegerColumn . getColumnName ( ) + " (" + autoIncrementIntegerColumn . getAutoIncrementSequence ( ) + ")" , e ) ; } }
Performs a database query to find the next integer in the sequence reserved for the given column .
252
19
14,437
static String unescapeEntity ( String e ) { // validate if ( e == null || e . isEmpty ( ) ) { return "" ; } // if our entity is an encoded unicode point, parse it. if ( e . charAt ( 0 ) == ' ' ) { int cp ; if ( e . charAt ( 1 ) == ' ' ) { // hex encoded unicode cp = Integer . parseInt ( e . substring ( 2 ) , 16 ) ; } else { // decimal encoded unicode cp = Integer . parseInt ( e . substring ( 1 ) ) ; } return new String ( new int [ ] { cp } , 0 , 1 ) ; } Character knownEntity = entity . get ( e ) ; if ( knownEntity == null ) { // we don't know the entity so keep it encoded return ' ' + e + ' ' ; } return knownEntity . toString ( ) ; }
Unescapes an XML entity encoding ;
191
9
14,438
private String convertLastSeqObj ( Object lastSeqObj ) throws Exception { if ( null == lastSeqObj ) { return null ; } else if ( lastSeqObj instanceof String ) { return ( String ) lastSeqObj ; } else if ( lastSeqObj instanceof Number ) { // Convert to string return "" + lastSeqObj ; } else { throw new Exception ( "Do not know how to handle parameter 'last_seq' in change feed: " + lastSeqObj . getClass ( ) ) ; } }
Converts the object last_seq found in the change feed to a String . In CouchDB 1 . x last_seq is an integer . In CouchDB 2 . x last_seq is a string .
116
42
14,439
public void renameAttachmentTo ( String newAttachmentName ) throws Exception { JSONObject doc = documentDescriptor . getJson ( ) ; JSONObject _attachments = doc . optJSONObject ( "_attachments" ) ; JSONObject nunaliit_attachments = doc . getJSONObject ( UploadConstants . KEY_DOC_ATTACHMENTS ) ; JSONObject files = nunaliit_attachments . getJSONObject ( "files" ) ; // Verify no collision within nunaliit_attachments.files { Object obj = files . opt ( newAttachmentName ) ; if ( null != obj ) { throw new Exception ( "Can not rename attachment because of name collision" ) ; } } // Verify no collision within _attachments if ( null != _attachments ) { Object obj = _attachments . opt ( newAttachmentName ) ; if ( null != obj ) { throw new Exception ( "Can not rename attachment because of name collision" ) ; } } // Not allowed to move a stub if ( null != _attachments ) { JSONObject att = _attachments . optJSONObject ( attName ) ; if ( null != att ) { throw new Exception ( "Can not rename attachment descriptor because file is already attached" ) ; } } // Move descriptor to new name String oldAttachmentName = attName ; JSONObject descriptor = files . getJSONObject ( oldAttachmentName ) ; files . remove ( oldAttachmentName ) ; files . put ( newAttachmentName , descriptor ) ; attName = newAttachmentName ; setStringAttribute ( UploadConstants . ATTACHMENT_NAME_KEY , newAttachmentName ) ; // Loop through all attachment descriptors, updating "source", "thumbnail" // and "original" attributes { Iterator < ? > it = files . keys ( ) ; while ( it . hasNext ( ) ) { Object objKey = it . next ( ) ; if ( objKey instanceof String ) { String key = ( String ) objKey ; JSONObject att = files . getJSONObject ( key ) ; { String value = att . optString ( "source" , null ) ; if ( oldAttachmentName . equals ( value ) ) { att . put ( "source" , newAttachmentName ) ; } } { String value = att . optString ( "thumbnail" , null ) ; if ( oldAttachmentName . equals ( value ) ) { att . put ( "thumbnail" , newAttachmentName ) ; } } { String value = att . optString ( "originalAttachment" , null ) ; if ( oldAttachmentName . equals ( value ) ) { att . put ( "original" , newAttachmentName ) ; } } } } } }
Renames an attachment . This ensures that there is no collision and that all references to this attachment are updated properly within this document .
578
26
14,440
static public FSEntry getPositionedFile ( String path , File file ) throws Exception { List < String > pathFrags = FSEntrySupport . interpretPath ( path ) ; // Start at leaf and work our way back int index = pathFrags . size ( ) - 1 ; FSEntry root = new FSEntryFile ( pathFrags . get ( index ) , file ) ; -- index ; while ( index >= 0 ) { FSEntryVirtualDirectory parent = new FSEntryVirtualDirectory ( pathFrags . get ( index ) ) ; parent . addChildEntry ( root ) ; root = parent ; -- index ; } return root ; }
Create a virtual tree hierarchy with a file supporting the leaf .
144
12
14,441
private String computeSelectScore ( List < String > searchFields ) throws Exception { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; if ( 0 == searchFields . size ( ) ) { throw new Exception ( "Must supply at least one search field" ) ; } else if ( 1 == searchFields . size ( ) ) { pw . print ( "coalesce(nullif(position(lower(?) IN lower(" ) ; pw . print ( searchFields . get ( 0 ) ) ; pw . print ( ")), 0), 9999)" ) ; } else { int loop ; for ( loop = 0 ; loop < searchFields . size ( ) - 1 ; ++ loop ) { pw . print ( "least(coalesce(nullif(position(lower(?) IN lower(" ) ; pw . print ( searchFields . get ( loop ) ) ; pw . print ( ")), 0), 9999)," ) ; } pw . print ( "coalesce(nullif(position(lower(?) IN lower(" ) ; pw . print ( searchFields . get ( loop ) ) ; pw . print ( ")), 0), 9999)" ) ; for ( loop = 0 ; loop < searchFields . size ( ) - 1 ; ++ loop ) { pw . print ( ")" ) ; } } pw . flush ( ) ; return sw . toString ( ) ; }
Create a SQL fragment that can be used to compute a score based on a search .
319
17
14,442
private String computeWhereFragment ( List < String > searchFields ) throws Exception { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; boolean first = true ; for ( int loop = 0 ; loop < searchFields . size ( ) ; ++ loop ) { if ( first ) { first = false ; pw . print ( " WHERE " ) ; } else { pw . print ( " OR " ) ; } pw . print ( "lower(" ) ; pw . print ( searchFields . get ( loop ) ) ; pw . print ( ") LIKE lower(?)" ) ; } pw . flush ( ) ; return sw . toString ( ) ; }
Given a number of search fields compute the SQL fragment used to filter the searched rows
155
16
14,443
private JSONArray executeStatementToJson ( PreparedStatement stmt , List < SelectedColumn > selectFields ) throws Exception { //logger.info("about to execute: " + stmt.toString()); if ( stmt . execute ( ) ) { // There's a ResultSet to be had ResultSet rs = stmt . getResultSet ( ) ; JSONArray array = new JSONArray ( ) ; try { Map < Integer , JSONObject > contributorMap = new HashMap < Integer , JSONObject > ( ) ; while ( rs . next ( ) ) { JSONObject obj = new JSONObject ( ) ; int index = 1 ; for ( int loop = 0 ; loop < selectFields . size ( ) ; ++ loop ) { SelectedColumn selCol = selectFields . get ( loop ) ; //logger.info("field: " + selCol.getName() + " (" + selCol.getType() + ")"); if ( ! "contributor_id" . equalsIgnoreCase ( selCol . getName ( ) ) ) { if ( SelectedColumn . Type . INTEGER == selCol . getType ( ) ) { obj . put ( selCol . getName ( ) , rs . getInt ( index ) ) ; ++ index ; } else if ( SelectedColumn . Type . STRING == selCol . getType ( ) ) { obj . put ( selCol . getName ( ) , rs . getString ( index ) ) ; ++ index ; } else if ( SelectedColumn . Type . DATE == selCol . getType ( ) ) { Date date = rs . getDate ( index ) ; if ( null != date ) { String dateString = dateFormatter . format ( date ) ; obj . put ( selCol . getName ( ) , dateString ) ; } ++ index ; } else { throw new Exception ( "Unkown selected column type" ) ; } } else { // Convert contributor id into user info int contribId = rs . getInt ( index ) ; JSONObject userInfo = fetchContributorFromIdWithCache ( contribId , contributorMap ) ; if ( null != userInfo ) { obj . put ( "contributor" , userInfo ) ; } ++ index ; } } array . put ( obj ) ; } } catch ( Exception je ) { throw new ServletException ( "Error while executing statement" , je ) ; } return array ; } else { // indicates an update count or no results - this must be no results throw new Exception ( "Query returned no results" ) ; } }
This method executes a prepared SQL statement and returns a JSON array that contains the result .
553
17
14,444
public JSONObject getAudioMediaFromPlaceId ( String place_id ) throws Exception { List < SelectedColumn > selectFields = new Vector < SelectedColumn > ( ) ; selectFields . add ( new SelectedColumn ( SelectedColumn . Type . INTEGER , "id" ) ) ; selectFields . add ( new SelectedColumn ( SelectedColumn . Type . INTEGER , "place_id" ) ) ; selectFields . add ( new SelectedColumn ( SelectedColumn . Type . STRING , "filename" ) ) ; selectFields . add ( new SelectedColumn ( SelectedColumn . Type . STRING , "mimetype" ) ) ; selectFields . add ( new SelectedColumn ( SelectedColumn . Type . STRING , "title" ) ) ; PreparedStatement stmt = connection . prepareStatement ( "SELECT id,place_id,filename,mimetype,title " + "FROM contributions " + "WHERE mimetype LIKE 'audio/%' AND place_id = ?;" ) ; stmt . setInt ( 1 , Integer . parseInt ( place_id ) ) ; JSONArray array = executeStatementToJson ( stmt , selectFields ) ; JSONObject result = new JSONObject ( ) ; result . put ( "media" , array ) ; return result ; }
Finds and returns all audio media associated with a place id .
280
13
14,445
static public boolean hasDocumentBeenModified ( JSONObject targetDoc ) { JSONObject targetManifest = targetDoc . optJSONObject ( MANIFEST_KEY ) ; if ( null == targetManifest ) { // Can not verify digest on target document. Let's assume it has // been modified return true ; } String targetDigest = targetManifest . optString ( "digest" ) ; if ( null == targetDigest ) { // Can not verify digest on target document, let's assume it // has changed return true ; } // Check type DigestComputer digestComputer = null ; { String type = targetManifest . optString ( "type" ) ; if ( null == type ) { // Has been modified sine type is missing return true ; } else if ( DigestComputerSha1 . DIGEST_COMPUTER_TYPE . equals ( type ) ) { digestComputer = sha1DigestComputer ; } else { // Unrecognized type. Assume it was changed return true ; } } try { String computedDigest = digestComputer . computeDigestFromJsonObject ( targetDoc ) ; if ( false == computedDigest . equals ( targetDigest ) ) { // Digests are different. It was changed return true ; } } catch ( Exception e ) { // Error computing digest, let's assume it was changed return true ; } // Verify attachments by checking each attachment in manifest and verifying // each attachment has not changed Set < String > attachmentNamesInManifest = new HashSet < String > ( ) ; JSONObject targetAttachmentManifests = targetManifest . optJSONObject ( "attachments" ) ; if ( null != targetAttachmentManifests ) { Iterator < ? > it = targetAttachmentManifests . keys ( ) ; while ( it . hasNext ( ) ) { Object keyObj = it . next ( ) ; if ( keyObj instanceof String ) { String attachmentName = ( String ) keyObj ; attachmentNamesInManifest . add ( attachmentName ) ; JSONObject attachmentManifest = targetAttachmentManifests . optJSONObject ( attachmentName ) ; if ( null == attachmentManifest ) { // Error. Must have been changed return true ; } else if ( false == JSONSupport . containsKey ( attachmentManifest , "revpos" ) ) { // revpos is gone, document must have been modified return true ; } else { int revpos = attachmentManifest . optInt ( "revpos" , 0 ) ; Integer actualRevPos = getAttachmentPosition ( targetDoc , attachmentName ) ; if ( null == actualRevPos ) { // Attachment is gone return true ; } else if ( revpos != actualRevPos . intValue ( ) ) { // Attachment has changed return true ; } } } } } // Verify that each attachment has a manifest declared for it JSONObject targetAttachments = targetDoc . optJSONObject ( "_attachments" ) ; if ( null != targetAttachments ) { Iterator < ? > it = targetAttachments . keys ( ) ; while ( it . hasNext ( ) ) { Object keyObj = it . next ( ) ; if ( keyObj instanceof String ) { String attachmentName = ( String ) keyObj ; if ( false == attachmentNamesInManifest . contains ( attachmentName ) ) { // This attachment was added since manifest was computed return true ; } } } } // If we make it here, the document has not changed according to the manifest return false ; }
Analyzes a document and determines if the document has been modified since the time the manifest was computed .
735
20
14,446
static public Integer getAttachmentPosition ( JSONObject targetDoc , String attachmentName ) { JSONObject targetAttachments = targetDoc . optJSONObject ( "_attachments" ) ; if ( null == targetAttachments ) { // No attachment on target doc return null ; } JSONObject targetAttachment = targetAttachments . optJSONObject ( attachmentName ) ; if ( null == targetAttachment ) { // Target document does not have an attachment with this name return null ; } if ( JSONSupport . containsKey ( targetAttachment , "revpos" ) ) { int revPos = targetAttachment . optInt ( "revpos" , - 1 ) ; if ( revPos < 0 ) { return null ; } return revPos ; } return null ; }
Given a JSON document and an attachment name returns the revision position associated with the attachment .
158
17
14,447
public static void setCompressionType ( ImageWriteParam param , BufferedImage image ) { // avoid error: first compression type is RLE, not optimal and incorrect for color images // TODO expose this choice to the user? if ( image . getType ( ) == BufferedImage . TYPE_BYTE_BINARY && image . getColorModel ( ) . getPixelSize ( ) == 1 ) { param . setCompressionType ( "CCITT T.6" ) ; } else { param . setCompressionType ( "LZW" ) ; } }
Sets the ImageIO parameter compression type based on the given image .
121
14
14,448
static public FSEntry getPositionedResource ( String path , ClassLoader classLoader , String resourceName ) throws Exception { List < String > pathFrags = FSEntrySupport . interpretPath ( path ) ; // Start at leaf and work our way back int index = pathFrags . size ( ) - 1 ; FSEntry root = create ( pathFrags . get ( index ) , classLoader , resourceName ) ; -- index ; while ( index >= 0 ) { FSEntryVirtualDirectory parent = new FSEntryVirtualDirectory ( pathFrags . get ( index ) ) ; parent . addChildEntry ( root ) ; root = parent ; -- index ; } return root ; }
Create a virtual tree hierarchy with a resource supporting the leaf .
149
12
14,449
static public FSEntryResource create ( ClassLoader classLoader , String resourceName ) throws Exception { return create ( null , classLoader , resourceName ) ; }
Creates an instance of FSEntryResource to represent an entry based on the resource specified by the classLoader and resource name .
34
27
14,450
static public FSEntryResource create ( String name , ClassLoader classLoader , String resourceName ) throws Exception { URL url = classLoader . getResource ( resourceName ) ; if ( "jar" . equals ( url . getProtocol ( ) ) ) { String path = url . getPath ( ) ; if ( path . startsWith ( "file:" ) ) { int bangIndex = path . indexOf ( ' ' ) ; if ( bangIndex >= 0 ) { String jarFileName = path . substring ( "file:" . length ( ) , bangIndex ) ; String resourceNameFile = path . substring ( bangIndex + 2 ) ; String resourceNameDir = resourceNameFile ; if ( false == resourceNameDir . endsWith ( "/" ) ) { resourceNameDir = resourceNameFile + "/" ; } JarFile jarFile = new JarFile ( URLDecoder . decode ( jarFileName , "UTF-8" ) ) ; Enumeration < JarEntry > entries = jarFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { JarEntry jarEntry = entries . nextElement ( ) ; String entryName = jarEntry . getName ( ) ; if ( entryName . equals ( resourceNameFile ) || entryName . equals ( resourceNameDir ) ) { // Compute name if required if ( null == name ) { name = nameFromJarEntry ( jarEntry ) ; } return new FSEntryResource ( name , jarFile , jarEntry ) ; } } } } throw new Exception ( "Unable to find resource: " + resourceName ) ; } else if ( "file" . equals ( url . getProtocol ( ) ) ) { File file = new File ( url . getFile ( ) ) ; if ( null == name ) { name = file . getName ( ) ; } return new FSEntryResource ( name , file ) ; } else { throw new Exception ( "Unable to create resource entry for protocol: " + url . getProtocol ( ) ) ; } }
Creates an instance of FSEntryResource to represent an entry based on the resource specified by the classLoader and resource name . This resource can be a file or a directory . Furthermore this resource can be located on file system or inside a JAR file .
433
53
14,451
private void performAdjustCookies ( HttpServletRequest request , HttpServletResponse response ) throws Exception { boolean loggedIn = false ; User user = null ; try { Cookie cookie = getCookieFromRequest ( request ) ; if ( null != cookie ) { user = CookieAuthentication . verifyCookieString ( userRepository , cookie . getValue ( ) ) ; loggedIn = true ; } } catch ( Exception e ) { // Ignore } if ( null == user ) { user = userRepository . getDefaultUser ( ) ; } acceptRequest ( response , loggedIn , user ) ; }
Adjusts the information cookie based on the authentication token
127
10
14,452
static public TreeRebalanceProcess . Result createTree ( List < ? extends TreeElement > elements ) throws Exception { Result results = new Result ( ) ; // Compute full interval, next cluster id and legacy nodes TimeInterval fullRegularInterval = null ; TimeInterval fullOngoingInterval = null ; results . nextClusterId = 1 ; Map < Integer , TreeNodeRegular > legacyRegularNodes = new HashMap < Integer , TreeNodeRegular > ( ) ; Map < Integer , TreeNodeOngoing > legacyOngoingNodes = new HashMap < Integer , TreeNodeOngoing > ( ) ; for ( TreeElement element : elements ) { Integer clusterId = element . getClusterId ( ) ; // Accumulate full intervals if ( element . getInterval ( ) . isOngoing ( ) ) { if ( null == fullOngoingInterval ) { fullOngoingInterval = element . getInterval ( ) ; } else { fullOngoingInterval = fullOngoingInterval . extendTo ( element . getInterval ( ) ) ; } } else { if ( null == fullRegularInterval ) { fullRegularInterval = element . getInterval ( ) ; } else { fullRegularInterval = fullRegularInterval . extendTo ( element . getInterval ( ) ) ; } } // Figure out next cluster id if ( null != clusterId ) { if ( clusterId >= results . nextClusterId ) { results . nextClusterId = clusterId + 1 ; } } // Accumulate legacy nodes if ( null != clusterId ) { TimeInterval elementInterval = element . getInterval ( ) ; if ( elementInterval . isOngoing ( ) ) { TreeNodeOngoing legacyNode = legacyOngoingNodes . get ( clusterId ) ; if ( null == legacyNode ) { legacyNode = new TreeNodeOngoing ( clusterId , element . getInterval ( ) ) ; legacyOngoingNodes . put ( clusterId , legacyNode ) ; } else { legacyNode . extendTo ( element . getInterval ( ) ) ; } } else { TreeNodeRegular legacyNode = legacyRegularNodes . get ( clusterId ) ; if ( null == legacyNode ) { legacyNode = new TreeNodeRegular ( clusterId , element . getInterval ( ) ) ; legacyRegularNodes . put ( clusterId , legacyNode ) ; } else { legacyNode . extendTo ( element . getInterval ( ) ) ; } } } } // Need a full interval if ( null == fullRegularInterval ) { // Create a default one fullRegularInterval = new TimeInterval ( 0 , 1500000000000L ) ; } if ( null == fullOngoingInterval ) { // Create a default one fullOngoingInterval = new TimeInterval ( 0 , ( NowReference ) null ) ; } // Create root node for tree TreeNodeRegular regularRootNode = new TreeNodeRegular ( results . nextClusterId , fullRegularInterval ) ; results . nextClusterId ++ ; TreeNodeOngoing ongoingRootNode = new TreeNodeOngoing ( results . nextClusterId , fullOngoingInterval ) ; results . nextClusterId ++ ; // Install root node in results results . regularRootNode = regularRootNode ; results . ongoingRootNode = ongoingRootNode ; // Install legacy nodes in results results . legacyNodes . addAll ( legacyRegularNodes . values ( ) ) ; results . legacyNodes . addAll ( legacyOngoingNodes . values ( ) ) ; return results ; }
Creates a new cluster tree given the provided elements . If these elements were already part of a cluster then legacy cluster nodes are created to account for those elements . This is the perfect process in case the previous tree was lost .
775
45
14,453
synchronized public Connection getDb ( String db ) throws Exception { Connection con = null ; if ( nameToConnection . containsKey ( db ) ) { con = nameToConnection . get ( db ) ; } else { ConnectionInfo info = nameToInfo . get ( db ) ; if ( null == info ) { throw new Exception ( "No information provided for database named: " + db ) ; } try { Class . forName ( info . getJdbcClass ( ) ) ; //load the driver con = DriverManager . getConnection ( info . getConnectionString ( ) , info . getUserName ( ) , info . getPassword ( ) ) ; //connect to the db DatabaseMetaData dbmd = con . getMetaData ( ) ; //get MetaData to confirm connection logger . info ( "Connection to " + dbmd . getDatabaseProductName ( ) + " " + dbmd . getDatabaseProductVersion ( ) + " successful.\n" ) ; nameToConnection . put ( db , con ) ; } catch ( Exception e ) { throw new Exception ( "Couldn't get db connection: " + db , e ) ; } } return ( con ) ; }
This method checks for the presence of a Connection associated with the input db parameter . It attempts to create the Connection and adds it to the connection map if it does not already exist . If the Connection exists or is created it is returned .
249
47
14,454
static public void captureReponseErrors ( Object response , String errorMessage ) throws Exception { if ( null == response ) { throw new Exception ( "Capturing errors from null response" ) ; } if ( false == ( response instanceof JSONObject ) ) { // Not an error return ; } JSONObject obj = ( JSONObject ) response ; if ( JSONSupport . containsKey ( obj , "error" ) ) { String serverMessage ; try { serverMessage = obj . getString ( "error" ) ; } catch ( Exception e ) { serverMessage = "Unable to parse error response" ; } if ( null == errorMessage ) { errorMessage = "Error returned by database: " ; } throw new Exception ( errorMessage + serverMessage ) ; } }
Analyze a CouchDb response and raises an exception if an error was returned in the response .
159
19
14,455
static public File computeAtlasDir ( String name ) { File atlasDir = null ; if ( null == name ) { // Current dir atlasDir = new File ( "." ) ; } else { atlasDir = new File ( name ) ; } // Force absolute if ( false == atlasDir . isAbsolute ( ) ) { atlasDir = atlasDir . getAbsoluteFile ( ) ; } return atlasDir ; }
Computes the directory where the atlas resides given a command - line argument provided by the user . If the argument is not given then this method should be called with a null argument .
94
37
14,456
static public File computeInstallDir ( ) { File installDir = null ; // Try to find the path of a known resource file File knownResourceFile = null ; { URL url = Main . class . getClassLoader ( ) . getResource ( "commandResourceDummy.txt" ) ; if ( null == url ) { // Nothing we can do since the resource is not found } else if ( "jar" . equals ( url . getProtocol ( ) ) ) { // The tool is called from an "app assembly". Find the // parent of the "repo" directory String path = url . getPath ( ) ; if ( path . startsWith ( "file:" ) ) { int bangIndex = path . indexOf ( ' ' ) ; if ( bangIndex >= 0 ) { String jarFileName = path . substring ( "file:" . length ( ) , bangIndex ) ; knownResourceFile = new File ( jarFileName ) ; } } } else if ( "file" . equals ( url . getProtocol ( ) ) ) { knownResourceFile = new File ( url . getFile ( ) ) ; } } // Try to find the package installation directory. This should be the parent // of a sub-directory called "repo". This is the directory where all the // JAR files are stored in the command-line tool if ( null == installDir && null != knownResourceFile ) { File tempFile = knownResourceFile ; boolean found = false ; while ( ! found && null != tempFile ) { if ( "repo" . equals ( tempFile . getName ( ) ) ) { found = true ; // Parent of "repo" is where the command-line tool is installed installDir = tempFile . getParentFile ( ) ; } else { // Go to parent tempFile = tempFile . getParentFile ( ) ; } } } // If the "repo" directory is not found, then look for the root // of the nunaliit2 project. In a development environment, this is what // we use to look for other directories. if ( null == installDir && null != knownResourceFile ) { installDir = computeNunaliitDir ( knownResourceFile ) ; } return installDir ; }
Computes the installation directory for the command line tool . This is done by looking for a known resource in a JAR file that ships with the command - line tool . When the resource is found the location of the associated JAR file is derived . From there the root directory of the installation is deduced . If the command - line tool is used in a development environment then the known resource is found either as a file or within a JAR that lives within the project directory . In that case return the root directory of the project .
470
107
14,457
static public File computeContentDir ( File installDir ) { if ( null != installDir ) { // Command-line package File contentDir = new File ( installDir , "content" ) ; if ( contentDir . exists ( ) && contentDir . isDirectory ( ) ) { return contentDir ; } // Development environment File nunaliit2Dir = computeNunaliitDir ( installDir ) ; contentDir = new File ( nunaliit2Dir , "nunaliit2-couch-sdk/src/main/content" ) ; if ( contentDir . exists ( ) && contentDir . isDirectory ( ) ) { return contentDir ; } } return null ; }
Finds the content directory from the installation location and returns it . If the command - line tool is packaged and deployed then the content directory is found at the root of the installation . If the command - line tool is run from the development environment then the content directory is found in the SDK sub - project .
145
61
14,458
static public File computeBinDir ( File installDir ) { if ( null != installDir ) { // Command-line package File binDir = new File ( installDir , "bin" ) ; if ( binDir . exists ( ) && binDir . isDirectory ( ) ) { return binDir ; } // Development environment File nunaliit2Dir = computeNunaliitDir ( installDir ) ; binDir = new File ( nunaliit2Dir , "nunaliit2-couch-sdk/target/appassembler/bin" ) ; if ( binDir . exists ( ) && binDir . isDirectory ( ) ) { return binDir ; } } return null ; }
Finds the bin directory from the installation location and returns it . If the command - line tool is packaged and deployed then the bin directory is found at the root of the installation . If the command - line tool is run from the development environment then the bin directory is found in the SDK sub - project .
148
61
14,459
static public File computeSiteDesignDir ( File installDir ) { if ( null != installDir ) { // Command-line package File templatesDir = new File ( installDir , "internal/siteDesign" ) ; if ( templatesDir . exists ( ) && templatesDir . isDirectory ( ) ) { return templatesDir ; } // Development environment File nunaliit2Dir = computeNunaliitDir ( installDir ) ; templatesDir = new File ( nunaliit2Dir , "nunaliit2-couch-sdk/src/main/internal/siteDesign" ) ; if ( templatesDir . exists ( ) && templatesDir . isDirectory ( ) ) { return templatesDir ; } } return null ; }
Finds the siteDesign directory from the installation location and returns it . If the command - line tool is packaged and deployed then the siteDesign directory is found at the root of the installation . If the command - line tool is run from the development environment then the siteDesign directory is found in the SDK sub - project .
152
64
14,460
static public File computeNunaliitDir ( File installDir ) { while ( null != installDir ) { // The root of the nunalii2 project contains "nunaliit2-couch-command", // "nunaliit2-couch-sdk" and "nunaliit2-js" boolean commandExists = ( new File ( installDir , "nunaliit2-couch-command" ) ) . exists ( ) ; boolean sdkExists = ( new File ( installDir , "nunaliit2-couch-sdk" ) ) . exists ( ) ; boolean jsExists = ( new File ( installDir , "nunaliit2-js" ) ) . exists ( ) ; if ( commandExists && sdkExists && jsExists ) { return installDir ; } else { // Go to parent installDir = installDir . getParentFile ( ) ; } } return null ; }
Given an installation directory find the root directory for the nunaliit2 project . This makes sense only in the context that the command - line tool is run from a development environment .
207
36
14,461
static public Set < String > getDescendantPathNames ( File dir , boolean includeDirectories ) { Set < String > paths = new HashSet < String > ( ) ; if ( dir . exists ( ) && dir . isDirectory ( ) ) { String [ ] names = dir . list ( ) ; for ( String name : names ) { File child = new File ( dir , name ) ; getPathNames ( child , paths , null , includeDirectories ) ; } } return paths ; }
Given a directory returns a set of strings which are the paths to all elements within the directory . This process recurses through all sub - directories .
103
29
14,462
static public void emptyDirectory ( File dir ) throws Exception { String [ ] fileNames = dir . list ( ) ; if ( null != fileNames ) { for ( String fileName : fileNames ) { File file = new File ( dir , fileName ) ; if ( file . isDirectory ( ) ) { emptyDirectory ( file ) ; } boolean deleted = false ; try { deleted = file . delete ( ) ; } catch ( Exception e ) { throw new Exception ( "Unable to delete: " + file . getAbsolutePath ( ) , e ) ; } if ( ! deleted ) { throw new Exception ( "Unable to delete: " + file . getAbsolutePath ( ) ) ; } } } }
Given a directory removes all the content found in the directory .
150
12
14,463
static public MailVetterDailyNotificationTask scheduleTask ( CouchDesignDocument serverDesignDoc , MailNotification mailNotification ) { Timer timer = new Timer ( ) ; MailVetterDailyNotificationTask installedTask = new MailVetterDailyNotificationTask ( timer , serverDesignDoc , mailNotification ) ; Calendar calendar = Calendar . getInstance ( ) ; // now Date now = calendar . getTime ( ) ; calendar . set ( Calendar . HOUR_OF_DAY , 0 ) ; calendar . set ( Calendar . MINUTE , 0 ) ; calendar . set ( Calendar . SECOND , 0 ) ; calendar . set ( Calendar . MILLISECOND , 0 ) ; Date start = calendar . getTime ( ) ; while ( start . getTime ( ) < now . getTime ( ) ) { start = new Date ( start . getTime ( ) + DAILY_PERIOD ) ; } if ( true ) { timer . schedule ( installedTask , start , DAILY_PERIOD ) ; // } else { // This code to test with a shorter period // start = new Date( now.getTime() + (1000*30) ); // timer.schedule(installedTask, start, 1000 * 30); } // Log { SimpleDateFormat sdf = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) ; String startString = sdf . format ( start ) ; logger . info ( "Vetter daily notifications set to start at: " + startString ) ; } return installedTask ; }
24 hours in ms
327
4
14,464
public Geometry simplifyGeometryAtResolution ( Geometry geometry , double resolution ) throws Exception { double inverseRes = 1 / resolution ; double p = Math . log10 ( inverseRes ) ; double exp = Math . ceil ( p ) ; if ( exp < 0 ) exp = 0 ; double factor = Math . pow ( 10 , exp ) ; Geometry simplifiedGeometry = simplify ( geometry , resolution , factor ) ; return simplifiedGeometry ; }
Accepts a geometry and a resolution . Returns a version of the geometry which is simplified for the given resolution . If the initial geometry is already simplified enough then return null .
94
34
14,465
private void performQuery ( HttpServletRequest request , HttpServletResponse response ) throws Exception { User user = AuthenticationUtils . getUserFromRequest ( request ) ; String tableName = getTableNameFromRequest ( request ) ; DbTableAccess tableAccess = DbTableAccess . getAccess ( dbSecurity , tableName , new DbUserAdaptor ( user ) ) ; List < RecordSelector > whereMap = getRecordSelectorsFromRequest ( request ) ; List < FieldSelector > selectSpecifiers = getFieldSelectorsFromRequest ( request ) ; List < FieldSelector > groupByColumnNames = getGroupByFromRequest ( request ) ; List < OrderSpecifier > orderBy = getOrderByList ( request ) ; Integer limit = getLimitFromRequest ( request ) ; Integer offset = getOffsetFromRequest ( request ) ; JSONArray queriedObjects = tableAccess . query ( whereMap , selectSpecifiers , groupByColumnNames , orderBy , limit , offset ) ; JSONObject obj = new JSONObject ( ) ; obj . put ( "queried" , queriedObjects ) ; sendJsonResponse ( response , obj ) ; }
Perform a SQL query of a specified table that must be accessible via dbSec .
248
17
14,466
private void performMultiQuery ( HttpServletRequest request , HttpServletResponse response ) throws Exception { User user = AuthenticationUtils . getUserFromRequest ( request ) ; String [ ] queriesStrings = request . getParameterValues ( "queries" ) ; if ( 1 != queriesStrings . length ) { throw new Exception ( "Parameter 'queries' must be specified exactly oncce" ) ; } // Create list of Query instances List < Query > queries = parseQueriesJson ( queriesStrings [ 0 ] ) ; // Perform queries JSONObject result = new JSONObject ( ) ; { Map < String , DbTableAccess > tableAccessCache = new HashMap < String , DbTableAccess > ( ) ; for ( Query query : queries ) { String tableName = query . getTableName ( ) ; List < RecordSelector > whereMap = query . getWhereExpressions ( ) ; List < FieldSelector > fieldSelectors = query . getFieldSelectors ( ) ; List < FieldSelector > groupByColumnNames = query . getGroupByColumnNames ( ) ; List < OrderSpecifier > orderSpecifiers = query . getOrderBySpecifiers ( ) ; Integer limit = query . getLimit ( ) ; Integer offset = query . getOffset ( ) ; DbTableAccess tableAccess = tableAccessCache . get ( tableName ) ; if ( null == tableAccess ) { tableAccess = DbTableAccess . getAccess ( dbSecurity , tableName , new DbUserAdaptor ( user ) ) ; tableAccessCache . put ( tableName , tableAccess ) ; } try { JSONArray queriedObjects = tableAccess . query ( whereMap , fieldSelectors , groupByColumnNames , orderSpecifiers , limit , offset ) ; result . put ( query . getQueryKey ( ) , queriedObjects ) ; } catch ( Exception e ) { result . put ( query . getQueryKey ( ) , errorToJson ( e ) ) ; } } } sendJsonResponse ( response , result ) ; }
Perform multiple SQL queries via dbSec .
436
9
14,467
private List < FieldSelector > getFieldSelectorsFromRequest ( HttpServletRequest request ) throws Exception { String [ ] fieldSelectorStrings = request . getParameterValues ( "select" ) ; if ( null == fieldSelectorStrings ) { return null ; } if ( 0 == fieldSelectorStrings . length ) { return null ; } List < FieldSelector > result = new Vector < FieldSelector > ( ) ; for ( String fieldSelectorString : fieldSelectorStrings ) { FieldSelector fieldSelector = parseFieldSelectorString ( fieldSelectorString ) ; result . add ( fieldSelector ) ; } return result ; }
Return a list of column names to be included in a select clause .
142
14
14,468
private List < OrderSpecifier > getOrderByList ( HttpServletRequest request ) throws Exception { String [ ] orderByStrings = request . getParameterValues ( "orderBy" ) ; if ( null == orderByStrings ) { return null ; } if ( 0 == orderByStrings . length ) { return null ; } List < OrderSpecifier > result = new Vector < OrderSpecifier > ( ) ; for ( String orderByString : orderByStrings ) { OrderSpecifier orderSpecifier = parseOrderSpecifier ( orderByString ) ; result . add ( orderSpecifier ) ; } return result ; }
Return a list of order specifiers found in request
134
10
14,469
public TableSchema getTableSchemaFromName ( String tableName , DbUser user ) throws Exception { List < String > tableNames = new Vector < String > ( ) ; tableNames . add ( tableName ) ; Map < String , TableSchemaImpl > nameToTableMap = getTableDataFromGroups ( user , tableNames ) ; if ( false == nameToTableMap . containsKey ( tableName ) ) { throw new Exception ( "A table named '" + tableName + "' does not exist or is not available" ) ; } return nameToTableMap . get ( tableName ) ; }
Computes from the database the access to a table for a given user . In this call a user is represented by the set of groups it belongs to .
130
31
14,470
public List < TableSchema > getAvailableTablesFromGroups ( DbUser user ) throws Exception { Map < String , TableSchemaImpl > nameToTableMap = getTableDataFromGroups ( user , null ) ; List < TableSchema > result = new Vector < TableSchema > ( ) ; result . addAll ( nameToTableMap . values ( ) ) ; return result ; }
Computes from the database the access to all tables for a given user . In this call a user is represented by the set of groups it belongs to .
86
31
14,471
static public List < String > breakUpCommand ( String command ) throws Exception { try { List < String > commandTokens = new Vector < String > ( ) ; StringBuilder currentToken = null ; boolean isTokenQuoted = false ; StringReader sr = new StringReader ( command ) ; int b = sr . read ( ) ; while ( b >= 0 ) { char c = ( char ) b ; if ( null == currentToken ) { // At token is not in progress // Skipping spaces if ( ' ' == c || ' ' == c ) { } else if ( ' ' == c ) { // Starting a quoted token currentToken = new StringBuilder ( ) ; //currentToken.append(c); isTokenQuoted = true ; } else { // Starting a non-quoted token currentToken = new StringBuilder ( ) ; currentToken . append ( c ) ; isTokenQuoted = false ; } } else if ( isTokenQuoted ) { // A quoted token is in progress. It ends with a quote if ( ' ' == c ) { //currentToken.append(c); String token = currentToken . toString ( ) ; currentToken = null ; commandTokens . add ( token ) ; } else { // Continuation currentToken . append ( c ) ; } } else { // A non-quoted token is in progress. It ends with a space if ( ' ' == c || ' ' == c ) { String token = currentToken . toString ( ) ; currentToken = null ; commandTokens . add ( token ) ; } else { // Continuation currentToken . append ( c ) ; } } b = sr . read ( ) ; } if ( null != currentToken ) { String token = currentToken . toString ( ) ; commandTokens . add ( token ) ; } return commandTokens ; } catch ( IOException e ) { throw new Exception ( "Error while breaking up command into tokens: " + command , e ) ; } }
Takes a single line command as a string and breaks it up in tokens acceptable for the java . lang . ProcessBuilder . ProcessBuilder
411
27
14,472
private UserAndPassword executeStatementToUser ( PreparedStatement preparedStmt ) throws Exception { if ( preparedStmt . execute ( ) ) { // There's a ResultSet to be had ResultSet rs = preparedStmt . getResultSet ( ) ; ResultSetMetaData rsmd = rs . getMetaData ( ) ; int numColumns = rsmd . getColumnCount ( ) ; if ( numColumns != 5 ) { throw new Exception ( "Unexpected number of columns returned" ) ; } if ( false == rs . next ( ) ) { throw new Exception ( "Result set empty" ) ; } int userId = JdbcUtils . extractIntResult ( rs , rsmd , 1 ) ; String email = JdbcUtils . extractStringResult ( rs , rsmd , 2 ) ; String displayName = JdbcUtils . extractStringResult ( rs , rsmd , 3 ) ; String dbPassword = JdbcUtils . extractStringResult ( rs , rsmd , 4 ) ; int groupId = JdbcUtils . extractIntResult ( rs , rsmd , 5 ) ; if ( true == rs . next ( ) ) { throw new Exception ( "Result set had more than one result" ) ; } // Return user UserAndPassword user = new UserAndPassword ( ) ; user . setId ( userId ) ; user . setUser ( email ) ; user . setDisplayName ( displayName ) ; user . setPassword ( dbPassword ) ; if ( 0 == groupId ) { user . setAnonymous ( true ) ; } else if ( 1 == groupId ) { user . setAdmin ( true ) ; } Vector < Integer > groups = new Vector < Integer > ( ) ; groups . add ( new Integer ( groupId ) ) ; user . setGroups ( groups ) ; return user ; } else { // indicates an update count or no results - this must be no results throw new Exception ( "Query returned no results" ) ; } }
This method executes a prepared SQL statement against the user table and returns a User .
427
16
14,473
private void writeNumber ( PrintWriter pw , NumberFormat numFormat , Number num ) { if ( num . doubleValue ( ) == Math . round ( num . doubleValue ( ) ) ) { // Integer if ( null != numFormat ) { pw . print ( numFormat . format ( num . intValue ( ) ) ) ; } else { pw . print ( num . intValue ( ) ) ; } } else { if ( null != numFormat ) { pw . print ( numFormat . format ( num ) ) ; } else { pw . print ( num ) ; } } }
Writes a number to the print writer . If the number is an integer do not write the decimal points .
126
22
14,474
static public Date parseGpsTimestamp ( String gpsTimestamp ) throws Exception { try { Matcher matcherTime = patternTime . matcher ( gpsTimestamp ) ; if ( matcherTime . matches ( ) ) { int year = Integer . parseInt ( matcherTime . group ( 1 ) ) ; int month = Integer . parseInt ( matcherTime . group ( 2 ) ) ; int day = Integer . parseInt ( matcherTime . group ( 3 ) ) ; int hour = Integer . parseInt ( matcherTime . group ( 4 ) ) ; int min = Integer . parseInt ( matcherTime . group ( 5 ) ) ; int sec = Integer . parseInt ( matcherTime . group ( 6 ) ) ; GregorianCalendar cal = new GregorianCalendar ( year , month - 1 , day , hour , min , sec ) ; cal . setTimeZone ( new SimpleTimeZone ( SimpleTimeZone . UTC_TIME , "UTC" ) ) ; Date date = cal . getTime ( ) ; return date ; } throw new Exception ( "Unrecognizd GPS timestamp: " + gpsTimestamp ) ; } catch ( Exception e ) { throw new Exception ( "Error parsing GPS timestamp" , e ) ; } }
Parses a GPS timestamp with a 1 second precision .
266
12
14,475
static public String safeSqlQueryStringValue ( String in ) throws Exception { if ( null == in ) { return "NULL" ; } if ( in . indexOf ( ' ' ) >= 0 ) { throw new Exception ( "Null character found in string value" ) ; } // All quotes should be escaped in = in . replace ( "'" , "''" ) ; // Add quotes again return "'" + in + "'" ; }
This method converts a string into a new one that is safe for a SQL query . It deals with strings that are expected to be string values .
92
29
14,476
static public String safeSqlQueryIntegerValue ( String in ) throws Exception { int intValue = Integer . parseInt ( in ) ; return "" + intValue ; }
This method converts a string into a new one that is safe for a SQL query . It deals with strings that are expected to be integer values .
35
29
14,477
static public String safeSqlQueryIdentifier ( String in ) throws Exception { if ( null == in ) { throw new Exception ( "Null string passed as identifier" ) ; } if ( in . indexOf ( ' ' ) >= 0 ) { throw new Exception ( "Null character found in identifier" ) ; } // All quotes should be escaped in = in . replace ( "\"" , "\"\"" ) ; in = "\"" + in + "\"" ; return in ; }
This method converts a string into a new one that is safe for a SQL query . It deals with strings that are supposed to be identifiers .
103
28
14,478
static public String extractStringResult ( ResultSet rs , ResultSetMetaData rsmd , int index ) throws Exception { int count = rsmd . getColumnCount ( ) ; if ( index > count || index < 1 ) { throw new Exception ( "Invalid index" ) ; } int type = rsmd . getColumnType ( index ) ; switch ( type ) { case java . sql . Types . VARCHAR : case java . sql . Types . CHAR : return rs . getString ( index ) ; } throw new Exception ( "Column type (" + type + ") invalid for a string at index: " + index ) ; }
This method returns a String result at a given index .
135
11
14,479
static public int extractIntResult ( ResultSet rs , ResultSetMetaData rsmd , int index ) throws Exception { int count = rsmd . getColumnCount ( ) ; if ( index > count || index < 1 ) { throw new Exception ( "Invalid index" ) ; } int type = rsmd . getColumnType ( index ) ; switch ( type ) { case java . sql . Types . INTEGER : case java . sql . Types . SMALLINT : return rs . getInt ( index ) ; } throw new Exception ( "Column type (" + type + ") invalid for a string at index: " + index ) ; }
This method returns an int result at a given index .
137
11
14,480
static public void addKnownString ( String mimeType , String knownString ) { Map < String , String > map = getKnownStrings ( ) ; if ( null != mimeType && null != knownString ) { map . put ( knownString . trim ( ) , mimeType . trim ( ) ) ; } }
Adds a relation between a known string for File and a mime type .
68
15
14,481
private static IIOMetadataNode getOrCreateChildNode ( IIOMetadataNode parentNode , String name ) { NodeList nodeList = parentNode . getElementsByTagName ( name ) ; if ( nodeList . getLength ( ) > 0 ) { return ( IIOMetadataNode ) nodeList . item ( 0 ) ; } IIOMetadataNode childNode = new IIOMetadataNode ( name ) ; parentNode . appendChild ( childNode ) ; return childNode ; }
Gets the named child node or creates and attaches it .
106
12
14,482
private static void setDPI ( IIOMetadata metadata , int dpi , String formatName ) throws IIOInvalidTreeException { IIOMetadataNode root = ( IIOMetadataNode ) metadata . getAsTree ( MetaUtil . STANDARD_METADATA_FORMAT ) ; IIOMetadataNode dimension = getOrCreateChildNode ( root , "Dimension" ) ; // PNG writer doesn't conform to the spec which is // "The width of a pixel, in millimeters" // but instead counts the pixels per millimeter float res = "PNG" . equals ( formatName . toUpperCase ( ) ) ? dpi / 25.4f : 25.4f / dpi ; IIOMetadataNode child ; child = getOrCreateChildNode ( dimension , "HorizontalPixelSize" ) ; child . setAttribute ( "value" , Double . toString ( res ) ) ; child = getOrCreateChildNode ( dimension , "VerticalPixelSize" ) ; child . setAttribute ( "value" , Double . toString ( res ) ) ; metadata . mergeTree ( MetaUtil . STANDARD_METADATA_FORMAT , root ) ; }
sets the DPI metadata
255
5
14,483
static void updateMetadata ( IIOMetadata metadata , int dpi ) throws IIOInvalidTreeException { MetaUtil . debugLogMetadata ( metadata , MetaUtil . JPEG_NATIVE_FORMAT ) ; // https://svn.apache.org/viewvc/xmlgraphics/commons/trunk/src/java/org/apache/xmlgraphics/image/writer/imageio/ImageIOJPEGImageWriter.java // http://docs.oracle.com/javase/6/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html Element root = ( Element ) metadata . getAsTree ( MetaUtil . JPEG_NATIVE_FORMAT ) ; NodeList jvarNodeList = root . getElementsByTagName ( "JPEGvariety" ) ; Element jvarChild ; if ( jvarNodeList . getLength ( ) == 0 ) { jvarChild = new IIOMetadataNode ( "JPEGvariety" ) ; root . appendChild ( jvarChild ) ; } else { jvarChild = ( Element ) jvarNodeList . item ( 0 ) ; } NodeList jfifNodeList = jvarChild . getElementsByTagName ( "app0JFIF" ) ; Element jfifChild ; if ( jfifNodeList . getLength ( ) == 0 ) { jfifChild = new IIOMetadataNode ( "app0JFIF" ) ; jvarChild . appendChild ( jfifChild ) ; } else { jfifChild = ( Element ) jfifNodeList . item ( 0 ) ; } if ( jfifChild . getAttribute ( "majorVersion" ) . isEmpty ( ) ) { jfifChild . setAttribute ( "majorVersion" , "1" ) ; } if ( jfifChild . getAttribute ( "minorVersion" ) . isEmpty ( ) ) { jfifChild . setAttribute ( "minorVersion" , "2" ) ; } jfifChild . setAttribute ( "resUnits" , "1" ) ; // inch jfifChild . setAttribute ( "Xdensity" , Integer . toString ( dpi ) ) ; jfifChild . setAttribute ( "Ydensity" , Integer . toString ( dpi ) ) ; if ( jfifChild . getAttribute ( "thumbWidth" ) . isEmpty ( ) ) { jfifChild . setAttribute ( "thumbWidth" , "0" ) ; } if ( jfifChild . getAttribute ( "thumbHeight" ) . isEmpty ( ) ) { jfifChild . setAttribute ( "thumbHeight" , "0" ) ; } // mergeTree doesn't work for ARGB metadata . setFromTree ( MetaUtil . JPEG_NATIVE_FORMAT , root ) ; }
Set dpi in a JPEG file
612
7
14,484
public String nextToken ( ) throws JSONException { char c ; char q ; StringBuilder sb = new StringBuilder ( ) ; do { c = next ( ) ; } while ( Character . isWhitespace ( c ) ) ; if ( c == ' ' || c == ' ' ) { q = c ; for ( ; ; ) { c = next ( ) ; if ( c < ' ' ) { throw syntaxError ( "Unterminated string." ) ; } if ( c == q ) { return sb . toString ( ) ; } sb . append ( c ) ; } } for ( ; ; ) { if ( c == 0 || Character . isWhitespace ( c ) ) { return sb . toString ( ) ; } sb . append ( c ) ; c = next ( ) ; } }
Get the next token or string . This is used in parsing HTTP headers .
175
15
14,485
public static JSONObject toJSONObject ( java . util . Properties properties ) throws JSONException { // can't use the new constructor for Android support // JSONObject jo = new JSONObject(properties == null ? 0 : properties.size()); JSONObject jo = new JSONObject ( ) ; if ( properties != null && ! properties . isEmpty ( ) ) { Enumeration < ? > enumProperties = properties . propertyNames ( ) ; while ( enumProperties . hasMoreElements ( ) ) { String name = ( String ) enumProperties . nextElement ( ) ; jo . put ( name , properties . getProperty ( name ) ) ; } } return jo ; }
Converts a property file object into a JSONObject . The property file object is a table of name value pairs .
140
23
14,486
private void performSubmittedInlineWork ( Work work ) throws Exception { String attachmentName = work . getAttachmentName ( ) ; FileConversionContext conversionContext = new FileConversionContextImpl ( work , documentDbDesign , mediaDir ) ; DocumentDescriptor docDescriptor = conversionContext . getDocument ( ) ; AttachmentDescriptor attDescription = null ; if ( docDescriptor . isAttachmentDescriptionAvailable ( attachmentName ) ) { attDescription = docDescriptor . getAttachmentDescription ( attachmentName ) ; } if ( null == attDescription ) { logger . info ( "Submission can not be found" ) ; } else if ( false == UploadConstants . UPLOAD_STATUS_SUBMITTED_INLINE . equals ( attDescription . getStatus ( ) ) ) { logger . info ( "File not in submit inline state" ) ; } else { // Verify that a file is attached to the document if ( false == attDescription . isFilePresent ( ) ) { // Invalid state throw new Exception ( "Invalid state. A file must be present for submitted_inline" ) ; } // Download file File outputFile = File . createTempFile ( "inline" , "" , mediaDir ) ; conversionContext . downloadFile ( attachmentName , outputFile ) ; // Create an original structure to point to the file in the // media dir. This way, when we go to "submitted" state, we will // be ready. OriginalFileDescriptor originalDescription = attDescription . getOriginalFileDescription ( ) ; originalDescription . setMediaFileName ( outputFile . getName ( ) ) ; // Delete current attachment attDescription . removeFile ( ) ; // Update status attDescription . setStatus ( UploadConstants . UPLOAD_STATUS_SUBMITTED ) ; conversionContext . saveDocument ( ) ; } }
This function is called when a media file was added on a different node such as a mobile device . In that case the media is marked as submitted_inline since the media is already attached to the document but as not yet gone through the process that the robot implements .
395
53
14,487
static void debugLogMetadata ( IIOMetadata metadata , String format ) { if ( ! logger . isDebugEnabled ( ) ) { return ; } // see http://docs.oracle.com/javase/7/docs/api/javax/imageio/ // metadata/doc-files/standard_metadata.html IIOMetadataNode root = ( IIOMetadataNode ) metadata . getAsTree ( format ) ; try { StringWriter xmlStringWriter = new StringWriter ( ) ; StreamResult streamResult = new StreamResult ( xmlStringWriter ) ; Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; // see http://stackoverflow.com/a/1264872/535646 transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . setOutputProperty ( "{http://xml.apache.org/xslt}indent-amount" , "2" ) ; DOMSource domSource = new DOMSource ( root ) ; transformer . transform ( domSource , streamResult ) ; logger . debug ( "\n" + xmlStringWriter ) ; } catch ( Exception e ) { logger . error ( "Error while reporting meta-data" , e ) ; } }
logs metadata as an XML tree if debug is enabled
267
11
14,488
static public FSEntry getPositionedBuffer ( String path , byte [ ] content ) throws Exception { List < String > pathFrags = FSEntrySupport . interpretPath ( path ) ; // Start at leaf and work our way back int index = pathFrags . size ( ) - 1 ; FSEntry root = new FSEntryBuffer ( pathFrags . get ( index ) , content ) ; -- index ; while ( index >= 0 ) { FSEntryVirtualDirectory parent = new FSEntryVirtualDirectory ( pathFrags . get ( index ) ) ; parent . addChildEntry ( root ) ; root = parent ; -- index ; } return root ; }
Create a virtual tree hierarchy with a buffer supporting the leaf .
146
12
14,489
static public Result insertElements ( Tree tree , List < TreeElement > elements , NowReference now ) throws Exception { ResultImpl result = new ResultImpl ( tree ) ; TreeNodeRegular regularRootNode = tree . getRegularRootNode ( ) ; TreeNodeOngoing ongoingRootNode = tree . getOngoingRootNode ( ) ; for ( TreeElement element : elements ) { TimeInterval elementInterval = element . getInterval ( ) ; if ( elementInterval . isOngoing ( ) ) { ongoingRootNode . insertElement ( element , result , tree . getOperations ( ) , now ) ; } else { regularRootNode . insertElement ( element , result , tree . getOperations ( ) , now ) ; } } return result ; }
Modifies a cluster tree as a result of adding a new elements in the tree .
162
17
14,490
public NunaliitGeometry getOriginalGometry ( ) throws Exception { NunaliitGeometryImpl result = null ; JSONObject jsonDoc = getJSONObject ( ) ; JSONObject nunalitt_geom = jsonDoc . optJSONObject ( CouchNunaliitConstants . DOC_KEY_GEOMETRY ) ; if ( null != nunalitt_geom ) { // By default, the wkt is the geometry String wkt = nunalitt_geom . optString ( "wkt" , null ) ; // Check if a simplified structure is specified JSONObject simplified = nunalitt_geom . optJSONObject ( "simplified" ) ; if ( null == simplified ) { logger . trace ( "Simplified structure is not available" ) ; } else { logger . trace ( "Accessing simplified structure" ) ; String originalAttachmentName = simplified . optString ( "original" , null ) ; if ( null == originalAttachmentName ) { throw new Exception ( "Original attachment name not found in simplified structure" ) ; } else { // The original geometry is in the specified attachment Attachment attachment = getAttachmentByName ( originalAttachmentName ) ; if ( null == attachment ) { throw new Exception ( "Named original attachment not found: " + getId ( ) + "/" + originalAttachmentName ) ; } else { InputStream is = null ; InputStreamReader isr = null ; try { is = attachment . getInputStream ( ) ; isr = new InputStreamReader ( is , "UTF-8" ) ; StringWriter sw = new StringWriter ( ) ; StreamUtils . copyStream ( isr , sw ) ; sw . flush ( ) ; wkt = sw . toString ( ) ; isr . close ( ) ; isr = null ; is . close ( ) ; is = null ; } catch ( Exception e ) { logger . error ( "Error obtaining attachment " + getId ( ) + "/" + originalAttachmentName , e ) ; if ( null != isr ) { try { isr . close ( ) ; isr = null ; } catch ( Exception e1 ) { // ignore } } if ( null != is ) { try { is . close ( ) ; is = null ; } catch ( Exception e1 ) { // ignore } } throw new Exception ( "Error obtaining attachment " + getId ( ) + "/" + originalAttachmentName , e ) ; } } } } if ( null != wkt ) { result = new NunaliitGeometryImpl ( ) ; result . setWKT ( wkt ) ; } } return result ; }
Return the original geometry associated with the document . This is the geometry that was first submitted with the document . If the document does not contain a geometry then null is returned .
559
34
14,491
static public String getDocumentIdentifierFromSubmission ( JSONObject submissionDoc ) throws Exception { JSONObject submissionInfo = submissionDoc . getJSONObject ( "nunaliit_submission" ) ; JSONObject originalReserved = submissionInfo . optJSONObject ( "original_reserved" ) ; JSONObject submittedReserved = submissionInfo . optJSONObject ( "submitted_reserved" ) ; // Get document id and revision String docId = null ; if ( null != originalReserved ) { docId = originalReserved . optString ( "id" ) ; } if ( null == docId && null != submittedReserved ) { docId = submittedReserved . optString ( "id" ) ; } return docId ; }
Computes the target document identifier for this submission . Returns null if it can not be found .
157
19
14,492
static public JSONObject getSubmittedDocumentFromSubmission ( JSONObject submissionDoc ) throws Exception { JSONObject submissionInfo = submissionDoc . getJSONObject ( "nunaliit_submission" ) ; JSONObject doc = submissionInfo . getJSONObject ( "submitted_doc" ) ; JSONObject reserved = submissionInfo . optJSONObject ( "submitted_reserved" ) ; return recreateDocumentFromDocAndReserved ( doc , reserved ) ; }
Re - creates the document submitted by the client from the submission document .
97
14
14,493
static public JSONObject getApprovedDocumentFromSubmission ( JSONObject submissionDoc ) throws Exception { JSONObject submissionInfo = submissionDoc . getJSONObject ( "nunaliit_submission" ) ; // Check if an approved version of the document is available JSONObject doc = submissionInfo . optJSONObject ( "approved_doc" ) ; if ( null != doc ) { JSONObject reserved = submissionInfo . optJSONObject ( "approved_reserved" ) ; return recreateDocumentFromDocAndReserved ( doc , reserved ) ; } else { // Use submission doc = submissionInfo . getJSONObject ( "submitted_doc" ) ; JSONObject reserved = submissionInfo . optJSONObject ( "submitted_reserved" ) ; return recreateDocumentFromDocAndReserved ( doc , reserved ) ; } }
Re - creates the approved document submitted by the client from the submission document .
172
15
14,494
static public JSONObject recreateDocumentFromDocAndReserved ( JSONObject doc , JSONObject reserved ) throws Exception { JSONObject result = JSONSupport . copyObject ( doc ) ; // Re-insert attributes that start with '_' if ( null != reserved ) { Iterator < ? > it = reserved . keys ( ) ; while ( it . hasNext ( ) ) { Object keyObj = it . next ( ) ; if ( keyObj instanceof String ) { String key = ( String ) keyObj ; Object value = reserved . opt ( key ) ; result . put ( "_" + key , value ) ; } } } return result ; }
Re - creates a document given the document and the reserved keys .
134
13
14,495
private void removeUndesiredFiles ( JSONObject doc , File dir ) throws Exception { Set < String > keysKept = new HashSet < String > ( ) ; // Loop through each child of directory File [ ] children = dir . listFiles ( ) ; for ( File child : children ) { String name = child . getName ( ) ; String extension = "" ; Matcher matcherNameExtension = patternNameExtension . matcher ( name ) ; if ( matcherNameExtension . matches ( ) ) { name = matcherNameExtension . group ( 1 ) ; extension = matcherNameExtension . group ( 2 ) ; } // Get child object Object childElement = doc . opt ( name ) ; // Verify if we should keep this file boolean keepFile = false ; if ( null == childElement ) { // No matching element } else if ( "_attachments" . equals ( name ) ) { // Always remove _attachments } else if ( keysKept . contains ( name ) ) { // Remove subsequent files that match same key } else if ( child . isDirectory ( ) ) { // If extension is array, then check if we have an array of that name if ( FILE_EXT_ARRAY . equals ( extension ) ) { // This must be an array if ( childElement instanceof JSONArray ) { // That's OK keepFile = true ; // Continue checking with files in directory JSONArray childArr = ( JSONArray ) childElement ; removeUndesiredFiles ( childArr , child ) ; } } else { // This must be an object if ( childElement instanceof JSONObject ) { // That's OK keepFile = true ; // Continue checking with files in directory JSONObject childObj = ( JSONObject ) childElement ; removeUndesiredFiles ( childObj , child ) ; } } } else { // Child is a file. if ( FILE_EXT_JSON . equals ( extension ) ) { // Anything can be saved in a .json file keepFile = true ; } else if ( childElement instanceof String ) { // Anything else must match a string keepFile = true ; } } // Remove file if it no longer fits the object if ( keepFile ) { keysKept . add ( name ) ; } else { if ( child . isDirectory ( ) ) { Files . emptyDirectory ( child ) ; } child . delete ( ) ; } } }
This function scans the directory for files that are no longer needed to represent the document given in arguments . The detected files are deleted from disk .
502
28
14,496
synchronized static private byte [ ] getSecret ( ) throws Exception { if ( null == secret ) { Date now = new Date ( ) ; long nowValue = now . getTime ( ) ; byte [ ] nowBytes = new byte [ 8 ] ; nowBytes [ 0 ] = ( byte ) ( ( nowValue >> 0 ) & 0xff ) ; nowBytes [ 1 ] = ( byte ) ( ( nowValue >> 8 ) & 0xff ) ; nowBytes [ 2 ] = ( byte ) ( ( nowValue >> 16 ) & 0xff ) ; nowBytes [ 3 ] = ( byte ) ( ( nowValue >> 24 ) & 0xff ) ; nowBytes [ 4 ] = ( byte ) ( ( nowValue >> 32 ) & 0xff ) ; nowBytes [ 5 ] = ( byte ) ( ( nowValue >> 40 ) & 0xff ) ; nowBytes [ 6 ] = ( byte ) ( ( nowValue >> 48 ) & 0xff ) ; nowBytes [ 7 ] = ( byte ) ( ( nowValue >> 56 ) & 0xff ) ; MessageDigest md = MessageDigest . getInstance ( "SHA" ) ; md . update ( nonce ) ; md . update ( nowBytes ) ; secret = md . digest ( ) ; } return secret ; }
protected for testing
267
3
14,497
static public void sendAuthRequiredError ( HttpServletResponse response , String realm ) throws IOException { response . setHeader ( "WWW-Authenticate" , "Basic realm=\"" + realm + "\"" ) ; response . setHeader ( "Cache-Control" , "no-cache,must-revalidate" ) ; response . setDateHeader ( "Expires" , ( new Date ( ) ) . getTime ( ) ) ; response . sendError ( HttpServletResponse . SC_UNAUTHORIZED , "Authorization Required" ) ; }
Sends a response to the client stating that authorization is required .
124
13
14,498
static public String userToCookieString ( boolean loggedIn , User user ) throws Exception { JSONObject cookieObj = new JSONObject ( ) ; cookieObj . put ( "logged" , loggedIn ) ; JSONObject userObj = user . toJSON ( ) ; cookieObj . put ( "user" , userObj ) ; StringWriter sw = new StringWriter ( ) ; cookieObj . write ( sw ) ; String cookieRaw = sw . toString ( ) ; String cookieStr = URLEncoder . encode ( cookieRaw , "UTF-8" ) ; cookieStr = cookieStr . replace ( "+" , "%20" ) ; return cookieStr ; }
Converts an instance of User to JSON object fit for a cookie
140
13
14,499
static public FSEntry findDescendant ( FSEntry root , String path ) throws Exception { if ( null == root ) { throw new Exception ( "root parameter should not be null" ) ; } List < String > pathFrags = interpretPath ( path ) ; // Iterate through path fragments, navigating through // the offered children FSEntry seekedEntry = root ; for ( String pathFrag : pathFrags ) { FSEntry nextEntry = null ; List < FSEntry > children = seekedEntry . getChildren ( ) ; for ( FSEntry child : children ) { if ( pathFrag . equals ( child . getName ( ) ) ) { // Found this one nextEntry = child ; break ; } } // If we have not found the next child, then it does not exist if ( null == nextEntry ) { return null ; } seekedEntry = nextEntry ; } return seekedEntry ; }
Traverses a directory structure designated by root and looks for a descendant with the provided path . If found the supporting instance of FSEntry for the path is returned . If not found null is returned .
200
42