idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
38,500 | private static boolean isValidStack ( VdmThread thread ) { final IDebugOptions debugOptions = thread . getDbgpSession ( ) . getDebugOptions ( ) ; if ( debugOptions . get ( DebugOption . ENGINE_VALIDATE_STACK ) ) { thread . updateStack ( ) ; if ( thread . hasStackFrames ( ) ) { return thread . isValidStack ( ) ; } } return true ; } | Tests if the specified thread has valid current stack . In some cases it is better to skip first internal location . |
38,501 | public void caseILexLocation ( ILexLocation node ) throws AnalysisException { AstLocation location = new AstLocation ( current , node ) ; if ( reference . contains ( node . getStartOffset ( ) , node . getEndOffset ( ) , node . getFile ( ) ) ) { throw new LocationFound ( location ) ; } else if ( reference . canMatch ( node . getFile ( ) ) ) { closest = getClosest ( reference , location ) ; } } | Never called by analysis from super |
38,502 | protected ValueList generateNumbers ( int min , int max , Context ctxt ) throws ValueException { ValueList list = new ValueList ( ) ; for ( int i = min ; i < max + 1 ; i ++ ) { list . add ( NumericValue . valueOf ( i , ctxt ) ) ; } return list ; } | Generator method for numeric type bindings . |
38,503 | private List < IDebugTarget > collectTargets ( IProcess process ) { ILaunchManager launchManager = DebugPlugin . getDefault ( ) . getLaunchManager ( ) ; ILaunch [ ] launches = launchManager . getLaunches ( ) ; List < IDebugTarget > targets = new ArrayList < IDebugTarget > ( ) ; for ( int i = 0 ; i < launches . length ; i ++ ) { ILaunch launch = launches [ i ] ; IProcess [ ] processes = launch . getProcesses ( ) ; for ( int j = 0 ; j < processes . length ; j ++ ) { IProcess process2 = processes [ j ] ; if ( process2 . equals ( process ) ) { IDebugTarget [ ] debugTargets = launch . getDebugTargets ( ) ; for ( int k = 0 ; k < debugTargets . length ; k ++ ) { targets . add ( debugTargets [ k ] ) ; } return targets ; } } } return targets ; } | Collects targets associated with a process . |
38,504 | public void addLabelDecorator ( ILabelDecorator decorator ) { if ( fLabelDecorators == null ) { fLabelDecorators = new ArrayList < ILabelDecorator > ( 2 ) ; } fLabelDecorators . add ( decorator ) ; } | Adds a decorator to the label provider |
38,505 | protected void fireLabelProviderChanged ( final LabelProviderChangedEvent event ) { Object [ ] listeners = fListeners . getListeners ( ) ; for ( int i = 0 ; i < listeners . length ; ++ i ) { final ILabelProviderListener l = ( ILabelProviderListener ) listeners [ i ] ; SafeRunner . run ( new SafeRunnable ( ) { public void run ( ) { l . labelProviderChanged ( event ) ; } } ) ; } } | Fires a label provider changed event to all registered listeners Only listeners registered at the time this method is called are notified . |
38,506 | protected Control createContents ( Composite parent ) { Composite top = new Composite ( parent , SWT . LEFT ) ; top . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; top . setLayout ( new GridLayout ( ) ) ; if ( Platform . getOS ( ) . equalsIgnoreCase ( Platform . OS_MACOSX ) ) { vdmPathMac = new DirectoryFieldEditor ( ICskConstants . VSLGDE_PATH , "Path to VDM Tools for VDM-SL (vdmgde):" , top ) ; vdmPathMac . setPage ( this ) ; vdmPathMac . setPreferenceStore ( getPreferenceStore ( ) ) ; vdmPathMac . load ( ) ; vppPathMac = new DirectoryFieldEditor ( ICskConstants . VPPGDE_PATH , "Path to VDM Tools for VDM-PP (vppgde):" , top ) ; vppPathMac . setPage ( this ) ; vppPathMac . setPreferenceStore ( getPreferenceStore ( ) ) ; vppPathMac . load ( ) ; Label listLabel = new Label ( top , SWT . BOLD ) ; listLabel . setText ( "NOTE: select the \"bin\" folder just above \"vxxgde\"" ) ; } else { vdmPath = new FileFieldEditor ( ICskConstants . VSLGDE_PATH , "Path to VDM Tools for VDM-SL (vdmgde):" , top ) ; vdmPath . setPage ( this ) ; vdmPath . setPreferenceStore ( getPreferenceStore ( ) ) ; vdmPath . load ( ) ; vppPath = new FileFieldEditor ( ICskConstants . VPPGDE_PATH , "Path to VDM Tools for VDM-PP (vppgde):" , top ) ; vppPath . setPage ( this ) ; vppPath . setPreferenceStore ( getPreferenceStore ( ) ) ; vppPath . load ( ) ; } return top ; } | DirectoryFieldEditor vicePathMac = null ; |
38,507 | private void setFileMarkers ( IFile file , ParseResult result ) throws CoreException { if ( file != null ) { FileUtility . deleteMarker ( file , IMarker . PROBLEM , ICoreConstants . PLUGIN_ID ) ; if ( result . hasParseErrors ( ) ) { file . deleteMarkers ( IMarker . PROBLEM , true , IResource . DEPTH_INFINITE ) ; int previousErrorNumber = - 1 ; for ( VDMError error : result . getErrors ( ) ) { if ( previousErrorNumber == error . number ) { continue ; } else { previousErrorNumber = error . number ; } FileUtility . addMarker ( file , error . toProblemString ( ) , error . location , IMarker . SEVERITY_ERROR , ICoreConstants . PLUGIN_ID , - 1 ) ; } } IVdmProject vdmProject = ( IVdmProject ) project . getAdapter ( IVdmProject . class ) ; if ( result . getWarnings ( ) . size ( ) > 0 && vdmProject != null && vdmProject . hasSuppressWarnings ( ) ) { for ( VDMWarning warning : result . getWarnings ( ) ) { FileUtility . addMarker ( file , warning . toProblemString ( ) , warning . location , IMarker . SEVERITY_WARNING , ICoreConstants . PLUGIN_ID , - 1 ) ; } } } } | Adds markers to a file based on the result . if errors occurred the problem markers are first cleared . |
38,508 | public synchronized static void leaving ( String classname , int fnr2 ) { int fn = fnr2 ; m . put ( classname , StaticOperationsCounters . fin [ fn ] ++ ) ; m . put ( classname , StaticOperationsCounters . active [ fn ] -- ) ; stateChanged ( ) ; } | this method is registering the termination of a method . |
38,509 | private synchronized static void waiting ( String classname , int fnr , int offset ) { m . put ( classname , StaticOperationsCounters . waiting [ fnr ] += offset ) ; stateChanged ( ) ; } | The offset defines how many methods of the same name are waiting . |
38,510 | private void setContext ( IWorkbenchPage page , IVdmStackFrame frame ) { if ( fContextsByPage == null ) { fContextsByPage = new HashMap < IWorkbenchPage , IVdmStackFrame > ( ) ; } fContextsByPage . put ( page , frame ) ; System . setProperty ( DEBUGGER_ACTIVE , "true" ) ; } | Sets the evaluation context for the given page and notes that a valid execution context exists . |
38,511 | private void removeContext ( IWorkbenchPage page ) { if ( fContextsByPage != null ) { fContextsByPage . remove ( page ) ; if ( fContextsByPage . isEmpty ( ) ) { System . setProperty ( DEBUGGER_ACTIVE , "false" ) ; System . setProperty ( INSTANCE_OF_IJAVA_STACK_FRAME , "false" ) ; System . setProperty ( SUPPORTS_FORCE_RETURN , "false" ) ; System . setProperty ( SUPPORTS_INSTANCE_RETRIEVAL , "false" ) ; } } } | Removes an evaluation context for the given page and determines if any valid execution context remain . |
38,512 | public static long timeToInternal ( TimeUnit unit , Double time ) { return Math . round ( time * unit . getValue ( ) / TimeUnit . nanosecond . getValue ( ) ) ; } | Utility method to convert a value in the given unit to the internal time |
38,513 | public static Double internalToTime ( TimeUnit unit , long internalTime ) { return Math . round ( internalTime * TimeUnit . nanosecond . getValue ( ) / unit . getValue ( ) * PRECISION ) / PRECISION ; } | Utility method to convert the internal time to the given unit . |
38,514 | protected void addBreakpoint ( final IDbgpSession session , IVdmBreakpoint breakpoint ) throws CoreException , DbgpException { final IDbgpCoreCommands commands = session . getCoreCommands ( ) ; DbgpBreakpointConfig config = createBreakpointConfig ( breakpoint ) ; String id = null ; URI bpUri = null ; if ( breakpoint instanceof IVdmLineBreakpoint ) { IVdmLineBreakpoint bp = ( IVdmLineBreakpoint ) breakpoint ; bpUri = bpPathMapper . map ( bp . getResourceURI ( ) ) ; } if ( breakpoint instanceof IVdmWatchpoint ) { IVdmWatchpoint watchpoint = ( IVdmWatchpoint ) breakpoint ; config . setExpression ( makeWatchpointExpression ( watchpoint ) ) ; id = commands . setWatchBreakpoint ( bpUri , watchpoint . getLineNumber ( ) , config ) ; } else if ( breakpoint instanceof IVdmMethodEntryBreakpoint ) { IVdmMethodEntryBreakpoint entryBreakpoint = ( IVdmMethodEntryBreakpoint ) breakpoint ; if ( entryBreakpoint . breakOnExit ( ) ) { final String exitId = commands . setReturnBreakpoint ( bpUri , entryBreakpoint . getMethodName ( ) , config ) ; entryBreakpoint . setExitBreakpointId ( exitId ) ; } if ( entryBreakpoint . breakOnEntry ( ) ) { final String entryId = commands . setCallBreakpoint ( bpUri , entryBreakpoint . getMethodName ( ) , config ) ; entryBreakpoint . setEntryBreakpointId ( entryId ) ; } } else if ( breakpoint instanceof IVdmLineBreakpoint ) { IVdmLineBreakpoint lineBreakpoint = ( IVdmLineBreakpoint ) breakpoint ; if ( VdmBreakpointUtils . isConditional ( lineBreakpoint ) ) { id = commands . setConditionalBreakpoint ( bpUri , lineBreakpoint . getLineNumber ( ) , config ) ; } else { id = commands . setLineBreakpoint ( bpUri , lineBreakpoint . getLineNumber ( ) , config ) ; } } breakpoint . setId ( session , id ) ; } | Adding removing updating |
38,515 | public static Value fwriteval ( Value fval , Value tval , Value dval ) { File file = getFile ( fval ) ; String fdir = dval . toString ( ) ; StringBuffer text = new StringBuffer ( ) ; if ( tval instanceof SeqValue ) { for ( Value val : ( ( SeqValue ) tval ) . values ) { text . append ( val . toString ( ) ) ; text . append ( "," ) ; } } if ( text . length ( ) > 0 && text . charAt ( text . length ( ) - 1 ) == ',' ) { text . deleteCharAt ( text . length ( ) - 1 ) ; } text . append ( '\n' ) ; try { FileOutputStream fos = new FileOutputStream ( file , fdir . equals ( "<append>" ) ) ; fos . write ( text . toString ( ) . getBytes ( Console . charset ) ) ; fos . close ( ) ; } catch ( IOException e ) { lastError = e . getMessage ( ) ; return new BooleanValue ( false ) ; } return new BooleanValue ( true ) ; } | Writes a seq of ? in a CSV format to the file specified |
38,516 | public static Value freadval ( Value fval , Value indexVal ) { ValueList result = new ValueList ( ) ; try { File file = getFile ( fval ) ; long index = indexVal . intValue ( null ) ; SeqValue lineCells = new SeqValue ( ) ; boolean success = false ; try { CsvParser parser = new CsvParser ( new CsvValueBuilder ( ) { public Value createValue ( String value ) throws Exception { return CSV . createValue ( "CSV" , "freadval" , value ) ; } } ) ; CsvResult res = parser . parseValues ( getLine ( file , index ) ) ; if ( ! res . dataOk ( ) ) { lastError = res . getErrorMsg ( ) ; success = false ; } else { lineCells . values . addAll ( res . getValues ( ) ) ; success = true ; } } catch ( Exception e ) { success = false ; lastError = e . getMessage ( ) ; } result . add ( new BooleanValue ( success ) ) ; result . add ( lineCells ) ; } catch ( Exception e ) { lastError = e . toString ( ) ; result = new ValueList ( ) ; result . add ( new BooleanValue ( false ) ) ; result . add ( new NilValue ( ) ) ; } return new TupleValue ( result ) ; } | Read a CSV live as a seq of ? in VDM |
38,517 | public static Value flinecount ( Value fval ) { ValueList result = new ValueList ( ) ; try { File file = getFile ( fval ) ; long count = getLineCount ( file ) ; result . add ( new BooleanValue ( true ) ) ; result . add ( new IntegerValue ( count ) ) ; } catch ( Exception e ) { lastError = e . toString ( ) ; result = new ValueList ( ) ; result . add ( new BooleanValue ( false ) ) ; result . add ( new NilValue ( ) ) ; } return new TupleValue ( result ) ; } | Gets the line count of the CSV file |
38,518 | public synchronized void syncBuildPath ( IVdmProject project ) throws CoreException { List < IVdmSourceUnit > syncedVdmSourceUnits = project . getSpecFiles ( ) ; List < IFile > removedFiles = new Vector < IFile > ( ) ; IProject p = ( IProject ) project . getAdapter ( IProject . class ) ; for ( IFile file : vdmSourceUnits . keySet ( ) ) { if ( file . getProject ( ) . equals ( p ) && ! syncedVdmSourceUnits . contains ( vdmSourceUnits . get ( file ) ) ) { removedFiles . add ( file ) ; System . out . println ( "Found an existing file removed from build path: " + file ) ; } } for ( IFile iFile : removedFiles ) { remove ( iFile ) ; } } | Sync existing IVdmSource files with the build path of the project . This is used when the build path changed and the project should be updated . This method removed old IVdmSource files which no longer is withing the build path . |
38,519 | public synchronized void setState ( DebugState newState ) { if ( ! states . contains ( newState ) ) { switch ( newState ) { case Disconnected : Assert . isLegal ( canChange ( DebugState . Disconnected ) , "Cannot disconnect a terminated state" ) ; case Terminated : Assert . isLegal ( canChange ( DebugState . Terminated ) , "Cannot terminate a terminated state" ) ; states . clear ( ) ; states . add ( newState ) ; break ; case Suspended : Assert . isLegal ( canChange ( DebugState . Suspended ) , "Can only suspend if resumed" ) ; states . remove ( DebugState . Resumed ) ; states . add ( newState ) ; break ; case IsStepping : Assert . isLegal ( canChange ( DebugState . IsStepping ) , "Cannot step if not suspended" ) ; states . add ( newState ) ; break ; case Resumed : Assert . isLegal ( canChange ( DebugState . Resumed ) , "Cannot resume in a terminated state" ) ; if ( states . contains ( DebugState . IsStepping ) ) { states . clear ( ) ; states . add ( DebugState . IsStepping ) ; } else { states . clear ( ) ; } states . add ( newState ) ; break ; case Deadlocked : states . add ( newState ) ; break ; } } } | Sets a new state an Assert . IsLegal is asserted if the given state is not valid based on the current state |
38,520 | public synchronized boolean canChange ( DebugState newState ) { switch ( newState ) { case Disconnected : return ! inState ( DebugState . Terminated ) && ! inState ( DebugState . Disconnected ) ; case Terminated : return ! inState ( DebugState . Terminated ) ; case Suspended : return inState ( DebugState . Resumed ) ; case IsStepping : return ( ! inState ( DebugState . Terminated ) || ! inState ( DebugState . Disconnected ) || ! inState ( DebugState . Deadlocked ) ) && inState ( DebugState . Suspended ) ; case Resumed : return states . size ( ) == 0 || inState ( DebugState . IsStepping ) || inState ( DebugState . Suspended ) ; default : return false ; } } | Checks if a change to the newState is allowed |
38,521 | public byte [ ] getGraph ( String dot_source , String type ) throws GraphVizException { File dot ; byte [ ] img_stream = null ; try { dot = writeDotSourceToFile ( dot_source ) ; if ( dot != null ) { img_stream = get_img_stream ( dot , type ) ; if ( ! dot . delete ( ) ) { throw new GraphVizException ( "Warning: " + dot . getAbsolutePath ( ) + " could not be deleted!" ) ; } return img_stream ; } return null ; } catch ( IOException ioe ) { return null ; } } | Returns the graph as an image in binary format . |
38,522 | private byte [ ] get_img_stream ( File dot , String type ) throws GraphVizException { File img ; byte [ ] img_stream = null ; try { img = File . createTempFile ( "graph_" , "." + type ) ; Runtime rt = Runtime . getRuntime ( ) ; String [ ] args = { dotPath , "-T" + type , dot . getAbsolutePath ( ) , "-o" , img . getAbsolutePath ( ) } ; Process p = rt . exec ( args ) ; p . waitFor ( ) ; FileInputStream in = new FileInputStream ( img . getAbsolutePath ( ) ) ; img_stream = new byte [ in . available ( ) ] ; in . read ( img_stream ) ; if ( in != null ) { in . close ( ) ; } if ( ! img . delete ( ) ) { throw new GraphVizException ( "Warning: " + img . getAbsolutePath ( ) + " could not be deleted!" ) ; } } catch ( IOException ioe ) { throw new GraphVizException ( "Error: in I/O processing of tempfile in dir. Or in calling external command" , ioe ) ; } catch ( InterruptedException ie ) { throw new GraphVizException ( "Error: the execution of the external program was interrupted" , ie ) ; } return img_stream ; } | It will call the external dot program and return the image in binary format . |
38,523 | private File writeDotSourceToFile ( String str ) throws java . io . IOException , GraphVizException { File temp ; try { temp = File . createTempFile ( "graph_" , ".dot.tmp" ) ; FileWriter fout = new FileWriter ( temp ) ; fout . write ( str ) ; fout . close ( ) ; } catch ( Exception e ) { throw new GraphVizException ( "Error: I/O error while writing the dot source to temp file!" ) ; } return temp ; } | Writes the source of the graph in a file and returns the written file as a File object . |
38,524 | public void readSource ( String input ) throws GraphVizException { StringBuilder sb = new StringBuilder ( ) ; try { FileInputStream fis = new FileInputStream ( input ) ; DataInputStream dis = new DataInputStream ( fis ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( dis ) ) ; String line ; while ( ( line = br . readLine ( ) ) != null ) { sb . append ( line ) ; } dis . close ( ) ; } catch ( Exception e ) { throw new GraphVizException ( "Error: " + e . getMessage ( ) ) ; } this . graph = sb ; } | Read a DOT graph from a text file . |
38,525 | public AEqualsBinaryExp readDefEqualsExpression ( ) throws ParserException , LexException { PExp exp = readEvaluatorP1Expression ( ) ; LexToken token = lastToken ( ) ; if ( readToken ( ) . is ( VDMToken . EQUALS ) ) { return AstFactory . newAEqualsBinaryExp ( exp , token , readEvaluatorP1Expression ( ) ) ; } throwMessage ( 2029 , "Expecting <set bind> = <expression>" ) ; return null ; } | Relations Family ... |
38,526 | private PExp readEvaluatorP1Expression ( ) throws ParserException , LexException { PExp exp = readEvaluatorP2Expression ( ) ; boolean more = true ; while ( more ) { LexToken token = lastToken ( ) ; switch ( token . type ) { case PLUS : nextToken ( ) ; exp = AstFactory . newAPlusNumericBinaryExp ( exp , token , readEvaluatorP2Expression ( ) ) ; break ; case MINUS : nextToken ( ) ; exp = AstFactory . newASubstractNumericBinaryExp ( exp , token , readEvaluatorP2Expression ( ) ) ; break ; case UNION : nextToken ( ) ; exp = AstFactory . newASetUnionBinaryExp ( exp , token , readEvaluatorP2Expression ( ) ) ; break ; case SETDIFF : nextToken ( ) ; exp = AstFactory . newASetDifferenceBinaryExp ( exp , token , readEvaluatorP2Expression ( ) ) ; break ; case MUNION : nextToken ( ) ; exp = AstFactory . newAMapUnionBinaryExp ( exp , token , readEvaluatorP2Expression ( ) ) ; break ; case PLUSPLUS : nextToken ( ) ; exp = AstFactory . newAPlusPlusBinaryExp ( exp , token , readEvaluatorP2Expression ( ) ) ; break ; case CONCATENATE : nextToken ( ) ; exp = AstFactory . newASeqConcatBinaryExp ( exp , token , readEvaluatorP2Expression ( ) ) ; break ; default : more = false ; break ; } } return exp ; } | Evaluator Family ... |
38,527 | private void xcmdOvertureResponse ( DBGPXCmdOvertureCommandType overtureCmd , StringBuilder hdr , StringBuilder body ) throws IOException { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "<xcmd_overture_response command=\"" ) ; sb . append ( command ) ; sb . append ( "\"" ) ; sb . append ( " overtureCmd=\"" ) ; sb . append ( overtureCmd ) ; sb . append ( "\"" ) ; if ( hdr != null ) { sb . append ( " " ) ; sb . append ( hdr ) ; } sb . append ( " transaction_id=\"" ) ; sb . append ( transaction ) ; sb . append ( "\"" ) ; if ( body != null ) { sb . append ( ">" ) ; sb . append ( body ) ; sb . append ( "</xcmd_overture_response>\n" ) ; } else { sb . append ( "/>\n" ) ; } write ( sb ) ; } | Send a xcmd Overture Response |
38,528 | protected StringBuilder propertyResponse ( NameValuePairMap vars , DBGPContextType context ) throws UnsupportedEncodingException { StringBuilder sb = new StringBuilder ( ) ; for ( Entry < ILexNameToken , Value > e : vars . entrySet ( ) ) { if ( ! e . getKey ( ) . getName ( ) . equals ( "self" ) ) { if ( isDebugVisible ( e . getValue ( ) ) ) { sb . append ( propertyResponse ( e . getKey ( ) , e . getValue ( ) , context ) ) ; } } } return sb ; } | Overrides super class by filtering all entries against isDebugVisible |
38,529 | private Integer getChildCount ( Value value ) { if ( value instanceof NumericValue || value instanceof CharacterValue || value instanceof NilValue || value instanceof TokenValue ) { return 0 ; } else if ( value instanceof SetValue ) { return ( ( SetValue ) value ) . values . size ( ) ; } else if ( value instanceof SeqValue ) { boolean isString = true ; for ( Value v : ( ( SeqValue ) value ) . values ) { if ( ! ( deref ( v ) instanceof CharacterValue ) ) { isString = false ; } } if ( isString ) { return 0 ; } else { return ( ( SeqValue ) value ) . values . size ( ) ; } } else if ( value instanceof MapValue ) { return ( ( MapValue ) value ) . values . size ( ) ; } else if ( value instanceof ObjectValue ) { int count = 0 ; for ( NameValuePair v : ( ( ObjectValue ) value ) . members . asList ( ) ) { if ( isDebugVisible ( v . value ) ) { count ++ ; } } return count ; } else if ( value instanceof UpdatableValue || value instanceof TransactionValue || value instanceof ReferenceValue ) { return getChildCount ( deref ( value ) ) ; } else if ( value instanceof RecordValue ) { RecordValue rVal = ( RecordValue ) value ; return rVal . fieldmap . size ( ) ; } else if ( value instanceof TupleValue ) { TupleValue tVal = ( TupleValue ) value ; return tVal . values . size ( ) ; } return 0 ; } | Calculates if a value has children and returns the child count |
38,530 | private Value deref ( Value value ) { if ( value instanceof ReferenceValue || value instanceof UpdatableValue || value instanceof TransactionValue ) { return value . deref ( ) ; } else { return value ; } } | Deref Value of Reference and Updatable Value types |
38,531 | private boolean isDebugVisible ( Value v ) { return v instanceof ReferenceValue || v instanceof NumericValue || v instanceof CharacterValue || v instanceof BooleanValue || v instanceof SetValue || v instanceof SeqValue || v instanceof MapValue || v instanceof TokenValue || v instanceof RecordValue || v instanceof ObjectValue || v instanceof NilValue || v instanceof FunctionValue ; } | Determines if a value should be shown in the debug client |
38,532 | protected void processLog ( DBGPCommand c ) throws IOException { StringBuilder out = new StringBuilder ( ) ; try { if ( c . data == null ) { if ( RTLogger . getLogSize ( ) > 0 ) { out . append ( "Flushing " + RTLogger . getLogSize ( ) + " RT events\n" ) ; } RTLogger . setLogfile ( RTTextLogger . class , null ) ; RTLogger . setLogfile ( NextGenRTLogger . class , ( File ) null ) ; out . append ( "RT events now logged to the console" ) ; } else if ( c . data . equals ( "off" ) ) { RTLogger . enable ( false ) ; out . append ( "RT event logging disabled" ) ; } else { File file = new File ( new URI ( c . data ) ) ; RTLogger . setLogfile ( RTTextLogger . class , file ) ; out . append ( "RT events now logged to " + c . data ) ; } } catch ( FileNotFoundException e ) { out . append ( "Cannot create RT event log: " + e . getMessage ( ) ) ; } catch ( URISyntaxException e ) { out . append ( "Cannot decode log file from URI: " + e . getMessage ( ) ) ; } xcmdOvertureResponse ( DBGPXCmdOvertureCommandType . LOG , null , out ) ; } | Overrides processLog to support URI file format and xcmdOvertureResponse as reply |
38,533 | public static TypeCompatibilityObligation newInstance ( PExp exp , PType etype , PType atype , IPOContextStack ctxt , IPogAssistantFactory assistantFactory ) throws AnalysisException { TypeCompatibilityObligation sto = new TypeCompatibilityObligation ( exp , etype , atype , ctxt , assistantFactory ) ; if ( sto . getValueTree ( ) != null ) { return sto ; } return null ; } | Factory Method since we need to return null STOs ( which should be discarded |
38,534 | public void enterDebugger ( Context ctxt ) { ISchedulableThread th = BasicSchedulableThread . getThread ( Thread . currentThread ( ) ) ; if ( th != null ) { th . suspendOthers ( ) ; } if ( Settings . usingDBGP ) { ctxt . threadState . dbgp . stopped ( ctxt , this ) ; } else { new DebuggerReader ( Interpreter . getInstance ( ) , this , ctxt ) . run ( ) ; } } | Actually stop and enter the debugger . The method returns when the user asks to continue or step the specification . |
38,535 | public boolean catchReturn ( Context ctxt ) { ThreadState state = ctxt . threadState ; return state . stepline != null && state . nextctxt == null && state . outctxt == null ; } | Test for whether an apply expression or operation call ought to catch a breakpoint after the return from the call . This only happens if we step into the call so that when we step out it is clear where we re unwinding too rather than jumping down the stack some considerable distance . |
38,536 | private boolean isAboveNext ( Context current ) { Context c = current . outer ; while ( c != null ) { if ( c == current . threadState . nextctxt ) { return true ; } c = c . outer ; } return false ; } | True if the context passed is above nextctxt . That means that the current context must have an outer chain that reaches nextctxt . |
38,537 | private boolean isOutOrBelow ( Context current ) { Context c = current . threadState . outctxt ; while ( c != null ) { if ( c == current ) { return true ; } c = c . outer ; } return false ; } | True if the context passed is equal to or below outctxt . That means that outctxt must have an outer chain that reaches current context . |
38,538 | private boolean containsSeverity ( IMarker [ ] markers , int severity ) { for ( int i = 0 ; i < markers . length ; i ++ ) { try { Object tmp = markers [ i ] . getAttribute ( IMarker . SEVERITY ) ; if ( tmp == null && ! ( tmp instanceof Integer ) ) { continue ; } if ( tmp != null && ( ( Integer ) tmp & severity ) != 0 ) { return true ; } } catch ( CoreException e ) { VdmUIPlugin . log ( "Faild to check marker attribute SEVERITY" , e ) ; } } return false ; } | Checks if any marker in the array has a defined severity which is set to the |
38,539 | public ABlockStmIR consComplexCompIterationBlock ( List < SMultipleBindIR > multipleSetBinds , ITempVarGen tempGen , IIterationStrategy strategy , IterationVarPrefixes iteVarPrefixes ) throws AnalysisException { ABlockStmIR outerBlock = new ABlockStmIR ( ) ; ABlockStmIR nextMultiBindBlock = outerBlock ; for ( SMultipleBindIR bind : multipleSetBinds ) { if ( hasEmptySet ( bind ) ) { multipleSetBinds . clear ( ) ; return outerBlock ; } } strategy . setFirstBind ( true ) ; for ( int i = 0 ; i < multipleSetBinds . size ( ) ; i ++ ) { strategy . setLastBind ( i == multipleSetBinds . size ( ) - 1 ) ; SMultipleBindIR mb = multipleSetBinds . get ( i ) ; if ( mb instanceof ASetMultipleBindIR ) { nextMultiBindBlock = consIterationBlock ( nextMultiBindBlock , mb . getPatterns ( ) , ( ( ASetMultipleBindIR ) mb ) . getSet ( ) , tempGen , strategy , iteVarPrefixes ) ; } else if ( mb instanceof ASeqMultipleBindIR ) { nextMultiBindBlock = consIterationBlock ( nextMultiBindBlock , mb . getPatterns ( ) , ( ( ASeqMultipleBindIR ) mb ) . getSeq ( ) , tempGen , strategy , iteVarPrefixes ) ; } else { log . error ( "Expected set multiple bind or sequence multiple bind. Got: " + mb ) ; } strategy . setFirstBind ( false ) ; } return outerBlock ; } | FIXME make this method work on generic PMUltipleBinds |
38,540 | protected boolean hasChildrenValuesLoaded ( ) { for ( int i = 0 ; i < variables . length ; ++ i ) { if ( variables [ i ] != null ) { return true ; } } return false ; } | Tests that some of the children are already created . |
38,541 | public Value check ( ILexNameToken name ) { Value v = get ( name ) ; if ( v != null ) { return v ; } if ( freeVariables != null ) { v = freeVariables . get ( name ) ; if ( v != null ) { return v ; } } v = assistantFactory . createSClassDefinitionAssistant ( ) . getStatic ( classdef , name ) ; if ( v != null ) { return v ; } Context g = getGlobal ( ) ; if ( g != this ) { return g . check ( name ) ; } return v ; } | Check for the name in the current context and classdef and if not present search the global context . Note that the context chain is not followed . |
38,542 | public synchronized boolean compatible ( PType to , PType from ) { done . clear ( ) ; return searchCompatible ( to , from , false ) == Result . Yes ; } | Test whether the two types are compatible . This means that at runtime it is possible that the two types are the same or sufficiently similar that the from value can be assigned to the to value . |
38,543 | private Result allCompatible ( List < PType > to , List < PType > from , boolean paramOnly ) { if ( to . size ( ) != from . size ( ) ) { return Result . No ; } else { for ( int i = 0 ; i < to . size ( ) ; i ++ ) { if ( searchCompatible ( to . get ( i ) , from . get ( i ) , paramOnly ) == Result . No ) { return Result . No ; } } } return Result . Yes ; } | Compare two type lists for placewise compatibility . This is used to check ordered lists of types such as those in a ProductType or parameters to a function or operation . |
38,544 | private Result allSubTypes ( List < PType > sub , List < PType > sup , boolean invignore ) { if ( sub . size ( ) != sup . size ( ) ) { return Result . No ; } else { for ( int i = 0 ; i < sub . size ( ) ; i ++ ) { if ( searchSubType ( sub . get ( i ) , sup . get ( i ) , invignore ) == Result . No ) { return Result . No ; } } } return Result . Yes ; } | Compare two type lists for placewise subtype compatibility . This is used to check ordered lists of types such as those in a ProductType or parameters to a function or operation . |
38,545 | public PTypeList checkComposeTypes ( PType type , Environment env , boolean newTypes ) { PTypeList undefined = new PTypeList ( ) ; for ( PType compose : env . af . createPTypeAssistant ( ) . getComposeTypes ( type ) ) { ARecordInvariantType composeType = ( ARecordInvariantType ) compose ; PDefinition existing = env . findType ( composeType . getName ( ) , null ) ; if ( existing != null ) { boolean matches = false ; if ( existing instanceof ATypeDefinition ) { ATypeDefinition edef = ( ATypeDefinition ) existing ; PType etype = existing . getType ( ) ; if ( edef . getInvExpression ( ) == null && etype instanceof ARecordInvariantType ) { ARecordInvariantType retype = ( ARecordInvariantType ) etype ; if ( retype . getFields ( ) . equals ( composeType . getFields ( ) ) ) { matches = true ; } } } if ( ! matches ) { TypeChecker . report ( 3325 , "Mismatched compose definitions for " + composeType . getName ( ) , composeType . getLocation ( ) ) ; TypeChecker . detail2 ( composeType . getName ( ) . getName ( ) , composeType . getLocation ( ) , existing . getName ( ) . getName ( ) , existing . getLocation ( ) ) ; } } else { if ( newTypes ) { undefined . add ( composeType ) ; } else { TypeChecker . report ( 3113 , "Unknown type name '" + composeType . getName ( ) + "'" , composeType . getLocation ( ) ) ; } } } LexNameList done = new LexNameList ( ) ; for ( PType c1 : undefined ) { for ( PType c2 : undefined ) { if ( c1 != c2 ) { ARecordInvariantType r1 = ( ARecordInvariantType ) c1 ; ARecordInvariantType r2 = ( ARecordInvariantType ) c2 ; if ( r1 . getName ( ) . equals ( r2 . getName ( ) ) && ! done . contains ( r1 . getName ( ) ) && ! r1 . getFields ( ) . equals ( r2 . getFields ( ) ) ) { TypeChecker . report ( 3325 , "Mismatched compose definitions for " + r1 . getName ( ) , r1 . getLocation ( ) ) ; TypeChecker . detail2 ( r1 . getName ( ) . getName ( ) , r1 . getLocation ( ) , r2 . getName ( ) . getName ( ) , r2 . getLocation ( ) ) ; done . add ( r1 . getName ( ) ) ; } } } } return undefined ; } | Check that the compose types that are referred to in a type have a matching definition in the environment . The method returns a list of types that do not exist if the newTypes parameter is passed . |
38,546 | public PType intersect ( PType a , PType b ) { Set < PType > tsa = new HashSet < PType > ( ) ; Set < PType > tsb = new HashSet < PType > ( ) ; boolean resolved = false ; while ( ! resolved ) { if ( a instanceof ABracketType ) { a = ( ( ABracketType ) a ) . getType ( ) ; continue ; } if ( b instanceof ABracketType ) { b = ( ( ABracketType ) b ) . getType ( ) ; continue ; } if ( a instanceof ANamedInvariantType ) { ANamedInvariantType nt = ( ANamedInvariantType ) a ; if ( nt . getInvDef ( ) == null ) { a = nt . getType ( ) ; continue ; } } if ( b instanceof ANamedInvariantType ) { ANamedInvariantType nt = ( ANamedInvariantType ) b ; if ( nt . getInvDef ( ) == null ) { b = nt . getType ( ) ; continue ; } } if ( a instanceof AOptionalType && b instanceof AOptionalType ) { a = ( ( AOptionalType ) a ) . getType ( ) ; b = ( ( AOptionalType ) b ) . getType ( ) ; continue ; } resolved = true ; } if ( a instanceof AUnionType ) { AUnionType uta = ( AUnionType ) a ; tsa . addAll ( uta . getTypes ( ) ) ; } else { tsa . add ( a ) ; } if ( b instanceof AUnionType ) { AUnionType utb = ( AUnionType ) b ; tsb . addAll ( utb . getTypes ( ) ) ; } else { tsb . add ( b ) ; } Set < PType > result = new HashSet < PType > ( ) ; for ( PType atype : tsa ) { for ( PType btype : tsb ) { if ( isSubType ( atype , btype ) ) { result . add ( btype ) ; } else if ( isSubType ( btype , atype ) ) { result . add ( atype ) ; } } } if ( result . isEmpty ( ) ) { return null ; } else { List < PType > list = new Vector < PType > ( ) ; list . addAll ( result ) ; return AstFactory . newAUnionType ( a . getLocation ( ) , list ) ; } } | Calculate the intersection of two types . |
38,547 | public PStm findStatement ( PStm stm , int lineno ) { try { return stm . apply ( af . getStatementFinder ( ) , lineno ) ; } catch ( AnalysisException e ) { return null ; } } | Find a statement starting on the given line . Single statements just compare their location to lineno but block statements and statements with sub - statements iterate over their branches . |
38,548 | public Boolean writeThyFiles ( String path ) throws IOException { File modelThyFile = new File ( path + modelThyName ) ; FileUtils . writeStringToFile ( modelThyFile , modelThy . getContent ( ) ) ; File posThyFile = new File ( path + posThyName ) ; FileUtils . writeStringToFile ( posThyFile , posThy ) ; return true ; } | Write Isabelle theory files to disk for the model and proof obligations |
38,549 | public boolean hasSupertype ( AClassType sclass , PType other ) { return af . createSClassDefinitionAssistant ( ) . hasSupertype ( sclass . getClassdef ( ) , other ) ; } | Used in the SClassDefinitionAssistantTC . |
38,550 | public boolean isConstructor ( PDefinition def ) { if ( def instanceof AExplicitOperationDefinition ) { AExplicitOperationDefinition op = ( AExplicitOperationDefinition ) def ; return op . getIsConstructor ( ) ; } else if ( def instanceof AImplicitOperationDefinition ) { AImplicitOperationDefinition op = ( AImplicitOperationDefinition ) def ; return op . getIsConstructor ( ) ; } else if ( def instanceof AInheritedDefinition ) { AInheritedDefinition op = ( AInheritedDefinition ) def ; return isConstructor ( op . getSuperdef ( ) ) ; } return false ; } | Test whether a definition is a class constructor . |
38,551 | public boolean inConstructor ( Environment env ) { PDefinition encl = env . getEnclosingDefinition ( ) ; if ( encl != null ) { return isConstructor ( encl ) ; } return false ; } | Test whether the calling environment indicates that we are within a constructor . |
38,552 | public ImageDescriptor getCUResourceImageDescriptor ( IFile file , int flags ) { Point size = useSmallSize ( flags ) ? SMALL_SIZE : BIG_SIZE ; return new VdmElementImageDescriptor ( VdmPluginImages . DESC_OBJS_CUNIT_RESOURCE , 0 , size ) ; } | Returns an image descriptor for a compilation unit not on the class path . The descriptor includes overlays if specified . |
38,553 | public static Display getStandardDisplay ( ) { Display display ; display = Display . getCurrent ( ) ; if ( display == null ) display = Display . getDefault ( ) ; return display ; } | Returns the standard display to be used . The method first checks if the thread calling this method has an associated display . If so this display is returned . Otherwise the method returns the default display . |
38,554 | public static int getButtonWidthHint ( Button button ) { button . setFont ( JFaceResources . getDialogFont ( ) ) ; PixelConverter converter = new PixelConverter ( button ) ; int widthHint = converter . convertHorizontalDLUsToPixels ( IDialogConstants . BUTTON_WIDTH ) ; return Math . max ( widthHint , button . computeSize ( SWT . DEFAULT , SWT . DEFAULT , true ) . x ) ; } | Returns a width hint for a button control . |
38,555 | public static void setAccessibilityText ( Control control , final String text ) { control . getAccessible ( ) . addAccessibleListener ( new AccessibleAdapter ( ) { public void getName ( AccessibleEvent e ) { e . result = text ; } } ) ; } | Adds an accessibility listener returning the given fixed name . |
38,556 | protected void valueChanged ( ) { String newValue = fViewer . getDocument ( ) . get ( ) ; if ( ! newValue . equals ( fOldValue ) ) { fOldValue = newValue ; } refreshValidState ( ) ; } | Handle that the value changed |
38,557 | private List < PMultipleBind > getSetBindList ( ILexNameToken finmap , ILexNameToken findex ) { AMapDomainUnaryExp domExp = new AMapDomainUnaryExp ( ) ; domExp . setType ( new ABooleanBasicType ( ) ) ; domExp . setExp ( getVarExp ( finmap ) ) ; return getMultipleSetBindList ( domExp , findex ) ; } | idx in set dom m |
38,558 | public PExp defaultSBinaryExp ( SBinaryExp node , Substitution question ) throws AnalysisException { PExp subl = node . getLeft ( ) . clone ( ) . apply ( main , question ) ; PExp subr = node . getRight ( ) . clone ( ) . apply ( main , question ) ; node . setLeft ( subl . clone ( ) ) ; node . setRight ( subr . clone ( ) ) ; return node ; } | Let s try to do most stuff with S family |
38,559 | public PExp caseAExistsExp ( AExistsExp node , Substitution question ) throws AnalysisException { PExp sub = node . getPredicate ( ) . clone ( ) . apply ( main , question ) ; node . setPredicate ( sub . clone ( ) ) ; return node ; } | cases here for what we need |
38,560 | public void typeCheck ( AFromModuleImports ifm , ModuleEnvironment env ) throws AnalysisException { TypeCheckVisitor tc = new TypeCheckVisitor ( ) ; TypeCheckInfo question = new TypeCheckInfo ( af , env , null , null ) ; for ( List < PImport > ofType : ifm . getSignatures ( ) ) { for ( PImport imp : ofType ) { imp . apply ( tc , question ) ; } } } | Overloads the typeCheck method of this class . |
38,561 | public static Value abort ( LocatedException e , Context ctxt ) { throw new ContextException ( e . number , e . getMessage ( ) , e . location , ctxt ) ; } | Abort the runtime interpretation of the definition throwing a ContextException to indicate the call stack . The information is based on that in the Exception passed . |
38,562 | public static void patternFail ( int number , String msg , ILexLocation location ) throws PatternMatchException { throw new PatternMatchException ( number , msg , location ) ; } | Throw a PatternMatchException with the given message . |
38,563 | public static Value patternFail ( ValueException ve , ILexLocation location ) throws PatternMatchException { throw new PatternMatchException ( ve . number , ve . getMessage ( ) , location ) ; } | Throw a PatternMatchException with a message from the ValueException . |
38,564 | private static boolean isBrowserDead ( ) { try { if ( ( ( FramesTransparentWebDriver ) getDriver ( ) ) . getWrappedDriver ( ) instanceof AppiumDriver ) { getDriver ( ) . getPageSource ( ) ; } else { getDriver ( ) . getCurrentUrl ( ) ; } return false ; } catch ( Throwable t ) { Report . jenkins ( "*****BROWSER IS DEAD ERROR***** " , t ) ; return true ; } } | Checks whether browser is dead . Used to catch situations like Error communicating with the remote browser . It may have died . exceptions |
38,565 | public static ExpectedCondition < List < WebElement > > visibilityOfFirstElements ( final By locator ) { return new ExpectedCondition < List < WebElement > > ( ) { public List < WebElement > apply ( final WebDriver driver ) { return getFirstVisibleWebElements ( driver , null , locator ) ; } public String toString ( ) { return String . format ( "visibility of element located by %s" , locator ) ; } } ; } | Expected condition to look for elements in frames that will return as soon as elements are found in any frame |
38,566 | private static boolean isAvailable ( WebElement element ) { return element . isDisplayed ( ) || isElementHiddenUnderScroll ( element ) && ! element . getCssValue ( "visibility" ) . equals ( "hidden" ) ; } | Defines whether it s possible to work with element i . e . is displayed or located under scroll . |
38,567 | private static boolean isElementHiddenUnderScroll ( WebElement element ) { return ExecutionUtils . isFF ( ) && element . getLocation ( ) . getX ( ) > 0 && element . getLocation ( ) . getY ( ) > 0 ; } | Trick with zero coordinates for not - displayed element works only in FF |
38,568 | public void append ( byte [ ] toWrite ) throws BitsyException { ByteBuffer buf = ByteBuffer . wrap ( toWrite ) ; append ( buf ) ; } | This method appends a line to the file channel |
38,569 | private IEdge removeEdgeOnVertexDelete ( UUID edgeId ) throws BitsyException { BitsyEdge edge = changedEdges . remove ( edgeId ) ; assert ( edge != null ) ; return edge ; } | This method is called to remove an edge through the IEdgeRemover |
38,570 | public boolean sizeBiggerThan24 ( ) { int currentSize = 0 ; for ( int i = 0 ; i < elements . length ; i ++ ) { Object elem = elements [ i ] ; if ( elem == null ) { continue ; } else if ( elem instanceof ArraySet ) { return true ; } else if ( elem instanceof SetMax ) { return true ; } else { currentSize += CompactSet . size ( elem ) ; } if ( currentSize > 24 ) { return true ; } } return false ; } | This method goes over the elements to see if this compact set can be fit inside a Set24 |
38,571 | public boolean isMatch ( Endpoint other ) { assert isMarker ( ) : "isMatch can only be used on marker end-points" ; int ans = 0 ; if ( edgeLabel == null ) { return true ; } if ( other . getEdgeLabel ( ) == null ) { return false ; } ans = edgeLabel . compareTo ( other . getEdgeLabel ( ) ) ; if ( ans != 0 ) { return false ; } if ( edgeId == null ) { return true ; } return ( edgeId . compareTo ( other . getEdgeId ( ) ) == 0 ) ; } | This method must only be called on marker endpoints i . e . end - points used for matching existing Endpoints in the B - Tree . It returns true if the given Endpoint matches this marker |
38,572 | public boolean checkObsolete ( IGraphStore store , boolean isReorg , int lineNo , String fileName ) { if ( type == RecordType . T ) { return isReorg ; } else if ( type == RecordType . L ) { return false ; } else if ( ( type != RecordType . V ) && ( type != RecordType . E ) ) { throw new BitsyException ( BitsyErrorCodes . INTERNAL_ERROR , "Unhanded record type: " + type ) ; } UUID id = null ; int version = - 1 ; String state = null ; JsonToken token ; try { JsonParser parser = factory . createJsonParser ( json ) ; while ( ( token = parser . nextToken ( ) ) != JsonToken . END_OBJECT ) { if ( token == JsonToken . FIELD_NAME ) { if ( parser . getCurrentName ( ) . equals ( "id" ) ) { parser . nextToken ( ) ; id = UUID . fromString ( parser . getText ( ) ) ; continue ; } if ( parser . getCurrentName ( ) . equals ( "v" ) ) { parser . nextToken ( ) ; version = parser . getIntValue ( ) ; continue ; } if ( parser . getCurrentName ( ) . equals ( "s" ) ) { parser . nextToken ( ) ; state = parser . getText ( ) ; break ; } } } if ( ( id == null ) || ( version == - 1 ) || ( state == null ) ) { throw new BitsyException ( BitsyErrorCodes . INTERNAL_ERROR , "Unable to parse record '" + json + "' in file " + fileName + " at line " + lineNo ) ; } if ( state . equals ( "D" ) ) { return isReorg ; } else { if ( type == RecordType . V ) { VertexBean curV = store . getVertex ( id ) ; if ( curV == null ) { return true ; } else if ( curV . getVersion ( ) != version ) { return true ; } else { return false ; } } else { assert ( type == RecordType . E ) ; EdgeBean curE = store . getEdge ( id ) ; if ( curE == null ) { return true ; } else if ( curE . getVersion ( ) != version ) { return true ; } else { return false ; } } } } catch ( Exception e ) { throw new BitsyException ( BitsyErrorCodes . INTERNAL_ERROR , "Possible bug in code. Error serializing line '" + json + "' in file " + fileName + " at line " + lineNo , e ) ; } } | This method checks to see if a record is obsolete i . e . its version is not present in the store |
38,573 | public static int getQueueSize ( ) { if ( instance != null && instance . executor != null ) { return instance . executor . getQueue ( ) . size ( ) ; } else { return 0 ; } } | Returns the current queue size . |
38,574 | public static synchronized void initialize ( GerritWorkersConfig config ) { if ( instance == null ) { instance = new GerritSendCommandQueue ( ) ; } getInstance ( ) . startQueue ( config ) ; } | Initializes the singleton instance and configures it . |
38,575 | public String asUrlPart ( ) { try { return encode ( projectName ) + "~" + encode ( branchName ) + "~" + id ; } catch ( UnsupportedEncodingException e ) { String parameter = projectName + "~" + branchName + "~" + id ; logger . error ( "Failed to encode ChangeId {}, falling back to unencoded {}" , this , parameter ) ; return parameter ; } } | As the part of the URL . |
38,576 | public boolean sendCommand ( String command ) { try { sendCommand2 ( command ) ; } catch ( Exception ex ) { logger . error ( "Could not run command " + command , ex ) ; return false ; } return true ; } | Sends a command to the Gerrit server . |
38,577 | public String sendCommandStr ( String command ) { String str = null ; try { str = sendCommand2 ( command ) ; } catch ( Exception ex ) { logger . error ( "Could not run command " + command , ex ) ; } return str ; } | Sends a command to the Gerrit server returning the output from the command . |
38,578 | public String sendCommand2 ( String command ) throws IOException { String str = null ; SshConnection ssh = null ; try { ssh = SshConnectionFactory . getConnection ( config . getGerritHostName ( ) , config . getGerritSshPort ( ) , config . getGerritProxy ( ) , config . getGerritAuthentication ( ) ) ; str = ssh . executeCommand ( command ) ; } catch ( Exception ex ) { throw new IOException ( "Error during sending command" , ex ) ; } finally { if ( ssh != null ) { ssh . disconnect ( ) ; } } return str ; } | Runs a command on the gerrit server and returns the output from the command . |
38,579 | private static KeyPair parsePrivateKeyFile ( File keyFile ) { if ( keyFile == null ) { return null ; } try { JSch jsch = new JSch ( ) ; KeyPair key = KeyPair . load ( jsch , keyFile . getAbsolutePath ( ) ) ; return key ; } catch ( JSchException ex ) { return null ; } } | Parses the keyFile hiding any Exceptions that might occur . |
38,580 | public static boolean checkPassPhrase ( File keyFilePath , String passPhrase ) { KeyPair key = parsePrivateKeyFile ( keyFilePath ) ; boolean isValidPhrase = passPhrase != null && ! passPhrase . trim ( ) . isEmpty ( ) ; if ( key == null ) { return false ; } else if ( key . isEncrypted ( ) != isValidPhrase ) { return false ; } else if ( key . isEncrypted ( ) ) { return key . decrypt ( passPhrase ) ; } return true ; } | Checks to see if the passPhrase is valid for the private key file . |
38,581 | private HttpPost createHttpPostEntity ( ReviewInput reviewInput , String reviewEndpoint ) { HttpPost httpPost = new HttpPost ( reviewEndpoint ) ; String asJson = GSON . toJson ( reviewInput ) ; StringEntity entity = null ; try { entity = new StringEntity ( asJson ) ; } catch ( UnsupportedEncodingException e ) { logger . error ( "Failed to create JSON for posting to Gerrit" , e ) ; if ( altLogger != null ) { altLogger . print ( "ERROR Failed to create JSON for posting to Gerrit: " + e . toString ( ) ) ; } return null ; } entity . setContentType ( "application/json" ) ; httpPost . setEntity ( entity ) ; return httpPost ; } | Construct the post . |
38,582 | public synchronized void connect ( ) throws IOException { logger . debug ( "connecting..." ) ; Authentication auth = authentication ; if ( updater != null ) { Authentication updatedAuth = updater . updateAuthentication ( authentication ) ; if ( updatedAuth != null && auth != updatedAuth ) { auth = updatedAuth ; } } try { client = new JSch ( ) ; if ( auth . getPrivateKeyPhrase ( ) == null ) { client . addIdentity ( auth . getPrivateKeyFile ( ) . getAbsolutePath ( ) , auth . getPrivateKeyFilePassword ( ) ) ; } else { client . addIdentity ( auth . getUsername ( ) , auth . getPrivateKeyPhrase ( ) , null , auth . getPrivateKeyFilePassword ( ) . getBytes ( "UTF-8" ) ) ; } client . setHostKeyRepository ( new BlindHostKeyRepository ( ) ) ; connectSession = client . getSession ( auth . getUsername ( ) , host , port ) ; connectSession . setConfig ( "PreferredAuthentications" , "publickey" ) ; if ( proxy != null && ! proxy . isEmpty ( ) ) { String [ ] splitted = proxy . split ( ":" ) ; if ( splitted . length > 2 && splitted [ 1 ] . length ( ) >= PROTO_HOST_DELIM_LENGTH ) { String pproto = splitted [ 0 ] ; String phost = splitted [ 1 ] . substring ( 2 ) ; int pport = Integer . parseInt ( splitted [ 2 ] ) ; if ( pproto . equals ( "socks5" ) || pproto . equals ( "http" ) ) { if ( pproto . equals ( "socks5" ) ) { connectSession . setProxy ( new ProxySOCKS5 ( phost , pport ) ) ; } else { connectSession . setProxy ( new ProxyHTTP ( phost , pport ) ) ; } } else { throw new MalformedURLException ( "Only http and socks5 protocols are supported" ) ; } } else { throw new MalformedURLException ( proxy ) ; } } connectSession . connect ( this . connectionTimeout ) ; logger . debug ( "Connected: {}" , connectSession . isConnected ( ) ) ; connectSession . setServerAliveInterval ( ALIVE_INTERVAL ) ; } catch ( JSchException ex ) { throw new SshException ( ex ) ; } } | Connects the connection . |
38,583 | public synchronized String executeCommand ( String command ) throws SshException { if ( ! isConnected ( ) ) { throw new IllegalStateException ( "Not connected!" ) ; } Channel channel = null ; try { logger . debug ( "Opening channel" ) ; channel = connectSession . openChannel ( CMD_EXEC ) ; ( ( ChannelExec ) channel ) . setCommand ( command ) ; ByteArrayOutputStream errOut = new ByteArrayOutputStream ( ) ; channel . setExtOutputStream ( errOut ) ; BufferedReader bufferedReader = new BufferedReader ( new InputStreamReader ( channel . getInputStream ( ) ) ) ; logger . debug ( "connecting channel." ) ; channel . connect ( ) ; String incomingLine = null ; StringBuilder commandOutput = new StringBuilder ( ) ; while ( ( incomingLine = bufferedReader . readLine ( ) ) != null ) { commandOutput . append ( incomingLine ) ; commandOutput . append ( '\n' ) ; logger . trace ( "Incoming line: {}" , incomingLine ) ; } logger . trace ( "Closing reader." ) ; bufferedReader . close ( ) ; waitForChannelClosure ( channel , CLOSURE_WAIT_TIMEOUT ) ; int exitCode = channel . getExitStatus ( ) ; if ( exitCode > 0 ) { String error = errOut . toString ( ) ; if ( error != null && error . trim ( ) . length ( ) > 0 ) { throw new SshException ( error . trim ( ) + " (" + String . valueOf ( exitCode ) + ")" ) ; } else { throw new SshException ( String . valueOf ( exitCode ) ) ; } } return commandOutput . toString ( ) ; } catch ( SshException ex ) { throw ex ; } catch ( JSchException ex ) { throw new SshException ( ex ) ; } catch ( IOException ex ) { throw new SshException ( ex ) ; } finally { if ( channel != null ) { logger . trace ( "disconnecting channel." ) ; channel . disconnect ( ) ; } } } | Execute an ssh command on the server . After the command is sent the used channel is disconnected . |
38,584 | private static void waitForChannelClosure ( Channel channel , long timoutInMs ) { final long start = System . currentTimeMillis ( ) ; final long until = start + timoutInMs ; try { while ( ! channel . isClosed ( ) && System . currentTimeMillis ( ) < until ) { Thread . sleep ( CLOSURE_WAIT_INTERVAL ) ; } logger . trace ( "Time waited for channel closure: " + ( System . currentTimeMillis ( ) - start ) ) ; } catch ( InterruptedException e ) { logger . trace ( "Interrupted" , e ) ; } if ( ! channel . isClosed ( ) ) { logger . trace ( "Channel not closed in timely manner!" ) ; } } | Blocks until the given channel is close or the timout is reached |
38,585 | public synchronized Reader executeCommandReader ( String command ) throws SshException , IOException { if ( ! isConnected ( ) ) { throw new IllegalStateException ( "Not connected!" ) ; } try { Channel channel = connectSession . openChannel ( "exec" ) ; ( ( ChannelExec ) channel ) . setCommand ( command ) ; InputStreamReader reader = new InputStreamReader ( channel . getInputStream ( ) , "utf-8" ) ; channel . connect ( ) ; return reader ; } catch ( JSchException ex ) { throw new SshException ( ex ) ; } } | Execute an ssh command on the server without closing the session so that a Reader can be returned with streaming data from the server . |
38,586 | public synchronized void disconnect ( ) { if ( connectSession != null ) { logger . debug ( "Disconnecting client connection." ) ; connectSession . disconnect ( ) ; connectSession = null ; } } | Disconnects the connection . |
38,587 | public static GerritJsonEvent getEventIfInteresting ( String jsonString ) { logger . trace ( "finding event for jsonString: {}" , jsonString ) ; try { JSONObject jsonObject = getJsonObjectIfInterestingAndUsable ( jsonString ) ; if ( jsonObject != null ) { return getEvent ( jsonObject ) ; } } catch ( Exception ex ) { logger . warn ( "Unanticipated error when creating DTO representation of JSON string." , ex ) ; } return null ; } | Tries to parse the provided string into a GerritJsonEvent DTO if it is interesting and usable . |
38,588 | public static String getString ( JSONObject json , String key , String defaultValue ) { if ( json . containsKey ( key ) ) { return json . getString ( key ) ; } else { return defaultValue ; } } | Returns the value of a JSON property as a String if it exists otherwise returns the defaultValue . |
38,589 | public static boolean getBoolean ( JSONObject json , String key , boolean defaultValue ) { if ( json . containsKey ( key ) ) { boolean result ; try { result = json . getBoolean ( key ) ; } catch ( JSONException ex ) { result = defaultValue ; } return result ; } else { return defaultValue ; } } | Returns the value of a JSON property as a boolean if it exists and boolean value otherwise returns the defaultValue . |
38,590 | public static Date getDate ( JSONObject json , String key ) { return getDate ( json , key , null ) ; } | Returns the value of a JSON property as a Date if it exists otherwise returns null . |
38,591 | public static Date getDate ( JSONObject json , String key , Date defaultValue ) { Date result = defaultValue ; if ( json . containsKey ( key ) ) { try { String secondsString = json . getString ( key ) ; Long milliseconds = TimeUnit . SECONDS . toMillis ( Long . parseLong ( secondsString ) ) ; result = new Date ( milliseconds ) ; } catch ( JSONException ex ) { } catch ( NumberFormatException nfe ) { } } return result ; } | Returns the value of a JSON property as a Date if it exists otherwise returns the defaultValue . |
38,592 | public void setEventCreatedOn ( String eventCreatedOn ) { Long milliseconds = TimeUnit . SECONDS . toMillis ( Long . parseLong ( eventCreatedOn ) ) ; this . eventCreatedOn = new Date ( milliseconds ) ; } | Gerrit server - based time stamp when the event was created by Gerrit Server . ONLY USE FOR UNIT TESTS! |
38,593 | public boolean isExceptionAtThisTime ( ) { Time now = new Time ( ) ; for ( TimeSpan span : timesOfDay ) { if ( span . isWithin ( now ) ) { return true ; } } return false ; } | If the current time is configured as an exception . |
38,594 | public boolean isExceptionToday ( ) { if ( daysOfWeek != null && daysOfWeek . length > 0 ) { int dayOfWeekNow = Calendar . getInstance ( ) . get ( Calendar . DAY_OF_WEEK ) ; for ( int exceptionDay : daysOfWeek ) { if ( exceptionDay == dayOfWeekNow ) { return true ; } } } return false ; } | If today is a day configured as an exception . |
38,595 | public boolean isEnabled ( ) { if ( daysOfWeek != null && daysOfWeek . length > 0 ) { return true ; } if ( timesOfDay != null && timesOfDay . size ( ) > 0 ) { return true ; } return false ; } | Returns true if any exception data has been added either days or time . |
38,596 | private List < String > hashtagsFromArray ( JSONObject json , String array ) { if ( json . containsKey ( array ) ) { JSONArray hashtagsArray = json . getJSONArray ( array ) ; List < String > result = new ArrayList < String > ( hashtagsArray . size ( ) ) ; for ( Object tag : hashtagsArray ) { result . add ( tag . toString ( ) ) ; } return result ; } return Collections . emptyList ( ) ; } | Converts an array key from JSON into a list of the strings it contains . |
38,597 | public void fromJson ( JSONObject json ) { super . fromJson ( json ) ; if ( json . containsKey ( CHANGE ) ) { change = new Change ( json . getJSONObject ( CHANGE ) ) ; } if ( json . containsKey ( PATCH_SET ) ) { patchSet = new PatchSet ( json . getJSONObject ( PATCH_SET ) ) ; } else if ( json . containsKey ( PATCHSET ) ) { patchSet = new PatchSet ( json . getJSONObject ( PATCHSET ) ) ; } } | Takes a JSON object and fills its internal data - structure . |
38,598 | private String getLine ( CharBuffer cb ) { String line = null ; int pos = cb . position ( ) ; int limit = cb . limit ( ) ; cb . flip ( ) ; for ( int i = 0 ; i < cb . length ( ) ; i ++ ) { if ( cb . charAt ( i ) == '\n' ) { line = getSubSequence ( cb , 0 , i ) . toString ( ) ; cb . position ( i + 1 ) ; break ; } } if ( line != null ) { cb . compact ( ) ; if ( eventBuffer != null ) { eventBuffer . append ( line ) ; String eventString = eventBuffer . toString ( ) ; eventBuffer = null ; line = eventString ; } line . trim ( ) ; } else { if ( cb . length ( ) > 0 ) { if ( cb . length ( ) == cb . capacity ( ) ) { if ( eventBuffer == null ) { logger . debug ( "Encountered big event." ) ; eventBuffer = new StringBuilder ( ) ; } eventBuffer . append ( getSubSequence ( cb , 0 , pos ) ) ; } else { cb . position ( pos ) ; cb . limit ( limit ) ; } } else { cb . clear ( ) ; } } return line ; } | Offers lines in buffer to queue . |
38,599 | private CharSequence getSubSequence ( CharBuffer cb , int start , int end ) { return cb . subSequence ( start , end ) ; } | Get sub sequence of buffer . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.