idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
14,000 | protected int getWaitPeriodInSeconds ( ) throws ActivityException { String unit = super . getAttributeValue ( WAIT_UNIT ) ; int factor ; if ( MINUTES . equals ( unit ) ) factor = 60 ; else if ( HOURS . equals ( unit ) ) factor = 3600 ; else if ( DAYS . equals ( unit ) ) factor = 86400 ; else factor = 1 ; // Means specified value is already in seconds int retTime ; String timeAttr ; try { timeAttr = super . getAttributeValueSmart ( WorkAttributeConstant . TIMER_WAIT ) ; } catch ( PropertyException e ) { throw new ActivityException ( - 1 , "failed to evaluate time expression" , e ) ; } retTime = StringHelper . getInteger ( timeAttr , DEFAULT_WAIT ) ; return retTime * factor ; } | Method that returns the wait period for the activity | 184 | 9 |
14,001 | public boolean isRoleMapped ( Long pRoleId ) { if ( userRoles == null || userRoles . length == 0 ) { return false ; } for ( int i = 0 ; i < userRoles . length ; i ++ ) { if ( userRoles [ i ] . getId ( ) . longValue ( ) == pRoleId . longValue ( ) ) { return true ; } } return false ; } | Checked if the passed in RoleId is mapped to this TaskAction | 91 | 14 |
14,002 | protected Process getSubflow ( Microservice service ) throws ActivityException { AssetVersionSpec spec = new AssetVersionSpec ( service . getSubflow ( ) ) ; try { Process process = ProcessCache . getProcessSmart ( spec ) ; if ( process == null ) throw new ActivityException ( "Subflow not found: " + service . getSubflow ( ) ) ; return process ; } catch ( DataAccessException ex ) { throw new ActivityException ( ex . getMessage ( ) , ex ) ; } } | Can be a process or template . | 105 | 7 |
14,003 | protected Map < String , String > createBindings ( List < Variable > childVars , int index , Microservice service , boolean passDocumentContent ) throws ActivityException { Map < String , String > parameters = new HashMap <> ( ) ; for ( int i = 0 ; i < childVars . size ( ) ; i ++ ) { Variable childVar = childVars . get ( i ) ; if ( childVar . isInput ( ) ) { String subflowVarName = childVar . getName ( ) ; Object value = service . getBindings ( ) . get ( subflowVarName ) ; if ( value != null ) { String stringValue = String . valueOf ( value ) ; if ( passDocumentContent ) { if ( VariableTranslator . isDocumentReferenceVariable ( getPackage ( ) , childVar . getType ( ) ) && stringValue . startsWith ( "DOCUMENT:" ) ) { stringValue = getDocumentContent ( new DocumentReference ( stringValue ) ) ; } } parameters . put ( subflowVarName , stringValue ) ; } } } String processName = getSubflow ( service ) . getName ( ) ; if ( processName . startsWith ( "$" ) && parameters . get ( processName ) == null ) { // template variable will populate process name parameters . put ( processName , service . getName ( ) ) ; } if ( parameters . get ( "i" ) == null ) parameters . put ( "i" , String . valueOf ( index ) ) ; return parameters ; } | Returns variable bindings to be passed into subprocess . | 324 | 10 |
14,004 | public static String getOverrideAttributeName ( String rawName , String subType , String subId ) { if ( OwnerType . ACTIVITY . equals ( subType ) ) return OVERRIDE_ACTIVITY + subId + ":" + rawName ; else if ( OwnerType . WORK_TRANSITION . equals ( subType ) ) return OVERRIDE_TRANSITION + subId + ":" + rawName ; else if ( OwnerType . PROCESS . equals ( subType ) ) return OVERRIDE_SUBPROC + subId + ":" + rawName ; else return rawName ; } | Returns raw name if subtype is null . | 130 | 9 |
14,005 | public void run ( ) throws SQLException { if ( ApplicationContext . isDevelopment ( ) && embeddedDb . checkRunning ( ) ) { // only checked in development (otherwise let db startup file due to locked resources) logger . severe ( "\n***WARNING***\nEmbedded DB appears to be running already. This can happen due to an unclean previous shutdown.\n***WARNING***" ) ; return ; } if ( shutdownHook != null ) { embeddedDb . shutdown ( ) ; Runtime . getRuntime ( ) . removeShutdownHook ( shutdownHook ) ; } shutdownHook = new Thread ( new Runnable ( ) { public void run ( ) { try { embeddedDb . shutdown ( ) ; } catch ( SQLException ex ) { System . err . println ( "ERROR: Cannot shut down embedded db cleanly" ) ; ex . printStackTrace ( ) ; } } } ) ; Runtime . getRuntime ( ) . addShutdownHook ( shutdownHook ) ; embeddedDb . startup ( ) ; if ( ! embeddedDb . checkMdwSchema ( ) ) { embeddedDb . createMdwSchema ( ) ; // seed users try { String usersJson = JsonUtil . read ( "seed_users.json" ) ; if ( usersJson != null ) { logger . info ( "Loading seed users into " + MDW_EMBEDDED_DB_CLASS + ":" ) ; JSONObject usersObj = new JsonObject ( usersJson ) ; if ( usersObj . has ( "users" ) ) { JSONArray usersArr = usersObj . getJSONArray ( "users" ) ; for ( int i = 0 ; i < usersArr . length ( ) ; i ++ ) { User user = new User ( usersArr . getJSONObject ( i ) ) ; logger . info ( " creating user: '" + user . getCuid ( ) + "'" ) ; embeddedDb . insertUser ( user ) ; } } } } catch ( Exception ex ) { throw new SQLException ( "Error inserting from seed_users.json" , ex ) ; } extensionsNeedInitialization = true ; } } | Starts the db if not running and connects to confirm process_instance table exists and creates the schema if the table is not found . | 470 | 27 |
14,006 | public long getId ( File file ) throws IOException { Long id = file2id . get ( file ) ; if ( id == null ) { id = gitHash ( file ) ; file2id . put ( file , id ) ; id2file . put ( id , file ) ; } return id ; } | Cannot use git object hash since identical files would return duplicate ids . Hash using git algorithm based on the relative file path . | 66 | 26 |
14,007 | public String getGitId ( File input ) throws IOException { String hash = "" ; if ( input . isFile ( ) ) { FileInputStream fis = null ; try { int fileSize = ( int ) input . length ( ) ; fis = new FileInputStream ( input ) ; byte [ ] fileBytes = new byte [ fileSize ] ; fis . read ( fileBytes ) ; //hash = localRepo.newObjectInserter().idFor(Constants.OBJ_BLOB, fileBytes).getName(); // This is slower than below code (even if reusing ObjectInserter instance) String blob = "blob " + fileSize + "\0" + new String ( fileBytes ) ; MessageDigest md = MessageDigest . getInstance ( "SHA-1" ) ; byte [ ] bytes = md . digest ( blob . getBytes ( ) ) ; hash = byteArrayToHexString ( bytes ) ; } catch ( Throwable ex ) { throw new IOException ( ex . getMessage ( ) , ex ) ; } finally { if ( fis != null ) fis . close ( ) ; } } return hash ; } | This produces the same hash for a given object that Git hash - object creates | 250 | 15 |
14,008 | public String getRemoteCommit ( String branch ) throws Exception { fetch ( ) ; ObjectId commit = localRepo . resolve ( "origin/" + branch ) ; if ( commit != null ) return commit . getName ( ) ; else return null ; } | Get remote HEAD commit . | 53 | 5 |
14,009 | public void checkout ( String branch ) throws Exception { if ( ! branch . equals ( getBranch ( ) ) ) { createBranchIfNeeded ( branch ) ; git . checkout ( ) . setName ( branch ) . setStartPoint ( "origin/" + branch ) . setUpstreamMode ( CreateBranchCommand . SetupUpstreamMode . TRACK ) . call ( ) ; // for some reason jgit needs this when branch is switched git . checkout ( ) . setName ( branch ) . call ( ) ; } } | Does not do anything if already on target branch . | 111 | 10 |
14,010 | protected void createBranchIfNeeded ( String branch ) throws Exception { fetch ( ) ; // in case the branch is not known locally if ( localRepo . findRef ( branch ) == null ) { git . branchCreate ( ) . setName ( branch ) . setUpstreamMode ( SetupUpstreamMode . TRACK ) . setStartPoint ( "origin/" + branch ) . call ( ) ; } } | Create a local branch for remote tracking if it doesn t exist already . | 87 | 14 |
14,011 | public CommitInfo getCommitInfo ( String path ) throws Exception { Iterator < RevCommit > revCommits = git . log ( ) . addPath ( path ) . setMaxCount ( 1 ) . call ( ) . iterator ( ) ; if ( revCommits . hasNext ( ) ) { RevCommit revCommit = revCommits . next ( ) ; CommitInfo commitInfo = new CommitInfo ( revCommit . getId ( ) . name ( ) ) ; PersonIdent committerIdent = revCommit . getCommitterIdent ( ) ; commitInfo . setCommitter ( committerIdent . getName ( ) ) ; commitInfo . setEmail ( committerIdent . getEmailAddress ( ) ) ; if ( ( commitInfo . getCommitter ( ) == null || commitInfo . getCommitter ( ) . isEmpty ( ) ) && commitInfo . getEmail ( ) != null ) commitInfo . setCommitter ( commitInfo . getEmail ( ) ) ; commitInfo . setDate ( committerIdent . getWhen ( ) ) ; commitInfo . setMessage ( revCommit . getShortMessage ( ) ) ; return commitInfo ; } return null ; } | Does not fetch . | 250 | 4 |
14,012 | protected String getPackageName ( String path ) throws IOException { return path . substring ( getAssetPath ( ) . length ( ) + 1 , path . length ( ) - 5 ) . replace ( ' ' , ' ' ) ; } | Paths are relative to the repository base . | 50 | 9 |
14,013 | public synchronized void setActivityInstanceStatus ( ActivityInstance actInst , Integer status , String statusMessage ) throws SQLException { if ( cache_activity_transition == CACHE_ONLY ) { actInst . setStatusCode ( status ) ; actInst . setMessage ( statusMessage ) ; } else { edadb . setActivityInstanceStatus ( actInst , status , statusMessage ) ; } } | changed to append in all cases | 86 | 6 |
14,014 | @ Override public int compareTo ( ServicePath servicePath ) { // longer paths come first if ( segments . length != servicePath . segments . length ) { return servicePath . segments . length - segments . length ; } else { for ( int i = 0 ; i < segments . length ; i ++ ) { boolean segmentIsParam = isParam ( segments [ i ] ) ; boolean serviceSegmentIsParam = isParam ( servicePath . segments [ i ] ) ; // non-params first if ( segmentIsParam && ! serviceSegmentIsParam ) return 1 ; else if ( serviceSegmentIsParam && ! segmentIsParam ) return - 1 ; } return path . compareTo ( servicePath . path ) ; } } | Sorting such that best match is found first . | 152 | 10 |
14,015 | @ Override @ Path ( "/{groupName}" ) @ ApiOperation ( value = "Retrieve a workgroup or all workgroups" , notes = "If groupName is not present, returns all workgroups." , response = Workgroup . class , responseContainer = "List" ) public JSONObject get ( String path , Map < String , String > headers ) throws ServiceException , JSONException { UserServices userServices = ServiceLocator . getUserServices ( ) ; try { String groupName = getSegment ( path , 1 ) ; if ( groupName == null ) // check parameter groupName = getParameters ( headers ) . get ( "name" ) ; if ( groupName != null ) { Workgroup group = userServices . getWorkgroup ( groupName ) ; if ( group == null ) throw new ServiceException ( ServiceException . NOT_FOUND , "Workgroup not found: " + groupName ) ; return group . getJson ( ) ; } else { return userServices . getWorkgroups ( ) . getJson ( ) ; } } catch ( ServiceException ex ) { throw ex ; } catch ( Exception ex ) { throw new ServiceException ( ex . getMessage ( ) , ex ) ; } } | Retrieve a workgroup or all workgroups . | 258 | 10 |
14,016 | static File getLibDir ( ) throws IOException { String mdwHome = System . getenv ( "MDW_HOME" ) ; if ( mdwHome == null ) mdwHome = System . getProperty ( "mdw.home" ) ; if ( mdwHome == null ) throw new IOException ( "Missing environment variable: MDW_HOME" ) ; File mdwDir = new File ( mdwHome ) ; if ( ! mdwDir . isDirectory ( ) ) throw new IOException ( "MDW_HOME is not a directory: " + mdwDir . getAbsolutePath ( ) ) ; File libDir = new File ( mdwDir + "/lib" ) ; if ( ! libDir . exists ( ) && ! libDir . mkdirs ( ) ) throw new IOException ( "Cannot create lib dir: " + libDir . getAbsolutePath ( ) ) ; return libDir ; } | Creates libDir and throws IOException if unable . | 199 | 11 |
14,017 | public void init ( String listenerName , Properties parameters ) throws PropertyException { try { if ( ! parameters . containsKey ( HOST_LIST ) ) throw new Exception ( "Missing bootstrap.servers property for Kafka listener" ) ; else { String [ ] hostarray = parameters . getProperty ( HOST_LIST ) . split ( "," ) ; if ( hostarray != null && hostarray . length > 0 ) hostList = Arrays . asList ( hostarray ) ; else throw new Exception ( "Missing value for bootstrap.servers property for Kafka listener" ) ; } } catch ( Exception e ) { throw new PropertyException ( e . getMessage ( ) ) ; } // STANDALONE logger = StandaloneLogger.getSingleton(); /* WITHENGINE */ logger = LoggerUtil . getStandardLogger ( ) ; logger . info ( "Starting Kafka consumer Listener name = " + listenerName ) ; kafkaListenerName = listenerName ; if ( ! parameters . containsKey ( TOPIC_LIST ) ) topics = Arrays . asList ( listenerName ) ; else { String [ ] topicList = parameters . getProperty ( TOPIC_LIST ) . split ( "," ) ; if ( topicList != null && topicList . length > 0 ) topics = Arrays . asList ( topicList ) ; else topics = Arrays . asList ( listenerName ) ; } if ( ! parameters . containsKey ( GROUP_ID ) ) { logger . warn ( "No group.id property specified for Kafka consumer " + kafkaListenerName + ", using \"" + kafkaListenerName + "\"..." ) ; parameters . put ( GROUP_ID , kafkaListenerName ) ; } if ( ! parameters . containsKey ( AUTO_COMMIT ) ) parameters . put ( AUTO_COMMIT , "true" ) ; if ( ! parameters . containsKey ( KEY_DESERIALIZER ) ) parameters . put ( KEY_DESERIALIZER , "org.apache.kafka.common.serialization.StringDeserializer" ) ; if ( ! parameters . containsKey ( VALUE_DESERIALIZER ) ) parameters . put ( VALUE_DESERIALIZER , "org.apache.kafka.common.serialization.StringDeserializer" ) ; // hostList = parameters.getProperty(HOST_LIST); auto_commit = getBooleanProperty ( parameters , AUTO_COMMIT , true ) ; poll_timeout = 1000 * getIntegerProperty ( parameters , POLL_TIMEOUT , 60 ) ; use_thread_pool = getBooleanProperty ( parameters , USE_THREAD_POOL , false ) ; xmlWrapper = parameters . getProperty ( XML_WRAPPER ) ; initParameters = parameters ; // Remove non-Kafka properties initParameters . remove ( KAFKAPOOL_CLASS_NAME ) ; initParameters . remove ( USE_THREAD_POOL ) ; initParameters . remove ( TOPIC_LIST ) ; initParameters . remove ( POLL_TIMEOUT ) ; initParameters . remove ( XML_WRAPPER ) ; } | null if processing using the same thread | 670 | 7 |
14,018 | private void startSpan ( ActivityRuntimeContext context ) { Tracing tracing = TraceHelper . getTracing ( "mdw-activity" ) ; Tracer tracer = tracing . tracer ( ) ; Span span = tracer . currentSpan ( ) ; if ( span == null ) { // async brave server if b3 requestHeaders populated (subspan) Object requestHeaders = context . getValue ( "requestHeaders" ) ; if ( requestHeaders instanceof Map ) { Map < ? , ? > headers = ( Map < ? , ? > ) requestHeaders ; if ( headers . containsKey ( "x-b3-traceid" ) ) { TraceContext . Extractor < Map < ? , ? > > extractor = tracing . propagation ( ) . extractor ( ( map , key ) -> { Object val = map . get ( key . toLowerCase ( ) ) ; return val == null ? null : val . toString ( ) ; } ) ; TraceContextOrSamplingFlags extracted = extractor . extract ( headers ) ; span = extracted . context ( ) != null ? tracer . joinSpan ( extracted . context ( ) ) : tracer . nextSpan ( extracted ) ; span . name ( "m" + context . getMasterRequestId ( ) ) . kind ( Span . Kind . SERVER ) ; span = tracer . newChild ( span . context ( ) ) . name ( "p" + context . getProcessInstanceId ( ) ) ; } } } if ( span == null ) { // create a new root span for async start span = tracer . nextSpan ( ) . name ( "a" + context . getActivityInstanceId ( ) ) ; } span . start ( ) . flush ( ) ; // async Tracer . SpanInScope spanInScope = tracer . withSpanInScope ( span ) ; context . getRuntimeAttributes ( ) . put ( Tracer . SpanInScope . class , spanInScope ) ; } | Resumes or forks | 423 | 4 |
14,019 | protected void populateResponseHeaders ( Set < String > requestHeaderKeys , Map < String , String > metaInfo , HttpServletResponse response ) { for ( String key : metaInfo . keySet ( ) ) { if ( ! Listener . AUTHENTICATED_USER_HEADER . equals ( key ) && ! Listener . AUTHENTICATED_JWT . equals ( key ) && ! Listener . METAINFO_HTTP_STATUS_CODE . equals ( key ) && ! Listener . METAINFO_ACCEPT . equals ( key ) && ! Listener . METAINFO_CONTENT_TYPE . equals ( key ) && ! Listener . METAINFO_DOWNLOAD_FORMAT . equals ( key ) && ! Listener . METAINFO_MDW_REQUEST_ID . equals ( key ) && ! requestHeaderKeys . contains ( key ) ) response . setHeader ( key , metaInfo . get ( key ) ) ; } // these always get populated if present if ( metaInfo . get ( Listener . METAINFO_REQUEST_ID ) != null ) response . setHeader ( Listener . METAINFO_REQUEST_ID , metaInfo . get ( Listener . METAINFO_REQUEST_ID ) ) ; if ( metaInfo . get ( Listener . METAINFO_MDW_REQUEST_ID ) != null && ! metaInfo . get ( Listener . METAINFO_MDW_REQUEST_ID ) . equals ( "0" ) ) response . setHeader ( Listener . METAINFO_MDW_REQUEST_ID , metaInfo . get ( Listener . METAINFO_MDW_REQUEST_ID ) ) ; if ( metaInfo . get ( Listener . METAINFO_CORRELATION_ID ) != null ) response . setHeader ( Listener . METAINFO_CORRELATION_ID , metaInfo . get ( Listener . METAINFO_CORRELATION_ID ) ) ; if ( metaInfo . get ( Listener . METAINFO_DOCUMENT_ID ) != null ) response . setHeader ( Listener . METAINFO_DOCUMENT_ID , metaInfo . get ( Listener . METAINFO_DOCUMENT_ID ) ) ; } | Populates response headers with values added by event handling . | 490 | 11 |
14,020 | private JSONObject createResponseMeta ( Map < String , String > metaInfo , Set < String > reqMetaInfo , Long ownerId , long requestTime ) throws EventHandlerException , JSONException , ServiceException { JSONObject meta = new JsonObject ( ) ; JSONObject headers = new JsonObject ( ) ; for ( String key : metaInfo . keySet ( ) ) { if ( ! Listener . AUTHENTICATED_USER_HEADER . equals ( key ) && ! Listener . METAINFO_HTTP_STATUS_CODE . equals ( key ) && ! Listener . METAINFO_ACCEPT . equals ( key ) && ! Listener . METAINFO_DOWNLOAD_FORMAT . equals ( key ) && ! Listener . METAINFO_MDW_REQUEST_ID . equals ( key ) && ! reqMetaInfo . contains ( key ) ) { headers . put ( key , metaInfo . get ( key ) ) ; } } // these always get populated if present if ( metaInfo . get ( Listener . METAINFO_REQUEST_ID ) != null ) headers . put ( Listener . METAINFO_REQUEST_ID , metaInfo . get ( Listener . METAINFO_REQUEST_ID ) ) ; if ( metaInfo . get ( Listener . METAINFO_MDW_REQUEST_ID ) != null && ! metaInfo . get ( Listener . METAINFO_MDW_REQUEST_ID ) . equals ( "0" ) ) headers . put ( Listener . METAINFO_MDW_REQUEST_ID , metaInfo . get ( Listener . METAINFO_MDW_REQUEST_ID ) ) ; if ( metaInfo . get ( Listener . METAINFO_CORRELATION_ID ) != null ) headers . put ( Listener . METAINFO_CORRELATION_ID , metaInfo . get ( Listener . METAINFO_CORRELATION_ID ) ) ; if ( metaInfo . get ( Listener . METAINFO_CONTENT_TYPE ) != null ) headers . put ( Listener . METAINFO_CONTENT_TYPE , metaInfo . get ( Listener . METAINFO_CONTENT_TYPE ) ) ; if ( ! headers . has ( Listener . METAINFO_CONTENT_TYPE ) ) headers . put ( Listener . METAINFO_CONTENT_TYPE , "application/json" ) ; meta . put ( "headers" , headers ) ; createDocument ( JSONObject . class . getName ( ) , meta , OwnerType . LISTENER_RESPONSE_META , ownerId ) ; ServiceLocator . getRequestServices ( ) . setElapsedTime ( OwnerType . LISTENER_RESPONSE , ownerId , System . currentTimeMillis ( ) - requestTime ) ; return meta ; } | Inserts the response meta DOCUMENT as well as INSTANCE_TIMING . | 616 | 18 |
14,021 | public Response createErrorResponse ( String req , Map < String , String > metaInfo , ServiceException ex ) { Request request = new Request ( 0L ) ; request . setContent ( req ) ; Response response = new Response ( ) ; String contentType = metaInfo . get ( Listener . METAINFO_CONTENT_TYPE ) ; if ( contentType == null && req != null && ! req . isEmpty ( ) ) contentType = req . trim ( ) . startsWith ( "{" ) ? Listener . CONTENT_TYPE_JSON : Listener . CONTENT_TYPE_XML ; if ( contentType == null ) contentType = Listener . CONTENT_TYPE_XML ; // compatibility metaInfo . put ( Listener . METAINFO_HTTP_STATUS_CODE , String . valueOf ( ex . getCode ( ) ) ) ; StatusMessage statusMsg = new StatusMessage ( ) ; statusMsg . setCode ( ex . getCode ( ) ) ; statusMsg . setMessage ( ex . getMessage ( ) ) ; response . setStatusCode ( statusMsg . getCode ( ) ) ; response . setStatusMessage ( statusMsg . getMessage ( ) ) ; response . setPath ( ServicePaths . getInboundResponsePath ( metaInfo ) ) ; if ( contentType . equals ( Listener . CONTENT_TYPE_JSON ) ) { response . setContent ( statusMsg . getJsonString ( ) ) ; } else { response . setContent ( statusMsg . getXml ( ) ) ; } return response ; } | Create a default error message . To customized this response use a ServiceMonitor . | 331 | 15 |
14,022 | public InternalEvent buildProcessStartMessage ( Long processId , Long eventInstId , String masterRequestId , Map < String , String > parameters ) { InternalEvent evMsg = InternalEvent . createProcessStartMessage ( processId , OwnerType . DOCUMENT , eventInstId , masterRequestId , null , null , null ) ; evMsg . setParameters ( parameters ) ; evMsg . setCompletionCode ( StartActivity . STANDARD_START ) ; // completion // code - // indicating // standard start return evMsg ; } | A utility method to build process start JMS message . | 111 | 11 |
14,023 | public Long getProcessId ( String procname ) throws Exception { Process proc = ProcessCache . getProcess ( procname , 0 ) ; if ( proc == null ) throw new DataAccessException ( 0 , "Cannot find process with name " + procname + ", version 0" ) ; return proc . getId ( ) ; } | Helper method to obtain process ID from process name . | 69 | 10 |
14,024 | public static String Replace ( String aSrcStr , String aSearchStr , String aReplaceStr ) { if ( aSrcStr == null || aSearchStr == null || aReplaceStr == null ) return aSrcStr ; if ( aSearchStr . length ( ) == 0 || aSrcStr . length ( ) == 0 || aSrcStr . indexOf ( aSearchStr ) == - 1 ) { return aSrcStr ; } StringBuffer mBuff = new StringBuffer ( ) ; int mSrcStrLen , mSearchStrLen ; mSrcStrLen = aSrcStr . length ( ) ; mSearchStrLen = aSearchStr . length ( ) ; for ( int i = 0 , j = 0 ; i < mSrcStrLen ; i = j + mSearchStrLen ) { j = aSrcStr . indexOf ( aSearchStr , i ) ; if ( j == - 1 ) { mBuff . append ( aSrcStr . substring ( i ) ) ; break ; } mBuff . append ( aSrcStr . substring ( i , j ) ) ; mBuff . append ( aReplaceStr ) ; } return mBuff . toString ( ) ; } | Replaces the search string with replace string in a given source string | 264 | 13 |
14,025 | public static boolean isEqualIgnoreCase ( String pStr1 , String pStr2 ) { if ( pStr1 == null && pStr2 == null ) { return true ; } else if ( pStr1 == null || pStr2 == null ) { return false ; } else if ( pStr1 . equalsIgnoreCase ( pStr2 ) ) { return true ; } return false ; } | Checks if both the strings are equal for value - Not Case sensitive . | 86 | 15 |
14,026 | public static boolean isEqual ( String pStr1 , String pStr2 ) { if ( pStr1 == null && pStr2 == null ) { return true ; } else if ( pStr1 == null || pStr2 == null ) { return false ; } else if ( pStr1 . equals ( pStr2 ) ) { return true ; } return false ; } | Checks if both the strings are equal for value - Case Sensitive . | 80 | 15 |
14,027 | public static String cleanString ( String pStr ) { if ( pStr == null || pStr . equals ( "" ) ) { return pStr ; } StringBuffer buff = new StringBuffer ( ) ; for ( int i = 0 ; i < pStr . length ( ) ; i ++ ) { char aChar = pStr . charAt ( i ) ; if ( Character . isLetterOrDigit ( aChar ) ) { buff . append ( aChar ) ; } } return buff . toString ( ) ; } | Removes all the spcial charactes and spaces from the passed in string - none letters or digits . | 109 | 21 |
14,028 | public static String stripNewLineChar ( String pString ) { String tmpFidValue = pString ; StringTokenizer aTokenizer = new StringTokenizer ( pString , "\n" ) ; if ( aTokenizer . countTokens ( ) > 1 ) { StringBuffer nameBuffer = new StringBuffer ( ) ; while ( aTokenizer . hasMoreTokens ( ) ) { nameBuffer . append ( aTokenizer . nextToken ( ) ) ; } tmpFidValue = nameBuffer . toString ( ) ; } return tmpFidValue ; } | This method strips out all new line characters from the passed String . | 117 | 13 |
14,029 | public static double getDouble ( String pStr ) { if ( isEmpty ( pStr ) ) { return 0.0 ; } double value = 0.0 ; pStr = pStr . substring ( 0 , pStr . length ( ) - 2 ) + "." + pStr . substring ( pStr . length ( ) - 2 ) ; try { value = Double . parseDouble ( pStr ) ; } catch ( NumberFormatException ex ) { } return value ; } | Returns the parsed double value out of the passed in String | 101 | 11 |
14,030 | public static long getLong ( String pStr ) { if ( isEmpty ( pStr ) ) { return 0 ; } long value = 0 ; try { value = Long . parseLong ( pStr ) ; } catch ( NumberFormatException nm ) { } return value ; } | Returns the parsed long value for the passed in String . | 57 | 11 |
14,031 | public static int getInteger ( String pStr , int defval ) { if ( isEmpty ( pStr ) ) return defval ; try { return Integer . parseInt ( pStr ) ; } catch ( NumberFormatException nm ) { return defval ; } } | Returns the parsed integer value for the passed in String . | 55 | 11 |
14,032 | public static boolean isContainedIn ( String strToBeSearched , String compositeStr , String regex ) { if ( ( null == strToBeSearched ) || ( null == compositeStr ) || ( null == regex ) ) return false ; String [ ] splitValues = compositeStr . split ( regex ) ; boolean isFound = false ; for ( int i = 0 ; i < splitValues . length ; i ++ ) { if ( strToBeSearched . equals ( splitValues [ i ] . trim ( ) ) ) { isFound = true ; break ; } } return isFound ; } | Method which checks whether a string which is having many values separated by a delimiter contains a particular value or not If the compositeStr is QC ATT L3 & strToBeSearched is QC & regex is then the method will return true . | 128 | 50 |
14,033 | public static String escapeWithBackslash ( String value , String metachars ) { StringBuffer sb = new StringBuffer ( ) ; int i , n = value . length ( ) ; char ch ; for ( i = 0 ; i < n ; i ++ ) { ch = value . charAt ( i ) ; if ( ch == ' ' || metachars . indexOf ( ch ) >= 0 ) { sb . append ( ' ' ) ; } sb . append ( ch ) ; } return sb . toString ( ) ; } | Escape meta characters with backslash . | 116 | 9 |
14,034 | public static String removeBackslashEscape ( String value ) { StringBuffer sb = new StringBuffer ( ) ; int i , n = value . length ( ) ; char ch ; boolean lastIsEscape = false ; for ( i = 0 ; i < n ; i ++ ) { ch = value . charAt ( i ) ; if ( lastIsEscape ) { sb . append ( ch ) ; lastIsEscape = false ; } else { if ( ch == ' ' ) lastIsEscape = true ; else sb . append ( ch ) ; } } return sb . toString ( ) ; } | Remove backslashes that are used as escape characters | 132 | 10 |
14,035 | public static String compress ( String uncompressedValue ) throws IOException { if ( uncompressedValue == null ) return null ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; GZIPOutputStream gzip = null ; try { gzip = new GZIPOutputStream ( out ) ; gzip . write ( uncompressedValue . getBytes ( ) ) ; gzip . close ( ) ; return out . toString ( "ISO-8859-1" ) ; } finally { if ( gzip != null ) gzip . close ( ) ; } } | Compress a string value using GZIP . | 121 | 10 |
14,036 | public static String uncompress ( String compressedValue ) throws IOException { if ( compressedValue == null ) return null ; ByteArrayInputStream in = new ByteArrayInputStream ( compressedValue . getBytes ( "ISO-8859-1" ) ) ; GZIPInputStream gzip = null ; Reader reader = null ; try { String value = "" ; gzip = new GZIPInputStream ( in ) ; reader = new InputStreamReader ( gzip , "ISO-8859-1" ) ; int i ; while ( ( i = reader . read ( ) ) != - 1 ) value += ( char ) i ; return value ; } finally { if ( gzip != null ) gzip . close ( ) ; if ( reader != null ) reader . close ( ) ; } } | Uncompress a string value that was compressed using GZIP . | 167 | 14 |
14,037 | public static int delimiterColumnCount ( String row , String delimeterChar , String escapeChar ) { if ( row . indexOf ( escapeChar ) > 0 ) return row . replace ( escapeChar , " " ) . length ( ) - row . replace ( "," , "" ) . length ( ) ; else return row . length ( ) - row . replace ( "," , "" ) . length ( ) ; } | To count comma separated columns in a row to maintain compatibility | 87 | 11 |
14,038 | public void sendMessage ( String requestMessage , String queueName , String correlationId , final Queue replyQueue , int delaySeconds , int deliveryMode ) throws JMSException { /** * If it's an internal message then always use jmsTemplate for ActiveMQ */ if ( jmsTemplate != null ) { jmsTemplate . setDeliveryMode ( deliveryMode ) ; if ( ! StringUtils . isEmpty ( queueName ) ) { jmsTemplate . send ( queueName , new MDWMessageCreator ( requestMessage , correlationId , replyQueue , delaySeconds ) ) ; } else { jmsTemplate . send ( new MDWMessageCreator ( requestMessage , correlationId , replyQueue ) ) ; } } } | Send a message to a queue with corrId delay and potential replyQueue | 152 | 15 |
14,039 | public void broadcastMessageToTopic ( String dest , String requestMessage ) { jmsTopicTemplate . setDeliveryPersistent ( true ) ; jmsTopicTemplate . send ( dest , new MDWMessageCreator ( requestMessage ) ) ; } | Broadcast a message to a specific topic | 50 | 8 |
14,040 | public static final com . centurylink . mdw . variable . VariableTranslator getTranslator ( Package packageVO , String type ) { com . centurylink . mdw . variable . VariableTranslator trans = null ; try { VariableType vo = VariableTypeCache . getVariableTypeVO ( Compatibility . getVariableType ( type ) ) ; if ( vo == null ) return null ; // try dynamic java first (preferred in case patch override is needed / Exclude MDW built-in translators) if ( ! mdwVariableTypes . contains ( vo ) ) { ClassLoader parentLoader = packageVO == null ? VariableTranslator . class . getClassLoader ( ) : packageVO . getClassLoader ( ) ; trans = ProviderRegistry . getInstance ( ) . getDynamicVariableTranslator ( vo . getTranslatorClass ( ) , parentLoader ) ; } if ( trans == null ) { com . centurylink . mdw . variable . VariableTranslator injected = SpringAppContext . getInstance ( ) . getVariableTranslator ( vo . getTranslatorClass ( ) , packageVO ) ; if ( injected != null ) trans = injected ; if ( trans == null ) { Class < ? > cl = Class . forName ( vo . getTranslatorClass ( ) ) ; trans = ( VariableTranslator ) cl . newInstance ( ) ; } } } catch ( Throwable th ) { th . printStackTrace ( ) ; trans = null ; } if ( trans != null ) trans . setPackage ( packageVO ) ; return trans ; } | Returns the translator for the passed in pType | 324 | 9 |
14,041 | public static Object toObject ( String type , String value ) { if ( StringHelper . isEmpty ( value ) || EMPTY_STRING . equals ( value ) ) { return null ; } com . centurylink . mdw . variable . VariableTranslator trans = getTranslator ( type ) ; return trans . toObject ( value ) ; } | Translates the Passed in String value based on the Passed in type | 72 | 14 |
14,042 | public static String realToString ( Package pkg , String type , Object value ) { if ( value == null ) return "" ; com . centurylink . mdw . variable . VariableTranslator trans = getTranslator ( pkg , type ) ; if ( trans instanceof DocumentReferenceTranslator ) return ( ( DocumentReferenceTranslator ) trans ) . realToString ( value ) ; else return trans . toString ( value ) ; } | Serializes a runtime variable object to its string value . Documents are expanded . | 91 | 15 |
14,043 | public static Object realToObject ( Package pkg , String type , String value ) { if ( StringHelper . isEmpty ( value ) ) return null ; com . centurylink . mdw . variable . VariableTranslator trans = getTranslator ( pkg , type ) ; if ( trans instanceof DocumentReferenceTranslator ) return ( ( DocumentReferenceTranslator ) trans ) . realToObject ( value ) ; else return trans . toObject ( value ) ; } | Deserializes variable string values to runtime objects . | 96 | 10 |
14,044 | public XAnnotation < javax . persistence . Id > createId ( Boolean source ) { return source == null ? null : createId ( source . booleanValue ( ) ) ; } | 9 . 1 . 8 | 39 | 5 |
14,045 | public XAnnotation < javax . persistence . OneToOne > createOneToOne ( OneToOne cOneToOne ) { return cOneToOne == null ? null : // new XAnnotation < javax . persistence . OneToOne > ( javax . persistence . OneToOne . class , // cOneToOne . getTargetEntity ( ) == null ? null : new XSingleAnnotationField < Class < Object > > ( "targetEntity" , Class . class , new XClassByNameAnnotationValue < Object > ( cOneToOne . getTargetEntity ( ) ) ) , // AnnotationUtils . create ( "cascade" , getCascadeType ( cOneToOne . getCascade ( ) ) ) , // AnnotationUtils . create ( "fetch" , getFetchType ( cOneToOne . getFetch ( ) ) ) , // AnnotationUtils . create ( "optional" , cOneToOne . isOptional ( ) ) , // AnnotationUtils . create ( "mappedBy" , cOneToOne . getMappedBy ( ) ) , // AnnotationUtils . create ( "orphanRemoval" , cOneToOne . isOrphanRemoval ( ) ) // ) ; } | 9 . 1 . 23 | 275 | 5 |
14,046 | public XAnnotation < javax . persistence . NamedQuery > createNamedQuery ( NamedQuery source ) { return source == null ? null : // new XAnnotation < javax . persistence . NamedQuery > ( javax . persistence . NamedQuery . class , // AnnotationUtils . create ( "query" , source . getQuery ( ) ) , // AnnotationUtils . create ( "hints" , createQueryHint ( source . getHint ( ) ) , QueryHint . class ) , // AnnotationUtils . create ( "name" , source . getName ( ) ) , AnnotationUtils . create ( "lockMode" , createLockMode ( source . getLockMode ( ) ) ) // ) ; } | 8 . 3 . 1 | 161 | 5 |
14,047 | public XAnnotation < javax . persistence . AssociationOverride > createAssociationOverride ( AssociationOverride source ) { return source == null ? null : // new XAnnotation < javax . persistence . AssociationOverride > ( javax . persistence . AssociationOverride . class , // AnnotationUtils . create ( "name" , source . getName ( ) ) , // AnnotationUtils . create ( "joinColumns" , createJoinColumn ( source . getJoinColumn ( ) ) , JoinColumn . class ) , // AnnotationUtils . create ( "joinTable" , createJoinTable ( source . getJoinTable ( ) ) ) // ) ; } | 9 . 1 . 12 | 141 | 5 |
14,048 | public void setDay ( Calendar source , XMLGregorianCalendar target ) { target . setDay ( source . get ( Calendar . DAY_OF_MONTH ) ) ; } | target ) ; | 37 | 3 |
14,049 | public static JType getCommonBaseType ( JCodeModel codeModel , Collection < ? extends JType > types ) { return getCommonBaseType ( codeModel , types . toArray ( new JType [ types . size ( ) ] ) ) ; } | Computes the common base type of two types . | 53 | 10 |
14,050 | protected void setupLogging ( ) { super . setupLogging ( ) ; final Logger rootLogger = LogManager . getRootLogger ( ) ; rootLogger . addAppender ( new NullAppender ( ) ) ; final Logger logger = LogManager . getLogger ( "org.jvnet.hyperjaxb3" ) ; final Log log = getLog ( ) ; logger . addAppender ( new Appender ( getLog ( ) , new PatternLayout ( "%m%n %c%n" ) ) ) ; if ( this . getDebug ( ) ) { log . debug ( "Logger level set to [debug]." ) ; logger . setLevel ( Level . DEBUG ) ; } else if ( this . getVerbose ( ) ) logger . setLevel ( Level . INFO ) ; else if ( log . isWarnEnabled ( ) ) logger . setLevel ( Level . WARN ) ; else logger . setLevel ( Level . ERROR ) ; } | Sets up the verbose and debug mode depending on mvn logging level and sets up hyperjaxb logging . | 209 | 25 |
14,051 | protected void logConfiguration ( ) throws MojoExecutionException { super . logConfiguration ( ) ; getLog ( ) . info ( "target:" + target ) ; getLog ( ) . info ( "roundtripTestClassName:" + roundtripTestClassName ) ; getLog ( ) . info ( "resourceIncludes:" + resourceIncludes ) ; getLog ( ) . info ( "variant:" + variant ) ; getLog ( ) . info ( "persistenceUnitName:" + persistenceUnitName ) ; getLog ( ) . info ( "persistenceXml:" + persistenceXml ) ; getLog ( ) . info ( "generateHashCode:" + generateHashCode ) ; getLog ( ) . info ( "generateEquals:" + generateEquals ) ; getLog ( ) . info ( "generateTransientId:" + generateTransientId ) ; getLog ( ) . info ( "result:" + result ) ; getLog ( ) . info ( "preArgs:" + Arrays . toString ( preArgs ) ) ; getLog ( ) . info ( "postArgs:" + Arrays . toString ( postArgs ) ) ; try { getLog ( ) . info ( "XJC loaded from:" + Options . class . getResource ( "Options.class" ) . toURI ( ) . toURL ( ) . toExternalForm ( ) ) ; } catch ( IOException ignored ) { } catch ( URISyntaxException ignored ) { } } | Logs options defined directly as mojo parameters . | 312 | 10 |
14,052 | public static boolean isAvailable ( Context context ) { if ( SDK_INT < JELLY_BEAN_MR2 ) { return false ; } Intent serviceIntent = new Intent ( "android.support.customtabs.action.CustomTabsService" ) . setPackage ( "com.android.chrome" ) ; ServiceConnection connection = new ServiceConnection ( ) { @ Override public void onServiceConnected ( ComponentName name , IBinder service ) { } @ Override public void onServiceDisconnected ( ComponentName name ) { } } ; boolean available = context . bindService ( serviceIntent , connection , Context . BIND_AUTO_CREATE | Context . BIND_WAIVE_PRIORITY ) ; context . unbindService ( connection ) ; return available ; } | Checks to see if this device supports Chrome Custom Tabs and if Chrome Custom Tabs are available . | 168 | 21 |
14,053 | private String parseMetadata ( DocumentMetadata metadata ) throws IOException { ResultItem item = result . next ( ) ; String uri = item . asString ( ) ; if ( uri == null ) { throw new IOException ( "Missing document URI for metadata." ) ; } item = result . next ( ) ; //node-kind, must exist String nKind = item . asString ( ) ; metadata . setFormat ( nKind ) ; item = result . next ( ) ; // handle collections, may not be present while ( item != null && item . getItemType ( ) == ValueType . XS_STRING ) { if ( ! copyCollection ) { item = result . next ( ) ; continue ; } metadata . addCollection ( item . asString ( ) ) ; item = result . next ( ) ; } // handle permissions, may not be present StringBuilder buf = new StringBuilder ( ) ; buf . append ( "<perms>" ) ; while ( item != null && ValueType . ELEMENT == item . getItemType ( ) ) { if ( ! copyPermission ) { item = result . next ( ) ; continue ; } try { readPermission ( ( XdmElement ) item . getItem ( ) , metadata , buf ) ; } catch ( Exception e ) { throw new IOException ( e ) ; } item = result . next ( ) ; } buf . append ( "</perms>" ) ; metadata . setPermString ( buf . toString ( ) ) ; // handle quality, always present even if not requested (barrier) metadata . setQuality ( ( XSInteger ) item . getItem ( ) ) ; // handle metadata item = result . next ( ) ; if ( copyMetadata ) { XdmItem metaItem = item . getItem ( ) ; if ( metaItem instanceof JsonItem ) { JsonNode node = ( ( JsonItem ) metaItem ) . asJsonNode ( ) ; metadata . meta = new HashMap < String , String > ( node . size ( ) ) ; for ( Iterator < String > names = node . fieldNames ( ) ; names . hasNext ( ) ; ) { String key = names . next ( ) ; JsonNode nodeVal = node . get ( key ) ; metadata . meta . put ( key , nodeVal . asText ( ) ) ; } item = result . next ( ) ; } } // handle prop:properties node, optional // if not present, there will be a 0 as a marker if ( copyProperties && ValueType . ELEMENT == item . getItemType ( ) ) { String pString = item . asString ( ) ; if ( pString != null ) { metadata . setProperties ( pString ) ; } item = result . next ( ) ; } if ( ValueType . XS_INTEGER != item . getItemType ( ) ) { throw new IOException ( uri + " unexpected " + item . getItemType ( ) + " " + item . asString ( ) + ", expected " + ValueType . XS_INTEGER + " 0" ) ; } return uri ; } | Parse metadata from the sequence store it into the DocumentMetadata object passed in | 664 | 16 |
14,054 | private int getDocumentType ( ) { NodeList children = getChildNodes ( ) ; int elemCount = 0 ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { Node n = children . item ( i ) ; switch ( n . getNodeType ( ) ) { case Node . ELEMENT_NODE : elemCount ++ ; break ; case Node . PROCESSING_INSTRUCTION_NODE : case Node . COMMENT_NODE : continue ; default : return NON_XML ; } } return elemCount <= 1 ? VALID_XML : NON_XML ; } | Check root node of a document to see if it conform to DOM Structure Model . The root node can only be ELEMENT_NODE PROCESSING_INSTRUCTION_NODE or COMMENT_NODE . | 137 | 44 |
14,055 | public static List < ContentPermission > getPermissions ( String [ ] perms ) { List < ContentPermission > permissions = null ; if ( perms != null && perms . length > 0 ) { int i = 0 ; while ( i + 1 < perms . length ) { String roleName = perms [ i ++ ] ; if ( roleName == null || roleName . isEmpty ( ) ) { LOG . error ( "Illegal role name: " + roleName ) ; continue ; } String perm = perms [ i ] . trim ( ) ; ContentCapability capability = getCapbility ( perm ) ; if ( capability != null ) { if ( permissions == null ) { permissions = new ArrayList < ContentPermission > ( ) ; } permissions . add ( new ContentPermission ( capability , roleName ) ) ; } i ++ ; } } return permissions ; } | Get a list of ContentPermission from given string | 187 | 10 |
14,056 | public static String getValidName ( String name ) { StringBuilder validname = new StringBuilder ( ) ; char ch = name . charAt ( 0 ) ; if ( ! XML11Char . isXML11NameStart ( ch ) ) { LOG . warn ( "Prepend _ to " + name ) ; validname . append ( "_" ) ; } for ( int i = 0 ; i < name . length ( ) ; i ++ ) { ch = name . charAt ( i ) ; if ( ! XML11Char . isXML11Name ( ch ) ) { LOG . warn ( "Character " + ch + " in " + name + " is converted to _" ) ; validname . append ( "_" ) ; } else { validname . append ( ch ) ; } } return validname . toString ( ) ; } | Get valid element name from a given string | 177 | 8 |
14,057 | protected void insertBatch ( Content [ ] batch , int id ) throws IOException { retry = 0 ; sleepTime = 500 ; while ( retry < maxRetries ) { try { if ( retry == 1 ) { LOG . info ( "Retrying document insert" ) ; } List < RequestException > errors = sessions [ id ] . insertContentCollectErrors ( batch ) ; if ( errors != null ) { for ( RequestException ex : errors ) { Throwable cause = ex . getCause ( ) ; if ( cause != null ) { if ( cause instanceof QueryException ) { LOG . error ( ( ( QueryException ) cause ) . getFormatString ( ) ) ; } else { LOG . error ( cause . getMessage ( ) ) ; } } if ( ex instanceof ContentInsertException ) { Content content = ( ( ContentInsertException ) ex ) . getContent ( ) ; DocumentURI failedUri = pendingUris [ id ] . remove ( content ) ; failed ++ ; if ( failedUri != null ) { LOG . warn ( "Failed document " + failedUri ) ; } } } } if ( retry > 0 ) { LOG . debug ( "Retry successful" ) ; } } catch ( Exception e ) { boolean retryable = true ; if ( e instanceof QueryException ) { LOG . error ( "QueryException:" + ( ( QueryException ) e ) . getFormatString ( ) ) ; retryable = ( ( QueryException ) e ) . isRetryable ( ) ; } else if ( e instanceof RequestServerException ) { // log error and continue on RequestServerException // not retryable so trying to connect to the replica LOG . error ( "RequestServerException:" + e . getMessage ( ) ) ; } else { LOG . error ( "Exception:" + e . getMessage ( ) ) ; } // necessary to roll back in certain scenarios. if ( needCommit ) { rollback ( id ) ; } if ( retryable && ++ retry < maxRetries ) { // necessary to close the session too. sessions [ id ] . close ( ) ; try { InternalUtilities . sleep ( sleepTime ) ; } catch ( Exception e2 ) { } sleepTime = sleepTime * 2 ; if ( sleepTime > maxSleepTime ) sleepTime = maxSleepTime ; // We need to switch host even for RetryableQueryException // because it could be "sync replicating" (bug:45785) sessions [ id ] = getSession ( id , true ) ; continue ; } else if ( retryable ) { LOG . info ( "Exceeded max retry" ) ; } failed += batch . length ; // remove the failed content from pendingUris for ( Content fc : batch ) { DocumentURI failedUri = pendingUris [ id ] . remove ( fc ) ; LOG . warn ( "Failed document " + failedUri ) ; } throw new IOException ( e ) ; } break ; } if ( needCommit ) { // move uris from pending to commit for ( DocumentURI uri : pendingUris [ id ] . values ( ) ) { commitUris [ id ] . add ( uri ) ; } } else { succeeded += pendingUris [ id ] . size ( ) ; } pendingUris [ id ] . clear ( ) ; } | Insert batch log errors and update stats . | 710 | 8 |
14,058 | public Node item ( int index ) { try { return item ( index , null ) ; } catch ( ParserConfigurationException e ) { throw new RuntimeException ( e ) ; } } | Returns the indexth item in the map . If index is greater than or equal to the number of nodes in this map this returns null ; if the item returned is a namespace declaration it is represented as an attribute whose owner document is a document containing the attribute only . | 38 | 53 |
14,059 | private boolean hasTextContent ( Node child ) { return child . getNodeType ( ) != Node . COMMENT_NODE && child . getNodeType ( ) != Node . PROCESSING_INSTRUCTION_NODE ; } | PROCESSING_INSTRUCTION_NODE nodes . | 49 | 13 |
14,060 | private void getTextContent ( StringBuilder sb ) throws DOMException { NodeList children = getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { Node child = children . item ( i ) ; if ( hasTextContent ( child ) ) { sb . append ( child . getTextContent ( ) ) ; } } } | internal method taking a StringBuffer in parameter | 83 | 8 |
14,061 | protected boolean setKey ( String uri , int line , int col , boolean encode ) { if ( key == null ) { key = new DocumentURIWithSourceInfo ( uri , srcId ) ; } // apply prefix, suffix and replace for URI if ( uri != null && ! uri . isEmpty ( ) ) { uri = URIUtil . applyUriReplace ( uri , conf ) ; key . setSkipReason ( "" ) ; if ( encode ) { try { URI uriObj = new URI ( null , null , null , 0 , uri , null , null ) ; uri = uriObj . toString ( ) ; } catch ( URISyntaxException e ) { uri = null ; key . setSkipReason ( e . getMessage ( ) ) ; } } uri = URIUtil . applyPrefixSuffix ( uri , conf ) ; } else { key . setSkipReason ( "empty uri value" ) ; } key . setUri ( uri ) ; key . setSrcId ( srcId ) ; key . setSubId ( subId ) ; key . setColNumber ( col ) ; key . setLineNumber ( line ) ; if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "Set key: " + key ) ; } return key . isSkip ( ) ; } | Apply URI replace option encode URI if specified apply URI prefix and suffix configuration options and set the result as DocumentURI key . | 294 | 24 |
14,062 | private static void setClassLoader ( File hdConfDir , Configuration conf ) throws Exception { ClassLoader parent = conf . getClassLoader ( ) ; URL url = hdConfDir . toURI ( ) . toURL ( ) ; URL [ ] urls = new URL [ 1 ] ; urls [ 0 ] = url ; ClassLoader classLoader = new URLClassLoader ( urls , parent ) ; Thread . currentThread ( ) . setContextClassLoader ( classLoader ) ; conf . setClassLoader ( classLoader ) ; } | Set class loader for current thread and for Confifguration based on Hadoop home . | 112 | 19 |
14,063 | public static ContentSource getInputContentSource ( Configuration conf ) throws URISyntaxException , XccConfigException , IOException { String host = conf . getStrings ( INPUT_HOST ) [ 0 ] ; if ( host == null || host . isEmpty ( ) ) { throw new IllegalArgumentException ( INPUT_HOST + " is not specified." ) ; } return getInputContentSource ( conf , host ) ; } | Get content source for input server . | 93 | 7 |
14,064 | public static ContentSource getInputContentSource ( Configuration conf , String host ) throws XccConfigException , IOException { String user = conf . get ( INPUT_USERNAME , "" ) ; String password = conf . get ( INPUT_PASSWORD , "" ) ; String port = conf . get ( INPUT_PORT , "8000" ) ; String db = conf . get ( INPUT_DATABASE_NAME ) ; int portInt = Integer . parseInt ( port ) ; boolean useSsl = conf . getBoolean ( INPUT_USE_SSL , false ) ; if ( useSsl ) { return getSecureContentSource ( host , portInt , user , password , db , getInputSslOptions ( conf ) ) ; } return ContentSourceFactory . newContentSource ( host , portInt , user , password , db ) ; } | Get input content source . | 182 | 5 |
14,065 | public static ContentSource getOutputContentSource ( Configuration conf , String hostName ) throws XccConfigException , IOException { String user = conf . get ( OUTPUT_USERNAME , "" ) ; String password = conf . get ( OUTPUT_PASSWORD , "" ) ; String port = conf . get ( OUTPUT_PORT , "8000" ) ; String db = conf . get ( OUTPUT_DATABASE_NAME ) ; int portInt = Integer . parseInt ( port ) ; boolean useSsl = conf . getBoolean ( OUTPUT_USE_SSL , false ) ; if ( useSsl ) { return getSecureContentSource ( hostName , portInt , user , password , db , getOutputSslOptions ( conf ) ) ; } return ContentSourceFactory . newContentSource ( hostName , portInt , user , password , db ) ; } | Get output content source . | 185 | 5 |
14,066 | public static String getHost ( TextArrayWritable hosts ) throws IOException { String [ ] hostStrings = hosts . toStrings ( ) ; if ( hostStrings == null || hostStrings . length == 0 ) throw new IOException ( "Number of forests is 0: " + "check forests in database" ) ; int count = hostStrings . length ; int position = ( int ) ( Math . random ( ) * count ) ; return hostStrings [ position ] ; } | Return the host from the host array based on a random fashion | 103 | 12 |
14,067 | public static XdmValue newValue ( ValueType valueType , Object value ) { if ( value instanceof Text ) { return ValueFactory . newValue ( valueType , ( ( Text ) value ) . toString ( ) ) ; } else if ( value instanceof BytesWritable ) { return ValueFactory . newValue ( valueType , ( ( BytesWritable ) value ) . getBytes ( ) ) ; } else if ( value instanceof IntWritable ) { return ValueFactory . newValue ( valueType , ( ( IntWritable ) value ) . get ( ) ) ; } else if ( value instanceof LongWritable ) { return ValueFactory . newValue ( valueType , ( ( LongWritable ) value ) . get ( ) ) ; } else if ( value instanceof VIntWritable ) { return ValueFactory . newValue ( valueType , ( ( VIntWritable ) value ) . get ( ) ) ; } else if ( value instanceof VLongWritable ) { return ValueFactory . newValue ( valueType , ( ( VLongWritable ) value ) . get ( ) ) ; } else if ( value instanceof BooleanWritable ) { return ValueFactory . newValue ( valueType , ( ( BooleanWritable ) value ) . get ( ) ) ; } else if ( value instanceof FloatWritable ) { return ValueFactory . newValue ( valueType , ( ( FloatWritable ) value ) . get ( ) ) ; } else if ( value instanceof DoubleWritable ) { return ValueFactory . newValue ( valueType , ( ( DoubleWritable ) value ) . get ( ) ) ; } else if ( value instanceof MarkLogicNode ) { return ValueFactory . newValue ( valueType , ( ( MarkLogicNode ) value ) . get ( ) ) ; } else { throw new UnsupportedOperationException ( "Value " + value . getClass ( ) . getName ( ) + " is unsupported." ) ; } } | Create new XdmValue from value type and Writables . | 415 | 12 |
14,068 | public static String getUriWithOutputDir ( DocumentURI key , String outputDir ) { String uri = key . getUri ( ) ; if ( outputDir != null && ! outputDir . isEmpty ( ) ) { uri = outputDir . endsWith ( "/" ) || uri . startsWith ( "/" ) ? outputDir + uri : outputDir + ' ' + uri ; key . setUri ( uri ) ; key . validate ( ) ; } return uri ; } | If outputDir is available and valid modify DocumentURI and return uri in string | 108 | 16 |
14,069 | public static void sleep ( long millis ) throws InterruptedException { while ( millis > 0 ) { // abort if the user kills mlcp in local mode String shutdown = System . getProperty ( "mlcp.shutdown" ) ; if ( shutdown != null ) { break ; } if ( millis > 1000 ) { Thread . sleep ( 1000 ) ; millis -= 1000 ; } else { Thread . sleep ( millis ) ; millis = 0 ; } } } | Wake up every 1 second to check whether to abort | 99 | 11 |
14,070 | public void updateStats ( int fIdx , long count ) { synchronized ( pq ) { frmtCount [ fIdx ] += count ; Stats tmp = new Stats ( fIdx , frmtCount [ fIdx ] ) ; // remove the stats object with the same fIdx pq . remove ( tmp ) ; pq . offer ( tmp ) ; } if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "update forest " + fIdx ) ; } } | add count to forest with index fIdx which may not be the forest with minimum frmtCount . Used by fragment count rollback . | 107 | 28 |
14,071 | @ Override public int getPlacementForestIndex ( DocumentURI uri ) { int idx = 0 ; try { idx = popAndInsert ( ) ; } catch ( InterruptedException e ) { LOG . error ( "Statistical assignment gets interrupted" ) ; } return idx ; } | get the index of the forest with smallest number of docs | 62 | 11 |
14,072 | protected void setKey ( String uri , String sub , int line , int col ) { if ( srcId == null ) { srcId = split . getPath ( ) . toString ( ) ; } // apply prefix and suffix for URI uri = URIUtil . applyUriReplace ( uri , conf ) ; uri = URIUtil . applyPrefixSuffix ( uri , conf ) ; if ( key == null ) { key = new DocumentURIWithSourceInfo ( uri , srcId , sub , line , col ) ; } else { key . setSkipReason ( "" ) ; key . setUri ( uri ) ; key . setSrcId ( srcId ) ; key . setSubId ( sub ) ; key . setColNumber ( col ) ; key . setLineNumber ( line ) ; } } | Apply URI prefix and suffix configuration options and set the result as DocumentURI key . | 180 | 16 |
14,073 | private LinkedMapWritable getMimetypesMap ( ) throws IOException { if ( mimetypeMap != null ) return mimetypeMap ; String mtmap = conf . get ( ConfigConstants . CONF_MIMETYPES ) ; if ( mtmap != null ) { mimetypeMap = DefaultStringifier . load ( conf , ConfigConstants . CONF_MIMETYPES , LinkedMapWritable . class ) ; return mimetypeMap ; } String [ ] hosts = conf . getStrings ( OUTPUT_HOST ) ; Session session = null ; ResultSequence result = null ; for ( int i = 0 ; i < hosts . length ; i ++ ) { try { String host = hosts [ i ] ; ContentSource cs = InternalUtilities . getOutputContentSource ( conf , host ) ; session = cs . newSession ( ) ; AdhocQuery query = session . newAdhocQuery ( MIMETYPES_QUERY ) ; RequestOptions options = new RequestOptions ( ) ; options . setDefaultXQueryVersion ( "1.0-ml" ) ; query . setOptions ( options ) ; result = session . submitRequest ( query ) ; if ( ! result . hasNext ( ) ) throw new IOException ( "Server-side transform requires MarkLogic 7 or later" ) ; mimetypeMap = new LinkedMapWritable ( ) ; while ( result . hasNext ( ) ) { String suffs = result . next ( ) . asString ( ) ; Text format = new Text ( result . next ( ) . asString ( ) ) ; // some extensions are in a space separated string for ( String s : suffs . split ( " " ) ) { Text suff = new Text ( s ) ; mimetypeMap . put ( suff , format ) ; } } return mimetypeMap ; } catch ( Exception e ) { if ( e . getCause ( ) instanceof ServerConnectionException ) { LOG . warn ( "Unable to connect to " + hosts [ i ] + " to query destination information" ) ; continue ; } LOG . error ( e . getMessage ( ) , e ) ; throw new IOException ( e ) ; } finally { if ( result != null ) { result . close ( ) ; } if ( session != null ) { session . close ( ) ; } } } return null ; } | initialize mimetype map if not initialized return the map | 507 | 12 |
14,074 | public static void setNumberOfThreads ( Job job , int threads ) { job . getConfiguration ( ) . setInt ( ConfigConstants . CONF_THREADS_PER_SPLIT , threads ) ; } | Set the number of threads in the pool for running maps . | 47 | 12 |
14,075 | protected Session getSession ( ) throws IOException { if ( session == null ) { // start a session try { ContentSource cs = InternalUtilities . getOutputContentSource ( conf , hostName ) ; session = cs . newSession ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Connect to " + session . getConnectionUri ( ) . getHost ( ) ) ; } if ( txnSize > 1 ) { session . setTransactionMode ( TransactionMode . UPDATE ) ; } } catch ( XccConfigException e ) { LOG . error ( "Error creating a new session: " , e ) ; throw new IOException ( e ) ; } } return session ; } | Get the session for this writer . One writer only maintains one session . | 149 | 14 |
14,076 | protected static ContentCreateOptions newContentCreateOptions ( DocumentMetadata meta , ContentCreateOptions options , boolean isCopyColls , boolean isCopyQuality , boolean isCopyMeta , boolean isCopyPerms , long effectiveVersion ) { ContentCreateOptions opt = ( ContentCreateOptions ) options . clone ( ) ; if ( meta != null ) { if ( isCopyQuality && opt . getQuality ( ) == 0 ) { opt . setQuality ( meta . quality ) ; } if ( isCopyColls ) { if ( opt . getCollections ( ) != null ) { HashSet < String > colSet = new HashSet < String > ( meta . collectionsList ) ; // union copy_collection and output_collection for ( String s : opt . getCollections ( ) ) { colSet . add ( s ) ; } opt . setCollections ( colSet . toArray ( new String [ colSet . size ( ) ] ) ) ; } else { opt . setCollections ( meta . getCollections ( ) ) ; } } if ( isCopyPerms ) { if ( effectiveVersion < MarkLogicConstants . MIN_NODEUPDATE_VERSION && meta . isNakedProps ( ) ) { boolean reset = false ; Vector < ContentPermission > perms = new Vector <> ( ) ; for ( ContentPermission perm : meta . permissionsList ) { if ( ! perm . getCapability ( ) . toString ( ) . equals ( ContentPermission . NODE_UPDATE . toString ( ) ) ) { perms . add ( perm ) ; } else { reset = true ; } } if ( reset ) { meta . clearPermissions ( ) ; meta . addPermissions ( perms ) ; meta . setPermString ( null ) ; } } if ( opt . getPermissions ( ) != null ) { HashSet < ContentPermission > pSet = new HashSet < ContentPermission > ( meta . permissionsList ) ; // union of output_permission & copy_permission for ( ContentPermission p : opt . getPermissions ( ) ) { pSet . add ( p ) ; } opt . setPermissions ( pSet . toArray ( new ContentPermission [ pSet . size ( ) ] ) ) ; } else { opt . setPermissions ( meta . getPermissions ( ) ) ; } } if ( isCopyMeta ) { opt . setMetadata ( meta . meta ) ; } } return opt ; } | fetch the options information from conf and metadata set to the field options | 520 | 14 |
14,077 | public static String applyUriReplace ( String uriSource , Configuration conf ) { if ( uriSource == null ) return null ; String [ ] uriReplace = conf . getStrings ( OUTPUT_URI_REPLACE ) ; if ( uriReplace == null ) return uriSource ; for ( int i = 0 ; i < uriReplace . length - 1 ; i += 2 ) { String replacement = uriReplace [ i + 1 ] . trim ( ) ; replacement = replacement . substring ( 1 , replacement . length ( ) - 1 ) ; uriSource = uriSource . replaceAll ( uriReplace [ i ] , replacement ) ; } return uriSource ; } | Apply URI replacement configuration option to a URI source string . The configuration option is a list of comma separated pairs of regex patterns and replacements . Validation of the configuration is done at command parsing time . | 154 | 39 |
14,078 | public static String applyPrefixSuffix ( String uriSource , Configuration conf ) { if ( uriSource == null ) return null ; String prefix = conf . get ( OUTPUT_URI_PREFIX ) ; String suffix = conf . get ( OUTPUT_URI_SUFFIX ) ; if ( prefix == null && suffix == null ) { return uriSource ; } int len = uriSource . length ( ) + ( prefix != null ? prefix . length ( ) : 0 ) + ( suffix != null ? suffix . length ( ) : 0 ) ; StringBuilder uriBuf = new StringBuilder ( len ) ; if ( prefix != null ) { uriBuf . append ( prefix ) ; } uriBuf . append ( uriSource ) ; if ( suffix != null ) { uriBuf . append ( suffix ) ; } return uriBuf . toString ( ) ; } | Apply URI prefix and suffix configuration option to a URI source string . | 194 | 13 |
14,079 | public static String [ ] expandArguments ( String [ ] args ) throws Exception { List < String > options = new ArrayList < String > ( ) ; for ( int i = 0 ; i < args . length ; i ++ ) { if ( args [ i ] . equals ( OPTIONS_FILE ) ) { if ( i == args . length - 1 ) { throw new Exception ( "Missing options file" ) ; } String fileName = args [ ++ i ] ; File optionsFile = new File ( fileName ) ; BufferedReader reader = null ; StringBuilder buffer = new StringBuilder ( ) ; try { reader = new BufferedReader ( new FileReader ( optionsFile ) ) ; String nextLine = null ; while ( ( nextLine = reader . readLine ( ) ) != null ) { nextLine = nextLine . trim ( ) ; if ( nextLine . length ( ) == 0 || nextLine . startsWith ( "#" ) ) { // empty line or comment continue ; } buffer . append ( nextLine ) ; if ( nextLine . endsWith ( "\\" ) ) { if ( buffer . charAt ( 0 ) == ' ' || buffer . charAt ( 0 ) == ' ' ) { throw new Exception ( "Multiline quoted strings not supported in file(" + fileName + "): " + buffer . toString ( ) ) ; } // Remove the trailing back-slash and continue buffer . deleteCharAt ( buffer . length ( ) - 1 ) ; } else { // The buffer contains a full option options . add ( removeQuotesEncolosingOption ( fileName , buffer . toString ( ) ) ) ; buffer . delete ( 0 , buffer . length ( ) ) ; } } // Assert that the buffer is empty if ( buffer . length ( ) != 0 ) { throw new Exception ( "Malformed option in options file(" + fileName + "): " + buffer . toString ( ) ) ; } } catch ( IOException ex ) { throw new Exception ( "Unable to read options file: " + fileName , ex ) ; } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException ex ) { LOG . info ( "Exception while closing reader" , ex ) ; } } } } else { // Regular option. Parse it and put it on the appropriate list options . add ( args [ i ] ) ; } } return options . toArray ( new String [ options . size ( ) ] ) ; } | Expands any options file that may be present in the given set of arguments . | 525 | 16 |
14,080 | private static String removeQuotesEncolosingOption ( String fileName , String option ) throws Exception { // Attempt to remove double quotes. If successful, return. String option1 = removeQuoteCharactersIfNecessary ( fileName , option , ' ' ) ; if ( ! option1 . equals ( option ) ) { // Quotes were successfully removed return option1 ; } // Attempt to remove single quotes. return removeQuoteCharactersIfNecessary ( fileName , option , ' ' ) ; } | Removes the surrounding quote characters as needed . It first attempts to remove surrounding double quotes . If successful the resultant string is returned . If no surrounding double quotes are found it attempts to remove surrounding single quote characters . If successful the resultant string is returned . If not the original string is returnred . | 104 | 59 |
14,081 | private static String removeQuoteCharactersIfNecessary ( String fileName , String option , char quote ) throws Exception { boolean startingQuote = ( option . charAt ( 0 ) == quote ) ; boolean endingQuote = ( option . charAt ( option . length ( ) - 1 ) == quote ) ; if ( startingQuote && endingQuote ) { if ( option . length ( ) == 1 ) { throw new Exception ( "Malformed option in options file(" + fileName + "): " + option ) ; } return option . substring ( 1 , option . length ( ) - 1 ) ; } if ( startingQuote || endingQuote ) { throw new Exception ( "Malformed option in options file(" + fileName + "): " + option ) ; } return option ; } | Removes the surrounding quote characters from the given string . The quotes are identified by the quote parameter the given string by option . The fileName parameter is used for raising exceptions with relevant message . | 162 | 38 |
14,082 | private int assignThreads ( int splitIndex , int splitCount ) { if ( threadsPerSplit > 0 ) { return threadsPerSplit ; } if ( splitCount == 1 ) { return threadCount ; } if ( splitCount * minThreads > threadCount ) { return minThreads ; } if ( splitIndex % threadCount < threadCount % splitCount ) { return threadCount / splitCount + 1 ; } else { return threadCount / splitCount ; } } | Assign thread count for a given split | 98 | 8 |
14,083 | public void configFields ( Configuration conf , String [ ] fields ) throws IllegalArgumentException , IOException { for ( int i = 0 ; i < fields . length ; i ++ ) { fields [ i ] = fields [ i ] . trim ( ) ; if ( "" . equals ( fields [ i ] ) ) { LOG . warn ( "Column " + ( i + 1 ) + " has no header and will be skipped" ) ; } } } | Check document header fields . | 95 | 5 |
14,084 | public void setClient ( AerospikeClient client ) { this . client = client ; this . updatePolicy = new WritePolicy ( this . client . writePolicyDefault ) ; this . updatePolicy . recordExistsAction = RecordExistsAction . UPDATE_ONLY ; this . insertPolicy = new WritePolicy ( this . client . writePolicyDefault ) ; this . insertPolicy . recordExistsAction = RecordExistsAction . CREATE_ONLY ; this . queryPolicy = client . queryPolicyDefault ; refreshCluster ( ) ; registerUDF ( ) ; } | Sets the AerospikeClient | 119 | 7 |
14,085 | public KeyRecordIterator select ( String namespace , String set , Filter filter , Qualifier ... qualifiers ) { Statement stmt = new Statement ( ) ; stmt . setNamespace ( namespace ) ; stmt . setSetName ( set ) ; if ( filter != null ) stmt . setFilters ( filter ) ; return select ( stmt , qualifiers ) ; } | Select records filtered by a Filter and Qualifiers | 76 | 9 |
14,086 | public void insert ( String namespace , String set , Key key , List < Bin > bins ) { insert ( namespace , set , key , bins , 0 ) ; } | inserts a record . If the record exists and exception will be thrown . | 34 | 15 |
14,087 | public void insert ( String namespace , String set , Key key , List < Bin > bins , int ttl ) { this . client . put ( this . insertPolicy , key , bins . toArray ( new Bin [ 0 ] ) ) ; } | inserts a record with a time to live . If the record exists and exception will be thrown . | 51 | 20 |
14,088 | public void insert ( Statement stmt , KeyQualifier keyQualifier , List < Bin > bins ) { insert ( stmt , keyQualifier , bins , 0 ) ; } | inserts a record using a Statement and KeyQualifier . If the record exists and exception will be thrown . | 37 | 22 |
14,089 | public void insert ( Statement stmt , KeyQualifier keyQualifier , List < Bin > bins , int ttl ) { Key key = keyQualifier . makeKey ( stmt . getNamespace ( ) , stmt . getSetName ( ) ) ; // Key key = new Key(stmt.getNamespace(), stmt.getSetName(), keyQualifier.getValue1()); this . client . put ( this . insertPolicy , key , bins . toArray ( new Bin [ 0 ] ) ) ; } | inserts a record with a time to live using a Statement and KeyQualifier . If the record exists and exception will be thrown . | 111 | 27 |
14,090 | public Map < String , Long > update ( Statement stmt , List < Bin > bins , Qualifier ... qualifiers ) { if ( qualifiers != null && qualifiers . length == 1 && qualifiers [ 0 ] instanceof KeyQualifier ) { KeyQualifier keyQualifier = ( KeyQualifier ) qualifiers [ 0 ] ; Key key = keyQualifier . makeKey ( stmt . getNamespace ( ) , stmt . getSetName ( ) ) ; this . client . put ( this . updatePolicy , key , bins . toArray ( new Bin [ 0 ] ) ) ; Map < String , Long > result = new HashMap < String , Long > ( ) ; result . put ( "read" , 1L ) ; result . put ( "write" , 1L ) ; return result ; } else { KeyRecordIterator results = select ( stmt , true , null , qualifiers ) ; return update ( results , bins ) ; } } | The list of Bins will update each record that match the Qualifiers supplied . | 196 | 16 |
14,091 | public Map < String , Long > delete ( Statement stmt , Qualifier ... qualifiers ) { if ( qualifiers == null || qualifiers . length == 0 ) { /* * There are no qualifiers, so delete every record in the set * using Scan UDF delete */ ExecuteTask task = client . execute ( null , stmt , QUERY_MODULE , "delete_record" ) ; task . waitTillComplete ( ) ; return null ; } if ( qualifiers . length == 1 && qualifiers [ 0 ] instanceof KeyQualifier ) { KeyQualifier keyQualifier = ( KeyQualifier ) qualifiers [ 0 ] ; Key key = keyQualifier . makeKey ( stmt . getNamespace ( ) , stmt . getSetName ( ) ) ; this . client . delete ( null , key ) ; Map < String , Long > map = new HashMap < String , Long > ( ) ; map . put ( "read" , 1L ) ; map . put ( "write" , 1L ) ; return map ; } KeyRecordIterator results = select ( stmt , true , null , qualifiers ) ; return delete ( results ) ; } | Deletes the records specified by the Statement and Qualifiers | 240 | 11 |
14,092 | public synchronized void refreshNamespaces ( ) { /* * cache namespaces */ if ( this . namespaceCache == null ) { this . namespaceCache = new TreeMap < String , Namespace > ( ) ; Node [ ] nodes = client . getNodes ( ) ; for ( Node node : nodes ) { try { String namespaceString = Info . request ( getInfoPolicy ( ) , node , "namespaces" ) ; if ( ! namespaceString . isEmpty ( ) ) { String [ ] namespaceList = namespaceString . split ( ";" ) ; for ( String namespace : namespaceList ) { Namespace ns = this . namespaceCache . get ( namespace ) ; if ( ns == null ) { ns = new Namespace ( namespace ) ; this . namespaceCache . put ( namespace , ns ) ; } refreshNamespaceData ( node , ns ) ; } } } catch ( AerospikeException e ) { log . error ( "Error geting Namespaces " , e ) ; } } } } | refreshes the cached Namespace information | 207 | 8 |
14,093 | public synchronized void refreshIndexes ( ) { /* * cache index by Bin name */ if ( this . indexCache == null ) this . indexCache = new TreeMap < String , Index > ( ) ; Node [ ] nodes = client . getNodes ( ) ; for ( Node node : nodes ) { if ( node . isActive ( ) ) { try { String indexString = Info . request ( getInfoPolicy ( ) , node , "sindex" ) ; if ( ! indexString . isEmpty ( ) ) { String [ ] indexList = indexString . split ( ";" ) ; for ( String oneIndexString : indexList ) { Index index = new Index ( oneIndexString ) ; this . indexCache . put ( index . toKeyString ( ) , index ) ; } } break ; } catch ( AerospikeException e ) { log . error ( "Error geting Index informaton" , e ) ; } } } } | refreshes the Index cache from the Cluster | 198 | 9 |
14,094 | @ Override public void close ( ) throws IOException { if ( this . client != null ) this . client . close ( ) ; indexCache . clear ( ) ; indexCache = null ; updatePolicy = null ; insertPolicy = null ; infoPolicy = null ; queryPolicy = null ; moduleCache . clear ( ) ; moduleCache = null ; } | closes the QueryEngine clearing the cached information are closing the AerospikeClient . Once the QueryEngine is closed it cannot be used nor can the AerospikeClient . | 73 | 35 |
14,095 | public void setIndexInfo ( String info ) { //ns=phobos_sindex:set=longevity:indexname=str_100_idx:num_bins=1:bins=str_100_bin:type=TEXT:sync_state=synced:state=RW; //ns=test:set=Customers:indexname=mail_index_userss:bin=email:type=STRING:indextype=LIST:path=email:sync_state=synced:state=RW if ( ! info . isEmpty ( ) ) { String [ ] parts = info . split ( ":" ) ; for ( String part : parts ) { kvPut ( part ) ; } } } | Populates the Index object from an info message from Aerospike | 156 | 13 |
14,096 | public void clear ( ) { Record record = this . client . get ( null , key , tailBin , topBin ) ; long tail = record . getLong ( tailBin ) ; long top = record . getLong ( topBin ) ; List < Key > subKeys = subrecordKeys ( tail , top ) ; for ( Key key : subKeys ) { this . client . delete ( null , key ) ; } } | clear all elements from the TimeSeries associated with a Key | 92 | 11 |
14,097 | public void destroy ( ) { clear ( ) ; this . client . operate ( null , key , Operation . put ( Bin . asNull ( binName ) ) ) ; } | Destroy the TimeSeries associated with a Key | 36 | 8 |
14,098 | List < Key > subrecordKeys ( long lowTime , long highTime ) { List < Key > keys = new ArrayList < Key > ( ) ; long lowBucketNumber = bucketNumber ( lowTime ) ; long highBucketNumber = bucketNumber ( highTime ) ; for ( long index = lowBucketNumber ; index <= highBucketNumber ; index += this . bucketSize ) { keys . add ( formSubrecordKey ( index ) ) ; } return keys ; } | creates a list of Keys in the time series | 101 | 10 |
14,099 | public void update ( Value value ) { if ( size ( ) == 0 ) { add ( value ) ; } else { Key subKey = makeSubKey ( value ) ; client . put ( this . policy , subKey , new Bin ( ListElementBinName , value ) ) ; } } | Update value in list if key exists . Add value to list if key does not exist . If value is a map the key is identified by key entry . Otherwise the value is the key . If large list does not exist create it . | 62 | 47 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.