idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
150,100
protected Element createPageElement ( ) { String pstyle = "" ; PDRectangle layout = getCurrentMediaBox ( ) ; if ( layout != null ) { /*System.out.println("x1 " + layout.getLowerLeftX()); System.out.println("y1 " + layout.getLowerLeftY()); System.out.println("x2 " + layout.getUpperRightX()); System.out.println("y2 " + layout.getUpperRightY()); System.out.println("rot " + pdpage.findRotation());*/ float w = layout . getWidth ( ) ; float h = layout . getHeight ( ) ; final int rot = pdpage . getRotation ( ) ; if ( rot == 90 || rot == 270 ) { float x = w ; w = h ; h = x ; } pstyle = "width:" + w + UNIT + ";" + "height:" + h + UNIT + ";" ; pstyle += "overflow:hidden;" ; } else log . warn ( "No media box found" ) ; Element el = doc . createElement ( "div" ) ; el . setAttribute ( "id" , "page_" + ( pagecnt ++ ) ) ; el . setAttribute ( "class" , "page" ) ; el . setAttribute ( "style" , pstyle ) ; return el ; }
Creates an element that represents a single page .
299
10
150,101
protected Element createTextElement ( float width ) { Element el = doc . createElement ( "div" ) ; el . setAttribute ( "id" , "p" + ( textcnt ++ ) ) ; el . setAttribute ( "class" , "p" ) ; String style = curstyle . toString ( ) ; style += "width:" + width + UNIT + ";" ; el . setAttribute ( "style" , style ) ; return el ; }
Creates an element that represents a single positioned box with no content .
99
14
150,102
protected Element createTextElement ( String data , float width ) { Element el = createTextElement ( width ) ; Text text = doc . createTextNode ( data ) ; el . appendChild ( text ) ; return el ; }
Creates an element that represents a single positioned box containing the specified text string .
47
16
150,103
protected Element createRectangleElement ( float x , float y , float width , float height , boolean stroke , boolean fill ) { float lineWidth = transformWidth ( getGraphicsState ( ) . getLineWidth ( ) ) ; float wcor = stroke ? lineWidth : 0.0f ; float strokeOffset = wcor == 0 ? 0 : wcor / 2 ; width = width - wcor < 0 ? 1 : width - wcor ; height = height - wcor < 0 ? 1 : height - wcor ; StringBuilder pstyle = new StringBuilder ( 50 ) ; pstyle . append ( "left:" ) . append ( style . formatLength ( x - strokeOffset ) ) . append ( ' ' ) ; pstyle . append ( "top:" ) . append ( style . formatLength ( y - strokeOffset ) ) . append ( ' ' ) ; pstyle . append ( "width:" ) . append ( style . formatLength ( width ) ) . append ( ' ' ) ; pstyle . append ( "height:" ) . append ( style . formatLength ( height ) ) . append ( ' ' ) ; if ( stroke ) { String color = colorString ( getGraphicsState ( ) . getStrokingColor ( ) ) ; pstyle . append ( "border:" ) . append ( style . formatLength ( lineWidth ) ) . append ( " solid " ) . append ( color ) . append ( ' ' ) ; } if ( fill ) { String fcolor = colorString ( getGraphicsState ( ) . getNonStrokingColor ( ) ) ; pstyle . append ( "background-color:" ) . append ( fcolor ) . append ( ' ' ) ; } Element el = doc . createElement ( "div" ) ; el . setAttribute ( "class" , "r" ) ; el . setAttribute ( "style" , pstyle . toString ( ) ) ; el . appendChild ( doc . createEntityReference ( "nbsp" ) ) ; return el ; }
Creates an element that represents a rectangle drawn at the specified coordinates in the page .
421
17
150,104
protected Element createLineElement ( float x1 , float y1 , float x2 , float y2 ) { HtmlDivLine line = new HtmlDivLine ( x1 , y1 , x2 , y2 ) ; String color = colorString ( getGraphicsState ( ) . getStrokingColor ( ) ) ; StringBuilder pstyle = new StringBuilder ( 50 ) ; pstyle . append ( "left:" ) . append ( style . formatLength ( line . getLeft ( ) ) ) . append ( ' ' ) ; pstyle . append ( "top:" ) . append ( style . formatLength ( line . getTop ( ) ) ) . append ( ' ' ) ; pstyle . append ( "width:" ) . append ( style . formatLength ( line . getWidth ( ) ) ) . append ( ' ' ) ; pstyle . append ( "height:" ) . append ( style . formatLength ( line . getHeight ( ) ) ) . append ( ' ' ) ; pstyle . append ( line . getBorderSide ( ) ) . append ( ' ' ) . append ( style . formatLength ( line . getLineStrokeWidth ( ) ) ) . append ( " solid " ) . append ( color ) . append ( ' ' ) ; if ( line . getAngleDegrees ( ) != 0 ) pstyle . append ( "transform:" ) . append ( "rotate(" ) . append ( line . getAngleDegrees ( ) ) . append ( "deg);" ) ; Element el = doc . createElement ( "div" ) ; el . setAttribute ( "class" , "r" ) ; el . setAttribute ( "style" , pstyle . toString ( ) ) ; el . appendChild ( doc . createEntityReference ( "nbsp" ) ) ; return el ; }
Create an element that represents a horizntal or vertical line .
389
14
150,105
protected Element createImageElement ( float x , float y , float width , float height , ImageResource resource ) throws IOException { StringBuilder pstyle = new StringBuilder ( "position:absolute;" ) ; pstyle . append ( "left:" ) . append ( x ) . append ( UNIT ) . append ( ' ' ) ; pstyle . append ( "top:" ) . append ( y ) . append ( UNIT ) . append ( ' ' ) ; pstyle . append ( "width:" ) . append ( width ) . append ( UNIT ) . append ( ' ' ) ; pstyle . append ( "height:" ) . append ( height ) . append ( UNIT ) . append ( ' ' ) ; //pstyle.append("border:1px solid red;"); Element el = doc . createElement ( "img" ) ; el . setAttribute ( "style" , pstyle . toString ( ) ) ; String imgSrc = config . getImageHandler ( ) . handleResource ( resource ) ; if ( ! disableImageData && ! imgSrc . isEmpty ( ) ) el . setAttribute ( "src" , imgSrc ) ; else el . setAttribute ( "src" , "" ) ; return el ; }
Creates an element that represents an image drawn at the specified coordinates in the page .
262
17
150,106
protected String createGlobalStyle ( ) { StringBuilder ret = new StringBuilder ( ) ; ret . append ( createFontFaces ( ) ) ; ret . append ( "\n" ) ; ret . append ( defaultStyle ) ; return ret . toString ( ) ; }
Generate the global CSS style for the whole document .
56
11
150,107
public void createPdfLayout ( Dimension dim ) { if ( pdfdocument != null ) //processing a PDF document { try { if ( createImage ) img = new BufferedImage ( dim . width , dim . height , BufferedImage . TYPE_INT_RGB ) ; Graphics2D ig = img . createGraphics ( ) ; log . info ( "Creating PDF boxes" ) ; VisualContext ctx = new VisualContext ( null , null ) ; boxtree = new CSSBoxTree ( ig , ctx , dim , baseurl ) ; boxtree . setConfig ( config ) ; boxtree . processDocument ( pdfdocument , startPage , endPage ) ; viewport = boxtree . getViewport ( ) ; root = boxtree . getDocument ( ) . getDocumentElement ( ) ; log . info ( "We have " + boxtree . getLastId ( ) + " boxes" ) ; viewport . initSubtree ( ) ; log . info ( "Layout for " + dim . width + "px" ) ; viewport . doLayout ( dim . width , true , true ) ; log . info ( "Resulting size: " + viewport . getWidth ( ) + "x" + viewport . getHeight ( ) + " (" + viewport + ")" ) ; log . info ( "Updating viewport size" ) ; viewport . updateBounds ( dim ) ; log . info ( "Resulting size: " + viewport . getWidth ( ) + "x" + viewport . getHeight ( ) + " (" + viewport + ")" ) ; if ( createImage && ( viewport . getWidth ( ) > dim . width || viewport . getHeight ( ) > dim . height ) ) { img = new BufferedImage ( Math . max ( viewport . getWidth ( ) , dim . width ) , Math . max ( viewport . getHeight ( ) , dim . height ) , BufferedImage . TYPE_INT_RGB ) ; ig = img . createGraphics ( ) ; } log . info ( "Positioning for " + img . getWidth ( ) + "x" + img . getHeight ( ) + "px" ) ; viewport . absolutePositions ( ) ; clearCanvas ( ) ; viewport . draw ( new GraphicsRenderer ( ig ) ) ; setPreferredSize ( new Dimension ( img . getWidth ( ) , img . getHeight ( ) ) ) ; revalidate ( ) ; } catch ( ParserConfigurationException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } else if ( root != null ) //processing a DOM tree { super . createLayout ( dim ) ; } }
Creates the box tree for the PDF file .
590
10
150,108
protected BlockBox createBlock ( BlockBox parent , Element n , boolean replaced ) { BlockBox root ; if ( replaced ) { BlockReplacedBox rbox = new BlockReplacedBox ( ( Element ) n , ( Graphics2D ) parent . getGraphics ( ) . create ( ) , parent . getVisualContext ( ) . create ( ) ) ; rbox . setViewport ( viewport ) ; rbox . setContentObj ( new ReplacedImage ( rbox , rbox . getVisualContext ( ) , baseurl , n . getAttribute ( "src" ) ) ) ; root = rbox ; } else { root = new BlockBox ( ( Element ) n , ( Graphics2D ) parent . getGraphics ( ) . create ( ) , parent . getVisualContext ( ) . create ( ) ) ; root . setViewport ( viewport ) ; } root . setBase ( baseurl ) ; root . setParent ( parent ) ; root . setContainingBlockBox ( parent ) ; root . setClipBlock ( viewport ) ; root . setOrder ( next_order ++ ) ; return root ; }
Creates a new block box from the given element with the given parent . No style is assigned to the resulting box .
236
24
150,109
protected TextBox createTextBox ( BlockBox contblock , Text n ) { TextBox text = new TextBox ( n , ( Graphics2D ) contblock . getGraphics ( ) . create ( ) , contblock . getVisualContext ( ) . create ( ) ) ; text . setOrder ( next_order ++ ) ; text . setContainingBlockBox ( contblock ) ; text . setClipBlock ( contblock ) ; text . setViewport ( viewport ) ; text . setBase ( baseurl ) ; return text ; }
Creates a text box with the given parent and text node assigned .
114
14
150,110
protected NodeData createBlockStyle ( ) { NodeData ret = CSSFactory . createNodeData ( ) ; TermFactory tf = CSSFactory . getTermFactory ( ) ; ret . push ( createDeclaration ( "display" , tf . createIdent ( "block" ) ) ) ; return ret ; }
Creates an empty block style definition .
63
8
150,111
protected NodeData createBodyStyle ( ) { NodeData ret = createBlockStyle ( ) ; TermFactory tf = CSSFactory . getTermFactory ( ) ; ret . push ( createDeclaration ( "background-color" , tf . createColor ( 255 , 255 , 255 ) ) ) ; return ret ; }
Creates a style definition used for the body element .
64
11
150,112
protected NodeData createPageStyle ( ) { NodeData ret = createBlockStyle ( ) ; TermFactory tf = CSSFactory . getTermFactory ( ) ; ret . push ( createDeclaration ( "position" , tf . createIdent ( "relative" ) ) ) ; ret . push ( createDeclaration ( "border-width" , tf . createLength ( 1f , Unit . px ) ) ) ; ret . push ( createDeclaration ( "border-style" , tf . createIdent ( "solid" ) ) ) ; ret . push ( createDeclaration ( "border-color" , tf . createColor ( 0 , 0 , 255 ) ) ) ; ret . push ( createDeclaration ( "margin" , tf . createLength ( 0.5f , Unit . em ) ) ) ; PDRectangle layout = getCurrentMediaBox ( ) ; if ( layout != null ) { float w = layout . getWidth ( ) ; float h = layout . getHeight ( ) ; final int rot = pdpage . getRotation ( ) ; if ( rot == 90 || rot == 270 ) { float x = w ; w = h ; h = x ; } ret . push ( createDeclaration ( "width" , tf . createLength ( w , unit ) ) ) ; ret . push ( createDeclaration ( "height" , tf . createLength ( h , unit ) ) ) ; } else log . warn ( "No media box found" ) ; return ret ; }
Creates a style definition used for pages .
314
9
150,113
protected NodeData createRectangleStyle ( float x , float y , float width , float height , boolean stroke , boolean fill ) { float lineWidth = transformLength ( ( float ) getGraphicsState ( ) . getLineWidth ( ) ) ; float lw = ( lineWidth < 1f ) ? 1f : lineWidth ; float wcor = stroke ? lw : 0.0f ; NodeData ret = CSSFactory . createNodeData ( ) ; TermFactory tf = CSSFactory . getTermFactory ( ) ; ret . push ( createDeclaration ( "position" , tf . createIdent ( "absolute" ) ) ) ; ret . push ( createDeclaration ( "left" , tf . createLength ( x , unit ) ) ) ; ret . push ( createDeclaration ( "top" , tf . createLength ( y , unit ) ) ) ; ret . push ( createDeclaration ( "width" , tf . createLength ( width - wcor , unit ) ) ) ; ret . push ( createDeclaration ( "height" , tf . createLength ( height - wcor , unit ) ) ) ; if ( stroke ) { ret . push ( createDeclaration ( "border-width" , tf . createLength ( lw , unit ) ) ) ; ret . push ( createDeclaration ( "border-style" , tf . createIdent ( "solid" ) ) ) ; String color = colorString ( getGraphicsState ( ) . getStrokingColor ( ) ) ; ret . push ( createDeclaration ( "border-color" , tf . createColor ( color ) ) ) ; } if ( fill ) { String color = colorString ( getGraphicsState ( ) . getNonStrokingColor ( ) ) ; if ( color != null ) ret . push ( createDeclaration ( "background-color" , tf . createColor ( color ) ) ) ; } return ret ; }
Creates the style definition used for a rectangle element based on the given properties of the rectangle
400
18
150,114
protected Declaration createDeclaration ( String property , Term < ? > term ) { Declaration d = CSSFactory . getRuleFactory ( ) . createDeclaration ( ) ; d . unlock ( ) ; d . setProperty ( property ) ; d . add ( term ) ; return d ; }
Creates a single property declaration .
59
7
150,115
private void init ( ) { style = new BoxStyle ( UNIT ) ; textLine = new StringBuilder ( ) ; textMetrics = null ; graphicsPath = new Vector < PathSegment > ( ) ; startPage = 0 ; endPage = Integer . MAX_VALUE ; fontTable = new FontTable ( ) ; }
Internal initialization .
68
3
150,116
protected void updateFontTable ( ) { PDResources resources = pdpage . getResources ( ) ; if ( resources != null ) { try { processFontResources ( resources , fontTable ) ; } catch ( IOException e ) { log . error ( "Error processing font resources: " + "Exception: {} {}" , e . getMessage ( ) , e . getClass ( ) ) ; } } }
Updates the font table by adding new fonts used at the current page .
85
15
150,117
protected void finishBox ( ) { if ( textLine . length ( ) > 0 ) { String s ; if ( isReversed ( Character . getDirectionality ( textLine . charAt ( 0 ) ) ) ) s = textLine . reverse ( ) . toString ( ) ; else s = textLine . toString ( ) ; curstyle . setLeft ( textMetrics . getX ( ) ) ; curstyle . setTop ( textMetrics . getTop ( ) ) ; curstyle . setLineHeight ( textMetrics . getHeight ( ) ) ; renderText ( s , textMetrics ) ; textLine = new StringBuilder ( ) ; textMetrics = null ; } }
Finishes the current box - empties the text line buffer and creates a DOM element from it .
148
20
150,118
protected void updateStyle ( BoxStyle bstyle , TextPosition text ) { String font = text . getFont ( ) . getName ( ) ; String family = null ; String weight = null ; String fstyle = null ; bstyle . setFontSize ( text . getFontSizeInPt ( ) ) ; bstyle . setLineHeight ( text . getHeight ( ) ) ; if ( font != null ) { //font style and weight for ( int i = 0 ; i < pdFontType . length ; i ++ ) { if ( font . toLowerCase ( ) . lastIndexOf ( pdFontType [ i ] ) >= 0 ) { weight = cssFontWeight [ i ] ; fstyle = cssFontStyle [ i ] ; break ; } } if ( weight != null ) bstyle . setFontWeight ( weight ) ; else bstyle . setFontWeight ( cssFontWeight [ 0 ] ) ; if ( fstyle != null ) bstyle . setFontStyle ( fstyle ) ; else bstyle . setFontStyle ( cssFontStyle [ 0 ] ) ; //font family //If it's a known common font don't embed in html output to save space String knownFontFamily = findKnownFontFamily ( font ) ; if ( ! knownFontFamily . equals ( "" ) ) family = knownFontFamily ; else { family = fontTable . getUsedName ( text . getFont ( ) ) ; if ( family == null ) family = font ; } if ( family != null ) bstyle . setFontFamily ( family ) ; } updateStyleForRenderingMode ( ) ; }
Updates the text style according to a new text position
338
11
150,119
protected float transformLength ( float w ) { Matrix ctm = getGraphicsState ( ) . getCurrentTransformationMatrix ( ) ; Matrix m = new Matrix ( ) ; m . setValue ( 2 , 0 , w ) ; return m . multiply ( ctm ) . getTranslateX ( ) ; }
Transforms a length according to the current transformation matrix .
64
11
150,120
protected float [ ] transformPosition ( float x , float y ) { Point2D . Float point = super . transformedPoint ( x , y ) ; AffineTransform pageTransform = createCurrentPageTransformation ( ) ; Point2D . Float transformedPoint = ( Point2D . Float ) pageTransform . transform ( point , null ) ; return new float [ ] { ( float ) transformedPoint . getX ( ) , ( float ) transformedPoint . getY ( ) } ; }
Transforms a position according to the current transformation matrix and current page transformation .
100
15
150,121
protected String stringValue ( COSBase value ) { if ( value instanceof COSString ) return ( ( COSString ) value ) . getString ( ) ; else if ( value instanceof COSNumber ) return String . valueOf ( ( ( COSNumber ) value ) . floatValue ( ) ) ; else return "" ; }
Obtains a string from a PDF value
71
8
150,122
protected String colorString ( PDColor pdcolor ) { String color = null ; try { float [ ] rgb = pdcolor . getColorSpace ( ) . toRGB ( pdcolor . getComponents ( ) ) ; color = colorString ( rgb [ 0 ] , rgb [ 1 ] , rgb [ 2 ] ) ; } catch ( IOException e ) { log . error ( "colorString: IOException: {}" , e . getMessage ( ) ) ; } catch ( UnsupportedOperationException e ) { log . error ( "colorString: UnsupportedOperationException: {}" , e . getMessage ( ) ) ; } return color ; }
Creates a CSS rgb specification from a PDF color
138
10
150,123
@ NonNull public static File [ ] listAllFiles ( File directory ) { if ( directory == null ) { return new File [ 0 ] ; } File [ ] files = directory . listFiles ( ) ; return files != null ? files : new File [ 0 ] ; }
Return list of all files in the directory .
57
9
150,124
static boolean isOnClasspath ( String className ) { boolean isOnClassPath = true ; try { Class . forName ( className ) ; } catch ( ClassNotFoundException exception ) { isOnClassPath = false ; } return isOnClassPath ; }
Checks if class is on class path
56
8
150,125
@ Nullable public static LocationEngineResult extractResult ( Intent intent ) { LocationEngineResult result = null ; if ( isOnClasspath ( GOOGLE_PLAY_LOCATION_RESULT ) ) { result = extractGooglePlayResult ( intent ) ; } return result == null ? extractAndroidResult ( intent ) : result ; }
Extracts location result from intent object
70
8
150,126
public void onRequestPermissionsResult ( int requestCode , String [ ] permissions , int [ ] grantResults ) { switch ( requestCode ) { case REQUEST_PERMISSIONS_CODE : if ( listener != null ) { boolean granted = grantResults . length > 0 && grantResults [ 0 ] == PackageManager . PERMISSION_GRANTED ; listener . onPermissionResult ( granted ) ; } break ; default : // Ignored } }
You should call this method from your activity onRequestPermissionsResult .
96
14
150,127
public static String retrieveVendorId ( ) { if ( MapboxTelemetry . applicationContext == null ) { return updateVendorId ( ) ; } SharedPreferences sharedPreferences = obtainSharedPreferences ( MapboxTelemetry . applicationContext ) ; String mapboxVendorId = sharedPreferences . getString ( MAPBOX_SHARED_PREFERENCE_KEY_VENDOR_ID , "" ) ; if ( TelemetryUtils . isEmpty ( mapboxVendorId ) ) { mapboxVendorId = TelemetryUtils . updateVendorId ( ) ; } return mapboxVendorId ; }
Do not call this method outside of activity!!!
135
9
150,128
private static boolean getSystemConnectivity ( Context context ) { try { ConnectivityManager cm = ( ConnectivityManager ) context . getSystemService ( Context . CONNECTIVITY_SERVICE ) ; if ( cm == null ) { return false ; } NetworkInfo activeNetwork = cm . getActiveNetworkInfo ( ) ; return activeNetwork . isConnectedOrConnecting ( ) ; } catch ( Exception exception ) { return false ; } }
Get the connectivity state as reported by the Android system
91
10
150,129
public static CrashReport fromJson ( String json ) throws IllegalArgumentException { try { return new CrashReport ( json ) ; } catch ( JSONException je ) { throw new IllegalArgumentException ( je . toString ( ) ) ; } }
Exports json encoded content to CrashReport object
52
9
150,130
static boolean uninstall ( ) { boolean uninstalled = false ; synchronized ( lock ) { if ( locationCollectionClient != null ) { locationCollectionClient . locationEngineController . onDestroy ( ) ; locationCollectionClient . settingsChangeHandlerThread . quit ( ) ; locationCollectionClient . sharedPreferences . unregisterOnSharedPreferenceChangeListener ( locationCollectionClient ) ; locationCollectionClient = null ; uninstalled = true ; } } return uninstalled ; }
Uninstall current location collection client .
93
7
150,131
@ Nullable public GeoTarget getCanonAncestor ( GeoTarget . Type type ) { for ( GeoTarget target = this ; target != null ; target = target . canonParent ( ) ) { if ( target . key . type == type ) { return target ; } } return null ; }
Finds an ancestor of a specific type if possible .
62
11
150,132
public byte [ ] encrypt ( byte [ ] plainData ) { checkArgument ( plainData . length >= OVERHEAD_SIZE , "Invalid plainData, %s bytes" , plainData . length ) ; // workBytes := initVector || payload || zeros:4 byte [ ] workBytes = plainData . clone ( ) ; ByteBuffer workBuffer = ByteBuffer . wrap ( workBytes ) ; boolean success = false ; try { // workBytes := initVector || payload || I(signature) int signature = hmacSignature ( workBytes ) ; workBuffer . putInt ( workBytes . length - SIGNATURE_SIZE , signature ) ; // workBytes := initVector || E(payload) || I(signature) xorPayloadToHmacPad ( workBytes ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( dump ( "Encrypted" , plainData , workBytes ) ) ; } success = true ; return workBytes ; } finally { if ( ! success && logger . isDebugEnabled ( ) ) { logger . debug ( dump ( "Encrypted (failed)" , plainData , workBytes ) ) ; } } }
Encrypts data .
246
5
150,133
public static BoxConfig readFrom ( Reader reader ) throws IOException { JsonObject config = JsonObject . readFrom ( reader ) ; JsonObject settings = ( JsonObject ) config . get ( "boxAppSettings" ) ; String clientId = settings . get ( "clientID" ) . asString ( ) ; String clientSecret = settings . get ( "clientSecret" ) . asString ( ) ; JsonObject appAuth = ( JsonObject ) settings . get ( "appAuth" ) ; String publicKeyId = appAuth . get ( "publicKeyID" ) . asString ( ) ; String privateKey = appAuth . get ( "privateKey" ) . asString ( ) ; String passphrase = appAuth . get ( "passphrase" ) . asString ( ) ; String enterpriseId = config . get ( "enterpriseID" ) . asString ( ) ; return new BoxConfig ( clientId , clientSecret , enterpriseId , publicKeyId , privateKey , passphrase ) ; }
Reads OAuth 2 . 0 with JWT app configurations from the reader . The file should be in JSON format .
217
24
150,134
public static BoxCollaborationWhitelist . Info create ( final BoxAPIConnection api , String domain , WhitelistDirection direction ) { URL url = COLLABORATION_WHITELIST_ENTRIES_URL_TEMPLATE . build ( api . getBaseURL ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( api , url , HttpMethod . POST ) ; JsonObject requestJSON = new JsonObject ( ) . add ( "domain" , domain ) . add ( "direction" , direction . toString ( ) ) ; request . setBody ( requestJSON . toString ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; BoxCollaborationWhitelist domainWhitelist = new BoxCollaborationWhitelist ( api , responseJSON . get ( "id" ) . asString ( ) ) ; return domainWhitelist . new Info ( responseJSON ) ; }
Creates a new Collaboration Whitelist for a domain .
224
12
150,135
public void delete ( ) { BoxAPIConnection api = this . getAPI ( ) ; URL url = COLLABORATION_WHITELIST_ENTRY_URL_TEMPLATE . build ( api . getBaseURL ( ) , this . getID ( ) ) ; BoxAPIRequest request = new BoxAPIRequest ( api , url , HttpMethod . DELETE ) ; BoxAPIResponse response = request . send ( ) ; response . disconnect ( ) ; }
Deletes this collaboration whitelist .
106
7
150,136
public static < T_Result , T_Source > List < T_Result > map ( Collection < T_Source > source , Mapper < T_Result , T_Source > mapper ) { List < T_Result > result = new LinkedList < T_Result > ( ) ; for ( T_Source element : source ) { result . add ( mapper . map ( element ) ) ; } return result ; }
Re - maps a provided collection .
90
7
150,137
public BoxFolder . Info createFolder ( String name ) { JsonObject parent = new JsonObject ( ) ; parent . add ( "id" , this . getID ( ) ) ; JsonObject newFolder = new JsonObject ( ) ; newFolder . add ( "name" , name ) ; newFolder . add ( "parent" , parent ) ; BoxJSONRequest request = new BoxJSONRequest ( this . getAPI ( ) , CREATE_FOLDER_URL . build ( this . getAPI ( ) . getBaseURL ( ) ) , "POST" ) ; request . setBody ( newFolder . toString ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; BoxFolder createdFolder = new BoxFolder ( this . getAPI ( ) , responseJSON . get ( "id" ) . asString ( ) ) ; return createdFolder . new Info ( responseJSON ) ; }
Creates a new child folder inside this folder .
219
10
150,138
public void rename ( String newName ) { URL url = FOLDER_INFO_URL_TEMPLATE . build ( this . getAPI ( ) . getBaseURL ( ) , this . getID ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( this . getAPI ( ) , url , "PUT" ) ; JsonObject updateInfo = new JsonObject ( ) ; updateInfo . add ( "name" , newName ) ; request . setBody ( updateInfo . toString ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; response . getJSON ( ) ; }
Renames this folder .
136
5
150,139
public BoxFile . Info uploadFile ( InputStream fileContent , String name , long fileSize , ProgressListener listener ) { FileUploadParams uploadInfo = new FileUploadParams ( ) . setContent ( fileContent ) . setName ( name ) . setSize ( fileSize ) . setProgressListener ( listener ) ; return this . uploadFile ( uploadInfo ) ; }
Uploads a new file to this folder while reporting the progress to a ProgressListener .
78
17
150,140
public BoxFile . Info uploadFile ( FileUploadParams uploadParams ) { URL uploadURL = UPLOAD_FILE_URL . build ( this . getAPI ( ) . getBaseUploadURL ( ) ) ; BoxMultipartRequest request = new BoxMultipartRequest ( getAPI ( ) , uploadURL ) ; JsonObject fieldJSON = new JsonObject ( ) ; JsonObject parentIdJSON = new JsonObject ( ) ; parentIdJSON . add ( "id" , getID ( ) ) ; fieldJSON . add ( "name" , uploadParams . getName ( ) ) ; fieldJSON . add ( "parent" , parentIdJSON ) ; if ( uploadParams . getCreated ( ) != null ) { fieldJSON . add ( "content_created_at" , BoxDateFormat . format ( uploadParams . getCreated ( ) ) ) ; } if ( uploadParams . getModified ( ) != null ) { fieldJSON . add ( "content_modified_at" , BoxDateFormat . format ( uploadParams . getModified ( ) ) ) ; } if ( uploadParams . getSHA1 ( ) != null && ! uploadParams . getSHA1 ( ) . isEmpty ( ) ) { request . setContentSHA1 ( uploadParams . getSHA1 ( ) ) ; } if ( uploadParams . getDescription ( ) != null ) { fieldJSON . add ( "description" , uploadParams . getDescription ( ) ) ; } request . putField ( "attributes" , fieldJSON . toString ( ) ) ; if ( uploadParams . getSize ( ) > 0 ) { request . setFile ( uploadParams . getContent ( ) , uploadParams . getName ( ) , uploadParams . getSize ( ) ) ; } else if ( uploadParams . getContent ( ) != null ) { request . setFile ( uploadParams . getContent ( ) , uploadParams . getName ( ) ) ; } else { request . setUploadFileCallback ( uploadParams . getUploadFileCallback ( ) , uploadParams . getName ( ) ) ; } BoxJSONResponse response ; if ( uploadParams . getProgressListener ( ) == null ) { response = ( BoxJSONResponse ) request . send ( ) ; } else { response = ( BoxJSONResponse ) request . send ( uploadParams . getProgressListener ( ) ) ; } JsonObject collection = JsonObject . readFrom ( response . getJSON ( ) ) ; JsonArray entries = collection . get ( "entries" ) . asArray ( ) ; JsonObject fileInfoJSON = entries . get ( 0 ) . asObject ( ) ; String uploadedFileID = fileInfoJSON . get ( "id" ) . asString ( ) ; BoxFile uploadedFile = new BoxFile ( getAPI ( ) , uploadedFileID ) ; return uploadedFile . new Info ( fileInfoJSON ) ; }
Uploads a new file to this folder with custom upload parameters .
630
13
150,141
public Iterable < BoxItem . Info > getChildren ( final String ... fields ) { return new Iterable < BoxItem . Info > ( ) { @ Override public Iterator < BoxItem . Info > iterator ( ) { String queryString = new QueryStringBuilder ( ) . appendParam ( "fields" , fields ) . toString ( ) ; URL url = GET_ITEMS_URL . buildWithQuery ( getAPI ( ) . getBaseURL ( ) , queryString , getID ( ) ) ; return new BoxItemIterator ( getAPI ( ) , url ) ; } } ; }
Returns an iterable containing the items in this folder and specifies which child fields to retrieve from the API .
125
21
150,142
public Iterable < BoxItem . Info > getChildren ( String sort , SortDirection direction , final String ... fields ) { QueryStringBuilder builder = new QueryStringBuilder ( ) . appendParam ( "sort" , sort ) . appendParam ( "direction" , direction . toString ( ) ) ; if ( fields . length > 0 ) { builder . appendParam ( "fields" , fields ) . toString ( ) ; } final String query = builder . toString ( ) ; return new Iterable < BoxItem . Info > ( ) { @ Override public Iterator < BoxItem . Info > iterator ( ) { URL url = GET_ITEMS_URL . buildWithQuery ( getAPI ( ) . getBaseURL ( ) , query , getID ( ) ) ; return new BoxItemIterator ( getAPI ( ) , url ) ; } } ; }
Returns an iterable containing the items in this folder sorted by name and direction .
181
16
150,143
public PartialCollection < BoxItem . Info > getChildrenRange ( long offset , long limit , String ... fields ) { QueryStringBuilder builder = new QueryStringBuilder ( ) . appendParam ( "limit" , limit ) . appendParam ( "offset" , offset ) ; if ( fields . length > 0 ) { builder . appendParam ( "fields" , fields ) . toString ( ) ; } URL url = GET_ITEMS_URL . buildWithQuery ( getAPI ( ) . getBaseURL ( ) , builder . toString ( ) , getID ( ) ) ; BoxAPIRequest request = new BoxAPIRequest ( this . getAPI ( ) , url , "GET" ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; String totalCountString = responseJSON . get ( "total_count" ) . toString ( ) ; long fullSize = Double . valueOf ( totalCountString ) . longValue ( ) ; PartialCollection < BoxItem . Info > children = new PartialCollection < BoxItem . Info > ( offset , limit , fullSize ) ; JsonArray jsonArray = responseJSON . get ( "entries" ) . asArray ( ) ; for ( JsonValue value : jsonArray ) { JsonObject jsonObject = value . asObject ( ) ; BoxItem . Info parsedItemInfo = ( BoxItem . Info ) BoxResource . parseInfo ( this . getAPI ( ) , jsonObject ) ; if ( parsedItemInfo != null ) { children . add ( parsedItemInfo ) ; } } return children ; }
Retrieves a specific range of child items in this folder .
352
13
150,144
@ Override public Iterator < BoxItem . Info > iterator ( ) { URL url = GET_ITEMS_URL . build ( this . getAPI ( ) . getBaseURL ( ) , BoxFolder . this . getID ( ) ) ; return new BoxItemIterator ( BoxFolder . this . getAPI ( ) , url ) ; }
Returns an iterator over the items in this folder .
72
10
150,145
public Metadata createMetadata ( String templateName , Metadata metadata ) { String scope = Metadata . scopeBasedOnType ( templateName ) ; return this . createMetadata ( templateName , scope , metadata ) ; }
Creates metadata on this folder using a specified template .
47
11
150,146
public Metadata createMetadata ( String templateName , String scope , Metadata metadata ) { URL url = METADATA_URL_TEMPLATE . build ( this . getAPI ( ) . getBaseURL ( ) , this . getID ( ) , scope , templateName ) ; BoxAPIRequest request = new BoxAPIRequest ( this . getAPI ( ) , url , "POST" ) ; request . addHeader ( "Content-Type" , "application/json" ) ; request . setBody ( metadata . toString ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; return new Metadata ( JsonObject . readFrom ( response . getJSON ( ) ) ) ; }
Creates metadata on this folder using a specified scope and template .
154
13
150,147
public Metadata setMetadata ( String templateName , String scope , Metadata metadata ) { Metadata metadataValue = null ; try { metadataValue = this . createMetadata ( templateName , scope , metadata ) ; } catch ( BoxAPIException e ) { if ( e . getResponseCode ( ) == 409 ) { Metadata metadataToUpdate = new Metadata ( scope , templateName ) ; for ( JsonValue value : metadata . getOperations ( ) ) { if ( value . asObject ( ) . get ( "value" ) . isNumber ( ) ) { metadataToUpdate . add ( value . asObject ( ) . get ( "path" ) . asString ( ) , value . asObject ( ) . get ( "value" ) . asFloat ( ) ) ; } else if ( value . asObject ( ) . get ( "value" ) . isString ( ) ) { metadataToUpdate . add ( value . asObject ( ) . get ( "path" ) . asString ( ) , value . asObject ( ) . get ( "value" ) . asString ( ) ) ; } else if ( value . asObject ( ) . get ( "value" ) . isArray ( ) ) { ArrayList < String > list = new ArrayList < String > ( ) ; for ( JsonValue jsonValue : value . asObject ( ) . get ( "value" ) . asArray ( ) ) { list . add ( jsonValue . asString ( ) ) ; } metadataToUpdate . add ( value . asObject ( ) . get ( "path" ) . asString ( ) , list ) ; } } metadataValue = this . updateMetadata ( metadataToUpdate ) ; } } return metadataValue ; }
Sets the provided metadata on the folder overwriting any existing metadata keys already present .
368
18
150,148
public Metadata getMetadata ( String templateName ) { String scope = Metadata . scopeBasedOnType ( templateName ) ; return this . getMetadata ( templateName , scope ) ; }
Gets the metadata on this folder associated with a specified template .
41
13
150,149
public void deleteMetadata ( String templateName ) { String scope = Metadata . scopeBasedOnType ( templateName ) ; this . deleteMetadata ( templateName , scope ) ; }
Deletes the metadata on this folder associated with a specified template .
39
13
150,150
public void deleteMetadata ( String templateName , String scope ) { URL url = METADATA_URL_TEMPLATE . build ( this . getAPI ( ) . getBaseURL ( ) , this . getID ( ) , scope , templateName ) ; BoxAPIRequest request = new BoxAPIRequest ( this . getAPI ( ) , url , "DELETE" ) ; BoxAPIResponse response = request . send ( ) ; response . disconnect ( ) ; }
Deletes the metadata on this folder associated with a specified scope and template .
102
15
150,151
public String addClassification ( String classificationType ) { Metadata metadata = new Metadata ( ) . add ( Metadata . CLASSIFICATION_KEY , classificationType ) ; Metadata classification = this . createMetadata ( Metadata . CLASSIFICATION_TEMPLATE_KEY , "enterprise" , metadata ) ; return classification . getString ( Metadata . CLASSIFICATION_KEY ) ; }
Adds a metadata classification to the specified file .
85
9
150,152
public BoxFile . Info uploadLargeFile ( InputStream inputStream , String fileName , long fileSize ) throws InterruptedException , IOException { URL url = UPLOAD_SESSION_URL_TEMPLATE . build ( this . getAPI ( ) . getBaseUploadURL ( ) ) ; return new LargeFileUpload ( ) . upload ( this . getAPI ( ) , this . getID ( ) , inputStream , url , fileName , fileSize ) ; }
Creates a new file .
101
6
150,153
public Iterable < BoxMetadataCascadePolicy . Info > getMetadataCascadePolicies ( String ... fields ) { Iterable < BoxMetadataCascadePolicy . Info > cascadePoliciesInfo = BoxMetadataCascadePolicy . getAll ( this . getAPI ( ) , this . getID ( ) , fields ) ; return cascadePoliciesInfo ; }
Retrieves all Metadata Cascade Policies on a folder .
80
12
150,154
public static BoxRetentionPolicy . Info createIndefinitePolicy ( BoxAPIConnection api , String name ) { return createRetentionPolicy ( api , name , TYPE_INDEFINITE , 0 , ACTION_REMOVE_RETENTION ) ; }
Used to create a new indefinite retention policy .
56
9
150,155
public static BoxRetentionPolicy . Info createFinitePolicy ( BoxAPIConnection api , String name , int length , String action , RetentionPolicyParams optionalParams ) { return createRetentionPolicy ( api , name , TYPE_FINITE , length , action , optionalParams ) ; }
Used to create a new finite retention policy with optional parameters .
65
12
150,156
private static BoxRetentionPolicy . Info createRetentionPolicy ( BoxAPIConnection api , String name , String type , int length , String action ) { return createRetentionPolicy ( api , name , type , length , action , null ) ; }
Used to create a new retention policy .
54
8
150,157
private static BoxRetentionPolicy . Info createRetentionPolicy ( BoxAPIConnection api , String name , String type , int length , String action , RetentionPolicyParams optionalParams ) { URL url = RETENTION_POLICIES_URL_TEMPLATE . build ( api . getBaseURL ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( api , url , "POST" ) ; JsonObject requestJSON = new JsonObject ( ) . add ( "policy_name" , name ) . add ( "policy_type" , type ) . add ( "disposition_action" , action ) ; if ( ! type . equals ( TYPE_INDEFINITE ) ) { requestJSON . add ( "retention_length" , length ) ; } if ( optionalParams != null ) { requestJSON . add ( "can_owner_extend_retention" , optionalParams . getCanOwnerExtendRetention ( ) ) ; requestJSON . add ( "are_owners_notified" , optionalParams . getAreOwnersNotified ( ) ) ; List < BoxUser . Info > customNotificationRecipients = optionalParams . getCustomNotificationRecipients ( ) ; if ( customNotificationRecipients . size ( ) > 0 ) { JsonArray users = new JsonArray ( ) ; for ( BoxUser . Info user : customNotificationRecipients ) { JsonObject userJSON = new JsonObject ( ) . add ( "type" , "user" ) . add ( "id" , user . getID ( ) ) ; users . add ( userJSON ) ; } requestJSON . add ( "custom_notification_recipients" , users ) ; } } request . setBody ( requestJSON . toString ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; BoxRetentionPolicy createdPolicy = new BoxRetentionPolicy ( api , responseJSON . get ( "id" ) . asString ( ) ) ; return createdPolicy . new Info ( responseJSON ) ; }
Used to create a new retention policy with optional parameters .
472
11
150,158
public Iterable < BoxRetentionPolicyAssignment . Info > getFolderAssignments ( int limit , String ... fields ) { return this . getAssignments ( BoxRetentionPolicyAssignment . TYPE_FOLDER , limit , fields ) ; }
Returns iterable with all folder assignments of this retention policy .
54
12
150,159
public Iterable < BoxRetentionPolicyAssignment . Info > getEnterpriseAssignments ( int limit , String ... fields ) { return this . getAssignments ( BoxRetentionPolicyAssignment . TYPE_ENTERPRISE , limit , fields ) ; }
Returns iterable with all enterprise assignments of this retention policy .
56
12
150,160
public Iterable < BoxRetentionPolicyAssignment . Info > getAllAssignments ( int limit , String ... fields ) { return this . getAssignments ( null , limit , fields ) ; }
Returns iterable with all assignments of this retention policy .
43
11
150,161
private Iterable < BoxRetentionPolicyAssignment . Info > getAssignments ( String type , int limit , String ... fields ) { QueryStringBuilder queryString = new QueryStringBuilder ( ) ; if ( type != null ) { queryString . appendParam ( "type" , type ) ; } if ( fields . length > 0 ) { queryString . appendParam ( "fields" , fields ) ; } URL url = ASSIGNMENTS_URL_TEMPLATE . buildWithQuery ( getAPI ( ) . getBaseURL ( ) , queryString . toString ( ) , getID ( ) ) ; return new BoxResourceIterable < BoxRetentionPolicyAssignment . Info > ( getAPI ( ) , url , limit ) { @ Override protected BoxRetentionPolicyAssignment . Info factory ( JsonObject jsonObject ) { BoxRetentionPolicyAssignment assignment = new BoxRetentionPolicyAssignment ( getAPI ( ) , jsonObject . get ( "id" ) . asString ( ) ) ; return assignment . new Info ( jsonObject ) ; } } ; }
Returns iterable with all assignments of given type of this retention policy .
228
14
150,162
public BoxRetentionPolicyAssignment . Info assignTo ( BoxFolder folder ) { return BoxRetentionPolicyAssignment . createAssignmentToFolder ( this . getAPI ( ) , this . getID ( ) , folder . getID ( ) ) ; }
Assigns this retention policy to folder .
54
9
150,163
public BoxRetentionPolicyAssignment . Info assignToMetadataTemplate ( String templateID , MetadataFieldFilter ... fieldFilters ) { return BoxRetentionPolicyAssignment . createAssignmentToMetadata ( this . getAPI ( ) , this . getID ( ) , templateID , fieldFilters ) ; }
Assigns this retention policy to a metadata template optionally with certain field values .
67
16
150,164
public static Iterable < BoxRetentionPolicy . Info > getAll ( final BoxAPIConnection api , String ... fields ) { return getAll ( null , null , null , DEFAULT_LIMIT , api , fields ) ; }
Returns all the retention policies .
52
6
150,165
public static Iterable < BoxRetentionPolicy . Info > getAll ( String name , String type , String userID , int limit , final BoxAPIConnection api , String ... fields ) { QueryStringBuilder queryString = new QueryStringBuilder ( ) ; if ( name != null ) { queryString . appendParam ( "policy_name" , name ) ; } if ( type != null ) { queryString . appendParam ( "policy_type" , type ) ; } if ( userID != null ) { queryString . appendParam ( "created_by_user_id" , userID ) ; } if ( fields . length > 0 ) { queryString . appendParam ( "fields" , fields ) ; } URL url = RETENTION_POLICIES_URL_TEMPLATE . buildWithQuery ( api . getBaseURL ( ) , queryString . toString ( ) ) ; return new BoxResourceIterable < BoxRetentionPolicy . Info > ( api , url , limit ) { @ Override protected BoxRetentionPolicy . Info factory ( JsonObject jsonObject ) { BoxRetentionPolicy policy = new BoxRetentionPolicy ( api , jsonObject . get ( "id" ) . asString ( ) ) ; return policy . new Info ( jsonObject ) ; } } ; }
Returns all the retention policies with specified filters .
276
9
150,166
public void start ( ) { if ( this . started ) { throw new IllegalStateException ( "Cannot start the EventStream because it isn't stopped." ) ; } final long initialPosition ; if ( this . startingPosition == STREAM_POSITION_NOW ) { BoxAPIRequest request = new BoxAPIRequest ( this . api , EVENT_URL . build ( this . api . getBaseURL ( ) , "now" ) , "GET" ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject jsonObject = JsonObject . readFrom ( response . getJSON ( ) ) ; initialPosition = jsonObject . get ( "next_stream_position" ) . asLong ( ) ; } else { assert this . startingPosition >= 0 : "Starting position must be non-negative" ; initialPosition = this . startingPosition ; } this . poller = new Poller ( initialPosition ) ; this . pollerThread = new Thread ( this . poller ) ; this . pollerThread . setUncaughtExceptionHandler ( new Thread . UncaughtExceptionHandler ( ) { public void uncaughtException ( Thread t , Throwable e ) { EventStream . this . notifyException ( e ) ; } } ) ; this . pollerThread . start ( ) ; this . started = true ; }
Starts this EventStream and begins long polling the API .
282
12
150,167
protected boolean isDuplicate ( String eventID ) { if ( this . receivedEvents == null ) { this . receivedEvents = new LRUCache < String > ( ) ; } return ! this . receivedEvents . add ( eventID ) ; }
Indicates whether or not an event ID is a duplicate .
52
12
150,168
public static BoxRetentionPolicyAssignment . Info createAssignmentToEnterprise ( BoxAPIConnection api , String policyID ) { return createAssignment ( api , policyID , new JsonObject ( ) . add ( "type" , TYPE_ENTERPRISE ) , null ) ; }
Assigns retention policy with givenID to the enterprise .
65
12
150,169
public static BoxRetentionPolicyAssignment . Info createAssignmentToFolder ( BoxAPIConnection api , String policyID , String folderID ) { return createAssignment ( api , policyID , new JsonObject ( ) . add ( "type" , TYPE_FOLDER ) . add ( "id" , folderID ) , null ) ; }
Assigns retention policy with givenID to the folder .
77
12
150,170
public static BoxRetentionPolicyAssignment . Info createAssignmentToMetadata ( BoxAPIConnection api , String policyID , String templateID , MetadataFieldFilter ... filter ) { JsonObject assignTo = new JsonObject ( ) . add ( "type" , TYPE_METADATA ) . add ( "id" , templateID ) ; JsonArray filters = null ; if ( filter . length > 0 ) { filters = new JsonArray ( ) ; for ( MetadataFieldFilter f : filter ) { filters . add ( f . getJsonObject ( ) ) ; } } return createAssignment ( api , policyID , assignTo , filters ) ; }
Assigns a retention policy to all items with a given metadata template optionally matching on fields .
146
19
150,171
private static BoxRetentionPolicyAssignment . Info createAssignment ( BoxAPIConnection api , String policyID , JsonObject assignTo , JsonArray filter ) { URL url = ASSIGNMENTS_URL_TEMPLATE . build ( api . getBaseURL ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( api , url , "POST" ) ; JsonObject requestJSON = new JsonObject ( ) . add ( "policy_id" , policyID ) . add ( "assign_to" , assignTo ) ; if ( filter != null ) { requestJSON . add ( "filter_fields" , filter ) ; } request . setBody ( requestJSON . toString ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; BoxRetentionPolicyAssignment createdAssignment = new BoxRetentionPolicyAssignment ( api , responseJSON . get ( "id" ) . asString ( ) ) ; return createdAssignment . new Info ( responseJSON ) ; }
Assigns retention policy with givenID to folder or enterprise .
242
13
150,172
public static Iterable < Metadata > getAllMetadata ( BoxItem item , String ... fields ) { QueryStringBuilder builder = new QueryStringBuilder ( ) ; if ( fields . length > 0 ) { builder . appendParam ( "fields" , fields ) ; } return new BoxResourceIterable < Metadata > ( item . getAPI ( ) , GET_ALL_METADATA_URL_TEMPLATE . buildWithQuery ( item . getItemURL ( ) . toString ( ) , builder . toString ( ) ) , DEFAULT_LIMIT ) { @ Override protected Metadata factory ( JsonObject jsonObject ) { return new Metadata ( jsonObject ) ; } } ; }
Used to retrieve all metadata associated with the item .
150
10
150,173
public Metadata add ( String path , String value ) { this . values . add ( this . pathToProperty ( path ) , value ) ; this . addOp ( "add" , path , value ) ; return this ; }
Adds a new metadata value .
48
6
150,174
public Metadata add ( String path , List < String > values ) { JsonArray arr = new JsonArray ( ) ; for ( String value : values ) { arr . add ( value ) ; } this . values . add ( this . pathToProperty ( path ) , arr ) ; this . addOp ( "add" , path , arr ) ; return this ; }
Adds a new metadata value of array type .
79
9
150,175
public Metadata replace ( String path , String value ) { this . values . set ( this . pathToProperty ( path ) , value ) ; this . addOp ( "replace" , path , value ) ; return this ; }
Replaces an existing metadata value .
48
7
150,176
public Metadata remove ( String path ) { this . values . remove ( this . pathToProperty ( path ) ) ; this . addOp ( "remove" , path , ( String ) null ) ; return this ; }
Removes an existing metadata value .
46
7
150,177
@ Deprecated public String get ( String path ) { final JsonValue value = this . values . get ( this . pathToProperty ( path ) ) ; if ( value == null ) { return null ; } if ( ! value . isString ( ) ) { return value . toString ( ) ; } return value . asString ( ) ; }
Returns a value .
73
4
150,178
public Date getDate ( String path ) throws ParseException { return BoxDateFormat . parse ( this . getValue ( path ) . asString ( ) ) ; }
Get a value from a date metadata field .
35
9
150,179
public List < String > getMultiSelect ( String path ) { List < String > values = new ArrayList < String > ( ) ; for ( JsonValue val : this . getValue ( path ) . asArray ( ) ) { values . add ( val . asString ( ) ) ; } return values ; }
Get a value from a multiselect metadata field .
66
11
150,180
public List < String > getPropertyPaths ( ) { List < String > result = new ArrayList < String > ( ) ; for ( String property : this . values . names ( ) ) { if ( ! property . startsWith ( "$" ) ) { result . add ( this . propertyToPath ( property ) ) ; } } return result ; }
Returns a list of metadata property paths .
74
8
150,181
private String pathToProperty ( String path ) { if ( path == null || ! path . startsWith ( "/" ) ) { throw new IllegalArgumentException ( "Path must be prefixed with a \"/\"." ) ; } return path . substring ( 1 ) ; }
Converts a JSON patch path to a JSON property name . Currently the metadata API only supports flat maps .
59
21
150,182
private void addOp ( String op , String path , String value ) { if ( this . operations == null ) { this . operations = new JsonArray ( ) ; } this . operations . add ( new JsonObject ( ) . add ( "op" , op ) . add ( "path" , path ) . add ( "value" , value ) ) ; }
Adds a patch operation .
78
5
150,183
protected static BoxCollaboration . Info create ( BoxAPIConnection api , JsonObject accessibleBy , JsonObject item , BoxCollaboration . Role role , Boolean notify , Boolean canViewPath ) { String queryString = "" ; if ( notify != null ) { queryString = new QueryStringBuilder ( ) . appendParam ( "notify" , notify . toString ( ) ) . toString ( ) ; } URL url ; if ( queryString . length ( ) > 0 ) { url = COLLABORATIONS_URL_TEMPLATE . buildWithQuery ( api . getBaseURL ( ) , queryString ) ; } else { url = COLLABORATIONS_URL_TEMPLATE . build ( api . getBaseURL ( ) ) ; } JsonObject requestJSON = new JsonObject ( ) ; requestJSON . add ( "item" , item ) ; requestJSON . add ( "accessible_by" , accessibleBy ) ; requestJSON . add ( "role" , role . toJSONString ( ) ) ; if ( canViewPath != null ) { requestJSON . add ( "can_view_path" , canViewPath . booleanValue ( ) ) ; } BoxJSONRequest request = new BoxJSONRequest ( api , url , "POST" ) ; request . setBody ( requestJSON . toString ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; BoxCollaboration newCollaboration = new BoxCollaboration ( api , responseJSON . get ( "id" ) . asString ( ) ) ; return newCollaboration . new Info ( responseJSON ) ; }
Create a new collaboration object .
375
6
150,184
public static Collection < Info > getPendingCollaborations ( BoxAPIConnection api ) { URL url = PENDING_COLLABORATIONS_URL . build ( api . getBaseURL ( ) ) ; BoxAPIRequest request = new BoxAPIRequest ( api , url , "GET" ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; int entriesCount = responseJSON . get ( "total_count" ) . asInt ( ) ; Collection < BoxCollaboration . Info > collaborations = new ArrayList < BoxCollaboration . Info > ( entriesCount ) ; JsonArray entries = responseJSON . get ( "entries" ) . asArray ( ) ; for ( JsonValue entry : entries ) { JsonObject entryObject = entry . asObject ( ) ; BoxCollaboration collaboration = new BoxCollaboration ( api , entryObject . get ( "id" ) . asString ( ) ) ; BoxCollaboration . Info info = collaboration . new Info ( entryObject ) ; collaborations . add ( info ) ; } return collaborations ; }
Gets all pending collaboration invites for the current user .
255
11
150,185
public Info getInfo ( ) { BoxAPIConnection api = this . getAPI ( ) ; URL url = COLLABORATION_URL_TEMPLATE . build ( api . getBaseURL ( ) , this . getID ( ) ) ; BoxAPIRequest request = new BoxAPIRequest ( api , url , "GET" ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject jsonObject = JsonObject . readFrom ( response . getJSON ( ) ) ; return new Info ( jsonObject ) ; }
Gets information about this collaboration .
121
7
150,186
public void updateInfo ( Info info ) { BoxAPIConnection api = this . getAPI ( ) ; URL url = COLLABORATION_URL_TEMPLATE . build ( api . getBaseURL ( ) , this . getID ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( api , url , "PUT" ) ; request . setBody ( info . getPendingChanges ( ) ) ; BoxAPIResponse boxAPIResponse = request . send ( ) ; if ( boxAPIResponse instanceof BoxJSONResponse ) { BoxJSONResponse response = ( BoxJSONResponse ) boxAPIResponse ; JsonObject jsonObject = JsonObject . readFrom ( response . getJSON ( ) ) ; info . update ( jsonObject ) ; } }
Updates the information about this collaboration with any info fields that have been modified locally .
170
17
150,187
public void delete ( ) { BoxAPIConnection api = this . getAPI ( ) ; URL url = COLLABORATION_URL_TEMPLATE . build ( api . getBaseURL ( ) , this . getID ( ) ) ; BoxAPIRequest request = new BoxAPIRequest ( api , url , "DELETE" ) ; BoxAPIResponse response = request . send ( ) ; response . disconnect ( ) ; }
Deletes this collaboration .
96
5
150,188
public static BoxLegalHoldAssignment . Info create ( BoxAPIConnection api , String policyID , String resourceType , String resourceID ) { URL url = ASSIGNMENTS_URL_TEMPLATE . build ( api . getBaseURL ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( api , url , "POST" ) ; JsonObject requestJSON = new JsonObject ( ) . add ( "policy_id" , policyID ) . add ( "assign_to" , new JsonObject ( ) . add ( "type" , resourceType ) . add ( "id" , resourceID ) ) ; request . setBody ( requestJSON . toString ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; BoxLegalHoldAssignment createdAssignment = new BoxLegalHoldAssignment ( api , responseJSON . get ( "id" ) . asString ( ) ) ; return createdAssignment . new Info ( responseJSON ) ; }
Creates new legal hold policy assignment .
236
8
150,189
public void addCustomNotificationRecipient ( String userID ) { BoxUser user = new BoxUser ( null , userID ) ; this . customNotificationRecipients . add ( user . new Info ( ) ) ; }
Add a user by ID to the list of people to notify when the retention period is ending .
48
19
150,190
public static Iterable < BoxCollection . Info > getAllCollections ( final BoxAPIConnection api ) { return new Iterable < BoxCollection . Info > ( ) { public Iterator < BoxCollection . Info > iterator ( ) { URL url = GET_COLLECTIONS_URL_TEMPLATE . build ( api . getBaseURL ( ) ) ; return new BoxCollectionIterator ( api , url ) ; } } ; }
Gets an iterable of all the collections for the given user .
93
14
150,191
public PartialCollection < BoxItem . Info > getItemsRange ( long offset , long limit , String ... fields ) { QueryStringBuilder builder = new QueryStringBuilder ( ) . appendParam ( "offset" , offset ) . appendParam ( "limit" , limit ) ; if ( fields . length > 0 ) { builder . appendParam ( "fields" , fields ) . toString ( ) ; } URL url = GET_COLLECTION_ITEMS_URL . buildWithQuery ( getAPI ( ) . getBaseURL ( ) , builder . toString ( ) , getID ( ) ) ; BoxAPIRequest request = new BoxAPIRequest ( this . getAPI ( ) , url , "GET" ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; String totalCountString = responseJSON . get ( "total_count" ) . toString ( ) ; long fullSize = Double . valueOf ( totalCountString ) . longValue ( ) ; PartialCollection < BoxItem . Info > items = new PartialCollection < BoxItem . Info > ( offset , limit , fullSize ) ; JsonArray entries = responseJSON . get ( "entries" ) . asArray ( ) ; for ( JsonValue entry : entries ) { BoxItem . Info entryInfo = ( BoxItem . Info ) BoxResource . parseInfo ( this . getAPI ( ) , entry . asObject ( ) ) ; if ( entryInfo != null ) { items . add ( entryInfo ) ; } } return items ; }
Retrieves a specific range of items in this collection .
342
12
150,192
@ Override public Iterator < BoxItem . Info > iterator ( ) { URL url = GET_COLLECTION_ITEMS_URL . build ( this . getAPI ( ) . getBaseURL ( ) , BoxCollection . this . getID ( ) ) ; return new BoxItemIterator ( BoxCollection . this . getAPI ( ) , url ) ; }
Returns an iterator over the items in this collection .
76
10
150,193
public static BoxCollaborationWhitelistExemptTarget . Info create ( final BoxAPIConnection api , String userID ) { URL url = COLLABORATION_WHITELIST_EXEMPT_TARGET_ENTRIES_URL_TEMPLATE . build ( api . getBaseURL ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( api , url , HttpMethod . POST ) ; JsonObject requestJSON = new JsonObject ( ) . add ( "user" , new JsonObject ( ) . add ( "type" , "user" ) . add ( "id" , userID ) ) ; request . setBody ( requestJSON . toString ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; BoxCollaborationWhitelistExemptTarget userWhitelist = new BoxCollaborationWhitelistExemptTarget ( api , responseJSON . get ( "id" ) . asString ( ) ) ; return userWhitelist . new Info ( responseJSON ) ; }
Creates a collaboration whitelist for a Box User with a given ID .
247
15
150,194
public BoxCollaborationWhitelistExemptTarget . Info getInfo ( ) { URL url = COLLABORATION_WHITELIST_EXEMPT_TARGET_ENTRY_URL_TEMPLATE . build ( this . getAPI ( ) . getBaseURL ( ) , this . getID ( ) ) ; BoxAPIRequest request = new BoxAPIRequest ( this . getAPI ( ) , url , HttpMethod . GET ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; return new Info ( JsonObject . readFrom ( response . getJSON ( ) ) ) ; }
Retrieves information for a collaboration whitelist for a given whitelist ID .
134
16
150,195
public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection ( String enterpriseId , String clientId , String clientSecret , JWTEncryptionPreferences encryptionPref , IAccessTokenCache accessTokenCache ) { BoxDeveloperEditionAPIConnection connection = new BoxDeveloperEditionAPIConnection ( enterpriseId , DeveloperEditionEntityType . ENTERPRISE , clientId , clientSecret , encryptionPref , accessTokenCache ) ; connection . tryRestoreUsingAccessTokenCache ( ) ; return connection ; }
Creates a new Box Developer Edition connection with enterprise token leveraging an access token cache .
112
17
150,196
public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection ( BoxConfig boxConfig ) { BoxDeveloperEditionAPIConnection connection = getAppEnterpriseConnection ( boxConfig . getEnterpriseId ( ) , boxConfig . getClientId ( ) , boxConfig . getClientSecret ( ) , boxConfig . getJWTEncryptionPreferences ( ) ) ; return connection ; }
Creates a new Box Developer Edition connection with enterprise token leveraging BoxConfig .
86
15
150,197
public static BoxDeveloperEditionAPIConnection getAppUserConnection ( String userId , String clientId , String clientSecret , JWTEncryptionPreferences encryptionPref , IAccessTokenCache accessTokenCache ) { BoxDeveloperEditionAPIConnection connection = new BoxDeveloperEditionAPIConnection ( userId , DeveloperEditionEntityType . USER , clientId , clientSecret , encryptionPref , accessTokenCache ) ; connection . tryRestoreUsingAccessTokenCache ( ) ; return connection ; }
Creates a new Box Developer Edition connection with App User token .
110
13
150,198
public static BoxDeveloperEditionAPIConnection getAppUserConnection ( String userId , BoxConfig boxConfig ) { return getAppUserConnection ( userId , boxConfig . getClientId ( ) , boxConfig . getClientSecret ( ) , boxConfig . getJWTEncryptionPreferences ( ) ) ; }
Creates a new Box Developer Edition connection with App User token levaraging BoxConfig .
68
18
150,199
public void authenticate ( ) { URL url ; try { url = new URL ( this . getTokenURL ( ) ) ; } catch ( MalformedURLException e ) { assert false : "An invalid token URL indicates a bug in the SDK." ; throw new RuntimeException ( "An invalid token URL indicates a bug in the SDK." , e ) ; } String jwtAssertion = this . constructJWTAssertion ( ) ; String urlParameters = String . format ( JWT_GRANT_TYPE , this . getClientID ( ) , this . getClientSecret ( ) , jwtAssertion ) ; BoxAPIRequest request = new BoxAPIRequest ( this , url , "POST" ) ; request . shouldAuthenticate ( false ) ; request . setBody ( urlParameters ) ; String json ; try { BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; json = response . getJSON ( ) ; } catch ( BoxAPIException ex ) { // Use the Date advertised by the Box server as the current time to synchronize clocks List < String > responseDates = ex . getHeaders ( ) . get ( "Date" ) ; NumericDate currentTime ; if ( responseDates != null ) { String responseDate = responseDates . get ( 0 ) ; SimpleDateFormat dateFormat = new SimpleDateFormat ( "EEE, d MMM yyyy HH:mm:ss zzz" ) ; try { Date date = dateFormat . parse ( responseDate ) ; currentTime = NumericDate . fromMilliseconds ( date . getTime ( ) ) ; } catch ( ParseException e ) { currentTime = NumericDate . now ( ) ; } } else { currentTime = NumericDate . now ( ) ; } // Reconstruct the JWT assertion, which regenerates the jti claim, with the new "current" time jwtAssertion = this . constructJWTAssertion ( currentTime ) ; urlParameters = String . format ( JWT_GRANT_TYPE , this . getClientID ( ) , this . getClientSecret ( ) , jwtAssertion ) ; // Re-send the updated request request = new BoxAPIRequest ( this , url , "POST" ) ; request . shouldAuthenticate ( false ) ; request . setBody ( urlParameters ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; json = response . getJSON ( ) ; } JsonObject jsonObject = JsonObject . readFrom ( json ) ; this . setAccessToken ( jsonObject . get ( "access_token" ) . asString ( ) ) ; this . setLastRefresh ( System . currentTimeMillis ( ) ) ; this . setExpires ( jsonObject . get ( "expires_in" ) . asLong ( ) * 1000 ) ; //if token cache is specified, save to cache if ( this . accessTokenCache != null ) { String key = this . getAccessTokenCacheKey ( ) ; JsonObject accessTokenCacheInfo = new JsonObject ( ) . add ( "accessToken" , this . getAccessToken ( ) ) . add ( "lastRefresh" , this . getLastRefresh ( ) ) . add ( "expires" , this . getExpires ( ) ) ; this . accessTokenCache . put ( key , accessTokenCacheInfo . toString ( ) ) ; } }
Authenticates the API connection for Box Developer Edition .
732
10