idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
14,400 | public < E > E load ( Class < E > entityClass , DatastoreKey parentKey , long id ) { EntityMetadata entityMetadata = EntityIntrospector . introspect ( entityClass ) ; Key nativeKey ; if ( parentKey == null ) { nativeKey = entityManager . newNativeKeyFactory ( ) . setKind ( entityMetadata . getKind ( ) ) . newKey ( id ) ; } else { nativeKey = Key . newBuilder ( parentKey . nativeKey ( ) , entityMetadata . getKind ( ) , id ) . build ( ) ; } return fetch ( entityClass , nativeKey ) ; } | Loads and returns the entity with the given ID . The entity kind is determined from the supplied class . |
14,401 | public < E > E load ( Class < E > entityClass , DatastoreKey key ) { return fetch ( entityClass , key . nativeKey ( ) ) ; } | Retrieves and returns the entity with the given key . |
14,402 | public < E > List < E > loadByKey ( Class < E > entityClass , List < DatastoreKey > keys ) { Key [ ] nativeKeys = DatastoreUtils . toNativeKeys ( keys ) ; return fetch ( entityClass , nativeKeys ) ; } | Retrieves and returns the entities for the given keys . |
14,403 | private < E > E fetch ( Class < E > entityClass , Key nativeKey ) { try { Entity nativeEntity = nativeReader . get ( nativeKey ) ; E entity = Unmarshaller . unmarshal ( nativeEntity , entityClass ) ; entityManager . executeEntityListeners ( CallbackType . POST_LOAD , entity ) ; return entity ; } catch ( DatastoreException exp ) { throw new EntityManagerException ( exp ) ; } } | Fetches the entity given the native key . |
14,404 | private < E > List < E > fetch ( Class < E > entityClass , Key [ ] nativeKeys ) { try { List < Entity > nativeEntities = nativeReader . fetch ( nativeKeys ) ; List < E > entities = DatastoreUtils . toEntities ( entityClass , nativeEntities ) ; entityManager . executeEntityListeners ( CallbackType . POST_LOAD , entities ) ; return entities ; } catch ( DatastoreException exp ) { throw new EntityManagerException ( exp ) ; } } | Fetches a list of entities for the given native keys . |
14,405 | private Key [ ] longListToNativeKeys ( Class < ? > entityClass , List < Long > identifiers ) { if ( identifiers == null || identifiers . isEmpty ( ) ) { return new Key [ 0 ] ; } EntityMetadata entityMetadata = EntityIntrospector . introspect ( entityClass ) ; Key [ ] nativeKeys = new Key [ identifiers . size ( ) ] ; KeyFactory keyFactory = entityManager . newNativeKeyFactory ( ) ; keyFactory . setKind ( entityMetadata . getKind ( ) ) ; for ( int i = 0 ; i < identifiers . size ( ) ; i ++ ) { long id = identifiers . get ( i ) ; nativeKeys [ i ] = keyFactory . newKey ( id ) ; } return nativeKeys ; } | Converts the given list of identifiers into an array of native Key objects . |
14,406 | private IncompleteKey getIncompleteKey ( Object entity ) { EntityMetadata entityMetadata = EntityIntrospector . introspect ( entity . getClass ( ) ) ; String kind = entityMetadata . getKind ( ) ; ParentKeyMetadata parentKeyMetadata = entityMetadata . getParentKeyMetadata ( ) ; DatastoreKey parentKey = null ; IncompleteKey incompleteKey = null ; if ( parentKeyMetadata != null ) { parentKey = ( DatastoreKey ) IntrospectionUtils . getFieldValue ( parentKeyMetadata , entity ) ; } if ( parentKey != null ) { incompleteKey = IncompleteKey . newBuilder ( parentKey . nativeKey ( ) , kind ) . build ( ) ; } else { incompleteKey = IncompleteKey . newBuilder ( datastore . getOptions ( ) . getProjectId ( ) , kind ) . setNamespace ( getEffectiveNamespace ( ) ) . build ( ) ; } return incompleteKey ; } | Returns an IncompleteKey of the given entity . |
14,407 | public void executeEntityListeners ( CallbackType callbackType , Object entity ) { if ( entity == null ) { return ; } EntityListenersMetadata entityListenersMetadata = EntityIntrospector . getEntityListenersMetadata ( entity ) ; List < CallbackMetadata > callbacks = entityListenersMetadata . getCallbacks ( callbackType ) ; if ( ! entityListenersMetadata . isExcludeDefaultListeners ( ) ) { executeGlobalListeners ( callbackType , entity ) ; } if ( callbacks == null ) { return ; } for ( CallbackMetadata callback : callbacks ) { switch ( callback . getListenerType ( ) ) { case EXTERNAL : Object listener = ListenerFactory . getInstance ( ) . getListener ( callback . getListenerClass ( ) ) ; invokeCallbackMethod ( callback . getCallbackMethod ( ) , listener , entity ) ; break ; case INTERNAL : invokeCallbackMethod ( callback . getCallbackMethod ( ) , entity ) ; break ; default : String message = String . format ( "Unknown or unimplemented callback listener type: %s" , callback . getListenerType ( ) ) ; throw new EntityManagerException ( message ) ; } } } | Executes the entity listeners associated with the given entity . |
14,408 | public void executeEntityListeners ( CallbackType callbackType , List < ? > entities ) { for ( Object entity : entities ) { executeEntityListeners ( callbackType , entity ) ; } } | Executes the entity listeners associated with the given list of entities . |
14,409 | private void executeGlobalListeners ( CallbackType callbackType , Object entity ) { if ( globalCallbacks == null ) { return ; } List < CallbackMetadata > callbacks = globalCallbacks . get ( callbackType ) ; if ( callbacks == null ) { return ; } for ( CallbackMetadata callback : callbacks ) { Object listener = ListenerFactory . getInstance ( ) . getListener ( callback . getListenerClass ( ) ) ; invokeCallbackMethod ( callback . getCallbackMethod ( ) , listener , entity ) ; } } | Executes the global listeners for the given event type for the given entity . |
14,410 | private static void invokeCallbackMethod ( Method callbackMethod , Object listener , Object entity ) { try { callbackMethod . invoke ( listener , entity ) ; } catch ( Exception exp ) { String message = String . format ( "Failed to execute callback method %s of class %s" , callbackMethod . getName ( ) , callbackMethod . getDeclaringClass ( ) . getName ( ) ) ; throw new EntityManagerException ( message , exp ) ; } } | Invokes the given callback method on the given target object . |
14,411 | @ SuppressWarnings ( "unchecked" ) private < T extends Indexer > T createIndexer ( Class < T > indexerClass ) { synchronized ( indexerClass ) { Indexer indexer = cache . get ( indexerClass ) ; if ( indexer == null ) { indexer = ( Indexer ) IntrospectionUtils . instantiateObject ( indexerClass ) ; cache . put ( indexerClass , indexer ) ; } return ( T ) indexer ; } } | Creates the Indexer of the given class . |
14,412 | private Indexer getDefaultIndexer ( Field field ) { Type type = field . getGenericType ( ) ; if ( type instanceof Class && type . equals ( String . class ) ) { return getIndexer ( LowerCaseStringIndexer . class ) ; } else if ( type instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; Class < ? > rawType = ( Class < ? > ) parameterizedType . getRawType ( ) ; if ( List . class . isAssignableFrom ( rawType ) || Set . class . isAssignableFrom ( rawType ) ) { Class < ? > [ ] collectionType = IntrospectionUtils . resolveCollectionType ( type ) ; if ( String . class . equals ( collectionType [ 1 ] ) ) { return getIndexer ( LowerCaseStringListIndexer . class ) ; } } } String message = String . format ( "No default indexer found for field %s in class %s" , field . getName ( ) , field . getDeclaringClass ( ) . getName ( ) ) ; throw new NoSuitableIndexerException ( message ) ; } | Returns the default indexer for the given field . |
14,413 | private void copyRequestHeaders ( HttpServletRequest servletRequest , HttpRequest proxyRequest ) throws URISyntaxException { Enumeration < ? > enumerationOfHeaderNames = servletRequest . getHeaderNames ( ) ; while ( enumerationOfHeaderNames . hasMoreElements ( ) ) { String headerName = ( String ) enumerationOfHeaderNames . nextElement ( ) ; if ( ! headerName . equalsIgnoreCase ( CONTENT_LENGTH ) && ! hopByHopHeaders . containsHeader ( headerName ) ) { Enumeration < ? > headers = servletRequest . getHeaders ( headerName ) ; while ( headers . hasMoreElements ( ) ) { String headerValue = ( String ) headers . nextElement ( ) ; if ( headerName . equalsIgnoreCase ( HOST ) ) { HttpHost host = URIUtils . extractHost ( new URI ( prerenderConfig . getPrerenderServiceUrl ( ) ) ) ; headerValue = host . getHostName ( ) ; if ( host . getPort ( ) != - 1 ) { headerValue += ":" + host . getPort ( ) ; } } proxyRequest . addHeader ( headerName , headerValue ) ; } } } } | Copy request headers from the servlet client to the proxy request . |
14,414 | private void copyResponseHeaders ( HttpResponse proxyResponse , final HttpServletResponse servletResponse ) { servletResponse . setCharacterEncoding ( getContentCharSet ( proxyResponse . getEntity ( ) ) ) ; from ( Arrays . asList ( proxyResponse . getAllHeaders ( ) ) ) . filter ( new Predicate < Header > ( ) { public boolean apply ( Header header ) { return ! hopByHopHeaders . containsHeader ( header . getName ( ) ) ; } } ) . transform ( new Function < Header , Boolean > ( ) { public Boolean apply ( Header header ) { servletResponse . addHeader ( header . getName ( ) , header . getValue ( ) ) ; return true ; } } ) . toList ( ) ; } | Copy proxied response headers back to the servlet client . |
14,415 | private String getContentCharSet ( final HttpEntity entity ) throws ParseException { if ( entity == null ) { return null ; } String charset = null ; if ( entity . getContentType ( ) != null ) { HeaderElement values [ ] = entity . getContentType ( ) . getElements ( ) ; if ( values . length > 0 ) { NameValuePair param = values [ 0 ] . getParameterByName ( "charset" ) ; if ( param != null ) { charset = param . getValue ( ) ; } } } return charset ; } | Get the charset used to encode the http entity . |
14,416 | @ SuppressWarnings ( "unchecked" ) public T getDefaultObject ( ) { if ( defaultValue instanceof IModel ) { return ( ( IModel < T > ) defaultValue ) . getObject ( ) ; } else { return ( T ) defaultValue ; } } | Returns default value |
14,417 | public JsonResponse getEmail ( String email ) throws IOException { Email emailObj = new Email ( ) ; emailObj . setEmail ( email ) ; return apiGet ( emailObj ) ; } | Get information about one of your users . |
14,418 | public JsonResponse getSend ( String sendId ) throws IOException { Map < String , Object > data = new HashMap < String , Object > ( ) ; data . put ( Send . PARAM_SEND_ID , sendId ) ; return apiGet ( ApiAction . send , data ) ; } | Get the status of a transational send |
14,419 | public JsonResponse cancelSend ( String sendId ) throws IOException { Map < String , Object > data = new HashMap < String , Object > ( ) ; data . put ( Send . PARAM_SEND_ID , sendId ) ; return apiDelete ( ApiAction . send , data ) ; } | Cancel a send that was scheduled for a future time . |
14,420 | public JsonResponse getBlast ( Integer blastId ) throws IOException { Blast blast = new Blast ( ) ; blast . setBlastId ( blastId ) ; return apiGet ( blast ) ; } | get information about a blast |
14,421 | public JsonResponse scheduleBlastFromTemplate ( String template , String list , Date scheduleTime , Blast blast ) throws IOException { blast . setCopyTemplate ( template ) ; blast . setList ( list ) ; blast . setScheduleTime ( scheduleTime ) ; return apiPost ( blast ) ; } | Schedule a mass mail from a template |
14,422 | public JsonResponse scheduleBlastFromBlast ( Integer blastId , Date scheduleTime , Blast blast ) throws IOException { blast . setCopyBlast ( blastId ) ; blast . setScheduleTime ( scheduleTime ) ; return apiPost ( blast ) ; } | Schedule a mass mail blast from previous blast |
14,423 | public JsonResponse updateBlast ( Integer blastId ) throws IOException { Blast blast = new Blast ( ) ; blast . setBlastId ( blastId ) ; return apiPost ( blast ) ; } | Update existing blast |
14,424 | public JsonResponse deleteBlast ( Integer blastId ) throws IOException { Blast blast = new Blast ( ) ; blast . setBlastId ( blastId ) ; return apiDelete ( blast ) ; } | Delete existing blast |
14,425 | 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 |
14,426 | 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 |
14,427 | 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 |
14,428 | 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 |
14,429 | 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 |
14,430 | public Map < String , Object > listStats ( ListStat stat ) throws IOException { return ( Map < String , Object > ) this . stats ( stat ) ; } | get list stats information |
14,431 | public Map < String , Object > blastStats ( BlastStat stat ) throws IOException { return ( Map < String , Object > ) this . stats ( stat ) ; } | get blast stats information |
14,432 | 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 |
14,433 | 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 |
14,434 | public OSchemaHelper linkedType ( OType linkedType ) { checkOProperty ( ) ; if ( ! Objects . equal ( linkedType , lastProperty . getLinkedType ( ) ) ) { lastProperty . setLinkedType ( linkedType ) ; } return this ; } | Set linked type to a current property |
14,435 | public OSchemaHelper field ( String field , Object value ) { checkODocument ( ) ; lastDocument . field ( field , value ) ; return this ; } | Sets a field value for a current document |
14,436 | public static < R > R sudo ( Function < ODatabaseDocument , R > func ) { return new DBClosure < R > ( ) { protected R execute ( ODatabaseDocument db ) { return func . apply ( db ) ; } } . execute ( ) ; } | Simplified function to execute under admin |
14,437 | public static void sudoConsumer ( Consumer < ODatabaseDocument > consumer ) { new DBClosure < Void > ( ) { protected Void execute ( ODatabaseDocument db ) { consumer . accept ( db ) ; return null ; } } . execute ( ) ; } | Simplified consumer to execute under admin |
14,438 | public static void sudoSave ( final ODocument ... docs ) { if ( docs == null || docs . length == 0 ) return ; new DBClosure < Boolean > ( ) { 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 |
14,439 | public static void sudoSave ( final ODocumentWrapper ... dws ) { if ( dws == null || dws . length == 0 ) return ; new DBClosure < Boolean > ( ) { 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 |
14,440 | 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 |
14,441 | 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 '\0' ; } 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 |
14,442 | 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 |
14,443 | 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 |
14,444 | 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 |
14,445 | public boolean isInProgress ( RequestCycle cycle ) { Boolean inProgress = cycle . getMetaData ( IN_PROGRESS_KEY ) ; return inProgress != null ? inProgress : false ; } | Is current transaction in progress? |
14,446 | 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 |
14,447 | 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 |
14,448 | public OQueryModel < K > setSort ( String sortableParameter , SortOrder order ) { setSortableParameter ( sortableParameter ) ; setAscending ( SortOrder . ASCENDING . equals ( order ) ) ; return this ; } | Set sorting configration |
14,449 | 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 |
14,450 | 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 |
14,451 | 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 |
14,452 | 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 |
14,453 | 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 |
14,454 | 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 |
14,455 | 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 |
14,456 | public JsonResponse apiGet ( ApiAction action , Map < String , Object > data ) throws IOException { return httpRequestJson ( action , HttpRequestMethod . GET , data ) ; } | HTTP GET Request with Map |
14,457 | public JsonResponse apiPost ( ApiAction action , Map < String , Object > data ) throws IOException { return httpRequestJson ( action , HttpRequestMethod . POST , data ) ; } | HTTP POST Request with Map |
14,458 | 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 |
14,459 | public JsonResponse apiDelete ( ApiAction action , Map < String , Object > data ) throws IOException { return httpRequestJson ( action , HttpRequestMethod . DELETE , data ) ; } | HTTP DELETE Request |
14,460 | static public int obtainNextIncrementInteger ( Connection connection , ColumnData autoIncrementIntegerColumn ) throws Exception { try { String sqlQuery = "SELECT nextval(?);" ; PreparedStatement pstmt = null ; { pstmt = connection . prepareStatement ( sqlQuery ) ; 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 . |
14,461 | static String unescapeEntity ( String e ) { if ( e == null || e . isEmpty ( ) ) { return "" ; } if ( e . charAt ( 0 ) == '#' ) { int cp ; if ( e . charAt ( 1 ) == 'x' ) { cp = Integer . parseInt ( e . substring ( 2 ) , 16 ) ; } else { cp = Integer . parseInt ( e . substring ( 1 ) ) ; } return new String ( new int [ ] { cp } , 0 , 1 ) ; } Character knownEntity = entity . get ( e ) ; if ( knownEntity == null ) { return '&' + e + ';' ; } return knownEntity . toString ( ) ; } | Unescapes an XML entity encoding ; |
14,462 | 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 ) { 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 . |
14,463 | 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" ) ; { Object obj = files . opt ( newAttachmentName ) ; if ( null != obj ) { throw new Exception ( "Can not rename attachment because of name collision" ) ; } } if ( null != _attachments ) { Object obj = _attachments . opt ( newAttachmentName ) ; if ( null != obj ) { throw new Exception ( "Can not rename attachment because of name collision" ) ; } } if ( null != _attachments ) { JSONObject att = _attachments . optJSONObject ( attName ) ; if ( null != att ) { throw new Exception ( "Can not rename attachment descriptor because file is already attached" ) ; } } String oldAttachmentName = attName ; JSONObject descriptor = files . getJSONObject ( oldAttachmentName ) ; files . remove ( oldAttachmentName ) ; files . put ( newAttachmentName , descriptor ) ; attName = newAttachmentName ; setStringAttribute ( UploadConstants . ATTACHMENT_NAME_KEY , newAttachmentName ) ; { 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 . |
14,464 | static public FSEntry getPositionedFile ( String path , File file ) throws Exception { List < String > pathFrags = FSEntrySupport . interpretPath ( path ) ; 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 . |
14,465 | 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 . |
14,466 | 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 |
14,467 | private JSONArray executeStatementToJson ( PreparedStatement stmt , List < SelectedColumn > selectFields ) throws Exception { if ( stmt . execute ( ) ) { 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 ) ; 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 { 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 { throw new Exception ( "Query returned no results" ) ; } } | This method executes a prepared SQL statement and returns a JSON array that contains the result . |
14,468 | 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 . |
14,469 | static public boolean hasDocumentBeenModified ( JSONObject targetDoc ) { JSONObject targetManifest = targetDoc . optJSONObject ( MANIFEST_KEY ) ; if ( null == targetManifest ) { return true ; } String targetDigest = targetManifest . optString ( "digest" ) ; if ( null == targetDigest ) { return true ; } DigestComputer digestComputer = null ; { String type = targetManifest . optString ( "type" ) ; if ( null == type ) { return true ; } else if ( DigestComputerSha1 . DIGEST_COMPUTER_TYPE . equals ( type ) ) { digestComputer = sha1DigestComputer ; } else { return true ; } } try { String computedDigest = digestComputer . computeDigestFromJsonObject ( targetDoc ) ; if ( false == computedDigest . equals ( targetDigest ) ) { return true ; } } catch ( Exception e ) { return true ; } 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 ) { return true ; } else if ( false == JSONSupport . containsKey ( attachmentManifest , "revpos" ) ) { return true ; } else { int revpos = attachmentManifest . optInt ( "revpos" , 0 ) ; Integer actualRevPos = getAttachmentPosition ( targetDoc , attachmentName ) ; if ( null == actualRevPos ) { return true ; } else if ( revpos != actualRevPos . intValue ( ) ) { return true ; } } } } } 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 ) ) { return true ; } } } } return false ; } | Analyzes a document and determines if the document has been modified since the time the manifest was computed . |
14,470 | static public Integer getAttachmentPosition ( JSONObject targetDoc , String attachmentName ) { JSONObject targetAttachments = targetDoc . optJSONObject ( "_attachments" ) ; if ( null == targetAttachments ) { return null ; } JSONObject targetAttachment = targetAttachments . optJSONObject ( attachmentName ) ; if ( null == targetAttachment ) { 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 . |
14,471 | public static void setCompressionType ( ImageWriteParam param , BufferedImage image ) { 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 . |
14,472 | static public FSEntry getPositionedResource ( String path , ClassLoader classLoader , String resourceName ) throws Exception { List < String > pathFrags = FSEntrySupport . interpretPath ( path ) ; 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 . |
14,473 | 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 . |
14,474 | 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 ) ) { 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 . |
14,475 | 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 ) { } if ( null == user ) { user = userRepository . getDefaultUser ( ) ; } acceptRequest ( response , loggedIn , user ) ; } | Adjusts the information cookie based on the authentication token |
14,476 | static public TreeRebalanceProcess . Result createTree ( List < ? extends TreeElement > elements ) throws Exception { Result results = new Result ( ) ; 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 ( ) ; 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 ( ) ) ; } } if ( null != clusterId ) { if ( clusterId >= results . nextClusterId ) { results . nextClusterId = clusterId + 1 ; } } 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 ( ) ) ; } } } } if ( null == fullRegularInterval ) { fullRegularInterval = new TimeInterval ( 0 , 1500000000000L ) ; } if ( null == fullOngoingInterval ) { fullOngoingInterval = new TimeInterval ( 0 , ( NowReference ) null ) ; } TreeNodeRegular regularRootNode = new TreeNodeRegular ( results . nextClusterId , fullRegularInterval ) ; results . nextClusterId ++ ; TreeNodeOngoing ongoingRootNode = new TreeNodeOngoing ( results . nextClusterId , fullOngoingInterval ) ; results . nextClusterId ++ ; results . regularRootNode = regularRootNode ; results . ongoingRootNode = ongoingRootNode ; 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 . |
14,477 | 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 ( ) ) ; con = DriverManager . getConnection ( info . getConnectionString ( ) , info . getUserName ( ) , info . getPassword ( ) ) ; DatabaseMetaData dbmd = con . getMetaData ( ) ; 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 . |
14,478 | 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 ) ) { 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 . |
14,479 | static public File computeAtlasDir ( String name ) { File atlasDir = null ; if ( null == name ) { atlasDir = new File ( "." ) ; } else { atlasDir = new File ( name ) ; } 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 . |
14,480 | static public File computeInstallDir ( ) { File installDir = null ; File knownResourceFile = null ; { URL url = Main . class . getClassLoader ( ) . getResource ( "commandResourceDummy.txt" ) ; if ( null == url ) { } else 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 ) ; knownResourceFile = new File ( jarFileName ) ; } } } else if ( "file" . equals ( url . getProtocol ( ) ) ) { knownResourceFile = new File ( url . getFile ( ) ) ; } } if ( null == installDir && null != knownResourceFile ) { File tempFile = knownResourceFile ; boolean found = false ; while ( ! found && null != tempFile ) { if ( "repo" . equals ( tempFile . getName ( ) ) ) { found = true ; installDir = tempFile . getParentFile ( ) ; } else { tempFile = tempFile . getParentFile ( ) ; } } } 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 . |
14,481 | static public File computeContentDir ( File installDir ) { if ( null != installDir ) { File contentDir = new File ( installDir , "content" ) ; if ( contentDir . exists ( ) && contentDir . isDirectory ( ) ) { return contentDir ; } 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 . |
14,482 | static public File computeBinDir ( File installDir ) { if ( null != installDir ) { File binDir = new File ( installDir , "bin" ) ; if ( binDir . exists ( ) && binDir . isDirectory ( ) ) { return binDir ; } 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 . |
14,483 | static public File computeSiteDesignDir ( File installDir ) { if ( null != installDir ) { File templatesDir = new File ( installDir , "internal/siteDesign" ) ; if ( templatesDir . exists ( ) && templatesDir . isDirectory ( ) ) { return templatesDir ; } 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 . |
14,484 | static public File computeNunaliitDir ( File installDir ) { while ( null != installDir ) { 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 { 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 . |
14,485 | 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 . |
14,486 | 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 . |
14,487 | static public MailVetterDailyNotificationTask scheduleTask ( CouchDesignDocument serverDesignDoc , MailNotification mailNotification ) { Timer timer = new Timer ( ) ; MailVetterDailyNotificationTask installedTask = new MailVetterDailyNotificationTask ( timer , serverDesignDoc , mailNotification ) ; Calendar calendar = Calendar . getInstance ( ) ; 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 ) ; } { 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 |
14,488 | 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 . |
14,489 | 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 . |
14,490 | 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" ) ; } List < Query > queries = parseQueriesJson ( queriesStrings [ 0 ] ) ; 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 . |
14,491 | 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 . |
14,492 | 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 |
14,493 | 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 . |
14,494 | 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 . |
14,495 | 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 ) { if ( ' ' == c || '\t' == c ) { } else if ( '"' == c ) { currentToken = new StringBuilder ( ) ; isTokenQuoted = true ; } else { currentToken = new StringBuilder ( ) ; currentToken . append ( c ) ; isTokenQuoted = false ; } } else if ( isTokenQuoted ) { if ( '"' == c ) { String token = currentToken . toString ( ) ; currentToken = null ; commandTokens . add ( token ) ; } else { currentToken . append ( c ) ; } } else { if ( ' ' == c || '\t' == c ) { String token = currentToken . toString ( ) ; currentToken = null ; commandTokens . add ( token ) ; } else { 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 |
14,496 | private UserAndPassword executeStatementToUser ( PreparedStatement preparedStmt ) throws Exception { if ( preparedStmt . execute ( ) ) { 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" ) ; } 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 { throw new Exception ( "Query returned no results" ) ; } } | This method executes a prepared SQL statement against the user table and returns a User . |
14,497 | private void writeNumber ( PrintWriter pw , NumberFormat numFormat , Number num ) { if ( num . doubleValue ( ) == Math . round ( num . doubleValue ( ) ) ) { 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 . |
14,498 | 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 . |
14,499 | static public String safeSqlQueryStringValue ( String in ) throws Exception { if ( null == in ) { return "NULL" ; } if ( in . indexOf ( '\0' ) >= 0 ) { throw new Exception ( "Null character found in string value" ) ; } in = in . replace ( "'" , "''" ) ; 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.