idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
1,100
public static void main ( String [ ] args ) { System . exit ( call ( System . out , System . err , args ) ? 0 : 1 ) ; }
Calls the main entry point and exits the JVM with an exit status determined by the return status .
1,101
protected Content getNavLinkIndex ( ) { Content li = HtmlTree . LI ( HtmlStyle . navBarCell1Rev , contents . indexLabel ) ; return li ; }
Get the index label for navigation bar .
1,102
protected void addDescription ( ModuleElement mdle , Content dlTree , SearchIndexItem si ) { String moduleName = utils . getFullyQualifiedName ( mdle ) ; Content link = getModuleLink ( mdle , new StringContent ( moduleName ) ) ; si . setLabel ( moduleName ) ; si . setCategory ( resources . getText ( "doclet.Modules" ) ) ; Content dt = HtmlTree . DT ( link ) ; dt . addContent ( " - " ) ; dt . addContent ( contents . module_ ) ; dt . addContent ( " " + moduleName ) ; dlTree . addContent ( dt ) ; Content dd = new HtmlTree ( HtmlTag . DD ) ; addSummaryComment ( mdle , dd ) ; dlTree . addContent ( dd ) ; }
Add one line summary comment for the module .
1,103
public Iterable < ? extends Element > analyze ( Iterable < ? extends Element > classes ) { enter ( null ) ; final ListBuffer < Element > results = new ListBuffer < > ( ) ; try { if ( classes == null ) { handleFlowResults ( compiler . flow ( compiler . attribute ( compiler . todo ) ) , results ) ; } else { Filter f = new Filter ( ) { public void process ( Env < AttrContext > env ) { handleFlowResults ( compiler . flow ( compiler . attribute ( env ) ) , results ) ; } } ; f . run ( compiler . todo , classes ) ; } } finally { compiler . log . flush ( ) ; } return results ; }
wrap it here
1,104
public Type parseType ( String expr , TypeElement scope ) { if ( expr == null || expr . equals ( "" ) ) throw new IllegalArgumentException ( ) ; compiler = JavaCompiler . instance ( context ) ; JavaFileObject prev = compiler . log . useSource ( null ) ; ParserFactory parserFactory = ParserFactory . instance ( context ) ; Attr attr = Attr . instance ( context ) ; try { CharBuffer buf = CharBuffer . wrap ( ( expr + "\u0000" ) . toCharArray ( ) , 0 , expr . length ( ) ) ; Parser parser = parserFactory . newParser ( buf , false , false , false ) ; JCTree tree = parser . parseType ( ) ; return attr . attribType ( tree , ( Symbol . TypeSymbol ) scope ) ; } finally { compiler . log . useSource ( prev ) ; } }
For internal use only . This method will be removed without warning .
1,105
public static ClassFinder instance ( Context context ) { ClassFinder instance = context . get ( classFinderKey ) ; if ( instance == null ) instance = new ClassFinder ( context ) ; return instance ; }
Get the ClassFinder instance for this invocation .
1,106
long getSupplementaryFlags ( ClassSymbol c ) { if ( jrtIndex == null || ! jrtIndex . isInJRT ( c . classfile ) || c . name == names . module_info ) { return 0 ; } if ( supplementaryFlags == null ) { supplementaryFlags = new HashMap < > ( ) ; } Long flags = supplementaryFlags . get ( c . packge ( ) ) ; if ( flags == null ) { long newFlags = 0 ; try { JRTIndex . CtSym ctSym = jrtIndex . getCtSym ( c . packge ( ) . flatName ( ) ) ; Profile minProfile = Profile . DEFAULT ; if ( ctSym . proprietary ) newFlags |= PROPRIETARY ; if ( ctSym . minProfile != null ) minProfile = Profile . lookup ( ctSym . minProfile ) ; if ( profile != Profile . DEFAULT && minProfile . value > profile . value ) { newFlags |= NOT_IN_PROFILE ; } } catch ( IOException ignore ) { } supplementaryFlags . put ( c . packge ( ) , flags = newFlags ) ; } return flags ; }
Returns any extra flags for a class symbol . This information used to be provided using private annotations in the class file in ct . sym ; in time this information will be available from the module system .
1,107
private void completeOwners ( Symbol o ) { if ( o . kind != PCK ) completeOwners ( o . owner ) ; o . complete ( ) ; }
complete up through the enclosing package .
1,108
private CompletionFailure newCompletionFailure ( TypeSymbol c , JCDiagnostic diag ) { if ( ! cacheCompletionFailure ) { return new CompletionFailure ( c , diag ) ; } else { CompletionFailure result = cachedCompletionFailure ; result . sym = c ; result . diag = diag ; return result ; } }
Static factory for CompletionFailure objects . In practice only one can be used at a time so we share one to reduce the expense of allocating new exception objects .
1,109
protected JavaFileObject preferredFileObject ( JavaFileObject a , JavaFileObject b ) { if ( preferSource ) return ( a . getKind ( ) == JavaFileObject . Kind . SOURCE ) ? a : b ; else { long adate = a . getLastModified ( ) ; long bdate = b . getLastModified ( ) ; return ( adate > bdate ) ? a : b ; } }
Implement policy to choose to derive information from a source file or a class file when both are present . May be overridden by subclasses .
1,110
private void scanModulePaths ( PackageSymbol p , ModuleSymbol msym ) throws IOException { Set < JavaFileObject . Kind > kinds = getPackageFileKinds ( ) ; Set < JavaFileObject . Kind > classKinds = EnumSet . copyOf ( kinds ) ; classKinds . remove ( JavaFileObject . Kind . SOURCE ) ; boolean wantClassFiles = ! classKinds . isEmpty ( ) ; Set < JavaFileObject . Kind > sourceKinds = EnumSet . copyOf ( kinds ) ; sourceKinds . remove ( JavaFileObject . Kind . CLASS ) ; boolean wantSourceFiles = ! sourceKinds . isEmpty ( ) ; String packageName = p . fullname . toString ( ) ; Location classLocn = msym . classLocation ; Location sourceLocn = msym . sourceLocation ; Location patchLocn = msym . patchLocation ; Location patchOutLocn = msym . patchOutputLocation ; boolean prevPreferCurrent = preferCurrent ; try { preferCurrent = false ; if ( wantClassFiles && ( patchOutLocn != null ) ) { fillIn ( p , patchOutLocn , list ( patchOutLocn , p , packageName , classKinds ) ) ; } if ( ( wantClassFiles || wantSourceFiles ) && ( patchLocn != null ) ) { Set < JavaFileObject . Kind > combined = EnumSet . noneOf ( JavaFileObject . Kind . class ) ; combined . addAll ( classKinds ) ; combined . addAll ( sourceKinds ) ; fillIn ( p , patchLocn , list ( patchLocn , p , packageName , combined ) ) ; } preferCurrent = true ; if ( wantClassFiles && ( classLocn != null ) ) { fillIn ( p , classLocn , list ( classLocn , p , packageName , classKinds ) ) ; } if ( wantSourceFiles && ( sourceLocn != null ) ) { fillIn ( p , sourceLocn , list ( sourceLocn , p , packageName , sourceKinds ) ) ; } } finally { preferCurrent = prevPreferCurrent ; } }
is the same as the module s classLocation .
1,111
private void scanUserPaths ( PackageSymbol p , boolean includeSourcePath ) throws IOException { Set < JavaFileObject . Kind > kinds = getPackageFileKinds ( ) ; Set < JavaFileObject . Kind > classKinds = EnumSet . copyOf ( kinds ) ; classKinds . remove ( JavaFileObject . Kind . SOURCE ) ; boolean wantClassFiles = ! classKinds . isEmpty ( ) ; Set < JavaFileObject . Kind > sourceKinds = EnumSet . copyOf ( kinds ) ; sourceKinds . remove ( JavaFileObject . Kind . CLASS ) ; boolean wantSourceFiles = ! sourceKinds . isEmpty ( ) ; boolean haveSourcePath = includeSourcePath && fileManager . hasLocation ( SOURCE_PATH ) ; if ( verbose && verbosePath ) { if ( fileManager instanceof StandardJavaFileManager ) { StandardJavaFileManager fm = ( StandardJavaFileManager ) fileManager ; if ( haveSourcePath && wantSourceFiles ) { List < Path > path = List . nil ( ) ; for ( Path sourcePath : fm . getLocationAsPaths ( SOURCE_PATH ) ) { path = path . prepend ( sourcePath ) ; } log . printVerbose ( "sourcepath" , path . reverse ( ) . toString ( ) ) ; } else if ( wantSourceFiles ) { List < Path > path = List . nil ( ) ; for ( Path classPath : fm . getLocationAsPaths ( CLASS_PATH ) ) { path = path . prepend ( classPath ) ; } log . printVerbose ( "sourcepath" , path . reverse ( ) . toString ( ) ) ; } if ( wantClassFiles ) { List < Path > path = List . nil ( ) ; for ( Path platformPath : fm . getLocationAsPaths ( PLATFORM_CLASS_PATH ) ) { path = path . prepend ( platformPath ) ; } for ( Path classPath : fm . getLocationAsPaths ( CLASS_PATH ) ) { path = path . prepend ( classPath ) ; } log . printVerbose ( "classpath" , path . reverse ( ) . toString ( ) ) ; } } } String packageName = p . fullname . toString ( ) ; if ( wantSourceFiles && ! haveSourcePath ) { fillIn ( p , CLASS_PATH , list ( CLASS_PATH , p , packageName , kinds ) ) ; } else { if ( wantClassFiles ) fillIn ( p , CLASS_PATH , list ( CLASS_PATH , p , packageName , classKinds ) ) ; if ( wantSourceFiles ) fillIn ( p , SOURCE_PATH , list ( SOURCE_PATH , p , packageName , sourceKinds ) ) ; } }
Scans class path and source path for files in given package .
1,112
private void scanPlatformPath ( PackageSymbol p ) throws IOException { fillIn ( p , PLATFORM_CLASS_PATH , list ( PLATFORM_CLASS_PATH , p , p . fullname . toString ( ) , allowSigFiles ? EnumSet . of ( JavaFileObject . Kind . CLASS , JavaFileObject . Kind . OTHER ) : EnumSet . of ( JavaFileObject . Kind . CLASS ) ) ) ; }
Scans platform class path for files in given package .
1,113
private void logMandatoryWarning ( DiagnosticPosition pos , String msg , Object ... args ) { if ( enforceMandatory ) log . mandatoryWarning ( lintCategory , pos , msg , args ) ; else log . warning ( lintCategory , pos , msg , args ) ; }
Reports a mandatory warning to the log . If mandatory warnings are not being enforced treat this as an ordinary warning .
1,114
private void logMandatoryNote ( JavaFileObject file , String msg , Object ... args ) { if ( enforceMandatory ) log . mandatoryNote ( file , msg , args ) ; else log . note ( file , msg , args ) ; }
Reports a mandatory note to the log . If mandatory notes are not being enforced treat this as an ordinary note .
1,115
private boolean isValidFile ( String s , Set < JavaFileObject . Kind > fileKinds ) { JavaFileObject . Kind kind = getKind ( s ) ; return fileKinds . contains ( kind ) ; }
container is a directory a zip file or a non - existent path .
1,116
public static String getRelativeName ( File file ) { if ( ! file . isAbsolute ( ) ) { String result = file . getPath ( ) . replace ( File . separatorChar , '/' ) ; if ( isRelativeUri ( result ) ) return result ; } throw new IllegalArgumentException ( "Invalid relative path: " + file ) ; }
Converts a relative file name to a relative URI . This is different from File . toURI as this method does not canonicalize the file before creating the URI . Furthermore no schema is used .
1,117
public void buildSummary ( XMLNode node , Content packageContentTree ) { Content summaryContentTree = packageWriter . getSummaryHeader ( ) ; buildChildren ( node , summaryContentTree ) ; packageContentTree . addContent ( summaryContentTree ) ; }
Build the package summary .
1,118
public Content getTargetModulePackageLink ( PackageElement pkg , String target , Content label , ModuleElement mdle ) { return getHyperLink ( pathString ( pkg , DocPaths . PACKAGE_SUMMARY ) , label , "" , target ) ; }
Get Module Package link with target frame .
1,119
public Content getTargetModuleLink ( String target , Content label , ModuleElement mdle ) { return getHyperLink ( pathToRoot . resolve ( DocPaths . moduleSummary ( mdle ) ) , label , "" , target ) ; }
Get Module link with target frame .
1,120
protected Content getNavLinkModule ( ModuleElement mdle ) { Content linkContent = getModuleLink ( mdle , contents . moduleLabel ) ; Content li = HtmlTree . LI ( linkContent ) ; return li ; }
Get link to the module summary page for the module passed .
1,121
public Content getNavLinkPrevious ( DocPath prev ) { Content li ; if ( prev != null ) { li = HtmlTree . LI ( getHyperLink ( prev , contents . prevLabel , "" , "" ) ) ; } else li = HtmlTree . LI ( contents . prevLabel ) ; return li ; }
Get link for previous file .
1,122
protected Content getNavLinkDeprecated ( ) { Content linkContent = getHyperLink ( pathToRoot . resolve ( DocPaths . DEPRECATED_LIST ) , contents . deprecatedLabel , "" , "" ) ; Content li = HtmlTree . LI ( linkContent ) ; return li ; }
Get Deprecated API link in the navigation bar .
1,123
public Content getTableCaption ( Content title ) { Content captionSpan = HtmlTree . SPAN ( title ) ; Content space = Contents . SPACE ; Content tabSpan = HtmlTree . SPAN ( HtmlStyle . tabEnd , space ) ; Content caption = HtmlTree . CAPTION ( captionSpan ) ; caption . addContent ( tabSpan ) ; return caption ; }
Get table caption .
1,124
protected DocPath pathString ( TypeElement te , DocPath name ) { return pathString ( utils . containingPackage ( te ) , name ) ; }
Return the path to the class page for a typeElement .
1,125
public Content getModuleLink ( ModuleElement mdle , Content label ) { boolean included = utils . isIncluded ( mdle ) ; return ( included ) ? getHyperLink ( pathToRoot . resolve ( DocPaths . moduleSummary ( mdle ) ) , label , "" , "" ) : label ; }
Get Module link .
1,126
public Content getDeprecatedPhrase ( Element e ) { return ( utils . isDeprecatedForRemoval ( e ) ) ? contents . deprecatedForRemovalPhrase : contents . deprecatedPhrase ; }
Get the deprecated phrase as content .
1,127
public void addScriptProperties ( Content head ) { HtmlTree javascript = HtmlTree . SCRIPT ( pathToRoot . resolve ( DocPaths . JAVASCRIPT ) . getPath ( ) ) ; head . addContent ( javascript ) ; if ( configuration . createindex ) { if ( pathToRoot != null && script != null ) { String ptrPath = pathToRoot . isEmpty ( ) ? "." : pathToRoot . getPath ( ) ; script . addContent ( new RawHtml ( "var pathtoroot = \"" + ptrPath + "/\";loadScripts(document, \'script\');" ) ) ; } addJQueryFile ( head , DocPaths . JSZIP_MIN ) ; addJQueryFile ( head , DocPaths . JSZIPUTILS_MIN ) ; head . addContent ( new RawHtml ( "<!--[if IE]>" ) ) ; addJQueryFile ( head , DocPaths . JSZIPUTILS_IE_MIN ) ; head . addContent ( new RawHtml ( "<![endif] ) ) ; addJQueryFile ( head , DocPaths . JQUERY_JS_1_10 ) ; addJQueryFile ( head , DocPaths . JQUERY_JS ) ; } }
Add a link to the JavaScript file .
1,128
public void addAnnotationInfo ( PackageElement packageElement , Content htmltree ) { addAnnotationInfo ( packageElement , packageElement . getAnnotationMirrors ( ) , htmltree ) ; }
Adds the annotation types for the given packageElement .
1,129
public void addAnnotationInfo ( Element element , Content htmltree ) { addAnnotationInfo ( element , element . getAnnotationMirrors ( ) , htmltree ) ; }
Adds the annotatation types for the given element .
1,130
public boolean addAnnotationInfo ( int indent , Element element , VariableElement param , Content tree ) { return addAnnotationInfo ( indent , element , param . getAnnotationMirrors ( ) , false , tree ) ; }
Add the annotatation types for the given element and parameter .
1,131
private void addAnnotationInfo ( Element element , List < ? extends AnnotationMirror > descList , Content htmltree ) { addAnnotationInfo ( 0 , element , descList , true , htmltree ) ; }
Adds the annotatation types for the given Element .
1,132
private boolean addAnnotationInfo ( int indent , Element element , List < ? extends AnnotationMirror > descList , boolean lineBreak , Content htmltree ) { List < Content > annotations = getAnnotations ( indent , descList , lineBreak ) ; String sep = "" ; if ( annotations . isEmpty ( ) ) { return false ; } for ( Content annotation : annotations ) { htmltree . addContent ( sep ) ; htmltree . addContent ( annotation ) ; if ( ! lineBreak ) { sep = " " ; } } return true ; }
Adds the annotation types for the given element .
1,133
public static DocTreeMaker instance ( Context context ) { DocTreeMaker instance = context . get ( treeMakerKey ) ; if ( instance == null ) instance = new DocTreeMaker ( context ) ; return instance ; }
Get the TreeMaker instance .
1,134
public DocTreeMaker at ( DiagnosticPosition pos ) { this . pos = ( pos == null ? Position . NOPOS : pos . getStartPosition ( ) ) ; return this ; }
Reassign current position .
1,135
private String fileExt ( String url ) { if ( url . indexOf ( "?" ) > - 1 ) { url = url . substring ( 0 , url . indexOf ( "?" ) ) ; } if ( url . lastIndexOf ( "." ) == - 1 ) { return null ; } else { String ext = url . substring ( url . lastIndexOf ( "." ) ) ; if ( ext . indexOf ( "%" ) > - 1 ) { ext = ext . substring ( 0 , ext . indexOf ( "%" ) ) ; } if ( ext . indexOf ( "/" ) > - 1 ) { ext = ext . substring ( 0 , ext . indexOf ( "/" ) ) ; } return ext . toLowerCase ( ) ; } }
Returns the file extension of a file .
1,136
public static Bitmap decodeSampledBitmapFromByteArray ( byte [ ] picture , int reqWidth , int reqHeight ) { BitmapFactory . Options options = new BitmapFactory . Options ( ) ; options . inJustDecodeBounds = true ; BitmapFactory . decodeByteArray ( picture , 0 , picture . length , options ) ; options . inSampleSize = calculateInSampleSize ( options , reqWidth , reqHeight ) ; options . inJustDecodeBounds = false ; return BitmapFactory . decodeByteArray ( picture , 0 , picture . length , options ) ; }
From the google examples decodes a bitmap as a byte array and then resizes it for the required width and hieght .
1,137
public static byte [ ] encodeBitmapToArray ( Bitmap bitmap , Bitmap . CompressFormat format ) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream ( ) ; bitmap . compress ( format , 0 , outputStream ) ; return outputStream . toByteArray ( ) ; }
Encodes a bitmap to a byte array .
1,138
public boolean directoryExists ( File [ ] files ) { for ( int i = 0 ; i < files . length ; i ++ ) { if ( files [ i ] . isDirectory ( ) ) { return true ; } } return false ; }
Checks if the files contain a directory .
1,139
public void toggleButton ( final boolean visible ) { if ( isFabShowing != visible ) { isFabShowing = visible ; int height = fab . getHeight ( ) ; if ( height == 0 ) { ViewTreeObserver vto = fab . getViewTreeObserver ( ) ; if ( vto . isAlive ( ) ) { vto . addOnPreDrawListener ( new ViewTreeObserver . OnPreDrawListener ( ) { public boolean onPreDraw ( ) { ViewTreeObserver currentVto = fab . getViewTreeObserver ( ) ; if ( currentVto . isAlive ( ) ) { currentVto . removeOnPreDrawListener ( this ) ; } toggleButton ( visible ) ; return true ; } } ) ; return ; } } int translationY = visible ? 0 : height ; fab . animate ( ) . setInterpolator ( interpolator ) . setDuration ( 350 ) . translationY ( translationY ) ; fab . setClickable ( visible ) ; } }
Toggles the material floating action button .
1,140
private void init ( ) { curDirectory = new File ( Environment . getExternalStorageDirectory ( ) . getPath ( ) ) ; currentFile = new File ( curDirectory . getPath ( ) ) ; lastDirectory = curDirectory . getParentFile ( ) ; if ( curDirectory . isDirectory ( ) ) { new UpdateFilesTask ( this ) . execute ( curDirectory ) ; } else { try { throw new Exception ( getString ( R . string . file_picker_directory_error ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } }
Initialize the current directory .
1,141
private void showButtons ( ) { if ( ! areButtonsShowing ) { buttonContainer . clearAnimation ( ) ; buttonContainer . startAnimation ( slideUp ) ; buttonContainer . setVisibility ( View . VISIBLE ) ; areButtonsShowing = true ; } }
Method that shows the sliding panel
1,142
private void hideButtons ( ) { if ( areButtonsShowing ) { buttonContainer . clearAnimation ( ) ; buttonContainer . startAnimation ( slideDown ) ; buttonContainer . setVisibility ( View . INVISIBLE ) ; areButtonsShowing = false ; } }
Method that hides the sliding panel
1,143
private void setHeaderBackground ( int colorResId , int drawableResId ) { if ( drawableResId == - 1 ) { try { header . setBackgroundColor ( getResources ( ) . getColor ( colorResId ) ) ; } catch ( Resources . NotFoundException e ) { e . printStackTrace ( ) ; } } else { try { header . setBackgroundDrawable ( getResources ( ) . getDrawable ( drawableResId ) ) ; } catch ( Resources . NotFoundException e ) { e . printStackTrace ( ) ; } } }
Set the background color of the header
1,144
public void setThemeType ( ThemeType themeType ) { if ( themeType == ThemeType . ACTIVITY ) { setTheme ( android . R . style . Theme_Holo_Light ) ; } else if ( themeType == ThemeType . DIALOG ) { setTheme ( android . R . style . Theme_Holo_Light_Dialog ) ; } else if ( themeType == ThemeType . DIALOG_NO_ACTION_BAR ) { setTheme ( android . R . style . Theme_Holo_Light_Dialog_NoActionBar ) ; } }
Sets the theme for this activity
1,145
public Intent build ( ) { Intent filePicker = new Intent ( mContext , useMaterial ? FilePicker . class : FilePickerActivity . class ) ; filePicker . putExtra ( FilePicker . SCOPE , mScope ) ; filePicker . putExtra ( FilePicker . REQUEST , requestCode ) ; filePicker . putExtra ( FilePicker . INTENT_EXTRA_COLOR_ID , color ) ; filePicker . putExtra ( FilePicker . MIME_TYPE , mimeType ) ; return filePicker ; }
Build the current intent .
1,146
public String getValidJavaIdentifier ( String name ) { if ( ! Character . isJavaIdentifierStart ( name . charAt ( 0 ) ) ) { name = "z" + name ; } return name ; }
Provides a valid java identifier from the given name . Currently only checks for a valid start character and adds z if the name has an invalid character at the start .
1,147
protected String getFullUrl ( String serviceName , String methodName , String id , ResultLimit resultLimit , String maskString ) { StringBuilder url = new StringBuilder ( baseUrl + serviceName ) ; if ( id != null ) { url . append ( '/' ) . append ( id ) ; } if ( methodName . startsWith ( "get" ) && ! "getObject" . equals ( methodName ) ) { url . append ( '/' ) . append ( methodName . substring ( 3 ) ) ; } else if ( ! IMPLICIT_SERVICE_METHODS . contains ( methodName ) ) { url . append ( '/' ) . append ( methodName ) ; } url . append ( ".json" ) ; if ( resultLimit != null ) { url . append ( "?resultLimit=" ) . append ( resultLimit . offset ) . append ( ',' ) . append ( resultLimit . limit ) ; } if ( maskString != null && ! maskString . isEmpty ( ) ) { url . append ( resultLimit == null ? '?' : '&' ) ; try { url . append ( "objectMask=" ) . append ( URLEncoder . encode ( maskString , "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } } return url . toString ( ) ; }
Get the full REST URL required to make a request .
1,148
public static Meta fromUrl ( URL url ) { InputStream stream = null ; try { stream = url . openStream ( ) ; Gson gson = new GsonBuilder ( ) . registerTypeAdapter ( PropertyForm . class , new TypeAdapter < PropertyForm > ( ) { public void write ( JsonWriter out , PropertyForm value ) throws IOException { out . value ( value . name ( ) . toLowerCase ( ) ) ; } public PropertyForm read ( JsonReader in ) throws IOException { return PropertyForm . valueOf ( in . nextString ( ) . toUpperCase ( ) ) ; } } ) . create ( ) ; Map < String , Type > types = gson . fromJson ( new InputStreamReader ( stream ) , new TypeToken < Map < String , Type > > ( ) { } . getType ( ) ) ; return new Meta ( types ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } finally { if ( stream != null ) { try { stream . close ( ) ; } catch ( Exception e ) { } } } }
Reads a JSON object from the given metadata URL and generates a new Meta object containing all types .
1,149
public String getHeader ( ) { String authPair = username + ':' + apiKey ; return "Basic " + Base64 . getEncoder ( ) . encodeToString ( authPair . getBytes ( ) ) ; }
Gets the encoded representation of the basic authentication credentials for use in an HTTP Authorization header .
1,150
public void setUnknownProperties ( Map < String , Object > unknownProperties ) { this . unknownProperties = Collections . unmodifiableMap ( new HashMap < > ( unknownProperties ) ) ; }
Set the unknown properties for this type . The values are copied to an immutable map . Note these values are NOT serialized into the type .
1,151
public static Event createEventFromString ( final String in ) throws AppPlatformException { JSONObject jsonObj = null ; try { jsonObj = ( JSONObject ) new JSONParser ( ) . parse ( in ) ; } catch ( final org . json . simple . parser . ParseException e ) { throw new AppPlatformException ( e ) ; } final EventType eventType = EventType . getEnum ( ( String ) jsonObj . get ( "eventType" ) ) ; Event event = null ; switch ( eventType ) { case INCOMINGCALL : event = new IncomingCallEvent ( jsonObj ) ; break ; case ANSWER : event = new AnswerEvent ( jsonObj ) ; break ; case SPEAK : event = new SpeakEvent ( jsonObj ) ; break ; case PLAYBACK : event = new PlaybackEvent ( jsonObj ) ; break ; case GATHER : event = new GatherEvent ( jsonObj ) ; break ; case HANGUP : event = new HangupEvent ( jsonObj ) ; break ; case DTMF : event = new DtmfEvent ( jsonObj ) ; break ; case REJECT : event = new RejectEvent ( jsonObj ) ; break ; case RECORDING : event = new RecordingEvent ( jsonObj ) ; break ; case TRANSCRIPTION : event = new TranscriptionEvent ( jsonObj ) ; break ; case SMS : event = new SmsEvent ( jsonObj ) ; break ; case TIMEOUT : event = new TimeoutEvent ( jsonObj ) ; break ; case CONFERENCE : event = new ConferenceEvent ( jsonObj ) ; break ; case CONFERENCE_MEMBER : event = new ConferenceMemberEvent ( jsonObj ) ; break ; case CONFERENCE_PLAYBACK : event = new ConferencePlaybackEvent ( jsonObj ) ; break ; case CONFERENCE_SPEAK : event = new ConferenceSpeakEvent ( jsonObj ) ; break ; default : event = new EventBase ( jsonObj ) ; } return event ; }
This method creates an event from a json string . Given an event from the App Plotform API the whole body can be passed in and the appropriate Event subclass will be returned .
1,152
public static Message get ( final BandwidthClient client , final String id ) throws Exception { final String messagesUri = client . getUserResourceInstanceUri ( BandwidthConstants . MESSAGES_URI_PATH , id ) ; final JSONObject jsonObject = toJSONObject ( client . get ( messagesUri , null ) ) ; return new Message ( client , jsonObject ) ; }
Gets information about a previously sent or received message .
1,153
public static Message create ( final String to , final String from , final String text ) throws Exception { final Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "to" , to ) ; params . put ( "from" , from ) ; params . put ( "text" , text ) ; return create ( params ) ; }
Convenience factory method to send a message given the to number the from number and the text
1,154
public static Message create ( final String to , final String from , final String text , final ReceiptRequest receiptRequest ) throws Exception { final Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "to" , to ) ; params . put ( "from" , from ) ; params . put ( "text" , text ) ; if ( receiptRequest != null ) { params . put ( "receiptRequested" , receiptRequest . toString ( ) ) ; } else { params . put ( "receiptRequested" , ReceiptRequest . NONE . toString ( ) ) ; } return create ( params ) ; }
Convenience factory method to send a message with receipt given the to number the from number and the text
1,155
public static Message create ( final BandwidthClient client , final Map < String , Object > params ) throws Exception { final String messageUri = client . getUserResourceUri ( BandwidthConstants . MESSAGES_URI_PATH ) ; final RestResponse response = client . post ( messageUri , params ) ; final String messageId = response . getLocation ( ) . substring ( client . getPath ( messageUri ) . length ( ) + 1 ) ; return get ( client , messageId ) ; }
Factory method to send a message from a params object given a client instance
1,156
public static PhoneNumber create ( final BandwidthClient client , final Map < String , Object > params ) throws Exception { final String uri = client . getUserResourceUri ( BandwidthConstants . PHONE_NUMBER_URI_PATH ) ; final RestResponse createResponse = client . post ( uri , params ) ; final RestResponse getResponse = client . get ( createResponse . getLocation ( ) , null ) ; final JSONObject jsonObject = toJSONObject ( getResponse ) ; return new PhoneNumber ( client , jsonObject ) ; }
Factory method to allocate a phone number given a set of params . Note that this assumes that the phone number has been previously search for as an AvailableNumber
1,157
public void commit ( ) throws Exception { final Map < String , Object > params = new HashMap < String , Object > ( ) ; final String applicationId = getPropertyAsString ( "applicationId" ) ; if ( applicationId != null ) params . put ( "applicationId" , applicationId ) ; final String name = getName ( ) ; if ( name != null ) params . put ( "name" , name ) ; final String fallbackNumber = getFallbackNumber ( ) ; if ( fallbackNumber != null ) params . put ( "fallbackNumber" , fallbackNumber ) ; final String uri = getUri ( ) ; client . post ( uri , params ) ; final JSONObject object = toJSONObject ( client . get ( uri , null ) ) ; updateProperties ( object ) ; }
Makes changes to a number you have .
1,158
public static Application get ( final String id ) throws Exception { assert ( id != null ) ; final BandwidthClient client = BandwidthClient . getInstance ( ) ; return Application . get ( client , id ) ; }
Factory method for Application . Returns Application object from id
1,159
public static Application get ( final BandwidthClient client , final String id ) throws Exception { assert ( id != null ) ; final String applicationUri = client . getUserResourceInstanceUri ( BandwidthConstants . APPLICATIONS_URI_PATH , id ) ; final JSONObject applicationObj = toJSONObject ( client . get ( applicationUri , null ) ) ; final Application application = new Application ( client , applicationObj ) ; return application ; }
Factory method for Application returns Application object
1,160
public static ResourceList < Application > list ( final int page , final int size ) throws IOException { final BandwidthClient client = BandwidthClient . getInstance ( ) ; return list ( client , page , size ) ; }
Factory method for Application list . Returns a list of Application object with page and size preferences
1,161
public static ResourceList < Application > list ( final BandwidthClient client , final int page , final int size ) throws IOException { final String applicationUri = client . getUserResourceUri ( BandwidthConstants . APPLICATIONS_URI_PATH ) ; final ResourceList < Application > applications = new ResourceList < Application > ( page , size , applicationUri , Application . class ) ; applications . setClient ( client ) ; applications . initialize ( ) ; return applications ; }
Factory method for Application list . Returns a list of Application object with page and size preferences Allow different Client implementaitons
1,162
public static Application create ( final String name ) throws Exception { final Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "name" , name ) ; return create ( params ) ; }
Convenience factory method to create an Application object with a given name
1,163
public static Application create ( final Map < String , Object > params ) throws Exception { return create ( BandwidthClient . getInstance ( ) , params ) ; }
Convenience factory method to create an Application object from a set of params
1,164
public static Application create ( final BandwidthClient client , final Map < String , Object > params ) throws Exception { assert ( client != null ) ; String uri = client . getUserResourceUri ( BandwidthConstants . APPLICATIONS_URI_PATH ) ; RestResponse response = client . post ( uri , params ) ; RestResponse getResponse = client . get ( response . getLocation ( ) , null ) ; return new Application ( client , toJSONObject ( getResponse ) ) ; }
Convenience factory method to create an Application object from a set of params with a given client
1,165
public void commit ( ) throws IOException , AppPlatformException { final Map < String , Object > params = toMap ( ) ; params . remove ( "id" ) ; client . post ( getUri ( ) , params ) ; }
Makes changes of the application .
1,166
private static void validateCredentials ( ) { try { Account . get ( ) . getAccountInfo ( ) ; } catch ( Exception e ) { if ( e instanceof AppPlatformException ) { AppPlatformException appEx = ( AppPlatformException ) e ; if ( appEx . getStatus ( ) == 401 ) { throw new InvalidCredentialsException ( ) ; } } else { throw new RuntimeException ( e ) ; } } }
Validate if the credentials are set and has access to catapult
1,167
public String getUserResourceInstanceUri ( final String path , final String instanceId ) { if ( StringUtils . isEmpty ( path ) || StringUtils . isEmpty ( instanceId ) ) { throw new IllegalArgumentException ( "Path and Instance Id cannot be null" ) ; } return getUserResourceUri ( path ) + "/" + instanceId ; }
Convenience method that returns the resource instance uri . E . g .
1,168
public RestResponse get ( final String uri , final Map < String , Object > params ) throws Exception { final String path = getPath ( uri ) ; final RestResponse response = request ( path , HttpGet . METHOD_NAME , params ) ; if ( response . isError ( ) ) { throw new IOException ( response . getResponseText ( ) ) ; } return response ; }
This method implements an HTTP GET . Use this method to retrieve a resource .
1,169
public RestResponse put ( final String uri , final Map < String , Object > params ) throws IOException , AppPlatformException { return request ( getPath ( uri ) , HttpPut . METHOD_NAME , params ) ; }
This method implements an HTTP put . Use this method to update a resource .
1,170
public RestResponse delete ( final String uri ) throws IOException , AppPlatformException { return request ( getPath ( uri ) , HttpDelete . METHOD_NAME ) ; }
This method implements an HTTP delete . Use this method to remove a resource .
1,171
public void upload ( final String uri , final File sourceFile , final String contentType ) throws IOException , AppPlatformException { final String path = getPath ( uri ) ; final HttpPut request = ( HttpPut ) setupRequest ( path , HttpPut . METHOD_NAME , null ) ; request . setEntity ( contentType == null ? new FileEntity ( sourceFile ) : new FileEntity ( sourceFile , ContentType . parse ( contentType ) ) ) ; performRequest ( request ) ; }
Convenience method to upload files to the server . User to upload media .
1,172
public void download ( final String uri , final File destFile ) throws IOException { final String path = getPath ( uri ) ; final HttpGet request = ( HttpGet ) setupRequest ( path , HttpGet . METHOD_NAME , Collections . < String , Object > emptyMap ( ) ) ; HttpResponse response ; OutputStream outputStream = null ; try { response = httpClient . execute ( request ) ; final HttpEntity entity = response . getEntity ( ) ; final StatusLine status = response . getStatusLine ( ) ; final int statusCode = status . getStatusCode ( ) ; if ( statusCode >= 400 ) { throw new IOException ( EntityUtils . toString ( entity ) ) ; } outputStream = new BufferedOutputStream ( new FileOutputStream ( destFile ) ) ; entity . writeTo ( outputStream ) ; } catch ( final ClientProtocolException e1 ) { throw new IOException ( e1 ) ; } catch ( final IOException e1 ) { throw new IOException ( e1 ) ; } finally { try { if ( outputStream != null ) { outputStream . close ( ) ; } } catch ( final IOException ignore ) { } } }
Convenience method to download files from the server . Used to retrieve media files .
1,173
protected RestResponse performRequest ( final HttpUriRequest request ) throws IOException , AppPlatformException { if ( this . usersUri == null || this . usersUri . isEmpty ( ) || this . token == null || this . token . isEmpty ( ) || this . secret == null || this . secret . isEmpty ( ) ) { throw new MissingCredentialsException ( ) ; } RestResponse restResponse = RestResponse . createRestResponse ( httpClient . execute ( request ) ) ; if ( restResponse . getStatus ( ) >= 400 ) { throw new AppPlatformException ( restResponse . getResponseText ( ) , restResponse . getStatus ( ) ) ; } return restResponse ; }
Helper method that executes the request on the server .
1,174
protected HttpUriRequest buildMethod ( final String method , final String path , final Map < String , Object > params ) { if ( StringUtils . equalsIgnoreCase ( method , HttpGet . METHOD_NAME ) ) { return generateGetRequest ( path , params ) ; } else if ( StringUtils . equalsIgnoreCase ( method , HttpPost . METHOD_NAME ) ) { return generatePostRequest ( path , params ) ; } else if ( StringUtils . equalsIgnoreCase ( method , HttpPut . METHOD_NAME ) ) { return generatePutRequest ( path , params ) ; } else if ( StringUtils . equalsIgnoreCase ( method , HttpDelete . METHOD_NAME ) ) { return generateDeleteRequest ( path ) ; } else { throw new RuntimeException ( "Must not be here." ) ; } }
Helper method that builds the request to the server .
1,175
protected HttpGet generateGetRequest ( final String path , final Map < String , Object > paramMap ) { final List < NameValuePair > pairs = new ArrayList < NameValuePair > ( ) ; for ( final String key : paramMap . keySet ( ) ) { pairs . add ( new BasicNameValuePair ( key , paramMap . get ( key ) . toString ( ) ) ) ; } final URI uri = buildUri ( path , pairs ) ; return new HttpGet ( uri ) ; }
Helper method to build the GET request for the server .
1,176
protected HttpPut generatePutRequest ( final String path , final Map < String , Object > paramMap ) { final HttpPut put = new HttpPut ( buildUri ( path ) ) ; if ( paramMap != null ) { put . setEntity ( new StringEntity ( JSONObject . toJSONString ( paramMap ) , ContentType . APPLICATION_JSON ) ) ; } return put ; }
Helper method to build the PUT request for the server .
1,177
protected URI buildUri ( final String path , final List < NameValuePair > queryStringParams ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( path ) ; if ( queryStringParams != null && queryStringParams . size ( ) > 0 ) { sb . append ( "?" ) . append ( URLEncodedUtils . format ( queryStringParams , "UTF-8" ) ) ; } try { return new URI ( sb . toString ( ) ) ; } catch ( final URISyntaxException e ) { throw new IllegalStateException ( "Invalid uri" , e ) ; } }
Helper method to return URI query parameters
1,178
public static Bridge get ( final String id ) throws Exception { final BandwidthClient client = BandwidthClient . getInstance ( ) ; return get ( client , id ) ; }
Convenience method to get information about a specific bridge . Returns a Bridge object given an id
1,179
public static Bridge get ( final BandwidthClient client , final String id ) throws Exception { assert ( client != null ) ; final String bridgesUri = client . getUserResourceInstanceUri ( BandwidthConstants . BRIDGES_URI_PATH , id ) ; final JSONObject jsonObject = toJSONObject ( client . get ( bridgesUri , null ) ) ; return new Bridge ( client , jsonObject ) ; }
Convenience method to return a bridge object given a client and an id
1,180
public static Bridge create ( final Call call1 , final Call call2 ) throws Exception { assert ( call1 != null ) ; final String callId1 = call1 . getId ( ) ; final String callId2 = call2 . getId ( ) ; return Bridge . create ( callId1 , callId2 ) ; }
Convenience factory method to create a Bridge object from two Call objects
1,181
public static Bridge create ( final String callId1 , final String callId2 ) throws Exception { assert ( callId1 != null ) ; final BandwidthClient client = BandwidthClient . getInstance ( ) ; return create ( client , callId1 , callId2 ) ; }
Convenience factory method to create a Bridge object from two call ids
1,182
public static Bridge create ( final BandwidthClient client , final String callId1 , final String callId2 ) throws Exception { assert ( callId1 != null ) ; final HashMap < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "bridgeAudio" , "true" ) ; String [ ] callIds = null ; if ( callId1 != null && callId2 != null ) { callIds = new String [ ] { callId1 , callId2 } ; } else if ( callId1 != null && callId2 == null ) { callIds = new String [ ] { callId1 } ; } else if ( callId1 == null && callId2 != null ) { callIds = new String [ ] { callId2 } ; } params . put ( "callIds" , callIds == null ? Collections . emptyList ( ) : Arrays . asList ( callIds ) ) ; return create ( client , params ) ; }
Convenience method to create a Bridge object from two call ids
1,183
public static Bridge create ( final BandwidthClient client , final Map < String , Object > params ) throws Exception { assert ( client != null && params != null ) ; final String bridgesUri = client . getUserResourceUri ( BandwidthConstants . BRIDGES_URI_PATH ) ; final RestResponse response = client . post ( bridgesUri , params ) ; final JSONObject callObj = toJSONObject ( client . get ( response . getLocation ( ) , null ) ) ; final Bridge bridge = new Bridge ( client , callObj ) ; return bridge ; }
Convenience factory method to create a Bridge object from a params maps
1,184
public List < Call > getBridgeCalls ( ) throws Exception { final String callsPath = StringUtils . join ( new String [ ] { getUri ( ) , "calls" } , '/' ) ; final JSONArray jsonArray = toJSONArray ( client . get ( callsPath , null ) ) ; final List < Call > callList = new ArrayList < Call > ( ) ; for ( final Object obj : jsonArray ) { callList . add ( new Call ( client , ( JSONObject ) obj ) ) ; } return callList ; }
Gets list of calls that are on the bridge
1,185
public void commit ( ) throws IOException , AppPlatformException { final Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "bridgeAudio" , isBridgeAudio ( ) ) ; final String [ ] callIds = getCallIds ( ) ; params . put ( "callIds" , callIds == null ? Collections . emptyList ( ) : Arrays . asList ( callIds ) ) ; client . post ( getUri ( ) , params ) ; }
Makes changes ob the bridge .
1,186
public static Error get ( final BandwidthClient client , final String id ) throws Exception { final String errorsUri = client . getUserResourceInstanceUri ( BandwidthConstants . ERRORS_URI_PATH , id ) ; final JSONObject jsonObject = toJSONObject ( client . get ( errorsUri , null ) ) ; return new Error ( client , errorsUri , jsonObject ) ; }
Factory method for Error . Returns Error object from id .
1,187
public static ResourceList < AvailableNumber > list ( final int page , final int size ) throws IOException { return list ( BandwidthClient . getInstance ( ) , page , size ) ; }
Factory method for AvailableNumber list returns list of AvailableNumber objects with page size preferences
1,188
public static ResourceList < AvailableNumber > list ( final BandwidthClient client , final int page , final int size ) throws IOException { final String availableNumbersUri = client . getUserResourceUri ( BandwidthConstants . AVAILABLE_NUMBERS_URI_PATH ) ; final ResourceList < AvailableNumber > availableNumbers = new ResourceList < AvailableNumber > ( page , size , availableNumbersUri , AvailableNumber . class ) ; availableNumbers . setClient ( client ) ; availableNumbers . initialize ( ) ; return availableNumbers ; }
Factory method for AvailableNumber list returns list of AvailableNumber objects with page size preferences with a given client
1,189
public static List < AvailableNumber > searchLocal ( final Map < String , Object > params ) throws Exception { return searchLocal ( BandwidthClient . getInstance ( ) , params ) ; }
Convenience factory method to return local numbers based on a given search criteria
1,190
public static List < AvailableNumber > searchLocal ( final BandwidthClient client , final Map < String , Object > params ) throws Exception { final String tollFreeUri = BandwidthConstants . AVAILABLE_NUMBERS_LOCAL_URI_PATH ; final JSONArray array = toJSONArray ( client . get ( tollFreeUri , params ) ) ; final List < AvailableNumber > numbers = new ArrayList < AvailableNumber > ( ) ; for ( final Object obj : array ) { numbers . add ( new AvailableNumber ( client , ( JSONObject ) obj ) ) ; } return numbers ; }
Convenience factory method to return local numbers based on a given search criteria for a given client
1,191
public static Conference createConference ( final Map < String , Object > params ) throws Exception { return createConference ( BandwidthClient . getInstance ( ) , params ) ; }
Factory method to create a conference given a set of params
1,192
public static Conference createConference ( final BandwidthClient client , final Map < String , Object > params ) throws Exception { final String conferencesUri = client . getUserResourceUri ( BandwidthConstants . CONFERENCES_URI_PATH ) ; final RestResponse response = client . post ( conferencesUri , params ) ; final String id = response . getLocation ( ) . substring ( client . getPath ( conferencesUri ) . length ( ) + 1 ) ; return getConference ( client , id ) ; }
Factory method to create a conference given a set of params and a client object
1,193
public List < ConferenceMember > getMembers ( ) throws Exception { final String membersPath = StringUtils . join ( new String [ ] { getUri ( ) , "members" } , '/' ) ; final JSONArray array = toJSONArray ( client . get ( membersPath , null ) ) ; final List < ConferenceMember > members = new ArrayList < ConferenceMember > ( ) ; for ( final Object obj : array ) { members . add ( new ConferenceMember ( client , ( JSONObject ) obj ) ) ; } return members ; }
Gets list all members from a conference . If a member had already hung up or removed from conference it will be displayed as completed .
1,194
public static void delete ( final BandwidthClient client , final String domainId , final String endpointId , final String token ) throws AppPlatformException , ParseException , IOException { assert ( client != null && domainId != null && endpointId != null && endpointId != null ) ; deleteToken ( client , domainId , endpointId , token ) ; }
Permanently deletes the Endpoint token .
1,195
public static Call get ( final String callId ) throws Exception { final BandwidthClient client = BandwidthClient . getInstance ( ) ; return get ( client , callId ) ; }
Factory method for Call returns information about an active or completed call .
1,196
public static Call get ( final BandwidthClient client , final String callId ) throws Exception { final String callsUri = client . getUserResourceInstanceUri ( BandwidthConstants . CALLS_URI_PATH , callId ) ; final JSONObject jsonObject = toJSONObject ( client . get ( callsUri , null ) ) ; return new Call ( client , jsonObject ) ; }
Convenience factory method for Call returns a Call object given an id
1,197
public static Call create ( final String to , final String from ) throws Exception { return create ( to , from , "none" , null ) ; }
Convenience factory method to make an outbound call
1,198
public static Call create ( final String to , final String from , final String callbackUrl , final String tag ) throws Exception { assert ( to != null && from != null ) ; final Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "to" , to ) ; params . put ( "from" , from ) ; params . put ( "callbackUrl" , callbackUrl ) ; params . put ( "tag" , tag ) ; final Call call = create ( params ) ; return call ; }
Convenience method to dials a call from a phone number to a phone number
1,199
public List < Recording > getRecordings ( ) throws Exception { final String recordingsPath = StringUtils . join ( new String [ ] { getUri ( ) , "recordings" } , '/' ) ; final JSONArray array = toJSONArray ( client . get ( recordingsPath , null ) ) ; final List < Recording > list = new ArrayList < Recording > ( ) ; for ( final Object object : array ) { list . add ( new Recording ( client , recordingsPath , ( JSONObject ) object ) ) ; } return list ; }
Retrieve all recordings related to the call .